Skip to content

Commit

Permalink
poll serial port every ten seconds
Browse files Browse the repository at this point in the history
  • Loading branch information
shlokamin committed Oct 30, 2023
1 parent 25a8db0 commit e53c288
Showing 1 changed file with 44 additions and 0 deletions.
44 changes: 44 additions & 0 deletions app-shell/src/usb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import type { PortInfo } from '@opentrons/usb-bridge/node-client'
import type { Action, Dispatch } from './types'

let usbHttpAgent: SerialPortHttpAgent | undefined
let usbFetchInterval: NodeJS.Timeout | undefined
const usbLog = createLogger('usb')

export function getSerialPortHttpAgent(): SerialPortHttpAgent | undefined {
Expand Down Expand Up @@ -110,6 +111,48 @@ async function usbListener(
}
}

function pollSerialPortAndCreateAgent(dispatch: Dispatch): void {
// usb poll already initialized
if (usbFetchInterval != null) {
return
}
usbFetchInterval = setInterval(() => {
// already connected to an Opentrons robot via USB
if (getSerialPortHttpAgent() != null) {
return
}
console.log('fetching serial port list')
fetchSerialPortList()
.then((list: PortInfo[]) => {
const ot3UsbSerialPort = list.find(
port =>
port.productId?.localeCompare(DEFAULT_PRODUCT_ID, 'en-US', {
sensitivity: 'base',
}) === 0 &&
port.vendorId?.localeCompare(DEFAULT_VENDOR_ID, 'en-US', {
sensitivity: 'base',
}) === 0
)

if (ot3UsbSerialPort == null) {
usbLog.debug('no OT-3 serial port found')
return
}

createSerialPortHttpAgent(ot3UsbSerialPort.path)
// remove any existing handler
ipcMain.removeHandler('usb:request')
ipcMain.handle('usb:request', usbListener)

dispatch(usbRequestsStart())
})
.catch(e =>
// eslint-disable-next-line @typescript-eslint/restrict-template-expressions
usbLog.debug(`fetchSerialPortList error ${e?.message ?? 'unknown'}`)
)
}, 10000)
}

function startUsbHttpRequests(dispatch: Dispatch): void {
fetchSerialPortList()
.then((list: PortInfo[]) => {
Expand Down Expand Up @@ -150,6 +193,7 @@ export function registerUsb(dispatch: Dispatch): (action: Action) => unknown {
if (action.payload.usbDevices.find(isUsbDeviceOt3) != null) {
startUsbHttpRequests(dispatch)
}
pollSerialPortAndCreateAgent(dispatch)
break
case USB_DEVICE_ADDED:
console.log('omg usb device ADDED')
Expand Down

0 comments on commit e53c288

Please sign in to comment.