Spanish Chat Bluetooth [Solucionado]

carlos7000

Active Member
Licensed User
Hola a todos.

Estoy tratando de crear una sencilla aplicación que permita enviar comandos y recibir respuestas de un arduino.

Este es el código que estoy empleando.

B4X:
#Region  Project Attributes
    #ApplicationLabel: B4A Example
    #VersionCode: 1
    #VersionName:
    'SupportedOrientations possible values: unspecified, landscape or portrait.
    #SupportedOrientations: unspecified
    #CanInstallToExternalStorage: False
#End Region

#Region  Activity Attributes
    #FullScreen: False
    #IncludeTitle: True
#End Region

Sub Process_Globals
    'These global variables will be declared once when the application starts.
    'These variables can be accessed from all modules.
 
    Dim Serial1 As Serial
End Sub

Sub Globals
    'These global variables will be redeclared each time the activity is created.
    'These variables can only be accessed from this module.
    Type NameAndMac(Name As String, Mas As String)
    Dim BTadmin As BluetoothAdmin
 
    Dim Ast As AsyncStreams
    Dim Conected As Boolean
 
    Private ButtonConnectar As Button
    Private ButtonDesconectar As Button
    Private LabelStatus As Label
    Private LabelSend As Label
    Private EditTextSend As EditText
    Private ButtonSend As Button
End Sub

Sub Activity_Create(FirstTime As Boolean)
    'Do not forget to load the layout file created with the visual designer. For example:
    Activity.LoadLayout("Layout1")
 
    If FirstTime Then
        BTadmin.Initialize("BT")
        Serial1.Initialize("Serial1")
    End If
End Sub

Sub Activity_Resume
    If BTadmin.IsEnabled = False Then
        If BTadmin.Enable = False Then
            ToastMessageShow("Bluetooth: Apagado. Enciendalo.", True)
        Else
            ToastMessageShow("Turn on bluetooth...", True)    
        End If
    Else
        BT_StateChanged(BTadmin.STATE_ON, 0)
    End If
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    If UserClosed Then
        Ast.Close
        Serial1.Disconnect
     
        Activity.Finish
        ExitApplication
    End If
End Sub

Private Sub admin_StateChanged(NewState As Int, OldState As Int)
 
End Sub

Private Sub EventName_Connected (Success As Boolean)
    ProgressDialogHide
    If Success Then
        ToastMessageShow("Conectado!", True)
        Conected = True
     
        If Ast.IsInitialized Then Ast.Close    
        Ast.Initialize(Serial1.InputStream, Serial1.OutputStream, "ast")
     
        If Conected Then
            Dim buf As String
            buf = "0" & Chr(10)
            Ast.Write(buf.GetBytes("UTF8"))
        End If
    Else
        Conected = False
        ToastMessageShow("Conección fallida!", True)
    End If
End Sub

Sub ast_error
    ToastMessageShow("Network Error", True)
End Sub

Sub ast_Terminated
    ToastMessageShow("Conexión rota", True)
End Sub

Sub ButtonConnectar_Click
    Dim PairedDevices As Map
    PairedDevices = Serial1.GetPairedDevices
 
    Dim il As List
    il.Initialize
 
    For i = 0 To PairedDevices.Size - 1
        il.Add(PairedDevices.GetKeyAt(i))    
    Next
 
    Dim res As Int
    res = InputList(il, "Select devices", -1)
 
    If (res <> DialogResponse.CANCEL) Then
        Serial1.Connect(PairedDevices.Get(il.Get(res)))
        LabelStatus.Text = "Status: Conectado"    
        Conected = True
    End If
 
End Sub

Sub ButtonDesconectar_Click
    Ast.Close
    Serial1.Disconnect
    Conected = False
 
    LabelStatus.Text = "Status: Desconectado"
End Sub

Sub ButtonSend_Click
    If Conected = True Then    
        EditTextSend.Text = EditTextSend.Text & Chr(10)
        Ast.Write(EditTextSend.Text.GetBytes("UTF8"))
        EditTextSend.Text= ""
    End If
End Sub

Public Sub ast_NewData (Buffer() As Byte)
    ToastMessageShow(Buffer, True)
End Sub

Public Sub ast_NewStream (Dir As String, FileName As String)
    ToastMessageShow (Dir, True)
End Sub
 
Public Sub BT_StateChanged (NewState As Int, OldState As Int)
    ToastMessageShow("Estado: " & NewState, True)
End Sub
Pero no funciona.

Estuve mirando el ejemplo que enconter en este link https://www.b4x.com/android/forum/threads/android-bluetooth-bluetoothadmin-tutorial.14768/

Pero el programa tampoco funciona. Al ejecutarlo aparece
Connection is broken
Supongo que podría ser porque está diseñado para chatear entre dos celulares.

¿Alguien me podría, por favor, ayudar?

Saludos.
 
Last edited:

carlos7000

Active Member
Licensed User
Ya encontré el problema.

El programa no funcionaba debido a que configure el programa como dice aquí:

When you initialize AStream you should use Initialize instead InitializePrefix. InitializePrefix can only be used when you are following the prefix mode protocol which is explained in the first post.
Eso solo debe hacerse si el programa se emplea para chatear con la misma aplicación en otro celular. Cosa que yo no iba a hacer. Eso causaba el problema. ;-)

Nota:

El código que inicialmente coloqué, nunca me funcionó. Por lo que las pruebas y la solución las realicé con el archivo de ejemplo que encontré en este link https://www.b4x.com/android/forum/threads/android-bluetooth-bluetoothadmin-tutorial.14768/
 
Last edited:
Top