index.ts 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import SerialPort = require('serialport')
  2. import {SmartKnob} from 'smartknobjs'
  3. import {PB} from 'smartknobjs-proto'
  4. import {Server, Socket} from 'socket.io'
  5. const io = new Server(parseInt(process.env.PORT ?? '3001'))
  6. const start = async () => {
  7. const ports = await SerialPort.list()
  8. const matchingPorts = ports.filter((portInfo) => {
  9. // Implement a check for your device's vendor+product+serial
  10. // (this is more robust than the alternative of just hardcoding a "path" like "/dev/ttyUSB0")
  11. return (
  12. (portInfo.vendorId?.toLowerCase() === '1a86'.toLowerCase() &&
  13. portInfo.productId?.toLowerCase() === '7523'.toLowerCase()) ||
  14. (portInfo.vendorId?.toLowerCase() === '303a'.toLowerCase() &&
  15. portInfo.productId?.toLowerCase() === '1001'.toLowerCase())
  16. // && portInfo.serialNumber === 'DEADBEEF'
  17. )
  18. })
  19. if (matchingPorts.length < 1) {
  20. console.error(`No smartknob usb serial port found! ${JSON.stringify(ports, undefined, 4)}`)
  21. return
  22. } else if (matchingPorts.length > 1) {
  23. console.error(`Multiple smartknob usb serial ports found: ${JSON.stringify(matchingPorts, undefined, 4)}`)
  24. return
  25. }
  26. const portInfo = matchingPorts[0]
  27. console.info('Connecting to ', portInfo)
  28. let lastLoggedState: PB.ISmartKnobState | undefined
  29. const smartknob = new SmartKnob(portInfo.path, (message: PB.FromSmartKnob) => {
  30. if (message.payload === 'log' && message.log) {
  31. console.log('LOG', message.log.msg)
  32. } else if (message.payload === 'smartknobState' && message.smartknobState) {
  33. const state = PB.SmartKnobState.toObject(message.smartknobState as PB.SmartKnobState, {defaults: true})
  34. io.emit('state', {pb: message.smartknobState})
  35. if (
  36. message.smartknobState.currentPosition !== lastLoggedState?.currentPosition ||
  37. Math.abs((message.smartknobState.subPositionUnit ?? 0) - (lastLoggedState?.subPositionUnit ?? 0)) > 1
  38. ) {
  39. console.log(`State:\n${JSON.stringify(state, undefined, 4)}`)
  40. lastLoggedState = message.smartknobState
  41. }
  42. }
  43. })
  44. smartknob.sendConfig(
  45. PB.SmartKnobConfig.create({
  46. detentStrengthUnit: 1,
  47. endstopStrengthUnit: 1,
  48. position: 0,
  49. minPosition: -5,
  50. maxPosition: 5,
  51. positionWidthRadians: (10 * Math.PI) / 180,
  52. snapPoint: 1.1,
  53. text: 'From TS!',
  54. }),
  55. )
  56. let currentSocket: Socket | null = null
  57. io.on('connection', (socket) => {
  58. if (currentSocket !== null) {
  59. currentSocket.disconnect(true)
  60. }
  61. currentSocket = socket
  62. socket.on('set_config', (config) => {
  63. console.log(config)
  64. smartknob.sendConfig(config)
  65. })
  66. })
  67. }
  68. start()