Visualizzazione dei risultati da 1 a 5 su 5

Discussione: problemi con java comm

  1. #1

    problemi con java comm

    credo di non comprendere esattamente l'uso delle operazioni di I\O infatti sto comunicando con un modem che è collegaato alla mia porta seriale e sto utilizzando gli esempi assieme alle java comm se utilizzo questa classe SimpleWrite:

    import java.io.*;
    import java.util.*;
    import javax.comm.*;

    public class SimpleWrite {
    static Enumeration portList;
    static CommPortIdentifier portId;
    static String messageString = "ATI6\n";
    static SerialPort serialPort;
    static OutputStream outputStream;
    static InputStream inputstream;

    public static void main(String[] args) {
    portList = CommPortIdentifier.getPortIdentifiers();

    while (portList.hasMoreElements()) {
    portId = (CommPortIdentifier) portList.nextElement();
    if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
    if (portId.getName().equals("COM4")) {
    // if (portId.getName().equals("/dev/term/a")) {
    try {
    serialPort = (SerialPort)
    portId.open("rs232", 2000);
    } catch (PortInUseException e) {}
    try {
    outputStream = serialPort.getOutputStream();

    } catch (IOException e) {}
    try {
    serialPort.setSerialPortParams(9600,
    SerialPort.DATABITS_8,
    SerialPort.STOPBITS_1,
    SerialPort.PARITY_NONE);
    } catch (UnsupportedCommOperationException e) {}
    try {
    outputStream.write(messageString.getBytes());

    } catch (IOException e) {}
    }
    }

    }
    }
    }
    non invio al modem il comando ATI6??
    se adesso faccio partire il codice relativo alla lettura non dovrebbe inviarmi la risposta? spero ma credo di non aver detto corbellerie ma ho un pò di confusione chiedo umilmente il vostro aiuto
    p.s. le java comm mi funzionano e vedono le porte naturalmente ciao se avete del codice efficace ve ne sarei grato grazie di tutto
    riccardo

  2. #2
    si, ma nel codice che hai postato non c'è la parte che gestisce la risposta del modem.....in quel modo scrivi solo sulla porta COM4 e basta....
    My SO:WinXP pro/Linux Debian/Gentoo 2006.0

  3. #3
    grazie della risposta vado al sodo se aggiungo a SimpleWrite nell'ultimo thread dopo la riga
    outputStream.write(messageString.getBytes()); la riga:
    SimpleRead reader =new SimpleRead(); che richiama questa classe:

    import java.io.*;

    import java.util.*;

    import javax.comm.*;


    public class SimpleRead implements Runnable, SerialPortEventListener {

    static CommPortIdentifier portId;

    static Enumeration portList;


    InputStream inputStream;

    SerialPort serialPort;

    Thread readThread;




    public SimpleRead() {


    try {
    inputStream = serialPort.getInputStream();
    }
    catch (NullPointerException e) {}
    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();
    }


    public void run() {

    try {

    Thread.sleep(20000);

    }
    catch (InterruptedException e) {}
    }


    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 (inputStream.available() > 0) {

    int numBytes = inputStream.read(readBuffer);
    }

    System.out.print(new String(readBuffer));
    }
    catch (IOException e) {}
    break;
    }
    }
    }
    scusa la lunghezza ma per chiarezza eclipse lanciando SimpleWrite mi dà questo errore:

    java.lang.NullPointerException
    at SimpleRead.<init>(SimpleRead.java:66)
    at SimpleWrite.main(SimpleWrite.java:69)
    Exception in thread "main" perchè? una volta inviato il comando non faccio altro che leggere o m sbaglio? Se puoi darmi consigli su come correggere il codice o delle dritte te ne sarei grato ciao a presto
    riccardo

  4. #4
    Ciao,premetto che nn ho usato eclipse ma solo notepad, ho provato a compilare e ad eseguire il tuo codice ma non ho riscontrato gli errori che hai postato tu, quindi nn so che dirti.....bye
    My SO:WinXP pro/Linux Debian/Gentoo 2006.0

  5. #5
    ho risolto questo codice mi funziona legge e scrive ma non si ferma cioè non termina l'esecuzione come posso elegantemente forzarlo a uscire dopo che ho ricevuto la risposta? riporto il codice nella sua interezza(così puoi farne copia&incolla):


    import java.io.InputStream;
    import java.io.OutputStream;
    import java.io.IOException;
    import java.io.Serializable;
    import java.util.TooManyListenersException;

    import javax.comm.*;
    public class SimpleReadWrite implements Runnable,
    SerialPortEventListener {

    static String DEFAULT_PORT = "COM4";

    InputStream in;
    OutputStream out;
    private String message = "AT\r";
    public void writeToCommPort(String message) {
    this.message = message;
    }


    /**
    * Main method.
    */
    public static void main(String[] args) {
    String portname = DEFAULT_PORT;
    if (args.length > 1) {
    System.err.println("Usage: java SimpleReadWrite [port_name]");
    System.exit(1);
    }
    else if (args.length == 1) {
    portname = args[0];
    }

    try {
    CommPortIdentifier portId =

    CommPortIdentifier.getPortIdentifier(portname);
    if (portId.getPortType() ==
    CommPortIdentifier.PORT_SERIAL) {
    SimpleReadWrite srw = new SimpleReadWrite(portId);
    }
    else {
    System.err.println(portname + " is not a serial port");
    System.exit(1);
    }
    }
    catch (NoSuchPortException e) { //Port nicht vorhanden
    System.err.println("No such port: " + portname);
    System.exit(1);
    }
    catch (PortInUseException e) { //Port ist gesperrt/inGebrauch
    System.err.println("Port in use: " + portname);
    System.exit(1);
    }
    }

    /**
    * Constructor.
    */
    public SimpleReadWrite(CommPortIdentifier portId) throws
    PortInUseException {
    try {
    SerialPort serialPort = (SerialPort)
    portId.open("SimpleReadWrite",
    2000);
    //Port mit
    in = serialPort.getInputStream();
    out = serialPort.getOutputStream();
    serialPort.addEventListener(this);
    serialPort.notifyOnDataAvailable(true);
    serialPort.setSerialPortParams(9600, //Schnittstelleneinstellungen initialisieren
    SerialPort.DATABITS_8,
    SerialPort.STOPBITS_1,
    SerialPort.PARITY_NONE);
    Thread readerThread = new Thread(this);

    readerThread.start();

    } //Exception-Handling
    catch (IOException e) {
    System.err.println("Problem opening streams");
    System.exit(1);
    }
    catch (TooManyListenersException e) {
    System.err.println("Too Many Listeners");
    System.exit(1);
    }
    catch (UnsupportedCommOperationException e) {
    System.err.println("Problem setting port parameters");
    System.exit(1);
    }
    }

    /**
    * This method loops forever, reading data from the
    * command line and writing it directly to the serial port.
    * No buffering is performed.
    */
    public void run() {

    try {
    while (true) {

    out.write(message.getBytes());

    }
    }
    catch (IOException e) {
    // Terminate thread
    }

    }

    /**
    * Process serial port events. This method is required
    * when implementing SerialPortEventListener
    *
    * @param event SerialPortEvent object to process
    */
    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:
    // If there is data available on serial port,
    // read it in in chunks <=20 bytes
    //
    byte[] readBuffer = new byte[1];
    try {
    while (in.available() > 0) {
    int numBytes = in.read(readBuffer);

    }

    System.out.print(new String(readBuffer));

    }
    catch (IOException e) {
    // Terminate handling this event on read error
    }
    break;
    default:
    System.out.print("Unknown SerialPortEvent type = " +
    event.getEventType());
    break;
    }
    }
    }
    Questi i threads che eclipse in fase di debug mi elenca:
    Thread [Win32SerialPort Notification thread] (in esecuzione)
    Thread [DestroyJavaVM] (in esecuzione)
    Thread [Thread-0] (in esecuzione)
    A presto e grazie!
    riccardo

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 © 2024 vBulletin Solutions, Inc. All rights reserved.