-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmain.go
70 lines (58 loc) · 1.68 KB
/
main.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
package main
import (
"fmt"
"log"
"math/rand"
"time"
homie "github.com/masgari/homie-go/homie"
)
var (
publisher homie.PeriodicPublisher
)
func randomPropertySetter(n homie.Node) {
valueProp := n.GetProperty("value")
valueProp.SetValue(fmt.Sprintf("%d", rand.Intn(1000)))
valueProp.Publish()
}
func periodicRandomIntPublisher(tickerPriod string) (homie.PeriodicPublisher, error) {
interval, err := time.ParseDuration(tickerPriod)
if err != nil {
return nil, err
}
return homie.NewPeriodicPublisher(interval), nil
}
func main() {
device := homie.NewDevice("test1", &homie.Config{
Mqtt: homie.MqttConfig{
Host: "localhost",
Port: 1883,
Username: "user",
Password: "password",
},
BaseTopic: "devices/",
StatsReportInterval: 60,
})
homie.NewDevicePublisher(device)
publisher, _ = periodicRandomIntPublisher("1s")
node := device.NewNode("RandomGenerator", "RandomValueGeneratorNode")
publisher.AddNodePublisher(node, randomPropertySetter)
node.NewProperty("value", "integer")
// to change interval, send a message to: devices/test1/RandomGenerator/interval/set
// sample intervals: 200ms, 3s
node.NewProperty("interval", "integer").
SetHandler(func(p homie.Property, payload []byte, topic string) (bool, error) {
interval := string(payload)
publisher.Close() // close current publisher
newPublisher, err := periodicRandomIntPublisher(interval)
if err != nil {
log.Fatalf("Invalid ticker duration: %s, %v", interval, err)
return false, err
}
publisher = newPublisher
publisher.AddNodePublisher(node, randomPropertySetter)
// invoke publisher again
publisher.Start()
return true, nil
})
device.Run(true)
}