--[[
  Copyright (c) 2021-2022 by Plexim GmbH
  All rights reserved.

  A free license is granted to anyone to use this software for any legal
  non safety-critical purpose, including commercial applications, provided
  that:
  1) IT IS NOT USED TO DIRECTLY OR INDIRECTLY COMPETE WITH PLEXIM, and
  2) THIS COPYRIGHT NOTICE IS PRESERVED in its entirety.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  SOFTWARE.
--]]--
local T = require('targets.TI28')
local U = require('common.utils')
local P = require('resources.TI2838x_pin_map')
local PLL = require('utils.pll_config')

local TripInputsAllocated = {}
local GpioAllocated = {}

function T.getFamilyPrefix()
  return '2838x'
end

function T.getC2pConfig(c2pAdapter)
  return '28388,6,4-CPU1_JTAG %s' % {c2pAdapter}
end

function T.getOptions()
  -- these are the values corresponding to drop down menu selections 
  -- in Coder Options. The order must match info.xml file.
  return {
    ChipCombo = {'28388D'},
    boards = {'custom', 'controlcard'},
    uniFlashConfigs = {
      controlcard = 'ControlCard_TMS320F28388S.ccxml',
    },
    c2pConfigs = {
      controlcard = T.getC2pConfig('xds100v2'),
    },
    linkerFiles = {
      {'f2838x_FLASH_lnk_cpu1.cmd', 'f2838x_RAM_lnk_cpu1.cmd'},
      {'f2838x_FLASH_lnk_cpu2.cmd'},
    },
  }
end

function T.configure(resources)
  resources:add('ADC A')
  resources:add('ADC B')
  resources:add('ADC C')
  resources:add('ADC D')
  resources:add('ADCA-SOC', 0, 15)
  resources:add('ADCB-SOC', 0, 15)
  resources:add('ADCC-SOC', 0, 15)
  resources:add('ADCD-SOC', 0, 15)
  resources:add('Base Task Load')
  resources:add('Base Task Load CPU2')
  resources:add('CAN A')
  resources:add('CAN B')
  resources:add('CAP', 1, 7)
  resources:add('CMPSS', 1, 8)
  resources:add('CPU1TIMER', 0, 1)
  resources:add('CPU2TIMER', 0, 1)
  resources:add('DAC A')
  resources:add('DAC B')
  resources:add('DAC C')
  resources:add('EXTSYNC', 1, 2)
  resources:add('GPIO', 0, 199)
  resources:add('IPC_FLAG', 4, 30)  -- only flags without interrupt capability, flag 31 used for start-up sync
  resources:add('MCAN A')
  resources:add('Powerstage Control')
  resources:add('Powerstage Control CPU2')
  resources:add('PWM', 1, 16)
  resources:add('QEP', 1, 3)
  resources:add('SCI A')
  resources:add('SCI B')
  resources:add('SCI C')
  resources:add('SCI D')
  resources:add('SDFM 1', 1, 4)
  resources:add('SDFM 2', 1, 4)
  resources:add('SPI A')
  resources:add('SPI B')
  resources:add('XBAR_INPUT', 1, 16)
end

function T.validateAlternateFunction(fun)
  local settings = P.getPinSettings(fun)
  return settings ~= nil
end

