-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
218 lines (193 loc) · 5.97 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
/*jslint node: true */
'use strict';
var winston = require('winston'),
path = require('path'),
fs = require('fs'),
yaml = require('js-yaml'),
async = require('async'),
mqtt = require('mqtt'),
fs = require('fs'),
FtpServer = require('ftpd').FtpServer;
var CONFIG_DIR = process.env.CONFIG_DIR || process.cwd(),
CONFIG_FILE = path.join(CONFIG_DIR, 'config.yml'),
SAMPLE_FILE = path.join(__dirname, '_config.yml'),
CURRENT_VERSION = require('./package').version;
var config,
server,
broker,
timeouts = {};
// Show Debug logs in console
winston.level = 'debug';
/**
* Load user configuration (or create it)
* @method loadConfiguration
* @return {Object} Configuration
*/
function loadConfiguration () {
if (!fs.existsSync(CONFIG_FILE)) {
fs.writeFileSync(CONFIG_FILE, fs.readFileSync(SAMPLE_FILE));
}
return yaml.safeLoad(fs.readFileSync(CONFIG_FILE));
}
/**
* Get the topic name for a given item
* @method getTopicFor
* @param {String} device Device Name
* @param {String} type Output type
* @return {String} MQTT Topic name
*/
function getTopicFor (device, type) {
return [config.mqtt.preface, device, type].join('/');
}
/**
* Notify the broker that something triggered
* @method notifyMQTT
* @param {String} id Identifier for the camera
* @param {String} value Value to set (ON, OFF)
*/
function notifyMQTT (id, value) {
var motionTopic = getTopicFor(id, 'motion'),
imageTopic = getTopicFor(id, 'image'),
events = [],
state = value ? 'active': 'inactive';
// Motion alert
winston.debug('Notifying MQTT %s with %s', motionTopic, state);
events.push(function (next) {
broker.publish(motionTopic, state, {
retain: true
}, next);
});
// Image alert
winston.debug('Notifying MQTT %s with %s', imageTopic, value ? 'image' : 'empty image');
events.push(function (next) {
broker.publish(imageTopic, value, {
retain: true
}, next);
});
async.parallel(events, function (err) {
if (err) {
winston.error('Error notifying MQTT', err);
}
});
}
/**
* Handle an events from the Camera
* @method cameraEvent
* @param {String} id Camera ID
* @param {String} file Filename
* @param {Stream} contents Contents of uploaded file
* @param {Function} callback Function to call when done
*/
function cameraEvent (id, file, contents, callback) {
winston.info('Motion detected on %s', id);
// Auto-clear motion alert after 10 seconds
clearTimeout(timeouts[id]);
timeouts[id] = setTimeout(notifyMQTT.bind(null, id, ''), 10000);
// Notify MQTT
notifyMQTT(id, contents);
callback();
}
/**
* Return a function that fails on call
* @method noop
* @return {Function} Yield error on function call
*/
function noop () {
return function () {
var callback = arguments[arguments.length - 1];
callback(new Error('Not implemented'));
};
}
/**
* Handle a client connecting to the FTP service
* @method handleClient
* @param {Connection} connection Details about the connection
*/
function handleClient (connection) {
var client = connection.socket.remoteAddress + ':' + connection.socket.remotePort,
identifier = '';
winston.debug('Client %s connected', client);
connection.on('command:user', function (user, success, failure) {
if (!user) {
return failure();
}
identifier = user;
success();
});
connection.on('command:pass', function (pass, success, failure) {
if (!pass) {
return failure();
}
success(identifier, {
writeFile: cameraEvent.bind(null, identifier),
readFile: noop(),
unlink: noop(),
readdir: noop(),
mkdir: noop(),
open: noop(),
close: noop(),
rmdir: noop(),
rename: noop(),
stat: function () {
var callback = arguments[arguments.length - 1];
callback(null, {
mode: '0777',
isDirectory: function () {
return true;
},
size: 1,
mtime: 1
});
}
});
});
connection.on('close', function () {
// @TODO find out where "Client connection closed" is coming from
winston.debug('client %s disconnected', client);
});
connection.on('error', function (error) {
winston.error('client %s had an error: %s', client, error.toString());
});
}
// Main flow
async.series([
function loadFromDisk (next) {
winston.info('Starting MQTT Camera FTPd - v%s', CURRENT_VERSION);
winston.info('Loading configuration');
config = loadConfiguration();
process.nextTick(next);
},
function connectToMQTT (next) {
winston.info('Connecting to MQTT at mqtt://%s', config.mqtt.host);
broker = mqtt.connect('mqtt://' + config.mqtt.host);
broker.on('connect', function () {
next();
// @TODO Not call this twice if we get disconnected
next = function () {};
});
},
function setupServer (next) {
winston.info('Configuring FTPd');
server = new FtpServer('127.0.0.1', {
getInitialCwd: function () {
return '/';
},
getRoot: function () {
return process.cwd();
},
useWriteFile: true,
useReadFile: true
});
server.on('client:connected', handleClient);
process.nextTick(next);
},
function setupApp (next) {
winston.info('Starting FTPd service');
server.listen(config.port, next);
}
], function (error) {
if (error) {
return winston.error(error);
}
winston.info('Listening at ftp://localhost:%s', config.port);
});