Visualizzazione dei risultati da 1 a 2 su 2
  1. #1
    Utente di HTML.it
    Registrato dal
    Dec 2005
    Messaggi
    24

    JAVA seriale COM problema

    Ciao a tutti
    mi serve il vostro aiuto...

    ho questo codice per laggere dalla COM:
    codice:
    package PortCom;
    
    /*
     * @(#)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.io.*;
    import java.util.*;
    import javax.comm.*;
    
    /**
     * Class declaration
     * 
     * 
     * @author
     * @version 1.8, 08/03/00
     */
    public class SimpleRead implements Runnable, SerialPortEventListener {
    	static CommPortIdentifier portId;
    
    	static Enumeration portList;
    
    	InputStream inputStream;
    
    	SerialPort serialPort;
    
    	Thread readThread;
    
    	/**
    	 * Method declaration
    	 * 
    	 * 
    	 * @param args
    	 * 
    	 * @see
    	 */
    	public static void main(String[] args) {
    		boolean portFound = false;
    		String defaultPort = "COM1";
    
    		if (args.length > 0) {
    			defaultPort = args[0];
    		}
    
    		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;
    					SimpleRead reader = new SimpleRead();
    				}
    			}
    		}
    		if (!portFound) {
    			System.out.println("port " + defaultPort + " not found.");
    		}
    
    	}
    
    	/**
    	 * Constructor declaration
    	 * 
    	 * 
    	 * @see
    	 */
    	public SimpleRead() {
    		try {
    			serialPort = (SerialPort) portId.open("SimpleReadApp", 2000);
    		} 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(20000);
    		} catch (InterruptedException e) {
    		}
    	}
    
    	/**
    	 * Method declaration
    	 * 
    	 * 
    	 * @param event
    	 * 
    	 * @see
    	 */
    	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:
    			System.out.print("OTHER");
    			break;
    
    		case SerialPortEvent.DATA_AVAILABLE:
    			byte[] readBuffer = new byte[20];
    
    			try {
    				FileWriter fileout = new FileWriter("scrivo1.txt");
    				while (inputStream.available() > 0) {
    					int numBytes = inputStream.read(readBuffer);
    				}
    
    				System.out.print(new String(readBuffer));
    				fileout.write(new String(readBuffer));
    				fileout.close();
    			} catch (IOException e) {
    			}
    
    			break;
    		}
    	}
    
    }
    ma quando lo lancio... mi da questo problema:

    Found port: COM1
    Exception in thread "main" java.lang.NullPointerException
    at PortCom.SimpleRead.<init>(SimpleRead.java:104)
    at PortCom.SimpleRead.main(SimpleRead.java:81)

    potete aiutarmi?
    grazie

  2. #2
    Utente di HTML.it
    Registrato dal
    Dec 2005
    Messaggi
    24
    ho provato ad usare altro codice per leggere da seriale...
    codice:
    package PortCom;
    
    import javax.comm.*;
    import java.io.*;
    
    /**
     * 
    
    
     * Title:
     * </p>
     * 
    
    
     * Description:
     * </p>
     * 
    
    
     * Copyright: Copyright (c) 2004
     * </p>
     * 
    
    
     * Company:
     * </p>
     * 
     * @author not attributable
     * @version 1.0
     */
    /*
     * Questa classe permette di leggere dalla porta seriale il cui nome è
     * specificato nel costruttore della stessa.
     */
    
    public class LeggiCOM extends Thread implements SerialPortEventListener {
    
    	// Riferimento all'InputStream da cui leggere
    	private InputStream in;
    
    	// Crea un oggetto che legge dalla porta seriale
    	// specificata nel costruttore
    
    	public LeggiCOM(String port) {
    		try {
    			// Prendiamo il descrittore della porta scelta.
    			// Nel caso in cui la porta non esista verrà sollevata una
    			// eccezione di tipo NoSuchPortException.
    			CommPortIdentifier id_porta;
    			id_porta = CommPortIdentifier.getPortIdentifier(port);
    
    			// Proviamo a prendere l'ownership della porta data.
    			// Nel caso in cui la porta sia già occupata verrà sollevata
    			// una eccezione di tipo PortInUseException
    
    			CommPort porta = id_porta.open("LeggiCOM", 200);
    
    			// Otteniamo un riferimento all'InputStream della porta
    			in = porta.getInputStream();
    
    			// Impostiamo le proprietà di comunicazione nel
    			// seguente modo:
    			// baudrate 9600
    			// dataBits DATABITS_8
    			// stopBits DATABITS_1
    			// parity PARITY_NONE
    
    			// Nel caso in cui i valori impostati non
    			// siano supportati verrà sollevata una eccezione di
    			// tipo UnsupportedCommOperationException
    
    			SerialPort porta_seriale = (SerialPort) porta;
    			porta_seriale.setSerialPortParams(9600, SerialPort.DATABITS_8,
    					SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
    
    			// Ci poniamo in ascolto di eventi sulla porta.
    			// Solamente un oggetto si può registrare come
    			// ascoltatore per cui bisogna gestire l'eccezione
    			// TooManyListenersException
    
    			porta_seriale.addEventListener(this);
    
    			// Avviamo il processo di lettura
    			start();
    		}
    
    		catch (NoSuchPortException ne) {
    			System.out.println("La porta " + port + " non e' presente");
    		}
    
    		catch (PortInUseException pe) {
    			System.out.println("La porta " + port + " è occupata da "
    					+ pe.currentOwner);
    		}
    
    		catch (UnsupportedCommOperationException ue) {
    			System.out.println("La porta non supporta le proprietà impostate");
    		}
    
    		catch (IOException ioe) {
    			System.out.println("Errore di IO");
    		}
    
    		catch (java.util.TooManyListenersException tme) {
    			System.out.println("Si può registrare solamente un ascoltatore");
    		}
    		// fine try/catch
    
    	}
    
    	// Rappresenta il corpo del Thread di lettura
    
    	public void run() {
    		try {
    			Thread.sleep(10000);
    		} catch (InterruptedException e) {
    		}
    	}// fine run
    
    	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[20];
    			try {
    				while (in.available() > 0) {
    					int numBytes = in.read(readBuffer);
    				}
    				System.out.print(new String(readBuffer));
    			} catch (IOException e) {
    			}
    			break;
    		}// fine switch
    	}// fine serialEvent
    
    	public static void main(String[] args) {
    
    		System.out.println("Usage java LeggiCOM");
    		LeggiCOM leggi = new LeggiCOM("COM1");
    		String tmp_ss = ""
    				+ (javax.comm.CommPortIdentifier.getPortIdentifiers())
    						.hasMoreElements();
    		System.out.println("ID COM: " + tmp_ss);
    
    	}// fine main
    
    }// fine
    e questa volta l'errore è:
    La porta COM1 è occupata da Unknown Windows Application
    ID COM: true
    Qual'è questa applicazione?

Permessi di invio

  • Non puoi inserire discussioni
  • Non puoi inserire repliche
  • Non puoi inserire allegati
  • Non puoi modificare i tuoi messaggi
  •  
Powered by vBulletin® Version 4.2.1
Copyright © 2025 vBulletin Solutions, Inc. All rights reserved.