串行数据事件侦听器Java [英] Serial Data Event Listener Java

查看:195
本文介绍了串行数据事件侦听器Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I would be really grateful if someone could point me in the right direction

如果没有收到数据,我将如何触发被调用的事件串行通讯示例如下?

How would i go about triggering an event that is called when no data is received from the serial communication example below?

谢谢,
玛丽亚。

Thank you, Maria.

    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();
        }
    }
}


推荐答案

您已在注释中说明了这一点:

You have stated this in a comment:


我需要检测到ID已经停止, b $ b超时(或者没有连续检测到id几次)然后
发送一个url调用(我已经有一个类发送呼叫) - 这应该
只发送一次而它正在读取ID,但是另一个url调用
应该再次发送一次只有

I need to be able to detect that the id has stopped and after a timeout(or after it not detecting the id a few times in a row) then send a url call( i already have a class to send the call)-this should only be sent once.while it is reading the id however another url call should be sent again-once only

如果我明白这个权利那么你需要检查两个不同的东西:

If I understand this right then you need to check for two different things:


  • 设备在发送ID时停止。

  • 设备发送一些空的ID。

这个要求是一种棘手的问题。正如我已经说过,如果没有数据到达串行端口,那么没有串口事件将被触发。我想您可以使用计时器来检查超时并使用计数器来注册到达的空ID号。这样的东西:

This requirement is a kind of tricky. As I've said if no data arrives to the serial port then no serial port event will be fired. I think you can use a Timer to check the timeout and use a counter to register the number of empty ID's arrived. Something like this:

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);
}

我不知道这是否是 / em> 你需要什么,但希望它是有帮助的。

I don't know if this is exactly what you need but hope it be helpful.

这篇关于串行数据事件侦听器Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