package com.waytous.anticollision.serial

import android.hardware.usb.UsbManager
import com.hoho.android.usbserial.driver.UsbSerialDriver
import com.hoho.android.usbserial.driver.UsbSerialProber

const val BAUD_RATE = 19200

fun UsbManager.refresh():List<SerialDeviceInfo>{
    val usbDefaultProbe = UsbSerialProber.getDefaultProber()
    val usbCustomProbe: UsbSerialProber = CustomProbe.getCustomProbe()
    val deviceInfos = mutableListOf<SerialDeviceInfo>()
    for (device in deviceList.values) {
        var driver: UsbSerialDriver? = usbDefaultProbe.probeDevice(device)
        if (driver == null) {
            driver = usbCustomProbe.probeDevice(device)
        }
        if (driver != null) {
            driver.ports.forEach { serialPort->
                deviceInfos.add(SerialDeviceInfo(device.deviceId,serialPort.portNumber,BAUD_RATE,device,driver))
            }
        } else {
            deviceInfos.add(SerialDeviceInfo(device.deviceId,0,BAUD_RATE,device,null))
        }
    }
    return deviceInfos
}