Klassenproblem

Ronin-Jay

Erfahrenes Mitglied
Hallo zusammen,

ich habe ein Problem, bei dem ich jetzt schon den 2. Tag grübel. Und zwar habe ich mir eine einfache Klasse inkl. Main-Methode geschrieben, um Daten von einem Transponder zu lesen. Damit kann ich den Transponderkey richtig auslesen.....

ComRead.java:
Code:
/*
 * @(#)SimpleRead.java	1.12 98/06/25 SMI
 * 
 * Copyright 2003 Sun Microsystems, Inc. All rights reserved.
 * SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 * 
 * Sun grants you ("Licensee") a non-exclusive, royalty free, license
 * to use, modify and redistribute this software in source and binary
 * code form, provided that i) this copyright notice and license appear
 * on all copies of the software; and ii) Licensee does not utilize the
 * software in a manner which is disparaging to Sun.
 * 
 * This software is provided "AS IS," without a warranty of any kind.
 * ALL EXPRESS OR IMPLIED CONDITIONS, REPRESENTATIONS AND WARRANTIES,
 * INCLUDING ANY IMPLIED WARRANTY OF MERCHANTABILITY, FITNESS FOR A
 * PARTICULAR PURPOSE OR NON-INFRINGEMENT, ARE HEREBY EXCLUDED. SUN AND
 * ITS LICENSORS SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED BY
 * LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THE
 * SOFTWARE OR ITS DERIVATIVES. IN NO EVENT WILL SUN OR ITS LICENSORS
 * BE LIABLE FOR ANY LOST REVENUE, PROFIT OR DATA, OR FOR DIRECT,
 * INDIRECT, SPECIAL, CONSEQUENTIAL, INCIDENTAL OR PUNITIVE DAMAGES,
 * HOWEVER CAUSED AND REGARDLESS OF THE THEORY OF LIABILITY, ARISING
 * OUT OF THE USE OF OR INABILITY TO USE SOFTWARE, EVEN IF SUN HAS BEEN
 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
 * 
 * This software is not designed or intended for use in on-line control
 * of aircraft, air traffic, aircraft navigation or aircraft
 * communications; or in the design, construction, operation or
 * maintenance of any nuclear facility. Licensee represents and
 * warrants that it will not use or redistribute the Software for such
 * purposes.
 */
import java.awt.Toolkit;
import java.io.*;
import java.util.*;
import javax.comm.*;

/**
 * Class declaration
 *
 *
 * @author
 * @version 1.8, 08/03/00
 */
public class ComRead implements Runnable, SerialPortEventListener {
    static CommPortIdentifier 	portId;
    static Enumeration			portList;
    InputStream		    		inputStream;
    SerialPort		    		serialPort;
    Thread		      			readThread;
    String						key = "",
    							lastKey = "";
    int numBytes = 0;
    
    
    //------------------------------------------------------------------------
    // ABSOLUTE TERMS:
    //
    //defines payload for the used transponder-key
    //e.g.: U80A0AE5F0E => 11
    final int payload = 11;
    
    //bytes for readBuffer
    final static String defaultPort = "COM3";
    
    //Portnumber
    final int portNum = 2000;
    
    //name for application which blocks the port
    final String blockName = "SimpleReadApp";
    //------------------------------------------------------------------------
    
    
    
    

