You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
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 with ID: [{CLIENT_ID}].");
|
|
|
|
|
|
|
|
|
|
await _mqttClient.SubscribeAsync(new MqttTopicFilterBuilder()
|
|
|
|
|
.WithTopic(TOPIC)
|
|
|
|
|
.Build());
|
|
|
|
|
|
|
|
|
|
Console.WriteLine($"Subscribed to topic '{TOPIC}'");
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|