Pessoal,
Eu já lí os tutoriais aqui do fórum e até encontrei uma implementação de diz atender o que eu preciso, mas não consegui fazer funcionar.
Tenho 2 sensores IV ligados através de um DB9 na minha COM1.
Verificando com o multimetro, percebí que quando os sensores são desalinhados (entenda como perda de sincronia) eu recebo 12v e quando estão alinhados -12v.
Eu estou tentando pegar o evento de quebra do sinal dos sensores, mas não estou conseguindo.
Será que alguém com alguma experiência poderia me ajudar?
Segue minha implementação que estou tentando usar:
package cc.marcio.serial.util;
import gnu.io.CommPort;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.TooManyListenersException;
/**
* <b>Description:</b><br /> TODO: Add here the class description
*
* @author <a href="mailto:marciobarroso@gmail.com">Márcio Alves Barroso</a>
* @author Generated by <a href="http://jcodegen.sourceforge.net/">JCodeGen</a>
* @since 03/10/2008 15:50:53
* @version 0.1
*/
public class SerialUtil implements Runnable, SerialPortEventListener {
private Integer bitsPorSegundos;
private Integer timeout;
private InputStream inputStream;
private OutputStream outputStream;
private String portId;
private SerialPort serialPort;
private Thread threadReader;
public SerialUtil(String port) {
super();
this.portExists(port);
this.portId = port;
this.bitsPorSegundos = 9600;
this.timeout = 2000;
this.open();
}
public SerialUtil(String port, Integer baudrate, Integer timeout) {
this(port);
this.bitsPorSegundos = baudrate;
this.timeout = timeout;
}
public void portExists(String port) {
try {
if( port != null && !("").equals(port) ) {
CommPortIdentifier.getPortIdentifier(port);
} else {
throw new SerialException("Favor entrar um valor válido para a porta");
}
} catch (NoSuchPortException e) {
throw new SerialException("A porta informada não existe", e);
}
}
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
throw new SerialException("Erro ao tentar iniciar a comunicação.", e);
}
}
public void serialEvent(SerialPortEvent ev) {
StringBuffer bufferLeitura = new StringBuffer();
int novoDado = 0;
switch (ev.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:
while (novoDado != -1) {
try {
novoDado = inputStream.read();
if (novoDado == -1) {
break;
}
if ('\r' == (char) novoDado) {
bufferLeitura.append('\n');
} else {
bufferLeitura.append((char) novoDado);
}
} catch (IOException ioe) {
System.out.println("Erro de leitura serial: " + ioe);
}
}
break;
}
}
public void open() {
try {
CommPortIdentifier portIdentifier = CommPortIdentifier
.getPortIdentifier(this.portId);
if (portIdentifier.isCurrentlyOwned()) {
throw new SerialException("A porta já esta em uso.");
} else {
CommPort commPort = portIdentifier.open(this.getClass().getName(), this.timeout);
this.inputStream = commPort.getInputStream();
this.outputStream = commPort.getOutputStream();
if (commPort instanceof SerialPort) {
this.serialPort = (SerialPort) commPort;
this.serialPort.setSerialPortParams( this.bitsPorSegundos,
SerialPort.DATABITS_8,
SerialPort.STOPBITS_1,
SerialPort.PARITY_NONE);
this.serialPort.enableReceiveTimeout(500);
this.serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
this.serialPort.notifyOnDataAvailable(true);
} else {
throw new SerialException("Esta implementação suporta somente conexão com portas serial");
}
}
} catch (NoSuchPortException e) {
throw new SerialException("A porta " + this.portId + " não foi encontrada.", e);
} catch (PortInUseException e) {
throw new SerialException("A porta " + this.portId + " já está em uso.", e);
} catch (UnsupportedCommOperationException e) {
throw new SerialException("A porta " + this.portId + " não suporta esta operação", e);
} catch (IOException e) {
throw new SerialException("A porta " + this.portId + " não suporta esta operação", e);
}
}
public void close() {
try {
this.inputStream.close();
this.outputStream.close();
this.serialPort.close();
} catch (IOException e) {
throw new SerialException("Ocorreram problemas ao efetuar o fechamento da sessão.", e);
}
}
public void read() {
try {
this.inputStream = this.serialPort.getInputStream();
this.serialPort.addEventListener(this);
this.serialPort.notifyOnDataAvailable(true);
this.threadReader = new Thread(this);
this.threadReader.start();
this.run();
} catch (IOException e) {
throw new SerialException("Ocorreram problemas ao tentar ler a porta serial", e);
} catch (TooManyListenersException e) {
throw new SerialException("Ocorreram problemas ao tentar acessar os dados da porta serial", e);
}
}
public void write(String message) {
OutputStream os = null;
try {
os = this.serialPort.getOutputStream();
os.write(message.getBytes());
Thread.sleep(100);
os.flush();
} catch (IOException e) {
throw new SerialException("A porta " + this.portId + " não está acessível para escrita.", e);
} catch (InterruptedException e) {
throw new SerialException("A porta " + this.portId + " não foi encontrada.", e);
}
}
public void sms(String mensagem, String ... numeros) {
for( String numero : numeros ) {
this.write("AT" + (char)13);
this.write("AT+CMGF=1" + (char)13);
this.write("AT+CMGS=\"+" + numero + "\"" + (char)13);
this.write(this.trataMensagem(mensagem) + (char)26 + (char)13);
}
}
public String trataMensagem(String mensagem) {
StringBuffer msg = new StringBuffer();
for( int i=0; i < mensagem.length(); i++ ) {
msg.append((char)mensagem.codePointAt(i));
}
return msg.toString();
}
public static void main(String[] args) {
SerialUtil su = new SerialUtil("COM1");
su.read();
su.close();
}
}
Qualquer ajuda é benvinda.
[]'s