function T.getTargetParameters()
  local params = {
    adcs = {
      peripheralType = 4,
      vrefConfigInterfaceType = 4,
      defaultVref = 3.0,
      num_channels = 16,
      vref_min = 2.4,
      vref_max = 3.3,      -- allowable range on external vref
      num_units = 4,       -- 4 ADCs with independent references
    },
    caps = {},
    cbc_trip_inputs = {8, 9, 10, 11, 12},
    clas = {
      type = 2,
    },
    comps = {
      positive = {
        A14 = 4,
        B14 = 4,
        C14 = 4,
        A2 = 1,
        A4 = 2,
        B2 = 3,
        C2 = 6,
        C4 = 5,
        D0 = 7,
        D2 = 8,
      },
    },
    cpu_timers = {0},
    dacs = {
      minOutputVoltage = 0.0,
      maxOutputVoltage = 3.3,       -- hardware upper voltage limit
      -- DAC A and B use vrefA
      -- DAC C uses vrefB
      vrefMap = {A = 'A', B = 'A', C = 'B'},
    },
    dcans = {
      type = 0,
    },
    epwms = {
      type = 4,
      max_event_period = 15,
      sync_group_size = 1,
      num_units = 16,
    },
    gpios = {
      openDrainSupported = true,
    },
    mcans = {
      type = 0,
    },
    qeps = {},
    scis = {
      num_units = 4,
    },
    sdfm = {
      num_units = 2,
    },
    spis = {
      type = 2, fifo_depth = 16,
    },
    trip_groups = {A = 4, B = 5, C = 7},
  }
  return params
end

function T.allocateGpio(gpio, properties, req, label)
  GpioAllocated[gpio] = properties
  req:add('GPIO', gpio, label)
end

function T.isGpioAllocated(gpio)
  return (GpioAllocated[gpio] ~= nil)
end

function T.getGpioProperties(gpio)
  return GpioAllocated[gpio]
end

function T.getNextAvailableTripInput()
  -- find next available trip input
  local availableInputs = T.getTargetParameters().cbc_trip_inputs
  for _, tin in ipairs(availableInputs) do
    if TripInputsAllocated[tin] == nil then
      TripInputsAllocated[tin] = true
      return tin
    end
  end
end

function T.getComparatorsForPin(pin)
  local comp = T.getTargetParameters().comps.positive[pin]
  if comp == nil then
    return nil
  end

  local compLowHigh = {
    unit = comp,
  }

  return {
    low = compLowHigh,
    high = compLowHigh,
  }
end

function T.checkGpioIsValidPwmSync(gpio)
  if gpio > 168 then
    U.error('Only GPIO from 0 to 168 can be selected as external synchronization source for this target.')
  end
end

function T.getPwmSyncInSel(params)
  local mux
  if params.type == 'external' then
    if params.source_unit == 1 then
      mux = 0x18
    elseif params.source_unit == 2 then
      mux = 0x19
    else
      U.error('Unsupported external sync unit (%d).' % {params.source_unit})
    end
  elseif params.type == 'epwm' then
    mux = params.source_unit
  else
    U.error('Unsupported sync type (%s).' % {params.type})
  end
  return mux
end

function T.getLowSpeedClock()
  return T.getCleanSysClkHz() / 4
end

function T.getPwmClock()
  -- TBCLOCK - CLKDIV=/1, HSPCLKDIV=/1
  return T.getCleanSysClkHz()
end

function T.getTimerClock()
  -- relevant clock for dispatcher
  return T.getPwmClock()
end

function T.getDeadTimeClock()
  -- TBCLOCK - CLKDIV=/1, HSPCLKDIV=/1
  return T.getPwmClock()
end

function T.getAdcClock()
  local sysClkHz = T.getCleanSysClkHz()
  if sysClkHz <= 50000000 then
    return sysClkHz
  elseif sysClkHz <= 75000000 then
    return sysClkHz / 1.5
  elseif sysClkHz <= 100000000 then
    return sysClkHz / 2
  elseif sysClkHz <= 120000000 then
    return sysClkHz / 2.5
  elseif sysClkHz <= 150000000 then
    return sysClkHz / 3.0
  elseif sysClkHz <= 175000000 then
    return sysClkHz / 3.5
  else
    return sysClkHz / 4
  end
end

function T.getCanClkAndMaxBrp()
  return T.getCleanSysClkHz(), 0x400
end

