-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
272 lines (232 loc) · 9.25 KB
/
index.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
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
"use strict";
var mqtt = require('mqtt');
var spawn = require('child_process').spawn;
var fs = require('fs');
var PRIVATE = require('./PRIVATE/common.json');
var id = require('./PRIVATE/id.json').id;
// === to set ===
var MEASURE_PERIOD = 5000; // in seconds
var SSH_TIMEOUT = 20 * 1000;
// ===
var sshProcess;
var sensorPusher;
var client;
var dataBunch = [];
var inited = false;
var events = require('events');
var seismic_sensor = new events.EventEmitter();
// Debug logger
var DEBUG = process.env.DEBUG || false;
var debug = function() {
if (DEBUG) {
[].unshift.call(arguments, '[DEBUG pheromon-client] ');
console.log.apply(console, arguments);
}
};
// call to sensor pusher
seismic_sensor.on('alarm', function(message){
console.log("sending ", message)
var payload = JSON.stringify([{
value: message,
date: new Date().toISOString()
}]);
send('measurement/'+id+'/sismic', payload, {qos: 1});
});
function startMeasurements(bunching_period) {
sensorPusher = spawn("/home/pi/sensor-pusher/main", ['LIS', '1000', '800', '10000', '0']);
sensorPusher.stdout.on('data', function(buffer){
var parts = buffer.toString().split(" ");
var data = {x: parseFloat(parts[0]),
y: parseFloat(parts[1]),
z: parseFloat(parts[2]),
dt: new Date().toISOString()
};
// dataBunch.push(data);
seismic_sensor.emit("alarm", data);
});
sensorPusher.on('close', function(code) {
console.log("sensor-pusher ended unexpectedily.");
sensorPusher = undefined;
});
}
// MQTT BLOCK
/*
** Subscribed on :
** all
** id
**
** Publish on :
** init/id
** status/id/client
** measurement/id/sismic
** cmdResult/id
*/
function mqttConnect() {
client = mqtt.connect('mqtt://' + PRIVATE.host + ':' + PRIVATE.port,
{
username: "pheroman",
password: PRIVATE.mqttToken,
clientId: id,
keepalive: 10,
clean: false,
reconnectPeriod: 1000 * 60 * 1
}
);
client.on('connect', function(){
console.log('connected to the server. ID :', id);
client.subscribe('all', {qos: 1});
client.subscribe(id + '/#', {qos: 1});
if (!inited) {
send('init/' + id, '');
inited = true;
}
});
client.on('offline', function(topic, message) {
console.log("offline")
})
client.on('message', function(topic, buffer) {
var destination = topic.split('/')[1]; // subtopics[0] is id or all => irrelevant
var message = buffer.toString();
console.log("data received :", message, 'destination', destination);
commandHandler(message, send, 'cmdResult/'+id);
});
}
function send(topic, message, options) {
if (client)
client.publish(topic, message, options);
else {
debug("mqtt client not ready");
setTimeout(function() {
send(topic, message, options);
}, 10000);
}
}
function openTunnel(queenPort, antPort, target) {
return new Promise(function(resolve, reject){
var myProcess = spawn("ssh", ["-v", "-N", "-o", "StrictHostKeyChecking=no", "-R", queenPort + ":localhost:" + antPort, target]);
debug("nodeprocess :", myProcess.pid, "myProcess: ", process.pid);
myProcess.stderr.on("data", function(chunkBuffer){
var message = chunkBuffer.toString();
debug("ssh stderr => " + message);
if (message.indexOf("remote forward success") !== -1){
resolve(myProcess);
} else if (message.indexOf("Warning: remote port forwarding failed for listen port") !== -1){
reject({process: myProcess, msg:"Port already in use."});
}
});
// if no error after SSH_TIMEOUT
setTimeout(function(){reject({process: myProcess, msg:"SSH timeout"}); }, SSH_TIMEOUT);
});
}
// COMMAND BLOCK
function commandHandler(fullCommand, sendFunction, topic) { // If a status is sent, his pattern is [command]:[status]
var commandArgs = fullCommand.split(' ');
var command = (commandArgs.length >= 1) ? commandArgs[0] : undefined;
debug('command received : ' + command);
debug("args :", commandArgs);
switch(commandArgs.length) {
case 1:
// command with no parameter
switch(command) {
case 'status': // Send statuses
// send('status/'+id+'/wifi', wifi.state);
sendFunction(topic, JSON.stringify({command: command, result: 'OK'}));
break;
case 'reboot': // Reboot the system
sendFunction(topic, JSON.stringify({command: command, result: 'OK'}));
setTimeout(function () {
spawn('reboot');
}, 1000);
break;
case 'resumerecord': // Start recording
if (sensorPusher)
startMeasurements(MEASURE_PERIOD);
sendFunction(topic, JSON.stringify({command: command, result: 'OK'}));
break;
case 'pauserecord': // Pause recording
if (sensorPusher)
sensorPusher.kill('SIGINT');
sendFunction(topic, JSON.stringify({command: command, result: 'OK'}));
break;
case 'closetunnel': // Close the SSH tunnel
if (sshProcess)
sshProcess.kill('SIGINT');
setTimeout(function () {
if (sshProcess)
sshProcess.kill();
}, 2000);
send('cmdResult/'+id, JSON.stringify({command: 'closetunnel', result: 'OK'}));
send('status/'+id+'/client', 'connected');
break;
}
break;
case 2:
// command with one parameters
switch(command) {
case 'changeperiod':
if (commandArgs[1].toString().match(/^\d{1,5}$/)) {
MEASURE_PERIOD = parseInt(commandArgs[1], 10);
// TODO: restart measures
sendFunction(topic, JSON.stringify({command: command, result: commandArgs[1]}));
} else {
console.log('Period is not an integer ', commandArgs[1]);
sendFunction(topic, JSON.stringify({command: command, result: 'KO'}));
}
break;
case 'date': // Change the sensor's date
var date = commandArgs[1].replace('t', ' ').split('.')[0];
changeDate()
.then(function () {
sendFunction(topic, JSON.stringify({command: command, result: date}));
})
.catch(function (err) {
sendFunction(topic, JSON.stringify({command: command, result: err}));
console.log('Error in changeDate :', err);
});
break;
}
break;
case 3:
switch(command){
case 'init': // Initialize period, start and stop time
if (commandArgs[1].match(/^\d{1,5}$/)) {
var date = commandArgs[2].replace('t', ' ').split('.')[0];
try {
spawn('timedatectl', ['set-time', date]);
} catch (err) {
console.log("Cannot change time :", err)
}
MEASURE_PERIOD = parseInt(commandArgs[1], 10);
startMeasurements(MEASURE_PERIOD);
sendFunction(topic, JSON.stringify({command: command, result: 'OK'}));
}
else {
sendFunction(topic, JSON.stringify({command: command, result: 'Error in arguments'}));
console.log('error in arguments of init');
}
break;
}
break;
case 4:
// command with three parameters
switch(command) {
case 'opentunnel': // Open a reverse SSH tunnel
openTunnel(commandArgs[1], commandArgs[2], commandArgs[3])
.then(function(process){
sshProcess = process;
send('cmdResult/'+id, JSON.stringify({command: 'opentunnel', result: 'OK'}));
send('status/'+id+'/client', 'tunnelling');
})
.catch(function(err){
console.log(err.msg);
console.log("Could not make the tunnel. Cleanning...");
send('cmdResult/'+id, JSON.stringify({command: 'opentunnel', result: 'Error : '+err.msg}));
});
break;
}
default:
console.log('Unrecognized command.', commandArgs);
break;
}
}
mqttConnect();