Bluetooth Chat - AsyncStreams in two activity modules

raphaelcno

Active Member
Licensed User
Longtime User
I'm using the Bluetooth Chat example, and I try to add another activity module/layout called Page3. In Page3 I want to use the Bluetooth connection with AsyncStreams, but I get error message "Connection is broken".

In the ChatActivity layout I press a button BtnPage3 in order to open the new layout Page3, with this code in the ChatActivity module:

B4X:
Sub BtnPage3_Click
   Page3.AStream3 = AStream  ' AStream3 is declared in Process_Globals in Page3 module
   AStream.Close  ' Close AsyncStreams in ChatActivity module
   StartActivity(Page3)  ' Open Page3
End Sub

In Page 3 I have the code:

B4X:
Sub Process_Globals
   Dim AStream3 As AsyncStreams
End Sub

Sub Activity_Create(FirstTime As Boolean)
   Activity.LoadLayout("LayoutPage3")
   If AStream3.IsInitialized = False Then
      AStream3.Initialize(Main.serial1.InputStream, Main.serial1.OutputStream, "AStream3")
   End If
End Sub

Sub AStream3_NewData (Buffer() As Byte)
[...]

If I don't close AStream before leaving ChatActivity module, I don't get error message "Connection is broken", but the connection in Page3 doesn't work correctly, that means many bytes are not received (it looks like half of the bytes go to Sub AStream_NewData in ChatActivity module, and the other half go to Sub AStream3_NewData in Page3 module).

I also tried to use directly the ChatActivity.AStream object in the Page3 module instead of declaring the new AStream3 object, but it is not accepted to write Sub ChatActivity.AStream_NewData (Buffer() As Byte).

How can I use AsyncStreams in different activity modules in the same application?
 

raphaelcno

Active Member
Licensed User
Longtime User
You should instead use a single service and handle the communication in the service.

Does it mean that it's possible to keep Sub AStream_NewData working normally in ChatActivity module while Page3 module is active (and then I can show incoming data in a view in LayoutPage3)? Or how should I keep a service active when I leave the activity module where the service was created? I think I understand how I can use a usual value (string, integer etc.) declared in Sub Process_Globals in another module, but how to do it with a service?
 
Upvote 0

raphaelcno

Active Member
Licensed User
Longtime User
Does it mean that it's possible to keep Sub AStream_NewData working normally in ChatActivity module while Page3 module is active (and then I can show incoming data in a view in LayoutPage3)? Or how should I keep a service active when I leave the activity module where the service was created?

Sorry for my previous question, I misunderstood the concept of service, I thought it was a part of a normal activity module... :sign0104:
I see now that there is a tutorial about service modules on http://www.b4x.com/forum/basic4android-getting-started-tutorials/7542-service-modules.html.
For the moment I still have an old version of B4A without service modules, but I will try again when I will upgrade to version 2.
 
Upvote 0

raphaelcno

Active Member
Licensed User
Longtime User
I have now moved AStream from ChatActivity module to a Service module, and it seems to work fine with several Activity modules :)

Here is my code in case other people want to do something similar.

Changes in the Main activity module:
B4X:
Sub Serial1_Connected (Success As Boolean)
   ProgressDialogHide
   Log("connected: " & Success)
   If Success = False Then
      Log(LastException.Message)
      ToastMessageShow("Error connecting: " & LastException.Message, True)
   Else
      ' NEW Start ServiceAStream module
      StartService(ServiceAStream)
      ' ORIGINAL
      StartActivity(ChatActivity)   
   End If
End Sub

New ServiceAStream module:
B4X:
Sub Process_Globals
   'These variables can be accessed from all modules.
   Dim AStream As AsyncStreams
   Dim MsgToSend As String
   Dim MsgToSendHex As String
   Dim MsgReceived As String
   Dim MsgReceivedHex As String
   Dim Conv As ByteConverter
End Sub

Sub Service_Create
   
End Sub

Sub Service_Start (StartingIntent As Intent)
   If AStream.IsInitialized Then AStream.Close  ' In case the connection was broken and restarted
   AStream.Initialize(Main.serial1.InputStream, Main.serial1.OutputStream, "AStream")
End Sub

Sub Service_Destroy
   AStream.Close
End Sub

' This Sub is called from Activity modules (ChatActivity or Page3)
' The Sub uses the variable MsgToSend declared in Process_Globals
Sub SendMsgBluetooth
   AStream.Write(MsgToSend.GetBytes("ISO-8859-1"))
End Sub

' This Sub is called from Activity modules (ChatActivity or Page3)
' to send hexadecimal message
Sub SendMsgHexBluetooth
   AStream.Write(Conv.HexToBytes(MsgToSendHex))
End Sub

B4X:
' Automatic event of AStream when receiving data
Sub AStream_NewData(Buffer() As Byte)
   ' The received message is stored in global variable accessible from Activity modules
   MsgReceived = BytesToString(Buffer, 0, Buffer.Length, "ISO-8859-1")
   MsgReceivedHex = Conv.HexFromBytes(Buffer)
   
   ' Activate Sub NewMsgFromServiceAStream in the active Activity module
   If IsPaused(ChatActivity) = False Then CallSub(ChatActivity, "NewMsgFromServiceAStream")
   If IsPaused(Page3) = False Then CallSub(Page3, "NewMsgFromServiceAStream")
End Sub

' Automatic event of AStream
Sub AStream_Error
   'ToastMessageShow("Connection is broken.", True)
   ToastMessageShow("Bluetooth-forbindelse er brutt.", True)
   
   ' Deactivate buttons in the active Activity module
   If IsPaused(ChatActivity) = False Then CallSub(ChatActivity, "DeactivateButtons")
   If IsPaused(Page3) = False Then CallSub(Page3, "DeactivateButtons")
End Sub

Sub AStream_Terminated
   AStream_Error
End Sub

Changes in the ChatActivity module (and also partly used in my new Page3 Activity module):
B4X:
Sub Process_Globals
'   (AStream moved to ServiceAStream:)
'   Dim AStream As AsyncStreams
End Sub

Sub Activity_Create(FirstTime As Boolean)
'   (AStream moved to ServiceAStream:)
'   If AStream.IsInitialized = False Then
'      AStream.Initialize(Main.serial1.InputStream, Main.serial1.OutputStream, "AStream")
'   End If
End Sub

Sub Activity_Pause (UserClosed As Boolean)
   If UserClosed Then
'      (AStream moved to ServiceAStream:)
'      AStream.Close
   End If
End Sub

' Sub AStream_NewData => Moved to ServiceAStream
' and replaced by Sub NewMsgFromServiceAStream

' NEW - This Sub is called from ServiceAStream when new data is received
Sub NewMsgFromServiceAStream
   ' The received message comes from the global variable MsgReceived from ServiceAStream
   LogMessage("You", ServiceAStream.MsgReceived)
End Sub

' Sub AStream_Error => Moved to ServiceAStream

' Sub AStream_Terminated => Moved to ServiceAStream

' Deactivate buttons when Bluetooth connection is broken
' This Sub is called from ServiceAStream
Sub DeactivateButtons
   btnSend.Enabled = False
   txtInput.Enabled = False
   btnSendHex.Enabled = False
   txtInputHex.Enabled = False
End Sub

B4X:
Sub btnSend_Click
'   ORIGINAL
'   AStream.Write(txtInput.Text.GetBytes("ISO-8859-1"))
'   NEW - MsgToSend is global variable in ServiceAStream
   ServiceAStream.MsgToSend = txtInput.Text
   CallSub(ServiceAStream, "SendMsgBluetooth")
   [...]
End Sub

' Send hexadecimal message after removing spaces " "
Sub btnSendHex_Click
   ServiceAStream.MsgToSendHex = txtInputHex.Text.Replace(" ", "")
   CallSub(ServiceAStream, "SendMsgHexBluetooth")
   [...]
End Sub
 
Upvote 0

todh

Member
Licensed User
Longtime User
Tri axial accelerometer communications

Raphael,
I have been attempting to use your modifications to get serial communications up and running but I can not even compile the code after making the mods. I am very new at B4A coding and most likely fat fingered the code. Is there any you can help me? I have been able to get the Bluetooth communications working and I am also able to request and receive the menu but when I attempt to get the data I can not read it. Erial recommended I try the Bluetooth Chat and that is where I am currently stuck.:BangHead:
 
Upvote 0

todh

Member
Licensed User
Longtime User
Learning curve

It has taken a while but I started some other projects and learned how to speak b4a. I got distracted by your page3 but know I understand. I carefully went through your changes and I have it working. Thanks for your help and posting. Serial data continues to be difficult to get correct. :sign0060:
 
Upvote 0
Top