    /**
     * Method declaration
     *
     *
     * @param args
     *
     * @see
     */
    public static void main(String[] args) {
    boolean		      portFound = false;
    //String		      defaultPort = comPort;
       
	portList = CommPortIdentifier.getPortIdentifiers();

	while (portList.hasMoreElements()) {
	    portId = (CommPortIdentifier) portList.nextElement();
	    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
			if (portId.getName().equals(defaultPort)) {
			    System.out.println("Found port: "+defaultPort);
			    portFound = true;
			    ComRead reader = new ComRead();
			} 
	    } 
	} 
	if (!portFound) {
	    System.out.println("Port " + defaultPort + " not found.");
	} 	
    } 

    
    /**
     * Constructor declaration
     *
     *
     * @see
     */
    public ComRead() {
	try {
	    serialPort = (SerialPort) portId.open(blockName, portNum);
	    System.out.println(serialPort);
	} catch (PortInUseException e) {}

	try {
	    inputStream = serialPort.getInputStream();
	} catch (IOException e) {}

	try {
	    serialPort.addEventListener(this);
	} catch (TooManyListenersException e) {}

	serialPort.notifyOnDataAvailable(true);

	try {
	    serialPort.setSerialPortParams(9600, 
	    		SerialPort.DATABITS_8, 
				SerialPort.STOPBITS_1, 
				SerialPort.PARITY_NONE);
	} catch (UnsupportedCommOperationException e) {}

	readThread = new Thread(this);
	readThread.start();
    }

    
    /**
     * Method declaration
     *
     *
     * @see
     */
    public void run() {
		try {
		    Thread.sleep(2000);
		} catch (InterruptedException e) {}
    } 

    
    /**
     * Method declaration
     *
     *
     * @param event
     *
     * @see
     */
    /* (non-Javadoc)
     * @see javax.comm.SerialPortEventListener#serialEvent(javax.comm.SerialPortEvent)
     */
    public void serialEvent(SerialPortEvent event) {
		switch (event.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:
		    byte[] readBuffer = new byte[128];	
		    String tmpStr;
			int tmpInt;
	
		    try {
		    	//get inputstreamdata
		    	while (inputStream.available() > 0) {
		    		tmpInt = inputStream.read(readBuffer);
		    		//um unnoetige zeichen zu entfernen
		    		tmpStr = new String(readBuffer).trim();
		    		
		    		if(tmpStr.equals("")){}
		    		else{
		    			System.out.println("STRING: "+tmpStr+" LENGTH ["+tmpInt+" | "+tmpStr.length()+"]");
		    		}
				}//while	
		    } catch (IOException e) {}
		}//switch
    }//serialEvent 

}//class

Die Ausgabe der Applikation sieht wie folgt aus:
Code:
STRING: U8 LENGTH [2 | 2]
STRING: 0 LENGTH [1 | 1]
STRING: 4 LENGTH [1 | 1]
STRING: 0 LENGTH [1 | 1]
STRING: 2 LENGTH [1 | 1]
STRING: F LENGTH [1 | 1]
STRING: 9 LENGTH [1 | 1]
STRING: 3 LENGTH [1 | 1]
STRING: 3 LENGTH [1 | 1]
STRING: C LENGTH [1 | 1]
STRING: U LENGTH [1 | 1]
STRING: 80402 LENGTH [5 | 5]
STRING: F LENGTH [1 | 1]
STRING: 9 LENGTH [1 | 1]
STRING: 3 LENGTH [1 | 1]
STRING: 3 LENGTH [1 | 1]
STRING: C LENGTH [1 | 1]
STRING: U LENGTH [1 | 1]
STRING: 8 LENGTH [1 | 1]
STRING: 0 LENGTH [1 | 1]
STRING: 4 LENGTH [1 | 1]
STRING: 0 LENGTH [1 | 1]
STRING: 2 LENGTH [1 | 1]
STRING: F LENGTH [1 | 1]
STRING: 9 LENGTH [1 | 1]
STRING: 3 LENGTH [1 | 1]
STRING: 3 LENGTH [1 | 1]
STRING: C LENGTH [1 | 1]
STRING: U LENGTH [1 | 1]
STRING: 8 LENGTH [1 | 1]
STRING: 0 LENGTH [1 | 1]
STRING: 4 LENGTH [1 | 1]
STRING: 0 LENGTH [1 | 1]
STRING: 2 LENGTH [1 | 1]
STRING: F LENGTH [1 | 1]
STRING: 9 LENGTH [1 | 1]
STRING: 3 LENGTH [1 | 1]
STRING: 3 LENGTH [1 | 1]
STRING: C LENGTH [1 | 1]


Nun habe ich versucht das gnaze in einer Klasse umzusetzen...

Transponder.java:
Code:
/**
 * <h1>
 * Title: Transponder-Class
 * </h1>
 * <p>
 * Description: Class to handle the transponder-reader an everything that 
 * deals with it.
 * </p>
 * <p>
 * Copyright: Copyright (c) 2007
 * </p>
 *
 */ 

package ECM;



import java.awt.Toolkit;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.PropertyResourceBundle;
import java.util.ResourceBundle;
import java.util.TooManyListenersException;

import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;



/****************************************************************************
 * 
 * @author 
 *
 ***************************************************************************/
public class Transponder implements Runnable, SerialPortEventListener{
	
