Getting Started with Home Automation Using MQTT

Michael just shared a new tutorial: "Getting Started with Home Automation Using MQTT"



What is MQTT?
MQTT (Message Queue Telemetry Transport) is a simple and ‘lightweight’ way for internet-connected devices to send each other messages. This is important for home-automation because devices need to send messages back an…

Read more

2 Likes

Hi, when I run the code python mqtt_publish_demo.py in my raspberry pi; there is some mistake like:

Traceback(most recent call last):
File “mqtt_publish-demo.py”, line 6, in
publish.single(“CoreElectronics/test”,“Hello”,…)

Hi, I am also having problems with getting the MQTT demo script working. For me, the Client never connects - in other words I can’t get a CONNACK from the server, and the program just hangs in the loop_forever function.
I’m using the Pi Zero-W, and can access the internet web pages, even if a little slow. So internet connection should be fine.
Anything else I can check?

Hi Paul,

Have you tried to ping the server to make sure there is nothing blocking local network traffic?

Hi Clinton,
Yes - ping works OK to my local PC, google and mosquitto web servers.

It’s never the easy solution :smile:
Are you using the same port and keepalive timeout as the tutorial?
If you go to the test.mosquitto.org it will give you a few other options for ports and information.
If you have not tried it already I would also add a bunch of print statements so that you can determine exactly where it is failing.

Thanks,
I tried making the timeout longer. No difference. I haven’t tried alternative ports - but they seam to include encryption or websockets.
I’ve already inserted print statements - the Client is created OK, it gets to the client.connect routine OK, then after a very short pause reaches the loop function.

Are you able to post your code?

Sometimes with these routines the Client is created but does not connect until it is used. There is not much modifiable in the client loop so I suspect something prior is wrong.

If everything else is fine you may want to try updating pip and the MQTT library with
sudo pip install --upgrade pip
sudo pip install --upgrade paho-mqtt

Hi Clinton, here is what happens - it exits from the same place in the loop when I ^C
New%20Picture%20(5)
and the code, copied from the tutorial:

Thanks a lot for clarifying the MQTT protocol with example code. By the way, KeyboardInterrupt is introducing during closing the mqtt_client_demo.py. Isn’t it better to handle this with Try/Except block. I did this as follows:

# MQTT Client demo
# Continuously monitor two different MQTT topics for data,
# check if the received data matches two predefined 'commands'
 
import paho.mqtt.client as mqtt
 
# The callback for when the client receives a CONNACK response from the server.
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
 
    # Subscribing in on_connect() - if we lose the connection and
    # reconnect then subscriptions will be renewed.
    client.subscribe("CoreElectronics/test")
    client.subscribe("CoreElectronics/topic")
 
# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

    if msg.payload == "Hello":
        print("Received message #1, do something")
        # Do something


    if msg.payload == "Programmer!":
        print("Received message #2, do something else")
        # Do something else

try:
    # Create an MQTT client and attach our routines to it.
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
 
    client.connect("test.mosquitto.org", 1883, 60)
 
    # Process network traffic and dispatch callbacks. This will also handle
    # reconnecting. Check the documentation at
    # https://github.com/eclipse/paho.mqtt.python
    # for information on how to use other loop*() functions
    client.loop_forever()
except KeyboardInterrupt:
    # disconnect
    print("Stropping the client ...")
    client.disconnect()

Hi, my mqtt broker requires authentication. Where do you put int the user/password?
Thanks!

1 Like

@Nuno125208 you are correct. Normally a MQTT client requires some form of Authentication.
However for Mosquitto they are basically allowing any user/pass combination.

Have you tried the answer on this page ?
http://www.steves-internet-guide.com/mqtt-username-password-example/

1 Like

Hi Nuno,

That’s a great question. What’s the exact output which is being listed that’s requiring authentication. It shouldn’t have any predetermined requirements for authentication as Andy said, but their may be a standard depending on the application. All the best with your project!

Bryce
Core Electronics | Support

Greetings team. It works great for me on my Raspberry. Except

Connected with result code 0
CoreElectronics/test b’Hello’ <== Notice how it added 'b’
Received message #1, do something <== Not showing
CoreElectronics/topic b’World!’ <== Notice how it added 'b’
Received message #2, do something else <== Not showing

Used the following client:

# The callback for when a PUBLISH message is received from the server.
def on_message(client, userdata, msg):
    print(msg.topic+" "+str(msg.payload))

    if msg.payload == "Hello":
        print("Received message #1, do something")
        # Do something

    if msg.payload == "World!":
        print("Received message #2, do something else")
        # Do something else
~~~~~~~~~~~

Resolved: I determined this occurred because I used “python3”. Error went away when I used “python”

1 Like

Excellent,

Thanks for letting us know Charles, hopefully, this will be useful for someone else in the future.

@Charles146621 I have similar issue - “Do something is not printing”. I wonder what it has to do with python3, if the program runs without any syntax/parsing error then it should work fine.
Does anyone get this working with python3?

1 Like