#!/usr/bin/env python3
#-*- coding: utf-8 -*-

""" sample program to switch a LED when two topic report 'ON' """

import paho.mqtt.client as mqtt
import gpiozero

debug = True

HOST = "192.168.1.200"
HOST = "mqttserver"
PORT = 1883
   
GPIO_LED = 13

#
# GroupID are defined here, change to whatever is needed
#

GROUP_ID_0 = 'A'
GROUP_ID_1 = 'B'

topics_button = [ 
            f"tutorial/{GROUP_ID_0}/BUTTON", 
            f"tutorial/{GROUP_ID_1}/BUTTON",
          ]
topic_powerswitch = "cmnd/delock/1807/POWER"

led = gpiozero.LED(GPIO_LED)

def on_connect(client, userdata, flags, rc):
    if debug:
        print("Connected with result code "+str(rc))

    # Subscribing in on_connect() means that if we lose the connection and
    # reconnect then subscriptions will be renewed.
    
    """ convert 'topics' to a list with qos added
             [
                ("tutorial/A/BUTTON", 0),  << 0 == QOS 
                ("tutorial/B/BUTTON", 0),
            ]
            """
    subscribe_list = []
    QOS = 0
    
    for topic in topics_button:
        subscribe_list.append( [topic, QOS,] )
        
    if debug:
        print("subscribe_list", subscribe_list)
        
    client.subscribe( subscribe_list )

        
cache = dict()


def on_message(client, userdata, msg):
    """The callback for when a PUBLISH message is received from the server."""
    
    if debug:
        print(msg.topic, str(msg.payload), "retain", msg.retain, "qos", msg.qos, str(userdata) )
    
    payload = msg.payload.decode('ascii', errors='ignore')
    #
    # use a dictionary to collect recent values
    #
    cache[msg.topic] = payload

    #
    # are all needed topics in cache ?     
    #
    missing = False
    for topic in topics_button:
        if not( topic in cache):
            missing = True
    if missing:
        if debug:
            print("Not all topics are yet available")
           
        client.publish(topic_powerswitch, "OFF")
        led.off()
        return
    
    on = True
    for topic in topics_button:
        if cache[topic] != 'ON':
            on = False
            break
    
    if on:
        client.publish(topic_powerswitch, "ON")
        led.on()
    else:
        client.publish(topic_powerswitch, "OFF")
        led.off()
        

client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message

client.connect(HOST, PORT, keepalive=60)

# Blocking call that processes network traffic, dispatches callbacks and
# handles reconnecting.
# Other loop*() functions are available that give a threaded interface and a
# manual interface.
try:
    client.loop_forever()
except KeyboardInterrupt:
    pass

client.disconnect()