function T.calcACQPS(ts, sigmodeDifferential)
  local tsMin
  local acqpsMax = 511
  local acqpsMin = 0
  if sigmodeDifferential then
    tsMin = math.max(320e-9, 1 / T.getAdcClock())    -- per datasheet, differential
  else
    tsMin = math.max(75e-9, 1 / T.getAdcClock())     -- per datasheet, single ended
  end

  if (not U.isScalar(ts)) or (ts < tsMin) then
    ts = tsMin
  end
  local sysClkHz = T.getCleanSysClkHz()

  return U.clampNumber(math.ceil(ts * sysClkHz) - 1, {acqpsMin, acqpsMax})
end

function T.getCpuTimerSetupCode(unit, params)
  local code = [[
    CpuTimer%(unit)dRegs.TCR.bit.TSS = 1; // stop timer
    CpuTimer%(unit)dRegs.TPRH.all = 0;
    CpuTimer%(unit)dRegs.PRD.all = %(period)d - 1;
    CpuTimer%(unit)dRegs.TCR.bit.TRB = 1; // reload period
    CpuTimer%(unit)dRegs.TCR.bit.TIE = 1; // enable trigger to SOC/interrupt
  ]] % {
    unit = unit,
    period = params.period,
  }

  if params.isr then
    -- note, this is really hard-coded for CPUTimer0
    local isrConfigCode = [[
      PieCtrlRegs.PIEIER1.bit.INTx7 = 1;
      EALLOW;
      PieVectTable.TIMER%(unit)d_INT = &%(isr)s;
      EDIS;
      PieCtrlRegs.PIEIER1.bit.INTx7 = 1;
      PieCtrlRegs.PIEACK.all = PIEACK_GROUP1; // acknowledge interrupt to PIE
	  ]] % {
      unit = unit,
      isr = params.isr,
    }

    code = code..isrConfigCode
  end

  return code
end

function T.getEpwmTimersSyncCode()
  return [[
    CpuSysRegs.PCLKCR0.bit.GTBCLKSYNC = 1; // start all the timers synced (global)
  ]]
end

function T.getAdcSetupCode(unit, params)
  local code = [[
    EALLOW;
    Adc%(adc)sRegs.ADCINTSEL1N2.bit.INT1CONT = 0; // disable ADCINT1 Continuous mode
    Adc%(adc)sRegs.ADCINTSEL1N2.bit.INT1SEL = %(int1sel)d; // setup EOC%(int1sel)d to trigger ADCINT1
    Adc%(adc)sRegs.ADCINTSEL1N2.bit.INT1E = 1; // enable ADCINT1
    Adc%(adc)sRegs.ADCCTL1.bit.INTPULSEPOS = 1; // ADCINT1 trips after AdcResults latch
    EDIS;
  ]] % {
    adc = string.char(97 + unit),
    int1sel = params.INT1SEL,
  }

  if params.isr then
    local pieVect, pieBitMask
    if unit <= 2 then
      pieVect = '(PINT *)((uint32_t)(&PieVectTable.ADCA1_INT) + ((uint32_t)%d)*sizeof(PINT *))' % {unit}
      pieBitMask = (1 << unit)
    else
      -- ADC C is special case
      pieVect = '(PINT *)&PieVectTable.ADCD1_INT'
      pieBitMask = (1 << 5)
    end

    local isrConfigCode = [[
      EALLOW;
      *%(pieVect)s = &%(isr)s;
      PieCtrlRegs.PIEIER1.all |= %(pieBitMask)s;
      PieCtrlRegs.PIEACK.all = PIEACK_GROUP1;
      EDIS;
    ]] % {
      pieVect = pieVect,
      isr = params.isr,
      pieBitMask = pieBitMask,
    }

    code = code..isrConfigCode
  end

  return code
end

function T.getAdcInterruptAcknCode(unit, params)
  local code = [[
    Adc%sRegs.ADCINTFLGCLR.bit.ADCINT1 = 1; // clear ADCINT1 flag reinitialize for next SOC
    PieCtrlRegs.PIEACK.all = PIEACK_GROUP1; // acknowledge interrupt to PIE (All ADCS in group 1)
    IER |= M_INT1;
  ]] % {string.char(97 + unit)}

  return code
end

local function setAndGetPllLimits(useInternalOsc, isAuxClock)
  local clockName = nil -- will default to "System Clock" for debug prints
  local sysDivMax
  if isAuxClock then
    clockName = 'Aux Clock'
    sysDivMax = 8 -- AUXCLKDIV has a max of 8 (and also allows odds, but we only support evens)
  else
    sysDivMax = 16
  end
  local limits = PLL.new(useInternalOsc, clockName)

  limits:set('INTERNAL_OSCILLATOR_SYSCLK', {max = 194e6}) -- limit to flash with internal clock
  limits:set('INTERNAL_OSCILLATOR_HZ', {value = 10e6}) -- INTOSC2

  limits:set('OSCCLK', {min = 10e6, max = 25e6})
  limits:set('INTCLK', {min = 10e6, max = 25e6})
  limits:set('VCOCLK', {min = 220e6, max = 600e6})
  limits:set('PLLRAWCLK', {min = 6e6, max = 400e6})
  limits:set('SYSCLK', {min = 2e6, max = 200e6})

  limits:set('REFDIV', {max = 32})
  limits:set('IMULT', {max = 127})
  limits:set('ODIV', {max = 32})
  limits:set('SYSDIV', {max = sysDivMax})

  return limits:getLimits() -- executes validation and returns limits
end

function T.getClockConfiguration()
  local useInternalOsc = (Target.Variables.useIntOsc == 1) -- convert gui value to boolean
  local limits = setAndGetPllLimits(useInternalOsc)

  local sysClkHz = T.getCleanSysClkHz()

  local inputClkHz
  local sysClkWcHi
  if useInternalOsc then 
    -- using internal oscillator with 3% error
    inputClkHz = limits.INTERNAL_OSCILLATOR_HZ.value
    sysClkWcHi = 1000000 * math.floor((sysClkHz * 1.03 + 500000) / 1000000)
  else
    inputClkHz = T.getCleanExtClkHz()
    sysClkWcHi = sysClkHz
  end

  -- establish AUXPLL settings
  local auxClkHz = 125e6
  -- Note the Aux Clock limits are the same as the primary PLL, 
  -- with the exception of AUXCLKDIV.
  local isAuxClock = true
  local aux_limits = setAndGetPllLimits(useInternalOsc, isAuxClock) 

  -- establish PLL settings
  local pllConfig = PLL.getClockConfiguration(limits, inputClkHz, sysClkHz)
  return {
    pllConfig = pllConfig,
    aux_pllConfig = PLL.getClockConfiguration(aux_limits, inputClkHz, auxClkHz),
    inputClkHz = inputClkHz,
    sysClkWcHi = sysClkWcHi,
    sysClkHz = sysClkHz,
    auxClkHz = auxClkHz,
    useInternalOsc = useInternalOsc,
  }
end

