UNPKG

alb3rt-sensors

Version:
119 lines (95 loc) 3.39 kB
'use strict'; const core = require('alb3rt-core'), python = require('alb3rt-python'), FILE_ID = '[alb3rt-sensors-motion]'; class Alb3rtSensorsMovement { constructor() { this.pyshell = null; this.subscriptions = {}; this.subscribe = this.subscribe.bind(this); this.unsubscribe = this.unsubscribe.bind(this); this.on = this.on.bind(this); this.off = this.off.bind(this); } subscribe(id, type, callback) { console.log(FILE_ID, 'Subscribing', id, 'to', type); this.subscriptions[type] = this.subscriptions[type] || {}; this.subscriptions[type][id] = callback; } unsubscribe(id, type) { if (this.subscriptions[type] && this.subscriptions[type][id]) { console.log(FILE_ID, 'Unubscribing', id, 'from', type); delete this.subscriptions[type][id]; } } get endpoint() { const types = ['on', 'off', 'error', 'event']; return { get: (query, callback) => { const type = query.type; if (!type || type && types.indexOf(type) === -1) { console.log(FILE_ID, 'Endpoint GET: No correct type provided in query, aborting...'); callback(false); return; } callback(true, { result: true }); if (type === 'on') { this.on(); } if (type === 'off') { this.off(); } if (type === 'error') { this.handlers.error(); } if (type === 'event') { this.handlers.event(); } } }; } get handlers() { const self = this; return { event() { console.log(FILE_ID, 'Received motion-detected event, handling...'); if (self.subscriptions.motion) { const keys = Object.keys(self.subscriptions.motion); keys.forEach(key => { self.subscriptions.motion[key](core.instance.current); }); } }, error() { console.log(FILE_ID, 'Sensor script error, aborting...'); } }; } on() { if (!this.pyshell) { console.log(FILE_ID, 'No sensor running, turning on...'); if (process.env.NODE_ENV === 'production') { python.run('detection', pyshell => { this.pyshell = pyshell; }); } } else { console.log(FILE_ID, 'An attempt to turn on motion sensor, but sensor is already running, aborting...'); } } off() { if (this.pyshell) { console.log(FILE_ID, 'Sensor running, turning off...'); if (process.env.NODE_ENV === 'production') { this.pyshell.childProcess.kill('SIGINT'); this.pyshell = null; python.stop('detection'); } } else { console.log(FILE_ID, 'An attempt to turn off motion sensor, but no sensor running, aborting...'); } } } module.exports = new Alb3rtSensorsMovement();