-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmqtt-sensor.go
More file actions
56 lines (44 loc) · 993 Bytes
/
mqtt-sensor.go
File metadata and controls
56 lines (44 loc) · 993 Bytes
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
package sensor
import (
mqtt "github.com/eclipse/paho.mqtt.golang"
"strconv"
"time"
)
type MqttOptions struct {
Options
ReportToAddress string
ReportToQos byte
ReportToRetained bool
}
type MqttSensor struct {
Sensor
options MqttOptions
ReportToClient mqtt.Client
}
func NewMqttSensor(options *MqttOptions) *MqttSensor {
s := &MqttSensor{}
s.State = Inactive
s.options = *options
return s
}
//goland:noinspection GoUnusedParameter
func (s *MqttSensor) Update(client mqtt.Client, msg mqtt.Message) {
value, err := strconv.ParseFloat(string(msg.Payload()), 8)
if err == nil {
s.SetValue(value)
}
}
func (s *MqttSensor) ReportTo() {
s.ReportToClient.Publish(s.options.ReportToAddress, s.options.ReportToQos, s.options.ReportToRetained, s.value)
}
func (s *MqttSensor) SetValue(value float64) {
s.UpdatedTime = time.Now()
s.State = Active
s.value = value
if s.Propagate != nil {
s.Propagate(s)
}
if s.ReportToClient != nil {
s.ReportTo()
}
}