serisal programming in linux

I have a program that use to tranfer data by serial port:
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#define BAUDRATE B19200            
#define MODEMDEVICE "/dev/ttyS0"
#define _POSIX_SOURCE 1
#define FALSE 0
#define TRUE 1

volatile int STOP=FALSE;

int main(int agrs, char* agvs)
{
 int fd, res;
 struct termios oldtio,newtio;
 char buf[255];
 fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY );
 if (fd <0) {perror(MODEMDEVICE); exit(-1); }
 tcgetattr(fd,&oldtio);
 bzero(&newtio, sizeof(newtio));
 newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
 newtio.c_iflag = IGNPAR | ICRNL;
 newtio.c_oflag = 0;
 newtio.c_lflag = 0;
 newtio.c_cc[VINTR]    = 0;  
 newtio.c_cc[VQUIT]    = 0;
 newtio.c_cc[VERASE]   = 0;
 newtio.c_cc[VKILL]    = 0;
 newtio.c_cc[VEOF]     = 4;
 newtio.c_cc[VTIME]    = 1;
 newtio.c_cc[VMIN]     = 1;
 newtio.c_cc[VSWTC]    = 0;
 newtio.c_cc[VSTART]   = 0;
 newtio.c_cc[VSTOP]    = 0;
 newtio.c_cc[VSUSP]    = 0;
 newtio.c_cc[VEOL]     = 0;
 newtio.c_cc[VREPRINT] = 0;
 newtio.c_cc[VDISCARD] = 0;
 newtio.c_cc[VWERASE]  = 0;
 newtio.c_cc[VLNEXT]   = 0;
 newtio.c_cc[VEOL2]    = 0;
 tcflush(fd, TCIFLUSH);
 tcsetattr(fd,TCSANOW,&newtio);
 while (STOP==FALSE)
 {
      res = read(fd,buf,255);
      buf[res]='\0';         
       printf(":%s:%d\n", buf, res);
    if (buf[0]=='z') STOP=TRUE;
 }
 tcsetattr(fd,TCSANOW,&oldtio);
 return 0;
}

