ws2801-alexa
Version:
An alexa connector for the WS2801-Pi module.
98 lines (97 loc) • 3.31 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AlexaDeviceHandler = void 0;
const sinricpro_1 = require("sinricpro");
const config_1 = require("./config/config");
const led_controller_1 = require("./led-controller");
const index_1 = require("./types/index");
// tslint:disable: no-any
class AlexaDeviceHandler {
constructor(config, ledController) {
this.running = false;
this.config = config ? config : config_1.defaultConfig;
this.ledController = new led_controller_1.LedController(ledController, config);
}
start() {
if (this.running) {
return;
}
this.running = true;
this.connect();
}
stop() {
this.running = false;
}
connect(isReconnect) {
const shouldRestoreState = !isReconnect;
this.sinric = new sinricpro_1.SinricPro(this.config.appKey, [this.config.deviceId], this.config.secretKey, shouldRestoreState);
const callbacks = {
setPowerState: this.setPowerState.bind(this),
setBrightness: this.setBrightness.bind(this),
setColor: this.setColor.bind(this),
setColorTemperature: this.setColorTemperature.bind(this),
onDisconnect: this.handleDisconnect.bind(this),
};
sinricpro_1.SinricProActions(this.sinric, callbacks);
}
setPowerState(deviceId, data) {
if (!this.running) {
return false;
}
if (this.config.logCommands) {
console.log(`Command 'setPowerState' received for device '${deviceId}': ${data}`);
}
if (data.toLowerCase() === 'Off'.toLowerCase()) {
this.ledController.off();
}
else if (data.toLowerCase() === 'On'.toLowerCase()) {
this.ledController.on();
}
else {
console.error(`Could not setPowerState. (Data: '${data}')`);
return false;
}
return true;
}
setBrightness(deviceId, data) {
if (!this.running) {
return false;
}
if (this.config.logCommands) {
console.log(`Command 'setBrightness' received for device '${deviceId}': ${data}`);
}
this.ledController.setBrightness(data);
return true;
}
setColor(deviceId, data) {
if (!this.running) {
return false;
}
if (this.config.logCommands) {
console.log(`Command 'setColor' received for device '${deviceId}': ${JSON.stringify(data, null, 2)}`);
}
const color = {
red: data.r,
green: data.g,
blue: data.b,
};
this.ledController.setColor(color);
return true;
}
setColorTemperature(deviceId, data) {
if (!this.running) {
return false;
}
if (this.config.logCommands) {
console.log(`Command 'setColorTemperature' received for device '${deviceId}': ${data}`);
}
const rgbColor = index_1.colorTemperature[data];
this.ledController.setColor(rgbColor);
return true;
}
handleDisconnect() {
console.log('Connection to SinricPro lost. Reconnecting...');
this.connect(true);
}
}
exports.AlexaDeviceHandler = AlexaDeviceHandler;