-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmotionHandler.js
123 lines (108 loc) · 2.67 KB
/
motionHandler.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
var cp = require('child_process');
var q = require('q');
var motionHandler = function() {
var processName = 'motion';
var processCmd = 'motion';
var processCmdParams;// = ['/Users/p_kos/Documents/dev/subLocator/app'];
var motionps;
function motionStatus(){
var defered = q.defer();
var cmd = 'ps aux | grep ' + processName;
if (processCmdParams){
cmd += ' ' + processCmdParams;
}
cmd += ' | grep -v grep';
console.log('cmd: '+ cmd);
cp.exec(cmd, function (error, stdout, stderr) {
if (error){
if (String(error.signal) === "null" ){
defered.resolve({on:false});
}
else {
defered.reject(error);
}
}
else if(stderr){
defered.reject(stderr);
}
else{
var pattern = /[0-9]+/;
var out = pattern.exec(stdout);
if (out){
processId = out[0];
defered.resolve({on:true, processId: processId});
}
if (!processId){
defered.resolve({on:false});
}
}
});
return defered.promise;
}
function killMotion(processId){
var defered = q.defer();
var cmd = "kill " + processId;
cp.exec(cmd, function (error, stdout, stderr) {
if (error){
defered.reject(error);
}
else if(stderr){
defered.reject(stderr);
}
else{
defered.resolve({success:true});
}
});
return defered.promise;
}
function turnOnMotion(){
var defered = q.defer();
var cmd = processCmd;
var child;
if (processCmdParams) {
child = cp.spawn(cmd, processCmdParams);
}
else{
child = cp.spawn(cmd);
}
waitForProcess(child, function(pid){
defered.resolve(child.pid);
});
return defered.promise;
}
function waitForProcess(child, callback){
if (child.pid){
return callback(child.pid);
}
setTimeout(waitForProcess(child), 1000);
}
return {
motionStatus: motionStatus ,
startStopMotion:function(on){
var defered = q.defer();
var turnOn = 0;
motionStatus()
.then(function(data) {
if (data.on === true && on === false) {
return killMotion(data.processId);
}
else if (data.on === false && on === true) {
return turnOnMotion();
}
var newDefered = q.defer();
newDefered.resolve('noaction');
return newDefered.promise;
})
.then(function(data){
return motionStatus();
})
.done(function(data){
defered.resolve(data);
});
return defered.promise;
}
}
}
module.exports ={
motionHandler: motionHandler
}