90 lines
2.4 KiB
JavaScript
90 lines
2.4 KiB
JavaScript
// Connect to serial port with 9600 baudrate
|
|
// everything in the browser
|
|
|
|
lightState = {
|
|
ring1: 0,
|
|
ring2: 0,
|
|
ring3: 0,
|
|
ring4: 0,
|
|
ring5: 0
|
|
};
|
|
|
|
let light1Inp = document.getElementById("light1");
|
|
let light2Inp = document.getElementById("light2");
|
|
let light3Inp = document.getElementById("light3");
|
|
let light4Inp = document.getElementById("light4");
|
|
let light5Inp = document.getElementById("light5");
|
|
|
|
light1Inp.addEventListener("change", (event) => {
|
|
lightState.ring1 = event.target.value;
|
|
sendLightData();
|
|
});
|
|
|
|
light2Inp.addEventListener("change", (event) => {
|
|
lightState.ring2 = event.target.value;
|
|
sendLightData();
|
|
});
|
|
|
|
light3Inp.addEventListener("change", (event) => {
|
|
lightState.ring3 = event.target.value;
|
|
sendLightData();
|
|
});
|
|
|
|
light4Inp.addEventListener("change", (event) => {
|
|
lightState.ring4 = event.target.value;
|
|
sendLightData();
|
|
});
|
|
|
|
light5Inp.addEventListener("change", (event) => {
|
|
lightState.ring5 = event.target.value;
|
|
sendLightData();
|
|
});
|
|
|
|
async function connectToLight() {
|
|
// usbVendorId: 0x0403, usbProductId: 0x6015
|
|
const usbVendorId = 0x0403;
|
|
port = await navigator.serial.requestPort({ filters: [{ usbVendorId }] })
|
|
await port.open({ baudRate: 9600 });
|
|
}
|
|
|
|
function setBuzz(value) {
|
|
lightState.buzzer = value;
|
|
sendLightData();
|
|
}
|
|
|
|
async function sendLightData() {
|
|
// WR12345<CR> 1: green, 2: yellow, 3: red, 4: buzzer, 5: empty (alsways 0)
|
|
let data = `WR${lightState.ring1}${lightState.ring2}${lightState.ring3}${lightState.ring4}${lightState.ring5}\r`;
|
|
console.log("Sending data: ", data);
|
|
const encoder = new TextEncoder();
|
|
const writer = port.writable.getWriter();
|
|
await writer.write(encoder.encode(data));
|
|
writer.releaseLock();
|
|
readData();
|
|
}
|
|
|
|
async function readData() {
|
|
console.log("Reading data");
|
|
while (port.readable) {
|
|
const reader = port.readable.getReader();
|
|
try {
|
|
while (true) {
|
|
const { value, done } = await reader.read();
|
|
if (done) {
|
|
// |reader| has been canceled.
|
|
break;
|
|
}
|
|
// Do something with |value|…
|
|
// Convert value to string
|
|
const decoder = new TextDecoder();
|
|
console.log(decoder.decode(value));
|
|
}
|
|
} catch (error) {
|
|
// Handle |error|…
|
|
} finally {
|
|
reader.releaseLock();
|
|
}
|
|
}
|
|
console.log("Done reading");
|
|
}
|
|
|