-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.js
79 lines (70 loc) · 2.24 KB
/
main.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
// import dependencies
require("dotenv").config();
const fetch = require("node-fetch");
const SerialPort = require("serialport");
const Readline = require("@serialport/parser-readline");
// vars populated by .env file
const portName = process.env.SERIALPORT; // the name of the serial port (same as arduino port)
const baudRate = +process.env.BAUDRATE; // should match the arduino's baudrate
const interval = +process.env.INTERVAL; // time interval for API requests
// an empty array to store pin data
let pins = [];
// container for our interval function
let sendData;
// setup the serial port
const port = new SerialPort(portName, { baudRate: baudRate }, function (err) {
if (err) {
console.log(
"❌ Cannot connect to serial port. Make sure your arduino is plugged in and check `portName`.",
err.message
);
}
});
// setup a parser to read the serial port
const parser = port.pipe(new Readline({ delimiter: "\n" })); // Read the port data
// do stuff once the port is open
port.on("open", () => {
console.log("✅ serial port open");
// parse data
parser.on("data", (data) => {
// remove any trailing whitespace and \n
data = data.trim();
// split at delimiter, convert to number, and assign to pins array
pins = data.split("\t").map(Number);
});
// convert data to API requests at regular intervals
sendData = setInterval(function () {
// create a new array based on parsed data
// *️⃣ add more pins to this array as needed. this should correspond with your arduino code
const allPins = [
{
id: "A0",
value: pins[0],
},
{
id: "A1",
value: pins[1],
},
{
id: "D2",
value: pins[2],
},
];
// step through the array and update each pin online
for (const pin of allPins) {
fetch(`${process.env.API_HOST}/pins/${pin.id}`, {
method: "PUT",
body: JSON.stringify(pin),
headers: { "Content-Type": "application/json" },
})
.then((res) => res.json())
.then((json) => console.log(json))
.catch((err) => console.log(err));
}
}, interval);
});
port.on("close", () => {
console.log("❎ serial port closed");
// stop sending data
clearInterval(sendData);
});