mqtt sample
This commit is contained in:
49
MQTTSample/MqttSubscriberApp/Program.cs
Normal file
49
MQTTSample/MqttSubscriberApp/Program.cs
Normal file
@@ -0,0 +1,49 @@
|
||||
using MQTTnet.Client;
|
||||
using MQTTnet;
|
||||
using System.Text;
|
||||
|
||||
namespace MqttSubscriberApp
|
||||
{
|
||||
internal class Program
|
||||
{
|
||||
private static IMqttClient _mqttClient;
|
||||
private static string CLIENT_ID = $"SubscriberClient_{Random.Shared.Next(1, 1000)}";
|
||||
private static string SERVER_IP = "localhost";
|
||||
private static readonly int PORT = 1883;
|
||||
private static readonly string TOPIC = "home/kitchen/temperature";
|
||||
|
||||
static async Task Main(string[] args)
|
||||
{
|
||||
var mqttFactory = new MqttFactory();
|
||||
_mqttClient = mqttFactory.CreateMqttClient();
|
||||
|
||||
var options = new MqttClientOptionsBuilder()
|
||||
.WithClientId(CLIENT_ID)
|
||||
.WithTcpServer(SERVER_IP, PORT)
|
||||
.Build();
|
||||
|
||||
_mqttClient.ConnectedAsync += MqttClient_ConnectedAsync;
|
||||
_mqttClient.ApplicationMessageReceivedAsync += MqttClient_ApplicationMessageReceivedAsync;
|
||||
|
||||
await _mqttClient.ConnectAsync(options);
|
||||
Console.ReadLine();
|
||||
}
|
||||
|
||||
private static async Task MqttClient_ApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs arg)
|
||||
{
|
||||
var message = Encoding.UTF8.GetString(arg.ApplicationMessage.PayloadSegment);
|
||||
Console.WriteLine($"Received message: {message}");
|
||||
}
|
||||
|
||||
private static async Task MqttClient_ConnectedAsync(MqttClientConnectedEventArgs arg)
|
||||
{
|
||||
Console.WriteLine("Connected to broker.");
|
||||
|
||||
await _mqttClient.SubscribeAsync(new MqttTopicFilterBuilder()
|
||||
.WithTopic(TOPIC)
|
||||
.Build());
|
||||
|
||||
Console.WriteLine($"Subscribed to topic '{TOPIC}'");
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user