javaserial-portread-writerxtxcrc64

Read and Write from serial port gives "OUTPUT_BUFFER_EMPTY" (maybe crc calc and checksum is not correct)


I can not figure out where I may have been wrong and what to change to make this program able to communicate with the card both for reading and writing.

This is the serial protocol, the general structure of the frame is as follows:

LEN----------------->total number of frame characters

IND------------------>Indicator

ADDR_ST--------->station address

COD _OP--------->operation code

ADDR_DAT------->given address

NR_DATI---------->operation data number

DATI---------------->write operation data

CRC---------------->Check checksums

This is the frame that i send through the serial port:

byte miastringa[]={0x08,0x3f,0x00,0x42,0x00,0x01,0,cks};

This is the Code:

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
//import javax.comm.*; // for SUN's serial/parallel port libraries
import gnu.io.*; // for rxtxSerial library

public class WriteReadSerialPort implements Runnable, SerialPortEventListener {
   static CommPortIdentifier portId;
   static CommPortIdentifier saveportId;
   static Enumeration        portList;
   InputStream           inputStream;
   SerialPort           serialPort;
   Thread           readThread;

byte cks= 0;
byte i;
byte cnt=0;
   byte miastringa[]={0x08,0x3f,0x00,0x42,0x00,0x01,0,cks}; 

   String  messageString ="0";

   static OutputStream      outputStream;
   static boolean        outputBufferEmptyFlag = false;

   public static void main(String[] args) {
      boolean           portFound = false;
      String           defaultPort;

      // determine the name of the serial port on several operating systems
      String osname = System.getProperty("os.name","").toLowerCase();
      if ( osname.startsWith("windows") ) {
         // windows
         defaultPort = "COM8";
      } else if (osname.startsWith("linux")) {
         // linux
        defaultPort = "/dev/ttyS0";
      } else if ( osname.startsWith("mac") ) {
         // mac
         defaultPort = "????";
      } else {
         System.out.println("Sorry, your operating system is not supported");
         return;
      }

      if (args.length > 0) {
         defaultPort = args[0];
      } 

      System.out.println("Set default port to "+defaultPort);

        // parse ports and if the default port is found, initialized the reader
      portList = CommPortIdentifier.getPortIdentifiers();
      while (portList.hasMoreElements()) {
         portId = (CommPortIdentifier) portList.nextElement();
         if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            if (portId.getName().equals(defaultPort)) {
               System.out.println("Found port: "+defaultPort);
               portFound = true;
               // init reader thread
               WriteReadSerialPort reader = new WriteReadSerialPort();
            } 
         } 

      } 
      if (!portFound) {
         System.out.println("port " + defaultPort + " not found.");
      } 

   } 

   public void initwritetoport() {
      // initwritetoport() assumes that the port has already been opened and
      //    initialized by "public WriteReadSerialPort()"

      try {
         // get the outputstream
         outputStream = serialPort.getOutputStream();
      } catch (IOException e) {}

      try {
         // activate the OUTPUT_BUFFER_EMPTY notifier
         serialPort.notifyOnOutputEmpty(true);
      } catch (Exception e) {
         System.out.println("Error setting event notification");
         System.out.println(e.toString());
         System.exit(-1);
      }

   }

   public void writetoport() {
      System.out.println("Writing \""+messageString+"\" to "+serialPort.getName());
      try {
         // write string to serial port

           char[] crc_tab ={
                   0, 94, 188, 226, 97, 63, 221, 131, 194, 156, 126, 32, 163, 253, 31, 65,
                   157, 195, 33, 127, 252, 162, 64, 30, 95, 1, 227, 189, 62, 96, 130, 220,
                   35, 125, 159, 193, 66, 28, 254, 160, 225, 191, 93, 3, 128, 222, 60, 98,
                   190, 224, 2, 92, 223, 129, 99, 61, 124, 34, 192, 158, 29, 67, 161, 255,
                   70, 24, 250, 164, 39, 121, 155, 197, 132, 218, 56, 102, 229, 187, 89, 7,
                   219, 133, 103, 57, 186, 228, 6, 88, 25, 71, 165, 251, 120, 38, 196, 154,
                   101, 59, 217, 135, 4, 90, 184, 230, 167, 249, 27, 69, 198, 152, 122, 36,
                   248, 166, 68, 26, 153, 199, 37, 123, 58, 100, 134, 216, 91, 5, 231, 185,
                   140, 210, 48, 110, 237, 179, 81, 15, 78, 16, 242, 172, 47, 113, 147, 205,
                   17, 79, 173, 243, 112, 46, 204, 146, 211, 141, 111, 49, 178, 236, 14, 80,
                   175, 241, 19, 77, 206, 144, 114, 44, 109, 51, 209, 143, 12, 82, 176, 238,
                   50, 108, 142, 208, 83, 13, 239, 177, 240, 174, 76, 18, 145, 207, 45, 115,
                   202, 148, 118, 40, 171, 245, 23, 73, 8, 86, 180, 234, 105, 55, 213, 139,
                   87, 9, 235, 181, 54, 104, 138, 212, 149, 203, 41, 119, 244, 170, 72, 22,
                   233, 183, 85, 11, 136, 214, 52, 106, 43, 117, 151, 201, 74, 20, 246, 168,
                   116, 42, 200, 150, 21, 75, 169, 247, 182, 232, 10, 84, 215, 137, 107, 53};


         //protocol

           for(i=0; i<miastringa.length  ; i++) {
                cks += crc_tab[cks ^ miastringa[i]];

                cks-=cks;   
            }
             System.out.println("cks : "+ cks);

        for(cnt=0; cnt<miastringa.length;cnt++) {

            //miastringa[cnt++]=cks;
           // miastringa[0]=cnt;            
           // miastringa[cnt]=0;

        }
        System.out.println("miastringa : "+ miastringa);       
        System.out.println("cnt : "+ cnt);

        outputStream.write(miastringa);

      } catch (IOException e) {}
   }

   public WriteReadSerialPort() {
      // initalize serial port
      try {
         serialPort = (SerialPort) portId.open("SimpleReadApp", 4000);
      } catch (PortInUseException e) {}

      try {
         inputStream = serialPort.getInputStream();
      } catch (IOException e) {}

      try {
         serialPort.addEventListener(this);
      } catch (TooManyListenersException e) {}

      // activate the DATA_AVAILABLE notifier
      serialPort.notifyOnDataAvailable(true);

      try {
         // set port parameters
         serialPort.setSerialPortParams(19200, SerialPort.DATABITS_8, 
                     SerialPort.STOPBITS_1, 
                     SerialPort.PARITY_NONE);
      } catch (UnsupportedCommOperationException e) {}

      // start the read thread
      readThread = new Thread(this);
      readThread.start();

   }

   public void run() {
      // first thing in the thread, we initialize the write operation
      initwritetoport();
      try {
         while (true) {
            // write string to port, the serialEvent will read it
            writetoport();
            Thread.sleep(1000);
         }
      } catch (InterruptedException e) {}
   } 


   public void serialEvent(SerialPortEvent event) {
       System.out.println(".............."+event.getEventType());
      switch (event.getEventType()) {
      case SerialPortEvent.BI:
          System.out.println("BI");
      case SerialPortEvent.OE:
          System.out.println("OE");
      case SerialPortEvent.FE:
          System.out.println("FE");
      case SerialPortEvent.PE:
          System.out.println("PE");
      case SerialPortEvent.CD:
          System.out.println("CD");
      case SerialPortEvent.CTS:
          System.out.println("CTS");
      case SerialPortEvent.DSR:
          System.out.println("DSR");
      case SerialPortEvent.RI:
          System.out.println("RI");
      case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
          System.out.println("OUTPUT_BUFFER_EMPTY");
       break;
      case SerialPortEvent.DATA_AVAILABLE:
         // we get here if data has been received
         byte[] readBuffer = new byte[20];
         try {
            // read data
            while (inputStream.available() > 0) {
               int numBytes = inputStream.read(readBuffer);
            } 
            // print data
            String result  = new String(readBuffer);
            System.out.println("Read: "+result);
         } catch (IOException e) {}

         break;
      }
   }

