MQTT Beginner Guide with Python

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
welcome everybody to my mqtt beginners guide with an example python implementation the video will cover two parts first a very short theoretical introduction and i promise i keep it very short and second a practical example of an mqtt implementation with python if you directly want to get your hands dirty of course you can skip the theoretical introduction and directly skip to minute seven but i recommend to stay before we start two things first you can find the whole code which i show later here on github and i'll put a link into the description and second i published everything i tell you in this video also on medium.com which is kind of a blog you will find all the theoretical examples which i tell you now written down here as well as the examples of the code i'll show in some minutes and i'll also put the link into the description alright so let's start with the theoretical explanation of mqtt mqtt is an open and simple client server publish subscribe message transfer protocol designed for machine to machine communication between different devices and environments of high latency and low network bandwidth what the hell let's break it down a little bit so first of all machine to machine communication what does that mean basically it means the need of one machine or let's call it better device to communicate with or talk to another machine or device and actually this happens all the time already especially in the iot context so imagine you're you're having a smart home right and perhaps you have an outside temperature sensor which informs your heating devices whenever the outside temperature is below a certain degree to turn on the radiators or something same time of course with your smartphone you want to know how cold it is outside and get informed at the same time you want to control your heating devices from your smartphone perhaps additionally you want to switch on and off your lights in your house with your smartphone or even better automated so whenever you leave the house to turn them on to turn them off sorry automatically at the same time you can control your vacuum cleaner with your smartphone or even get information from your fridge whenever something is missing so the need is already present that devices talk to each other frequently and mqtt is a protocol which enables which is a perfect match for especially those iot contexts to enable machines to talk to each other alright so machine to machine communication check next environments of high latency and low network bandwidth so mqtt is a very lightweight protocol it's very efficient and has a small footprint at the same time it has different levels of quality of services which ensures that messages between devices are actually delivered even if the environments are unstable like unwired connections via wi-fi bluetooth satellite and so on mqtt is very resistant here which makes it a perfect match for iot scenarios all right environments of high latency and low network bandwidth check next client server publish subscribe so this is actually a very powerful feature of mqtt let's recap on on the picture before like imagine you're having a smart home having a lot of devices talking to each other being connected with each other it will get chaotic and no one will have an overview anymore which device is talking to which device how frequently about which topics and so on so it will get chaotic so how will mqtt solve this actually mqtt comes with the mqtt broker which is a server which structures communication into different topics here an example we have a topic temperature and a topic position the different devices can now publish information to these topics so imagine having your outside temperatures and sensor publishing information to the temperature topic at the same time your heating devices can publish their current temperature to this topic and as well as your smartphone can publish to the temperature topic to control the temperature for example to say all heating devices please 22 degrees so devices can not only publish information to this topic at the same time interested devices can subscribe to the topic for example the smartphone can subscribe to the temperature topic because it's interested in the outside temperature at the same time the heating devices can subscribe to the temperature topic to be informed whenever whenever the smartphone sends a control message to regulate the temperature let's have a look on the position topic so for example the smartphone can publish its actual position for example if the user leaves his house the position is located outside at the same time for example the vacuum cleaner can publish its position to say in which room is actually cleaning on the other hand other devices can subscribe if they are interested in the position for example the heating devices and the light bulbs to turn off whenever the user leaves his home the security camera can turn on whenever the user leaves a home at the same time the robot the vacuum cleaner can can subscribe to the position topic to start whenever the user is not at home to not annoy him that's how mqtt structures communication here and decouples the devices from each other the mqtt broker here acts as a server while as all devices publishing or subscribing information will act as a client alright client server publish subscribe check now let's have a look on how simple mqtt is and we'll get our hands dirty with python we'll run a free mqtt broker server and write some clients to publish and subscribe messages to within pi's and then you can see how simple it is all right to get started we need two things one an mqtt broker of server and an mqtt client so for the mqtt broker or server there are some free ones available online so just type in mqtt eclipse and you'll find the free server here mqtt mqtt.eclipseprojects.io and this is basically already an mqtt broker you can connect to on a free basis next is we need a client in python and for this we'll use a payo mqtt library so just type in payo mqtt and you'll find a good documentation on what you need basically you can install it quickly with pip let's do it pip install payo mqtt hit enter and i already installed it before so what we are gonna do today is we create two publishers two mqtt publishers um faking the inside temperature from uh from a heating device and one faking the outside temperature from an outside temperature sensor and then we are writing a receiver or a subscriber to subscribe so smash messages from the mqtt broker let's first start with the publisher let's create a new file here somehow wait a second new file like this mqtt publish one py and first do the imports let's delete this so from pay ho mqtt we import the client as mqtt we do some imports from random to later publish randomized numbers and we import time to do this on a regular basis next thing is basically to connect to the broker and create the client so with only three lines of code we connected to our mqtt broker this one and we just pasted it over this ul i i'll also put it into the description of the video next the thing is we create a client with the payo mqtt client library here and give the client a name in this this time i just named it temperature inside and then from the client which we named temperature inside we can connect to our broker which we specified before to finish our first mqtt publisher all we need now is from this client publish messages to this broker so let's do this so all we do here with these four lines of code is we'll generate a random number between 20 and 21 which will basically fake the inside temperature we'll publish this random number two and this is important the topic called temperature which we specify here from our client which we call temperature inside and then we just print it out to the console so just published the random number to topic temperature we sleep one second and then do the same again until forever let's try to run it mqtt publish one dot py and i made an error somewhere yes here so you don't need to specify the http it's fine if you just do it like this and let's rerun it and it seems to work so it's telling me just published then the random number to topic temperature all the time each second yeah basically it seems as if it's working we can't verify because we don't we can't see inside the broker we need to look on the other side on the subscriber to actually see if we can subscribe these messages from the broker topic temperature but before we do so first let's finish off also our second publisher the outside temperature so for our second publisher the outside temperature we can copy over the complete code just create a new file here mqtt publish2.py paste it over and we keep everything exactly the same just we renamed the client here to temperature outside and we'll use another temperature between 20 and 21 degrees we'll use rand range to create a temperature between 0 and 10 degrees which is quite of common in the winter in germany all right rest stays the same we connect to our broker we spin up a client with the name temperature outside and we connect from the client to the broker we generate a random number between 0 and 10 and publish this to the temperature topic let's try to run it and you see it generates a random number between 0 and 10 and just prints out to the console that it published it successfully to the topic on the broker but as mentioned to be able to really see that we can subscribe and read it out of the topic from the other side we need to create a subscriber so let's do this all right time for our subscriber so let's create a new file mqtt subscribe dot py and again we can copy over a lot of things here basically the first six lines ah we don't need this random stuff anymore like this so we import the payo mqtt client we again connect to the broker and then this time our client should fake our smartphone from which we subscribe to the temperature from outside and inside to have all the relevant information available on our phone and we again connect to the mqtt broker so until here no change but now it's getting interested so we need to subscribe to a topic within a loop so let's first of all create this loop so we start the loop here and end it here and wait 30 30 seconds before we end the loop from the client here and from within the loop now we can subscribe to messages of a certain topic let's do this so basically with only one line of code we can subscribe already to the topic temperature but and this means we already receive messages but we will not see them because to be able to see them to do something with a message we need a on message callback function to define so let's do it so what we do here so here we have our loop with in the loop which which runs for 30 seconds within the loop we subscribe to our temperature topic and whenever we receive a message while subscribing we execute this function on message and onmessage is defined as following so whenever a message comes in we just print out receive message and then we print out the payload of the message and decode it that's it let's see if it works subscribe dot py and we see we'll get certain messages which were published before perhaps let's turn it around let's run our subscriber here and then run the publishers in a separate comment line so let me prepare it quickly so let's first run our sub subscriber here and then quickly run our producers [Music] publish two dot py and one dot py and go back to our subscriber and we see our two publishers are running with outside and inside temperature and in our subscriber we are directly getting it out of the temperature topic here basically that's it already with my quick demo so this runs now for 30 second and then it reaches loop blue band and that's it that's the purpose we got our hands dirty got some experience with some basic mqtt functions publishing and subscribing hope you liked it thank you for watching see you soon
Info
Channel: Techletters
Views: 51,103
Rating: undefined out of 5
Keywords: mqtt, mqtt broker, mqtt client, paho mqtt, mosquitto, python, python3, programming, development, 100daysofcode, iot, internet of things, How does MQTT work?, Mqtt python
Id: kuyCd53AOtg
Channel Id: undefined
Length: 17min 59sec (1079 seconds)
Published: Wed Dec 23 2020
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.