Ruby, Ruby-SerialPort and the missing bytes

written by Jan on November 22nd, 2006 @ 07:21 PM

The past 3 days I’ve been working on some ruby code to communicate with our new PMU’s. The communication goes over the serial port, and I found that ruby has a nice way of talking over a serial port, namely ruby-serialport. But after day 1 I got some funny results: I expected 7 bytes from the devices, but from some devices I got 6 bytes. And from 1 device I even only got 5 bytes.

We first suspected a problem with the devices, since the problem was easily reproducible. After some debugging on different devices and even different operating systems (we even tested it on windows), we found out it was a bug in the ruby code, but we couldn’t find out why.

After a lot of fiddling with code and working around the ruby-serialport code, I found out I got the same result while actually File.open()’ing and File#read and File#write’ing. Suddenly, after some changes, I got the right results. The solution: opening the file non-blocking.

So what did I do to make it work with ruby-serialport? I made a small change to the serialport.c file:

1
2
3
4
5
6
7
8
9
10
--- ruby-serialport-0.6/serialport.c    2003-02-13 20:55:48.000000000 +0100
+++ ruby-serialport-0.6-new/serialport.c        2006-11-22 17:04:37.000000000 +0100
@@ -608,7 +608,7 @@ static VALUE sp_create(class, _port)
break;
}
-  fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY);
+  fd = open(port, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK);
if (fd == -1)
rb_sys_fail(port);
if (!isatty(fd)) {

That’s all really. Don’t ask me why this behaviour occurs, don’t ask me why nonblock solves it, just assume that, if you’re missing bytes in your ruby-serialport code, this might help.



Comments

  • tom on 06 Mar 23:45

    interesting find. did you send the patch to the author? regards, TOM
  • remi on 17 May 09:36

    i'm still missing bytes, even with this patch :(

Post a comment

Options:

Size