UNPKG

@iotile/iotile-cloud

Version:

A typescript library for interfacing with the IOTile Cloud API

1,456 lines (1,411 loc) 342 kB
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('@iotile/iotile-common'), require('typescript-logging')) : typeof define === 'function' && define.amd ? define(['exports', '@iotile/iotile-common', 'typescript-logging'], factory) : (factory((global.iotileCloud = {}),global.iotileCommon,global.typescriptLogging)); }(this, (function (exports,iotileCommon,typescriptLogging) { 'use strict'; var ApiFilter = /** @class */ (function () { function ApiFilter() { this.filters = []; } ApiFilter.prototype.filterString = function () { // Build a '?name1=val1&name2=val2' string if (this.filters.length) { var dataFilter = '?' + this.filters.join('&'); return dataFilter; } return ''; }; ApiFilter.prototype.addFilter = function (name, value, unique) { if (unique === void 0) { unique = false; } var arg = name + '=' + value; if (unique) { this.removeFilter(name); } this.filters.push(arg); }; ApiFilter.prototype.removeFilter = function (name) { var arg = name + '='; this.filters = this.filters.filter(function (item) { return item.indexOf(arg) !== 0; }); }; // nb: if there are duplicate values for a key, returns the first ApiFilter.prototype.getFilter = function (name) { var value; for (var _i = 0, _a = this.filters; _i < _a.length; _i++) { var filter = _a[_i]; var _b = filter.split('='), key = _b[0], val = _b[1]; if (key == name) { value = val; break; } } return value; }; ApiFilter.prototype.copy = function () { var copy = new ApiFilter(); for (var _i = 0, _a = this.filters; _i < _a.length; _i++) { var filter = _a[_i]; var _b = filter.split('='), key = _b[0], val = _b[1]; copy.addFilter(key, val); } return copy; }; return ApiFilter; }()); var Credentials = /** @class */ (function () { function Credentials(username, password) { this.username = username; this.password = password; this.token = ''; } Credentials.prototype.getPayload = function () { return { username: this.username, password: this.password }; }; Credentials.prototype.setToken = function (token) { this.token = token; }; Credentials.prototype.getToken = function () { return this.token; }; Credentials.prototype.clearToken = function () { this.token = ''; }; return Credentials; }()); var DataBlock = /** @class */ (function () { function DataBlock(data) { this.description = ''; this.pid = ''; this.id = data.id; this.slug = data.slug; this.title = data.title; this.org = data.org; this.block = data.block; this.sensorGraphSlug = data.sg; this.createdOn = new Date(data.created_on); this.createdBy = data.created_by; if ('description' in data) { this.description = data.description; } if ('pid' in data) { this.pid = data.pid; } } DataBlock.prototype.getPostPayload = function () { var payload = { title: this.title, device: this.slug, description: '' }; if (this.description) { payload.description = this.description; } if (this.onComplete) { payload['on_complete'] = this.onComplete; } return payload; }; return DataBlock; }()); var DataFilterArgs = /** @class */ (function () { function DataFilterArgs() { } DataFilterArgs.prototype.buildFilterString = function () { var parameters = []; if (this.startDate) { parameters.push('start=' + this.startDate.toISOString()); } var now = new Date(); if (!this.endDate || this.endDate > now) { this.endDate = now; } if (this.endDate) { parameters.push('end=' + this.endDate.toISOString()); } if (this.lastN) { parameters.push('lastn=' + this.lastN); } if (this.page) { parameters.push('page=' + this.page); } if (this.pageSize) { parameters.push('page_size=' + this.pageSize); } if (this.filter) { parameters.push('filter=' + this.filter); } if (this.startIncrementalId) { parameters.push('streamer_id_0=' + this.startIncrementalId); } if (this.endIncrementalId) { parameters.push('streamer_id_1=' + this.endIncrementalId); } if (this.extras && this.extras.length > 0) { this.extras.forEach(function (p) { parameters.push(p); }); } if (parameters.length) { var dataFilter = '?' + parameters.join('&'); return dataFilter; } return ''; }; DataFilterArgs.prototype.buildFilterLabel = function () { var filterLabel = ''; if (this.startDate) { filterLabel += ' from ' + this.startDate.toLocaleDateString('en-US'); } if (this.endDate) { filterLabel += ' to ' + this.endDate.toLocaleDateString('en-US'); } if (this.lastN) { filterLabel += ' last ' + this.lastN + ' entries'; } if (!this.startDate && !this.endDate && !this.lastN) { filterLabel = ''; } return filterLabel; }; return DataFilterArgs; }()); /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } function __awaiter(thisArg, _arguments, P, generator) { return new (P || (P = Promise))(function (resolve, reject) { function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); } step((generator = generator.apply(thisArg, _arguments || [])).next()); }); } function __generator(thisArg, body) { var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g; return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; function verb(n) { return function (v) { return step([n, v]); }; } function step(op) { if (f) throw new TypeError("Generator is already executing."); while (_) try { if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; if (y = 0, t) op = [op[0] & 2, t.value]; switch (op[0]) { case 0: case 1: t = op; break; case 4: _.label++; return { value: op[1], done: false }; case 5: _.label++; y = op[1]; op = [0]; continue; case 7: op = _.ops.pop(); _.trys.pop(); continue; default: if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } if (t[2]) _.ops.pop(); _.trys.pop(); continue; } op = body.call(thisArg, _); } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; } } var Page = /** @class */ (function () { function Page(url, thisPage, pageCount) { this.baseUrl = url; this.page = thisPage; this.pageCount = pageCount; } Page.prototype.pageUrl = function () { var url = this.baseUrl; url += '&page=' + this.page; return url; }; return Page; }()); var DataPage = /** @class */ (function (_super) { __extends(DataPage, _super); function DataPage(url, thisPage, pageCount, stream) { var _this = _super.call(this, url, thisPage, pageCount) || this; _this.stream = stream; _this.data = []; return _this; } return DataPage; }(Page)); var DataPoint = /** @class */ (function () { function DataPoint(data) { if (data === void 0) { data = {}; } this.timestamp = new Date(data.timestamp); if ('id' in data) { this.id = data.id; } if ('stream' in data) { // Only getData returns a stream slug this.stream = data.stream; } if ('value' in data) { // NewScheme: Value represents a number as per the Stream's VarType this.value = data.value; } if ('int_value' in data) { // OldScheme: We only store the raw number from the device this.rawValue = data.int_value; } if ('output_value' in data) { this.outValue = data.output_value; } if ('display_value' in data) { this.displayValue = data.display_value; } if ('streamer_local_id' in data) { this.incrementalId = data.streamer_local_id; } if ('dirty_ts' in data) { this.dirtyTimestamp = data.dirty_ts; } } return DataPoint; }()); (function (DeltaStatus) { DeltaStatus[DeltaStatus["Applies"] = 0] = "Applies"; DeltaStatus[DeltaStatus["Outdated"] = 1] = "Outdated"; DeltaStatus[DeltaStatus["Conflicted"] = 2] = "Conflicted"; })(exports.DeltaStatus || (exports.DeltaStatus = {})); var ModelDelta = /** @class */ (function () { function ModelDelta(name, slug, guidString) { if (guidString == null) { this.id = iotileCommon.guid(); } else { this.id = guidString; } this.slug = slug; this.classname = name; } ModelDelta.prototype.serialize = function () { return { classname: this.classname, guid: this.id, slug: this.slug, args: this.serializeArguments() }; }; return ModelDelta; }()); var Device = /** @class */ (function () { function Device(data) { if (data === void 0) { data = {}; } this.busy = false; this.id = data.id; this.slug = data.slug; this.gid = data.gid; this.label = data.label || data.slug; this.template = data.template || ''; this.rawData = data; this.project = data.project; this.drifterMode = data.drifter_mode || false; this.isModified = false; this.active = data.active || true; this.state = data.state || undefined; this.externalId = data.external_id || undefined; this.sensorGraphSlug = data.sg; this.properties = []; this.propertyMap = {}; if ('busy' in data) { this.busy = data.busy; } if ('org' in data) { this.org = data.org; } if ('lat' in data && data.lat !== null) { this.lat = parseFloat(data.lat); } if ('lon' in data && data.lon !== null) { this.lon = parseFloat(data.lon); } } Device.prototype.toJson = function () { var result = this.rawData; result.label = this.label; result.drifter_mode = this.drifterMode; result.lat = this.lat; result.lon = this.lon; return result; }; Device.prototype.getPatchPayload = function () { var payload = { label: this.label }; if (this.lat) { payload.lat = this.lat; } if (this.lon) { payload.lon = this.lon; } payload.active = this.active; if (this.state) { payload.state = this.state; } return payload; }; Device.prototype.addProperties = function (properties) { var _this = this; this.properties = properties; this.properties.forEach(function (property) { _this.propertyMap[property.name] = property; }); }; Device.prototype.getProperty = function (name) { return this.propertyMap[name]; }; Device.prototype.isDataBlock = function () { return this.dataBlock != null; }; Device.prototype.getStateDisplay = function () { if (this.state) { var factory = { N0: 'Available', N1: 'Active', B0: 'Resetting', B1: 'Archiving' }; return factory[this.state]; } else { return ''; } }; return Device; }()); var DeviceDelta = /** @class */ (function (_super) { __extends(DeviceDelta, _super); function DeviceDelta() { return _super !== null && _super.apply(this, arguments) || this; } return DeviceDelta; }(ModelDelta)); var DeviceLocationDelta = /** @class */ (function (_super) { __extends(DeviceLocationDelta, _super); function DeviceLocationDelta(oldLat, oldLng, newLat, newLng, slug, guid$$1) { var _this = _super.call(this, DeviceLocationDelta.ClassName, slug, guid$$1) || this; _this.oldLat = oldLat; _this.oldLng = oldLng; _this.newLat = newLat; _this.newLng = newLng; return _this; } DeviceLocationDelta.prototype.check = function (device) { if (device.lat === this.newLat && device.lon === this.newLng) { return exports.DeltaStatus.Outdated; } else if ((device.lat === this.oldLat && device.lon === this.oldLng) || (isNaN(device.lat) && isNaN(this.oldLat) && isNaN(device.lon) && isNaN(this.oldLng))) { return exports.DeltaStatus.Applies; } else { return exports.DeltaStatus.Conflicted; } }; DeviceLocationDelta.prototype.apply = function (device) { device.lat = this.newLat; device.lon = this.newLng; }; DeviceLocationDelta.prototype.getPatch = function () { return { lat: this.newLat, lon: this.newLng }; }; DeviceLocationDelta.prototype.serializeArguments = function () { return { oldLat: this.oldLat, oldLng: this.oldLng, newLat: this.newLat, newLng: this.newLng }; }; DeviceLocationDelta.Deserialize = function (guid$$1, slug, serializedArgs) { return new DeviceLocationDelta(serializedArgs.oldLat, serializedArgs.oldLng, serializedArgs.newLat, serializedArgs.newLng, slug, guid$$1); }; DeviceLocationDelta.ClassName = 'DeviceLocationDelta'; return DeviceLocationDelta; }(DeviceDelta)); var DeviceDrifterDelta = /** @class */ (function (_super) { __extends(DeviceDrifterDelta, _super); function DeviceDrifterDelta(oldDrifter, newDrifter, slug, guid$$1) { var _this = _super.call(this, DeviceDrifterDelta.ClassName, slug, guid$$1) || this; _this.oldDrifter = oldDrifter; _this.newDrifter = newDrifter; return _this; } DeviceDrifterDelta.prototype.check = function (device) { if (device.drifterMode === this.newDrifter) { return exports.DeltaStatus.Outdated; } else { return exports.DeltaStatus.Applies; } }; DeviceDrifterDelta.prototype.apply = function (device) { device.drifterMode = this.newDrifter; }; DeviceDrifterDelta.prototype.getPatch = function () { return {}; }; DeviceDrifterDelta.prototype.serializeArguments = function () { return { oldDrifter: this.oldDrifter, newDrifter: this.newDrifter }; }; DeviceDrifterDelta.Deserialize = function (guid$$1, slug, serializedArgs) { return new DeviceDrifterDelta(serializedArgs.oldDrifter, serializedArgs.newDrifter, slug, guid$$1); }; DeviceDrifterDelta.ClassName = 'DeviceDrifterDelta'; return DeviceDrifterDelta; }(DeviceDelta)); var DeviceLabelDelta = /** @class */ (function (_super) { __extends(DeviceLabelDelta, _super); function DeviceLabelDelta(oldLabel, newLabel, slug, guid$$1) { var _this = _super.call(this, DeviceLabelDelta.ClassName, slug, guid$$1) || this; _this.oldLabel = oldLabel; _this.newLabel = newLabel; return _this; } DeviceLabelDelta.prototype.check = function (device) { if (device.label == this.newLabel) { return exports.DeltaStatus.Outdated; } else if (device.label !== this.oldLabel) { return exports.DeltaStatus.Conflicted; } return exports.DeltaStatus.Applies; }; DeviceLabelDelta.prototype.apply = function (device) { device.label = this.newLabel; }; DeviceLabelDelta.prototype.getPatch = function () { return { label: this.newLabel }; }; DeviceLabelDelta.prototype.serializeArguments = function () { return { oldLabel: this.oldLabel, newLabel: this.newLabel }; }; DeviceLabelDelta.Deserialize = function (guid$$1, slug, serializedArgs) { return new DeviceLabelDelta(serializedArgs.oldLabel, serializedArgs.newLabel, slug, guid$$1); }; DeviceLabelDelta.ClassName = 'DeviceLabelDelta'; return DeviceLabelDelta; }(DeviceDelta)); var RPCArgs = /** @class */ (function () { function RPCArgs(data) { if (data === void 0) { data = {}; } if (data) { this.addr = data.addr || null; this.rpcId = Number(data.rpc_id) || null; this.callFmt = data.call_fmt || ""; this.respFmt = data.resp_fmt || ""; this.args = data.args || []; this.timeout = data.timeout || null; } } return RPCArgs; }()); var StatefulRPCArgs = /** @class */ (function (_super) { __extends(StatefulRPCArgs, _super); function StatefulRPCArgs(data) { if (data === void 0) { data = {}; } var _this = _super.call(this, data) || this; _this.currentState = data.cur_state || false; _this.transitionStates = data.trans_states || []; _this.auto = data.auto || false; return _this; } return StatefulRPCArgs; }(RPCArgs)); var StatefulSwitchArgs = /** @class */ (function () { function StatefulSwitchArgs(data) { if (data === void 0) { data = {}; } this.currentState = false; this.transitionStates = []; this.rpcs = []; if (data) { for (var rpc in data.rpcs) { this.rpcs.push(new StatefulRPCArgs(rpc)); } this.currentState = data.cur_state || false; this.transitionStates = data.trans_states || []; } } return StatefulSwitchArgs; }()); // export class WebArgs { // public options: WebOptions | any; // constructor(data: any = {}){ // this.options = new WebOptions(data.options) || data.options; // } // } // export class WebOptions { // public tabViewId: string; // public ngComponent: string; // public seriesGroup: string; // public downloadable: boolean; // public chart?: any; // public ngComponentInputs?: any; // constructor(data: any = {}){ // this.tabViewId = data.tabViewId; // this.ngComponent = data.ngComponent; // this.seriesGroup = data.seriesGroup; // this.downloadable = data.downloadable || false; // if ('chart' in data){ // this.chart = data.chart; // } // if ('ngComponentInputs' in data){ // this.ngComponentInputs = data.ngComponentInputs; // } // } // } var DisplayWidget = /** @class */ (function () { function DisplayWidget(data) { if (data === void 0) { data = {}; } this.label = data.label; this.lid = data.lid_hex; this.type = data.type; this.varType = data.var_type; this.derivedType = data.derived_unit_type; this.showInApp = data.show_in_app || false; this.showInWeb = data.show_in_web || false; if (!data.args) { this.args = null; } else if ('auto' in data.args) { this.args = new StatefulRPCArgs(data.args); } else if ('rpcs' in data.args) { this.args = new StatefulSwitchArgs(data.args); } else if (this.showInWeb) { this.args = data.args; } else { this.args = new RPCArgs(data.args); } } return DisplayWidget; }()); var EventPage = /** @class */ (function (_super) { __extends(EventPage, _super); function EventPage(url, thisPage, pageCount) { var _this = _super.call(this, url, thisPage, pageCount) || this; _this.data = []; return _this; } return EventPage; }(Page)); var EventPoint = /** @class */ (function () { function EventPoint(data) { if (data === void 0) { data = {}; } this.id = data.id; this.timestamp = new Date(data.timestamp); this.ext = data.ext; if ('stream' in data) { // Only getData returns a stream slug this.stream = data.stream; } if ('streamer_local_id' in data) { this.incrementalId = data.streamer_local_id; } if ('dirty_ts' in data) { this.dirtyTimestamp = data.dirty_ts; } if ('extra_data' in data) { this.summaryData = data.extra_data; } } return EventPoint; }()); var FleetDevice = /** @class */ (function () { function FleetDevice(data) { this.device = data.device; this.alwaysOn = data.always_on; this.isAccessPoint = data.is_access_point; } return FleetDevice; }()); var Fleet = /** @class */ (function () { function Fleet(data) { this.id = data.id; this.name = data.name; this.slug = data.slug; this.description = data.description; this.isNetwork = data.is_network; this.memberDictionary = {}; this.members = []; } Fleet.prototype.addDevice = function (item) { this.members.push(item); this.memberDictionary[item.device] = item; }; Fleet.prototype.getPostPayload = function () { var payload = {}; payload['name'] = this.name; payload['description'] = this.description; payload['is_network'] = this.isNetwork; return payload; }; return Fleet; }()); var IndexFile = /** @class */ (function () { function IndexFile(data) { if (data === void 0) { data = {}; } this.id = data['id'] || ''; this.title = data['title'] || ''; this.url = data['url'] || ''; this.fileType = data['file_type'] || ''; this.createdOn = new Date(data['created_on']) || ''; this.createdBy = data['created_by'] || ''; } return IndexFile; }()); var User = /** @class */ (function () { function User(data, token) { if (data === void 0) { data = {}; } this.slug = ''; this.isStaff = false; this.tagline = data.tagline || ''; this.username = data.username || ""; this.name = data.name || ""; this.email = data.email || ""; this.isStaff = data.is_staff || false; this.id = data.id || ""; this.orgRoles = data.orgRoles || {}; if ('slug' in data) { this.slug = data.slug; } if (data.avatar) { this.avatarUrl = data.avatar.thumbnail; } if (data.created_at) { this.creationDate = new Date(data.created_at); } else { this.creationDate = new Date(); } this.token = data.token || token || null; } User.prototype.toJson = function () { var rawData = { "username": this.username, "name": this.name, "email": this.email, "created_at": this.creationDate, "is_staff": this.isStaff, "id": this.id, "token": this.token, "avatar": {}, "orgRoles": this.orgRoles }; if (this.avatarUrl) { rawData.avatar["thumbnail"] = this.avatarUrl; } return rawData; }; User.Unserialize = function (obj) { var user = new User(obj); var server = undefined; if (obj['server']) { server = obj['server']; } return { user: user, server: server }; }; User.prototype.getFullName = function () { var name = ""; if (this.name) { name = this.name; } else { name = this.username; } return name; }; User.prototype.getUsername = function () { return "@" + this.username; }; User.prototype.getAvatar = function () { if (this.avatarUrl) { return this.avatarUrl; } else { return ""; } }; User.prototype.setOrgRoles = function (roles) { this.orgRoles = roles; }; User.prototype.canReadProperties = function (orgSlug) { if (orgSlug in this.orgRoles) { return this.isStaff || this.orgRoles[orgSlug].permissions['can_read_device_properties'] || false; } return this.isStaff; }; User.prototype.canModifyDevice = function (orgSlug) { if (orgSlug in this.orgRoles) { return this.isStaff || this.orgRoles[orgSlug].permissions['can_modify_device'] || false; } return this.isStaff; }; User.prototype.canModifyStreamVariables = function (orgSlug) { if (orgSlug in this.orgRoles) { return this.isStaff || this.orgRoles[orgSlug].permissions['can_modify_stream_variables'] || false; } return this.isStaff; }; User.prototype.canResetDevice = function (orgSlug) { if (orgSlug in this.orgRoles) { return this.isStaff || this.orgRoles[orgSlug].permissions['can_reset_device'] || false; } return this.isStaff; }; return User; }()); var GeneratedReport = /** @class */ (function () { function GeneratedReport(data) { if (data === void 0) { data = {}; } this.userInfo = new User(); this.id = data['id'] || ''; this.label = data['label'] || ''; this.sourceRef = data['source_ref'] || ''; this.createdOn = new Date(data['created_on']) || new Date(); this.createdBy = data['created_by'] || ''; this.org = data['org'] || ''; this.status = data['status'] || ''; this.template = data['template'] || ''; this.groupSlug = data['group_slug'] || ''; this.token = data['token'] || ''; this.userInfo.email = data['user'] || ''; if ('index_file' in data && data['index_file'] != null) { this.indexFile = new IndexFile(data['index_file']); } else { delete this.indexFile; } if ('user_info' in data && data['user_info'] != null) { this.userInfo.username = data['user_info']['username']; this.userInfo.slug = data['user_info']['slug']; this.userInfo.avatarUrl = data['user_info']['tiny_avatar']; } if ('args' in data && data['args'] != null) { this.args = data['args']; } else { delete this.args; } } GeneratedReport.prototype.getSchedulPostPayload = function () { var payload = { slug: this.sourceRef, template: this.template }; if (this.args) { payload.args = this.args; } if (!payload.slug || !payload.template) { throw new Error("Payload cannot be returned because of missing fields: " + JSON.stringify(payload, null, 2) + "."); } return payload; }; GeneratedReport.prototype.getStatusDisplay = function () { var factory = { 'G0': 'In Progress...', 'G1': 'Completed', 'GE': 'Error' }; return factory[this.status]; }; return GeneratedReport; }()); var DeviceGlobalId = /** @class */ (function () { function DeviceGlobalId(id) { this.id = id; } /** * * This class represents a Device ID * It helps converts a device id like 0x20 to a string slug of * the form: * d--XXXX-XXXX-XXXX-XXXX * * The slug always has the hex string in lowercase. * */ DeviceGlobalId.prototype.toString = function () { var hexString = Number(this.id).toString(16); while (hexString.length < 16) { hexString = '0' + hexString; } hexString = hexString.toLowerCase(); return 'd--' + hexString.substr(0, 4) + '-' + hexString.substr(4, 4) + '-' + hexString.substr(8, 4) + '-' + hexString.substr(12, 4); }; return DeviceGlobalId; }()); var HttpError = /** @class */ (function () { function HttpError(resp) { var _this = this; this.raw = resp; var data = resp.response || resp; this.status = data.status || -1; this.statusText = data.statusText || 'Unknown Issue'; this.nonFieldErrors = []; this.fieldErrors = {}; if (data.data && (typeof data.data === "object")) { var fieldNames = Object.keys(data.data); fieldNames.forEach(function (name) { if (name === 'status') { // Ignore } else if (name === 'message' || name === 'detail') { _this.nonFieldErrors.push(data.data[name]); } else if (name === 'non_field_errors') { var that_1 = _this; data.data[name].forEach(function (err) { if (!that_1.nonFieldErrors) { that_1.nonFieldErrors = []; } that_1.nonFieldErrors.push(err); }); } else { var msg_1 = ''; if (data.data[name] instanceof Array) { data.data[name].forEach(function (err) { msg_1 += err; }); } else { // It seems like in some cases, data.response shows arrays and in some cases, strings msg_1 += data.data[name]; } _this.fieldErrors[name] = msg_1; } }); } else if ((typeof data.data === "string") && data.data !== '') { this.heuristicallyParseErrorData(data.data); } else if (this.status == -1) { this.nonFieldErrors.push("Could not reach iotile.cloud. Check your internet connection."); } if (resp.config) { if (resp.config.method) { this.method = resp.config.method.toUpperCase(); } if (resp.config.url) { this.url = resp.config.url; } } } /* * Do our best to extract a meaningful error message from a string message thrown * by some deep part of the network stack. */ HttpError.prototype.heuristicallyParseErrorData = function (data) { if (data.indexOf('ENOTFOUND') !== -1) { this.nonFieldErrors.push("Could not reach iotile.cloud. Check your internet connection."); } else { this.nonFieldErrors.push(data); } }; HttpError.prototype._formatFieldErrors = function () { var _this = this; var msg = ''; if (this.nonFieldErrors && this.nonFieldErrors.length) { this.nonFieldErrors.forEach(function (err) { msg += ' ' + err; }); } else { if (Object.keys(this.fieldErrors).length > 0) { msg += ' ('; var fieldNames = Object.keys(this.fieldErrors); fieldNames.forEach(function (name) { msg += ' ' + name + ': ' + _this.fieldErrors[name]; }); msg += ' )'; } } return msg; }; HttpError.prototype.shortUserErrorMsg = function () { var msg = 'Error!'; var fieldErrors = this._formatFieldErrors(); if (fieldErrors) { msg += fieldErrors; } else { // If no field or non-field errors were found, still give generic error msg += ' ' + this.statusText; } return msg; }; HttpError.prototype.longUserErrorMsg = function () { var msg = 'Error ' + this.status + '! '; msg += this.statusText; var fieldErrors = this._formatFieldErrors(); if (fieldErrors) { msg += ':' + fieldErrors; } return msg; }; HttpError.prototype.extraInfo = function () { var msg = this.longUserErrorMsg(); if (this.method && this.url) { msg += ' -> ' + this.method + ':' + this.url; } else { if (this.status === -1) { msg += ' -> ' + JSON.stringify(this.raw); } } return msg; }; Object.defineProperty(HttpError.prototype, "message", { get: function () { return this.shortUserErrorMsg(); }, enumerable: true, configurable: true }); Object.defineProperty(HttpError.prototype, "userMessage", { get: function () { return this.shortUserErrorMsg(); }, enumerable: true, configurable: true }); return HttpError; }()); var Invitation = /** @class */ (function () { function Invitation(data) { if (data === void 0) { data = {}; } this.email = ""; if ('email' in data) { this.email = data.email; } if ('sent_on' in data) { this.sentOn = new Date(data.sent_on); } if ('sent_by' in data) { this.sentBy = data.sent_by; } } Invitation.prototype.postPayload = function () { var payload = { email: this.email }; return payload; }; return Invitation; }()); var IOTileSysVar = /** @class */ (function () { function IOTileSysVar() { this.battery = '5800'; this.gatewayScanBegin = '5a00'; this.gatewayScanEnd = '5a01'; this.gatewayScanFailure = '5a03'; this.endOfTripSummary = '5a07'; this.middleOfTripSummary = '5a08'; this.reboot = '5c00'; this.tripStarted = '0e00'; this.tripEnded = '0e01'; this.tripRecording = '0e02'; } return IOTileSysVar; }()); var MAX_INT32 = 2147483647; var Mdo = /** @class */ (function () { function Mdo(data) { if (data === void 0) { data = {}; } this.m = data.multiplication_factor || data.m || 1; this.d = data.division_factor || data.d || 1; this.o = data.offset || data.o || 0; if (data.mdo_label) { this.label = data.mdo_label; } } Mdo.prototype.equal = function (other) { if (this.m !== other.m || this.d !== other.d || this.o !== other.o || this.label !== other.label) { return false; } return true; }; Mdo.prototype.addToObject = function (obj, longNames) { if (longNames) { obj['offset'] = this.o; obj['multiplication_factor'] = this.m; obj['division_factor'] = this.d; obj['mdo_label'] = this.label; } else { obj['m'] = this.m; obj['d'] = this.d; obj['o'] = this.o; } }; Mdo.prototype.toJson = function (longNames) { var obj = {}; this.addToObject(obj, longNames); return obj; }; /* private _round(value, decimals) { // See http://www.jacklmoore.com/notes/rounding-in-javascript/ return Number(Math.round(value+'e'+decimals)+'e-'+decimals); } */ Mdo.prototype._retr_dec = function (num) { // let numberFixedDecimal = num.toFixed(10); var numberString = num.toString(); var decimalLength = (numberString.split(".")[1] || []).length; if (decimalLength > 8) { // Limit number of decimals to 8 decimalLength = 8; } return decimalLength; }; Mdo.prototype.computeValue = function (value) { var result = value; if (this.m) { result = result * this.m; } if (this.d) { result = result / this.d; } if (this.o) { result += this.o; } return result; }; Mdo.prototype.setFromMdo = function (src) { if (src.m) { this.m = src.m; } if (src.d) { this.d = src.d; } if (src.o) { this.o = src.o; } if (src.label) { this.label = src.label; } }; Mdo.prototype.setFromFactor = function (factor, invert) { var multiplication_factor = 1; var newFactor; if (factor < MAX_INT32) { // console.debug('factor is ' + factor); var decimals = this._retr_dec(factor); // console.debug('Decimals is ' + decimals); multiplication_factor = Math.pow(10, decimals); // console.debug('multiplication_factor is ' + multiplication_factor); newFactor = Math.round(factor * multiplication_factor); while (newFactor >= MAX_INT32) { // console.debug('factor is too large: ' + newFactor); newFactor = Math.round(newFactor / 10); multiplication_factor = Math.round(multiplication_factor / 10); } } else { newFactor = MAX_INT32; } this.o = 0.0; if (invert) { this.d = newFactor; this.m = multiplication_factor; } else { this.m = newFactor; this.d = multiplication_factor; } }; Mdo.prototype.eq = function () { var eqStr = 'V * ' + this.m + '/' + this.d; if (this.o) { eqStr += ' + ' + this.o; } return eqStr; }; Mdo.prototype.getPatchPayload = function () { var payload = { multiplication_factor: this.m, division_factor: this.d, offset: this.o }; if (this.label) { payload['mdo_label'] = this.label; } return payload; }; return Mdo; }()); var Permissions = /** @class */ (function () { function Permissions(data) { if (data === void 0) { data = {}; } this.canDeleteOrg = data['can_delete_org']; this.canManageUsers = data['can_manage_users']; this.canManageOta = data['can_manage_ota']; this.canManageOrgAndProjects = data['can_manage_org_and_projects']; this.canClaimDevices = data['can_claim_devices']; this.canModifyDevice = data['can_modify_device']; this.canReadDeviceProperties = data['can_read_device_roperties']; this.canModifyDeviceProperties = data['can_modify_device_properties']; this.canReadNotes = data['can_read_notes']; this.canReadDeviceLocations = data['can_read_device_locations']; this.canReadStreamData = data['can_read_stream_data']; this.canCreateStreamData = data['can_create_stream_data']; this.canCreateDatablock = data['can_create_datablock']; this.canAccessDatablock = data['can_access_datablock']; this.canAccessWebapp = data['can_access_webapp']; this.canAccessReports = data['can_access_reports']; this.canCreateReports = data['can_create_reports']; } return Permissions; }()); var Member = /** @class */ (function () { function Member(data) { if (data === void 0) { data = {}; } if ('user_details' in data) { this.user = new User(data['user_details']); } if ('created_on' in data) { this.createdOn = new Date(data['created_on']); } if ('is_active' in data) { this.isActive = data['is_active']; } if ('role' in data) { this.role = data['role']; } if ('permissions' in data) { this.permissions = new Permissions(data['permissions']); } if ('role_name' in data) { this.roleName = data['role_name']; } } return Member; }()); var Membership = /** @class */ (function () { function Membership(data) { if (data === void 0) { data = {}; } this.user = data.user; this.isActive = data.is_active; this.permissions = data.permissions; this.role = data.role; } Membership.prototype.toJson = function () { var rawData = { "user": this.user, "is_active": this.isActive, "permissions": this.permissions, "role": this.role }; return rawData; }; Membership.Unserialize = function (obj) { var membership = new Membership(obj); return membership; }; return Membership; }()); var Note = /** @class */ (function () { function Note(data) { if (data === void 0) { data = {}; } this.id = 0; this.type = 'ui'; this.target = data.target; this.timestamp = data.timestamp || new Date().toISOString(); this.note = data.note; this.type = data.type; if ('id' in data) { this.id = data.id; } if ('user_info' in data) { this.userInfo = { username: data.user_info.username, slug: data.user_info.slug, tinyAvatar: data.user_info.tiny_avatar }; } if ('attachment' in data && data.attachment != null) { this.attachment = { title: data.attachment.title, url: data.attachment.url, fileType: data.attachment.file_type }; } } Note.prototype.postPayload = function () { var payload = { target: this.target, timestamp: this.timestamp, note: this.note, type: this.type }; return payload; }; return Note; }()); var OrgTemplate = /** @class */ (function () { function OrgTemplate(data) { if (data === void 0) { data = {}; } this.id = data.id || ''; this.name = data.name || ''; this.slug = data.slug || ''; this.createdOn = new Date(data.created_on); if ('version' in data) { this.version = data.version; } if ('extra_data' in data) { this.extraData = data['extra_data']; } } OrgTemplate.prototype.getExtraData = function () { if (this.extraData && 'web' in this.extraData) { return this.extraData['web']; } }; return OrgTemplate; }()); var Org = /** @class */ (function () { function Org(data) { if (data === void 0) { data = {}; } this.about = ''; this.members = []; this.memberMap = {}; this.pendingInvites = []; this.pendingInviteMap = {}; this.slug = data.slug; this.name = data.name; this.createdBy = data.created_by; this.createdOn = new Date(data.created_on); this.rawData = data; if (data.about) { this.about = data.about; } if (data.avatar) { this.thumbnailUrl = data.avatar.thumbnail; this.tinyUrl = data.avatar.tiny; } if (data.current_member) { this.currentMember = new Member(data.current_member); } if (data.counts) { this.counts = data.counts; } if (data.ot) { this.orgTemplate = data.ot; } } Org.prototype.toJson = function () { return this.rawData; }; Org.prototype.getPatchPayload = function () { var payload = { name: this.name }; if (this.about) { payload.about = this.about; } return payload; }; Org.prototype.addMembers = function (members) { var _this = this; this.members = members; this.memberMap = {}; this.members.forEach(function (m) { if (m.user) { _this.memberMap[m.user.email] = m; } }); }; Org.prototype.getMember = function (slug) { return this.memberMap[slug]; }; Org.prototype.addPendingInvites = function (pendingInvites) { var _this = this; this.pendingInvites = pendingInvites; this.pendingInviteMap = {}; this.pendingInvites.forEach(function (pv) { if (pv.email) { _this.pendingInviteMap[pv.email] = pv; } }); }; Org.prototype.getPendingInvite = function (email) { return this.pendingInviteMap[email]; }; return Org; }()); var Unit = /** @class */ (function () { function Unit(data) { if (data === void 0) { data = {}; } this.mdo = new Mdo(data); this.fullName = data.unit_full; this.shortName = data.unit_short; this.slug = data.slug; if ('decimal_places' in data) { this.decimalPlaces = data.decimal_places; } if ('derived_units' in data) { this.derivedUnits = {}; for (var key in data['derived_units']) { this.derivedUnits[key] = {}; for (var name_1 in data['derived_units'][key]) { this.derivedUnits[key][name_1] = new Mdo(data['derived_units'][key][name_1]); } } } } Unit.prototype.initFromJSON = function (data) { this.mdo = new Mdo(data); this.fullName = data.unit_full; this.shortName = data.unit_short; this.slug = data.slug; if ('decimal_places' in data) { this.decimalPlaces = data.decimal_places; } if ('derived_units' in data) { this.derivedUnits = {};