关于串口通信开发的几点注意事项

时间:2024-02-21 20:14:47

1.注意串口设备本身的性能:

发送的消息间隔,发送的时候使用线程休眠即可

2.单工还是双工:

这个问题和使用的IO流相关。若为单工,则虽可以获取到串口对应的输入流和输出流,但不能够同时使用,也就是需要使用同步操作控制流的使用。

这样可保证串口通信工作稳定,不至于出现跑着跑着没有响应消息了。

 public synchronized void serialEvent(SerialPortEvent event) {
        System.out.println("事件通知" + event.getEventType());
        switch (event.getEventType()) {
            case SerialPortEvent.BI:
            case SerialPortEvent.OE:
            case SerialPortEvent.FE:
            case SerialPortEvent.PE:
            case SerialPortEvent.CD:
            case SerialPortEvent.CTS:
            case SerialPortEvent.DSR:
            case SerialPortEvent.RI:
            case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
                break;
            case SerialPortEvent.DATA_AVAILABLE:// 当有可用数据时读取数据,并且给串口返回数据

                byte[] btAryBuffer = new byte[4096];
                try {
                    if (inputStream.available() > 0) {
                        int nLenRead = inputStream.read(btAryBuffer);
                        if (nLenRead > 0) {
                            byte[] btAryReceiveData = new byte[nLenRead];
                            System.arraycopy(btAryBuffer, 0, btAryReceiveData, 0,
                                    nLenRead);
                            runReceiveDataCallback(btAryReceiveData);
                        }
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }
                break;
        }
    }

 

  private synchronized int sendMessage(byte[] btArySenderData) {
        System.out.println("发送的数据" + ConvertUtil.bytesToHexString(btArySenderData));
        try {
            synchronized (outputStream) {        //防止并发
                outputStream.write(btArySenderData);
            }
        } catch (IOException e) {
            onLostConnect();
            System.out.println("输入流崩溃");
            e.printStackTrace();
            return -1;
        } catch (Exception e) {
            return -1;
        }

        sendData(btArySenderData);

        return 0;
    }