# Affichage de données arrivant sur un MQTT
# sur un écran ePaper
# Auteur : Arofarn
# v0.1

#################
# Configuration #
#################



###########
# IMPORTS #
###########

from cameteo import *
import paho.mqtt.client as mqtt
from spidev import SpiDev
import EPD_driver
import json
import netifaces

#############
# CALLBACKS #
#############

#Callback pour la connection au MQTT : souscriptions aux topics
def on_connect(client, userdata, flags, rc):
    print(mqtt.connack_string(rc))
    if rc == 0:
        print("Subscribing to %s ..." % mqtt_topic)
        client.subscribe(mqtt_topic)
        print("OK")
    

#Callback de gestion des messages arrivant au MQTT :
#  affichage et enregistrement en base de données
def on_message(client, userdata, msg):
    top=msg.topic[len(mqtt_topic)-1:].strip()

    subtopics = top.split("/")
    payload = msg.payload.decode()
    print(payload)
    val = json.loads(payload)
        
    #Test présence et cohérence de la valeur        
    try:
        val['value'] = float(val['value'] )
    except:
        print("Value error: {}".format(val['value']))
        val['value'] = float('nan')
    
    #Gestion du symbole des degrés parfois difficile pour certaines sources
    #val['unit'] = val['unit'].replace('deg', '°')
    
    #Affichage des données
    coord_type = { 'TA' : 33,
                   'HR' : 49,
                   'PA' : 65
                   }
                   
    disp.Dis_String(110, coord_type[val['type']], "{} {}  ".format(val['value'], val['unit']), 16)
        
#Callback particulier pour gérer les date/heure arrivent sur le broker MQTT
def on_message_date(client, userdata, msg):
    payload = msg.payload.decode()
    #try:
    d = datetime.strptime(payload, "%H:%M:%S %d/%m/%Y")
    disp.Dis_String(0, 17, d.strftime("%d/%m/%Y %H:%M:%S"), 16)
    #except:
    #    print("Date mal formatée : %s" % payload)
    
#Callback de déconnexion au broker MQTT
def on_disconnect(client, userdata, msg):
    if msg != 0:
        print("Déconnexion imprévu : %s" % msg)
    exit()
    
########
# Main #
########

#init and Clear full screen
bus = 0 
device = 0
disp = EPD_driver.EPD_driver(spi=SpiDev(bus, device))

print("Start display...")
disp.Dis_Clear_full()
disp.Dis_Clear_part()
print("OK")

#disp.Dis_String(0, 0, "{} | {}".format(socket.gethostname(), netifaces.ifaddresses('wlan0')[2][0]['addr']), 12)
disp.Dis_String(0, 0,  "IPv4        : {}".format(netifaces.ifaddresses('wlan0')[2][0]['addr']), 16)
disp.Dis_String(0, 33, "Temperature : ", 16)
disp.Dis_String(0, 49, "Humidity    : ", 16)
disp.Dis_String(0, 65, "Pression    : ", 16)

#Connect to MQTT broker and loop...
mqtt_client = mqtt.Client(mqtt_client_id, clean_session=False)
mqtt_client.username_pw_set(mqtt_user, mqtt_pass)
mqtt_client.on_connect = on_connect
mqtt_client.on_message = on_message
mqtt_client.on_disconnect = on_disconnect

mqtt_client.message_callback_add("huzzah0/NTP/date", on_message_date)

print(mqtt_host + ":" + str(mqtt_port))
mqtt_client.connect(mqtt_host, int(mqtt_port), 60)

mqtt_client.loop_forever()

