-
Notifications
You must be signed in to change notification settings - Fork 6
/
mqtt.go
80 lines (68 loc) · 1.76 KB
/
mqtt.go
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package main
import (
"fmt"
"log"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
// MQTT represents an MQTT client configuration
type MQTT struct {
Host string
Port string
User string
Pass string
Client mqtt.Client
id string
}
// Server returns a new MQTT connection string
func (m *MQTT) Server() string {
return fmt.Sprintf("tcp://%s:%s", m.Host, m.Port)
}
// Connect connects to an MQTT broker
func (m *MQTT) Connect(id string) error {
log.Printf("[MQTT:Connect] Connecting: %s", id)
m.id = id
opts := mqtt.NewClientOptions().AddBroker(m.Server())
opts.SetClientID(id)
opts.SetKeepAlive(30 * time.Second)
opts.SetPingTimeout(10 * time.Second)
if m.User != "" {
opts.SetUsername(m.User)
}
if m.Pass != "" {
opts.SetPassword(m.Pass)
}
log.Print("[MQTT] Creating")
m.Client = mqtt.NewClient(opts)
log.Print("[MQTT] Connecting")
if token := m.Client.Connect(); token.Wait() && token.Error() != nil {
return (token.Error())
}
return nil
}
// Disconnect disconnects from an MQTT broker
func (m *MQTT) Disconnect() {
log.Print("[MQTT] Disconnecting")
m.Client.Disconnect(250)
}
// Publish publishes a message to an MQTT topic
func (m *MQTT) Publish(name string, r *Reading) {
log.Printf("[MQTT:Publish] %s (%s)", name, r.String())
format := "prometheus/job/%s/node/%s/%s"
// Publish Temperature
{
topic := fmt.Sprintf(format, m.id, name, "temperature")
value := fmt.Sprintf("%04f", r.Temperature)
m.publish(topic, value)
}
// Publish Humidity
{
topic := fmt.Sprintf(format, m.id, name, "humidity")
value := fmt.Sprintf("%04f", r.Humidity)
m.publish(topic, value)
}
}
func (m *MQTT) publish(topic string, payload interface{}) {
log.Printf("[MQTT:publish] %s (%v)", topic, payload)
m.Client.Publish(topic, 0, false, payload)
}