-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
96 lines (74 loc) · 2.53 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
const fs = require("fs");
const rf = require("rpi-433-v3")
const express = require("express");
const app = express();
const handlebars = require("handlebars");
const _ = require("lodash");
const config = require("./config.json");
const template = fs.readFileSync('index.twig', 'utf8');
const indexTpl = handlebars.compile(template);
const port = config.port;
const IP = _.chain(Object.values(require("os").networkInterfaces()))
.flatten()
.filter(({family, internal}) => family === "IPv4" && !internal)
.map(({address}) => address)
.head()
.value();
app.get("/", (req, res) => {
console.log("sending /");
res.send(indexTpl({commands: config.commands}));
})
app.get("/execute/:action", (req, res) => {
if (!_.keys(config.commands).includes(req.params.action)) {
console.log("rf command not set, returning");
res.send("<h1>invalid command.</h1><a href=\"/\">back</a>");
return;
}
console.log("sending rf command " + req.params.action);
const rfEmitter = rf.emitter({
pin: config.pins.send,
pulseLength: config.commands[req.params.action].pulse,
protocol: 1
});
rfEmitter.sendCode(config.commands[req.params.action].code, (error, stdout) => {
console.log(error, stdout);
});
console.log("ok, redirecting to home");
res.redirect("/");
});
app.get("/api/v1/", (req, res) => {
console.log("sending /api/v1");
res.send({
status: "ok",
statusCode: 200,
data: _.mapValues(config.commands, item => item.label)
});
});
app.post("/api/v1/:action", (req, res) => {
if (!_.keys(config.commands).includes(req.params.action)) {
console.log("api rf command not set, returning");
res.send({
status: "error",
statusCode: 404
});
return;
}
console.log("sending rf command " + req.params.action);
const rfEmitter = rf.emitter({
pin: config.pins.send,
pulseLength: config.commands[req.params.action].pulse,
protocol: 1
});
rfEmitter.sendCode(config.commands[req.params.action].code, (error, stdout) => {
console.log(error, stdout);
});
console.log("sending /api/v1/" + req.params.action);
res.send({
status: "ok",
statusCode: 200,
data: req.params.action
});
})
app.listen(port, () => {
console.log(`WebRF listening at http://${IP}:${port}`);
})