I bought one of the really inexpensive USB relay boards from china with two relays. I am trying to switch the relays on and off from Chrome Javascript using webHID.
Found this sample code https://blink1.thingm.com/ and modified it for this relay hardware.
I made good progess I found the data strings that would turn both relays On and Off
see code below. This code works for the all on and all off cases.
But I am stuck without away to control each Relay separately. I am pretty sure 0xFD and 0xFF are part of the data set needed and assume I need to give the relay number as well. I have tried a lot of different combinations with no luck.
Anyone have an idea?
document.getElementById('start-button').addEventListener('click', handleConnectClick);
async function handleConnectClick() {
let device = await openDevice();
let allOn = [0xFE, 0, 0, 0, 0, 0, 0, 0];
await setRelay(device, allOn);
alert(allOn);
let allOff = [0xFC, 0, 0, 0, 0, 0, 0, 0];
await setRelay(device, allOff);
alert(allOff);
}
async function openDevice() {
const vendorId = 5824; // 16C0
const productId = 1503; // 05DF
const device_list = await navigator.hid.getDevices();
console.log(device_list)
let device = device_list.find(d => d.vendorId === vendorId && d.productId === productId);
if (!device) {
// this returns an array now
let devices = await navigator.hid.requestDevice({
filters: [{vendorId, productId}],
});
console.log("devices:", devices);
device = devices[0];
if (!device)
return null;
}
if (!device.opened) {
await device.open();
}
console.log("device opened:", device);
return device;
}
async function setRelay(device, [a, b, c, d, e, f, g, h]) {
if (!device)
return;
const reportId = 0;
const data = Uint8Array.from([a, b, c, d, e, f, g, h]);
try {
await device.sendFeatureReport(reportId, data);
} catch (error) {
console.error('set_Relay: failed:', error);
}
}
Well I fiugred it out when I found this post Can webusb connect a website to a Kmtronic Usb one relay device in a ChromeOs chromebox?. The USB data doesn't need all eight elements. It only works for single relay when it has 3 elements.
let oneOn = [0xFF, 0x01, 0x01];
let oneOff= [0xFD, 0x01, 0x01];
let twoOn = [0xFF, 0x02, 0x02];
let twoOff= [0xFD, 0x02, 0x02];
Kinda strange the all eight elements version worked for the all Relay USB sentence.