#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import paho.mqtt.client as mqtt
import gpiozero

debug = True

HOST = "192.168.1.200"
PORT = 1883
    
GPIO_LED = 13
GROUP_ID = 'A'

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.
    
    client.subscribe(
            [
                ( f"tutorial/{GROUP_ID}/LED", 0), 
            ]
    )


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) )
    
    """
       The message payload is a 'binary blob'. To compare with Strings, it is needed to decoded.
       Best practice is to define a robust error handling with errors='ignore' or catch Exceptions.
    """
    payload = msg.payload.decode('ascii', errors='ignore') 
    
    if payload in [ 'ON', '1', 'AN']:
        led.on()
    elif payload in [ 'OFF', '0', 'AUS']:
        led.off()
    else:
        print( f"Error, can't decode {payload}") 


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()
client.loop_stop()
print("finished")
