-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathlib.py
900 lines (615 loc) · 22.5 KB
/
lib.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
#! /usr/bin/python
# -*- coding: utf-8 -*-
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Title: lib
Author: David Leclerc
Version: 0.1
Date: 24.05.2016
License: GNU General Public License, Version 3
(http://www.gnu.org/licenses/gpl.html)
Overview: This is a script that contains user-defined functions to make the
communications with the CareLink stick easier.
Notes: ...
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# LIBRARIES
import usb
import copy
import json
import datetime
import math
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import sys
# CONSTANTS
# CRC8
CRC8_TABLE = [0, 155, 173, 54, 193, 90, 108, 247,
25, 130, 180, 47, 216, 67, 117, 238,
50, 169, 159, 4, 243, 104, 94, 197,
43, 176, 134, 29, 234, 113, 71, 220,
100, 255, 201, 82, 165, 62, 8, 147,
125, 230, 208, 75, 188, 39, 17, 138,
86, 205, 251, 96, 151, 12, 58, 161,
79, 212, 226, 121, 142, 21, 35, 184,
200, 83, 101, 254, 9, 146, 164, 63,
209, 74, 124, 231, 16, 139, 189, 38,
250, 97, 87, 204, 59, 160, 150, 13,
227, 120, 78, 213, 34, 185, 143, 20,
172, 55, 1, 154, 109, 246, 192, 91,
181, 46, 24, 131, 116, 239, 217, 66,
158, 5, 51, 168, 95, 196, 242, 105,
135, 28, 42, 177, 70, 221, 235, 112,
11, 144, 166, 61, 202, 81, 103, 252,
18, 137, 191, 36, 211, 72, 126, 229,
57, 162, 148, 15, 248, 99, 85, 206,
32, 187, 141, 22, 225, 122, 76, 215,
111, 244, 194, 89, 174, 53, 3, 152,
118, 237, 219, 64, 183, 44, 26, 129,
93, 198, 240, 107, 156, 7, 49, 170,
68, 223, 233, 114, 133, 30, 40, 179,
195, 88, 110, 245, 2, 153, 175, 52,
218, 65, 119, 236, 27, 128, 182, 45,
241, 106, 92, 199, 48, 171, 157, 6,
232, 115, 69, 222, 41, 178, 132, 31,
167, 60, 10, 145, 102, 253, 203, 80,
190, 37, 19, 136, 127, 228, 210, 73,
149, 14, 56, 163, 84, 207, 249, 98,
140, 23, 33, 186, 77, 214, 224, 123]
# CRC16
CRC16_TABLE = [0, 4129, 8258, 12387, 16516, 20645, 24774, 28903,
33032, 37161, 41290, 45419, 49548, 53677, 57806, 61935,
4657, 528, 12915, 8786, 21173, 17044, 29431, 25302,
37689, 33560, 45947, 41818, 54205, 50076, 62463, 58334,
9314, 13379, 1056, 5121, 25830, 29895, 17572, 21637,
42346, 46411, 34088, 38153, 58862, 62927, 50604, 54669,
13907, 9842, 5649, 1584, 30423, 26358, 22165, 18100,
46939, 42874, 38681, 34616, 63455, 59390, 55197, 51132,
18628, 22757, 26758, 30887, 2112, 6241, 10242, 14371,
51660, 55789, 59790, 63919, 35144, 39273, 43274, 47403,
23285, 19156, 31415, 27286, 6769, 2640, 14899, 10770,
56317, 52188, 64447, 60318, 39801, 35672, 47931, 43802,
27814, 31879, 19684, 23749, 11298, 15363, 3168, 7233,
60846, 64911, 52716, 56781, 44330, 48395, 36200, 40265,
32407, 28342, 24277, 20212, 15891, 11826, 7761, 3696,
65439, 61374, 57309, 53244, 48923, 44858, 40793, 36728,
37256, 33193, 45514, 41451, 53516, 49453, 61774, 57711,
4224, 161, 12482, 8419, 20484, 16421, 28742, 24679,
33721, 37784, 41979, 46042, 49981, 54044, 58239, 62302,
689, 4752, 8947, 13010, 16949, 21012, 25207, 29270,
46570, 42443, 38312, 34185, 62830, 58703, 54572, 50445,
13538, 9411, 5280, 1153, 29798, 25671, 21540, 17413,
42971, 47098, 34713, 38840, 59231, 63358, 50973, 55100,
9939, 14066, 1681, 5808, 26199, 30326, 17941, 22068,
55628, 51565, 63758, 59695, 39368, 35305, 47498, 43435,
22596, 18533, 30726, 26663, 6336, 2273, 14466, 10403,
52093, 56156, 60223, 64286, 35833, 39896, 43963, 48026,
19061, 23124, 27191, 31254, 2801, 6864, 10931, 14994,
64814, 60687, 56684, 52557, 48554, 44427, 40424, 36297,
31782, 27655, 23652, 19525, 15522, 11395, 7392, 3265,
61215, 65342, 53085, 57212, 44955, 49082, 36825, 40952,
28183, 32310, 20053, 24180, 11923, 16050, 3793, 7920]
# FUNCTIONS
def isEqual(x, y, precision):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ISEQUAL
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test equality between two numbers for a given precision.
"""
if not precision > 0:
raise ValueError("Precision should be a number greater than 0.")
return abs(x - y) <= precision
def derivate(x, t):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DERIVATE
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# Vectorize input
x = np.array(x)
t = np.array(t)
# Compute deltas
dx = x[1:] - x[:-1]
dt = t[1:] - t[:-1]
# Evaluate derivative
D = dx / dt
# Return derivative
return list(D)
def integrate(x, t, args):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
INTEGRATE
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This is a module that approximates the integral I of a given function x from
a to b, given an equally spaced time vector t. In order to do that, it uses
the Simpson method, and uses said time vector to evaluate the number n of
intervals and the integration step h.
"""
# Read limits of integral
a = t[0]
b = t[-1]
# Delete last t to not add contribution of [b, b + h] to the integral!
t = t[0:-1]
# Read number of steps to integrate on
n = len(t)
# Compute integration step
h = (b - a) / float(n)
# Evaluate definite integral I of x from a to b
I = np.sum(h/6 * (x(t, args) +
x(t + h/2, args) * 4 +
x(t + h, args)))
# Info
# print "I[" + str(a) + ", " + str(b) + "] = " + str(I)
# Return result of definite integral
return I
def getPolyFitMax(x, y, n, N):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GETPOLYFITMAX
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
f(x) = a_n * x^n + a_(n - 1) * x^(n - 1) + ... + a_0
"""
# Generate nth-order polynomial fit
a = np.polyfit(x, y, n)
# Build x-axis
x = np.linspace(x[0], x[-1], N)
# Initialize y-axis
y = np.zeros(N)
# Loop through the n degrees of order
for i in range(n):
# Compute values on y-axis
y += a[i] * x ** (n - i)
# Find index of max
index = np.argmax(y)
# Return max
return x[index]
def getMaxMiddle(x, y, threshold):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GETMAXMIDDLE
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# Get max
yMax = np.max(y)
# Initialize indices
indices = []
# Get indices or values near absolute max within threshold
for i in range(len(x)):
# Fits within threshold
if y[i] >= (yMax - threshold):
# Add index
indices.append(i)
# Get average index
index = int(round(np.mean(indices)))
# Return corresponding max
return x[index]
def decodeTime(x):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DECODETIME
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
second = x[0] & 63
minute = x[1] & 63
hour = x[2] & 31
day = x[3] & 31
month = ((x[0] & 192) >> 4) | ((x[1] & 192) >> 6)
year = (x[4] & 127) + 2000
return [year, month, day, hour, minute, second]
def formatDate(date):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FORMATDATE
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Using a date object, return corresponding string in following format:
YYYY/MM/DD/
"""
# If datetime object
if type(date) is datetime.datetime or type(date) is datetime.date:
# Format date
return datetime.datetime.strftime(date, "%Y/%m/%d")
# Raise error
raise NotImplementedError("Incorrect date object type: " + type(date))
def formatTime(t):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FORMATTIME
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# Define time formats
f = "%Y.%m.%d - %H:%M:%S"
F = "%H:%M"
# If datetime object
if type(t) is datetime.datetime:
t = datetime.datetime.strftime(t, f)
# Otherwise
else:
# Try first format
try:
t = datetime.datetime.strptime(t, f)
except:
pass
# Try second format
try:
t = datetime.datetime.strptime(t, F).time()
except:
pass
# Return formatted time
return t
def normalizeTime(t, ref):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NORMALIZETIME
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Compare a datetime object to another one, which serves as a reference.
Return the time difference in hours.
"""
# Test types
if type(t) is not datetime.datetime or type(ref) is not datetime.datetime:
raise TypeError("Only datetime objects can be normalized.")
# Compute positive time difference (s)
if t >= ref:
dt = (t - ref).total_seconds()
# Compute negative time difference (s)
else:
dt = -(ref - t).total_seconds()
# Return time difference in hours
return dt / 3600.0
def encode(x):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ENCODE
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
return [ord(i) for i in str(x).decode("HEX")]
def nMax(x, n = 1):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
NMAX
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# Get max possible number of output values
n = min(n, len(x))
# Initialize results
X = []
# Find n max values in x
for _ in range(n):
# Get index of max value
j = np.argmax(x)
# Store value
X.append(x[j])
# Delete it from x
del x[j]
# Return results
return X
def unzip(z):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
UNZIP
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unzip lists.
"""
# Non-empty list
if z:
return [list(x) for x in zip(*z)]
# Otherwise
return [[], []]
def merge(base, new, n = 1):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MERGE
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Merge dictionaries together. Overwriting of entries is forbidden!
"""
# Start
if n == 1:
# Check if dict given as input
if type (base) is not dict or type(new) is not dict:
raise TypeError("Only dicts can be merged.")
# Copy base in order to not overwrite it
base = copy.deepcopy(base)
# Loop over keys
for key, value in new.items():
# Key exists
if key in base:
# Both current values are of same type:
if type(base[key]) is type(value):
# Both dicts: dive in deeper
if type(value) is dict:
merge(base[key], value, n + 1)
# Otherwise: entry mismatch
elif base[key] != value:
raise ValueError("Cannot merge dicts: conflicting values.")
# Otherwise: type mismatch
else:
raise TypeError("Cannot merge dicts: conflicting types.")
# Otherwise: generate new entry
else:
base[key] = value
# End
if n == 1:
# Return merged dicts
return base
def mergeDicts(*args):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
MERGEDICTS
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# Verify number of args
if len(args) < 2:
raise IOError("Feed at least 2 dictionaries to merge.")
# Destructure dicts
base, args = args[0], args[1:]
# Loop on dicts
for new in args:
# Update base
base = merge(base, new)
# Info
# print "New merged dictionary:\n" + JSONize(base)
# Return updated base
return base
def flatten(l):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
FLATTEN
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
return [x for ll in l for x in ll]
def uniqify(x):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
UNIQIFY
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
return sorted(list(set(x)))
def hexify(x):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
HEXIFY
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
if type(x) is not list:
x = [x]
return ["{0:#04X}".format(y) for y in x]
def dehexify(x):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
DEHEXIFY
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
if type(x) is not list:
x = [x]
return [int(y, 16) for y in x]
def charify(x):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
CHARIFY
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
if type(x) is not list:
x = [x]
return ["." if (y < 32) | (y > 126) else chr(y) for y in x]
def getByte(x, n):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GETBYTE
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This is a function that extracts the byte in position n of a integer x.
"""
return (x >> (8 * n)) & 0xFF
def pack(x, order = ">", n = None):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
PACK
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This converts a natural number to its representation in bytes, given a
minimal number of bytes to be returned in a certain order.
"""
# Only natural numbers
if x < 0 or int(x) != x:
# Raise error
raise ArithmeticError("Only natural numbers allowed.")
# Compute minimum number of bytes required (no byte would not make sense)
N = 1
# Loop until number is covered
while x >= 0xFF ** N:
# Increase it
N += 1
# If number of wanted bytes not given
if n is None:
# Assign it minimum required
n = N
# If it is too small though
elif n < N:
# Raise error
raise ArithmeticError("Minimum number of bytes required to represent " +
str(x) + ": " + str(N))
# Initialize bytes and their string representation
bytes = []
bytes_ = []
# Build bytes
for i in range(n):
# Compute ith byte
bytes.insert(0, (x & (0xFF << (8 * i))) >> (8 * i))
# Sort them according to given order
# From MSB to LSB
if order == ">":
# Already ordered
pass
# From LSB to MSB
elif order == "<":
# Order
bytes.reverse()
# Otherwise
else:
# Raise error
raise NotImplementedError("Unknown byte order.")
# Build their string representation
for b in bytes:
# Convert byte to string
byte = bin(b)[2:]
# Fill with zeros
while len(byte) != 8:
# Add zero upfront
byte = "0" + byte
# Append byte
bytes_.append(byte)
# Return them
return bytes
def unpack(bytes, order = ">"):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
UNPACK
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This is a function that converts a number expressed in an array of bytes
to its decimal equivalent.
"""
# Only natural numbers
if np.any([not (int(b) == b and (0 <= b <= 0xFF)) for b in bytes]):
# Raise error
raise ArithmeticError("Invalid bytes to unpack in a number.")
# Compute number of bytes
n = len(bytes)
# Initialize result
x = 0
# Unpack bytes in x
for i in range(n):
# From MSB to LSB
if order == ">":
# Add ith byte
x += bytes[i] * 256 ** (n - 1 - i)
# From LSB to MSB
elif order == "<":
# Add ith byte
x += bytes[i] * 256 ** i
# Return
return x
def JSONize(x):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
JSONIZE
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Return a dictionary using a particular JSON formatting.
"""
return json.dumps(x, indent = 2, separators = (",", ": "), sort_keys = True)
def translate(x):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
TRANSLATE
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This converts and returns the bytes received on the IN EP of a USB
device.
"""
return "".join([chr(y) for y in x])
def split(x, n):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SPLIT
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This splits a string in groups of n characters and stores them in an
array.
"""
# Compute number of hexadecimal values within string
N = int(math.ceil(len(x) / float(n)))
# Return splitted string
return [x[(n * i):(n * (i + 1))] for i in range(0, N)]
def withinRangeInt(x, r, error):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
WITHINRANGEINT
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Test a value to see if it is an integer and fits within given range.
If not, raise input/output error.
"""
# Test value
if not (int(x) == x and min(r) <= x <= max(r)):
# Raise error
raise IOError(error)
def computeCRC8(x):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
COMPUTECRC8
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# Initialize CRC
CRC = 0
# Look for CRC in table
for i in range(len(x)):
# Compute it
CRC = CRC8_TABLE[CRC ^ getByte(x[i], 0)]
# Return CRC
return CRC
def computeCRC16(x):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
COMPUTECRC16
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# Initialize CRC
CRC = 0xFFFF
# Look for CRC in table
for i in range(len(x)):
# Compute it
CRC = (CRC16_TABLE[x[i] ^ CRC >> 8] ^ CRC << 8) & 0xFFFF
# Return CRC
return CRC
def isNumber(x):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ISNUMBER
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
# Python 2
if sys.version_info[0] < 3:
return (isinstance(x, (int, long, float, complex)) and
not isinstance(x, bool))
# Python 3
return isinstance(x, (int, float, complex)) and not isinstance(x, bool)
def isRealNumber(x):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
ISREALNUMBER
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
"""
return isNumber(x) and not isinstance(x, complex)
def getUSBEP(configuration, direction, interface = 0, setting = 0):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GETUSBEP
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
This finds a matching EP on a USB device given a configuration, a
direction, an interface and a setting input, using the PyUSB library.
"""
# Get direction
# IN
if direction == "IN":
# Reassign it
direction = usb.util.ENDPOINT_IN
# OUT
elif direction == "OUT":
# Reassign it
direction = usb.util.ENDPOINT_OUT
# Otherwise
else:
# Raise error
raise IOError("Bad EP direction: " + direction)
# Return EP
return usb.util.find_descriptor(configuration[(interface, setting)],
custom_match = lambda e:
usb.util.endpoint_direction(e.bEndpointAddress) == direction)
def initPlot(n = 0):
"""
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
INITPLOT
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Initialize matplotlib module and generate a figure to work with.
"""
# Configure graph
mpl.rc("font", size = 10, family = "Ubuntu")
# Define figure
fig = plt.figure(n, figsize = (10, 8), tight_layout = True)
# Return figure
return fig