⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 readoscilloscopepackage.java

📁 一个基于sensor的中间件
💻 JAVA
字号:
/* * To change this template, choose Tools | Templates * and open the template in the editor. */package SensorData;import java.io.*;import java.util.*;import javax.comm.*;/** * There are two classes used for the sensor, ReadPacket.java and SaveData.java  * this class is used for connecting and get data from sensors * I think this file may get O * @author Liuyuyang * @version 06/18/08 */public class ReadOscilloscopePackage implements Runnable, SerialPortEventListener {    static CommPortIdentifier portId;    static Enumeration portList;    InputStream inputStream;    Thread readThread;    SerialPort serialPort;    private static int count,  st;    private static final byte[] highDigits;    private static final byte[] lowDigits;    private byte[] readBuffers = new byte[400];    Vector reads = new Vector();    SaveData sensorData = new SaveData();    static {        final byte[] digits = {            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'        };        int i;        byte[] high = new byte[256];        byte[] low = new byte[256];        for (i = 0; i < 256; i++) {            high[i] = digits[i >>> 4];            low[i] = digits[i & 0x0F];        }        highDigits = high;        lowDigits = low;    }       /**     * Constructor declaration     *      *     * @see     */    //@see 应该是对继承哪个类的说明    public ReadOscilloscopePackage() {                count = -1;        try {            //  CommPort.open(java.lang.String appname, int timeout)             serialPort = (SerialPort) portId.open("ReadOscilloscopePacket", 1000);        } catch (PortInUseException e) {        }        try {            inputStream = serialPort.getInputStream();        } catch (IOException e) {        }        try {            serialPort.addEventListener(this);        } catch (TooManyListenersException e) {        }        serialPort.notifyOnDataAvailable(true);        try {            serialPort.setSerialPortParams(57600,                    SerialPort.DATABITS_8,                    SerialPort.STOPBITS_1,                    SerialPort.PARITY_NONE);        } catch (UnsupportedCommOperationException e) {        }        readThread = new Thread(this);        readThread.start();    }    public static void main(String[] args) {        //초기 포트 설정        portList = CommPortIdentifier.getPortIdentifiers();        System.out.println(portList.hasMoreElements());        while (portList.hasMoreElements()) {            portId = (CommPortIdentifier) portList.nextElement();            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {                if (portId.getName().equals("COM4")) {                    ReadOscilloscopePackage reader = new ReadOscilloscopePackage();  //생성자 호출                }            }        }    //If the port is used, so we have to wait for some minutes.        WaitSec ws = new WaitSec();        Thread time = new Thread(ws);        time.start();    }    public void run() {        try {            Thread.sleep(20000);        } catch (InterruptedException e) {        }    }    public static String getHexDump(int num) {        String result = "";        int byteValue = num & 0xFF;        result += (char) highDigits[byteValue];        result += (char) lowDigits[byteValue];        return result;    }    public String Dataview(int[] reads) {        for (int i = 0; i < 100; i++) {            System.out.print(getHexDump(reads[i]) + " ");        }        System.out.println();        return "";    }    /**     * Method declaration     *     *     * @param event     *     * @see     */    public void serialEvent(SerialPortEvent event) {        switch (event.getEventType()) {            case SerialPortEvent.BI: /*Break interrupt,通讯中断*/            case SerialPortEvent.OE: /*Overrun error,溢位错误*/            case SerialPortEvent.FE: /*Overrun error,溢位错误*/            case SerialPortEvent.PE: /*Framing error,传帧错误*/            case SerialPortEvent.CD: /*Parity error,校验错误*/            case SerialPortEvent.CTS: /*Clear to send,清除发送*/            case SerialPortEvent.DSR: /*Data set ready,数据设备就绪*/            case SerialPortEvent.RI: /*Data set ready,数据设备就绪*/            case SerialPortEvent.OUTPUT_BUFFER_EMPTY: /*Ring indicator,响铃指示*/                break;            case SerialPortEvent.DATA_AVAILABLE:                /*Data available at the serial port,端口有可用                数据。读到缓冲数组,输出到终端*/                try {                    //This command need to be tested.                    //To fill the coming data into dataset.                    // data.update(omsg.get_id(), omsg.get_count(), omsg.get_readings());                    while (inputStream.available() > 0) //InputStream으로부터 읽을수 있는 바이트 수를 반환 > 0                    {                        int num = inputStream.read();         //한 바이트를 읽는다.                        if (st == 1) {                            reads.add(num + "");              //save one byte in the vector                            count++;                          //카운트 증가                        }                        //System.out.println(getHexDump(num).toString());                        //"7E" means the front and end of one packet.                        if (getHexDump(num).equals("7E")) //받아온 한 바이트가 0x7E(126)이면                        {                            if (st == 0) {                                reads.add(num + "");                                st = 1;                                count++;                            } else if (st == 1) {                                if (reads.size() > 10) {                                    st = 0;                                    count = 0;//this part is the test//                                    for (int i = 0; i < reads.size(); i++) {//                                        int value = Integer.valueOf(reads.elementAt(i).toString());//                                        System.out.println(getHexDump(value));//                                    }                                    //the end of test                                    if (!reads.elementAt(1).toString().equals("64")) {                                                                                if (reads.size() == 41) {                                            /* Update interval and mote data *///                                            Package OscilloscopePackage = new Package(reads);//                                            periodUpdate(OscilloscopePackage.get_version(),//                                                    OscilloscopePackage.get_interval());//                                            data.update(OscilloscopePackage.get_id(),//                                                    OscilloscopePackage.get_count(),//                                                    OscilloscopePackage.get_readings());                                            sensorData.Save(reads);                                            //System.out.println("data updated");                                            /* Inform the GUI that new data showed up *///                                            window.newData();                                            //System.out.println("window updated");                                        }                                    }                                    //데이터를 받을 새로운 벡터를 생성한다.                                    reads = new Vector();                                } else {                                    reads.removeElementAt(reads.size() - 1);                                }                            }                        }                    }    // end of //while                } // end of// try                catch (Exception e) {                    e.printStackTrace();                }                break;        }    }}class WaitSec implements Runnable {    private int seconds = 0;    public void run() {        while (true) {            try {                Thread.sleep(1000);            } catch (Exception e) {            }            //every 5 minutes trasform data to Utopia            if (seconds == 3) {                seconds = 0;                SaveData sd = new SaveData();                System.out.println("Data will be receive again after 10 seconds");                sd.Socket();            } else {                seconds++;            }        }    }    }//~ Formatted by Jindent --- http://www.jindent.com

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -