yocto_api.cpp
Go to the documentation of this file.
1 /*********************************************************************
2  *
3  * $Id: yocto_api.cpp 29703 2018-01-23 18:06:02Z seb $
4  *
5  * High-level programming interface, common to all modules
6  *
7  * - - - - - - - - - License information: - - - - - - - - -
8  *
9  * Copyright (C) 2011 and beyond by Yoctopuce Sarl, Switzerland.
10  *
11  * Yoctopuce Sarl (hereafter Licensor) grants to you a perpetual
12  * non-exclusive license to use, modify, copy and integrate this
13  * file into your software for the sole purpose of interfacing
14  * with Yoctopuce products.
15  *
16  * You may reproduce and distribute copies of this file in
17  * source or object form, as long as the sole purpose of this
18  * code is to interface with Yoctopuce products. You must retain
19  * this notice in the distributed source file.
20  *
21  * You should refer to Yoctopuce General Terms and Conditions
22  * for additional information regarding your rights and
23  * obligations.
24  *
25  * THE SOFTWARE AND DOCUMENTATION ARE PROVIDED "AS IS" WITHOUT
26  * WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
27  * WITHOUT LIMITATION, ANY WARRANTY OF MERCHANTABILITY, FITNESS
28  * FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO
29  * EVENT SHALL LICENSOR BE LIABLE FOR ANY INCIDENTAL, SPECIAL,
30  * INDIRECT OR CONSEQUENTIAL DAMAGES, LOST PROFITS OR LOST DATA,
31  * COST OF PROCUREMENT OF SUBSTITUTE GOODS, TECHNOLOGY OR
32  * SERVICES, ANY CLAIMS BY THIRD PARTIES (INCLUDING BUT NOT
33  * LIMITED TO ANY DEFENSE THEREOF), ANY CLAIMS FOR INDEMNITY OR
34  * CONTRIBUTION, OR OTHER SIMILAR COSTS, WHETHER ASSERTED ON THE
35  * BASIS OF CONTRACT, TORT (INCLUDING NEGLIGENCE), BREACH OF
36  * WARRANTY, OR OTHERWISE.
37  *
38  *********************************************************************/
39 #define __FILE_ID__ "yocto_api"
40 #define _CRT_SECURE_NO_DEPRECATE
41 #include "yocto_api.h"
42 #include "yapi/yapi.h"
43 
44 #ifdef WINDOWS_API
45 #include <Windows.h>
46 #define yySleep(ms) Sleep(ms)
47 #else
48 #include <unistd.h>
49 #define yySleep(ms) usleep(ms*1000)
50 #endif
51 
52 #include <string.h>
53 #include <stdio.h>
54 #include <stdlib.h>
55 #include <cfloat>
56 #include <cmath>
57 #include <time.h>
58 #include <stdarg.h>
59 #include <math.h>
60 #include "yapi/yproto.h"
61 
64 
65 static std::vector<YFunction*> _FunctionCallbacks;
66 static std::vector<YFunction*> _TimedReportCallbackList;
67 
68 
72 
74 
75 int _ystrpos(const string& haystack, const string& needle)
76 {
77  size_t pos = haystack.find(needle);
78  if(pos == string::npos) {
79  return -1;
80  }
81  return (int)pos;
82 }
83 
84 
85 vector<string> _strsplit(const string& str, char delimiter)
86 {
87  vector<string> res;
88  size_t pos = 0;
89  size_t found;
90 
91  do {
92  found = str.find(delimiter, pos);
93  if (found != std::string::npos) {
94  res.push_back(str.substr(pos, found - pos));
95  pos = found+1;
96  }
97  } while (found != std::string::npos);
98  res.push_back(str.substr(pos));
99  return res;
100 }
101 
102 
103 
104 YJSONContent* YJSONContent::ParseJson(const string& data, int start, int stop)
105 {
106  int cur_pos = YJSONContent::SkipGarbage(data, start, stop);
107  YJSONContent* res;
108  if (data[cur_pos] == '[') {
109  res = new YJSONArray(data, start, stop);
110  } else if (data[cur_pos] == '{') {
111  res = new YJSONObject(data, start, stop);
112  } else if (data[cur_pos] == '"') {
113  res = new YJSONString(data, start, stop);
114  } else {
115  res = new YJSONNumber(data, start, stop);
116  }
117  res->parse();
118  return res;
119 }
120 
121 YJSONContent::YJSONContent(const string& data, int start, int stop, YJSONType type)
122 {
123  _data = data;
124  _data_start = start;
125  _data_boundary = stop;
126  _type = type;
127 }
128 
130 {
131  _data = "";//todo: check not null
132 }
133 
135 {
136  _data = ref->_data;
137  _data_start = ref->_data_start;
139  _data_len = ref->_data_len;
140  _type = ref->_type;
141 }
142 
143 
145 {
146  _data = "";
147 }
148 
150 {
151  return _type;
152 }
153 
154 int YJSONContent::SkipGarbage(const string& data, int start, int stop)
155 {
156  if (data.length() <= (unsigned) start) {
157  return start;
158  }
159  char sti = data[start];
160  while (start < stop && (sti == '\n' || sti == '\r' || sti == ' ')) {
161  start++;
162  }
163  return start;
164 }
165 
166 string YJSONContent::FormatError(const string& errmsg, int cur_pos)
167 {
168  int ststart = cur_pos - 10;
169  int stend = cur_pos + 10;
170  if (ststart < 0)
171  ststart = 0;
172  if (stend > _data_boundary)
173  stend = _data_boundary;
174  if (_data == "") {//todo: check not null
175  return errmsg;
176  }
177  return errmsg + " near " + _data.substr(ststart, cur_pos - ststart) + _data.substr(cur_pos, stend - cur_pos);
178 }
179 
180 
181 
182 YJSONArray::YJSONArray(const string& data, int start, int stop) : YJSONContent(data, start, stop, ARRAY)
183 { }
184 
185 
187 { }
188 
190 {
191  for (unsigned i = 0; i < ref->_arrayValue.size(); i++) {
192  YJSONType type = ref->_arrayValue[i]->getJSONType();
193  switch (type) {
194  case ARRAY:
195  {
196  YJSONArray* tmp = new YJSONArray((YJSONArray*)ref->_arrayValue[i]);
197  _arrayValue.push_back(tmp);
198  }
199  break;
200  case NUMBER:
201  {
202  YJSONNumber* tmp = new YJSONNumber((YJSONNumber*)ref->_arrayValue[i]);
203  _arrayValue.push_back(tmp);
204  }
205  break;
206  case STRING:
207  {
208  YJSONString* tmp = new YJSONString((YJSONString*)ref->_arrayValue[i]);
209  _arrayValue.push_back(tmp);
210  }
211  break;
212  case OBJECT:
213  {
214  YJSONObject* tmp = new YJSONObject((YJSONObject*)ref->_arrayValue[i]);
215  _arrayValue.push_back(tmp);
216  }
217  break;
218  }
219  }
220 }
221 
222 
224 {
225  for (unsigned i = 0; i < _arrayValue.size(); i++) {
226  delete _arrayValue[i];
227  }
228  _arrayValue.clear();
229 }
230 
232 {
233  return (int) _arrayValue.size();
234 }
235 
237 {
238  int cur_pos = SkipGarbage(_data, _data_start, _data_boundary);
239 
240  if (_data[cur_pos] != '[') {
241  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("Opening braces was expected", cur_pos));
242  }
243  cur_pos++;
244  Tjstate state = JWAITFORDATA;
245 
246  while (cur_pos < _data_boundary) {
247  char sti = _data[cur_pos];
248  switch (state) {
249  case JWAITFORDATA:
250  if (sti == '{') {
251  YJSONObject* jobj = new YJSONObject(_data, cur_pos, _data_boundary);
252  int len = jobj->parse();
253  cur_pos += len;
254  _arrayValue.push_back(jobj);
255  state = JWAITFORNEXTARRAYITEM;
256  //cur_pos is already incremented
257  continue;
258  } else if (sti == '[') {
259  YJSONArray* jobj = new YJSONArray(_data, cur_pos, _data_boundary);
260  int len = jobj->parse();
261  cur_pos += len;
262  _arrayValue.push_back(jobj);
263  state = JWAITFORNEXTARRAYITEM;
264  //cur_pos is already incremented
265  continue;
266  } else if (sti == '"') {
267  YJSONString* jobj = new YJSONString(_data, cur_pos, _data_boundary);
268  int len = jobj->parse();
269  cur_pos += len;
270  _arrayValue.push_back(jobj);
271  state = JWAITFORNEXTARRAYITEM;
272  //cur_pos is already incremented
273  continue;
274  } else if (sti == '-' || (sti >= '0' && sti <= '9')) {
275  YJSONNumber* jobj = new YJSONNumber(_data, cur_pos, _data_boundary);
276  int len = jobj->parse();
277  cur_pos += len;
278  _arrayValue.push_back(jobj);
279  state = JWAITFORNEXTARRAYITEM;
280  //cur_pos is already incremented
281  continue;
282  } else if (sti == ']') {
283  _data_len = cur_pos + 1 - _data_start;
284  return _data_len;
285  } else if (sti != ' ' && sti != '\n' && sti != '\r') {
286  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("invalid char: was expecting \",0..9,t or f", cur_pos));
287  }
288  break;
290  if (sti == ',') {
291  state = JWAITFORDATA;
292  } else if (sti == ']') {
293  _data_len = cur_pos + 1 - _data_start;
294  return _data_len;
295  } else {
296  if (sti != ' ' && sti != '\n' && sti != '\r') {
297  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("invalid char: was expecting ,", cur_pos));
298  }
299  }
300  break;
301  default:
302  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("invalid state for YJSONObject", cur_pos));
303  }
304  cur_pos++;
305  }
306  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("unexpected end of data", cur_pos));
307 }
308 
310 {
311  return (YJSONObject*)_arrayValue[i];
312 }
313 
315 {
316  YJSONString* ystr = (YJSONString*)_arrayValue[i];
317  return ystr->getString();
318 }
319 
321 {
322  return _arrayValue[i];
323 }
324 
326 {
327  return (YJSONArray*)_arrayValue[i];
328 }
329 
331 {
332  YJSONNumber* ystr = (YJSONNumber*)_arrayValue[i];
333  return ystr->getInt();
334 }
336 {
337  YJSONNumber* ystr = (YJSONNumber*)_arrayValue[i];
338  return ystr->getLong();
339 }
340 
341  void YJSONArray::put(const string& flatAttr)
342 {
343  YJSONString* strobj = new YJSONString();
344  strobj->setContent(flatAttr);
345  _arrayValue.push_back(strobj);
346 }
347 
349 {
350  string res ="[";
351  string sep = "";
352  unsigned int i;
353  for (i = 0; i < _arrayValue.size(); i++){
354  YJSONContent* yjsonContent = _arrayValue[i];
355  string subres = yjsonContent->toJSON();
356  res += sep;
357  res += subres;
358  sep = ",";
359  }
360  res += ']';
361  return res;
362 }
363 
365 {
366  string res ="[";
367  string sep = "";
368  unsigned int i;
369  for (i = 0; i < _arrayValue.size(); i++){
370  YJSONContent* yjsonContent = _arrayValue[i];
371  string subres = yjsonContent->toString();
372  res += sep;
373  res += subres;
374  sep = ",";
375  }
376  res += ']';
377  return res;
378 }
379 
380 
381 
382 YJSONString::YJSONString(const string& data, int start, int stop) : YJSONContent(data, start, stop, STRING)
383 { }
384 
386 { }
387 
389 {
390  _stringValue = ref->_stringValue;
391 }
392 
394 {
395  string value = "";
396  int cur_pos = SkipGarbage(_data, _data_start, _data_boundary);
397 
398  if (_data[cur_pos] != '"') {
399  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("double quote was expected", cur_pos));
400  }
401  cur_pos++;
402  int str_start = cur_pos;
404 
405  while (cur_pos < _data_boundary) {
406  unsigned char sti = _data[cur_pos];
407  switch (state) {
408  case JWAITFORSTRINGVALUE:
409  if (sti == '\\') {
410  value += _data.substr(str_start, cur_pos - str_start);
411  str_start = cur_pos;
412  state = JWAITFORSTRINGVALUE_ESC;
413  } else if (sti == '"') {
414  value += _data.substr(str_start, cur_pos - str_start);
415  _stringValue = value;
416  _data_len = (cur_pos + 1) - _data_start;
417  return _data_len;
418  } else if (sti < 32) {
419  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("invalid char: was expecting string value", cur_pos));
420  }
421  break;
423  value += sti;
424  state = JWAITFORSTRINGVALUE;
425  str_start = cur_pos + 1;
426  break;
427  default:
428  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("invalid state for YJSONObject", cur_pos));
429  }
430  cur_pos++;
431  }
432  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("unexpected end of data", cur_pos));
433 }
434 
436 {
437  string res = "\"";
438  const char* c =_stringValue.c_str();
439  while(*c) {
440  switch (*c) {
441  case '"':
442  res += "\\\"";
443  break;
444  case '\\':
445  res += "\\\\";
446  break;
447  case '/':
448  res += "\\/";
449  break;
450  case '\b':
451  res += "\\b";
452  break;
453  case '\f':
454  res += "\\f";
455  break;
456  case '\n':
457  res += "\\n";
458  break;
459  case '\r':
460  res += "\\r";
461  break;
462  case '\t':
463  res += "\\t";
464  break;
465  default:
466  res += *c;
467  break;
468  }
469  c++;
470  }
471  res += '"';
472  return res;
473 }
474 
476 {
477  return _stringValue;
478 }
479 
481 {
482  return _stringValue;
483 }
484 
485  void YJSONString::setContent(const string& value)
486 {
487  _stringValue = value;
488 }
489 
490 
491 
492 YJSONNumber::YJSONNumber(const string& data, int start, int stop) : YJSONContent(data, start, stop, NUMBER), _intValue(0),_doubleValue(0),_isFloat(false)
493 { }
494 
496 {
497  _intValue = ref->_intValue;
498  _doubleValue = ref->_doubleValue;
499  _isFloat = ref->_isFloat;
500 }
501 
502 
504 {
505 
506  bool neg = false;
507  int start;
508  char sti;
509  int cur_pos = SkipGarbage(_data, _data_start, _data_boundary);
510  sti = _data[cur_pos];
511  if (sti == '-') {
512  neg = true;
513  cur_pos++;
514  }
515  start = cur_pos;
516  while (cur_pos < _data_boundary) {
517  sti = _data[cur_pos];
518  if (sti == '.' && _isFloat == false) {
519  string int_part = _data.substr(start, cur_pos - start);
520  _intValue = yatoi((int_part).c_str());
521  _isFloat = true;
522  } else if (sti < '0' || sti > '9') {
523  string numberpart = _data.substr(start, cur_pos - start);
524  if (_isFloat) {
525  _doubleValue = atof((numberpart).c_str());
526  } else {
527  _intValue = yatoi((numberpart).c_str());
528  }
529  if (neg) {
531  _intValue = 0 - _intValue;
532  }
533  return cur_pos - _data_start;
534  }
535  cur_pos++;
536  }
537  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("unexpected end of data", cur_pos));
538 }
539 
541 {
542  if (_isFloat)
543  return YapiWrapper::ysprintf("%f", _doubleValue);
544  else
545  return YapiWrapper::ysprintf("%d", _intValue);
546 }
547 
549 {
550  if (_isFloat)
551  return (s64)_doubleValue;
552  else
553  return _intValue;
554 }
555 
557 {
558  if (_isFloat)
559  return (int)_doubleValue;
560  else
561  return (int)_intValue;
562 }
563 
565 {
566  if (_isFloat)
567  return _doubleValue;
568  else
569  return (double)_intValue;
570 }
571 
573 {
574  if (_isFloat)
575  return YapiWrapper::ysprintf("%f", _doubleValue);
576  else
577  return YapiWrapper::ysprintf("%d", _intValue);
578 }
579 
580 
581 
582 
583 
584 
585 YJSONObject::YJSONObject(const string& data) : YJSONContent(data, 0, (int)data.length(), OBJECT)
586 { }
587 
588 YJSONObject::YJSONObject(const string& data, int start, int len) : YJSONContent(data, start, len, OBJECT)
589 { }
590 
592 {
593 
594  for (unsigned i = 0; i < ref->_keys.size(); i++) {
595  string key = ref->_keys[i];
596  _keys.push_back(key);
597  YJSONType type = ref->_parsed[key]->getJSONType();
598  switch (type) {
599  case ARRAY:
600  _parsed[key] = new YJSONArray((YJSONArray*)ref->_parsed[key]);
601  break;
602  case NUMBER:
603  _parsed[key] = new YJSONNumber((YJSONNumber*)ref->_parsed[key]);
604  break;
605  case STRING:
606  _parsed[key] = new YJSONString((YJSONString*)ref->_parsed[key]);
607  break;
608  case OBJECT:
609  _parsed[key] = new YJSONObject((YJSONObject*)ref->_parsed[key]);
610  break;
611  }
612  }
613 }
614 
616 {
617  //printf("relase YJSONObject\n");
618  for (unsigned i = 0; i < _keys.size(); i++) {
619  delete _parsed[_keys[i]];
620  }
621  _parsed.clear();
622  _keys.clear();
623 }
624 
626 {
627  string current_name = "";
628  int name_start = _data_start;
629  int cur_pos = SkipGarbage(_data, _data_start, _data_boundary);
630 
631  if (_data.length() <= (unsigned)cur_pos || _data[cur_pos] != '{') {
632  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("Opening braces was expected", cur_pos));
633  }
634  cur_pos++;
635  Tjstate state = JWAITFORNAME;
636 
637  while (cur_pos < _data_boundary) {
638  char sti = _data[cur_pos];
639  switch (state) {
640  case JWAITFORNAME:
641  if (sti == '"') {
642  state = JWAITFORENDOFNAME;
643  name_start = cur_pos + 1;
644  } else if (sti == '}') {
645  _data_len = cur_pos + 1 - _data_start;
646  return _data_len;
647  } else {
648  if (sti != ' ' && sti != '\n' && sti != '\r') {
649  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("invalid char: was expecting \"", cur_pos));
650  }
651  }
652  break;
653  case JWAITFORENDOFNAME:
654  if (sti == '"') {
655  current_name = _data.substr(name_start, cur_pos - name_start);
656  state = JWAITFORCOLON;
657 
658  } else {
659  if (sti < 32) {
660  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("invalid char: was expecting an identifier compliant char", cur_pos));
661  }
662  }
663  break;
664  case JWAITFORCOLON:
665  if (sti == ':') {
666  state = JWAITFORDATA;
667  } else {
668  if (sti != ' ' && sti != '\n' && sti != '\r') {
669  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("invalid char: was expecting \"", cur_pos));
670  }
671  }
672  break;
673  case JWAITFORDATA:
674  if (sti == '{') {
675  YJSONObject* jobj = new YJSONObject(_data, cur_pos, _data_boundary);
676  int len = jobj->parse();
677  cur_pos += len;
678  _parsed[current_name] = jobj;
679  _keys.push_back(current_name);
680  state = JWAITFORNEXTSTRUCTMEMBER;
681  //cur_pos is already incremented
682  continue;
683  } else if (sti == '[') {
684  YJSONArray* jobj = new YJSONArray(_data, cur_pos, _data_boundary);
685  int len = jobj->parse();
686  cur_pos += len;
687  _parsed[current_name] = jobj;
688  _keys.push_back(current_name);
689  state = JWAITFORNEXTSTRUCTMEMBER;
690  //cur_pos is already incremented
691  continue;
692  } else if (sti == '"') {
693  YJSONString* jobj = new YJSONString(_data, cur_pos, _data_boundary);
694  int len = jobj->parse();
695  cur_pos += len;
696  _parsed[current_name] = jobj;
697  _keys.push_back(current_name);
698  state = JWAITFORNEXTSTRUCTMEMBER;
699  //cur_pos is already incremented
700  continue;
701  } else if (sti == '-' || (sti >= '0' && sti <= '9')) {
702  YJSONNumber* jobj = new YJSONNumber(_data, cur_pos, _data_boundary);
703  int len = jobj->parse();
704  cur_pos += len;
705  _parsed[current_name] = jobj;
706  _keys.push_back(current_name);
707  state = JWAITFORNEXTSTRUCTMEMBER;
708  //cur_pos is already incremented
709  continue;
710  } else if (sti != ' ' && sti != '\n' && sti != '\r') {
711  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("invalid char: was expecting \",0..9,t or f", cur_pos));
712  }
713  break;
715  if (sti == ',') {
716  state = JWAITFORNAME;
717  name_start = cur_pos + 1;
718  } else if (sti == '}') {
719  _data_len = cur_pos + 1 - _data_start;
720  return _data_len;
721  } else {
722  if (sti != ' ' && sti != '\n' && sti != '\r') {
723  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("invalid char: was expecting ,", cur_pos));
724  }
725  }
726  break;
727  default:
728  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("invalid state for YJSONObject", cur_pos));
729  }
730  cur_pos++;
731  }
732  throw YAPI_Exception(YAPI_IO_ERROR, FormatError("unexpected end of data", cur_pos));
733 }
734 
735 bool YJSONObject::has(const string& key)
736 {
737  if (_parsed.find(key) == _parsed.end()) {
738  return false;
739  } else {
740  return true;
741  }
742 }
743 
745 {
746  return (YJSONObject*)_parsed[key];
747 }
748 
750 {
751  return (YJSONString*)_parsed[key];
752 }
753 
755 {
756  return (YJSONArray*)_parsed[key];
757 }
758 
759 vector<string> YJSONObject::keys()
760 {
761  vector<string> v;
762  for (map<string, YJSONContent*>::iterator it = _parsed.begin(); it != _parsed.end(); ++it) {
763  v.push_back(it->first);
764  }
765  return v;
766 }
767 
769 {
770  return (YJSONNumber*)_parsed[key];
771 }
772 
773 string YJSONObject::getString(const string& key)
774 {
775  YJSONString* ystr = (YJSONString*)_parsed[key];
776  return ystr->getString();
777 }
778 
779 int YJSONObject::getInt(const string& key)
780 {
781  YJSONNumber* yint = (YJSONNumber*)_parsed[key];
782  return yint->getInt();
783 }
784 
785 YJSONContent* YJSONObject::get(const string& key)
786 {
787  return _parsed[key];
788 }
789 
790 s64 YJSONObject::getLong(const string& key)
791 {
792  YJSONNumber* yint = (YJSONNumber*)_parsed[key];
793  return yint->getLong();
794 }
795 
796 double YJSONObject::getDouble(const string& key)
797 {
798  YJSONNumber* yint = (YJSONNumber*)_parsed[key];
799  return yint->getDouble();
800 }
801 
803 {
804  string res = "{";
805  string sep = "";
806  unsigned int i;
807  for (i = 0; i < _keys.size(); i++) {
808  string key = _keys[i];
809  YJSONContent* subContent = _parsed[key];
810  string subres = subContent->toJSON();
811  res += sep;
812  res += '"';
813  res += key;
814  res += "\":";
815  res += subres;
816  sep = ",";
817  }
818  res += '}';
819  return res;
820 }
821 
823 {
824  string res = "{";
825  string sep = "";
826  unsigned int i;
827  for (i = 0; i < _keys.size(); i++) {
828  string key = _keys[i];
829  YJSONContent* subContent = _parsed[key];
830  string subres = subContent->toString();
831  res += sep;
832  res += '"';
833  res += key;
834  res += "\":";
835  res += subres;
836  sep = ",";
837  }
838  res += '}';
839  return res;
840 }
841 
842 
843 
845 {
846  if (reference != NULL) {
847  try {
849  yzon->parse();
850  convert(reference, yzon);
851  delete yzon;
852  return;
853  } catch (std::exception) {
854 
855  }
856  }
857  this->parse();
858 }
859 
860 void YJSONObject::convert(YJSONObject* reference, YJSONArray* newArray)
861 {
862  int length = newArray->length();
863  for (int i = 0; i < length; i++) {
864  string key = reference->getKeyFromIdx(i);
865  YJSONContent* item = newArray->get(i);
866  YJSONContent* reference_item = reference->get(key);
867  YJSONType type = item->getJSONType();
868  if (type == reference_item->getJSONType()) {
869  switch (type) {
870  case ARRAY:
871  _parsed[key] = new YJSONArray((YJSONArray*)item);
872  break;
873  case NUMBER:
874  _parsed[key] = new YJSONNumber((YJSONNumber*)item);
875  break;
876  case STRING:
877  _parsed[key] = new YJSONString((YJSONString*)item);
878  break;
879  case OBJECT:
880  _parsed[key] = new YJSONObject((YJSONObject*)item);
881  break;
882  }
883  _keys.push_back(key);
884  } else if (type == ARRAY && reference_item->getJSONType() == OBJECT) {
885  YJSONObject* jobj = new YJSONObject(item->_data, item->_data_start, reference_item->_data_boundary);
886  jobj->convert((YJSONObject*) reference_item, (YJSONArray*) item);
887  _parsed[key] =jobj;
888  _keys.push_back(key);
889  } else {
890  throw YAPI_Exception(YAPI_IO_ERROR,"Unable to convert yzon struct");
891 
892  }
893  }
894 }
895 
897 {
898  return _keys[i];
899 }
900 
901 
903 //--- (generated code: YDataStream initialization)
904  _parent(NULL)
905  ,_runNo(0)
906  ,_utcStamp(0)
907  ,_nCols(0)
908  ,_nRows(0)
909  ,_duration(0)
910  ,_isClosed(0)
911  ,_isAvg(0)
912  ,_isScal(0)
913  ,_isScal32(0)
914  ,_decimals(0)
915  ,_offset(0.0)
916  ,_scale(0.0)
917  ,_samplesPerHour(0)
918  ,_minVal(0.0)
919  ,_avgVal(0.0)
920  ,_maxVal(0.0)
921  ,_decexp(0.0)
922  ,_caltyp(0)
923 //--- (end of generated code: YDataStream initialization)
924 {
925  _parent = parent;
926 }
927 
928 
929 
930 // YDataStream constructor for the new datalogger
931 YDataStream::YDataStream(YFunction *parent, YDataSet& dataset, const vector<int>& encoded):
932 //--- (generated code: YDataStream initialization)
933  _parent(NULL)
934  ,_runNo(0)
935  ,_utcStamp(0)
936  ,_nCols(0)
937  ,_nRows(0)
938  ,_duration(0)
939  ,_isClosed(0)
940  ,_isAvg(0)
941  ,_isScal(0)
942  ,_isScal32(0)
943  ,_decimals(0)
944  ,_offset(0.0)
945  ,_scale(0.0)
946  ,_samplesPerHour(0)
947  ,_minVal(0.0)
948  ,_avgVal(0.0)
949  ,_maxVal(0.0)
950  ,_decexp(0.0)
951  ,_caltyp(0)
952 //--- (end of generated code: YDataStream initialization)
953 {
954  _parent = parent;
955  this->_initFromDataSet(&dataset, encoded);
956 }
957 
958 
960 {
961  _columnNames.clear();
962  _calpar.clear();
963  _calraw.clear();
964  _calref.clear();
965  _values.clear();
966 }
967 
968 // YDataSet constructor, when instantiated directly by a function
969 YDataSet::YDataSet(YFunction *parent, const string& functionId, const string& unit, s64 startTime, s64 endTime):
970 //--- (generated code: YDataSet initialization)
971  _parent(NULL)
972  ,_startTime(0)
973  ,_endTime(0)
974  ,_progress(0)
975 //--- (end of generated code: YDataSet initialization)
976 {
977  _parent = parent;
978  _functionId = functionId;
979  _unit = unit;
980  _startTime = startTime;
981  _endTime = endTime;
982  _summary = YMeasure(0, 0, 0, 0, 0);
983  _progress = -1;
984 }
985 
986 // YDataSet constructor for the new datalogger
988 //--- (generated code: YDataSet initialization)
989  _parent(NULL)
990  ,_startTime(0)
991  ,_endTime(0)
992  ,_progress(0)
993 //--- (end of generated code: YDataSet initialization)
994 {
995  _parent = parent;
996  _startTime = 0;
997  _endTime = 0;
998  _summary = YMeasure(0, 0, 0, 0, 0);
999 }
1000 
1001 // YDataSet parser for stream list
1002 int YDataSet::_parse(const string& json)
1003 {
1005  double summaryMinVal=DBL_MAX;
1006  double summaryMaxVal=-DBL_MAX;
1007  double summaryTotalTime=0;
1008  double summaryTotalAvg=0;
1009 
1010 
1011  // Parse JSON data
1012  j.src = json.c_str();
1013  j.end = j.src + strlen(j.src);
1014  j.st = YJSON_START;
1015  if(yJsonParse(&j) != YJSON_PARSE_AVAIL || j.st != YJSON_PARSE_STRUCT) {
1016  return YAPI_NOT_SUPPORTED;
1017  }
1018  while(yJsonParse(&j) == YJSON_PARSE_AVAIL && j.st == YJSON_PARSE_MEMBNAME) {
1019  if (!strcmp(j.token, "id")) {
1020  if (yJsonParse(&j) != YJSON_PARSE_AVAIL) {
1021  return YAPI_NOT_SUPPORTED;
1022  }
1024  } else if (!strcmp(j.token, "unit")) {
1025  if (yJsonParse(&j) != YJSON_PARSE_AVAIL) {
1026  return YAPI_NOT_SUPPORTED;
1027  }
1028  _unit = _parent->_parseString(j);
1029  } else if (!strcmp(j.token, "calib")) {
1030  if (yJsonParse(&j) != YJSON_PARSE_AVAIL) {
1031  return YAPI_NOT_SUPPORTED;
1032  }
1034  _calib[0] = _calib[0] / 1000;
1035  } else if (!strcmp(j.token, "cal")) {
1036  if (yJsonParse(&j) != YJSON_PARSE_AVAIL) {
1037  return YAPI_NOT_SUPPORTED;
1038  }
1039  if(_calib.size() == 0) {
1041  }
1042  } else if (!strcmp(j.token, "streams")) {
1043  YDataStream *stream;
1044  s64 streamEndTime, endTime = 0;
1045  s64 streamStartTime, startTime = 0x7fffffff;
1046  _streams = vector<YDataStream*>();
1047  _preview = vector<YMeasure>();
1048  _measures = vector<YMeasure>();
1049  if (yJsonParse(&j) != YJSON_PARSE_AVAIL || j.token[0] != '[') {
1050  return YAPI_NOT_SUPPORTED;
1051  }
1052  // select streams for specified timeframe
1053  while(yJsonParse(&j) == YJSON_PARSE_AVAIL && j.token[0] != ']') {
1054  stream = _parent->_findDataStream(*this,_parent->_parseString(j));
1055  streamStartTime = stream->get_startTimeUTC() - stream->get_dataSamplesIntervalMs()/1000;
1056  streamEndTime = stream->get_startTimeUTC() + stream->get_duration();
1057  if(_startTime > 0 && streamEndTime <= _startTime) {
1058  // this stream is too early, drop it
1059  } else if(_endTime > 0 && stream->get_startTimeUTC() > _endTime) {
1060  // this stream is too late, drop it
1061  } else {
1062  _streams.push_back(stream);
1063  if(startTime > streamStartTime) {
1064  startTime = streamStartTime;
1065  }
1066  if(endTime < streamEndTime) {
1067  endTime = streamEndTime;
1068  }
1069  if(stream->isClosed() && stream->get_startTimeUTC() >= _startTime &&
1070  (_endTime == 0 || streamEndTime <= _endTime)) {
1071  if (summaryMinVal > stream->get_minValue())
1072  summaryMinVal =stream->get_minValue();
1073  if (summaryMaxVal < stream->get_maxValue())
1074  summaryMaxVal =stream->get_maxValue();
1075  summaryTotalAvg += stream->get_averageValue() * stream->get_duration();
1076  summaryTotalTime += stream->get_duration();
1077 
1078  YMeasure rec = YMeasure((double)stream->get_startTimeUTC(),
1079  (double)streamEndTime,
1080  stream->get_minValue(),
1081  stream->get_averageValue(),
1082  stream->get_maxValue());
1083  _preview.push_back(rec);
1084  }
1085  }
1086  }
1087  if((_streams.size() > 0) && (summaryTotalTime>0)) {
1088  // update time boundaries with actual data
1089  if(_startTime < startTime) {
1090  _startTime = startTime;
1091  }
1092  if(_endTime == 0 || _endTime > endTime) {
1093  _endTime = endTime;
1094  }
1095  _summary = YMeasure((double)_startTime,(double)_endTime,summaryMinVal,summaryTotalAvg/summaryTotalTime,summaryMaxVal);
1096  }
1097  } else {
1098  yJsonSkip(&j, 1);
1099  }
1100  }
1101  _progress = 0;
1102  return this->get_progress();
1103 }
1104 
1105 
1106 YFirmwareUpdate::YFirmwareUpdate(string serialNumber, string path, string settings) :
1107 //--- (generated code: YFirmwareUpdate initialization)
1108  _progress_c(0)
1109  ,_progress(0)
1110  ,_restore_step(0)
1111  ,_force(0)
1112 //--- (end of generated code: YFirmwareUpdate initialization)
1113 {
1114  _serial = serialNumber;
1115  _settings = settings;
1116  _firmwarepath = path;
1117 }
1118 YFirmwareUpdate::YFirmwareUpdate(string serialNumber, string path, string settings, bool force) :
1119 //--- (generated code: YFirmwareUpdate initialization)
1120  _progress_c(0)
1121  ,_progress(0)
1122  ,_restore_step(0)
1123  ,_force(0)
1124 //--- (end of generated code: YFirmwareUpdate initialization)
1125 {
1126  _serial = serialNumber;
1127  _settings = settings;
1128  _firmwarepath = path;
1129  _force = force;
1130 }
1131 
1133  //--- (generated code: YFirmwareUpdate initialization)
1134  _progress_c(0)
1135  ,_progress(0)
1136  ,_restore_step(0)
1137  ,_force(0)
1138 //--- (end of generated code: YFirmwareUpdate initialization)
1139 {}
1140 
1141 
1142 
1143 //--- (generated code: YFirmwareUpdate implementation)
1144 // static attributes
1145 
1146 
1148 {
1149  char errmsg[YOCTO_ERRMSG_LEN];
1150  YModule* m = NULL;
1151  int res = 0;
1152  string serial;
1153  string firmwarepath;
1154  string settings;
1155  string prod_prefix;
1156  int force = 0;
1157  if ((_progress_c < 100) && (_progress_c != YAPI_VERSION_MISMATCH)) {
1158  serial = _serial;
1159  firmwarepath = _firmwarepath;
1160  settings = _settings;
1161  if (_force) {
1162  force = 1;
1163  } else {
1164  force = 0;
1165  }
1166  res = yapiUpdateFirmwareEx(serial.c_str(), firmwarepath.c_str(), settings.c_str(), force, newupdate, errmsg);
1167  if ((res == YAPI_VERSION_MISMATCH) && ((int)(_settings).size() != 0)) {
1168  _progress_c = res;
1169  _progress_msg = string(errmsg);
1170  return _progress;
1171  }
1172  if (res < 0) {
1173  _progress = res;
1174  _progress_msg = string(errmsg);
1175  return res;
1176  }
1177  _progress_c = res;
1178  _progress = ((_progress_c * 9) / (10));
1179  _progress_msg = string(errmsg);
1180  } else {
1181  if (((int)(_settings).size() != 0)) {
1182  _progress_msg = "restoring settings";
1183  m = YModule::FindModule(_serial + ".module");
1184  if (!(m->isOnline())) {
1185  return _progress;
1186  }
1187  if (_progress < 95) {
1188  prod_prefix = (m->get_productName()).substr( 0, 8);
1189  if (prod_prefix == "YoctoHub") {
1190  {string ignore_error; YAPI::Sleep(1000, ignore_error);};
1191  _progress = _progress + 1;
1192  return _progress;
1193  } else {
1194  _progress = 95;
1195  }
1196  }
1197  if (_progress < 100) {
1199  m->saveToFlash();
1200  _settings = string(0, (char)0);
1203  _progress_msg = "Unable to update firmware";
1204  } else {
1205  _progress = 100;
1206  _progress_msg = "success";
1207  }
1208  }
1209  } else {
1210  _progress = 100;
1211  _progress_msg = "success";
1212  }
1213  }
1214  return _progress;
1215 }
1216 
1225 {
1226  char errmsg[YOCTO_ERRMSG_LEN];
1227  char smallbuff[1024];
1228  char *bigbuff;
1229  int buffsize = 0;
1230  int fullsize = 0;
1231  int yapi_res = 0;
1232  string bootloader_list;
1233  vector<string> bootladers;
1234  fullsize = 0;
1235  yapi_res = yapiGetBootloaders(smallbuff, 1024, &fullsize, errmsg);
1236  if (yapi_res < 0) {
1237  return bootladers;
1238  }
1239  if (fullsize <= 1024) {
1240  bootloader_list = string(smallbuff, yapi_res);
1241  } else {
1242  buffsize = fullsize;
1243  bigbuff = (char *)malloc(buffsize);
1244  yapi_res = yapiGetBootloaders(bigbuff, buffsize, &fullsize, errmsg);
1245  if (yapi_res < 0) {
1246  free(bigbuff);
1247  return bootladers;
1248  } else {
1249  bootloader_list = string(bigbuff, yapi_res);
1250  }
1251  free(bigbuff);
1252  }
1253  if (!(bootloader_list == "")) {
1254  bootladers = _strsplit(bootloader_list,',');
1255  }
1256  return bootladers;
1257 }
1258 
1272 string YFirmwareUpdate::CheckFirmware(string serial,string path,int minrelease)
1273 {
1274  char errmsg[YOCTO_ERRMSG_LEN];
1275  char smallbuff[1024];
1276  char *bigbuff;
1277  int buffsize = 0;
1278  int fullsize = 0;
1279  int res = 0;
1280  string firmware_path;
1281  string release;
1282  fullsize = 0;
1283  release = YapiWrapper::ysprintf("%d",minrelease);
1284  res = yapiCheckFirmware(serial.c_str(), release.c_str(), path.c_str(), smallbuff, 1024, &fullsize, errmsg);
1285  if (res < 0) {
1286  firmware_path = "error:" + string(errmsg);
1287  return "error:" + string(errmsg);
1288  }
1289  if (fullsize <= 1024) {
1290  firmware_path = string(smallbuff, fullsize);
1291  } else {
1292  buffsize = fullsize;
1293  bigbuff = (char *)malloc(buffsize);
1294  res = yapiCheckFirmware(serial.c_str(), release.c_str(), path.c_str(), bigbuff, buffsize, &fullsize, errmsg);
1295  if (res < 0) {
1296  firmware_path = "error:" + string(errmsg);
1297  } else {
1298  firmware_path = string(bigbuff, fullsize);
1299  }
1300  free(bigbuff);
1301  }
1302  return firmware_path;
1303 }
1304 
1316 {
1317  if (_progress >= 0) {
1318  this->_processMore(0);
1319  }
1320  return _progress;
1321 }
1322 
1330 {
1331  return _progress_msg;
1332 }
1333 
1345 {
1346  string err;
1347  int leng = 0;
1348  err = _settings;
1349  leng = (int)(err).length();
1350  if (( leng >= 6) && ("error:" == (err).substr(0, 6))) {
1351  _progress = -1;
1352  _progress_msg = (err).substr( 6, leng - 6);
1353  } else {
1354  _progress = 0;
1355  _progress_c = 0;
1356  this->_processMore(1);
1357  }
1358  return _progress;
1359 }
1360 //--- (end of generated code: YFirmwareUpdate implementation)
1361 
1362 
1363 //--- (generated code: YDataStream implementation)
1364 // static attributes
1365 
1366 
1367 int YDataStream::_initFromDataSet(YDataSet* dataset,vector<int> encoded)
1368 {
1369  int val = 0;
1370  int i = 0;
1371  int maxpos = 0;
1372  int iRaw = 0;
1373  int iRef = 0;
1374  double fRaw = 0.0;
1375  double fRef = 0.0;
1376  double duration_float = 0.0;
1377  vector<int> iCalib;
1378  // decode sequence header to extract data
1379  _runNo = encoded[0] + (((encoded[1]) << (16)));
1380  _utcStamp = encoded[2] + (((encoded[3]) << (16)));
1381  val = encoded[4];
1382  _isAvg = (((val) & (0x100)) == 0);
1383  _samplesPerHour = ((val) & (0xff));
1384  if (((val) & (0x100)) != 0) {
1385  _samplesPerHour = _samplesPerHour * 3600;
1386  } else {
1387  if (((val) & (0x200)) != 0) {
1388  _samplesPerHour = _samplesPerHour * 60;
1389  }
1390  }
1391  val = encoded[5];
1392  if (val > 32767) {
1393  val = val - 65536;
1394  }
1395  _decimals = val;
1396  _offset = val;
1397  _scale = encoded[6];
1398  _isScal = (_scale != 0);
1399  _isScal32 = ((int)encoded.size() >= 14);
1400  val = encoded[7];
1401  _isClosed = (val != 0xffff);
1402  if (val == 0xffff) {
1403  val = 0;
1404  }
1405  _nRows = val;
1406  duration_float = _nRows * 3600 / _samplesPerHour;
1407  _duration = (int) floor(duration_float+0.5);
1408  // precompute decoding parameters
1409  _decexp = 1.0;
1410  if (_scale == 0) {
1411  i = 0;
1412  while (i < _decimals) {
1413  _decexp = _decexp * 10.0;
1414  i = i + 1;
1415  }
1416  }
1417  iCalib = dataset->_get_calibration();
1418  _caltyp = iCalib[0];
1419  if (_caltyp != 0) {
1420  _calhdl = YAPI::_getCalibrationHandler(_caltyp);
1421  maxpos = (int)iCalib.size();
1422  _calpar.clear();
1423  _calraw.clear();
1424  _calref.clear();
1425  if (_isScal32) {
1426  i = 1;
1427  while (i < maxpos) {
1428  _calpar.push_back(iCalib[i]);
1429  i = i + 1;
1430  }
1431  i = 1;
1432  while (i + 1 < maxpos) {
1433  fRaw = iCalib[i];
1434  fRaw = fRaw / 1000.0;
1435  fRef = iCalib[i + 1];
1436  fRef = fRef / 1000.0;
1437  _calraw.push_back(fRaw);
1438  _calref.push_back(fRef);
1439  i = i + 2;
1440  }
1441  } else {
1442  i = 1;
1443  while (i + 1 < maxpos) {
1444  iRaw = iCalib[i];
1445  iRef = iCalib[i + 1];
1446  _calpar.push_back(iRaw);
1447  _calpar.push_back(iRef);
1448  if (_isScal) {
1449  fRaw = iRaw;
1450  fRaw = (fRaw - _offset) / _scale;
1451  fRef = iRef;
1452  fRef = (fRef - _offset) / _scale;
1453  _calraw.push_back(fRaw);
1454  _calref.push_back(fRef);
1455  } else {
1456  _calraw.push_back(YAPI::_decimalToDouble(iRaw));
1457  _calref.push_back(YAPI::_decimalToDouble(iRef));
1458  }
1459  i = i + 2;
1460  }
1461  }
1462  }
1463  // preload column names for backward-compatibility
1464  _functionId = dataset->get_functionId();
1465  if (_isAvg) {
1466  _columnNames.clear();
1467  _columnNames.push_back(YapiWrapper::ysprintf("%s_min",_functionId.c_str()));
1468  _columnNames.push_back(YapiWrapper::ysprintf("%s_avg",_functionId.c_str()));
1469  _columnNames.push_back(YapiWrapper::ysprintf("%s_max",_functionId.c_str()));
1470  _nCols = 3;
1471  } else {
1472  _columnNames.clear();
1473  _columnNames.push_back(_functionId);
1474  _nCols = 1;
1475  }
1476  // decode min/avg/max values for the sequence
1477  if (_nRows > 0) {
1478  if (_isScal32) {
1479  _avgVal = this->_decodeAvg(encoded[8] + (((((encoded[9]) ^ (0x8000))) << (16))), 1);
1480  _minVal = this->_decodeVal(encoded[10] + (((encoded[11]) << (16))));
1481  _maxVal = this->_decodeVal(encoded[12] + (((encoded[13]) << (16))));
1482  } else {
1483  _minVal = this->_decodeVal(encoded[8]);
1484  _maxVal = this->_decodeVal(encoded[9]);
1485  _avgVal = this->_decodeAvg(encoded[10] + (((encoded[11]) << (16))), _nRows);
1486  }
1487  }
1488  return 0;
1489 }
1490 
1491 int YDataStream::_parseStream(string sdata)
1492 {
1493  int idx = 0;
1494  vector<int> udat;
1495  vector<double> dat;
1496  if ((int)(sdata).size() == 0) {
1497  _nRows = 0;
1498  return YAPI_SUCCESS;
1499  }
1500 
1501  udat = YAPI::_decodeWords(_parent->_json_get_string(sdata));
1502  _values.clear();
1503  idx = 0;
1504  if (_isAvg) {
1505  while (idx + 3 < (int)udat.size()) {
1506  dat.clear();
1507  if (_isScal32) {
1508  dat.push_back(this->_decodeVal(udat[idx + 2] + (((udat[idx + 3]) << (16)))));
1509  dat.push_back(this->_decodeAvg(udat[idx] + (((((udat[idx + 1]) ^ (0x8000))) << (16))), 1));
1510  dat.push_back(this->_decodeVal(udat[idx + 4] + (((udat[idx + 5]) << (16)))));
1511  idx = idx + 6;
1512  } else {
1513  dat.push_back(this->_decodeVal(udat[idx]));
1514  dat.push_back(this->_decodeAvg(udat[idx + 2] + (((udat[idx + 3]) << (16))), 1));
1515  dat.push_back(this->_decodeVal(udat[idx + 1]));
1516  idx = idx + 4;
1517  }
1518  _values.push_back(dat);
1519  }
1520  } else {
1521  if (_isScal && !(_isScal32)) {
1522  while (idx < (int)udat.size()) {
1523  dat.clear();
1524  dat.push_back(this->_decodeVal(udat[idx]));
1525  _values.push_back(dat);
1526  idx = idx + 1;
1527  }
1528  } else {
1529  while (idx + 1 < (int)udat.size()) {
1530  dat.clear();
1531  dat.push_back(this->_decodeAvg(udat[idx] + (((((udat[idx + 1]) ^ (0x8000))) << (16))), 1));
1532  _values.push_back(dat);
1533  idx = idx + 2;
1534  }
1535  }
1536  }
1537 
1538  _nRows = (int)_values.size();
1539  return YAPI_SUCCESS;
1540 }
1541 
1543 {
1544  string url;
1545  url = YapiWrapper::ysprintf("logger.json?id=%s&run=%d&utc=%u",
1546  _functionId.c_str(),_runNo,_utcStamp);
1547  return url;
1548 }
1549 
1551 {
1552  return this->_parseStream(_parent->_download(this->_get_url()));
1553 }
1554 
1556 {
1557  double val = 0.0;
1558  val = w;
1559  if (_isScal32) {
1560  val = val / 1000.0;
1561  } else {
1562  if (_isScal) {
1563  val = (val - _offset) / _scale;
1564  } else {
1565  val = YAPI::_decimalToDouble(w);
1566  }
1567  }
1568  if (_caltyp != 0) {
1569  if (_calhdl != NULL) {
1570  val = _calhdl(val, _caltyp, _calpar, _calraw, _calref);
1571  }
1572  }
1573  return val;
1574 }
1575 
1576 double YDataStream::_decodeAvg(int dw,int count)
1577 {
1578  double val = 0.0;
1579  val = dw;
1580  if (_isScal32) {
1581  val = val / 1000.0;
1582  } else {
1583  if (_isScal) {
1584  val = (val / (100 * count) - _offset) / _scale;
1585  } else {
1586  val = val / (count * _decexp);
1587  }
1588  }
1589  if (_caltyp != 0) {
1590  if (_calhdl != NULL) {
1591  val = _calhdl(val, _caltyp, _calpar, _calraw, _calref);
1592  }
1593  }
1594  return val;
1595 }
1596 
1598 {
1599  return _isClosed;
1600 }
1601 
1609 {
1610  return _runNo;
1611 }
1612 
1627 {
1628  return (int)(_utcStamp - ((unsigned)time(NULL)));
1629 }
1630 
1641 {
1642  return _utcStamp;
1643 }
1644 
1654 {
1655  return ((3600000) / (_samplesPerHour));
1656 }
1657 
1659 {
1660  return 3600.0 / _samplesPerHour;
1661 }
1662 
1675 {
1676  if ((_nRows != 0) && _isClosed) {
1677  return _nRows;
1678  }
1679  this->loadStream();
1680  return _nRows;
1681 }
1682 
1697 {
1698  if (_nCols != 0) {
1699  return _nCols;
1700  }
1701  this->loadStream();
1702  return _nCols;
1703 }
1704 
1722 vector<string> YDataStream::get_columnNames(void)
1723 {
1724  if ((int)_columnNames.size() != 0) {
1725  return _columnNames;
1726  }
1727  this->loadStream();
1728  return _columnNames;
1729 }
1730 
1742 {
1743  return _minVal;
1744 }
1745 
1757 {
1758  return _avgVal;
1759 }
1760 
1772 {
1773  return _maxVal;
1774 }
1775 
1784 {
1785  if (_isClosed) {
1786  return _duration;
1787  }
1788  return (int)(((unsigned)time(NULL)) - _utcStamp);
1789 }
1790 
1806 vector< vector<double> > YDataStream::get_dataRows(void)
1807 {
1808  if (((int)_values.size() == 0) || !(_isClosed)) {
1809  this->loadStream();
1810  }
1811  return _values;
1812 }
1813 
1830 double YDataStream::get_data(int row,int col)
1831 {
1832  if (((int)_values.size() == 0) || !(_isClosed)) {
1833  this->loadStream();
1834  }
1835  if (row >= (int)_values.size()) {
1836  return Y_DATA_INVALID;
1837  }
1838  if (col >= (int)_values[row].size()) {
1839  return Y_DATA_INVALID;
1840  }
1841  return _values[row][col];
1842 }
1843 //--- (end of generated code: YDataStream implementation)
1844 
1845 YMeasure::YMeasure(double start, double end, double minVal, double avgVal, double maxVal):
1846 //--- (generated code: YMeasure initialization)
1847  _start(0.0)
1848  ,_end(0.0)
1849  ,_minVal(0.0)
1850  ,_avgVal(0.0)
1851  ,_maxVal(0.0)
1852 //--- (end of generated code: YMeasure initialization)
1853 {
1854  _start = start;
1855  _end = end;
1856  _minVal = minVal;
1857  _avgVal = avgVal;
1858  _maxVal = maxVal;
1859  _startTime_t = (time_t)(start+0.5);
1860  _stopTime_t = (time_t)(end+0.5);
1861 
1862 }
1863 
1865 //--- (generated code: YMeasure initialization)
1866  _start(0.0)
1867  ,_end(0.0)
1868  ,_minVal(0.0)
1869  ,_avgVal(0.0)
1870  ,_maxVal(0.0)
1871 //--- (end of generated code: YMeasure initialization)
1872 {
1873  _start = 0;
1874  _end = 0;
1875  _minVal = 0;
1876  _avgVal = 0;
1877  _maxVal = 0;
1878  _startTime_t = 0;
1879  _stopTime_t = 0;
1880 }
1881 
1882 //--- (generated code: YMeasure implementation)
1883 // static attributes
1884 
1885 
1895 {
1896  return _start;
1897 }
1898 
1908 {
1909  return _end;
1910 }
1911 
1919 {
1920  return _minVal;
1921 }
1922 
1930 {
1931  return _avgVal;
1932 }
1933 
1941 {
1942  return _maxVal;
1943 }
1944 //--- (end of generated code: YMeasure implementation)
1945 
1947 {
1948  if(time){
1949  memcpy(time,&this->_stopTime_t,sizeof(time_t));
1950  }
1951  return &this->_startTime_t;
1952 
1953 }
1955 {
1956  if(time){
1957  memcpy(time,&this->_stopTime_t,sizeof(time_t));
1958  }
1959  return &this->_stopTime_t;
1960 }
1961 
1962 //--- (generated code: YDataSet implementation)
1963 // static attributes
1964 
1965 
1967 {
1968  return _calib;
1969 }
1970 
1971 int YDataSet::processMore(int progress,string data)
1972 {
1973  YDataStream* stream = NULL;
1974  vector< vector<double> > dataRows;
1975  string strdata;
1976  double tim = 0.0;
1977  double itv = 0.0;
1978  int nCols = 0;
1979  int minCol = 0;
1980  int avgCol = 0;
1981  int maxCol = 0;
1982 
1983  if (progress != _progress) {
1984  return _progress;
1985  }
1986  if (_progress < 0) {
1987  strdata = data;
1988  if (strdata == "{}") {
1989  _parent->_throw(YAPI_VERSION_MISMATCH, "device firmware is too old");
1990  return YAPI_VERSION_MISMATCH;
1991  }
1992  return this->_parse(strdata);
1993  }
1994  stream = _streams[_progress];
1995  stream->_parseStream(data);
1996  dataRows = stream->get_dataRows();
1997  _progress = _progress + 1;
1998  if ((int)dataRows.size() == 0) {
1999  return this->get_progress();
2000  }
2001  tim = (double) stream->get_startTimeUTC();
2002  itv = stream->get_dataSamplesInterval();
2003  if (tim < itv) {
2004  tim = itv;
2005  }
2006  nCols = (int)dataRows[0].size();
2007  minCol = 0;
2008  if (nCols > 2) {
2009  avgCol = 1;
2010  } else {
2011  avgCol = 0;
2012  }
2013  if (nCols > 2) {
2014  maxCol = 2;
2015  } else {
2016  maxCol = 0;
2017  }
2018 
2019  for (unsigned ii = 0; ii < dataRows.size(); ii++) {
2020  if ((tim >= _startTime) && ((_endTime == 0) || (tim <= _endTime))) {
2021  _measures.push_back(YMeasure(tim - itv, tim,
2022  dataRows[ii][minCol],
2023  dataRows[ii][avgCol],dataRows[ii][maxCol]));
2024  }
2025  tim = tim + itv;
2026  tim = floor(tim * 1000+0.5) / 1000.0;
2027  }
2028  return this->get_progress();
2029 }
2030 
2031 vector<YDataStream*> YDataSet::get_privateDataStreams(void)
2032 {
2033  return _streams;
2034 }
2035 
2047 {
2048  YModule* mo = NULL;
2049  if (!(_hardwareId == "")) {
2050  return _hardwareId;
2051  }
2052  mo = _parent->get_module();
2053  _hardwareId = YapiWrapper::ysprintf("%s.%s", mo->get_serialNumber().c_str(),this->get_functionId().c_str());
2054  return _hardwareId;
2055 }
2056 
2064 {
2065  return _functionId;
2066 }
2067 
2076 {
2077  return _unit;
2078 }
2079 
2093 {
2094  return _startTime;
2095 }
2096 
2110 {
2111  return _endTime;
2112 }
2113 
2123 {
2124  if (_progress < 0) {
2125  return 0;
2126  }
2127  // index not yet loaded
2128  if (_progress >= (int)_streams.size()) {
2129  return 100;
2130  }
2131  return ((1 + (1 + _progress) * 98) / ((1 + (int)_streams.size())));
2132 }
2133 
2144 {
2145  string url;
2146  YDataStream* stream = NULL;
2147  if (_progress < 0) {
2148  url = YapiWrapper::ysprintf("logger.json?id=%s",_functionId.c_str());
2149  if (_startTime != 0) {
2150  url = YapiWrapper::ysprintf("%s&from=%u",url.c_str(),_startTime);
2151  }
2152  if (_endTime != 0) {
2153  url = YapiWrapper::ysprintf("%s&to=%u",url.c_str(),_endTime);
2154  }
2155  } else {
2156  if (_progress >= (int)_streams.size()) {
2157  return 100;
2158  } else {
2159  stream = _streams[_progress];
2160  url = stream->_get_url();
2161  }
2162  }
2163  return this->processMore(_progress, _parent->_download(url));
2164 }
2165 
2181 {
2182  return _summary;
2183 }
2184 
2203 vector<YMeasure> YDataSet::get_preview(void)
2204 {
2205  return _preview;
2206 }
2207 
2221 vector<YMeasure> YDataSet::get_measuresAt(YMeasure measure)
2222 {
2223  s64 startUtc = 0;
2224  YDataStream* stream = NULL;
2225  vector< vector<double> > dataRows;
2226  vector<YMeasure> measures;
2227  double tim = 0.0;
2228  double itv = 0.0;
2229  int nCols = 0;
2230  int minCol = 0;
2231  int avgCol = 0;
2232  int maxCol = 0;
2233 
2234  startUtc = (s64) floor(measure.get_startTimeUTC()+0.5);
2235  stream = NULL;
2236  for (unsigned ii = 0; ii < _streams.size(); ii++) {
2237  if (_streams[ii]->get_startTimeUTC() == startUtc) {
2238  stream = _streams[ii];
2239  }
2240  }
2241  if (stream == NULL) {
2242  return measures;
2243  }
2244  dataRows = stream->get_dataRows();
2245  if ((int)dataRows.size() == 0) {
2246  return measures;
2247  }
2248  tim = (double) stream->get_startTimeUTC();
2249  itv = stream->get_dataSamplesInterval();
2250  if (tim < itv) {
2251  tim = itv;
2252  }
2253  nCols = (int)dataRows[0].size();
2254  minCol = 0;
2255  if (nCols > 2) {
2256  avgCol = 1;
2257  } else {
2258  avgCol = 0;
2259  }
2260  if (nCols > 2) {
2261  maxCol = 2;
2262  } else {
2263  maxCol = 0;
2264  }
2265 
2266  for (unsigned ii = 0; ii < dataRows.size(); ii++) {
2267  if ((tim >= _startTime) && ((_endTime == 0) || (tim <= _endTime))) {
2268  measures.push_back(YMeasure(tim - itv, tim,
2269  dataRows[ii][minCol],
2270  dataRows[ii][avgCol],dataRows[ii][maxCol]));
2271  }
2272  tim = tim + itv;
2273  }
2274  return measures;
2275 }
2276 
2302 vector<YMeasure> YDataSet::get_measures(void)
2303 {
2304  return _measures;
2305 }
2306 //--- (end of generated code: YDataSet implementation)
2307 
2308 
2309 std::map<string,YFunction*> YFunction::_cache;
2310 
2311 
2312 // Constructor is protected. Use the device-specific factory function to instantiate
2313 YFunction::YFunction(const string& func):
2314  _className("Function"),_func(func),
2315  _lastErrorType(YAPI_SUCCESS),_lastErrorMsg(""),
2316  _fundescr(Y_FUNCTIONDESCRIPTOR_INVALID), _userData(NULL)
2317 
2318 //--- (generated code: YFunction initialization)
2319  ,_logicalName(LOGICALNAME_INVALID)
2320  ,_advertisedValue(ADVERTISEDVALUE_INVALID)
2321  ,_valueCallbackFunction(NULL)
2322  ,_cacheExpiration(0)
2323 //--- (end of generated code: YFunction initialization)
2324 {
2326 }
2327 
2329 {
2330 //--- (generated code: YFunction cleanup)
2331 //--- (end of generated code: YFunction cleanup)
2334 }
2335 
2336 
2337 // function cache methods
2338 YFunction* YFunction::_FindFromCache(const string& classname, const string& func)
2339 {
2340  if(_cache.find(classname + "_" + func) != _cache.end())
2341  return _cache[classname + "_" + func];
2342  return NULL;
2343 }
2344 
2345 void YFunction::_AddToCache(const string& classname, const string& func, YFunction *obj)
2346 {
2347  _cache[classname + "_" + func] = obj;
2348 }
2349 
2351 {
2352  for (std::map<string, YFunction*>::iterator cache_iterator = _cache.begin();
2353  cache_iterator != _cache.end(); ++cache_iterator){
2354  delete cache_iterator->second;
2355  }
2356  _cache.clear();
2357  _cache = std::map<string, YFunction*>();
2358 }
2359 
2360 
2361 
2362 //--- (generated code: YFunction implementation)
2363 // static attributes
2366 
2368 {
2369  if(json_val->has("logicalName")) {
2370  _logicalName = json_val->getString("logicalName");
2371  }
2372  if(json_val->has("advertisedValue")) {
2373  _advertisedValue = json_val->getString("advertisedValue");
2374  }
2375  return 0;
2376 }
2377 
2378 
2387 {
2388  string res;
2390  try {
2393  {
2396  }
2397  }
2398  }
2399  res = _logicalName;
2400  } catch (std::exception) {
2402  throw;
2403  }
2405  return res;
2406 }
2407 
2420 int YFunction::set_logicalName(const string& newval)
2421 {
2422  string rest_val;
2423  int res;
2424  if (!YAPI::CheckLogicalName(newval)) {
2425  _throw(YAPI_INVALID_ARGUMENT, "Invalid name :" + newval);
2426  return YAPI_INVALID_ARGUMENT;
2427  }
2429  try {
2430  rest_val = newval;
2431  res = _setAttr("logicalName", rest_val);
2432  } catch (std::exception) {
2434  throw;
2435  }
2437  return res;
2438 }
2439 
2448 {
2449  string res;
2451  try {
2454  {
2457  }
2458  }
2459  }
2460  res = _advertisedValue;
2461  } catch (std::exception) {
2463  throw;
2464  }
2466  return res;
2467 }
2468 
2469 int YFunction::set_advertisedValue(const string& newval)
2470 {
2471  string rest_val;
2472  int res;
2474  try {
2475  rest_val = newval;
2476  res = _setAttr("advertisedValue", rest_val);
2477  } catch (std::exception) {
2479  throw;
2480  }
2482  return res;
2483 }
2484 
2513 {
2514  YFunction* obj = NULL;
2515  int taken = 0;
2516  if (YAPI::_apiInitialized) {
2518  taken = 1;
2519  }try {
2520  obj = (YFunction*) YFunction::_FindFromCache("Function", func);
2521  if (obj == NULL) {
2522  obj = new YFunction(func);
2523  YFunction::_AddToCache("Function", func, obj);
2524  }
2525  } catch (std::exception) {
2527  throw;
2528  }
2530  return obj;
2531 }
2532 
2545 {
2546  string val;
2547  if (callback != NULL) {
2549  } else {
2551  }
2552  _valueCallbackFunction = callback;
2553  // Immediately invoke value callback with current value
2554  if (callback != NULL && this->isOnline()) {
2555  val = _advertisedValue;
2556  if (!(val == "")) {
2557  this->_invokeValueCallback(val);
2558  }
2559  }
2560  return 0;
2561 }
2562 
2564 {
2565  if (_valueCallbackFunction != NULL) {
2566  _valueCallbackFunction(this, value);
2567  } else {
2568  }
2569  return 0;
2570 }
2571 
2584 {
2585  return this->set_advertisedValue("SILENT");
2586 }
2587 
2599 {
2600  return this->set_advertisedValue("");
2601 }
2602 
2613 string YFunction::loadAttribute(string attrName)
2614 {
2615  string url;
2616  string attrVal;
2617  url = YapiWrapper::ysprintf("api/%s/%s", this->get_functionId().c_str(),attrName.c_str());
2618  attrVal = this->_download(url);
2619  return attrVal;
2620 }
2621 
2623 {
2624  return 0;
2625 }
2626 
2628 {
2629  string hwid;
2630 
2631  if(YISERR(_nextFunction(hwid)) || hwid=="") {
2632  return NULL;
2633  }
2634  return YFunction::FindFunction(hwid);
2635 }
2636 
2638 {
2639  vector<YFUN_DESCR> v_fundescr;
2640  YDEV_DESCR ydevice;
2641  string serial, funcId, funcName, funcVal, errmsg;
2642 
2643  if(YISERR(YapiWrapper::getFunctionsByClass("Function", 0, v_fundescr, sizeof(YFUN_DESCR), errmsg)) ||
2644  v_fundescr.size() == 0 ||
2645  YISERR(YapiWrapper::getFunctionInfo(v_fundescr[0], ydevice, serial, funcId, funcName, funcVal, errmsg))) {
2646  return NULL;
2647  }
2648  return YFunction::FindFunction(serial+"."+funcId);
2649 }
2650 
2651 //--- (end of generated code: YFunction implementation)
2652 
2653 //--- (generated code: YFunction functions)
2654 //--- (end of generated code: YFunction functions)
2655 
2656 void YFunction::_throw(YRETCODE errType, string errMsg)
2657 {
2659  _lastErrorMsg = errMsg;
2660  // Method used to throw exceptions or save error type/message
2662  throw YAPI_Exception(errType, errMsg);
2663  }
2664 }
2665 
2666 // Method used to resolve our name to our unique function descriptor (may trigger a hub scan)
2668 {
2669  int res;
2670  YFUN_DESCR tmp_fundescr;
2671 
2672  tmp_fundescr = YapiWrapper::getFunction(_className, _func, errmsg);
2673  if(YISERR(tmp_fundescr)) {
2674  res = YapiWrapper::updateDeviceList(true,errmsg);
2675  if(YISERR(res)) {
2676  return (YRETCODE)res;
2677  }
2678  tmp_fundescr = YapiWrapper::getFunction(_className, _func, errmsg);
2679  if(YISERR(tmp_fundescr)) {
2680  return (YRETCODE)tmp_fundescr;
2681  }
2682  }
2683  _fundescr = fundescr = tmp_fundescr;
2684  return YAPI_SUCCESS;
2685 }
2686 
2687 // Return a pointer to our device caching object (may trigger a hub scan)
2689 {
2690  YFUN_DESCR fundescr;
2691  YDEV_DESCR devdescr;
2692  YRETCODE res;
2693 
2694  // Resolve function name
2695  res = _getDescriptor(fundescr, errmsg);
2696  if(YISERR(res)) return res;
2697 
2698  // Get device descriptor
2699  devdescr = YapiWrapper::getDeviceByFunction(fundescr, errmsg);
2700  if(YISERR(devdescr)) return (YRETCODE)devdescr;
2701 
2702  // Get device object
2703  dev = YDevice::getDevice(devdescr);
2704 
2705  return YAPI_SUCCESS;
2706 }
2707 
2708 // Return the next known function of current class listed in the yellow pages
2710 {
2711  vector<YFUN_DESCR> v_fundescr;
2712  YFUN_DESCR fundescr;
2713  YDEV_DESCR devdescr;
2714  string serial, funcId, funcName, funcVal, errmsg;
2715  int res;
2716 
2717  res = _getDescriptor(fundescr, errmsg);
2718  if(YISERR(res)) {
2719  _throw((YRETCODE)res, errmsg);
2720  return (YRETCODE)res;
2721  }
2722  res = YapiWrapper::getFunctionsByClass(_className, fundescr, v_fundescr, sizeof(YFUN_DESCR), errmsg);
2723  if(YISERR((YRETCODE)res)) {
2724  _throw((YRETCODE)res, errmsg);
2725  return (YRETCODE)res;
2726  }
2727  if(v_fundescr.size() == 0) {
2728  hwid = "";
2729  return YAPI_SUCCESS;
2730  }
2731  res = YapiWrapper::getFunctionInfo(v_fundescr[0], devdescr, serial, funcId, funcName, funcVal, errmsg);
2732  if(YISERR(res)) {
2733  _throw((YRETCODE)res, errmsg);
2734  return (YRETCODE)res;
2735  }
2736  hwid = serial+"."+funcId;
2737 
2738  return YAPI_SUCCESS;
2739 }
2740 
2741 // Parse a long JSON string
2743 {
2744  string res;
2745 
2746  do {
2747 #ifdef WINDOWS_API
2748  res += j.token;
2749 #else
2750  char buffer[128];
2751  char *pt, *s;
2752  s = j.token;
2753  pt = buffer;
2754  while (*s) {
2755  unsigned char c = *s++;
2756  if (c < 128) {
2757  *pt++ = c;
2758  } else {
2759  // UTF8-encode character
2760  *pt++ = 0xc2 + (c>0xbf ? 1 : 0);
2761  *pt++ = (c & 0x3f) + 0x80;
2762  }
2763  }
2764  *pt = 0;
2765  res += buffer;
2766 #endif
2767  } while (j.next == YJSON_PARSE_STRINGCONT && yJsonParse(&j) == YJSON_PARSE_AVAIL);
2768 
2769  return res;
2770 }
2771 
2772 string YFunction::_json_get_key(const string& json, const string& key)
2773 {
2775 
2776  // Parse JSON data for the device and locate our function in it
2777  j.src = json.c_str();
2778  j.end = j.src + strlen(j.src);
2779  j.st = YJSON_START;
2780  if(yJsonParse(&j) != YJSON_PARSE_AVAIL || j.st != YJSON_PARSE_STRUCT) {
2781  this->_throw(YAPI_IO_ERROR,"JSON structure expected");
2782  return YAPI_INVALID_STRING;
2783  }
2784  while(yJsonParse(&j) == YJSON_PARSE_AVAIL && j.st == YJSON_PARSE_MEMBNAME) {
2785  if (!strcmp(j.token, key.c_str())) {
2786  if (yJsonParse(&j) != YJSON_PARSE_AVAIL) {
2787  this->_throw(YAPI_IO_ERROR,"JSON structure expected");
2788  return YAPI_INVALID_STRING;
2789  }
2790  return _parseString(j);
2791  }
2792  yJsonSkip(&j, 1);
2793  }
2794  this->_throw(YAPI_IO_ERROR,"invalid JSON structure");
2795  return YAPI_INVALID_STRING;
2796 }
2797 
2798 string YFunction::_json_get_string(const string& json)
2799 {
2801  j.src = json.c_str();
2802  j.end = j.src + strlen(j.src);
2803  j.st = YJSON_START;
2804  if(yJsonParse(&j) != YJSON_PARSE_AVAIL || j.st != YJSON_PARSE_STRING) {
2805  this->_throw(YAPI_IO_ERROR,"JSON string expected");
2806  return "";
2807  }
2808  return _parseString(j);
2809 }
2810 
2811 vector<string> YFunction::_json_get_array(const string& json)
2812 {
2813  vector<string> res;
2815  const char *json_cstr,*last;
2816  string backup = json;
2817  j.src = json_cstr = json.c_str();
2818  j.end = j.src + strlen(j.src);
2819  j.st = YJSON_START;
2820  if(yJsonParse(&j) != YJSON_PARSE_AVAIL || j.st != YJSON_PARSE_ARRAY) {
2821  this->_throw(YAPI_IO_ERROR,"JSON structure expected");
2822  return res;
2823  }
2824  int depth = j.depth;
2825  do {
2826  last = j.src;
2827  while (yJsonParse(&j) == YJSON_PARSE_AVAIL) {
2828  if (j.next == YJSON_PARSE_STRINGCONT || j.depth > depth){
2829  continue;
2830  }
2831  break;
2832  }
2833  if (j.st == YJSON_PARSE_ERROR) {
2834  this->_throw(YAPI_IO_ERROR, "invalid JSON structure");
2835  return res;
2836  }
2837 
2838  if (j.depth == depth) {
2839  long location, length;
2840  while (*last == ',' || *last == '\n'){
2841  last++;
2842  }
2843  location = (long)(last - json_cstr);
2844  length = (long)(j.src - last);
2845  string item = json.substr(location, length);
2846  res.push_back(item);
2847  }
2848  } while (j.st != YJSON_PARSE_ARRAY );
2849  return res;
2850 }
2851 
2852 string YFunction::_get_json_path(const string& json, const string& path)
2853 {
2854  const char *json_data = json.c_str();
2855  int len = (int)(json.length() & 0x0fffffff);
2856  const char *p;
2857  char errbuff[YOCTO_ERRMSG_LEN];
2858  int res;
2859 
2860  res = yapiJsonGetPath(path.c_str(), json_data, len, &p, errbuff);
2861  if (res >= 0) {
2862  string result = string(p, res);
2863  if (res > 0) {
2864  yapiFreeMem((void*)p);
2865  }
2866  return result;
2867  }
2868  return "";
2869 }
2870 
2871 string YFunction::_decode_json_string(const string& json)
2872 {
2873  int len = (int)(json.length() & 0x0fffffff);
2874  char buffer[128];
2875  char *p = buffer;
2876  int decoded_len;
2877 
2878  if (len >= 127){
2879  p = (char*) malloc(len + 1);
2880 
2881  }
2882  decoded_len = yapiJsonDecodeString(json.c_str(), p);
2883  string result = string(p, decoded_len);
2884  if (len >= 127){
2885  free(p);
2886  }
2887  return result;
2888 }
2889 
2890 
2891 string YFunction::_escapeAttr(const string& changeval)
2892 {
2893  const char *p;
2894  unsigned char c;
2895  unsigned char esc[3];
2896  string escaped = "";
2897  esc[0] = '%';
2898  for (p = changeval.c_str(); (c = *p) != 0; p++) {
2899  if (c <= ' ' || (c > 'z' && c != '~') || c == '"' || c == '%' || c == '&' ||
2900  c == '+' || c == '<' || c == '=' || c == '>' || c == '\\' || c == '^' || c == '`') {
2901  if ((c==0xc2 || c==0xc3) && (p[1] & 0xc0)==0x80) {
2902  // UTF8-encoded ISO-8859-1 character: translate to plain ISO-8859-1
2903  c = (c & 1) * 0x40;
2904  p++;
2905  c += *p;
2906  }
2907  esc[1] = (c >= 0xa0 ? (c >> 4) - 10 + 'A' : (c >> 4) + '0');
2908  c &= 0xf;
2909  esc[2] = (c >= 0xa ? c - 10 + 'A' : c + '0');
2910  escaped.append((char*)esc, 3);
2911  } else {
2912  escaped.append((char*)&c, 1);
2913  }
2914  }
2915  return escaped;
2916 }
2917 
2918 
2919 YRETCODE YFunction::_buildSetRequest( const string& changeattr, const string *changeval, string& request, string& errmsg)
2920 {
2921  int res;
2922  YFUN_DESCR fundesc;
2923  char funcid[YOCTO_FUNCTION_LEN];
2924  char errbuff[YOCTO_ERRMSG_LEN];
2925 
2926 
2927  // Resolve the function name
2928  res = _getDescriptor(fundesc, errmsg);
2929  if(YISERR(res)) {
2930  return (YRETCODE)res;
2931  }
2932 
2933  if(YISERR(res=yapiGetFunctionInfo(fundesc, NULL, NULL, funcid, NULL, NULL,errbuff))){
2934  errmsg = errbuff;
2935  _throw((YRETCODE)res, errmsg);
2936  return (YRETCODE)res;
2937  }
2938  request = "GET /api/";
2939  request.append(funcid);
2940  request.append("/");
2941  //request.append(".json/");
2942 
2943  if(changeattr!="") {
2944  request.append(changeattr);
2945  if(changeval) {
2946  request.append("?");
2947  request.append(changeattr);
2948  request.append("=");
2949  request.append(_escapeAttr(*changeval));
2950  }
2951  }
2952  // don't append HTTP/1.1 so that we get light headers from hub
2953  // but append &. suffix to enable connection keepalive on newer hubs
2954  request.append("&. \r\n\r\n");
2955  return YAPI_SUCCESS;
2956 }
2957 
2958 
2959 
2961 {
2962  this->_parseAttr(j);
2963  this->_parserHelper();
2964  return 0;
2965 }
2966 
2967 // Set an attribute in the function, and parse the resulting new function state
2968 YRETCODE YFunction::_setAttr(string attrname, string newvalue)
2969 {
2970  string errmsg, request;
2971  int res;
2972  YDevice *dev;
2973 
2974  // Execute http request
2975  res = _buildSetRequest(attrname, &newvalue, request, errmsg);
2976  if(YISERR(res)) {
2977  _throw((YRETCODE)res, errmsg);
2978  return (YRETCODE)res;
2979  }
2980  // Get device Object
2981  res = _getDevice(dev, errmsg);
2982  if(YISERR(res)) {
2983  _throw((YRETCODE)res, errmsg);
2984  return (YRETCODE)res;
2985  }
2986 
2987  res = dev->HTTPRequestAsync(0, request, NULL, NULL, errmsg);
2988  if(YISERR(res)) {
2989  // Check if an update of the device list does not solve the issue
2990  res = YapiWrapper::updateDeviceList(true,errmsg);
2991  if(YISERR(res)) {
2992  _throw((YRETCODE)res, errmsg);
2993  return (YRETCODE)res;
2994  }
2995  res = dev->HTTPRequestAsync(0, request, NULL, NULL, errmsg);
2996  if(YISERR(res)) {
2997  _throw((YRETCODE)res, errmsg);
2998  return (YRETCODE)res;
2999  }
3000  }
3001  if (_cacheExpiration != 0) {
3002  _cacheExpiration=0;
3003  }
3004  return YAPI_SUCCESS;
3005 
3006 }
3007 
3008 
3009 // Method used to send http request to the device (not the function)
3010 string YFunction::_requestEx(int channel, const string& request, yapiRequestProgressCallback callback, void *context)
3011 {
3012  YDevice *dev;
3013  string errmsg, buffer;
3014  int res;
3015 
3016 
3017  // Resolve our reference to our device, load REST API
3018  res = _getDevice(dev, errmsg);
3019  if (YISERR(res)) {
3020  _throw((YRETCODE)res, errmsg);
3021  return YAPI_INVALID_STRING;
3022  }
3023  res = dev->HTTPRequest(channel, request, buffer, callback, context, errmsg);
3024  if (YISERR(res)) {
3025  // Check if an update of the device list does notb solve the issue
3026  res = YapiWrapper::updateDeviceList(true, errmsg);
3027  if (YISERR(res)) {
3028  this->_throw((YRETCODE)res, errmsg);
3029  return YAPI_INVALID_STRING;
3030  }
3031  res = dev->HTTPRequest(channel, request, buffer, callback, context, errmsg);
3032  if (YISERR(res)) {
3033  this->_throw((YRETCODE)res, errmsg);
3034  return YAPI_INVALID_STRING;
3035  }
3036  }
3037  if (0 != buffer.find("OK\r\n")) {
3038  if (0 != buffer.find("HTTP/1.1 200 OK\r\n")) {
3039  this->_throw(YAPI_IO_ERROR, "http request failed");
3040  return YAPI_INVALID_STRING;
3041  }
3042  }
3043  return buffer;
3044 }
3045 
3046 string YFunction::_request(const string& request)
3047 {
3048  return _requestEx(0, request, NULL, NULL);
3049 }
3050 
3051 
3052 // Method used to send http request to the device (not the function)
3053 string YFunction::_download(const string& url)
3054 {
3055  string request,buffer;
3056  size_t found;
3057 
3058  request = "GET /"+url+" HTTP/1.1\r\n\r\n";
3059  buffer = this->_request(request);
3060  found = buffer.find("\r\n\r\n");
3061  if(string::npos == found){
3062  this->_throw(YAPI_IO_ERROR,"http request failed");
3063  return YAPI_INVALID_STRING;
3064  }
3065 
3066  return buffer.substr(found+4);
3067 }
3068 
3069 
3070 // Method used to upload a file to the device
3071 YRETCODE YFunction::_uploadWithProgress(const string& path, const string& content, yapiRequestProgressCallback callback, void *context)
3072 {
3073 
3074  string request, buffer;
3075  string boundary;
3076  size_t found;
3077 
3078  request = "POST /upload.html HTTP/1.1\r\n";
3079  string body = "Content-Disposition: form-data; name=\"" + path + "\"; filename=\"api\"\r\n" +
3080  "Content-Type: application/octet-stream\r\n" +
3081  "Content-Transfer-Encoding: binary\r\n\r\n" + content;
3082  do {
3083  boundary = YapiWrapper::ysprintf("Zz%06xzZ", rand() & 0xffffff);
3084  } while (body.find(boundary) != string::npos);
3085  request += "Content-Type: multipart/form-data; boundary=" + boundary + "\r\n";
3086  request += "\r\n--" + boundary + "\r\n" + body + "\r\n--" + boundary + "--\r\n";
3087  buffer = this->_requestEx(0, request, callback, context);
3088  found = buffer.find("\r\n\r\n");
3089  if (string::npos == found) {
3090  this->_throw(YAPI_IO_ERROR, "http request failed");
3091  return YAPI_IO_ERROR;
3092  }
3093  return YAPI_SUCCESS;
3094 }
3095 
3096 
3097 // Method used to upload a file to the device
3098 YRETCODE YFunction::_upload(const string& path, const string& content)
3099 {
3100  return this->_uploadWithProgress(path, content, NULL, NULL);
3101 }
3102 
3103 
3104 // Method used to cache DataStream objects (new DataLogger)
3105 YDataStream *YFunction::_findDataStream(YDataSet& dataset, const string& def)
3106 {
3107  string key = dataset.get_functionId()+":"+def;
3108  if(_dataStreams.find(key) != _dataStreams.end())
3109  return _dataStreams[key];
3110 
3111  YDataStream *newDataStream = new YDataStream(this, dataset, YAPI::_decodeWords(def));
3112  _dataStreams[key] = newDataStream;
3113  return newDataStream;
3114 }
3115 
3116 // Method used to clear cache of DataStream object (undocumented)
3118 {
3119  std::map<string, YDataStream*>::iterator it;
3120  for (it = _dataStreams.begin(); it != _dataStreams.end(); ++it) {
3121  YDataStream *ds = it->second;
3122 
3123  delete(ds);
3124  }
3125  _dataStreams.clear();
3126 }
3127 
3128 
3129 
3130 // Return a string that describes the function (class and logical name or hardware id)
3132 {
3133  YFUN_DESCR fundescr;
3134  YDEV_DESCR devdescr;
3135  string errmsg, serial, funcId, funcName, funcValue;
3136  string descr = _func;
3137  string res;
3138 
3140  fundescr = YapiWrapper::getFunction(_className, _func, errmsg);
3141  if(!YISERR(fundescr) && !YISERR(YapiWrapper::getFunctionInfo(fundescr, devdescr, serial, funcId, funcName, funcValue, errmsg))) {
3142  res = _className + "(" + _func + ")=" + serial + "." + funcId;
3143  } else {
3144  res = _className + "(" + _func + ")=unresolved";
3145  }
3147  return res;
3148 }
3149 
3150 // Return a string that describes the function (class and logical name or hardware id)
3152 {
3153  YFUN_DESCR fundescr,moddescr;
3154  YDEV_DESCR devdescr;
3155  YRETCODE retcode;
3156  string errmsg, serial, funcId, funcName, funcValue;
3157  string mod_serial, mod_funcId,mod_funcname;
3158 
3160  // Resolve the function name
3161  retcode = _getDescriptor(fundescr, errmsg);
3162  if(!YISERR(retcode) && !YISERR(YapiWrapper::getFunctionInfo(fundescr, devdescr, serial, funcId, funcName, funcValue, errmsg))) {
3163  if(funcName!="") {
3164  funcId = funcName;
3165  }
3166 
3167  moddescr = YapiWrapper::getFunction("Module", serial, errmsg);
3168  if(!YISERR(moddescr) && !YISERR(YapiWrapper::getFunctionInfo(moddescr, devdescr, mod_serial, mod_funcId, mod_funcname, funcValue, errmsg))) {
3169  if(mod_funcname!="") {
3171  return mod_funcname+"."+funcId;
3172  }
3173  }
3175  return serial+"."+funcId;
3176  }
3179  return Y_FRIENDLYNAME_INVALID;
3180 }
3181 
3182 
3183 
3184 
3195 {
3196  YRETCODE retcode;
3197  YFUN_DESCR fundesc;
3198  string errmsg;
3199  char snum[YOCTO_SERIAL_LEN];
3200  char funcid[YOCTO_FUNCTION_LEN];
3201  char errbuff[YOCTO_ERRMSG_LEN];
3202 
3204  // Resolve the function name
3205  retcode = _getDescriptor(fundesc, errmsg);
3206  if(YISERR(retcode)) {
3208  _throw(retcode, errmsg);
3209  return HARDWAREID_INVALID;
3210  }
3211  if(YISERR(retcode=yapiGetFunctionInfo(fundesc, NULL, snum, funcid, NULL, NULL,errbuff))){
3212  errmsg = errbuff;
3214  _throw(retcode, errmsg);
3215  return HARDWAREID_INVALID;
3216  }
3218  return string(snum)+string(".")+string(funcid);
3219 }
3220 
3230 {
3231  YRETCODE retcode;
3232  YFUN_DESCR fundesc;
3233  string errmsg;
3234  char funcid[YOCTO_FUNCTION_LEN];
3235  char errbuff[YOCTO_ERRMSG_LEN];
3236 
3238  // Resolve the function name
3239  retcode = _getDescriptor(fundesc, errmsg);
3240  if(YISERR(retcode)) {
3242  _throw(retcode, errmsg);
3243  return HARDWAREID_INVALID;
3244  }
3245  if(YISERR(retcode=yapiGetFunctionInfo(fundesc, NULL, NULL, funcid, NULL, NULL,errbuff))){
3246  errmsg = errbuff;
3248  _throw(retcode, errmsg);
3249  return HARDWAREID_INVALID;
3250  }
3252  return string(funcid);
3253 }
3254 
3255 
3265 {
3266  return _lastErrorType;
3267 }
3268 
3278 {
3279  return _lastErrorMsg;
3280 }
3281 
3292 {
3293  YDevice *dev;
3294  string errmsg;
3295  YJSONObject *apires;
3296 
3298  try {
3299  // A valid value in cache means that the device is online
3302  return true;
3303  }
3304 
3305  // Check that the function is available, without throwing exceptions
3306  if (YISERR(_getDevice(dev, errmsg))) {
3308  return false;
3309  }
3310 
3311  // Try to execute a function request to be positively sure that the device is ready
3312  if(YISERR(dev->requestAPI(apires, errmsg))) {
3314  return false;
3315  }
3316 
3317  // Preload the function data, since we have it in device cache
3319  } catch (std::exception) {
3321  return false;
3322  }
3324  return true;
3325 }
3326 
3328 {
3329  YJSONObject *j,*node;
3330  YDevice *dev;
3331  string errmsg;
3332  YFUN_DESCR fundescr;
3333  int res;
3334  char errbuf[YOCTO_ERRMSG_LEN];
3335  char serial[YOCTO_SERIAL_LEN];
3336  char funcId[YOCTO_FUNCTION_LEN];
3337 
3338  // Resolve our reference to our device, load REST API
3339  res = _getDevice(dev, errmsg);
3340  if(YISERR(res)) {
3341  _throw((YRETCODE)res, errmsg);
3342  return (YRETCODE)res;
3343  }
3344  res = dev->requestAPI(j, errmsg);
3345  if(YISERR(res)) {
3346  _throw((YRETCODE)res, errmsg);
3347  return (YRETCODE)res;
3348  }
3349 
3350  // Get our function Id
3351  fundescr = YapiWrapper::getFunction(_className, _func, errmsg);
3352  if(YISERR(fundescr)) {
3353  _throw((YRETCODE)fundescr, errmsg);
3354  return (YRETCODE)fundescr;
3355  }
3356  res = yapiGetFunctionInfo(fundescr, NULL, serial, funcId, NULL, NULL, errbuf);
3357  if(YISERR(res)) {
3358  _throw((YRETCODE)res, errbuf);
3359  return (YRETCODE)res;
3360  }
3361  _cacheExpiration = yapiGetTickCount() + msValidity;
3362  _serial = serial;
3363  _funId = funcId;
3364  _hwId = _serial + '.' + _funId;
3365 
3366  try {
3367  node = j->getYJSONObject(funcId);
3368  } catch (std::exception ex) {
3369  _throw(YAPI_IO_ERROR, "unexpected JSON structure: missing function " + _funId);
3370  return YAPI_IO_ERROR;
3371  }
3372  _parse(node);
3373  return YAPI_SUCCESS;
3374 }
3375 
3376 
3391 YRETCODE YFunction::load(int msValidity)
3392 {
3393  YRETCODE res;
3395  try{
3396  res = this->_load_unsafe(msValidity);
3397  } catch (std::exception) {
3399  throw;
3400  }
3402  return res;
3403 }
3404 
3405 
3413 {
3414  YDevice *dev;
3415  string errmsg, apires;
3416 
3417 
3419  // Resolve our reference to our device, load REST API
3420  int res = _getDevice(dev, errmsg);
3421  if (YISERR(res)) {
3423  return;
3424  }
3425  dev->clearCache(false);
3426  if (_cacheExpiration){
3428  }
3430 }
3431 
3432 
3441 {
3442  YFUN_DESCR fundescr;
3443  YDEV_DESCR devdescr;
3444  string errmsg, serial, funcId, funcName, funcValue;
3445 
3447  fundescr = YapiWrapper::getFunction(_className, _func, errmsg);
3448  if(!YISERR(fundescr)) {
3449  if(!YISERR(YapiWrapper::getFunctionInfo(fundescr, devdescr, serial, funcId, funcName, funcValue, errmsg))) {
3451  return yFindModule(serial+".module");
3452  }
3453  }
3454  // return a true YModule object even if it is not a module valid for communicating
3456  return yFindModule(string("module_of_")+_className+"_"+_func);
3457 }
3458 
3459 
3460 
3470 {
3471  void *res;
3473  res = _userData;
3475  return res;
3476 }
3477 
3478 
3486 void YFunction::set_userData(void* data)
3487 {
3489  _userData = data;
3491 }
3492 
3493 
3504 {
3505  // do not take CS un purpose
3506  return _fundescr;
3507 }
3508 
3510 {
3511  if (add) {
3512  func->isOnline();
3513  vector<YFunction*>::iterator it;
3514  for ( it=_FunctionCallbacks.begin() ; it < _FunctionCallbacks.end(); it++ ){
3515  if (*it == func)
3516  return;
3517  }
3518  _FunctionCallbacks.push_back(func);
3519  }else{
3520  vector<YFunction*>::iterator it;
3521  for ( it=_FunctionCallbacks.begin() ; it < _FunctionCallbacks.end(); it++ ){
3522  if (*it == func) {
3523  _FunctionCallbacks.erase(it);
3524  break;
3525  }
3526  }
3527  }
3528 }
3529 
3530 
3532 {
3533  if (add) {
3534  func->isOnline();
3535  vector<YFunction*>::iterator it;
3536  for ( it=_TimedReportCallbackList.begin() ; it < _TimedReportCallbackList.end(); it++ ){
3537  if (*it == func)
3538  return;
3539  }
3540  _TimedReportCallbackList.push_back(func);
3541  }else{
3542  vector<YFunction*>::iterator it;
3543  for ( it=_TimedReportCallbackList.begin() ; it < _TimedReportCallbackList.end(); it++ ){
3544  if (*it == func) {
3545  _TimedReportCallbackList.erase(it);
3546  break;
3547  }
3548  }
3549  }
3550 }
3551 
3552 
3553 // This is the internal device cache object
3554 vector<YDevice*> YDevice::_devCache;
3555 
3556 YDevice::YDevice(YDEV_DESCR devdesc): _devdescr(devdesc), _cacheStamp(0), _cacheJson(NULL), _subpath(NULL) {
3558 };
3559 
3560 
3561 YDevice::~YDevice() // destructor
3562 {
3563  clearCache(true);
3565 }
3566 
3568 {
3569  for(unsigned int idx = 0; idx < YDevice::_devCache.size(); idx++) {
3570  delete _devCache[idx];
3571  }
3572  _devCache.clear();
3573  _devCache = vector<YDevice*>();
3574 }
3575 
3576 
3578 {
3579  // Search in cache
3581  for(unsigned int idx = 0; idx < YDevice::_devCache.size(); idx++) {
3582  if(YDevice::_devCache[idx]->_devdescr == devdescr) {
3584  return YDevice::_devCache[idx];
3585  }
3586  }
3587 
3588  // Not found, add new entry
3589  YDevice *dev = new YDevice(devdescr);
3590  YDevice::_devCache.push_back(dev);
3592 
3593  return dev;
3594 }
3595 
3596 
3597 YRETCODE YDevice::HTTPRequestPrepare(const string& request, string& fullrequest, char *errbuff)
3598 {
3599  YRETCODE res;
3600  size_t pos;
3601  // mutex allready taken by caller
3602  if(_subpath==NULL){
3603  int neededsize;
3604  res = yapiGetDevicePath(_devdescr, _rootdevice, NULL, 0, &neededsize, errbuff);
3605  if(YISERR(res)) return res;
3606  _subpath = new char[neededsize];
3607  res = yapiGetDevicePath(_devdescr, _rootdevice, _subpath, neededsize, NULL, errbuff);
3608  if(YISERR(res)) return res;
3609  }
3610  pos = request.find_first_of('/');
3611  fullrequest = request.substr(0,pos) + (string)_subpath + request.substr(pos+1);
3612 
3613  return YAPI_SUCCESS;
3614 }
3615 
3616 
3617 
3618 YRETCODE YDevice::HTTPRequest_unsafe(int channel, const string& request, string& buffer, yapiRequestProgressCallback callback, void *context, string& errmsg)
3619 {
3620  char errbuff[YOCTO_ERRMSG_LEN] = "";
3621  YRETCODE res;
3622  YIOHDL iohdl;
3623  string fullrequest;
3624  char *reply;
3625  int replysize = 0;
3626 
3627  if (YISERR(res = HTTPRequestPrepare(request, fullrequest, errbuff))) {
3628  errmsg = (string)errbuff;
3629  return res;
3630  }
3631  if (YISERR(res = yapiHTTPRequestSyncStartOutOfBand(&iohdl, channel, _rootdevice, fullrequest.data(), (int)fullrequest.size(), &reply, &replysize, callback, context, errbuff))) {
3632  errmsg = (string)errbuff;
3633  return res;
3634  }
3635  if (replysize > 0 && reply != NULL) {
3636  buffer = string(reply, replysize);
3637  } else {
3638  buffer = "";
3639  }
3640  if (YISERR(res = yapiHTTPRequestSyncDone(&iohdl, errbuff))) {
3641  errmsg = (string)errbuff;
3642  return res;
3643  }
3644 
3645  return YAPI_SUCCESS;
3646 }
3647 
3648 
3649 YRETCODE YDevice::HTTPRequestAsync(int channel, const string& request, HTTPRequestCallback callback, void *context, string& errmsg)
3650 {
3651  char errbuff[YOCTO_ERRMSG_LEN]="";
3652  YRETCODE res = YAPI_SUCCESS;
3653  string fullrequest;
3655  _cacheStamp = YAPI::GetTickCount(); //invalidate cache
3656  if(YISERR(res=HTTPRequestPrepare(request, fullrequest, errbuff)) ||
3657  YISERR(res=yapiHTTPRequestAsyncOutOfBand(channel, _rootdevice, fullrequest.c_str(), (int)fullrequest.length(), NULL, NULL, errbuff))){
3658  errmsg = (string)errbuff;
3659  }
3661  return res;
3662 }
3663 
3664 
3665 YRETCODE YDevice::HTTPRequest(int channel, const string& request, string& buffer, yapiRequestProgressCallback callback, void *context, string& errmsg)
3666 {
3667  YRETCODE res;
3668  int locked = 0;
3669  int i;
3670 
3671  for (i = 0; !locked && i < 5 ; i++) {
3672  locked = yTryEnterCriticalSection(&_lock);
3673  if (!locked) {
3674  yApproximateSleep(50);
3675  }
3676  }
3677  if (!locked) {
3679  }
3680  res = HTTPRequest_unsafe(channel, request, buffer, callback, context, errmsg);
3682  return res;
3683 }
3684 
3685 
3686 YRETCODE YDevice::requestAPI(YJSONObject*& apires, string& errmsg)
3687 {
3689  string rootdev, buffer;
3690  string request = "GET /api.json \r\n\r\n";
3691  string json_str;
3692  int res;
3693 
3695 
3696  // Check if we have a valid cache value
3698  apires = _cacheJson;
3700  return YAPI_SUCCESS;
3701  }
3702  if (_cacheJson == NULL) {
3703  request = "GET /api.json \r\n\r\n";
3704  } else {
3705  request = "GET /api.json?fw="+_cacheJson->getYJSONObject("module")->getString("firmwareRelease")+" \r\n\r\n";
3706  }
3707  // send request, without HTTP/1.1 suffix to get light headers
3708  res = this->HTTPRequest_unsafe(0, request, buffer, NULL, NULL, errmsg);
3709  if(YISERR(res)) {
3711  // Check if an update of the device list does not solve the issue
3712  res = YapiWrapper::updateDeviceList(true,errmsg);
3713  if(YISERR(res)) {
3714  return (YRETCODE)res;
3715  }
3717  // send request, without HTTP/1.1 suffix to get light headers
3718  res = this->HTTPRequest_unsafe(0, request, buffer, NULL, NULL, errmsg);
3719  if(YISERR(res)) {
3721  return (YRETCODE)res;
3722  }
3723  }
3724 
3725  // Parse HTTP header
3726  j.src = buffer.data();
3727  j.end = j.src + buffer.size();
3728  j.st = YJSON_HTTP_START;
3730  errmsg = "Failed to parse HTTP header";
3732  return YAPI_IO_ERROR;
3733  }
3734  if(string(j.token) != "200") {
3735  errmsg = string("Unexpected HTTP return code: ")+j.token;
3737  return YAPI_IO_ERROR;
3738  }
3739  if(yJsonParse(&j) != YJSON_PARSE_AVAIL || j.st != YJSON_HTTP_READ_MSG) {
3740  errmsg = "Unexpected HTTP header format";
3742  return YAPI_IO_ERROR;
3743  }
3744  if(yJsonParse(&j) != YJSON_PARSE_AVAIL || (j.st != YJSON_PARSE_STRUCT && j.st != YJSON_PARSE_ARRAY)) {
3745  errmsg = "Unexpected JSON reply format";
3747  return YAPI_IO_ERROR;
3748  }
3749  // we know for sure that the last character parsed was a '{' or '['
3750  do j.src--; while(j.src[0] != '{' && j.src[0] != '[');
3751  json_str = string(j.src);
3752  try {
3753  apires = new YJSONObject(json_str, 0, (int)json_str.length());
3754  apires->parseWithRef(_cacheJson);
3755  } catch (std::exception ex) {
3756  errmsg = "unexpected JSON structure: " + string(ex.what());
3757  if (_cacheJson) {
3758  delete _cacheJson;
3759  _cacheJson = NULL;
3760  }
3762  return YAPI_IO_ERROR;
3763  }
3764  // store result in cache
3765  if (_cacheJson) {
3766  delete _cacheJson;
3767  }
3768  _cacheJson = apires;
3771 
3772  return YAPI_SUCCESS;
3773 }
3774 
3775 
3776 
3777 
3778 
3779 void YDevice::clearCache(bool clearSubpath)
3780 {
3782  _cacheStamp = 0;
3783  if (clearSubpath) {
3784  if (_cacheJson) {
3785  delete _cacheJson;
3786  _cacheJson = NULL;
3787  }
3788  if (_subpath) {
3789  delete _subpath;
3790  _subpath = NULL;
3791  }
3792  }
3794 }
3795 
3796 YRETCODE YDevice::getFunctions(vector<YFUN_DESCR> **functions, string& errmsg)
3797 {
3799  if(_functions.size() == 0) {
3800  int res = YapiWrapper::getFunctionsByDevice(_devdescr, 0, _functions, 64, errmsg);
3801  if(YISERR(res)) return (YRETCODE)res;
3802  }
3803  *functions = &_functions;
3805 
3806  return YAPI_SUCCESS;
3807 }
3808 
3809 
3810 queue<yapiGlobalEvent> YAPI::_plug_events;
3811 queue<yapiDataEvent> YAPI::_data_events;
3812 
3813 u64 YAPI::_nextEnum = 0;
3814 bool YAPI::_apiInitialized = false;
3815 
3816 std::map<int,yCalibrationHandler> YAPI::_calibHandlers;
3818 
3819 
3820 // Default cache validity (in [ms]) before reloading data from device. This saves a lots of trafic.
3821 // Note that a value undger 2 ms makes little sense since a USB bus itself has a 2ms roundtrip period
3823 
3824 // Switch to turn off exceptions and use return codes instead, for source-code compatibility
3825 // with languages without exception support like pure C
3826 bool YAPI::ExceptionsDisabled = false;
3827 
3829 
3830 // standard error objects
3832 const double YAPI::INVALID_DOUBLE = (-DBL_MAX);
3833 
3834 
3839 
3840 void YAPI::_yapiLogFunctionFwd(const char *log, u32 loglen)
3841 {
3842  if(YAPI::LogFunction)
3843  YAPI::LogFunction(string(log));
3844 }
3845 
3846 
3847 void YAPI::_yapiDeviceLogCallbackFwd(YDEV_DESCR devdesc, const char* line)
3848 {
3849  YModule *module;
3850  yDeviceSt infos;
3851  string errmsg;
3852  YModuleLogCallback callback;
3853 
3854  if(YapiWrapper::getDeviceInfo(devdesc, infos, errmsg) != YAPI_SUCCESS) return;
3855  module = YModule::FindModule(string(infos.serial)+".module");
3856  callback = module->get_logCallback();
3857  if (callback) {
3858  callback(module, string(line));
3859  }
3860 }
3861 
3862 
3864 {
3865  yapiGlobalEvent ev;
3866  yapiDataEvent dataEv;
3867  yDeviceSt infos;
3868  string errmsg;
3869  vector<YFunction*>::iterator it;
3870 
3871  YDevice *dev = YDevice::getDevice(devdesc);
3872  dev->clearCache(true);
3873  dataEv.type = YAPI_FUN_REFRESH;
3874  for ( it=_FunctionCallbacks.begin() ; it < _FunctionCallbacks.end(); it++ ){
3875  if ((*it)->functionDescriptor() == Y_FUNCTIONDESCRIPTOR_INVALID){
3876  dataEv.fun = *it;
3877  _data_events.push(dataEv);
3878  }
3879  }
3880  if (YAPI::DeviceArrivalCallback == NULL) return;
3881  ev.type = YAPI_DEV_ARRIVAL;
3882  //the function is allready thread safe (use yapiLockDeviceCallaback)
3883  if(YapiWrapper::getDeviceInfo(devdesc, infos, errmsg) != YAPI_SUCCESS) return;
3884  ev.module = yFindModule(string(infos.serial)+".module");
3885  ev.module->setImmutableAttributes(&infos);
3886  _plug_events.push(ev);
3887 }
3888 
3890 {
3891  yapiGlobalEvent ev;
3892  yDeviceSt infos;
3893  string errmsg;
3894 
3895  if (YAPI::DeviceRemovalCallback == NULL) return;
3896  ev.type = YAPI_DEV_REMOVAL;
3897  if(YapiWrapper::getDeviceInfo(devdesc, infos, errmsg) != YAPI_SUCCESS) return;
3898  ev.module = yFindModule(string(infos.serial)+".module");
3899  //the function is allready thread safe (use yapiLockDeviceCallaback)
3900  _plug_events.push(ev);
3901 }
3902 
3904 {
3905  yapiGlobalEvent ev;
3906  yDeviceSt infos;
3907  string errmsg;
3908 
3909  if (YAPI::DeviceChangeCallback == NULL) return;
3910  ev.type = YAPI_DEV_CHANGE;
3911  if(YapiWrapper::getDeviceInfo(devdesc, infos, errmsg) != YAPI_SUCCESS) return;
3912  ev.module = yFindModule(string(infos.serial)+".module");
3913  ev.module->setImmutableAttributes(&infos);
3914  //the function is allready thread safe (use yapiLockDeviceCallaback)
3915  _plug_events.push(ev);
3916 }
3917 
3919 {
3920  yapiDataEvent ev;
3921 
3922  //the function is allready thread safe (use yapiLockFunctionCallaback)
3923  if(value==NULL){
3924  ev.type = YAPI_FUN_UPDATE;
3925  }else{
3926  ev.type = YAPI_FUN_VALUE;
3927  memcpy(ev.value,value,YOCTO_PUBVAL_LEN);
3928  }
3929  for (unsigned i=0 ; i< _FunctionCallbacks.size();i++) {
3930  if (_FunctionCallbacks[i]->get_functionDescriptor() == fundesc) {
3931  ev.fun = _FunctionCallbacks[i];
3932  _data_events.push(ev);
3933  }
3934  }
3935 }
3936 
3937 void YAPI::_yapiFunctionTimedReportCallbackFwd(YAPI_FUNCTION fundesc,double timestamp, const u8 *bytes, u32 len)
3938 {
3939  yapiDataEvent ev;
3940 
3941  for (unsigned i=0 ; i< _TimedReportCallbackList.size();i++) {
3942  if (_TimedReportCallbackList[i]->get_functionDescriptor() == fundesc) {
3943  u32 p = 0;
3946  ev.timestamp = timestamp;
3947  ev.len = len;
3948  while(p < len) {
3949  ev.report[p++] = *bytes++;
3950  }
3951  _data_events.push(ev);
3952  }
3953  }
3954 }
3955 
3956 void YAPI::_yapiHubDiscoveryCallbackFwd(const char *serial, const char *url)
3957 {
3958  yapiGlobalEvent ev;
3959 
3960  if (YAPI::_HubDiscoveryCallback == NULL) return;
3961  ev.type = YAPI_HUB_DISCOVER;
3962  strcpy(ev.serial, serial);
3963  strcpy(ev.url, url);
3964  _plug_events.push(ev);
3965 }
3966 
3967 
3968 
3969 
3970 
3971 static double decExp[16] = {
3972  1.0e-6, 1.0e-5, 1.0e-4, 1.0e-3, 1.0e-2, 1.0e-1, 1.0,
3973  1.0e1, 1.0e2, 1.0e3, 1.0e4, 1.0e5, 1.0e6, 1.0e7, 1.0e8, 1.0e9 };
3974 
3975 // Convert Yoctopuce 16-bit decimal floats to standard double-precision floats
3976 //
3977 double YAPI::_decimalToDouble(s16 val)
3978 {
3979  int negate = 0;
3980  int mantis = val & 2047;
3981  double res;
3982 
3983  if(mantis == 0) return 0.0;
3984  if(val < 0) {
3985  negate = 1;
3986  val = -val;
3987  }
3988  res = (double)(mantis) * decExp[val >> 11];
3989 
3990  return (negate ? -res : res);
3991 }
3992 
3993 // Convert standard double-precision floats to Yoctopuce 16-bit decimal floats
3994 //
3995 s16 YAPI::_doubleToDecimal(double val)
3996 {
3997  int negate = 0;
3998  double comp, mant;
3999  int decpow;
4000  int res;
4001 
4002  if(val == 0.0) {
4003  return 0;
4004  }
4005  if(val < 0) {
4006  negate = 1;
4007  val = -val;
4008  }
4009  comp = val / 1999.0;
4010  decpow = 0;
4011  while(comp > decExp[decpow] && decpow < 15) {
4012  decpow++;
4013  }
4014  mant = val / decExp[decpow];
4015  if(decpow == 15 && mant > 2047.0) {
4016  res = (15 << 11) + 2047; // overflow
4017  } else {
4018  res = (decpow << 11) + (int)floor(mant+.5);
4019  }
4020  return (negate ? -res : res);
4021 }
4022 
4024 {
4025  if(YAPI::_calibHandlers.find(calibType) == YAPI::_calibHandlers.end()) {
4026  return NULL;
4027  }
4028  return YAPI::_calibHandlers[calibType];
4029 }
4030 
4031 
4032 // Parse an array of u16 encoded in a base64-like string with memory-based compresssion
4033 vector<int> YAPI::_decodeWords(string sdat)
4034 {
4035  vector<int> udat;
4036 
4037  for(unsigned p = 0; p < sdat.size();) {
4038  unsigned val;
4039  unsigned c = sdat[p++];
4040  if(c == '*') {
4041  val = 0;
4042  } else if(c == 'X') {
4043  val = 0xffff;
4044  } else if(c == 'Y') {
4045  val = 0x7fff;
4046  } else if(c >= 'a') {
4047  int srcpos = (int)udat.size()-1-(c-'a');
4048  if(srcpos < 0)
4049  val = 0;
4050  else
4051  val = udat[srcpos];
4052  } else {
4053  if(p+2 > sdat.size()) return udat;
4054  val = (c - '0');
4055  c = sdat[p++];
4056  val += (c - '0') << 5;
4057  c = sdat[p++];
4058  if(c == 'z') c = '\\';
4059  val += (c - '0') << 10;
4060  }
4061  udat.push_back((int)val);
4062  }
4063  return udat;
4064 }
4065 
4066 // Parse a list of floats and return them as an array of fixed-point 1/1000 numbers
4067 vector<int> YAPI::_decodeFloats(string sdat)
4068 {
4069  vector<int> idat;
4070 
4071  for(unsigned p = 0; p < sdat.size();) {
4072  int val = 0;
4073  int sign = 1;
4074  int dec = 0;
4075  int decInc = 0;
4076  unsigned c = sdat[p++];
4077  while(c != '-' && (c < '0' || c > '9')) {
4078  if(p >= sdat.size()) {
4079  return idat;
4080  }
4081  c = sdat[p++];
4082  }
4083  if(c == '-') {
4084  if(p >= sdat.size()) {
4085  return idat;
4086  }
4087  sign = -sign;
4088  c = sdat[p++];
4089  }
4090  while((c >= '0' && c <= '9') || c == '.') {
4091  if(c == '.') {
4092  decInc = 1;
4093  } else if(dec < 3) {
4094  val = val * 10 + (c - '0');
4095  dec += decInc;
4096  }
4097  if(p < sdat.size()) {
4098  c = sdat[p++];
4099  } else {
4100  c = 0;
4101  }
4102  }
4103  if(dec < 3) {
4104  if(dec == 0) val *= 1000;
4105  else if(dec == 1) val *= 100;
4106  else val *= 10;
4107  }
4108  idat.push_back(sign*val);
4109  }
4110  return idat;
4111 }
4112 
4113 
4114 static const char* hexArray = "0123456789ABCDEF";
4115 
4116 string YAPI::_bin2HexStr(const string& data)
4117 {
4118  const u8 *ptr = (u8*) data.data();
4119  size_t len = data.length();
4120  string res = string(len * 2, 0);
4121  for (size_t j = 0; j < len; j++, ptr++) {
4122  u8 v = *ptr;
4123  res[j * 2] = hexArray[v >> 4];
4124  res[j * 2 + 1] = hexArray[v & 0x0F];
4125  }
4126  return res;
4127 
4128 }
4129 
4130 string YAPI::_hexStr2Bin(const string& hex_str)
4131 {
4132  size_t len = hex_str.length() / 2;
4133  const char *p = hex_str.c_str();
4134  string res = string(len, 0);
4135  for (size_t i = 0; i < len; i++) {
4136  u8 b = 0;
4137  int j;
4138  for(j = 0; j < 2; j++) {
4139  b <<= 4;
4140  if(*p >= 'a' && *p <='f'){
4141  b += 10 + *p - 'a';
4142  }else if(*p >= 'A' && *p <='F'){
4143  b += 10 + *p - 'A';
4144  }else if(*p >='0' && *p <='9'){
4145  b += *p - '0';
4146  }
4147  p++;
4148  }
4149  res[i] = b;
4150  }
4151  return res;
4152 }
4153 
4154 
4155 
4156 s64 yatoi(const char *p)
4157 {
4158  s64 value = 0;
4159  bool neg = *p == '-';
4160  if (*p == '+' || neg) {
4161  p++;
4162  }
4163  while (*p >= '0' && *p <= '9') {
4164  value *= 10;
4165  value += *p - '0';
4166  p++;
4167  }
4168  if (neg) {
4169  return -value;
4170  } else {
4171  return value;
4172  }
4173 }
4174 
4175 
4193 {
4194  string version;
4195  string date;
4196  YapiWrapper::getAPIVersion(version,date);
4197  return version;
4198 }
4199 
4200 
4221 YRETCODE YAPI::InitAPI(int mode, string& errmsg)
4222 {
4223  char errbuf[YOCTO_ERRMSG_LEN];
4224  int i;
4225 
4227  return YAPI_SUCCESS;
4228  YRETCODE res = yapiInitAPI(mode, errbuf);
4229  if(YISERR(res)) {
4230  errmsg = errbuf;
4231  return res;
4232  }
4241 
4244  yInitializeCriticalSection(&_global_cs);
4245  for(i = 0; i <= 20; i++) {
4247  }
4249  YAPI::_apiInitialized = true;
4250 
4251  return YAPI_SUCCESS;
4252 }
4253 
4262 void YAPI::FreeAPI(void)
4263 {
4264  if(YAPI::_apiInitialized) {
4265  yapiFreeAPI();
4266  YAPI::_apiInitialized = false;
4269  yDeleteCriticalSection(&_global_cs);
4272  while (!_plug_events.empty()) {
4273  _plug_events.pop();
4274  }
4275  while (!_data_events.empty()) {
4276  _data_events.pop();
4277  }
4278  _calibHandlers.clear();
4279  }
4280 }
4281 
4289 { YAPI::ExceptionsDisabled = true; }
4290 
4299 { YAPI::ExceptionsDisabled = false; }
4300 
4309 {
4310  YAPI::LogFunction = logfun;
4311 }
4312 
4322 {
4323  YAPI::DeviceArrivalCallback = arrivalCallback;
4324  if(arrivalCallback) {
4325  YModule *mod =YModule::FirstModule();
4326  while(mod){
4327  if(mod->isOnline()){
4328  yapiLockDeviceCallBack(NULL);
4329  _yapiDeviceArrivalCallbackFwd(mod->functionDescriptor());
4331  }
4332  mod = mod->nextModule();
4333  }
4334  }
4335 }
4336 
4346 {
4347  YAPI::DeviceRemovalCallback = removalCallback;
4348 }
4349 
4351 {
4352  YAPI::DeviceChangeCallback = changeCallback;
4353 }
4354 
4366 {
4367  YAPI::_HubDiscoveryCallback = hubDiscoveryCallback;
4368  string error;
4370 }
4371 
4382 {
4383  YRETCODE res;
4384  char errbuf[YOCTO_ERRMSG_LEN];
4385  if (!YAPI::_apiInitialized) {
4386  res = YAPI::InitAPI(0, errmsg);
4387  if (YISERR(res)) return res;
4388  }
4389  res = yapiTriggerHubDiscovery(errbuf);
4390  if(YISERR(res)) {
4391  errmsg = errbuf;
4392  return res;
4393  }
4394  return YAPI_SUCCESS;
4395 }
4396 
4397 
4398 
4399 // Register a new value calibration handler for a given calibration type
4400 //
4401 void YAPI::RegisterCalibrationHandler(int calibrationType, yCalibrationHandler calibrationHandler)
4402 {
4403  YAPI::_calibHandlers[calibrationType] = calibrationHandler;
4404 }
4405 
4406 // Standard value calibration handler (n-point linear error correction)
4407 //
4408 double YAPI::LinearCalibrationHandler(double rawValue, int calibType, intArr params, floatArr rawValues, floatArr refValues)
4409 {
4410  double x = rawValues[0];
4411  double adj = refValues[0] - x;
4412  int i = 0;
4413  int npt;
4414 
4415  if(calibType < YOCTO_CALIB_TYPE_OFS) {
4416  // calibration types n=1..10 and 11..20 are meant for linear calibration using n points
4417  npt = calibType % 10;
4418  if(npt > (int)rawValues.size()) npt = (int)rawValues.size();
4419  if(npt > (int)refValues.size()) npt = (int)refValues.size();
4420  } else {
4421  npt = (int)refValues.size();
4422  }
4423  while(rawValue > rawValues[i] && ++i < npt) {
4424  double x2 = x;
4425  double adj2 = adj;
4426 
4427  x = rawValues[i];
4428  adj = refValues[i] - x;
4429 
4430  if(rawValue < x && x > x2) {
4431  adj = adj2 + (adj - adj2) * (rawValue - x2) / (x - x2);
4432  }
4433  }
4434  return rawValue + adj;
4435 }
4436 
4437 
4453 YRETCODE YAPI::TestHub(const string& url, int mstimeout, string& errmsg)
4454 {
4455  char errbuf[YOCTO_ERRMSG_LEN];
4456  YRETCODE res;
4457  res = yapiTestHub(url.c_str(), mstimeout, errbuf);
4458  if (YISERR(res)) {
4459  errmsg = errbuf;
4460  }
4461  return res;
4462 }
4463 
4464 
4509 YRETCODE YAPI::RegisterHub(const string& url, string& errmsg)
4510 {
4511  char errbuf[YOCTO_ERRMSG_LEN];
4512  YRETCODE res;
4513  if(!YAPI::_apiInitialized) {
4514  res = YAPI::InitAPI(0, errmsg);
4515  if(YISERR(res)) return res;
4516  }
4517  res = yapiRegisterHub(url.c_str(), errbuf);
4518  if(YISERR(res)) {
4519  errmsg = errbuf;
4520  }
4521  return res;
4522 }
4523 
4539 YRETCODE YAPI::PreregisterHub(const string& url, string& errmsg)
4540 {
4541  char errbuf[YOCTO_ERRMSG_LEN];
4542  YRETCODE res;
4543  if(!YAPI::_apiInitialized) {
4544  res = YAPI::InitAPI(0, errmsg);
4545  if(YISERR(res)) return res;
4546  }
4547  res = yapiPreregisterHub(url.c_str(), errbuf);
4548  if(YISERR(res)) {
4549  errmsg = errbuf;
4550  }
4551  return res;
4552 }
4560 void YAPI::UnregisterHub(const string& url)
4561 {
4562  if(!YAPI::_apiInitialized){
4563  return;
4564  }
4565  yapiUnregisterHub(url.c_str());
4566 }
4567 
4568 
4585 {
4586  if(!YAPI::_apiInitialized) {
4587  YRETCODE res = YAPI::InitAPI(0, errmsg);
4588  if(YISERR(res)) return res;
4589  }
4590  // prevent reentrance into this function
4592  // call the updateDeviceList of the yapi layer
4593  // yapi know when it is needed to do a full update
4594  YRETCODE res = YapiWrapper::updateDeviceList(false,errmsg);
4595  if(YISERR(res)) {
4597  return res;
4598  }
4599  // handle other notification
4600  res = YapiWrapper::handleEvents(errmsg);
4601  if(YISERR(res)) {
4603  return res;
4604  }
4605  // unpop plug/unplug event and call user callback
4606  while(!_plug_events.empty()){
4607  yapiGlobalEvent ev;
4608  yapiLockDeviceCallBack(NULL);
4609  if(_plug_events.empty()){
4611  break;
4612  }
4613  ev = _plug_events.front();
4614  _plug_events.pop();
4616  switch(ev.type){
4617  case YAPI_DEV_ARRIVAL:
4618  if(!YAPI::DeviceArrivalCallback) break;
4620  break;
4621  case YAPI_DEV_REMOVAL:
4622  if(!YAPI::DeviceRemovalCallback) break;
4624  break;
4625  case YAPI_DEV_CHANGE:
4626  if(!YAPI::DeviceChangeCallback) break;
4628  break;
4629  case YAPI_HUB_DISCOVER:
4630  if (!YAPI::_HubDiscoveryCallback) break;
4631  YAPI::_HubDiscoveryCallback(string(ev.serial),string(ev.url));
4632  break;
4633  default:
4634  break;
4635  }
4636  }
4638  return YAPI_SUCCESS;
4639 }
4640 
4659 {
4660  YRETCODE res;
4661 
4662  // prevent reentrance into this function
4664  // handle other notification
4665  res = YapiWrapper::handleEvents(errmsg);
4666  if(YISERR(res)) {
4668  return res;
4669  }
4670  // pop data event and call user callback
4671  while (!_data_events.empty()) {
4672  yapiDataEvent ev;
4673  YSensor *sensor;
4674  vector<int> report;
4675 
4677  if (_data_events.empty()) {
4679  break;
4680  }
4681  ev = _data_events.front();
4682  _data_events.pop();
4684  switch (ev.type) {
4685  case YAPI_FUN_VALUE:
4686  ev.fun->_invokeValueCallback((string)ev.value);
4687  break;
4688  case YAPI_FUN_TIMEDREPORT:
4689  if(ev.report[0] <= 2) {
4690  sensor = ev.sensor;
4691  report.assign(ev.report, ev.report + ev.len);
4692  sensor->_invokeTimedReportCallback(sensor->_decodeTimedReport(ev.timestamp, report));
4693  }
4694  break;
4695  case YAPI_FUN_REFRESH:
4696  ev.fun->isOnline();
4697  break;
4698  default:
4699  break;
4700  }
4701  }
4703  return YAPI_SUCCESS;
4704 }
4705 
4725 YRETCODE YAPI::Sleep(unsigned ms_duration, string& errmsg)
4726 {
4727  char errbuf[YOCTO_ERRMSG_LEN];
4728  YRETCODE res;
4729  u64 waituntil = YAPI::GetTickCount() + ms_duration;
4730  do{
4731  res = YAPI::HandleEvents(errmsg);
4732  if(YISERR(res)) {
4733  errmsg = errbuf;
4734  return res;
4735  }
4736  if(waituntil>YAPI::GetTickCount()){
4737  res = yapiSleep(2, errbuf);
4738  if(YISERR(res)) {
4739  errmsg = errbuf;
4740  return res;
4741  }
4742  }
4743  }while(waituntil>YAPI::GetTickCount());
4744 
4745  return YAPI_SUCCESS;
4746 }
4747 
4756 {
4757  return yapiGetTickCount();
4758 }
4759 
4771 bool YAPI::CheckLogicalName(const string& name)
4772 {
4773  return (yapiCheckLogicalName(name.c_str())!=0);
4774 }
4775 
4776 u16 YapiWrapper::getAPIVersion(string& version,string& date)
4777 {
4778  const char *_ver, *_date;
4779  u16 res = yapiGetAPIVersion(&_ver, &_date);
4780  version = _ver;
4781  date = _date;
4782  return res;
4783 }
4784 
4785 YDEV_DESCR YapiWrapper::getDevice(const string& device_str, string& errmsg)
4786 {
4787  char errbuf[YOCTO_ERRMSG_LEN];
4788  YDEV_DESCR res;
4789 
4790  res = yapiGetDevice(device_str.data(), errbuf);
4791  if(YISERR(res)) {
4792  errmsg = errbuf;
4793  }
4794  return (YDEV_DESCR)res;
4795 }
4796 
4797 int YapiWrapper::getAllDevices(vector<YDEV_DESCR>& buffer, string& errmsg)
4798 {
4799  char errbuf[YOCTO_ERRMSG_LEN];
4800  int n_elems = 32;
4801  int initsize = n_elems * sizeof(YDEV_DESCR);
4802  int neededsize, res;
4803  YDEV_DESCR *ptr = new YDEV_DESCR[n_elems];
4804 
4805  res = yapiGetAllDevices(ptr, initsize, &neededsize, errbuf);
4806  if(YISERR(res)) {
4807  delete [] ptr;
4808  errmsg = errbuf;
4809  return (YRETCODE)res;
4810  }
4811  if(neededsize > initsize) {
4812  delete [] ptr;
4813  n_elems = neededsize / sizeof(YDEV_DESCR);
4814  initsize = n_elems * sizeof(YDEV_DESCR);
4815  ptr = new YDEV_DESCR[n_elems];
4816  res = yapiGetAllDevices(ptr, initsize, NULL, errbuf);
4817  if(YISERR(res)) {
4818  delete [] ptr;
4819  errmsg = errbuf;
4820  return (YRETCODE)res;
4821  }
4822  }
4823  buffer = vector<YDEV_DESCR>(ptr, ptr+res);
4824  delete [] ptr;
4825 
4826  return res;
4827 }
4828 
4830 {
4831  char errbuf[YOCTO_ERRMSG_LEN];
4832  YRETCODE res;
4833 
4834  res = yapiGetDeviceInfo(devdesc, &infos, errbuf);
4835  if(YISERR(res)) {
4836  errmsg = errbuf;
4837  }
4838  return res;
4839 }
4840 
4841 YFUN_DESCR YapiWrapper::getFunction(const string& class_str, const string& function_str, string& errmsg)
4842 {
4843  char errbuf[YOCTO_ERRMSG_LEN];
4844 
4845  YFUN_DESCR res = yapiGetFunction(class_str.data(), function_str.data(), errbuf);
4846  if(YISERR(res)) {
4847  errmsg = errbuf;
4848  }
4849  return res;
4850 }
4851 
4852 int YapiWrapper::getFunctionsByClass(const string& class_str, YFUN_DESCR prevfundesc, vector<YFUN_DESCR>& buffer, int maxsize, string& errmsg)
4853 {
4854  char errbuf[YOCTO_ERRMSG_LEN];
4855  int n_elems = 32;
4856  int initsize = n_elems * sizeof(YDEV_DESCR);
4857  int neededsize;
4858  YFUN_DESCR *ptr = new YFUN_DESCR[n_elems];
4859 
4860  int res = yapiGetFunctionsByClass(class_str.data(), prevfundesc, ptr, initsize, &neededsize, errbuf);
4861  if(YISERR(res)) {
4862  delete [] ptr;
4863  errmsg = errbuf;
4864  return res;
4865  }
4866  if(neededsize > initsize) {
4867  delete [] ptr;
4868  n_elems = neededsize / sizeof(YFUN_DESCR);
4869  initsize = n_elems * sizeof(YFUN_DESCR);
4870  ptr = new YFUN_DESCR[n_elems];
4871  res = yapiGetFunctionsByClass(class_str.data(), prevfundesc, ptr, initsize, NULL, errbuf);
4872  if(YISERR(res)) {
4873  delete [] ptr;
4874  errmsg = errbuf;
4875  return res;
4876  }
4877  }
4878  buffer = vector<YFUN_DESCR>(ptr, ptr+res);
4879  delete [] ptr;
4880 
4881  return res;
4882 }
4883 
4884 int YapiWrapper::getFunctionsByDevice(YDEV_DESCR devdesc, YFUN_DESCR prevfundesc, vector<YFUN_DESCR>& buffer, int maxsize, string& errmsg)
4885 {
4886  char errbuf[YOCTO_ERRMSG_LEN];
4887  int n_elems = 32;
4888  int initsize = n_elems * sizeof(YDEV_DESCR);
4889  int neededsize;
4890  YFUN_DESCR *ptr = new YFUN_DESCR[n_elems];
4891 
4892  int res = yapiGetFunctionsByDevice(devdesc, prevfundesc, ptr, initsize, &neededsize, errbuf);
4893  if(YISERR(res)) {
4894  delete [] ptr;
4895  errmsg = errbuf;
4896  return res;
4897  }
4898  if(neededsize > initsize) {
4899  delete [] ptr;
4900  n_elems = neededsize / sizeof(YFUN_DESCR);
4901  initsize = n_elems * sizeof(YFUN_DESCR);
4902  ptr = new YFUN_DESCR[n_elems];
4903  res = yapiGetFunctionsByDevice(devdesc, prevfundesc, ptr, initsize, NULL, errbuf);
4904  if(YISERR(res)) {
4905  delete [] ptr;
4906  errmsg = errbuf;
4907  return res;
4908  }
4909  }
4910  buffer = vector<YFUN_DESCR>(ptr, ptr+res);
4911  delete [] ptr;
4912 
4913  return res;
4914 }
4915 
4917 {
4918  char errbuf[YOCTO_ERRMSG_LEN];
4919  YDEV_DESCR dev;
4920 
4921  int res = yapiGetFunctionInfo(fundesc, &dev, NULL, NULL, NULL, NULL, errbuf);
4922  if(YISERR(res)) {
4923  errmsg = errbuf;
4924  return res;
4925  }
4926 
4927  return dev;
4928 }
4929 
4930 YRETCODE YapiWrapper::getFunctionInfo(YFUN_DESCR fundesc, YDEV_DESCR& devdescr, string& serial, string& funcId, string& funcName, string& funcVal, string& errmsg)
4931 {
4932  char errbuf[YOCTO_ERRMSG_LEN];
4933  char snum[YOCTO_SERIAL_LEN];
4934  char fnid[YOCTO_FUNCTION_LEN];
4935  char fnam[YOCTO_LOGICAL_LEN];
4936  char fval[YOCTO_PUBVAL_LEN];
4937 
4938  YRETCODE res = yapiGetFunctionInfoEx(fundesc, &devdescr, snum, fnid, NULL, fnam, fval, errbuf);
4939  if (YISERR(res)) {
4940  errmsg = errbuf;
4941  } else {
4942  serial = snum;
4943  funcId = fnid;
4944  funcName = fnam;
4945  funcVal = fval;
4946  }
4947 
4948  return res;
4949 }
4950 
4951 YRETCODE YapiWrapper::getFunctionInfoEx(YFUN_DESCR fundesc, YDEV_DESCR& devdescr, string& serial, string& funcId, string& baseType, string& funcName, string& funcVal, string& errmsg)
4952 {
4953  char errbuf[YOCTO_ERRMSG_LEN];
4954  char snum[YOCTO_SERIAL_LEN];
4955  char fnid[YOCTO_FUNCTION_LEN];
4956  char fbt[YOCTO_FUNCTION_LEN];
4957  char fnam[YOCTO_LOGICAL_LEN];
4958  char fval[YOCTO_PUBVAL_LEN];
4959 
4960  YRETCODE res = yapiGetFunctionInfoEx(fundesc, &devdescr, snum, fnid, fbt, fnam, fval, errbuf);
4961  if(YISERR(res)) {
4962  errmsg = errbuf;
4963  } else {
4964  serial = snum;
4965  funcId = fnid;
4966  baseType = fbt;
4967  funcName = fnam;
4968  funcVal = fval;
4969  }
4970 
4971  return res;
4972 }
4973 
4974 YRETCODE YapiWrapper::updateDeviceList(bool forceupdate,string& errmsg)
4975 {
4976  char errbuf[YOCTO_ERRMSG_LEN];
4977  YRETCODE res = yapiUpdateDeviceList(forceupdate?1:0,errbuf);
4978  if(YISERR(res)) {
4979  errmsg = errbuf;
4980  return res;
4981  }
4982  return YAPI_SUCCESS;
4983 }
4984 
4986 {
4987  char errbuf[YOCTO_ERRMSG_LEN];
4988  YRETCODE res = yapiHandleEvents(errbuf);
4989  if(YISERR(res)) {
4990  errmsg = errbuf;
4991  return res;
4992  }
4993  return YAPI_SUCCESS;
4994 }
4995 
4996 
4997 string YapiWrapper::ysprintf(const char *fmt, ...)
4998 {
4999  va_list args;
5000  char on_stack_buffer[1024];
5001  int n, size = 1024;
5002  char *buffer = on_stack_buffer;
5003  string res = "";
5004 
5005  for (int i = 0; i < 13; i++) {
5006  va_start(args, fmt);
5007  n = vsnprintf(buffer, size, fmt, args);
5008  va_end(args);
5009  if (n > -1 && n < size) {
5010  res = string(buffer);
5011  break;
5012  }
5013 
5014  if (n > -1) {
5015  size = n + 1;
5016  } else {
5017  size *= 2;
5018  }
5019  if (buffer != on_stack_buffer) {
5020  free(buffer);
5021  }
5022  buffer = (char*)malloc(size);
5023  }
5024  if (buffer != on_stack_buffer) {
5025  free(buffer);
5026  }
5027  return res;
5028 }
5029 
5030 
5031 
5032 
5033 
5034 
5035 //--- (generated code: YModule constructor)
5036 YModule::YModule(const string& func): YFunction(func)
5037 //--- (end of generated code: YModule constructor)
5038 //--- (generated code: YModule initialization)
5039  ,_productName(PRODUCTNAME_INVALID)
5040  ,_serialNumber(SERIALNUMBER_INVALID)
5041  ,_productId(PRODUCTID_INVALID)
5042  ,_productRelease(PRODUCTRELEASE_INVALID)
5043  ,_firmwareRelease(FIRMWARERELEASE_INVALID)
5044  ,_persistentSettings(PERSISTENTSETTINGS_INVALID)
5045  ,_luminosity(LUMINOSITY_INVALID)
5046  ,_beacon(BEACON_INVALID)
5047  ,_upTime(UPTIME_INVALID)
5048  ,_usbCurrent(USBCURRENT_INVALID)
5049  ,_rebootCountdown(REBOOTCOUNTDOWN_INVALID)
5050  ,_userVar(USERVAR_INVALID)
5051  ,_valueCallbackModule(NULL)
5052  ,_logCallback(NULL)
5053 //--- (end of generated code: YModule initialization)
5054 {
5055  _className = "Module";
5056 }
5057 
5059 {
5060  //--- (generated code: YModule cleanup)
5061 //--- (end of generated code: YModule cleanup)
5062 }
5063 
5064 
5065 
5066 
5067 //--- (generated code: YModule implementation)
5068 // static attributes
5072 
5074 {
5075  if(json_val->has("productName")) {
5076  _productName = json_val->getString("productName");
5077  }
5078  if(json_val->has("serialNumber")) {
5079  _serialNumber = json_val->getString("serialNumber");
5080  }
5081  if(json_val->has("productId")) {
5082  _productId = json_val->getInt("productId");
5083  }
5084  if(json_val->has("productRelease")) {
5085  _productRelease = json_val->getInt("productRelease");
5086  }
5087  if(json_val->has("firmwareRelease")) {
5088  _firmwareRelease = json_val->getString("firmwareRelease");
5089  }
5090  if(json_val->has("persistentSettings")) {
5091  _persistentSettings = (Y_PERSISTENTSETTINGS_enum)json_val->getInt("persistentSettings");
5092  }
5093  if(json_val->has("luminosity")) {
5094  _luminosity = json_val->getInt("luminosity");
5095  }
5096  if(json_val->has("beacon")) {
5097  _beacon = (Y_BEACON_enum)json_val->getInt("beacon");
5098  }
5099  if(json_val->has("upTime")) {
5100  _upTime = json_val->getLong("upTime");
5101  }
5102  if(json_val->has("usbCurrent")) {
5103  _usbCurrent = json_val->getInt("usbCurrent");
5104  }
5105  if(json_val->has("rebootCountdown")) {
5106  _rebootCountdown = json_val->getInt("rebootCountdown");
5107  }
5108  if(json_val->has("userVar")) {
5109  _userVar = json_val->getInt("userVar");
5110  }
5111  return YFunction::_parseAttr(json_val);
5112 }
5113 
5114 
5123 {
5124  string res;
5126  try {
5127  if (_cacheExpiration == 0) {
5129  {
5132  }
5133  }
5134  }
5135  res = _productName;
5136  } catch (std::exception) {
5138  throw;
5139  }
5141  return res;
5142 }
5143 
5152 {
5153  string res;
5155  try {
5156  if (_cacheExpiration == 0) {
5158  {
5161  }
5162  }
5163  }
5164  res = _serialNumber;
5165  } catch (std::exception) {
5167  throw;
5168  }
5170  return res;
5171 }
5172 
5181 {
5182  int res = 0;
5184  try {
5185  if (_cacheExpiration == 0) {
5187  {
5190  }
5191  }
5192  }
5193  res = _productId;
5194  } catch (std::exception) {
5196  throw;
5197  }
5199  return res;
5200 }
5201 
5210 {
5211  int res = 0;
5213  try {
5216  {
5219  }
5220  }
5221  }
5222  res = _productRelease;
5223  } catch (std::exception) {
5225  throw;
5226  }
5228  return res;
5229 }
5230 
5239 {
5240  string res;
5242  try {
5245  {
5248  }
5249  }
5250  }
5251  res = _firmwareRelease;
5252  } catch (std::exception) {
5254  throw;
5255  }
5257  return res;
5258 }
5259 
5269 {
5272  try {
5275  {
5278  }
5279  }
5280  }
5281  res = _persistentSettings;
5282  } catch (std::exception) {
5284  throw;
5285  }
5287  return res;
5288 }
5289 
5291 {
5292  string rest_val;
5293  int res;
5295  try {
5296  char buf[32]; sprintf(buf, "%d", newval); rest_val = string(buf);
5297  res = _setAttr("persistentSettings", rest_val);
5298  } catch (std::exception) {
5300  throw;
5301  }
5303  return res;
5304 }
5305 
5314 {
5315  int res = 0;
5317  try {
5320  {
5323  }
5324  }
5325  }
5326  res = _luminosity;
5327  } catch (std::exception) {
5329  throw;
5330  }
5332  return res;
5333 }
5334 
5348 {
5349  string rest_val;
5350  int res;
5352  try {
5353  char buf[32]; sprintf(buf, "%d", newval); rest_val = string(buf);
5354  res = _setAttr("luminosity", rest_val);
5355  } catch (std::exception) {
5357  throw;
5358  }
5360  return res;
5361 }
5362 
5371 {
5372  Y_BEACON_enum res;
5374  try {
5377  {
5379  return YModule::BEACON_INVALID;
5380  }
5381  }
5382  }
5383  res = _beacon;
5384  } catch (std::exception) {
5386  throw;
5387  }
5389  return res;
5390 }
5391 
5402 {
5403  string rest_val;
5404  int res;
5406  try {
5407  rest_val = (newval>0 ? "1" : "0");
5408  res = _setAttr("beacon", rest_val);
5409  } catch (std::exception) {
5411  throw;
5412  }
5414  return res;
5415 }
5416 
5425 {
5426  s64 res = 0;
5428  try {
5431  {
5433  return YModule::UPTIME_INVALID;
5434  }
5435  }
5436  }
5437  res = _upTime;
5438  } catch (std::exception) {
5440  throw;
5441  }
5443  return res;
5444 }
5445 
5454 {
5455  int res = 0;
5457  try {
5460  {
5463  }
5464  }
5465  }
5466  res = _usbCurrent;
5467  } catch (std::exception) {
5469  throw;
5470  }
5472  return res;
5473 }
5474 
5485 {
5486  int res = 0;
5488  try {
5491  {
5494  }
5495  }
5496  }
5497  res = _rebootCountdown;
5498  } catch (std::exception) {
5500  throw;
5501  }
5503  return res;
5504 }
5505 
5507 {
5508  string rest_val;
5509  int res;
5511  try {
5512  char buf[32]; sprintf(buf, "%d", newval); rest_val = string(buf);
5513  res = _setAttr("rebootCountdown", rest_val);
5514  } catch (std::exception) {
5516  throw;
5517  }
5519  return res;
5520 }
5521 
5531 {
5532  int res = 0;
5534  try {
5537  {
5539  return YModule::USERVAR_INVALID;
5540  }
5541  }
5542  }
5543  res = _userVar;
5544  } catch (std::exception) {
5546  throw;
5547  }
5549  return res;
5550 }
5551 
5563 int YModule::set_userVar(int newval)
5564 {
5565  string rest_val;
5566  int res;
5568  try {
5569  char buf[32]; sprintf(buf, "%d", newval); rest_val = string(buf);
5570  res = _setAttr("userVar", rest_val);
5571  } catch (std::exception) {
5573  throw;
5574  }
5576  return res;
5577 }
5578 
5601 {
5602  YModule* obj = NULL;
5603  int taken = 0;
5604  if (YAPI::_apiInitialized) {
5606  taken = 1;
5607  }try {
5608  obj = (YModule*) YFunction::_FindFromCache("Module", func);
5609  if (obj == NULL) {
5610  obj = new YModule(func);
5611  YFunction::_AddToCache("Module", func, obj);
5612  }
5613  } catch (std::exception) {
5615  throw;
5616  }
5618  return obj;
5619 }
5620 
5633 {
5634  string val;
5635  if (callback != NULL) {
5637  } else {
5639  }
5640  _valueCallbackModule = callback;
5641  // Immediately invoke value callback with current value
5642  if (callback != NULL && this->isOnline()) {
5643  val = _advertisedValue;
5644  if (!(val == "")) {
5645  this->_invokeValueCallback(val);
5646  }
5647  }
5648  return 0;
5649 }
5650 
5652 {
5653  if (_valueCallbackModule != NULL) {
5654  _valueCallbackModule(this, value);
5655  } else {
5657  }
5658  return 0;
5659 }
5660 
5671 {
5673 }
5674 
5684 {
5686 }
5687 
5697 int YModule::reboot(int secBeforeReboot)
5698 {
5699  return this->set_rebootCountdown(secBeforeReboot);
5700 }
5701 
5711 int YModule::triggerFirmwareUpdate(int secBeforeReboot)
5712 {
5713  return this->set_rebootCountdown(-secBeforeReboot);
5714 }
5715 
5731 string YModule::checkFirmware(string path,bool onlynew)
5732 {
5733  string serial;
5734  int release = 0;
5735  string tmp_res;
5736  if (onlynew) {
5737  release = atoi((this->get_firmwareRelease()).c_str());
5738  } else {
5739  release = 0;
5740  }
5741  //may throw an exception
5742  serial = this->get_serialNumber();
5743  tmp_res = YFirmwareUpdate::CheckFirmware(serial,path, release);
5744  if (_ystrpos(tmp_res, "error:") == 0) {
5745  this->_throw(YAPI_INVALID_ARGUMENT, tmp_res);
5746  }
5747  return tmp_res;
5748 }
5749 
5760 {
5761  string serial;
5762  string settings;
5763 
5764  serial = this->get_serialNumber();
5765  settings = this->get_allSettings();
5766  if ((int)(settings).size() == 0) {
5767  this->_throw(YAPI_IO_ERROR, "Unable to get device settings");
5768  settings = "error:Unable to get device settings";
5769  }
5770  return YFirmwareUpdate(serial, path, settings, force);
5771 }
5772 
5782 {
5783  return this->updateFirmwareEx(path, false);
5784 }
5785 
5795 {
5796  string settings;
5797  string json;
5798  string res;
5799  string sep;
5800  string name;
5801  string item;
5802  string t_type;
5803  string id;
5804  string url;
5805  string file_data;
5806  string file_data_bin;
5807  string temp_data_bin;
5808  string ext_settings;
5809  vector<string> filelist;
5810  vector<string> templist;
5811 
5812  settings = this->_download("api.json");
5813  if ((int)(settings).size() == 0) {
5814  return settings;
5815  }
5816  ext_settings = ", \"extras\":[";
5817  templist = this->get_functionIds("Temperature");
5818  sep = "";
5819  for (unsigned ii = 0; ii < templist.size(); ii++) {
5820  if (atoi((this->get_firmwareRelease()).c_str()) > 9000) {
5821  url = YapiWrapper::ysprintf("api/%s/sensorType", templist[ii].c_str());
5822  t_type = this->_download(url);
5823  if (t_type == "RES_NTC") {
5824  id = ( templist[ii]).substr( 11, (int)( templist[ii]).length() - 11);
5825  temp_data_bin = this->_download(YapiWrapper::ysprintf("extra.json?page=%s",id.c_str()));
5826  if ((int)(temp_data_bin).size() == 0) {
5827  return temp_data_bin;
5828  }
5829  item = YapiWrapper::ysprintf("%s{\"fid\":\"%s\", \"json\":%s}\n", sep.c_str(), templist[ii].c_str(),temp_data_bin.c_str());
5830  ext_settings = ext_settings + item;
5831  sep = ",";
5832  }
5833  }
5834  }
5835  ext_settings = ext_settings + "],\n\"files\":[";
5836  if (this->hasFunction("files")) {
5837  json = this->_download("files.json?a=dir&f=");
5838  if ((int)(json).size() == 0) {
5839  return json;
5840  }
5841  filelist = this->_json_get_array(json);
5842  sep = "";
5843  for (unsigned ii = 0; ii < filelist.size(); ii++) {
5844  name = this->_json_get_key( filelist[ii], "name");
5845  if (((int)(name).length() > 0) && !(name == "startupConf.json")) {
5846  file_data_bin = this->_download(this->_escapeAttr(name));
5847  file_data = YAPI::_bin2HexStr(file_data_bin);
5848  item = YapiWrapper::ysprintf("%s{\"name\":\"%s\", \"data\":\"%s\"}\n", sep.c_str(), name.c_str(),file_data.c_str());
5849  ext_settings = ext_settings + item;
5850  sep = ",";
5851  }
5852  }
5853  }
5854  res = "{ \"api\":" + settings + ext_settings + "]}";
5855  return res;
5856 }
5857 
5858 int YModule::loadThermistorExtra(string funcId,string jsonExtra)
5859 {
5860  vector<string> values;
5861  string url;
5862  string curr;
5863  string currTemp;
5864  int ofs = 0;
5865  int size = 0;
5866  url = "api/" + funcId + ".json?command=Z";
5867 
5868  this->_download(url);
5869  // add records in growing resistance value
5870  values = this->_json_get_array(jsonExtra);
5871  ofs = 0;
5872  size = (int)values.size();
5873  while (ofs + 1 < size) {
5874  curr = values[ofs];
5875  currTemp = values[ofs + 1];
5876  url = YapiWrapper::ysprintf("api/%s/.json?command=m%s:%s", funcId.c_str(), curr.c_str(),currTemp.c_str());
5877  this->_download(url);
5878  ofs = ofs + 2;
5879  }
5880  return YAPI_SUCCESS;
5881 }
5882 
5883 int YModule::set_extraSettings(string jsonExtra)
5884 {
5885  vector<string> extras;
5886  string functionId;
5887  string data;
5888  extras = this->_json_get_array(jsonExtra);
5889  for (unsigned ii = 0; ii < extras.size(); ii++) {
5890  functionId = this->_get_json_path( extras[ii], "fid");
5891  functionId = this->_decode_json_string(functionId);
5892  data = this->_get_json_path( extras[ii], "json");
5893  if (this->hasFunction(functionId)) {
5894  this->loadThermistorExtra(functionId, data);
5895  }
5896  }
5897  return YAPI_SUCCESS;
5898 }
5899 
5914 {
5915  string down;
5916  string json;
5917  string json_api;
5918  string json_files;
5919  string json_extra;
5920  json = settings;
5921  json_api = this->_get_json_path(json, "api");
5922  if (json_api == "") {
5923  return this->set_allSettings(settings);
5924  }
5925  json_extra = this->_get_json_path(json, "extras");
5926  if (!(json_extra == "")) {
5927  this->set_extraSettings(json_extra);
5928  }
5929  this->set_allSettings(json_api);
5930  if (this->hasFunction("files")) {
5931  vector<string> files;
5932  string res;
5933  string name;
5934  string data;
5935  down = this->_download("files.json?a=format");
5936  res = this->_get_json_path(down, "res");
5937  res = this->_decode_json_string(res);
5938  if (!(res == "ok")) {
5939  _throw(YAPI_IO_ERROR,"format failed");
5940  return YAPI_IO_ERROR;
5941  }
5942  json_files = this->_get_json_path(json, "files");
5943  files = this->_json_get_array(json_files);
5944  for (unsigned ii = 0; ii < files.size(); ii++) {
5945  name = this->_get_json_path( files[ii], "name");
5946  name = this->_decode_json_string(name);
5947  data = this->_get_json_path( files[ii], "data");
5948  data = this->_decode_json_string(data);
5949  this->_upload(name, YAPI::_hexStr2Bin(data));
5950  }
5951  }
5952  return YAPI_SUCCESS;
5953 }
5954 
5963 bool YModule::hasFunction(string funcId)
5964 {
5965  int count = 0;
5966  int i = 0;
5967  string fid;
5968 
5969  count = this->functionCount();
5970  i = 0;
5971  while (i < count) {
5972  fid = this->functionId(i);
5973  if (fid == funcId) {
5974  return true;
5975  }
5976  i = i + 1;
5977  }
5978  return false;
5979 }
5980 
5988 vector<string> YModule::get_functionIds(string funType)
5989 {
5990  int count = 0;
5991  int i = 0;
5992  string ftype;
5993  vector<string> res;
5994 
5995  count = this->functionCount();
5996  i = 0;
5997  while (i < count) {
5998  ftype = this->functionType(i);
5999  if (ftype == funType) {
6000  res.push_back(this->functionId(i));
6001  } else {
6002  ftype = this->functionBaseType(i);
6003  if (ftype == funType) {
6004  res.push_back(this->functionId(i));
6005  }
6006  }
6007  i = i + 1;
6008  }
6009  return res;
6010 }
6011 
6012 string YModule::_flattenJsonStruct(string jsoncomplex)
6013 {
6014  char errmsg[YOCTO_ERRMSG_LEN];
6015  char smallbuff[1024];
6016  char *bigbuff;
6017  int buffsize = 0;
6018  int fullsize = 0;
6019  int res = 0;
6020  string jsonflat;
6021  string jsoncomplexstr;
6022  fullsize = 0;
6023  jsoncomplexstr = jsoncomplex;
6024  res = yapiGetAllJsonKeys(jsoncomplexstr.c_str(), smallbuff, 1024, &fullsize, errmsg);
6025  if (res < 0) {
6026  this->_throw(YAPI_INVALID_ARGUMENT, string(errmsg));
6027  jsonflat = "error:" + string(errmsg);
6028  return jsonflat;
6029  }
6030  if (fullsize <= 1024) {
6031  jsonflat = string(smallbuff, fullsize);
6032  } else {
6033  fullsize = fullsize * 2;
6034  buffsize = fullsize;
6035  bigbuff = (char *)malloc(buffsize);
6036  res = yapiGetAllJsonKeys(jsoncomplexstr.c_str(), bigbuff, buffsize, &fullsize, errmsg);
6037  if (res < 0) {
6038  this->_throw(YAPI_INVALID_ARGUMENT, string(errmsg));
6039  jsonflat = "error:" + string(errmsg);
6040  } else {
6041  jsonflat = string(bigbuff, fullsize);
6042  }
6043  free(bigbuff);
6044  }
6045  return jsonflat;
6046 }
6047 
6048 int YModule::calibVersion(string cparams)
6049 {
6050  if (cparams == "0,") {
6051  return 3;
6052  }
6053  if (_ystrpos(cparams, ",") >= 0) {
6054  if (_ystrpos(cparams, " ") > 0) {
6055  return 3;
6056  } else {
6057  return 1;
6058  }
6059  }
6060  if (cparams == "" || cparams == "0") {
6061  return 1;
6062  }
6063  if (((int)(cparams).length() < 2) || (_ystrpos(cparams, ".") >= 0)) {
6064  return 0;
6065  } else {
6066  return 2;
6067  }
6068 }
6069 
6070 int YModule::calibScale(string unit_name,string sensorType)
6071 {
6072  if (unit_name == "g" || unit_name == "gauss" || unit_name == "W") {
6073  return 1000;
6074  }
6075  if (unit_name == "C") {
6076  if (sensorType == "") {
6077  return 16;
6078  }
6079  if (atoi((sensorType).c_str()) < 8) {
6080  return 16;
6081  } else {
6082  return 100;
6083  }
6084  }
6085  if (unit_name == "m" || unit_name == "deg") {
6086  return 10;
6087  }
6088  return 1;
6089 }
6090 
6091 int YModule::calibOffset(string unit_name)
6092 {
6093  if (unit_name == "% RH" || unit_name == "mbar" || unit_name == "lx") {
6094  return 0;
6095  }
6096  return 32767;
6097 }
6098 
6099 string YModule::calibConvert(string param,string currentFuncValue,string unit_name,string sensorType)
6100 {
6101  int paramVer = 0;
6102  int funVer = 0;
6103  int funScale = 0;
6104  int funOffset = 0;
6105  int paramScale = 0;
6106  int paramOffset = 0;
6107  vector<int> words;
6108  vector<string> words_str;
6109  vector<double> calibData;
6110  vector<int> iCalib;
6111  int calibType = 0;
6112  int i = 0;
6113  int maxSize = 0;
6114  double ratio = 0.0;
6115  int nPoints = 0;
6116  double wordVal = 0.0;
6117  // Initial guess for parameter encoding
6118  paramVer = this->calibVersion(param);
6119  funVer = this->calibVersion(currentFuncValue);
6120  funScale = this->calibScale(unit_name, sensorType);
6121  funOffset = this->calibOffset(unit_name);
6122  paramScale = funScale;
6123  paramOffset = funOffset;
6124  if (funVer < 3) {
6125  // Read the effective device scale if available
6126  if (funVer == 2) {
6127  words = YAPI::_decodeWords(currentFuncValue);
6128  if ((words[0] == 1366) && (words[1] == 12500)) {
6129  // Yocto-3D RefFrame used a special encoding
6130  funScale = 1;
6131  funOffset = 0;
6132  } else {
6133  funScale = words[1];
6134  funOffset = words[0];
6135  }
6136  } else {
6137  if (funVer == 1) {
6138  if (currentFuncValue == "" || (atoi((currentFuncValue).c_str()) > 10)) {
6139  funScale = 0;
6140  }
6141  }
6142  }
6143  }
6144  calibData.clear();
6145  calibType = 0;
6146  if (paramVer < 3) {
6147  // Handle old 16 bit parameters formats
6148  if (paramVer == 2) {
6149  words = YAPI::_decodeWords(param);
6150  if ((words[0] == 1366) && (words[1] == 12500)) {
6151  // Yocto-3D RefFrame used a special encoding
6152  paramScale = 1;
6153  paramOffset = 0;
6154  } else {
6155  paramScale = words[1];
6156  paramOffset = words[0];
6157  }
6158  if (((int)words.size() >= 3) && (words[2] > 0)) {
6159  maxSize = 3 + 2 * ((words[2]) % (10));
6160  if (maxSize > (int)words.size()) {
6161  maxSize = (int)words.size();
6162  }
6163  i = 3;
6164  while (i < maxSize) {
6165  calibData.push_back((double) words[i]);
6166  i = i + 1;
6167  }
6168  }
6169  } else {
6170  if (paramVer == 1) {
6171  words_str = _strsplit(param,',');
6172  for (unsigned ii = 0; ii < words_str.size(); ii++) {
6173  words.push_back(atoi((words_str[ii]).c_str()));
6174  }
6175  if (param == "" || (words[0] > 10)) {
6176  paramScale = 0;
6177  }
6178  if (((int)words.size() > 0) && (words[0] > 0)) {
6179  maxSize = 1 + 2 * ((words[0]) % (10));
6180  if (maxSize > (int)words.size()) {
6181  maxSize = (int)words.size();
6182  }
6183  i = 1;
6184  while (i < maxSize) {
6185  calibData.push_back((double) words[i]);
6186  i = i + 1;
6187  }
6188  }
6189  } else {
6190  if (paramVer == 0) {
6191  ratio = atof((param).c_str());
6192  if (ratio > 0) {
6193  calibData.push_back(0.0);
6194  calibData.push_back(0.0);
6195  calibData.push_back(floor(65535 / ratio+0.5));
6196  calibData.push_back(65535.0);
6197  }
6198  }
6199  }
6200  }
6201  i = 0;
6202  while (i < (int)calibData.size()) {
6203  if (paramScale > 0) {
6204  // scalar decoding
6205  calibData[i] = (calibData[i] - paramOffset) / paramScale;
6206  } else {
6207  // floating-point decoding
6208  calibData[i] = YAPI::_decimalToDouble((int) floor(calibData[i]+0.5));
6209  }
6210  i = i + 1;
6211  }
6212  } else {
6213  // Handle latest 32bit parameter format
6214  iCalib = YAPI::_decodeFloats(param);
6215  calibType = (int) floor(iCalib[0] / 1000.0+0.5);
6216  if (calibType >= 30) {
6217  calibType = calibType - 30;
6218  }
6219  i = 1;
6220  while (i < (int)iCalib.size()) {
6221  calibData.push_back(iCalib[i] / 1000.0);
6222  i = i + 1;
6223  }
6224  }
6225  if (funVer >= 3) {
6226  // Encode parameters in new format
6227  if ((int)calibData.size() == 0) {
6228  param = "0,";
6229  } else {
6230  param = YapiWrapper::ysprintf("%d",30 + calibType);
6231  i = 0;
6232  while (i < (int)calibData.size()) {
6233  if (((i) & (1)) > 0) {
6234  param = param + ":";
6235  } else {
6236  param = param + " ";
6237  }
6238  param = param + YapiWrapper::ysprintf("%d",(int) floor(calibData[i] * 1000.0 / 1000.0+0.5));
6239  i = i + 1;
6240  }
6241  param = param + ",";
6242  }
6243  } else {
6244  if (funVer >= 1) {
6245  // Encode parameters for older devices
6246  nPoints = (((int)calibData.size()) / (2));
6247  param = YapiWrapper::ysprintf("%d",nPoints);
6248  i = 0;
6249  while (i < 2 * nPoints) {
6250  if (funScale == 0) {
6251  wordVal = YAPI::_doubleToDecimal((int) floor(calibData[i]+0.5));
6252  } else {
6253  wordVal = calibData[i] * funScale + funOffset;
6254  }
6255  param = param + "," + YapiWrapper::ysprintf("%f",floor(wordVal+0.5));
6256  i = i + 1;
6257  }
6258  } else {
6259  // Initial V0 encoding used for old Yocto-Light
6260  if ((int)calibData.size() == 4) {
6261  param = YapiWrapper::ysprintf("%f",floor(1000 * (calibData[3] - calibData[1]) / calibData[2] - calibData[0]+0.5));
6262  }
6263  }
6264  }
6265  return param;
6266 }
6267 
6279 int YModule::set_allSettings(string settings)
6280 {
6281  vector<string> restoreLast;
6282  string old_json_flat;
6283  vector<string> old_dslist;
6284  vector<string> old_jpath;
6285  vector<int> old_jpath_len;
6286  vector<string> old_val_arr;
6287  string actualSettings;
6288  vector<string> new_dslist;
6289  vector<string> new_jpath;
6290  vector<int> new_jpath_len;
6291  vector<string> new_val_arr;
6292  int cpos = 0;
6293  int eqpos = 0;
6294  int leng = 0;
6295  int i = 0;
6296  int j = 0;
6297  string njpath;
6298  string jpath;
6299  string fun;
6300  string attr;
6301  string value;
6302  string url;
6303  string tmp;
6304  string new_calib;
6305  string sensorType;
6306  string unit_name;
6307  string newval;
6308  string oldval;
6309  string old_calib;
6310  string each_str;
6311  bool do_update = 0;
6312  bool found = 0;
6313  tmp = settings;
6314  tmp = this->_get_json_path(tmp, "api");
6315  if (!(tmp == "")) {
6316  settings = tmp;
6317  }
6318  oldval = "";
6319  newval = "";
6320  old_json_flat = this->_flattenJsonStruct(settings);
6321  old_dslist = this->_json_get_array(old_json_flat);
6322  for (unsigned ii = 0; ii < old_dslist.size(); ii++) {
6323  each_str = this->_json_get_string(old_dslist[ii]);
6324  // split json path and attr
6325  leng = (int)(each_str).length();
6326  eqpos = _ystrpos(each_str, "=");
6327  if ((eqpos < 0) || (leng == 0)) {
6328  this->_throw(YAPI_INVALID_ARGUMENT, "Invalid settings");
6329  return YAPI_INVALID_ARGUMENT;
6330  }
6331  jpath = (each_str).substr( 0, eqpos);
6332  eqpos = eqpos + 1;
6333  value = (each_str).substr( eqpos, leng - eqpos);
6334  old_jpath.push_back(jpath);
6335  old_jpath_len.push_back((int)(jpath).length());
6336  old_val_arr.push_back(value);
6337  }
6338 
6339  actualSettings = this->_download("api.json");
6340  actualSettings = this->_flattenJsonStruct(actualSettings);
6341  new_dslist = this->_json_get_array(actualSettings);
6342  for (unsigned ii = 0; ii < new_dslist.size(); ii++) {
6343  // remove quotes
6344  each_str = this->_json_get_string(new_dslist[ii]);
6345  // split json path and attr
6346  leng = (int)(each_str).length();
6347  eqpos = _ystrpos(each_str, "=");
6348  if ((eqpos < 0) || (leng == 0)) {
6349  this->_throw(YAPI_INVALID_ARGUMENT, "Invalid settings");
6350  return YAPI_INVALID_ARGUMENT;
6351  }
6352  jpath = (each_str).substr( 0, eqpos);
6353  eqpos = eqpos + 1;
6354  value = (each_str).substr( eqpos, leng - eqpos);
6355  new_jpath.push_back(jpath);
6356  new_jpath_len.push_back((int)(jpath).length());
6357  new_val_arr.push_back(value);
6358  }
6359  i = 0;
6360  while (i < (int)new_jpath.size()) {
6361  njpath = new_jpath[i];
6362  leng = (int)(njpath).length();
6363  cpos = _ystrpos(njpath, "/");
6364  if ((cpos < 0) || (leng == 0)) {
6365  continue;
6366  }
6367  fun = (njpath).substr( 0, cpos);
6368  cpos = cpos + 1;
6369  attr = (njpath).substr( cpos, leng - cpos);
6370  do_update = true;
6371  if (fun == "services") {
6372  do_update = false;
6373  }
6374  if ((do_update) && (attr == "firmwareRelease")) {
6375  do_update = false;
6376  }
6377  if ((do_update) && (attr == "usbCurrent")) {
6378  do_update = false;
6379  }
6380  if ((do_update) && (attr == "upTime")) {
6381  do_update = false;
6382  }
6383  if ((do_update) && (attr == "persistentSettings")) {
6384  do_update = false;
6385  }
6386  if ((do_update) && (attr == "adminPassword")) {
6387  do_update = false;
6388  }
6389  if ((do_update) && (attr == "userPassword")) {
6390  do_update = false;
6391  }
6392  if ((do_update) && (attr == "rebootCountdown")) {
6393  do_update = false;
6394  }
6395  if ((do_update) && (attr == "advertisedValue")) {
6396  do_update = false;
6397  }
6398  if ((do_update) && (attr == "poeCurrent")) {
6399  do_update = false;
6400  }
6401  if ((do_update) && (attr == "readiness")) {
6402  do_update = false;
6403  }
6404  if ((do_update) && (attr == "ipAddress")) {
6405  do_update = false;
6406  }
6407  if ((do_update) && (attr == "subnetMask")) {
6408  do_update = false;
6409  }
6410  if ((do_update) && (attr == "router")) {
6411  do_update = false;
6412  }
6413  if ((do_update) && (attr == "linkQuality")) {
6414  do_update = false;
6415  }
6416  if ((do_update) && (attr == "ssid")) {
6417  do_update = false;
6418  }
6419  if ((do_update) && (attr == "channel")) {
6420  do_update = false;
6421  }
6422  if ((do_update) && (attr == "security")) {
6423  do_update = false;
6424  }
6425  if ((do_update) && (attr == "message")) {
6426  do_update = false;
6427  }
6428  if ((do_update) && (attr == "currentValue")) {
6429  do_update = false;
6430  }
6431  if ((do_update) && (attr == "currentRawValue")) {
6432  do_update = false;
6433  }
6434  if ((do_update) && (attr == "currentRunIndex")) {
6435  do_update = false;
6436  }
6437  if ((do_update) && (attr == "pulseTimer")) {
6438  do_update = false;
6439  }
6440  if ((do_update) && (attr == "lastTimePressed")) {
6441  do_update = false;
6442  }
6443  if ((do_update) && (attr == "lastTimeReleased")) {
6444  do_update = false;
6445  }
6446  if ((do_update) && (attr == "filesCount")) {
6447  do_update = false;
6448  }
6449  if ((do_update) && (attr == "freeSpace")) {
6450  do_update = false;
6451  }
6452  if ((do_update) && (attr == "timeUTC")) {
6453  do_update = false;
6454  }
6455  if ((do_update) && (attr == "rtcTime")) {
6456  do_update = false;
6457  }
6458  if ((do_update) && (attr == "unixTime")) {
6459  do_update = false;
6460  }
6461  if ((do_update) && (attr == "dateTime")) {
6462  do_update = false;
6463  }
6464  if ((do_update) && (attr == "rawValue")) {
6465  do_update = false;
6466  }
6467  if ((do_update) && (attr == "lastMsg")) {
6468  do_update = false;
6469  }
6470  if ((do_update) && (attr == "delayedPulseTimer")) {
6471  do_update = false;
6472  }
6473  if ((do_update) && (attr == "rxCount")) {
6474  do_update = false;
6475  }
6476  if ((do_update) && (attr == "txCount")) {
6477  do_update = false;
6478  }
6479  if ((do_update) && (attr == "msgCount")) {
6480  do_update = false;
6481  }
6482  if (do_update) {
6483  do_update = false;
6484  newval = new_val_arr[i];
6485  j = 0;
6486  found = false;
6487  while ((j < (int)old_jpath.size()) && !(found)) {
6488  if ((new_jpath_len[i] == old_jpath_len[j]) && (new_jpath[i] == old_jpath[j])) {
6489  found = true;
6490  oldval = old_val_arr[j];
6491  if (!(newval == oldval)) {
6492  do_update = true;
6493  }
6494  }
6495  j = j + 1;
6496  }
6497  }
6498  if (do_update) {
6499  if (attr == "calibrationParam") {
6500  old_calib = "";
6501  unit_name = "";
6502  sensorType = "";
6503  new_calib = newval;
6504  j = 0;
6505  found = false;
6506  while ((j < (int)old_jpath.size()) && !(found)) {
6507  if ((new_jpath_len[i] == old_jpath_len[j]) && (new_jpath[i] == old_jpath[j])) {
6508  found = true;
6509  old_calib = old_val_arr[j];
6510  }
6511  j = j + 1;
6512  }
6513  tmp = fun + "/unit";
6514  j = 0;
6515  found = false;
6516  while ((j < (int)new_jpath.size()) && !(found)) {
6517  if (tmp == new_jpath[j]) {
6518  found = true;
6519  unit_name = new_val_arr[j];
6520  }
6521  j = j + 1;
6522  }
6523  tmp = fun + "/sensorType";
6524  j = 0;
6525  found = false;
6526  while ((j < (int)new_jpath.size()) && !(found)) {
6527  if (tmp == new_jpath[j]) {
6528  found = true;
6529  sensorType = new_val_arr[j];
6530  }
6531  j = j + 1;
6532  }
6533  newval = this->calibConvert(old_calib, new_val_arr[i], unit_name, sensorType);
6534  url = "api/" + fun + ".json?" + attr + "=" + this->_escapeAttr(newval);
6535  this->_download(url);
6536  } else {
6537  url = "api/" + fun + ".json?" + attr + "=" + this->_escapeAttr(oldval);
6538  if (attr == "resolution") {
6539  restoreLast.push_back(url);
6540  } else {
6541  this->_download(url);
6542  }
6543  }
6544  }
6545  i = i + 1;
6546  }
6547  for (unsigned ii = 0; ii < restoreLast.size(); ii++) {
6548  this->_download(restoreLast[ii]);
6549  }
6550  this->clearCache();
6551  return YAPI_SUCCESS;
6552 }
6553 
6563 string YModule::download(string pathname)
6564 {
6565  return this->_download(pathname);
6566 }
6567 
6576 {
6577  return this->_download("icon2d.png");
6578 }
6579 
6588 {
6589  string content;
6590 
6591  content = this->_download("logs.txt");
6592  return content;
6593 }
6594 
6606 int YModule::log(string text)
6607 {
6608  return this->_upload("logs.txt", text);
6609 }
6610 
6618 vector<string> YModule::get_subDevices(void)
6619 {
6620  char errmsg[YOCTO_ERRMSG_LEN];
6621  char smallbuff[1024];
6622  char *bigbuff;
6623  int buffsize = 0;
6624  int fullsize = 0;
6625  int yapi_res = 0;
6626  string subdevice_list;
6627  vector<string> subdevices;
6628  string serial;
6629 
6630  serial = this->get_serialNumber();
6631  fullsize = 0;
6632  yapi_res = yapiGetSubdevices(serial.c_str(), smallbuff, 1024, &fullsize, errmsg);
6633  if (yapi_res < 0) {
6634  return subdevices;
6635  }
6636  if (fullsize <= 1024) {
6637  subdevice_list = string(smallbuff, yapi_res);
6638  } else {
6639  buffsize = fullsize;
6640  bigbuff = (char *)malloc(buffsize);
6641  yapi_res = yapiGetSubdevices(serial.c_str(), bigbuff, buffsize, &fullsize, errmsg);
6642  if (yapi_res < 0) {
6643  free(bigbuff);
6644  return subdevices;
6645  } else {
6646  subdevice_list = string(bigbuff, yapi_res);
6647  }
6648  free(bigbuff);
6649  }
6650  if (!(subdevice_list == "")) {
6651  subdevices = _strsplit(subdevice_list,',');
6652  }
6653  return subdevices;
6654 }
6655 
6664 {
6665  char errmsg[YOCTO_ERRMSG_LEN];
6666  char hubserial[YOCTO_SERIAL_LEN];
6667  int pathsize = 0;
6668  int yapi_res = 0;
6669  string serial;
6670 
6671  serial = this->get_serialNumber();
6672  // retrieve device object
6673  pathsize = 0;
6674  yapi_res = yapiGetDevicePathEx(serial.c_str(), hubserial, NULL, 0, &pathsize, errmsg);
6675  if (yapi_res < 0) {
6676  return "";
6677  }
6678  return string(hubserial);
6679 }
6680 
6687 string YModule::get_url(void)
6688 {
6689  char errmsg[YOCTO_ERRMSG_LEN];
6690  char path[1024];
6691  int pathsize = 0;
6692  int yapi_res = 0;
6693  string serial;
6694 
6695  serial = this->get_serialNumber();
6696  // retrieve device object
6697  pathsize = 0;
6698  yapi_res = yapiGetDevicePathEx(serial.c_str(), NULL, path, 1024, &pathsize, errmsg);
6699  if (yapi_res < 0) {
6700  return "";
6701  }
6702  return string(path);
6703 }
6704 
6706 {
6707  string hwid;
6708 
6709  if(YISERR(_nextFunction(hwid)) || hwid=="") {
6710  return NULL;
6711  }
6712  return YModule::FindModule(hwid);
6713 }
6714 
6716 {
6717  vector<YFUN_DESCR> v_fundescr;
6718  YDEV_DESCR ydevice;
6719  string serial, funcId, funcName, funcVal, errmsg;
6720 
6721  if(YISERR(YapiWrapper::getFunctionsByClass("Module", 0, v_fundescr, sizeof(YFUN_DESCR), errmsg)) ||
6722  v_fundescr.size() == 0 ||
6723  YISERR(YapiWrapper::getFunctionInfo(v_fundescr[0], ydevice, serial, funcId, funcName, funcVal, errmsg))) {
6724  return NULL;
6725  }
6726  return YModule::FindModule(serial+"."+funcId);
6727 }
6728 
6729 //--- (end of generated code: YModule implementation)
6730 
6731 // Return a string that describes the function (class and logical name or hardware id)
6733 {
6734  YFUN_DESCR fundescr,moddescr;
6735  YDEV_DESCR devdescr;
6736  string errmsg, serial, funcId, funcName, funcValue;
6737  string mod_serial, mod_funcId,mod_funcname;
6738 
6740  fundescr = YapiWrapper::getFunction(_className, _func, errmsg);
6741  if(!YISERR(fundescr) && !YISERR(YapiWrapper::getFunctionInfo(fundescr, devdescr, serial, funcId, funcName, funcValue, errmsg))) {
6742  moddescr = YapiWrapper::getFunction("Module", serial, errmsg);
6743  if(!YISERR(moddescr) && !YISERR(YapiWrapper::getFunctionInfo(moddescr, devdescr, mod_serial, mod_funcId, mod_funcname, funcValue, errmsg))) {
6744  if(mod_funcname!="") {
6746  return mod_funcname;
6747  }
6748  }
6750  return serial;
6751  }
6753  return Y_FRIENDLYNAME_INVALID;
6754 }
6755 
6756 
6757 
6758 
6760 {
6761  // do not take CS on purpose (called for update device list)
6762  _serialNumber = (string) infos->serial;
6763  _productName = (string) infos->productname;
6764  _productId = infos->deviceid;
6766 }
6767 
6768 
6769 // Return the properties of the nth function of our device
6770 YRETCODE YModule::_getFunction(int idx, string& serial, string& funcId, string& baseType, string& funcName, string& funcVal, string& errmsg)
6771 {
6772  vector<YFUN_DESCR> *functions;
6773  YDevice *dev;
6774  int res;
6775  YFUN_DESCR fundescr;
6776  YDEV_DESCR devdescr;
6777 
6778  // retrieve device object
6779  res = _getDevice(dev, errmsg);
6780  if(YISERR(res)) {
6781  _throw((YRETCODE)res, errmsg);
6782  return (YRETCODE)res;
6783  }
6784 
6785  // get reference to all functions from the device
6786  res = dev->getFunctions(&functions, errmsg);
6787  if(YISERR(res)) return (YRETCODE)res;
6788 
6789  // get latest function info from yellow pages
6790  fundescr = functions->at(idx);
6791  res = YapiWrapper::getFunctionInfoEx(fundescr, devdescr, serial, funcId, baseType, funcName, funcVal, errmsg);
6792  if(YISERR(res)) return (YRETCODE)res;
6793 
6794  return YAPI_SUCCESS;
6795 }
6796 
6797 // Retrieve the number of functions (beside "module") in the device
6799 {
6800  vector<YFUN_DESCR> *functions;
6801  YDevice *dev;
6802  string errmsg;
6803  int res;
6804 
6806  res = _getDevice(dev, errmsg);
6807  if(YISERR(res)) {
6809  _throw((YRETCODE)res, errmsg);
6810  return (YRETCODE)res;
6811  }
6812  res = dev->getFunctions(&functions, errmsg);
6813  if(YISERR(res)) {
6815  _throw((YRETCODE)res, errmsg);
6816  return (YRETCODE)res;
6817  }
6819  return (int)functions->size();
6820 }
6821 
6822 // Retrieve the Id of the nth function (beside "module") in the device
6823 string YModule::functionId(int functionIndex)
6824 {
6825  string serial, funcId, funcName, basetype, funcVal, errmsg;
6826  int res;
6827 
6829  try {
6830  res = _getFunction(functionIndex, serial, funcId, basetype, funcName, funcVal, errmsg);
6831  } catch (std::exception) {
6833  throw;
6834  }
6836  if(YISERR(res)) {
6837  _throw((YRETCODE)res, errmsg);
6838  return YAPI_INVALID_STRING;
6839  }
6840  return funcId;
6841 }
6842 
6843 // Retrieve the logical name of the nth function (beside "module") in the device
6844 string YModule::functionName(int functionIndex)
6845 {
6846  string serial, funcId, basetype, funcName, funcVal, errmsg;
6847  int res;
6849  try {
6850  res = _getFunction(functionIndex, serial, funcId, basetype, funcName, funcVal, errmsg);
6851  } catch (std::exception) {
6853  throw;
6854  }
6856  if(YISERR(res)) {
6857  _throw((YRETCODE)res, errmsg);
6858  return YAPI_INVALID_STRING;
6859  }
6860 
6861  return funcName;
6862 }
6863 
6864 // Retrieve the advertised value of the nth function (beside "module") in the device
6865 string YModule::functionValue(int functionIndex)
6866 {
6867  string serial, funcId, basetype, funcName, funcVal, errmsg;
6868  int res;
6870  try {
6871  res = _getFunction(functionIndex, serial, funcId, basetype, funcName, funcVal, errmsg);
6872  } catch (std::exception) {
6874  throw;
6875  }
6877  if(YISERR(res)) {
6878  _throw((YRETCODE)res, errmsg);
6879  return YAPI_INVALID_STRING;
6880  }
6881 
6882  return funcVal;
6883 }
6884 
6885 
6886 // Retrieve the Id of the nth function (beside "module") in the device
6887 string YModule::functionType(int functionIndex)
6888 {
6889  string serial, funcId, basetype, funcName, funcVal, errmsg;
6890  char buffer[YOCTO_FUNCTION_LEN], *d = buffer;
6891  const char *p;
6892  int res;
6894  try {
6895  res = _getFunction(functionIndex, serial, funcId, basetype, funcName, funcVal, errmsg);
6896  } catch (std::exception) {
6898  throw;
6899  }
6901  if (YISERR(res)) {
6902  _throw((YRETCODE)res, errmsg);
6903  return YAPI_INVALID_STRING;
6904  }
6905  p = funcId.c_str();
6906  *d++ = *p++ & 0xdf;
6907  while (*p && (*p <'0' || *p >'9')) {
6908  *d++ = *p++;
6909  }
6910  *d = 0;
6911  return string(buffer);
6912 }
6913 
6914 // Retrieve the Id of the nth function (beside "module") in the device
6915 string YModule::functionBaseType(int functionIndex)
6916 {
6917  string serial, funcId, basetype, funcName, funcVal, errmsg;
6918  int res;
6920  try {
6921  res = _getFunction(functionIndex, serial, funcId, basetype, funcName, funcVal, errmsg);
6922  } catch (std::exception) {
6924  throw;
6925  }
6927  if (YISERR(res)) {
6928  _throw((YRETCODE)res, errmsg);
6929  return YAPI_INVALID_STRING;
6930  }
6931 
6932  return basetype;
6933 }
6934 
6935 
6945 {
6947  _logCallback = callback;
6950 }
6951 
6953 {
6954  YModuleLogCallback res;
6956  res = _logCallback;
6958  return res;
6959 }
6960 
6961 
6962 //--- (generated code: YModule functions)
6963 //--- (end of generated code: YModule functions)
6964 
6965 
6966 
6967 
6968 YSensor::YSensor(const string& func): YFunction(func)
6969 //--- (generated code: YSensor initialization)
6970  ,_unit(UNIT_INVALID)
6971  ,_currentValue(CURRENTVALUE_INVALID)
6972  ,_lowestValue(LOWESTVALUE_INVALID)
6973  ,_highestValue(HIGHESTVALUE_INVALID)
6974  ,_currentRawValue(CURRENTRAWVALUE_INVALID)
6975  ,_logFrequency(LOGFREQUENCY_INVALID)
6976  ,_reportFrequency(REPORTFREQUENCY_INVALID)
6977  ,_advMode(ADVMODE_INVALID)
6978  ,_calibrationParam(CALIBRATIONPARAM_INVALID)
6979  ,_resolution(RESOLUTION_INVALID)
6980  ,_sensorState(SENSORSTATE_INVALID)
6981  ,_valueCallbackSensor(NULL)
6982  ,_timedReportCallbackSensor(NULL)
6983  ,_prevTimedReport(0.0)
6984  ,_iresol(0.0)
6985  ,_offset(0.0)
6986  ,_scale(0.0)
6987  ,_decexp(0.0)
6988  ,_isScal(0)
6989  ,_isScal32(0)
6990  ,_caltyp(0)
6991 //--- (end of generated code: YSensor initialization)
6992 {
6993  _className = "Sensor";
6994 }
6995 
6997 {
6998 //--- (generated code: YSensor cleanup)
6999 //--- (end of generated code: YSensor cleanup)
7000 }
7001 
7002 
7003 //--- (generated code: YSensor implementation)
7004 // static attributes
7014 
7016 {
7017  if(json_val->has("unit")) {
7018  _unit = json_val->getString("unit");
7019  }
7020  if(json_val->has("currentValue")) {
7021  _currentValue = floor(json_val->getDouble("currentValue") * 1000.0 / 65536.0 + 0.5) / 1000.0;
7022  }
7023  if(json_val->has("lowestValue")) {
7024  _lowestValue = floor(json_val->getDouble("lowestValue") * 1000.0 / 65536.0 + 0.5) / 1000.0;
7025  }
7026  if(json_val->has("highestValue")) {
7027  _highestValue = floor(json_val->getDouble("highestValue") * 1000.0 / 65536.0 + 0.5) / 1000.0;
7028  }
7029  if(json_val->has("currentRawValue")) {
7030  _currentRawValue = floor(json_val->getDouble("currentRawValue") * 1000.0 / 65536.0 + 0.5) / 1000.0;
7031  }
7032  if(json_val->has("logFrequency")) {
7033  _logFrequency = json_val->getString("logFrequency");
7034  }
7035  if(json_val->has("reportFrequency")) {
7036  _reportFrequency = json_val->getString("reportFrequency");
7037  }
7038  if(json_val->has("advMode")) {
7039  _advMode = (Y_ADVMODE_enum)json_val->getInt("advMode");
7040  }
7041  if(json_val->has("calibrationParam")) {
7042  _calibrationParam = json_val->getString("calibrationParam");
7043  }
7044  if(json_val->has("resolution")) {
7045  _resolution = floor(json_val->getDouble("resolution") * 1000.0 / 65536.0 + 0.5) / 1000.0;
7046  }
7047  if(json_val->has("sensorState")) {
7048  _sensorState = json_val->getInt("sensorState");
7049  }
7050  return YFunction::_parseAttr(json_val);
7051 }
7052 
7053 
7061 string YSensor::get_unit(void)
7062 {
7063  string res;
7065  try {
7068  {
7070  return YSensor::UNIT_INVALID;
7071  }
7072  }
7073  }
7074  res = _unit;
7075  } catch (std::exception) {
7077  throw;
7078  }
7080  return res;
7081 }
7082 
7092 {
7093  double res = 0.0;
7095  try {
7098  {
7101  }
7102  }
7103  }
7104  res = this->_applyCalibration(_currentRawValue);
7105  if (res == YSensor::CURRENTVALUE_INVALID) {
7106  res = _currentValue;
7107  }
7108  res = res * _iresol;
7109  res = floor(res+0.5) / _iresol;
7110  } catch (std::exception) {
7112  throw;
7113  }
7115  return res;
7116 }
7117 
7128 int YSensor::set_lowestValue(double newval)
7129 {
7130  string rest_val;
7131  int res;
7133  try {
7134  char buf[32]; sprintf(buf,"%d", (int)floor(newval * 65536.0 + 0.5)); rest_val = string(buf);
7135  res = _setAttr("lowestValue", rest_val);
7136  } catch (std::exception) {
7138  throw;
7139  }
7141  return res;
7142 }
7143 
7154 {
7155  double res = 0.0;
7157  try {
7160  {
7163  }
7164  }
7165  }
7166  res = _lowestValue * _iresol;
7167  res = floor(res+0.5) / _iresol;
7168  } catch (std::exception) {
7170  throw;
7171  }
7173  return res;
7174 }
7175 
7186 int YSensor::set_highestValue(double newval)
7187 {
7188  string rest_val;
7189  int res;
7191  try {
7192  char buf[32]; sprintf(buf,"%d", (int)floor(newval * 65536.0 + 0.5)); rest_val = string(buf);
7193  res = _setAttr("highestValue", rest_val);
7194  } catch (std::exception) {
7196  throw;
7197  }
7199  return res;
7200 }
7201 
7212 {
7213  double res = 0.0;
7215  try {
7218  {
7221  }
7222  }
7223  }
7224  res = _highestValue * _iresol;
7225  res = floor(res+0.5) / _iresol;
7226  } catch (std::exception) {
7228  throw;
7229  }
7231  return res;
7232 }
7233 
7244 {
7245  double res = 0.0;
7247  try {
7250  {
7253  }
7254  }
7255  }
7256  res = _currentRawValue;
7257  } catch (std::exception) {
7259  throw;
7260  }
7262  return res;
7263 }
7264 
7275 {
7276  string res;
7278  try {
7281  {
7284  }
7285  }
7286  }
7287  res = _logFrequency;
7288  } catch (std::exception) {
7290  throw;
7291  }
7293  return res;
7294 }
7295 
7309 int YSensor::set_logFrequency(const string& newval)
7310 {
7311  string rest_val;
7312  int res;
7314  try {
7315  rest_val = newval;
7316  res = _setAttr("logFrequency", rest_val);
7317  } catch (std::exception) {
7319  throw;
7320  }
7322  return res;
7323 }
7324 
7335 {
7336  string res;
7338  try {
7341  {
7344  }
7345  }
7346  }
7347  res = _reportFrequency;
7348  } catch (std::exception) {
7350  throw;
7351  }
7353  return res;
7354 }
7355 
7369 int YSensor::set_reportFrequency(const string& newval)
7370 {
7371  string rest_val;
7372  int res;
7374  try {
7375  rest_val = newval;
7376  res = _setAttr("reportFrequency", rest_val);
7377  } catch (std::exception) {
7379  throw;
7380  }
7382  return res;
7383 }
7384 
7394 {
7395  Y_ADVMODE_enum res;
7397  try {
7400  {
7402  return YSensor::ADVMODE_INVALID;
7403  }
7404  }
7405  }
7406  res = _advMode;
7407  } catch (std::exception) {
7409  throw;
7410  }
7412  return res;
7413 }
7414 
7426 {
7427  string rest_val;
7428  int res;
7430  try {
7431  char buf[32]; sprintf(buf, "%d", newval); rest_val = string(buf);
7432  res = _setAttr("advMode", rest_val);
7433  } catch (std::exception) {
7435  throw;
7436  }
7438  return res;
7439 }
7440 
7442 {
7443  string res;
7445  try {
7448  {
7451  }
7452  }
7453  }
7454  res = _calibrationParam;
7455  } catch (std::exception) {
7457  throw;
7458  }
7460  return res;
7461 }
7462 
7463 int YSensor::set_calibrationParam(const string& newval)
7464 {
7465  string rest_val;
7466  int res;
7468  try {
7469  rest_val = newval;
7470  res = _setAttr("calibrationParam", rest_val);
7471  } catch (std::exception) {
7473  throw;
7474  }
7476  return res;
7477 }
7478 
7489 int YSensor::set_resolution(double newval)
7490 {
7491  string rest_val;
7492  int res;
7494  try {
7495  char buf[32]; sprintf(buf,"%d", (int)floor(newval * 65536.0 + 0.5)); rest_val = string(buf);
7496  res = _setAttr("resolution", rest_val);
7497  } catch (std::exception) {
7499  throw;
7500  }
7502  return res;
7503 }
7504 
7514 {
7515  double res = 0.0;
7517  try {
7520  {
7523  }
7524  }
7525  }
7526  res = _resolution;
7527  } catch (std::exception) {
7529  throw;
7530  }
7532  return res;
7533 }
7534 
7546 {
7547  int res = 0;
7549  try {
7552  {
7555  }
7556  }
7557  }
7558  res = _sensorState;
7559  } catch (std::exception) {
7561  throw;
7562  }
7564  return res;
7565 }
7566 
7595 {
7596  YSensor* obj = NULL;
7597  int taken = 0;
7598  if (YAPI::_apiInitialized) {
7600  taken = 1;
7601  }try {
7602  obj = (YSensor*) YFunction::_FindFromCache("Sensor", func);
7603  if (obj == NULL) {
7604  obj = new YSensor(func);
7605  YFunction::_AddToCache("Sensor", func, obj);
7606  }
7607  } catch (std::exception) {
7609  throw;
7610  }
7612  return obj;
7613 }
7614 
7627 {
7628  string val;
7629  if (callback != NULL) {
7631  } else {
7633  }
7634  _valueCallbackSensor = callback;
7635  // Immediately invoke value callback with current value
7636  if (callback != NULL && this->isOnline()) {
7637  val = _advertisedValue;
7638  if (!(val == "")) {
7639  this->_invokeValueCallback(val);
7640  }
7641  }
7642  return 0;
7643 }
7644 
7646 {
7647  if (_valueCallbackSensor != NULL) {
7648  _valueCallbackSensor(this, value);
7649  } else {
7651  }
7652  return 0;
7653 }
7654 
7656 {
7657  int position = 0;
7658  int maxpos = 0;
7659  vector<int> iCalib;
7660  int iRaw = 0;
7661  int iRef = 0;
7662  double fRaw = 0.0;
7663  double fRef = 0.0;
7664  _caltyp = -1;
7665  _scale = -1;
7666  _isScal32 = false;
7667  _calpar.clear();
7668  _calraw.clear();
7669  _calref.clear();
7670  // Store inverted resolution, to provide better rounding
7671  if (_resolution > 0) {
7672  _iresol = floor(1.0 / _resolution+0.5);
7673  } else {
7674  _iresol = 10000;
7675  _resolution = 0.0001;
7676  }
7677  // Old format: supported when there is no calibration
7678  if (_calibrationParam == "" || _calibrationParam == "0") {
7679  _caltyp = 0;
7680  return 0;
7681  }
7682  if (_ystrpos(_calibrationParam, ",") >= 0) {
7683  // Plain text format
7685  _caltyp = ((iCalib[0]) / (1000));
7686  if (_caltyp > 0) {
7687  if (_caltyp < YOCTO_CALIB_TYPE_OFS) {
7688  // Unknown calibration type: calibrated value will be provided by the device
7689  _caltyp = -1;
7690  return 0;
7691  }
7693  if (!(_calhdl != NULL)) {
7694  // Unknown calibration type: calibrated value will be provided by the device
7695  _caltyp = -1;
7696  return 0;
7697  }
7698  }
7699  // New 32bit text format
7700  _isScal = true;
7701  _isScal32 = true;
7702  _offset = 0;
7703  _scale = 1000;
7704  maxpos = (int)iCalib.size();
7705  _calpar.clear();
7706  position = 1;
7707  while (position < maxpos) {
7708  _calpar.push_back(iCalib[position]);
7709  position = position + 1;
7710  }
7711  _calraw.clear();
7712  _calref.clear();
7713  position = 1;
7714  while (position + 1 < maxpos) {
7715  fRaw = iCalib[position];
7716  fRaw = fRaw / 1000.0;
7717  fRef = iCalib[position + 1];
7718  fRef = fRef / 1000.0;
7719  _calraw.push_back(fRaw);
7720  _calref.push_back(fRef);
7721  position = position + 2;
7722  }
7723  } else {
7724  // Recorder-encoded format, including encoding
7726  // In case of unknown format, calibrated value will be provided by the device
7727  if ((int)iCalib.size() < 2) {
7728  _caltyp = -1;
7729  return 0;
7730  }
7731  // Save variable format (scale for scalar, or decimal exponent)
7732  _isScal = (iCalib[1] > 0);
7733  if (_isScal) {
7734  _offset = iCalib[0];
7735  if (_offset > 32767) {
7736  _offset = _offset - 65536;
7737  }
7738  _scale = iCalib[1];
7739  _decexp = 0;
7740  } else {
7741  _offset = 0;
7742  _scale = 1;
7743  _decexp = 1.0;
7744  position = iCalib[0];
7745  while (position > 0) {
7746  _decexp = _decexp * 10;
7747  position = position - 1;
7748  }
7749  }
7750  // Shortcut when there is no calibration parameter
7751  if ((int)iCalib.size() == 2) {
7752  _caltyp = 0;
7753  return 0;
7754  }
7755  _caltyp = iCalib[2];
7757  // parse calibration points
7758  if (_caltyp <= 10) {
7759  maxpos = _caltyp;
7760  } else {
7761  if (_caltyp <= 20) {
7762  maxpos = _caltyp - 10;
7763  } else {
7764  maxpos = 5;
7765  }
7766  }
7767  maxpos = 3 + 2 * maxpos;
7768  if (maxpos > (int)iCalib.size()) {
7769  maxpos = (int)iCalib.size();
7770  }
7771  _calpar.clear();
7772  _calraw.clear();
7773  _calref.clear();
7774  position = 3;
7775  while (position + 1 < maxpos) {
7776  iRaw = iCalib[position];
7777  iRef = iCalib[position + 1];
7778  _calpar.push_back(iRaw);
7779  _calpar.push_back(iRef);
7780  if (_isScal) {
7781  fRaw = iRaw;
7782  fRaw = (fRaw - _offset) / _scale;
7783  fRef = iRef;
7784  fRef = (fRef - _offset) / _scale;
7785  _calraw.push_back(fRaw);
7786  _calref.push_back(fRef);
7787  } else {
7788  _calraw.push_back(YAPI::_decimalToDouble(iRaw));
7789  _calref.push_back(YAPI::_decimalToDouble(iRef));
7790  }
7791  position = position + 2;
7792  }
7793  }
7794  return 0;
7795 }
7796 
7806 {
7807  if (!(this->isOnline())) {
7808  return false;
7809  }
7810  if (!(_sensorState == 0)) {
7811  return false;
7812  }
7813  return true;
7814 }
7815 
7824 {
7825  YDataLogger* logger = NULL;
7826  YModule* modu = NULL;
7827  string serial;
7828  string hwid;
7829 
7830  modu = this->get_module();
7831  serial = modu->get_serialNumber();
7832  if (serial == YAPI_INVALID_STRING) {
7833  return NULL;
7834  }
7835  hwid = serial + ".dataLogger";
7836  logger = YDataLogger::FindDataLogger(hwid);
7837  return logger;
7838 }
7839 
7848 {
7849  string res;
7850 
7851  res = this->_download("api/dataLogger/recording?recording=1");
7852  if (!((int)(res).size()>0)) {
7853  _throw(YAPI_IO_ERROR,"unable to start datalogger");
7854  return YAPI_IO_ERROR;
7855  }
7856  return YAPI_SUCCESS;
7857 }
7858 
7865 {
7866  string res;
7867 
7868  res = this->_download("api/dataLogger/recording?recording=0");
7869  if (!((int)(res).size()>0)) {
7870  _throw(YAPI_IO_ERROR,"unable to stop datalogger");
7871  return YAPI_IO_ERROR;
7872  }
7873  return YAPI_SUCCESS;
7874 }
7875 
7902 YDataSet YSensor::get_recordedData(s64 startTime,s64 endTime)
7903 {
7904  string funcid;
7905  string funit;
7906 
7907  funcid = this->get_functionId();
7908  funit = this->get_unit();
7909  return YDataSet(this,funcid,funit,startTime,endTime);
7910 }
7911 
7924 {
7925  YSensor* sensor = NULL;
7926  sensor = this;
7927  if (callback != NULL) {
7929  } else {
7931  }
7932  _timedReportCallbackSensor = callback;
7933  return 0;
7934 }
7935 
7937 {
7938  if (_timedReportCallbackSensor != NULL) {
7939  _timedReportCallbackSensor(this, value);
7940  } else {
7941  }
7942  return 0;
7943 }
7944 
7966 int YSensor::calibrateFromPoints(vector<double> rawValues,vector<double> refValues)
7967 {
7968  string rest_val;
7969  int res = 0;
7970 
7972  try {
7973  rest_val = this->_encodeCalibrationPoints(rawValues, refValues);
7974  res = this->_setAttr("calibrationParam", rest_val);
7975  } catch (std::exception) {
7977  throw;
7978  }
7980  return res;
7981 }
7982 
7996 int YSensor::loadCalibrationPoints(vector<double>& rawValues,vector<double>& refValues)
7997 {
7998  rawValues.clear();
7999  refValues.clear();
8000  // Load function parameters if not yet loaded
8002  try {
8003  if (_scale == 0) {
8005  {
8007  return YAPI_DEVICE_NOT_FOUND;
8008  }
8009  }
8010  }
8011  if (_caltyp < 0) {
8012  this->_throw(YAPI_NOT_SUPPORTED, "Calibration parameters format mismatch. Please upgrade your library or firmware.");
8013  {
8015  return YAPI_NOT_SUPPORTED;
8016  }
8017  }
8018  rawValues.clear();
8019  refValues.clear();
8020  for (unsigned ii = 0; ii < _calraw.size(); ii++) {
8021  rawValues.push_back(_calraw[ii]);
8022  }
8023  for (unsigned ii = 0; ii < _calref.size(); ii++) {
8024  refValues.push_back(_calref[ii]);
8025  }
8026  } catch (std::exception) {
8028  throw;
8029  }
8031  return YAPI_SUCCESS;
8032 }
8033 
8034 string YSensor::_encodeCalibrationPoints(vector<double> rawValues,vector<double> refValues)
8035 {
8036  string res;
8037  int npt = 0;
8038  int idx = 0;
8039  int iRaw = 0;
8040  int iRef = 0;
8041  npt = (int)rawValues.size();
8042  if (npt != (int)refValues.size()) {
8043  this->_throw(YAPI_INVALID_ARGUMENT, "Invalid calibration parameters (size mismatch)");
8044  return YAPI_INVALID_STRING;
8045  }
8046  // Shortcut when building empty calibration parameters
8047  if (npt == 0) {
8048  return "0";
8049  }
8050  // Load function parameters if not yet loaded
8051  if (_scale == 0) {
8053  return YAPI_INVALID_STRING;
8054  }
8055  }
8056  // Detect old firmware
8057  if ((_caltyp < 0) || (_scale < 0)) {
8058  this->_throw(YAPI_NOT_SUPPORTED, "Calibration parameters format mismatch. Please upgrade your library or firmware.");
8059  return "0";
8060  }
8061  if (_isScal32) {
8062  // 32-bit fixed-point encoding
8064  idx = 0;
8065  while (idx < npt) {
8066  res = YapiWrapper::ysprintf("%s,%g,%g", res.c_str(), rawValues[idx],refValues[idx]);
8067  idx = idx + 1;
8068  }
8069  } else {
8070  if (_isScal) {
8071  // 16-bit fixed-point encoding
8072  res = YapiWrapper::ysprintf("%d",npt);
8073  idx = 0;
8074  while (idx < npt) {
8075  iRaw = (int) floor(rawValues[idx] * _scale + _offset+0.5);
8076  iRef = (int) floor(refValues[idx] * _scale + _offset+0.5);
8077  res = YapiWrapper::ysprintf("%s,%d,%d", res.c_str(), iRaw,iRef);
8078  idx = idx + 1;
8079  }
8080  } else {
8081  // 16-bit floating-point decimal encoding
8082  res = YapiWrapper::ysprintf("%d",10 + npt);
8083  idx = 0;
8084  while (idx < npt) {
8085  iRaw = (int) YAPI::_doubleToDecimal(rawValues[idx]);
8086  iRef = (int) YAPI::_doubleToDecimal(refValues[idx]);
8087  res = YapiWrapper::ysprintf("%s,%d,%d", res.c_str(), iRaw,iRef);
8088  idx = idx + 1;
8089  }
8090  }
8091  }
8092  return res;
8093 }
8094 
8095 double YSensor::_applyCalibration(double rawValue)
8096 {
8097  if (rawValue == Y_CURRENTVALUE_INVALID) {
8098  return Y_CURRENTVALUE_INVALID;
8099  }
8100  if (_caltyp == 0) {
8101  return rawValue;
8102  }
8103  if (_caltyp < 0) {
8104  return Y_CURRENTVALUE_INVALID;
8105  }
8106  if (!(_calhdl != NULL)) {
8107  return Y_CURRENTVALUE_INVALID;
8108  }
8109  return _calhdl(rawValue, _caltyp, _calpar, _calraw, _calref);
8110 }
8111 
8112 YMeasure YSensor::_decodeTimedReport(double timestamp,vector<int> report)
8113 {
8114  int i = 0;
8115  int byteVal = 0;
8116  int poww = 0;
8117  int minRaw = 0;
8118  int avgRaw = 0;
8119  int maxRaw = 0;
8120  int sublen = 0;
8121  int difRaw = 0;
8122  double startTime = 0.0;
8123  double endTime = 0.0;
8124  double minVal = 0.0;
8125  double avgVal = 0.0;
8126  double maxVal = 0.0;
8127  startTime = _prevTimedReport;
8128  endTime = timestamp;
8129  _prevTimedReport = endTime;
8130  if (startTime == 0) {
8131  startTime = endTime;
8132  }
8133  if (report[0] == 2) {
8134  // 32bit timed report format
8135  if ((int)report.size() <= 5) {
8136  // sub-second report, 1-4 bytes
8137  poww = 1;
8138  avgRaw = 0;
8139  byteVal = 0;
8140  i = 1;
8141  while (i < (int)report.size()) {
8142  byteVal = report[i];
8143  avgRaw = avgRaw + poww * byteVal;
8144  poww = poww * 0x100;
8145  i = i + 1;
8146  }
8147  if (((byteVal) & (0x80)) != 0) {
8148  avgRaw = avgRaw - poww;
8149  }
8150  avgVal = avgRaw / 1000.0;
8151  if (_caltyp != 0) {
8152  if (_calhdl != NULL) {
8153  avgVal = _calhdl(avgVal, _caltyp, _calpar, _calraw, _calref);
8154  }
8155  }
8156  minVal = avgVal;
8157  maxVal = avgVal;
8158  } else {
8159  // averaged report: avg,avg-min,max-avg
8160  sublen = 1 + ((report[1]) & (3));
8161  poww = 1;
8162  avgRaw = 0;
8163  byteVal = 0;
8164  i = 2;
8165  while ((sublen > 0) && (i < (int)report.size())) {
8166  byteVal = report[i];
8167  avgRaw = avgRaw + poww * byteVal;
8168  poww = poww * 0x100;
8169  i = i + 1;
8170  sublen = sublen - 1;
8171  }
8172  if (((byteVal) & (0x80)) != 0) {
8173  avgRaw = avgRaw - poww;
8174  }
8175  sublen = 1 + ((((report[1]) >> (2))) & (3));
8176  poww = 1;
8177  difRaw = 0;
8178  while ((sublen > 0) && (i < (int)report.size())) {
8179  byteVal = report[i];
8180  difRaw = difRaw + poww * byteVal;
8181  poww = poww * 0x100;
8182  i = i + 1;
8183  sublen = sublen - 1;
8184  }
8185  minRaw = avgRaw - difRaw;
8186  sublen = 1 + ((((report[1]) >> (4))) & (3));
8187  poww = 1;
8188  difRaw = 0;
8189  while ((sublen > 0) && (i < (int)report.size())) {
8190  byteVal = report[i];
8191  difRaw = difRaw + poww * byteVal;
8192  poww = poww * 0x100;
8193  i = i + 1;
8194  sublen = sublen - 1;
8195  }
8196  maxRaw = avgRaw + difRaw;
8197  avgVal = avgRaw / 1000.0;
8198  minVal = minRaw / 1000.0;
8199  maxVal = maxRaw / 1000.0;
8200  if (_caltyp != 0) {
8201  if (_calhdl != NULL) {
8202  avgVal = _calhdl(avgVal, _caltyp, _calpar, _calraw, _calref);
8203  minVal = _calhdl(minVal, _caltyp, _calpar, _calraw, _calref);
8204  maxVal = _calhdl(maxVal, _caltyp, _calpar, _calraw, _calref);
8205  }
8206  }
8207  }
8208  } else {
8209  // 16bit timed report format
8210  if (report[0] == 0) {
8211  // sub-second report, 1-4 bytes
8212  poww = 1;
8213  avgRaw = 0;
8214  byteVal = 0;
8215  i = 1;
8216  while (i < (int)report.size()) {
8217  byteVal = report[i];
8218  avgRaw = avgRaw + poww * byteVal;
8219  poww = poww * 0x100;
8220  i = i + 1;
8221  }
8222  if (_isScal) {
8223  avgVal = this->_decodeVal(avgRaw);
8224  } else {
8225  if (((byteVal) & (0x80)) != 0) {
8226  avgRaw = avgRaw - poww;
8227  }
8228  avgVal = this->_decodeAvg(avgRaw);
8229  }
8230  minVal = avgVal;
8231  maxVal = avgVal;
8232  } else {
8233  // averaged report 2+4+2 bytes
8234  minRaw = report[1] + 0x100 * report[2];
8235  maxRaw = report[3] + 0x100 * report[4];
8236  avgRaw = report[5] + 0x100 * report[6] + 0x10000 * report[7];
8237  byteVal = report[8];
8238  if (((byteVal) & (0x80)) == 0) {
8239  avgRaw = avgRaw + 0x1000000 * byteVal;
8240  } else {
8241  avgRaw = avgRaw - 0x1000000 * (0x100 - byteVal);
8242  }
8243  minVal = this->_decodeVal(minRaw);
8244  avgVal = this->_decodeAvg(avgRaw);
8245  maxVal = this->_decodeVal(maxRaw);
8246  }
8247  }
8248  return YMeasure( startTime, endTime, minVal, avgVal,maxVal);
8249 }
8250 
8251 double YSensor::_decodeVal(int w)
8252 {
8253  double val = 0.0;
8254  val = w;
8255  if (_isScal) {
8256  val = (val - _offset) / _scale;
8257  } else {
8258  val = YAPI::_decimalToDouble(w);
8259  }
8260  if (_caltyp != 0) {
8261  if (_calhdl != NULL) {
8262  val = _calhdl(val, _caltyp, _calpar, _calraw, _calref);
8263  }
8264  }
8265  return val;
8266 }
8267 
8268 double YSensor::_decodeAvg(int dw)
8269 {
8270  double val = 0.0;
8271  val = dw;
8272  if (_isScal) {
8273  val = (val / 100 - _offset) / _scale;
8274  } else {
8275  val = val / _decexp;
8276  }
8277  if (_caltyp != 0) {
8278  if (_calhdl != NULL) {
8279  val = _calhdl(val, _caltyp, _calpar, _calraw, _calref);
8280  }
8281  }
8282  return val;
8283 }
8284 
8286 {
8287  string hwid;
8288 
8289  if(YISERR(_nextFunction(hwid)) || hwid=="") {
8290  return NULL;
8291  }
8292  return YSensor::FindSensor(hwid);
8293 }
8294 
8296 {
8297  vector<YFUN_DESCR> v_fundescr;
8298  YDEV_DESCR ydevice;
8299  string serial, funcId, funcName, funcVal, errmsg;
8300 
8301  if(YISERR(YapiWrapper::getFunctionsByClass("Sensor", 0, v_fundescr, sizeof(YFUN_DESCR), errmsg)) ||
8302  v_fundescr.size() == 0 ||
8303  YISERR(YapiWrapper::getFunctionInfo(v_fundescr[0], ydevice, serial, funcId, funcName, funcVal, errmsg))) {
8304  return NULL;
8305  }
8306  return YSensor::FindSensor(serial+"."+funcId);
8307 }
8308 
8309 //--- (end of generated code: YSensor implementation)
8310 
8311 //--- (generated code: YSensor functions)
8312 //--- (end of generated code: YSensor functions)
8313 
8314 
8315 
8317  unsigned stamp, unsigned utc, unsigned itv)
8318 : YDataStream(parent)
8319 {
8320  _dataLogger = parent;
8321  _runNo = run;
8322  _timeStamp = stamp;
8323  _utcStamp = utc;
8324  _interval = itv;
8325  _samplesPerHour = 3600 / _interval;
8326  _isClosed = 1;
8330 }
8331 
8332 // Preload all values into the data stream object
8334 {
8335  string buffer;
8337  int res, ival;
8338  double fval;
8339  unsigned p, c = 0;
8340  vector<int> coldiv, coltyp;
8341  vector<double> colscl;
8342  vector<int> colofs;
8343  vector<yCalibrationHandler> calhdl;
8344  vector<int> caltyp;
8345  vector<intArr> calpar;
8346  vector<floatArr> calraw;
8347  vector<floatArr> calref;
8348 
8349  vector<int> udat;
8350  vector<double> dat;
8351 
8352  _values.clear();
8353  if((res = _dataLogger->getData(_runNo, _timeStamp, buffer, j)) != YAPI_SUCCESS) {
8354  return res;
8355  }
8356  if(yJsonParse(&j) != YJSON_PARSE_AVAIL || j.st != YJSON_PARSE_STRUCT) {
8357  fail:
8358  _parent->_throw(YAPI_IO_ERROR, "Unexpected JSON reply format");
8359  return YAPI_IO_ERROR;
8360  }
8361  _nRows = _nCols = 0;
8362  _columnNames.clear();
8363  while(yJsonParse(&j) == YJSON_PARSE_AVAIL && j.st == YJSON_PARSE_MEMBNAME) {
8364  if(!strcmp(j.token, "time")) {
8365  if(yJsonParse(&j) != YJSON_PARSE_AVAIL) goto fail;
8366  _timeStamp = atoi(j.token);
8367  } else if(!strcmp(j.token, "UTC")) {
8368  if(yJsonParse(&j) != YJSON_PARSE_AVAIL) goto fail;
8369  _utcStamp = atoi(j.token);
8370  } else if(!strcmp(j.token, "interval")) {
8371  if(yJsonParse(&j) != YJSON_PARSE_AVAIL) goto fail;
8372  _interval = atoi(j.token);
8373  } else if(!strcmp(j.token, "nRows")) {
8374  if(yJsonParse(&j) != YJSON_PARSE_AVAIL) goto fail;
8375  _nRows = atoi(j.token);
8376  } else if(!strcmp(j.token, "keys")) {
8377  if(yJsonParse(&j) != YJSON_PARSE_AVAIL || j.st != YJSON_PARSE_ARRAY) break;
8378  while(yJsonParse(&j) == YJSON_PARSE_AVAIL && j.st == YJSON_PARSE_STRING) {
8379  _columnNames.push_back(_parent->_parseString(j));
8380  }
8381  if(j.token[0] != ']') goto fail;
8382  if(_nCols == 0) {
8383  _nCols = (int)_columnNames.size();
8384  } else if(_nCols != (int)_columnNames.size()) {
8385  _nCols = 0;
8386  goto fail;
8387  }
8388  } else if(!strcmp(j.token, "div")) {
8389  if(yJsonParse(&j) != YJSON_PARSE_AVAIL || j.st != YJSON_PARSE_ARRAY) break;
8390  while(yJsonParse(&j) == YJSON_PARSE_AVAIL && j.st == YJSON_PARSE_NUM) {
8391  coldiv.push_back(atoi(j.token));
8392  }
8393  if(j.token[0] != ']') goto fail;
8394  if(_nCols == 0) {
8395  _nCols = (int)coldiv.size();
8396  } else if(_nCols != (int)coldiv.size()) {
8397  _nCols = 0;
8398  goto fail;
8399  }
8400  } else if(!strcmp(j.token, "type")) {
8401  if(yJsonParse(&j) != YJSON_PARSE_AVAIL || j.st != YJSON_PARSE_ARRAY) break;
8402  while(yJsonParse(&j) == YJSON_PARSE_AVAIL && j.st == YJSON_PARSE_NUM) {
8403  coltyp.push_back(atoi(j.token));
8404  }
8405  if(j.token[0] != ']') goto fail;
8406  if(_nCols == 0) {
8407  _nCols = (int)coltyp.size();
8408  } else if(_nCols != (int)coltyp.size()) {
8409  _nCols = 0;
8410  goto fail;
8411  }
8412  } else if(!strcmp(j.token, "scal")) {
8413  if(yJsonParse(&j) != YJSON_PARSE_AVAIL || j.st != YJSON_PARSE_ARRAY) break;
8414  c = 0;
8415  while(yJsonParse(&j) == YJSON_PARSE_AVAIL && j.st == YJSON_PARSE_NUM) {
8416  colscl.push_back((double)atoi(j.token) / 65536.0);
8417  colofs.push_back(coltyp[c++] != 0 ? -32767 : 0);
8418  }
8419  if(j.token[0] != ']') goto fail;
8420  if(_nCols == 0) {
8421  _nCols = (int)colscl.size();
8422  } else if(_nCols != (int)colscl.size()) {
8423  _nCols = 0;
8424  goto fail;
8425  }
8426  } else if(!strcmp(j.token, "cal")) {
8427  if(yJsonParse(&j) != YJSON_PARSE_AVAIL || j.st != YJSON_PARSE_ARRAY) break;
8428  while(yJsonParse(&j) == YJSON_PARSE_AVAIL && j.st == YJSON_PARSE_STRING) {
8429  char *p = j.token;
8430  int calibType = (*p ? atoi(p) : 0);
8431  calhdl[c] = YAPI::_getCalibrationHandler(calibType);
8432  if(!calhdl[c]) {
8433  caltyp[c] = 0;
8434  continue;
8435  }
8436  caltyp[c] = calibType;
8437  while(*p && *p != ',') p++;
8438  while(*p) {
8439  p++; // skip ','
8440  ival = atoi(p);
8441  if(calibType <= 10) {
8442  fval = (double)(ival + colofs[c]) / coldiv[c];
8443  } else {
8444  fval = YAPI::_decimalToDouble(ival);
8445  }
8446  calpar[c].push_back(ival);
8447  while(*p && *p != ',') p++;
8448  if(calpar[c].size() & 1) {
8449  calraw[c].push_back(fval);
8450  } else {
8451  calref[c].push_back(fval);
8452  }
8453  }
8454  c++;
8455  }
8456  if(j.token[0] != ']') goto fail;
8457  } else if(!strcmp(j.token, "data")) {
8458  if(colscl.size() == 0) {
8459  for(p = 0; p < coldiv.size(); p++) {
8460  colscl.push_back(1.0 / (double)coldiv[p]);
8461  colofs.push_back(coltyp[p] != 0 ? -32767 : 0);
8462  }
8463  }
8464  if(yJsonParse(&j) != YJSON_PARSE_AVAIL) break;
8465  if(j.st == YJSON_PARSE_STRING) {
8467  } else if(j.st == YJSON_PARSE_ARRAY) {
8468  udat.clear();
8469  while(yJsonParse(&j) == YJSON_PARSE_AVAIL && j.st == YJSON_PARSE_NUM) {
8470  udat.push_back(atoi(j.token));
8471  }
8472  if(j.token[0] != ']' ) goto fail;
8473  } else {
8474  goto fail;
8475  }
8476  dat.clear();
8477  c = 0;
8478  for(p = 0; p < udat.size(); p++) {
8479  double val;
8480  if(coltyp[c] < 2) {
8481  val = (udat[p] + colofs[c]) * colscl[c];
8482  } else {
8483  val = YAPI::_decimalToDouble((int)udat[p]-32767);
8484  }
8485  if(caltyp[c] > 0 && calhdl.size() >= c && calhdl[c]) {
8486  if(caltyp[c] <= 10) {
8487  // linear calibration using unscaled value
8488  val = calhdl[c]((udat[p] + colofs[c]) / coldiv[c], caltyp[c], calpar[c], calraw[c], calref[c]);
8489  } else if(caltyp[c] > 20) {
8490  // custom calibration function: floating-point value is uncalibrated in the datalogger
8491  val = calhdl[c](val, caltyp[c], calpar[c], calraw[c], calref[c]);
8492  }
8493  }
8494  dat.push_back(val);
8495  c++;
8496  if((int)c == _nCols) {
8497  _values.push_back(dat);
8498  dat.clear();
8499  c = 0;
8500  }
8501  }
8502  if(dat.size() > 0) goto fail;
8503  } else {
8504  // ignore unknown field
8505  yJsonSkip(&j, 1);
8506  }
8507  }
8508 
8509  return YAPI_SUCCESS;
8510 }
8511 
8524 {
8525  return _timeStamp;
8526 }
8527 
8540 {
8541  return _interval;
8542 }
8543 
8544 // DataLogger-specific method to retrieve and pre-parse recorded data
8545 //
8546 int YDataLogger::getData(unsigned runIdx, unsigned timeIdx, string &buffer, yJsonStateMachine &j)
8547 {
8548  YDevice *dev;
8549  char query[128];
8550  string errmsg;
8551  int res;
8552 
8553  if(this->dataLoggerURL == "") this->dataLoggerURL = "/logger.json";
8554 
8555  // Resolve our reference to our device, load REST API
8556  res = _getDevice(dev, errmsg);
8557  if(YISERR(res)) {
8558  _throw((YRETCODE)res, errmsg);
8559  return (YRETCODE)res;
8560  }
8561  if(timeIdx) {
8562  // used by old datalogger only
8563  sprintf(query, "GET %s?run=%u&time=%u \r\n\r\n", this->dataLoggerURL.c_str(), runIdx, timeIdx);
8564  } else {
8565  sprintf(query, "GET %s \r\n\r\n", this->dataLoggerURL.c_str());
8566  }
8567  res = dev->HTTPRequest(0, query, buffer, NULL, NULL, errmsg);
8568  if(YISERR(res)) {
8569  // Check if an update of the device list does not solve the issue
8570  res = YAPI::UpdateDeviceList(errmsg);
8571  if(YISERR(res)) {
8572  _throw((YRETCODE)res, errmsg);
8573  return (YRETCODE)res;
8574  }
8575  res = dev->HTTPRequest(0, query, buffer, NULL, NULL, errmsg);
8576  if(YISERR(res)) {
8577  _throw((YRETCODE)res, errmsg);
8578  return (YRETCODE)res;
8579  }
8580  }
8581 
8582  // Parse HTTP header
8583  j.src = buffer.data();
8584  j.end = j.src + buffer.size();
8585  j.st = YJSON_HTTP_START;
8587  _throw(YAPI_IO_ERROR, "Failed to parse HTTP header");
8588  return YAPI_IO_ERROR;
8589  }
8590  if(string(j.token) != "200") {
8591  if(string(j.token) == "404" && this->dataLoggerURL != "/dataLogger.json") {
8592  // retry using backward-compatible datalogger URL
8593  this->dataLoggerURL = "/dataLogger.json";
8594  return this->getData(runIdx, timeIdx, buffer, j);
8595  }
8596  _throw(YAPI_IO_ERROR, string("Unexpected HTTP return code: ")+j.token);
8597  return YAPI_IO_ERROR;
8598  }
8599  if(yJsonParse(&j) != YJSON_PARSE_AVAIL || j.st != YJSON_HTTP_READ_MSG) {
8600  _throw(YAPI_IO_ERROR, "Unexpected HTTP header format");
8601  return YAPI_IO_ERROR;
8602  }
8603 
8604  return YAPI_SUCCESS;
8605 }
8606 
8624 int YDataLogger::get_dataStreams(vector<YDataStream *>& v)
8625 {
8626  string buffer;
8628  int res;
8629  unsigned i, si, arr[4];
8630  YOldDataStream *ods;
8631 
8632  v.clear();
8633  if((res = getData(0, 0, buffer, j)) != YAPI_SUCCESS) {
8634  return res;
8635  }
8636  if(yJsonParse(&j) != YJSON_PARSE_AVAIL || j.st != YJSON_PARSE_ARRAY) {
8637  _throw(YAPI_IO_ERROR, "Unexpected JSON reply format");
8638  return YAPI_IO_ERROR;
8639  }
8640  // expect arrays in array
8641  while(yJsonParse(&j) == YJSON_PARSE_AVAIL) {
8642  if(j.token[0] == '[') {
8643  // old datalogger format: [runIdx, timerel, utc, interval]
8644  for(i = 0; i < 4; i++) {
8645  if(yJsonParse(&j) != YJSON_PARSE_AVAIL || j.st != YJSON_PARSE_NUM) break;
8646  arr[i] = atoi(j.token);
8647  }
8648  if(i < 4) break;
8649  // skip any extra item in array
8650  while(yJsonParse(&j) == YJSON_PARSE_AVAIL && j.token[0] != ']')
8651  ;
8652  // instantiate a data stream
8653  ods = new YOldDataStream(this,arr[0],arr[1],arr[2],arr[3]);
8654  v.push_back(ods);
8655  } else if(j.token[0] == '{') {
8656  // new datalogger format: {"id":"...","unit":"...","streams":["...",...]}
8657  size_t pos = buffer.find("\r\n\r\n", 0);
8658  buffer = buffer.substr(pos+4);
8659  vector<YDataSet> sets = this->parse_dataSets(buffer);
8660  for (i=0; i < sets.size(); i++) {
8661  vector<YDataStream*> ds = sets[i].get_privateDataStreams();
8662  for (si=0; si < ds.size(); si++) {
8663  // return a user-owned copy
8664 
8665  v.push_back(new YDataStream(*ds[si]));
8666  }
8667  }
8668  break;
8669  } else break;
8670  }
8671 
8672  return YAPI_SUCCESS;
8673 }
8674 
8675 
8676 
8677 YDataLogger::YDataLogger(const string& func): YFunction(func)
8678 //--- (generated code: YDataLogger initialization)
8679  ,_currentRunIndex(CURRENTRUNINDEX_INVALID)
8680  ,_timeUTC(TIMEUTC_INVALID)
8681  ,_recording(RECORDING_INVALID)
8682  ,_autoStart(AUTOSTART_INVALID)
8683  ,_beaconDriven(BEACONDRIVEN_INVALID)
8684  ,_clearHistory(CLEARHISTORY_INVALID)
8685  ,_valueCallbackDataLogger(NULL)
8686 //--- (end of generated code: YDataLogger initialization)
8687 {
8688  _className = "DataLogger";
8689 }
8690 
8692 {
8693  //--- (generated code: YDataLogger cleanup)
8694 //--- (end of generated code: YDataLogger cleanup)
8695 }
8696 
8697 
8698 //--- (generated code: YDataLogger implementation)
8699 // static attributes
8700 
8702 {
8703  if(json_val->has("currentRunIndex")) {
8704  _currentRunIndex = json_val->getInt("currentRunIndex");
8705  }
8706  if(json_val->has("timeUTC")) {
8707  _timeUTC = json_val->getLong("timeUTC");
8708  }
8709  if(json_val->has("recording")) {
8710  _recording = (Y_RECORDING_enum)json_val->getInt("recording");
8711  }
8712  if(json_val->has("autoStart")) {
8713  _autoStart = (Y_AUTOSTART_enum)json_val->getInt("autoStart");
8714  }
8715  if(json_val->has("beaconDriven")) {
8716  _beaconDriven = (Y_BEACONDRIVEN_enum)json_val->getInt("beaconDriven");
8717  }
8718  if(json_val->has("clearHistory")) {
8719  _clearHistory = (Y_CLEARHISTORY_enum)json_val->getInt("clearHistory");
8720  }
8721  return YFunction::_parseAttr(json_val);
8722 }
8723 
8724 
8735 {
8736  int res = 0;
8738  try {
8741  {
8744  }
8745  }
8746  }
8747  res = _currentRunIndex;
8748  } catch (std::exception) {
8750  throw;
8751  }
8753  return res;
8754 }
8755 
8764 {
8765  s64 res = 0;
8767  try {
8770  {
8773  }
8774  }
8775  }
8776  res = _timeUTC;
8777  } catch (std::exception) {
8779  throw;
8780  }
8782  return res;
8783 }
8784 
8795 {
8796  string rest_val;
8797  int res;
8799  try {
8800  char buf[32]; sprintf(buf, "%u", (u32)newval); rest_val = string(buf);
8801  res = _setAttr("timeUTC", rest_val);
8802  } catch (std::exception) {
8804  throw;
8805  }
8807  return res;
8808 }
8809 
8819 {
8820  Y_RECORDING_enum res;
8822  try {
8825  {
8828  }
8829  }
8830  }
8831  res = _recording;
8832  } catch (std::exception) {
8834  throw;
8835  }
8837  return res;
8838 }
8839 
8851 {
8852  string rest_val;
8853  int res;
8855  try {
8856  char buf[32]; sprintf(buf, "%d", newval); rest_val = string(buf);
8857  res = _setAttr("recording", rest_val);
8858  } catch (std::exception) {
8860  throw;
8861  }
8863  return res;
8864 }
8865 
8875 {
8876  Y_AUTOSTART_enum res;
8878  try {
8881  {
8884  }
8885  }
8886  }
8887  res = _autoStart;
8888  } catch (std::exception) {
8890  throw;
8891  }
8893  return res;
8894 }
8895 
8909 {
8910  string rest_val;
8911  int res;
8913  try {
8914  rest_val = (newval>0 ? "1" : "0");
8915  res = _setAttr("autoStart", rest_val);
8916  } catch (std::exception) {
8918  throw;
8919  }
8921  return res;
8922 }
8923 
8933 {
8934  Y_BEACONDRIVEN_enum res;
8936  try {
8939  {
8942  }
8943  }
8944  }
8945  res = _beaconDriven;
8946  } catch (std::exception) {
8948  throw;
8949  }
8951  return res;
8952 }
8953 
8967 {
8968  string rest_val;
8969  int res;
8971  try {
8972  rest_val = (newval>0 ? "1" : "0");
8973  res = _setAttr("beaconDriven", rest_val);
8974  } catch (std::exception) {
8976  throw;
8977  }
8979  return res;
8980 }
8981 
8983 {
8984  Y_CLEARHISTORY_enum res;
8986  try {
8989  {
8992  }
8993  }
8994  }
8995  res = _clearHistory;
8996  } catch (std::exception) {
8998  throw;
8999  }
9001  return res;
9002 }
9003 
9005 {
9006  string rest_val;
9007  int res;
9009  try {
9010  rest_val = (newval>0 ? "1" : "0");
9011  res = _setAttr("clearHistory", rest_val);
9012  } catch (std::exception) {
9014  throw;
9015  }
9017  return res;
9018 }
9019 
9048 {
9049  YDataLogger* obj = NULL;
9050  int taken = 0;
9051  if (YAPI::_apiInitialized) {
9053  taken = 1;
9054  }try {
9055  obj = (YDataLogger*) YFunction::_FindFromCache("DataLogger", func);
9056  if (obj == NULL) {
9057  obj = new YDataLogger(func);
9058  YFunction::_AddToCache("DataLogger", func, obj);
9059  }
9060  } catch (std::exception) {
9062  throw;
9063  }
9065  return obj;
9066 }
9067 
9080 {
9081  string val;
9082  if (callback != NULL) {
9084  } else {
9086  }
9087  _valueCallbackDataLogger = callback;
9088  // Immediately invoke value callback with current value
9089  if (callback != NULL && this->isOnline()) {
9090  val = _advertisedValue;
9091  if (!(val == "")) {
9092  this->_invokeValueCallback(val);
9093  }
9094  }
9095  return 0;
9096 }
9097 
9099 {
9100  if (_valueCallbackDataLogger != NULL) {
9101  _valueCallbackDataLogger(this, value);
9102  } else {
9104  }
9105  return 0;
9106 }
9107 
9117 {
9118  return this->set_clearHistory(Y_CLEARHISTORY_TRUE);
9119 }
9120 
9133 vector<YDataSet> YDataLogger::get_dataSets(void)
9134 {
9135  return this->parse_dataSets(this->_download("logger.json"));
9136 }
9137 
9138 vector<YDataSet> YDataLogger::parse_dataSets(string json)
9139 {
9140  vector<string> dslist;
9141  YDataSet* dataset = NULL;
9142  vector<YDataSet> res;
9143 
9144  dslist = this->_json_get_array(json);
9145  res.clear();
9146  for (unsigned ii = 0; ii < dslist.size(); ii++) {
9147  dataset = new YDataSet(this);
9148  dataset->_parse(dslist[ii]);
9149  res.push_back(*dataset);
9150  }
9151  return res;
9152 }
9153 
9155 {
9156  string hwid;
9157 
9158  if(YISERR(_nextFunction(hwid)) || hwid=="") {
9159  return NULL;
9160  }
9161  return YDataLogger::FindDataLogger(hwid);
9162 }
9163 
9165 {
9166  vector<YFUN_DESCR> v_fundescr;
9167  YDEV_DESCR ydevice;
9168  string serial, funcId, funcName, funcVal, errmsg;
9169 
9170  if(YISERR(YapiWrapper::getFunctionsByClass("DataLogger", 0, v_fundescr, sizeof(YFUN_DESCR), errmsg)) ||
9171  v_fundescr.size() == 0 ||
9172  YISERR(YapiWrapper::getFunctionInfo(v_fundescr[0], ydevice, serial, funcId, funcName, funcVal, errmsg))) {
9173  return NULL;
9174  }
9175  return YDataLogger::FindDataLogger(serial+"."+funcId);
9176 }
9177 
9178 //--- (end of generated code: YDataLogger implementation)
9179 
9180 //--- (generated code: YDataLogger functions)
9181 //--- (end of generated code: YDataLogger functions)
virtual int get_progress(void)
Definition: yocto_api.cpp:2122
virtual s64 get_endTimeUTC(void)
Definition: yocto_api.cpp:2109
virtual int get_runIndex(void)
Definition: yocto_api.cpp:1608
string _json_get_key(const string &json, const string &data)
Definition: yocto_api.cpp:2772
virtual int parse()
Definition: yocto_api.cpp:236
d
static vector< int > _decodeWords(string s)
Definition: yocto_api.cpp:4033
static const int USERVAR_INVALID
Definition: yocto_api.h:2154
virtual double _decodeVal(int w)
Definition: yocto_api.cpp:1555
virtual string toString()
Definition: yocto_api.cpp:364
virtual string get_functionId(void)
Definition: yocto_api.cpp:2063
string _advertisedValue
Definition: yocto_api.h:1569
void(* YHubDiscoveryCallback)(const string &serial, const string &url)
prototype of the Hub discoverycallback
Definition: yocto_api.h:220
string get_logicalName(void)
Definition: yocto_api.cpp:2386
static YHubDiscoveryCallback _HubDiscoveryCallback
Definition: yocto_api.h:444
static std::vector< YFunction * > _FunctionCallbacks
Definition: yocto_api.cpp:65
YAPI_FUNCTION YAPI_FUNCTION_EXPORT yapiGetFunction(const char *class_str, const char *function_str, char *errmsg)
Definition: yapi.c:4533
string get_productName(void)
Definition: yocto_api.cpp:5122
string FormatError(const string &errmsg, int cur_pos)
Definition: yocto_api.cpp:166
double getDouble(const string &key)
Definition: yocto_api.cpp:796
YFUN_DESCR _fundescr
Definition: yocto_api.h:1562
YFunction * fun
Definition: yocto_api.h:281
static void FreeAPI(void)
Definition: yocto_api.cpp:4262
yCRITICAL_SECTION _this_cs
Definition: yocto_api.h:1563
YDataLogger * nextDataLogger(void)
Definition: yocto_api.cpp:9154
string get_unit(void)
Definition: yocto_api.cpp:7061
virtual int get_duration(void)
Definition: yocto_api.cpp:1783
YJSONObject(const string &data)
Definition: yocto_api.cpp:585
YDataLoggerValueCallback _valueCallbackDataLogger
Definition: yocto_api.h:3646
int set_luminosity(int newval)
Definition: yocto_api.cpp:5347
static YJSONContent * ParseJson(const string &data, int start, int stop)
Definition: yocto_api.cpp:104
YRETCODE YAPI_FUNCTION_EXPORT yapiGetFunctionInfo(YAPI_FUNCTION fundesc, YAPI_DEVICE *devdesc, char *serial, char *funcId, char *funcName, char *funcVal, char *errmsg)
Definition: yapi.c:4562
virtual int parse()=0
YRETCODE YAPI_FUNCTION_EXPORT yapiTestHub(const char *url, int mstimeout, char *errmsg)
Definition: yapi.c:4403
vector< YDataStream * > _streams
Definition: yocto_api.h:1306
virtual int set_allSettingsAndFiles(string settings)
Definition: yocto_api.cpp:5913
static YDEV_DESCR getDevice(const string &device_str, string &errmsg)
Definition: yocto_api.cpp:4785
static std::vector< YFunction * > _TimedReportCallbackList
Definition: yocto_api.cpp:66
static YSensor * FindSensor(string func)
Definition: yocto_api.cpp:7594
virtual int get_columnCount(void)
Definition: yocto_api.cpp:1696
double _scale
Definition: yocto_api.h:962
virtual int _parserHelper(void)
Definition: yocto_api.cpp:7655
static const double DATA_INVALID
Definition: yocto_api.h:983
static const double LOWESTVALUE_INVALID
Definition: yocto_api.h:2718
int set_rebootCountdown(int newval)
Definition: yocto_api.cpp:5506
virtual ~YFunction()
Definition: yocto_api.cpp:2328
double _highestValue
Definition: yocto_api.h:2676
static const int PRODUCTRELEASE_INVALID
Definition: yocto_api.h:2141
Y_PERSISTENTSETTINGS_enum get_persistentSettings(void)
Definition: yocto_api.cpp:5268
virtual string get_allSettings(void)
Definition: yocto_api.cpp:5794
static void RegisterHubDiscoveryCallback(YHubDiscoveryCallback hubDiscoveryCallback)
Definition: yocto_api.cpp:4365
static void _UpdateTimedReportCallbackList(YFunction *func, bool add)
Definition: yocto_api.cpp:3531
YRETCODE HTTPRequest_unsafe(int channel, const string &request, string &buffer, yapiRequestProgressCallback progress_cb, void *progress_ctx, string &errmsg)
Definition: yocto_api.cpp:3618
double _currentRawValue
Definition: yocto_api.h:2677
virtual vector< YDataStream * > get_privateDataStreams(void)
Definition: yocto_api.cpp:2031
void * yCRITICAL_SECTION
Definition: ydef.h:366
virtual string get_friendlyName(void)
Definition: yocto_api.cpp:3151
yapiGlobalEventType type
Definition: yocto_api.h:258
virtual string get_icon2d(void)
Definition: yocto_api.cpp:6575
static YDevice * getDevice(YDEV_DESCR devdescr)
Definition: yocto_api.cpp:3577
string _json_get_string(const string &json)
Definition: yocto_api.cpp:2798
YModule * module
Definition: yocto_api.h:260
s64 yatoi(const char *p)
Definition: yocto_api.cpp:4156
ROSCPP_DECL void start()
int set_autoStart(Y_AUTOSTART_enum newval)
Definition: yocto_api.cpp:8908
char serial[YOCTO_SERIAL_LEN]
Definition: yocto_api.h:262
int set_calibrationParam(const string &newval)
Definition: yocto_api.cpp:7463
yCRITICAL_SECTION _lock
Definition: yocto_api.h:1515
static YFUN_DESCR getFunction(const string &class_str, const string &function_str, string &errmsg)
Definition: yocto_api.cpp:4841
void * YIOHDL
Definition: ydef.h:260
string _serial
Definition: yocto_api.h:841
YRETCODE _load_unsafe(int msValidity)
Definition: yocto_api.cpp:3327
void yInitializeCriticalSection(yCRITICAL_SECTION *cs)
Definition: ythread.c:629
string _productName
Definition: yocto_api.h:1999
virtual ~YJSONArray()
Definition: yocto_api.cpp:223
virtual int startUpdate(void)
Definition: yocto_api.cpp:1344
char * _subpath
Definition: yocto_api.h:1514
s32 YAPI_FUNCTION
Definition: ydef.h:217
static const int REBOOTCOUNTDOWN_INVALID
Definition: yocto_api.h:2153
yapiDataEventType type
Definition: yocto_api.h:278
static int getFunctionsByDevice(YDEV_DESCR devdesc, YFUN_DESCR prevfundesc, vector< YFUN_DESCR > &buffer, int maxsize, string &errmsg)
Definition: yocto_api.cpp:4884
virtual string checkFirmware(string path, bool onlynew)
Definition: yocto_api.cpp:5731
YRETCODE YAPI_FUNCTION_EXPORT yapiGetBootloaders(char *buffer, int buffersize, int *fullsize, char *errmsg)
Definition: yapi.c:4673
static yCRITICAL_SECTION _updateDeviceList_CS
Definition: yocto_api.cpp:62
YJSONString * getYJSONString(const string &key)
Definition: yocto_api.cpp:749
void YAPI_FUNCTION_EXPORT yapiRegisterDeviceLogCallback(yapiDeviceLogCallback logCallback)
Definition: yapi.c:4318
virtual int get_startTime(void)
Definition: yocto_api.cpp:1626
YRETCODE errType(void)
Definition: yocto_api.h:1879
string get_firmwareRelease(void)
Definition: yocto_api.cpp:5238
string functionBaseType(int functionIndex)
Definition: yocto_api.cpp:6915
YModule(const string &func)
Definition: yocto_api.cpp:5036
void convert(YJSONObject *reference, YJSONArray *newArray)
Definition: yocto_api.cpp:860
Y_BEACONDRIVEN_enum
Definition: yocto_api.h:183
static const string ADVERTISEDVALUE_INVALID
Definition: yocto_api.h:1662
double get_currentRawValue(void)
Definition: yocto_api.cpp:7243
string _unit
Definition: yocto_api.h:1301
#define Y_CURRENTVALUE_INVALID
Definition: yocto_api.h:137
int _progress
Definition: yocto_api.h:1304
YRETCODE YAPI_FUNCTION_EXPORT yapiGetDevicePath(YAPI_DEVICE devdesc, char *rootdevice, char *request, int requestsize, int *neededsize, char *errmsg)
Definition: yapi.c:4515
virtual bool isSensorReady(void)
Definition: yocto_api.cpp:7805
int set_lowestValue(double newval)
Definition: yocto_api.cpp:7128
virtual int _parserHelper(void)
Definition: yocto_api.cpp:2622
virtual vector< int > _get_calibration(void)
Definition: yocto_api.cpp:1966
virtual int _initFromDataSet(YDataSet *dataset, vector< int > encoded)
Definition: yocto_api.cpp:1367
string get_hardwareId(void)
Definition: yocto_api.cpp:3194
int _currentRunIndex
Definition: yocto_api.h:3640
virtual string toJSON()=0
Y_RECORDING_enum
Definition: yocto_api.h:166
virtual bool isClosed(void)
Definition: yocto_api.cpp:1597
Y_BEACON_enum
Definition: yocto_api.h:101
char _rootdevice[YOCTO_SERIAL_LEN]
Definition: yocto_api.h:1513
virtual string get_url(void)
Definition: yocto_api.cpp:6687
std::map< string, YDataStream * > _dataStreams
Definition: yocto_api.h:1564
int _productId
Definition: yocto_api.h:2001
time_t * get_startTimeUTC_asTime_t(time_t *time)
Definition: yocto_api.cpp:1946
int get_productId(void)
Definition: yocto_api.cpp:5180
static vector< string > GetAllBootLoaders(void)
Definition: yocto_api.cpp:1224
static const string REPORTFREQUENCY_INVALID
Definition: yocto_api.h:2722
void YAPI_FUNCTION_EXPORT yapiRegisterTimedReportCallback(yapiTimedReportCallback timedReportCallback)
Definition: yapi.c:4360
virtual int _parseAttr(YJSONObject *json_val)
Definition: yocto_api.cpp:8701
double _end
Definition: yocto_api.h:1199
YRETCODE HTTPRequestAsync(int channel, const string &request, HTTPRequestCallback callback, void *context, string &errmsg)
Definition: yocto_api.cpp:3649
double _maxVal
Definition: yocto_api.h:966
static void UnregisterHub(const string &url)
Definition: yocto_api.cpp:4560
vector< YFUN_DESCR > _functions
Definition: yocto_api.h:1512
static YModule * FindModule(string func)
Definition: yocto_api.cpp:5600
YModule * get_module(void)
Definition: yocto_api.cpp:3440
static YDEV_DESCR getDeviceByFunction(YFUN_DESCR fundesc, string &errmsg)
Definition: yocto_api.cpp:4916
virtual string toString()
Definition: yocto_api.cpp:572
static const string FRIENDLYNAME_INVALID
Definition: yocto_api.h:1652
YJSONArray * getYJSONArray(int i)
Definition: yocto_api.cpp:325
XmlRpcServer s
YJSONNumber(const string &data, int start, int stop)
Definition: yocto_api.cpp:492
static string _bin2HexStr(const string &data)
Definition: yocto_api.cpp:4116
double timestamp
Definition: yocto_api.h:286
static void EnableExceptions(void)
Definition: yocto_api.cpp:4298
virtual string toString()
Definition: yocto_api.cpp:480
char token[62]
Definition: yjson.h:88
static const string CALIBRATIONPARAM_INVALID
Definition: yocto_api.h:2728
static const string LOGFREQUENCY_INVALID
Definition: yocto_api.h:2721
static YRETCODE PreregisterHub(const string &url, string &errmsg)
Definition: yocto_api.cpp:4539
int getData(unsigned runIdx, unsigned timeIdx, string &buffer, yJsonStateMachine &j)
Definition: yocto_api.cpp:8546
virtual string toJSON()
Definition: yocto_api.cpp:802
virtual double get_maxValue(void)
Definition: yocto_api.cpp:1940
double get_dataSamplesInterval(void)
Definition: yocto_api.cpp:8539
string functionName(int functionIndex)
Definition: yocto_api.cpp:6844
YRETCODE _upload(const string &path, const string &content)
Definition: yocto_api.cpp:3098
static void _yapiDeviceArrivalCallbackFwd(YDEV_DESCR devdesc)
Definition: yocto_api.cpp:3863
vector< double > _calraw
Definition: yocto_api.h:970
virtual int revertFromFlash(void)
Definition: yocto_api.cpp:5683
void(* yapiRequestProgressCallback)(void *context, u32 acked, u32 totalbytes)
Definition: ydef.h:866
virtual string toString()=0
bool _isScal32
Definition: yocto_api.h:959
static int DefaultCacheValidity
Definition: yocto_api.h:468
void(* YSensorValueCallback)(YSensor *func, const string &functionValue)
Definition: yocto_api.h:123
YRETCODE HTTPRequestPrepare(const string &request, string &fullrequest, char *errbuff)
Definition: yocto_api.cpp:3597
static std::map< string, YFunction * > _cache
Definition: yocto_api.h:1585
string getString(const string &key)
Definition: yocto_api.cpp:773
YJSONObject * getYJSONObject(const string &key)
Definition: yocto_api.cpp:744
time_t * get_endTimeUTC_asTime_t(time_t *time)
Definition: yocto_api.cpp:1954
double _prevTimedReport
Definition: yocto_api.h:2686
static const string HARDWAREID_INVALID
Definition: yocto_api.h:1650
int get_startTime(void)
Definition: yocto_api.cpp:8523
void(* HTTPRequestCallback)(YDevice *device, void *context, YRETCODE returnval, const string &result, string &errmsg)
Definition: yocto_api.h:1500
YJSONContent(const string &data, int start, int stop, YJSONType type)
Definition: yocto_api.cpp:121
int YAPI_FUNCTION_EXPORT yapiJsonDecodeString(const char *json_string, char *output)
Definition: yapi.c:4683
virtual string _get_url(void)
Definition: yocto_api.cpp:1542
double _resolution
Definition: yocto_api.h:2682
virtual double get_minValue(void)
Definition: yocto_api.cpp:1741
YRETCODE get_errorType(void)
Definition: yocto_api.cpp:3264
YJSONContent * get(int i)
Definition: yocto_api.cpp:320
virtual YFirmwareUpdate updateFirmwareEx(string path, bool force)
Definition: yocto_api.cpp:5759
string _escapeAttr(const string &changeval)
Definition: yocto_api.cpp:2891
vector< double > floatArr
prototype of the value calibration handlers
Definition: yocto_api.h:225
virtual int get_progress(void)
Definition: yocto_api.cpp:1315
double get_resolution(void)
Definition: yocto_api.cpp:7513
virtual double get_averageValue(void)
Definition: yocto_api.cpp:1756
Y_AUTOSTART_enum get_autoStart(void)
Definition: yocto_api.cpp:8874
int _samplesPerHour
Definition: yocto_api.h:963
double _decexp
Definition: yocto_api.h:2690
static const string LOGICALNAME_INVALID
Definition: yocto_api.h:1661
Y_CLEARHISTORY_enum get_clearHistory(void)
Definition: yocto_api.cpp:8982
YFunction * nextFunction(void)
Definition: yocto_api.cpp:2627
virtual int loadCalibrationPoints(vector< double > &rawValues, vector< double > &refValues)
Definition: yocto_api.cpp:7996
int report[18]
Definition: yocto_api.h:288
double _currentValue
Definition: yocto_api.h:2674
static const string FIRMWARERELEASE_INVALID
Definition: yocto_api.h:2142
static const int DEVICE_NOT_FOUND
Definition: yocto_api.h:495
string get_advertisedValue(void)
Definition: yocto_api.cpp:2447
u64 _cacheExpiration
Definition: yocto_api.h:1571
string _serial
Definition: yocto_api.h:1572
virtual int get_dataSamplesIntervalMs(void)
Definition: yocto_api.cpp:1653
void set_userData(void *data)
Definition: yocto_api.cpp:3486
int _ystrpos(const string &haystack, const string &needle)
Definition: yocto_api.cpp:75
void _throw(YRETCODE errType, string errMsg)
Definition: yocto_api.cpp:2656
bool _isAvg
Definition: yocto_api.h:957
yJsonState next
Definition: yjson.h:85
static const Y_BEACONDRIVEN_enum BEACONDRIVEN_INVALID
Definition: yocto_api.h:3707
static u16 getAPIVersion(string &version, string &date)
Definition: yocto_api.cpp:4776
virtual string get_friendlyName(void)
Definition: yocto_api.cpp:6732
yJsonRetCode yJsonParse(yJsonStateMachine *j)
Definition: yjson.c:83
static vector< int > _decodeFloats(string sdat)
Definition: yocto_api.cpp:4067
Y_ADVMODE_enum get_advMode(void)
Definition: yocto_api.cpp:7393
static const string FUNCTIONID_INVALID
Definition: yocto_api.h:1651
_FAR const char * src
Definition: yjson.h:82
bool _isScal32
Definition: yocto_api.h:2692
static const int PRODUCTID_INVALID
Definition: yocto_api.h:2140
static void RegisterDeviceArrivalCallback(yDeviceUpdateCallback arrivalCallback)
Definition: yocto_api.cpp:4321
YJSONContent * get(const string &key)
Definition: yocto_api.cpp:785
YRETCODE load(int msValidity)
Definition: yocto_api.cpp:3391
static YRETCODE getDeviceInfo(YDEV_DESCR devdesc, yDeviceSt &infos, string &errmsg)
Definition: yocto_api.cpp:4829
#define YOCTO_SERIAL_LEN
Definition: ydef.h:420
string _request(const string &request)
Definition: yocto_api.cpp:3046
void yLeaveCriticalSection(yCRITICAL_SECTION *cs)
Definition: ythread.c:672
static string GetAPIVersion(void)
Definition: yocto_api.cpp:4192
virtual int parse()
Definition: yocto_api.cpp:625
void YAPI_FUNCTION_EXPORT yapiFreeAPI(void)
Definition: yapi.c:4304
virtual vector< YMeasure > get_preview(void)
Definition: yocto_api.cpp:2203
YSensor * nextSensor(void)
Definition: yocto_api.cpp:8285
vector< double > _calraw
Definition: yocto_api.h:2695
YRETCODE YAPI_FUNCTION_EXPORT yapiLockFunctionCallBack(char *errmsg)
Definition: yapi.c:4367
virtual string download(string pathname)
Definition: yocto_api.cpp:6563
#define YOCTO_ERRMSG_LEN
Definition: ydef.h:418
void setImmutableAttributes(yDeviceSt *infos)
Definition: yocto_api.cpp:6759
YRETCODE getFunctions(vector< YFUN_DESCR > **functions, string &errmsg)
Definition: yocto_api.cpp:3796
string _logicalName
Definition: yocto_api.h:1568
YRETCODE _getDevice(YDevice *&dev, string &errMsg)
Definition: yocto_api.cpp:2688
virtual string _encodeCalibrationPoints(vector< double > rawValues, vector< double > refValues)
Definition: yocto_api.cpp:8034
int get_usbCurrent(void)
Definition: yocto_api.cpp:5453
Y_BEACONDRIVEN_enum get_beaconDriven(void)
Definition: yocto_api.cpp:8932
virtual s64 get_startTimeUTC(void)
Definition: yocto_api.cpp:1640
string _download(const string &url)
Definition: yocto_api.cpp:3053
static YRETCODE RegisterHub(const string &url, string &errmsg)
Definition: yocto_api.cpp:4509
static yDeviceUpdateCallback DeviceRemovalCallback
Definition: yocto_api.h:481
static YRETCODE getFunctionInfo(YFUN_DESCR fundesc, YDEV_DESCR &devdescr, string &serial, string &funcId, string &funcName, string &funcVal, string &errmsg)
Definition: yocto_api.cpp:4930
static YRETCODE updateDeviceList(bool forceupdate, string &errmsg)
Definition: yocto_api.cpp:4974
double _decexp
Definition: yocto_api.h:967
int getInt()
Definition: yocto_api.cpp:556
static YRETCODE TestHub(const string &url, int mstimeout, string &errmsg)
Definition: yocto_api.cpp:4453
string _get_json_path(const string &json, const string &path)
Definition: yocto_api.cpp:2852
YDataLogger * _dataLogger
Definition: yocto_api.h:3580
static const double INVALID_DOUBLE
Definition: yocto_api.h:473
char url[64]
Definition: yocto_api.h:263
s64 _startTime
Definition: yocto_api.h:1302
int _duration
Definition: yocto_api.h:953
virtual vector< YDataSet > parse_dataSets(string json)
Definition: yocto_api.cpp:9138
Y_RECORDING_enum get_recording(void)
Definition: yocto_api.cpp:8818
static queue< yapiGlobalEvent > _plug_events
Definition: yocto_api.h:442
virtual string toString()
Definition: yocto_api.cpp:822
Y_ADVMODE_enum _advMode
Definition: yocto_api.h:2680
int YAPI_FUNCTION_EXPORT yapiGetAllDevices(YAPI_DEVICE *buffer, int maxsize, int *neededsize, char *errmsg)
Definition: yapi.c:4497
YModuleLogCallback get_logCallback()
Definition: yocto_api.cpp:6952
virtual int set_allSettings(string settings)
Definition: yocto_api.cpp:6279
static const int CURRENTRUNINDEX_INVALID
Definition: yocto_api.h:3696
string describe(void)
Definition: yocto_api.cpp:3131
virtual ~YJSONContent()
Definition: yocto_api.cpp:144
YRETCODE _buildSetRequest(const string &changeattr, const string *changeval, string &request, string &errmsg)
Definition: yocto_api.cpp:2919
virtual int loadMore(void)
Definition: yocto_api.cpp:2143
void yJsonSkip(yJsonStateMachine *j, int nitems)
Definition: yjson.c:367
string functionType(int functionIndex)
Definition: yocto_api.cpp:6887
YDevice(YDEV_DESCR devdesc)
Definition: yocto_api.cpp:3556
char value[YOCTO_PUBVAL_LEN]
Definition: yocto_api.h:282
static double _decimalToDouble(s16 val)
Definition: yocto_api.cpp:3977
string _data
Definition: yocto_api.h:325
#define YOCTO_PUBVAL_LEN
Definition: ydef.h:428
double get_currentValue(void)
Definition: yocto_api.cpp:7091
virtual int _parseStream(string sdata)
Definition: yocto_api.cpp:1491
static void RegisterDeviceChangeCallback(yDeviceUpdateCallback changeCallback)
Definition: yocto_api.cpp:4350
virtual vector< string > get_subDevices(void)
Definition: yocto_api.cpp:6618
void * get_userData(void)
Definition: yocto_api.cpp:3469
virtual string get_hardwareId(void)
Definition: yocto_api.cpp:2046
double _minVal
Definition: yocto_api.h:964
string _serialNumber
Definition: yocto_api.h:2000
YFUN_DESCR functionDescriptor(void)
Definition: yocto_api.h:1952
#define YAPI_INVALID_STRING
Definition: yocto_api.h:69
YFUN_DESCR get_functionDescriptor(void)
Definition: yocto_api.cpp:3503
virtual int _parseAttr(YJSONObject *json_val)
Definition: yocto_api.cpp:5073
YRETCODE _getDescriptor(YFUN_DESCR &fundescr, string &errMsg)
Definition: yocto_api.cpp:2667
YRETCODE
Definition: ydef.h:376
double _avgVal
Definition: yocto_api.h:1201
string get_functionId(void)
Definition: yocto_api.cpp:3229
Y_BEACON_enum _beacon
Definition: yocto_api.h:2006
int _parse(YJSONObject *j)
Definition: yocto_api.cpp:2960
virtual int _parseAttr(YJSONObject *json_val)
Definition: yocto_api.cpp:2367
static void RegisterDeviceRemovalCallback(yDeviceUpdateCallback removalCallback)
Definition: yocto_api.cpp:4345
YDEV_DESCR _devdescr
Definition: yocto_api.h:1509
double get_lowestValue(void)
Definition: yocto_api.cpp:7153
int functionCount()
Definition: yocto_api.cpp:6798
YAPI_DEVICE YAPI_FUNCTION_EXPORT yapiGetDevice(const char *device_str, char *errmsg)
Definition: yapi.c:4488
virtual int loadThermistorExtra(string funcId, string jsonExtra)
Definition: yocto_api.cpp:5858
int YAPI_FUNCTION_EXPORT yapiCheckLogicalName(const char *name)
Definition: yapi.c:4464
virtual string toJSON()
Definition: yocto_api.cpp:435
virtual int reboot(int secBeforeReboot)
Definition: yocto_api.cpp:5697
s64 get_upTime(void)
Definition: yocto_api.cpp:5424
Y_CLEARHISTORY_enum
Definition: yocto_api.h:191
_FAR const char * end
Definition: yjson.h:83
u16 deviceid
Definition: ydef.h:449
static const int LUMINOSITY_INVALID
Definition: yocto_api.h:2147
void YAPI_FUNCTION_EXPORT yapiRegisterLogFunction(yapiLogFunction logfun)
Definition: yapi.c:4311
int set_highestValue(double newval)
Definition: yocto_api.cpp:7186
YDataStream * _findDataStream(YDataSet &dataset, const string &def)
Definition: yocto_api.cpp:3105
#define yApproximateSleep(ms)
Definition: yproto.h:433
static double LinearCalibrationHandler(double rawValue, int calibType, intArr params, floatArr rawValues, floatArr refValues)
Definition: yocto_api.cpp:4408
virtual int saveToFlash(void)
Definition: yocto_api.cpp:5670
static const s64 UPTIME_INVALID
Definition: yocto_api.h:2151
virtual YMeasure _decodeTimedReport(double timestamp, vector< int > report)
Definition: yocto_api.cpp:8112
YAPI_FUNCTION YFUN_DESCR
Definition: yocto_api.h:230
static void _yapiDeviceLogCallbackFwd(YDEV_DESCR devdesc, const char *line)
Definition: yocto_api.cpp:3847
static void ClearCache()
Definition: yocto_api.cpp:3567
virtual int registerTimedReportCallback(YSensorTimedReportCallback callback)
Definition: yocto_api.cpp:7923
Tjstate
Definition: yocto_api.h:306
int getInt(const string &key)
Definition: yocto_api.cpp:779
virtual YFirmwareUpdate updateFirmware(string path)
Definition: yocto_api.cpp:5781
virtual int registerValueCallback(YModuleValueCallback callback)
Definition: yocto_api.cpp:5632
int set_advertisedValue(const string &newval)
Definition: yocto_api.cpp:2469
virtual double get_dataSamplesInterval(void)
Definition: yocto_api.cpp:1658
static u64 GetTickCount(void)
Definition: yocto_api.cpp:4755
virtual vector< vector< double > > get_dataRows(void)
Definition: yocto_api.cpp:1806
int YAPI_FUNCTION_EXPORT yapiGetFunctionsByClass(const char *class_str, YAPI_FUNCTION prevfundesc, YAPI_FUNCTION *buffer, int maxsize, int *neededsize, char *errmsg)
Definition: yapi.c:4542
static void _AddToCache(const string &classname, const string &func, YFunction *obj)
Definition: yocto_api.cpp:2345
virtual double get_startTimeUTC(void)
Definition: yocto_api.cpp:1894
YModule * nextModule(void)
Definition: yocto_api.cpp:6705
static void DisableExceptions(void)
Definition: yocto_api.cpp:4288
YFunction * _parent
Definition: yocto_api.h:948
static const Y_RECORDING_enum RECORDING_INVALID
Definition: yocto_api.h:3701
string get_logFrequency(void)
Definition: yocto_api.cpp:7274
virtual int registerValueCallback(YDataLoggerValueCallback callback)
Definition: yocto_api.cpp:9079
string _logFrequency
Definition: yocto_api.h:2678
void YAPI_FUNCTION_EXPORT yapiRegisterHubDiscoveryCallback(yapiHubDiscoveryCallback hubDiscoveryCallback)
Definition: yapi.c:4657
Y_BEACON_enum get_beacon(void)
Definition: yocto_api.cpp:5370
int get_userVar(void)
Definition: yocto_api.cpp:5530
vector< string > _strsplit(const string &str, char delimiter)
Definition: yocto_api.cpp:85
s64 get_timeUTC(void)
Definition: yocto_api.cpp:8763
#define YAPI_INVALID_DOUBLE
Definition: yocto_api.h:73
unsigned _interval
Definition: yocto_api.h:3582
virtual double get_averageValue(void)
Definition: yocto_api.cpp:1929
virtual int _invokeValueCallback(string value)
Definition: yocto_api.cpp:5651
string get_calibrationParam(void)
Definition: yocto_api.cpp:7441
string _funId
Definition: yocto_api.h:1573
void * _userData
Definition: yocto_api.h:1565
int YAPI_FUNCTION_EXPORT yapiGetFunctionsByDevice(YAPI_DEVICE devdesc, YAPI_FUNCTION prevfundesc, YAPI_FUNCTION *buffer, int maxsize, int *neededsize, char *errmsg)
Definition: yapi.c:4552
#define YOCTO_CALIB_TYPE_OFS
Definition: ydef.h:407
virtual string loadAttribute(string attrName)
Definition: yocto_api.cpp:2613
virtual int _invokeTimedReportCallback(YMeasure value)
Definition: yocto_api.cpp:7936
int set_reportFrequency(const string &newval)
Definition: yocto_api.cpp:7369
YAPI_FUNCTION_EXPORT void yapiFreeMem(void *ptr)
Definition: yapi.c:4724
string getKeyFromIdx(int i)
Definition: yocto_api.cpp:896
string _stringValue
Definition: yocto_api.h:367
virtual int _invokeValueCallback(string value)
Definition: yocto_api.cpp:7645
virtual double _applyCalibration(double rawValue)
Definition: yocto_api.cpp:8095
#define YOCTO_FUNCTION_LEN
Definition: ydef.h:425
YMeasure _summary
Definition: yocto_api.h:1307
virtual string get_parentHub(void)
Definition: yocto_api.cpp:6663
vector< YJSONContent * > _arrayValue
Definition: yocto_api.h:345
static const int SENSORSTATE_INVALID
Definition: yocto_api.h:2730
virtual string toJSON()
Definition: yocto_api.cpp:348
int YAPI_FUNCTION_EXPORT yapiJsonGetPath(const char *path, const char *json_data, int json_size, const char **result, char *errmsg)
Definition: yapi.c:4691
int set_persistentSettings(Y_PERSISTENTSETTINGS_enum newval)
Definition: yocto_api.cpp:5290
Y_AUTOSTART_enum _autoStart
Definition: yocto_api.h:3643
string getString()
Definition: yocto_api.cpp:475
virtual int forgetAllDataStreams(void)
Definition: yocto_api.cpp:9116
YSensor * sensor
Definition: yocto_api.h:285
static void RegisterLogFunction(yLogFunction logfun)
Definition: yocto_api.cpp:4308
YJSONNumber * getYJSONNumber(const string &key)
Definition: yocto_api.cpp:768
YAPI_DEVICE YDEV_DESCR
Definition: yocto_api.h:229
s64 _utcStamp
Definition: yocto_api.h:950
static YFunction * _FindFromCache(const string &classname, const string &func)
Definition: yocto_api.cpp:2338
static const string SERIALNUMBER_INVALID
Definition: yocto_api.h:2139
int get_productRelease(void)
Definition: yocto_api.cpp:5209
virtual int calibVersion(string cparams)
Definition: yocto_api.cpp:6048
string _hwId
Definition: yocto_api.h:1574
yJsonState st
Definition: yjson.h:84
vector< vector< double > > _values
Definition: yocto_api.h:972
static YModule * FirstModule(void)
Definition: yocto_api.cpp:6715
vector< YMeasure > _preview
Definition: yocto_api.h:1308
YRETCODE YAPI_FUNCTION_EXPORT yapiHTTPRequestSyncDone(YIOHDL *iohdl, char *errmsg)
Definition: yapi.c:4611
YRETCODE YAPI_FUNCTION_EXPORT yapiHTTPRequestSyncStartOutOfBand(YIOHDL *iohdl, int channel, const char *device, const char *request, int requestsize, char **reply, int *replysize, yapiRequestProgressCallback progress_cb, void *progress_ctx, char *errmsg)
Definition: yapi.c:4601
virtual string toJSON()
Definition: yocto_api.cpp:540
vector< string > _json_get_array(const string &json)
Definition: yocto_api.cpp:2811
virtual vector< YDataSet > get_dataSets(void)
Definition: yocto_api.cpp:9133
vector< int > _calpar
Definition: yocto_api.h:2694
void _clearDataStreamCache()
Definition: yocto_api.cpp:3117
int _userVar
Definition: yocto_api.h:2010
s64 _intValue
Definition: yocto_api.h:385
string get_errorMessage(void)
Definition: yocto_api.cpp:3277
YRETCODE YAPI_FUNCTION_EXPORT yapiGetAllJsonKeys(const char *json_buffer, char *buffer, int buffersize, int *fullsize, char *errmsg)
Definition: yapi.c:4706
static string ysprintf(const char *fmt,...)
Definition: yocto_api.cpp:4997
void clearCache()
Definition: yocto_api.cpp:3412
int get_dataStreams(vector< YDataStream * > &v)
Definition: yocto_api.cpp:8624
static void RegisterCalibrationHandler(int calibrationType, yCalibrationHandler calibrationHandler)
Definition: yocto_api.cpp:4401
virtual string get_lastLogs(void)
Definition: yocto_api.cpp:6587
int getInt(int i)
Definition: yocto_api.cpp:330
static const string PRODUCTNAME_INVALID
Definition: yocto_api.h:2138
u16 YAPI_FUNCTION_EXPORT yapiGetAPIVersion(const char **version, const char **apidate)
Definition: yapi.c:4472
virtual vector< YMeasure > get_measuresAt(YMeasure measure)
Definition: yocto_api.cpp:2221
void(* YFunctionValueCallback)(YFunction *func, const string &functionValue)
Definition: yocto_api.h:79
static string CheckFirmware(string serial, string path, int minrelease)
Definition: yocto_api.cpp:1272
int _decimals
Definition: yocto_api.h:960
virtual string _flattenJsonStruct(string jsoncomplex)
Definition: yocto_api.cpp:6012
static void _ClearCache(void)
Definition: yocto_api.cpp:2350
virtual int get_rowCount(void)
Definition: yocto_api.cpp:1674
YRETCODE YAPI_FUNCTION_EXPORT yapiInitAPI(int detect_type, char *errmsg)
Definition: yapi.c:4295
int set_clearHistory(Y_CLEARHISTORY_enum newval)
Definition: yocto_api.cpp:9004
YRETCODE YAPI_FUNCTION_EXPORT yapiGetFunctionInfoEx(YAPI_FUNCTION fundesc, YAPI_DEVICE *devdesc, char *serial, char *funcId, char *baseType, char *funcName, char *funcVal, char *errmsg)
Definition: yapi.c:4572
void YAPI_FUNCTION_EXPORT yapiRegisterDeviceChangeCallback(yapiDeviceUpdateCallback changeCallback)
Definition: yapi.c:4346
static yCalibrationHandler _getCalibrationHandler(int calibType)
Definition: yocto_api.cpp:4023
YSensorTimedReportCallback _timedReportCallbackSensor
Definition: yocto_api.h:2685
void put(const string &flatAttr)
Definition: yocto_api.cpp:341
void yEnterCriticalSection(yCRITICAL_SECTION *cs)
Definition: ythread.c:647
string _func
Definition: yocto_api.h:1559
static void _yapiHubDiscoveryCallbackFwd(const char *serial, const char *url)
Definition: yocto_api.cpp:3956
static yCRITICAL_SECTION _global_cs
Definition: yocto_api.h:476
static yDeviceUpdateCallback DeviceChangeCallback
Definition: yocto_api.h:482
virtual double _decodeVal(int w)
Definition: yocto_api.cpp:8251
int set_logicalName(const string &newval)
Definition: yocto_api.cpp:2420
Y_AUTOSTART_enum
Definition: yocto_api.h:175
string _decode_json_string(const string &json)
Definition: yocto_api.cpp:2871
static const Y_AUTOSTART_enum AUTOSTART_INVALID
Definition: yocto_api.h:3704
void(* YModuleValueCallback)(YModule *func, const string &functionValue)
Definition: yocto_api.h:89
bool isOnline(void)
Definition: yocto_api.cpp:3291
virtual int calibScale(string unit_name, string sensorType)
Definition: yocto_api.cpp:6070
static const string UNIT_INVALID
Definition: yocto_api.h:2716
string _parseString(yJsonStateMachine &j)
Definition: yocto_api.cpp:2742
int set_beaconDriven(Y_BEACONDRIVEN_enum newval)
Definition: yocto_api.cpp:8966
virtual int _processMore(int newupdate)
Definition: yocto_api.cpp:1147
static queue< yapiDataEvent > _data_events
Definition: yocto_api.h:443
void(* YDataLoggerValueCallback)(YDataLogger *func, const string &functionValue)
Definition: yocto_api.h:163
string _firmwarepath
Definition: yocto_api.h:843
virtual int calibOffset(string unit_name)
Definition: yocto_api.cpp:6091
static YRETCODE Sleep(unsigned ms_duration, string &errmsg)
Definition: yocto_api.cpp:4725
static string _hexStr2Bin(const string &str)
Definition: yocto_api.cpp:4130
static YRETCODE InitAPI(int mode, string &errmsg)
Definition: yocto_api.cpp:4221
int set_userVar(int newval)
Definition: yocto_api.cpp:5563
virtual int registerValueCallback(YFunctionValueCallback callback)
Definition: yocto_api.cpp:2544
static bool ExceptionsDisabled
Definition: yocto_api.h:469
void YAPI_FUNCTION_EXPORT yapiStartStopDeviceLogCallback(const char *serial, int start)
Definition: yapi.c:4325
s64 getLong(int i)
Definition: yocto_api.cpp:335
virtual vector< string > get_functionIds(string funType)
Definition: yocto_api.cpp:5988
virtual int triggerFirmwareUpdate(int secBeforeReboot)
Definition: yocto_api.cpp:5711
YFunctionValueCallback _valueCallbackFunction
Definition: yocto_api.h:1570
Y_PERSISTENTSETTINGS_enum
Definition: yocto_api.h:92
static YRETCODE getFunctionInfoEx(YFUN_DESCR fundesc, YDEV_DESCR &devdescr, string &serial, string &funcId, string &baseType, string &funcName, string &funcVal, string &errmsg)
Definition: yocto_api.cpp:4951
double _offset
Definition: yocto_api.h:2688
YRETCODE _uploadWithProgress(const string &path, const string &content, yapiRequestProgressCallback callback, void *context)
Definition: yocto_api.cpp:3071
virtual YDataLogger * get_dataLogger(void)
Definition: yocto_api.cpp:7823
virtual int _parseAttr(YJSONObject *json_val)
Definition: yocto_api.cpp:7015
virtual string calibConvert(string param, string currentFuncValue, string unit_name, string sensorType)
Definition: yocto_api.cpp:6099
int set_recording(Y_RECORDING_enum newval)
Definition: yocto_api.cpp:8850
#define Y_FRIENDLYNAME_INVALID
Definition: yocto_api.h:234
double _avgVal
Definition: yocto_api.h:965
virtual int registerValueCallback(YSensorValueCallback callback)
Definition: yocto_api.cpp:7626
void yDeleteCriticalSection(yCRITICAL_SECTION *cs)
Definition: ythread.c:682
string _reportFrequency
Definition: yocto_api.h:2679
vector< int > _calpar
Definition: yocto_api.h:969
static int getFunctionsByClass(const string &class_str, YFUN_DESCR prevfundesc, vector< YFUN_DESCR > &buffer, int maxsize, string &errmsg)
Definition: yocto_api.cpp:4852
double _lowestValue
Definition: yocto_api.h:2675
virtual string get_unit(void)
Definition: yocto_api.cpp:2075
int yTryEnterCriticalSection(yCRITICAL_SECTION *cs)
Definition: ythread.c:657
string _lastErrorMsg
Definition: yocto_api.h:1561
YRETCODE _lastErrorType
Definition: yocto_api.h:1560
static YDataLogger * FirstDataLogger(void)
Definition: yocto_api.cpp:9164
virtual int unmuteValueCallbacks(void)
Definition: yocto_api.cpp:2598
static YDataLogger * FindDataLogger(string func)
Definition: yocto_api.cpp:9047
int _luminosity
Definition: yocto_api.h:2005
YJSONType
Definition: yocto_api.h:299
virtual double get_maxValue(void)
Definition: yocto_api.cpp:1771
static const double CURRENTVALUE_INVALID
Definition: yocto_api.h:2717
vector< string > _keys
Definition: yocto_api.h:406
virtual int parse()
Definition: yocto_api.cpp:393
static const Y_ADVMODE_enum ADVMODE_INVALID
Definition: yocto_api.h:2727
virtual vector< string > get_columnNames(void)
Definition: yocto_api.cpp:1722
int set_resolution(double newval)
Definition: yocto_api.cpp:7489
int length()
Definition: yocto_api.cpp:231
YRETCODE _getFunction(int idx, string &serial, string &funcId, string &baseType, string &funcName, string &funcVal, string &errMsg)
Definition: yocto_api.cpp:6770
time_t _stopTime_t
Definition: yocto_api.h:1207
virtual int _invokeValueCallback(string value)
Definition: yocto_api.cpp:9098
double _minVal
Definition: yocto_api.h:1200
static void _yapiDeviceRemovalCallbackFwd(YDEV_DESCR devdesc)
Definition: yocto_api.cpp:3889
virtual string get_progressMessage(void)
Definition: yocto_api.cpp:1329
static const s64 TIMEUTC_INVALID
Definition: yocto_api.h:3697
Y_BEACONDRIVEN_enum _beaconDriven
Definition: yocto_api.h:3644
static double decExp[16]
Definition: yocto_api.cpp:3971
string _className
Definition: yocto_api.h:1558
YRETCODE YAPI_FUNCTION_EXPORT yapiTriggerHubDiscovery(char *errmsg)
Definition: yapi.c:4664
static YSensor * FirstSensor(void)
Definition: yocto_api.cpp:8295
void(* yLogFunction)(const string &msg)
prototype of the log callback
Definition: yocto_api.h:214
double _iresol
Definition: yocto_api.h:2687
s64 getLong(const string &key)
Definition: yocto_api.cpp:790
virtual int parse()
Definition: yocto_api.cpp:503
static yDeviceUpdateCallback DeviceArrivalCallback
Definition: yocto_api.h:480
void setContent(const string &value)
Definition: yocto_api.cpp:485
int _parse(const string &json)
Definition: yocto_api.cpp:1002
vector< double > _calref
Definition: yocto_api.h:971
virtual s64 get_startTimeUTC(void)
Definition: yocto_api.cpp:2092
u64 YAPI_FUNCTION_EXPORT yapiGetTickCount(void)
Definition: yapi.c:2713
YRETCODE YAPI_FUNCTION_EXPORT yapiSleep(int ms_duration, char *errmsg)
Definition: yapi.c:4455
YJSONObject * _cacheJson
Definition: yocto_api.h:1511
void YAPI_FUNCTION_EXPORT yapiRegisterFunctionUpdateCallback(yapiFunctionUpdateCallback updateCallback)
Definition: yapi.c:4353
string _calibrationParam
Definition: yocto_api.h:2681
void registerLogCallback(YModuleLogCallback callback)
Definition: yocto_api.cpp:6944
int _productRelease
Definition: yocto_api.h:2002
static void _yapiLogFunctionFwd(const char *log, u32 loglen)
Definition: yocto_api.cpp:3840
static void _yapiDeviceChangeCallbackFwd(YDEV_DESCR devdesc)
Definition: yocto_api.cpp:3903
Y_RECORDING_enum _recording
Definition: yocto_api.h:3642
Y_ADVMODE_enum
Definition: yocto_api.h:128
vector< int > _calib
Definition: yocto_api.h:1305
static YRETCODE HandleEvents(string &errmsg)
Definition: yocto_api.cpp:4658
YFunction(const string &func)
Definition: yocto_api.cpp:2313
static s16 _doubleToDecimal(double val)
Definition: yocto_api.cpp:3995
void(* YSensorTimedReportCallback)(YSensor *func, YMeasure measure)
Definition: yocto_api.h:125
u64 _cacheStamp
Definition: yocto_api.h:1510
#define Y_FUNCTIONDESCRIPTOR_INVALID
Definition: yocto_api.h:231
virtual bool hasFunction(string funcId)
Definition: yocto_api.cpp:5963
static const int USBCURRENT_INVALID
Definition: yocto_api.h:2152
char serial[YOCTO_SERIAL_LEN]
Definition: ydef.h:454
YRETCODE YAPI_FUNCTION_EXPORT yapiPreregisterHub(const char *url, char *errmsg)
Definition: yapi.c:4421
string _progress_msg
Definition: yocto_api.h:844
double _maxVal
Definition: yocto_api.h:1202
s64 getLong()
Definition: yocto_api.cpp:548
YJSONArray * getYJSONArray(const string &key)
Definition: yocto_api.cpp:754
int _sensorState
Definition: yocto_api.h:2683
virtual int processMore(int progress, string data)
Definition: yocto_api.cpp:1971
int _usbCurrent
Definition: yocto_api.h:2008
yCalibrationHandler _calhdl
Definition: yocto_api.h:2697
static const double RESOLUTION_INVALID
Definition: yocto_api.h:2729
int set_logFrequency(const string &newval)
Definition: yocto_api.cpp:7309
vector< double > _calref
Definition: yocto_api.h:2696
YRETCODE YAPI_FUNCTION_EXPORT yapiUnlockDeviceCallBack(char *errmsg)
Definition: yapi.c:4394
time_t _startTime_t
Definition: yocto_api.h:1206
string _settings
Definition: yocto_api.h:842
static const Y_PERSISTENTSETTINGS_enum PERSISTENTSETTINGS_INVALID
Definition: yocto_api.h:2146
int _caltyp
Definition: yocto_api.h:2693
YJSONType _type
Definition: yocto_api.h:329
vector< YMeasure > _measures
Definition: yocto_api.h:1309
int _data_start
Definition: yocto_api.h:326
void YAPI_FUNCTION_EXPORT yapiRegisterDeviceRemovalCallback(yapiDeviceUpdateCallback removalCallback)
Definition: yapi.c:4339
virtual double get_endTimeUTC(void)
Definition: yocto_api.cpp:1907
static const string INVALID_STRING
Definition: yocto_api.h:470
static vector< YDevice * > _devCache
Definition: yocto_api.h:1506
s64 _endTime
Definition: yocto_api.h:1303
YDataLogger(const string &func)
Definition: yocto_api.cpp:8677
int set_advMode(Y_ADVMODE_enum newval)
Definition: yocto_api.cpp:7425
YFunction * _parent
Definition: yocto_api.h:1298
string _firmwareRelease
Definition: yocto_api.h:2003
YRETCODE YAPI_FUNCTION_EXPORT yapiLockDeviceCallBack(char *errmsg)
Definition: yapi.c:4385
double _doubleValue
Definition: yocto_api.h:386
void YAPI_FUNCTION_EXPORT yapiUnregisterHub(const char *url)
Definition: yapi.c:4430
static const char * hexArray
Definition: yocto_api.cpp:4114
static void _yapiFunctionTimedReportCallbackFwd(YAPI_FUNCTION fundesc, double timestamp, const u8 *bytes, u32 len)
Definition: yocto_api.cpp:3937
int _data_boundary
Definition: yocto_api.h:328
static bool _apiInitialized
Definition: yocto_api.h:475
string functionId(int functionIndex)
Definition: yocto_api.cpp:6823
YRETCODE _nextFunction(string &hwId)
Definition: yocto_api.cpp:2709
static const double CURRENTRAWVALUE_INVALID
Definition: yocto_api.h:2720
string functionValue(int functionIndex)
Definition: yocto_api.cpp:6865
int _rebootCountdown
Definition: yocto_api.h:2009
virtual int log(string text)
Definition: yocto_api.cpp:6606
void parseWithRef(YJSONObject *reference)
Definition: yocto_api.cpp:844
vector< string > keys()
Definition: yocto_api.cpp:759
static void _yapiFunctionUpdateCallbackFwd(YFUN_DESCR fundesc, const char *value)
Definition: yocto_api.cpp:3918
YRETCODE YAPI_FUNCTION_EXPORT yapiUnlockFunctionCallBack(char *errmsg)
Definition: yapi.c:4376
static const double HIGHESTVALUE_INVALID
Definition: yocto_api.h:2719
YModuleValueCallback _valueCallbackModule
Definition: yocto_api.h:2011
string get_reportFrequency(void)
Definition: yocto_api.cpp:7334
double getDouble()
Definition: yocto_api.cpp:564
YOldDataStream(YDataLogger *parent, unsigned run, unsigned stamp, unsigned utc, unsigned itv)
Definition: yocto_api.cpp:8316
bool _isClosed
Definition: yocto_api.h:956
virtual int stopDataLogger(void)
Definition: yocto_api.cpp:7864
virtual ~YJSONObject()
Definition: yocto_api.cpp:615
YRETCODE HTTPRequest(int channel, const string &request, string &buffer, yapiRequestProgressCallback progress_cb, void *progress_ctx, string &errmsg)
Definition: yocto_api.cpp:3665
static yCRITICAL_SECTION _handleEvent_CS
Definition: yocto_api.cpp:63
static void _UpdateValueCallbackList(YFunction *func, bool add)
Definition: yocto_api.cpp:3509
YRETCODE YAPI_FUNCTION_EXPORT yapiGetSubdevices(const char *serial, char *buffer, int buffersize, int *fullsize, char *errmsg)
Definition: yapi.c:4758
Y_PERSISTENTSETTINGS_enum _persistentSettings
Definition: yocto_api.h:2004
#define YISERR(retcode)
Definition: ydef.h:394
string _unit
Definition: yocto_api.h:2673
void(* YModuleLogCallback)(YModule *module, const string &logline)
Definition: yocto_api.h:88
char productname[YOCTO_PRODUCTNAME_LEN]
Definition: ydef.h:453
void clearCache(bool clearSubpath)
Definition: yocto_api.cpp:3779
string getString(int i)
Definition: yocto_api.cpp:314
void(* yDeviceUpdateCallback)(YModule *module)
prototype of the device arrival/update/removal callback
Definition: yocto_api.h:217
int get_luminosity(void)
Definition: yocto_api.cpp:5313
static bool CheckLogicalName(const string &name)
Definition: yocto_api.cpp:4771
vector< string > _columnNames
Definition: yocto_api.h:954
static YFunction * FirstFunction(void)
Definition: yocto_api.cpp:2637
map< string, YJSONContent * > _parsed
Definition: yocto_api.h:405
virtual YDataSet get_recordedData(s64 startTime, s64 endTime)
Definition: yocto_api.cpp:7902
virtual double _decodeAvg(int dw)
Definition: yocto_api.cpp:8268
YSensor(const string &func)
Definition: yocto_api.cpp:6968
double get_highestValue(void)
Definition: yocto_api.cpp:7211
bool _isFloat
Definition: yocto_api.h:387
YDataStream(YFunction *parent)
Definition: yocto_api.cpp:902
double _start
Definition: yocto_api.h:1198
YModuleLogCallback _logCallback
Definition: yocto_api.h:2012
virtual int startDataLogger(void)
Definition: yocto_api.cpp:7847
virtual int loadStream(void)
Definition: yocto_api.cpp:1550
double _offset
Definition: yocto_api.h:961
YModule * yFindModule(const string &func)
Definition: yocto_api.h:3548
static YRETCODE TriggerHubDiscovery(string &errmsg)
Definition: yocto_api.cpp:4381
static yLogFunction LogFunction
Definition: yocto_api.h:479
virtual YMeasure get_summary(void)
Definition: yocto_api.cpp:2180
bool has(const string &key)
Definition: yocto_api.cpp:735
YRETCODE YAPI_FUNCTION_EXPORT yapiHTTPRequestAsyncOutOfBand(int channel, const char *device, const char *request, int requestsize, yapiRequestAsyncCallback callback, void *context, char *errmsg)
Definition: yapi.c:4638
int loadStream(void)
Definition: yocto_api.cpp:8333
bool _isScal
Definition: yocto_api.h:2691
string get_serialNumber(void)
Definition: yocto_api.cpp:5151
int set_beacon(Y_BEACON_enum newval)
Definition: yocto_api.cpp:5401
static int SkipGarbage(const string &data, int start, int stop)
Definition: yocto_api.cpp:154
void YAPI_FUNCTION_EXPORT yapiRegisterDeviceArrivalCallback(yapiDeviceUpdateCallback arrivalCallback)
Definition: yapi.c:4332
string _requestEx(int tcpchan, const string &request, yapiRequestProgressCallback callback, void *context)
Definition: yocto_api.cpp:3010
YRETCODE _setAttr(string attrname, string newvalue)
Definition: yocto_api.cpp:2968
virtual double _decodeAvg(int dw, int count)
Definition: yocto_api.cpp:1576
YSensorValueCallback _valueCallbackSensor
Definition: yocto_api.h:2684
int set_timeUTC(s64 newval)
Definition: yocto_api.cpp:8794
int get_sensorState(void)
Definition: yocto_api.cpp:7545
int get_currentRunIndex(void)
Definition: yocto_api.cpp:8734
virtual double get_data(int row, int col)
Definition: yocto_api.cpp:1830
YRETCODE YAPI_FUNCTION_EXPORT yapiGetDeviceInfo(YAPI_DEVICE devdesc, yDeviceSt *infos, char *errmsg)
Definition: yapi.c:4506
static YRETCODE handleEvents(string &errmsg)
Definition: yocto_api.cpp:4985
int get_rebootCountdown(void)
Definition: yocto_api.cpp:5484
double(* yCalibrationHandler)(double rawValue, int calibType, vector< int > params, vector< double > rawValues, vector< double > refValues)
Definition: yocto_api.h:227
s64 _upTime
Definition: yocto_api.h:2007
static const Y_BEACON_enum BEACON_INVALID
Definition: yocto_api.h:2150
YRETCODE YAPI_FUNCTION_EXPORT yapiUpdateDeviceList(u32 forceupdate, char *errmsg)
Definition: yapi.c:4437
virtual int muteValueCallbacks(void)
Definition: yocto_api.cpp:2583
vector< int > intArr
Definition: yocto_api.h:226
Y_CLEARHISTORY_enum _clearHistory
Definition: yocto_api.h:3645
YJSONType getJSONType()
Definition: yocto_api.cpp:149
static u64 _nextEnum
Definition: yocto_api.h:445
YRETCODE YAPI_FUNCTION_EXPORT yapiCheckFirmware(const char *serial, const char *rev, const char *path, char *buffer, int buffersize, int *fullsize, char *errmsg)
Definition: yapi.c:4730
virtual int set_extraSettings(string jsonExtra)
Definition: yocto_api.cpp:5883
string _functionId
Definition: yocto_api.h:1300
unsigned _timeStamp
Definition: yocto_api.h:3581
bool _isScal
Definition: yocto_api.h:958
double _scale
Definition: yocto_api.h:2689
static YFunction * FindFunction(string func)
Definition: yocto_api.cpp:2512
virtual vector< YMeasure > get_measures(void)
Definition: yocto_api.cpp:2302
virtual int _invokeValueCallback(string value)
Definition: yocto_api.cpp:2563
YJSONObject * getYJSONObject(int i)
Definition: yocto_api.cpp:309
static const Y_CLEARHISTORY_enum CLEARHISTORY_INVALID
Definition: yocto_api.h:3710
#define YOCTO_LOGICAL_LEN
Definition: ydef.h:424
virtual double get_minValue(void)
Definition: yocto_api.cpp:1918
virtual ~YDataStream()
Definition: yocto_api.cpp:959
static int getAllDevices(vector< YDEV_DESCR > &buffer, string &errmsg)
Definition: yocto_api.cpp:4797
YRETCODE requestAPI(YJSONObject *&apires, string &errmsg)
Definition: yocto_api.cpp:3686
static map< int, yCalibrationHandler > _calibHandlers
Definition: yocto_api.h:447
YRETCODE YAPI_FUNCTION_EXPORT yapiRegisterHub(const char *url, char *errmsg)
Definition: yapi.c:4412
static YRETCODE UpdateDeviceList(string &errmsg)
Definition: yocto_api.cpp:4584
#define Y_DATA_INVALID
Definition: yocto_api.h:236
YRETCODE YAPI_FUNCTION_EXPORT yapiHandleEvents(char *errmsg)
Definition: yapi.c:4446
virtual int calibrateFromPoints(vector< double > rawValues, vector< double > refValues)
Definition: yocto_api.cpp:7966
YRETCODE YAPI_FUNCTION_EXPORT yapiUpdateFirmwareEx(const char *serial, const char *firmwarePath, const char *settings, int force, int startUpdate, char *msg)
Definition: yapi.c:4748
YRETCODE YAPI_FUNCTION_EXPORT yapiGetDevicePathEx(const char *serial, char *rootdevice, char *request, int requestsize, int *neededsize, char *errmsg)
Definition: yapi.c:4524
YDataSet(YFunction *parent, const string &functionId, const string &unit, s64 startTime, s64 endTime)
Definition: yocto_api.cpp:969


yoctopuce_altimeter
Author(s): Anja Sheppard
autogenerated on Mon Jun 10 2019 15:49:10