-
Notifications
You must be signed in to change notification settings - Fork 0
/
types.go
71 lines (61 loc) · 1.41 KB
/
types.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
package smarthome
import (
"encoding/json"
"time"
mqtt "github.com/eclipse/paho.mqtt.golang"
)
const (
setPath = "set"
getPath = "get"
commandPath = "command"
statusPath = "status"
connectedPath = "connected"
statusPathComplete = "/" + statusPath + "/"
allStatusTopic = "+" + statusPathComplete + "#"
)
type Value struct {
Value interface{}
Time time.Time
LastChanged time.Time
}
type valueJSON struct {
Value interface{} `json:"val"`
Time int64 `json:"ts"`
LastChanged int64 `json:"lc"`
}
func (v *Value) UnmarshalJSON(text []byte) error {
val := valueJSON{}
if err := json.Unmarshal(text, &val); err != nil {
return err
}
v.Value = val.Value
v.Time = time.Unix(val.Time, 0).UTC()
v.LastChanged = time.Unix(val.LastChanged, 0).UTC()
return nil
}
func (v Value) MarshalJSON() ([]byte, error) {
val := valueJSON{
Value: v.Value,
Time: v.Time.UnixNano() / 1e9,
LastChanged: v.LastChanged.UnixNano() / 1e9,
}
return json.Marshal(val)
}
func PayloadToValue(data []byte) Value {
v := Value{}
if err := json.Unmarshal(data, &v); err != nil && v.Value != nil {
return v
}
v.Value = string(data)
return v
}
func DefaultMQTTClientOptions() *mqtt.ClientOptions {
return mqtt.NewClientOptions().
SetAutoReconnect(true).
SetCleanSession(false)
}
type StatusMessage struct {
Toplevel string
Item string
Value Value
}