-
Notifications
You must be signed in to change notification settings - Fork 0
/
yocto_api.py
8762 lines (7624 loc) · 339 KB
/
yocto_api.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
# -*- coding: utf-8 -*-
# *********************************************************************
# *
# * $Id: yocto_api.py 56115 2023-08-16 09:40:13Z seb $
# *
# * High-level programming interface, common to all modules
# *
# * - - - - - - - - - License information: - - - - - - - - -
# *
# * Copyright (C) 2011 and beyond by Yoctopuce Sarl, Switzerland.
# *
# * Yoctopuce Sarl (hereafter Licensor) grants to you a perpetual
# * non-exclusive license to use, modify, copy and integrate this
# * file into your software for the sole purpose of interfacing
# * with Yoctopuce products.
# *
# * You may reproduce and distribute copies of this file in
# * source or object form, as long as the sole purpose of this
# * code is to interface with Yoctopuce products. You must retain
# * this notice in the distributed source file.
# *
# * You should refer to Yoctopuce General Terms and Conditions
# * for additional information regarding your rights and
# * obligations.
# *
# * THE SOFTWARE AND DOCUMENTATION ARE PROVIDED 'AS IS' WITHOUT
# * WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
# * WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS
# * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO
# * EVENT SHALL LICENSOR BE LIABLE FOR ANY INCIDENTAL, SPECIAL,
# * INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA,
# * COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR
# * SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT
# * LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
# * CONTRIBUTION, OR OTHER SIMILAR COSTS, WHETHER ASSERTED ON THE
# * BASIS OF CONTRACT, TORT (INCLUDING NEGLIGENCE), BREACH OF
# * WARRANTY, OR OTHERWISE.
# *
# *********************************************************************/
from __future__ import division
__docformat__ = 'restructuredtext en'
import datetime
import ctypes
import math
import platform
# import abc (not supported in 2.5.x)
import random
import sys
import os
import time
import array
import binascii
from ctypes import *
#
# PYTHON 2.x VS PYTHON 3.x compatibility check
#
def YByte2StringPython2x(binBuffer):
return binBuffer.decode("latin-1")
def YString2BytePython2x(strBuffer):
return strBuffer.encode("latin-1")
def YGetBytePython2x(binBuffer, idx):
item = binBuffer[idx]
if type(item) is int:
return item
return ord(item)
def YAddBytePython2x(binBuffer, b):
return binBuffer + chr(b)
def YRelTickCountPython2x(dt):
td = dt - datetime.datetime(1970, 1, 1)
return int(round((td.seconds + td.days * 24 * 3600 * 1000) + td.microseconds / 1000))
def YByte2StringPython3x(binBuffer):
return binBuffer.decode("latin-1")
def YString2BytePython3x(strBuffer):
return strBuffer.encode("latin-1")
def YGetBytePython3x(binBuffer, l):
return binBuffer[l]
def YAddBytePython3x(binBuffer, b):
return binBuffer + bytes([b])
def YRelTickCountPython3x(dt):
td = dt - datetime.datetime(1970, 1, 1)
return int(round(td.total_seconds() * 1000.0))
def YArrayToBytesPython2x(a):
return a.tostring()
# array.tostring is deprecated in Python 3.2 and was removed in 3.9!
def YArrayToBytesPython32plus(a):
return a.tobytes()
YByte2String = None
YString2Byte = None
YGetByte = None
YAddByte = None
YRelTickCount = None
YArrayToBytes = None
if sys.version_info < (3, 0):
YByte2String = YByte2StringPython2x
YString2Byte = YString2BytePython2x
YGetByte = YGetBytePython2x
YAddByte = YAddBytePython2x
YRelTickCount = YRelTickCountPython2x
YArrayToBytes = YArrayToBytesPython2x
else:
YByte2String = YByte2StringPython3x
YString2Byte = YString2BytePython3x
YGetByte = YGetBytePython3x
YAddByte = YAddBytePython3x
YRelTickCount = YRelTickCountPython3x
if sys.version_info < (3, 2):
YArrayToBytes = YArrayToBytesPython2x
else:
YArrayToBytes = YArrayToBytesPython32plus
# Ugly global var for Python 2 compatibility
yLogFct = None
yDeviceLogFct = None
yArrivalFct = None
yRemovalFct = None
yChangeFct = None
yHubDiscoveryCallback = None
# This class is used to mimic "ByReference" parameter in function calls
class YRefParam:
def __init__(self, initialValue=None):
self.value = initialValue
def __str__(self):
return str(self.value)
class YAPI_Exception(Exception):
def __init__(self, errType, errMsg):
super(YAPI_Exception, self).__init__(errMsg)
self.errorType = errType
self.errorMessage = errMsg
# noinspection PyClassHasNoInit
class YJSONType:
STRING, NUMBER, ARRAY, OBJECT = range(4)
# noinspection PyClassHasNoInit
class Tjstate:
JSTART, JWAITFORNAME, JWAITFORENDOFNAME, JWAITFORCOLON, JWAITFORDATA, JWAITFORNEXTSTRUCTMEMBER, JWAITFORNEXTARRAYITEM, \
JWAITFORSTRINGVALUE, JWAITFORSTRINGVALUE_ESC, JWAITFORINTVALUE, JWAITFORBOOLVALUE = range(11)
class YJSONContent(object):
@staticmethod
def ParseJson(data, start, stop):
cur_pos = YJSONContent.SkipGarbage(data, start, stop)
c = data[cur_pos]
if c == '[':
res = YJSONArray(data, start, stop)
elif c == '{':
res = YJSONObject(data, start, stop)
elif c == '"':
res = YJSONString(data, start, stop)
else:
res = YJSONNumber(data, start, stop)
res.parse()
return res
def __init__(self, data, start, stop, typ):
self._data = data
self._data_start = start
self._data_len = start
self._data_boundary = stop
self._type = typ
def getJSONType(self):
return self._type
def parse(self):
raise Exception("abstract methode")
@staticmethod
def SkipGarbage(data, start, stop):
if stop <= start:
return start
while start < stop:
sti = data[start]
if sti != ' ' and sti != '\n' and sti != '\r':
break
start += 1
return start
def formatError(self, errmsg, cur_pos):
ststart = cur_pos - 10
stend = cur_pos + 10
if ststart < 0:
ststart = 0
if stend > self._data_boundary:
stend = self._data_boundary
if self._data is not None:
return errmsg + " near " + self._data[ststart: stend]
return errmsg
class YJSONString(YJSONContent):
def __init__(self, data, start, stop):
super(YJSONString, self).__init__(data, start, stop, YJSONType.STRING)
self._stringValue = None
def parse(self):
value = ""
cur_pos = YJSONContent.SkipGarbage(self._data, self._data_start, self._data_boundary)
if cur_pos >= self._data_boundary or self._data[cur_pos] != '"':
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT, self.formatError("double quote was expected", cur_pos))
cur_pos += 1
str_start = cur_pos
state = Tjstate.JWAITFORSTRINGVALUE
while cur_pos < self._data_boundary:
sti = self._data[cur_pos]
if state == Tjstate.JWAITFORSTRINGVALUE:
if sti == '\\':
value += self._data[str_start: cur_pos]
str_start = cur_pos
state = Tjstate.JWAITFORSTRINGVALUE_ESC
elif sti == '"':
value += self._data[str_start: cur_pos]
self._stringValue = value
self._data_len = (cur_pos + 1) - self._data_start
return self._data_len
elif sti < ' ':
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT,
self.formatError("invalid char: was expecting string value", cur_pos))
elif state == Tjstate.JWAITFORSTRINGVALUE_ESC:
value += sti
state = Tjstate.JWAITFORSTRINGVALUE
str_start = cur_pos + 1
else:
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT,
self.formatError("invalid state for YJSONObject", cur_pos))
cur_pos += 1
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT, self.formatError("unexpected end of data", cur_pos))
def toJSON(self):
res = '"'
le = len(self._stringValue)
for i in range(0, le):
c = self._stringValue[i]
if c == '"':
res += "\\\""
elif c == '\\':
res += "\\\\"
elif c == '/':
res += "\\/"
elif c == '\b':
res += "\\b"
elif c == '\f':
res += "\\f"
elif c == '\n':
res += "\\n"
elif c == '\r':
res += "\\r"
elif c == '\t':
res += "\\t"
else:
res += c
res += '"'
return res
def getString(self):
return self._stringValue
def toString(self):
return self._stringValue
def setContent(self, value):
self._stringValue = value
class YJSONNumber(YJSONContent):
def __init__(self, data, start, stop):
super(YJSONNumber, self).__init__(data, start, stop, YJSONType.NUMBER)
self._intValue = 0
self._doubleValue = 0
self._isFloat = False
def parse(self):
neg = False
cur_pos = YJSONContent.SkipGarbage(self._data, self._data_start, self._data_boundary)
if cur_pos >= self._data_boundary or self._data is None:
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT, "no data")
sti = self._data[cur_pos]
if sti == '-':
neg = True
cur_pos += 1
start = cur_pos
while cur_pos < self._data_boundary:
sti = self._data[cur_pos]
if sti == '.' and not self._isFloat:
int_part = self._data[start: cur_pos]
self._intValue = int(int_part)
self._isFloat = True
elif sti < '0' or sti > '9':
numberpart = self._data[start: cur_pos]
if self._isFloat:
self._doubleValue = float(numberpart)
else:
self._intValue = int(numberpart)
if neg:
self._doubleValue = 0 - self._doubleValue
self._intValue = 0 - self._intValue
return cur_pos - self._data_start
cur_pos += 1
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT, self.formatError("unexpected end of data", cur_pos))
def toJSON(self):
if self._isFloat:
return str(self._doubleValue)
else:
return str(self._intValue)
def getLong(self):
if self._isFloat:
return self._doubleValue
else:
return self._intValue
def getInt(self):
if self._isFloat:
return self._doubleValue
else:
return self._intValue
def getDouble(self):
if self._isFloat:
return self._doubleValue
else:
return self._intValue
def getString(self):
if self._isFloat:
return str(self._doubleValue)
else:
return str(self._intValue)
def toString(self):
if self._isFloat:
return str(self._doubleValue)
else:
return str(self._intValue)
class YJSONArray(YJSONContent):
def __init__(self, data, start, stop):
super(YJSONArray, self).__init__(data, start, stop, YJSONType.ARRAY)
self._arrayValue = []
def length(self):
return len(self._arrayValue)
def parse(self):
cur_pos = YJSONContent.SkipGarbage(self._data, self._data_start, self._data_boundary)
if cur_pos >= self._data_boundary or self._data[cur_pos] != '[':
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT, self.formatError("Opening braces was expected", cur_pos))
cur_pos += 1
state = Tjstate.JWAITFORDATA
while cur_pos < self._data_boundary:
sti = self._data[cur_pos]
if state == Tjstate.JWAITFORDATA:
if sti == '{':
jobj = YJSONObject(self._data, cur_pos, self._data_boundary)
length = jobj.parse()
cur_pos += length
self._arrayValue.append(jobj)
state = Tjstate.JWAITFORNEXTARRAYITEM
# cur_pos is already incremented
continue
elif sti == '[':
jobj = YJSONArray(self._data, cur_pos, self._data_boundary)
length = jobj.parse()
cur_pos += length
self._arrayValue.append(jobj)
state = Tjstate.JWAITFORNEXTARRAYITEM
# cur_pos is already incremented
continue
elif sti == '"':
jobj = YJSONString(self._data, cur_pos, self._data_boundary)
length = jobj.parse()
cur_pos += length
self._arrayValue.append(jobj)
state = Tjstate.JWAITFORNEXTARRAYITEM
# #cur_pos is already incremented
continue
elif sti == '-' or ('0' <= sti <= '9'):
jobj = YJSONNumber(self._data, cur_pos, self._data_boundary)
length = jobj.parse()
cur_pos += length
self._arrayValue.append(jobj)
state = Tjstate.JWAITFORNEXTARRAYITEM
# cur_pos is already incremented
continue
elif sti == ']':
self._data_len = cur_pos + 1 - self._data_start
return self._data_len
elif sti != ' ' and sti != '\n' and sti != '\r':
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT,
self.formatError("invalid char: was expecting \",0..9,t or f", cur_pos))
elif state == Tjstate.JWAITFORNEXTARRAYITEM:
if sti == ',':
state = Tjstate.JWAITFORDATA
elif sti == ']':
self._data_len = cur_pos + 1 - self._data_start
return self._data_len
else:
if sti != ' ' and sti != '\n' and sti != '\r':
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT,
self.formatError("invalid char: was expecting ,", cur_pos))
else:
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT,
self.formatError("invalid state for YJSONObject", cur_pos))
cur_pos += 1
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT, self.formatError("unexpected end of data", cur_pos))
def getYJSONObject(self, i):
if i >= len(self._arrayValue):
return None
return self._arrayValue[i]
def getString(self, i):
if i >= len(self._arrayValue):
return None
ystr = self._arrayValue[i]
return ystr.getString()
def get(self, i):
if i >= len(self._arrayValue):
return None
return self._arrayValue[i]
def getYJSONArray(self, i):
if i >= len(self._arrayValue):
return None
return self._arrayValue[i]
def getInt(self, i):
if i >= len(self._arrayValue):
return None
ystr = self._arrayValue[i]
return ystr.getInt()
def getLong(self, i):
if i >= len(self._arrayValue):
return None
ystr = self._arrayValue[i]
return ystr.getLong()
def getDouble(self, i):
if i >= len(self._arrayValue):
return None
ystr = self._arrayValue[i]
return ystr.getDouble()
def put(self, flatAttr):
strobj = YJSONString(None, 0, 0)
strobj.setContent(flatAttr)
self._arrayValue.append(strobj)
def toJSON(self):
res = '['
sep = ""
for yjsonContent in self._arrayValue:
subres = yjsonContent.toJSON()
res += sep
res += subres
sep = ","
res += ']'
return res
def toString(self):
res = '['
sep = ""
for yjsonContent in self._arrayValue:
subres = yjsonContent.toString()
res += sep
res += subres
sep = ","
res += ']'
return res
class YJSONObject(YJSONContent):
def __init__(self, data, start, stop):
super(YJSONObject, self).__init__(data, start, stop, YJSONType.OBJECT)
self._parsed = {}
self._keys = []
def parse(self):
current_name = ""
name_start = self._data_start
cur_pos = YJSONContent.SkipGarbage(self._data, self._data_start, self._data_boundary)
if len(self._data) <= cur_pos or cur_pos >= self._data_boundary or self._data[cur_pos] != '{':
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT, self.formatError("Opening braces was expected", cur_pos))
cur_pos += 1
state = Tjstate.JWAITFORNAME
while cur_pos < self._data_boundary:
sti = self._data[cur_pos]
if state == Tjstate.JWAITFORNAME:
if sti == '"':
state = Tjstate.JWAITFORENDOFNAME
name_start = cur_pos + 1
elif sti == '}':
self._data_len = cur_pos + 1 - self._data_start
return self._data_len
else:
if sti != ' ' and sti != '\n' and sti != '\r':
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT,
self.formatError("invalid char: was expecting \"", cur_pos))
elif state == Tjstate.JWAITFORENDOFNAME:
if sti == '"':
current_name = self._data[name_start: cur_pos]
state = Tjstate.JWAITFORCOLON
else:
if sti < ' ':
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT,
self.formatError(
"invalid char: was expecting an identifier compliant char",
cur_pos))
elif state == Tjstate.JWAITFORCOLON:
if sti == ':':
state = Tjstate.JWAITFORDATA
else:
if sti != ' ' and sti != '\n' and sti != '\r':
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT,
self.formatError("invalid char: was expecting \"", cur_pos))
elif state == Tjstate.JWAITFORDATA:
if sti == '{':
jobj = YJSONObject(self._data, cur_pos, self._data_boundary)
length = jobj.parse()
self._parsed[current_name] = jobj
self._keys.append(current_name)
cur_pos += length
state = Tjstate.JWAITFORNEXTSTRUCTMEMBER
continue
elif sti == '[':
jobj = YJSONArray(self._data, cur_pos, self._data_boundary)
length = jobj.parse()
cur_pos += length
self._parsed[current_name] = jobj
self._keys.append(current_name)
state = Tjstate.JWAITFORNEXTSTRUCTMEMBER
continue
elif sti == '"':
jobj = YJSONString(self._data, cur_pos, self._data_boundary)
length = jobj.parse()
cur_pos += length
self._parsed[current_name] = jobj
self._keys.append(current_name)
state = Tjstate.JWAITFORNEXTSTRUCTMEMBER
continue
elif sti == '-' or ('0' <= sti <= '9'):
jobj = YJSONNumber(self._data, cur_pos, self._data_boundary)
length = jobj.parse()
cur_pos += length
self._parsed[current_name] = jobj
self._keys.append(current_name)
state = Tjstate.JWAITFORNEXTSTRUCTMEMBER
continue
elif sti != ' ' and sti != '\n' and sti != '\r':
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT,
self.formatError("invalid char: was expecting \",0..9,t or f", cur_pos))
elif state == Tjstate.JWAITFORNEXTSTRUCTMEMBER:
if sti == ',':
state = Tjstate.JWAITFORNAME
name_start = cur_pos + 1
elif sti == '}':
self._data_len = cur_pos + 1 - self._data_start
return self._data_len
else:
if sti != ' ' and sti != '\n' and sti != '\r':
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT,
self.formatError("invalid char: was expecting ,", cur_pos))
elif state == Tjstate.JWAITFORNEXTARRAYITEM or state == Tjstate.JWAITFORSTRINGVALUE or state == Tjstate.JWAITFORINTVALUE or state == Tjstate.JWAITFORBOOLVALUE:
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT,
self.formatError("invalid state for YJSONObject", cur_pos))
cur_pos += 1
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT, self.formatError("unexpected end of data", cur_pos))
def has(self, key):
if key in self._parsed:
return True
return False
def getYJSONObject(self, key):
if key not in self._parsed:
return None
return self._parsed[key]
def getYJSONString(self, key):
if key not in self._parsed:
return None
return self._parsed[key]
def getYJSONArray(self, key):
if key not in self._parsed:
return None
return self._parsed[key]
def getKeys(self):
return self._parsed.keys()
def getYJSONNumber(self, key):
if key not in self._parsed:
return None
return self._parsed[key]
def remove(self, key):
self._parsed.pop(key, None)
def getString(self, key):
if key not in self._parsed:
return ""
ystr = self._parsed[key]
return ystr.getString()
def getInt(self, key):
if key not in self._parsed:
return None
yint = self._parsed[key]
return yint.getInt()
def get(self, key):
if key not in self._parsed:
return None
return self._parsed[key]
def getLong(self, key):
if key not in self._parsed:
return None
yint = self._parsed[key]
return yint.getLong()
def getDouble(self, key):
if key not in self._parsed:
return None
yint = self._parsed[key]
return yint.getDouble()
def toJSON(self):
res = '{'
sep = ""
for key in self._parsed.keys():
subContent = self._parsed[key]
subres = subContent.toJSON()
res += sep
res += '"'
res += key
res += "\":"
res += subres
sep = ","
res += '}'
return res
def toString(self):
res = '{'
sep = ""
for key in self._parsed.keys():
subContent = self._parsed[key]
subres = subContent.toString()
res += sep
res += key
res += "=>"
res += subres
sep = ","
res += '}'
return res
def parseWithRef(self, reference):
if reference is not None:
try:
yzon = YJSONArray(self._data, self._data_start, self._data_boundary)
yzon.parse()
self.convert(reference, yzon)
return
except YAPI.YAPI_Exception:
self.parse()
return
self.parse()
def convert(self, reference, newArray):
length = newArray.length()
for i in range(0, length):
key = reference.getKeyFromIdx(i)
new_item = newArray.get(i)
reference_item = reference.get(key)
if new_item.getJSONType() == reference_item.getJSONType():
self._parsed[key] = new_item
self._keys.append(key)
elif new_item.getJSONType() == YJSONType.ARRAY and reference_item.getJSONType() == YJSONType.OBJECT:
jobj = YJSONObject(new_item._data, new_item._data_start, reference_item._data_boundary)
jobj.convert(reference_item, new_item)
self._parsed[key] = jobj
self._keys.append(key)
else:
raise YAPI.YAPI_Exception(YAPI.INVALID_ARGUMENT, "Unable to convert %s to %s" % (
new_item.getJSONType(), reference.getJSONType()))
def getKeyFromIdx(self, i):
return self._keys[i]
# --- (generated code: YAPIContext class start)
#noinspection PyProtectedMember
class YAPIContext(object):
#--- (end of generated code: YAPIContext class start)
# --- (generated code: YAPIContext return codes)
#--- (end of generated code: YAPIContext return codes)
# --- (generated code: YAPIContext dlldef)
#--- (end of generated code: YAPIContext dlldef)
# --- (generated code: YAPIContext definitions)
#--- (end of generated code: YAPIContext definitions)
def __init__(self):
# --- (generated code: YAPIContext attributes)
self._defaultCacheValidity = 5
#--- (end of generated code: YAPIContext attributes)
self._yhub_cache = {}
# --- (generated code: YAPIContext implementation)
def SetDeviceListValidity(self, deviceListValidity):
"""
Modifies the delay between each forced enumeration of the used YoctoHubs.
By default, the library performs a full enumeration every 10 seconds.
To reduce network traffic, you can increase this delay.
It's particularly useful when a YoctoHub is connected to the GSM network
where traffic is billed. This parameter doesn't impact modules connected by USB,
nor the working of module arrival/removal callbacks.
Note: you must call this function after yInitAPI.
@param deviceListValidity : nubmer of seconds between each enumeration.
@noreturn
"""
YAPI._yapiSetNetDevListValidity(deviceListValidity)
def GetDeviceListValidity(self):
"""
Returns the delay between each forced enumeration of the used YoctoHubs.
Note: you must call this function after yInitAPI.
@return the number of seconds between each enumeration.
"""
# res
res = YAPI._yapiGetNetDevListValidity()
return res
def AddUdevRule(self, force):
"""
Adds a UDEV rule which authorizes all users to access Yoctopuce modules
connected to the USB ports. This function works only under Linux. The process that
calls this method must have root privileges because this method changes the Linux configuration.
@param force : if true, overwrites any existing rule.
@return an empty string if the rule has been added.
On failure, returns a string that starts with "error:".
"""
# msg
# res
# c_force
errmsg = ctypes.create_string_buffer(YAPI.YOCTO_ERRMSG_LEN)
if force:
c_force = 1
else:
c_force = 0
res = YAPI._yapiAddUdevRulesForYocto(c_force, errmsg)
if res < 0:
msg = "error: " + YByte2String(errmsg.value)
else:
msg = ""
return msg
def SetNetworkTimeout(self, networkMsTimeout):
"""
Modifies the network connection delay for yRegisterHub() and yUpdateDeviceList().
This delay impacts only the YoctoHubs and VirtualHub
which are accessible through the network. By default, this delay is of 20000 milliseconds,
but depending or you network you may want to change this delay,
gor example if your network infrastructure is based on a GSM connection.
@param networkMsTimeout : the network connection delay in milliseconds.
@noreturn
"""
YAPI._yapiSetNetworkTimeout(networkMsTimeout)
def GetNetworkTimeout(self):
"""
Returns the network connection delay for yRegisterHub() and yUpdateDeviceList().
This delay impacts only the YoctoHubs and VirtualHub
which are accessible through the network. By default, this delay is of 20000 milliseconds,
but depending or you network you may want to change this delay,
for example if your network infrastructure is based on a GSM connection.
@return the network connection delay in milliseconds.
"""
# res
res = YAPI._yapiGetNetworkTimeout()
return res
def SetCacheValidity(self, cacheValidityMs):
"""
Change the validity period of the data loaded by the library.
By default, when accessing a module, all the attributes of the
module functions are automatically kept in cache for the standard
duration (5 ms). This method can be used to change this standard duration,
for example in order to reduce network or USB traffic. This parameter
does not affect value change callbacks
Note: This function must be called after yInitAPI.
@param cacheValidityMs : an integer corresponding to the validity attributed to the
loaded function parameters, in milliseconds.
@noreturn
"""
self._defaultCacheValidity = cacheValidityMs
def GetCacheValidity(self):
"""
Returns the validity period of the data loaded by the library.
This method returns the cache validity of all attributes
module functions.
Note: This function must be called after yInitAPI .
@return an integer corresponding to the validity attributed to the
loaded function parameters, in milliseconds
"""
return self._defaultCacheValidity
def nextHubInUseInternal(self, hubref):
# nextref
nextref = YAPI._yapiGetNextHubRef(hubref)
if nextref < 0:
return None
return self.getYHubObj(nextref)
def getYHubObj(self, hubref):
# obj
obj = self._findYHubFromCache(hubref)
if obj is None:
obj = YHub(self, hubref)
self._addYHubToCache(hubref, obj)
return obj
#--- (end of generated code: YAPIContext implementation)
def _findYHubFromCache(self, hubref):
self._yhub_cache
if hubref in self._yhub_cache:
return self._yhub_cache[hubref]
return None
def _addYHubToCache(self, hubref, obj):
self._yhub_cache[hubref] = obj
# --- (generated code: YAPIContext functions)
#--- (end of generated code: YAPIContext functions)
# noinspection PyClassHasNoInit,PyProtectedMember
# noinspection PyUnresolvedReferences
class YAPI:
# noinspection PyUnresolvedReferences
class YPCHAR(ctypes.Structure):
_fields_ = [("buffer", ctypes.c_char_p)]
# Switch to turn off exceptions and use return codes instead, for source-code compatibility
# with languages without exception support like C
ExceptionsDisabled = False
_apiInitialized = False
_ydllLoaded = False
# Default cache validity (in [ms]) before reloading data from device. This saves a lots of traffic.
# Note that a value under 2 ms makes little sense since a USB bus itself has a 2ms round-trip period
DefaultCacheValidity = datetime.timedelta(milliseconds=5)
INVALID_STRING = "!INVALID!"
INVALID_DOUBLE = -1.79769313486231E+308
MIN_DOUBLE = float('-inf')
MAX_DOUBLE = float('inf')
INVALID_INT = -2147483648
INVALID_UINT = -1
INVALID_LONG = -9223372036854775807
# yInitAPI argument
Y_DETECT_NONE = 0
Y_DETECT_USB = 1
Y_DETECT_NET = 2
Y_RESEND_MISSING_PKT = 4
Y_DETECT_ALL = Y_DETECT_USB | Y_DETECT_NET
DETECT_NONE = 0
DETECT_USB = 1
DETECT_NET = 2
RESEND_MISSING_PKT = 4
DETECT_ALL = DETECT_USB | DETECT_NET
YOCTO_API_VERSION_STR = "1.10"
YOCTO_API_VERSION_BCD = 0x0110
YOCTO_API_BUILD_NO = "PATCH_WITH_BUILD"
YOCTO_DEFAULT_PORT = 4444
YOCTO_VENDORID = 0x24e0
YOCTO_DEVID_FACTORYBOOT = 1
YOCTO_DEVID_BOOTLOADER = 2
YOCTO_ERRMSG_LEN = 256
YOCTO_MANUFACTURER_LEN = 20
YOCTO_SERIAL_LEN = 20
YOCTO_BASE_SERIAL_LEN = 8
YOCTO_PRODUCTNAME_LEN = 28
YOCTO_FIRMWARE_LEN = 22
YOCTO_LOGICAL_LEN = 20
YOCTO_FUNCTION_LEN = 20
HASH_BUF_SIZE = 28
# Size of the data (can be non null terminated)
YOCTO_PUBVAL_SIZE = 6
# Temporary storage, > YOCTO_PUBVAL_SIZE
YOCTO_PUBVAL_LEN = 16
YOCTO_PASS_LEN = 20
YOCTO_REALM_LEN = 20
YIOHDL_SIZE = 8
INVALID_YHANDLE = 0
YOCTO_CALIB_TYPE_OFS = 30
yUnknowSize = 1024
C_INTSIZE = 4 # we assume an int size is 4 byte
_PlugEvents = []
_DataEvents = []
_CalibHandlers = {}
# private extern static void DllCallTest(ref yDeviceSt data);
# _DllCallTest = yApiCLib.DllCallTest
# _DllCallTest.restypes = ctypes.c_int
# _DllCallTest.argtypes = [ctypes.c_void_p]
_yApiCLibFile = ""
_yApiCLibFileFallback = ""
_yApiCLib = None
_yapiContext = YAPIContext()
@staticmethod
def SelectArchitecture(arch):
"""
Select the architecture or the library to be loaded to access to USB.
By default, the Python library automatically detects the appropriate
library to use. However, for Linux ARM, it not possible to reliably
distinguish between a Hard Float (armhf) and a Soft Float (armel)
install. For in this case, it is therefore recommended to manually
select the proper architecture by calling SelectArchitecture()
before any other call to the library.
@param arch : A string containing the architecture to use.
Possibles value are: "armhf","armel",
"aarch64","i386","x86_64",
"32bit", "64bit"