I have two Raspberry Pi’s one running HA and mosquitto broker and the other running python script using flask mqtt. I cannot get the HA switch to work, it toggle on then back off a second later. I am missing something on setting up MQTT properly. Here is my configuration.yaml and my phyton script. Nothing is getting logged in my log file so I don’t think the commands are making it to my remote Pi. Any help would be appreciated. Thank you.
Switch
switch:
- platform: rpi_gpio
ports:
11: LED Blue
12: LED White
- platform: mqtt
unique_id: remote_led_switch
name: Remote LED
command_topic: "toggle/LED"
state_topic: "state/LED"
payload_on: "on"
payload_off: "off"
state_on: "1"
state_off: "0"
optimistic: false
qos: 0
retain: true
Python Script
from flask import Flask, request, jsonify
import RPi.GPIO as GPIO
from flask_mqtt import Mqtt
import time
#from w1thermsensor import W1ThermSensor
import logging
#from apscheduler.schedulers.background import BackgroundScheduler
app = Flask(__name__)
logging.basicConfig(filename='/home/pi/web/log/Frosty_app.log', level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s' ,
datefmt='%d-%m-%Y %H:%M:%S')
# Setup MQTT broker connection
app.config['MQTT_BROKER_URL'] = '192.168.10.10'
app.config['MQTT_BROKER_PORT'] = 1883
app.config['MQTT_USERNAME'] = 'homeassistant'
app.config['MQTT_PASSWORD'] = 'Password'
app.config['MQTT_REFRESH_TIME'] = 1.0 # refresh time in seconds
mqtt = Mqtt(app)
logging.info("MQTT - Connected to Broker")
#@app.route('/')
#def index():
# return render_template('index.html')
# Define the GPIO ports that each channel will use.
LED = 4
#Inital set all MQTT to off
mqtt.publish('state/LED', 0)
# Setup each of the GPIO Ports
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(LED, GPIO.OUT, initial=0)
#scheduler = BackgroundScheduler()
#scheduler.add_job(func=mqtt_sensor_publish, trigger="interval", seconds=temp_sched)
#scheduler.start()
# ######################## MQTT ##########################
mqtt.subscribe('toggle/LED')
@mqtt.on_topic('toggle/LED')
def handle_mytopic(client, userdata, message):
with app.app_context():
status=int(GPIO.input(LED))
if status == 1 and message.payload.decode() == "off":
GPIO.output(LED, GPIO.LOW)
verify_state = GPIO.input(LED)
mqtt.publish('state/LED', verify_state)
logging.info("MQTT - LED turned off")
elif status== 0 and message.payload.decode() == "on":
GPIO.output(LED, GPIO.HIGH)
verify_state = GPIO.input(LED)
mqtt.publish('state/LED', verify_state)
logging.info("MQTT - LED turned on")
else:
logging.info("MQTT - LED - Nah Bruh")
# -- status/update is used when Home assistant restarts.
# -- It re-publishes the current state of all channels and temperature probes
mqtt.subscribe('status/update')
@mqtt.on_topic('status/update')
def handle_mytopic(client, userdata, message):
with app.app_context():
LED_status=int(GPIO.input(LED))
mqtt.publish('state/LED', LED_status)
logging.info("MQTT Updated state info")