summaryrefslogtreecommitdiff
path: root/dexcom_reader/dexcom_dumper.py
blob: c4db06a042c5a7471fc77bcb29f39c5d1e84b949 (plain)
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
#!/usr/bin/env python
import constants
import readdata
import sys
import json
import traceback
import subprocess
from devicer import simple_devicer
# import requests # As this takes SEVEN SECONDS, it's delayed until needed
from sys import stdout, stderr
from datetime import timedelta, datetime
from time import sleep
from itertools import islice, takewhile
from database_records import GenericTimestampedRecord, EGVRecord, EventRecord
# from pytz import UTC # Since the dependency is external, don't import unless needed

from optparse import OptionParser

G5_IS_DEFAULT = True

def get_dracos_host():
	res = subprocess.check_output([
		'sh',
		'-c',
		'dracos_host=localhost:8001; [ -e /etc/dracos.conf ] && . /etc/dracos.conf; printf "%s" "$dracos_host" || true'])
	return res.decode('utf-8')

parser = OptionParser()
parser.add_option("--g4", action="store_false", dest="g5", default=G5_IS_DEFAULT, help="use Dexcom G4 instead of Dexcom G5")
parser.add_option("--g5", action="store_true",  dest="g5", default=G5_IS_DEFAULT, help="use Dexcom G5 instead of Dexcom G4")

parser.add_option("-a", "--all",  action="store_const", dest="command", const="dump_everything", help="dump all available records")
parser.add_option("-p", "--poll", action="store_const", dest="command", const="poll",            help="poll for latest CGM record")
parser.add_option("--test",       action="store_const", dest="command", const="test",            help="test")

parser.add_option("--hours", type="int", dest="hours", default=None, help="display N most recent hours of CGM records")
parser.add_option("-n", type="int", dest="num_records", default=None, help="number of CGM records to display")
parser.add_option("-v", "--verbose", action="store_true", dest="verbose", help="verbosity (currently for debugging)")
parser.add_option("-H", "--human", action="store_true", dest="human", help="print human-readable times")
parser.add_option("-j", "--json", action="store_true", dest="json", help="print JSON output")
parser.add_option("--http", type="string", dest="host", help="submit via HTTP")
parser.add_option("--client", action="store_true", dest="client", help="act as client to dracos")

(options, args) = parser.parse_args()

command = options.command or "dump_cgm"
VERBOSE = options.verbose
HUMAN = options.human
JSON = options.json
HOST = options.host

if options.client and not HOST:
	dracos_host = get_dracos_host()
	if dracos_host:
		HOST = "http://" + dracos_host
	else:
		raise ValueError("Option '--client' specified but 'dracos_host' not specified in '/etc/dracos.conf'")


if command is 'dump_cgm' and options.num_records is None and not options.hours:
        options.hours = 2
if options.num_records <= 0:
        options.num_records = None

def get_dexcom_reader():
        if options.g5:
                dd = readdata.DexcomG5.FindDevice()
                return readdata.DexcomG5(dd)
        else:
                dd = readdata.Dexcom.FindDevice()
                return readdata.Dexcom(dd)

dr = None

if command is not 'poll':
        dr = get_dexcom_reader()

def parseable_record_types():
        unparseable = ['FIRMWARE_PARAMETER_DATA', 'RECEIVER_LOG_DATA', 'USER_SETTING_DATA', 'MAX_VALUE', 'RECEIVER_ERROR_DATA']
        parsed_to_xml = ['MANUFACTURING_DATA', 'PC_SOFTWARE_PARAMETER']
        skip = unparseable + parsed_to_xml
        return filter(lambda v: not v in skip, constants.RECORD_TYPES)

def choose_range(rs):
        if options.hours:
                now = dr.ReadSystemTime()
                when = now - timedelta(hours=options.hours)
                return takewhile(lambda r: r.system_time > when, rs)
        else:
                return islice(rs, options.num_records)

def dump_everything():
        for t in parseable_record_types():
                print t + ":"
                for r in choose_range(dr.iter_records(t)):
                        print toJSON(r) if JSON else r

def dump_cgm():
        for cr in reversed(list(choose_range(dr.iter_records('EGV_DATA')))):
                if not cr.display_only:
                        print toJSON(cr) if JSON else cr

def recent(t):
        now = dr.ReadSystemTime()
        return t.system_time > now - timedelta(minutes=5)

