B4R Question Send Mqtt data Receive app

Cesar_Morisco

Active Member
Hey guys
As I said Getting Started Using MQTT
I need to send the temperature of the esp8266 to my app It's giving an error
here is the snippet of my code.
Thank you already
B4R:
Sub mqtt_publish(Topic As String,msg As String)
    If connected=True Then
        mqtt.Publish(Topic,msg.GetBytes)
    Else
        Log("Publishg, ERROR ! MQTT Not Connected")
    End If
End Sub

Sub Temp
    Dim TempESP32 As String = 23 'Graus teste
    mqtt_publish("temperature/",TempESP32)
End Sub
B4A:
Sub mqtt_MessageArrived(Topic As String, payload()As Byte)
    Dim obj As Object = serializator.ConvertBytesToObject(payload)
    EditText1.Text=obj
    End Sub
 

candide

Active Member
Licensed User
Dim obj As Object = serializator.ConvertBytesToObject(payload)
in esp you are sending a string directly, without to use serializator but you want to convert a byte array to object at reception in B4A.
in B4A you can try without serializator and you should see string sent ..
 
Upvote 0

Cesar_Morisco

Active Member
in esp you are sending a string directly, without to use serializator but you want to convert a byte array to object at reception in B4A.
in B4A you can try without serializator and you should see string sent ..
Hello Candide how are you?
It keeps crashing and crashing

I don't even know if it works, what I'm trying to do is show the status of the relay on and off
Thanks for your help

B4A:
Sub mqtt_MessageArrived(Topic As String, payload()As Byte)
    EditText1.Text = BytesToString(payload,0,payload.Length,"UTF-8")
    End Sub
B4R:
Sub Temp
    SendSelect(Array(ClientId, "Select_led", "tag", 539))
End Sub

Sub SendSelect(Message() As Object)
    mqtt.Publish("Select", ser.ConvertArrayToBytes(Message))
End Sub
 
Upvote 0

XorAndOr

Active Member
Licensed User
Longtime User
I need to send the temperature of the esp8266 to my app
You have to use the OneWire library.
After you have the value in Double... you send it to android with
mqtt_publish("temperature/", BC.StringToBytes(NumberFormat(celsius, 0, 1)))

anyway for your question....
B4R:
'Process_Globals
Private bc As ByteConverter

Sub Temp 
  Dim TempESP32 As String = 23 'Graus teste
  mqtt_publish("temperature/",bc.StringToBytes(TempESP32))
End Sub
B4A:
'Class_Globals
Private Temp As String
Private bc As ByteConverter
'................................................. ..................
Private Sub MQTT_MessageArrived (Topic As String, Payload() As Byte)
      Temp = bc.StringFromBytes(Payload,"utf8")
      Log(Temp)
      EditText1.Text = Temp
End Sub
 
Upvote 0

Cesar_Morisco

Active Member
You have to use the OneWire library.
After you have the value in Double... you send it to android with
mqtt_publish("temperature/", BC.StringToBytes(NumberFormat(celsius, 0, 1)))

anyway for your question....
B4R:
'Process_Globals
Private bc As ByteConverter

Sub Temp
  Dim TempESP32 As String = 23 'Graus teste
  mqtt_publish("temperature/",bc.StringToBytes(TempESP32))
End Sub
B4A:
'Class_Globals
Private Temp As String
Private bc As ByteConverter
'................................................. ..................
Private Sub MQTT_MessageArrived (Topic As String, Payload() As Byte)
      Temp = bc.StringFromBytes(Payload,"utf8")
      Log(Temp)
      EditText1.Text = Temp
End Sub
Thanks for your response
I am not getting the test temperature example 23 I get true and False when I press the button
 

Attachments

  • Sem título.png
    Sem título.png
    161.5 KB · Views: 145
Upvote 0

josejad

Expert
Licensed User
Longtime User
I'm not in my computer now, but if I remember well, I sent a string in this example.

 
Upvote 0

Cesar_Morisco

Active Member
I'm not in my computer now, but if I remember well, I sent a string in this example.

Hello José, how are you? About your project I didn't see you use this code here
B4A:
Private Sub MQTT_MessageArrived (Topic As String, Payload() As Byte)
       code here
End Sub

It is not necessary
To receive the MQTT data
Thank you from the heart
 
