Skip to content

MQTT Using Mosquitto on Yocto

MaanasMDK edited this page May 6, 2023 · 2 revisions

Description

This page helps you to build MQTT services on a Yocto image and shows how to use mosquitto broker to send messages between two devices.

Links to implementation

  1. core-image-aesd.bb changes
  2. Build script changes to add meta-networking layer
  3. mosquitto publisher implementation
  4. mosquitto subscriber implementation

Steps required to add Mosquitto MQTT into Yocto

  1. Add the meta-networking layer into your image. The mosquitto services are contained within the recipes-connectivity of the meta-networking layer from the meta-openembedded repository. The assumption here is that meta-openembedded has been installed as a git submodule in your project repository. If not, the steps are
git submodule add https://github.com/openembedded/meta-openembedded.git
cd meta-openembedded
git checkout kirkstone

To add meta-networking to your build.sh file

bitbake-layers show-layers | grep "meta-networking" > /dev/null
layer_networking_info=$?

if [ $layer_networking_info -ne 0 ];then
	echo "Adding meta-networking layer"
	bitbake-layers add-layer ../meta-openembedded/meta-networking
else
	echo "meta-networking layer already exists"
fi
  1. Adding the mosquitto broker package and the mosquitto-clients package into your core-image-aesd.bb file
# Adding the package for mosquitto services  
CORE_IMAGE_EXTRA_INSTALL += " mosquitto mosquitto-clients"
  1. Build the image by running the build script. ./build.sh

Setting up the image before using MQTT

  1. Make sure the system is connected to internet and the IP address is noted. To setup wifi please refer here.

  2. Edit the mosquitto.conf file to allow external connections and set the listener port. On the Yocto image booted target edit the /etc/mosquitto/mosquitto.conf file to add the following lines.

allow_anonymous true
listener 1883
  1. Start the mosquitto broker service using the following command. Note that -d is to run the broker as a daemon.
mosquitto -c /etc/mosquitto/mosquitto.conf -d

Transferring messages using Mosquitto broker

  1. mosquitto_pub is used to publish a message to the broker. The syntax to publish a message is as follows
mosquitto_pub -t <Topic> -h <Broker_IP> -m <Message>
image
  1. mosquitto_sub is used to subscribe to a particular topic and receive messages. The syntax to publish a message is as follows
mosquitto_sub -t <Topic> -h <Broker_IP>
image

You're all set!! Time to build cool applications using MQTT :)