I begin running my program, I get a problem:
while I receive string "0123456789" from another PC(this PC use Terminal v19b with baudrate 19200, 8N1 to sent). sometimes, I received "01234567" on buffer instead of "0123456789". how to receive complete data from buffer (I dont' know length of data sent). pleas help me.
k6tAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Infinity08Commented:
I assume that you just have to do another read, something like this :

      char *buf_ptr = buf
      while ((res = read(fd,buf_ptr,255)) > 0) {
        buf_ptr += res;
      }
      *buf_ptr='\0';
0
mokuleCommented:
Good practice is to use some even simplest frame for transmission.
For example start mark byte at the beggining and end mark byte at the end.
These marks should be chosen such that thay cannot occur in Your data.
Other possibility is to send byte count at the beggining.

Otherwise You never know if You received everything.
0
itsmeandnobodyelseCommented:
>>>> I dont' know length of data sent
If you are responsible for sending and receiving, you might change sending so that they pass the length of the message first.

struct Message
{
    int lenMsg;
    char szMsg[1020];
    Message(const char* pszMsg)
       : lenMsg{strlen(pszMsg+1)) { strcpy(szMsg, pszMsg); }
     const char* buffer() { return (const char*)this; }
     int msglen() { return lenMsg + sizeof(int); }
};

     ....
     Message msg("12345678);
     send(fd, msg.buffer(), msg.msglen());

     
     
     int msglen = 0;
     int nread = 0;
     char* p =  (char*)&msglen;
     while ((nread += read(fd, p, sizeof(int) - nread)) < sizeof(int))
           p =  ((char*)&msglen) + nread;
     if (msglen > 0)
     {
          char* pszMsg = new char[msglen];
          p = pszMsg;
          nread = 0;
          while ((nread += read(fd, p, msglen - nread)) < msglen)
               p = pszMsg + nread;
     }

Of course you could implement the receiver's side by using struct Message as well. Then the read loops would be made by a member function of struct Message.

Regards, Alex


0
Determine the Perfect Price for Your IT Services

Do you wonder if your IT business is truly profitable or if you should raise your prices? Learn how to calculate your overhead burden with our free interactive tool and use it to determine the right price for your IT services. Download your free eBook now!

itsmeandnobodyelseCommented:
>>>> Other possibility is to send byte count
Sorry I missed your comment or I would have made a reference.
0
jkrCommented:
I'd suggest to take a look at http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/ for more information and code examples.
0
k6tAuthor Commented:
char *buf_ptr = buf
      while ((res = read(fd,buf_ptr,255)) > 0) {
        buf_ptr += res;
      }
      *buf_ptr='\0';

with your code, my program will block. because res > 0. then the while control no break.
0
Infinity08Commented:
Well, it's a very crude solution, and has to be refined, but read() will return a value > 0 for as long as there is data to receive. If there is no data to be received, it will either return 0 or <0.

However, as mokule suggested, I would send the length of the data in some way, so the receiver knows how much he has t o receive.
0
k6tAuthor Commented:
thanks you. but, in my practical, I don't know length of data. In theorical read() function will return a value > 0 for as long as there is data to receive. If there is no data to be received, it will either return 0 or <0. if you don't set 0_NDELAY or same thing by  fcntl(fd, F_SETFL, FNDELAY) function, read() will block until look for data on buffer.
0
Infinity08Commented:
>> I don't know length of data

The sender knows how much data it's sending, and can give that information to the receiver ...
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
draguljCommented:
Several things to recommend:

Replace
   bzero(&newtio, sizeof(newtio));
with
  memcpy (&newtio, &oldtio, sizeof(newtio));

This will copy serial port configuration to a new structure. Then you just change several parameters:

   newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD;
   newtio.c_iflag = IGNPAR | IGNBRK;     // Ignore bad parity bytes and break chars
   newtio.c_oflag = 0;   // raw sending
   newtio.c_lflag = 0;    // no echo, noncanonical ...

And crucial thing:

   newtio.c_cc[VTIME] = 5;         // Timeout is 0.5s
   newtio.c_cc[VMIN]  = 0;         // Wait for a byte until timeout

Then:

   tcflush (fd, TCIOFLUSH);                                     // Clean the line
   tcsetattr (fd, TCSANOW, &newtio);              // Activate new port configuration

   memset (buf, 0, sizeof(buf));
   while (TRUE) {
      res = read (fd, buf, 255);
      if (res > 0) {
         buf[res] = 0;
         printf ("%s", buf);
         if (buf[0] == 'z')
            break;
      }
      else {
         // You can do something or break from while loop
     }
   }

    tcflush (fd, TCIOFLUSH);                                  
    tcsetattr (fd, TCSANOW, &oldtio);
    close (fd);


I hope this will work.
0
SeanDurkinCommented:
No comment has been added to this question in more than 21 days, so it is now classified as abandoned.

I will leave the following recommendation for this question in the Cleanup Zone:
      Split: mokule {http:#18842293} & itsmeandnobodyelse {http:#18842375} & Infinity08 {http:#18863033}

Any objections should be posted here in the next 4 days. After that time, the question will be closed.

Sean
EE Cleanup Volunteer
0
jkrCommented:
I'd like to point out the pointer to http://www.tldp.org/HOWTO/Serial-Programming-HOWTO/ also...
0
SeanDurkinCommented:
It looks, from the code samples, as though the Asker pulled source code from that site (or one with very similar source) and edited it to suit his needs (the code he provided is almost exactly the same as some of the source code from the link you provided, with minor changes). I assumed he had done a little research first before asking this question, or at least did not want to do the research in the first place, and while I may be wrong, it looks as though he ignored your above comment.

That's just my personal opinion, but I'll alert the moderator who reviews this to take extra note of your comments.

Sean
EE Cleanup Volunteer
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Programming

From novice to tech pro — start learning today.