Results 1 to 16 of 16
  1. #1
    Roshani is offline Member
    Join Date
    Jul 2016
    Posts
    18
    Rep Power
    0

    Default JSSC serial port variable packet length problem

    Hi All !

    I am using JSSC serial port library .

    I am receiving serial data on event, packet length is fixed. Here is the event listener code which I am using & working perfect.


    Java Code:
     static class SerialPortReader implements SerialPortEventListener {
    
                            @Override
    		        public void serialEvent(SerialPortEvent event) {
    		          
    		        	
    		                if(event.getEventValue() == 26){//Check bytes count in the input buffer
    		                    //Read data, if 26 bytes available 
    		                    try {
    		                        byte buffer[] = serialPort.readBytes(26);
    		                        
    		                        //for (int i = 0; i < buffer.length; i++){
    		                        //	System.out.print(Character.toChars(buffer[i]));
    		                        // }
    		                        
    		                        try {
    									rxData = new String(buffer, "UTF-8");
    								
    								} catch (UnsupportedEncodingException e) {
    									// TODO Auto-generated catch block
    									e.printStackTrace();
    									System.out.print("could not convert string");
    								}  
    		                       
    		                       
    		                        
    		                       cnt++;
    		                       jLabel2.setText("Data: " + rxData + ", " + cnt);
    		                       
    		                      
    		                 
    		                        buffer = null;
    		                   
    		                    }
    		                    catch (SerialPortException ex) {
    		                        System.out.println(ex);
    		                    }
    		                }
    		            }
    		    	
    		        }

    Now I want to buffer receive data until "\n" new line received.

    I mean to say serial packet end with new line but packet length is variable, like this.

    "This is test string\n"

    or

    "This is my new string\n"

    Need Help.

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: JSSC serial port variable packet length problem

    Are you asking how to determine if the last character in a String is "\n"?
    See the String class for useful methods.
    If you don't understand my response, don't ignore it, ask a question.

  3. #3
    Roshani is offline Member
    Join Date
    Jul 2016
    Posts
    18
    Rep Power
    0

    Default Re: JSSC serial port variable packet length problem

    Yes,

    if the last character is new line then I can know string is complete.

    I tried with built in library below method, but could not get success.
    Java Code:
    rxData = serialPort.readString();
    string terminate with null char. If I change my hardware string data.

    If I add null char instead of new line ? currently my string data end with new line.

    Need help.

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: JSSC serial port variable packet length problem

    if the last character is new line then I can know string is complete.
    Can you explain what you want changed?

    add null char instead of new line ?
    Yes you can change the newline character to a null character (0). Why do you want to do that?
    If you don't understand my response, don't ignore it, ask a question.

  5. #5
    Roshani is offline Member
    Join Date
    Jul 2016
    Posts
    18
    Rep Power
    0

    Default Re: JSSC serial port variable packet length problem

    Dear Sir,

    I have implement my serial event code.

    I want to check new line character, if found it means packet is complete.

    Here is the serial event code. Working ok, no data is missing but processing is too much slow.

    Every second hardware is sending one packet, packet end with new line & size is 28 char.


    Java Code:
    static class SerialPortReader implements SerialPortEventListener {
            @Override
    	public void serialEvent(SerialPortEvent event) {
                    if (event.isRXCHAR() && event.getEventValue() > 0){
                        
                        try {
                            byte buffer[] = serialPort.readBytes(1);
                            byte b = buffer[0];
                            char c = (char)b;
                           // System.out.println(c);
                            rxData = rxData +c;
                            if (c == '\n'){
                                ok = true;
                                System.out.println(rxData);
                                cnt++;
                                jLabel2.setText("RxData:" + rxData + ", " + cnt);
                                
                                rxData = "";
                            }
                        } catch (SerialPortException ex) {
                            Logger.getLogger(MySerial.class.getName()).log(Level.SEVERE, null, ex);
                        }
                            
                        
                        
                        
                    
            }
    		    	
    	}
            }
    I am attaching one gif file, which will play my screen.
    Attached Thumbnails Attached Thumbnails JSSC serial port variable packet length problem-screen.gif  

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: JSSC serial port variable packet length problem

    Did you have a question now?
    If you don't understand my response, don't ignore it, ask a question.

  7. #7
    Roshani is offline Member
    Join Date
    Jul 2016
    Posts
    18
    Rep Power
    0

    Default Re: JSSC serial port variable packet length problem

    Sir,

    still have problem.

    I can receive one byte at a time & print it. It is working.

    I tried to receive one byte, append it in string, check if byte == newline then set flag

    working but processing is very slow.

    Although no character is missing, but it is due to buffer.

    As you can see in image data is appearing slow, it should be update in every second.

    I have put one second counter at the last of data.


    Need help to get byte, add it in string & if byte is new line then set flag.

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: JSSC serial port variable packet length problem

    Need help to get byte, add it in string & if byte is new line then set flag.
    The code in post#5 looks like it does that. What is wrong with that code?
    What is printed by the println on line 14? What was printed by the println statement on line 10?

    What package/class is the serialPort object?
    Last edited by Norm; 07-11-2016 at 02:47 PM.
    If you don't understand my response, don't ignore it, ask a question.

  9. #9
    Roshani is offline Member
    Join Date
    Jul 2016
    Posts
    18
    Rep Power
    0

    Default Re: JSSC serial port variable packet length problem

    Dear Sir,

    I am using JSSC.

    https://github.com/scream3r/java-sim...rial-connector

    https://code.google.com/archive/p/ja...ial-connector/

    as you you can see in my post#5 , see image.

    I have record this image in real time.

    one packet is coming in every second.

    packet length is approx 30 char including new line.


    every second i am updating my jlabel2, what i have received. But you can see this speed is not for 1 sec.

    That is my problem.

  10. #10
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: JSSC serial port variable packet length problem

    Sorry, I don't know anything about the third party package you are working with. Is there a forum for that package where you can ask questions about how it works?

    every second i am updating my jlabel2, what i have received. But you can see this speed is not for 1 sec.
    Can you change the code so it prints to the console and shows the value of System.currentTimeMillis()?
    Then copy the output and paste it here. I have no idea what the image you posted is supposed to show.
    Add some comments to the print out saying what is wrong with it and describe what you want to be different.
    If you don't understand my response, don't ignore it, ask a question.

  11. #11
    Roshani is offline Member
    Join Date
    Jul 2016
    Posts
    18
    Rep Power
    0

    Default Re: JSSC serial port variable packet length problem

    Dear Sir,

    Here is the modified code with as you wish.

    Java Code:
      static class SerialPortReader implements SerialPortEventListener {
            @Override
        public void serialEvent(SerialPortEvent event) {
                    if (event.isRXCHAR() && event.getEventValue() > 0){
                         
                        try {
                            byte buffer[] = serialPort.readBytes(1);
                            byte b = buffer[0];
                            char c = (char)b;
                           // System.out.println(c);
                            rxData = rxData +c;
                            if (c == '\n'){
                                ok = true;
                                System.out.println(rxData);
                                current = System.currentTimeMillis();
                             
                                if (old == 0){
                                    old = current;
                                }
                                if (current != old){
                                    System.out.println("Operation took " + (current - old) + " milliseconds.");
                                    old = current;
    
                                }
                                
                                cnt++;
                                jLabel2.setText("RxData:" + rxData + ", " + cnt);
                                 
                                rxData = "";
                            }
                        } catch (SerialPortException ex) {
                            Logger.getLogger(MySerial.class.getName()).log(Level.SEVERE, null, ex);
                        }
                             
                     
            }
                     
        }
            }

    Here i am attaching snap shot of screen. In console window You can see 2000ms delay is between 2 packets.
    Attached Thumbnails Attached Thumbnails JSSC serial port variable packet length problem-cap.png  

  12. #12
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    Eastern Florida
    Posts
    20,003
    Rep Power
    33

    Default Re: JSSC serial port variable packet length problem

    Please copy and paste the contents of the console, not an image. Text can not be copied from an image for including in a response or for doing searches.

    see 2000ms delay is between 2 packets.
    That time is between calls to the method. Not necessarily the time spent in the method.
    To show the time used in the method, save the time when the method starts execution and the time when it exits. Don't include time spent outside of the method.
    Last edited by Norm; 07-11-2016 at 06:00 PM.
    If you don't understand my response, don't ignore it, ask a question.

  13. #13
    Roshani is offline Member
    Join Date
    Jul 2016
    Posts
    18
    Rep Power
    0

    Default Re: JSSC serial port variable packet length problem

    Dear Sir,

    Here is the content of console.


    Java Code:
    run:
    run once a time when program start
    Connect Button Is Pressed
    7.70,8.90,3.30,4.80,5.00
    
    7.20,3.40,1.80,6.30,2.90
    
    Operation took 1999 milliseconds.
    1.00,4.50,5.20,7.20,3.70
    
    Operation took 2006 milliseconds.
    9.30,1.70,8.90,8.00,9.20
    
    Operation took 1994 milliseconds.
    4.30,2.90,1.90,5.70,5.00
    
    Operation took 1999 milliseconds.
    4.30,7.90,2.80,3.60,3.50
    
    Operation took 1999 milliseconds.
    1.70,6.60,4.20,4.70,9.00
    
    Operation took 2002 milliseconds.
    7.30,2.90,2.90,1.90,3.10
    
    Operation took 1029 milliseconds.
    4.70,1.20,8.30,4.60,7.50
    
    Operation took 2002 milliseconds.
    7.50,4.80,4.10,3.40,7.70
    
    Operation took 2000 milliseconds.
    DisConnect Button Is Pressed
    true

    Here is the complete code.

    Java Code:
    import java.util.logging.Level;
    import java.util.logging.Logger;
    import javax.swing.JOptionPane;
    import jssc.SerialPort;
    import jssc.SerialPortEvent;
    import jssc.SerialPortEventListener;
    import jssc.SerialPortException;
    import jssc.SerialPortList;
    
    
    
    
    
    /*
     * 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 roshan1
     */
    public class MySerial extends javax.swing.JFrame {
        
        
    
        /**
         * Creates new form MySerial
         */
        public MySerial() {
            initComponents();
            searchPorts();
           
        }
    
        
        // search available com ports
        public static void searchPorts(){
            System.out.println("run once a time when program start");
            portList = SerialPortList.getPortNames();
            for (int i = 0; i < portList.length; i++){
                jComboBox1.addItem(portList[i]);
            }
            
            
            
            
            
        }
        /**
         * This method is called from within the constructor to initialize the form.
         * WARNING: Do NOT modify this code. The content of this method is always
         * regenerated by the Form Editor.
         */
        @SuppressWarnings("unchecked")
        // <editor-fold defaultstate="collapsed" desc="Generated Code">                          
        private void initComponents() {
    
            jLabel1 = new javax.swing.JLabel();
            jComboBox1 = new javax.swing.JComboBox<>();
            jButton1 = new javax.swing.JButton();
            jButton2 = new javax.swing.JButton();
            jLabel2 = new javax.swing.JLabel();
            jScrollPane1 = new javax.swing.JScrollPane();
            jTextArea1 = new javax.swing.JTextArea();
    
            setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
            setTitle("My Serial Port Tester");
    
            jLabel1.setText("Select Port:");
    
            jButton1.setText("Connect");
            jButton1.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton1ActionPerformed(evt);
                }
            });
    
            jButton2.setText("Disconnect");
            jButton2.addActionListener(new java.awt.event.ActionListener() {
                public void actionPerformed(java.awt.event.ActionEvent evt) {
                    jButton2ActionPerformed(evt);
                }
            });
    
            jLabel2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
            jLabel2.setText("RxData:");
    
            jTextArea1.setColumns(20);
            jTextArea1.setRows(5);
            jScrollPane1.setViewportView(jTextArea1);
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(18, 18, 18)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(jLabel2)
                            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING)
                                .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jLabel1)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 112, Short.MAX_VALUE)
                                    .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, 88, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGap(35, 35, 35))))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(40, 40, 40)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel1)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addComponent(jButton1)
                    .addGap(18, 18, 18)
                    .addComponent(jButton2)
                    .addGap(18, 18, 18)
                    .addComponent(jLabel2)
                    .addGap(18, 18, 18)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(25, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>                        
    
        private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // TODO add your handling code here:
            // connect button pressed
            System.out.println("Connect Button Is Pressed");
            selectedPort = (String)jComboBox1.getSelectedItem();
            serialPort = new SerialPort(selectedPort);
            try{
    					isOpen = false;
    					isOpen = serialPort.openPort();
    					serialPort.setParams(9600, 8, 1, 0, false, false);
    					//serialPort.setFlowControlMode();
                                             serialPort.setFlowControlMode(SerialPort.FLOWCONTROL_NONE);
    
    					if (isOpen){
    						cnt=0;
    						serialPort.writeString("start\n");
    						int mask = SerialPort.MASK_RXCHAR;
    						jButton1.setEnabled(false);
                                                    jButton2.setEnabled(true);
                                                    
    						serialPort.setEventsMask(mask);
    						serialPort.addEventListener(new SerialPortReader());
    					}
    				}catch(SerialPortException s1){
    					JOptionPane.showMessageDialog(null, "Error In Opening Port", "Roshan", JOptionPane.INFORMATION_MESSAGE);
    				}
    
            
        }                                        
    
        private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {                                         
            // TODO add your handling code here:
            // disconnect button is pressed
            System.out.println("DisConnect Button Is Pressed");
             try {
    					 serialPort.writeString("stop\n");
    						isClosed = false;
    						isClosed = serialPort.closePort();
    						System.out.println(isClosed);
    						if (isClosed){
    							jButton1.setEnabled(true);
    							jButton2.setEnabled(false);
    						}
    					} catch (SerialPortException e) {
    						// TODO Auto-generated catch block
    						System.out.println(isOpen);
    						e.printStackTrace();
    					}	 
    				
    
           			
        }                                        
    
        // serial port event
        // serial port event
        static class SerialPortReader implements SerialPortEventListener {
            @Override
        public void serialEvent(SerialPortEvent event) {
                    if (event.isRXCHAR() && event.getEventValue() > 0){
                         
                        try {
                            byte buffer[] = serialPort.readBytes(1);
                            byte b = buffer[0];
                            char c = (char)b;
                           // System.out.println(c);
                            rxData = rxData +c;
                            if (c == '\n'){
                                ok = true;
                                System.out.println(rxData);
                                current = System.currentTimeMillis();
                             
                                if (old == 0){
                                    old = current;
                                }
                                if (current != old){
                                    System.out.println("Operation took " + (current - old) + " milliseconds.");
                                    old = current;
    
                                }
                                
                                cnt++;
                                jLabel2.setText("RxData:" + rxData + ", " + cnt);
                                 
                                rxData = "";
                            }
                        } catch (SerialPortException ex) {
                            Logger.getLogger(MySerial.class.getName()).log(Level.SEVERE, null, ex);
                        }
                             
                         
                         
                         
                     
            }
                     
        }
            }
    	
    
        
        
        
        
        
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            /* Set the Nimbus look and feel */
            //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
            /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
             * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
             */
            try {
                for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                    if ("Nimbus".equals(info.getName())) {
                        javax.swing.UIManager.setLookAndFeel(info.getClassName());
                        break;
                    }
                }
            } catch (ClassNotFoundException ex) {
                java.util.logging.Logger.getLogger(MySerial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (InstantiationException ex) {
                java.util.logging.Logger.getLogger(MySerial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (IllegalAccessException ex) {
                java.util.logging.Logger.getLogger(MySerial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            } catch (javax.swing.UnsupportedLookAndFeelException ex) {
                java.util.logging.Logger.getLogger(MySerial.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
            }
            //</editor-fold>
    
            /* Create and display the form */
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MySerial().setVisible(true);
                }
            });
        }
    
        // user variables
        public static String[] portList;
        public static String selectedPort ;
        public static SerialPort serialPort;
        public static String rxData = "";
        
        // boolean
        public static boolean isOpen = false;
        public static boolean isClosed = false;
        public static boolean ok = false;
        
        // long
        public static long old;
        public static long current;
        // int
        public static byte b;
        public static int pointer = 0;
        public static int cnt = 0;
        public static byte buffer[];
        public static byte bufferNew[];
        public static char bb[];
        
        // Variables declaration - do not modify                     
        private javax.swing.JButton jButton1;
        private javax.swing.JButton jButton2;
        public static javax.swing.JComboBox<String> jComboBox1;
        private javax.swing.JLabel jLabel1;
        public static javax.swing.JLabel jLabel2;
        private javax.swing.JScrollPane jScrollPane1;
        public static javax.swing.JTextArea jTextArea1;
        // End of variables declaration                   
    }
    Please help to sort problem.

  14. #14
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    14,422
    Blog Entries
    7
    Rep Power
    28

    Default Re: JSSC serial port variable packet length problem

    Quote Originally Posted by Roshani View Post
    Sir,

    still have problem.

    I can receive one byte at a time & print it. It is working.

    I tried to receive one byte, append it in string, check if byte == newline then set flag

    working but processing is very slow.
    I can imagine: you are appending chars to a String over and over again; a String is an immutable object, so each time an entirely new String is created after the character is appended to a (new) StringBuilder. You can do better than that: create a single StringBuilder and append your characters to the StringBuilder; when you're done, convert the StringBuilder to a String once. It surprises me that your SerialPort object can't read single bytes ...

    kind regards,

    Jos
    Build a wall around Donald Trump; I'll pay for it.

  15. #15
    Tolls is offline Moderator
    Join Date
    Apr 2009
    Posts
    13,541
    Rep Power
    27

    Default Re: JSSC serial port variable packet length problem

    Something somewhere is sleeping for 2 seconds.
    That's not coincidence.
    Either in your code (including JSSC) or in whatever is sending the data.
    Please do not ask for code as refusal often offends.

    ** This space for rent **

  16. #16
    Roshani is offline Member
    Join Date
    Jul 2016
    Posts
    18
    Rep Power
    0

    Default Re: JSSC serial port variable packet length problem

    Dear Sir,

    Problem solved. Here is the modified serial event.

    I have changed my string end with "\r\n", which is CR & LF OR NEW LINE.

    posting here to take benefit for other users.

    Java Code:
    static class SerialPortReader implements SerialPortEventListener {
            @Override
        public void serialEvent(SerialPortEvent event) {
                    if (event.isRXCHAR() && event.getEventValue() > 0){
                       
                        try {
                        sb.append(serialPort.readString(event.getEventValue()));
                        ch=sb.toString();
                        if (ch.endsWith("\r\n")){
                             c = ch.split("\n");
                             rxData = c[cnt];
                             jLabel2.setText("RxData: " + rxData);
                             cnt++;
                            
                        }
                        
                        
                        
                        } catch (SerialPortException e) {
                        System.out.println("SerialEvent error:"+ e.toString());
    }
                     
                        
                    }
                     
        }
            }
    Also attaching animated snap shot of my program.

    Thanks to every one for help & discussion with me.

    Attached Thumbnails Attached Thumbnails JSSC serial port variable packet length problem-screen002.gif  

Similar Threads

  1. Java app and com port with jssc in linux
    By nando88 in forum New To Java
    Replies: 0
    Last Post: 04-05-2015, 08:11 PM
  2. Serial Port code problem
    By Z.K. in forum New To Java
    Replies: 0
    Last Post: 05-08-2011, 11:37 PM
  3. Serial port Communication Problem
    By rjagan in forum New To Java
    Replies: 8
    Last Post: 04-20-2011, 12:36 PM
  4. Serial port communication via jSSC
    By scream3r in forum New To Java
    Replies: 5
    Last Post: 02-15-2011, 08:12 PM
  5. Replies: 1
    Last Post: 07-30-2010, 08:29 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •