/*
 * drv8350.cpp
 * win cp1251 ru
 *
 *  Created on: 7/03/2019.
 *      Author: Lityagin Aleksandr
 *              alexrayne <alexraynepe196@gmail.com>
  ------------------------------------------------------------------------
    Copyright (c) alexrayne

   All rights reserved.
   Redistribution and use in source and binary forms, with or without
   modification, are permitted provided that the following conditions are met:
   - Redistributions of source code must retain the above copyright
     notice, this list of conditions and the following disclaimer.
   - Redistributions in binary form must reproduce the above copyright
     notice, this list of conditions and the following disclaimer in the
     documentation and/or other materials provided with the distribution.
   - Neither the name of ARM nor the names of its contributors may be used
     to endorse or promote products derived from this software without
     specific prior written permission.
   *
   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
   AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
   IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
   ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
   LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
   CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
   SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
   CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
   ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
   POSSIBILITY OF SUCH DAMAGE. *
 *------------------------------------------------------------------------------------------
 * драйвер 3фазного контроллера вентилей для BLDC двигателя.
 * \sa http://www.ti.com/lit/ds/symlink/drv8350r.pdf
 * контроллер сидит на общей SPI шине, и выбирает свой узел селектором
 */

#include "drv8350_device.hpp"
#include <gpio.h>
#include <mcu_system.h>

#include <trace_probes.h>
#ifndef trace_drv8350_spi
trace_need(drv8350_spi)
#endif



DRV8350_Device::DRV8350_Device()
: inherited()
, enable_pin(NULL)
, fault_pin(NULL)
, mode_cache(0)
, access_timeout(0)
, last_access_tick(0)
{
    Power_Manager::state = HALT;
}

DevResult DRV8350_Device::init( const INIT* x , int csid){
    connect(x->port);
    enable_pin = &x->enable_pin;
    gpio_conf_out(enable_pin);
    gpio_off(enable_pin);
    fault_pin = &x->fault_pin;
    gpio_conf_out(fault_pin);
    gpio_off(fault_pin);
    cs(csid);

    // timeout 0.5us
    // must be at least DRV8350::WORDS_TIMEOUT_NS
    access_timeout = (SystemCoreClock>>20)/2;

    regs_setup.reset();

    setPower(SLEEP);

    return DEV_OK;
}

DRV8350_Device::IOResult DRV8350_Device::write_reg(REG_ADDRid rid, unsigned x){
    TRACE_GUARD(body, drv8350_spi);

    msg_assign_buf(1);
    ssp_buf16[0]= reg_t::as_wr(rid, x);
    reg_timeout();
    IOResult ok = msg_trx();
    last_access_tick = clock_systick();
    if (ok < 0)
        return ok;
    return reg_t::DATAof( ssp_buf16[0]) ;
}

DRV8350_Device::IOResult DRV8350_Device::read_reg(REG_ADDRid rid) {
    TRACE_GUARD(body, drv8350_spi);

    msg_assign_buf(1);
    ssp_buf16[0]= reg_t::as_rd(rid, 0);
    reg_timeout();
    IOResult ok = msg_trx();
    last_access_tick = clock_systick();
    if (ok < 0)
        return ok;
    if (ssp_buf16[0] == 0xffff){
        return -1;
    }
    return reg_t::DATAof( ssp_buf16[0]) ;
};

void DRV8350_Device::reg_timeout(){
    unsigned now = clock_systick();
    long passed = (now - last_access_tick);
    if ( passed < access_timeout){
        clock_delay_systick( access_timeout - passed );
    }
}

void DRV8350_Device::mode(mode_t m){
    regs_setup.ctrl.raw = regs_setup.ctrl.as_wr(m);
    regs_setup.ocp.set_fields(modeOCP_Msk, m >>16);

    if (!is_enabled())
        return;

    IOResult ok = write_reg( DRV8350::adrDRIVE_CTRL, m);
    if (ok >= 0){
        ok = write_reg( DRV8350::adrOCP_CTRL, regs_setup.ocp.raw);
        mode_cache = m;
    }
};

void DRV8350_Device::mode_cache_refresh(){
    mode_cache = regs_setup.ctrl.field.data
               | (regs_setup.ocp.field.data << 16)
               ;
}

