-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathraspiServer.js
90 lines (78 loc) · 2.65 KB
/
raspiServer.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
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var sys = require('util');
var exec = require('child_process').exec;
var queue = require('express-queue');
var child;
app.use(queue({ activeLimit: 1 }));
app.use(bodyParser.json()); // to support JSON-encoded bodies
var rpi433 = require('rpi-433'),
rfSniffer = rpi433.sniffer({
pin: 2, //Snif on GPIO 2 (or Physical PIN 13)
debounceDelay: 500 //Wait 500ms before reading another code
});
var request = require('request');
// Receive (data is like {code: xxx, pulseLength: xxx})
rfSniffer.on('data', function (data) {
console.log('Code received: '+data.code+' pulse length : '+data.pulseLength);
console.log(data.code);
if (data.code === 119) {
console.log("hola");
request.post({
headers: {'content-type' : 'application/json'},
url: 'http://192.168.0.28:8080/playsound'
}, function(error, response, body){
console.log(body);
});
}
});
app.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', "*");
res.header('Access-Control-Allow-Methods','GET,PUT,POST,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
// JSON API
app.post('/switch',function (req,res){
console.log(req.body);
var systemCode = req.body.systemCode;
var socketNumber = req.body.socketNumber;
var status = req.body.status;
var executedString = systemCode + " " + socketNumber;
executeSudoSend(executedString + " " + status, res);
});
app.post('/switchallon',function (req,res){
console.log(req.body);
var status = 1;
var executedString= "";
req.body.forEach( function (jsonPart){
executedString+=jsonPart.systemCode + " "+ jsonPart.socketNumber + " ";
});
executeSudoSend(executedString + " " + status, res);
});
app.post('/switchalloff',function (req,res){
console.log(req.body);
var status = 0;
var executedString = "";
req.body.forEach( function (jsonPart){
executedString+=jsonPart.systemCode + " "+ jsonPart.socketNumber + " ";
});
executeSudoSend(executedString + " " + status, res);
});
function executeSudoSend(string,res){
child = exec('sudo /home/pi/raspberry-remote/send '+ string, function (error, stdout, stderr) {
sys.print('stdout: ' + stdout);
sys.print('stderr: ' + stderr);
if (error !== null) {
console.log('exec error: ' + error);
res.sendStatus(500);
} else {
res.sendStatus(200);
}
});
};
// Start server
var port= 8081;
app.listen(port);
console.log("Server running at http://localhost:" + port );