ASync Bluetooth example?

Dutch2

Member
Licensed User
Longtime User
I'm trying to use AsyncStreams to work with Bluetooth because I need to receive an array of unsigned bytes through a Bluetooth connection.

This is what I have:

B4X:
Sub Process_Globals
   Dim Serial1 As Serial
   Dim Timer1 As Timer
   Dim connected As Boolean
   Dim AStreams As AsyncStreams
End Sub

Sub Activity_Create(FirstTime As Boolean)
   If FirstTime Then
      Serial1.Initialize("Serial1")
      Timer1.Initialize("Timer1", 200)
      Timer1.Enabled = False
   End If
        Activity.LoadLayout("1")
End Sub

Sub Serial1_Connected (Success As Boolean)
   If Success Then
      ToastMessageShow("Connected successfully", False)
      AStreams.InitializePrefix(Serial1.InputStream, False, Serial1.OutputStream, "AStreams")
      timer1.Enabled = True
      connected = True
   Else
      connected = False
      Timer1.Enabled = False
      Msgbox(LastException.Message, "Error connecting.")
   End If
End Sub

Sub AStreams_NewData (Buffer() As Byte)
    Dim msg As String
    msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
    ToastMessageShow(msg, False)
    Log(msg)
End Sub

Sub AStreams_Error
    ToastMessageShow(LastException.Message, True)
End Sub

Sub Timer1_Tick
   If connected Then
          Dim Buffer() As Byte
          Buffer = "z".GetBytes("UTF8") 'send z to trigger other end to send data
          AStreams.Write(Buffer)
   End If
End Sub

It connects successfully (connect code not shown) but then I get a "...has stopped unexpectedly".

I got this to work using TextReader and Writer but I'm unable to convert the Char array returned by the reader into unsigned values.

Any suggestions will be greatly appreciated!

D2.
 
Top