hid_test.js 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 isWin = (os.platform() === 'win32');
  8. var devices = HID.devices();
  9. // this will choose any device found in the boards.js file
  10. var deviceInfo = devices.find(anySupportedBoard);
  11. var reportLen = 64;
  12. var message = "Hello World!"
  13. // Turn our string into an array of integers e.g. 'ascii codes', though charCodeAt spits out UTF-16
  14. // 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
  15. var messageBuffer = Array.from(message, function(c){return c.charCodeAt(0)});
  16. // Windows wants you to prepend a 0 to whatever you send
  17. if(isWin){
  18. messageBuffer.unshift(0)
  19. }
  20. // Some OSes expect that you always send a buffer that equals your report length
  21. // So lets fill up the rest of the buffer with zeros
  22. var paddingBuf = Array(reportLen-messageBuffer.length);
  23. paddingBuf.fill(0)
  24. messageBuffer = messageBuffer.concat(paddingBuf)
  25. // check if we actually found a device and if so send our messageBuffer to it
  26. if( deviceInfo ) {
  27. console.log(deviceInfo)
  28. var device = new HID.HID( deviceInfo.path );
  29. // register an event listener for data coming from the device
  30. device.on("data", function(data) {
  31. // Print what we get from the device
  32. console.log(data.toString('ascii'));
  33. });
  34. // the same for any error that occur
  35. device.on("error", function(err) {console.log(err)});
  36. // send our message to the device every 500ms
  37. setInterval(function () {
  38. device.write(messageBuffer);
  39. },500)
  40. }
  41. function anySupportedBoard(d) {
  42. for (var key in boards) {
  43. if (boards.hasOwnProperty(key)) {
  44. if (isDevice(boards[key],d)) {
  45. console.log("Found " + d.product);
  46. return true;
  47. }
  48. }
  49. }
  50. return false;
  51. }
  52. function isDevice(board,d){
  53. return d.vendorId==board[0] && d.productId==board[1];
  54. }