Upvote 0

XorAndOr

Active Member
Licensed User
Longtime User
I did with you said and nothing to receive data
my example code was referring to post #1

now I see that in post #3 everything changes when publishing the temperature
you make use of object.
can we know what is the "true" code with which you send the temperature?
I know it's not that simple for you, but it's certainly much more complicated for those who want to help you,
we don't have the project.
you need to be more clear in the questions, and attach the right code.
 
Upvote 0

Cesar_Morisco

Active Member
my example code was referring to post #1

now I see that in post #3 everything changes when publishing the temperature
you make use of object.
can we know what is the "true" code with which you send the temperature?
I know it's not that simple for you, but it's certainly much more complicated for those who want to help you,
we don't have the project.
you need to be more clear in the questions, and attach the right code.
right my friend
here my code
B4R:
Sub Process_Globals
    Public Serial1 As Serial
    Public Wifi As ESP8266WiFi
    Public esp As ESP8266
    Public eeprom As EEPROM
    Private const MAGIC_EEPROM As Byte = 213
    Private sr As B4RSerializator
    Private bc As ByteConverter
    Public mqtt As MqttClient
    Private mqttSocket As WiFiSocket
    Private MQTTOpt As MqttConnectOptions
   
    Private d1 As D1Pins
    Private PinGPIO05 As Pin
    Private PinGPIO04 As Pin
    Private PinGPIO00 As Pin
    Private PinGPIO15 As Pin
    Private PinGPIO13 As Pin
    Private PinGPIO12 As Pin
    Private PinGPIO14 As Pin
    Private PinGPIO16 As Pin
    Private bc As ByteConverter
    Private State As Boolean
    Public Timer1 As Timer
End Sub

Private Sub AppStart
    Serial1.Initialize(115200)
    Log("AppStart")
   
   
    PinGPIO05.Initialize(d1.D1,PinGPIO05.MODE_OUTPUT)'Pin D2 ESP Relay 1
    PinGPIO04.Initialize(d1.D2,PinGPIO04.MODE_OUTPUT)'Pin D5 ESP Relay 2
    PinGPIO00.Initialize(d1.D3,PinGPIO00.MODE_OUTPUT)'Pin D6 ESP Relay 3
    PinGPIO15.Initialize(d1.D8,PinGPIO15.MODE_OUTPUT)'Pin D7 ESP Relay 4
    PinGPIO13.Initialize(d1.D7,PinGPIO13.MODE_OUTPUT)'Pin D2 ESP Relay 5
    PinGPIO12.Initialize(d1.D6,PinGPIO12.MODE_OUTPUT)'Pin D5 ESP Relay 6
    PinGPIO14.Initialize(d1.D5,PinGPIO14.MODE_OUTPUT)'Pin D6 ESP Relay 7
    PinGPIO16.Initialize(d1.D0,PinGPIO16.MODE_OUTPUT)'Pin D7 ESP Relay 8
   
    'Set Desligar Pinos ESP
    PinGPIO05.DigitalWrite(False)
    PinGPIO04.DigitalWrite(False)
    PinGPIO00.DigitalWrite(False)
    PinGPIO15.DigitalWrite(False)
    PinGPIO13.DigitalWrite(False)
    PinGPIO12.DigitalWrite(False)
    PinGPIO14.DigitalWrite(False)
    PinGPIO16.DigitalWrite(False)
   
    WiFiServer.Start
    ConnectToNetwork
    Timer1.Initialize("Temp",1000)
    Timer1.Enabled=True
End Sub

Public Sub ConnectToNetwork
    Wifi.Disconnect
 If GetStoredData = 1 Then
    'read settings from EEPROM
          Dim SSID As String = bc.StringFromBytes(GStore1.slot0) 'ignore
        Dim Password As String = bc.StringFromBytes(GStore1.slot1) 'ignore" '
        Log("Tentando se Conectar a: ", SSID, " Senha: ", Password)
        If Wifi.Connect2(SSID,Password) Then
            Log("Conectado com Sucesso : ", GStore1.slot0)
            Log("IP Local: ", Wifi.LocalIp)
            StopAP
            ConnectToMqtt
       Else
            Log("WIFI Falha ao Se Conectar - Iniciar WifiServer ")
            WiFiServer.Start
      End If
    Else
        Log("Dados de Rede não Encontrados .")
        WiFiServer.Start
    End If
End Sub

Public Sub SaveNetworkDetails(Data() As Byte)
    Log("Salvando dados de Rede")
    Log("Comprimento de Dados : ", Data.Length)
    Log("Memoria=", AvailableRAM)
    Log("Tamanho :",StackBufferUsage)
    eeprom.WriteBytes(Array As Byte(MAGIC_EEPROM, Data.Length), 0)
    eeprom.WriteBytes(Data, 2)
    ConnectToNetwork
End Sub

Private Sub ConnectToMqtt
    mqtt.Initialize2(mqttSocket.Stream, bc.StringFromBytes(GStore1.slot2),bc.StringFromBytes(GStore1.slot3), bc.StringFromBytes(GStore1.slot4), "mqtt_MessageArrived", "mqtt_Disconnected") 'ignore
    MQTTOpt.Initialize(bc.StringFromBytes(GStore1.Slot5),bc.StringFromBytes(GStore1.slot6))
   
    If mqtt.Connect2(MQTTOpt) = False Then
        Log("Erro de Conexão com o Broker")
Else
        Log("Nova Conexão Com o broker OK")
        'Subscribe to topic = to B4J/B4A/B4i/B4R/WebApp/Html......
        mqtt.Subscribe("Control_Rele8/#",1) '<---Mude o nome do tópico!
        mqtt.Subscribe("Rele_A",1)'         <---Mude o nome do tópico!
        mqtt.Subscribe("Rele_B",1)'         <---Mude o nome do tópico!
        mqtt.Subscribe("Rele_C",1)'         <---Mude o nome do tópico!
        mqtt.Subscribe("Rele_D",1)'         <---Mude o nome do tópico!
        mqtt.Subscribe("Rele_E",1)'         <---Mude o nome do tópico!
        mqtt.Subscribe("Rele_F",1)'         <---Mude o nome do tópico!
        mqtt.Subscribe("Rele_G",1)'         <---Mude o nome do tópico!
        mqtt.Subscribe("Rele_H",1)'         <---Mude o nome do tópico!
    End If

End Sub

Sub mqtt_MessageArrived(Topic As String, payload()As Byte)
    If bc.StringFromBytes(payload) = "true" Then State = True Else State = False
    Log(Topic," ",Not(State))
    Select Case Topic
        Case "Rele_A"
            PinGPIO05.DigitalWrite(Not(State))'Relay 1
        Case "Rele_B"
            PinGPIO04.DigitalWrite(Not(State))'Relay 2
        Case "Rele_C"
            PinGPIO00.DigitalWrite(Not(State))'Relay 3
        Case "Rele_D"
            PinGPIO15.DigitalWrite(Not(State))'Relay 4
        Case "Rele_E"
            PinGPIO13.DigitalWrite(Not(State))'Relay 5
        Case "Rele_F"
            PinGPIO12.DigitalWrite(Not(State))'Relay 6
        Case "Rele_G"
            PinGPIO14.DigitalWrite(Not(State))'Relay 7
        Case "Rele_H"
            PinGPIO16.DigitalWrite(True) '(Not(State))'Relay 8
            CallSubPlus("Rele_Portao",1000, 1)'---> Sub
    End Select
End Sub

'Motor Garage impulse OFF
Sub Rele_Portao(Tag As Byte)
    PinGPIO16.DigitalWrite(False)'Relay 4 OFF Motor Garage
End Sub

Sub Temp
    Dim TempESP32 As String = 23 'Graus teste
    mqtt.Publish("temperature",bc.StringToBytes(TempESP32))
    Log("Temperature ",TempESP32)
End Sub

public Sub mqtt_Disconnected
    Log("MQTT_Disconnected")
End Sub


Public Sub GetStoredDataLength As Byte
    Dim header() As Byte = eeprom.ReadBytes(0, 2)
    If header(0) = MAGIC_EEPROM Then
        Return header(1)
    End If
    Return 0
End Sub

