Duvidas com relação a porta serial

2 respostas
GraGarcia

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

2 Respostas

E

Bem-vindo ao mundo da transmissão serial de dados!
De fato, o “término da transmissão” depende do equipamento com o qual você está se comunicando.
Para alguns equipamentos, é necessário criar uma máquina de estados e um timer que você deixa configurado para disparar algum tempo depois de você receber o último byte.
Se depois do último byte não chegar mais nada dentro de algum tempo, muitas vezes isso é um “término de transmissão”.
Para outros equipamentos, o “término da transmissão” é o recebimento de um determinado byte, definido pelo engenheiro que projetou o tal do equipamento.
Às vezes é um pino ou um sinal na serial que define isso (procure por “flow control” ou “controle de fluxo”).

Ou seja: você precisa conhecer o equipamento ao qual você vai se conectar. Cada bicho funciona de um jeito, e pior, pode ser que ele funcione de jeitos diferentes de acordo com alguma configuração (por exemplo, algum switch que você tem de ligar ou desligar no equipamento).

GraGarcia

entanglement, bom dia!

Muito obrigado pelo retorno.

 O equipamento que estou tentando integrar, é um medidor de vazão, diante do que você me respondeu, estarei pesquisando mais sobre e realizar novos testes.

Att,
Graziani Garcia

Criado 5 de julho de 2013
Ultima resposta 6 de jul. de 2013
Respostas 2
Participantes 2