@smj0x/homebridge-shortcuts-buttons
Version:
Run any Apple Shortcut with just the tap of a button, and execute a custom unix command (or another shortcut!) after completion to handle its success/failure, using x-callback-url.
79 lines • 2.76 kB
JavaScript
import { HSBShortcut } from './shortcut.js';
class HSBServiceState {
isOn = false;
}
class HSBServiceToggleBackOffTimeout {
callback;
delay = 650;
timeout;
constructor(callback) {
this.callback = callback;
}
set() {
this.timeout = setTimeout(this.callback, this.delay);
}
clear() {
clearTimeout(this.timeout);
}
}
export class HSBService {
log;
service;
serviceConfig;
Characteristic;
state;
shortcut;
constructor(log, service, serviceConfig, server, utils, Characteristic) {
this.log = log;
this.service = service;
this.serviceConfig = serviceConfig;
this.Characteristic = Characteristic;
this.state = new HSBServiceState();
this.shortcut = new HSBShortcut(serviceConfig.shortcutName, server, utils);
service
.setCharacteristic(Characteristic.Name, serviceConfig.serviceName)
.setCharacteristic(Characteristic.ConfiguredName, serviceConfig.serviceName)
.getCharacteristic(Characteristic.On)
.onGet(this.getOn.bind(this))
.onSet(this.setOn.bind(this));
}
async getOn() {
const isOn = this.state.isOn;
this.log.debug(`Service(${this.service.displayName})::getOn`, `Value=${isOn}`);
return isOn;
}
async setOn(value) {
this.log.debug(this.logSetHandlerContext, `Value=${value}`);
if (value === false) {
if (this.state.isOn === false) {
this.log.debug(this.logSetHandlerContext, 'State value was already false, skipping handler');
return;
}
this.state.isOn = false;
this.log.debug(this.logSetHandlerContext, 'State value was true, skipping shortcut run');
return;
}
this.toggleBackOffTimeout.clear();
this.state.isOn = true;
try {
await this.shortcut.run();
this.log.success(`${this.logShortcutRunContext} Executed successfully`);
}
catch (e) {
this.log.error(`${this.logShortcutRunContext} Execution failed`, e);
}
this.toggleBackOffTimeout.set();
}
toggleBackOffTimeout = new HSBServiceToggleBackOffTimeout(() => {
this.state.isOn = false;
this.service.updateCharacteristic(this.Characteristic.On, false);
this.log.debug(this.logSetHandlerContext, 'Characteristic value set back to false');
});
get logSetHandlerContext() {
return `Service(${this.service.displayName})::setOn`;
}
get logShortcutRunContext() {
return `${this.logSetHandlerContext} Shortcut(${this.serviceConfig.shortcutName})::run`;
}
}
//# sourceMappingURL=service.js.map