Issue (mqtt switch)

Hi, i’m a little bit confused please help.

I’m trying to run a python script on mosquitto powered by a raspberry pi on mqttcloud.com, when i check the websocket i get the message back so i seems to work. My issue is that when i want to set a switch to trigger an led but it doesn’t do anything.

if someone can help me it will be great!
(sorry for my bad english)

my python code running on mosquito (raspberry pi)

#!/usr/bin/env python

import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO

def on_connect(client, userdata, rc):
    #print ("Connected with rc: " + str(rc))
    client.subscribe("kwf/demo/led")

def on_message(client, userdata, msg):
    #print ("Topic: "+ msg.topic+"\nMessage: "+str(msg.payload))
    if "green" in msg.payload:
        #print("  Green on!")
        GPIO.output(11, True)
    else:
        #print("  Green off!")
        GPIO.output(11, False)
    if "yellow" in msg.payload:
        #print("  Yellow on!")
        GPIO.output(12, True)
    else:
        #print("  Yellow off!")
        GPIO.output(12, False)
    if "red" in msg.payload:
        #print("  Red on!")
        GPIO.output(13, True)
    else:
        #print("  Red off!")
        GPIO.output(13, False)
        

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect("m21.cloudmqtt.com", 17644, 60)

GPIO.setmode(GPIO.BOARD)
GPIO.setup(11, GPIO.OUT)
GPIO.setup(12, GPIO.OUT)
GPIO.setup(13, GPIO.OUT)

client.loop_forever() 

switch:
- platform: mqtt
    name: mqttswitch
    state_topic: "kwf/demo/led"
    command_topic: "kwf/demo/led/green"
    payload_on: "off"
    payload_off: "on"

mqtt:
  broker: m21.cloudmqtt.com
  port: 17644
  client_id: home-assistant-1
  keepalive: 60
  username: !secret mqtt_user_name
  password: !secret mqtt_user_passwd

Please format your code blocks in your post so they can be read correctly. Highlight your code blocks and press the preformated text button in the post editor as shown below:

There are lots of things that may be going wrong, so to start with, if you uncomment the print lines, what gets printed out?

That should help narrow the possibilities.

Hi gpbenton thank you for anwsering on this issue, i get this after uncomment the print line: !/usr/bin/env python

/home/pi/mqtt_led_client.py: line 1: !/usr/bin/env: No such file or directory
/home/pi/mqtt_led_client.py: line 3: import: command not found
/home/pi/mqtt_led_client.py: line 4: import: command not found
/home/pi/mqtt_led_client.py: line 6: syntax error near unexpected token `('
/home/pi/mqtt_led_client.py: line 6: `def on_connect(client, userdata, rc):'

I think you removed the comment from the first line, as well as the print lines. The comment on the first line is important, so you need to put it back and run the program again.

I get this after commenting the first line: Connected with rc: 5

Good. You connected, which is normally the tricky bit.

Now I think you want to turn the lights on by changing a switch in the HA screen,
If so, you need to change the switch state_topic and command_topic to 'kwf/demo/led`, to match the topic being received.

The ‘payload_on’ needs to be ‘green’ (to switch the green led on) and the ‘payload_off’ needs to be an empty string “” (or anything other than green, yellow or red)

Sir you mean like this?

switch:
- platform: mqtt
    name: mqttswitch
    state_topic: "kwf/demo/led"
    command_topic: "kwf/demo/led"
    payload_on: "kwf/demo/led/green"
    payload_off: ""

just green in the payload_on

switch:
- platform: mqtt
    name: mqttswitch
    state_topic: "kwf/demo/led"
    command_topic: "kwf/demo/led"
    payload_on: "green"
    payload_off: ""

i get this on myt CloudMQTT Console wen i switching:

but my leds are initially ON wen i run my python script

Does your python script print anything out? It should at least print the Topic and payload message in on_message.

i get only this wen i switching: Connected with rc: 5, should i change permission on the file: /home/pi/mqtt_led_client.py ?

and on cloudmqtt:

read and wright are enable

The file is running, so there is no need to change file permissions for the moment. You may need to once we get the message from cloudmqtt, because I don’t know if you need root permission to access the GPIO pins.

Leaving read and write enabled on the broker is fine for now, but you may want to tighten it up once it is working.

At the moment I’m puzzled as to why the broker is not passing on the message, as it obviously has received it, and it looks like the subscription is ok.

Wat i find strange is that on first line get always this message ‘green/off’ on the mqttcould console:

I’m not sure where this is coming from. Is something else publishing to this topic from your yaml file?

I have looked more closely at your connect message, and rc: 5 indicates

Connection refused - not authorised 

So you have to include a username and password in your python script to connect to mqtt. I haven’t used paho, but looking through the documentation, I think you just need to do

client.username_pw_set(username, password)

after on_message and before client.connect(…)

have this error wen running the script:

  Traceback (most recent call last):
      File "/home/pi/mqtt_led_client.py", line 35, in <module>
        client.username_pw_set(rsbpi, rspbi)
    NameError: name 'rsbpi' is not defined

i passed line like you said

The username and password are strings and need to be in quotes. The way you have referred to them they are seen as variables, which it can’t find the definition of.

client.username_pw_set("yournamehere", "yourpassword")

I have just been doing some testing and the username and password you need are defined on the cloudmqtt overview page.

Great it works, gpbenton you are the best thank you!!!
thank you for you time!!!

Happy to help :slight_smile: