node-red-contrib-home-assistant-websocket
Version:
Node-RED integration with Home Assistant through websocket and REST API
141 lines (140 loc) • 6.62 kB
JavaScript
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() { return m[k]; } };
}
Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
if (k2 === undefined) k2 = k;
o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
__setModuleDefault(result, mod);
return result;
};
var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) {
if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter");
if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
};
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
var _SensorBase_instances, _SensorBase_getAttributes;
Object.defineProperty(exports, "__esModule", { value: true });
const slugify_1 = __importDefault(require("slugify"));
const InputOutputController_1 = __importDefault(require("../../common/controllers/InputOutputController"));
const InvalidPropertyValueError_1 = __importDefault(require("../../common/errors/InvalidPropertyValueError"));
const NoConnectionError_1 = __importDefault(require("../../common/errors/NoConnectionError"));
const InputService_1 = require("../../common/services/InputService");
const const_1 = require("../../const");
const BaseError_1 = __importDefault(require("../errors/BaseError"));
const HomeAssistantError_1 = __importStar(require("../errors/HomeAssistantError"));
const InputError_1 = __importDefault(require("../errors/InputError"));
class SensorBase extends InputOutputController_1.default {
constructor() {
super(...arguments);
_SensorBase_instances.add(this);
}
async onInput({ parsedMessage, message, send, done }) {
var _a, _b;
if (!((_a = this.integration) === null || _a === void 0 ? void 0 : _a.isConnected)) {
throw new NoConnectionError_1.default();
}
if (!this.integration.isIntegrationLoaded) {
throw new InputError_1.default('home-assistant.error.integration_not_loaded', 'home-assistant.error.error');
}
let state = parsedMessage.state.value;
let stateType = parsedMessage.stateType.value;
if (this.node.config.inputOverride === 'block') {
state = this.node.config.state;
stateType = this.node.config.stateType;
}
else if (parsedMessage.state.source === InputService_1.DataSource.Message &&
stateType !== 'message') {
// Set default for state from input to string
stateType = 'str';
}
state = await this.typedInputService.getValue(state, stateType, {
message,
});
if (state === undefined) {
throw new InvalidPropertyValueError_1.default('home-assistant.error.invalid_state', 'home-assistant.error.error');
}
const attributes = __classPrivateFieldGet(this, _SensorBase_instances, "m", _SensorBase_getAttributes).call(this, parsedMessage);
let attr = {};
try {
attr = await attributes.reduce(async (acc, cur) => {
const attrs = await acc;
// Change string to lower-case and remove unwanted characters
const property = (0, slugify_1.default)(cur.property, {
replacement: '_',
remove: /[^A-Za-z0-9-_~ ]/,
lower: true,
});
attrs[property] = await this.typedInputService.getValue(cur.value, cur.valueType, { message });
return attrs;
}, Promise.resolve({}));
}
catch (e) {
if (e instanceof BaseError_1.default) {
throw e;
}
throw new InputError_1.default(`Attribute: ${e}`);
}
let payload;
try {
payload = await ((_b = this.integration) === null || _b === void 0 ? void 0 : _b.updateStateAndAttributes(state, attr));
this.status.setSuccess(payload === null || payload === void 0 ? void 0 : payload.state);
}
catch (err) {
if ((0, HomeAssistantError_1.isHomeAssistantApiError)(err)) {
throw new HomeAssistantError_1.default(err, 'home-assistant.error.error');
}
throw new Error(`Error updating state and attributes. ${JSON.stringify(err)}`);
}
this.status.setSuccess(state);
await this.setCustomOutputs(this.node.config.outputProperties, message, {
config: this.node.config,
data: payload,
});
send(message);
done();
}
}
_SensorBase_instances = new WeakSet(), _SensorBase_getAttributes = function _SensorBase_getAttributes(parsedMessage) {
let attributes = [];
if (parsedMessage.attributes.source !== 'message' ||
this.node.config.inputOverride === 'block') {
attributes = this.node.config.attributes;
}
else {
if (this.node.config.inputOverride === 'merge') {
const keys = Object.keys(parsedMessage.attributes.value).map((e) => e.toLowerCase());
this.node.config.attributes.forEach((ele) => {
if (!keys.includes(ele.property.toLowerCase())) {
attributes.push(ele);
}
});
}
for (const [prop, val] of Object.entries(parsedMessage.attributes.value)) {
attributes.push({
property: prop,
value: val,
valueType: const_1.TypedInputTypes.String,
});
}
}
return attributes;
};
exports.default = SensorBase;
;