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:
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:
Dim client As MqttClient
I also declared my variables that I moved subscribed topic messages to.
Dim client As MqttClient
Dim t1_temp As String
Dim t1_humidity As String
On the Private Sub MainForm_Load I inserted the following:
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:
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:
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