-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontrol.js
100 lines (92 loc) · 2.64 KB
/
control.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
(function() {
"use strict";
function toBytesInt32(num) {
let arr = new Uint8Array([
(num & 0xff000000) >> 24,
(num & 0x00ff0000) >> 16,
(num & 0x0000ff00) >> 8,
num & 0x000000ff
]);
return arr;
}
function displayMessage(selector, msg) {
$(selector).html(msg);
$(selector).fadeIn();
setTimeout(function() {
$(selector).fadeOut();
}, 4000);
}
document.addEventListener("DOMContentLoaded", event => {
let connectButton = document.querySelector("#connect");
let statusDisplay = document.querySelector("#status");
let brightnessSlider = document.querySelector("#brightness");
let port;
function connect() {
port
.connect()
.then(
() => {
displayMessage("#status", "Connection successful");
connectButton.innerHTML = "Disconnect";
connectButton.disabled = false;
port.onReceive = data => {
let textDecoder = new TextDecoder();
console.log(textDecoder.decode(data));
};
port.onReceiveError = error => {
console.error(error);
};
},
error => {
displayMessage("#status", error);
connectButton.disabled = false;
}
)
.then(() => {
setTimeout(onUpdate, 1000);
});
}
function onUpdate() {
if (!port) {
return;
}
let value = parseInt(brightnessSlider.value);
console.log("Current brightness value", value);
port.send(toBytesInt32(value));
}
brightnessSlider.addEventListener("input", onUpdate);
connectButton.addEventListener("click", function() {
if (port) {
connectButton.disabled = true;
port.disconnect().then(() => {
connectButton.innerHTML = "Connect";
connectButton.disabled = false;
displayMessage("#status", "Connection closed");
port = null;
});
} else {
serial
.requestPort()
.then(selectedPort => {
port = selectedPort;
displayMessage("#status", "Connecting...");
connectButton.disabled = true;
setTimeout(connect, 2000);
})
.catch(error => {
displayMessage("#status", error);
});
}
});
serial.getPorts().then(ports => {
if (ports.length == 0) {
displayMessage("#status", "No device found.");
} else {
port = ports[0];
displayMessage("#status", "Connecting...");
connectButton.disabled = true;
setTimeout(connect, 2000);
}
});
});
})();