-
-
Notifications
You must be signed in to change notification settings - Fork 116
/
main.go
65 lines (58 loc) · 1.58 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
package main
import (
"bytes"
"fmt"
"log"
"time"
coap "github.com/plgd-dev/go-coap/v3"
"github.com/plgd-dev/go-coap/v3/message"
"github.com/plgd-dev/go-coap/v3/message/codes"
"github.com/plgd-dev/go-coap/v3/mux"
)
func getPath(opts message.Options) string {
path, err := opts.Path()
if err != nil {
log.Printf("cannot get path: %v", err)
return ""
}
return path
}
func sendResponse(cc mux.Conn, token []byte, subded time.Time, obs int64) error {
m := cc.AcquireMessage(cc.Context())
defer cc.ReleaseMessage(m)
m.SetCode(codes.Content)
m.SetToken(token)
m.SetBody(bytes.NewReader([]byte(fmt.Sprintf("Been running for %v", time.Since(subded)))))
m.SetContentFormat(message.TextPlain)
if obs >= 0 {
m.SetObserve(uint32(obs))
}
return cc.WriteMessage(m)
}
func periodicTransmitter(cc mux.Conn, token []byte) {
subded := time.Now()
for obs := int64(2); ; obs++ {
err := sendResponse(cc, token, subded, obs)
if err != nil {
log.Printf("Error on transmitter, stopping: %v", err)
return
}
time.Sleep(time.Second)
}
}
func main() {
log.Fatal(coap.ListenAndServe("udp", ":5688",
mux.HandlerFunc(func(w mux.ResponseWriter, r *mux.Message) {
log.Printf("Got message path=%v: %+v from %v", getPath(r.Options()), r, w.Conn().RemoteAddr())
obs, err := r.Options().Observe()
switch {
case r.Code() == codes.GET && err == nil && obs == 0:
go periodicTransmitter(w.Conn(), r.Token())
case r.Code() == codes.GET:
err := sendResponse(w.Conn(), r.Token(), time.Now(), -1)
if err != nil {
log.Printf("Error on transmitter: %v", err)
}
}
})))
}