def print_verbose(s, newline=True):
        global VERBOSE
        if VERBOSE:
                stderr.write('%s%s' % (str(s), '\n' if newline else ''))

def read_recent_egv_data():
        now = dr.ReadSystemTime()
        r = dr.ReadRecords('EGV_DATA', 1)[-1]
        if recent(r) and not r.is_special and not r.display_only:
                return (r, now)
        else:
                return (None, now)

def time_fmt(t):
        global HUMAN
        return t.strftime('%c' if HUMAN else '%s')

def format_times(now, stamp):
        diff = (stamp - now).total_seconds()
        operand = '-' if diff < 0 else '+' # should always be -
        return '%s %s %d' % (time_fmt(now), operand, abs(diff))

CONNECTED = None
def connected(state):
        global CONNECTED
        if (state == CONNECTED):
                return
        else:
                CONNECTED = state
                print_verbose('Dexcom receiver %s connected.' % ('is' if state else 'is not'))

VERBOSITY_INSANE = False
def sleep_verbose(n):
        if VERBOSITY_INSANE:
                print_verbose('sleep(%d)' % n)
        sleep(n)

imported_requests = None
def import_requests():
        global imported_requests
        if not imported_requests:
                print_verbose("Loading 'requests' HTTP client library... ", newline=False)
                import requests
                print_verbose("done.")
                imported_requests = requests
        return imported_requests

def POST(path, json_str):
        msg = None
        try:
                requests = import_requests()
                resp = requests.post(HOST + path, data=json_str,
                                     headers={'Content-type': 'application/json'})
                msg = resp.text
                resp.raise_for_status()
                return True
        except requests.exceptions.HTTPError as e:
                print_verbose(e)
                if msg:
                        print_verbose(msg)
                return False

def send_ping(now):
        if HOST:
                POST('/ping', toJSON(now))

def print_cgm_bg(now, r):
        if JSON:
                print toJSON(r)
        else:
                print '%s: %s %s' % (format_times(now, r.system_time), r.glucose, r.trend_arrow)
        stdout.flush()

MAX_POLL_WAIT_SECONDS = 5
MIN_POLL_WAIT_SECONDS = 1

def poll_remote():
        (n, r) = remote_update('EGV_DATA')
        if n is None:
                return MAX_POLL_WAIT_SECONDS
        else:
                now = dr.ReadSystemTime()
                if n == 0:
                        send_ping(now)
                if r:
                        for t in ['METER_DATA', 'INSERTION_TIME', 'USER_EVENT_DATA']:
                        # TODO: track how long this takes & adjust sleep accordingly
                                try:
                                        remote_update(t)
                                except:
                                        traceback.print_exc()
                        next_reading = (r.system_time - now + timedelta(minutes=5, seconds=2)).total_seconds()
                        return max(MIN_POLL_WAIT_SECONDS, min(MAX_POLL_WAIT_SECONDS, next_reading))
                else:
                        return MAX_POLL_WAIT_SECONDS

def poll():
        print_verbose('Started dexcom_dumper.')
	if HOST:
		print_verbose("Acting as client to dracos server at " + HOST)
        poll_once = poll_remote if HOST else poll_stdout

        dexcom_g5_product = '22a3/47/100'

        def is_dexcom_g5(dev):
                try: return dev.parent.get('PRODUCT') == dexcom_g5_product
                except: return False

        devicer = simple_devicer('tty', is_dexcom_g5)

        while True:
            try:
                print_verbose("Waiting for device.")
                if not devicer.wait_add(600):
                        # This does not really need to time out, but if there
                        # is no timeout, then keyboard interrupt does not work.
                        # Might as well use the opportunity to print more
                        # garbage into the log, though.
                        continue
                print_verbose("Device found.")

                global dr
                if dr:
                        dr.Disconnect()
                dr = readdata.DexcomG5(devicer.device.device_node)

                print("Device opened.")
                while devicer.have():
                        print_verbose("Polling device.")
                        try:
                                sleeptime = poll_once()
                        except:
				traceback.print_exc(0)
                                sleeptime = 10

                        if devicer.wait_remove(sleeptime):
                                print_verbose("Device unplugged.")
                                dr.Disconnect()
                                dr = None
            except KeyboardInterrupt:
                break

def poll_stdout():
        (r, now) = read_recent_egv_data()
        if r is None:
                return 10
        else:
                print_cgm_bg(now, r)
                next_reading = (r.system_time - now + timedelta(minutes=5, seconds=2)).total_seconds()
                return next_reading if (next_reading > 0) else 10


def since(when, rectype):
        filt = lambda r: (r.system_time > when) if when else True
        return list(reversed(list(takewhile(filt, dr.iter_records(rectype)))))

def since_and_first(when, rectype):
        class closure:
                fst = None
        def filt(r):
                closure.fst = closure.fst or r
                return (r.system_time > when) if when else True
        return (list(reversed(list(takewhile(filt, dr.iter_records(rectype))))), closure.fst)

def parsetime(s):
        return datetime.strptime(s, "%Y-%m-%dT%H:%M:%SZ")

# Update the remote site with any records of 'rectype' that are missing.
# The server is queried to determine its last update.
#
# Returns (a,b) where:
#
# a = the number of records sent to the server (possibly zero), or None for a server error
#
# b = the latest record available on the Dexcom
#
# TODO: This has a race condition if you imagine multiple clients,
# server restarts, etc.; it should send back the value it got in the
# query to the server, so that the server can verify that the updates
# are consecutive.
REMOTE_HAS = {}
def check_remote_has(rectype):
        global REMOTE_HAS

        if REMOTE_HAS.get(rectype, None) is not None:
                return REMOTE_HAS[rectype]

        requests = import_requests()

        resp = requests.get(HOST + '/' + rectype + '/1')
        resp.raise_for_status()

        when = None
        if len(resp.json()):
                when = parsetime(resp.json()[0]['system_time'])
                print_verbose("Latest %s record on server: %s" % (rectype, when.isoformat()))

        REMOTE_HAS[rectype] = when
        return when

def remote_update(rectype):
        global REMOTE_HAS
        when = check_remote_has(rectype)

        (rs, r) = since_and_first(when, rectype)

        connected(True)
        if len(rs):
                REMOTE_HAS[rectype] = None
                print_verbose("Sending %d %s record%s... " % (len(rs), rectype, '' if len(rs) == 1 else 's'), newline=False)
                result = POST('/' + rectype, toJSON(rs))
                print_verbose("done.  (Result: %s.)" % 'success' if result else 'failure')
                return (len(rs) if result else None, r)
        else:
                return (0, r)

def test():
        remote_update('USER_EVENT_DATA')

def test0():
        for t in parseable_record_types():
                remote_update(t)

from datetime import tzinfo, timedelta, datetime

ZERO = timedelta(0)

class UTCtzinfo(tzinfo):
    def utcoffset(self, dt):
        return ZERO

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return ZERO

UTC = UTCtzinfo()

class JSON_Time(json.JSONEncoder):
        def default(self, o):
                if isinstance(o, datetime):
                        if o.tzinfo is None:

                                return o.replace(tzinfo=UTC).isoformat()
                        else:
                                return o.isoformat()

                return json.JSONEncoder.default(self, o)

class JSON_CGM(JSON_Time):
        def default(self, o):

                if isinstance(o, EGVRecord) and o.is_special:
                        op={}
                        record={}
                        for k in o.BASE_FIELDS:
                                op[k] = getattr(o, k)
                        op['record'] = [getattr(o, 'glucose_special_meaning'), []]
                        return op

                elif isinstance(o, EventRecord):
                        op={}
                        for k in o.BASE_FIELDS:
                                op[k] = getattr(o, k)
                        if o.event_sub_type:
                                op['record'] = [o.event_type + '_' + str(o.event_sub_type), []]
                        else:
                                op['record'] = [o.event_type, o.event_value]
                        return op

                elif isinstance(o, GenericTimestampedRecord):
                        op={}
                        record={}
                        for k in o.BASE_FIELDS:
                                op[k] = getattr(o, k)
                        for k in o.FIELDS:
                                record[k] = getattr(o, k)

                        if isinstance(o, EGVRecord):
                                record = ['EGVRecord', record]

                        op['record'] = record
                        return op

                else:
                        return JSON_Time.default(self, o)

def toJSON(o):
        return json.dumps(o, cls=JSON_CGM)

{"dump_everything": dump_everything,
 "dump_cgm":        dump_cgm,
 "poll":            poll,
 "test":            poll,
}[command]()