-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
266 lines (235 loc) · 6.35 KB
/
app.js
File metadata and controls
266 lines (235 loc) · 6.35 KB
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
try {
require("dotenv").config();
} catch (e) {
// dotenv is only installed and needed for dev
}
const ttn = require("ttn");
const express = require("express");
const fs = require("fs");
const mls = require("mls");
const PORT = process.env.PORT || 3000;
const STATE_PATH = process.env.STATE_PATH || "locks.json";
const TTN_APP_ID = process.env.TTN_APP_ID;
const TTN_ACCESS_KEY = process.env.TTN_ACCESS_KEY;
const MLS_API_KEY = process.env.MLS_API_KEY;
const UNLOCK_TIMEOUT = 60;
if (
typeof TTN_APP_ID === "undefined" ||
typeof TTN_ACCESS_KEY === "undefined" ||
typeof MLS_API_KEY === "undefined"
) {
console.error(
"please set the env variables TTN_APP_ID, TTN_ACCESS_KEY and MLS_API_KEY"
);
process.exit(1);
}
const toHex = i => (i < 0x10 ? "0" : "") + i.toString(16);
const mozlocation = new mls(MLS_API_KEY);
const app = express();
app.set("view engine", "ejs");
let locks;
let lockQueue = [];
let client;
let log = [];
try {
locks = JSON.parse(fs.readFileSync(STATE_PATH));
} catch (e) {
locks = [];
}
const dumpLocks = () => {
console.log("#", "writing locks state");
try {
fs.writeFileSync(STATE_PATH, JSON.stringify(locks));
} catch (e) {
console.log("!", "couldn't write locks file:", e);
}
};
process.on("exit", dumpLocks);
process.on("SIGINT", process.exit);
(async () => {
// https://www.thethingsnetwork.org/docs/applications/nodejs/api.html#dataclient
// TODO: research: check if connection aborts, reconnect? already supported by the lib?
client = await ttn.data(TTN_APP_ID, TTN_ACCESS_KEY);
console.log("connected to ttn");
client.on("uplink", function(device_id, payload) {
console.log("Received uplink from ", device_id);
console.log(payload);
log.push({
time: new Date(),
device: device_id,
type: "received",
payload: payload
});
let lock = locks.find(l => l.id === device_id);
if (typeof lock === "undefined") {
lock = {
id: device_id,
hardware_serial: payload.hardware_serial,
state: null,
last_seen: null,
location: {}
};
locks.push(lock);
}
// send downlink if we have some in our queue
if (typeof lockQueue[lock.id] !== "undefined" && lockQueue[lock.id].length > 0) {
lockQueue[lock.id] = lockQueue[lock.id].filter((item) => {
if (typeof item === "undefined" || typeof item.port === "undefined" || typeof item.data === "undefined") {
return false;
}
if (+(new Date()) > item.timeout) {
log.push({
time: new Date(),
device: lock.id,
type: "timeout",
created: item.created,
timeout: item.timeout,
payload: item.data,
port: item.port,
confirmed: item.confirmed
});
return false; // remove item
}
client.send(lock.id, item.data, item.port, item.confirmed, "last");
log.push({
time: new Date(),
device: lock.id,
type: "sent",
created: item.created,
payload: item.data,
port: item.port,
confirmed: item.confirmed
});
return false; // remove item
});
}
let port = payload.port;
let data = payload.payload_raw;
if (port == 1 && data[0] == 0x01) {
lock.state = data[1] === 0x01 ? "locked" : "open";
}
if (port == 10 && data[0] == 0x02) {
lock.location = lock.location || {};
lock.location.gps = {};
lock.location.gps.lat =
((data[1] << 16) >>> 0) + ((data[2] << 8) >>> 0) + data[3];
lock.location.gps.lat =
(lock.location.gps.lat / 16777215.0) * 180 - 90;
lock.location.gps.lng =
((data[4] << 16) >>> 0) + ((data[5] << 8) >>> 0) + data[6];
lock.location.gps.lng =
(lock.location.gps.lng / 16777215.0) * 360 - 180;
var altValue = ((data[7] << 8) >>> 0) + data[8];
var sign = data[7] & (1 << 7);
if (sign) {
lock.location.gps.alt = 0xffff0000 | altValue;
} else {
lock.location.gps.alt = altValue;
}
lock.location.gps.hdop = data[9] / 10.0;
lock.location.gps.sat = data[10];
lock.location.gps.valid = (lock.location.gps.lat != -90 && lock.location.gps.lat != -180 && lock.location.gps.alt != 0);
}
if (port == 11 && data[0] == 0x02) {
lock.location = lock.location || {};
lock.location.wifi = [];
for (var i = 1; i <= data.length; i++) {
try {
let bssid =
toHex(data[i]) +
":" +
toHex(data[++i]) +
":" +
toHex(data[++i]) +
":" +
toHex(data[++i]) +
":" +
toHex(data[++i]) +
":" +
toHex(data[++i]);
let rssi = data[++i] * -1;
lock.location.wifi.push({ bssid: bssid, rssi: rssi });
} catch (e) {}
}
// remove old key
if (lock.location.wifi_mls) {
delete lock.location.wifi_mls;
}
if (lock.location.wifi.length > 0) {
let mlsdata = {
wifiAccessPoints: lock.location.wifi.map(wifi => ({
macAddress: wifi.bssid,
signalStrength: wifi.rssi
}))
};
mozlocation.geolocate(mlsdata, function(err, loc) {
lock.location.mls = loc;
});
}
}
lock.last_seen = payload.metadata.time;
});
})();
app.get("/", (req, res) => {
res.render("index", { locks: locks, log: log.slice(-50) });
});
app.get("/dump", (req, res) => {
dumpLocks();
res.redirect("back");
});
app.get("/state", (req, res) => {
res.sendFile(STATE_PATH);
});
app.post("/lock/:id/unlock", (req, res) => {
var lock = locks.find(l => l.id === req.params.id);
if (typeof lock === "undefined") {
res.status(404).send("Sorry, we cannot find that lock!");
return;
}
if (typeof lockQueue[lock.id] === "undefined") {
lockQueue[lock.id] = [];
}
let data = Buffer.from([0x01, 0x01, 0x01]);
let timeout = +(new Date()) + UNLOCK_TIMEOUT * 1000;
lockQueue[lock.id].push({
created: +(new Date()),
timeout: timeout,
data: data,
port: 1,
confirmed: false
})
log.push({
time: new Date(),
device: lock.id,
type: "queued",
timeout: timeout,
payload: data
});
res.redirect("back");
});
setInterval(() => {
for (let lockId in lockQueue) {
if (lockQueue[lockId].length <= 0) {
continue;
}
lockQueue[lockId] = lockQueue[lockId].filter((item) => {
if (+(new Date()) > item.timeout) {
log.push({
time: new Date(),
device: lockId,
type: "timeout",
created: item.created,
timeout: item.timeout,
payload: item.data,
port: item.port,
confirmed: item.confirmed
});
return false; // remove item
}
return true;
});
}
}, 5 * 1000);
const server = app.listen(PORT, () =>
console.log(`lockhandler running on ${JSON.stringify(server.address())}`)
);