/// <summary> /// Builds a list of all data streams hold by the data logger (legacy method). /// The caller must pass by reference an empty array to hold YDataStream /// objects, and the function fills it with objects describing available /// data sequences. /// /// This is the old way to retrieve data from the DataLogger. /// For new applications, you should rather use get_dataSets() /// method, or call directly get_recordedData() on the /// sensor object. /// </summary> /// <param name="v"> : an array of YDataStream objects to be filled in /// </param> /// <returns> YAPI.SUCCESS if the call succeeds. /// </returns> /// <exception cref="YAPI_Exception"> on error </exception> public virtual async Task <int> get_dataStreams(List <YDataStream> v) { byte[] loadval = await getData(null, null); YJSONArray jsonAllStreams = new YJSONArray(YAPI.DefaultEncoding.GetString(loadval)); jsonAllStreams.parse(); if (jsonAllStreams.Length == 0) { return(YAPI.SUCCESS); } if (jsonAllStreams.get(0) is YJSONArray) { // old datalogger format: [runIdx, timerel, utc, interval] _throw(YAPI.NOT_SUPPORTED, "Old datalogger is no more supported. Please upgrade your device."); return(YAPI.NOT_SUPPORTED); } else { // new datalogger format: {"id":"...","unit":"...","streams":["...",...]} List <YDataSet> sets = await this.parse_dataSets(YAPI.DefaultEncoding.GetBytes(jsonAllStreams.ToString())); for (int j = 0; j < sets.Count; j++) { List <YDataStream> ds = await sets[j].get_privateDataStreams(); for (int si = 0; si < ds.Count; si++) { v.Add(ds[si]); } } return(YAPI.SUCCESS); } }
private string imm_get_json_path_array(YJSONArray jsonArray, string[] paths, int ofs) { int key = Convert.ToInt32(paths[ofs]); if (jsonArray.Length <= key) { return(""); } YJSONContent obj = jsonArray.get(key); if (obj != null) { if (paths.Length == ofs + 1) { return(obj.ToString()); } if (obj is YJSONArray) { return(imm_get_json_path_array(jsonArray.getYJSONArray(key), paths, ofs + 1)); } else if (obj is YJSONObject) { return(imm_get_json_path_struct(jsonArray.getYJSONObject(key), paths, ofs + 1)); } } return(""); }
private void convert(YJSONObject reference, YJSONArray newArray) { int length = newArray.Length; for (int i = 0; i < length; i++) { string key = reference.getKeyFromIdx(i); YJSONContent new_item = newArray.get(i); YJSONContent reference_item = reference.get(key); if (new_item.getJSONType() == reference_item.getJSONType()) { parsed.Add(key, new_item); _keys.Add(key); } else if (new_item.getJSONType() == YJSONType.ARRAY && reference_item.getJSONType() == YJSONType.OBJECT) { YJSONObject jobj = new YJSONObject(new_item._data, new_item._data_start, reference_item._data_boundary); jobj.convert((YJSONObject)reference_item, (YJSONArray)new_item); parsed.Add(key, jobj); _keys.Add(key); } else { throw new System.Exception("Unable to convert " + new_item.getJSONType().ToString() + " to " + reference.getJSONType().ToString()); } } }
public void parseWithRef(YJSONObject reference) { if (reference != null) { try { YJSONArray yzon = new YJSONArray(_data, _data_start, _data_boundary); yzon.parse(); convert(reference, yzon); return; } catch (Exception) { } } this.parse(); }
protected internal virtual List <string> imm_json_get_array(byte[] json) { YJSONArray array = new YJSONArray(YAPI.DefaultEncoding.GetString(json)); array.parse(); List <string> list = new List <string>(); int len = array.Length; for (int i = 0; i < len; i++) { YJSONContent o = array.get(i); list.Add(o.toJSON()); } return(list); }
public override async Task <List <string> > getBootloaders() { List <string> res = new List <string>(); byte[] raw_data = await _notificationHandler.hubRequestSync("GET /flash.json?a=list", null, YIO_DEFAULT_TCP_TIMEOUT); string jsonstr = YAPI.DefaultEncoding.GetString(raw_data); YJSONObject flashres = new YJSONObject(jsonstr); flashres.parse(); YJSONArray list = flashres.getYJSONArray("list"); for (int i = 0; i < list.Length; i++) { res.Add(list.getString(i)); } return(res); }
internal static YJSONContent ParseJson(string data, int start, int stop) { int cur_pos = SkipGarbage(data, start, stop); YJSONContent res; if (data[cur_pos] == '[') { res = new YJSONArray(data, start, stop); } else if (data[cur_pos] == '{') { res = new YJSONObject(data, start, stop); } else if (data[cur_pos] == '"') { res = new YJSONString(data, start, stop); } else { res = new YJSONNumber(data, start, stop); } res.parse(); return(res); }
public override int parse() { string current_name = ""; int name_start = _data_start; int cur_pos = SkipGarbage(_data, _data_start, _data_boundary); if (_data.Length <= cur_pos || _data[cur_pos] != '{') { throw new System.Exception(FormatError("Opening braces was expected", cur_pos)); } cur_pos++; Tjstate state = Tjstate.JWAITFORNAME; while (cur_pos < _data_boundary) { char sti = _data[cur_pos]; switch (state) { case Tjstate.JWAITFORNAME: if (sti == '"') { state = Tjstate.JWAITFORENDOFNAME; name_start = cur_pos + 1; } else if (sti == '}') { _data_len = cur_pos + 1 - _data_start; return(_data_len); } else { if (sti != ' ' && sti != '\n' && sti != '\r') { throw new System.Exception(FormatError("invalid char: was expecting \"", cur_pos)); } } break; case Tjstate.JWAITFORENDOFNAME: if (sti == '"') { current_name = _data.Substring(name_start, cur_pos - name_start); state = Tjstate.JWAITFORCOLON; } else { if (sti < 32) { throw new System.Exception(FormatError("invalid char: was expecting an identifier compliant char", cur_pos)); } } break; case Tjstate.JWAITFORCOLON: if (sti == ':') { state = Tjstate.JWAITFORDATA; } else { if (sti != ' ' && sti != '\n' && sti != '\r') { throw new System.Exception( FormatError("invalid char: was expecting \"", cur_pos)); } } break; case Tjstate.JWAITFORDATA: if (sti == '{') { YJSONObject jobj = new YJSONObject(_data, cur_pos, _data_boundary); int len = jobj.parse(); cur_pos += len; parsed.Add(current_name, jobj); _keys.Add(current_name); state = Tjstate.JWAITFORNEXTSTRUCTMEMBER; //cur_pos is already incremented continue; } else if (sti == '[') { YJSONArray jobj = new YJSONArray(_data, cur_pos, _data_boundary); int len = jobj.parse(); cur_pos += len; parsed.Add(current_name, jobj); _keys.Add(current_name); state = Tjstate.JWAITFORNEXTSTRUCTMEMBER; //cur_pos is already incremented continue; } else if (sti == '"') { YJSONString jobj = new YJSONString(_data, cur_pos, _data_boundary); int len = jobj.parse(); cur_pos += len; parsed.Add(current_name, jobj); _keys.Add(current_name); state = Tjstate.JWAITFORNEXTSTRUCTMEMBER; //cur_pos is already incremented continue; } else if (sti == '-' || (sti >= '0' && sti <= '9')) { YJSONNumber jobj = new YJSONNumber(_data, cur_pos, _data_boundary); int len = jobj.parse(); cur_pos += len; parsed.Add(current_name, jobj); _keys.Add(current_name); state = Tjstate.JWAITFORNEXTSTRUCTMEMBER; //cur_pos is already incremented continue; } else if (sti != ' ' && sti != '\n' && sti != '\r') { throw new System.Exception(FormatError("invalid char: was expecting \",0..9,t or f", cur_pos)); } break; case Tjstate.JWAITFORNEXTSTRUCTMEMBER: if (sti == ',') { state = Tjstate.JWAITFORNAME; name_start = cur_pos + 1; } else if (sti == '}') { _data_len = cur_pos + 1 - _data_start; return(_data_len); } else { if (sti != ' ' && sti != '\n' && sti != '\r') { throw new System.Exception(FormatError("invalid char: was expecting ,", cur_pos)); } } break; case Tjstate.JWAITFORNEXTARRAYITEM: case Tjstate.JWAITFORSTRINGVALUE: case Tjstate.JWAITFORINTVALUE: case Tjstate.JWAITFORBOOLVALUE: throw new System.Exception(FormatError("invalid state for YJSONObject", cur_pos)); } cur_pos++; } throw new System.Exception(FormatError("unexpected end of data", cur_pos)); }
public override int parse() { int cur_pos = SkipGarbage(_data, _data_start, _data_boundary); if (_data[cur_pos] != '[') { throw new System.Exception(FormatError("Opening braces was expected", cur_pos)); } cur_pos++; Tjstate state = Tjstate.JWAITFORDATA; while (cur_pos < _data_boundary) { char sti = _data[cur_pos]; switch (state) { case Tjstate.JWAITFORDATA: if (sti == '{') { YJSONObject jobj = new YJSONObject(_data, cur_pos, _data_boundary); int len = jobj.parse(); cur_pos += len; _arrayValue.Add(jobj); state = Tjstate.JWAITFORNEXTARRAYITEM; //cur_pos is already incremented continue; } else if (sti == '[') { YJSONArray jobj = new YJSONArray(_data, cur_pos, _data_boundary); int len = jobj.parse(); cur_pos += len; _arrayValue.Add(jobj); state = Tjstate.JWAITFORNEXTARRAYITEM; //cur_pos is already incremented continue; } else if (sti == '"') { YJSONString jobj = new YJSONString(_data, cur_pos, _data_boundary); int len = jobj.parse(); cur_pos += len; _arrayValue.Add(jobj); state = Tjstate.JWAITFORNEXTARRAYITEM; //cur_pos is already incremented continue; } else if (sti == '-' || (sti >= '0' && sti <= '9')) { YJSONNumber jobj = new YJSONNumber(_data, cur_pos, _data_boundary); int len = jobj.parse(); cur_pos += len; _arrayValue.Add(jobj); state = Tjstate.JWAITFORNEXTARRAYITEM; //cur_pos is already incremented continue; } else if (sti == ']') { _data_len = cur_pos + 1 - _data_start; return(_data_len); } else if (sti != ' ' && sti != '\n' && sti != '\r') { throw new System.Exception(FormatError("invalid char: was expecting \",0..9,t or f", cur_pos)); } break; case Tjstate.JWAITFORNEXTARRAYITEM: if (sti == ',') { state = Tjstate.JWAITFORDATA; } else if (sti == ']') { _data_len = cur_pos + 1 - _data_start; return(_data_len); } else { if (sti != ' ' && sti != '\n' && sti != '\r') { throw new System.Exception(FormatError("invalid char: was expecting ,", cur_pos)); } } break; default: throw new System.Exception(FormatError("invalid state for YJSONObject", cur_pos)); } cur_pos++; } throw new System.Exception(FormatError("unexpected end of data", cur_pos)); }
internal override async Task <List <string> > firmwareUpdate(string serial, YFirmwareFile firmware, byte[] settings, UpdateProgress progress) { bool use_self_flash = false; string baseurl = ""; bool need_reboot = true; if (_serial.StartsWith("VIRTHUB", StringComparison.Ordinal)) { use_self_flash = false; } else if (serial.Equals(_serial)) { use_self_flash = true; } else { // check if subdevice support self flashing try { await _notificationHandler.hubRequestSync("GET /bySerial/" + serial + "/flash.json?a=state", null, YIO_DEFAULT_TCP_TIMEOUT); baseurl = "/bySerial/" + serial; use_self_flash = true; } catch (YAPI_Exception) { } } //5% -> 10% await progress(5, "Enter in bootloader"); List <string> bootloaders = await getBootloaders(); bool is_shield = serial.StartsWith("YHUBSHL1", StringComparison.Ordinal); foreach (string bl in bootloaders) { if (bl.Equals(serial)) { need_reboot = false; } else if (is_shield) { if (bl.StartsWith("YHUBSHL1", StringComparison.Ordinal)) { throw new YAPI_Exception(YAPI.IO_ERROR, "Only one YoctoHub-Shield is allowed in update mode"); } } } if (!use_self_flash && need_reboot && bootloaders.Count >= 4) { throw new YAPI_Exception(YAPI.IO_ERROR, "Too many devices in update mode"); } // ensure flash engine is not busy byte[] bytes = await _notificationHandler.hubRequestSync("GET" + baseurl + "/flash.json?a=state", null, YIO_DEFAULT_TCP_TIMEOUT); string uploadstate = YAPI.DefaultEncoding.GetString(bytes); YJSONObject uploadres = new YJSONObject(uploadstate); uploadres.parse(); string state = uploadres.getYJSONString("state").getString(); if (state.Equals("uploading") || state.Equals("flashing")) { throw new YAPI_Exception(YAPI.IO_ERROR, "Cannot start firmware update: busy (" + state + ")"); } // start firmware upload //10% -> 40% await progress(10, "Send firmware file"); byte[] head_body = YDevice.imm_formatHTTPUpload("firmware", firmware.Data); await _notificationHandler.hubRequestSync("POST " + baseurl + "/upload.html", head_body, 0); //check firmware upload result bytes = await _notificationHandler.hubRequestSync("GET " + baseurl + "/flash.json?a=state", null, YIO_10_MINUTES_TCP_TIMEOUT); string uploadresstr = YAPI.DefaultEncoding.GetString(bytes); uploadres = new YJSONObject(uploadresstr); uploadres.parse(); state = uploadres.getString("state"); if (state != "valid") { throw new YAPI_Exception(YAPI.IO_ERROR, "Upload of firmware failed: invalid firmware(" + state + ")"); } if (uploadres.getInt("progress") != 100) { throw new YAPI_Exception(YAPI.IO_ERROR, "Upload of firmware failed: incomplete upload"); } if (use_self_flash) { byte[] startupConf; string json = YAPI.DefaultEncoding.GetString(settings); YJSONObject jsonObject = new YJSONObject(json); jsonObject.parse(); YJSONObject settingsOnly = jsonObject.getYJSONObject("api"); settingsOnly.remove("services"); string startupConfStr = settingsOnly.ToString(); startupConf = YAPI.DefaultEncoding.GetBytes(startupConfStr); await progress(20, "Upload startupConf.json"); head_body = YDevice.imm_formatHTTPUpload("startupConf.json", startupConf); await _notificationHandler.hubRequestSync("POST " + baseurl + "/upload.html", head_body, YIO_10_MINUTES_TCP_TIMEOUT); await progress(20, "Upload firmwareConf"); head_body = YDevice.imm_formatHTTPUpload("firmwareConf", startupConf); await _notificationHandler.hubRequestSync("POST " + baseurl + "/upload.html", head_body, YIO_10_MINUTES_TCP_TIMEOUT); } //40%-> 80% if (use_self_flash) { await progress(40, "Flash firmware"); // the hub itself -> reboot in autoflash mode await _notificationHandler.hubRequestSync( "GET " + baseurl + "/api/module/rebootCountdown?rebootCountdown=-1003", null, YIO_DEFAULT_TCP_TIMEOUT); await Task.Delay(TimeSpan.FromSeconds(7)); } else { // reboot device to bootloader if needed if (need_reboot) { // reboot subdevice await _notificationHandler.hubRequestSync( "GET /bySerial/" + serial + "/api/module/rebootCountdown?rebootCountdown=-2", null, YIO_DEFAULT_TCP_TIMEOUT); } // verify that the device is in bootloader ulong timeout = YAPI.GetTickCount() + YPROG_BOOTLOADER_TIMEOUT; byte[] res; bool found = false; await progress(40, "Wait for device to be in bootloader"); do { List <string> list = await getBootloaders(); foreach (string bl in list) { if (bl.Equals(serial)) { found = true; break; } } if (!found) { //fixme: replace by async //Thread.Sleep(100); } } while (!found && YAPI.GetTickCount() < timeout); //start flash await progress(45, "Flash firmware"); res = await _notificationHandler.hubRequestSync("GET /flash.json?a=flash&s=" + serial, null, YIO_10_MINUTES_TCP_TIMEOUT); string jsonstr = YAPI.DefaultEncoding.GetString(res); YJSONObject flashres = new YJSONObject(jsonstr); flashres.parse(); YJSONArray logslist = flashres.getYJSONArray("logs"); List <string> logs = new List <string>(logslist.Length); for (int i = 0; i < logslist.Length; i++) { logs.Add(logslist.getString(i)); } return(logs); } return(null); }
internal override async Task updateDeviceListAsync(bool forceupdate) { ulong now = YAPI.GetTickCount(); if (forceupdate) { _devListExpires = 0; } if (_devListExpires > now) { return; } if (!_notificationHandler.Connected) { if (_reportConnnectionLost) { throw new YAPI_Exception(YAPI.TIMEOUT, "hub " + _http_params.Url + " is not reachable"); } else { return; } } string json_data; try { byte[] data = await _notificationHandler.hubRequestSync("GET /api.json", null, YIO_DEFAULT_TCP_TIMEOUT); json_data = YAPI.DefaultEncoding.GetString(data); } catch (YAPI_Exception) { if (_reportConnnectionLost) { throw; } return; } Dictionary <string, List <YPEntry> > yellowPages = new Dictionary <string, List <YPEntry> >(); List <WPEntry> whitePages = new List <WPEntry>(); YJSONObject loadval = new YJSONObject(json_data); loadval.parse(); if (!loadval.has("services") || !loadval.getYJSONObject("services").has("whitePages")) { throw new YAPI_Exception(YAPI.INVALID_ARGUMENT, "Device " + _http_params.Host + " is not a hub"); } _serial = loadval.getYJSONObject("module").getString("serialNumber"); YJSONArray whitePages_json = loadval.getYJSONObject("services").getYJSONArray("whitePages"); YJSONObject yellowPages_json = loadval.getYJSONObject("services").getYJSONObject("yellowPages"); if (loadval.has("network")) { string adminpass = loadval.getYJSONObject("network").getString("adminPassword"); _writeProtected = adminpass.Length > 0; } // Reindex all functions from yellow pages //HashMap<String, Boolean> refresh = new HashMap<String, Boolean>(); List <string> keys = yellowPages_json.keys(); foreach (string classname in keys) { YJSONArray yprecs_json = yellowPages_json.getYJSONArray(classname); List <YPEntry> yprecs_arr = new List <YPEntry>(yprecs_json.Length); for (int i = 0; i < yprecs_json.Length; i++) { YPEntry yprec = new YPEntry(yprecs_json.getYJSONObject(i)); yprecs_arr.Add(yprec); } yellowPages[classname] = yprecs_arr; } _serialByYdx.Clear(); // Reindex all devices from white pages for (int i = 0; i < whitePages_json.Length; i++) { YJSONObject jsonObject = whitePages_json.getYJSONObject(i); WPEntry devinfo = new WPEntry(jsonObject); int index = jsonObject.getInt("index"); _serialByYdx[index] = devinfo.SerialNumber; whitePages.Add(devinfo); } await updateFromWpAndYp(whitePages, yellowPages); // reset device list cache timeout for this hub now = YAPI.GetTickCount(); _devListExpires = now + _devListValidity; }