hid_test.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. // IMPORTANT: install the dependency via 'npm i node-hid' in the same location as the script
  2. // If the install fails on windows you may need to run 'npm i -g windows-build-tools' first to be able to compile native code needed for this library
  3. var HID = require('node-hid');
  4. var os = require('os')
  5. // list of supported devices
  6. var boards = require('./boards.js')
  7. var devices = HID.devices();
  8. // this will choose any device found in the boards.js file
  9. var deviceInfo = devices.find(anySupportedBoard);
  10. var reportLen = 64;
  11. var message = "Hello World!"
  12. // Turn our string into an array of integers e.g. 'ascii codes', though charCodeAt spits out UTF-16
  13. // This means if you have characters in your string that are not Latin-1 you will have to add additional logic for character codes above 255
  14. var messageBuffer = Array.from(message, function(c){return c.charCodeAt(0)});
  15. // HIDAPI requires us to prepend a 0 for single hid report as dummy reportID
  16. messageBuffer.unshift(0)
  17. // Some OSes expect that you always send a buffer that equals your report length
  18. // So lets fill up the rest of the buffer with zeros
  19. var paddingBuf = Array(reportLen-messageBuffer.length);
  20. paddingBuf.fill(0)
  21. messageBuffer = messageBuffer.concat(paddingBuf)
  22. // check if we actually found a device and if so send our messageBuffer to it
  23. if( deviceInfo ) {
  24. console.log(deviceInfo)
  25. var device = new HID.HID( deviceInfo.path );
  26. // register an event listener for data coming from the device
  27. device.on("data", function(data) {
  28. // Print what we get from the device
  29. console.log(data.toString('ascii'));
  30. });
  31. // the same for any error that occur
  32. device.on("error", function(err) {console.log(err)});
  33. // send our message to the device every 500ms
  34. setInterval(function () {
  35. device.write(messageBuffer);
  36. },500)
  37. }
  38. function anySupportedBoard(d) {
  39. for (var key in boards) {
  40. if (boards.hasOwnProperty(key)) {
  41. if (isDevice(boards[key],d)) {
  42. console.log("Found " + d.product);
  43. return true;
  44. }
  45. }
  46. }
  47. return false;
  48. }
  49. function isDevice(board,d){
  50. // product id 0xff is matches all
  51. return d.vendorId==board[0] && (d.productId==board[1] || board[1] == 0xFFFF);
  52. }