void DRV8350_Device::mode_ocp(mode_ocp_t m){
    regs_setup.ocp.set_fields(ocpMode_Msk, m);
    regs_setup.gatel.set_fields(regs_setup.gatel.CBC
                            , (m & ocpCBC)? regs_setup.gatel.CBC : 0
                            );

    if (!is_enabled())
        return;
    IOResult ok;
    ok = write_reg( DRV8350::adrOCP_CTRL, regs_setup.ocp.raw);
    ok = write_reg( DRV8350::adrGATEL, regs_setup.gatel.raw);
    (void)ok;
    mode_cache_refresh();
}

void DRV8350_Device::mode_gate_strong(ISink_ID isink, ISour_ID isour){
    const unsigned msk = (int)DRV8350::ISink_Msk | (int)DRV8350::ISour_Msk;
    const unsigned imode = ((int)isink | (int)isour);
    regs_setup.gatel.set_fields( msk, imode);
    regs_setup.gateh.set_fields( msk, imode);

    if (!is_enabled())
        return;
    IOResult ok;
    ok = write_reg( DRV8350::adrGATEH, regs_setup.gateh.raw);
    ok = write_reg( DRV8350::adrGATEL, regs_setup.gatel.raw);
    (void)ok;
}

void DRV8350_Device::mode_ocp_level(OCP_VDSLevel vds, mode_ocp_sence_level_t sen){
    unsigned msk = (int)DRV8350::regCSA_CTRL::SEN_Lvl_Ocp_Msk
                | (int)ocpSEN_DISABLE
                ;
    regs_setup.csa.set_fields( msk, sen);
    regs_setup.ocp.set_fields( DRV8350::regOCP_CTRL::VDS_Level_Msk, vds);

    if (!is_enabled())
        return;
    IOResult ok;
    ok = write_reg( DRV8350::adrOCP_CTRL, regs_setup.ocp.raw);
    ok = write_reg( DRV8350::adrCSA_CTRL, regs_setup.csa.raw);
    (void)ok;
    mode_cache_refresh();
}

void DRV8350_Device::mode_isen_gain(GainID x){
    regs_setup.csa.set_fields( DRV8350::regCSA_CTRL::Gain_Msk, x);

    if (!is_enabled())
        return;
    IOResult ok;
    ok = write_reg( DRV8350::adrCSA_CTRL, regs_setup.csa.raw);
    (void)ok;
}

// write all config registers from regs_setup
void DRV8350_Device::reinit(){
    if (enabled())
    for (int adr = regs_setup.adrCFG; adr < regs_setup.adrLIMIT ; adr++){
        write_reg( (REG_ADDRid)adr, regs_setup.regs[adr].raw );
    }
    mode_cache_refresh();
}

DRV8350_Device::mode_t DRV8350_Device::mode(){
    if (!is_enabled()){
        mode_cache = DRV8350::regDRIVE_CTRL::defaults;
        return mode_cache;
    }

    mode_cache = read_reg( DRV8350::adrDRIVE_CTRL);
    mode_cache |= (read_reg( DRV8350::adrOCP_CTRL) & modeOCP_Msk) << 16;
    return mode_cache;
}

void DRV8350_Device::fault_clear(){
    if (!is_enabled()) {
        last_status.raw = 0;
        return;
    }

    write_reg( DRV8350::adrDRIVE_CTRL, mode_cache
             | DRV8350::regDRIVE_CTRL::CLR_FLT
             );
}

DRV8350_Device::status_t DRV8350_Device::status(){
    status_t& res = last_status;

    if (!is_enabled()){
        res.raw = -1;
        return res;
    }

    IOResult ok = read_reg(DRV8350::adrFAULT_STAT);
    if (ok < 0){
        res.raw = -1;
        return res;
    }
    res.faults.raw = ok;

    // between words need DRV8350::WORDS_TIMEOUT_NS
    clock_delay_usec(1);

    ok = read_reg(DRV8350::adrVGS_STAT);
    if (ok < 0){
        res.raw = -1;
        return res;
    }
    res.vgs.raw = ok;
    return res;
}


