-
Notifications
You must be signed in to change notification settings - Fork 30
/
Copy pathapp.js
140 lines (120 loc) · 3.5 KB
/
app.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
require("dotenv").config();
const PythonShell = require("python-shell");
const fs = require("fs");
const express = require("express");
const bodyParser = require("body-parser");
const path = require("path");
const app = express();
// Switch states held in memory
const switches = [];
// Read state from saveState.json, populate switches array
var readableStream = fs.createReadStream("saveState.json");
var data = "";
readableStream.on("data", function(chunk) {
data += chunk;
});
readableStream.on("end", function() {
var parsed = JSON.parse(data);
for (i = 0; i < parsed.switches.length; i++) {
switches.push(new Switch(parsed.switches[i]));
}
});
// Switch Model
// Expects an object:{
// id:"sw" + number,
// state: "on" or "off",
// name: any name you want to display. Defaults to "switch"
// }
function Switch(switchValues) {
this.id = switchValues.id || "sw";
this.state = switchValues.state || "off";
this.name = switchValues.name || "switch";
this.toggle = function() {
if (this.state === "on") {
this.setState("off");
} else {
this.setState("on");
}
};
this.setState = function(state) {
var str = state === "on" ? onString(this.id[2]) : offString(this.id[2]);
PythonShell.run(str, function(err) {
if (!process.env.DEV) {
if (err) throw err;
}
});
this.state = state;
};
// Invokes setState on init to set the switch to its last recalled state.
this.setState(this.state);
}
// needed due to a quirk with PythonShell
function onString(number) {
return "./public/python/sw" + number + "_on.py";
}
function offString(number) {
return "./public/python/sw" + number + "_off.py";
}
// Switch Lookup
function getSwitch(string) {
return switches.filter(function(element) {
return element.id === string;
})[0];
}
// Updates saveState.json
function saveState() {
var formattedState = {
switches: switches
};
fs.writeFile("./saveState.json", JSON.stringify(formattedState), function(
err
) {
if (err) {
console.error(err);
} else {
let date = new Date();
console.log(`
${date.toLocaleDateString()} ${date.toLocaleTimeString()} State has been updated
New state: ${JSON.stringify(formattedState)}
`);
}
});
}
//Server Configuration
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static(__dirname + "/public"));
// If you have a frontend, drop it in the Public folder with an entry point of index.html
app.get("/", function(req, res) {
res.sendFile("index");
});
// Switch Routes for API
app.get("/api/switches", function(req, res) {
res.send(switches);
});
app.get("/api/switches/:id", function(req, res) {
var found = getSwitch(req.params.id);
res.json(found);
});
app.post("/api/switches/:id", function(req, res) {
// For now, uses a simple password query in the url string.
// Example: POST to localhost:8000/API/switches/sw1?password=test
if (req.query.password === process.env.PASS) {
var foundSwitch = getSwitch(req.params.id);
// Optional On / Off command. If not included, defaults to a toggle.
if (!(req.query.command === "on" || req.query.command === "off")) {
foundSwitch.toggle();
} else {
foundSwitch.setState(req.query.command);
}
saveState();
console.log("postSwitch " + JSON.stringify(foundSwitch));
res.json(foundSwitch);
} else {
console.log("invalid password");
res.send("try again");
}
});
const port = process.env.PORT || 8000;
app.listen(port, function() {
console.log("Listening on port " + port);
});