diff --git a/README.md b/README.md index f6be595..059401c 100644 --- a/README.md +++ b/README.md @@ -41,6 +41,10 @@ It can also be used to change data points that are not sent by the API. ## Changelog +### **WORK IN PROGRESS** + +- Crash after 'unhandled promise rejection' fixed #15 + ### 0.7.0 (2024-02-04) - Forbidden characters are removed from the category diff --git a/build/main.js b/build/main.js index 622f7ba..3827c65 100644 --- a/build/main.js +++ b/build/main.js @@ -162,9 +162,11 @@ class Myuplink extends utils.Adapter { const datetime = newDate.today() + " " + newDate.timeNow(); this.setState("info.updateTime", { val: datetime, ack: true }); this.setState("info.currentError", { val: "", ack: true }); - (_a = systems.systems) == null ? void 0 : _a.forEach(async (value) => { - await this.setSystemWithDevicesAsync(value, accessToken); - }); + if (systems.systems) { + for (const value of systems.systems) { + await this.setSystemWithDevicesAsync(value, accessToken); + } + } } } } catch (error) { @@ -176,6 +178,7 @@ class Myuplink extends utils.Adapter { this.setState("info.lastError", { val: "" + error, ack: true }); this.setState("info.currentError", { val: "" + error, ack: true }); } + this.log.debug("Set timer"); this.timeout = this.setTimeout( async () => { await this.getDataAsync(); @@ -184,7 +187,7 @@ class Myuplink extends utils.Adapter { ); } async setSystemWithDevicesAsync(system, accessToken) { - var _a, _b, _c; + var _a, _b; if (system.systemId != void 0 && system.name != void 0) { const systemIdExists = this.existingSystemIds.includes(system.systemId); const firstRun = !systemIdExists; @@ -209,11 +212,13 @@ class Myuplink extends utils.Adapter { if (system.hasAlarm != void 0) { await this.myCreateBooleanStateAsync(`${systemPath}.hasAlarm`, "Has Alarm", "indicator.alarm", system.hasAlarm, firstRun); } - (_a = system.devices) == null ? void 0 : _a.forEach(async (dev) => { - await this.setSystemDeviceAsync(dev, systemPath, accessToken); - }); + if (system.devices) { + for (const device of system.devices) { + await this.setSystemDeviceAsync(device, systemPath, accessToken); + } + } if (this.config.AddActiveNotifications) { - const notifications = await ((_b = this.myUplinkRepository) == null ? void 0 : _b.getActiveNotificationsAsync(system.systemId, accessToken)); + const notifications = await ((_a = this.myUplinkRepository) == null ? void 0 : _a.getActiveNotificationsAsync(system.systemId, accessToken)); if (this.config.AddRawActiveNotifications) { await this.myCreateStringStateAsync( `${systemPath}.rawActiveNotifications`, @@ -223,7 +228,7 @@ class Myuplink extends utils.Adapter { ); } let notificationsDescriptions = ""; - (_c = notifications == null ? void 0 : notifications.notifications) == null ? void 0 : _c.forEach((notification) => { + (_b = notifications == null ? void 0 : notifications.notifications) == null ? void 0 : _b.forEach((notification) => { notificationsDescriptions += `${notification.header}: ${notification.description} `; }); @@ -264,9 +269,11 @@ class Myuplink extends utils.Adapter { if (this.config.AddRawData) { await this.myCreateStringStateAsync(`${devicePath}.rawData`, "Received raw JSON of parameter data", JSON.stringify(devicePoints, null, ""), firstRun); } - devicePoints == null ? void 0 : devicePoints.forEach(async (data) => { - await this.setParameterDataAsync(data, devicePath, device.id, stateIdByParameterId); - }); + if (devicePoints) { + for (const data of devicePoints) { + await this.setParameterDataAsync(data, devicePath, device.id, stateIdByParameterId); + } + } if (firstRun) { await this.setObjectNotExistsAsync(`${devicePath}.setData`, { type: "state", @@ -558,13 +565,13 @@ class Myuplink extends utils.Adapter { await this.setStateAsync(id, { val: state.val, q: this.constants.STATE_QUALITY.GOOD, ack: true, c: void 0 }); const objectIdByParameterId = this.objectIdIdByParameterIdByDeviceId.get(deviceId); if (objectIdByParameterId && result.payload) { - Object.entries(keyValueDictionary).forEach(async ([parameterId, value2]) => { + for (const [parameterId, value2] of Object.entries(keyValueDictionary)) { const objectId = objectIdByParameterId.get(parameterId); const valNumber = parseFloat(value2); if (objectId && !Number.isNaN(valNumber) && parameterId in result.payload && result.payload[parameterId] == "modified") { await this.setStateAsync(objectId, { val: valNumber, ack: true }); } - }); + } } } else { this.log.error(`SetData: "${value}" diff --git a/build/main.js.map b/build/main.js.map index 5423523..0e48f27 100644 --- a/build/main.js.map +++ b/build/main.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["../src/main.ts"], - "sourcesContent": ["/*\n * Created with @iobroker/create-adapter v2.5.0\n */\n\n// The adapter-core module gives you access to the core ioBroker functions\n// you need to create an adapter\nimport * as utils from '@iobroker/adapter-core';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { AuthRepository } from './authRepository';\nimport { Alarm } from './models/Alarm';\nimport { EnumValues } from './models/EnumValues';\nimport { ParameterData } from './models/ParameterData';\nimport { SystemDevice } from './models/SystemDevice';\nimport { SystemWithDevices } from './models/SystemWithDevices';\nimport { MyUplinkRepository } from './myuplinkRepository';\n\n// Helper functions:\n\n// For todays date;\ndeclare global {\n interface Date {\n today(): string;\n }\n}\nDate.prototype.today = function (): string {\n return this.getFullYear() + '-' + (this.getMonth() + 1 < 10 ? '0' : '') + (this.getMonth() + 1) + '-' + (this.getDate() < 10 ? '0' : '') + this.getDate();\n};\n\n// For the time now\ndeclare global {\n interface Date {\n timeNow(): string;\n }\n}\nDate.prototype.timeNow = function (): string {\n return (this.getHours() < 10 ? '0' : '') + this.getHours() + ':' + (this.getMinutes() < 10 ? '0' : '') + this.getMinutes() + ':' + (this.getSeconds() < 10 ? '0' : '') + this.getSeconds();\n};\n\nclass Myuplink extends utils.Adapter {\n public constructor(options: Partial = {}) {\n super({\n ...options,\n name: 'myuplink',\n });\n this.on('ready', this.onReady.bind(this));\n this.on('stateChange', this.onStateChange.bind(this));\n this.on('unload', this.onUnload.bind(this));\n this.refreshInterval = 0;\n }\n\n private STRICT_FORBIDDEN_CHARS = /[^a-zA-Z0-9_-]+/gu;\n\n private authRepository: AuthRepository | undefined;\n private myUplinkRepository: MyUplinkRepository | undefined;\n private timeout: ioBroker.Timeout | undefined;\n private refreshInterval: number;\n private systemIds: Map = new Map();\n private deviceIds: Map = new Map();\n private categories: Map = new Map();\n private parameterIds: Map = new Map();\n private parameterIdToCategory: Map = new Map();\n private objectIdIdByParameterIdByDeviceId: Map> = new Map>();\n private existingSystemIds: string[] = [];\n private existingFolders: string[] = [];\n\n /**\n * Is called when databases are connected and adapter received configuration.\n */\n private async onReady(): Promise {\n // Initialize your adapter here\n\n this.log.info('Starting adapter.');\n\n await this.setInfoObjects();\n\n this.config.RenameSystemIds?.forEach((renameData: ioBroker.RenameData) => {\n if (renameData.OriginalId && renameData.NewId) {\n this.log.debug(`Map System ID: ${renameData.OriginalId} -> ${renameData.NewId}`);\n this.systemIds.set(renameData.OriginalId, this.replaceForbiddenCharacters(renameData.NewId));\n }\n });\n this.config.RenameDeviceIds?.forEach((renameData: ioBroker.RenameData) => {\n if (renameData.OriginalId && renameData.NewId) {\n this.log.debug(`Map Device ID: ${renameData.OriginalId} -> ${renameData.NewId}`);\n this.deviceIds.set(renameData.OriginalId, this.replaceForbiddenCharacters(renameData.NewId));\n }\n });\n this.config.RenameCategories?.forEach((renameData: ioBroker.RenameData) => {\n if (renameData.OriginalId && renameData.NewId) {\n this.log.debug(`Map Category: ${renameData.OriginalId} -> ${renameData.NewId}`);\n this.categories.set(renameData.OriginalId, this.replaceForbiddenCharacters(renameData.NewId));\n }\n });\n this.config.RenameDataIds?.forEach((renameData: ioBroker.RenameData) => {\n if (renameData.OriginalId && renameData.NewId) {\n this.log.debug(`Map Data ID: ${renameData.OriginalId} -> ${renameData.NewId}`);\n this.parameterIds.set(renameData.OriginalId, renameData.NewId);\n if (renameData.Category) {\n this.parameterIdToCategory.set(renameData.OriginalId, this.replaceForbiddenCharacters(renameData.Category));\n }\n }\n });\n\n this.refreshInterval = this.config.Interval * 60;\n if (this.refreshInterval < 60) {\n this.refreshInterval = 60;\n }\n\n const identifier: string = this.config.Identifier.trim();\n const secret: string = this.config.Secret.trim();\n const callbackURL: string = this.config.CallbackURL.trim();\n const configured: boolean = this.config.Configured;\n\n let error = false;\n if (identifier == '' || identifier == null) {\n if (configured != false) {\n this.log.error('Missing Identifier in the settings!');\n }\n error = true;\n }\n if (secret == '' || secret == null) {\n if (configured != false) {\n this.log.error('Missing Secret in the settings!');\n }\n error = true;\n }\n if (callbackURL == '' || callbackURL == null) {\n if (configured != false) {\n this.log.error('Missing Callback URL in the settings!');\n }\n error = true;\n }\n if (error) {\n this.setState('info.connection', { val: false, ack: true });\n this.setState('info.currentError', { val: 'Missing settings!', ack: true });\n return;\n }\n\n const dataDir: string = utils.getAbsoluteDefaultDataDir();\n let storeDir: string = path.join(dataDir, 'myuplink');\n try {\n // create directory\n if (!fs.existsSync(storeDir)) {\n fs.mkdirSync(storeDir);\n }\n } catch (err) {\n this.log.error('Could not create storage directory (' + storeDir + '): ' + err);\n storeDir = __dirname;\n }\n const storeFile = path.join(storeDir, 'session.' + this.instance + '.json');\n\n this.authRepository = new AuthRepository(\n {\n clientId: identifier,\n clientSecret: secret,\n useAuthorizationCodeGrant: this.config.UseAuthorizationCodeGrant,\n redirectUri: callbackURL,\n authCode: this.config.AuthCode.trim(),\n sessionStoreFilePath: storeFile,\n baseUrl: 'https://api.myuplink.com',\n scope: 'READSYSTEM WRITESYSTEM',\n timeout: 45000,\n userAgent: 'iobroker.myuplink',\n renewBeforeExpiry: 5 * 60 * 1000,\n },\n this.log,\n );\n\n this.myUplinkRepository = new MyUplinkRepository(\n {\n baseUrl: 'https://api.myuplink.com',\n timeout: 45000,\n userAgent: 'iobroker.myuplink',\n language: this.config.Language,\n },\n this.log,\n );\n\n await this.subscribeStatesAsync('*');\n\n this.log.info('Adapter started.');\n\n await this.getDataAsync();\n }\n\n private async getDataAsync(): Promise {\n try {\n if (this.authRepository) {\n const accessToken = await this.authRepository.getAccessToken();\n if (accessToken && this.myUplinkRepository) {\n const systems = await this.myUplinkRepository.getSystemsAndDevicesAsync(accessToken);\n this.setState('info.connection', { val: true, expire: this.refreshInterval + 30, ack: true });\n const newDate = new Date();\n const datetime = newDate.today() + ' ' + newDate.timeNow();\n this.setState('info.updateTime', { val: datetime, ack: true });\n this.setState('info.currentError', { val: '', ack: true });\n\n systems.systems?.forEach(async (value: SystemWithDevices) => {\n await this.setSystemWithDevicesAsync(value, accessToken);\n });\n }\n }\n } catch (error) {\n this.log.error('' + error);\n\n this.setState('info.connection', { val: false, ack: true });\n\n const newDate = new Date();\n const datetime = newDate.today() + ' ' + newDate.timeNow();\n this.setState('info.lastErrorTime', { val: datetime, ack: true });\n this.setState('info.lastError', { val: '' + error, ack: true });\n this.setState('info.currentError', { val: '' + error, ack: true });\n }\n\n this.timeout = this.setTimeout(\n async () => {\n await this.getDataAsync();\n },\n this.refreshInterval * 1000,\n );\n }\n\n private async setSystemWithDevicesAsync(system: SystemWithDevices, accessToken: string): Promise {\n if (system.systemId != undefined && system.name != undefined) {\n const systemIdExists = this.existingSystemIds.includes(system.systemId);\n const firstRun = !systemIdExists;\n if (!systemIdExists) {\n this.existingSystemIds.push(system.systemId);\n }\n const systemId = this.replaceForbiddenCharacters(system.systemId);\n const newSystemId = this.systemIds.get(systemId);\n const systemPath = newSystemId ?? systemId;\n const systemName = this.removeSoftHyphen(system.name);\n if (firstRun) {\n await this.myCreateDeviceAsync(systemPath, systemName);\n }\n await this.myCreateStringStateAsync(`${systemPath}.systemId`, 'System ID', system.systemId, firstRun);\n await this.myCreateStringStateAsync(`${systemPath}.name`, 'Name', systemName, firstRun, 'info.name');\n if (system.country != undefined) {\n await this.myCreateStringStateAsync(`${systemPath}.country`, 'Country', system.country, firstRun);\n }\n if (system.securityLevel != undefined) {\n await this.myCreateStringStateAsync(`${systemPath}.securityLevel`, 'Security Level', system.securityLevel, firstRun);\n }\n if (system.hasAlarm != undefined) {\n await this.myCreateBooleanStateAsync(`${systemPath}.hasAlarm`, 'Has Alarm', 'indicator.alarm', system.hasAlarm, firstRun);\n }\n system.devices?.forEach(async (dev: SystemDevice) => {\n await this.setSystemDeviceAsync(dev, systemPath, accessToken);\n });\n\n if (this.config.AddActiveNotifications) {\n const notifications = await this.myUplinkRepository?.getActiveNotificationsAsync(system.systemId, accessToken);\n if (this.config.AddRawActiveNotifications) {\n await this.myCreateStringStateAsync(\n `${systemPath}.rawActiveNotifications`,\n 'Received raw JSON of active notifications',\n JSON.stringify(notifications?.notifications, null, ''),\n firstRun,\n );\n }\n let notificationsDescriptions: string = '';\n notifications?.notifications?.forEach((notification: Alarm) => {\n notificationsDescriptions += `${notification.header}: ${notification.description}\\n`;\n });\n await this.myCreateStringStateAsync(`${systemPath}.activeNotifications`, 'Active notification descriptions', notificationsDescriptions, firstRun);\n }\n }\n }\n\n private async setSystemDeviceAsync(device: SystemDevice, systemPath: string, accessToken: string): Promise {\n if (device.id != undefined && device.product?.name != undefined) {\n const existingMap = this.objectIdIdByParameterIdByDeviceId.get(device.id);\n const firstRun = !existingMap;\n const stateIdByParameterId = existingMap ?? new Map();\n if (!existingMap) {\n this.objectIdIdByParameterIdByDeviceId.set(device.id, stateIdByParameterId);\n }\n const deviceId = this.replaceForbiddenCharacters(device.id);\n const newDeviceId = this.deviceIds.get(deviceId);\n const deviceSubPath = newDeviceId ?? deviceId;\n const devicePath = `${systemPath}.${deviceSubPath}`;\n const deviceName = this.removeSoftHyphen(device.product.name);\n if (firstRun) {\n await this.myCreateChannelAsync(devicePath, deviceName);\n }\n await this.myCreateStringStateAsync(`${devicePath}.deviceId`, 'Device ID', device.id, firstRun);\n await this.myCreateStringStateAsync(`${devicePath}.name`, 'Name', deviceName, firstRun, 'info.name');\n if (device.connectionState != undefined) {\n await this.myCreateStringStateAsync(`${devicePath}.connectionState`, 'Connection State', device.connectionState, firstRun, 'info.status');\n }\n if (device.currentFwVersion != undefined) {\n await this.myCreateStringStateAsync(`${devicePath}.currentFwVersion`, 'Current Firmware Version', device.currentFwVersion, firstRun, 'info.firmware');\n }\n if (device.product?.serialNumber != undefined) {\n await this.myCreateStringStateAsync(`${devicePath}.serialNumber`, 'Serial Number', device.product.serialNumber, firstRun, 'info.serial');\n }\n\n if (this.config.AddData) {\n const devicePoints = await this.myUplinkRepository?.getDevicePointsAsync(device.id, accessToken);\n if (this.config.AddRawData) {\n await this.myCreateStringStateAsync(`${devicePath}.rawData`, 'Received raw JSON of parameter data', JSON.stringify(devicePoints, null, ''), firstRun);\n }\n devicePoints?.forEach(async (data: ParameterData) => {\n await this.setParameterDataAsync(data, devicePath, device.id, stateIdByParameterId);\n });\n if (firstRun) {\n await this.setObjectNotExistsAsync(`${devicePath}.setData`, {\n type: 'state',\n common: {\n name: 'Send raw JSON of parameter data',\n type: 'string',\n role: 'json',\n read: true,\n write: true,\n },\n native: {\n rawJson: true,\n writable: true,\n deviceId: device.id,\n },\n });\n }\n }\n }\n }\n\n private async setParameterDataAsync(data: ParameterData, devicePath: string, deviceId: string | null | undefined, stateIdByParameterId: Map): Promise {\n if (data.parameterId) {\n const existingObjectId = stateIdByParameterId.get(data.parameterId);\n const stateId = existingObjectId ?? (await this.getObjectIdAndCreateCategoryAsync(data.parameterId, data.category, devicePath));\n if (!existingObjectId) {\n stateIdByParameterId.set(data.parameterId, stateId);\n await this.createParameterObjectAsync(data, deviceId, stateId);\n }\n await this.setStateAsync(stateId, { val: data.value, ack: true });\n }\n }\n\n private async getObjectIdAndCreateCategoryAsync(parameterId: string, category: string | null | undefined, devicePath: string): Promise {\n const newParameterId = this.parameterIds.get(parameterId) ?? parameterId;\n const parameterSubPath = this.replaceForbiddenCharacters(newParameterId);\n let objectId = `${devicePath}.${parameterSubPath}`;\n const newCategory = this.parameterIdToCategory.get(parameterId);\n if (newCategory) {\n objectId = `${devicePath}.${newCategory}.${parameterSubPath}`;\n } else if (category) {\n const categoryId = this.replaceForbiddenCharacters(category);\n const newCategoryId = this.categories.get(categoryId);\n const categorySubPath = newCategoryId ?? categoryId;\n const catPath = `${devicePath}.${categorySubPath}`;\n const pathWithCat = `${catPath}.${parameterSubPath}`;\n if (this.config.GroupData) {\n await this.delObjectAsync(objectId);\n objectId = pathWithCat;\n await this.myCreateFolderAsync(catPath, category);\n } else {\n await this.delObjectAsync(pathWithCat);\n await this.delObjectAsync(catPath);\n }\n }\n return objectId;\n }\n\n private async createParameterObjectAsync(data: ParameterData, deviceId: string | null | undefined, stateId: string): Promise {\n const obj: ioBroker.SettableObject = {\n type: 'state',\n common: {\n name: this.removeSoftHyphen(data.parameterName ?? ''),\n type: 'number',\n role: 'value',\n read: true,\n write: data.writable ?? false,\n },\n native: {\n parameterId: data.parameterId,\n writable: data.writable,\n deviceId: deviceId,\n },\n };\n if (data.parameterUnit) {\n obj.common.unit = data.parameterUnit;\n switch (data.parameterUnit) {\n case 'kWh':\n case 'Ws':\n obj.common.role = 'value.energy';\n break;\n case 'W':\n case 'kW':\n obj.common.role = 'value.power';\n break;\n case '\u00B0C':\n obj.common.role = 'value.temperature';\n break;\n case 'Hz':\n obj.common.role = 'value.frequency';\n break;\n case 'A':\n obj.common.role = 'value.current';\n break;\n case 'V':\n obj.common.role = 'value.voltage';\n break;\n case '%RH':\n obj.common.role = 'value.humidity';\n obj.common.unit = '%';\n break;\n case 'bar':\n obj.common.role = 'value.pressure';\n break;\n }\n }\n if (data.minValue) {\n obj.common.min = data.minValue;\n }\n if (data.maxValue) {\n obj.common.max = data.maxValue;\n }\n if (data.stepValue) {\n obj.common.step = data.stepValue;\n }\n if (data.enumValues && data.enumValues.length > 0) {\n const states: Record = {};\n data.enumValues.forEach((enumValue: EnumValues) => {\n if (enumValue.text && enumValue.value) {\n states[enumValue.value] = this.removeSoftHyphen(enumValue.text);\n }\n });\n obj.common.states = states;\n }\n await this.setObjectNotExistsAsync(stateId, obj);\n }\n\n private async setInfoObjects(): Promise {\n await this.setObjectNotExistsAsync('info', {\n type: 'channel',\n common: {\n name: 'Information',\n },\n native: {},\n });\n await this.setObjectNotExistsAsync('info.connection', {\n type: 'state',\n common: {\n name: 'Connected to myUplink',\n role: 'indicator.connected',\n type: 'boolean',\n read: true,\n write: false,\n def: false,\n },\n native: {},\n });\n await this.setObjectNotExistsAsync('info.currentError', {\n type: 'state',\n common: {\n name: 'Current Error',\n role: 'text',\n type: 'string',\n read: true,\n write: false,\n def: '',\n },\n native: {},\n });\n await this.setObjectNotExistsAsync('info.updateTime', {\n type: 'state',\n common: {\n name: 'Time of the last update',\n role: 'text',\n type: 'string',\n read: true,\n write: false,\n def: '',\n },\n native: {},\n });\n await this.setObjectNotExistsAsync('info.lastError', {\n type: 'state',\n common: {\n name: 'Last Error',\n role: 'text',\n type: 'string',\n read: true,\n write: false,\n def: '',\n },\n native: {},\n });\n await this.setObjectNotExistsAsync('info.lastErrorTime', {\n type: 'state',\n common: {\n name: 'Time of the last error',\n role: 'text',\n type: 'string',\n read: true,\n write: false,\n def: '',\n },\n native: {},\n });\n }\n\n private async myCreateDeviceAsync(path: string, name: string): Promise {\n this.log.debug(`create Device: ${path}`);\n await this.setObjectNotExistsAsync(path, {\n type: 'device',\n common: {\n name: name,\n },\n native: {},\n });\n }\n\n private async myCreateChannelAsync(path: string, name: string): Promise {\n this.log.debug(`create Channel: ${path}`);\n await this.setObjectNotExistsAsync(path, {\n type: 'channel',\n common: {\n name: name,\n },\n native: {},\n });\n }\n\n private async myCreateFolderAsync(path: string, name: string): Promise {\n if (!this.existingFolders.includes(path)) {\n this.existingFolders.push(path);\n this.log.debug(`create Folder: ${path}`);\n await this.setObjectNotExistsAsync(path, {\n type: 'folder',\n common: {\n name: name,\n },\n native: {},\n });\n }\n }\n\n private async myCreateStringStateAsync(path: string, name: string, value: string, createObject: boolean, role: string = 'text'): Promise {\n if (createObject) {\n this.log.debug(`create State: ${path}`);\n await this.setObjectNotExistsAsync(path, {\n type: 'state',\n common: {\n name: name,\n type: 'string',\n role: role,\n read: true,\n write: false,\n },\n native: {},\n });\n }\n await this.setStateAsync(path, { val: value, ack: true });\n }\n\n private async myCreateBooleanStateAsync(path: string, name: string, role: string, value: boolean, createObject: boolean): Promise {\n if (createObject) {\n this.log.debug(`create State: ${path}`);\n await this.setObjectNotExistsAsync(path, {\n type: 'state',\n common: {\n name: name,\n type: 'boolean',\n role: role,\n read: true,\n write: false,\n },\n native: {},\n });\n }\n await this.setStateAsync(path, { val: value, ack: true });\n }\n\n private removeSoftHyphen(text: string): string {\n return text.replace(new RegExp('\\u00AD', 'g'), '');\n }\n\n private replaceForbiddenCharacters(text: string): string {\n return this.removeSoftHyphen(text).replace(this.STRICT_FORBIDDEN_CHARS, '_');\n }\n\n /**\n * Is called if a subscribed state changes\n */\n private async onStateChange(id: string, state: ioBroker.State | null | undefined): Promise {\n if (state != null && state.ack === false && state.q == this.constants.STATE_QUALITY.GOOD && state.val != null && this.authRepository != null && this.myUplinkRepository != null) {\n this.log.debug(`state ${id} changed: ${state.val} (ack = ${state.ack})`);\n const obj = await this.getObjectAsync(id);\n if (obj != null && obj.native != null && obj.native.writable == true && obj.native.deviceId != null && obj.native.deviceId != '') {\n try {\n const accessToken = await this.authRepository.getAccessToken();\n if (accessToken) {\n const deviceId = obj.native.deviceId;\n const value = state.val.toString();\n if (obj.native.parameterId != null && obj.native.parameterId != '') {\n const parameterId = obj.native.parameterId.toString();\n const result = await this.myUplinkRepository.setDevicePointAsync(deviceId, accessToken, parameterId, value);\n if (result.status == 200 && result.payload && parameterId in result.payload && result.payload[parameterId] == 'modified') {\n this.log.debug(`Parameter ${parameterId} modified by API`);\n await this.setStateAsync(id, { val: state.val, ack: true });\n }\n } else if (obj.native.rawJson === true && value) {\n const keyValueDictionary: Record = JSON.parse(value);\n const result = await this.myUplinkRepository.setDevicePointsAsync(deviceId, accessToken, keyValueDictionary);\n if (result.status == 200) {\n await this.setStateAsync(id, { val: state.val, q: this.constants.STATE_QUALITY.GOOD, ack: true, c: undefined });\n const objectIdByParameterId = this.objectIdIdByParameterIdByDeviceId.get(deviceId);\n if (objectIdByParameterId && result.payload) {\n Object.entries(keyValueDictionary).forEach(async ([parameterId, value]) => {\n const objectId = objectIdByParameterId.get(parameterId);\n const valNumber = parseFloat(value);\n if (objectId && !Number.isNaN(valNumber) && parameterId in result.payload && result.payload[parameterId] == 'modified') {\n await this.setStateAsync(objectId, { val: valNumber, ack: true });\n }\n });\n }\n } else {\n this.log.error(`SetData: \"${value}\"\\nResult: \"${JSON.stringify(result, null, ' ')}\"`);\n await this.setStateAsync(id, { val: state.val, q: this.constants.STATE_QUALITY.DEVICE_ERROR_REPORT, ack: false, c: `Status: ${result.status}` });\n }\n }\n }\n } catch (error) {\n const errorString = `${error}`;\n this.log.error(errorString);\n const quality = this.constants.STATE_QUALITY.DEVICE_ERROR_REPORT;\n await this.setStateAsync(id, { val: state.val, q: quality, c: errorString, ack: false });\n }\n }\n }\n }\n\n /**\n * Is called when adapter shuts down - callback has to be called under any circumstances!\n */\n private onUnload(callback: () => void): void {\n try {\n this.clearTimeout(this.timeout);\n this.timeout = undefined;\n this.authRepository = undefined;\n this.myUplinkRepository = undefined;\n this.setState('info.connection', { val: false, ack: true });\n this.log.info('Cleaned everything up...');\n callback();\n } catch (e) {\n callback();\n }\n }\n}\n\nif (require.main !== module) {\n // Export the constructor in compact mode\n module.exports = (options: Partial | undefined) => new Myuplink(options);\n} else {\n // otherwise start the instance directly\n (() => new Myuplink())();\n}\n"], - "mappings": ";;;;;;;;;;;;;;;;;;;AAMA,YAAuB;AACvB,SAAoB;AACpB,WAAsB;AACtB,4BAA+B;AAM/B,gCAAmC;AAUnC,KAAK,UAAU,QAAQ,WAAoB;AACvC,SAAO,KAAK,YAAY,IAAI,OAAO,KAAK,SAAS,IAAI,IAAI,KAAK,MAAM,OAAO,KAAK,SAAS,IAAI,KAAK,OAAO,KAAK,QAAQ,IAAI,KAAK,MAAM,MAAM,KAAK,QAAQ;AAC5J;AAQA,KAAK,UAAU,UAAU,WAAoB;AACzC,UAAQ,KAAK,SAAS,IAAI,KAAK,MAAM,MAAM,KAAK,SAAS,IAAI,OAAO,KAAK,WAAW,IAAI,KAAK,MAAM,MAAM,KAAK,WAAW,IAAI,OAAO,KAAK,WAAW,IAAI,KAAK,MAAM,MAAM,KAAK,WAAW;AAC7L;AAEA,MAAM,iBAAiB,MAAM,QAAQ;AAAA,EAC1B,YAAY,UAAyC,CAAC,GAAG;AAC5D,UAAM;AAAA,MACF,GAAG;AAAA,MACH,MAAM;AAAA,IACV,CAAC;AAOL,SAAQ,yBAAyB;AAMjC,SAAQ,YAAiC,oBAAI,IAAoB;AACjE,SAAQ,YAAiC,oBAAI,IAAoB;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AA,EACJ;AACJ;AAEA,IAAI,QAAQ,SAAS,QAAQ;AAEzB,SAAO,UAAU,CAAC,YAAuD,IAAI,SAAS,OAAO;AACjG,OAAO;AAEH,GAAC,MAAM,IAAI,SAAS,GAAG;AAC3B;", + "sourcesContent": ["/*\n * Created with @iobroker/create-adapter v2.5.0\n */\n\n// The adapter-core module gives you access to the core ioBroker functions\n// you need to create an adapter\nimport * as utils from '@iobroker/adapter-core';\nimport * as fs from 'fs';\nimport * as path from 'path';\nimport { AuthRepository } from './authRepository';\nimport { Alarm } from './models/Alarm';\nimport { EnumValues } from './models/EnumValues';\nimport { ParameterData } from './models/ParameterData';\nimport { SystemDevice } from './models/SystemDevice';\nimport { SystemWithDevices } from './models/SystemWithDevices';\nimport { MyUplinkRepository } from './myuplinkRepository';\n\n// Helper functions:\n\n// For todays date;\ndeclare global {\n interface Date {\n today(): string;\n }\n}\nDate.prototype.today = function (): string {\n return this.getFullYear() + '-' + (this.getMonth() + 1 < 10 ? '0' : '') + (this.getMonth() + 1) + '-' + (this.getDate() < 10 ? '0' : '') + this.getDate();\n};\n\n// For the time now\ndeclare global {\n interface Date {\n timeNow(): string;\n }\n}\nDate.prototype.timeNow = function (): string {\n return (this.getHours() < 10 ? '0' : '') + this.getHours() + ':' + (this.getMinutes() < 10 ? '0' : '') + this.getMinutes() + ':' + (this.getSeconds() < 10 ? '0' : '') + this.getSeconds();\n};\n\nclass Myuplink extends utils.Adapter {\n public constructor(options: Partial = {}) {\n super({\n ...options,\n name: 'myuplink',\n });\n this.on('ready', this.onReady.bind(this));\n this.on('stateChange', this.onStateChange.bind(this));\n this.on('unload', this.onUnload.bind(this));\n this.refreshInterval = 0;\n }\n\n private STRICT_FORBIDDEN_CHARS = /[^a-zA-Z0-9_-]+/gu;\n\n private authRepository: AuthRepository | undefined;\n private myUplinkRepository: MyUplinkRepository | undefined;\n private timeout: ioBroker.Timeout | undefined;\n private refreshInterval: number;\n private systemIds: Map = new Map();\n private deviceIds: Map = new Map();\n private categories: Map = new Map();\n private parameterIds: Map = new Map();\n private parameterIdToCategory: Map = new Map();\n private objectIdIdByParameterIdByDeviceId: Map> = new Map>();\n private existingSystemIds: string[] = [];\n private existingFolders: string[] = [];\n\n /**\n * Is called when databases are connected and adapter received configuration.\n */\n private async onReady(): Promise {\n // Initialize your adapter here\n\n this.log.info('Starting adapter.');\n\n await this.setInfoObjects();\n\n this.config.RenameSystemIds?.forEach((renameData: ioBroker.RenameData) => {\n if (renameData.OriginalId && renameData.NewId) {\n this.log.debug(`Map System ID: ${renameData.OriginalId} -> ${renameData.NewId}`);\n this.systemIds.set(renameData.OriginalId, this.replaceForbiddenCharacters(renameData.NewId));\n }\n });\n this.config.RenameDeviceIds?.forEach((renameData: ioBroker.RenameData) => {\n if (renameData.OriginalId && renameData.NewId) {\n this.log.debug(`Map Device ID: ${renameData.OriginalId} -> ${renameData.NewId}`);\n this.deviceIds.set(renameData.OriginalId, this.replaceForbiddenCharacters(renameData.NewId));\n }\n });\n this.config.RenameCategories?.forEach((renameData: ioBroker.RenameData) => {\n if (renameData.OriginalId && renameData.NewId) {\n this.log.debug(`Map Category: ${renameData.OriginalId} -> ${renameData.NewId}`);\n this.categories.set(renameData.OriginalId, this.replaceForbiddenCharacters(renameData.NewId));\n }\n });\n this.config.RenameDataIds?.forEach((renameData: ioBroker.RenameData) => {\n if (renameData.OriginalId && renameData.NewId) {\n this.log.debug(`Map Data ID: ${renameData.OriginalId} -> ${renameData.NewId}`);\n this.parameterIds.set(renameData.OriginalId, renameData.NewId);\n if (renameData.Category) {\n this.parameterIdToCategory.set(renameData.OriginalId, this.replaceForbiddenCharacters(renameData.Category));\n }\n }\n });\n\n this.refreshInterval = this.config.Interval * 60;\n if (this.refreshInterval < 60) {\n this.refreshInterval = 60;\n }\n\n const identifier: string = this.config.Identifier.trim();\n const secret: string = this.config.Secret.trim();\n const callbackURL: string = this.config.CallbackURL.trim();\n const configured: boolean = this.config.Configured;\n\n let error = false;\n if (identifier == '' || identifier == null) {\n if (configured != false) {\n this.log.error('Missing Identifier in the settings!');\n }\n error = true;\n }\n if (secret == '' || secret == null) {\n if (configured != false) {\n this.log.error('Missing Secret in the settings!');\n }\n error = true;\n }\n if (callbackURL == '' || callbackURL == null) {\n if (configured != false) {\n this.log.error('Missing Callback URL in the settings!');\n }\n error = true;\n }\n if (error) {\n this.setState('info.connection', { val: false, ack: true });\n this.setState('info.currentError', { val: 'Missing settings!', ack: true });\n return;\n }\n\n const dataDir: string = utils.getAbsoluteDefaultDataDir();\n let storeDir: string = path.join(dataDir, 'myuplink');\n try {\n // create directory\n if (!fs.existsSync(storeDir)) {\n fs.mkdirSync(storeDir);\n }\n } catch (err) {\n this.log.error('Could not create storage directory (' + storeDir + '): ' + err);\n storeDir = __dirname;\n }\n const storeFile = path.join(storeDir, 'session.' + this.instance + '.json');\n\n this.authRepository = new AuthRepository(\n {\n clientId: identifier,\n clientSecret: secret,\n useAuthorizationCodeGrant: this.config.UseAuthorizationCodeGrant,\n redirectUri: callbackURL,\n authCode: this.config.AuthCode.trim(),\n sessionStoreFilePath: storeFile,\n baseUrl: 'https://api.myuplink.com',\n scope: 'READSYSTEM WRITESYSTEM',\n timeout: 45000,\n userAgent: 'iobroker.myuplink',\n renewBeforeExpiry: 5 * 60 * 1000,\n },\n this.log,\n );\n\n this.myUplinkRepository = new MyUplinkRepository(\n {\n baseUrl: 'https://api.myuplink.com',\n timeout: 45000,\n userAgent: 'iobroker.myuplink',\n language: this.config.Language,\n },\n this.log,\n );\n\n await this.subscribeStatesAsync('*');\n\n this.log.info('Adapter started.');\n\n await this.getDataAsync();\n }\n\n private async getDataAsync(): Promise {\n try {\n if (this.authRepository) {\n const accessToken = await this.authRepository.getAccessTokenAsync();\n if (accessToken && this.myUplinkRepository) {\n const systems = await this.myUplinkRepository.getSystemsAndDevicesAsync(accessToken);\n this.setState('info.connection', { val: true, expire: this.refreshInterval + 30, ack: true });\n const newDate = new Date();\n const datetime = newDate.today() + ' ' + newDate.timeNow();\n this.setState('info.updateTime', { val: datetime, ack: true });\n this.setState('info.currentError', { val: '', ack: true });\n if (systems.systems) {\n for (const value of systems.systems) {\n await this.setSystemWithDevicesAsync(value, accessToken);\n }\n }\n }\n }\n } catch (error) {\n this.log.error('' + error);\n\n this.setState('info.connection', { val: false, ack: true });\n\n const newDate = new Date();\n const datetime = newDate.today() + ' ' + newDate.timeNow();\n this.setState('info.lastErrorTime', { val: datetime, ack: true });\n this.setState('info.lastError', { val: '' + error, ack: true });\n this.setState('info.currentError', { val: '' + error, ack: true });\n }\n\n this.log.debug('Set timer');\n this.timeout = this.setTimeout(\n async () => {\n await this.getDataAsync();\n },\n this.refreshInterval * 1000,\n );\n }\n\n private async setSystemWithDevicesAsync(system: SystemWithDevices, accessToken: string): Promise {\n if (system.systemId != undefined && system.name != undefined) {\n const systemIdExists = this.existingSystemIds.includes(system.systemId);\n const firstRun = !systemIdExists;\n if (!systemIdExists) {\n this.existingSystemIds.push(system.systemId);\n }\n const systemId = this.replaceForbiddenCharacters(system.systemId);\n const newSystemId = this.systemIds.get(systemId);\n const systemPath = newSystemId ?? systemId;\n const systemName = this.removeSoftHyphen(system.name);\n if (firstRun) {\n await this.myCreateDeviceAsync(systemPath, systemName);\n }\n await this.myCreateStringStateAsync(`${systemPath}.systemId`, 'System ID', system.systemId, firstRun);\n await this.myCreateStringStateAsync(`${systemPath}.name`, 'Name', systemName, firstRun, 'info.name');\n if (system.country != undefined) {\n await this.myCreateStringStateAsync(`${systemPath}.country`, 'Country', system.country, firstRun);\n }\n if (system.securityLevel != undefined) {\n await this.myCreateStringStateAsync(`${systemPath}.securityLevel`, 'Security Level', system.securityLevel, firstRun);\n }\n if (system.hasAlarm != undefined) {\n await this.myCreateBooleanStateAsync(`${systemPath}.hasAlarm`, 'Has Alarm', 'indicator.alarm', system.hasAlarm, firstRun);\n }\n if (system.devices) {\n for (const device of system.devices) {\n await this.setSystemDeviceAsync(device, systemPath, accessToken);\n }\n }\n\n if (this.config.AddActiveNotifications) {\n const notifications = await this.myUplinkRepository?.getActiveNotificationsAsync(system.systemId, accessToken);\n if (this.config.AddRawActiveNotifications) {\n await this.myCreateStringStateAsync(\n `${systemPath}.rawActiveNotifications`,\n 'Received raw JSON of active notifications',\n JSON.stringify(notifications?.notifications, null, ''),\n firstRun,\n );\n }\n let notificationsDescriptions: string = '';\n notifications?.notifications?.forEach((notification: Alarm) => {\n notificationsDescriptions += `${notification.header}: ${notification.description}\\n`;\n });\n await this.myCreateStringStateAsync(`${systemPath}.activeNotifications`, 'Active notification descriptions', notificationsDescriptions, firstRun);\n }\n }\n }\n\n private async setSystemDeviceAsync(device: SystemDevice, systemPath: string, accessToken: string): Promise {\n if (device.id != undefined && device.product?.name != undefined) {\n const existingMap = this.objectIdIdByParameterIdByDeviceId.get(device.id);\n const firstRun = !existingMap;\n const stateIdByParameterId = existingMap ?? new Map();\n if (!existingMap) {\n this.objectIdIdByParameterIdByDeviceId.set(device.id, stateIdByParameterId);\n }\n const deviceId = this.replaceForbiddenCharacters(device.id);\n const newDeviceId = this.deviceIds.get(deviceId);\n const deviceSubPath = newDeviceId ?? deviceId;\n const devicePath = `${systemPath}.${deviceSubPath}`;\n const deviceName = this.removeSoftHyphen(device.product.name);\n if (firstRun) {\n await this.myCreateChannelAsync(devicePath, deviceName);\n }\n await this.myCreateStringStateAsync(`${devicePath}.deviceId`, 'Device ID', device.id, firstRun);\n await this.myCreateStringStateAsync(`${devicePath}.name`, 'Name', deviceName, firstRun, 'info.name');\n if (device.connectionState != undefined) {\n await this.myCreateStringStateAsync(`${devicePath}.connectionState`, 'Connection State', device.connectionState, firstRun, 'info.status');\n }\n if (device.currentFwVersion != undefined) {\n await this.myCreateStringStateAsync(`${devicePath}.currentFwVersion`, 'Current Firmware Version', device.currentFwVersion, firstRun, 'info.firmware');\n }\n if (device.product?.serialNumber != undefined) {\n await this.myCreateStringStateAsync(`${devicePath}.serialNumber`, 'Serial Number', device.product.serialNumber, firstRun, 'info.serial');\n }\n\n if (this.config.AddData) {\n const devicePoints = await this.myUplinkRepository?.getDevicePointsAsync(device.id, accessToken);\n if (this.config.AddRawData) {\n await this.myCreateStringStateAsync(`${devicePath}.rawData`, 'Received raw JSON of parameter data', JSON.stringify(devicePoints, null, ''), firstRun);\n }\n if (devicePoints) {\n for (const data of devicePoints) {\n await this.setParameterDataAsync(data, devicePath, device.id, stateIdByParameterId);\n }\n }\n if (firstRun) {\n await this.setObjectNotExistsAsync(`${devicePath}.setData`, {\n type: 'state',\n common: {\n name: 'Send raw JSON of parameter data',\n type: 'string',\n role: 'json',\n read: true,\n write: true,\n },\n native: {\n rawJson: true,\n writable: true,\n deviceId: device.id,\n },\n });\n }\n }\n }\n }\n\n private async setParameterDataAsync(data: ParameterData, devicePath: string, deviceId: string | null | undefined, stateIdByParameterId: Map): Promise {\n if (data.parameterId) {\n const existingObjectId = stateIdByParameterId.get(data.parameterId);\n const stateId = existingObjectId ?? (await this.getObjectIdAndCreateCategoryAsync(data.parameterId, data.category, devicePath));\n if (!existingObjectId) {\n stateIdByParameterId.set(data.parameterId, stateId);\n await this.createParameterObjectAsync(data, deviceId, stateId);\n }\n await this.setStateAsync(stateId, { val: data.value, ack: true });\n }\n }\n\n private async getObjectIdAndCreateCategoryAsync(parameterId: string, category: string | null | undefined, devicePath: string): Promise {\n const newParameterId = this.parameterIds.get(parameterId) ?? parameterId;\n const parameterSubPath = this.replaceForbiddenCharacters(newParameterId);\n let objectId = `${devicePath}.${parameterSubPath}`;\n const newCategory = this.parameterIdToCategory.get(parameterId);\n if (newCategory) {\n objectId = `${devicePath}.${newCategory}.${parameterSubPath}`;\n } else if (category) {\n const categoryId = this.replaceForbiddenCharacters(category);\n const newCategoryId = this.categories.get(categoryId);\n const categorySubPath = newCategoryId ?? categoryId;\n const catPath = `${devicePath}.${categorySubPath}`;\n const pathWithCat = `${catPath}.${parameterSubPath}`;\n if (this.config.GroupData) {\n await this.delObjectAsync(objectId);\n objectId = pathWithCat;\n await this.myCreateFolderAsync(catPath, category);\n } else {\n await this.delObjectAsync(pathWithCat);\n await this.delObjectAsync(catPath);\n }\n }\n return objectId;\n }\n\n private async createParameterObjectAsync(data: ParameterData, deviceId: string | null | undefined, stateId: string): Promise {\n const obj: ioBroker.SettableObject = {\n type: 'state',\n common: {\n name: this.removeSoftHyphen(data.parameterName ?? ''),\n type: 'number',\n role: 'value',\n read: true,\n write: data.writable ?? false,\n },\n native: {\n parameterId: data.parameterId,\n writable: data.writable,\n deviceId: deviceId,\n },\n };\n if (data.parameterUnit) {\n obj.common.unit = data.parameterUnit;\n switch (data.parameterUnit) {\n case 'kWh':\n case 'Ws':\n obj.common.role = 'value.energy';\n break;\n case 'W':\n case 'kW':\n obj.common.role = 'value.power';\n break;\n case '\u00B0C':\n obj.common.role = 'value.temperature';\n break;\n case 'Hz':\n obj.common.role = 'value.frequency';\n break;\n case 'A':\n obj.common.role = 'value.current';\n break;\n case 'V':\n obj.common.role = 'value.voltage';\n break;\n case '%RH':\n obj.common.role = 'value.humidity';\n obj.common.unit = '%';\n break;\n case 'bar':\n obj.common.role = 'value.pressure';\n break;\n }\n }\n if (data.minValue) {\n obj.common.min = data.minValue;\n }\n if (data.maxValue) {\n obj.common.max = data.maxValue;\n }\n if (data.stepValue) {\n obj.common.step = data.stepValue;\n }\n if (data.enumValues && data.enumValues.length > 0) {\n const states: Record = {};\n data.enumValues.forEach((enumValue: EnumValues) => {\n if (enumValue.text && enumValue.value) {\n states[enumValue.value] = this.removeSoftHyphen(enumValue.text);\n }\n });\n obj.common.states = states;\n }\n await this.setObjectNotExistsAsync(stateId, obj);\n }\n\n private async setInfoObjects(): Promise {\n await this.setObjectNotExistsAsync('info', {\n type: 'channel',\n common: {\n name: 'Information',\n },\n native: {},\n });\n await this.setObjectNotExistsAsync('info.connection', {\n type: 'state',\n common: {\n name: 'Connected to myUplink',\n role: 'indicator.connected',\n type: 'boolean',\n read: true,\n write: false,\n def: false,\n },\n native: {},\n });\n await this.setObjectNotExistsAsync('info.currentError', {\n type: 'state',\n common: {\n name: 'Current Error',\n role: 'text',\n type: 'string',\n read: true,\n write: false,\n def: '',\n },\n native: {},\n });\n await this.setObjectNotExistsAsync('info.updateTime', {\n type: 'state',\n common: {\n name: 'Time of the last update',\n role: 'text',\n type: 'string',\n read: true,\n write: false,\n def: '',\n },\n native: {},\n });\n await this.setObjectNotExistsAsync('info.lastError', {\n type: 'state',\n common: {\n name: 'Last Error',\n role: 'text',\n type: 'string',\n read: true,\n write: false,\n def: '',\n },\n native: {},\n });\n await this.setObjectNotExistsAsync('info.lastErrorTime', {\n type: 'state',\n common: {\n name: 'Time of the last error',\n role: 'text',\n type: 'string',\n read: true,\n write: false,\n def: '',\n },\n native: {},\n });\n }\n\n private async myCreateDeviceAsync(path: string, name: string): Promise {\n this.log.debug(`create Device: ${path}`);\n await this.setObjectNotExistsAsync(path, {\n type: 'device',\n common: {\n name: name,\n },\n native: {},\n });\n }\n\n private async myCreateChannelAsync(path: string, name: string): Promise {\n this.log.debug(`create Channel: ${path}`);\n await this.setObjectNotExistsAsync(path, {\n type: 'channel',\n common: {\n name: name,\n },\n native: {},\n });\n }\n\n private async myCreateFolderAsync(path: string, name: string): Promise {\n if (!this.existingFolders.includes(path)) {\n this.existingFolders.push(path);\n this.log.debug(`create Folder: ${path}`);\n await this.setObjectNotExistsAsync(path, {\n type: 'folder',\n common: {\n name: name,\n },\n native: {},\n });\n }\n }\n\n private async myCreateStringStateAsync(path: string, name: string, value: string, createObject: boolean, role: string = 'text'): Promise {\n if (createObject) {\n this.log.debug(`create State: ${path}`);\n await this.setObjectNotExistsAsync(path, {\n type: 'state',\n common: {\n name: name,\n type: 'string',\n role: role,\n read: true,\n write: false,\n },\n native: {},\n });\n }\n await this.setStateAsync(path, { val: value, ack: true });\n }\n\n private async myCreateBooleanStateAsync(path: string, name: string, role: string, value: boolean, createObject: boolean): Promise {\n if (createObject) {\n this.log.debug(`create State: ${path}`);\n await this.setObjectNotExistsAsync(path, {\n type: 'state',\n common: {\n name: name,\n type: 'boolean',\n role: role,\n read: true,\n write: false,\n },\n native: {},\n });\n }\n await this.setStateAsync(path, { val: value, ack: true });\n }\n\n private removeSoftHyphen(text: string): string {\n return text.replace(new RegExp('\\u00AD', 'g'), '');\n }\n\n private replaceForbiddenCharacters(text: string): string {\n return this.removeSoftHyphen(text).replace(this.STRICT_FORBIDDEN_CHARS, '_');\n }\n\n /**\n * Is called if a subscribed state changes\n */\n private async onStateChange(id: string, state: ioBroker.State | null | undefined): Promise {\n if (state != null && state.ack === false && state.q == this.constants.STATE_QUALITY.GOOD && state.val != null && this.authRepository != null && this.myUplinkRepository != null) {\n this.log.debug(`state ${id} changed: ${state.val} (ack = ${state.ack})`);\n const obj = await this.getObjectAsync(id);\n if (obj != null && obj.native != null && obj.native.writable == true && obj.native.deviceId != null && obj.native.deviceId != '') {\n try {\n const accessToken = await this.authRepository.getAccessTokenAsync();\n if (accessToken) {\n const deviceId = obj.native.deviceId;\n const value = state.val.toString();\n if (obj.native.parameterId != null && obj.native.parameterId != '') {\n const parameterId = obj.native.parameterId.toString();\n const result = await this.myUplinkRepository.setDevicePointAsync(deviceId, accessToken, parameterId, value);\n if (result.status == 200 && result.payload && parameterId in result.payload && result.payload[parameterId] == 'modified') {\n this.log.debug(`Parameter ${parameterId} modified by API`);\n await this.setStateAsync(id, { val: state.val, ack: true });\n }\n } else if (obj.native.rawJson === true && value) {\n const keyValueDictionary: Record = JSON.parse(value);\n const result = await this.myUplinkRepository.setDevicePointsAsync(deviceId, accessToken, keyValueDictionary);\n if (result.status == 200) {\n await this.setStateAsync(id, { val: state.val, q: this.constants.STATE_QUALITY.GOOD, ack: true, c: undefined });\n const objectIdByParameterId = this.objectIdIdByParameterIdByDeviceId.get(deviceId);\n if (objectIdByParameterId && result.payload) {\n for (const [parameterId, value] of Object.entries(keyValueDictionary)) {\n const objectId = objectIdByParameterId.get(parameterId);\n const valNumber = parseFloat(value);\n if (objectId && !Number.isNaN(valNumber) && parameterId in result.payload && result.payload[parameterId] == 'modified') {\n await this.setStateAsync(objectId, { val: valNumber, ack: true });\n }\n }\n }\n } else {\n this.log.error(`SetData: \"${value}\"\\nResult: \"${JSON.stringify(result, null, ' ')}\"`);\n await this.setStateAsync(id, { val: state.val, q: this.constants.STATE_QUALITY.DEVICE_ERROR_REPORT, ack: false, c: `Status: ${result.status}` });\n }\n }\n }\n } catch (error) {\n const errorString = `${error}`;\n this.log.error(errorString);\n const quality = this.constants.STATE_QUALITY.DEVICE_ERROR_REPORT;\n await this.setStateAsync(id, { val: state.val, q: quality, c: errorString, ack: false });\n }\n }\n }\n }\n\n /**\n * Is called when adapter shuts down - callback has to be called under any circumstances!\n */\n private onUnload(callback: () => void): void {\n try {\n this.clearTimeout(this.timeout);\n this.timeout = undefined;\n this.authRepository = undefined;\n this.myUplinkRepository = undefined;\n this.setState('info.connection', { val: false, ack: true });\n this.log.info('Cleaned everything up...');\n callback();\n } catch (e) {\n callback();\n }\n }\n}\n\nif (require.main !== module) {\n // Export the constructor in compact mode\n module.exports = (options: Partial | undefined) => new Myuplink(options);\n} else {\n // otherwise start the instance directly\n (() => new Myuplink())();\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;AAMA,YAAuB;AACvB,SAAoB;AACpB,WAAsB;AACtB,4BAA+B;AAM/B,gCAAmC;AAUnC,KAAK,UAAU,QAAQ,WAAoB;AACvC,SAAO,KAAK,YAAY,IAAI,OAAO,KAAK,SAAS,IAAI,IAAI,KAAK,MAAM,OAAO,KAAK,SAAS,IAAI,KAAK,OAAO,KAAK,QAAQ,IAAI,KAAK,MAAM,MAAM,KAAK,QAAQ;AAC5J;AAQA,KAAK,UAAU,UAAU,WAAoB;AACzC,UAAQ,KAAK,SAAS,IAAI,KAAK,MAAM,MAAM,KAAK,SAAS,IAAI,OAAO,KAAK,WAAW,IAAI,KAAK,MAAM,MAAM,KAAK,WAAW,IAAI,OAAO,KAAK,WAAW,IAAI,KAAK,MAAM,MAAM,KAAK,WAAW;AAC7L;AAEA,MAAM,iBA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EACJ;AAAA,EAKQ,SAAS,UAA4B;AACzC,QAAI;AACA,WAAK,aAAa,KAAK,OAAO;AAC9B,WAAK,UAAU;AACf,WAAK,iBAAiB;AACtB,WAAK,qBAAqB;AAC1B,WAAK,SAAS,mBAAmB,EAAE,KAAK,OAAO,KAAK,KAAK,CAAC;AAC1D,WAAK,IAAI,KAAK,0BAA0B;AACxC,eAAS;AAAA,IACb,SAAS,GAAP;AACE,eAAS;AAAA,IACb;AAAA,EACJ;AACJ;AAEA,IAAI,QAAQ,SAAS,QAAQ;AAEzB,SAAO,UAAU,CAAC,YAAuD,IAAI,SAAS,OAAO;AACjG,OAAO;AAEH,GAAC,MAAM,IAAI,SAAS,GAAG;AAC3B;", "names": ["path", "value"] } diff --git a/build/myuplinkRepository.js b/build/myuplinkRepository.js index 484e608..4e9e16d 100644 --- a/build/myuplinkRepository.js +++ b/build/myuplinkRepository.js @@ -42,16 +42,16 @@ class MyUplinkRepository { getSystemsAndDevicesAsync(accessToken) { return this.getFromMyUplinkAsync("/v2/systems/me", accessToken); } - async getDevicePointsAsync(deviceId, accessToken) { - return await this.getFromMyUplinkAsync(`/v3/devices/${deviceId}/points`, accessToken); + getDevicePointsAsync(deviceId, accessToken) { + return this.getFromMyUplinkAsync(`/v3/devices/${deviceId}/points`, accessToken); } - async setDevicePointAsync(deviceId, accessToken, parameterId, value) { + setDevicePointAsync(deviceId, accessToken, parameterId, value) { const body = {}; setProperty(body, parameterId, value); - return await this.setDevicePointsAsync(deviceId, accessToken, body); + return this.setDevicePointsAsync(deviceId, accessToken, body); } - async setDevicePointsAsync(deviceId, accessToken, keyValueDictionary) { - return await this.patchToMyUplinkAsync(`/v2/devices/${deviceId}/points`, keyValueDictionary, accessToken); + setDevicePointsAsync(deviceId, accessToken, keyValueDictionary) { + return this.patchToMyUplinkAsync(`/v2/devices/${deviceId}/points`, keyValueDictionary, accessToken); } getActiveNotificationsAsync(systemId, accessToken) { return this.getFromMyUplinkAsync(`/v2/systems/${systemId}/notifications/active?itemsPerPage=100`, accessToken); diff --git a/build/myuplinkRepository.js.map b/build/myuplinkRepository.js.map index 55fca3f..6bd4aa2 100644 --- a/build/myuplinkRepository.js.map +++ b/build/myuplinkRepository.js.map @@ -1,7 +1,7 @@ { "version": 3, "sources": ["../src/myuplinkRepository.ts"], - "sourcesContent": ["import axios, { AxiosError } from 'axios';\nimport { AlarmsPaged } from './models/AlarmsPaged';\nimport { CloudToDeviceMethodResult } from './models/CloudToDeviceMethodResult';\nimport { PagedSystemResult } from './models/PagedSystemResult';\nimport { ParameterData } from './models/ParameterData';\n\nfunction setProperty(obj: any, propertyName: K, value: any): void {\n obj[propertyName] = value;\n}\n\nexport default interface MyUplinkOptions {\n baseUrl: string;\n timeout: number;\n userAgent: string;\n language: string;\n}\n\nexport class MyUplinkRepository {\n constructor(options: MyUplinkOptions, log: ioBroker.Log) {\n this.log = log;\n this.options = options;\n\n axios.defaults.baseURL = options.baseUrl;\n axios.defaults.headers.common['user-agent'] = options.userAgent;\n axios.defaults.timeout = options.timeout;\n }\n\n private log: ioBroker.Log;\n private options: MyUplinkOptions;\n\n getSystemsAndDevicesAsync(accessToken: string): Promise {\n return this.getFromMyUplinkAsync('/v2/systems/me', accessToken);\n }\n\n async getDevicePointsAsync(deviceId: string, accessToken: string): Promise {\n return await this.getFromMyUplinkAsync(`/v3/devices/${deviceId}/points`, accessToken);\n }\n\n async setDevicePointAsync(deviceId: string, accessToken: string, parameterId: string, value: string): Promise {\n const body = {};\n setProperty(body, parameterId, value);\n return await this.setDevicePointsAsync(deviceId, accessToken, body);\n }\n\n async setDevicePointsAsync(deviceId: string, accessToken: string, keyValueDictionary: Record): Promise {\n return await this.patchToMyUplinkAsync(`/v2/devices/${deviceId}/points`, keyValueDictionary, accessToken);\n }\n\n getActiveNotificationsAsync(systemId: string, accessToken: string): Promise {\n return this.getFromMyUplinkAsync(`/v2/systems/${systemId}/notifications/active?itemsPerPage=100`, accessToken);\n }\n\n private async getFromMyUplinkAsync(url: string, accessToken: string): Promise {\n const lang = this.options.language;\n this.log.debug(`GET ${url} (lang: ${lang})`);\n try {\n const { data } = await axios.get(url, {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Accept-Language': lang,\n },\n });\n this.log.silly(JSON.stringify(data, null, ' '));\n return data;\n } catch (error) {\n throw this.checkError(url, error);\n }\n }\n\n private async patchToMyUplinkAsync(url: string, body: any, accessToken: string): Promise {\n const lang = this.options.language;\n this.log.debug(`PATCH ${url} (lang: ${lang})`);\n this.log.silly(`PATCH body: ${JSON.stringify(body, null, ' ')}`);\n try {\n const { data } = await axios.patch(url, body, {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Accept-Language': lang,\n },\n });\n this.log.debug(JSON.stringify(data, null, ' '));\n return data;\n } catch (error) {\n throw this.checkError(url, error);\n }\n }\n\n private checkError(suburl: string, error: unknown): unknown {\n this.log.error(`error from ${suburl}`);\n this.log.error(JSON.stringify(error, null, ' '));\n if (axios.isAxiosError(error)) {\n const axiosError = error as AxiosError;\n if (axiosError.response != null) {\n if (axiosError.response.data != null) {\n const responseText = JSON.stringify(axiosError.response.data, null, ' ');\n const errorMessage = `${axiosError.response.statusText}: ${responseText}`;\n return new Error(errorMessage);\n } else {\n return new Error(axiosError.response.statusText);\n }\n }\n }\n return error;\n }\n}\n"], - "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkC;AAMlC,SAAS,YAAiC,KAAU,cAAiB,OAAkB;AACnF,MAAI,gBAAgB;AACxB;AASO,MAAM,mBAAmB;AAAA,EAC5B,YAAY,SAA0B,KAAmB;AACrD,SAAK,MAAM;AACX,SAAK,UAAU;AAEf,iBAAAA,QAAM,SAAS,UAAU,QAAQ;AACjC,iBAAAA,QAAM,SAAS,QAAQ,OAAO,gBAAgB,QAAQ;AACtD,iBAAAA,QAAM,SAAS,UAAU,QAAQ;AAAA,EACrC;AAAA,EAKA,0BAA0B,aAAiD;AACvE,WAA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AK,MAAM;AAAA,QAC7C,SAAS;AAAA,UACL,eAAe,UAAU;AAAA,UACzB,mBAAmB;AAAA,QACvB;AAAA,MACJ,CAAC;AACD,WAAK,IAAI,MAAM,KAAK,UAAU,MAAM,MAAM,GAAG,CAAC;AAC9C,aAAO;AAAA,IACX,SAAS,OAAP;AACE,YAAM,KAAK,WAAW,KAAK,KAAK;AAAA,IACpC;AAAA,EACJ;AAAA,EAEQ,WAAW,QAAgB,OAAyB;AACxD,SAAK,IAAI,MAAM,cAAc,QAAQ;AACrC,SAAK,IAAI,MAAM,KAAK,UAAU,OAAO,MAAM,GAAG,CAAC;AAC/C,QAAI,aAAAA,QAAM,aAAa,KAAK,GAAG;AAC3B,YAAM,aAAa;AACnB,UAAI,WAAW,YAAY,MAAM;AAC7B,YAAI,WAAW,SAAS,QAAQ,MAAM;AAClC,gBAAM,eAAe,KAAK,UAAU,WAAW,SAAS,MAAM,MAAM,GAAG;AACvE,gBAAM,eAAe,GAAG,WAAW,SAAS,eAAe;AAC3D,iBAAO,IAAI,MAAM,YAAY;AAAA,QACjC,OAAO;AACH,iBAAO,IAAI,MAAM,WAAW,SAAS,UAAU;AAAA,QACnD;AAAA,MACJ;AAAA,IACJ;AACA,WAAO;AAAA,EACX;AACJ;", + "sourcesContent": ["import axios, { AxiosError } from 'axios';\nimport { AlarmsPaged } from './models/AlarmsPaged';\nimport { CloudToDeviceMethodResult } from './models/CloudToDeviceMethodResult';\nimport { PagedSystemResult } from './models/PagedSystemResult';\nimport { ParameterData } from './models/ParameterData';\n\nfunction setProperty(obj: any, propertyName: K, value: any): void {\n obj[propertyName] = value;\n}\n\nexport default interface MyUplinkOptions {\n baseUrl: string;\n timeout: number;\n userAgent: string;\n language: string;\n}\n\nexport class MyUplinkRepository {\n constructor(options: MyUplinkOptions, log: ioBroker.Log) {\n this.log = log;\n this.options = options;\n\n axios.defaults.baseURL = options.baseUrl;\n axios.defaults.headers.common['user-agent'] = options.userAgent;\n axios.defaults.timeout = options.timeout;\n }\n\n private log: ioBroker.Log;\n private options: MyUplinkOptions;\n\n getSystemsAndDevicesAsync(accessToken: string): Promise {\n return this.getFromMyUplinkAsync('/v2/systems/me', accessToken);\n }\n\n getDevicePointsAsync(deviceId: string, accessToken: string): Promise {\n return this.getFromMyUplinkAsync(`/v3/devices/${deviceId}/points`, accessToken);\n }\n\n setDevicePointAsync(deviceId: string, accessToken: string, parameterId: string, value: string): Promise {\n const body = {};\n setProperty(body, parameterId, value);\n return this.setDevicePointsAsync(deviceId, accessToken, body);\n }\n\n setDevicePointsAsync(deviceId: string, accessToken: string, keyValueDictionary: Record): Promise {\n return this.patchToMyUplinkAsync(`/v2/devices/${deviceId}/points`, keyValueDictionary, accessToken);\n }\n\n getActiveNotificationsAsync(systemId: string, accessToken: string): Promise {\n return this.getFromMyUplinkAsync(`/v2/systems/${systemId}/notifications/active?itemsPerPage=100`, accessToken);\n }\n\n private async getFromMyUplinkAsync(url: string, accessToken: string): Promise {\n const lang = this.options.language;\n this.log.debug(`GET ${url} (lang: ${lang})`);\n try {\n const { data } = await axios.get(url, {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Accept-Language': lang,\n },\n });\n this.log.silly(JSON.stringify(data, null, ' '));\n return data;\n } catch (error) {\n throw this.checkError(url, error);\n }\n }\n\n private async patchToMyUplinkAsync(url: string, body: any, accessToken: string): Promise {\n const lang = this.options.language;\n this.log.debug(`PATCH ${url} (lang: ${lang})`);\n this.log.silly(`PATCH body: ${JSON.stringify(body, null, ' ')}`);\n try {\n const { data } = await axios.patch(url, body, {\n headers: {\n Authorization: `Bearer ${accessToken}`,\n 'Accept-Language': lang,\n },\n });\n this.log.debug(JSON.stringify(data, null, ' '));\n return data;\n } catch (error) {\n throw this.checkError(url, error);\n }\n }\n\n private checkError(suburl: string, error: unknown): unknown {\n this.log.error(`error from ${suburl}`);\n this.log.error(JSON.stringify(error, null, ' '));\n if (axios.isAxiosError(error)) {\n const axiosError = error as AxiosError;\n if (axiosError.response != null) {\n if (axiosError.response.data != null) {\n const responseText = JSON.stringify(axiosError.response.data, null, ' ');\n const errorMessage = `${axiosError.response.statusText}: ${responseText}`;\n return new Error(errorMessage);\n } else {\n return new Error(axiosError.response.statusText);\n }\n }\n }\n return error;\n }\n}\n"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,mBAAkC;AAMlC,SAAS,YAAiC,KAAU,cAAiB,OAAkB;AACnF,MAAI,gBAAgB;AACxB;AASO,MAAM,mBAAmB;AAAA,EAC5B,YAAY,SAA0B,KAAmB;AACrD,SAAK,MAAM;AACX,SAAK,UAAU;AAEf,iBAAAA,QAAM,SAAS,UAAU,QAAQ;AACjC,iBAAAA,QAAM,SAAS,QAAQ,OAAO,gBAAgB,QAAQ;AACtD,iBAAAA,QAAM,SAAS,UAAU,QAAQ;AAAA,EACrC;AAAA,EAKA,0BAA0B,aAAiD;AACvE,WAAO,KAAK,qBAAwC,kBAAkB,WAAW;AAAA,EACrF;AAAA,EAEA,qBAAqB,UAAkB,aAA+C;AAClF,WAAO,KAAK,qBAAsC,eAAe,mBAAmB,WAAW;AAAA,EACnG;AAAA,EAEA,oBAAoB,UAAkB,aAAqB,aAAqB,OAAmD;AAC/H,UAAM,OAAO,CAAC;AACd,gBAAY,MAAM,aAAa,KAAK;AACpC,WAAO,KAAK,qBAAqB,UAAU,aAAa,IAAI;AAAA,EAChE;AAAA,EAEA,qBAAqB,UAAkB,aAAqB,oBAAgF;AACxI,WAAO,KAAK,qBAAgD,eAAe,mBAAmB,oBAAoB,WAAW;AAAA,EACjI;AAAA,EAEA,4BAA4B,UAAkB,aAA2C;AACrF,WAAO,KAAK,qBAAkC,eAAe,kDAAkD,WAAW;AAAA,EAC9H;AAAA,EAEA,MAAc,qBAAwB,KAAa,aAAiC;AAChF,UAAM,OAAO,KAAK,QAAQ;AAC1B,SAAK,IAAI,MAAM,OAAO,cAAc,OAAO;AAC3C,QAAI;AACA,YAAM,EAAE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AO,IAAI,MAAM,WAAW,SAAS,UAAU;AAAA,QACnD;AAAA,MACJ;AAAA,IACJ;AACA,WAAO;AAAA,EACX;AACJ;", "names": ["axios"] } diff --git a/src/main.ts b/src/main.ts index c5d9f80..58dada3 100644 --- a/src/main.ts +++ b/src/main.ts @@ -195,10 +195,11 @@ class Myuplink extends utils.Adapter { const datetime = newDate.today() + ' ' + newDate.timeNow(); this.setState('info.updateTime', { val: datetime, ack: true }); this.setState('info.currentError', { val: '', ack: true }); - - systems.systems?.forEach(async (value: SystemWithDevices) => { - await this.setSystemWithDevicesAsync(value, accessToken); - }); + if (systems.systems) { + for (const value of systems.systems) { + await this.setSystemWithDevicesAsync(value, accessToken); + } + } } } } catch (error) { @@ -213,6 +214,7 @@ class Myuplink extends utils.Adapter { this.setState('info.currentError', { val: '' + error, ack: true }); } + this.log.debug('Set timer'); this.timeout = this.setTimeout( async () => { await this.getDataAsync(); @@ -246,9 +248,11 @@ class Myuplink extends utils.Adapter { if (system.hasAlarm != undefined) { await this.myCreateBooleanStateAsync(`${systemPath}.hasAlarm`, 'Has Alarm', 'indicator.alarm', system.hasAlarm, firstRun); } - system.devices?.forEach(async (dev: SystemDevice) => { - await this.setSystemDeviceAsync(dev, systemPath, accessToken); - }); + if (system.devices) { + for (const device of system.devices) { + await this.setSystemDeviceAsync(device, systemPath, accessToken); + } + } if (this.config.AddActiveNotifications) { const notifications = await this.myUplinkRepository?.getActiveNotificationsAsync(system.systemId, accessToken); @@ -302,9 +306,11 @@ class Myuplink extends utils.Adapter { if (this.config.AddRawData) { await this.myCreateStringStateAsync(`${devicePath}.rawData`, 'Received raw JSON of parameter data', JSON.stringify(devicePoints, null, ''), firstRun); } - devicePoints?.forEach(async (data: ParameterData) => { - await this.setParameterDataAsync(data, devicePath, device.id, stateIdByParameterId); - }); + if (devicePoints) { + for (const data of devicePoints) { + await this.setParameterDataAsync(data, devicePath, device.id, stateIdByParameterId); + } + } if (firstRun) { await this.setObjectNotExistsAsync(`${devicePath}.setData`, { type: 'state', @@ -609,13 +615,13 @@ class Myuplink extends utils.Adapter { await this.setStateAsync(id, { val: state.val, q: this.constants.STATE_QUALITY.GOOD, ack: true, c: undefined }); const objectIdByParameterId = this.objectIdIdByParameterIdByDeviceId.get(deviceId); if (objectIdByParameterId && result.payload) { - Object.entries(keyValueDictionary).forEach(async ([parameterId, value]) => { + for (const [parameterId, value] of Object.entries(keyValueDictionary)) { const objectId = objectIdByParameterId.get(parameterId); const valNumber = parseFloat(value); if (objectId && !Number.isNaN(valNumber) && parameterId in result.payload && result.payload[parameterId] == 'modified') { await this.setStateAsync(objectId, { val: valNumber, ack: true }); } - }); + } } } else { this.log.error(`SetData: "${value}"\nResult: "${JSON.stringify(result, null, ' ')}"`); diff --git a/src/myuplinkRepository.ts b/src/myuplinkRepository.ts index c7e2d5e..f8d840b 100644 --- a/src/myuplinkRepository.ts +++ b/src/myuplinkRepository.ts @@ -32,18 +32,18 @@ export class MyUplinkRepository { return this.getFromMyUplinkAsync('/v2/systems/me', accessToken); } - async getDevicePointsAsync(deviceId: string, accessToken: string): Promise { - return await this.getFromMyUplinkAsync(`/v3/devices/${deviceId}/points`, accessToken); + getDevicePointsAsync(deviceId: string, accessToken: string): Promise { + return this.getFromMyUplinkAsync(`/v3/devices/${deviceId}/points`, accessToken); } - async setDevicePointAsync(deviceId: string, accessToken: string, parameterId: string, value: string): Promise { + setDevicePointAsync(deviceId: string, accessToken: string, parameterId: string, value: string): Promise { const body = {}; setProperty(body, parameterId, value); - return await this.setDevicePointsAsync(deviceId, accessToken, body); + return this.setDevicePointsAsync(deviceId, accessToken, body); } - async setDevicePointsAsync(deviceId: string, accessToken: string, keyValueDictionary: Record): Promise { - return await this.patchToMyUplinkAsync(`/v2/devices/${deviceId}/points`, keyValueDictionary, accessToken); + setDevicePointsAsync(deviceId: string, accessToken: string, keyValueDictionary: Record): Promise { + return this.patchToMyUplinkAsync(`/v2/devices/${deviceId}/points`, keyValueDictionary, accessToken); } getActiveNotificationsAsync(systemId: string, accessToken: string): Promise {