function T.getClockConfigurationCode(clockConfig)
  local pllConfig = clockConfig.pllConfig
  local aux_pllConfig = clockConfig.aux_pllConfig

  local clkSrcMacro, clkSrcMacroAux
  if clockConfig.useInternalOsc then 
    clkSrcMacro = 'SYSCTL_OSCSRC_OSC2'
    clkSrcMacroAux = 'SYSCTL_AUXPLL_OSCSRC_OSC2'
  else
    clkSrcMacro = 'SYSCTL_OSCSRC_XTAL'
    clkSrcMacroAux = 'SYSCTL_AUXPLL_OSCSRC_XTAL'
  end
  local dccBase = 1
  local dccBaseAux = 0

  -- CONTINUE SWITCHING TO NEW PLL CODE HERE:
  local cmClkHz = clockConfig.auxClkHz
  local cpuRate = 100.0 / clockConfig.sysClkHz * 10000000

  local declarations = [[
    void DevInit(uint32_t aDeviceClkConf, uint32_t aAuxClockConf);
    void InitFlashHz(Uint32 clkHz);
    void PieCntlInit(void);
	  void F28x_usDelay(long LoopCount);

// Clock configuration
#define PLX_DEVICE_SETCLOCK_CFG       (%(clkSrcMacro)s | SYSCTL_IMULT(%(imult)d) | \
                                      SYSCTL_REFDIV(%(refdiv)d) | SYSCTL_ODIV(%(odiv)d) | \
                                      SYSCTL_SYSDIV(%(sysdiv)d) | SYSCTL_PLL_ENABLE | \
                                      SYSCTL_DCC_BASE_%(dccBase)d)

#define PLX_DEVICE_AUXSETCLOCK_CFG    (%(clkSrcMacroAux)s | SYSCTL_AUXPLL_IMULT(%(imultAux)d) |  \
                                      SYSCTL_REFDIV(%(refdivAux)d) | SYSCTL_ODIV(%(odivAux)d) | \
                                      SYSCTL_AUXPLL_DIV_%(sysdivAux)d | SYSCTL_AUXPLL_ENABLE | \
                                      SYSCTL_DCC_BASE_%(dccBaseAux)d)

#define SYSCLK_HZ %(sysClkHz)dL
#define SYSCLK_WC_HI_HZ %(sysClkWcHi)dL
#define LSPCLK_HZ (%(sysClkHz)dL / 4l)
#define CM_SYSCLK_HZ %(cmClkHz)dL

#define PLX_DELAY_US(A)  F28x_usDelay(\
      ((((long double) A * 1000.0L) / (long double)%(cpuRate)fL) - 9.0L) / 5.0L)
  ]] % {
    clkSrcMacro = clkSrcMacro,
    imult = pllConfig.imult,
    refdiv = pllConfig.refdiv,
    odiv = pllConfig.odiv,
    sysdiv = pllConfig.sysdiv,
    dccBase = dccBase,
    clkSrcMacroAux = clkSrcMacroAux,
    imultAux = aux_pllConfig.imult,
    refdivAux = aux_pllConfig.refdiv,
    odivAux = aux_pllConfig.odiv,
    sysdivAux = aux_pllConfig.sysdiv,
    dccBaseAux = dccBaseAux,
    sysClkHz = clockConfig.sysClkHz,
    sysClkWcHi = clockConfig.sysClkWcHi,
    cmClkHz = cmClkHz,
    cpuRate = cpuRate,
  }

  local code = [[
    SysCtl_disableWatchdog();
    {
      uint32_t sysPllConfig = PLX_DEVICE_SETCLOCK_CFG;
      uint32_t auxPllConfig = PLX_DEVICE_AUXSETCLOCK_CFG;
      DevInit(sysPllConfig, auxPllConfig);

      SysCtl_setLowSpeedClock(SYSCTL_LSPCLK_PRESCALE_4);
      SysCtl_setCMClk(SYSCTL_CMCLKOUT_DIV_1,SYSCTL_SOURCE_AUXPLL);
    }

    InitFlashHz(SYSCLK_WC_HI_HZ);

    // set cpu timers to same clock as ePWM
    CPUTimer_setPreScaler(CPUTIMER0_BASE, 0);
    CPUTimer_setPreScaler(CPUTIMER1_BASE, 0);
    CPUTimer_setPreScaler(CPUTIMER2_BASE, 0);

    EALLOW;
    CpuSysRegs.PCLKCR0.bit.CPUTIMER0 = 1;
    CpuSysRegs.PCLKCR0.bit.CPUTIMER1 = 1;
    CpuSysRegs.PCLKCR0.bit.CPUTIMER2 = 1;
    CpuSysRegs.PCLKCR0.bit.TBCLKSYNC = 0; // stop all the TB clocks on the local cpu
    CpuSysRegs.PCLKCR0.bit.GTBCLKSYNC = 0; // stop all the TB clocks
    ClkCfgRegs.PERCLKDIVSEL.bit.EPWMCLKDIV = 0;
    EDIS;
  ]]

  return {declarations = declarations, code = code}
