alb3rt-sensors
Version:
128 lines (104 loc) • 3.91 kB
JavaScript
;
const fs = require('fs-extra'),
moment = require('moment'),
core = require('alb3rt-core'),
http = core.http,
python = require('alb3rt-python'),
CONFIG = core.config,
FILE_ID = '[alb3rt-sensors-camera]';
class Alb3rtSensorsCamera {
constructor() {
this.pyshell = null;
this.on = this.on.bind(this);
this.off = this.off.bind(this);
}
get endpoint() {
const types = ['on', 'off', 'error'];
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(query.filename);
}
if (type === 'error') {
this.error();
}
}
};
}
error() {
console.log(FILE_ID, 'Sensor script error, aborting...');
}
on() {
if (!this.pyshell) {
console.log(FILE_ID, 'No camera running, turning on...');
fs.ensureDir('./videos/temp')
.catch((videosFolderError) => {
console.log(FILE_ID, 'Error while creating directory ./videos/temp', videosFolderError);
});
if (process.env.NODE_ENV === 'production') {
python.run('camera', pyshell => {
this.pyshell = pyshell;
});
}
} else {
console.log(FILE_ID, 'An attempt to turn on camera, but it is already running, aborting...');
}
}
off(filename) {
if (this.pyshell) {
console.log(FILE_ID, 'Camera running, turning off...');
if (process.env.NODE_ENV === 'production') {
this.pyshell.childProcess.kill('SIGINT');
this.pyshell = null;
python.stop('camera');
}
} else {
console.log(FILE_ID, 'An attempt to turn off camera, but no camera running, aborting...');
}
if (filename) {
fs.pathExists('./videos/' + filename + '.mp4', (videoFileError, exists) => {
if (!videoFileError && exists) {
console.log(FILE_ID, 'Notifying master about', filename);
const body = {
created: (new Date()).getTime(),
filepath: '/videos/',
extension: '.mp4',
type: 'movie',
httpPort: CONFIG.HTTP_PORT,
httpsPort: CONFIG.HTTPS_PORT,
ip: process.env.IP_ADDRESS
};
fs.pathExists('./videos/' + filename + '.jpg', (thumbnailFileError, thumbnailExists) => {
if (!thumbnailFileError && thumbnailExists) {
body.thumbnail = filename + '.jpg';
}
this.notify(filename, body);
});
}
});
}
}
notify(filename, body) {
http.put({
url: CONFIG.MASTER_SERVER_ADDRESS + '/api/downloads/' + filename,
body
}, (downloadRequestError, res) => {
if (downloadRequestError || res.statusCode !== 200) {
console.log(FILE_ID, 'Error when notifying master about video', filename + ':', res.statusCode);
}
});
}
}
module.exports = new Alb3rtSensorsCamera();