-
Notifications
You must be signed in to change notification settings - Fork 48
/
read_minimed_next24.py
1974 lines (1610 loc) · 82.4 KB
/
read_minimed_next24.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
#!/usr/bin/env python
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)
# a nasty workaround on missing hidapi.dll on my windows (allows testing from saved files, but not download of pump)
try:
import hid # pip install hidapi - Platform independant
except WindowsError:
pass
import astm # pip install astm
import struct
import binascii
import datetime
import crc16 # pip install crc16
import Crypto.Cipher.AES # pip install PyCrypto
import sqlite3
import hashlib
import re
import pickle # needed for local history export
import lzo # pip install python-lzo
from .pump_history_parser import NGPHistoryEvent, BloodGlucoseReadingEvent
from .helpers import DateTimeHelper
from datetime import time, timedelta
logger = logging.getLogger(__name__)
ascii= {
'ACK' : 0x06,
'CR' : 0x0D,
'ENQ' : 0x05,
'EOT' : 0x04,
'ETB' : 0x17,
'ETX' : 0x03,
'LF' : 0x0A,
'NAK' : 0x15,
'STX' : 0x02
}
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 ):
def __init__( self, session=None, responsePayload=None ):
MedtronicMessage.__init__( self, session=session )
self.responsePayload = responsePayload
@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
elif response.messageType == COM_D_COMMAND.READ_BOLUS_WIZARD_CARB_RATIOS_RESPONSE:
response.__class__ = PumpBolusWizardCarbRatiosResponseMessage
elif response.messageType == COM_D_COMMAND.READ_BOLUS_WIZARD_SENSITIVITY_FACTORS_RESPONSE:
response.__class__ = PumpBolusWizardSensitivityFactorsResponseMessage
elif response.messageType == COM_D_COMMAND.READ_BOLUS_WIZARD_BG_TARGETS_RESPONSE:
response.__class__ = PumpBolusWizardBGTargetsResponseMessage
return response
@property
def messageType( self ):
return struct.unpack( '>H', self.responsePayload[1:3] )[0]
@property
def wholePayloadHex(self):
return binascii.hexlify(self.responsePayload).upper().decode("utf-8")
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
@property
def currentBasalRate( self ):
return float( struct.unpack( '>I', self.responsePayload[0x1b:0x1f] )[0] ) / 10000
@property
def tempBasalRate( self ):
return float( struct.unpack( '>H', self.responsePayload[0x21: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 batteryLevelPercentage( self ):
return int( struct.unpack( '>B', self.responsePayload[0x2a:0x2b] )[0] )
@property
def insulinUnitsRemaining( self ):
return int( struct.unpack( '>I', self.responsePayload[0x2b:0x2f] )[0] ) / 10000
@property
def activeInsulin( self ):
return float( struct.unpack( '>I', self.responsePayload[0x31:0x35] )[0] ) / 10000
@property
def sensorBGL( self ):
return int( struct.unpack( '>H', self.responsePayload[0x35:0x37] )[0] )
@property
def trendArrowValue(self):
if self.StatusCgm:
status = int( struct.unpack( '>B', self.responsePayload[0x40:0x41] )[0] )
if status & 0xF0 == 0x60:
return 0
elif status & 0xF0 == 0xc0:
return 3
elif status & 0xF0 == 0xa0:
return 2
elif status & 0xF0 == 0x80:
return 1
elif status & 0xF0 == 0x40:
return -1
elif status & 0xF0 == 0x20:
return -2
elif status & 0xF0 == 0x00:
return -3
else:
return None
else:
return None
@property
def trendArrow( self ):
if self.StatusCgm:
status = int( struct.unpack( '>B', self.responsePayload[0x40:0x41] )[0] )
if status & 0xF0 == 0x60:
return "No arrows"
elif status & 0xF0 == 0xc0:
return "3 arrows up"
elif status & 0xF0 == 0xa0:
return "2 arrows up"
elif status & 0xF0 == 0x80:
return "1 arrow up"
elif status & 0xF0 == 0x40:
return "1 arrow down"
elif status & 0xF0 == 0x20:
return "2 arrows down"
elif status & 0xF0 == 0x00:
return "3 arrows down"
elif status & 0xF0 == 0xE0:
return "Unknown trend"
else:
return None
@property
def sensorRateOfChangePerMin(self):
status = float(struct.unpack('>h', self.responsePayload[0x46:0x48])[0]) / 100
return status
@property
def sensorStatusValue(self):
status = int(struct.unpack('>B', self.responsePayload[0x41:0x42])[0])
return status
@property
def sensorStatus(self):
if not self.StatusCgm:
return None
status = int(struct.unpack('>B', self.responsePayload[0x41:0x42])[0])
ret = "Unknown sensor status: 0x{:02X}".format(status)
if status == 0x00:
ret = "Sensor init cycle."
elif status == 0x04:
ret = "Sensor not calibrated."
elif status == 0x10:
ret = "Sensor operational."
elif status == 0x14:
ret = "Sensor operational (high BGL)."
# value not observed so far on 640 pump
if status & 0x01 == 0x01:
ret = "{} Calibrating.".format(ret)
# value not observed so far on 640 pump
elif status & 0x02 == 0x02:
ret = "{} Calibration complete.".format(ret)
return ret
@property
def sensorControl(self):
status = int(struct.unpack('>B', self.responsePayload[0x42:0x43])[0])
return "0x{0:02X} ({0:08b})".format(status)
return status
@property
def sensorControlValue(self):
status = int(struct.unpack('>B', self.responsePayload[0x42:0x43])[0])
return status
@property
def sensorCalibrationMinutesRemaining(self):
minutes = int(struct.unpack('>H', self.responsePayload[0x43:0x45])[0])
return minutes
@property
def sensorBatteryPercent(self):
battery_percent = 100 * (0x0F & int(struct.unpack('>B', self.responsePayload[0x45:0x46])[0])) / 0x0F
return battery_percent
@property
def sensorBGLTimestamp( self ):
dateTimeData = struct.unpack( '>Q', self.responsePayload[55:63] )[0]
return DateTimeHelper.decodeDateTime( dateTimeData )
@property
def recentBolusWizard( self ):
if self.responsePayload[72] == 0:
return False
else:
return True
@property
def bolusWizardBGL( self ):
return struct.unpack( '>H', self.responsePayload[0x49:0x4B] )[0]
@property
def StatusValue(self):
status = int(struct.unpack('>B', self.responsePayload[0x03:0x04])[0])
return status
@property
def StatusCgm(self):
return self.StatusValue & 0x40 != 0
@property
def StatusTempBasal(self):
return self.StatusValue & 0x20 != 0
@property
def StatusInsulinDelivery(self):
return self.StatusValue & 0x10 != 0
@property
def StatusBolusingDual(self):
return self.StatusValue & 0x08 != 0
@property
def StatusBolusingSquare(self):
return self.StatusValue & 0x04 != 0
@property
def StatusBolusingNormal(self):
return self.StatusValue & 0x02 != 0
@property
def StatusSuspended(self):
return self.StatusValue & 0x01 != 0
@property
def Status(self):
status = {
"CGM Active": self.StatusCgm,
"Temp basal active": self.StatusTempBasal,
"Insulin delivery": self.StatusInsulinDelivery,
"Bolusing dual": self.StatusBolusingDual,
"Bolusing square": self.StatusBolusingSquare,
"Bolusing normal": self.StatusBolusingNormal,
"Suspended": self.StatusSuspended,
}
return status
@property
def lastBolusAmount( self ):
return float( struct.unpack( '>I', self.responsePayload[0x10:0x14] )[0] ) / 10000
@property
def lastBolusTimestamp( self ):
dateTimeData = struct.unpack( '>L', self.responsePayload[0x14:0x18])[0]
return DateTimeHelper.decodeDateTime( dateTimeData, 0 )
class PumpBolusWizardAbstractResponseMessage( MedtronicReceiveMessage ):
@classmethod
def get_record_size(cls):
pass
def getRecord(self, i):
pass
@property
def recordCount(self):
count = struct.unpack( '>B', self.responsePayload[0x05:0x06] )[0]
return count
def _get_record_part(self, index):
return self.responsePayload[0x06 + index * self.get_record_size():0x06 + (index + 1) * self.get_record_size()]
@property
def FullConfiguration(self):
return {
"count": self.recordCount,
"records": [
self.getRecord(i) for i in range(0, self.recordCount)
]
}
class PumpBolusWizardCarbRatiosResponseMessage( PumpBolusWizardAbstractResponseMessage ):
@classmethod
def decode( cls, message, session ):
response = MedtronicReceiveMessage.decode( message, session )
if response.messageType != COM_D_COMMAND.READ_BOLUS_WIZARD_CARB_RATIOS_RESPONSE:
raise UnexpectedMessageException( "Expected to get a Carb Ratios Response message '{0}'. Got {1}.".format( COM_D_COMMAND.READ_BOLUS_WIZARD_CARB_RATIOS_RESPONSE, response.messageType ) )
# Since we only add behaviour, we can cast this class to ourselves
response.__class__ = PumpBolusWizardCarbRatiosResponseMessage
return response
@classmethod
def get_record_size(cls):
return 9
def CarbRatio(self, index):
ratio = float(struct.unpack(">H", self._get_record_part(index)[0x06:0x08])[0]) / 1000
return ratio
def StartTime(self, index):
time_slot = struct.unpack(">B", self._get_record_part(index)[0x08:0x09])[0]
return time(int(time_slot / 2), 30 * (time_slot % 2))
def EndTime(self, index):
return self.StartTime(index + 1) \
if index + 1 != self.recordCount \
else time.max
def getRecord(self, i):
return {
"starttime": self.StartTime(i),
"endtime": self.EndTime(i),
"ratio": self.CarbRatio(i)
}
class PumpBolusWizardSensitivityFactorsResponseMessage( PumpBolusWizardAbstractResponseMessage ):
@classmethod
def decode( cls, message, session ):
response = MedtronicReceiveMessage.decode( message, session )
if response.messageType != COM_D_COMMAND.READ_BOLUS_WIZARD_CARB_RATIOS_RESPONSE:
raise UnexpectedMessageException( "Expected to get a Carb Ratios Response message '{0}'. Got {1}.".format( COM_D_COMMAND.READ_BOLUS_WIZARD_CARB_RATIOS_RESPONSE, response.messageType ) )
# Since we only add behaviour, we can cast this class to ourselves
response.__class__ = PumpBolusWizardSensitivityFactorsResponseMessage
return response
@classmethod
def get_record_size(cls):
return 5
def FactorMgDl(self, index):
factor = struct.unpack(">H", self._get_record_part(index)[0x00:0x02])[0]
return factor
def FactorMmolL(self, index):
factor = struct.unpack(">H", self._get_record_part(index)[0x02:0x04])[0]
return factor
def StartTime(self, index):
time_slot = struct.unpack(">B", self._get_record_part(index)[0x04:0x05])[0]
return time(int(time_slot / 2), 30 * (time_slot % 2))
def EndTime(self, index):
return self.StartTime(index + 1) \
if index + 1 != self.recordCount \
else time.max
def getRecord(self, i):
return {
"starttime": self.StartTime(i),
"endtime": self.EndTime(i),
"factorMgDl": self.FactorMgDl(i),
"factorMmolL": self.FactorMmolL(i),
}
class PumpBolusWizardBGTargetsResponseMessage( PumpBolusWizardAbstractResponseMessage ):
@classmethod
def decode( cls, message, session ):
response = MedtronicReceiveMessage.decode( message, session )
if response.messageType != COM_D_COMMAND.READ_BOLUS_WIZARD_CARB_RATIOS_RESPONSE:
raise UnexpectedMessageException( "Expected to get a Carb Ratios Response message '{0}'. Got {1}.".format( COM_D_COMMAND.READ_BOLUS_WIZARD_CARB_RATIOS_RESPONSE, response.messageType ) )
# Since we only add behaviour, we can cast this class to ourselves
response.__class__ = PumpBolusWizardBGTargetsResponseMessage
return response
@classmethod
def get_record_size(cls):
return 9
def LowTargetMgDl(self, index):
factor = struct.unpack(">H", self._get_record_part(index)[0x04:0x06])[0]
return factor
def LowTargetMmolL(self, index):
factor = struct.unpack(">H", self._get_record_part(index)[0x06:0x08])[0]
return factor
def HighTargetMgDl(self, index):
factor = struct.unpack(">H", self._get_record_part(index)[0x00:0x02])[0]
return factor
def HighTargetMmolL(self, index):
factor = struct.unpack(">H", self._get_record_part(index)[0x02:0x04])[0]
return factor
def StartTime(self, index):
time_slot = struct.unpack(">B", self._get_record_part(index)[0x08:0x09])[0]
return time(int(time_slot / 2), 30 * (time_slot % 2))
def EndTime(self, index):
return self.StartTime(index + 1) \
if index + 1 != self.recordCount \
else time.max
def getRecord(self, i):
return {
"starttime": self.StartTime(i),
"endtime": self.EndTime(i),
"lowTargetMgDl": self.LowTargetMgDl(i),
"lowTargetMmolL": self.LowTargetMmolL(i),
"highTargetMgDl": self.HighTargetMgDl(i),
"highTargetMmolL": self.HighTargetMmolL(i),
}
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 PumpBolusWizardCarbRatiosRequestMessage( MedtronicSendMessage ):
def __init__( self, session ):
MedtronicSendMessage.__init__( self, COM_D_COMMAND.READ_BOLUS_WIZARD_CARB_RATIOS_REQUEST, session )
class PumpBolusWizardSensitivityFactorsRequestMessage( MedtronicSendMessage ):
def __init__( self, session ):
MedtronicSendMessage.__init__( self, COM_D_COMMAND.READ_BOLUS_WIZARD_SENSITIVITY_FACTORS_REQUEST, session )
class PumpBolusWizardBGTargetsRequestMessage( MedtronicSendMessage ):
def __init__( self, session ):
MedtronicSendMessage.__init__( self, COM_D_COMMAND.READ_BOLUS_WIZARD_BG_TARGETS_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