-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.js
74 lines (64 loc) · 2.21 KB
/
client.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
const { io } = require("socket.io-client");
const { SerialPort } = require("serialport");
const config = require("./config.js");
const currentCamID = config.client.cameraID;
// ARDUINO STUFF ===========================================================
let ArduinoPort;
let ArduinoFail = true;
async function connectArduino() {
if (ArduinoFail || !ArduinoPort) {
// list and connect automatically to the arduino card
SerialPort.list().then((ports) => {
let done = false;
let count = 0;
let allports = ports.length;
ports.forEach(function (port) {
count = count + 1;
pm = port.manufacturer;
if (typeof pm !== "undefined" && pm.toLowerCase().includes("arduino")) {
path = port.path;
ArduinoPort = new SerialPort({ baudRate: 9600, path });
ArduinoPort.on("open", function () {
ArduinoFail = false;
console.log(`connected! arduino is now connected at port ${path}`);
});
// Open errors will be emitted as an error event
ArduinoPort.on("error", function (err) {
console.log("Error: ", err.message);
ArduinoFail = true;
});
done = true;
}
if (count === allports && done === false) {
console.log(`can't find any arduino`);
ArduinoFail = true;
}
});
});
} else {
// check if the arduino is still connected
ArduinoPort.write("test");
}
}
setInterval(connectArduino, 1000); // check every second if the arduino is connected
// SOCKET STUFF ===========================================================
const socket = io(config.client.serverAdress, { autoConnect: true });
socket.on("connect", () => {
console.log("connected to server");
if (ArduinoPort) ArduinoPort.write("0");
});
socket.on("disconnect", () => {
console.log("disconnected from server");
if (ArduinoPort) ArduinoPort.write("2");
});
socket.on("broadcast", (data) => {
if (data.id == currentCamID) {
if (data.status == "active") {
console.log("camera is active");
if (ArduinoPort) ArduinoPort.write("1");
} else {
console.log("camera is inactive");
if (ArduinoPort) ArduinoPort.write("0");
}
}
});