MQTT Script Help


Im having some trouble with my Python script authentication to my MQTT Broker.

I have a PIR Sensor connected to a Pi and a python script that will publish its state to home assistant. I have this bit working just fine if I don’t use authentication on my broker.

The bit I’m stuck with is how to incorporate my brokers authentication into my python script so I can keep it secure. Ive googled around online and so many people script it in different ways and I cant find a way that works with my script.

Here is my script below, can someone help me incorporate a line so I can add my brokers username and password.


# Detect movement using a PIR module
# Author : Matt Hawkins
# Date   : 21/01/2013

# Import required Python libraries
import RPi.GPIO as GPIO
import time
import paho.mqtt.publish as publish

# Use BCM GPIO references
# instead of physical pin numbers

# Define GPIO to use on Pi

print "PIR Module Test (CTRL-C to exit)"

# Set pin as input
GPIO.setup(GPIO_PIR,GPIO.IN)      # Echo

Current_State  = 0
Previous_State = 0


  print "Waiting for PIR to settle ..."

  # Loop until PIR output is 0
  while GPIO.input(GPIO_PIR)==1:
    Current_State  = 0

  print "  Ready"

  # Loop until users quits with CTRL-C
  while True :

    # Read PIR state
    Current_State = GPIO.input(GPIO_PIR)

    if Current_State==1 and Previous_State==0:
      # PIR is triggered
      print "  Motion detected!"
      publish.single("motion/motion", "Motion Detected", retain=True, hostname="")
      # Record previous state
    elif Current_State==0 and Previous_State==1:
      # PIR has returned to ready state
      print "  Ready"
      publish.single("motion/motion", "No Motion", retain=True, hostname="")
    # Wait for 10 milliseconds

except KeyboardInterrupt:
  print "  Quit"
  # Reset GPIO settings

The api doc for your library is at

From that, I think you need your publish lines to be

      publish.single("motion/motion", "No Motion", retain=True, hostname="", auth = {'username': "yourusername", 'password': "Your Password"})
1 Like

Awesome worked perfectly! So simple too! I couldn’t find that anywhere.