How to send WhatsApp messages in Īwesome news, this opens up the possibility of more complex IoT systems, since it can be used by multiple devices. Update: Works great on my Raspberry Pi that I keep up as a little print server in back. In MQTTlens, you should now see the messages sent to the topic, such as shown in figure 3.įigure 3 - Messages received from the subscribed topic. On the command line, insert the message you want, such as exemplified in figure 2. Otherwise, we will print a error message. It has the value 0 when the connection is successful.
In this example we are only going to use the argument specified in the previous link as rcwhich contains the result of the connection. It receives 4 arguments, as can be seen here. In the except block, since the program will finish, we call the disconnect method, to disconnect from the broker. To send a message to a topic, we just need to call the publish method, passing as first argument the topic where we want to publish, and has second argument the message to be sent. After that, we will run a continuous loop in a try except block, that will catch a keyboard interrupt. As we said, this will be done in our callback function, which we still need to specify. On the background, it calls a method called loop. It will receive as input the broker address and the port. Finally, we will call the connect method, for establishing the connection to the broker.
We will just assign the function for now and define the actual code latter. This method should be called before the connect method, which we will call in a moment. You can check here other optional arguments that the constructor takes. We will pass as argument of the constructor a unique client identifier in format of a string. Now, we will create a new client instance. You should use the information from your instance. This will be the information mentioned in the introduction section, shown in figure 1. Next, we will declare 4 variables to hold the information needed to connect to the server. The important credentials that we will be using are the serverthe userthe password and the port.įirst, we need to import the client class, to have access to all the functionality needed to connect to the broker and publish some messages to topics. After completing the procedure, check the instance information page, which should be similar to the one shown in figure 1. You can check here how to create an account and how to create a broker instance. To do so, we just need the following command.
As usual, the easiest way to install this library is by using pipa tool for installing Python packages. For this example, we will be using paho-mqtt for Python.
The objective of this post is to explain how to connect to a MQTT broker and post some messages to a topic, using Python.