	//declarations
	private final String 		CONF_FILE = "inc/settings.conf";
	private CommPortIdentifier 	portId;
	private Enumeration			portList;
	private InputStream		    in;
	private ResourceBundle 		res;
	private SerialPort		    serialPort;
	private byte[] 				readBuffer = new byte[128];
	private Thread		      	readThread;
	private String				key = "",
    							lastKey = "",
    							defaultPort,
    							blockName;
	private int 	numBytes = 0,
					payload,
					baudrate,
					portNum;
	private boolean portFound = false;
	
	
	/************************************************************************
	 * Contructor
	 ***********************************************************************/
	public Transponder(){
		//read conf-file
		try{
			in = ClassLoader.getSystemResourceAsStream(CONF_FILE);
		    res = new PropertyResourceBundle(in);
		} catch (IOException ioe) {
			System.err.println("Could not find \"settings.conf\"");
			System.exit(1);
		  }
		
		//set values
		payload		= Integer.valueOf( res.getString("ECM.Payload")).intValue();
		defaultPort = res.getString("ECM.DefaultPort");
		portNum 	= Integer.valueOf( res.getString("ECM.Portnumber"))
					  .intValue();
		blockName	= res.getString("ECM.Name");
		baudrate	= Integer.valueOf( res.getString("ECM.Baud")).intValue();
		
		//looking for serial-port
		//if port found connect and start reading, else shown message 
		portList = CommPortIdentifier.getPortIdentifiers();
		while (portList.hasMoreElements()) {
		    portId = (CommPortIdentifier) portList.nextElement();
		    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
				if (portId.getName().equals(defaultPort)) {
				    portFound = true;
				    start();
				} 
		    } 
		} 
		if (!portFound) {
		    System.out.println("Port " + defaultPort + " not found.");
		} 	
	}//Constructor
	
	
	/************************************************************************
	 * connects to the transpondereader (open port and blocks it) and start
	 * reading data input
	 ***********************************************************************/
	public void start(){
		//open serialport set in config-file
		try {
		    serialPort = (SerialPort) portId.open(blockName, portNum);
		} catch (PortInUseException e) {}

		//get inputstream on that port
		try {
		    in = serialPort.getInputStream();
		} catch (IOException e) {}

		//add eventlistener[serialEvent] to port
		try {
		    serialPort.addEventListener(this);
		} catch (TooManyListenersException e) {}

		serialPort.notifyOnDataAvailable(true);

		try {
		    serialPort.setSerialPortParams(9600, 
		    		SerialPort.DATABITS_8, 
					SerialPort.STOPBITS_1, 
					SerialPort.PARITY_NONE);
		} catch (UnsupportedCommOperationException e) {}
		
		//start readingThread
		readThread = new Thread(this);
		readThread.start();
		
		
	}//start()

	
	/************************************************************************
	 * Threadmethod
	 ***********************************************************************/
	public void run() {
		// TODO Auto-generated method stub		
		try {
		    Thread.sleep(2000);
		} catch (InterruptedException e) {}
	}//run()

	
	/************************************************************************
     * handle events from serialport
     ***********************************************************************/
	public void serialEvent(SerialPortEvent event) {
		// TODO Auto-generated method stub
		switch (event.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:
		    //byte[] readBuffer = new byte[128];	
		    String tmpStr;
		    String tmp = "";
		    char tmpChar;
			int tmpInt;
			int i=0;
	
		    try {		    	
		    	//get inputstreamdata
		    	while (in.available() > 0) {
		    		tmpInt = in.read(readBuffer);
		    		//um unnoetige zeichen zu entfernen
		    		tmpStr = new String(readBuffer).trim();
		    		
		    		if(tmpStr.equals("")){}
		    		else{
		    			System.out.println("STRING: "+tmpStr+" LENGTH ["+tmpInt+" | "+tmpStr.length()+"]");
		    		}
				}//while		
		    } catch (IOException e) {}		    
		}//switch
	}//serialEvent()
	
	//========================================================================
	// help-methods
	//========================================================================
		
    /**
     * help-method to test class and see if settings were imported correctly
     */
    public void printInfos(){
    	System.out.println("Payload: " +payload);
    	System.out.println("DefaultPort: " +defaultPort);
    	System.out.println("Portnumber: " +portNum);
    	System.out.println("Baudrate: " +baudrate);
    	System.out.println("Block-Name: " +blockName);
    }//printInfos()	

}//class

die Test-Klasse, welche die Transponder-Klasse nutzt:
Code:
package ECM;

/**
 * Class to test Transponder-class
 *
 */
public class TEST_Trans {

	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		Transponder tp = new Transponder();
		//tp.printInfos();
		
	}//main
	

}//TEST-class

Die SerialEvent - Listener sind bei beiden Klassen gleich, allerdings erhalte ich über TEST-Transponder Klasse eine andere Ausgabe:
Code:
STRING: U8 LENGTH [2 | 2]
STRING: 08 LENGTH [1 | 2]
STRING: 48 LENGTH [1 | 2]
STRING: 08 LENGTH [1 | 2]
STRING: 28 LENGTH [1 | 2]
STRING: F8 LENGTH [1 | 2]
STRING: 98 LENGTH [1 | 2]
STRING: 38 LENGTH [1 | 2]
STRING: 38 LENGTH [1 | 2]
STRING: C8 LENGTH [1 | 2]
==> STRING: 8 LENGTH [1 | 1]
==> STRING: 8 LENGTH [1 | 1]
STRING: U8 LENGTH [1 | 2]
STRING: 80402 LENGTH [5 | 5]
STRING: F0402 LENGTH [1 | 5]
STRING: 90402 LENGTH [1 | 5]
STRING: 30402 LENGTH [1 | 5]
STRING: 30402 LENGTH [1 | 5]
STRING: C0402 LENGTH [1 | 5]
==> STRING: 0402 LENGTH [1 | 4]
==> STRING: 0402 LENGTH [1 | 4]
STRING: U0402 LENGTH [1 | 5]
STRING: 80402 LENGTH [1 | 5]
STRING: 00402 LENGTH [1 | 5]
STRING: 40402 LENGTH [1 | 5]
STRING: 00402 LENGTH [1 | 5]
STRING: 20402 LENGTH [1 | 5]
STRING: F0402 LENGTH [1 | 5]
STRING: 90402 LENGTH [1 | 5]
STRING: 30402 LENGTH [1 | 5]
STRING: 30402 LENGTH [1 | 5]
STRING: C0402 LENGTH [1 | 5]
==> STRING: 0402 LENGTH [1 | 4]
==> STRING: 0402 LENGTH [1 | 4]
STRING: U0402 LENGTH [1 | 5]
STRING: 80402 LENGTH [1 | 5]
STRING: 00402 LENGTH [1 | 5]
STRING: 40402 LENGTH [1 | 5]
STRING: 00402 LENGTH [1 | 5]
STRING: 20402 LENGTH [1 | 5]
STRING: F0402 LENGTH [1 | 5]
STRING: 90402 LENGTH [1 | 5]
STRING: 30402 LENGTH [1 | 5]
STRING: 30402 LENGTH [1 | 5]
STRING: C0402 LENGTH [1 | 5]
==> STRING: 0402 LENGTH [1 | 4]
==> STRING: 0402 LENGTH [1 | 4]

Wieso unterscheidet sich die Ausgabe so gravierend und wieso wird bei letzten Ausgabe das CR/LF mal als "8" und mal als "0" erfaßt, während es bei ComRead.java durch new String (byte[]).trim() in "" gewandelt und dann durch die Zeile "if(tmpStr.equals("")){}" rausgefilter wird [mit ==> in der Ausgabe gekennzeichnet]..... :confused:

Sehe sicherlich den Wald vor lauter Bäumen nicht und die Lösung ist trivial. Bin für Hinweise dankbar.

Der Key, der ausgelesen werden soll, lautet "U80402F933C". Die Klassen habe ich mal als Text-Datei angehängt.


//EDIT:
Blind muß man sein. Wenn man die Ausgabe richtig interpretiert, stellt man fest, daß sich noch "Müll" im readBuffer befindet. Da er nicht im serialEvent deklariert ist, wird er nicht überschrieben und Müll könnte liegen bleiben....ergo readBuffer im Event deklarieren, dann klappts auch mit den Daten ;-)
 

Anhänge

  • ComRead.txt
    5,5 KB · Aufrufe: 34
  • Transponder.txt
    5,8 KB · Aufrufe: 32
  • TEST_Trans.txt
    300 Bytes · Aufrufe: 30
Zuletzt bearbeitet:
Zurück