index.ts 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. import SerialPort = require('serialport')
  2. import {SmartKnob} from 'smartknobjs'
  3. import {PB} from 'smartknobjs-proto'
  4. const main = async () => {
  5. const ports = await SerialPort.list()
  6. const matchingPorts = ports.filter((portInfo) => {
  7. // Implement a check for your device's vendor+product+serial
  8. // (this is more robust than the alternative of just hardcoding a "path" like "/dev/ttyUSB0")
  9. return (
  10. portInfo.vendorId?.toLowerCase() === '1a86'.toLowerCase() && portInfo.productId?.toLowerCase() === '7523'.toLowerCase()
  11. // && portInfo.serialNumber === 'DEADBEEF'
  12. )
  13. })
  14. if (matchingPorts.length < 1) {
  15. console.error(`No smartknob usb serial port found! ${JSON.stringify(ports, undefined, 4)}`)
  16. return
  17. } else if (matchingPorts.length > 1) {
  18. console.error(`Multiple smartknob usb serial ports found: ${JSON.stringify(matchingPorts, undefined, 4)}`)
  19. return
  20. }
  21. const portInfo = matchingPorts[0]
  22. let lastLoggedState: PB.ISmartKnobState | undefined
  23. const smartknob = new SmartKnob(portInfo.path, (message: PB.FromSmartKnob) => {
  24. if (message.payload === 'log' && message.log) {
  25. console.log('LOG', message.log.msg)
  26. } else if (message.payload === 'smartknobState' && message.smartknobState) {
  27. if (
  28. message.smartknobState.currentPosition !== lastLoggedState?.currentPosition ||
  29. Math.abs((message.smartknobState.subPositionUnit ?? 0) - (lastLoggedState?.subPositionUnit ?? 0)) > 1
  30. ) {
  31. console.log(
  32. `State:\n${JSON.stringify(
  33. PB.SmartKnobState.toObject(message.smartknobState as PB.SmartKnobState, {defaults: true}),
  34. undefined,
  35. 4,
  36. )}`,
  37. )
  38. lastLoggedState = message.smartknobState
  39. }
  40. }
  41. })
  42. smartknob.sendConfig(
  43. PB.SmartKnobConfig.create({
  44. detentStrengthUnit: 1,
  45. endstopStrengthUnit: 1,
  46. numPositions: 5,
  47. position: 0,
  48. positionWidthRadians: (10 * Math.PI) / 180,
  49. snapPoint: 1.1,
  50. text: 'From TS!',
  51. }),
  52. )
  53. }
  54. main()