RXTX: balance serial port connection

3

I'm trying to take the weight off the scale, but I can not find success in this battle.

As you can see the connection to the SERIAL port (actually it's USB) everything is ok:

Stable Library
=========================================
Native lib Version = RXTX-2.1-7
Java lib Version = RXTX-2.1-7

Manual can be found at this link: manual , which says:

  

Protocol used: 9600bps rate, 8 data bits, no parity, 2 stop bits.

The classes I'm using are:

  • SerialCom :
import gnu.io.CommPortIdentifier;
import java.util.Enumeration;

/**
 *
 * @author DexBook
 */
public class SerialCom {

    protected String[] portas;

    protected Enumeration listaDePortas;

    public SerialCom() {
        listaDePortas = CommPortIdentifier.getPortIdentifiers();
    }

    public String[] ObterPortas() {
        return portas;
    }

    protected String[] ListarPortas() {
        int i = 0;

        portas = new String[10];

        while (listaDePortas.hasMoreElements()) {

            CommPortIdentifier ips =

            (CommPortIdentifier) listaDePortas.nextElement();

            portas = ips.getName();

            i++;
        }

        return portas;
    }

    public boolean PortaExiste(String COMp) {
        String temp;

        boolean e = false;

        while (listaDePortas.hasMoreElements()) {
            CommPortIdentifier ips = (CommPortIdentifier) listaDePortas.nextElement();

            temp = ips.getName();

            if (temp.equals(COMp) == true) {
                e = true;
            }

        }

        return e;
    }

}
  • SerialComLeitura :
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 *
 * @author DexBook
 */
public class SerialComLeitura implements Runnable, SerialPortEventListener {

    public String Dadoslidos;

    public int nodeBytes;

    private int baudrate;

    private int timeout;

    private CommPortIdentifier cp;

    private SerialPort porta;

    private OutputStream saida;

    private InputStream entrada;

    private Thread threadLeitura;

    private boolean IDPortaOK;

    private boolean PortaOK;

    private boolean Leitura;

    private boolean Escrita;

    private String Porta;

    protected String peso;

    public void setPeso(String peso) {

        this.peso = peso;

    }

    public String getPeso() {
        return peso;
    }

    public SerialComLeitura(String p, int b, int t) {
        this.Porta = p;

        this.baudrate = b;

        this.timeout = t;
    }

    public void HabilitarEscrita() {
        Escrita = true;

        Leitura = false;
    }

    public void HabilitarLeitura() {
        Escrita = false;

        Leitura = true;
    }

    public void ObterIdDaPorta() {
        try {
            cp = CommPortIdentifier.getPortIdentifier(Porta);

            if (cp == null) {

                System.out.println("Erro na porta");

                IDPortaOK = false;

                System.exit(1);

            }
            IDPortaOK = true;
        } catch (Exception e) {
            System.out.println("Erro obtendo ID da porta: " + e);

            IDPortaOK = false;

            System.exit(1);
        }
    }

    public void AbrirPorta() {
        try {
            porta = (SerialPort) cp.open("SerialComLeitura", timeout);

            PortaOK = true;

            // configurar parâmetros

            porta.setSerialPortParams(baudrate,

            porta.DATABITS_8, porta.STOPBITS_2, porta.PARITY_NONE);

            porta.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);

            System.out.println("Porta " + Porta + " aberta!");
        } catch (Exception e) {
            PortaOK = false;

            System.out.println("Erro abrindo comunicação: " + e);

            System.exit(1);
        }
    }

    public void LerDados() {
        if (Escrita == false) {
            try {
                entrada = porta.getInputStream();
            } catch (Exception e) {
                System.out.println("Erro de stream: " + e);

                System.exit(1);
            }
            try {
                porta.addEventListener(this);
            } catch (Exception e) {
                System.out.println("Erro de listener: " + e);

                System.exit(1);
            }
            porta.notifyOnDataAvailable(true);

            try {
                threadLeitura = new Thread(this);

                threadLeitura.start();

                run();
            } catch (Exception e) {
                System.out.println("Erro de Thred: " + e);
            }
        }
    }

    public void EnviarUmaString(String msg) {
        if (Escrita == true) {
            try {
                saida = porta.getOutputStream();

                System.out.println("FLUXO OK!");
            } catch (Exception e) {

                System.out.println("Erro.STATUS: " + e);
            }

            try {
                System.out.println("Enviando um byte para " + Porta);

                System.out.println("Enviando : " + msg);

                saida.write(msg.getBytes());

                Thread.sleep(100);

                saida.flush();
            } catch (Exception e) {
                System.out.println("Houve um erro durante o envio. ");

                System.out.println("STATUS: " + e);

                System.exit(1);
            }
        } else {
            System.exit(1);
        }
    }

    public void run() {
        try {
            Thread.sleep(5);
        } catch (Exception e) {
            System.out.println("Erro de Thred: " + e);
        }
    }

    // Essa procedure pode conter incompatibilidades, qualquer problema rever.

    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:

            // Novo algoritmo de leitura.

            while (novoDado != -1) {
                try {
                    novoDado = entrada.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);
                }

            }

            setPeso(new String(bufferLeitura));

            System.out.println("Peso: " + getPeso());

            break;
        }

    }

    public void FecharCom() {
        try {
            porta.close();
        } catch (Exception e) {
            System.out.println("Erro fechando porta: " + e);

            System.exit(0);
        }

    }

    public String obterPorta() {
        return Porta;
    }

    public int obterBaudrate() {
        return baudrate;
    }

}
  • TCC_Serial :
