I am trying to go data from a Mqtt-broker but I have no glue how to implement this in c#. Has anybody a solution for my problem?
CodePudding user response:
I would suggest taking a look at MQTTnet, which is probably the most popular .Net (C#) MQTT client/server package out there. It is well documented and actively maintained.
https://github.com/chkr1011/MQTTnet
Examples of connecting to a broker can be found on their wiki at:
https://github.com/chkr1011/MQTTnet/wiki/Client
Update with example code:
using MQTTnet;
using MQTTnet.Client.Connecting;
using MQTTnet.Client.Disconnecting;
using MQTTnet.Client.Options;
using MQTTnet.Client.Receiving;
using MQTTnet.Extensions.ManagedClient;
using System;
using System.Threading.Tasks;
namespace ConsoleSubscriber
{
class Program
{
static async Task Main()
{
var mqttClientId = "MyClientId"; // Unique ClientId or pass a GUID as string for something random
var mqttBrokerAddress = "127.0.0.1"; // hostname or IP address of your MQTT broker
var mqttBrokerUsername = "MyUsername"; // Broker Auth username if using auth
var mqttBrokerPassword = "MyPassword"; // Broker Auth password if using auth
var topic = "MyTopicOfData"; // topic to subscribe to
var mqttClient = new MqttFactory().CreateManagedMqttClient();
var mqttClientOptions = new ManagedMqttClientOptionsBuilder()
.WithAutoReconnectDelay(TimeSpan.FromSeconds(5))
.WithClientOptions(new MqttClientOptionsBuilder()
.WithTcpServer(mqttBrokerAddress)
.WithClientId(mqttClientId)
.WithCredentials(mqttBrokerUsername, mqttBrokerPassword) // Remove this line if no auth
.WithCleanSession()
.Build()
)
.Build();
mqttClient.ApplicationMessageReceivedHandler = new MqttApplicationMessageReceivedHandlerDelegate(e => MqttOnNewMessage(e));
mqttClient.ConnectedHandler = new MqttClientConnectedHandlerDelegate(e => MqttOnConnected(e));
mqttClient.DisconnectedHandler = new MqttClientDisconnectedHandlerDelegate(e => MqttOnDisconnected(e));
await mqttClient.SubscribeAsync(new MqttTopicFilterBuilder().WithTopic(topic).WithExactlyOnceQoS().Build());
await mqttClient.StartAsync(mqttClientOptions);
}
private static void MqttOnNewMessage(MqttApplicationMessageReceivedEventArgs e)
{
// Do something with each incoming message from the topic
Console.WriteLine($"MQTT Client: OnNewMessage Topic: {e.ApplicationMessage.Topic} / Message: {e.ApplicationMessage.Payload}");
}
private static void MqttOnConnected(MqttClientConnectedEventArgs e) => Console.WriteLine($"MQTT Client: Connected with result: {e.ConnectResult.ResultCode}");
private static void MqttOnDisconnected(MqttClientDisconnectedEventArgs e) => Console.WriteLine($"MQTT Client: Broker connection lost with reason: {e.Reason}.");
}
}