First internet of things application.
First step is to install nuget packages for mqtt. MQTTnet, MQTTnet.Extensions.ManagedClient.
Mqtt has three components: broker, subscriber and publisher. We have two ways how we can run broker. Make a small console application or run docker with a broker server. I prefer to run docker. Be default mosquitto listen port 1883, our publisher and subscriber will interact with this port.
Let’s write code. Basically we are creating a library, our wrappers on mqtt and we can set up from outside like connection options, credentials and logger.
We are still gonna make our own broker. Broker will give us notifications about intercepting data and when somebody will make a connection with the broker.
Subscriber and publisher are having the same code. The only difference is the publisher knows how to publish messages.
All magic we put in the create method. There we make a couple events onConnect OnDisconnect and subscribe to a topic.
Instead of copy pasting it is better to inherit all code for subscribe and method publish message.
It’s time to test to make a console application. Our subscriber using events that we defined in it, the most important one is onMessageReceived. Here we create a connection with a broker that is run in docker, in the connection we put a broker address and topic that we want to listen to.
In a publisher we use the same event to understand when we are connected to the broker. Here is the most important method for publishing messages.
Now you know how to make an application for the internet of things using .net. If you need to take a close look on project here is the link.
Originally published at http://tomorrowmeannever.wordpress.com on April 25, 2021.