#Region Project Attributes
#AutoFlushLogs: True
#CheckArrayBounds: True
#StackBufferSize: 300
#End Region
Sub Process_Globals
'These global variables will be declared once when the application starts.
'Public variables can be accessed from all modules.
Public Serial1 As Serial
Public WiFi As ESP8266WiFi
Public esp As ESP8266
Private mqtt As MqttClient
Public WiFiClient As WiFiSocket
Private username As String="test"
Private pwd As String="test123"
Private bc As ByteConverter
End Sub
Private Sub AppStart
Serial1.Initialize(115200)
Log("AppStart")
If WiFi.Connect2("EDIMAX","kh16@35d412t4878") Then
Log("Connected successfully to: ", "EDIMAX")
Dim serverIp() As Byte = Array As Byte(192, 168, 0, 82)
Log(WiFi.LocalIp)
mqtt.Initialize(WiFiClient.Stream, serverIp, 25645, "wemos_client", "Mqtt_MessageArrived", "Mqtt_Disconnected")
Connect(0)
Else
Log("Failed to connect.")
End If
End Sub
Sub Connect(unused As Byte)
Dim mo As MqttConnectOptions
mo.Initialize(username,pwd)
mo.SetLastWill("wemos/disconnect","wemos_client",0,False)
If mqtt.Connect2(mo) = False Then
Log("trying to connect again")
CallSubPlus("Connect", 1000, 0)
Return
End If
Log("Connected to broker")
mqtt.Subscribe("wemos/disconnect", 0)
mqtt.Subscribe("server_client", 0)
mqtt.Publish("wemos/connect","wemos_client")
End Sub
Sub Mqtt_Disconnected
Log("Disconnected")
mqtt.Close
Connect(0)
End Sub
Sub Mqtt_MessageArrived (Topic As String, Payload() As Byte)
Dim PayLoadStr As String = bc.StringFromBytes(Payload)
If Topic="wemos/connect" Then
Log("client_MessageArrived-" , Topic ,"-" , PayLoadStr)
Else If Topic="wemos/disconnect" Then
Log("client_MessageArrived-" , Topic , "-" , PayLoadStr)
Else If Topic="server_client" Then
Log("client_MessageArrived-" , Topic , "-" , PayLoadStr)
mqtt.Publish("wemos_client","wemos_client")
End If
End Sub