#!/usr/bin/env python
#
# Copyright 2005 Free Software Foundation, Inc.
# 
# This file is part of GNU Radio
# 
# GNU Radio is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option)
# any later version.
# 
# GNU Radio is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with GNU Radio; see the file COPYING.  If not, write to
# the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
# Boston, MA 02111-1307, USA.
# 

from usrp_prims import *
from optparse import OptionParser
import sys
import usrp_dbid

slot_info = {
    'TX_A': { 'i2c_addr' : 0x54, 'dbid' : usrp_dbid.BASIC_TX, 'oe' : 0x0000 },
    'RX_A': { 'i2c_addr' : 0x55, 'dbid' : usrp_dbid.BASIC_RX, 'oe' : 0x0000 },
    'TX_B': { 'i2c_addr' : 0x56, 'dbid' : usrp_dbid.BASIC_TX, 'oe' : 0x0000 },
    'RX_B': { 'i2c_addr' : 0x57, 'dbid' : usrp_dbid.BASIC_RX, 'oe' : 0x0000 }
    }

def open_cmd_interface (which_board = 0):
    if not usrp_load_standard_bits (which_board, 0):
        raise RuntimeError, "usrp_load_standard_bits"
    dev = usrp_find_device (which_board)
    if not dev:
        raise RuntimeError, "usrp_find_device"
    u = usrp_open_cmd_interface (dev)
    if not u:
        raise RuntimeError, "usrp_open_cmd_interface"
    return u

def write_dboard_eeprom (u, i2c_addr, dbid, oe):
    eeprom = 0x20 * [0]
    eeprom[0] = 0xDB                    # magic value
    eeprom[1] = dbid & 0xff
    eeprom[2] = (dbid >> 8) & 0xff
    eeprom[3] = oe & 0xff
    eeprom[4] = (oe >> 8) & 0xff
    eeprom[0x1f] = 0xff & (-reduce(lambda x, y: x+y, eeprom)) # checksum
    s = ''.join (map (chr, eeprom))
    ok = usrp_eeprom_write (u, i2c_addr, 0, s)
    return ok

def init_eeprom (u, which, force):
    i2c_addr = slot_info[which]['i2c_addr']
    dbid = slot_info[which]['dbid']
    oe = slot_info[which]['oe']

    e = usrp_eeprom_read (u, i2c_addr, 0, 0x20)
    if not e:
        print "%s: no d'board, skipped" % (which,)
        return True
    
    if not force and (sum (map (ord, e)) & 0xff) == 0 and ord (e[0]) == 0xDB:
        print "%s: already initialized, skipped" % (which,)
        return True
        
    if not write_dboard_eeprom (u, i2c_addr, dbid, oe):
        print "%s: failed to write d'board EEPROM" % (which,)
        return False

    print "%s: OK" % (which,)
    return True


def main (which, force):
    u = open_cmd_interface (0)
    ok = True
    for w in which:
        ok = ok | init_eeprom (u, w, force)
    return ok

if __name__ == "__main__":

    usage = "usage: %prog [options] (tx_a|rx_a|tx_b|rx_b)*"
    parser = OptionParser(usage=usage)
    parser.add_option ("-a", "--all", action="store_true", default=False,
                       help="initialize all d'board eeproms")
    parser.add_option ("-f", "--force", action="store_true", default=False,
                       help="force init of already initialized eeproms")

    (options, args) = parser.parse_args ()

    which = []
    for a in args:
        au = a.upper ()
        if not au in ["TX_A", "RX_A", "TX_B", "RX_B"]:
            sys.stderr.write ("%s: invalid d'board slot name\n" % (a,))
            parser.print_help ()
            sys.exit (1)
        which.append (au)

    if options.all:
        which = ["TX_A", "RX_A", "TX_B", "RX_B"]

    if len (which) == 0:
        sys.stderr.write ("You must specify at least one slot or use the -a option\n")
        parser.print_help ()
        sys.exit (1)

    ok = main (which, options.force)
    if ok:
        sys.exit (0)
    else:
        sys.exit (1)
