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

📄 ipsadc_ipico_io.java

📁 一个开源的rfid middleware 资料
💻 JAVA
字号:
/*
 * Copyright 2005 i-Konect LLC
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 */
package org.firstopen.singularity.devicemgr.interrogator;

import gnu.io.CommPortIdentifier;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;
import java.util.TooManyListenersException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.firstopen.singularity.config.DeviceProfile;
import org.firstopen.singularity.system.ReaderEvent;
import org.firstopen.singularity.system.Sensor;
import org.firstopen.singularity.system.Shutdown;
import org.firstopen.singularity.system.ShutdownManager;
import org.firstopen.singularity.system.Tag;

/**
 * Class declaration
 * 
 * @author Tom Rose
 * @version $Id: IPSADC_IPICO_IO.java 1242 2006-01-14 03:34:08Z TomRose $
 * 
 * 
 */
public class IPSADC_IPICO_IO implements SerialPortEventListener, Interrogator,
		Shutdown {

    private  CommPortIdentifier portId;

	private  Enumeration portList;

	protected InputStream inputStream;

	protected OutputStream outputStream;

	private SerialPort serialPort;

	protected ByteArrayOutputStream message = new ByteArrayOutputStream();

	private Log log = LogFactory.getLog(this.getClass());

	private DeviceProfile deviceProfile = null;

	private boolean commandline = false;

	private HashMap<String, String> commands = new HashMap<String, String>();

	protected final String RFON = "RFON";

	protected final String RFOFF = "RFOFF";

	protected int RECORD_LENGTH = 38;

	protected InterrogatorIO interrogatorIO;

	/**
	 * Main Method declaration for testing
	 * 
	 * @param args
	 * @throws Exception
	 * 
	 * @see
	 */
	public static void main(String[] args) {
    
		String defaultPort = "/dev/tty.usbserial-FTCAYDDH";
		String defaultBaud = "9600";

		char CR = '\r';
		char LF = '\n';
		StringBuffer CRLF = new StringBuffer();
		CRLF.append(CR);
		CRLF.append(LF);

		for (int i = 0; i < args.length; i++) {
			switch (i) {
			case 0:
				defaultPort = args[i];
				break;
			case 1:
				defaultBaud = args[i];
				break;
			}
		}// end for
		ShutdownManager sdm = new ShutdownManager();
		Runtime.getRuntime().addShutdownHook(sdm);
		try {

			DeviceProfile deviceProfile = new DeviceProfile("Dummy");

			deviceProfile.setPort(defaultPort);
			deviceProfile.setBaud(defaultBaud);
			Set<Sensor> sensors = new HashSet<Sensor>();
			sensors.add(new Sensor("embeddedAntenna"));
			deviceProfile.setSensorSet(sensors);

			IPSADC_IPICO_IO reader = new IPSADC_IPICO_IO(deviceProfile);

			reader.commandline = true;

			reader.run();

			reader.serialPort.addEventListener(new SimpleEventListener(
					reader.serialPort));

			BufferedReader br = new BufferedReader(new InputStreamReader(
					System.in));

			String commandLine = null;

			OutputStream outputStream = reader.serialPort.getOutputStream();

			String sLRC = null;

			while (true) {
				System.out.print("enter command > ");
				commandLine = br.readLine();
				sLRC = reader.calcLRC(commandLine.getBytes());

				commandLine = commandLine + sLRC + CRLF;
				System.out.println("Length is " + commandLine.length());
				System.out.println("LRC is: " + sLRC);

				outputStream.write(commandLine.getBytes());
				outputStream.flush();
			}

		} catch (IOException ioe) {
			System.out.println("IO error trying to read command");

		} catch (Exception e) {

			e.printStackTrace();
		}
	}

	/**
	 * Constructor declaration
	 * 
	 * 
	 * @see
	 */
	public IPSADC_IPICO_IO() {
		setupCommands();
	}

	/**
	 * Constructor declaration
	 * 
	 * 
	 * @see
	 */
	public IPSADC_IPICO_IO(DeviceProfile deviceProfile) {
		this();
		this.setDeviceProfile(deviceProfile);

	}

	public void run() {
		try {

			String defaultPort = deviceProfile.getPort();
			int defaultBaud = Integer.parseInt(deviceProfile.getBaud());

			boolean portFound = false;

			portList = CommPortIdentifier.getPortIdentifiers();

			while (portList.hasMoreElements()) {

				portId = (CommPortIdentifier) portList.nextElement();
				log.debug("Found  port: " + portId.getName());
				if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
					if (portId.getName().equals(defaultPort)) {
						log.info("Found port match: " + defaultPort);
						portFound = true;

					}
				}
			}
			if (!portFound) {
				System.out.println("port " + defaultPort + " not found.");
			}

			else {

				serialPort = (SerialPort) portId.open(
						this.getClass().getName(), 2000);

				inputStream = serialPort.getInputStream();

				outputStream = serialPort.getOutputStream();

				if (commandline == false)
					serialPort.addEventListener(this);
			}
			serialPort.notifyOnDataAvailable(true);

			serialPort.setSerialPortParams(defaultBaud, SerialPort.DATABITS_8,
					SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);

			switchRF(this.RFON);

			/*
			 * register with shutdown manager
			 */
			ShutdownManager.addManagedObject(this);

		} catch (UnsupportedCommOperationException e) {
			log.error("unable to intatiate Interrogator ", e);
		} catch (TooManyListenersException e) {
			log.error("unable to intatiate Interrogator ", e);
		} catch (PortInUseException e) {
			log.error("unable to intatiate Interrogator ", e);
		} catch (IOException e) {
			log.error("unable to intatiate Interrogator ", e);
		}

	}

	/**
	 * Method declaration
	 * 
	 * 
	 * @param serialEvent
	 * @throws Exception
	 * 
	 * @see
	 */
	public void serialEvent(SerialPortEvent serialEvent) {
		switch (serialEvent.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:

			try {

				/*
				 * Refresh the reader buffer, each call
				 */
				byte[] readBuffer = new byte[64];
				int numBytes = 0;
				while (inputStream.available() > 0) {
					numBytes = inputStream.read(readBuffer);
					message.write(readBuffer, 0, numBytes);
					log.debug("Bytes Read = " + numBytes);

				}
			} catch (IOException e) {
				log.error("Failed to read from serial input stream ", e);
			}
			log.debug("message is: " + message);
			/*
			 * see if there are any complete messages found in teh output stream
			 * (message)
			 */
			ArrayList<byte[]> messageList = findMessage(message);

			log.info("message size is :" + messageList.size());

			if (messageList.size() > 0) {

				try {
					/*
					 * decode a list of messages multipe ecodings can exists
					 * this one asumes the ascii encoding.
					 */
					ArrayList<Tag> tagList = decodeData(messageList);

					Sensor sensor = deviceProfile.getSensorSet().iterator().next();

					ReaderEvent event = new ReaderEvent(sensor);

					event.setTagIds(tagList);

					event.setReaderName(deviceProfile.getDeviceProfileID());

					interrogatorIO.sendEvent(event);

				} catch (InterrogatorException e) {
					log.error("undable to decode message, info ignored", e);
				} catch (Exception e) {
					log.error("unable to send event to Device Manager", e);
				}
			}// end if

			break;
		}// end switch
	}// end SerialEvent

	/**
	 * find ascii encoded messages in the OutputStream a valid message begins
	 * with "aa" and ends with "<CR><LF>" Thee may be 1 or more messages in
	 * the buffer. The buffer is reset, and then partial messsages are added
	 * back to the buffer for processing on the serial event.
	 * 
	 * @param message
	 * @return messageList
	 */
	protected ArrayList<byte[]> findMessage(ByteArrayOutputStream message) {

		ArrayList<byte[]> messageList = new ArrayList<byte[]>();

		synchronized (message) {

			// log.debug("message is " + message + " record length = " +
			// RECORD_LENGTH);

			byte[] buffer = message.toByteArray();
			byte[] messageBuf = new byte[RECORD_LENGTH];

			message.reset();
			for (int i = 0; i < buffer.length - 1; i++) {
				if (buffer[i] == 97 && buffer[i + 1] == 97) {
					if (i + RECORD_LENGTH - 1 > buffer.length) {
						
						message.write(buffer, i, buffer.length - i);
						break;
					}
					if (buffer[i + RECORD_LENGTH - 2] == 13
							&& buffer[i + RECORD_LENGTH - 1] == 10) {
						messageBuf = new byte[RECORD_LENGTH];
						System.arraycopy(buffer, i, messageBuf, 0,
								RECORD_LENGTH);
						messageList.add(messageBuf);
						i = i + RECORD_LENGTH - 1; // index to end of message
					}
					
				}// end if start message found
			}
		}
		return messageList;

	}

	/**
	 * Byte Description Info - Hexadecimal ASCII delimited records 0 Header
	 * character 1 Frame header, 1 Header character 2-3 Reader ID 0-255 in ASCII
	 * hex 4-15 Tag ID MS digit first 16-19 I and Q channel counter Binary
	 * counters 0-255 in ASCII hex 20-33 Date/Time Date and time with 10ms
	 * resolution. 390ms/10 = 39 =(27 = 0x32 + 0x37) and the month 12 is 0x31+
	 * 0x32. 34-35 LRC Checksum on bytes 2 to 33 36-37 End of packet (CR, LF)
	 * 0x0d, 0x0a
	 * 
	 * (i.e. ASCII converison of byte array =
	 * aa0000000003e52e0102050625025124319b
	 * 
	 * 
	 * Instantaneous ID hits and IDs in transit are spooled in small packets,
	 * one for each ID. These can be considered as stand alone data-grams
	 * similar to the UDP protocol. Table 1 depicts the content of these
	 * data-grams for the hexadecimal ASCII format. This format converts the
	 * binary data to ASCII but with a hexadecimal base (e.g. 0b00101111 is
	 * converted to 

⌨️ 快捷键说明

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