Serial Example Hangs on HTC Hero 2.1

Rick in North Carolina

Member
Licensed User
Longtime User
I looked at the trial version and really wanted to try out the Serial (BlueTooth) library so went ahead and shelled out $39. Was dissappointed that the SerialExample would only connect (Toast message) then hang (toast msg still there), finally getting an Application Not Responding (ANR) dialog. Before I looked into Basic4Android, I was using Eclipse SDK sample BlueToothChat with no problems, so I know it should work. (I just saw in your Serial Tutorial forum, someone else is having a similiar issue). Rick
 

Rick in North Carolina

Member
Licensed User
Longtime User
No, as soon as the toast message says "Connect" the program stops responding (the toast message remains displayed), click on the EditBox, nothing happens (no keypad) and in 15 secs the ANR dialog displays.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Lets try to add some logging messages to this code:
B4X:
Sub Serial1_Connected (Success As Boolean)
    If Success Then
        ToastMessageShow("Connected successfully", False)
        Log("1")
        TextReader1.Initialize(Serial1.InputStream)
        Log("2")
        TextWriter1.Initialize(Serial1.OutputStream)
        Log("3")
        'timer1.Enabled = True
        connected = True
    Else
        connected = False
        Timer1.Enabled = False
        Msgbox(LastException.Message, "Error connecting.")
    End If
End Sub
I've also commented out timer1.enabled line. You can see the messages by going to the LogCat tab in the right pane and pressing Connect.
If it doesn't hang after disabling the timer then you should enable the timer and update this code:
B4X:
Sub Timer1_Tick
    If connected Then
        Log("T1")
        If TextReader1.Ready Then 'check if there is any data waiting to be read
            Log("T2")
            txtLog.Text = txtLog.Text & TextReader1.ReadLine & CRLF
            Log("T3")
            txtLog.SelectionStart = txtLog.Text.Length
        End If
    End If
End Sub
 
Upvote 0

Rick in North Carolina

Member
Licensed User
Longtime User
Ok, That narrowed it down. Got:
** Activity (main) Create, isFirst = true **
** Activity (main) Resume **
1
3
T1
T2

So hanging in Timer1_Tick on txtLog.Text = txtLog.Text & TextReader1.ReadLine & CRLF
, then I changed to "count = TextReader1.Read(buffer,0,1)" since my data would be just ascii (no line feed nor carriage return). Still hangs there.

Since my bluetooth does not send data to the phone unless asked (must be asked for data by a Send cmd from phone first), it looks like If TextReader1.Ready Then is giving a incorrect state, indicating True when no data is present in the TextReader1. Then TextReader1.Read is called and waits...... since no data is there.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
Lets try to use a raw InputStream instead of a TextReader:
B4X:
'Activity module
Sub Process_Globals
    Dim Serial1 As Serial
    Dim TextReader1 As TextReader
    Dim TextWriter1 As TextWriter
    Dim Timer1 As Timer
    Dim connected As Boolean
    Dim in As InputStream
End Sub

Sub Globals
    Dim btnSend As Button
    Dim txtLog As EditText
    Dim txtSend As EditText
End Sub

Sub Activity_Create(FirstTime As Boolean)
    If FirstTime Then
        Serial1.Initialize("Serial1")
        Timer1.Initialize("Timer1", 200)
    End If
    Activity.LoadLayout("1")
    Activity.AddMenuItem("Connect", "mnuConnect")
    Activity.AddMenuItem("Disconnect", "mnuDisconnect")
End Sub
Sub Activity_Resume
    If Serial1.IsEnabled = False Then
        Msgbox("Please enable Bluetooth.", "")
    Else
        Serial1.Listen 'listen for incoming connections
    End If
End Sub
Sub mnuConnect_Click
    Dim PairedDevices As Map
    PairedDevices = Serial1.GetPairedDevices
    Dim l As List
    l.Initialize
    For i = 0 To PairedDevices.Size - 1
        l.Add(PairedDevices.GetKeyAt(i))
    Next
    Dim res As Int
    res = InputList(l, "Choose device", -1) 'show list with paired devices
    If res <> DialogResponse.CANCEL Then
        Serial1.Connect(PairedDevices.Get(l.Get(res))) 'convert the name to mac address
    End If
End Sub

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

Sub Activity_Pause (UserClosed As Boolean)

End Sub

Sub btnSend_Click
    If connected Then
        TextWriter1.WriteLine(txtSend.Text)
        TextWriter1.Flush
        txtSend.Text = ""
    End If
End Sub
Sub Timer1_Tick
    If connected Then
        Log("Bytes available: " & in.BytesAvailable)
        If in.BytesAvailable > 0 Then
            Dim buffer(in.ReadBytes) As Byte
            Dim count As Int
            count = in.ReadBytes(buffer, 0, buffer.Length)
            Log("Read " & count & " bytes.")
            Log(BytesToString(buffer, 0, count, "ASCII"))
        End If
