[plt-scheme] Need low-level help: blocking on reading from serial port in Windows

From: YC (yinso.chen at gmail.com)
Date: Sat Oct 24 14:58:17 EDT 2009

On Sat, Oct 24, 2009 at 8:06 AM, Nadeem Abdul Hamid <nadeem at acm.org> wrote:

> On Fri, Oct 23, 2009 at 9:35 PM, Nadeem Abdul Hamid <nadeem at acm.org>
> wrote:
> >
> > The delay causes the code to "hang" for about 5 to 10 seconds before
> > it the read comes through. An interval of 5 causes a much longer
> > "hang". And as YC suggested, the CPU usage is max-ed out during that
> > period...
> >
>
> Sorry, this was dumb. It delays exactly as expected. I've been working
> on this too long...
>

Nadeem -

to reduce the CPU usage you can use sync or the blocking variety of the
read-* functions, so that you are not melting your computer waiting for the
bytes to come through.  Looking at your function's logic it doesn't appear
you need the non-blocking methods, and the logic appears very similar to
read-bytes, but it returns a list of bytes instead of a byte-string.  So
something like the below should work:

(define (read-bytes/list num in)
  (bytes->list (read-bytes num in)))

read-bytes will hang unless it has captured enough bytes or encounter an
EOF.  If you need the function to return before encountering EOF but doesn't
hang forever - you can use other mechanisms, such as installing a max
timeout:

(define (read-bytes/list/timeout num in timeout)
  (define (helper alarm acc count)
    (let ((evt (sync alarm in)))
      (if (eq? alarm evt)
          (reverse acc)
          (let ((b (read-byte in)))
            (cond ((eof-object? b)
                   (if (null? acc)
                       b
                       (reverse acc)))
                  ((= (add1 count) num)
                   (reverse (cons b acc)))
                  (else
                   (helper alarm (cons b acc) (add1 count))))))))
  (helper (alarm-evt (+ (current-inexact-milliseconds) (* 1000 timeout)))
'() 0))

In any event, it's likely that the issue lies at the port level if your
simulation that provides a deterministic flow of bytes works correctly even
when the cpu is maxed out.  You might have better luck to investigate the
port to make sure the data is flowing through.

HTH,
yc
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20091024/ab2e4361/attachment.html>

Posted on the users mailing list.