forked from ecc1/medtronic
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcommand.go
502 lines (464 loc) · 13.2 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
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
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
package medtronic
import (
"bytes"
"fmt"
"log"
"github.com/ecc1/medtronic/packet"
)
// Command represents a pump command.
type Command byte
//go:generate stringer -type Command
const (
ack Command = 0x06
nak Command = 0x15
cgmWriteTimestamp Command = 0x28
setBasalPatternA Command = 0x30
setBasalPatternB Command = 0x31
setClock Command = 0x40
setMaxBolus Command = 0x41
bolus Command = 0x42
selectBasalPattern Command = 0x4A
setAbsoluteTempBasal Command = 0x4C
suspend Command = 0x4D
button Command = 0x5B
wakeup Command = 0x5D
setPercentTempBasal Command = 0x69
setMaxBasal Command = 0x6E
setBasalRates Command = 0x6F
clock Command = 0x70
pumpID Command = 0x71
battery Command = 0x72
reservoir Command = 0x73
firmwareVersion Command = 0x74
errorStatus Command = 0x75
historyPage Command = 0x80
carbUnits Command = 0x88
glucoseUnits Command = 0x89
carbRatios Command = 0x8A
insulinSensitivities Command = 0x8B
glucoseTargets512 Command = 0x8C
model Command = 0x8D
settings512 Command = 0x91
basalRates Command = 0x92
basalPatternA Command = 0x93
basalPatternB Command = 0x94
tempBasal Command = 0x98
glucosePage Command = 0x9A
isigPage Command = 0x9B
calibrationFactor Command = 0x9C
lastHistoryPage Command = 0x9D
glucoseTargets Command = 0x9F
settings Command = 0xC0
cgmPageCount Command = 0xCD
status Command = 0xCE
vcntrPage Command = 0xD5
)
// NoResponseError indicates that no response to a command was received.
type NoResponseError Command
func (e NoResponseError) Error() string {
return fmt.Sprintf("no response to %v", Command(e))
}
// NoResponse checks whether the pump has a NoResponseError.
func (pump *Pump) NoResponse() bool {
_, ok := pump.Error().(NoResponseError)
return ok
}
// InvalidCommandError indicates that the pump rejected a command as invalid.
type InvalidCommandError struct {
Command Command
PumpError PumpError
}
// PumpError represents an error response from the pump.
type PumpError byte
//go:generate stringer -type PumpError
// Pump error codes.
const (
CommandRefused PumpError = 0x08
MaxSettingExceeded PumpError = 0x09
BolusInProgress PumpError = 0x0C
InvalidHistoryPageNumber PumpError = 0x0D
)
func (e InvalidCommandError) Error() string {
return fmt.Sprintf("%v error: %v", e.Command, e.PumpError)
}
// BadResponseError indicates an unexpected response to a command.
type BadResponseError struct {
Command Command
Data []byte
}
func (e BadResponseError) Error() string {
return fmt.Sprintf("unexpected response to %v: % X", e.Command, e.Data)
}
// BadResponse sets the pump's error state to a BadResponseError.
func (pump *Pump) BadResponse(cmd Command, data []byte) {
pump.SetError(BadResponseError{Command: cmd, Data: data})
}
const (
shortPacketLength = 6 // excluding CRC byte
longPacketLength = 70 // excluding CRC byte
encodedLongPacketLength = 107
payloadLength = 64
fragmentLength = payloadLength + 1 // including sequence number
doneBit = 1 << 7
maxNAKs = 10
)
var (
shortPacket = make([]byte, shortPacketLength)
longPacket = make([]byte, longPacketLength)
ackPacket []byte
)
func precomputePackets() {
addr := PumpAddress()
shortPacket[0] = packet.Pump
copy(shortPacket[1:4], addr)
longPacket[0] = packet.Pump
copy(longPacket[1:4], addr)
ackPacket = shortPumpPacket(ack)
}
// shortPumpPacket constructs a 7-byte packet with the specified command code:
// device type (0xA7)
// 3 bytes of pump ID
// command code
// length of parameters (0)
// CRC-8 (added by packet.Encode)
func shortPumpPacket(cmd Command) []byte {
p := shortPacket
p[4] = byte(cmd)
p[5] = 0
return packet.Encode(p)
}
// longPumpPacket constructs a 71-byte packet with
// the specified command code and parameters:
// device type (0xA7)
// 3 bytes of pump ID
// command code
// length of parameters (or fragment number if non-zero)
// 64 bytes of parameters plus zero padding
// CRC-8 (added by packet.Encode)
func longPumpPacket(cmd Command, fragNum int, params []byte) []byte {
p := longPacket
p[4] = byte(cmd)
if fragNum == 0 {
p[5] = byte(len(params))
} else {
// Use a fragment number instead of the length.
p[5] = uint8(fragNum)
}
copy(p[6:], params)
// Zero-pad the remainder of the packet.
for i := 6 + len(params); i < longPacketLength; i++ {
p[i] = 0
}
return packet.Encode(p)
}
// Execute sends a command and parameters to the pump and returns its response.
// 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 {
return pump.perform(cmd, cmd, shortPumpPacket(cmd))
}
pump.perform(cmd, ack, shortPumpPacket(cmd))
if pump.NoResponse() {
pump.SetError(fmt.Errorf("%v command not performed", cmd))
return nil
}
t := pump.Timeout()
defer pump.SetTimeout(t)
pump.SetTimeout(2 * t)
return pump.perform(cmd, ack, longPumpPacket(cmd, 0, params))
}
// ExtendedRequest sends a command and a sequence of parameter packets
// to the pump and returns its response.
func (pump *Pump) ExtendedRequest(cmd Command, params ...byte) []byte {
seqNum := 1
i := 0
var result []byte
done := false
for !done && pump.Error() == nil {
j := i + payloadLength
if j >= len(params) {
done = true
j = len(params)
}
if seqNum == 1 {
pump.perform(cmd, ack, shortPumpPacket(cmd))
if pump.NoResponse() {
pump.SetError(fmt.Errorf("%v command not performed", cmd))
break
}
}
p := longPumpPacket(cmd, seqNum, params[i:j])
data := pump.perform(cmd, ack, p)
result = append(result, data...)
seqNum++
i = j
}
if done {
t := pump.Timeout()
defer pump.SetTimeout(t)
pump.SetTimeout(2 * t)
p := longPumpPacket(cmd, seqNum|doneBit, nil)
data := pump.perform(cmd, ack, p)
result = append(result, data...)
}
return result
}
// ExtendedResponse sends a command and parameters to the pump and
// collects the sequence of packets that make up its response.
func (pump *Pump) ExtendedResponse(cmd Command, params ...byte) []byte {
var result []byte
data := pump.Execute(cmd, params...)
expected := 1
retries := pump.Retries()
defer pump.SetRetries(retries)
pump.SetRetries(1)
for pump.Error() == nil {
if len(data) != fragmentLength {
pump.SetError(fmt.Errorf("%v: received %d-byte response", cmd, len(data)))
break
}
seqNum := int(data[0] &^ doneBit)
if seqNum != expected {
pump.SetError(fmt.Errorf("%v: received response %d instead of %d", cmd, seqNum, expected))
break
}
result = append(result, data[1:]...)
if data[0]&doneBit != 0 {
break
}
// Acknowledge this fragment.
data = pump.perform(ack, cmd, ackPacket)
expected++
}
return result
}
// History pages are returned as a series of 65-byte fragments:
// sequence number (1 to numFragments)
// 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.
type pageStructure struct {
numFragments int // 16 or 32
historyPageSize int // 1024 or 2048, including CRC-16
paramBits int // 8 or 32
}
var pageData = map[Command]pageStructure{
historyPage: pageStructure{
numFragments: 16,
historyPageSize: 1024,
paramBits: 8,
},
glucosePage: pageStructure{
numFragments: 16,
historyPageSize: 1024,
paramBits: 32,
},
isigPage: pageStructure{
numFragments: 32,
historyPageSize: 2048,
paramBits: 32,
},
vcntrPage: pageStructure{
numFragments: 16,
historyPageSize: 1024,
paramBits: 8,
},
}
// Download requests the given history page from the pump.
func (pump *Pump) Download(cmd Command, page int) []byte {
data, ps := pump.execPage(cmd, page)
if pump.Error() != nil {
return nil
}
retries := pump.Retries()
defer pump.SetRetries(retries)
pump.SetRetries(1)
results := make([]byte, 0, ps.historyPageSize)
seq := 1
for {
payload, n := pump.checkFragment(ps, page, data, seq)
if pump.Error() != nil {
return nil
}
if n == seq {
results = append(results, payload...)
seq++
}
if n == ps.numFragments {
return pump.checkPageCRC(ps, page, results)
}
// Acknowledge the current fragment and receive the next.
next := pump.perform(ack, cmd, ackPacket)
if pump.Error() != nil {
if !pump.NoResponse() {
return nil
}
next = pump.handleNoResponse(cmd, page, seq)
}
data = next
}
}
func (pump *Pump) execPage(cmd Command, page int) ([]byte, pageStructure) {
ps := pageData[cmd]
switch ps.paramBits {
case 8:
return pump.Execute(cmd, byte(page)), ps
case 32:
return pump.Execute(cmd, marshalUint32(uint32(page))...), ps
default:
log.Panicf("%v: unexpected parameter size (%d)", cmd, ps.paramBits)
}
panic("unreachable")
}
// checkFragment verifies that a fragment has the expected sequence number
// and returns the payload and sequence number.
func (pump *Pump) checkFragment(ps pageStructure, page int, data []byte, expected int) ([]byte, int) {
if len(data) != fragmentLength {
pump.SetError(fmt.Errorf("history page %d: unexpected fragment length (%d)", page, len(data)))
return nil, 0
}
seqNum := int(data[0] &^ doneBit)
if seqNum > expected {
// Missed fragment.
pump.SetError(fmt.Errorf("history page %d: received fragment %d instead of %d", page, seqNum, expected))
return nil, 0
}
if seqNum < expected {
// Skip duplicate responses.
return nil, seqNum
}
// This is the next fragment.
done := data[0]&doneBit != 0
if (done && seqNum != ps.numFragments) || (!done && seqNum == ps.numFragments) {
pump.SetError(fmt.Errorf("history page %d: unexpected final sequence number (%d)", page, seqNum))
return nil, seqNum
}
return data[1:], seqNum
}
// handleNoResponse sends NAKs to request retransmission of the expected fragment.
func (pump *Pump) handleNoResponse(cmd Command, page int, expected int) []byte {
for count := 0; count < maxNAKs; count++ {
pump.SetError(nil)
data := pump.perform(nak, cmd, shortPumpPacket(nak))
if pump.Error() == nil {
seqNum := int(data[0] &^ doneBit)
format := "history page %d: received fragment %d after %d NAK"
if count != 0 {
format += "s"
}
log.Printf(format, page, seqNum, count+1)
return data
}
if !pump.NoResponse() {
return nil
}
}
pump.SetError(fmt.Errorf("history page %d: lost fragment %d", page, expected))
return nil
}
// checkPageCRC verifies the history page CRC and returns the page data with the CRC removed.
// In a 2048-byte ISIG page, the CRC-16 is stored in the last 4 bytes: [high 0 low 0]
func (pump *Pump) checkPageCRC(ps pageStructure, page int, data []byte) []byte {
if len(data) != ps.historyPageSize {
pump.SetError(fmt.Errorf("history page %d: unexpected size (%d)", page, len(data)))
return nil
}
var dataCRC uint16
switch ps.historyPageSize {
case 1024:
dataCRC = twoByteUint(data[1022:])
data = data[:1022]
case 2048:
dataCRC = uint16(data[2044])<<8 | uint16(data[2046])
data = data[:2044]
default:
log.Panicf("unexpected history page size (%d)", ps.historyPageSize)
}
calcCRC := packet.CRC16(data)
if calcCRC != dataCRC {
pump.SetError(fmt.Errorf("history page %d: computed CRC %04X but received %04X", page, calcCRC, dataCRC))
return nil
}
return data
}
func (pump *Pump) perform(cmd Command, resp Command, p []byte) []byte {
if pump.Error() != nil {
return nil
}
maxTries := pump.retries
if len(p) == encodedLongPacketLength {
// Don't attempt state-changing commands more than once.
maxTries = 1
}
for tries := 0; tries < maxTries; tries++ {
pump.SetError(nil)
response, rssi := pump.Radio.SendAndReceive(p, pump.Timeout())
if pump.Error() != nil {
continue
}
if len(response) == 0 {
pump.SetError(NoResponseError(cmd))
continue
}
data, err := packet.Decode(response)
if err != nil {
pump.SetError(err)
continue
}
if pump.unexpected(cmd, resp, data) {
return nil
}
logTries(cmd, tries)
pump.rssi = rssi
return data[5:]
}
if pump.Error() == nil {
panic("perform")
}
return nil
}
func logTries(cmd Command, tries int) {
if tries == 0 {
return
}
r := "retries"
if tries == 1 {
r = "retry"
}
log.Printf("%v command required %d %s", cmd, tries, r)
}
func (pump *Pump) unexpected(cmd Command, resp Command, data []byte) bool {
if len(data) < 6 {
pump.BadResponse(cmd, data)
return true
}
if !bytes.Equal(data[:4], shortPacket[:4]) {
pump.BadResponse(cmd, data)
return true
}
switch Command(data[4]) {
case cmd:
return false
case resp:
return false
case ack:
if cmd == cgmWriteTimestamp || cmd == wakeup {
return false
}
pump.BadResponse(cmd, data)
return true
case nak:
pump.SetError(InvalidCommandError{
Command: cmd,
PumpError: PumpError(data[5]),
})
return true
default:
pump.BadResponse(cmd, data)
return true
}
}