#!/usr/bin/env python3
#-*- coding: utf-8 -*-

import paho.mqtt.client as mqtt

debug = True

HOST = "192.168.1.200"
HOST = "mqttserver"
PORT = 1883
    

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.
    
    rc = client.subscribe(
            [
                ("tutorial/A/LED", 1), 
            ]
    )
    if debug: print("Subscription performed")
    

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
    """
    payload = msg.payload.decode('ascii', errors='ignore') 
    
    # process payload    
    if payload in ['ON', '1']:
        print("received ON")
        
    elif payload in ['OFF', '0']:
        print("received OFF")
 
    else:
        print( f"received '{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")
