B4J Question Serial Port - bytes available question

rspitzer

Active Member
First, I know I should be using the async streams for the serial ports. I am doing that and it works very well. I wanted to explore just getting the serial data without using async streams and have run into two issues.

sample getting serial data:
    input = sp1.GetInputStream
    
    Dim buffer(1024) As Byte
    Dim count As Int

    count = input.BytesAvailable

    Log(count) - always zero here for some reason?

    count = input.ReadBytes(buffer, 0, buffer.length) - hangs here forever if I unplug the serial port (not the USB), so there's no data.
    If count > 0 Then
        Main.read_knife_adjust_byte = buffer(count-1)
        Main.knife_adjust_board_installed = True
    End If

In the above code, I have a board that is continually sending just one byte of data at 9600 baud. The code works fine except for 2 odd issues.

1: The count in the input.bytesavailble line always returns 0 (zero) - don't know why?
2: If I unplug the serial port (not the USB side, its still plugged in), the program hangs at the readbytes line and never returns. Don't know why?

Its not the end of the world here, as I said, I implemented the this using async streams without any problems, I am just curious as to what I missed here?
 

DonManfred

Expert
Licensed User
Longtime User
Upvote 0

rspitzer

Active Member
I understand both your answers in terms of using Async Methods, I know this already, I was experimenting with trying to read the serial data synchronously, and ran into the 2 problems. I am assuming by your non answers, that you don't have an answer for the issues, and the answer basically is avoid using synchronous reads of the serial port. This is a little dismaying, I assume there is a bug of sort in the synchronous read and synchronous reads should be avoided. A bit dismaying.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
This is really a waste of time but I will answer (one last time):

1. InputStream.BytesAvailable returns 0 because the number of bytes available are not known. It depends on the way the underlying stream is implemented.

If I unplug the serial port (not the USB side, its still plugged in), the program hangs at the readbytes line and never returns. Don't know why?
2. ReadBytes waits until it reads at least one byte or the connection breaks. In the case of serial ports, the connection is never considered broken.
 
Upvote 0
Top