public class TCC_Serial extends SerialCom {

    /**
     * @param args
     *            the command line arguments
     */
    public static void main(String[] args) {

        SerialComLeitura leitura = new SerialComLeitura("COM3", 9600, 500);

        // Iniciando leitura serial

        leitura.HabilitarEscrita();

        leitura.ObterIdDaPorta();

        leitura.AbrirPorta();

        leitura.EnviarUmaString("0x04");

        leitura.HabilitarLeitura();

        leitura.ObterIdDaPorta();

        leitura.LerDados();

        // Controle de tempo da leitura aberta na serial

        try {

            Thread.sleep(1000);

        } catch (InterruptedException ex) {

            System.out.println("Erro na Thread: " + ex);

        }

        leitura.FecharCom();

    }

}

In the manual says:

  

Sending a command character (04 in hexadecimal).

In class TCC_Serial I put:

leitura.EnviarUmaString("04");

leitura.EnviarUmaString("4");

leitura.EnviarUmaString("0x04");

When I run the program it appears:

Stable Library
=========================================
Native lib Version = RXTX-2.1-7
Java lib Version = RXTX-2.1-7
Porta COM3 aberta!
FLUXO OK!
Enviando um byte para COM3
Enviando : 0x04

It does not give an error, it does not give anything, and it does not return the weight of the scale.

Can anyone give me a light? Because I really can not imagine what can be the problem.

+++++++++++++++++++++++++++++++++++++++++++++++ ++++++++++++++++++++++++++++ with JSSC java

SerialPort serialPort = new SerialPort ("COM3");         try {             System.out.println ("Port opened:" + serialPort.openPort ());             System.out.println ("Params setted:" + serialPort.setParams (9600, 8, 2, 0));             System.out.println ("successfully writen to port:" + serialPort.writeBytes ("0x04" .getBytes ()));             byte [] buffer = serialPort.readBytes (46) // Read 10 bytes from serial port

        System.out.println(buffer.length);

        for (int i = 0; i < buffer.length; i++) {
            System.out.println(buffer[i]);
        }

        System.out.println("Port closed: " + serialPort.closePort());
    } catch (SerialPortException ex) {
        System.out.println(ex);
    }

It returns

run: COM3 Port opened: true Params setted: true successfully writen to port: true 46 112 -10 64 2 -120 -65 -58 1 -112 -65 -58 1 24 32 -93 20 -40 31 -93 20 0 -68 -58 1 0 0 0 0 -44 21 -28 111 20 0 0 0 -4 -10 64 2 32 -9 116 106 0 -68 Port closed: true

    
asked by anonymous 21.08.2015 / 12:54

3 answers

2

The problem is occurring, as it is sending a set of bytes to the scale that does not match the expected hexadecimal character.

This is being done:

leitura.EnviarUmaString("0x04");

Within the SendUmaString method this is happening:

saida.write(msg.getBytes());

Where msg is the message passed as parameter and output is an OutputStream.

Anyway, what is being sent is the bytes of the 0x04 string. This is not a hexadecimal. Basically, instead of sending 1 byte as expected, 4 bytes are being sent.

to solve do so:

saida.write(new byte[]{0x04});
    
21.08.2015 / 13:36
1

My friend, I also use RXTX for communication and I can extract information from the hour scale by returning different characters and time returning the weight.

There are two issues that I have come up with:

1st - Return of special characters: I have already checked all configuration data like speed, parity among others that may be the cause of the error but are all correct and time returns these characters differently.

2nd - The balance has to be in the intermittent sending information configuration so it will keep sending the weight while the communication with it is open, how do I extract the weight and stop communication.

    
31.05.2016 / 16:34
0

Thanks @cantoni I got thanks to your tips ...

If anyone needs to:

*  * To change this license header, choose License Headers in Project Properties.  * To change this template file, choose Tools | Templates  * and open the template in the editor.  * /

/ **  *  * @author DexBook  * /

import java.io.UnsupportedEncodingException;

import jssc.SerialPort;

import jssc.SerialPortException;

import jssc.SerialPortList;

public class Main {

public static void main(String[] args) throws UnsupportedEncodingException {
    String[] portNames = SerialPortList.getPortNames();
    for (String portName : portNames) {
        System.out.println(portName);
    }

    SerialPort serialPort = new SerialPort("COM3");
    try {
        System.out.println("Port opened: " + serialPort.openPort());
        System.out.println("Params setted: " + serialPort.setParams(9600, 8, 2, 0));
        System.out.println("successfully writen to port: " + serialPort.writeBytes(new byte[]{0x04}));
        byte[] buffer = serialPort.readBytes(46);//Read 10 bytes from serial port
        System.out.println(new String(buffer));
        System.out.println("Port closed: " + serialPort.closePort());
    } catch (SerialPortException ex) {
        System.out.println(ex);
    }

}

}

    
22.08.2015 / 16:55