Skip to content

Instantly share code, notes, and snippets.

@danawoodman
Last active July 19, 2018 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danawoodman/cdc24755f574ea63a8a8473d1d5b10b6 to your computer and use it in GitHub Desktop.
Save danawoodman/cdc24755f574ea63a8a8473d1d5b10b6 to your computer and use it in GitHub Desktop.
Turn on a generic USB relay using node-hid, naive approach
/**
* Control a USB relay board using USB.
*
* This code helped a lot in the understanding of what they boards
* expect for hex inputs:
* https://github.com/jaketeater/Very-Simple-USB-Relay/blob/master/relay.py
*/
const HID = require('node-hid')
const ON = 0xfe
const OFF = 0xfc
const VENDOR_ID = 5824
const PRODUCT_ID = 1503
// convert integer to binary representation
const itob = num => Number(parseInt(num, 10).toString(2))
class Relay {
constructor() {
this.device = new HID.HID(VENDOR_ID, PRODUCT_ID)
if (!this.device) throw new Error('No device found!')
console.log('CURRENT STATE:', this.getStatus())
}
/**
*
*/
getStatus() {
const state = this.device.getFeatureReport(1, 8)[7]
return itob(state)
}
on(delay) {
this.device.sendFeatureReport([ON, ON])
if (delay) setTimeout(() => this.off(), delay)
}
off() {
this.device.sendFeatureReport([OFF, OFF])
}
}
const relay = new Relay()
// Make sure the relay defaults to off
relay.off()
const delay = 1000
relay.on(delay)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment