Android Question USBSerial wait for receiving bytes

wroyw

Member
Licensed User
Hi,

is it possible to wait for a specified count of bytes after write to USBserial port ?

I would like send many commands to a device with different length of answer.

e.g.

send 0x01 , receive 2 bytes
send 0x51 , recieve 8 bytes

and many others,

So I will write and than wait for the answer.

Is that possible with the USBserial lib ?

Thanks in advance

Roy
 

Erel

B4X founder
Staff member
Licensed User
Longtime User
AsyncStreams NewData event (in non-prefix mode) is raised whenever there is data available.

In your case the solution is relatively simple. You need to create an array of bytes that is large enough to hold the largest message (start with 10000 if you are not sure).

Create a global variable that will be used to track the current array index.
Something like:
B4X:
Sub Process_Globals
   Private bc As ByteConverter
   Private GlobalBuffer(10000) As Byte
   Private GlobalIndex As Int
   Private ExpectedMessageSize As Int
End Sub

Sub AStream_NewData (Buffer() As Byte)
   bc.ArrayCopy(Buffer, 0, GlobalBuffer, GlobalIndex, Buffer.Length)
   GlobalIndex = GlobalIndex + Buffer.Length
   If GlobalIndex >= ExpectedMessageSize Then
     Dim msg(ExpectedMessageSize) As Byte
     bc.ArrayCopy(GlobalBuffer, 0, msg, 0, ExpectedMessageSize)
     MessageArrived(msg)
     GlobalIndex = 0     
   End If
   
End Sub

Sub MessageArrived (msg() As Byte)
   
End Sub
 
Upvote 0
Top