from migen import *

from litex.soc.interconnect.wishbone import *
from litex.soc.integration.soc import SoCRegion

class Sampler(Module):
    def __init__(self, adc_pins):
        # TODO correct addr width
        self.bus = Interface(data_width=32, adr_width=11)

        # self.clock_domains.foo = ClockDomain() is how to add a new clock domain, accessible at self.foo

        # Provide a slow clock to the ADC, 60MHz / 600 = 100kHz
        self._counter = Signal(32)
        self.sync += self._counter.eq(self._counter + 1)
        self.sync += If(self._counter >= 600, self._counter.eq(0), adc_pins.refclk.eq(~adc_pins.refclk))

        # Set config pins to constant values
        self.comb += adc_pins.oen_b.eq(0)       # Data pins enable
        self.comb += adc_pins.standby.eq(0)     # Sampling standby
        self.comb += adc_pins.dfs.eq(0)         # DFS (raw or two's complement)
        # The only remaining pin, OTR, is an out of range status indicator

        # Read directly from the data pins into the wishbone bus for now, just for bringup
        self.comb += self.bus.dat_r.eq(adc_pins.data)
        self.sync += self.bus.ack.eq(0)
        self.sync += If(self.bus.cyc & self.bus.stb, self.bus.ack.eq(1))

