<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title></title>
	<atom:link href="http://www.steves-internet-guide.com/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.steves-internet-guide.com</link>
	<description></description>
	<lastBuildDate>Mon, 18 May 2026 18:05:26 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	<generator>https://wordpress.org/?v=6.9.4</generator>
	<item>
		<title>Docker Networking Basics</title>
		<link>http://www.steves-internet-guide.com/docker-networking-basics/</link>
					<comments>http://www.steves-internet-guide.com/docker-networking-basics/#respond</comments>
		
		<dc:creator><![CDATA[steve]]></dc:creator>
		<pubDate>Mon, 18 May 2026 17:10:53 +0000</pubDate>
				<category><![CDATA[Internet]]></category>
		<guid isPermaLink="false">http://www.steves-internet-guide.com/?p=18923</guid>

					<description><![CDATA[<p>By default docker creates a single host bridge network which allows all docker containers on the same host to communicate with each other and with the host. if you use the command docker network ls on a new docker installation you will see three networks. When you use the run command to run a container without using the network switch the container will use the default bridge network. On the bridge network container apps can communicate using  the IP address of the container. &#160; Containers on the bridge network are given an IP address from the address pool. This is </p>
The post <a href="http://www.steves-internet-guide.com/docker-networking-basics/">Docker Networking Basics</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></description>
										<content:encoded><![CDATA[<p>By default docker creates a single host bridge network which allows all docker containers on the <strong>same host</strong> to communicate with each other and with the host.</p>
<p>if you use the command <strong>docker network ls</strong> on a new docker installation you will see three networks.<span id="more-18923"></span></p>
<p><img decoding="async" class="aligncenter size-full wp-image-18924" src="http://www.steves-internet-guide.com/wp-content/uploads/docker-metwork-list.png" alt="docker-metwork-list" width="372" height="103" srcset="http://www.steves-internet-guide.com/wp-content/uploads/docker-metwork-list.png 372w, http://www.steves-internet-guide.com/wp-content/uploads/docker-metwork-list-300x83.png 300w" sizes="(max-width: 372px) 100vw, 372px" /></p>
<p>When you use the run command to run a container without using the <strong>network switch</strong> the container will use the default bridge network.</p>
<p>On the bridge network <strong>container apps</strong> can communicate using  the <strong>IP address</strong> of the container.</p>
<p>&nbsp;</p>
<p>Containers on the bridge network are given an IP address from the address pool. This is  usually 172.x.0.0 range.</p>
<p>For applications on the main network to access applications in a container requires that the container must map/publish ports.</p>
<p>This is why you see  container run commands looking like this</p>
<pre>docker run -it –name mos2 -p 1883:1883 -p 8853:8883</pre>
<h3>The Host network switch</h3>
<p>You may see  run commands looking like this (mosquitto example):</p>
<pre>docker run -it –name mos2 --network=host</pre>
<p>You should notice that no port mapping is being used but applications on the main network can access the mosquitto broker on any ports that mosquitto has been configured to use.</p>
<p>This is very similar to starting mosquitto normally( without docker).</p>
<p>The IP address of the broker is the same as the IP address of the host.</p>
<p>However this option will expose all listening ports in the container and so it is not often used except for container Applications that need to listen to network broadcast messages.</p>
<p>Broadcast messages  can&#8217;t be forwarded using the bridge e.g a DHCP server &#8211;<a href="https://stackoverflow.com/questions/43316376/what-does-network-host-option-in-docker-command-really-do" target="_blank" rel="noopener">ref .</a></p>
<p><a href="https://stevessmarthomeguide.com/running-home-assistant-in-a-docker-container/" target="_blank" rel="noopener">Home assistant on docker</a> requires this option for <strong>device discovery</strong> to work.</p>
<h3>Creating additional Networks</h3>
<p>You can also create your own networks using the docker network create command. example</p>
<pre>docker network create -d bridge my-net</pre>
<p>Where <strong>my-net</strong> is the name of the network.</p>
<p>When you run a container you can connect it to the network using the network= switch. e.g</p>
<pre>docker run --network=my-net -itd --name=mos eclipse-mosquitto:2</pre>
<p>You can also connect  a running container to a network using the <a href="https://docs.docker.com/reference/cli/docker/network/connect/" target="_blank" rel="noopener">connect command</a> and also specify an IP address the container will use on that network if desired. e.g.</p>
<pre>docker network connect --ip 172.19.1.4 my-net mos</pre>
<p>On  a network containers can communicate using the IP address or the container name.</p>
<p>So for example if you start two containers using the &#8211;<strong>-name</strong> switch set to c1 and c2 then from container c1 you can ping c2 using the command :</p>
<pre>ping c2</pre>
<p>and vice versa.</p>
<h3>Example Docker Network</h3>
<p>In the example docker network as shown in the diagram below we have 3 containers</p>
<ul>
<li>A mosquitto broker using port 1883</li>
<li>A node-red Server using port 1880</li>
<li>An influxdb database using port 8086</li>
</ul>
<p><img fetchpriority="high" decoding="async" class="aligncenter wp-image-19563 size-full" src="http://www.steves-internet-guide.com/wp-content/uploads/docker-network-example.png" alt="docker-network" width="628" height="498" srcset="http://www.steves-internet-guide.com/wp-content/uploads/docker-network-example.png 628w, http://www.steves-internet-guide.com/wp-content/uploads/docker-network-example-300x238.png 300w" sizes="(max-width: 628px) 100vw, 628px" /></p>
<p><strong>Requirements</strong></p>
<p>1. Clients on the host network need to connect to the mosquitto broker and the node-red server.</p>
<p>2. The node-red server needs to connect to the influxdb database</p>
<h3>Setup</h3>
<p>1. We need to map ports for the mosquitto broker and node-red server but not the inflluxdb database.</p>
<p>2. The container for the influxdb database should have a fixed IP address which requires a <strong>user defined network.</strong></p>
<p>3. Create a user defined network and place all 3 containers on it.</p>
<p>4. For completion give all containers a fixed IP address (optional).</p>
<h3>Common Questions and Answers</h3>
<p><strong>Q- Do I need to create my own network?</strong></p>
<p>A- No it is usually only done when running multiple containers that need to be isolated from each other or containers that require a fixed IP address.</p>
<p><strong>Q-If I don&#8217;t map ports will my applications still work?</strong></p>
<p>A- Yes but will only be accessible to containers on the same network and not to users on the host network.</p>
<p><strong>Related Tutorials and Resources:</strong></p>
<ul>
<li><a href="http://www.steves-internet-guide.com/running-the-mosquitto-mqtt-broker-in-docker-beginners-guide/">Running The Mosquitto MQTT Broker In Docker – Beginners Guide</a></li>
</ul>
<p>&nbsp;</p>
<div style='text-align:left' class='yasr-auto-insert-visitor'></div>The post <a href="http://www.steves-internet-guide.com/docker-networking-basics/">Docker Networking Basics</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></content:encoded>
					
					<wfw:commentRss>http://www.steves-internet-guide.com/docker-networking-basics/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Sending Files Using MQTT</title>
		<link>http://www.steves-internet-guide.com/sending-files-using-mqtt/</link>
					<comments>http://www.steves-internet-guide.com/sending-files-using-mqtt/#respond</comments>
		
		<dc:creator><![CDATA[steve]]></dc:creator>
		<pubDate>Thu, 15 Jan 2026 18:20:42 +0000</pubDate>
				<category><![CDATA[Internet]]></category>
		<guid isPermaLink="false">http://www.steves-internet-guide.com/?p=19522</guid>

					<description><![CDATA[<p>It is possible to send any type of data using MQTT including files,images and video. However MQTT wasn&#8217;t designed for file sending but for sending small data packets from remote sensors. Having said that the actual maximum message size is very large (256MB). However not all MQTT brokers will support the maximum packet size and all public brokers have message size restrictions often between 128KB and 256kB. In addition clients will also have message size restrictions. Therefore a common practise is to split large files into chunks for sending. File Data and Meta Data Generally we will want to send</p>
The post <a href="http://www.steves-internet-guide.com/sending-files-using-mqtt/">Sending Files Using MQTT</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></description>
										<content:encoded><![CDATA[<p>It is possible to send any type of data using MQTT including files,images and video.</p>
<p>However MQTT wasn&#8217;t designed for file sending but for sending small data packets from remote sensors.</p>
<p>Having said that the actual maximum message size is very large (256MB).<span id="more-19522"></span></p>
<p>However not all MQTT brokers will support the maximum packet size and all public brokers have message size restrictions often between 128KB and 256kB.</p>
<p>In addition clients will also have message size restrictions.</p>
<p>Therefore a common practise is to <strong>split large files into chunks</strong> for sending.</p>
<h4>File Data and Meta Data</h4>
<p>Generally we will want to send the actual file data along with the file name.</p>
<p>When reading a file from disk a text file can be converted to text on reading or read directly as bytes.</p>
<p>For image/video files then they will be read as bytes.</p>
<p>To avoid complications I prefer to read all files as binary data so that they can be place directly in the message payload as MQTT is a binary protocol.</p>
<p>However sending binary data makes it more difficult to add meta data to the file data.</p>
<p>For the file name which is most important bit of meta data the easiest approach is to include it as part of the topic.</p>
<p><strong>MQTTv5</strong> introduced some important additions which allows you to add the file meta data outside of the payload using User properties.</p>
<h4>Indicating Start and end of File</h4>
<p>To tell the receiver that the file transfer is starting we can use a start and end message.</p>
<p>These messages would not contain file data but would contain file meta data.</p>
<h4>Verifying Successful transfer</h4>
<p>There are a number of ways this can be done e.g.</p>
<ul>
<li>Use the file length</li>
<li>Use a file hash</li>
<li>length + file hash.</li>
</ul>
<p>To avoid the the problem of buffering the entire file then the file length and digest is send in the end of file  message.</p>
<h4>Broker/Sever Extensions</h4>
<p>Some commercial brokers have developed server extensions aimed at making file transfer over MQTT easier. See <a href="https://www.hivemq.com/blog/how-to-build-file-based-protocol-adapter-hivemq-edge/" target="_blank" rel="noopener">hiveMQ</a> and <a href="https://www.emqx.com/en/blog/file-transfer-over-mqtt" target="_blank" rel="noopener">EMQX</a></p>
<h4>Common Questions and Answers</h4>
<p>Q1- MQTT wasn&#8217;t designed for file transfer so why use it?</p>
<p>A1- For convenience. HTTP wasn&#8217;t designed for email or file downloading but it used for both.</p>
<p>Q2 &#8211; Is MQTTv5 better than MQTT v3.1.1 for File transfer.</p>
<p>A2- MQTTv5 has some useful features that make file sending easier as data can be sent outside the message payload.</p>
<p>Q3 &#8211; Can I use QOS of 0?</p>
<p>A3 -Yes but many programs will use the puback to control message flow</p>
<h4>Common Use Cases</h4>
<ul>
<li>Uploading diagnostic logs or telemetry data from vehicles or sensors.</li>
<li>Sending firmware updates (OTA) to IoT devices.</li>
<li>Transferring images or video clips from security cameras to a server or to different locations.</li>
</ul>
<h4>Summary</h4>
<p>Although MQTT was intended as a file transport protocol it can be used for sending files across a network.</p>
<p>Although it may be frowned upon by some it will probably become a common use case in the future due the ease of doing it and the convenience.</p>
<h4>File Transfer Examples</h4>
<ul>
<li><a title="How to Send a File Using MQTT and Python" href="http://www.steves-internet-guide.com/send-file-mqtt/" target="_blank" rel="noopener">Send files using Python and MQTT</a></li>
</ul>
<p>&nbsp;</p>
<div style='text-align:left' class='yasr-auto-insert-visitor'></div>The post <a href="http://www.steves-internet-guide.com/sending-files-using-mqtt/">Sending Files Using MQTT</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></content:encoded>
					
					<wfw:commentRss>http://www.steves-internet-guide.com/sending-files-using-mqtt/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Understanding MQTT Birth and Death Messages (with Examples)</title>
		<link>http://www.steves-internet-guide.com/understanding-mqtt-birth-and-death-messages-with-examples/</link>
					<comments>http://www.steves-internet-guide.com/understanding-mqtt-birth-and-death-messages-with-examples/#respond</comments>
		
		<dc:creator><![CDATA[steve]]></dc:creator>
		<pubDate>Fri, 18 Apr 2025 17:24:56 +0000</pubDate>
				<category><![CDATA[MQTT]]></category>
		<category><![CDATA[MQTT-Design]]></category>
		<guid isPermaLink="false">http://www.steves-internet-guide.com/?p=19407</guid>

					<description><![CDATA[<p>When designing reliable systems using MQTT (Message Queuing Telemetry Transport), it&#8217;s important to know whether your devices are online. Birth and Death messages are special messages that help communicate the state of a device to other clients in a MQTT network. The MQTT protocol has provision for death messages known as last will and testament but not birth messages. Birth messages are part of the Sparkplug specification and are sent by the MQTT client and are normal MQTT messages with a specific format.  Birth and Death Message Formats Birth Messages are sent by a client when it connects (or reconnects)</p>
The post <a href="http://www.steves-internet-guide.com/understanding-mqtt-birth-and-death-messages-with-examples/">Understanding MQTT Birth and Death Messages (with Examples)</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></description>
										<content:encoded><![CDATA[<p>When designing reliable systems using MQTT (Message Queuing Telemetry Transport), it&#8217;s important to know whether your devices are online.</p>
<p>Birth and Death messages are special messages that help communicate the state of a device to other clients in a MQTT network.<span id="more-19407"></span></p>
<p>The MQTT protocol has provision for death messages known as<strong> last will and testament</strong> but not birth messages.</p>
<p>Birth messages are part of the <a title="Introduction to MQTT +Sparkplug For IIOT" href="http://www.steves-internet-guide.com/introduction-to-mqtt-sparkplug-for-iiot/" target="_blank" rel="noopener">Sparkplug</a> specification and are sent by the MQTT client and are normal MQTT messages with a specific format.</p>
<h4> Birth and Death Message Formats</h4>
<p><strong>Birth Messages</strong> are sent by a client when it connects (or reconnects) to an MQTT broker, signalling that it&#8217;s alive and ready to communicate.</p>
<p><strong>Death Messages</strong> are published by the broker on behalf of the client when the client unexpectedly disconnects (e.g., due to a crash or power failure).</p>
<p>A<strong> last will and testament message</strong> requires:</p>
<ul>
<li>a Topic</li>
<li>A message</li>
<li>A QOS level (quality of service)</li>
<li>A message Retain setting.</li>
</ul>
<p>Birth messages follow the same format.</p>
<p>Example</p>
<p><strong>Birth messages</strong></p>
<p>Topic=topic_base/connection<br />
Message=online<br />
QOS=0<br />
Retain=true</p>
<p><strong>Death messages</strong></p>
<p>Topic=topic_base/connection<br />
Message=offline<br />
QOS=0<br />
Retain=true</p>
<h3>Example Implementation Using Python</h3>
<p>It can easily be added to existing code in the <strong>on_connect</strong> callback. Here is my code with the addition.</p>
<pre>def on_connect(client, userdata, flags, rc):
 logging.debug("Connected flags"+str(flags)+"result code "\
 +str(rc)+"client1_id")
 if rc==0:
 client.connected_flag=True
client.publish(connection_topic,"online",0,retain=True)
 else:
 client.bad_connection_flag=True
</pre>
<p>We also need to Set the last will message.Payload is 0 and we use the retain flag.</p>
<pre>client.will_set(connected_topic,"offline",0, retain=True) #set will
</pre>
<p>The last will will take care of an abnormal disconnect. For a normal disconnect we need to remember to update the status before we disconnect as follows:</p>
<pre>client.publish(connection_topic,0,retain=True)
client.disconnect()</pre>
<p><strong>Note</strong>: The retain flag should be set in both messages to ensure new subscribers get the current state.</p>
<h3>Example implementation including Python Code.</h3>
<p>The <a href="http://www.steves-internet-guide.com/checking-active-mqtt-client-connections/" target="_blank" rel="noopener">checking active connections</a> tutorial has an example and also suggestions on making the message more useful.</p>
<p><strong>Related Tutorials</strong></p>
<ul>
<li><a href="http://www.steves-internet-guide.com/mosquitto_pub-sub-clients/">Using The Mosquitto_pub and Mosquitto_sub MQTT Client Tools- Examples</a></li>
<li class="sitemap"><a href="http://www.steves-internet-guide.com/mqtt-retained-messages-example/">MQTT Retained Messages Explained</a></li>
<li class="sitemap"><a href="http://www.steves-internet-guide.com/mqtt-last-will-example/">MQTT Last Will and Testament Examples</a></li>
<li><a href="http://www.steves-internet-guide.com/understanding-mqtt-topics/">Understanding MQTT Topic Naming and Design Notes</a></li>
<li><a title="Introduction to MQTT +Sparkplug For IIOT" href="http://www.steves-internet-guide.com/introduction-to-mqtt-sparkplug-for-iiot/" target="_blank" rel="noopener">Introduction to MQTT +Sparkplug For IIOT</a></li>
</ul>
<p>&nbsp;</p>
<div style='text-align:left' class='yasr-auto-insert-visitor'></div>The post <a href="http://www.steves-internet-guide.com/understanding-mqtt-birth-and-death-messages-with-examples/">Understanding MQTT Birth and Death Messages (with Examples)</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></content:encoded>
					
					<wfw:commentRss>http://www.steves-internet-guide.com/understanding-mqtt-birth-and-death-messages-with-examples/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>HTTP vs MQTT for IOT Devices</title>
		<link>http://www.steves-internet-guide.com/http-vs-mqtt-for-iot-devices/</link>
					<comments>http://www.steves-internet-guide.com/http-vs-mqtt-for-iot-devices/#comments</comments>
		
		<dc:creator><![CDATA[steve]]></dc:creator>
		<pubDate>Wed, 09 Apr 2025 17:47:34 +0000</pubDate>
				<category><![CDATA[MQTT]]></category>
		<guid isPermaLink="false">http://www.steves-internet-guide.com/?p=19376</guid>

					<description><![CDATA[<p>Most IOT devices can use both the  HTTP and MQTT protocols to communicate with IOT  control systems. The HTTP protocol is generally used for initial  device set up. However when it comes to sending device data and for subsequent device control HTTP is not usually the best protocol. Generally when you look for a comparison between the protocols the main emphasis is on the fact that HTTP is a text based protocol and not as efficient as MQTT which is a binary based protocol. However when dealing with only a few devices that send data infrequently then it is not</p>
The post <a href="http://www.steves-internet-guide.com/http-vs-mqtt-for-iot-devices/">HTTP vs MQTT for IOT Devices</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></description>
										<content:encoded><![CDATA[<p>Most IOT devices can use both the  HTTP and MQTT protocols to communicate with IOT  control systems.</p>
<p>The HTTP protocol is generally used for initial  device set up.</p>
<p>However when it comes to sending device data and for subsequent device control HTTP is not usually the best protocol.<span id="more-19376"></span></p>
<p>Generally when you look for a comparison between the protocols the main emphasis is on the fact that HTTP is a text based protocol and not as efficient as MQTT which is a binary based protocol.</p>
<p>However when dealing with only a few devices that send data infrequently then it is not really a problem.</p>
<p>IMO ,the main issues  are the fact that MQTT is a real time protocol and because of the publish and subscribe model is excellent for working with a large number of devices and real time data.</p>
<p>As an example imagine you have 100 parking space sensors. How would you get the status of each sensor?</p>
<p>With HTTP you would need to poll each sensor frequently and you would require 100 client connections from the control dashboard.</p>
<p>With MQTT you would only require one connection to the broker from the control dashboard, and to subscribe to a single topic to receive status changes in real time.</p>
<p>This is what ChatGPT said about use cases</p>
<table>
<thead>
<tr>
<th>Use Case</th>
<th><strong>HTTP</strong></th>
<th><strong>MQTT</strong></th>
</tr>
</thead>
</table>
<div>
<table>
<tbody>
<tr>
<td class="" data-start="3377" data-end="3408">Device Control</td>
<td class="" data-start="3408" data-end="3446">OK for simple commands</td>
<td class="" data-start="3446" data-end="3496">Excellent for real-time control</td>
</tr>
</tbody>
</table>
</div>
<div>
<table>
<tbody>
<tr>
<td class="" data-start="3497" data-end="3528">Sensor Data Reporting</td>
<td class="" data-start="3528" data-end="3566">Less efficient</td>
<td class="" data-start="3566" data-end="3616">Highly efficient</td>
</tr>
</tbody>
</table>
</div>
<div>
<table>
<tbody>
<tr>
<td class="" data-start="3617" data-end="3648">Low Power/Resource Devices</td>
<td class="" data-start="3648" data-end="3686">Not ideal</td>
<td class="" data-start="3686" data-end="3736">Optimized</td>
</tr>
</tbody>
</table>
</div>
<div>
<table>
<tbody>
<tr>
<td class="" data-start="3737" data-end="3768">Scalability (many devices)</td>
<td class="" data-start="3768" data-end="3806">Harder to scale</td>
<td class="" data-start="3806" data-end="3856">Broker makes scaling easier</td>
</tr>
</tbody>
</table>
</div>
<h4>Device IP Addresses</h4>
<p>Another very important point that is not discussed is that when using HTTP for device control then the control dashboard needs to know the IP address of the device.</p>
<p>With many devices DHCP will be used and so keeping track of device IP addresses isn&#8217;t always easy.</p>
<p>See <a href="https://stevessmarthomeguide.com/how-to-find-the-ip-address-of-a-new-network-device/#more-17104" target="_blank" rel="noopener">Finding New Device IP addresses</a></p>
<p>However the task will become increasingly more difficult as networks move to IPV6 as the methods used for IPv4 networks won&#8217;t work on IPv6.</p>
<p>Because MQTT doesn&#8217;t have a direct connection between devices then knowing the IP address of any device isn&#8217;t necessary.</p>
<h4>Video</h4>
<p><iframe title="HTTP vs MQTT in IOT/Home Automation" width="810" height="608" src="https://www.youtube.com/embed/a_pBqxRp8YI?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe></p>
<p><strong>Related Tutorials and Resources:</strong></p>
<ul>
<li><a href="http://www.steves-internet-guide.com/http-basics/">Understanding HTTP Basics</a></li>
<li><a href="http://www.steves-internet-guide.com/using-http-apis-for-iot-beginners-guide/">Using HTTP APIs For IOT -Beginners Guide</a></li>
<li><a href="http://www.steves-internet-guide.com/ipv6-guide/">IPv6 Explained for Beginners</a></li>
<li><a href="http://www.steves-internet-guide.com/mqtt-works/" target="_blank" rel="noopener noreferrer">How MQTT Works </a></li>
</ul>
<p>&nbsp;</p>
<div style='text-align:left' class='yasr-auto-insert-visitor'></div>The post <a href="http://www.steves-internet-guide.com/http-vs-mqtt-for-iot-devices/">HTTP vs MQTT for IOT Devices</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></content:encoded>
					
					<wfw:commentRss>http://www.steves-internet-guide.com/http-vs-mqtt-for-iot-devices/feed/</wfw:commentRss>
			<slash:comments>2</slash:comments>
		
		
			</item>
		<item>
		<title>Design A Network of 100s of MQTT Parking lot Sensors</title>
		<link>http://www.steves-internet-guide.com/design-a-network-of-100s-of-mqtt-parking-lot-sensors/</link>
					<comments>http://www.steves-internet-guide.com/design-a-network-of-100s-of-mqtt-parking-lot-sensors/#respond</comments>
		
		<dc:creator><![CDATA[steve]]></dc:creator>
		<pubDate>Tue, 01 Apr 2025 18:25:00 +0000</pubDate>
				<category><![CDATA[MQTT]]></category>
		<category><![CDATA[MQTT-Design]]></category>
		<guid isPermaLink="false">http://www.steves-internet-guide.com/?p=19339</guid>

					<description><![CDATA[<p>Task -Design an MQTT topic and security structure with Mosquitto as the MQTT broker for a network of 100s of Parking lot sensors. Overview In this design example we take the case of a network of parking sensors. Sensors will be sending an occupied/unoccupied state message as well as supplementary information like battery level,signal level IP address etc. Data is not confidential and not critical. A control dashboard application will receive the data and process as necessary Topic and Payload Structure A starting structure is shown below. All messages will be sent as JSON encoded data. parking/ ├── sensors/ │</p>
The post <a href="http://www.steves-internet-guide.com/design-a-network-of-100s-of-mqtt-parking-lot-sensors/">Design A Network of 100s of MQTT Parking lot Sensors</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></description>
										<content:encoded><![CDATA[<h3>Task -Design an MQTT topic and security structure with Mosquitto as the MQTT broker for a network of 100s of Parking lot sensors.</h3>
<h4>Overview</h4>
<p>In this design example we take the case of a network of parking sensors. Sensors will be sending an occupied/unoccupied state message as well as supplementary information like battery level,signal level IP address etc.<span id="more-19339"></span></p>
<p>Data is not confidential and not critical.</p>
<p>A control dashboard application will receive the data and process as necessary<!--more--></p>
<h3>Topic and Payload Structure</h3>
<p>A starting structure is shown below. All messages will be sent as JSON encoded data.</p>
<p>parking/<br />
├── sensors/<br />
│ ├── zone1/<br />
│ │ ├── sensor001/<br />
│ │ │ ├── status (e.g., &#8220;occupied&#8221;, &#8220;vacant&#8221;)<br />
│ │ │ ├── battery (e.g., &#8220;80%&#8221;)<br />
│ │ │ ├── signal (e.g., &#8220;strong&#8221;, &#8220;weak&#8221;)<br />
│ │ │ ├── connected (e.g., &#8220;online&#8221;, &#8220;offline&#8221;)<br />
│ │ ├── sensor002/<br />
│ │ ├── &#8230;<br />
│ ├── zone2/<br />
│ ├── &#8230;<br />
├── commands/<br />
│ ├── reset/<br />
│ │ ├── all<br />
│ │ ├── zone1<br />
│ │ ├── sensor001<br />
│ ├── update-firmware/<br />
│ │ ├── all<br />
│ │ ├── zone1<br />
│ │ ├── sensor001<br />
├── alerts/<br />
│ ├── low-battery/<br />
│ │ ├── sensor001<br />
│ │ ├── sensor045<br />
│ ├── malfunction/<br />
│ │ ├── sensor120<br />
│ │ ├── sensor234<br />
│ ├── disconnected/<br />
│ │ ├── sensor050<br />
│ │ ├── sensor123<br />
├── analytics/<br />
│ ├── occupancy/<br />
│ │ ├── zone1<br />
│ │ ├── zone2<br />
│ │ ├── total<br />
│ ├── usage-patterns/<br />
│ ├── average-duration/</p>
<h3>Explanation:</h3>
<p><strong>sensors/zoneX/sensorYYY/</strong> → Each sensor reports status, battery, and signal strength.</p>
<p><strong>commands/</strong> → Commands to reset, update firmware, or send other instructions.</p>
<p><strong>alerts/</strong> → Separate topics for low battery, malfunction, or other issues.</p>
<p><strong>analytics/</strong> → Aggregated data for parking usage and occupancy statistics.</p>
<p><strong>connected</strong> status under each sensor to indicate if it&#8217;s online or offline.</p>
<p><strong>alerts/disconnected/</strong> for tracking sensors that have lost connection.</p>
<h4>Possible Enhancements</h4>
<p>Include a time stamp for each sensor attribute e.g. battery,signal etc</p>
<h3>Example Topics and MQTT payloads</h3>
<p><strong>Topic</strong>: parking/sensors/zone1/sensor001/status</p>
<p><strong>Payload</strong>: JSON</p>
<p>{<br />
&#8220;value&#8221;: &#8220;occupied&#8221;,<br />
&#8220;timestamp&#8221;: &#8220;2025-03-23T12:34:56Z&#8221;<br />
}</p>
<h4>Payload:</h4>
<p>{<br />
&#8220;value&#8221;: &#8220;online&#8221;,<br />
&#8220;timestamp&#8221;: &#8220;2025-03-23T12:37:15Z&#8221;<br />
}</p>
<h3>Using Sparkplug For MQTT</h3>
<p>The topic structure does resemble the Sparkplug topic structure. However adopting the Sparkplug topic and payload structure is a consideration so here is what chatGPT has to say:</p>
<blockquote><p><strong data-start="67" data-end="80">Sparkplug</strong> is a better option than plain JSON when dealing with <strong data-start="134" data-end="172">IIoT (Industrial IoT) applications</strong> that require structured payloads, state awareness, and efficient bandwidth usage. It provides <strong data-start="267" data-end="324">data modeling, compression, and device state tracking</strong> out of the box.</p></blockquote>
<p>However I would go for JSON data as it is much easier to work with than<strong> Google Protocol buffers</strong>.</p>
<h3>QOS and Retained</h3>
<p>Occupancy data can use a QOS of either 0 or 1. Generally 1 is the default choice but as this data is not really critical I would opt for a QOS of 0 unless the network was unreliable.</p>
<p>For occupancy data,will  and birth messages the retained flag should also be set.</p>
<h3>Designing an ACL (Access Control List) for MQTT Sensors on Mosquitto Broker</h3>
<p>The sensors will both send data and receive commands. It is important that sensors are restricted to sending data on their own topic and that only authorised devices are able to send commands.</p>
<p>An <strong data-start="90" data-end="119">ACL (Access Control List)</strong> in Mosquitto controls which clients (sensors, gateways, admins) can <strong data-start="188" data-end="199">publish</strong> and <strong data-start="204" data-end="217">subscribe</strong> to specific topics.</p>
<p>Below is a structured ACL design for your <strong data-start="280" data-end="309">parking lot sensor system</strong>, considering security and scalability.</p>
<p><strong>Roles:</strong></p>
<ul>
<li class="" data-start="385" data-end="450">
<p class="" data-start="387" data-end="450"><strong data-start="387" data-end="413">Sensors (<code data-start="398" data-end="410">sensor_XXX</code>)</strong> → Can only publish their own data.</p>
</li>
<li class="" data-start="451" data-end="541">
<p class="" data-start="453" data-end="541"><strong data-start="453" data-end="481">Gateways (<code data-start="465" data-end="478">gateway_XXX</code>)</strong> → Can publish and subscribe to all sensors in their zone.</p>
</li>
<li class="" data-start="542" data-end="594">
<p class="" data-start="544" data-end="594"><strong data-start="544" data-end="563">Admin (<code data-start="553" data-end="560">admin</code>)</strong> → Full access to all topics.</p>
</li>
</ul>
<p><strong>Notes:</strong> although the ACL uses the user name it is not necessary to have a passwords file unless you are also using user name and password authentication.</p>
<h4>The following file was suggested by ChatGPT</h4>
<pre># ===========================
# ACL for MQTT Parking System
# ===========================

# ----- Admin Full Access -----
user admin
topic readwrite parking/#

# ----- Gateway Access -----
# Each gateway can publish and subscribe to its zone's sensors.
user gateway_zone1
topic readwrite parking/sensors/zone1/#
topic readwrite parking/alerts/zone1/#
topic readwrite parking/commands/zone1/#

user gateway_zone2
topic readwrite parking/sensors/zone2/#
topic readwrite parking/alerts/zone2/#
topic readwrite parking/commands/zone2/#

# ----- Sensor Access -----
# Each sensor can only publish to its own topic and read commands for itself.

user sensor_001
topic write parking/sensors/zone1/sensor001/#
topic read parking/commands/zone1/sensor001/#
topic read parking/alerts/disconnected/sensor001

user sensor_002
topic write parking/sensors/zone1/sensor002/#
topic read parking/commands/zone1/sensor002/#
topic read parking/alerts/disconnected/sensor002

# (Repeat for all sensors...)

# ----- Public Read-Only Access -----
# If you want a dashboard or external system to read aggregated data.
user dashboard
topic read parking/analytics/#

# ===========================
</pre>
<p>However a better solution is to use the pattern option:</p>
<p><strong>pattern write parking/sensors/zone1/%u/#<br />
pattern read parking/commands/zone1/%u/#<br />
pattern read parking/alerts/disconnected/%u</strong></p>
<p>An alternative is to use the Pattern option with the sensor Id. This is my preferred approach if user name authentication isn&#8217;t going to be used.</p>
<p><strong>pattern write parking/sensors/zone1/%c/#<br />
pattern read parking/commands/zone1/%c/#<br />
pattern read parking/alerts/disconnected/%c</strong></p>
<h4>mosquitto conf file addition.</h4>
<pre>allow_anonymous true
acl_file /etc/mosquitto/mosquitto.acl</pre>
<p><strong>Note:</strong> I have used the standard location for the acl file on Linux in the example above. However in practise, for testing, I always place the files in my home folder and the example files you can download will use my local path.</p>
<h3>Authentication</h3>
<p>As an extra level of security you can also use user name and password authentication.</p>
<p>This requires creating a passwords file and forcing authentication in the mosquitto.conf file.</p>
<pre>allow_anonymous false
acl_file /etc/mosquitto/mosquitto.acl
password_file /etc/mosquitto/passwd</pre>
<p>Although most texts will recommend a unique user name and password for each sensor such a scenario is difficult to administer.</p>
<p>If you are using user names as part of the acl restrictions then a unique user name for each sensor is necessary but a unique password isn’t.</p>
<p>If you use the sensor ID for ACL restrictions (recommended) then all sensors can use the same user name and password.</p>
<p>Because the data isn&#8217;t really confidential I <strong>would not</strong> implement user name authentication in this scenario.</p>
<h3>Encryption (SSL or End to End)</h3>
<p>In our current implantation we are only sending non sensitive data and so there is no need to encrypt the data.</p>
<p>If our messages contained personal data like vehicle registration plates, or billing data then we would need to use some form of encryption.</p>
<p>If you use SSL then you must implement it on each link.</p>
<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/1f534.png" alt="🔴" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Problem: If data is only protected with SSL/TLS (which secures data in transit but not at rest), the broker can still see and store unencrypted license plates and payment data. If the broker is compromised, attackers could steal sensitive information.</p>
<p>If data is to be stored then end to end Encryption is the preferred choice.</p>
<p><strong>Key Benefits of E2EE </strong></p>
<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Even if the MQTT broker is hacked, data remains protected.</p>
<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Prevents unauthorized users from accessing sensitive parking and payment data.</p>
<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Ensures only intended recipients (backend, app) can decrypt messages.</p>
<p><img src="https://s.w.org/images/core/emoji/17.0.2/72x72/2705.png" alt="✅" class="wp-smiley" style="height: 1em; max-height: 1em;" /> Complies with privacy regulations (GDPR, PCI-DSS for payments).</p>
<h3><a name="_Toc194067803"></a>Data Frequency</h3>
<p>A 5 minute send cycle would be often enough as changes are always sent immediately.</p>
<h4>Questions</h4>
<p>Q1- What would be the occupancy status if the sensor was detected to be offline?</p>
<p>Q2- If anonymous access is allowed and there is no password file do you need to send a password with the user name?</p>
<h3>Workbook and Scripts</h3>
<p>I will be making test python scripts, ACL files and mosquitto conf files available soon .</p>
<h4>Answers</h4>
<p>A1- unknown</p>
<p>A2 &#8211; no &#8211;</p>
<p>The follow table shows how the <strong>anonymous access</strong> setting and the <strong>password file</strong> settings<strong> affect client access</strong>.</p>
<table class="tablenorm">
<tbody class="table-norm">
<tr>
<td width="189">Anonymous access</td>
<td width="189"><strong>Password file Specified</strong></td>
<td width="189"><strong>Access Restricted</strong></td>
</tr>
<tr>
<td width="189"><strong>True</strong></td>
<td width="189">No</td>
<td width="189">No</td>
</tr>
<tr>
<td width="189"><strong>True</strong></td>
<td width="189">Yes</td>
<td width="189">Yes See Note 1</td>
</tr>
<tr>
<td width="189"><strong>False</strong></td>
<td width="189">No</td>
<td width="189">Yes -see Note 2</td>
</tr>
<tr>
<td width="189"><strong>False</strong></td>
<td width="189">Yes</td>
<td width="189">Yes</td>
</tr>
</tbody>
</table>
<p><strong>Note1</strong>: If a password file is specified then if the client sends a username/password then it must be valid otherwise an authentication error is returned.</p>
<p>If it doesn’t send one then none is required and a normal connection results.</p>
<p><strong>Note 2</strong>: The client must send a User name and password, but it is not checked. If the client doesn’t send a user name/password then an <strong>authentication error code</strong> is generated.</p>
<p>Taken from <a href="http://www.steves-internet-guide.com/mqtt-username-password-example/">Mosquitto Username and Password Authentication -Configuration and Testing</a></p>
<h4>Questions?</h4>
<p>Do you have any questions? Please use the comments form to ask</p>
<p><strong>References:</strong></p>
<ul>
<li><a href="http://www.steves-internet-guide.com/topic-restriction-mosquitto-configuration/">Mosquitto ACL -Configuring and Testing MQTT Topic Restrictions</a></li>
<li><a href="http://www.steves-internet-guide.com/mosquitto-bridge-encryption/">Configure a Mosquitto Bridge With SSL Encryption</a></li>
</ul>
<p>&nbsp;</p>
<div style='text-align:left' class='yasr-auto-insert-visitor'></div>The post <a href="http://www.steves-internet-guide.com/design-a-network-of-100s-of-mqtt-parking-lot-sensors/">Design A Network of 100s of MQTT Parking lot Sensors</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></content:encoded>
					
					<wfw:commentRss>http://www.steves-internet-guide.com/design-a-network-of-100s-of-mqtt-parking-lot-sensors/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Python Broker Checker</title>
		<link>http://www.steves-internet-guide.com/python-broker-checker/</link>
					<comments>http://www.steves-internet-guide.com/python-broker-checker/#respond</comments>
		
		<dc:creator><![CDATA[steve]]></dc:creator>
		<pubDate>Wed, 19 Feb 2025 19:30:24 +0000</pubDate>
				<category><![CDATA[Python MQTT-Projects]]></category>
		<guid isPermaLink="false">http://www.steves-internet-guide.com/?p=19306</guid>

					<description><![CDATA[<p>Python Broker checker I have developed a number of tools for monitoring MQTT brokers that use node-red. The reason for using node-red is that it is easy to use, and comes with a dashboard. However when it comes to monitoring multiple brokers it gets complicated. My solution it to do the monitoring using Python and then use node-red to log and display the results. Python MQTT Broker Checker The broker check monitors to state of a list of MQTT brokers by periodically trying to connect to the broker. The script makes use of threads so that a failed connections doesn&#8217;t</p>
The post <a href="http://www.steves-internet-guide.com/python-broker-checker/">Python Broker Checker</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></description>
										<content:encoded><![CDATA[<h4>Python Broker checker</h4>
<p>I have developed a number of <a href="http://www.steves-internet-guide.com/monitoring-mqtt-brokers/" target="_blank" rel="noopener">tools</a> for monitoring MQTT brokers that use node-red.</p>
<p>The reason for using node-red is that it is easy to use, and comes with a dashboard.</p>
<p>However when it comes to monitoring multiple brokers it gets complicated.</p>
<p>My solution it to do the monitoring using Python and then use node-red to log and display the results.<span id="more-19306"></span></p>
<h3>Python MQTT Broker Checker</h3>
<p>The broker check monitors to state of a list of MQTT brokers by periodically trying to connect to the broker.</p>
<p>The script makes use of threads so that a failed connections doesn&#8217;t cause a big delay.</p>
<p>If it can connect then it flags the broker as <strong>UP</strong> otherwise the broker is <strong>DOWN</strong>.</p>
<p>In addition it also logs the connection time interval as this is a measure of how responsive the broker is.</p>
<p>The broker list can be reloaded as an array of dictionary objects. An example is shown below:</p>
<p>{<br />
&#8220;broker_name&#8221;:&#8221;192.168.1.23&#8243;,<br />
&#8220;port&#8221;:1883,<br />
&#8220;username&#8221;:&#8221;steve&#8221;,<br />
&#8220;password&#8221;:&#8221;password&#8221;,<br />
&#8220;SSL&#8221;:False<br />
}</p>
<p>In addition you can add/remove brokers dynamically be sending commands using MQTT.</p>
<p>The tool reports the status of the broker on the topic</p>
<p><strong>public/brokers/alerts</strong></p>
<p>it receives commands on the topic</p>
<p><strong>public/brokers/commands/[add/remove]</strong></p>
<p>A command response is sent on the topic</p>
<p><strong>public/brokers/responses</strong></p>
<p>When sending commands the payload is a JSON  object like that shown below and also in the script.</p>
<p>Currently script defaults are</p>
<ul>
<li>Maximum threads 4</li>
<li>Loop interval 30secs</li>
<li>Max connection time 20secs</li>
</ul>
<p>The results are sent to an MQTT report broker at the end of each cycle and they can be retrieved by a suitable monitor.</p>
<p>This is what the connection report looks like:</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-19297" src="http://www.steves-internet-guide.com/wp-content/uploads/broker-monitor-report.png" alt="broker-monitor-report" width="680" height="188" srcset="http://www.steves-internet-guide.com/wp-content/uploads/broker-monitor-report.png 680w, http://www.steves-internet-guide.com/wp-content/uploads/broker-monitor-report-300x83.png 300w" sizes="auto, (max-width: 680px) 100vw, 680px" /></p>
<h3></h3>
<p>Here are some command examples screen shots using MQTT Explorer</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-19309" src="http://www.steves-internet-guide.com/wp-content/uploads/broker-add.png" alt="broker-add" width="711" height="393" srcset="http://www.steves-internet-guide.com/wp-content/uploads/broker-add.png 711w, http://www.steves-internet-guide.com/wp-content/uploads/broker-add-300x166.png 300w" sizes="auto, (max-width: 711px) 100vw, 711px" /></p>
<h3>Removing a broker from the Lists</h3>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-19310" src="http://www.steves-internet-guide.com/wp-content/uploads/broker-remove.png" alt="broker-remove" width="725" height="286" srcset="http://www.steves-internet-guide.com/wp-content/uploads/broker-remove.png 725w, http://www.steves-internet-guide.com/wp-content/uploads/broker-remove-300x118.png 300w" sizes="auto, (max-width: 725px) 100vw, 725px" /></p>
<p>&nbsp;</p>
<h4>Main Loop</h4>
<p>This is a while loop which usually runs indefinitely (count=0). The code is show below:<br />
<img loading="lazy" decoding="async" class="aligncenter size-full wp-image-19315" src="http://www.steves-internet-guide.com/wp-content/uploads/broker-check-main-loop.png" alt="broker-check-main" width="762" height="638" srcset="http://www.steves-internet-guide.com/wp-content/uploads/broker-check-main-loop.png 762w, http://www.steves-internet-guide.com/wp-content/uploads/broker-check-main-loop-300x251.png 300w" sizes="auto, (max-width: 762px) 100vw, 762px" /></p>
<p>The broker check is started in a separate thread.Once the maximum number of threads has been started then the script waits (while loop).</p>
<h4>Code Download</h4>
<p><a href="https://buymeacoffee.com/steveh5u/e/376049" target="_blank" rel="noopener"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-15784" src="http://www.steves-internet-guide.com/wp-content/uploads/download.jpg" alt="download" width="198" height="63" /></a></p>
<h4>Questions</h4>
<p>If you have any questions require code explanation then let me know and I will assist.</p>
<p>If you have any suggestions,maybe you would like to see the data displayed on a simple web page without node-red. Or perhaps you want email alerts using python etc then please let me know and I will try to incorporate your suggestion into the project</p>
<h4>Part 2</h4>
<p>In Part 2 we will look at using node-red to display the broker status on a Dashboard.</p>
<div style='text-align:left' class='yasr-auto-insert-visitor'></div>The post <a href="http://www.steves-internet-guide.com/python-broker-checker/">Python Broker Checker</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></content:encoded>
					
					<wfw:commentRss>http://www.steves-internet-guide.com/python-broker-checker/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Paho MQTT Python Client Version 2</title>
		<link>http://www.steves-internet-guide.com/paho-mqtt-python-client-version-2/</link>
					<comments>http://www.steves-internet-guide.com/paho-mqtt-python-client-version-2/#respond</comments>
		
		<dc:creator><![CDATA[steve]]></dc:creator>
		<pubDate>Wed, 19 Feb 2025 18:07:43 +0000</pubDate>
				<category><![CDATA[Python-MQTT]]></category>
		<guid isPermaLink="false">http://www.steves-internet-guide.com/?p=19287</guid>

					<description><![CDATA[<p>The Paho MQTT python client version 2 introduced some changes that break easier scripts. All of the scripts currently available on this site used the 1.5 to 1.6 client version and so if you upgrade to the new version you will need to make changes to these scripts. The changes revolve around the callback functions which have been changed to take into account the properties feature of MQTTv5. Previously when using version 1.x with MQTTv5 you would need to add the properties object to some of the callbacks as scripts written for MQTTv3.1 would fail because they didn&#8217;t have the</p>
The post <a href="http://www.steves-internet-guide.com/paho-mqtt-python-client-version-2/">Paho MQTT Python Client Version 2</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></description>
										<content:encoded><![CDATA[<p>The Paho MQTT python client version 2 introduced some changes that break easier scripts.</p>
<p>All of the scripts currently available on this site used the 1.5 to 1.6 client version and so if you upgrade to the new version you will need to make changes to these scripts.<span id="more-19287"></span></p>
<p>The changes revolve around the callback functions which have been changed to take into account the properties feature of MQTTv5.</p>
<p>Previously when using version 1.x with MQTTv5 you would need to add the properties object to some of the callbacks as scripts written for MQTTv3.1 would fail because they didn&#8217;t have the properties object.</p>
<p>As an illustration the callback function for on_connect</p>
<pre>Old signature for MQTT v3.1 and v3.1.1 is:
on_connect(client, userdata, flags, rc)

signature for MQTT v5.0 client:
on_connect(client, userdata, flags, reasonCode, properties=None)

</pre>
<p><strong>Notice</strong> the extra properties field.</p>
<p>However existing code written for v3.1.1 used the following callback signature:</p>
<pre>connect(client, userdata, flags, rc)</pre>
<p>This will still work with MQTTv3.1.1 but you will get an error with MQTTv5</p>
<p>To make the callback work with v3.1.1 and v5 connections use:</p>
<pre>on_connect(client, userdata, flags, rc, properties=None)</pre>
<h3>Version 2 Changes</h3>
<p>In version all callbacks that require the properties field have one.</p>
<p>This means that it works with both MQTTv3.1 and MQTTv5.</p>
<p>In addition a flag has been added so that old code written for MQTTv3.1 and version 1.x client will still work with the version2 client.</p>
<p>The flag is shown below:</p>
<pre>mqtt.CallbackAPIVersion.VERSION1</pre>
<p>and</p>
<pre>mqtt.CallbackAPIVersion.VERSION2</pre>
<p>This is set at client creation so instead of:</p>
<pre>client = mqtt.Client(client_name)</pre>
<p>you need to use:</p>
<pre>client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION1,client_name)</pre>
<p>if you are still using old callbacks or</p>
<pre>client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,client_name)</pre>
<p>for new callbacks.</p>
<p>In addition the reason code (rc) returned in callbacks was previously an integer, but is now an instance of <strong>ReasonCode</strong>.</p>
<p>Finally new properties have been added to the client class which might be an issue if you have sub classed or added additional properties.</p>
<p>I use a <strong>connected_flag</strong> in many of my scripts and there is no conflict with the new ones.</p>
<p>You can find all the details and example code on the migration page <a href="https://eclipse.dev/paho/files/paho.mqtt.python/html/migrations.html" target="_blank" rel="noopener">here</a></p>
<p>I did an article on python client changes for MQTTv5 a while ago and it is <a href="http://www.steves-internet-guide.com/python-mqtt-client-changes/" target="_blank" rel="noopener">here.</a></p>
<h4>Video Overview</h4>
<p><iframe loading="lazy" title="Paho MQTT Python Client 2 versus 1.x Overview" width="810" height="608" src="https://www.youtube.com/embed/pMscNhJ4W5k?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen></iframe></p>
<p><strong>Related tutorial and Resources:</strong></p>
<ul>
<li class="sitemap"><a href="http://www.steves-internet-guide.com/mqtt-python-callbacks/">Paho Python MQTT Client – Understanding Callbacks</a></li>
<li class="sitemap"><a href="http://www.steves-internet-guide.com/loop-python-mqtt-client/">Paho Python MQTT Client-Understanding The Loop</a></li>
<li class="sitemap"><a href="http://www.steves-internet-guide.com/client-objects-python-mqtt/">Paho Python MQTT Client Objects</a></li>
<li></li>
<li></li>
</ul>
<p>&nbsp;</p>
<div style='text-align:left' class='yasr-auto-insert-visitor'></div>The post <a href="http://www.steves-internet-guide.com/paho-mqtt-python-client-version-2/">Paho MQTT Python Client Version 2</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></content:encoded>
					
					<wfw:commentRss>http://www.steves-internet-guide.com/paho-mqtt-python-client-version-2/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>How to use the Mosquitto Broker with IPv6</title>
		<link>http://www.steves-internet-guide.com/use-mosquitto-broker-with-ipv6/</link>
					<comments>http://www.steves-internet-guide.com/use-mosquitto-broker-with-ipv6/#respond</comments>
		
		<dc:creator><![CDATA[steve]]></dc:creator>
		<pubDate>Fri, 10 Jan 2025 14:04:09 +0000</pubDate>
				<category><![CDATA[Mosquitto]]></category>
		<guid isPermaLink="false">http://www.steves-internet-guide.com/?p=19225</guid>

					<description><![CDATA[<p>You can connect to the Mosquitto broker using IPV6 as well as IPv4 provided IPv6 is enabled on your machine. When you start mosquitto using a basic configuration file like the one shown below mosquitto will listen for connections on both  IPv4 and IPv6. include_dir /etc/mosquitto/conf.d log_type error log_type notice log_type information log_type debug log_type websockets log_timestamp_format %Y-%m-%dT%H:%M:%S connection_messages true log_dest stdout allow_anonymous true listener 1883 This is shown in the screen shot below: Just like with IPv4 you need to know the IPv6 address of the broker or the domain name if using DNS to connect to it. With</p>
The post <a href="http://www.steves-internet-guide.com/use-mosquitto-broker-with-ipv6/">How to use the Mosquitto Broker with IPv6</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></description>
										<content:encoded><![CDATA[<p><img loading="lazy" decoding="async" class="size-full wp-image-19245 alignleft" src="http://www.steves-internet-guide.com/wp-content/uploads/mosquitto-ipv6.png" alt="mosquitto-ipv6" width="235" height="87" />You can connect to the Mosquitto broker using <strong>IPV6</strong> as well as <strong>IPv4</strong> provided IPv6 is enabled on your machine.</p>
<p>When you start mosquitto using a basic configuration file like the one shown below mosquitto will listen for connections on both  IPv4 and IPv6.<span id="more-19225"></span></p>
<pre>include_dir /etc/mosquitto/conf.d
log_type error
log_type notice
log_type information
log_type debug
log_type websockets
log_timestamp_format %Y-%m-%dT%H:%M:%S
connection_messages true
log_dest stdout

allow_anonymous true
listener 1883

</pre>
<p>This is shown in the screen shot below:</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-19226" src="http://www.steves-internet-guide.com/wp-content/uploads/mosquitto-running-ipv6.png" alt="mosquitto-running-ipv6" width="573" height="120" srcset="http://www.steves-internet-guide.com/wp-content/uploads/mosquitto-running-ipv6.png 573w, http://www.steves-internet-guide.com/wp-content/uploads/mosquitto-running-ipv6-300x63.png 300w" sizes="auto, (max-width: 573px) 100vw, 573px" /></p>
<p>Just like with IPv4 you need to know the IPv6 address of the broker or the domain name if using DNS to connect to it.</p>
<p>With IPv4 the IP address is usually static and preferably fixed via DHCP.</p>
<p><strong>Note</strong> DHCP can be used to provide static IP addresses.</p>
<p>With IPv6 the addresses can be <strong>automatically assigned</strong> or can be  static depending on your network configuration.</p>
<p>The screen shot below shows the IPv6 addresses automatically assigned on a raspberry Pi.</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-19227" src="http://www.steves-internet-guide.com/wp-content/uploads/ipv6-addresses-linux.png" alt="ipv6-addresses-linux" width="511" height="335" srcset="http://www.steves-internet-guide.com/wp-content/uploads/ipv6-addresses-linux.png 511w, http://www.steves-internet-guide.com/wp-content/uploads/ipv6-addresses-linux-300x197.png 300w, http://www.steves-internet-guide.com/wp-content/uploads/ipv6-addresses-linux-120x80.png 120w" sizes="auto, (max-width: 511px) 100vw, 511px" /></p>
<p>If I reboot the machine the IP addresses will be the same.</p>
<p>So all we need to do is use one of these addresses to connect to the broker.</p>
<p>The address starting with <strong>2a00</strong> (global) would be used by an external client, and  the address start with <strong>fe80</strong> (link local) would be used on the local network with no routers.</p>
<p>The address starting with <strong>fdaa</strong> (unique local) would be used on the local network with or without routers.</p>
<p>Because of the length of these addresses and for ease of use making a DNS entry for these addresses would be the best option.</p>
<p>Below is a screen shot of my DNS entry:</p>
<p><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-19232" src="http://www.steves-internet-guide.com/wp-content/uploads/mosquitto-dns-ipv6.png" alt="mosquitto-dns-ipv6" width="632" height="60" srcset="http://www.steves-internet-guide.com/wp-content/uploads/mosquitto-dns-ipv6.png 632w, http://www.steves-internet-guide.com/wp-content/uploads/mosquitto-dns-ipv6-300x28.png 300w" sizes="auto, (max-width: 632px) 100vw, 632px" /></p>
<p>You should not that I have an entry for IPv4 and IPv6.</p>
<h4>Restricting IP Versions on The Broker</h4>
<p>It is possible to restrict the broker to listening on a protocol version using the <strong>socket_domain</strong> option as shown below:</p>
<p><strong>listener 1883</strong><br />
<strong>socket_domain ipv4</strong></p>
<p>will restrict the broker to IPv4</p>
<p>and</p>
<p><strong>listener 1883</strong><br />
<strong>socket_domain ipv6</strong></p>
<p>will restrict the broker to IPv6</p>
<p>With no bind address specified for the listener the broker will accept connections on any of the <strong>3 IPv6 addresses</strong>. In my case the addresses are:</p>
<p>fdaa:bbcc:ddee:0:d0a7:5928:ac3c:5b56<br />
fe80::a3f2:69f7:ca08:f9f<br />
2a00:23c6:d886:2901:a838:6c7d:851b:8a39</p>
<p>You can get the broker to listen on a particular address only using the following:</p>
<p><strong>listener 1883 fdaa:bbcc:ddee:0:d0a7:5928:ac3c:5b56</strong></p>
<p><strong>Note:</strong> it also works with the global address <strong>2a00</strong> but failed to start using the link local address.(not sure why).</p>
<h4>Connecting to the broker using a Client</h4>
<p>I tried connecting using a Python client and the mosquitto_sub client and using the domain name.</p>
<p>In both cases it connected using IPv6  by default.</p>
<p>This was with the client on a Windows 10 and a raspberry pi machine.</p>
<h4>Summary</h4>
<p>The mosquitto broker has had support for both IPv4 and IPv6 for a long time and generally to use it there is no need for any extra broker configuration required.</p>
<p>If using IPv6 then Using a Local DNS server is recommended.</p>
<p><strong>Related Tutorials and resources:</strong></p>
<ul>
<li><a href="http://www.steves-internet-guide.com/ipv6-guide/">IPv6 Explained for Beginners</a></li>
<li><a href="http://www.steves-internet-guide.com/ipv4-basics/">Understanding IPv4 Addressing and Address Classes</a></li>
<li><a href="http://www.steves-internet-guide.com/mossquitto-conf-file/">Quick Guide to The Mosquitto.conf File With Examples</a></li>
<li><a href="http://www.steves-internet-guide.com/dns-guide-beginners/">Understanding DNS – Beginners Guide to DNS</a></li>
<li><a href="https://stevessmarthomeguide.com/understanding-dhcp-home-networks/" target="_blank" rel="noopener">Understanding DHCP</a></li>
</ul>
<p>&nbsp;</p>
<div style='text-align:left' class='yasr-auto-insert-visitor'></div>The post <a href="http://www.steves-internet-guide.com/use-mosquitto-broker-with-ipv6/">How to use the Mosquitto Broker with IPv6</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></content:encoded>
					
					<wfw:commentRss>http://www.steves-internet-guide.com/use-mosquitto-broker-with-ipv6/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Using the  ArduinoMQTT Client Library</title>
		<link>http://www.steves-internet-guide.com/using-the-arduinomqtt-client-library/</link>
					<comments>http://www.steves-internet-guide.com/using-the-arduinomqtt-client-library/#comments</comments>
		
		<dc:creator><![CDATA[steve]]></dc:creator>
		<pubDate>Mon, 14 Oct 2024 15:08:09 +0000</pubDate>
				<category><![CDATA[Arduino]]></category>
		<guid isPermaLink="false">http://www.steves-internet-guide.com/?p=19053</guid>

					<description><![CDATA[<p>There are several  MQTT clients available for Arduino and we are going to use the PubSub MQTT client. Before you can use this client you need to install it into the Arduino Library. Go to the Library manager and so a search for MQTT. You will find quite a few listings scroll down the select the ArduinoMQTT client. The documentation for the library is here, but I did not find it particularly helpful. There are also code examples on the Github page here. About This Tutorial In this tutorial we will look at using the ArduinoMQTT Client Library with code</p>
The post <a href="http://www.steves-internet-guide.com/using-the-arduinomqtt-client-library/">Using the  ArduinoMQTT Client Library</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></description>
										<content:encoded><![CDATA[<p><img loading="lazy" decoding="async" class="size-full wp-image-15249 alignleft" src="http://www.steves-internet-guide.com/wp-content/uploads/arduino.png" alt="arduino" width="128" height="87" />There are several  MQTT clients available for Arduino and we are going to use the PubSub MQTT client.</p>
<p>Before you can use this client you need to install it into the Arduino Library.</p>
<p>Go to the Library manager and so a search for MQTT. You will find quite a few listings scroll down the select the ArduinoMQTT client.<span id="more-19053"></span></p>
<p>The documentation for the library is <a href="https://docs.arduino.cc/libraries/arduinomqttclient/" target="_blank" rel="noopener">here</a>, but I did not find it particularly helpful.</p>
<p>There are also code examples on the Github page <a href="https://github.com/arduino-libraries/ArduinoMqttClient/tree/master/examples" target="_blank" rel="noopener">here</a>.<!--more--></p>
<h3>About This Tutorial</h3>
<p>In this tutorial we will look at using the ArduinoMQTT Client Library with code examples for Arduino Uno (Ethernet), ESP8266 and ESP32 boards.</p>
<p>We will start by going through the basic functions available and how and in what order they are used.</p>
<p>We will see how you connect to a broker,subscribe to topics and publish messages and finally how we receive incoming messages. Working Demo scripts are available for download at the end.</p>
<h4>MQTT Client Basics</h4>
<p>For any MQTT client we have 4 distinct stages</p>
<ol>
<li>Connect</li>
<li>Subscribe</li>
<li>Publish</li>
<li>Disconnect</li>
</ol>
<p>Steps 2 and 3 are optional.</p>
<p>Before we connect we need to <strong>create a client object</strong>.</p>
<p>This client object is tied to the underlying physical connection i.e. (Ethernet or Wi-Fi).</p>
<p>For Wi-FI you will see something similar to this near the top of the code</p>
<pre>WiFiClient espClient;
MqttClient mqttClient(espClient);
</pre>
<p>All MQTT clients are required to have a <strong>unique client id</strong> .</p>
<p>and for Ethernet we have</p>
<pre>EthernetClient ethClient;
MqttClient mqttClient(ethClient);
</pre>
<p>You need to set this before connecting along with any other connection parameters like clean session, username/password etc.<br />
To set the <strong>client id</strong> use:</p>
<pre>mqttClient.setId("esp32-1");</pre>
<p>were <strong>esp32-1</strong> is the client name.</p>
<p>Some Other commands are :</p>
<ul>
<li>MqttClient.setKeepAliveInterval(unsigned long interval)</li>
<li>MqttClient.setCleanSession(bool cleanSession)</li>
<li>void MqttClient.setUsernamePassword(const char* username, const char* password)</li>
</ul>
<p>Once you have set the client options you can then connect to the broker using the <strong>mqttClient.connect(broker,port) </strong> call as shown below:</p>
<pre>const char broker[] = "192.168.1.33";
int        port     = 1883;
mqttClient.connect(broker,port);
</pre>
<p>The call returns true if successful and false if not, and so it is normal to put this call in a while and if loop the psuedo code is:</p>
<blockquote><p>while not connected<br />
try and connect</p></blockquote>
<p>Actual code is below and uses the mqttClient.connected() function call to test the connection (0=connected,1=not connected).</p>
<pre>  
void reconnect() {
while (mqttClient.connected()==0) {
      mqttClient.setId("esp32-1");
      Serial.print("Attempting to connect to the MQTT broker: ");
      Serial.println(broker);

  if (!mqttClient.connect(broker, port)) {
    Serial.print("MQTT connection failed! Error code = ");
    Serial.println(mqttClient.connectError());
         Serial.print("failed, rc=");
      Serial.println(" try again in 5 seconds");
      delay(5000);
   }
 else {
  
  Serial.println("Connected to the MQTT broker!");
  Serial.println();
 Serial.println("connected so subscribe");
 mqttClient.subscribe(topic);
    }
  }//end while
} //end function
</pre>
<p>In many online scripts this code is placed in the setup, but if you do this the client will not reconnect so I place it inside a function and call the function from the loop. You can see this in the code above.</p>
<h3>Receiving Messages</h3>
<p>In order to receive messages you will need to:</p>
<ul>
<li>subscribe to a topic or topics</li>
<li>configure a callback to handle the received message</li>
</ul>
<p>To subscribe to a topic or topics use <strong>mqttClient.subscribe(topic)</strong> function.</p>
<p>You should note that you can use wild cards when subscribing see <a title="Understanding MQTT Topics" href="http://www.steves-internet-guide.com/understanding-mqtt-topics/" target="_blank" rel="noopener">Understanding MQTT topics</a> for details.</p>
<p>The subscribe code is paled in the connect loop and you can see it in the code above<strong>&#8211; mqttClient.subscribe(topic).</strong></p>
<p>The call back consists of a callback function and a set up. Sample call back function is shown below:</p>
<pre>void onMqttMessage(int messageSize) {
  // we received a message, print out the topic and contents
  Serial.println("Received a message with topic '");
  Serial.print(mqttClient.messageTopic());
  Serial.print("', length ");
  Serial.print(messageSize);
  Serial.println(" bytes:");

  // use the Stream interface to print the contents


  while (mqttClient.available()) {
   Serial.print((char)mqttClient.read());
  }
  Serial.println();

}
</pre>
<p>In the setup you need to register this callback using</p>
<pre> mqttClient.onMessage(onMqttMessage); //callback
</pre>
<h3>mqttClient.poll() Function</h3>
<p>This function needs to be called on a regular basis and it processes the receive buffer.</p>
<p>Without this function you want see any incoming messages including control messages like puback,pingresp.</p>
<p>I did a tutorial on <a title="Paho Python MQTT Client-Understanding The Loop" href="http://www.steves-internet-guide.com/loop-python-mqtt-client/" target="_blank" rel="noopener">the loop</a> in relation to python but it is applicable to all MQTT clients.</p>
<p>The arduino client is single threaded and so it must be placed in the loop.</p>
<p>In addition the loop should not  have any delays . Here is my loop example:</p>
<pre>void loop() {
  // call poll() regularly to allow the library to send MQTT keep alives which
  // avoids being disconnected by the broker
  mqttClient.poll();
 if (mqttClient.connected()==0) {
    reconnect();
  }
  // to avoid having delays in loop, we'll use the strategy from BlinkWithoutDelay
  // see: File -&gt; Examples -&gt; 02.Digital -&gt; BlinkWithoutDelay for more info
      unsigned long now = millis();
     if (now - lastMsg &gt; 5000) {
    lastMsg = now;
    Serial.print("Publishing message: ");
    Serial.println(msg);
    publish_msg(topic, msg);
    //Serial.printf("RSSI: %d dBm\n", WiFi.RSSI());
    WiFi.printDiag(Serial);
 
     }
    
}
</pre>
<p>Notice we do not use delay(5000) to control the print as this would cause a delay.<br />
Also notice that the connection is tested and if it has failed the reconnect function is called.</p>
<h3>Publishing Messages</h3>
<p>This is done with the calls to three functions<br />
beginMessage(),print() and end. Actual code is shown below:</p>
<pre>    mqttClient.beginMessage(topic);
    mqttClient.print(msg);
    mqttClient.endMessage();
</pre>
<p>The begin message function can also take the retain flag and QOS,<br />
e.g to publish with a QOS or 1 and retain flag set use:</p>
<pre>mqttClient.beginMessage(topic,true,1);</pre>
<h4>User names and Passwords</h4>
<p>If the broker requires authentication you can set the username and password the you can set this before you connect using</p>
<p>mqttClient.setUsernamePassword(&#8220;username&#8221;, &#8220;password&#8221;);</p>
<h4>Last Will Message</h4>
<p>The <a title="MQTT Last Will and Testament Use and Examples" href="http://www.steves-internet-guide.com/mqtt-last-will-example/" target="_blank" rel="noopener">last will message</a> and topic need to be set before connecting and use the same format as the publish as shown in the code below.</p>
<pre>   char willTopic[]        = "connected/esp-32";
  char willPayload[] = "not connected";
  bool willRetain = true;
  int willQos = 1;

  mqttClient.beginWill(willTopic, willRetain, willQos);
  mqttClient.print(willPayload);
  mqttClient.endWill();
</pre>
<p><strong>Code Examples</strong></p>
<p>The example code will subscribe to a topic and publish a message on the same  topic every 5 seconds.</p>
<p>It also sets a will message and uses authentication.</p>
<p>The code for all three boards -arduino, ESP32 and ESP8266 is virtually identical and only differs in the libraries.</p>
<p>At the top of the ESP code you will see:</p>
<pre>#include &lt;ArduinoMqttClient.h&gt;
#include &lt;ESP8266WiFi.h&gt; //use this for ESP8266
//#include &lt;WiFi.h&gt; //use this and comment out above when using ESP32 boards
//#include "arduino_secrets.h"
//#include "arduino_secrets.h"
//#include "arduino_secrets.h"
//#include "arduino_secrets.h"
///////please enter your sensitive data in the Secret tab/arduino_secrets.h
char ssid[] = "Akehurst";    // your network SSID (name)
char pass[] = "akehurst122012";    // your network password (use for WPA, or use as key for WEP)

WiFiClient espClient;
MqttClient mqttClient(espClient);
</pre>
<p>for esp8266 we use:</p>
<pre>#include &lt;ESP8266WiFi.h&gt;</pre>
<p>and for ESP32 we use</p>
<pre>#include &lt;WiFi.h&gt;</pre>
<h4>Arduino Ethernet</h4>
<p>For the arduino board with Ethernet we have:</p>
<pre>#include &lt;ArduinoMqttClient.h&gt;
#include &lt;Ethernet.h&gt;

// Update these with values suitable for your network.
byte mac[]    = {  0xDE, 0xED, 0xBA, 0xFE, 0xFE, 0xED };
IPAddress ip(192, 168, 1, 89); //address of client
EthernetClient ethClient;
MqttClient mqttClient(ethClient);
</pre>
<h4>Full Demo code</h4>
<p><a href="http://www.steves-internet-guide.com/download/aduinomqtt-client-for-esp328266-and-arduino-uno/" target="_blank" rel="noopener"><img loading="lazy" decoding="async" class="aligncenter size-full wp-image-15784" src="http://www.steves-internet-guide.com/wp-content/uploads/download.jpg" alt="download" width="198" height="63" /></a></p>
<p><strong>Related Tutorials and Resources:</strong></p>
<ul>
<li class="sitemap"><a href="http://www.steves-internet-guide.com/send-and-receive-integers-and-floats-with-arduino-over-mqtt/">Send and Receive Integers and Floats with Arduino over MQTT</a></li>
<li class="sitemap"><a href="http://www.steves-internet-guide.com/arduino-sending-receiving-json-mqtt/">Arduino -Sending and Receiving JSON Data over MQTT</a></li>
<li class="sitemap"><a href="http://www.steves-internet-guide.com/using-arduino-pubsub-mqtt-client/">Using the Arduino PubSub MQTT Client</a></li>
</ul>
<div style='text-align:left' class='yasr-auto-insert-visitor'></div>The post <a href="http://www.steves-internet-guide.com/using-the-arduinomqtt-client-library/">Using the  ArduinoMQTT Client Library</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></content:encoded>
					
					<wfw:commentRss>http://www.steves-internet-guide.com/using-the-arduinomqtt-client-library/feed/</wfw:commentRss>
			<slash:comments>1</slash:comments>
		
		
			</item>
		<item>
		<title>MQTT C client &#8211; Connect, pub and subscribe,Single Thread</title>
		<link>http://www.steves-internet-guide.com/mqtt-c-client-connect-pub-and-subscribesingle-thread/</link>
					<comments>http://www.steves-internet-guide.com/mqtt-c-client-connect-pub-and-subscribesingle-thread/#respond</comments>
		
		<dc:creator><![CDATA[steve]]></dc:creator>
		<pubDate>Wed, 28 Aug 2024 18:38:53 +0000</pubDate>
				<category><![CDATA[C-MQTT]]></category>
		<guid isPermaLink="false">http://www.steves-internet-guide.com/?p=18956</guid>

					<description><![CDATA[<p>In This tutorial we will look in more detail on how to connect , publish and subscribe using the MQTT v 3.1.1 client synchronous client using a single thread. We will not be using callbacks. If you use callbacks then second thread is started automatically to process the callbacks. If you don’t declare callbacks then you need to manually check for received messages using the MQTTClient_receive function. This function needs to be called often, and is often found in an infinite loop. Basic Code Structure In the previous tutorial MQTT Client Basics we looked at the general code structure: The</p>
The post <a href="http://www.steves-internet-guide.com/mqtt-c-client-connect-pub-and-subscribesingle-thread/">MQTT C client – Connect, pub and subscribe,Single Thread</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></description>
										<content:encoded><![CDATA[<p><img loading="lazy" decoding="async" class="size-full wp-image-18958 alignnone" src="http://www.steves-internet-guide.com/wp-content/uploads/mqtt-c-client.png" alt="mqtt-c-client" width="226" height="58" />In This tutorial we will look in more detail on how to connect , publish and subscribe using the MQTT v 3.1.1 client synchronous client using a single thread.</p>
<p>We will not be using callbacks. If you use callbacks then <strong>second thread</strong> is started automatically to process the callbacks.<span id="more-18956"></span></p>
<p>If you don’t declare callbacks then you need to manually check for received messages using the <strong>MQTTClient_receive</strong> function.</p>
<p><img loading="lazy" decoding="async" class="aligncenter wp-image-18822 size-full" src="http://www.steves-internet-guide.com/wp-content/uploads/mqttclient_receive-function.png" sizes="auto, (max-width: 764px) 100vw, 764px" srcset="http://www.steves-internet-guide.com/wp-content/uploads/mqttclient_receive-function.png 764w, http://www.steves-internet-guide.com/wp-content/uploads/mqttclient_receive-function-300x162.png 300w" alt="mqttclient_receive-function" width="764" height="413" /></p>
<p>This function needs to be called often, and is often found in an infinite loop.</p>
<h4>Basic Code Structure</h4>
<p>In the previous tutorial MQTT Client Basics we looked at the general code structure:</p>
<p>The Basic code structure used is:</p>
<ul>
<li>Create a client object</li>
<li>Set the options to connect to an MQTT server</li>
<li>Set up callback functions if multi-threaded</li>
<li>Subscribe to any topics.</li>
<li>Publish  messages</li>
<li>Handle any incoming messages</li>
<li>Disconnect the client</li>
<li>Free any memory being used by the client</li>
</ul>
<p>Now will look at an example client and the code.-</p>
<p>The example  code simulates a simple sensor that publishes data at regular intervals (10 secs) on topic MQTT-OUT and can also receive data (commands) on the topic MQTT-IN.</p>
<p>At the top of the code we create the client and then initialise the connection options, and the publish message structures.<br />
The <strong>delivery token</strong> is actually the <strong>msgid</strong> that is present on messages published with QOS of 1 or 2.</p>
<pre>MQTTClient Client; 
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer; MQTTClient_deliveryToken token;
</pre>
<p>Because we are using a single thread we need to call <strong>MQTTClient_receive</strong> function at regular intervals.</p>
<p>This is a blocking call so we set the time out to be short (0.01) so as to not cause a delay in the loop.</p>
<p>We use the time function with a flag to determine when to call the publish function (every 10 seconds) . The code is below</p>
<pre>while (1)
{

rc=MQTTClient_receive(Client,&amp;topicName,&amp;topiclen,&amp;message,0.01);

if(topicName){
printf("Message received on topic %s is %.*s.\n", topicName, message-&gt;payloadlen, (char*)(message-&gt;payload));
}
seconds=time(NULL);
if(seconds%10==0 &amp;&amp; pub_flag==0)
{
printf("publishing");
pub_flag=1; //don't want to publish too many messages
pub_msg();
}
if(seconds%10==1&amp;&amp; pub_flag==1)
{

pub_flag=0; //reset
;
}
</pre>
<p>So as to avoid having to pass parameters into the <strong>pub_msg</strong> function I declare most of the variables outside of the main function.</p>
<p>The code will publish messages and receive messages until stopped using CTRL+C and the complete code is shown below:</p>
<pre>#include 
#include 
#include 
#include "MQTTClient.h"
#include 
#include 

#define ADDRESS     "tcp://localhost:1884"
#define CLIENTID    "ExampleClientPub"
#define TOPIC_IN    "MQTT-IN"
#define TOPIC_OUT    "MQTT-OUT"
#define PAYLOAD     "testing"
#define QOS         1
#define TIMEOUT     10000L
time_t seconds;

MQTTClient Client;
MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
MQTTClient_message pubmsg = MQTTClient_message_initializer;
MQTTClient_deliveryToken token;

void pub_msg()
{
    pubmsg.payload=PAYLOAD;
    pubmsg.payloadlen = (int)strlen(pubmsg.payload);
    pubmsg.qos = QOS;
    pubmsg.retained = 0;
    int rc;

    MQTTClient_publishMessage(Client, TOPIC_OUT, &amp;pubmsg, &amp;token);
    printf("Waiting here for up to %d seconds for publication of %s\n"
            "on topic %s for client with ClientID: %s\n",
            (int)(TIMEOUT/1000), PAYLOAD, TOPIC_OUT, CLIENTID);
    rc = MQTTClient_waitForCompletion(Client, token, TIMEOUT);
    printf("Message with delivery token %d delivered\n", token);
}

int main(int argc, char* argv[])
{

    int rc;
    rc=MQTTClient_create(&amp;Client, ADDRESS, CLIENTID,
        MQTTCLIENT_PERSISTENCE_NONE, NULL);

    char * topicName=NULL;
    int topiclen;
    MQTTClient_message *message=NULL;

    conn_opts.keepAliveInterval = 120;
    conn_opts.cleansession = 1;
    if ((rc = MQTTClient_connect(Client, &amp;conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        exit(EXIT_FAILURE);
    }
    rc=MQTTClient_subscribe(Client,TOPIC_IN,QOS);
    printf("Subscribed %d \n",rc);
int pub_flag=0;
while (1)
{
    
rc=MQTTClient_receive(Client,&amp;topicName,&amp;topiclen,&amp;message,0.01);

if(topicName){
        printf("Message received on topic %s is %.*s.\n", topicName, message-&gt;payloadlen, (char*)(message-&gt;payload));
}
seconds=time(NULL);
//sleep(5);
if(seconds%10==0 &amp;&amp; pub_flag==0)
{
	printf("publishing");
	pub_flag=1; //don't want to publish too many messages
pub_msg();
}
if(seconds%10==1&amp;&amp; pub_flag==1)
{

	pub_flag=0; //reset
;
}
}

    printf("end Sleeping \n");
    //sleep(100);
    MQTTClient_disconnect(Client, 10000);
    MQTTClient_destroy(&amp;Client);
    return rc;
}

</pre>
<p><strong>Related Tutorials and resources:</strong></p>
<ul>
<li><a href="http://www.steves-internet-guide.com/paho-mqtt-c-client-introduction/">Paho MQTT C Client Introduction</a></li>
<li><a href="http://www.steves-internet-guide.com/loop-python-mqtt-client/">Paho Python MQTT Client-Understanding The Loop</a></li>
</ul>
<div style='text-align:left' class='yasr-auto-insert-visitor'></div>The post <a href="http://www.steves-internet-guide.com/mqtt-c-client-connect-pub-and-subscribesingle-thread/">MQTT C client – Connect, pub and subscribe,Single Thread</a> first appeared on <a href="http://www.steves-internet-guide.com"></a>.]]></content:encoded>
					
					<wfw:commentRss>http://www.steves-internet-guide.com/mqtt-c-client-connect-pub-and-subscribesingle-thread/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
