#!/usr/bin/env python3

import deps

import argparse

from migen import *
from migen.genlib.io import CRG

from platforms import icestick

from litex.soc.integration.soc_core import SoCCore
from litex.soc.interconnect.csr import AutoCSR, CSRStorage
from litex.soc.cores.uart import UARTWishboneBridge

from litex.soc.integration.builder import Builder, builder_args, builder_argdict

class _CRG(Module):
	def __init__(self, platform):
		clk12 = platform.request('clk12')
		
		self.clock_domains.cd_sys = ClockDomain()
		self.clock_domains.cd_por = ClockDomain(reset_less = True)
		
		clk48 = Signal()
		
		self.specials += Instance(
			'SB_PLL40_CORE',
			# Parameters
			p_DIVR = 0,
			p_DIVF = 3,
			p_DIVQ = 0,
			p_FILTER_RANGE = 1,
			p_FEEDBACK_PATH = "SIMPLE",
			#p_DELAY_ADJUSTMENT_MODE_FEEDBACK = "FIXED",
			#p_FDA_FEEDBACK = 0,
			#p_DELAY_ADJUSTMENT_MODE_RELATIVE = "FIXED",
			#p_FDA_RELATIVE = 0,
			#p_SHIFTREG_DIV_MODE = 1,
			#p_PLLOUT_SELECT_PORTB = "GENCLK",
			#p_ENABLE_ICEGATE_PORTA = 0,
			#p_ENABLE_ICEGATE_PORTB = 0,
			# IO
			#i_PACKAGEPIN = clk12,
			i_REFERENCECLK = clk12,
			o_PLLOUTGLOBAL = clk48,
			i_BYPASS = 0,
			i_RESETB = 1,
		)
		
		platform.add_period_constraint(clk48, 1e9/48e6)
		
		int_rst = Signal(reset = 1)
		self.sync.por += int_rst.eq(0)
		
		self.comb += [
			self.cd_por.clk.eq(clk12),
			self.cd_sys.clk.eq(clk48),
			self.cd_sys.rst.eq(int_rst),
		]

class SERVSoC(SoCCore):
	def __init__(self, platform):
		sys_clk_freq = int(48e6)
		SoCCore.__init__(self, platform, sys_clk_freq,
			cpu_type = 'serv',
			integrated_rom_size = 0x1000,
			integrated_sram_size = 0x1000,
			with_timer = False,
			with_ctrl = False,
		)
		
		self.submodules.crg = _CRG(platform)
		
if __name__ == "__main__":
	parser = argparse.ArgumentParser()
	builder_args(parser)
	args = parser.parse_args()
	
	plat = icestick.Platform()
	soc = SERVSoC(plat)
	
	builder = Builder(soc, **builder_argdict(args))
	builder.build()