Sub    GetStoredData As Byte
    Dim length As Byte = GetStoredDataLength  
    Log("Parâmetros do Wifi Salvo na Eeprom  =",length)
    If length > 0 Then
        Dim ObjectsBuffer(8) As Object
        Dim Data() As Byte = eeprom.ReadBytes(2, length)
        Dim Objects() As Object = sr.ConvertBytesToArray(Data, ObjectsBuffer)
        If Objects.Length <> 0 Then
          For i = 0 To 7
          GStore1.Put(i,Objects(i))
          Next
          Return 1
        Else
          Return 0
        End If  
    Else
        Return 0  
    End If        
End Sub

Public Sub ClearStoredDataLength
    Dim header() As Byte = eeprom.ReadBytes(0, 2)
    If header(0) = MAGIC_EEPROM Then
        header(1) = 0
        eeprom.WriteBytes(header,0)  
        Log("Eeprom Apagada")
    End If
    GStore1.Slot0(" ")
    GStore1.Slot1(" ")
    Delay(100)
    esp.restart
End Sub

public Sub StopAP
    Log("Stop AP")
    RunNative("stopAP", Null)
End Sub
#if C
  #include <ESP8266WiFi.h>
  void stopAP (B4R::Object* u) {
  WiFi.softAPdisconnect(1);
  }
#end if
B4A:
'MQTT CONNECT AND SUBSCRIBE TO TOPIC
Sub MQTT_Connected (Success As Boolean)
    If Success = False Then
        Log(LastException)
        xui.MsgboxAsync("Error de Conexão","")
    Else
        Conectar.Text = "Conectado"
        Conectar.TextColor = xui.Color_Red
        MQTT.Subscribe("Control_Rele8/#", 1)'change the name of the topic!
        MQTT.Subscribe("Rele_A",1)'change the name of the topic!
        MQTT.Subscribe("Rele_B",1)'change the name of the topic!
        MQTT.Subscribe("Rele_C",1)'change the name of the topic!
        MQTT.Subscribe("Rele_D",1)'change the name of the topic!
        MQTT.Subscribe("Rele_E",1)'change the name of the topic!
        MQTT.Subscribe("Rele_F",1)'change the name of the topic!
        MQTT.Subscribe("Rele_G",1)'change the name of the topic!
        MQTT.Subscribe("Rele_H",1)'change the name of the topic!
    End If
End Sub

Sub B4XPage_MenuClick (Tag As String)
    If Tag = "menu" Then 'für iOS Hauptmenü, quasi Sub pg_BarButtonClick (Tag As String)
        #if B4i
        Dim sheet As ActionSheet
        sheet.Initialize("sheet", "", "Cancel", "", s_Menu)
        sheet.Show(Root)
        Wait For sheet_Click (result As String)
        B4XPage_MenuClick(result)
        #End If
    Else
        Dim iIndex As Int = GetIndexInArray(s_Menu, Tag)
        Select iIndex
            Case 0 'Configurar
                Panel1.Visible=True
                Panel2.Visible=False
                'Panel3.Visible=False
            Case 1 'Controle
                Panel2.Visible=True
                Panel1.Visible=False
                'Panel3.Visible=False
            'Case 2 'Controle
                'Panel3.Visible=True
                'Panel1.Visible=False
                'Panel2.Visible=False
        End Select
    End If
End Sub

Sub GetIndexInArray(arr() As String, txt As String) As Int
    Dim iIndex As Int = -1, iCount As Int = 0
    For Each sTxt As String In arr
        If sTxt = txt Then iIndex = iCount
        iCount = iCount + 1
    Next
    Return iIndex
End Sub

Private Sub Conectar_Click
    If Conectar.Text = "Conectado" Then
        xui.MsgboxAsync("Você está Conectado!","Casa Controle 1")
    Else
        MQTT_Connect
    End If
End Sub

Sub mqtt_MessageArrived(Topic As String, payload()As Byte)
    Temp = BC.StringFromBytes(payload,"utf8")
    Log(Temp)
    EditText1.Text = Temp
End Sub
    


Private Sub Desconectar_Click
    If MQTT.IsInitialized Then
        MQTT.Close
    End If
    ExitApplication
End Sub
 
Upvote 0

XorAndOr

