串行数据事件监听器Java

时间:2014-02-08 15:18:08

标签: java event-handling serial-port

如果有人能指出我正确的方向,我将非常感激

如果从下面的串行通信示例中未收到任何数据,我将如何触发调用的事件?

谢谢你, 玛丽亚。

    public void connect(String portName) throws Exception {
     CommPortIdentifier portIdentifier = CommPortIdentifier.getPortIdentifier(portName);
        if (portIdentifier.isCurrentlyOwned()) {
            System.out.println("Error: Port is currently in use");
        } else {
            CommPort commPort = portIdentifier.open(this.getClass().getName(),
                    2000);
            if (commPort instanceof SerialPort) {
                SerialPort serialPort = (SerialPort) commPort;
                serialPort.setSerialPortParams(9600, SerialPort.DATABITS_8,
                        SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

                InputStream in = serialPort.getInputStream();
                OutputStream out = serialPort.getOutputStream();
                theSerialWriter = new SerialWriter(this, out);
                new Thread(theSerialWriter).start();

                serialPort.addEventListener(new SerialReader(this, in));
                serialPort.notifyOnDataAvailable(true);
            } else {
                System.out.println("Error: Only serial ports are handled by this                          example.");
            }
        }
    }
        public void serialEvent(SerialPortEvent arg0) {
            int data;
            // boolean setFlagDoorLock = false ;
            // if(arg0= 1){}
            try {
                int len = 0;
                while ((data = in.read()) > -1) {

                    if (data == '\n') {
                        break;
                    }
                    buffer[len++] = (byte) data;
                    asHexStr = DatatypeConverter.printHexBinary(buffer);
                    if (asHexStr.contains("FB1")) {
                        // Thread.sleep(1000);
                        ActivateSystem = true;
                        if ((asHexStr.contains("FB1") && (ActivateSystem == true))) {
                            ActivateSystem = false;
                            asHexStr = "";
                        } else {
                            System.out.println("Here2");
                        }
                    }
                }
            } catch (IOException e) {
                e.printStackTrace();
                System.exit(-1);
            }
            System.out.println("Received"); 
        }
    }
    public static class SerialWriter implements Runnable {
        OutputStream out;
        SerialPortConnector main = null;

        public SerialWriter(SerialPortConnector twoWaySerialComm,
                OutputStream out) {
            main = twoWaySerialComm;
            this.out = out;
        }    
        public void send(String stringToSend) {
            try {
                int intToSend = Integer.parseInt(stringToSend);
                this.out.write(intToSend);
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        public void run() {
            try {
                int c = 0;
                Thread.sleep(1000);

                if (asHexStr == "") {
                    System.out.println("Here");
                    // ActivateSystem = false;
                }  
            }
            // catch ( IOException e )
            catch (Exception e) {
                e.printStackTrace();
                System.exit(-1);
            }
        }
    }  
    public static void main(String[] args) {
        try {
            (new SerialPortConnector()).connect("COM12");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

1 个答案:

答案 0 :(得分:1)

您已在评论中说明了这一点:

  

我需要能够检测到id已停止并且在a之后   超时(或者在连续几次没有检测到id之后)   发送网址电话(我已经有一个班级来发送电话) - 这应该   只发送一次。而它正在读取id但是另一个url调用   应该再次发送 - 只有一次

如果我理解这一点,那么你需要检查两件不同的事情:

  • 设备在发送ID时停止。
  • 设备会发送一些空ID。

这个要求是一种棘手的问题。正如我所说,如果没有数据到达串口,那么就不会触发串口事件。我认为您可以使用Timer来检查超时并使用计数器来记录到达的空ID的数量。像这样:

int numberOfEmptyIds = 0;
int maxNumberOfAttempts = 5;
boolean urlSent = false;
long timeoutInMillis = 10000; // let's say 10000 millis, equivalent to 10 seconds
Timer timer = null;

public void connect(String portName) throws Exception {
    ...
    scheduleTimer();
}

public void serialEvent(SerialPortEvent evt) {
    if(evt.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        try {
            while(in.read(buffer) > -1) {
                String asHexStr = DatatypeConverter.printHexBinary(buffer);
                if(asHexStr.contains("FB1")) {
                    scheduleTimer();
                    numberOfEmptyIds = 0;

                } else {
                    numberOfEmtyIds++;
                    if(numberOfEmptyIds == maxNumberOfAttempts && !urlSent) {
                        // send the url here
                    }
                }             
            }
        } catch (IOException ex) {
           // Log the exception here
        }
    }
}

private void scheduleTimer() {
    if(timer != null) {
        timer.cancel();
    }
    timer = new Timer("Timeout");
    TimerTask task = new TimerTask() {
        @Override
        public void run() {
            if(!urlSent) {
                // send the url here
            }
        }
    };
    timer.schedule(task, timeoutInMillis);
}

我不知道这是 完全 您需要什么,但希望它有所帮助。