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

"""
author  Baptiste Marechal
brief   Driver for VNH5019 H bridge motor driver device.
"""
import pyb


class Vnh5019(object):
    """Handle the VNH5019 motor driver.
    """

    def __init__(self, in_a, in_b, pwm, timer, freq, ch):
        self.in_a = pyb.Pin(in_a, pyb.Pin.OUT_PP)
        self.in_b = pyb.Pin(in_b, pyb.Pin.OUT_PP)
        self.pwm = pyb.Timer(timer, freq=freq).channel(ch,
                                                       pyb.Timer.PWM,
                                                       pin=pyb.Pin(pwm))
        self.set_pwm(0)

    def set_pwm_percent(self, value=0):
        if value >= 0:
            self.set_dir(1)
            self.pwm.pulse_width_percent(value)
        else:
            self.set_dir(-1)
            self.pwm.pulse_width_percent(-value)

    def set_pwm(self, value=0):
        if value >= 0:
            self.set_dir(1)
            self.pwm.pulse_width(value)
        else:
            self.set_dir(-1)
            self.pwm.pulse_width(-value)

    def set_dir(self, val=1):
        if val == 1:
            self.in_a.low()
            self.in_b.high()
        elif val == -1:
            self.in_a.high()
            self.in_b.low()

    def write(self, value):
        self.set_pwm_percent(value / 320)
