-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhelloworld.go
63 lines (48 loc) · 1.14 KB
/
helloworld.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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"math/rand"
"time"
"github.com/pkg/errors"
"github.com/PandaXGO/device-sdk-go/client"
"github.com/PandaXGO/device-sdk-go/util/wait"
)
const (
_brokerAddr = "tcp://127.0.0.1:1883"
_username = "ZjI1M2IyNGMtNjNjZi0zMzM5LWFlMDMtYjBkOWVlYTQ4ZDNh"
_pwd = ""
)
func main() {
log.SetFlags(log.Lshortfile)
cli := client.NewClient(_brokerAddr, _username, _pwd)()
err := cli.Connect()
if err != nil {
log.Fatalln(err)
}
_ = cli.SubscribeRpcReq(context.TODO(), commandsTopicHandler)
tm := time.Second * 1
wait.EveryWithContext(context.Background(), func(ctx context.Context) {
v, _ := deviceValue()
// telemetry.
_ = cli.PublishTelemetry(ctx, v)
}, tm)
select {}
}
func commandsTopicHandler(message client.Message) (interface{}, error) {
fmt.Printf("commands=%s\n", string(message.Payload()))
return "success", nil
}
func deviceValue() ([]byte, error) {
mv := map[string]interface{}{
"humidity": rand.Intn(20),
"temperature": rand.Intn(20),
}
bys, err := json.Marshal(mv)
if err != nil {
err = errors.Wrap(err, "deviceValue")
}
return bys, err
}