-
Notifications
You must be signed in to change notification settings - Fork 5
/
packet.go
331 lines (282 loc) · 7.18 KB
/
packet.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
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
//
// This work is based largely on the info and reverse eng effort HclX did:
// https://hclxing.wordpress.com/2019/06/06/reverse-engineering-wyzesense-bridge-protocol-part-iii/
// https://github.com/HclX/WyzeSensePy
//
package gosense
import (
"bufio"
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"os"
"strings"
"time"
log "github.com/sirupsen/logrus"
)
type cmdType int
const (
syncCommand = cmdType(0x43)
asyncCommand = cmdType(0x53)
// Sync packets
// Commands initiated from host side
cmdGetEnr = syncCommand<<8 | 0x02
cmdGetMac = syncCommand<<8 | 0x04
cmdGetKey = syncCommand<<8 | 0x06
cmdInquiry = syncCommand<<8 | 0x27
// Async packets
asyncAck = cmdType(asyncCommand<<8 | 0xff)
// Commands initiated from dongle side
cmdFinishAuth = asyncCommand<<8 | 0x14
cmdGetDongleVersion = asyncCommand<<8 | 0x16
cmdEnableScan = asyncCommand<<8 | 0x1c
cmdGetSensorR1 = asyncCommand<<8 | 0x21
cmdVerifySensor = asyncCommand<<8 | 0x23
cmdDelSensor = asyncCommand<<8 | 0x25
cmdGetSensorCount = asyncCommand<<8 | 0x2e
cmdGetSensorList = asyncCommand<<8 | 0x30
// Notifications initiated from dongle side
notifyButtonPressed = asyncCommand<<8 | 0x18
notifySensorAlarm = asyncCommand<<8 | 0x19
notifySensorScan = asyncCommand<<8 | 0x20
notifySyncTime = asyncCommand<<8 | 0x32
notifyEventLog = asyncCommand<<8 | 0x35
)
type SensorType byte
// These are the different sensor types.
const (
// Not known yet
SenseUnknown SensorType = 0
// Magnetic Switch
SenseSwitch SensorType = 1
// IR motion sensor
SenseMotion SensorType = 2
)
// Convert the SensorType to a string.
func (s SensorType) String() string {
if b, err := s.MarshalText(); err == nil {
return string(b)
}
return "unknown"
}
// ParseSensorType takes a string sensor type and returns the SensorType constant.
func ParseSensorType(sts string) (SensorType, error) {
switch strings.ToLower(sts) {
case "0":
fallthrough
case "unknown":
return SenseUnknown, nil
case "1":
fallthrough
case "switch":
return SenseSwitch, nil
case "2":
fallthrough
case "motionsensor":
return SenseMotion, nil
}
var s SensorType
return s, fmt.Errorf("not a valid SensorType: %q", sts)
}
// UnmarshalText implements encoding.TextUnmarshaler.
func (s *SensorType) UnmarshalText(text []byte) error {
l, err := ParseSensorType(string(text))
if err != nil {
return err
}
*s = SensorType(l)
return nil
}
func (s SensorType) MarshalText() ([]byte, error) {
switch s {
case SenseUnknown:
return []byte("unknown"), nil
case SenseSwitch:
return []byte("switch"), nil
case SenseMotion:
return []byte("motionsensor"), nil
}
return nil, fmt.Errorf("not a valid SensorType %d", s)
}
type SenseSensor struct {
MAC string
SensorType SensorType
Present bool
}
type Event struct {
MAC string
SensorFlags byte
SensorType SensorType
Timestamp time.Time
}
type Alarm struct {
Event
SignalStrength byte
Battery byte
State byte
}
// Packet defines packets going to and coming from the device.
type packet struct {
cmd cmdType
payload []byte
}
func newPacket(cmd cmdType, payload []byte) packet {
p := packet{
cmd: cmd,
payload: payload,
}
return p
}
func parsePacket(buf []byte) (packet, error) {
var err error
p := packet{}
if len(buf) < 5 {
err = fmt.Errorf("Invalid packet lenght: %d", len(buf))
log.Error(err)
return p, err
}
magic := binary.BigEndian.Uint16(buf)
ct := int(buf[2])
b2 := buf[3]
cmdID := int(buf[4])
if magic != 0x55AA && magic != 0xAA55 {
err = fmt.Errorf("Invalid packet magic: %x", magic)
log.Error(err)
return p, err
}
cmd := cmdType(ct<<8 | cmdID)
var payload []byte
if cmd == asyncAck {
if len(buf) < 7 {
err = fmt.Errorf("Invalid packet len for asyncAck")
log.Error(err)
return p, err
}
buf = buf[:7]
payload = nil //cm << 8 | b2
} else {
if len(buf) < int(b2+4) {
err = fmt.Errorf("Invalid packet len for regular response")
log.Error(err)
return p, err
}
buf = buf[:b2+4]
payload = buf[5 : len(buf)-2]
}
l := len(buf)
csRemote := int(buf[l-2])<<8 + int(buf[l-1])
checksum := 0
for _, i := range buf[:l-2] {
checksum = checksum + int(i)
}
if csRemote != checksum {
err = fmt.Errorf("Mismatched checksum, remote=%04X, local=%04X", csRemote, checksum)
log.Error(err)
return p, err
}
p = newPacket(cmd, payload)
return p, nil
}
// Packet creation helpers
func inquiry() packet { return newPacket(cmdInquiry, make([]byte, 0)) }
func getMac() packet { return newPacket(cmdGetMac, make([]byte, 0)) }
func getVersion() packet { return newPacket(cmdGetDongleVersion, make([]byte, 0)) }
func enableScan(state byte) packet {
pay := make([]byte, 1)
pay[0] = state
return newPacket(cmdEnableScan, pay)
}
func getSensorR1(MAC string, code string) packet {
if len(MAC) != 8 {
panic("len MAC is not 8!")
}
if len(code) != 16 {
panic("len code is not 16!")
}
pay := []byte(MAC + code)
return newPacket(cmdGetSensorR1, pay)
}
func verifySensor(MAC string) packet {
if len(MAC) != 8 {
panic("len MAC is not 8!")
}
pay := []byte(MAC + "\xFF\x04")
return newPacket(cmdVerifySensor, pay)
}
func deleteSensor(MAC string) packet {
if len(MAC) != 8 {
panic("len MAC is not 8!")
}
pay := []byte(MAC)
return newPacket(cmdDelSensor, pay)
}
func getSensorCount() packet { return newPacket(cmdGetSensorCount, make([]byte, 0)) }
func getSensorList(count byte) packet {
pay := make([]byte, 1)
pay[0] = count
return newPacket(cmdGetSensorList, pay)
}
func finishAuth() packet {
pay := make([]byte, 1)
pay[0] = byte(0xff)
return newPacket(cmdFinishAuth, pay)
}
func AsyncAck(cmd cmdType) packet {
pay := make([]byte, 1)
pay[0] = byte(cmd)
return newPacket(asyncAck, pay)
}
func syncTimeAck(cmd cmdType) packet {
pay := make([]byte, 8)
t := uint64(time.Now().Unix() * 1000)
binary.BigEndian.PutUint64(pay, t)
return newPacket(cmd+1, pay)
}
func (p *packet) lenght() int {
if p.cmd == asyncAck {
return 7
} else {
return len(p.payload) + 7
}
}
func (p *packet) toString() string {
var str string
if p.cmd == asyncAck {
str = fmt.Sprintf("Packet: Cmd:%04x, Payload: ACK[%04x]", p.cmd, p.payload[0])
} else {
str = fmt.Sprintf("Packet: Cmd:%04x, Payload: [%s]", p.cmd, hex.EncodeToString(p.payload))
}
return str
}
func (p *packet) send(fd *os.File) error {
var err error
var b bytes.Buffer
w := bufio.NewWriter(&b)
err = binary.Write(w, binary.BigEndian, uint16(0xaa55))
err = binary.Write(w, binary.BigEndian, byte(p.cmd>>8))
if p.cmd == asyncAck {
err = binary.Write(w, binary.BigEndian, p.payload[0])
err = binary.Write(w, binary.BigEndian, byte(p.cmd&0xff))
} else {
err = binary.Write(w, binary.BigEndian, byte(len(p.payload)+3))
err = binary.Write(w, binary.BigEndian, byte(p.cmd&0xff))
if len(p.payload) > 0 {
err = binary.Write(w, binary.BigEndian, p.payload)
}
}
err = binary.Write(w, binary.BigEndian, uint16(0x0000))
w.Flush()
buf := b.Bytes()
checksum := 0
for _, i := range buf {
checksum = checksum + int(i)
}
binary.BigEndian.PutUint16(buf[len(buf)-2:], uint16(checksum&0xffff))
log.Debugf("Sending: %s", hex.EncodeToString(buf))
l, err := fd.Write(buf)
if l < len(buf) || err != nil {
return err
}
return nil
}