#!/usr/bin/python3
# -*- coding: UTF8 -*-

# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <https://www.gnu.org/licenses/>.

"""
Transmit data from UART (GPIO) to MQTT broker
"""
__version__ = "0.2"

###########
# Imports #
###########
import serial
import json
import pprint
import paho.mqtt.publish as mqtt
from cameteo_conf import *

########
# Main #
########

# Serial : UART settings
uart_name = "/dev/ttyAMA0"  # ttyAMA0 = UART on GPIO
uart_baud_rate = 115200

# MQTT settings
mqtt_client_id = "uart"
mqtt_topic = "feather0"

with serial.Serial(uart_name, uart_baud_rate, timeout=2) as uart:
    print(uart.name)

    while True:
        line = uart.readline()
        if line != b'':
            # If the line is not empty, it's data and they should be formatted as
            # compact JSON as bytes. Lets decode and load everything !
            try:
                data = json.loads(line.decode('utf8'))
                reception_date = datetime.utcnow().strftime("%Y/%m/%d %H:%M:%S")
                #print("{} :\n{}".format(reception_date, data))

                # Formatting data for sending to MQTT broker (one source at a time)
                for s in data.items():
                    for d in s[1].items():
                        payload = json.dumps({"date":  reception_date,
                                              "value": d[1],
                                              "unit":  data_unit[d[0]],
                                              "type":  data_type[d[0]]})
                        print(payload)
                        mqtt.single("{}/{}".format(mqtt_topic, s[0]),
                                    payload=    payload             ,
                                    qos=        2                   ,
                                    retain=     True                ,
                                    hostname=   mqtt_host           ,
                                    port=       mqtt_port           ,
                                    client_id=  mqtt_client_id      ,
                                    auth=       mqtt_auth           )
            except:
                print("Bad data:\n{}".format(line))
