MQTT Support

MQTT allows AndyMOTE to publish it's current activity state to other systems (for example Home Assistant). Andymote requires that the AndyMOTE Server has a MQTT Broker such as Mosquitto installed.

With the AndyMOTE Server properly configured, AndyMOTE will publish the current activity state to the the AndyMOTE Server MQTT Broker. For example if AndyMOTE has an Activity called Watch BluRay and this is activated; AndyMOTE will publish status of andymote = Watch BluRay to the MQTT Broker. If no activities are running then the published status will be set to Off.

Application Note

This application note describes the use of MQTT to switch on a Raspberry Pi when AndyMOTE publishes it's current activity as andymote = Watch Kodi to the MQTT Broker.

Concept

  • AndyMOTE publishes status of andymote = Watch BluRay
  • Python Script (running on AndyMOTE Server) detects this and triggers relay for 1 second

Circuit Diagram

The Circuit Diagram shows the hardware setup for this application. The AndyMOTE Server provides power to a Relay Module via a Micro USB to DIP Adapter and controls the operation of Relay 1 (on the Relay Module) through pin 36 (GPIO 16). Relay 2 is unused.

The Relay 1, normally open (NO) contacts, are connected to Pins 5 & 6 of the Kodi Device (eg RaspberryPi 4). Pins 5 & 6 of a Raspberry Pi, when connected together, cause the device to switch on.

Circuit Diagram

Python Script

Requires

  • Python 3
  • paho-mqtt
  • Rpi.GPIO
#!/usr/bin/env python3
import time
import paho.mqtt.client as mqtt
import RPi.GPIO as GPIO

Broker = "192.168.1.110"

sub_topic = "andymote"    # receive messages on this topic

# when kodi needs switching on do this;
def on_kodi():
    GPIO.setmode(GPIO.BCM)
    GPIO.setwarnings(False)
    GPIO.setup(16,GPIO.OUT)
    print ("Relay on")
    GPIO.output(16,GPIO.LOW)
    time.sleep(1)
    print ("Relay off")
    GPIO.output(16,GPIO.HIGH)

# when connecting to mqtt do this;
def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+str(rc))
    client.subscribe(sub_topic)

# when receiving a mqtt message do this;
def on_message(client, userdata, msg):
    message = str(msg.payload)
    print("AndyMote Status: "+message)
    if (message == "b'Watch Kodi'"):
      on_kodi()

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(Broker, 1883, 60)

try:
 client.loop_forever()
 except KeyboardInterrupt:
 print("Keyboard Interrupt: Program Closed")

Run as a Service

create the file /lib/systemd/system/mqttRelay.service with content as shown below:

[Unit]
Description=run mqttRelay as a service

[Service]
Type=simple
RemainAfterExit=false
Restart=always
RestartSec=30
ExecStop=/bin/true
ExecStart=/home/pi/relayProject/mqttRelay.py

[Install]
WantedBy=multi-user.target

To enable the service:

$ sudo systemctl unmask mqttRelay
$ sudo systemctl enable mqttRelay
$ sudo systemctl start mqttRelay