CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Jun 2011
    Location
    Buenos Aires, Argentina
    Posts
    130

    Post Serialport incoming message manager

    Hi, I'm writing a little message control app that will use a custom packet protocol to be sent between two or more devices.

    I will be sending and recieving messages with a header containing destination and source address, message number, length, etc.

    The problem is, when a message arrives a DataRecieved event will occur for the serialport, but the BytesToRead variable might not have the final value it will have after the entire packet is recieved, so I will not have all the incoming data. Even if I save whatever I got so far in a temp buffer, DataRecieved is not triggered again so until the next message arrives I will not finish recieving the first one.

    I've set the threshold to trigger DataRecieved only after SIZEOF_HEADER bytes are recieved, so that I know for sure how many bytes I will be expecting, but I can't increase the threshold more since an empty packet would never trigger an event otherwise...

    I could raise a <newData> flag and start a timer to look for data after a few ticks, but I doubt it's very "clean" to do so. How long should I wait? If I wait to long, my input buffer could overflow if continous data is arriving, or I could not have recieved the whole packet yet if I wait to little...

    What other ways of recieving data are there? What's the best way of making sure I read everything I need avoing the risk of data loss?

    Thanks for the help!

  2. #2
    Join Date
    Jul 2008
    Location
    WV
    Posts
    5,362

    Re: Serialport incoming message manager

    Well I have not used the serial class much in .net so it may not work exactly as I am acustomed to but normally I would set the receive threshold to 1 so the event ques up to fire anytime a byte comes into the buffer. I also check to see if bytes are there but I do not use that value in the read statement as more bytes could have came in between statements. I would issue a read and check the number of bytes read if needed.

    After the read the event shoudl fire again if more data came in after the read took place if this is not happening then there are a couple of things you can do.

    1: You can check after you read and process your data to see if there is anything in the buffer waiting to be received and loop until the buffer is empty.

    2: You can set the receive threshold to 0 and use a timer to poll the port if the event handler does not work for you.
    Always use [code][/code] tags when posting code.

Tags for this Thread

Posting Permissions

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





Click Here to Expand Forum to Full Width

Featured