end

function T.getClockConfigurationCodeCpu2(clockConfig)
  local cpuRate = 100.0 / clockConfig.sysClkHz * 10000000

  local declarations = [[
    void DevInit();
    void InitFlashHz(Uint32 clkHz);
    void PieCntlInit(void);
	  void F28x_usDelay(long LoopCount);

#define SYSCLK_HZ %(sysClkHz)dL
#define SYSCLK_WC_HI_HZ %(sysClkWcHiHz)dL
#define LSPCLK_HZ (%(sysClkHz)dL / 4l)

#define PLX_DELAY_US(A)  F28x_usDelay(((((long double) A * 1000.0L) / (long double)%(cpuRate)fL) - 9.0L) / 5.0L)
  ]] % {
    sysClkHz = clockConfig.sysClkHz,
    sysClkWcHiHz = clockConfig.sysClkWcHi,
    cpuRate = cpuRate,
  }

  local code = [[
    SysCtl_disableWatchdog();
    DevInit();
	  InitFlashHz(SYSCLK_WC_HI_HZ);

    // set cpu timers to same clock as ePWM
    CPUTimer_setPreScaler(CPUTIMER0_BASE, 0);
    CPUTimer_setPreScaler(CPUTIMER1_BASE, 0);
    CPUTimer_setPreScaler(CPUTIMER2_BASE, 0);

    EALLOW;
    CpuSysRegs.PCLKCR0.bit.CPUTIMER0 = 1;
    CpuSysRegs.PCLKCR0.bit.CPUTIMER1 = 1;
    CpuSysRegs.PCLKCR0.bit.CPUTIMER2 = 1;
    CpuSysRegs.PCLKCR0.bit.TBCLKSYNC = 0; // stop all the TB clocks on the local cpu
    ClkCfgRegs.PERCLKDIVSEL.bit.EPWMCLKDIV = 0;
	  EDIS;
  ]]

  return {declarations = declarations, code = code}
end

function T.getCpu2BootCode()
  local declarations = [[
#define BOOTMODE_BOOT_TO_FLASH_SECTOR0 0x03U
#define BOOT_KEY 0x5A000000UL
#define CPU2_BOOT_FREQ_200MHZ 0xC800U

    static void BootCPU2ToFlashSector0()
    {
      IPC_setBootMode(IPC_CPU1_L_CPU2_R,
                  (BOOT_KEY | CPU2_BOOT_FREQ_200MHZ | BOOTMODE_BOOT_TO_FLASH_SECTOR0));
      IPC_setFlagLtoR(IPC_CPU1_L_CPU2_R, IPC_FLAG0);
      SysCtl_controlCPU2Reset(SYSCTL_CORE_DEACTIVE);
      while(SysCtl_isCPU2Reset() == 0x1U);
    }
  ]]

  local code = [[
    SysCtl_controlCPU2Reset(SYSCTL_CORE_ACTIVE);
    BootCPU2ToFlashSector0();
    // wait for CPU2 to signal that has completed its initialization
    IPC_sync(IPC_CPU1_L_CPU2_R, IPC_FLAG31);
    IPC_clearFlagLtoR(IPC_CPU1_L_CPU2_R, IPC_FLAG_ALL);
  ]]

  return {declarations = declarations, code = code}
end

function T.getCpu2BootCodeCpu2()
  local code = [[
    // signal to CPU1 that we are configured
    IPC_sync(IPC_CPU2_L_CPU1_R, IPC_FLAG31);
    IPC_clearFlagLtoR(IPC_CPU2_L_CPU1_R, IPC_FLAG_ALL);
  ]]

  return {declarations = nil, code = code}
end

T.ts_epwm = require('peripherals.epwm_type4').getFunctions(T)

return T
