-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtilt.js
89 lines (72 loc) · 2.29 KB
/
tilt.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
"use strict";
const fs = require("fs");
const noble = require("@abandonware/noble");
const Gpio = require("onoff").Gpio;
const { fromEvent } = require("rxjs");
const { filter, map, throttleTime } = require("rxjs/operators");
const rfs = require("rotating-file-stream");
const ble = require("./ble");
const calculator = require("./calculator");
const config = require("./config");
const file = require("./file");
const parser = require("./parser");
const utils = require("./utils");
let runState = null;
const button = new Gpio(config.BUTTON_PIN, "in", "rising", {
debounceTimeout: config.BUTTON_DEBOUNCE_MS,
});
const led = new Gpio(config.LED_PIN, "out");
const setLedState = () => led.writeSync(Number(runState));
const buttonPressed = () => {
runState = !runState;
saveRunState();
setLedState();
};
const loadRunState = () => {
try {
const rawdata = fs.readFileSync("runState.json");
runState = JSON.parse(rawdata).isRunning;
console.log("Run state loaded: ", runState);
} catch (_) {
runState = false;
console.log("Run state was not saved. Set state to: ", runState);
}
};
const saveRunState = () => {
const data = JSON.stringify({
changedAt: utils.timestamp("YYYYMMDD-HHmmss"),
isRunning: runState,
});
fs.writeFileSync("runState.json", data);
console.log("Run state saved: ", runState);
};
(async () => {
console.log("Tilt client started");
loadRunState();
setLedState();
const incomingData = fromEvent(noble, "discover").pipe(
filter((_) => runState),
filter((x) => x.uuid == config.TILT_RED_ADDRESS),
throttleTime(config.THROTTLE_DATA_MS),
map((x) => ble.parse(x)),
map((x) => calculator.calculate(x)),
map((x) => parser.prettify(x)),
map((x) => parser.csvString(x, config.CSV_DELIMITER))
);
incomingData.subscribe((data) => file.writeCsvData(data));
incomingData.subscribe((data) => console.log(data));
// scan for all devices, allow duplicates (as we need to receive new data continously)
// unable to filter by UUID as noble filters by serviceUUID not by BeaconUUID
noble.startScanning([], true);
button.watch(async (err, value) => {
if (err) {
console.log(err);
}
buttonPressed();
});
process.on("SIGINT", () => {
noble.stopScanning();
led.unexport();
button.unexport();
});
})();