-
Notifications
You must be signed in to change notification settings - Fork 0
/
manager.js
196 lines (170 loc) · 6.36 KB
/
manager.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
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
const fs = require("fs");
const merge = require("deepmerge2");
// const _ = require("underscore");
const flatten = require("flat");
const fastcsv = require('fast-csv');
const settings = require('./settings');
const scanner = require("./ble-discover/scanner");
const trigger = require("./trigger_server");
const sensors = require("./data-acquisition/retrieve_sensors_data");
const buzzer = require("./feedback/buzzer").Buzzer;
const getLampState = require("./influx-db/query_data").getLampState;
const VPfile = "./omnia/virtual-personas.json";
const logNoMatchingFile = "./omnia/logNoMatching.json";
const feedbackBuzzer = new buzzer(4); // feedback buzzer on gpio 4
const automaticNoActionSnapshotInterval = settings.automaticNoActionSnapshotInterval;
const lampInThisRoom = settings.lampInThisRoom;
var oldVPobj = fs.readFileSync(VPfile, "utf-8");
var oldVPjson = JSON.parse(oldVPobj);
var logNoMatchingObj = fs.readFileSync(logNoMatchingFile, "utf-8");
var logNoMatchingJson = JSON.parse(logNoMatchingObj);
var possibleCandidate = "";
var triggerData = "";
var waitForCandidate = "";
var candidate_actionTimeout = settings.candidate_actionTimeout;
var label = "";
var automaticNoActionSnapshotTimeout = "";
var noVPnearBy = false; // set to true after scanner does not detect any VP near by
function updateVPhistory(updateVPjson) {
var newVPjson = merge(oldVPjson, updateVPjson);
writeJsonToFile(newVPjson, VPfile);
oldVPjson = newVPjson;
};
function updateDataset(featJson, triggerDevice) {
var dataset = [];
Object.entries(featJson).forEach(([actionTimestamp, snapshot]) => {
// console.log("Triggered by: " + snapshot["triggeredBy"] + " at timestamp: " + actionTimestamp)
var flatSnapshot = flatten(snapshot);
flatSnapshot["actionTimestamp"] = actionTimestamp;
// dataset should not have values that are not numbers
for (const [key, value] of Object.entries(flatSnapshot)) {
if (typeof(value) !== "number") {
delete flatSnapshot[key];
}
}
// console.log(flatSnapshot);
dataset.push(flatSnapshot);
})
datasetName = triggerDevice + "_dataset.csv";
fastcsv.writeToPath("./omnia/" + datasetName, dataset, {headers: true})
.on('error', (err) => {
console.log("Error while updating dataset", err);
feedbackBuzzer.alarm();
})
}
function setNoVPnearBy() {
noVPnearBy = true;
}
function resetNoVPnearBy() {
noVPnearBy = false;
}
// functions for automatic snapshots when no recent action is detected
async function getAutomaticNoActionSnapshot() {
console.log("\nTaking automatic no action snapshot");
if (noVPnearBy) {
console.log("Setting label to 0 (light should be off)");
var currentLampState = 0;
}
else {
var currentLampState = await getLampState();
if (currentLampState) {
currentLampState = 1;
}
else {
currentLampState = 0;
}
console.log("Setting label to ", currentLampState);
}
sensors.retrieveData("", lampInThisRoom, currentLampState, sensorsNearBy, noVPnearBy, updateDataset); // considering lamp in this room as the trigger device
automaticNoActionSnapshotTimeout = setTimeout(() => {
getAutomaticNoActionSnapshot();
}, automaticNoActionSnapshotInterval);
}
function stopAutomaticNoActionSnapshotTimeout() {
if (automaticNoActionSnapshotTimeout !== "") {
clearTimeout(automaticNoActionSnapshotTimeout);
automaticNoActionSnapshotTimeout = "";
console.log("\nAutomatic no action snapshot timeout stopped");
}
}
function determineWhoTriggered(data) {
feedbackBuzzer.beep();
console.log("\nAction triggered in: " + data["room"] + " from device: " + data["trigger"]);
console.log("New state: ", data["newState"]);
triggerData = data;
waitForCandidate = setTimeout(() => {
triggerData = "";
waitForCandidate = "";
console.log("No candidate found");
logNoMatchingJson["countActionsWithoutCandidate"] += 1;
writeJsonToFile(logNoMatchingJson, logNoMatchingFile);
}, candidate_actionTimeout);
}
function setPossibleCandidate(VPaddress, VPdata, btn0Timestamp) {
console.log("\n[" + VPaddress + "]: possible candidate found");
possibleCandidate = {
"address": VPaddress,
"data": VPdata,
"timestamp": btn0Timestamp
};
if (waitForCandidate !== "") {
candidateFound(possibleCandidate);
}
else {
setTimeout(() => {
if (triggerData !== "") {
candidateFound(possibleCandidate);
}
else {
possibleCandidate = "";
logNoMatchingJson["candidatesWithoutActions"].push([VPaddress, new Date(btn0Timestamp)]);
writeJsonToFile(logNoMatchingJson, logNoMatchingFile);
console.log("Couldn't find any action");
}
}, candidate_actionTimeout)
}
}
function candidateFound() {
clearTimeout(waitForCandidate);
waitForCandidate = "";
let invalid = false;
console.log("Candidate: " + possibleCandidate["address"]);
feedbackBuzzer.doubleBeep();
switch (triggerData["newState"]) {
case "On":
label = 1;
break;
case "Off":
label = 0;
break;
default:
console.log("Invalid label in trigger JSON");
invalid = true;
}
if (! invalid) {
sensors.retrieveData(possibleCandidate, triggerData["trigger"], label, sensorsNearBy, noVPnearBy, updateDataset);
}
else {
console.log("Discarding datapoint");
}
triggerData = "";
possibleCandidate = "";
}
function writeJsonToFile(newJson, file) {
var newObj = JSON.stringify(newJson);
fs.writeFile(file, newObj, (err) => {
if (err) {
console.log("Error while writing file", err);
feedbackBuzzer.alarm()
}
else {
// console.log("\nFile written successfully")
}
})
}
const sensorsNearBy = settings.sensorsNearBy;
feedbackBuzzer.start()
console.log("\nStart listening for triggers")
trigger.listen(determineWhoTriggered, getAutomaticNoActionSnapshot, stopAutomaticNoActionSnapshotTimeout);
console.log("\nStart scanning for VPs")
scanner.scan(updateVPhistory, setPossibleCandidate, setNoVPnearBy, resetNoVPnearBy);