-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathyocto_api.php
9869 lines (9250 loc) · 377 KB
/
yocto_api.php
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
<?php
/*********************************************************************
*
* $Id: yocto_api.php 29949 2018-02-16 00:33:22Z mvuilleu $
*
* 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.
*
*********************************************************************/
//--- (generated code: YFunction definitions)
// Yoctopuce error codes, also used by default as function return value
define('YAPI_SUCCESS', 0); // everything worked all right
define('YAPI_NOT_INITIALIZED', -1); // call yInitAPI() first !
define('YAPI_INVALID_ARGUMENT', -2); // one of the arguments passed to the function is invalid
define('YAPI_NOT_SUPPORTED', -3); // the operation attempted is (currently) not supported
define('YAPI_DEVICE_NOT_FOUND', -4); // the requested device is not reachable
define('YAPI_VERSION_MISMATCH', -5); // the device firmware is incompatible with this API version
define('YAPI_DEVICE_BUSY', -6); // the device is busy with another task and cannot answer
define('YAPI_TIMEOUT', -7); // the device took too long to provide an answer
define('YAPI_IO_ERROR', -8); // there was an I/O problem while talking to the device
define('YAPI_NO_MORE_DATA', -9); // there is no more data to read from
define('YAPI_EXHAUSTED', -10); // you have run out of a limited resource, check the documentation
define('YAPI_DOUBLE_ACCES', -11); // you have two process that try to access to the same device
define('YAPI_UNAUTHORIZED', -12); // unauthorized access to password-protected device
define('YAPI_RTC_NOT_READY', -13); // real-time clock has not been initialized (or time was lost)
define('YAPI_FILE_NOT_FOUND', -14); // the file is not found
define('YAPI_INVALID_INT', 0x7fffffff);
define('YAPI_INVALID_UINT', -1);
define('YAPI_INVALID_LONG', 0x7fffffffffffffff);
define('YAPI_INVALID_DOUBLE', -66666666.66666666);
define('YAPI_INVALID_STRING', "!INVALID!");
define('Y_FUNCTIONDESCRIPTOR_INVALID', YAPI_INVALID_STRING);
define('Y_HARDWAREID_INVALID', YAPI_INVALID_STRING);
define('Y_FUNCTIONID_INVALID', YAPI_INVALID_STRING);
define('Y_FRIENDLYNAME_INVALID', YAPI_INVALID_STRING);
if(!defined('Y_LOGICALNAME_INVALID')) define('Y_LOGICALNAME_INVALID', YAPI_INVALID_STRING);
if(!defined('Y_ADVERTISEDVALUE_INVALID')) define('Y_ADVERTISEDVALUE_INVALID', YAPI_INVALID_STRING);
//--- (end of generated code: YFunction definitions)
define('YAPI_HASH_BUF_SIZE', 28);
//--- (generated code: YMeasure definitions)
//--- (end of generated code: YMeasure definitions)
if(!defined('Y_DATA_INVALID')) define('Y_DATA_INVALID', YAPI_INVALID_DOUBLE);
if(!defined('Y_DURATION_INVALID')) define('Y_DURATION_INVALID', YAPI_INVALID_INT);
//--- (generated code: YFirmwareUpdate definitions)
//--- (end of generated code: YFirmwareUpdate definitions)
//--- (generated code: YDataStream definitions)
//--- (end of generated code: YDataStream definitions)
//--- (generated code: YDataSet definitions)
//--- (end of generated code: YDataSet definitions)
//--- (generated code: YSensor definitions)
if(!defined('Y_ADVMODE_IMMEDIATE')) define('Y_ADVMODE_IMMEDIATE', 0);
if(!defined('Y_ADVMODE_PERIOD_AVG')) define('Y_ADVMODE_PERIOD_AVG', 1);
if(!defined('Y_ADVMODE_PERIOD_MIN')) define('Y_ADVMODE_PERIOD_MIN', 2);
if(!defined('Y_ADVMODE_PERIOD_MAX')) define('Y_ADVMODE_PERIOD_MAX', 3);
if(!defined('Y_ADVMODE_INVALID')) define('Y_ADVMODE_INVALID', -1);
if(!defined('Y_UNIT_INVALID')) define('Y_UNIT_INVALID', YAPI_INVALID_STRING);
if(!defined('Y_CURRENTVALUE_INVALID')) define('Y_CURRENTVALUE_INVALID', YAPI_INVALID_DOUBLE);
if(!defined('Y_LOWESTVALUE_INVALID')) define('Y_LOWESTVALUE_INVALID', YAPI_INVALID_DOUBLE);
if(!defined('Y_HIGHESTVALUE_INVALID')) define('Y_HIGHESTVALUE_INVALID', YAPI_INVALID_DOUBLE);
if(!defined('Y_CURRENTRAWVALUE_INVALID')) define('Y_CURRENTRAWVALUE_INVALID', YAPI_INVALID_DOUBLE);
if(!defined('Y_LOGFREQUENCY_INVALID')) define('Y_LOGFREQUENCY_INVALID', YAPI_INVALID_STRING);
if(!defined('Y_REPORTFREQUENCY_INVALID')) define('Y_REPORTFREQUENCY_INVALID', YAPI_INVALID_STRING);
if(!defined('Y_CALIBRATIONPARAM_INVALID')) define('Y_CALIBRATIONPARAM_INVALID', YAPI_INVALID_STRING);
if(!defined('Y_RESOLUTION_INVALID')) define('Y_RESOLUTION_INVALID', YAPI_INVALID_DOUBLE);
if(!defined('Y_SENSORSTATE_INVALID')) define('Y_SENSORSTATE_INVALID', YAPI_INVALID_INT);
//--- (end of generated code: YSensor definitions)
//--- (generated code: YModule definitions)
if(!defined('Y_PERSISTENTSETTINGS_LOADED')) define('Y_PERSISTENTSETTINGS_LOADED', 0);
if(!defined('Y_PERSISTENTSETTINGS_SAVED')) define('Y_PERSISTENTSETTINGS_SAVED', 1);
if(!defined('Y_PERSISTENTSETTINGS_MODIFIED')) define('Y_PERSISTENTSETTINGS_MODIFIED', 2);
if(!defined('Y_PERSISTENTSETTINGS_INVALID')) define('Y_PERSISTENTSETTINGS_INVALID', -1);
if(!defined('Y_BEACON_OFF')) define('Y_BEACON_OFF', 0);
if(!defined('Y_BEACON_ON')) define('Y_BEACON_ON', 1);
if(!defined('Y_BEACON_INVALID')) define('Y_BEACON_INVALID', -1);
if(!defined('Y_PRODUCTNAME_INVALID')) define('Y_PRODUCTNAME_INVALID', YAPI_INVALID_STRING);
if(!defined('Y_SERIALNUMBER_INVALID')) define('Y_SERIALNUMBER_INVALID', YAPI_INVALID_STRING);
if(!defined('Y_PRODUCTID_INVALID')) define('Y_PRODUCTID_INVALID', YAPI_INVALID_UINT);
if(!defined('Y_PRODUCTRELEASE_INVALID')) define('Y_PRODUCTRELEASE_INVALID', YAPI_INVALID_UINT);
if(!defined('Y_FIRMWARERELEASE_INVALID')) define('Y_FIRMWARERELEASE_INVALID', YAPI_INVALID_STRING);
if(!defined('Y_LUMINOSITY_INVALID')) define('Y_LUMINOSITY_INVALID', YAPI_INVALID_UINT);
if(!defined('Y_UPTIME_INVALID')) define('Y_UPTIME_INVALID', YAPI_INVALID_LONG);
if(!defined('Y_USBCURRENT_INVALID')) define('Y_USBCURRENT_INVALID', YAPI_INVALID_UINT);
if(!defined('Y_REBOOTCOUNTDOWN_INVALID')) define('Y_REBOOTCOUNTDOWN_INVALID', YAPI_INVALID_INT);
if(!defined('Y_USERVAR_INVALID')) define('Y_USERVAR_INVALID', YAPI_INVALID_INT);
//--- (end of generated code: YModule definitions)
// yInitAPI constants (not really useful in PHP, but defined for code portability)
define('Y_DETECT_NONE', 0);
define('Y_DETECT_USB', 1);
define('Y_DETECT_NET', 2);
define('Y_DETECT_ALL', Y_DETECT_USB | Y_DETECT_NET);
// Calibration types
define('YOCTO_CALIB_TYPE_OFS', 30);
// Maximum device request timeout
define('YAPI_BLOCKING_REQUEST_TIMEOUT', 30000);
define('NOTIFY_NETPKT_NAME', '0');
define('NOTIFY_NETPKT_CHILD', '2');
define('NOTIFY_NETPKT_FUNCNAME', '4');
define('NOTIFY_NETPKT_FUNCVAL', '5');
define('NOTIFY_NETPKT_LOG', '7');
define('NOTIFY_NETPKT_FUNCNAMEYDX', '8');
define('NOTIFY_NETPKT_FLUSHV2YDX', 't');
define('NOTIFY_NETPKT_FUNCV2YDX', 'u');
define('NOTIFY_NETPKT_TIMEV2YDX', 'v');
define('NOTIFY_NETPKT_DEVLOGYDX', 'w');
define('NOTIFY_NETPKT_TIMEVALYDX', 'x');
define('NOTIFY_NETPKT_FUNCVALYDX', 'y');
define('NOTIFY_NETPKT_TIMEAVGYDX', 'z');
define('NOTIFY_NETPKT_NOT_SYNC', '@');
define('NOTIFY_NETPKT_STOP', 10); // =\n
define('NOTIFY_V2_LEGACY', 0); // unused (reserved for compatibility with legacy notifications)
define('NOTIFY_V2_6RAWBYTES', 1); // largest type: data is always 6 bytes
define('NOTIFY_V2_TYPEDDATA', 2); // other types: first data byte holds the decoding format
define('NOTIFY_V2_FLUSHGROUP', 3); // no data associated
define('PUBVAL_LEGACY', 0); // 0-6 ASCII characters (normally sent as YSTREAM_NOTICE)
define('PUBVAL_1RAWBYTE', 1); // 1 raw byte (=2 characters)
define('PUBVAL_2RAWBYTES', 2); // 2 raw bytes (=4 characters)
define('PUBVAL_3RAWBYTES', 3); // 3 raw bytes (=6 characters)
define('PUBVAL_4RAWBYTES', 4); // 4 raw bytes (=8 characters)
define('PUBVAL_5RAWBYTES', 5); // 5 raw bytes (=10 characters)
define('PUBVAL_6RAWBYTES', 6); // 6 hex bytes (=12 characters) (sent as V2_6RAWBYTES)
define('PUBVAL_C_LONG', 7); // 32-bit C signed integer
define('PUBVAL_C_FLOAT', 8); // 32-bit C float
define('PUBVAL_YOCTO_FLOAT_E3', 9); // 32-bit Yocto fixed-point format (e-3)
define('PUBVAL_YOCTO_FLOAT_E6', 10); // 32-bit Yocto fixed-point format (e-6)
define('YOCTO_PUBVAL_LEN', 16);
define('YOCTO_PUBVAL_SIZE', 6);
define('YOCTO_SERIAL_LEN', 20);
define('YOCTO_BASE_SERIAL_LEN', 8);
//
// Class used to report exceptions within Yocto-API
// Do not instantiate directly
//
class YAPI_Exception extends Exception {}
// Pseudo class used to create structures in PHP
class YAggregate {}
// numeric strpos helper
function Ystrpos($haystack, $needle)
{
$res = strpos($haystack, $needle);
if($res === false) $res = -1;
return $res;
}
//
// Structure used internally to report results of a query. It only uses public attributes.
// Do not instantiate directly
//
class YAPI_YReq
{
public $hwid = "";
public $deviceid = "";
public $functionid = "";
public $errorType;
public $errorMsg;
public $result;
function __construct($str_hwid, $int_errType, $str_errMsg, $obj_result)
{
$sep = strpos($str_hwid, ".");
if($sep !== false) {
$this->hwid = $str_hwid;
$this->deviceid = substr($str_hwid, 0, $sep);
$this->functionid = substr($str_hwid, $sep+1);
}
$this->errorType = $int_errType;
$this->errorMsg = $str_errMsg;
$this->result = $obj_result;
}
}
//
// YTcpHub Class (used internally)
//
// Instances of this class represent a VirtualHub or a networked Yoctopuce device
// to which we can connect to get access to device functions. For historical reasons,
// this class is mostly used like a structure, rather than a real object.
//
class YTcpHub
{
// attributes
public $rooturl; // root url of the hub (without auth parameters)
public $streamaddr; // stream address of the hub ("tcp://addr:port")
public $notifurl; // notification file used by this hub
/** @var YTcpReq */
public $notifReq; // notification request, or null if not open
public $notifPos; // absolute position in notification stream
public $devListValidity; // default validity of updateDeviceList
public $devListExpires; // timestamp of next useful updateDeviceList
/** @var YTcpReq */
public $devListReq; // updateDeviceList request, or null if not open
public $serialByYdx; // serials by hub-specific devYdx
public $retryDelay; // delay before reconnecting in case of error
public $retryExpires; // timestamp of next reconnection attempt
public $missing; // list of missing devices during updateDeviceList
public $writeProtected; // true if an adminPassword is set
public $user; // user for authentication
public $callbackData; // raw HTTP callback data received
public $callbackCache; // pre-parsed cache for callback-based API
public $reuseskt; // keep-alive socket to be reused
protected $realm; // hub authentication realm
protected $pwd; // password for authentication
protected $nonce; // lasPrint(t received nonce
protected $opaque; // last received opaque
protected $ha1; // our authentication ha1 string
protected $nc; // nounce usage count
function __construct($rooturl, $auth)
{
$this->rooturl = $rooturl;
$this->streamaddr = str_replace('http://', 'tcp://', $rooturl);
$colon = strpos($auth, ':');
if($colon === false) {
$this->user = $auth;
$this->pwd = '';
} else {
$this->user = substr($auth, 0, $colon);
$this->pwd = substr($auth, $colon+1);
}
$this->notifurl = 'not.byn';
$this->notifHandle = null;
$this->notifPos = -1;
$this->devListValidity = 500;
$this->devListExpires = 0;
$this->serialByYdx = Array();
$this->retryDelay = 15;
$this->retryExpires = 0;
$this->writeProtected = false;
}
/**
* @param mixed
* @param mixed
* @return mixed
*/
static function decodeJZON($jzon, $ref)
{
$res = array();
$ofs = 0;
if (is_array($ref)) {
foreach ($ref as $key => $value) {
if (key_exists($key, $jzon)) {
$res[$key] = self::decodeJZON($jzon[$key], $value);
} else if (isset($jzon[$ofs])){
$res[$key] = self::decodeJZON($jzon[$ofs], $value);
}
$ofs++;
}
return $res;
}
return $jzon;
}
/**
* @param array
* @return mixed
*/
static function cleanJsonRef($ref)
{
$res = array();
foreach ($ref as $key => $value) {
if (is_array($value)) {
$res[$key] = self::cleanJsonRef($value);
} else if ($key =="serialNumber"){
$res[$key] = substr($value,0, YOCTO_BASE_SERIAL_LEN);
} else if ($key =="firmwareRelease") {
$res[$key] = $value;
} else {
$res[$key] = "";
}
}
return $res;
}
function verfiyStreamAddr($fullTest = true, &$errmsg = '')
{
if ($this->streamaddr == 'tcp://CALLBACK/') {
if (!isset($_SERVER['REQUEST_METHOD']) || $_SERVER['REQUEST_METHOD'] != 'POST') {
$errmsg = "invalid request method";
$this->callbackCache = Array();
return YAPI_IO_ERROR;
}
if (!isset($_SERVER['CONTENT_TYPE']) || $_SERVER['CONTENT_TYPE'] != 'application/json') {
$errmsg = "invalid content type";
$this->callbackCache = Array();
return YAPI_IO_ERROR;
}
if (!isset($_SERVER['HTTP_USER_AGENT'])) {
$errmsg = "not agent provided";
$this->callbackCache = Array();
return YAPI_IO_ERROR;
}
$useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
$patern = 'yoctohub';
if ($useragent != 'virtualhub' && substr($useragent, 0, strlen($patern)) != $patern) {
$errmsg = "no user agent provided";
$this->callbackCache = Array();
return YAPI_IO_ERROR;
}
if ($fullTest) {
$data = file_get_contents('php://input', 'rb');
$this->callbackData = $data;
if ($data == "") {
$errmsg = "RegisterHub(callback) used without posting YoctoAPI data";
Print("\n!YoctoAPI:$errmsg\n");
$this->callbackCache = Array();
return YAPI_IO_ERROR;
} else {
$utf8_encode = utf8_encode($data);
$this->callbackCache = json_decode($utf8_encode, true);
if (is_null($this->callbackCache)) {
$errmsg = "invalid data:[\n$data\n]";
Print("\n!YoctoAPI:$errmsg\n");
$this->callbackCache = Array();
return YAPI_IO_ERROR;
}
if ($this->pwd != '') {
// callback data signed, verify signature
if (!isset($this->callbackCache['sign'])) {
$errmsg = "missing signature from incoming YoctoHub (callback password required)";
Print("\n!YoctoAPI:$errmsg\n");
$this->callbackCache = Array();
return YAPI_UNAUTHORIZED;
}
$sign = $this->callbackCache['sign'];
$salt = $this->pwd;
if (strlen($salt) != 32) $salt = md5($salt);
$data = str_replace($sign, strtolower($salt), $data);
$check = strtolower(md5($data));
if ($check != $sign) {
//Print("Computed signature: $check\n");
//Print("Received signature: $sign\n");
$errmsg = "invalid signature from incoming YoctoHub (invalid callback password)";
Print("\n!YoctoAPI:$errmsg\n");
$this->callbackCache = Array();
return YAPI_UNAUTHORIZED;
}
}
if (isset($this->callbackCache['serial']) && !is_null(YAPI::$_jzonCacheDir)) {
$jzonCacheDir = YAPI::$_jzonCacheDir;
$mergedCache = array();
$upToDate = true;
foreach ($this->callbackCache as $req => $value) {
$pos = strpos($req, "/api.json");
if ($pos !== False) {
$fwpos = strpos($req, "?fw=", $pos);
$isJZON = false;
if ($fwpos !== False) {
if (key_exists('module', $value)) {
// device did not returned JZON (probably due to fw update)
$req = substr($req, 0, $fwpos);
} else {
$isJZON = true;
}
}
if ($isJZON) {
if ($pos == 0) {
$serial = $this->callbackCache['serial'];
} else {
// "/bySerial/" = 10 chars
$serial = substr($req, 10, $pos - 10);
}
$firm = substr($req, $fwpos + 4);
$base = substr($serial,0, YOCTO_BASE_SERIAL_LEN);
if (!is_file("{$jzonCacheDir}{$base}_{$firm}.json")) {
$errmsg = "No JZON reference file for {$serial}/{$firm}";
Print("\n!YoctoAPI:$errmsg\n");
$this->callbackCache = Array();
Print("\n@YoctoAPI:#!noref\n");
return YAPI_IO_ERROR;
}
$ref = file_get_contents("{$jzonCacheDir}{$base}_{$firm}.json");
$ref = json_decode($ref, true);
$decoded = self::decodeJZON($value, $ref);
if ($ref['module']['firmwareRelease'] != $decoded['module']['firmwareRelease']) {
$errmsg = "invalid JZON data";
Print("\n!YoctoAPI:$errmsg\n");
$this->callbackCache = Array();
Print("\n@YoctoAPI:#!invalid\n");
return YAPI_IO_ERROR;
}
$req = substr($req, 0, $fwpos);
$mergedCache[$req] = $decoded;
//Print("Use jzon data for{$serial}/{$firm}\n");
} else {
$serial = $value['module']['serialNumber'];
$base = substr($serial,0, YOCTO_BASE_SERIAL_LEN);
$firm = $value['module']['firmwareRelease'];
$clean_struct = self::cleanJsonRef($value);
file_put_contents("{$jzonCacheDir}{$base}_{$firm}.json", json_encode($clean_struct));
$mergedCache[$req] = $value;
Print("\n@YoctoAPI:#{$serial}/{$firm}\n");
$upToDate=false;
}
}
}
if ($upToDate) {
Print("\n@YoctoAPI:#=\n");
}
$this->callbackCache = $mergedCache;
}
}
}
} else {
$this->callbackCache = NULL;
}
return 0;
}
// Update the hub internal variables according
// to a received header with WWW-Authenticate
function parseWWWAuthenticate($header)
{
$pos = stripos($header, "\r\nWWW-Authenticate:");
if($pos === false) return;
$header = substr($header, $pos+19);
$eol = strpos($header, "\r");
if($eol !== false) {
$header = substr($header, 0, $eol);
}
$tags = null;
if(preg_match_all('~(?<tag>\w+)="(?<value>[^"]*)"~m', $header, $tags) == false) {
return;
}
$this->realm = '';
$this->qop = '';
$this->nonce = '';
$this->opaque = '';
for($i = 0; $i < sizeof($tags['tag']); $i++) {
if($tags['tag'][$i] == "realm") {
$this->realm = $tags['value'][$i];
} else if($tags['tag'][$i] == "qop") {
$this->qop = $tags['value'][$i];
} else if($tags['tag'][$i] == "nonce") {
$this->nonce = $tags['value'][$i];
} else if($tags['tag'][$i] == "opaque") {
$this->opaque = $tags['value'][$i];
}
}
$this->nc = 0;
$this->ha1 = md5($this->user.':'.$this->realm.':'.$this->pwd);
}
// Return an Authorization header for a given request
function getAuthorization($request)
{
if($this->user == '' || $this->realm == '') return '';
$this->nc++;
$pos = strpos($request, ' ');
$method = substr($request, 0, $pos);
$uri = substr($request, $pos+1);
$nc = sprintf("%08x", $this->nc);
$cnonce = sprintf("%08x", mt_rand(0,0x7fffffff));
$ha1 = $this->ha1;
$ha2 = md5("{$method}:{$uri}");
$nonce = $this->nonce;
$response = md5("{$ha1}:{$nonce}:{$nc}:{$cnonce}:auth:{$ha2}");
$res = 'Authorization: Digest username="'.$this->user.'", realm="'.$this->realm.'",'.
' nonce="'.$this->nonce.'", uri="'.$uri.'", qop=auth, nc='.$nc.','.
' cnonce="'.$cnonce.'", response="'.$response.'", opaque="'.$this->opaque.'"';
return "$res\r\n";
}
// Return true if a hub is just a virtual cache (for callback mode)
function isCachedHub()
{
return !is_null($this->callbackCache);
}
// Execute a query for cached hub (for callback mode)
function cachedQuery($str_query, $str_body)
{
// apply POST remotely
if(substr($str_query, 0, 5) == 'POST ') {
$boundary = '???';
$endb = strpos($str_body, "\r");
if(substr($str_body, 0, 2)=='--' && $endb > 2 && $endb < 20) {
$boundary = substr($str_body, 2, $endb-2);
}
Printf("\n@YoctoAPI:$str_query %d:%s\n%s", strlen($str_body), $boundary, $str_body);
return "OK\r\n\r\n";
}
if(substr($str_query, 0, 4) != 'GET ')
return NULL;
// remove JZON trigger if present (not relevant in callback mode)
$jzon = strpos($str_query, '?fw=');
if($jzon !== FALSE && strpos($str_query, '&', $jzon) === FALSE) {
$str_query = substr($str_query, 0, $jzon);
}
// dispatch between cached get and remote set
if(strpos($str_query, '?') === FALSE ||
strpos($str_query, '/logs.txt') !== FALSE ||
strpos($str_query, '/logger.json') !== FALSE ||
strpos($str_query, '/ping.txt') !== FALSE ||
strpos($str_query, '/files.json?a=dir') !== FALSE) {
// read request, load from cache
$parts = explode(' ',$str_query);
$url = $parts[1];
$getmodule = (strpos($url, 'api/module.json') !== FALSE);
if($getmodule) {
$url = str_replace('api/module.json','api.json',$url);
}
if(!isset($this->callbackCache[$url])) {
Print("\n!YoctoAPI:$url is not preloaded, adding to list");
Print("\n@YoctoAPI:+$url\n");
return NULL;
}
// Print("\n[$url found]\n");
$jsonres = $this->callbackCache[$url];
if($getmodule) $jsonres = $jsonres['module'];
if(strpos($str_query, '.json') !== FALSE) {
$jsonres = json_encode($jsonres);
}
return "OK\r\n\r\n$jsonres";
} else {
// change request, print to output stream
Print("\n@YoctoAPI:$str_query\n");
return "OK\r\n\r\n";
}
}
}
//
// YTcpReq Class (used internally)
//
// Instances of this class represent an open TCP connection to a HTTP socket.
// The class handles digest authorization transparently.
//
class YTcpReq
{
// attributes
/* @var $hub YTcpHub */
public $hub; // the YTcpHub to which we connect
public $async; // true if the request is async
public $skt; // stream socket
public $request; // request to be sent
public $reqbody; // request body to send, if any
public $boundary; // request body boundary, if used
public $meta; // HTTP headers received in reply
public $reply; // reply buffer
public $retryCount; // number of retries for this request
// the following attributes should not be taken for granted unless eof() returns true
public $errorType; // status of current connection
public $errorMsg; // last error message
public $reqcnt;
public static $totalTcpReqs = 0;
function __construct($hub, $request, $async, $reqbody='', $mstimeout = YAPI_BLOCKING_REQUEST_TIMEOUT)
{
$pos = strpos($request, "\r");
if($pos !== false) {
$request = substr($request, 0, $pos);
}
$boundary = '';
if($reqbody != '') {
do {
$boundary = sprintf("Zz%06xzZ", mt_rand(0, 0xffffff));
} while(strpos($reqbody, $boundary) !== false);
$reqbody = "--{$boundary}\r\n{$reqbody}\r\n--{$boundary}--\r\n";
}
$this->hub = $hub;
$this->async = $async;
$this->request = trim($request);
$this->reqbody = $reqbody;
$this->boundary = $boundary;
$this->meta = '';
$this->reply = '';
$this->retryCount = 0;
$this->mstimeout = $mstimeout;
$this->errorType = YAPI_IO_ERROR;
$this->errorMsg = 'could not open connection';
$this->reqcnt = ++YTcpReq::$totalTcpReqs;
}
function eof()
{
if(!is_null($this->skt)) {
// there is still activity going on
return false;
}
if($this->meta != '' && $this->errorType == YAPI_SUCCESS) {
// connection was done and ended successfully
return true;
}
if($this->retryCount > 3) {
// connection permanently failed
return true;
}
// connection is expected to be reopened
return false;
}
function newsocket(&$errno, &$errstr, $mstimeout)
{
// for now, use client socket only since server sockets
// for callbacks are not reliably available on a public server
$addr = $this->hub->streamaddr;
$pos = strpos($addr, '/', 9);
if($pos !== FALSE) {
$addr = substr($addr, 0, $pos);
}
return @stream_socket_client($addr, $errno, $errstr, $mstimeout / 1000);
}
function process(&$errmsg = '')
{
if($this->eof()) {
if($this->errorType != YAPI_SUCCESS) {
$errmsg = $this->errorMsg;
}
return $this->errorType;
}
if(!is_null($this->skt) && !is_resource($this->skt)) {
// connection died, need to reopen
$this->skt = null;
}
if(is_null($this->skt)) {
// need to reopen connection
if($this->hub->isCachedHub()) {
// special handling for "connection-less" callback mode
$data = $this->hub->cachedQuery($this->request, $this->reqbody);
if(is_null($data)) {
$this->errorType = YAPI_NOT_SUPPORTED;
$this->errorMsg = "query is not available in callback mode";
$this->retryCount = 99;
return YAPI_SUCCESS; // will propagate error later if needed
}
$skt = fopen('data:text/plain;base64,'.base64_encode($data), 'rb');
if ($skt === false) {
$this->errorType = YAPI_IO_ERROR;
$this->errorMsg = "failed to open data stream";
$this->retryCount = 99;
return YAPI_SUCCESS; // will propagate error later if needed
}
stream_set_blocking($skt, 0);
$this->skt = $skt;
} else {
$skt = null;
if(!is_null($this->hub->reuseskt)) {
$skt = $this->hub->reuseskt;
$this->hub->reuseskt = null;
if(!is_resource($skt)) {
// reusable socket is no more valid
$skt = null;
}
}
if(is_null($skt)) {
$errno = 0;
$errstr = '';
$skt = $this->newsocket($errno, $errstr, $this->mstimeout);
if ($skt === false) {
$this->errorType = YAPI_IO_ERROR;
$this->errorMsg = "failed to open socket ($errno): $errstr";
$this->retryCount++;
return YAPI_SUCCESS; // will retry later
}
}
stream_set_blocking($skt, 0);
$request = $this->request . " \r\n" . // no HTTP/1.1 suffix for light queries
$this->hub->getAuthorization($this->request);
if($this->boundary != '') {
$request .= "Content-Type: multipart/form-data; boundary={$this->boundary}\r\n";
}
if(substr($this->request,-2) == "&.") {
$request .= "\r\n";
} else {
$request .= "Connection: close\r\n\r\n";
}
$reqlen = strlen($request);
if (fwrite($skt, $request, $reqlen) != $reqlen) {
fclose($skt);
$this->errorType = YAPI_IO_ERROR;
$this->errorMsg = "failed to write to socket";
$this->retryCount++;
return YAPI_SUCCESS; // will retry later
}
$this->skt = $skt;
}
} else {
// read anything available on current socket, and process authentication headers
while(true) {
$data = fread($this->skt, 8192);
if($data === false) {
$this->errorType = YAPI_IO_ERROR;
$this->errorMsg = "failed to read from socket";
$this->retryCount++;
return YAPI_SUCCESS; // will retry later
}
//Printf("[read %d bytes]\n",strlen($data));
if(strlen($data) == 0) break;
if($this->reply == '' && strpos($this->meta, "\r\n\r\n") === false) {
$this->meta .= $data;
$eoh = strpos($this->meta, "\r\n\r\n");
if($eoh !== false) {
// fully received header
$this->reply = substr($this->meta, $eoh+4);
$this->meta = substr($this->meta, 0, $eoh+4);
$firstline = substr($this->meta, 0, strpos($this->meta, "\r"));
if(substr($firstline, 0, 12) == 'HTTP/1.1 401') {
// authentication required
$this->errorType = YAPI_UNAUTHORIZED;
$this->errorMsg = "Authentication required";
fclose($this->skt);
$this->skt = null;
$this->hub->parseWWWAuthenticate($this->meta);
if($this->hub->user != '') {
$this->meta = '';
$this->reply = '';
$this->retryCount++;
} else {
$this->retryCount = 99;
}
return YAPI_SUCCESS; // will propagate error later if needed
}
}
} else {
$this->reply .= $data;
}
// so far so good
$this->errorType = YAPI_SUCCESS;
}
// write request body, if any, once header is fully received
if($this->reqbody != '' && strpos($this->meta, "\r\n\r\n") !== false) {
$bodylen = strlen($this->reqbody);
$written = fwrite($this->skt, $this->reqbody, $bodylen);
if($written > 0) {
$this->reqbody = substr($this->reqbody, $written);
}
}
if(!is_resource($this->skt)) {
// socket dropped dead
$this->skt = null;
} else if(feof($this->skt)) {
fclose($this->skt);
$this->skt = null;
} else if($this->meta == "0K\r\n\r\n" && $this->reply == "\r\n") {
if(is_null($this->hub->reuseskt)) {
$this->hub->reuseskt = $this->skt;
} else {
fclose($this->skt);
}
$this->skt = null;
}
}
return YAPI_SUCCESS;
}
function close()
{
if($this->skt) fclose($this->skt);
}
}
//
// YFunctionType Class (used internally)
//
// Instances of this class stores everything we know about a given type of function:
// Mapping between function logical names and Hardware ID as discovered on hubs,
// and existing instances of YFunction (either already connected or simply requested).
// To keep it simple, this implementation separates completely the name resolution
// mechanism, implemented using the yellow pages, and the storage and retrieval of
// existing YFunction instances.
//
class YFunctionType
{
// private attributes, to be used within yocto_api only
protected $_className;
protected $_connectedFns; // functions requested and available, by Hardware Id
protected $_requestedFns; // functions requested but not yet known, by any type of name
protected $_hwIdByName; // hash table of function Hardware Id by logical name
protected $_nameByHwId; // hash table of function logical name by Hardware Id
protected $_valueByHwId; // hash table of function advertised value by logical name
protected $_baseType; // default to no abstract base type (generic YFunction)
function __construct($str_classname)
{
if(ord($str_classname[strlen($str_classname)-1]) <= 57) throw new Exception("Invalid function type",-1);
$this->_className = $str_classname;
$this->_connectedFns = Array();
$this->_requestedFns = Array();
$this->_hwIdByName = Array();
$this->_nameByHwId = Array();
$this->_valueByHwId = Array();
$this->_baseType = 0;
}
// Index a single function given by HardwareId and logical name; store any advertised value
// Return true iff there was a logical name discrepency
public function reindexFunction($str_hwid, $str_name, $str_val, $int_basetype)
{
$currname = '';
$res = false;
if(isset($this->_nameByHwId[$str_hwid])) {
$currname = $this->_nameByHwId[$str_hwid];
}
if($currname == '') {
if($str_name != '') {
$this->_nameByHwId[$str_hwid] = $str_name;
$res = true;
}
} else if($currname != $str_name) {
if($this->_hwIdByName[$currname] == $str_hwid)
unset($this->_hwIdByName[$currname]);
if($str_name != '') {
$this->_nameByHwId[$str_hwid] = $str_name;
} else {
unset($this->_nameByHwId[$str_hwid]);
}
$res = true;
}
if($str_name != '') {
$this->_hwIdByName[$str_name] = $str_hwid;
}
if(!is_null($str_val)) {
$this->_valueByHwId[$str_hwid] = $str_val;
} else {
if(!isset($this->_valueByHwId[$str_hwid])) {
$this->_valueByHwId[$str_hwid] = '';
}
}
if(!is_null($int_basetype)) {
if($this->_baseType == 0) {
$this->_baseType = $int_basetype;
}
}
return $res;
}
// Forget a disconnected function given by HardwareId
public function forgetFunction($str_hwid)
{
if(isset($this->_nameByHwId[$str_hwid])) {
$currname = $this->_nameByHwId[$str_hwid];
if($currname != '' && $this->_hwIdByName[$currname] == $str_hwid) {
unset($this->_hwIdByName[$currname]);
}
unset($this->_nameByHwId[$str_hwid]);
}
if(isset($this->_valueByHwId[$str_hwid])) {
unset($this->_valueByHwId[$str_hwid]);
}
}
// Find the exact Hardware Id of the specified function, if currently connected
// If device is not known as connected, return a clean error
// This function will not cause any network access
public function resolve($str_func)
{
// Try to resolve str_func to a known Function instance, if possible, without any device access
$dotpos = strpos($str_func, '.');
if($dotpos === false) {
// First case: str_func is the logicalname of a function
if(isset($this->_hwIdByName[$str_func])) {
return new YAPI_YReq($this->_hwIdByName[$str_func],
YAPI_SUCCESS,
'no error',
$this->_hwIdByName[$str_func]);
}
// fallback to assuming that str_func is a logicalname or serial number of a module
// with an implicit function name (like serial.module for instance)
$dotpos = strlen($str_func);
$str_func .= '.'.strtolower($this->_className[0]).substr($this->_className,1);
}
// Second case: str_func is in the form: device_id.function_id
// quick lookup for a known pure hardware id
if(isset($this->_valueByHwId[$str_func])) {
return new YAPI_YReq($this->_valueByHwId[$str_func],
YAPI_SUCCESS,
'no error',
$str_func);
}
if($dotpos>0){
// either the device id is a logical name, or the function is unknown
$devid = substr($str_func, 0, $dotpos);
$funcid = substr($str_func, $dotpos+1);
$dev = YAPI::getDevice($devid);
if(!$dev) {
return new YAPI_YReq($str_func,
YAPI_DEVICE_NOT_FOUND,
"Device [$devid] not online",
null);
}
$serial = $dev->getSerialNumber();
$res = "$serial.$funcid";
if(isset($this->_valueByHwId[$res])) {
return new YAPI_YReq($res,
YAPI_SUCCESS,
'no error',
$res);
}
// not found neither, may be funcid is a function logicalname
$nfun = $dev->functionCount();
for($i = 0; $i < $nfun; $i++) {
$res = "$serial.".$dev->functionId($i);
if(isset($this->_nameByHwId[$res])) {
$name = $this->_nameByHwId[$res];
if($name == $funcid) {
return new YAPI_YReq($res,
YAPI_SUCCESS,
'no error',
$res);
}
}
}
} else {
$serial = '';
$funcid = substr($str_func, 1);
// only functionId (ie ".temperature")
foreach(array_keys($this->_connectedFns) as $hwid_str){
$pos = strpos($hwid_str, '.');
$function = substr($hwid_str, $pos+1);
//print("search for $funcid in {$this->_className} $function\n");
if($function == $funcid){
return new YAPI_YReq($hwid_str,
YAPI_SUCCESS,
'no error',
$hwid_str);
}
}
}
return new YAPI_YReq("$serial.$funcid",
YAPI_DEVICE_NOT_FOUND,
"No function [$funcid] found on device [$serial]",
null);
}
public function getFriendlyName($str_func)
{
$resolved = $this->resolve($str_func);
if($resolved->errorType != YAPI_SUCCESS) {
return $resolved;
}
if($this->_className =="Module"){
$friend =$resolved->result;
if(isset($this->_nameByHwId[$resolved->result]))
$friend = $this->_nameByHwId[$resolved->result];
return new YAPI_YReq($resolved->result,