1
Open Discussion / Re: Anyone had any luck getting MQTT to work within AdvancedHMI?
« on: October 10, 2023, 05:57:19 AM »
First right click on AdvancedHMI in the Solution Explorer tab. Select Manage NuGet Packages. Click the Browse tab and search for "Plt.M2Mqtt" and install it.
At the very top of the coding page insert this:
At the beginning of the Public Class MainForm Declare the Client variable as follows:
I also declared my variables that I moved subscribed topic messages to.
On the Private Sub MainForm_Load I inserted the following:
I then added this sub:
For Publishing you can set it up in a clicked sub or a timer:
At the very top of the coding page insert this:
Code: [Select]
Imports System
Imports System.Reflection.Emit
Imports System.Text
Imports System.Windows.Forms.VisualStyles.VisualStyleElement
Imports uPLibrary.Networking.M2Mqtt
Imports uPLibrary.Networking.M2Mqtt.Messages
At the beginning of the Public Class MainForm Declare the Client variable as follows:
Code: [Select]
Dim client As MqttClient
I also declared my variables that I moved subscribed topic messages to.
Code: [Select]
Dim client As MqttClient
Dim t1_temp As String
Dim t1_humidity As String
On the Private Sub MainForm_Load I inserted the following:
Code: [Select]
Try
client = New MqttClient("<Broker IP>", 1883, False, Nothing, Nothing, MqttSslProtocols.None)
Dim clientId As String = "HMI"
AddHandler client.MqttMsgPublishReceived, AddressOf Client_MqttMsgPublishReceived
AddHandler client.ConnectionClosed, AddressOf Client_Disconnect
client.Connect(clientId, "<user name>", "<password>")
Catch ex As Exception
ToolStripStatusLabel1.Text = "Error mqtt connect."
MsgBox(ex.Message(), MsgBoxStyle.Critical)
End Try
Try
Dim topics() As String = {"t1_temp", "t1_humidity"}
Dim qosLevels() As Byte = {MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE, MqttMsgBase.QOS_LEVEL_AT_LEAST_ONCE}
client.Subscribe(topics, qosLevels)
Catch ex As Exception
ToolStripStatusLabel1.Text = "Error mqtt subcribe"
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try
I then added this sub:
Code: [Select]
Private Sub Client_MqttMsgPublishReceived(ByVal sender As Object, ByVal e As MqttMsgPublishEventArgs)
If e.Topic = "t1_temp" Then
t1_temp = System.Text.Encoding.UTF8.GetString(e.Message)
ElseIf e.Topic = "t1_humidity" Then
t1_humidity = System.Text.Encoding.UTF8.GetString(e.Message)
End If
End Sub
For Publishing you can set it up in a clicked sub or a timer:
Code: [Select]
Try
Dim Qos As Byte = 1
client.Publish("<Topic>", Encoding.Default.GetBytes(<Variable that holds message> ), Qos, False)
Catch ex As Exception
ToolStripStatusLabel1.Text = "Error"
MsgBox(ex.Message, MsgBoxStyle.Critical)
End Try