B4J Question AsyncStreamsText and serial port

johan vetsuypens

Member
Licensed User
Longtime User
Attached you can find a B4J sample using AsyncStreamsText to send and receive data over the serial port to a serial device.

In the sample you will find a function SendToDevice that sends a string to the connected device , and waits in a loop until it receives data or a timeout is exceeded.

The problem I have is that the AStream_NewText event is fired after exit of the SendToDevice function.

it seems that you can't wait for an answer in a loop. In .net you can give the application some thread time with DoEvents, but as I read, this is not possible in B4J.

Can you find a nice construction where I can easily send a command to the serial port and wait for an answer before continuing then next sending block.

In the sample you see that I send 3 commands to the device. What is happening is that after the third command, I receive the answer on the first command I send.

the actual log file output

Program started.
open port COM1
Write to com port : $+$!
Write to com port : $a
Write to com port : i
Data received : Gryphon-GD44xx SOFTWARE RELEASE 610001021 Version 5.3.103.R Oct 29 2013


Should be

Program started.
open port COM1
Write to com port : $+$!
Data received : Gryphon-GD44xx SOFTWARE RELEASE 610001021 Version 5.3.103.R Oct 29 2013
Write to com port : $a
Data received : 610001021
Write to com port : i
Data received : Build XYZ



Thanks,

Johan
 

Attachments

  • B4Jsrc.zip
    3.2 KB · Views: 321

Erel

B4X founder
Staff member
Licensed User
Longtime User
it seems that you can't wait for an answer in a loop
That's true.

You need to manage the connection state.

There are many ways to do it.
The NewText event sub is the place to send the next message each time.

So you send the first message and then do nothing until the NewText event is raised. Now you send the next message.

The actual implementation depends on the specific requirements. If for example the three messages are always the same then you can create a global list with the messages and store the current position in the list in a global variable.

Advance the position variable in NewText event and send the next message each time (until you reached the end of the list).
 
Upvote 0
Top