-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
58 lines (51 loc) · 1.58 KB
/
main.go
File metadata and controls
58 lines (51 loc) · 1.58 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"fmt"
mqtt "github.com/eclipse/paho.mqtt.golang"
"time"
)
var massagePubHandler mqtt.MessageHandler = func(client mqtt.Client, msg mqtt.Message) {
fmt.Printf("Сообщение получено: %s , из топика: %s\n", msg.Payload(), msg.Topic())
}
var connectHandler mqtt.OnConnectHandler = func(client mqtt.Client) {
fmt.Println("Connected")
}
var connectLostHandler mqtt.ConnectionLostHandler = func(client mqtt.Client, err error) {
fmt.Printf("Connection lost error - %v\n", err.Error())
}
func main() {
var broker = "mqtt0.bast-dev.ru"
var port = 1883
var topicPrefix = "service/weather_logger/#"
var userName = "hackathon"
var password = "Autumn2021"
opts := mqtt.NewClientOptions()
opts.AddBroker(fmt.Sprintf("tcp://%s:%d/", broker, port))
opts.SetClientID(fmt.Sprintf("data-set%d", time.Now().Unix()))
opts.SetUsername(userName)
opts.SetPassword(password)
opts.SetDefaultPublishHandler(massagePubHandler)
opts.OnConnect = connectHandler
opts.OnConnectionLost = connectLostHandler
client := mqtt.NewClient(opts)
if token := client.Connect(); token.Wait() && token.Error() != nil {
panic(token.Error())
}
sub(client, topicPrefix)
publish(client, topicPrefix)
client.Disconnect(100)
}
func publish(client mqtt.Client, topic string) {
num := 16
for true{
text := fmt.Sprintf("Message %d", num)
token := client.Publish(topic, 0, false, text)
token.Wait()
time.Sleep(time.Second * 1)
}
}
func sub(client mqtt.Client, topic string) {
token := client.Subscribe(topic, 1, nil)
token.Wait()
fmt.Printf("Subscribed to topic: %s\n", topic)
}