'        If TextReader1.Ready Then 'check if there is any data waiting to be read
'            txtLog.Text = txtLog.Text & TextReader1.ReadLine & CRLF
'            txtLog.SelectionStart = txtLog.Text.Length
'        End If
    End If
End Sub
 
Upvote 0

Rick in North Carolina

Member
Licensed User
Longtime User
Ok, here are the results (for Timer1_Tick):

Bytes available: 69600


Then hangs after "If in.BytesAvailable > 0 Then" because there is nothing to read in in.ReadBytes(....)

I tried an additional test with the bluetooth sending a powerup message and seeing if the app would recieve it..it did but "bytes available: 69600" never changed and the app hung after the bytes were read:
Bytes available: 69600
Read 10 bytes.
MONITOR v
Bytes available: 69600
Read 7 bytes.
1.1a>
Bytes available: 69600

<....app hangs....>


p.s. I changed for simplicity line Dim buffer(in.ReadBytes) As Byte to Dim buffer(10) As Byte because it errored and in.Readbytes needs another buffer() too.
 
Upvote 0

Erel

B4X founder
Staff member
Licensed User
Longtime User
I changed for simplicity line Dim buffer(in.ReadBytes) As Byte
It should have been Dim buffer(in.BytesAvailable). Sorry.

However the problem as described also in the link posted by agraham is that the HTC Hero returns a wrong value for the bytes available API. This means that you cannot read the stream this way. I had some plans to add support for asynchronous streams. I will give it a try.
 
Upvote 0

Rick in North Carolina

Member
Licensed User
Longtime User
Ah, very good, Thank you. Works well.

Here is the changed Serial Example code for those following this thread:

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

Sub Globals
   Dim btnSend As Button
   Dim txtLog As EditText
   Dim txtSend As EditText
End Sub

Sub Activity_Create(FirstTime As Boolean)
   If FirstTime Then
      Serial1.Initialize("Serial1")
      'Timer1.Initialize("Timer1", 200)
   End If
   Activity.LoadLayout("1")
   Activity.AddMenuItem("Connect", "mnuConnect")
   Activity.AddMenuItem("Disconnect", "mnuDisconnect")
End Sub
Sub Activity_Resume
   If Serial1.IsEnabled = False Then
      Msgbox("Please enable Bluetooth.", "")
   Else
      Serial1.Listen 'listen for incoming connections
   End If
End Sub
Sub mnuConnect_Click
   Dim PairedDevices As Map
   PairedDevices = Serial1.GetPairedDevices
   Dim l As List
   l.Initialize
   For i = 0 To PairedDevices.Size - 1
      l.Add(PairedDevices.GetKeyAt(i))
   Next
   Dim res As Int
   res = InputList(l, "Choose device", -1) 'show list with paired devices
   If res <> DialogResponse.CANCEL Then
      Serial1.Connect(PairedDevices.Get(l.Get(res))) 'convert the name to mac address
   End If
End Sub

Sub Serial1_Connected (Success As Boolean)
   If Success Then
      ToastMessageShow("Connected successfully", False)
      AStreams.Initialize(Serial1.InputStream, Serial1.OutputStream, "AStreams")
      Log("AStreams Initialized")
      'timer1.Enabled = True
      connected = True
   Else
      connected = False
      'Timer1.Enabled = False
      Msgbox(LastException.Message, "Error connecting.")
   End If
End Sub
Sub mnuDisconnect_Click
   If connected Then
      AStreams.Close
      Serial1.Disconnect
      connected = False
      Log("AStreams Closed")
   End If
End Sub

Sub Activity_Pause (UserClosed As Boolean)
   If UserClosed Then
        Log("closing")
        AStreams.Close
    End If
End Sub

Sub btnSend_Click
   If connected Then
      If AStreams.IsInitialized = False Then 
         Return
      End If
      If txtSend.Text.Length > 0 Then
         Dim buffer() As Byte
         txtSend.Text = txtSend.Text
         buffer = txtSend.Text.GetBytes("UTF8")
         AStreams.Write(buffer)
         Log("Sending: " & txtSend.Text)
         txtSend.Text = ""
      End If
   End If
End Sub

Sub AStreams_NewData (Buffer() As Byte)
    Dim msg As String
    msg = BytesToString(Buffer, 0, Buffer.Length, "UTF8")
   txtLog.Text = txtLog.Text & msg
    Log("Rec: " & msg)
End Sub

Sub AStreams_Error
   Log("AStreams Error: " & LastException.Message)
    ToastMessageShow(LastException.Message, True)
End Sub


'Sub Timer1_Tick
'   If connected Then
'      
'   End If
'End Sub
 
Last edited:
Upvote 0

Brad

Active Member
Licensed User
Longtime User
I had a similar problem with my droid hooking up to my odbii bluetooth dongle. I got it working by receiving via async method and sending using the textwriter. Now to create something useful. :)
 
Upvote 0
Top