Android Question Wait For with Astream

yo3ggx

Active Member
Licensed User
Hello everybody.

I have the following situation. I'm sending some data over usb serial and I have to wait for an answer from the other party (a hardware device) before sending data again.
I want to use Wait For with AsyncStream, but there are situations when the other party does not answer at all, or returns an unexpected answer. As there is no timeout implemented in Wait For, how can I deal with the situation without being stuck in Wait For, as the communication is performed in a loop? Currently I'm using a timer and a standard astream_newdata routine, but in this way I don't know when previous command was send and answer received, so I'm forced to use a bigger timer interval to be sure, which decrease the performance a lot (the answer can be received in a few ms or hundreds of ms).

I don't think that the solution proposed by Erel here (or I'm wrong) can be applied in my case.

Thank you.
 

Erel

Administrator
Staff member
Licensed User
As there is no timeout implemented in Wait For
You are looking for a timeout in AsyncStreams, not Wait For. A time out in Wait For would have caused the app state to become unmanageable.

I would have done it like this:
B4X:
Private Sub AStream_NewData(Data() As Byte)
Buffer.Append(Data)  'Buffer is a class global B4XBytesBuilder
End Sub

'send message
Dim timeout As Long = DateTime.Now + 1000 'one second
Dim result() As Byte
Do While DateTime.Now < timeout
Sleep(50)
If Buffer.Length > ... Then
   result = Buffer.SubArray2(...)
    Buffer.Remove(...)
   Exit '<---------------
End If
If result.Length = 0 Then
   Log("timeout")
Else
  Log("work with response")
End Sub
 
Upvote 0
Top