美文网首页
jSerialComm 使用

jSerialComm 使用

作者: 九霄龙呤 | 来源:发表于2019-09-29 16:09 被阅读0次

    @Async("asyncServiceExecutor")

    public void executeAsync(SerialPort globalSerialPort,byte[] msg) {

       //logger.info("开始异步发送数据");

       if(globalSerialPort == null || !globalSerialPort.isOpen()) {

           logger.info("串口异步发送数据失败");

            return;

        }

        try{

           globalSerialPort.writeBytes(msg,msg.length);//发送数据

        }catch(Exception e){

           logger.debug(e.toString());

        }

       logger.info("串口异步发送数据结束");

    }

    public static SerialPort LiqSerialPort = null;

    //串口初始化

    public void openAndListenerLiqCOM(StringLiquidCoolCOM) {

       if(LiqSerialPort != null && LiqSerialPort.isOpen()) {

           logger.info("串口{}[isOpen:{}]已开启",LiquidCoolCOM,LiqSerialPort.isOpen());

            return;

        }

       if(LiqSerialPort == null) {

           LiqSerialPort = SerialPort.getCommPort(LiquidCoolCOM);

           LiqSerialPort.setComPortTimeouts(SerialPort.TIMEOUT_READ_SEMI_BLOCKING,0, 0);

           LiqSerialPort.setBaudRate(9600);

           LiqSerialPort.setNumDataBits(8);

           LiqSerialPort.setNumStopBits(1);

           LiqSerialPort.openPort();

           logger.info("串口{}[isOpen:{}]",LiquidCoolCOM,LiqSerialPort.isOpen());

        }

       if(!LiqSerialPort.isOpen()) {

            return;

        }

       logger.info("串口{}监听开始",LiquidCoolCOM);

       LiqSerialPort.addDataListener(new SerialPortDataListener() {

           @Override

            publicint getListeningEvents() {

               return SerialPort.LISTENING_EVENT_DATA_AVAILABLE;

            }

           @Override

            publicvoid serialEvent(SerialPortEvent serialPortEvent) {

                if(serialPortEvent.getEventType() != SerialPort.LISTENING_EVENT_DATA_AVAILABLE){

                   //System.out.println(" event_type="+serialPortEvent.getEventType());

                   logger.info("事件类型:"+serialPortEvent.getEventType());

                    return;

                }

                try{

                   int len = serialPortEvent.getSerialPort().bytesAvailable();

                   byte bytes[] = new byte[len];

                   serialPortEvent.getSerialPort().readBytes(bytes, len);

                    logger.info("串口接收数据回报[{}]={}",len,bytes);

                } catch (Exception exp) {

                   logger.debug("串口异常:"+exp.toString());

                }

            }

        });

    }

    //串口关闭

    public void closeLiqSerialPort() {

       if(LiqSerialPort != null && LiqSerialPort.isOpen()) {

           LiqSerialPort.removeDataListener();

           LiqSerialPort.closePort();

           LiqSerialPort = null;

           logger.info("串口关闭");

        }

    }

    相关文章

      网友评论

          本文标题:jSerialComm 使用

          本文链接:https://www.haomeiwen.com/subject/yjnvyctx.html