The Console Log gives me this error:

Writing "0" to //./COM8

cks : 0

miastringa : [B@32cff37c

cnt : 8

..............2

OUTPUT_BUFFER_EMPTY

Thanks for the suggestions that will come


Solution

  • I've got a similar issue, you have to split the string into multiple parts and scroll through them in my case the following code worked:

    Thread thread = new Thread() {
    
        @Override
        public void run() {
    
    
    
            while (true) {
                byte miastringacopy[] = {0X07, 0x3f, 0x01, 'b', 0x00, 0x08, 0x4f};
                byte miastringa1copy[] = {0X07, 0x3f, 0x01, 'b', 0x01, 0x08, 0x4e};
                byte miastringa2copy[] = {0X07, 0x3f, 0x01, 'b', 0x02, 0x08, 0x4d};
                byte miastringa3copy[] = {0X07, 0x3f, 0x01, 'b', 0x03, 0x08, 0x4c};
    
                if (co == 4) {
    
                    co = 0;
    
    
                    miastringa = miastringacopy;
                    miastringa1 = miastringa1copy;
                    miastringa2 = miastringa2copy;
                    miastringa3 = miastringa3copy;
                }
    
    
    
                try {
                    writeport();
                    Thread.sleep(100);
                    co++;
    
    
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
    
    
            }
    
        }
    };
    
    
    UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
            @Override
            public void onReceivedData(byte[] readbuffer) {
                // Get the port input stream.
    
            byte readbuffer2[];
            readbuffer2 = new byte[20];
    
            // read data
            int numBytes = readbuffer.length;
            if(numBytes>=15) {
    
    
                for (i = 0; i < readbuffer.length; i++) {
                    readbuffer2[i] = readbuffer[i];
    
                }
                if (co == 0) {
    
                    for (i = 0; i < 8; i++) {
                        outputBuffer1[i] = readbuffer2[i + 6];
    
                    }
    
                }
    
                if (co == 1) {
                    for (i = 0; i < 8; i++) {
                        outputBuffer1[i + 8] = readbuffer2[i + 6];
    
                    }
    
    
                }
    
    
                if (co == 2) {
                    for (i = 0; i < 8; i++) {
                        outputBuffer2[i] = readbuffer2[i + 6];
    
                    }
    
    
                }
    
                if (co == 3) {
    
                    for (i = 0; i < 8; i++) {
                        outputBuffer2[i + 8] = readbuffer2[i + 6];
    
                    }
    
    
                }