#!/usr/bin/env python
#
# Copyright 2006,2007 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 3, 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., 51 Franklin Street,
# Boston, MA 02110-1301, USA.
# 

from usrpm.usrp_prims import *
from optparse import OptionParser
import sys
import time


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_serial_number_eeprom(u, serial_number):
    if not str(serial_number):
        raise TypeError

    i2c_addr = 0x50                 # usrp boot rom
    serial_number_offset = 248      # offset to serial number
    serial_number_len = 8           # length of serial number

    lsn = len(serial_number)
    if lsn > serial_number_len:
        serial_number = serial_number[0:serial_number_len]
    if lsn < serial_number_len:
        serial_number = serial_number + (serial_number_len - lsn) * ' '
    
    ok = usrp_eeprom_write (u, i2c_addr, serial_number_offset, serial_number)
    return ok


def main():

    default_serial_number = hex(int(time.time()))[2:]
    parser = OptionParser()
    parser.add_option ("-s", "--serial-number", default=default_serial_number,
                       help="set serial number [default=%default]")
    (options, args) = parser.parse_args ()

    if len(args) != 0:
        parser.print_help()
        sys.exit(1)

    u = open_cmd_interface (0)
    ok = write_serial_number_eeprom(u, options.serial_number)

    if ok:
        sys.exit(0)
    else:
        sys.exit(1)

if __name__ == "__main__":
    main ()
