-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathping.go
95 lines (79 loc) · 2.45 KB
/
ping.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
package ping
import (
"fmt"
"log"
"math/rand"
"os"
"os/signal"
"syscall"
"time"
"github.com/arduino/iot-cloud-cli/internal/mqtt"
"github.com/arduino/iot-cloud-cli/internal/properties"
paho "github.com/eclipse/paho.mqtt.golang"
)
type Params struct {
Host string // MQTT Broker URL
Username string // Virtual device ID
Password string // Virtual device secret
ThingID string // ID of thing with `int` property named `counter` attached to the virtual device
Troubleshooting bool // Enable/disable verbose logging of MQTT client
}
func Ping(params *Params) error {
if params.Troubleshooting {
paho.ERROR = log.New(os.Stdout, "[ERROR] ", 0)
paho.CRITICAL = log.New(os.Stdout, "[CRIT] ", 0)
paho.WARN = log.New(os.Stdout, "[WARN] ", 0)
paho.DEBUG = log.New(os.Stdout, "[DEBUG] ", 0)
}
mqttAdapter := mqtt.NewAdapterWithAuth(
params.Host,
params.Username,
params.Username,
params.Password,
)
err := mqttAdapter.Connect()
if err != nil {
return err
}
fmt.Println("Connected to Arduino IoT Cloud")
inboundTopic := fmt.Sprintf("/a/t/%s/e/i", params.ThingID)
outboundTopic := fmt.Sprintf("/a/t/%s/e/o", params.ThingID)
// Subscribing to the thing inbound topic to received new properties
// values from the cloud.
ok, _ := mqttAdapter.On(inboundTopic, func(msg paho.Message) {
fmt.Println("received a message", msg)
})
fmt.Println("Subscribed", ok)
// Sending new random values (in the 0-100 range) to the thing specified
// using the flags
go func() {
for {
randomValue := rand.Intn(100)
property, err := properties.NewInteger("counter", randomValue)
if err != nil {
fmt.Println("Failed to encode property value", err)
}
// Publishing a new random value to the outbound topic of the thing
err = mqttAdapter.Publish(outboundTopic, property)
if err != nil {
fmt.Println("Failed to send property to Arduino IoT Cloud", err)
}
fmt.Println("Property value sent successfully", randomValue)
wait := 3
time.Sleep(time.Duration(wait) * time.Second)
}
}()
// Wait for a sigterm signal (CTRL+C) to disconnect from the broker
// and say good bye
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM, syscall.SIGINT)
// blocking here waiting for a signal from the terminal 😪
<-c
mqttAdapter.Disconnect()
if err != nil {
return err
}
fmt.Println("Disconnected from Arduino IoT Cloud.")
fmt.Println("Completed successfully.")
return nil
}