USB转串口调试硬件设备

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第4天,点击查看活动详情

场景

首先我这里是一台长方形的设备,虽然玩了这么久我不知道这个玩意叫啥,但是没关系它里面是装的android系统,然后这台设备需要链接一个称重的设备进行串口调试,意思很明显,长方形设备需要获取到称重设备的重量信息,从而来进行相应的处理。

我这台设备可以直链接串口也可以转usb链接,其实原本就是直链接串口的线,只是我直插串口链接不到,后来再接了个usb插上去,然后......好了。

所以这里提醒一下广大的朋友,如有类似情况可以转个usb试试。

搜索设备方法,listItems是一个集合,listitem是封装的一个bean类

  /**
     * 搜索设备
     */
    fun searchEquipment() {
        val usbManager = activity.getSystemService(Context.USB_SERVICE) as UsbManager
        val usbDefaultProber: UsbSerialProber = UsbSerialProber.getDefaultProber()
        val usbCustomProber: UsbSerialProber? = CustomProber.getCustomProber()
        for (device in usbManager.deviceList.values) {
            var driver = usbDefaultProber.probeDevice(device)
            if (driver == null) {
                driver = usbCustomProber!!.probeDevice(device)
            }
            if (driver != null) {
                for (port in driver.getPorts().indices) {
                    listItems.add(
                        ListItem(
                            device,
                            port,
                            driver
                        )
                    )
                }
            } else {
                listItems.add(
                    ListItem(
                        device,
                        0,
                        null
                    )
                )
            }
        }
    } 
复制代码

下面直接给我的工具类,依赖usb-serial-forandroid 每次调用工具类之前必须先调用initUSB方法

 /**
 * 操作USB类封装
 */
class OperationUSB : OpernationUSBimpl {
    private var activity: Activity? = null
    private var Datas: ByteArray? = null //接收到数据集
    private var Index = 0 //循环下标
    private var type = 0 //0等于非称重操作 1表示称重操作
    private val ArrayLenth: Int = 100 //默认数组长度

    private var deviceId: Int? = null
    private var portNum: Int? = null
    private var baudRate: Int? = null
    private var usbIoManager: SerialInputOutputManager? = null
    private var usbSerialPort: UsbSerialPort? = null
    private var connected = false

    private var Times: ArrayList<Timebean> = ArrayList<Timebean>()

    private var callback: OperationUSBCallBack? = null

    fun setOperationUSBCallBack(callback: OperationUSBCallBack) {
        this.callback = callback
    }

    companion object {
        val operationusb: OperationUSB? = OperationUSB()
        val 获取重量: String = "*********"
        val 置零: String = "*********"
        var isstable: Boolean = false //抛出外部访问变量是否稳定 默认不稳定
        var nowWeight: Int = 0 //抛出外部访问变量当前重量 默认为0
    }

    override fun send(instruction: String, type: Int) {
        this.type = type
        if (!connected) {
            Toast.makeText(activity, "not connected", Toast.LENGTH_SHORT).show()
            return
        }
        reset()
        USBUtil.send(instruction, usbSerialPort)
    }

    override fun initUSB(activity: Activity, deviceId: Int, portNum: Int, baudRate: Int) {
        this.activity = activity
        this.deviceId = deviceId
        this.portNum = portNum
        this.baudRate = baudRate
    }

