MQTT C example
What is MQTT?
MQTT (Message Queuing Telemetry Transport) is a lightweight, publish-subscribe network protocol that transports messages between devices. It is designed for connections with remote locations where a small code footprint is required or network bandwidth is limited. It is widely used in Internet of Things (IoT) applications.
How to use MQTT in C?
Using MQTT in C typically involves using an MQTT client library. One popular library for MQTT in C is the Paho MQTT library by the Eclipse Foundation. Paho API can be found here. Paho library can be installed with the following steps:
git clone https://github.com/eclipse/paho.mqtt.c.git cd paho.mqtt.c mkdir build cd build cmake .. make sudo make install
Creating Publisher
Paho provides an example publisher application here. In order to test this app, follow these steps:
- Copy the content of the code to a pub_async.c file
- Compile the file:
gcc -o pub_async pub_async.c -lpaho-mqtt3c
- Run the app:
./pub_async
- You will see something like this:
Waiting for publication of Hello World! on topic MQTT Examples for client with ClientID: ExampleClientPub Message with token value 1 delivery confirmed
Creating Subscriber
Paho provides an example subscriber application here. In order to test this app, follow these steps:
- Copy the content of the code to a sub_async.c file
- Compile the file:
gcc -o sub_async sub_async.c -lpaho-mqtt3c
- Run the app:
./sub_async
- You will see something like this:
Subscribing to topic MQTT Examples for client ExampleClientSub using QoS1 Press Q<Enter> to quit
- The app will wait for the publisher app to send a message, if you run the publisher app once you will see the following message:
Message arrived topic: MQTT Examples message: Hello World!
- The app will remain active listening for messages until the user closes it.