Boa tarde!
Estou tendo dificuldades em trabalhar com a porta serial, meu problema é o seguinte:
Não sei como fazer pra identificar o termino da transmissão de dados. Tentei de algumas formas, mas sem sucesso. Caso alguém poder ajudar, agradeço.
Obs.:
Segue código abaixo.
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.TooManyListenersException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.swing.JOptionPane;
public class MainClass implements Runnable, SerialPortEventListener {
static CommPortIdentifier portId;
static Enumeration portList;
InputStream inputStream;
SerialPort serialPort;
Thread readThread;
int i = 0;
public String Dadoslidos;
private Connection conn;
private PreparedStatement prepared;
private String sSql;
Frame frame = new Frame();
public static void main(String[] args) {
Frame frame = new Frame();
portList = CommPortIdentifier.getPortIdentifiers();
while (portList.hasMoreElements()) {
portId = (CommPortIdentifier) portList.nextElement();
if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
if (portId.getName().equals("COM1")) {
MainClass reader = new MainClass();
}
}
}
}
public MainClass() {
try {
serialPort = (SerialPort) portId.open("MainClassApp", 2000);
} catch (PortInUseException e) {
JOptionPane.showMessageDialog(null,"A porta já está sendo usada! " + e);
}
try {
inputStream = serialPort.getInputStream();
} catch (IOException e) {
JOptionPane.showMessageDialog(null,"Falha ou Interrupção de E / S! " + e);
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,"Erro.STATUS: " + e);
System.exit(1);
}
try {
serialPort.addEventListener(this);
} catch (TooManyListenersException e) {
}
catch (Exception e) {
JOptionPane.showMessageDialog(null,"Erro ao criar listener. STATUS: " + e);
System.exit(1);
}
serialPort.notifyOnDataAvailable(true);
try {
serialPort.setSerialPortParams(4800, SerialPort.DATABITS_8, SerialPort.STOPBITS_1, SerialPort.PARITY_NONE);
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Erro ao abrir a porta! STATUS: " + e );
}
readThread = new Thread(this);
readThread.start();
}
public void run() {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
JOptionPane.showMessageDialog(null,"Thread Interrompida: " + 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:
break;
case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
JOptionPane.showMessageDialog(null, "Passou");
AbrirConexao();
sSql = "Update Usu_T001Med Set Usu_QtdMed = " + Dadoslidos + " Where Usu_NumSer = '441'";
try {
prepared = conn.prepareStatement(sSql);
prepared.executeUpdate();
prepared.close();
} catch (SQLException e) {
JOptionPane.showMessageDialog(null, "Problemas ao Gravar Dados no Banco! " + e);
}
try {
prepared.close();
conn.close();
} catch (SQLException ex) {
Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
}
break;
case SerialPortEvent.DATA_AVAILABLE:
byte[] readBuffer = new byte[20];
try {
while (inputStream.available() > 0) {
int numBytes = inputStream.read(readBuffer);
Dadoslidos = new String(readBuffer);
// i ++;
// frame.teste.setText(Integer.toString(i));
Dadoslidos = Dadoslidos.replaceAll("\\D", "");
if(!Dadoslidos.equals("")){
frame.sQtdMed.setText(Dadoslidos);
}
}
if(inputStream.available() == 0) {
i = i +1;
frame.teste.setText(Integer.toString(i));
}else{
frame.teste.setText("teste");
}
}
catch (IOException e) {
}
break;
}
Object obj;
try {
obj = inputStream.available();
frame.sEvento.setText(obj.toString());
} catch (IOException ex) {
Logger.getLogger(MainClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void AbrirConexao(){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@DELL:1521:dbprod", "sapiens_novo", "sapiens_novo");
}
catch(ClassNotFoundException erro)
{
JOptionPane.showMessageDialog(null,"Driver JDBC_ORACLE não encontrado! \n" + erro);
}
catch(SQLException erro)
{
JOptionPane.showMessageDialog(null,"Problemas na conexão com o banco de dados. \n" + erro);
}
}
}
Att,
Graziani Garcia