DEV Community

Basic MQTT with C#

Eduardo Julião on July 04, 2021

In this post, we're going to have a look on how to work with MQTT and Csharp. Creating a Broker and a Client that sends data to it. But first... ...
Collapse
 
simondarksidej profile image
Simon (Darkside) Jackson

Great example and got me going quick and simple. Needs updating to the latest version of mqtt, but a fantastic start.

Collapse
 
djaus2 profile image
David Jones

This is a clear and simple guide for getting started with MQTTnet, Thanks.
I am looking at using it for sending Telemetry to an Azure IoT Hub. The only chenages I have made thus far are:

                MqttClientOptionsBuilder builder = new MqttClientOptionsBuilder()
                                        .WithClientId(Secrets.deviceId)
                                        .WithTcpServer(Secrets.IOT_CONFIG_IOTHUB_FQDN, 8883);
Enter fullscreen mode Exit fullscreen mode

IOT_CONFIG_IOTHUB_FQDN is of the form HUB_NAME.azure-devices.net
It "works" OK but doesn't report connect/non connection, but doesn't fail.
Does report non connection if incorrect Hub FQDN is used.

I understand I have to create a secure connection using the SAS key or connection string.
Any ideas of how to proceed? I can manually get the SAS key so can skip that code.

Thx in advance.

Collapse
 
djaus2 profile image
David Jones

Nb: Can attempt to send messages. They do get queued.

Collapse
 
djaus2 profile image
David Jones • Edited

Have improved my code. Got to work out Authentication:

                MqttClientOptionsBuilder builder = new MqttClientOptionsBuilder()
                                        .WithClientId(Secrets.deviceId)
                                        .WithTls()
                                        //.WithAuthentication( )
                                        .WithTcpServer(Secrets.IOT_CONFIG_IOTHUB_FQDN, Secrets.MqttPort);
Enter fullscreen mode Exit fullscreen mode
Collapse
 
nhatanhni profile image
nhatanhni

thanks

Collapse
 
qtaza profile image
QT

Thanks for this code example! 👍

In github code, you have ApplicationMessageReceivedHandler which is probably never called in this sample. (not working for me localy)

Collapse
 
codemaker profile image
codemaker

Nice article, Could you please give tutorial or article on enabling TLS on MQTT communication? also explain more on port 8883. It helps

Collapse
 
thanhdt2782 profile image
thanhdt2782

Thanks.

Collapse
 
simonong profile image
simonong

Hi: Is there anyway to poll the Topic and payload instead of using event?
or the broker will send the message periodically ?

Collapse
 
elgamily profile image
Hassan Elgamily

How to connect Client to Broker remotely on two different devices?

Collapse
 
rmaurodev profile image
Ricardo

According to the documentation there are multiple protocol communication you can use, such as websocket, socket and even http.

Check out the documentation for more details