from init_regs_value import init_regs_value
from regs_addr import regs_addr
import time
CONFIG_REGS = regs_addr["CONFIG_REGS"]
STROBES = regs_addr["STROBES"]
STATUS = regs_addr["STATUS"]
MEMORY = regs_addr["MEMORY"]
MASKS = regs_addr["MASKS"]
ACCESS = regs_addr["ACCESS"]
SRES = STROBES["SRES"]
SNOP = STROBES["SNOP"]
VERSION = STATUS["VERSION"]

def get_addr(name):
    addr = ""
    stop = False
    for reg_type, reg_data in regs_addr.items():
        for reg_name, reg_addr in reg_data.items():
            if reg_name == name:
                stop = True
                addr = reg_addr
    if stop == False:
        raise Exception("Failed to find address for "+name)
    return addr

def strobe(spi, command):
    """Send a command strobe to CC2500"""
    spi.xfer2([command])

def write_reg(spi, addr, value):
    """Write single byte to a register"""
    spi.xfer2([addr, value])

def read_register(spi, addr):
    READ_SINGLE = get_addr("READ_SINGLE")
    # Send address | 0x80 (read), then 0x00 dummy to clock in response
    response = spi.xfer2([READ_SINGLE | addr, 0x00])
    return response[1]

def disable_crc(spi):
    spi.xfer2([CONFIG_REGS["PKTCTRL0"], 0x01])

def init_regs(spi):
    for reg_name, value in init_regs_value.items():
        addr = get_addr(reg_name)
        write_reg(spi, addr, value)

def test_read_write_reg(spi):
    FIFOTHR = get_addr("FIFOTHR")
    initial_val = read_register(spi, FIFOTHR)
    test_value = initial_val + 1
    write_reg(spi, FIFOTHR, test_value)
    check = read_register(spi, FIFOTHR)
    write_reg(spi, FIFOTHR, initial_val)
    if check != test_value:
        print("initial value ", initial_val)
        print("test value ", test_value)
        print("check ",check)
        raise Exception("Test Read+Write failed")
    return check == test_value

def dump_regs(spi):
    for reg_type, reg_data in regs_addr.items():
        for reg_name, reg_addr in reg_data.items():
            name :str = reg_name
            value = read_register(spi, reg_addr)
            print((name+":").ljust(15) +hex(value).ljust(4)+"\t"+str(value))

def sleep(t):
    return time.sleep(t)