-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathexample_test.go
121 lines (89 loc) · 1.74 KB
/
example_test.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
package mqtt_sonoff_basic_r2_test
import (
sonoff "github.com/fromsi/mqtt_sonoff_basic_r2"
mqtt "github.com/mochi-mqtt/server/v2"
mqttauth "github.com/mochi-mqtt/server/v2/hooks/auth"
"github.com/mochi-mqtt/server/v2/listeners"
"log"
"os"
"os/signal"
"syscall"
)
func Example_withServer() {
// init
sigSystem := make(chan os.Signal, 1)
signal.Notify(sigSystem, syscall.SIGINT, syscall.SIGTERM)
server := mqtt.New(
&mqtt.Options{
InlineClient: true,
},
)
tcp := listeners.NewTCP(listeners.Config{ID: "t1", Address: ":1883"})
err := server.AddListener(tcp)
if err != nil {
panic(err.Error())
}
err = server.AddHook(new(mqttauth.AllowHook), nil)
if err != nil {
panic(err.Error())
}
sonoffServer, err := sonoff.NewSonoffBasicR2WithServer(server, 2)
if err != nil {
panic(err.Error())
}
// run
go func() {
_ = sonoffServer.Serve()
_ = server.Serve()
}()
// ... your code ...
go func() {
for {
select {
case id, ok := <-sonoffServer.TeleConnected():
if !ok {
return
}
log.Println("Connected", id)
sonoffServer.PowerToggle(id)
}
}
}()
// stop
select {
case <-sigSystem:
_ = sonoffServer.Close()
_ = server.Close()
}
}
func Example_withoutServer() {
// init
sigSystem := make(chan os.Signal, 1)
signal.Notify(sigSystem, syscall.SIGINT, syscall.SIGTERM)
server, err := sonoff.NewSonoffBasicR2("", 1883, 0)
if err != nil {
panic(err.Error())
}
// run
go func() {
_ = server.Serve()
}()
// ... your code ...
go func() {
for {
select {
case id, ok := <-server.TeleConnected():
if !ok {
return
}
log.Println("Connected", id)
server.PowerToggle(id)
}
}
}()
// stop
select {
case <-sigSystem:
_ = server.Close()
}
}