// pulse ENABLE for reset device
void DRV8350_Device::reset(){
    if (Power_Manager::state > WORK)
        return;
    if (!is_enabled())
        return;

    enable_gates(false);
    __NOP();
    __NOP();
    __NOP();
    __NOP();
    enable_gates(true);
}

//virtual
int DRV8350_Device::setPower(POWER_STATE state){
    enable(state <= WORK);
    Power_Manager::state = state;
    return DEV_OK;
}

void DRV8350_Device::enable( bool onoff){
    if (onoff){
        Power_Manager::state = WORK;
        enable_gates(true);
    }
    else {
        if (Power_Manager::state < SLEEP)
            Power_Manager::state = SLEEP;
        enable_gates(false);
        last_status.raw = 0;
    }
}

// \return true - if gateh.locked field in LOCK state
bool DRV8350_Device::is_locked(void){
    if (!is_enabled())
        return false;

    DRV8350::regGATEH gateh;
    gateh.raw = read_reg(gateh.REG_ADDR);
    return gateh.is_locked();
}

void DRV8350_Device::lock_registers(bool onoff){
    DRV8350::regGATEH gateh;
    gateh.raw = read_reg(gateh.REG_ADDR);
    write_reg(gateh.REG_ADDR, gateh.as_locked(onoff));
}

// вкл/выкл режимеа торможения - все нижние вентили вкл и коротят обмотки
bool DRV8350_Device::brake(bool onoff){
    if (!is_enabled())
        return false;

    unsigned m = mode();
    bool is_brake_on = ( (m & DRV8350::regDRIVE_CTRL::BRAKE) != 0 );
    if ( is_brake_on == onoff)
        return true;

    if (onoff)
        m |=  DRV8350::regDRIVE_CTRL::BRAKE;
    else
        m &= ~ DRV8350::regDRIVE_CTRL::BRAKE;

    IOResult ok = write_reg( DRV8350::adrDRIVE_CTRL, m);
    if (ok >= 0){
        mode_cache = m;
    }
    return ok > 0;
}

bool DRV8350_Device::is_brake(){
    if (!is_enabled())
        return false;
    //mode()
    return (mode_cache & DRV8350::regDRIVE_CTRL::BRAKE) != 0;
}




//----------------------------------------------------------------------
//                      CLI

DRV8350_CLI::DRV8350_CLI(const_cmd name,  DRV8350_Device& target )
: inherited(name)
, CLICommand(name)  //virtual base class
,io(&target)
{};

//virtual
void DRV8350_CLI::cli_onoff(bool onoff){
    io->setPower( (onoff)? io->WORK : io->SLEEP );
}

//virtual
void DRV8350_CLI::cli_brake_onoff(CLI_shell* shell, bool onoff){
    bool ok = io->brake(onoff);
    shell->printf("%s: brake on%d ->ok%d", cmd_name, onoff, ok);
}



using namespace cli;

//CLICommand
//virtual
int DRV8350_CLI::cli_process(CLI_shell* shell, const_line cmd){
    int res = cli::CLI_OnOffCommand::cli_process(shell, cmd);
    if (res > 0)
        return res;

    const_line line = after_cmd(cmd);
    if (line == NULL)
        return 0;

    static const char* functions[] = {
        "show", "reset", "clear", "init"
        , "lock", "unlock"
        , "set"
        , "help", "?"
        , "brake"
        , NULL
    };

    while (cli::is_no_eol(line) ) {

    int fi = cli::mutch_names(line, &line, functions);
    switch (fi){
        case 0:
            res = cli_process_show(shell, line);
            if (res <= 0)
                return res;
            line += res;
            break;

        case 1: //reset
            io->reset();
            break;

        case 2: //clear
            io->fault_clear();
            cli_show_stat(shell);
            break;

        case 3: //init
            io->reinit();
            break;

        case 4: //lock
            io->lock_registers(true);
            break;

        case 5: //unlock
            io->lock_registers(false);
            break;

        case 6: //set
            res = cli_process_set(shell, line);
            if (res <= 0)
                return res;
            line += res;
            break;

        case 7: //help
        case 8: //?
            cli_help(shell);
            break;

        case 9: {//brake
            fi = cli::mutch_onoff(line, &line);
            if (fi == 0)
                cli_brake_onoff(shell, false);
            else if (fi == 1)
                cli_brake_onoff(shell, true);
            else {
                shell->on_fail(line);
            }
            break;
        }

        default:
            shell->on_fail(line);
            return line - cmd;
    };//switch(

    }; // while()

    return line - cmd;
}

int DRV8350_CLI::cli_process_show(CLI_shell* shell, const_line cmd){
    const_line line = cmd;

    static const char* functions[] = {
        "all", "status", "stat", "r", NULL
    };
    int fi = cli::mutch_names(line, &line, functions);
    if (fi < 0){
      line += cli::space_len(line, ~0);
        if (is_eol(line))
            fi = 0;
    }
    switch (fi){
        case 0: { //all
            enum { adr_max = DRV8350::adrTOTAL };
            for (int adr = 0; adr < adr_max; adr++ ){
                unsigned x = io->read_reg((addr_id)adr);
                shell->printf("reg%x:$%x\n", adr, x);
            }
            break;
        }

        case 1: // status
        case 2: {// stat
            cli_show_stat(shell);
            break;
        }

        case 3: {//r
            line += cli::space_len(line, ~0);

            long adr = 0;
            line = pass_number(adr, line);
            if (line == NULL){
                return 0;
            }

            unsigned x = io->read_reg((addr_id)adr);
            shell->printf("reg%x:$%x\n", adr, x);
            break;
        }

        default:
            shell->on_fail(line);
            break;
    }
    return line - cmd;
}

void DRV8350_CLI::cli_show_stat(CLI_shell* shell){
    io_t::status_t x = io->status();
    shell->printf("status faults:$%x vgs:$%x\n"
            , x.faults.raw, x.vgs.raw);
}


int DRV8350_CLI::cli_process_set(CLI_shell* shell, const_line cmd){
    const_line line = cmd;

    static const char* functions[] = {
        "r"
        , "strong"
        , NULL
    };
    int fi = cli::mutch_names(line, &line, functions);
    if (fi < 0){
      line += cli::space_len(line, ~0);
        if (is_eol(line))
            fi = 0;
    }
    switch (fi){
        case 0: {//r
            line += cli::space_len(line, ~0);

            long adr = 0;
            line = pass_number(adr, line);
            if (line == NULL)
                return 0;

            if (*line++ != '='){
                shell->on_fail(line);
                return line - cmd;
            }

            long x = 0;
            line = pass_number(x, line);
            if (line == NULL)
                return 0;

            io->write_reg((addr_id)adr, x);

            x = io->read_reg((addr_id)adr);
            shell->printf("reg%x:$%x\n", adr, x);
            break;
        }

        case 1: {//strong
            long isink;
            long isour;
            line = pass_number('=', isink, ',', isour, line);
            if (line == NULL){
                return 0;
            }
            io->mode_gate_strong(
                    (io_t::ISink_ID)(isink<< DRV8350::ISink_Pos)
                    , (io_t::ISour_ID)(isour<< DRV8350::ISour_Pos)
                    );
            break;
        }

        default:
            shell->on_fail(line);
            break;
    }
    return line - cmd;

}


//* печатает хелп команды в шелл
//virtual
void DRV8350_CLI::cli_help(CLI_shell* shell){
    shell->printf( "%s - gate driver control:\n", cmd_name );
    cli::CLI_OnOffCommand::cli_help(shell);
    shell->puts("\tshow <all|stat|status|r idx> - dump all regs\n"
                "\t\t all - \tdump all regs\n"
                "\t\t stat[us] - \tdump status regs\n"
                "\t\t r <idx> - \tdump reg <idx>\n"
                "\treset - \treset driver\n"
                "\tclear - \tclear faults\n"
                "\tlock  - \tlock driver registers\n"
                "\tunlock- \tunlock driver registers\n"
                "\tset <r idx=value> - set reg value\n"
                "\t\t  <strong =<gatel>,<gateh> > - set Isink, ISour strength\n"
                "\thelp|?   - this help\n"
                );
}

