B4R Question ESP8266 connection problems.

dragonguy

Active Member
Licensed User
Hi all,
i use esp8266 to connect to mqtt server, but sometime my esp8266 mqtt or wifi connection down and didn't connect back, i need manually press the reset button to connect again. how can i prevent this situation?

Below is my code:
B4X:
 Private Sub AppStart
    Connect2Network(0)
 End Sub
 
 Public Sub Connect2Network(unused As Byte)
    WiFi.Disconnect
    RunNative("SetSTA", Null)
    If WiFi.Connect2(SSID, Password) Then
        Log("Connected successfully to: ", SSID)
        ConnectToMqtt(0)
    Else   
        Log("Failed to connect.")
        CallSubPlus("Connect2Network", 30000,0)
    End If
End Sub

Private Sub ConnectToMqtt(unused As Byte)
    Log("ConnectToMQTT")
    Dim mo As MqttConnectOptions
    mo.SetLastWill("test/device_disconnect",get_device_id,0,False)
    mo.Initialize("test", "test1234") 'ignore
    Dim port As UInt = 1883
    Dim s As String  = JoinStrings(Array As String(get_device_id, Rnd(1000000,9999999)))
    mqtt.Initialize2(mqttSocket.Stream, "234.146.89.100", port,s, "mqtt_MessageArrived", "mqtt_Disconnected") 'ignore
    If mqtt.Connect2(mo)=False Then
        Log("Failed to connect to MQTT Server")
        mqtt.Close
        MqttConnected = False
        Log("trying to connect again")
        CallSubPlus("ConnectToMqtt", 30000,0)
        Return
    End If
    mqtt.Subscribe(get_device_id,0)
    mqtt.Subscribe("test/#",0)
    Log("mqtt connected : ",MqttConnected, " subcribe topic : ",get_device_id)
End Sub

Sub get_device_id As String
    espex.GetMacAddress(mac)
    Dim result As String
    result=JoinStrings(Array As String(prefix_id,bc.StringFromBytes(bc.HexFromBytes(mac))))
    Return result
End Sub

Sub mqtt_Disconnected
    Log("MQTT_Disconnected")
    ConnectToMqtt(0)
End Sub
Is it i can check the internet connection, if the internet connection broke i force disconnect the wifi and reconnect again. How to better way to check internet connection in B4R?

Thanks!
 
Top