This repository has been archived by the owner on May 5, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
cnl24driverlib.py
1912 lines (1573 loc) · 80.2 KB
/
cnl24driverlib.py
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
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
###############################################################################
#
# Contour Next Link 2.4 driver library
#
# Description:
#
# This is the driver library for the Contour Next Link 2.4 USB radio bridge
# to read the data from the Medtronic Minimed 670G insulin pump
#
# It is an adaptation of the original driver code from Lennart Goedhart:
# https://github.com/pazaan/decoding-contour-next-link
#
# Changes:
# 30/03/2020: Backport comms robustness improvements from Android uploader
# 06/04/2020: Extract more sensor related data from pump status message
# 13/04/2020: Return complete pump status data in statusDownload()
# 28/06/2020: Updated syntax for Python3
# 09/11/2020: Add calculation of pump time drift
#
###############################################################################
import logging
# logging.basicConfig has to be before astm import, otherwise logs don't appear
logging.basicConfig(format='%(asctime)s %(levelname)s [%(name)s] %(message)s', level=logging.WARNING)
import hid # pip install hidapi - Platform independant
import astm # pip install astm
import crc16 # pip install crc16
import lzo # pip install python-lzo
import Crypto.Cipher.AES # pip install PyCrypto
import struct
import datetime
import binascii
import sqlite3
import hashlib
import re
from helpers import DateTimeHelper
logger = logging.getLogger(__name__)
ascii= {
'STX' : 0x02,
'ETX' : 0x03,
'EOT' : 0x04,
'ENQ' : 0x05,
'ACK' : 0x06,
'LF' : 0x0A,
'CR' : 0x0D,
'NAK' : 0x15,
'ETB' : 0x17
}
def ord_hack(char_or_byte):
return char_or_byte if isinstance(char_or_byte, int) else ord(char_or_byte)
class COM_D_COMMAND:
HIGH_SPEED_MODE_COMMAND = 0x0412
TIME_REQUEST = 0x0403
TIME_RESPONSE = 0x0407
READ_PUMP_STATUS_REQUEST = 0x0112
READ_PUMP_STATUS_RESPONSE = 0x013C
READ_BASAL_PATTERN_REQUEST = 0x0116
READ_BASAL_PATTERN_RESPONSE = 0x0123
READ_BOLUS_WIZARD_CARB_RATIOS_REQUEST = 0x012B
READ_BOLUS_WIZARD_CARB_RATIOS_RESPONSE = 0x012C
READ_BOLUS_WIZARD_SENSITIVITY_FACTORS_REQUEST = 0x012E
READ_BOLUS_WIZARD_SENSITIVITY_FACTORS_RESPONSE = 0x012F
READ_BOLUS_WIZARD_BG_TARGETS_REQUEST = 0x0131
READ_BOLUS_WIZARD_BG_TARGETS_RESPONSE = 0x0132
DEVICE_STRING_REQUEST = 0x013A
DEVICE_STRING_RESPONSE = 0x013B
DEVICE_CHARACTERISTICS_REQUEST = 0x0200
DEVICE_CHARACTERISTICS_RESPONSE = 0x0201
READ_HISTORY_REQUEST = 0x0304
READ_HISTORY_RESPONSE = 0x0305
END_HISTORY_TRANSMISSION = 0x030A
READ_HISTORY_INFO_REQUEST = 0x030C
READ_HISTORY_INFO_RESPONSE = 0x030D
UNMERGED_HISTORY_RESPONSE = 0x030E
INITIATE_MULTIPACKET_TRANSFER = 0xFF00
MULTIPACKET_SEGMENT_TRANSMISSION = 0xFF01
MULTIPACKET_RESEND_PACKETS = 0xFF02
ACK_MULTIPACKET_COMMAND = 0x00FE # TODO ACK_COMMAND
NAK_COMMAND = 0x00FF
BOLUSES_REQUEST = 0x0114
REMOTE_BOLUS_REQUEST = 0x0100
REQUEST_0x0124 = 0x0124
REQUEST_0x0405 = 0x0405
TEMP_BASAL_REQUEST = 0x0115
SUSPEND_RESUME_REQUEST = 0x0107
NGP_PARAMETER_REQUEST = 0x0138
class HISTORY_DATA_TYPE:
PUMP_DATA = 0x02
SENSOR_DATA = 0x03
class TimeoutException( Exception ):
pass
class ChecksumException( Exception ):
pass
class UnexpectedMessageException( Exception ):
pass
class UnexpectedStateException( Exception ):
pass
class NegotiationException( Exception ):
pass
class InvalidMessageError( Exception ):
pass
class ChecksumError( Exception ):
pass
class DataIncompleteError( Exception ):
pass
class Config( object ):
def __init__( self, stickSerial ):
self.conn = sqlite3.connect( 'read_minimed.db' )
self.c = self.conn.cursor()
self.c.execute( '''CREATE TABLE IF NOT EXISTS
config ( stick_serial TEXT PRIMARY KEY, hmac TEXT, key TEXT, last_radio_channel INTEGER )''' )
self.c.execute( "INSERT OR IGNORE INTO config VALUES ( ?, ?, ?, ? )", ( stickSerial, '', '', 0x14 ) )
self.conn.commit()
self.loadConfig( stickSerial )
def loadConfig( self, stickSerial ):
self.c.execute( 'SELECT * FROM config WHERE stick_serial = ?', ( stickSerial, ) )
self.data = self.c.fetchone()
@property
def stickSerial( self ):
return self.data[0]
@property
def lastRadioChannel( self ):
return self.data[3]
@lastRadioChannel.setter
def lastRadioChannel( self, value ):
self.c.execute( "UPDATE config SET last_radio_channel = ? WHERE stick_serial = ?", ( value, self.stickSerial ) )
self.conn.commit()
self.loadConfig( self.stickSerial )
@property
def hmac( self ):
return self.data[1]
@hmac.setter
def hmac( self, value ):
self.c.execute( "UPDATE config SET hmac = ? WHERE stick_serial = ?", ( value, self.stickSerial ) )
self.conn.commit()
self.loadConfig( self.stickSerial )
@property
def key( self ):
return self.data[2]
@key.setter
def key( self, value ):
self.c.execute( "UPDATE config SET key = ? WHERE stick_serial = ?", ( value, self.stickSerial ) )
self.conn.commit()
self.loadConfig( self.stickSerial )
class MedtronicSession( object ):
radioChannel = None
bayerSequenceNumber = 1
minimedSequenceNumber = 1
sendSequenceNumber = 0
@property
def HMAC( self ):
serial = bytearray( re.sub( r"\d+-", "", self.stickSerial ), 'ascii' )
paddingKey = b"A4BD6CED9A42602564F413123"
digest = hashlib.sha256(serial + paddingKey).hexdigest()
return "".join(reversed([digest[i:i+2] for i in range(0, len(digest), 2)]))
@property
def hexKey( self ):
if self.config.key == "":
raise Exception( "Key not found in config database. Run get_hmac_and_key.py to get populate HMAC and key." )
return self.config.key
@property
def stickSerial( self ):
return self._stickSerial
@stickSerial.setter
def stickSerial( self, value ):
self._stickSerial = value
self.config = Config( self.stickSerial )
self.radioChannel = self.config.lastRadioChannel
@property
def linkMAC( self ):
return self._linkMAC
@linkMAC.setter
def linkMAC( self, value ):
self._linkMAC = value
@property
def pumpMAC( self ):
return self._pumpMAC
@pumpMAC.setter
def pumpMAC( self, value ):
self._pumpMAC = value
@property
def linkSerial( self ):
return self.linkMAC & 0xffffff
@property
def pumpSerial( self ):
return self.pumpMAC & 0xffffff
@property
def KEY( self ):
return self._key
@KEY.setter
def KEY( self, value ):
self._key = value
@property
def IV( self ):
tmp = bytearray()
tmp.append(self.radioChannel)
tmp += self.KEY[1:]
return bytes(tmp)
class MedtronicMessage( object ):
ENVELOPE_SIZE = 2
def __init__( self, commandAction=None, session=None, payload=None ):
self.commandAction = commandAction
self.session = session
if payload:
self.setPayload( payload )
def setPayload( self, payload ):
self.payload = payload
self.envelope = struct.pack( '<BB', self.commandAction,
len( self.payload ) + self.ENVELOPE_SIZE )
@classmethod
def calculateCcitt( self, data ):
crc = crc16.crc16xmodem( bytes(data), 0xffff )
return crc & 0xffff
def pad( self, x, n = 16 ):
p = n - ( len( x ) % n )
return x + bytes(bytearray(p))#chr(p) * p
# Encrpytion equivalent to Java's AES/CFB/NoPadding mode
def encrypt( self, clear ):
cipher = Crypto.Cipher.AES.new(
key=self.session.KEY,
mode=Crypto.Cipher.AES.MODE_CFB,
IV=self.session.IV,
segment_size=128
)
encrypted = cipher.encrypt(self.pad(clear))[0:len(clear)]
return encrypted
# Decryption equivalent to Java's AES/CFB/NoPadding mode
def decrypt( self, encrypted ):
cipher = Crypto.Cipher.AES.new(
key=self.session.KEY,
mode=Crypto.Cipher.AES.MODE_CFB,
IV=self.session.IV,
segment_size=128
)
decrypted = cipher.decrypt(self.pad(encrypted))[0:len(encrypted)]
return decrypted
def encode( self ):
# Increment the Minimed Sequence Number
self.session.minimedSequenceNumber += 1
message = self.envelope + self.payload
crc = struct.pack( '<H', crc16.crc16xmodem( message, 0xffff ) & 0xffff )
return message + crc
@classmethod
def decode( cls, message, session ):
response = cls()
response.session = session
response.envelope = message[0:2]
response.payload = message[2:-2]
response.originalMessage = message
checksum = struct.unpack( '<H', message[-2:] )[0]
calcChecksum = MedtronicMessage.calculateCcitt( response.envelope + response.payload )
if( checksum != calcChecksum ):
raise ChecksumException( 'Expected to get {0}. Got {1}'.format( calcChecksum, checksum ) )
return response
class ChannelNegotiateMessage( MedtronicMessage ):
def __init__( self, session ):
MedtronicMessage.__init__( self, 0x03, session )
# The minimedSequenceNumber is always sent as 1 for this message,
# even though the sequence should keep incrementing as normal
payload = struct.pack( '<BB8s', 1, session.radioChannel,
b'\x00\x00\x00\x07\x07\x00\x00\x02' )
payload += struct.pack( '<Q', session.linkMAC )
payload += struct.pack( '<Q', session.pumpMAC )
self.setPayload( payload )
class MedtronicSendMessage( MedtronicMessage ):
def __init__( self, messageType, session, payload=None ):
MedtronicMessage.__init__( self, 0x05, session )
# FIXME - make this not be hard coded
if messageType == COM_D_COMMAND.HIGH_SPEED_MODE_COMMAND:
seqNo = self.session.sendSequenceNumber | 0x80
else:
seqNo = self.session.sendSequenceNumber
encryptedPayload = struct.pack( '>BH', seqNo, messageType )
if payload:
encryptedPayload += payload
crc = crc16.crc16xmodem( encryptedPayload, 0xffff )
encryptedPayload += struct.pack( '>H', crc & 0xffff )
#logger.debug("### PAYLOAD")
#logger.debug(binascii.hexlify( encryptedPayload ))
mmPayload = struct.pack( '<QBBB',
self.session.pumpMAC,
self.session.minimedSequenceNumber,
0x11, # Mode flags
len( encryptedPayload )
)
mmPayload += self.encrypt( encryptedPayload )
self.setPayload( mmPayload )
self.session.sendSequenceNumber += 1
class MedtronicReceiveMessage( MedtronicMessage ):
@classmethod
def decode( cls, message, session ):
response = MedtronicMessage.decode( message, session )
# TODO - check validity of the envelope
response.responseEnvelope = response.payload[0:22]
decryptedResponsePayload = response.decrypt( bytes(response.payload[22:]) )
response.responsePayload = decryptedResponsePayload[0:-2]
#logger.debug("### DECRYPTED PAYLOAD:")
#logger.debug(binascii.hexlify( response.responsePayload ))
if len( response.responsePayload ) > 2:
checksum = struct.unpack( '>H', decryptedResponsePayload[-2:])[0]
calcChecksum = MedtronicMessage.calculateCcitt( response.responsePayload )
if( checksum != calcChecksum ):
raise ChecksumException( 'Expected to get {0}. Got {1}'.format( calcChecksum, checksum ) )
response.__class__ = MedtronicReceiveMessage
if response.messageType == COM_D_COMMAND.TIME_RESPONSE:
response.__class__ = PumpTimeResponseMessage
elif response.messageType == COM_D_COMMAND.READ_HISTORY_INFO_RESPONSE:
response.__class__ = PumpHistoryInfoResponseMessage
elif response.messageType == COM_D_COMMAND.READ_PUMP_STATUS_RESPONSE:
response.__class__ = PumpStatusResponseMessage
elif response.messageType == COM_D_COMMAND.INITIATE_MULTIPACKET_TRANSFER:
response.__class__ = MultiPacketSegment
elif response.messageType == COM_D_COMMAND.MULTIPACKET_SEGMENT_TRANSMISSION:
response.__class__ = MultiPacketSegment
elif response.messageType == COM_D_COMMAND.END_HISTORY_TRANSMISSION:
response.__class__ = MultiPacketSegment
return response
@property
def messageType( self ):
return struct.unpack( '>H', self.responsePayload[1:3] )[0]
class ReadInfoResponseMessage( object ):
@classmethod
def decode( cls, message ):
response = cls()
response.responsePayload = message
return response
@property
def linkMAC( self ):
return struct.unpack( '>Q', self.responsePayload[0:8] )[0]
@property
def pumpMAC( self ):
return struct.unpack( '>Q', self.responsePayload[8:16] )[0]
class ReadLinkKeyResponseMessage( object ):
@classmethod
def decode( cls, message ):
response = cls()
response.responsePayload = message
return response
@property
def packedLinkKey( self ):
return struct.unpack( '>55s', self.responsePayload[0:55] )[0]
def linkKey( self, serialNumber ):
key = bytearray(b"")
pos = ord_hack( serialNumber[-1:] ) & 7
for it in range(16):
if ( ord_hack( self.packedLinkKey[pos + 1] ) & 1) == 1:
key.append(~ord_hack( self.packedLinkKey[pos] ) & 0xff)
else:
key.append(self.packedLinkKey[pos])
if (( ord_hack( self.packedLinkKey[pos + 1] ) >> 1 ) & 1 ) == 0:
pos += 3
else:
pos += 2
return key
class PumpTimeResponseMessage( MedtronicReceiveMessage ):
@classmethod
def decode( cls, message, session ):
response = MedtronicReceiveMessage.decode( message, session )
if response.messageType != COM_D_COMMAND.TIME_RESPONSE:
raise UnexpectedMessageException( "Expected to get a Time Response message '{0}'. Got {1}.".format( COM_D_COMMAND.TIME_RESPONSE, response.messageType ) )
# Since we only add behaviour, we can cast this class to ourselves
response.__class__ = PumpTimeResponseMessage
return response
@property
def timeSet( self ):
if self.responsePayload[3] == 0:
return False
else:
return True
@property
def encodedDatetime( self ):
return struct.unpack( '>Q', self.responsePayload[4:] )[0]
@property
def datetime( self ):
dateTimeData = self.encodedDatetime
return DateTimeHelper.decodeDateTime( dateTimeData )
@property
def offset( self ):
dateTimeData = self.encodedDatetime
return DateTimeHelper.decodeDateTimeOffset( dateTimeData )
class PumpHistoryInfoResponseMessage( MedtronicReceiveMessage ):
@classmethod
def decode( cls, message, session ):
response = MedtronicReceiveMessage.decode( message, session )
if response.messageType != COM_D_COMMAND.READ_HISTORY_INFO_RESPONSE:
raise UnexpectedMessageException( "Expected to get a Time Response message '{0}'. Got {1}.".format( COM_D_COMMAND.READ_HISTORY_INFO_RESPONSE, response.messageType ) )
# Since we only add behaviour, we can cast this class to ourselves
response.__class__ = PumpHistoryInfoResponseMessage
return response
@property
def historySize( self ):
return struct.unpack( '>I', self.responsePayload[4:8] )[0]
@property
def encodedDatetimeStart( self ):
return struct.unpack( '>Q', self.responsePayload[8:16] )[0]
@property
def encodedDatetimeEnd( self ):
return struct.unpack( '>Q', self.responsePayload[16:24] )[0]
@property
def datetimeStart( self ):
dateTimeData = self.encodedDatetimeStart
return DateTimeHelper.decodeDateTime( dateTimeData )
@property
def datetimeEnd( self ):
dateTimeData = self.encodedDatetimeEnd
return DateTimeHelper.decodeDateTime( dateTimeData )
class MultiPacketSegment( MedtronicReceiveMessage ):
@classmethod
def decode( cls, message, session ):
response = MedtronicReceiveMessage.decode( message, session )
# Since we only add behaviour, we can cast this class to ourselves
response.__class__ = MultiPacketSegment
return response
@property
def packetNumber( self ):
return struct.unpack( '>H', self.responsePayload[3:5] )[0]
@property
def payload( self ):
return self.responsePayload[5:]
@property
def segmentSize( self ):
return struct.unpack( '>I', self.responsePayload[3:7] )[0]
@property
def packetSize( self ):
return struct.unpack( '>H', self.responsePayload[7:9] )[0]
@property
def lastPacketSize( self ):
return struct.unpack( '>H', self.responsePayload[9:11] )[0]
@property
def packetsToFetch( self ):
return struct.unpack( '>H', self.responsePayload[11:13] )[0]
class PumpStatusResponseMessage( MedtronicReceiveMessage ):
MMOL = 1
MGDL = 2
@classmethod
def decode( cls, message, session ):
response = MedtronicReceiveMessage.decode( message, session )
if response.messageType != COM_D_COMMAND.READ_PUMP_STATUS_RESPONSE:
raise UnexpectedMessageException( "Expected to get a Status Response message '{0}'. Got {1}.".format( COM_D_COMMAND.READ_PUMP_STATUS_RESPONSE, response.messageType ) )
# Since we only add behaviour, we can cast this class to ourselves
response.__class__ = PumpStatusResponseMessage
return response
# see https://github.com/pazaan/600SeriesAndroidUploader/blob/master/app/src/main/java/info/nightscout/android/medtronic/message/PumpStatusResponseMessage.java
@property
def isPumpStatusSuspended( self ):
if ( struct.unpack( '>B', self.responsePayload[0x03:0x04] )[0] ) & 0x01 :
return 1
else:
return 0
@property
def isPumpStatusBolusingNormal( self ):
if ( struct.unpack( '>B', self.responsePayload[0x03:0x04] )[0] ) & 0x02 :
return 1
else:
return 0
@property
def isPumpStatusBolusingSquare( self ):
if ( struct.unpack( '>B', self.responsePayload[0x03:0x04] )[0] ) & 0x04 :
return 1
else:
return 0
@property
def isPumpStatusBolusingDual( self ):
if ( struct.unpack( '>B', self.responsePayload[0x03:0x04] )[0] ) & 0x08 :
return 1
else:
return 0
@property
def isPumpStatusDeliveringInsulin( self ):
if ( struct.unpack( '>B', self.responsePayload[0x03:0x04] )[0] ) & 0x10 :
return 1
else:
return 0
@property
def isPumpStatusTempBasalActive( self ):
if ( struct.unpack( '>B', self.responsePayload[0x03:0x04] )[0] ) & 0x20 :
return 1
else:
return 0
@property
def isPumpStatusCgmActive( self ):
if ( struct.unpack( '>B', self.responsePayload[0x03:0x04] )[0] ) & 0x40 :
return 1
else:
return 0
@property
def bolusingDelivered( self ):
return float( struct.unpack( '>I', self.responsePayload[0x04:0x08] )[0] ) / 10000
@property
def bolusingMinutesRemaining( self ):
return int( struct.unpack( '>H', self.responsePayload[0x0c:0x0e] )[0] )
@property
def bolusingReference( self ):
return int( struct.unpack( '>B', self.responsePayload[0x0e:0x0f] )[0] )
@property
def lastBolusAmount(self):
return float(struct.unpack('>I', self.responsePayload[0x10:0x14])[0]) / 10000
@property
def lastBolusTime(self):
dateTimeData = struct.unpack('>L', self.responsePayload[0x14:0x18])[0]
return DateTimeHelper.decodeDateTime(dateTimeData, 0)
@property
def lastBolusReference( self ):
return int( struct.unpack( '>B', self.responsePayload[0x18:0x19] )[0] )
@property
def activeBasalPattern( self ):
return int( struct.unpack( '>B', self.responsePayload[0x1a:0x1b] )[0] ) & 0x0F
@property
def activeTempBasalPattern( self ):
return int( (struct.unpack( '>B', self.responsePayload[0x1a:0x1b] )[0] ) >> 4 ) & 0x0F
@property
def currentBasalRate( self ):
return float( struct.unpack( '>I', self.responsePayload[0x1b:0x1f] )[0] ) / 10000
@property
def tempBasalRate( self ):
return float( struct.unpack( '>I', self.responsePayload[0x1f:0x23] )[0] ) / 10000
@property
def tempBasalPercentage( self ):
return int( struct.unpack( '>B', self.responsePayload[0x23:0x24] )[0] )
@property
def tempBasalMinutesRemaining( self ):
return int( struct.unpack( '>H', self.responsePayload[0x24:0x26] )[0] )
@property
def basalUnitsDeliveredToday( self ):
return float( struct.unpack( '>I', self.responsePayload[0x26:0x2a] )[0] ) / 10000
@property
def batteryLevelPercentage( self ):
return int( struct.unpack( '>B', self.responsePayload[0x2a:0x2b] )[0] )
@property
def insulinUnitsRemaining( self ):
return float( struct.unpack( '>I', self.responsePayload[0x2b:0x2f] )[0] ) / 10000
@property
def minutesOfInsulinRemaining( self ):
Hours = int(struct.unpack('>B', self.responsePayload[0x2f:0x30])[0])
Minutes = int( struct.unpack( '>B', self.responsePayload[0x30:0x31] )[0] )
return int ((Hours * 60) + Minutes)
@property
def activeInsulin( self ):
return float( struct.unpack( '>I', self.responsePayload[0x31:0x35] )[0] ) / 10000
@property
def sensorBGL( self ):
# // In mg/DL. 0x0000 = no CGM reading, 0x03NN = sensor exception
return int( struct.unpack( '>H', self.responsePayload[0x35:0x37] )[0] )
@property
def sensorBGLTimestamp( self ):
dateTimeData = struct.unpack( '>Q', self.responsePayload[0x37:0x3f] )[0]
return DateTimeHelper.decodeDateTime( dateTimeData )
@property
def isPlgmAlertOnHigh(self):
if (struct.unpack('>B', self.responsePayload[0x3f:0x40])[0]) & 0x01:
return 1
else:
return 0
@property
def isPlgmAlertOnLow(self):
if (struct.unpack('>B', self.responsePayload[0x3f:0x40])[0]) & 0x02:
return 1
else:
return 0
@property
def isPlgmAlertBeforeHigh(self):
if (struct.unpack('>B', self.responsePayload[0x3f:0x40])[0]) & 0x04:
return 1
else:
return 0
@property
def isPlgmAlertBeforeLow(self):
if (struct.unpack('>B', self.responsePayload[0x3f:0x40])[0]) & 0x08:
return 1
else:
return 0
@property
def isPlgmAlertSuspend(self):
if (struct.unpack('>B', self.responsePayload[0x3f:0x40])[0]) & 0x80:
return 1
else:
return 0
@property
def islgmAlertSuspendLow(self):
# needs discovery confirmation!
if (struct.unpack('>B', self.responsePayload[0x3f:0x40])[0]) & 0x10:
return 1
else:
return 0
@property
def trendArrow( self ):
status = int( struct.unpack( '>B', self.responsePayload[0x40:0x41] )[0] ) & 0xF0
if status == 0xc0:
return 3 #"3 arrows up"
elif status == 0xa0:
return 2 #"2 arrows up"
elif status == 0x80:
return 1 #"1 arrow up"
elif status == 0x60:
return 0 #"No arrows"
elif status == 0x40:
return -1 #"1 arrow down"
elif status == 0x20:
return -2 #"2 arrows down"
elif status == 0x00:
return -3 #"3 arrows down"
else:
return None #"Unknown trend"
@property
def isSensorStatusCalibrating( self ):
if ( struct.unpack( '>B', self.responsePayload[0x41:0x42] )[0] ) & 0x01 :
return 1
else:
return 0
@property
def isSensorStatusCalibrationComplete( self ):
if ( struct.unpack( '>B', self.responsePayload[0x41:0x42] )[0] ) & 0x02 :
return 1
else:
return 0
@property
def isSensorStatusException( self ):
if ( struct.unpack( '>B', self.responsePayload[0x41:0x42] )[0] ) & 0x04 :
return 1
else:
return 0
@property
def sensorCalMinutesRemaining( self ):
return int( struct.unpack( '>H', self.responsePayload[0x43:0x45] )[0] )
@property
def sensorBatteryLevelPercentage( self ):
sbatt_raw = int( struct.unpack( '>B', self.responsePayload[0x45:0x46] )[0] )
return int(round(((sbatt_raw & 0x0F) * 100.0) / 15.0))
@property
def sensorRateOfChange( self ):
return float( struct.unpack( '>h', self.responsePayload[0x46:0x48] )[0] ) / 100
@property
def recentBolusWizard( self ):
# Bitfield of the Bolus Wizard status. 0x01 if the Bolus Wizard has been used in the last 15 minutes
if self.responsePayload[0x48] == 0:
return 0
else:
return 1
@property
def recentBGL( self ):
# Blood Glucose Level entered into the Bolus Wizard, in mg/dL
return struct.unpack( '>H', self.responsePayload[0x49:0x4b] )[0]
#Active alert
@property
def alert( self ):
return struct.unpack( '>H', self.responsePayload[0x4b:0x4d] )[0]
@property
def alertDate( self ):
dateTimeData = struct.unpack( '>Q', self.responsePayload[0x4d:0x55] )[0]
return DateTimeHelper.decodeDateTime( dateTimeData )
@property
def isAlertSilenceHigh(self):
if (struct.unpack('>B', self.responsePayload[0x55:0x56])[0]) & 0x01:
return 1
else:
return 0
@property
def isAlertSilenceHighLow(self):
if (struct.unpack('>B', self.responsePayload[0x55:0x56])[0]) & 0x02:
return 1
else:
return 0
@property
def isAlertSilenceAll(self):
if (struct.unpack('>B', self.responsePayload[0x55:0x56])[0]) & 0x04:
return 1
else:
return 0
@property
def alertSilenceMinutesRemaining(self):
return struct.unpack( '>H', self.responsePayload[0x56:0x58] )[0]
##############################
class BeginEHSMMessage( MedtronicSendMessage ):
def __init__( self, session ):
payload = struct.pack( '>B', 0x00 )
MedtronicSendMessage.__init__( self, COM_D_COMMAND.HIGH_SPEED_MODE_COMMAND, session, payload )
class FinishEHSMMessage( MedtronicSendMessage ):
def __init__( self, session ):
payload = struct.pack( '>B', 0x01 )
MedtronicSendMessage.__init__( self, COM_D_COMMAND.HIGH_SPEED_MODE_COMMAND, session, payload )
class PumpTimeRequestMessage( MedtronicSendMessage ):
def __init__( self, session ):
MedtronicSendMessage.__init__( self, COM_D_COMMAND.TIME_REQUEST, session )
class PumpStatusRequestMessage( MedtronicSendMessage ):
def __init__( self, session ):
MedtronicSendMessage.__init__( self, COM_D_COMMAND.READ_PUMP_STATUS_REQUEST, session )
class PumpHistoryInfoRequestMessage( MedtronicSendMessage ):
def __init__( self, session, dateStart, dateEnd, dateOffset, requestType = HISTORY_DATA_TYPE.PUMP_DATA):
histDataType_PumpData = requestType
fromRtc = DateTimeHelper.rtcFromDate(dateStart, dateOffset)
toRtc = DateTimeHelper.rtcFromDate(dateEnd, dateOffset)
payload = struct.pack( '>BBIIH', histDataType_PumpData, 0x04, fromRtc, toRtc, 0x00 )
MedtronicSendMessage.__init__( self, COM_D_COMMAND.READ_HISTORY_INFO_REQUEST, session, payload )
class PumpHistoryRequestMessage( MedtronicSendMessage ):
def __init__( self, session, dateStart, dateEnd, dateOffset, requestType = HISTORY_DATA_TYPE.PUMP_DATA ):
histDataType_PumpData = requestType
fromRtc = DateTimeHelper.rtcFromDate(dateStart, dateOffset)
toRtc = DateTimeHelper.rtcFromDate(dateEnd, dateOffset)
payload = struct.pack( '>BBIIH', histDataType_PumpData, 0x04, fromRtc, toRtc, 0x00 )
MedtronicSendMessage.__init__( self, COM_D_COMMAND.READ_HISTORY_REQUEST, session, payload )
class AckMultipacketRequestMessage( MedtronicSendMessage ):
SEGMENT_COMMAND__INITIATE_TRANSFER = COM_D_COMMAND.INITIATE_MULTIPACKET_TRANSFER
SEGMENT_COMMAND__SEND_NEXT_SEGMENT = COM_D_COMMAND.MULTIPACKET_SEGMENT_TRANSMISSION
def __init__( self, session, segmentCommand ):
payload = struct.pack( '>H', segmentCommand )
MedtronicSendMessage.__init__( self, COM_D_COMMAND.ACK_MULTIPACKET_COMMAND, session, payload )
class BasicNgpParametersRequestMessage( MedtronicSendMessage ):
def __init__( self, session ):
MedtronicSendMessage.__init__( self, COM_D_COMMAND.NGP_PARAMETER_REQUEST, session )
class DeviceCharacteristicsRequestMessage( MedtronicSendMessage ):
def __init__( self, session ):
MedtronicSendMessage.__init__( self, COM_D_COMMAND.DEVICE_CHARACTERISTICS_REQUEST, session )
class SuspendResumeRequestMessage( MedtronicSendMessage ):
def __init__( self, session ):
# TODO: Bug? Shall the payload be passed to the message, or not needed?
payload = struct.pack( '>B', 0x01 )
MedtronicSendMessage.__init__( self, COM_D_COMMAND.SUSPEND_RESUME_REQUEST, session )
class PumpTempBasalRequestMessage( MedtronicSendMessage ):
def __init__( self, session ):
MedtronicSendMessage.__init__( self, COM_D_COMMAND.TEMP_BASAL_REQUEST, session )
class PumpBolusesRequestMessage( MedtronicSendMessage ):
def __init__( self, session ):
MedtronicSendMessage.__init__( self, COM_D_COMMAND.BOLUSES_REQUEST, session )
class PumpRemoteBolusRequestMessage( MedtronicSendMessage ):
def __init__( self, session, bolusID, amount, execute ):
unknown1 = 0 # ??
unknown2 = 0 # Square Wave amount?
unknown3 = 0 # Square Wave length?
payload = struct.pack( '>BBHHBH', bolusID, execute, unknown1, amount * 10000, unknown2, unknown3 )
MedtronicSendMessage.__init__( self, COM_D_COMMAND.REMOTE_BOLUS_REQUEST, session, payload )
class Type405RequestMessage( MedtronicSendMessage ):
def __init__( self, session, pumpDateTime ):
payload = struct.pack( '>BQ', 0x01, pumpDateTime )
MedtronicSendMessage.__init__( self, COM_D_COMMAND.REQUEST_0x0405, session, payload )
class Type124RequestMessage( MedtronicSendMessage ):
def __init__( self, session, pumpDateTime ):
payload = struct.pack( '>QBB', pumpDateTime, 0x00, 0xFF )
MedtronicSendMessage.__init__( self, COM_D_COMMAND.REQUEST_0x0124, session, payload )
class BayerBinaryMessage( object ):
def __init__( self, messageType=None, session=None, payload=None ):
self.payload = payload
self.session = session
if messageType and self.session:
self.envelope = struct.pack( '<BB6s10sBI5sI', 0x51, 3, b'000000', b'\x00' * 10,
messageType, self.session.bayerSequenceNumber, b'\x00' * 5,
len( self.payload ) if self.payload else 0 )
self.envelope += struct.pack( 'B', self.makeMessageCrc() )
def makeMessageCrc( self ):
checksum = 0
for x in self.envelope[0:32]:
checksum += ord_hack(x)
#checksum = sum( bytearray(self.envelope[0:32], 'utf-8') )
if self.payload:
checksum += sum( bytearray( self.payload ) )
return checksum & 0xff
def encode( self ):
# Increment the Bayer Sequence Number
self.session.bayerSequenceNumber += 1
if self.payload:
return self.envelope + self.payload
else:
return self.envelope
@classmethod
def decode( cls, message ):
response = cls()
response.envelope = message[0:33]
response.payload = message[33:]
checksum = message[32]
calcChecksum = response.makeMessageCrc()
if( checksum != calcChecksum ):
logger.error('ChecksumException: Expected to get {0}. Got {1}'.format( calcChecksum, checksum ))
raise ChecksumException( 'Expected to get {0}. Got {1}'.format( calcChecksum, checksum ) )
return response
@property
def linkDeviceOperation( self ):
return ord_hack(self.envelope[18])
# HACK: This is just a debug try, session param shall not be there
def checkLinkDeviceOperation( self, expectedValue, session = None ):
if self.linkDeviceOperation != expectedValue:
logger.debug("### checkLinkDeviceOperation BayerBinaryMessage.envelope: {0}".format(binascii.hexlify(self.envelope)))
logger.debug("### checkLinkDeviceOperation BayerBinaryMessage.payload: {0}".format(binascii.hexlify(self.payload)))
# HACK: This is just a debug try
if self.linkDeviceOperation == 0x80:
response = MedtronicReceiveMessage.decode( self.payload, session )
logger.warning("#### Message type of caught 0x80: 0x{0:x}".format(response.messageType))
raise UnexpectedMessageException( "Expected to get linkDeviceOperation {0:x}. Got {1:x}".format( expectedValue, self.linkDeviceOperation ) )
class Medtronic600SeriesDriver( object ):
USB_BLOCKSIZE = 64
USB_VID = 0x1a79
USB_PID = 0x6210
MAGIC_HEADER = b'ABC'
ERROR_CLEAR_TIMEOUT_MS = 25000
PRESEND_CLEAR_TIMEOUT_MS = 50
READ_TIMEOUT_MS = 25000
CNL_READ_TIMEOUT_MS = 2000
CHANNELS = [ 0x14, 0x11, 0x0e, 0x17, 0x1a ] # In the order that the CareLink applet requests them
session = None
def __init__( self ):
self.session = MedtronicSession()
self.device = None
self.deviceInfo = None
def openDevice( self ):
logger.info("# Opening device")
self.device = hid.device()
self.device.open( self.USB_VID, self.USB_PID )
logger.info("Manufacturer: %s" % self.device.get_manufacturer_string())
logger.info("Product: %s" % self.device.get_product_string())
logger.info("Serial No: %s" % self.device.get_serial_number_string())
def closeDevice( self ):
logger.info("# Closing device")
self.device.close()
def readMessage( self, timeout_ms=READ_TIMEOUT_MS ):
payload = bytearray()
bytesRead = 0
payloadSize = 0
expectedSize = 0
first = True