forked from ecc1/medtronic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.go
286 lines (262 loc) · 6.57 KB
/
command.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
package medtronic
import (
"bytes"
"fmt"
"log"
"os"
"time"
)
const (
pumpEnvVar = "MEDTRONIC_PUMP_ID"
PumpDevice = 0xA7
maxPacketSize = 71 // including CRC byte
historyPageSize = 1024
)
var (
commandPrefix []byte
)
func initCommandPrefix() {
if len(commandPrefix) != 0 {
return
}
id := os.Getenv(pumpEnvVar)
if len(id) == 0 {
log.Fatalf("%s environment variable is not set", pumpEnvVar)
}
if len(id) != 6 {
log.Fatalf("%s environment variable must be 6 digits", pumpEnvVar)
}
commandPrefix = []byte{
PumpDevice,
(id[0]-'0')<<4 | (id[1] - '0'),
(id[2]-'0')<<4 | (id[3] - '0'),
(id[4]-'0')<<4 | (id[5] - '0'),
}
}
type Command byte
//go:generate stringer -type Command
const (
Ack Command = 0x06
Nak Command = 0x15
)
type NoResponseError Command
func (e NoResponseError) Error() string {
return fmt.Sprintf("no response to %v", Command(e))
}
type InvalidCommandError Command
func (e InvalidCommandError) Error() string {
return fmt.Sprintf("invalid %v command", Command(e))
}
type BadResponseError struct {
Command Command
Data []byte
}
func (e BadResponseError) Error() string {
return fmt.Sprintf("unexpected response to %v: % X", e.Command, e.Data)
}
func (pump *Pump) BadResponse(cmd Command, data []byte) {
pump.SetError(BadResponseError{Command: cmd, Data: data})
}
// commandPacket constructs a packet
// with the specified command code and parameters.
// A command packet with no parameters is 7 bytes long:
// device type (0xA7)
// 3 bytes of pump ID
// command code
// length of parameters (0)
// CRC-8
// A command packet with parameters is 71 bytes long:
// device type (0xA7)
// 3 bytes of pump ID
// command code
// length of parameters
// 64 bytes of parameters plus padding
// CRC-8
func commandPacket(cmd Command, params []byte) []byte {
initCommandPrefix()
data := []byte{}
if len(params) == 0 {
data = make([]byte, 7)
} else {
data = make([]byte, maxPacketSize)
}
copy(data, commandPrefix)
data[4] = byte(cmd)
data[5] = byte(len(params))
if len(params) != 0 {
copy(data[6:], params)
}
return EncodePacket(data)
}
// Commands with parameters require an initial exchange with no parameters,
// followed by an exchange with the actual arguments.
func (pump *Pump) Execute(cmd Command, params ...byte) []byte {
if len(params) != 0 {
pump.perform(cmd, Ack, nil)
return pump.perform(cmd, Ack, params)
}
return pump.perform(cmd, cmd, nil)
}
// History pages are returned as a series of 65-byte fragments:
// sequence number (1 to 16)
// 64 bytes of payload
// The caller must send an Ack to receive the next fragment
// or a Nak to have the current one retransmitted.
// The 0x80 bit is set in the sequence number of the final fragment.
// The page consists of the concatenated payloads.
// The final 2 bytes are the CRC-16 of the preceding data.
const (
numFragments = 16
fragmentLength = 65
maxNaks = 10
downloadTimeout = 150 * time.Millisecond
)
func (pump *Pump) Download(cmd Command, page int) []byte {
data := pump.Execute(cmd, byte(page))
if pump.Error() != nil {
return nil
}
results := []byte{}
retries := pump.Retries()
pump.SetRetries(1)
defer pump.SetRetries(retries)
timeout := pump.Timeout()
pump.SetTimeout(downloadTimeout)
defer pump.SetTimeout(timeout)
expected := byte(1)
for {
if len(data) != fragmentLength {
pump.SetError(fmt.Errorf("unexpected history fragment length (%d)", len(data)))
return nil
}
done := data[0]&0x80 != 0
seqNum := data[0] &^ 0x80
payload := data[1:]
if seqNum == expected {
// Got the next fragment as expected.
results = append(results, payload...)
if done {
if seqNum != numFragments {
pump.SetError(fmt.Errorf("unexpected final sequence number for history page (%d)", seqNum))
return nil
}
break
}
expected = seqNum + 1
} else if seqNum < expected {
// Skip duplicate responses.
} else {
// Missed fragment.
pump.SetError(fmt.Errorf("received fragment %d instead of %d in history page", seqNum, expected))
return nil
}
next := []byte{}
// Acknowledge the current fragment.
next = pump.perform(Ack, cmd, nil)
if pump.Error() == nil {
data = next
continue
}
_, noResponse := pump.Error().(NoResponseError)
if !noResponse {
return nil
}
// No response to ACK. Send NAK to request retransmission.
pump.SetError(nil)
for count := 0; count < maxNaks; count++ {
next = pump.perform(Nak, cmd, nil)
if pump.Error() == nil {
format := "received fragment %d after %d NAK"
if count != 0 {
format += "s"
}
log.Printf(format, next[0]&^0x80, count+1)
break
}
_, noResponse := pump.Error().(NoResponseError)
if !noResponse {
return nil
}
pump.SetError(nil)
}
if next == nil {
pump.SetError(fmt.Errorf("lost fragment %d in history page", expected))
return nil
}
data = next
}
if len(results) != historyPageSize {
pump.SetError(fmt.Errorf("unexpected history page size (%d)", len(results)))
return nil
}
dataCrc := twoByteUint(results[historyPageSize-2:])
results = results[:historyPageSize-2]
calcCrc := Crc16(results)
if dataCrc != calcCrc {
pump.SetError(fmt.Errorf("CRC should be %02X, not %02X", calcCrc, dataCrc))
return nil
}
return results
}
func (pump *Pump) perform(cmd Command, resp Command, params []byte) []byte {
if pump.Error() != nil {
return nil
}
packet := commandPacket(cmd, params)
for tries := 0; tries < pump.retries || pump.retries == 0; tries++ {
pump.Radio.Send(packet)
response, rssi := pump.Radio.Receive(pump.Timeout())
if len(response) == 0 {
pump.SetError(nil)
continue
}
data := pump.DecodePacket(response)
if pump.Error() != nil {
pump.SetError(nil)
continue
}
if pump.unexpected(cmd, resp, data) {
return nil
}
pump.rssi = rssi
return data[5:]
}
pump.SetError(NoResponseError(cmd))
return nil
}
func (pump *Pump) unexpected(cmd Command, resp Command, data []byte) bool {
if len(data) < 5 {
pump.BadResponse(cmd, data)
return true
}
n := len(commandPrefix)
if !bytes.Equal(data[:n], commandPrefix) {
pump.BadResponse(cmd, data)
return true
}
switch Command(data[n]) {
case cmd:
return false
case resp:
return false
case Ack:
if cmd != Wakeup {
break
}
return false
case Nak:
pump.SetError(InvalidCommandError(cmd))
return true
}
pump.BadResponse(cmd, data)
return true
}
func twoByteInt(data []byte) int {
return int(data[0])<<8 | int(data[1])
}
func twoByteUint(data []byte) uint16 {
return uint16(data[0])<<8 | uint16(data[1])
}
func fourByteInt(data []byte) int {
return twoByteInt(data[0:2])<<16 | twoByteInt(data[2:4])
}