-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathHow to MQTT in C#
92 lines (77 loc) · 2.97 KB
/
How to MQTT in C#
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
// For å få uPLibarary til å virke trykker du i visual studio Tool -> NuGet Package Manager -> Manage NuGet Package Solution -> Browse -> Søk -> Plt.M2Mqtt og install
// På raspberry pi må du laste ned exe filen og M2Mqtt.Net.dll
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using uPLibrary.Networking.M2Mqtt;
using uPLibrary.Networking.M2Mqtt.Messages;
namespace mqtttest
{
public partial class Form1 : Form
{
MqttClient client;
string clientId;
Random rand = new Random();
public Form1()
{
InitializeComponent();
string BrokerAddress = "192.168.43.208";
client = new MqttClient(BrokerAddress);
// register a callback-function (we have to implement, see below) which is called by the library when a message was received
client.MqttMsgPublishReceived += client_MqttMsgPublishReceived;
// use a unique id as client id, each time we start the application
clientId = Guid.NewGuid().ToString();
client.Connect(clientId);
}
protected override void OnClosed(EventArgs e)
{
client.Disconnect();
base.OnClosed(e);
this.Close();
}
private void button1_Click(object sender, EventArgs e)
{
Button test = (Button)sender;
test.Text = rand.Next(99999).ToString();
if (txtTopicSubscribe.Text != "")
{
// whole topic
string Topic = txtTopicSubscribe.Text;
// subscribe to the topic with QoS 2
client.Subscribe(new string[] { Topic }, new byte[] { 2 }); // we need arrays as parameters because we can subscribe to different topics with one call
txtReceived.Text = "";
}
else
{
MessageBox.Show("You have to enter a topic to subscribe!");
}
}
private void button2_Click(object sender, EventArgs e)
{
Button test = (Button)sender;
test.Text = rand.Next(99999).ToString();
if (txtTopicPublish.Text != "")
{
// whole topic
string Topic = txtTopicPublish.Text;
// publish a message with QoS 2
client.Publish(Topic, Encoding.UTF8.GetBytes(txtPublish.Text), MqttMsgBase.QOS_LEVEL_EXACTLY_ONCE, true);
}
else
{
MessageBox.Show("You have to enter a topic to publish!");
}
}
void client_MqttMsgPublishReceived(object sender, MqttMsgPublishEventArgs e)
{
string ReceivedMessage = Encoding.UTF8.GetString(e.Message);
txtReceived.Invoke((MethodInvoker)(() => txtReceived.Text = ReceivedMessage));
}
}
}