segunda-feira, 14 de fevereiro de 2011

Criando uma conexão com uma portal serial

Criar um projeto com um nome qualquer, e depois criar um classe chamada SerialConnection.

import java.io.InputStream;
import java.io.OutputStream;
import javax.comm.CommDriver;
import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;

/**
 *
 * @author gilberto.masetto
 */
public class SerialConnection {

    private SerialPort porta;
    private InputStream in;
    private OutputStream out;
    public static final int VELOCIDADE_PADRAO = 9600;
    public static final int BITS_DADOS_PADRAO = SerialPort.DATABITS_8;
    public static final int BITS_PARADA_PADRAO = SerialPort.STOPBITS_2;
    public static final int PARIDADE_PADRAO = SerialPort.PARITY_NONE;
    public static final int TIMEOUT_PADRAO = 1000;
    public static final String PORTA_PADRAO_WINDOWS = "COM1";


    //Construtor que inicializa com a porta setada
    public void openCommunication() throws Exception {
        try {
            //Acessa a lib comm.jar que fica dentro do JDK 1.6
            String driverName = "com.sun.comm.Win32Driver";
            //Cria uma instância
            CommDriver commDriver = (CommDriver) Class.forName(driverName).newInstance();
            synchronized (commDriver) {
                //Inicializa o driver e abre e cria a conexão com a porta
                commDriver.initialize();
                porta = (SerialPort) commDriver.getCommPort(PORTA_PADRAO_WINDOWS, CommPortIdentifier.PORT_SERIAL);
            }
            setParameters(VELOCIDADE_PADRAO, BITS_DADOS_PADRAO, BITS_PARADA_PADRAO, PARIDADE_PADRAO);
            //Entrada de dados
            in = porta.getInputStream();
            //Saída de dados
            out = porta.getOutputStream();
        } catch (PortInUseException e) {
            throw new Exception("A porta " + PORTA_PADRAO_WINDOWS + " está em uso", e);
        } catch (Exception e) {
            throw new Exception("Porta não encontrada " + PORTA_PADRAO_WINDOWS, e);
        }
    }

    //Verifica se está conectado
    public boolean isConnected() {
        if (porta != null) {
            return true;
        } else {
            return false;
        }
    }

    //Desconecta
    public void disconect() throws Exception {
        if (isConnected()) {
            closeCommunication();
        }
    }

    public void setParameters(int velocidade, int dados, int parada, int paridade) throws Exception {
        try {
            porta.setSerialPortParams(velocidade, dados, parada, paridade);
        } catch (Exception e) {
            throw new Exception("Operação não suportada", e);
        }
    }

  
    public void closeCommunication() throws Exception {
        try {
            if (in != null) {
                in.close();
            }
            if (out != null) {
                out.close();
            }
            if (porta != null) {
                porta.close();
            }
        } catch (Exception e) {
            throw new Exception("Erro ao fechar porta", e);
        }
    }
}

Nenhum comentário:

Postar um comentário