    override fun connect() {
        var device: UsbDevice? =  null
        val usbManager = activity!!.getSystemService(Context.USB_SERVICE) as UsbManager
        for (v in usbManager.deviceList.values) {
            if (v.deviceId == deviceId) {
                device = v
            }
        }
        var driver = UsbSerialProber.getDefaultProber().probeDevice(device)
        if (driver == null) {
            driver = CustomProber.getCustomProber()!!.probeDevice(device)
        }
        if (driver.ports.size < this!!.portNum!!) {
            this.callback?.OperationInfo("connection failed: not enough ports at device")
            return
        }
        usbSerialPort = driver.ports[this!!.portNum!!]
        val usbConnection = usbManager.openDevice(driver.device)

        if (usbConnection == null) {
            if (!usbManager.hasPermission(driver.getDevice())) {
                val intent = PendingIntent.getBroadcast(
                    activity,
                    0,
                    Intent(BuildConfig.APPLICATION_ID + ".GRANT_USB"),
                    0
                )
                usbManager.requestPermission(driver.getDevice(), intent)
                this.callback?.OperationInfo("connection failed: permission denied")
            } else {
                this.callback?.OperationInfo("connection failed: open failed")
            }
            return
        }
        try {
            usbSerialPort!!.open(usbConnection)
            usbSerialPort!!.setParameters(
                baudRate!!,
                UsbSerialPort.DATABITS_8,
                UsbSerialPort.STOPBITS_1,
                UsbSerialPort.PARITY_EVEN
            )
            usbIoManager = SerialInputOutputManager(usbSerialPort,
                object : SerialInputOutputManager.Listener {
                    override fun onRunError(e: Exception?) {
                        this@OperationUSB.callback?.OperationInfo("onRunError:"+e!!.message)
                    }

                    override fun onNewData(data: ByteArray?) {
                        activity!!.runOnUiThread(Runnable {
                            run {
                                if (data != null) {
                                    read(data)
                                }
                            }
                        })
                    }

                }
            )
            Executors.newSingleThreadExecutor().submit(usbIoManager)
            this.callback?.OperationInfo("connected")
            connected = true
        } catch (e: Exception) {
            this.callback?.OperationInfo("connection failed: " + e.message)
            disconnect()
        }
    }

    override fun disconnect() {
        connected = false
        if (usbIoManager != null) usbIoManager!!.stop()
        usbIoManager = null
        try {
            usbSerialPort!!.close()
        } catch (ignored: IOException) {
        }
        usbSerialPort = null
    }

    override fun read(data: ByteArray) {
        for (i in data.indices) {
            Datas?.set(Index, data[i])
            Index++
        }
        if (type == 1 && Index == 7) {
            nowWeight = USBUtil.BtArrToInt(Datas!!.get(3), Datas!!.get(4))
            if (nowWeight > 30000) {
                //置零
                send(置零,0)
                this.callback?.OperationInfo("启动置零操作")
                return
            }
            if (Datas!!.get(1).toInt() == 0x03) {
                val temps: MutableList<Byte> =
                    ArrayList()
                for (i in Datas!!.indices) {
                    temps.add(Datas!!.get(i))
                }
                val a: Any = checkState(Timebean(nowWeight, System.currentTimeMillis()), Times)
                if (a is Int && a == -1) {
                    this.callback?.OperationInfo("Times数据集长度异常:" + Times)
                    Times.clear()
                } else if (a is Boolean) {
                    isstable = a
                }
                this.callback?.OperationRead(nowWeight)
            }
        }
    }

    /**
     * 复位
     */
    fun reset() {
        Datas = ByteArray(ArrayLenth)
        Index = 0
    }

}
复制代码

然后发送的模块我用java写的,就一个方法,这里面还有一个计算重量的方法,这是我拿到返回的数据以后进行的计算,具体你怎么计算的问问厂家。

public class USBUtil {

    public static void send(String hexstring, UsbSerialPort usbSerialPort) {
        try {
            byte[] data = new byte[hexstring.length()/2];
            int j=0;
            for(int i=0;i<data.length;i++) {
                byte high = (byte) (Character.digit(hexstring.charAt(j), 16) & 0xff);
                byte low = (byte) (Character.digit(hexstring.charAt(j + 1), 16) & 0xff);
                data[i] = (byte) (high << 4 | low);
                j+=2;
            }
            usbSerialPort.write(data, 2000);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 计算重量结果
     */
    private static int byteArrayToInt(byte[] bytes) {
        ~~~~~
        return value;
    }

    public static int BtArrToInt(byte b1, byte b2) {
        ~~~~~
        return s;
    }

}
复制代码

综上链接的一些方法都在上面,注意链接的时候需要注意 校验位 端口号信息,具体这个数据是多少你也要问问厂商的哦。

如果你还有什么问题需要帮助,可以发邮件给我哦。[email protected]

END

猜你喜欢

转载自juejin.im/post/7106314250171187214
今日推荐