Sub Process_Globals
Private Py As PyBridge
Private mqtt As MqttClient
Private MqttWorking As Boolean = True
End Sub
Sub AppStart (Args() As String)
Start
StartMessageLoop
End Sub
'This event will be called once, before the page becomes visible.
Private Sub Start
Py.Initialize(Me, "Py")
Dim opt As PyOptions = Py.CreateOptions("Python/python/python.exe")
Py.Start(opt)
Wait For Py_Connected (Success As Boolean)
If Success = False Then
LogError("Failed to start Python process.")
Return
End If
ConnectAndReconnect ("tcp://192.168.1.153:1883", "PC")
End Sub
Sub ConnectAndReconnect (uri As String, ClientId As String)
Do While MqttWorking
If mqtt.IsInitialized Then mqtt.Close
Do While mqtt.IsInitialized
Sleep(100)
Loop
mqtt.Initialize("mqtt", uri, ClientId)
Dim mo As MqttConnectOptions
mo.Initialize("", "")
Log("Trying to connect")
mqtt.Connect2(mo)
Wait For Mqtt_Connected (Success As Boolean)
If Success Then
Log("Mqtt connected")
AfterConnected
Do While MqttWorking And mqtt.Connected
mqtt.Publish2("ping", Array As Byte(0), 1, False) 'change the ping topic as needed
Sleep(5000)
Loop
Log("Disconnected")
Else
Log("Error connecting.")
End If
Sleep(5000)
Loop
End Sub
Private Sub AfterConnected
mqtt.Subscribe("rpi", mqtt.QOS_1_LEAST_ONCE)
End Sub
Private Sub Mqtt_MessageArrived (Topic As String, Payload() As Byte)
Log($"message arrived: ${Topic}"$)
If Topic = "rpi" Then
ShowNotification("Message from RPi", BytesToString(Payload, 0, Payload.Length, "utf8"), "B4J") _
.ArgNamed("image", "C:\Users\H\Downloads\172694.png")
End If
End Sub
Private Sub mqtt_Disconnected
Log("disconnected")
End Sub
Private Sub ShowNotification(Title As String, Body As String, AppId As String) As PyWrapper
Dim toast As PyWrapper = Py.ImportModuleFrom("win11toast", "toast")
Return toast.Call.Arg(Title).Arg(Body).ArgNamed("app_id", AppId)
End Sub
Private Sub CloseProgram 'ignore
MqttWorking = False
Py.KillProcess
Sleep(100)
StopMessageLoop
End Sub
Private Sub Py_Disconnected
Log("PyBridge disconnected")
End Sub