Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java: Общие вопросы > Как переделать?


Автор: barin_Student 21.1.2008, 08:14
Есть примеры работы с com портом и библиотекой javax.comm , вот как их запустить , точнее вот что надо:
SimpleRead:
Код


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 = "/dev/term/a";

    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:
        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;
    }
    } 

}

SimpeWrite:
Код


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

/**
 * Class declaration
 *
 *
 * @author
 * @version 1.10, 08/04/00
 */
public class SimpleWrite {
    static Enumeration        portList;
    static CommPortIdentifier portId;
    static String         messageString = "Hello, world!";
    static SerialPort         serialPort;
    static OutputStream       outputStream;
    static boolean        outputBufferEmptyFlag = false;
    /**
     * Method declaration
     *
     *
     * @param args
     *
     * @see
     */
    public static void main(String[] args) {
    boolean portFound = false;
    String  defaultPort = "/dev/term/a";

    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;

            try {
            serialPort = 
                (SerialPort) portId.open("SimpleWrite", 2000);
            } catch (PortInUseException e) {
            System.out.println("Port in use.");

            continue;
            } 

            try {
            outputStream = serialPort.getOutputStream();
            } catch (IOException e) {}

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

            try {
                serialPort.notifyOnOutputEmpty(true);
            } catch (Exception e) {
            System.out.println("Error setting event notification");
            System.out.println(e.toString());
            System.exit(-1);
            }
            
            
            System.out.println(
                "Writing \""+messageString+"\" to "
            +serialPort.getName());

            try {
            outputStream.write(messageString.getBytes());
            } catch (IOException e) {}

            try {
               Thread.sleep(2000);  // Be sure data is xferred before closing
            } catch (Exception e) {}
            serialPort.close();
            System.exit(1);
        } 
        } 
    } 

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


}

Убираю main , ставлю просто метод и создаю main class сам в своем проекте, все это делается , что получилась писалка - читалка , но ничаго не выходит..  как мне правильно эти классы вывести из main , чтоб мне можно было правильно оперировать в своем main?

Добавлено через 6 минут и 57 секунд
Мне бы просто самый простой пример составили , отправил сообщение на com , и просчитал ответ, был бы неимоверно благодарен...
 smile 

Автор: barin_Student 21.1.2008, 13:15
Раз нет ответов , то не хочу создавать новую тему , похожую , вопрос еще один будет...
Почему вылазиет ошибка и как лечится :

Parport PPClaim : Bad file descriptor


Exception in "main" java.lang.RuntimeException:
   Error opening "/dev/parport1"
   Permission denied
       ------
и тд , указывается бла бла бла....
вот этот класс запускаю:
Код


/*
 * Main.java
 *
 * Created on January 3, 2008, 4:27 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

//package google;

/**
 *
 * @author student
 */
import javax.comm.*;
import java.util.Enumeration;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.IOException;

public class Owner {
    static CommPortIdentifier portId;
    static Enumeration        portList;
    InputStream           inputStream;
    SerialPort            serialPort;
    Thread            readThread;
    private int                timeOut   = 1500;
    private int                baud      = 115200;
    public static final int    BUFF_SIZE = 256;
    //private CommPortIdentifier portId = null;
    private SerialPort         port   = null;

    //private InputStream        inputStream;
    private OutputStream       outputStream;

    /** Creates a new instance of Main */
   /* private void init(int port)
    {
        if((port<1)||(port>16))
        {
            System.err.println("Port with this number COM"+port); 
            portId=null; 
            return;
        }
        try
        {
            portId = CommPortIdentifier.getPortIdentifier("COM"+port);
        }catch (NoSuchPortException e)
        {
            System.err.println("No such port: COM"+port); 
            portId=null; 
        }
    }*/
    public void make()
    {
        String defaultPort ="/dev/ttyS1";
        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);
        } 
        } 
    } 
        try {
        port = (SerialPort) portId.open("OwnerApp", 2000);
    } catch (PortInUseException e) {}
        try
        {
            inputStream  = port.getInputStream();
        } 
        catch (IOException e)
        {
            e.printStackTrace();
        }
        try
        {
            outputStream = port.getOutputStream();
        }
        catch (IOException e)
        {
            e.printStackTrace(); 
        }
        try
        {
            Thread.sleep(500);
        } 
        catch(InterruptedException e){}
    }
    synchronized public void Write()
    {
        try
        {
            outputStream.write("at+csca?".getBytes());
            outputStream.flush();
        }
        catch (IOException e)
        {
            e.printStackTrace(); 
        }
    }
    synchronized public void Read()
    {
        byte[] bytes;
        bytes=null;
        int rez;
        try  
        {
            rez=inputStream.read(bytes);
            while (rez!=-1)
            {
                System.out.print(new String(bytes));
                rez=inputStream.read(bytes);
                
            }
            
        }
        catch (IOException e)
        {
            rez=-1; 
            e.printStackTrace();
        }
    }
    public Owner() {
       this.make();
        this.Write();
        this.Read();
       
    }
    
    /**
     * @param args the command line arguments
     */
    public static void go()
    {
        new Owner();
        
    }
    public static void main(String[] args) 
    {
       go();
        // TODO code application logic here
    }
    
}



Автор: LSD 21.1.2008, 13:32
Цитата(barin_Student @  21.1.2008,  13:15 Найти цитируемый пост)
Почему вылазиет ошибка и как лечится :

Попробуй запустить от root-а.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)