Como ler dados em uma porta serial usando JavaCom?

3 respostas
P

Pessoal eu estou implementando um protocolo de comunicação serial e estou enviando para porta serial com3 uma array de bytes fazendo assim:

SerialCom vetor = new SerialCom(); if ( vetor.PortaExiste("COM3") == true) { System.out.println("Iniciando comunicação!"); SCom sc = new SCom("COM3",9600,2000); sc.HabilitarEscrita(); sc.ObterIdDaPorta(); sc.AbrirPorta(); sc.EnviarUmArrayBytes(Pacote.pacote); sc.FecharCom();

E para ler os dados da porta eu estou fazendo:

SerialCom st2 = new SerialCom(); if ( st2.PortaExiste("COM4") == true) { System.out.println("Iniciando comunicação!"); SCom sc2 = new SCom("COM4",9600,2000); sc2.HabilitarLeitura(); sc2.ObterIdDaPorta(); sc2.AbrirPorta(); sc2.LerDados(); System.out.println(sc2.entrada); sc2.FecharCom(); }

Se precisarem das classes que usei eu coloco aqui tb…

O meu problema é que quando mando imprimir oque foi lido aparece NULL no console… abaixo temos o método LERDADOS

public void LerDados(){ if (Escrita == true){ try { entrada = porta.getInputStream(); System.out.println("FLUXO OK!"); } catch (Exception e) { System.out.println("Erro.STATUS: " + e ); System.exit(1); } try { porta.addEventListener(this); System.out.println("SUCESSO. Porta aguardando..."); } catch (Exception e) { System.out.println("Erro ao criar listener: "); System.out.println("STATUS: " + e); System.exit(1); } porta.notifyOnDataAvailable(true); try { threadLeitura = new Thread(this); threadLeitura.start(); } catch (Exception e) { System.out.println("Erro ao iniciar leitura: " + e ); } } }

Como faço pra ler a array de byte que enviei?

3 Respostas

M

onde você imprime o inputStream ? você abre um input mais não mostra ele ?

segue um exemplo.. mais aqui utilizo Sockets.

Classe CLIENTE.

recebe um array de bytes do servidor e mostra em tela.

package SocketTes;

import java.io.IOException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;

public class Client {

	public static void main(String[] args) throws UnknownHostException,
			IOException {

		String mensageEnviada;
		byte[] buffer = new byte[2048];

		Socket client = new Socket("127.0.0.1", 12345);
		System.out.println(" O cliente se conectou ao servidor!");

		InputStream doServidor = client.getInputStream(); // abre Input
		OutputStream paraServidor = client.getOutputStream();

		Scanner teclado = new Scanner(System.in);
		while (teclado.hasNext()) {
			

			mensageEnviada = teclado.next();
			buffer = mensageEnviada.getBytes();
			paraServidor.write(buffer);
			doServidor.read(buffer); // Lê input
			System.out.println(buffer);

		}

		// saida.close();
		teclado.close();
		client.close();
		System.exit(1);
	}

}
M

corrigindo

System.out.println("Segundo Buffer: " + doServidor.read(buffer));
M
public class ImpressaoBytes {
    public static void main(String[] args) {
        System.out.println(paraStringHexa(
            new byte[] { 0x0F, 0x7f, 0x3d, 0x00, -0x23 }));
    }

    private static String paraStringHexa(byte[] bytes) {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            int parteAlta = ((bytes[i] >> 4) & 0xf) << 4;
            int parteBaixa = bytes[i] & 0xf;
            if (parteAlta == 0) s.append('0');
            s.append(Integer.toHexString(parteAlta | parteBaixa));
        }
        return s.toString();
    }
}
Criado 15 de fevereiro de 2012
Ultima resposta 16 de fev. de 2012
Respostas 3
Participantes 2