Active Member
Licensed User
Longtime User
here my code
When you publish something to mqtt with mqtt.Publish("temperature",bc.StringToBytes(TempESP32))
In B4A where is the subscription "temperature"???
You should add :
B4X:
MQTT.Subscribe("Control_Rele8/#", 1)
MQTT.Subscribe("Rele_A",1)
MQTT.Subscribe("Rele_B",1)
MQTT.Subscribe("Rele_C",1)
MQTT.Subscribe("Rele_D",1)
MQTT.Subscribe("Rele_E",1)
MQTT.Subscribe("Rele_F",1)
MQTT.Subscribe("Rele_G",1)
MQTT.Subscribe("Rele_H",1)

MQTT.Subscribe("temperature",1)'<--- ADD
 
Upvote 0

Cesar_Morisco

Active Member
There are 2 things I would like to tell you...
1) Don't just copy the codes, study them too.
2) change the name of mqtt Topic, otherwise we'll turn on the lights in your home!!
Hello XorAndOr How are you. kkkkkk
Yes I will change.
About the codes I'm already studying yes
Just like I said, you're the one who told me about MQTT. For me, your project reassured me.

Simple question for you how to remove the true and false when I press the button
 
Upvote 0

Cesar_Morisco

Active Member
I have no idea why you get that true/false
here on editex I don't see true-false
try renaming the "temperature" topic to Temperature both in b4r publish and b4a subscribe
sorry weight
I'm even a little embarrassed to post here
As I said this is new to me.
On my board I have a sensor ds18b20 ne
With your help and the example it had works.
Then I added the code using OneWire
After I went to realize that it wasn't my temperature that I was receiving, I didn't check with my display
 
Upvote 0

Cesar_Morisco

Active Member
Is this a new question?
Hello XorAndOr
B4R:
Private Sub ReadTemparature (u As Byte)
    onewire.Reset
    onewire.Select(address)
    onewire.Write(0xBE, False)
    Dim data(12) As Byte
    onewire.ReadBytes(data, 9)
    Dim raw As Int = Bit.Or(Bit.ShiftLeft(data(1), 8), data(0))
    If type_s Then
        raw = Bit.ShiftLeft(raw, 3)
        If data(7) = 0x10 Then
            raw = Bit.And(raw, 0xFFF0) + 12 - data(6)
        End If
    Else
        Dim cfg As Byte = Bit.And(data(4), 0x60)
        If cfg = 0 Then
            raw = Bit.And(raw, Bit.Not(7))
        Else if cfg = 0x20 Then
            raw = Bit.And(raw, Bit.Not(3))
        Else if cfg = 0x40 Then
            Bit.And(raw, Bit.Not(1))
        End If
    End If
    Dim celsius As Double = raw/16
    Log("Temp_Ds = ", NumberFormat(celsius,0,1),"°C")
    mqtt.Publish("Temp_Ds" , NumberFormat(celsius,0,1))
End Sub

It's working fine
The only problem that I keep showing false and true in the temperature when pressing the button
B4A:
MQTT.Subscribe("Temp_Ds",1)'Temperature name had to change I worked
   

Sub mqtt_MessageArrived(Topic As String, payload()As Byte)
    Temp = BC.StringFromBytes(payload,"utf8")
    EditText1.Text = Temp & "°C"
    End Sub
Yes OneWire and that reads the Sensor DS18B20 that is on my board to compare the reading in the Log and the MQTT
 
Upvote 0

XorAndOr

Active Member
Licensed User
Longtime User
The only problem that I keep showing false and true in the temperature when pressing the button
I don't know exactly, but... If you only need the temperature in

B4A:
Sub mqtt_MessageArrived(Topic As String, payload()As Byte)
    Temp = BC.StringFromBytes(payload,"utf8")
    EditText1.Text = Temp & "°C"
End Sub
In B4A you have to comment
B4A:
'MQTT.Subscribe("Rele_A",1)
'MQTT.Subscribe("Rele_B",1)
'MQTT.Subscribe("Rele_C",1)
'MQTT.Subscribe("Rele_D",1)
'MQTT.Subscribe("Rele_E",1)
'MQTT.Subscribe("Rele_F",1)
'MQTT.Subscribe("Rele_G",1)
'MQTT.Subscribe("Rele_H",1)
Otherwise the Broker also sends to you what you send to ESP
that's why you have "true" and "false" ...
it would be the command you send to the esp ... but it returns to you in B4A on EditText

While if you also want the return of the status of the relays you only have to change the subscribe slightly.
 
Upvote 0
Top