iobroker.lovelace
Version:
With this adapter you can build visualization for ioBroker with Home Assistant Lovelace UI
999 lines (909 loc) • 143 kB
JavaScript
const fs = require('fs');
const crypto = require('crypto');
const WebSocket = require('ws');
const bodyParser = require('body-parser');
const SERVICES = require('./services');
const PANELS = require('./panels');
const multer = require('multer');
const mime = require('mime');
const yaml = require('js-yaml');
const axios = require('axios');
const jstz = require('jstimezonedetect');
const utils = require('./converters/utils');
const processBlind = require('./converters/cover').processBlind;
const converterSwitch = require('./converters/switch');
const converterLight = require('./converters/light');
const converterBinarySensors = require('./converters/binary_sensor');
const converterSensors = require('./converters/sensor');
const processMediaPlayer = require('./converters/media_player').processMediaPlayer;
const converterClimate = require('./converters/climate');
const converterWeather = require('./converters/weather');
const processImage = require('./converters/camera').processImage;
const processLock = require('./converters/lock').processLock;
const processLocation = require('./converters/geo_location').processLocation;
const converterDatetime = require('./converters/input_datetime');
const converterAlarmCP = require('./converters/alarm_control_panel');
const converterInputSelect = require('./converters/input_select');
const entityData = require('./dataSingleton');
const bindings = require('./bindings');
const TIMEOUT_PASSWORD_ENTER = 180000; // 3 min
const TIMEOUT_AUTH_CODE = 10000; // 10sec
const {Types, ChannelDetector} = require('iobroker.type-detector');
const ignoreIds = [
/^system\./,
/^script\./,
];
const express = require('express');
const ROOT_DIR = '../hass_frontend';
const VERSION = '0.102.1';
const NO_TOKEN = 'no_token';
function getRootPath() {
if (ROOT_DIR.match(/^\w:/) || ROOT_DIR.startsWith('/')) {
return ROOT_DIR + '/';
} else {
return `${__dirname}/${ROOT_DIR}/`;
}
}
const generateRandomToken = function (callback) {
crypto.randomBytes(256, (ex, buffer) => {
crypto.randomBytes(32, (ex, secret) => {
if (ex) {
return callback('server_error');
}
const token = crypto
.createHmac('sha256', secret)
.update(buffer)
.digest('hex');
callback(false, token);
});
});
};
/*
possible HASS entity types:
- fan
- input_boolean
- light => STATE on/off, attributes: [brightness, hs_color([h,s]), min_mireds, max_mireds, color_temp, white_value, effect_list, effect, supported_features ], commands: turn_on(brightness_pct, hs_color, brightness, color_temp, white_value, effect), turn_off, toggle
supported_features: brightness=0x01, colorTemp=0x02, effectList=0x04, color=0x10, whiteValue=0x80
- switch => STATE on/off, attributes: [brightness, hs_color], commands: turn_on, turn_off, toggle
- group
- automation
- climate => STATE on/off, attributes: [current_temperature, operation_mode, operation_list, target_temp_step, target_temp_low, target_temp_high,min_temp, max_temp, temperature], commands:
- cover
- configurator
- input_select
- input_number
- input_text
- lock
- media_player =>
STATE on/off/playing/paused/idle/standby/unknown,
attributes: [media_content_type(music/game/music/tvshow/...), entity_picture(as cover), media_duration, supported_features, is_volume_muted, volume_level, media_duration, media_position, media_position_updated_at, media_title, media_artist, media_series_title, media_season, media_episode, app_name, source, source_list, sound_mode, sound_mode_list],
commands: media_play_pause, media_next_track, media_play_pause, media_previous_track, volume_set(volume_level), turn_off, turn_on, volume_down, volume_mute(is_volume_muted), volume_up, select_source(source), select_sound_mode(sound_mode),
features for supported_features: PAUSE 0x1, volume_set 0x4, volume_mute 0x8, media_previous_track 0x10, media_next_track 0x20, turn_on 0x80, turn_off 0x100, play_media 0x200, volume_down/volume_up 0x400, select_source 0x800, select_sound_mode (0x10000), play (0x4000)
- scene
- script
- timer => STATE idle/paused/active, attributes: [remaining]
- vacuum
- water_heater
- weblink
- camera
- history_graph
- input_datetime
- sun
- updater
- binary_sensor => STATE on/off
- geo_location => attributes: [latitude, longitude, passive, icon, radius, entity_picture, gps_accuracy, source]
- weather => STATE any-text(no icon)/clear-night/cloudy/fog/hail/lightning/lightning-rainy/partlycloudy/pouring/rainy/snowy/snowy-rainy/sunny/windy/windy-variant, attributes: [temperature, pressure, humidity, wind_speed, wind_bearing, forecast]
forecast is an array with max 5 items [{datetime: something for new Date(aa), temperature, templow, condition(see STATE), precipitation}, {...}]
*/
class WebServer {
constructor(options) {
this._lovelaceConfig = null;
this._ressourceConfig = []; //new place to store custom cards (modules) and stuff.
this.adapter = options.adapter;
this.config = this.adapter.config;
this.log = this.adapter.log;
this.lang = 'en';
this.detector = new ChannelDetector();
this.config.ttl = parseInt(this.config.ttl, 10) || 3600;
this.words = options.words || {};
//setup entityData:
entityData.adapter = this.adapter;
entityData.log = this.adapter.log;
entityData.words = this.words;
this._notifications = [];
this._subscribed = [];
this._server = options.server;
this._app = options.app;
this._auth_flows = {};
this.templateStates = {};
this._themes = {}; //themes storage
this._currentTheme = this.config.defaultTheme || 'default';
this._currentThemeDark = this.config.defaultThemeDark || 'default';
this._darkMode = false;
//object data for updates:
this._objectData = {
objects: {}, //id -> object storage
ids: [], //array of object ids.
rooms: [],
functions: [],
roomNames: {}, //id -> name storage
funcNames: {},
updatedObjects: [], //id + object pairs on updates to handle burst updates after burst.
usedKeys: [] //temporary storage for used keys (type-detector)
};
this.converter = {
[Types.socket]: converterSwitch.processSocket,
[Types.light]: converterLight.processLight,
[Types.dimmer]: converterLight.processLightAdvanced,
[Types.ct]: converterLight.processLightAdvanced,
[Types.hue]: converterLight.processLightAdvanced,
[Types.rgb]: converterLight.processLightAdvanced,
[Types.rgbSingle]: converterLight.processLightAdvanced,
[Types.motion]: converterBinarySensors.processMotion,
[Types.window]: converterBinarySensors.processWindow,
[Types.windowTilt]: converterSensors.processWindowTilt,
[Types.door]: converterBinarySensors.processDoor,
[Types.button]: converterSwitch.processSocket,
[Types.temperature]: converterSensors.processTemperature,
[Types.humidity]: converterSensors.processHumidity,
[Types.lock]: processLock,
[Types.airCondition]: converterClimate.processThermostatOrAirConditioning,
[Types.thermostat]: converterClimate.processThermostatOrAirConditioning,
[Types.blind]: processBlind,
[Types.blindButtons]: processBlind,
[Types.weatherForecast]: converterWeather.processWeather,
[Types.accuWeatherForecast]: converterWeather.processAccuWeather,
[Types.location]: processLocation,
[Types.location_one]: processLocation,
[Types.media]: processMediaPlayer,
[Types.image]: processImage,
};
const concurrentPromises = [
this.adapter.getForeignObjectAsync('system.config')
.then(config => {
this.lang = config.common.language;
entityData.lang = this.lang;
this.systemConfig = config.common;
this._updateConstantEntities();
return this.adapter.getObjectAsync('configuration');
})
.then(config => {
if (config && config.native && config.native.title) {
this._lovelaceConfig = config.native;
this._lovelaceConfig.hideToolbar = this.config.hideHeader;
} else {
this._lovelaceConfig = require('./defaultConfig');
}
return this._readNotifications();
}),
this._readAllEntities(),
this._listFiles(),
this._initThemes()
];
Promise.all(concurrentPromises).then(() => {
this.adapter.subscribeObjects('configuration');
this.adapter.subscribeStates('control.*');
this.adapter.subscribeStates('notifications.*');
this.adapter.subscribeStates('conversation');
this._init();
// check every minute
if (this.config.auth !== false) {
this._clearInterval = setInterval(() => this.clearAuth(), 60000);
}
this.log.debug('Initialization done.');
});
}
async _readAllEntities() {
const smartDevices = await this._updateDevices();
for (const entity of smartDevices) {
//fill entity into
utils.fillEntityIntoCaches(entity);
}
await this._getAllEntities(); //creates manual entities.
//now all entities are created. Check for icon urls:
for (const entity of entityData.entities) {
if (entity.attributes.entity_picture && !entity.attributes.entity_picture.match(/^data:image\//)) {
const url = entity.attributes.entity_picture.replace(/^\./, '');
if (!entityData.entityIconUrls.includes(url)) {
entityData.entityIconUrls.push(url);
}
}
}
await this._getAllStates();
this._manageSubscribesFromConfig();
await this.adapter.setStateAsync('info.entitiesUpdated', true, true);
}
clearAuth() {
const now = Date.now();
let changed = false;
Object.keys(this._auth_flows).forEach(flowId => {
const flow = this._auth_flows[flowId];
if (flow.auth_ttl) {
if (now - flow.ts > flow.auth_ttl) {
this.log.debug(`Deleted old flowId ${flow.username} ${flowId}`);
delete this._auth_flows[flowId];
changed = true;
}
} else {
if (now - flow.ts > TIMEOUT_PASSWORD_ENTER) {
this.log.debug('Deleted old flowId (no password) ' + flowId);
delete this._auth_flows[flowId];
changed = true;
}
}
});
changed && this._saveAuth();
}
async _getAllEntities() {
try {
const doc = await this.adapter.getObjectViewAsync('custom', 'state', {});
const ids = [];
if (doc && doc.rows) {
for (let i = 0, l = doc.rows.length; i < l; i++) {
if (doc.rows[i].value) {
const id = doc.rows[i].id;
if (doc.rows[i].value[this.adapter.namespace]) {
ids.push(id);
}
}
}
}
ids.push(this.adapter.namespace + '.control.alarm');
for (const id of ids) {
const entities = await this._processManualEntity(id);
for (const entity of entities) {
utils.fillEntityIntoCaches(entity);
}
}
} catch (e) {
this.adapter.log.error(`Could not get object view for getAllEntities: ${e.toString()} - ${e.stack}`);
}
}
// ------------------------------- START OF CONVERTERS ---------------------------------------- //
_iobState2EntityState(id, val, type) {
type = type || entityData.iobID2entity[id][0].context.type;
const pos = type.lastIndexOf('.');
if (pos !== -1) {
type = type.substring(pos + 1);
}
if (type === 'light' || type === 'switch' || type=== 'input_boolean') {
return val ? 'on' : 'off';
} else
if (type === 'binary_sensor') {
return val ? 'on' : 'off';
} else
if (type === 'lock') {
return val ? 'unlocked' : 'locked';
} else
if (typeof val === 'boolean') {
return val ? 'on' : 'off';
} else {
return val === null || val === undefined ? 'unknown' : val;
}
}
// Process manually created entity
/**
* Create manual entity from custom-part.
* @param {string} id of ioBroker object
* @param {string} [forcedEntityId] possible forced entity Id on conflict case.
* @returns {Promise<{context: {id: string, type: string}, attributes: {friendly_name: string}, entity_id: string}[]|entity[]|*[]>}
* @private
*/
async _processManualEntity(id, forcedEntityId) {
try {
const obj = await this.adapter.getForeignObjectAsync(id);
if (id === this.adapter.namespace + '.control.alarm') {
obj.common.custom = obj.common.custom || {};
obj.common.custom[this.adapter.namespace] = obj.common.custom[this.adapter.namespace] || {};
obj.common.custom[this.adapter.namespace].name = obj.common.custom[this.adapter.namespace].name || 'defaultAlarm';
obj.common.custom[this.adapter.namespace].entity = 'alarm_control_panel';
obj.common.custom[this.adapter.namespace].states = {
state: id,
arm_state: this.adapter.namespace + '.control.alarm_arm_state'
};
}
const custom = obj.common.custom[this.adapter.namespace] || {};
const entityType = custom.entity || utils.autoDetermineEntityType(obj);
const entity_id = forcedEntityId || utils.createEntityNameFromCuston(obj, this.adapter.namespace);
const entity = utils.processCommon(null, null, null, obj, entityType, entity_id);
if (custom.attr_assumed_state && ['switch', 'light', 'cover', 'climate', 'fan', 'humidifier', 'group', 'water_heater'].includes(entityType)) {
entity.attributes.assumed_state = true;
}
entity.context.STATE = {getId: id, setId: id};
utils.addID2entity(id, entity);
if (custom.states && custom.states.stateRead) {
entity.context.STATE.getId = custom.states.stateRead;
utils.addID2entity(custom.states.stateRead, entity);
}
entity.isManual = true;
if (custom.states) {
if (custom.states.state && custom.states.state !== id) {
this.log.error(`Please define custom settings on main object ${custom.states.state} and not on ${id}. Entity skipped`);
return [];
}
custom.states.state = id;
utils.fillEntityFromStates(custom.states, entity);
}
for (const key of Object.keys(custom)) {
if (key.startsWith('attr_')) {
const attributeName = key.substring('attr_'.length);
entity.attributes[attributeName] = custom[key];
}
}
this.log.debug(`Create manual ${entityType} device: ${entity.entity_id} - ${id}`);
if (entityType === 'light') {
return converterLight.processManualEntity(id, obj, entity, this._objectData.objects, custom);
} else if(entityType === 'input_datetime') {
return converterDatetime.processManualEntity(id, obj, entity, this._objectData.objects, custom);
} else if (entityType === 'binary_sensor') {
return converterBinarySensors.processManualEntity(id, obj, entity, this._objectData.objects, custom);
} else if (entityType === 'sensor') {
return converterSensors.processManualEntity(id, obj, entity, this._objectData.objects, custom);
} else if (entityType === 'climate') {
return converterClimate.processManualEntity(id, obj, entity, this._objectData.objects, custom);
} else if (entityType === 'camera') {
entity.context.STATE = {getValue: 'on'};
entity.context.ATTRIBUTES = [{getId: id, attribute: 'url'}];
entity.attributes.code_format = 'number';
entity.attributes.access_token = crypto
.createHmac('sha256', (Math.random() * 1000000000).toString())
.update(Date.now().toString())
.digest('hex');
entity.attributes.model_name = 'Simulated URL';
entity.attributes.brand = 'ioBroker';
entity.attributes.motion_detection = false;
} else if (entityType === 'alarm_control_panel') {
return converterAlarmCP.processManualEntity(id, obj, entity, this._objectData.objects, custom);
} else if (entityType === 'input_number') {
entity.attributes.min = obj.common.min !== undefined ? obj.common.min : 0;
entity.attributes.max = obj.common.max !== undefined ? obj.common.max : 100;
entity.attributes.step = obj.common.step || 1;
entity.attributes.mode = entity.attributes.mode || obj.common.custom[this.adapter.namespace].mode || 'slider'; //or box, will become input box.
const state = await this.adapter.getForeignStateAsync(id);
entity.attributes.initial = state ? state.val || 0 : 0;
}
else if (entityType === 'input_boolean') {
const state = await this.adapter.getForeignStateAsync(id);
entity.attributes.initial = this._iobState2EntityState(id, state ? state.val : undefined, entityType);
}
else if (entityType === 'input_select') {
return converterInputSelect.processManualEntity(id, obj, entity, this._objectData.objects, custom);
}
else if (entityType === 'switch') {
return converterSwitch.processManualEntity(id, obj, entity, this._objectData.objects, custom);
} else if (entityType === 'timer') {
// - timer => STATE idle/paused/active, attributes: [remaining]
entity.context.STATE = {getId: null, setId: null}; // will be simulated
entity.context.lastValue = null;
entity.attributes.remaining = 0;
entity.context.ATTRIBUTES = [{
attribute: 'remaining',
getId: id,
setId: id,
getParser: function (entity, attr, state) {
state = state || {val: null};
// - timer => STATE idle/paused/active, attributes: [remaining]
// if 0 => timer is off
if (!state.val) {
entity.state = 'idle';
} else if (entity.context.lastValue === null) {
entity.state = 'active';
} else if (entity.context.lastValue === state.val) {
// pause
entity.state = 'paused';
} else {
// active
entity.state = 'active';
}
entity.context.lastValue = state.val;
// seconds to D HH:MM:SS
if (typeof state.val === 'string' && state.val.indexOf(':') !== -1) {
entity.attributes.remaining = state.val;
} else {
state.val = parseInt(state.val, 10);
const hours = Math.floor(state.val / 3600);
const minutes = Math.floor((state.val % 3600) / 60);
const seconds = state.val % 60;
entity.attributes.remaining = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
}
}
}];
}
utils.addID2entity(id, entity);
return [entity];
} catch (e) {
this.adapter.log.error(`Could not process manual entity ${id}: ${e.toString()} - ${e.stack}`);
}
}
async _processSingleCall(ws, data, entity_id) {
const user = await this._getUserId(ws.__auth.username || this.config.defaultUser);
const entity = entityData.entityId2Entity[entity_id];
const id = entity.context.STATE.setId;
if (entity.context.COMMANDS) {
const command = entity.context.COMMANDS.find(c => c.service === data.service);
if (command && command.parseCommand) {
return command.parseCommand(entity, command, data, user)
.then(result => this._sendResponse(ws, data.id, result))
.catch(e => this._sendResponse(ws, data.id, {result: false, error: e.message || e}));
}
}
if (data.service === 'toggle') {
this.log.debug('toggle ' + id);
this.adapter.getForeignState(id, {user}, (err, state) =>
this.adapter.setForeignState(id, state ? !state.val : true, false, {user}, () =>
this._sendResponse(ws, data.id)));
} else
if (data.service === 'volume_set') {
this.log.debug('volume_set ' + id);
this.adapter.setForeignState(id, data.service_data.value, false, {user}, () =>
this._sendResponse(ws, data.id));
} else
if (data.service === 'trigger' || data.service === 'turn_on' || data.service === 'unlock') {
this.log.debug(`${data.service} ${id}`);
this.adapter.setForeignState(id, true, false, {user}, () =>
this._sendResponse(ws, data.id));
} else
if (data.service === 'turn_off' || data.service === 'lock') {
this.log.debug(`${data.service} ${id}`);
this.adapter.setForeignState(id, false, false, {user}, () =>
this._sendResponse(ws, data.id));
} else
if (data.service === 'set_temperature') {
this.log.debug('set_temperature ' + data.service_data.temperature);
if (data.service_data.temperature !== undefined) {
if (entity.context.ATTRIBUTES) {
const attr = entity.context.ATTRIBUTES.find(attr => attr.attribute === 'temperature');
if (attr) {
return this.adapter.setForeignState(attr.setId, data.service_data.temperature, false, {user}, () =>
this._sendResponse(ws, data.id));
}
}
}
this.log.warn(`Cannot find attribute temperature in ${entity_id}`);
this._sendResponse(ws, data.id);
} else
if (data.service === 'set_operation_mode') {
this.log.debug(`set_operation_mode ${data.service_data.operation_mode}`);
this.adapter.setForeignState(id, false, false, {user}, () =>
this._sendResponse(ws, data.id));
} else
if (data.service === 'set_page') {
this.log.debug(`set_page ${JSON.stringify(data.service_data.page)}`);
if (typeof data.service_data.page === 'object') {
this.adapter.setState('control.data', {
val: data.service_data.page.title,
ack: true
}, () => {
/*this.adapter.setState('control.instance', {
val: self._instance,
ack: true
}, () => {*/
this.adapter.setState('control.command', {
val: 'changedView',
ack: true
});
//});
});
}
} else
if (data.service.startsWith('set_') && data.service !== 'set_datetime') {
this.log.debug(data.service + ': ' + id + ' = ' + data.service_data[data.service.substring(4)]);
// set_value => service_data.value
// set_operation_mode => service_data.operation_mode
// set_temperature => service_data.temperature
// set_speed => service_data.speed
this.adapter.setForeignState(id, data.service_data[data.service.substring(4)], false, {user}, () =>
this._sendResponse(ws, data.id));
} else
if (data.service === 'volume_mute') {
this.log.debug(`volume_mute ${id} = ${data.service_data.is_volume_muted}`);
// volume_mute => service_data.is_volume_muted
this.adapter.setForeignState(id, data.service_data.is_volume_muted, false, {user}, () =>
this._sendResponse(ws, data.id));
} else
if (data.service.startsWith('select_')) {
this.log.debug(`${data.service}: ${id} = ${data.service_data[data.service.substring(7)]}`);
// select_option => service_data.option
// select_source => service_data.source
this.adapter.setForeignState(id, data.service_data[data.service.substring(7)], false, {user}, () =>
this._sendResponse(ws, data.id));
} else if (data.service.endsWith('_say')) {
this.adapter.setForeignState(id, data.service_data.message, false, {user}, () => {
this._sendResponse(ws, data.id);
});
} else {
this.log.warn(`Unknown service: ${data.service} (${JSON.stringify(data)})`);
//{'id": 21, "type": "result", "success": false, "error": {"code": "not_found", "message": "Service not found."}}
ws.send(JSON.stringify({id, type: 'result', success: false, error: {code: 'not_found', message: 'Service not found.'}}));
}
}
async _processCall(ws, data) {
if (!data.service) {
this.log.warn('Invalid service call. Make sure service looks like domain.service_name');
return;
}
if (data.service === 'dismiss') {
this.log.debug('dismiss ' + data.service_data.notification_id);
return this._clearNotification(data.service_data.notification_id).then(() =>
this._sendResponse(ws, data.id));
}
if(data.domain === 'system_log' && data.service === 'write') {
this.log.info('Log from UI ' + data.service_data.message);
return this._sendResponse(ws, data.id);
}
let ids = [data.service_data.entity_id];
if (data.service_data.entity_id instanceof Array) {
ids = data.service_data.entity_id;
}
delete data.service_data.entity_id; //make sure we do not use entity_id array in processSingleCall -> use param entity_id there.
for (const id of ids) {
if (!entityData.entityId2Entity[id]) {
this.log.warn(`Unknown entity: ${id} for service call ${JSON.stringify(data)}`);
} else {
await this._processSingleCall(ws, data, id);
}
}
}
async _getAllStates() {
let entity = entityData.entities.find(e => e.state === undefined);
while (entity) {
entity.state = 'unknown';
if (entity.context.STATE && entity.context.STATE.getId) {
try {
const user = await this._getUserId(this.config.defaultUser); //TODO: why is this always defaultUser?
const state = await this.adapter.getForeignStateAsync(entity.context.STATE.getId, {user});
if (state) {
this.onStateChange(entity.context.STATE.getId, state);
} else {
entity.state = 'unknown';
try {
entity.last_changed = new Date().toISOString();
} catch (e) {
this.adapter.log.warn(`Invalid last changed for ${entity.context.STATE.getId}`);
}
entity.last_updated = entity.last_changed;
}
} catch (e) {
this.adapter.log.error(`Could not get state ${entity.context.STATE.getId}: ${e} - ${e.stack}`);
}
} else if (entity.context.type === 'switch') {
entity.state = 'off';
} else if (entity.context.STATE.getValue !== undefined) {
entity.state = entity.context.STATE.getValue;
} else if (entity.context.type === 'climate') {
entity.state = 'on';
}
//handle attributes:
if (entity.context.ATTRIBUTES) {
const ids = entity.context.ATTRIBUTES.map(entry => entry.getId || '');
try {
const states = await this.adapter.getForeignStatesAsync(ids);
if (ids && ids.length) {
entity.attributes = entity.attributes || {};
ids.forEach((id, i) => {
const attribute = entity.context.ATTRIBUTES[i].attribute;
if (attribute === 'remaining' && entity.context.type === 'timer') {
if (!states[id].val) {
entity.state = 'idle';
} else {
entity.state = 'active';
}
entity.context.lastValue = states[id].val;
} else {
this.onStateChange(id, states[id]);
}
});
}
} catch (e) {
this.adapter.log.error(`Could not update state: ${e} - ${e.stack}`);
}
}
entity = entityData.entities.find(e => e.state === undefined);
}
}
async onStateChange(id, state, forceUpdate = false) {
if (state) {
if (id === this.adapter.namespace + '.control.shopping_list') {
return this._sendUpdate('shopping_list_updated');
} else if (id === this.adapter.namespace + '.notifications.list') {
if (!state.ack) {
await this._readNotifications();
}
return this._sendUpdate('persistent_notifications_updated');
} else if (id === this.adapter.namespace + '.notifications.add') {
return !state.ack &&
this.addNotification(state.val).then(() =>
this._sendUpdate('persistent_notifications_updated'));
} else if (id === this.adapter.namespace + '.notifications.clear') {
return !state.ack &&
this._clearNotification(state.val).then(() =>
this._sendUpdate('persistent_notifications_updated'));
} else if (id === this.adapter.namespace + '.control.theme' || id === this.adapter.namespace + '.control.themeDark') {
const dark = id.includes('Dark');
if (this._themes[state.val] || state.val === 'default') {
this[dark ? '_currentThemeDark' : '_currentTheme'] = state.val;
this._sendUpdate('themes_updated');
}
} else if (id === this.adapter.namespace + '.control.darkMode') {
if (this._darkMode !== state.val) {
this._darkMode = !!state.val;
this._sendUpdate('themes_updated');
}
} else if (id === this.adapter.namespace + '.conversation') {
if (state.ack) {
// send answer to conversation dialog
this._wss && this._wss.clients.forEach(client => {
if (client.__conversations && client.readyState === WebSocket.OPEN) {
Object.keys(client.__conversations).forEach(conversation_id => {
client.__conversations[conversation_id].timer && clearTimeout(client.__conversations[conversation_id].timer);
const answer = {
id: client.__conversations[conversation_id].id,
type: 'result',
success: true,
result: {
speech: {
plain: {
speech: state.val,
extra_data: null
}
},
card: {}
}
};
client.send(JSON.stringify(answer));
});
}
});
}
}
}
const changedStates = {};
this._wss && this._wss.clients.forEach(client => {
if (client.__templates && client.readyState === WebSocket.OPEN) {
client.__templates.forEach(t => {
if (t.ids.includes(id)) {
const _state = state || {val: null};
if (changedStates[id] || (this.templateStates[id] && this.templateStates[id].val !== _state.val)) {
this.templateStates[id] = _state;
changedStates[id] = true;
const event = {
id: t.id,
type: 'event',
event: {
result: bindings.formatBinding(t.template, this.templateStates)
}
};
client.send(JSON.stringify(event));
}
}
});
}
});
const entities = entityData.iobID2entity[id];
if (entities) {
entities.forEach(entity => {
let updated = false;
if (state) {
// {id: 2, type: "event", "event": {"event_type": "state_changed", "data": {"entity_id": "sun.sun", "old_state": {"entity_id": "sun.sun", "state": "above_horizon", "attributes": {"next_dawn": "2019-05-17T02:57:08+00:00", "next_dusk": "2019-05-16T19:44:32+00:00", "next_midnight": "2019-05-16T23:21:40+00:00", "next_noon": "2019-05-17T11:21:38+00:00", "next_rising": "2019-05-17T03:36:58+00:00", "next_setting": "2019-05-16T19:04:54+00:00", "elevation": 54.81, "azimuth": 216.35, "friendly_name": "Sun"}, "last_changed": "2019-05-16T09:09:53.424242+00:00", "last_updated": "2019-05-16T12:46:30.001390+00:00", "context": {id: "05356b1a7df54b2f939d3c7f8a3e05b4", "parent_id": null, "user_id": null}}, "new_state": {"entity_id": "sun.sun", "state": "above_horizon", "attributes": {"next_dawn": "2019-05-17T02:57:08+00:00", "next_dusk": "2019-05-16T19:44:32+00:00", "next_midnight": "2019-05-16T23:21:40+00:00", "next_noon": "2019-05-17T11:21:38+00:00", "next_rising": "2019-05-17T03:36:58+00:00", "next_setting": "2019-05-16T19:04:54+00:00", "elevation": 54.71, "azimuth": 216.72, "friendly_name": "Sun"}, "last_changed": "2019-05-16T09:09:53.424242+00:00", "last_updated": "2019-05-16T12:47:30.000414+00:00", "context": {id: "e738dc26af1d48b4964c6d9805179595", "parent_id": null, "user_id": null}}}, "origin": "LOCAL", "time_fired": "2019-05-16T12:47:30.000414+00:00", "context": {id: "e738dc26af1d48b4964c6d9805179595", "parent_id": null, "user_id": null}}}
if (entity.context.STATE.getId === id) {
updated = true;
try {
entity.last_changed = new Date(state.lc).toISOString();
} catch (e) {
this.adapter.log.warn(`Invalid last changed for ${entity.context.STATE.getId}`);
}
try {
entity.last_updated = new Date(state.ts).toISOString();
} catch (e) {
this.adapter.log.warn(`Invalid timestamp for ${entity.context.STATE.getId}`);
}
if (entity.context.STATE.getParser) {
entity.context.STATE.getParser(entity, 'state', state);
} else {
entity.state = this._iobState2EntityState(id, state.val);
}
}
//can have identical id for state and attributes.
if (entity.context.ATTRIBUTES) {
const attributes = entity.context.ATTRIBUTES.filter(e => e.getId === id);
for (const attr of attributes) {
updated = true;
try {
entity.last_changed = new Date(state.lc).toISOString();
} catch (e) {
this.adapter.log.warn(`Invalid last changed for ${attr.getId}`);
}
try {
entity.last_updated = new Date(state.ts).toISOString();
} catch (e) {
this.adapter.log.warn(`Invalid timestamp for ${attr.getId}`);
}
if (attr.getParser) {
attr.getParser(entity, attr, state);
} else {
utils.setJsonAttribute(entity.attributes, attr.attribute, this._iobState2EntityState(null, state.val, attr.attribute), this.log);
}
}
}
}
if (!updated && !forceUpdate) {
return; //nothing happened -> do not notify UI.
}
let time_fired;
try {
time_fired = new Date(state ? state.ts : undefined).toISOString();
} catch (e) {
time_fired = new Date().toISOString();
}
const t = {
type: 'event',
event: {
event_type: 'state_changed',
data: {
entity_id: entity.entity_id,
new_state: entity
},
origin: 'LOCAL',
time_fired
}
};
this._wss && this._wss.clients.forEach(ws => {
if (ws._subscribes && ws._subscribes.state_changed) {
ws._subscribes.state_changed.forEach(id => {
t.id = id;
ws.send(JSON.stringify(t));
});
}
});
});
}
}
// ------------------------------- END OF CONVERTERS ---------------------------------------- //
async _processIobState(ids, objects, id, roomName, funcName, result, forcedEntityId) {
if (!id) {
return;
}
// object might be deleted but still in room/func enums.
if (!objects[id]) {
return;
}
let friendlyName = utils.getSmartName(objects, id);
if (typeof friendlyName === 'object' && friendlyName) {
friendlyName = friendlyName[this.lang] || friendlyName.en;
}
if (!friendlyName && !roomName && !funcName) {
return;
}
try {
// try to detect device
const options = {
objects: objects,
id: id,
_keysOptional: ids,
_usedIdsOptional: this._objectData.usedKeys
};
delete this.detector.cache[id];
const controls = this.detector.detect(options);
if (controls) {
for (const control of controls) {
if (this.converter[control.type]) {
const entities = await this.converter[control.type](id, control, friendlyName, roomName, funcName, objects[id], objects, forcedEntityId);
// converter could return one ore more devices as array
if (entities && entities.length) {
//try to create battery_alarm:
const mainEntity = entities.find(x => x && x.entity_id);
if (mainEntity) {
//make battery have sensible entity id and make sure it is different from "host" device:
entities.push(converterBinarySensors.processBattery.call(this, control, friendlyName, roomName, funcName, objects, 'binary_sensor.' + mainEntity.entity_id.split('.')[1] + '_BatteryWarning'));
}
// iterate through entities
for (const entity of entities) {
if (!entity) continue;
if (!entity.context.iobType) {
entity.context.iobType = control.type; //remember type.
}
const _entity = result.find(e => e.entity_id === entity.entity_id);
if (_entity) {
this.log.debug(`Duplicates found for ${entity.entity_id}`);
continue;
}
result.push(entity);
this.adapter.log.debug(`[Type-Detector] Created auto device: ${entity.entity_id} - ${control.type} - ${id}`);
}
}
} else {
this.adapter.log.debug(`[Type-Detector] device ${control.states.find(e => e.id).id} - ${control.type} - ${id} is not yet supported`);
}
}
} else {
console.log(`[Type-Detector] Nothing found for ${options.id}`);
}
} catch (e) {
this.adapter.log.error(`[Type-Detector] Cannot process "${id}": ${e} stack: ${e.stack}`);
throw e;
}
}
_updateConstantEntities() {
//zone.home:
let entityHome = entityData.entityId2Entity['zone.home'];
if (!entityHome) {
entityHome = {
'entity_id': 'zone.home',
'state': 'zoning',
'attributes': {
'hidden': true,
'radius': 10,
'friendly_name': 'Home',
'icon': 'mdi:home'
},
'context': {
'id': 'system.config', //not sure this makes a lot of sense. But prevents crash in UI.
'STATE': {} //prevent warning on getting history.
}
};
entityData.entities.push(entityHome);
entityData.entityId2Entity[entityHome.entity_id] = entityHome;
}
const now = new Date().toISOString();
entityHome.attributes.latitude = parseFloat(this.systemConfig.latitude);
entityHome.attributes.longitude = parseFloat(this.systemConfig.longitude);
entityHome.last_changed = now;
entityHome.last_updated = now;
}
/**
* Create one entity from type-detector
* @param {string} id of main object (i.e. device)
* @param {string} [forcedEntityId] possible forced entity_id on conflict cases.
* @returns {Promise<*[]>}
* @private
*/
async _createOneDevice(id, forcedEntityId) {
const foundRoom = utils.findEnumForId(Object.values(this._objectData.rooms), id);
const foundFunc = utils.findEnumForId(Object.values(this._objectData.functions), id);
if (foundRoom && foundFunc) {
if (this._objectData.ids.length !== Object.keys(this._objectData.objects).length) {
this._objectData.ids = Object.keys(this._objectData.objects);
this._objectData.ids.sort();
}
let roomName = this._objectData.roomNames[foundRoom._id];
let funcName = this._objectData.funcNames[foundFunc._id];
if (!roomName) {
roomName = utils.getEnumName(foundRoom, this.lang);
this._objectData.roomNames[foundRoom._id] = roomName;
}
if (!funcName) {
funcName = utils.getEnumName(foundFunc, this.lang);
this._objectData.roomNames[foundFunc._id] = funcName;
}
const entities = [];
this.log.debug('Starting processIobState');
await this._processIobState(this._objectData.ids, this._objectData.objects, id, roomName,
funcName, entities, forcedEntityId);
this._objectData.usedKeys = []; //clean this up again.
this.log.debug('Done processIobState');
if (entities.length) {
for (const entity of entities) {
this.log.debug(`Object ${id} changed, updated entity ${entity.entity_id}.`);
//entityData.entities and entityData.entityId2Entity is already updated / overwritten in processCommon!
//update _ID2entity:
entityData.iobID2entity[id] = entityData.iobID2entity[id] || []; //make sure it exists.
}
this.log.debug(`Object ${id} did change, got ${entities.length} updated entities.`);
} else {
this.log.debug(`Object ${id} did change, got no updated entities.`);
}
return entities;
}
return [];
}
async _updateDevices() {
const result = [];
try {
await this._readObjects();
if (this._objectData.ids.length !== Object.keys(this._objectData.objects).length) {
this._objectData.ids = Object.keys(this._objectData.objects);
this._objectData.ids.sort();
}
this._objectData.roomNames = {}; //reset names on full update.
for (const func of Object.values(this._objectData.functions)) {
if (!func.common || !func.common.members || typeof func.common.members !== 'object' || !func.common.members.length) continue;