# -*- coding: utf-8 -*-

"""
author  Benoit Dubois
licence GPL v3+
brief   Main file of PWM controller (VNH5019 device).
"""
import pyb
import ujson
import serial_com as sc
import vnh5019

# Avoid use of timer 2, 3, 5 and 6
# see http://docs.micropython.org/en/latest/pyboard/library/pyb.Timer.html
TIMER_PWM_ID = 4

TIMER_PWM_FREQ = 1000

TIMER_PWM1_CH = 1
TIMER_PWM2_CH = 2

PIN_INA1 = 'PD5'
PIN_INB1 = 'PD6'
PIN_INA2 = 'PD1'
PIN_INB2 = 'PD2'
PIN_PWM1 = 'PB6'
PIN_PWM2 = 'PB7'


#----------------------------------------------------------
class MySerialCom(sc.SerialCom):

    MNEMO_LIST = ["value"]

    def decode_message(self, msg):
        """Message can be of type request or command.
        Request message are made of a mnemonique followed by '?'.
        Command message are made of 2 parts:
        - a mnemonique,
        - the value to be applied.
        Each parts are separated with a space.
        """
        if msg[:-1] == '?': # Request
            return
        else:
            cmd = msg.split()
            if len(cmd) != 3:
                print("Decode error: bad command format")
                return
            mnemo = str(cmd[0])
            if mnemo not in self.MNEMO_LIST:
                print("Decode error: bad mnemonique")
                return
            num = int(cmd[1])
            if num != 0 and num != 1:
                print("Decode error: bad controller number")
                return
            try:
                val = int(cmd[2])
            except ValueError:
                print("Decode error: bad command value")
                return
            return (mnemo, num, val)


#----------------------------------------------------------
class PwmHandler(object):

    def __init__(self, config_filename):
        self.scom = MySerialCom()
        vnh0 = vnh5019.Vnh5019(in_a=PIN_INA1, in_b=PIN_INB1, pwm=PIN_PWM1,
                               timer=TIMER_PWM_ID, freq=TIMER_PWM_FREQ,
                               ch=TIMER_PWM1_CH)
        vnh1 = vnh5019.Vnh5019(in_a=PIN_INA2, in_b=PIN_INB2, pwm=PIN_PWM2,
                               timer=TIMER_PWM_ID, freq=TIMER_PWM_FREQ,
                               ch=TIMER_PWM2_CH)
        self.pwm = [vnh0, vnh1]
        with open(config_filename, 'r') as f:
            config = ujson.loads(f.read())
        self.pwm[0].set_pwm_percent(config['val0'])
        self.pwm[1].set_pwm_percent(config['val1'])

    def apply_cmd(self, cmd):
        if len(cmd) == 1: # Request
            pass
        else:
            if cmd[0] == "value":
                self.pwm[cmd[1]].set_pwm_percent(cmd[2])

    def run(self):
        while True:
            self.scom.poller.poll(250)
            if self.scom.vcom.any():
                msg = self.scom.read_message()
                if msg is not None:
                    cmd = self.scom.decode_message(msg)
                    if cmd is not None:
                        #print("pwm_handler.run.cmd:", cmd)
                        self.apply_cmd(cmd)
                        self.scom.write_message(msg)


#----------------------------------------------------------
if __name__=='__main__':
    my_pwm = PwmHandler(config_filename='config.json')
    my_pwm.run()
