Ejemplo n.º 1
0
 def _init_gps_sensors(self):
     "Init and register the GPSd Iface and related sensor functions"
     self.log.trace("Initializing GPSd interface")
     self._gpsd = GPSDIfaceExtension()
     new_methods = self._gpsd.extend(self)
     for method_name in new_methods:
         try:
             # Extract the sensor name from the getter
             sensor_name = re.search(r"get_(.*)_sensor", method_name).group(1)
             # Register it with the MB sensor framework
             self.mboard_sensor_callback_map[sensor_name] = method_name
             self.log.trace("Adding %s sensor function", sensor_name)
         except AttributeError:
             # re.search will return None is if can't find the sensor name
             self.log.warning("Error while registering sensor function: %s", method_name)
Ejemplo n.º 2
0
 def __init__(self, clk_aux_board, log):
     assert clk_aux_board and clk_aux_board.is_gps_supported()
     self._clocking_auxbrd = clk_aux_board
     self.log = log.getChild('GPS')
     self.log.trace("Initializing GPSd interface")
     self._gpsd = GPSDIfaceExtension()
     # To disable sensors, we simply return an empty value if GPS is disabled.
     # For TPV, SKY, and GPGGA, we can do this in the same fashion (they are
     # very similar). gps_time is different (it returns an int) so for sake
     # of simplicity it's defined separately below.
     for sensor_name in ('gps_tpv', 'gps_sky', 'gps_gpgga'):
         sensor_api = f'get_{sensor_name}_sensor'
         setattr(
             self, sensor_api,
             lambda sensor_name=sensor_name: {
                 'name': sensor_name, 'type': 'STRING',
                 'unit': '', 'value': 'n/a'} \
             if not self.is_gps_enabled() \
             else getattr(self._gpsd, f'get_{sensor_name}_sensor')()
         )
Ejemplo n.º 3
0
Archivo: e320.py Proyecto: bpkempke/uhd
 def _init_gps_sensors(self):
     "Init and register the GPSd Iface and related sensor functions"
     self.log.trace("Initializing GPSd interface")
     self._gpsd = GPSDIfaceExtension()
     new_methods = self._gpsd.extend(self)
     for method_name in new_methods:
         try:
             # Extract the sensor name from the getter
             sensor_name = re.search(r"get_(.*)_sensor", method_name).group(1)
             # Register it with the MB sensor framework
             self.mboard_sensor_callback_map[sensor_name] = method_name
             self.log.trace("Adding %s sensor function", sensor_name)
         except AttributeError:
             # re.search will return None is if can't find the sensor name
             self.log.warning("Error while registering sensor function: %s", method_name)
Ejemplo n.º 4
0
Archivo: e320.py Proyecto: bpkempke/uhd
class e320(ZynqComponents, PeriphManagerBase):
    """
    Holds E320 specific attributes and methods
    """
    #########################################################################
    # Overridables
    #
    # See PeriphManagerBase for documentation on these fields
    #########################################################################
    description = "E300-Series Device"
    pids = {0xe320: 'e320'}
    mboard_eeprom_addr = "e0004000.i2c"
    mboard_eeprom_offset = 0
    mboard_eeprom_max_len = 256
    mboard_info = {"type": "e3xx",
                   "product": "e320"
                  }
    mboard_max_rev = 2  # RevB
    mboard_sensor_callback_map = {
        'ref_locked': 'get_ref_lock_sensor',
        'gps_locked': 'get_gps_lock_sensor',
        'fan': 'get_fan_sensor',
        'temp_fpga' : 'get_fpga_temp_sensor',
        'temp_internal' : 'get_internal_temp_sensor',
        'temp_rf_channelA' : 'get_rf_channelA_temp_sensor',
        'temp_rf_channelB' : 'get_rf_channelB_temp_sensor',
        'temp_main_power' : 'get_main_power_temp_sensor',
    }
    max_num_dboards = 1

    # We're on a Zynq target, so the following two come from the Zynq standard
    # device tree overlay (tree/arch/arm/boot/dts/zynq-7000.dtsi)
    dboard_spimaster_addrs = ["e0006000.spi", "e0007000.spi"]
    # E320-specific settings
    # Label for the mboard UIO
    mboard_regs_label = "mboard-regs"
    # Override the list of updateable components
    updateable_components = {
        'fpga': {
            'callback': "update_fpga",
            'path': '/lib/firmware/{}.bin',
            'reset': True,
        },
        'dts': {
            'callback': "update_dts",
            'path': '/lib/firmware/{}.dts',
            'output': '/lib/firmware/{}.dtbo',
            'reset': False,
        },
    }

    @staticmethod
    def list_required_dt_overlays(device_info):
        """
        Lists device tree overlays that need to be applied before this class can
        be used. List of strings.
        Are applied in order.

        eeprom_md -- Dictionary of info read out from the mboard EEPROM
        device_args -- Arbitrary dictionary of info, typically user-defined
        """
        return [device_info['product']]

    ###########################################################################
    # Ctor and device initialization tasks
    ###########################################################################
    def __init__(self, args):
        super(e320, self).__init__()
        self.overlay_apply()
        self.init_dboards(args)
        if not self._device_initialized:
            # Don't try and figure out what's going on. Just give up.
            return
        self._tear_down = False
        self._status_monitor_thread = None
        self._ext_clock_freq = E320_DEFAULT_EXT_CLOCK_FREQ
        self._clock_source = None
        self._time_source = None
        self._available_endpoints = list(range(256))
        self._gpsd = None
        self.dboard = self.dboards[E320_DBOARD_SLOT_IDX]
        from functools import partial
        for sensor_name, sensor_cb_name in self.mboard_sensor_callback_map.items():
            if sensor_name[:5] == 'temp_':
                setattr(self, sensor_cb_name, partial(self.get_temp_sensor, sensor_name))
        try:
            self._init_peripherals(args)
        except Exception as ex:
            self.log.error("Failed to initialize motherboard: %s", str(ex))
            self._initialization_status = str(ex)
            self._device_initialized = False

    def _init_dboards(self, _, override_dboard_pids, default_args):
        """
        Initialize all the daughterboards

        (dboard_infos) -- N/A
        override_dboard_pids -- List of dboard PIDs to force
        default_args -- Default args
        """
        # Override the base class's implementation in order to avoid initializing our one "dboard"
        # in the same way that, for example, N310's dboards are initialized. Specifically,
        # - skip dboard EEPROM setup (we don't have one)
        # - change the way we handle SPI devices
        if override_dboard_pids:
            self.log.warning("Overriding daughterboard PIDs with: {}"
                             .format(override_dboard_pids))
            raise NotImplementedError("Can't override dboard pids")
        # The DBoard PID is the same as the MBoard PID
        db_pid = list(self.pids.keys())[0]
        # Set up the SPI nodes
        spi_nodes = []
        for spi_addr in self.dboard_spimaster_addrs:
            for spi_node in get_spidev_nodes(spi_addr):
                bisect.insort(spi_nodes, spi_node)
        self.log.trace("Found spidev nodes: {0}".format(spi_nodes))

        if not spi_nodes:
            self.log.warning("No SPI nodes for dboard %d.", E320_DBOARD_SLOT_IDX)
        dboard_info = {
            'eeprom_md': self.mboard_info,
            'eeprom_rawdata': self._eeprom_rawdata,
            'pid': db_pid,
            'spi_nodes': spi_nodes,
            'default_args': default_args,
        }
        # This will actually instantiate the dboard class:
        self.dboards.append(Neon(E320_DBOARD_SLOT_IDX, **dboard_info))
        self.log.info("Found %d daughterboard(s).", len(self.dboards))

    def _check_fpga_compat(self):
        " Throw an exception if the compat numbers don't match up "
        actual_compat = self.mboard_regs_control.get_compat_number()
        self.log.debug("Actual FPGA compat number: {:d}.{:d}".format(
            actual_compat[0], actual_compat[1]
        ))
        assert_compat_number(
            E320_FPGA_COMPAT,
            self.mboard_regs_control.get_compat_number(),
            component="FPGA",
            fail_on_old_minor=True,
            log=self.log
        )

    def _init_ref_clock_and_time(self, default_args):
        """
        Initialize clock and time sources. After this function returns, the
        reference signals going to the FPGA are valid.
        """
        self._ext_clock_freq = float(
            default_args.get('ext_clock_freq', E320_DEFAULT_EXT_CLOCK_FREQ)
        )
        if not self.dboards:
            self.log.warning(
                "No dboards found, skipping setting clock and time source "
                "configuration."
            )
            self._clock_source = E320_DEFAULT_CLOCK_SOURCE
            self._time_source = E320_DEFAULT_TIME_SOURCE
        else:
            self.set_clock_source(
                default_args.get('clock_source', E320_DEFAULT_CLOCK_SOURCE)
            )
            self.set_time_source(
                default_args.get('time_source', E320_DEFAULT_TIME_SOURCE)
            )

    def _monitor_status(self):
        """
        Status monitoring thread: This should be executed in a thread. It will
        continuously monitor status of the following peripherals:

        - GPS lock
        """
        self.log.trace("Launching monitor loop...")
        cond = threading.Condition()
        cond.acquire()
        while not self._tear_down:
            gps_locked = self.get_gps_lock_sensor()['value'] == 'true'
            # Now wait
            if cond.wait_for(
                    lambda: self._tear_down,
                    E320_MONITOR_THREAD_INTERVAL):
                break
        cond.release()
        self.log.trace("Terminating monitor loop.")

    def _init_peripherals(self, args):
        """
        Turn on all peripherals. This may throw an error on failure, so make
        sure to catch it.

        Peripherals are initialized in the order of least likely to fail, to most
        likely.
        """
        # Sanity checks
        assert self.mboard_info.get('product') in self.pids.values(), \
            "Device product could not be determined!"
        # Init Mboard Regs
        self.mboard_regs_control = MboardRegsControl(
            self.mboard_regs_label, self.log)
        self.mboard_regs_control.get_git_hash()
        self.mboard_regs_control.get_build_timestamp()
        self._check_fpga_compat()
        self._update_fpga_type()
        self.crossbar_base_port = self.mboard_regs_control.get_xbar_baseport()
        # Init peripherals
        self.enable_gps(
            enable=str2bool(
                args.get('enable_gps', E320_DEFAULT_ENABLE_GPS)
            )
        )
        self.enable_fp_gpio(
            enable=args.get(
                        'enable_fp_gpio',
                        E320_DEFAULT_ENABLE_FPGPIO
                    )
        )
        # Init clocking
        self._init_ref_clock_and_time(args)
        # Init GPSd iface and GPS sensors
        self._init_gps_sensors()
        # Init CHDR transports
        self._xport_mgrs = {
            'udp': E320XportMgrUDP(self.log.getChild('UDP'), args),
            'liberio': E320XportMgrLiberio(self.log.getChild('liberio')),
        }
        # Spawn status monitoring thread
        self.log.trace("Spawning status monitor thread...")
        self._status_monitor_thread = threading.Thread(
            target=self._monitor_status,
            name="E320StatusMonitorThread",
            daemon=True,
        )
        self._status_monitor_thread.start()
        # Init complete.
        self.log.debug("mboard info: {}".format(self.mboard_info))

    def _init_gps_sensors(self):
        "Init and register the GPSd Iface and related sensor functions"
        self.log.trace("Initializing GPSd interface")
        self._gpsd = GPSDIfaceExtension()
        new_methods = self._gpsd.extend(self)
        for method_name in new_methods:
            try:
                # Extract the sensor name from the getter
                sensor_name = re.search(r"get_(.*)_sensor", method_name).group(1)
                # Register it with the MB sensor framework
                self.mboard_sensor_callback_map[sensor_name] = method_name
                self.log.trace("Adding %s sensor function", sensor_name)
            except AttributeError:
                # re.search will return None is if can't find the sensor name
                self.log.warning("Error while registering sensor function: %s", method_name)

    ###########################################################################
    # Session init and deinit
    ###########################################################################
    def init(self, args):
        """
        Calls init() on the parent class, and then programs the Ethernet
        dispatchers accordingly.
        """
        if not self._device_initialized:
            self.log.warning(
                "Cannot run init(), device was never fully initialized!")
            return False
        if args.get("clock_source", "") != "":
            self.set_clock_source(args.get("clock_source"))
        if args.get("time_source", "") != "":
            self.set_time_source(args.get("time_source"))
        result = super(e320, self).init(args)
        for xport_mgr in itervalues(self._xport_mgrs):
            xport_mgr.init(args)
        return result

    def deinit(self):
        """
        Clean up after a UHD session terminates.
        """
        if not self._device_initialized:
            self.log.warning(
                "Cannot run deinit(), device was never fully initialized!")
            return
        super(e320, self).deinit()
        for xport_mgr in itervalues(self._xport_mgrs):
            xport_mgr.deinit()
        self.log.trace("Resetting SID pool...")
        self._available_endpoints = list(range(256))

    def tear_down(self):
        """
        Tear down all members that need to be specially handled before
        deconstruction.
        For E320, this means the overlay.
        """
        self.log.trace("Tearing down E320 device...")
        self._tear_down = True
        if self._device_initialized:
            self._status_monitor_thread.join(3 * E320_MONITOR_THREAD_INTERVAL)
            if self._status_monitor_thread.is_alive():
                self.log.error("Could not terminate monitor thread! This could result in resource leaks.")
        active_overlays = self.list_active_overlays()
        self.log.trace("E320 has active device tree overlays: {}".format(
            active_overlays
        ))
        for overlay in active_overlays:
            dtoverlay.rm_overlay(overlay)

    ###########################################################################
    # Transport API
    ###########################################################################
    def request_xport(
            self,
            dst_address,
            suggested_src_address,
            xport_type
        ):
        """
        See PeriphManagerBase.request_xport() for docs.
        """
        # Try suggested address first, then just pick the first available one:
        src_address = suggested_src_address
        if src_address not in self._available_endpoints:
            if not self._available_endpoints:
                raise RuntimeError(
                    "Depleted pool of SID endpoints for this device!")
            else:
                src_address = self._available_endpoints[0]
        sid = SID(src_address << 16 | dst_address)
        # Note: This SID may change its source address!
        self.log.trace(
            "request_xport(dst=0x%04X, suggested_src_address=0x%04X, xport_type=%s): " \
            "operating on temporary SID: %s",
            dst_address, suggested_src_address, str(xport_type), str(sid))
        # FIXME token!
        assert self.mboard_info['rpc_connection'] in ('remote', 'local')
        if self.mboard_info['rpc_connection'] == 'remote':
            return self._xport_mgrs['udp'].request_xport(
                sid,
                xport_type,
            )
        elif self.mboard_info['rpc_connection'] == 'local':
            return self._xport_mgrs['liberio'].request_xport(
                sid,
                xport_type,
            )

    def commit_xport(self, xport_info):
        """
        See PeriphManagerBase.commit_xport() for docs.

        Reminder: All connections are incoming, i.e. "send" or "TX" means
        remote device to local device, and "receive" or "RX" means this local
        device to remote device. "Remote device" can be, for example, a UHD
        session.
        """
        ## Go, go, go
        assert self.mboard_info['rpc_connection'] in ('remote', 'local')
        sid = SID(xport_info['send_sid'])
        self._available_endpoints.remove(sid.src_ep)
        self.log.debug("Committing transport for SID %s, xport info: %s",
                       str(sid), str(xport_info))
        if self.mboard_info['rpc_connection'] == 'remote':
            return self._xport_mgrs['udp'].commit_xport(sid, xport_info)
        elif self.mboard_info['rpc_connection'] == 'local':
            return self._xport_mgrs['liberio'].commit_xport(sid, xport_info)

    ###########################################################################
    # Device info
    ###########################################################################
    def get_device_info_dyn(self):
        """
        Append the device info with current IP addresses.
        """
        if not self._device_initialized:
            return {}
        device_info = self._xport_mgrs['udp'].get_xport_info()
        device_info.update({
            'fpga_version': "{}.{}".format(
                *self.mboard_regs_control.get_compat_number()),
            'fpga': self.updateable_components.get('fpga', {}).get('type',""),
        })
        return device_info

    ###########################################################################
    # Clock/Time API
    ###########################################################################
    def get_clock_sources(self):
        " Lists all available clock sources. "
        self.log.trace("Listing available clock sources...")
        return ('external', 'internal', 'gpsdo')

    def get_clock_source(self):
        " Returns the currently selected clock source "
        return self._clock_source

    def set_clock_source(self, *args):
        """
        Switch reference clock.

        Throws if clock_source is not a valid value.
        """
        clock_source = args[0]
        assert clock_source in self.get_clock_sources()
        self.log.debug("Setting clock source to `{}'".format(clock_source))
        if clock_source == self.get_clock_source():
            self.log.trace("Nothing to do -- clock source already set.")
            return
        self._clock_source = clock_source
        ref_clk_freq = self.get_ref_clock_freq()
        self.mboard_regs_control.set_clock_source(clock_source, ref_clk_freq)
        self.log.debug("Reference clock frequency is: {} MHz".format(
            ref_clk_freq/1e6
        ))
        self.dboard.update_ref_clock_freq(ref_clk_freq)

    def set_ref_clock_freq(self, freq):
        """
        Tell our USRP what the frequency of the external reference clock is.

        Will throw if it's not a valid value.
        """
        # Other frequencies have not been tested
        assert freq in (10e6, 20e6)
        self.log.debug("We've been told the external reference clock " \
                       "frequency is {} MHz.".format(freq / 1e6))
        if self._ext_clock_freq == freq:
            self.log.trace("New external reference clock frequency " \
                           "assignment matches previous assignment. Ignoring " \
                           "update command.")
            return
        self._ext_clock_freq = freq
        if self.get_clock_source() == 'external':
            for slot, dboard in enumerate(self.dboards):
                if hasattr(dboard, 'update_ref_clock_freq'):
                    self.log.trace(
                        "Updating reference clock on dboard %d to %f MHz...",
                        slot, freq/1e6
                    )
                    dboard.update_ref_clock_freq(freq)


    def get_ref_clock_freq(self):
        " Returns the currently active reference clock frequency"
        clock_source = self.get_clock_source()
        if clock_source == "internal" or clock_source == "gpsdo":
            return E320_DEFAULT_INT_CLOCK_FREQ
        elif clock_source == "external":
            return self._ext_clock_freq

    def get_time_sources(self):
        " Returns list of valid time sources "
        return ['internal', 'external', 'gpsdo']

    def get_time_source(self):
        " Return the currently selected time source "
        return self._time_source

    def set_time_source(self, time_source):
        " Set a time source "
        assert time_source in self.get_time_sources()
        if time_source == self.get_time_source():
            self.log.trace("Nothing to do -- time source already set.")
            return
        self._time_source = time_source
        self.mboard_regs_control.set_time_source(time_source, self.get_ref_clock_freq())

    ###########################################################################
    # Hardware peripheral controls
    ###########################################################################

    def set_fp_gpio_master(self, value):
        """set driver for front panel GPIO
        Arguments:
            value {unsigned} -- value is a single bit bit mask of 12 pins GPIO
        """
        self.mboard_regs_control.set_fp_gpio_master(value)

    def get_fp_gpio_master(self):
        """get "who" is driving front panel gpio
           The return value is a bit mask of 8 pins GPIO.
           0: means the pin is driven by PL
           1: means the pin is driven by PS
        """
        return self.mboard_regs_control.get_fp_gpio_master()

    def set_fp_gpio_radio_src(self, value):
        """set driver for front panel GPIO
        Arguments:
            value {unsigned} -- value is 2-bit bit mask of 8 pins GPIO
           00: means the pin is driven by radio 0
           01: means the pin is driven by radio 1
        """
        self.mboard_regs_control.set_fp_gpio_radio_src(value)

    def get_fp_gpio_radio_src(self):
        """get which radio is driving front panel gpio
           The return value is 2-bit bit mask of 8 pins GPIO.
           00: means the pin is driven by radio 0
           01: means the pin is driven by radio 1
        """
        return self.mboard_regs_control.get_fp_gpio_radio_src()

    def enable_gps(self, enable):
        """
        Turn power to the GPS (CLK_GPS_PWR_EN) off or on.
        """
        self.mboard_regs_control.enable_gps(enable)

    def enable_fp_gpio(self, enable):
        """
        Turn power to the front panel GPIO off or on and set voltage
        to 3.3V.
        """
        self.log.trace("{} power to front-panel GPIO".format(
            "Enabling" if enable else "Disabling"
        ))
        self.mboard_regs_control.enable_fp_gpio(enable)

    def set_fp_gpio_voltage(self, value):
        """
        Set Front Panel GPIO voltage (3.3 Volts)
        """
        self.log.trace("Setting front-panel GPIO voltage to {:3.1f} V".format(value))
        self.mboard_regs_control.set_fp_gpio_voltage(value)

    def get_fp_gpio_voltage(self):
        """
        Get Front Panel GPIO voltage (1.8, 2.5 or 3.3 Volts)
        """
        value = self.mboard_regs_control.get_fp_gpio_voltage()
        self.log.trace("Current front-panel GPIO voltage {:3.1f} V".format(value))
        return value

    def set_channel_mode(self, channel_mode):
        "Set channel mode in FPGA and select which tx channel to use"
        self.mboard_regs_control.set_channel_mode(channel_mode)

    ###########################################################################
    # Sensors
    ###########################################################################
    def get_ref_lock_sensor(self):
        """
        Get refclk lock from CLK_MUX_OUT signal from ADF4002
        """
        self.log.trace("Querying ref lock status from adf4002.")
        lock_status = self.mboard_regs_control.get_refclk_lock()
        return {
            'name': 'ref_locked',
            'type': 'BOOLEAN',
            'unit': 'locked' if lock_status else 'unlocked',
            'value': str(lock_status).lower(),
        }

    def get_temp_sensor(self, sensor_name):
        """
        Get temperature sensor reading of the E320.
        """
        temp_sensor_map = {
            "temp_internal" : 0,
            "temp_rf_channelA" : 1,
            "temp_fpga" : 2,
            "temp_rf_channelB" : 3,
            "temp_main_power" : 4
        }
        self.log.trace("Reading temperature.")
        return_val = '-1'
        sensor = temp_sensor_map[sensor_name]
        try:
            raw_val = read_thermal_sensors_value('cros-ec-thermal', 'temp')[sensor]
            return_val = str(raw_val / 1000)
        except ValueError:
            self.log.warning("Error when converting temperature value")
        except KeyError:
            self.log.warning("Can't read temp on thermal_zone".format(sensor))
        return {
            'name': sensor_name,
            'type': 'REALNUM',
            'unit': 'C',
            'value': return_val
        }

    def get_gps_lock_sensor(self):
        """
        Get lock status of GPS as a sensor dict
        """
        gps_locked = bool(self.mboard_regs_control.get_gps_locked_val())
        return {
            'name': 'gps_lock',
            'type': 'BOOLEAN',
            'unit': 'locked' if gps_locked else 'unlocked',
            'value': str(gps_locked).lower(),
        }

    def get_fan_sensor(self):
        """
        Return a sensor dictionary containing the RPM of the cooling device/fan0
        """
        self.log.trace("Reading cooling device.")
        return_val = '-1'
        try:
            raw_val = read_thermal_sensor_value('Fan', 'cur_state')
            return_val = str(raw_val)
        except ValueError:
            self.log.warning("Error when converting fan speed value")
        except KeyError:
            self.log.warning("Can't read cur_state on Fan")
        return {
            'name': 'cooling fan',
            'unit': 'rpm',
            'type': 'INTEGER',
            'value': return_val
        }

    ###########################################################################
    # EEPROMs
    ###########################################################################
    def get_mb_eeprom(self):
        """
        Return a dictionary with EEPROM contents.

        All key/value pairs are string -> string.

        We don't actually return the EEPROM contents, instead, we return the
        mboard info again. This filters the EEPROM contents to what we think
        the user wants to know/see.
        """
        return self.mboard_info

    def set_mb_eeprom(self, eeprom_vals):
        """
        See PeriphManagerBase.set_mb_eeprom() for docs.
        """
        self.log.warn("Called set_mb_eeprom(), but not implemented!")
        raise NotImplementedError

    def get_db_eeprom(self, dboard_idx):
        """
        See PeriphManagerBase.get_db_eeprom() for docs.
        """
        if dboard_idx != E320_DBOARD_SLOT_IDX:
            self.log.warn("Trying to access invalid dboard index {}. "
                          "Using the only dboard.".format(dboard_idx))
        db_eeprom_data = copy.copy(self.dboard.device_info)
        for blob_id, blob in iteritems(self.dboard.get_user_eeprom_data()):
            if blob_id in db_eeprom_data:
                self.log.warn("EEPROM user data contains invalid blob ID "
                              "%s", blob_id)
            else:
                db_eeprom_data[blob_id] = blob
        return db_eeprom_data

    def set_db_eeprom(self, dboard_idx, eeprom_data):
        """
        Write new EEPROM contents with eeprom_map.

        Arguments:
        dboard_idx -- Slot index of dboard (can only be E320_DBOARD_SLOT_IDX)
        eeprom_data -- Dictionary of EEPROM data to be written. It's up to the
                       specific device implementation on how to handle it.
        """
        if dboard_idx != E320_DBOARD_SLOT_IDX:
            self.log.warn("Trying to access invalid dboard index {}. "
                          "Using the only dboard.".format(dboard_idx))
        safe_db_eeprom_user_data = {}
        for blob_id, blob in iteritems(eeprom_data):
            if blob_id in self.dboard.device_info:
                error_msg = "Trying to overwrite read-only EEPROM " \
                            "entry `{}'!".format(blob_id)
                self.log.error(error_msg)
                raise RuntimeError(error_msg)
            if not isinstance(blob, str) and not isinstance(blob, bytes):
                error_msg = "Blob data for ID `{}' is not a " \
                            "string!".format(blob_id)
                self.log.error(error_msg)
                raise RuntimeError(error_msg)
            assert isinstance(blob, str)
            safe_db_eeprom_user_data[blob_id] = blob.encode('ascii')
        self.dboard.set_user_eeprom_data(safe_db_eeprom_user_data)

    ###########################################################################
    # Component updating
    ###########################################################################
    # Note: Component updating functions defined by ZynqComponents
    @no_rpc
    def _update_fpga_type(self):
        """Update the fpga type stored in the updateable components"""
        fpga_type = self.mboard_regs_control.get_fpga_type()
        self.log.debug("Updating mboard FPGA type info to {}".format(fpga_type))
        self.updateable_components['fpga']['type'] = fpga_type
Ejemplo n.º 5
0
class X4xxGPSMgr:
    """
    Manager class for GPS-related actions for the X4XX.

    This also "disables" the sensors when the GPS is not enabled.
    """
    def __init__(self, clk_aux_board, log):
        assert clk_aux_board and clk_aux_board.is_gps_supported()
        self._clocking_auxbrd = clk_aux_board
        self.log = log.getChild('GPS')
        self.log.trace("Initializing GPSd interface")
        self._gpsd = GPSDIfaceExtension()
        # To disable sensors, we simply return an empty value if GPS is disabled.
        # For TPV, SKY, and GPGGA, we can do this in the same fashion (they are
        # very similar). gps_time is different (it returns an int) so for sake
        # of simplicity it's defined separately below.
        for sensor_name in ('gps_tpv', 'gps_sky', 'gps_gpgga'):
            sensor_api = f'get_{sensor_name}_sensor'
            setattr(
                self, sensor_api,
                lambda sensor_name=sensor_name: {
                    'name': sensor_name, 'type': 'STRING',
                    'unit': '', 'value': 'n/a'} \
                if not self.is_gps_enabled() \
                else getattr(self._gpsd, f'get_{sensor_name}_sensor')()
            )

    def extend(self, context):
        """
        Extend 'context' with the sensor methods of this class (get_gps_*_sensor).
        If 'context' already has such a method, it is skipped.

        Returns a dictionary compatible to mboard_sensor_callback_map.
        """
        new_methods = {
            re.search(r"get_(.*)_sensor", method_name).group(1): method_name
            for method_name in dir(self)
            if not method_name.startswith('_') \
            and callable(getattr(self, method_name)) \
            and method_name.endswith("sensor")}
        for method_name in new_methods.values():
            if hasattr(context, method_name):
                continue
            new_method = getattr(self, method_name)
            self.log.trace("%s: Adding %s method", context, method_name)
            setattr(context, method_name, new_method)
        return new_methods

    def is_gps_enabled(self):
        """
        Return True if the GPS is enabled/active.
        """
        return self._clocking_auxbrd.is_gps_enabled()

    def get_gps_enabled_sensor(self):
        """
        Get enabled status of GPS as a sensor dict
        """
        gps_enabled = self.is_gps_enabled()
        return {
            'name': 'gps_enabled',
            'type': 'BOOLEAN',
            'unit': 'enabled' if gps_enabled else 'disabled',
            'value': str(gps_enabled).lower(),
        }

    def get_gps_locked_sensor(self):
        """
        Get lock status of GPS as a sensor dict
        """
        gps_locked = self.is_gps_enabled() and \
                bool(self._clocking_auxbrd.get_gps_lock())
        return {
            'name': 'gps_lock',
            'type': 'BOOLEAN',
            'unit': 'locked' if gps_locked else 'unlocked',
            'value': str(gps_locked).lower(),
        }

    def get_gps_alarm_sensor(self):
        """
        Get alarm status of GPS as a sensor dict
        """
        gps_alarm = self.is_gps_enabled() and \
                bool(self._clocking_auxbrd.get_gps_alarm())
        return {
            'name': 'gps_alarm',
            'type': 'BOOLEAN',
            'unit': 'active' if gps_alarm else 'not active',
            'value': str(gps_alarm).lower(),
        }

    def get_gps_warmup_sensor(self):
        """
        Get warmup status of GPS as a sensor dict
        """
        gps_warmup = self.is_gps_enabled() and \
                bool(self._clocking_auxbrd.get_gps_warmup())
        return {
            'name': 'gps_warmup',
            'type': 'BOOLEAN',
            'unit': 'warming up' if gps_warmup else 'warmup done',
            'value': str(gps_warmup).lower(),
        }

    def get_gps_survey_sensor(self):
        """
        Get survey status of GPS as a sensor dict
        """
        gps_survey = self.is_gps_enabled() and \
                bool(self._clocking_auxbrd.get_gps_survey())
        return {
            'name': 'gps_survey',
            'type': 'BOOLEAN',
            'unit': 'survey active' if gps_survey else 'survey not active',
            'value': str(gps_survey).lower(),
        }

    def get_gps_phase_lock_sensor(self):
        """
        Get phase_lock status of GPS as a sensor dict
        """
        gps_phase_lock = self.is_gps_enabled() and \
                bool(self._clocking_auxbrd.get_gps_phase_lock())
        return {
            'name': 'gps_phase_lock',
            'type': 'BOOLEAN',
            'unit': 'phase locked' if gps_phase_lock else 'no phase lock',
            'value': str(gps_phase_lock).lower(),
        }

    def get_gps_time_sensor(self):
        """
        Get GPS time in integer seconds as a sensor dict
        """
        if not self.is_gps_enabled():
            return {
                'name': 'gps_time',
                'type': 'INTEGER',
                'unit': 'seconds',
                'value': str(-1),
            }
        return self._gpsd.get_gps_time_sensor()
Ejemplo n.º 6
0
Archivo: e320.py Proyecto: zwm152/uhd
class e320(ZynqComponents, PeriphManagerBase):
    """
    Holds E320 specific attributes and methods
    """
    #########################################################################
    # Overridables
    #
    # See PeriphManagerBase for documentation on these fields
    #########################################################################
    description = "E300-Series Device"
    pids = {0xe320: 'e320'}
    mboard_eeprom_addr = "e0004000.i2c"
    mboard_eeprom_offset = 0
    mboard_eeprom_max_len = 256
    mboard_info = {"type": "e3xx", "product": "e320"}
    mboard_max_rev = 4  # rev E
    mboard_sensor_callback_map = {
        'ref_locked': 'get_ref_lock_sensor',
        'gps_locked': 'get_gps_lock_sensor',
        'fan': 'get_fan_sensor',
        'temp_fpga': 'get_fpga_temp_sensor',
        'temp_internal': 'get_internal_temp_sensor',
        'temp_rf_channelA': 'get_rf_channelA_temp_sensor',
        'temp_rf_channelB': 'get_rf_channelB_temp_sensor',
        'temp_main_power': 'get_main_power_temp_sensor',
    }
    max_num_dboards = 1

    # We're on a Zynq target, so the following two come from the Zynq standard
    # device tree overlay (tree/arch/arm/boot/dts/zynq-7000.dtsi)
    dboard_spimaster_addrs = ["e0006000.spi", "e0007000.spi"]
    # E320-specific settings
    # Label for the mboard UIO
    mboard_regs_label = "mboard-regs"
    # Override the list of updateable components
    updateable_components = {
        'fpga': {
            'callback': "update_fpga",
            'path': '/lib/firmware/{}.bin',
            'reset': True,
        },
        'dts': {
            'callback': "update_dts",
            'path': '/lib/firmware/{}.dts',
            'output': '/lib/firmware/{}.dtbo',
            'reset': False,
        },
    }

    @staticmethod
    def list_required_dt_overlays(device_info):
        """
        Lists device tree overlays that need to be applied before this class can
        be used. List of strings.
        Are applied in order.

        eeprom_md -- Dictionary of info read out from the mboard EEPROM
        device_args -- Arbitrary dictionary of info, typically user-defined
        """
        return [device_info['product']]

    ###########################################################################
    # Ctor and device initialization tasks
    ###########################################################################
    def __init__(self, args):
        super(e320, self).__init__()
        self.overlay_apply()
        self.init_dboards(args)
        if not self._device_initialized:
            # Don't try and figure out what's going on. Just give up.
            return
        self._tear_down = False
        self._status_monitor_thread = None
        self._ext_clock_freq = E320_DEFAULT_EXT_CLOCK_FREQ
        self._clock_source = None
        self._time_source = None
        self._gpsd = None
        self.dboard = self.dboards[E320_DBOARD_SLOT_IDX]
        from functools import partial
        for sensor_name, sensor_cb_name in self.mboard_sensor_callback_map.items(
        ):
            if sensor_name[:5] == 'temp_':
                setattr(self, sensor_cb_name,
                        partial(self.get_temp_sensor, sensor_name))
        try:
            self._init_peripherals(args)
        except BaseException as ex:
            self.log.error("Failed to initialize motherboard: %s", str(ex))
            self._initialization_status = str(ex)
            self._device_initialized = False

    def _init_dboards(self, _, override_dboard_pids, default_args):
        """
        Initialize all the daughterboards

        (dboard_infos) -- N/A
        override_dboard_pids -- List of dboard PIDs to force
        default_args -- Default args
        """
        # Override the base class's implementation in order to avoid initializing our one "dboard"
        # in the same way that, for example, N310's dboards are initialized. Specifically,
        # - skip dboard EEPROM setup (we don't have one)
        # - change the way we handle SPI devices
        if override_dboard_pids:
            self.log.warning("Overriding daughterboard PIDs with: {}".format(
                override_dboard_pids))
            raise NotImplementedError("Can't override dboard pids")
        # The DBoard PID is the same as the MBoard PID
        db_pid = list(self.pids.keys())[0]
        # Set up the SPI nodes
        spi_nodes = []
        for spi_addr in self.dboard_spimaster_addrs:
            for spi_node in get_spidev_nodes(spi_addr):
                bisect.insort(spi_nodes, spi_node)
        self.log.trace("Found spidev nodes: {0}".format(spi_nodes))

        if not spi_nodes:
            self.log.warning("No SPI nodes for dboard %d.",
                             E320_DBOARD_SLOT_IDX)
        dboard_info = {
            'eeprom_md': self.mboard_info,
            'eeprom_rawdata': self._eeprom_rawdata,
            'pid': db_pid,
            'spi_nodes': spi_nodes,
            'default_args': default_args,
        }
        # This will actually instantiate the dboard class:
        self.dboards.append(Neon(E320_DBOARD_SLOT_IDX, **dboard_info))
        self.log.info("Found %d daughterboard(s).", len(self.dboards))

    def _check_fpga_compat(self):
        " Throw an exception if the compat numbers don't match up "
        actual_compat = self.mboard_regs_control.get_compat_number()
        self.log.debug("Actual FPGA compat number: {:d}.{:d}".format(
            actual_compat[0], actual_compat[1]))
        assert_compat_number(E320_FPGA_COMPAT,
                             self.mboard_regs_control.get_compat_number(),
                             component="FPGA",
                             fail_on_old_minor=True,
                             log=self.log)

    def _init_ref_clock_and_time(self, default_args):
        """
        Initialize clock and time sources. After this function returns, the
        reference signals going to the FPGA are valid.
        """
        self._ext_clock_freq = float(
            default_args.get('ext_clock_freq', E320_DEFAULT_EXT_CLOCK_FREQ))
        if not self.dboards:
            self.log.warning(
                "No dboards found, skipping setting clock and time source "
                "configuration.")
            self._clock_source = E320_DEFAULT_CLOCK_SOURCE
            self._time_source = E320_DEFAULT_TIME_SOURCE
        else:
            self.set_clock_source(
                default_args.get('clock_source', E320_DEFAULT_CLOCK_SOURCE))
            self.set_time_source(
                default_args.get('time_source', E320_DEFAULT_TIME_SOURCE))

    def _monitor_status(self):
        """
        Status monitoring thread: This should be executed in a thread. It will
        continuously monitor status of the following peripherals:

        - GPS lock
        """
        self.log.trace("Launching monitor loop...")
        cond = threading.Condition()
        cond.acquire()
        while not self._tear_down:
            gps_locked = self.get_gps_lock_sensor()['value'] == 'true'
            # Now wait
            if cond.wait_for(lambda: self._tear_down,
                             E320_MONITOR_THREAD_INTERVAL):
                break
        cond.release()
        self.log.trace("Terminating monitor loop.")

    def _init_peripherals(self, args):
        """
        Turn on all peripherals. This may throw an error on failure, so make
        sure to catch it.

        Peripherals are initialized in the order of least likely to fail, to most
        likely.
        """
        # Sanity checks
        assert self.mboard_info.get('product') in self.pids.values(), \
            "Device product could not be determined!"
        # Init Mboard Regs
        self.mboard_regs_control = MboardRegsControl(self.mboard_regs_label,
                                                     self.log)
        self.mboard_regs_control.get_git_hash()
        self.mboard_regs_control.get_build_timestamp()
        self._check_fpga_compat()
        self._update_fpga_type()
        # Init peripherals
        self.enable_gps(
            enable=str2bool(args.get('enable_gps', E320_DEFAULT_ENABLE_GPS)))
        self.enable_fp_gpio(
            enable=args.get('enable_fp_gpio', E320_DEFAULT_ENABLE_FPGPIO))
        # Init clocking
        self._init_ref_clock_and_time(args)
        # Init GPSd iface and GPS sensors
        self._init_gps_sensors()
        # Init CHDR transports
        self._xport_mgrs = {
            'udp': E320XportMgrUDP(self.log, args),
            'liberio': E320XportMgrLiberio(self.log),
        }
        # Spawn status monitoring thread
        self.log.trace("Spawning status monitor thread...")
        self._status_monitor_thread = threading.Thread(
            target=self._monitor_status,
            name="E320StatusMonitorThread",
            daemon=True,
        )
        self._status_monitor_thread.start()
        # Init complete.
        self.log.debug("mboard info: {}".format(self.mboard_info))

    def _init_gps_sensors(self):
        "Init and register the GPSd Iface and related sensor functions"
        self.log.trace("Initializing GPSd interface")
        self._gpsd = GPSDIfaceExtension()
        new_methods = self._gpsd.extend(self)
        for method_name in new_methods:
            try:
                # Extract the sensor name from the getter
                sensor_name = re.search(r"get_(.*)_sensor",
                                        method_name).group(1)
                # Register it with the MB sensor framework
                self.mboard_sensor_callback_map[sensor_name] = method_name
                self.log.trace("Adding %s sensor function", sensor_name)
            except AttributeError:
                # re.search will return None is if can't find the sensor name
                self.log.warning("Error while registering sensor function: %s",
                                 method_name)

    ###########################################################################
    # Session init and deinit
    ###########################################################################
    def init(self, args):
        """
        Calls init() on the parent class, and then programs the Ethernet
        dispatchers accordingly.
        """
        if not self._device_initialized:
            self.log.warning(
                "Cannot run init(), device was never fully initialized!")
            return False
        if args.get("clock_source", "") != "":
            self.set_clock_source(args.get("clock_source"))
        if args.get("time_source", "") != "":
            self.set_time_source(args.get("time_source"))
        result = super(e320, self).init(args)
        for xport_mgr in itervalues(self._xport_mgrs):
            xport_mgr.init(args)
        return result

    def deinit(self):
        """
        Clean up after a UHD session terminates.
        """
        if not self._device_initialized:
            self.log.warning(
                "Cannot run deinit(), device was never fully initialized!")
            return
        super(e320, self).deinit()
        for xport_mgr in itervalues(self._xport_mgrs):
            xport_mgr.deinit()

    def tear_down(self):
        """
        Tear down all members that need to be specially handled before
        deconstruction.
        For E320, this means the overlay.
        """
        self.log.trace("Tearing down E320 device...")
        self._tear_down = True
        if self._device_initialized:
            self._status_monitor_thread.join(3 * E320_MONITOR_THREAD_INTERVAL)
            if self._status_monitor_thread.is_alive():
                self.log.error(
                    "Could not terminate monitor thread! This could result in resource leaks."
                )
        active_overlays = self.list_active_overlays()
        self.log.trace(
            "E320 has active device tree overlays: {}".format(active_overlays))
        for overlay in active_overlays:
            dtoverlay.rm_overlay(overlay)

    ###########################################################################
    # Transport API
    ###########################################################################
    def get_chdr_link_types(self):
        """
        This will only ever return a single item (udp or liberio).
        """
        assert self.mboard_info['rpc_connection'] in ('remote', 'local')
        if self.mboard_info['rpc_connection'] == 'remote':
            return ["udp"]
        # else:
        return ["liberio"]

    def get_chdr_link_options(self, xport_type):
        """
        Returns a list of dictionaries. Every dictionary contains information
        about one way to connect to this device in order to initiate CHDR
        traffic.

        The interpretation of the return value is very highly dependant on the
        transport type (xport_type).
        For UDP, the every entry of the list has the following keys:
        - ipv4 (IP Address)
        - port (UDP port)
        - link_rate (bps of the link, e.g. 10e9 for 10GigE)

        For Liberio, every entry has the following keys:
        - tx_dev: TX device (/dev/tx-dma*)
        - rx_dev: RX device (/dev/rx-dma*)
        """
        if xport_type not in self._xport_mgrs:
            self.log.warning(
                "Can't get link options for unknown link type: `{}'.".format(
                    xport_type))
            return []
        return self._xport_mgrs[xport_type].get_chdr_link_options()

    ###########################################################################
    # Device info
    ###########################################################################
    def get_device_info_dyn(self):
        """
        Append the device info with current IP addresses.
        """
        if not self._device_initialized:
            return {}
        device_info = self._xport_mgrs['udp'].get_xport_info()
        device_info.update({
            'fpga_version':
            "{}.{}".format(*self.mboard_regs_control.get_compat_number()),
            'fpga_version_hash':
            "{:x}.{}".format(*self.mboard_regs_control.get_git_hash()),
            'fpga':
            self.updateable_components.get('fpga', {}).get('type', ""),
        })
        return device_info

    ###########################################################################
    # Clock/Time API
    ###########################################################################
    def get_clock_sources(self):
        " Lists all available clock sources. "
        self.log.trace("Listing available clock sources...")
        return ('external', 'internal', 'gpsdo')

    def get_clock_source(self):
        " Returns the currently selected clock source "
        return self._clock_source

    def set_clock_source(self, *args):
        """
        Switch reference clock.

        Throws if clock_source is not a valid value.
        """
        clock_source = args[0]
        assert clock_source in self.get_clock_sources()
        self.log.debug("Setting clock source to `{}'".format(clock_source))
        if clock_source == self.get_clock_source():
            self.log.trace("Nothing to do -- clock source already set.")
            return
        self._clock_source = clock_source
        ref_clk_freq = self.get_ref_clock_freq()
        self.mboard_regs_control.set_clock_source(clock_source, ref_clk_freq)
        self.log.debug("Reference clock frequency is: {} MHz".format(
            ref_clk_freq / 1e6))
        self.dboard.update_ref_clock_freq(ref_clk_freq)

    def set_ref_clock_freq(self, freq):
        """
        Tell our USRP what the frequency of the external reference clock is.

        Will throw if it's not a valid value.
        """
        # Other frequencies have not been tested
        assert freq in (10e6, 20e6)
        self.log.debug("We've been told the external reference clock " \
                       "frequency is {} MHz.".format(freq / 1e6))
        if self._ext_clock_freq == freq:
            self.log.trace("New external reference clock frequency " \
                           "assignment matches previous assignment. Ignoring " \
                           "update command.")
            return
        self._ext_clock_freq = freq
        if self.get_clock_source() == 'external':
            for slot, dboard in enumerate(self.dboards):
                if hasattr(dboard, 'update_ref_clock_freq'):
                    self.log.trace(
                        "Updating reference clock on dboard %d to %f MHz...",
                        slot, freq / 1e6)
                    dboard.update_ref_clock_freq(freq)

    def get_ref_clock_freq(self):
        " Returns the currently active reference clock frequency"
        clock_source = self.get_clock_source()
        if clock_source == "internal" or clock_source == "gpsdo":
            return E320_DEFAULT_INT_CLOCK_FREQ
        # elif clock_source == "external":
        return self._ext_clock_freq

    def get_time_sources(self):
        " Returns list of valid time sources "
        return ['internal', 'external', 'gpsdo']

    def get_time_source(self):
        " Return the currently selected time source "
        return self._time_source

    def set_time_source(self, time_source):
        " Set a time source "
        assert time_source in self.get_time_sources()
        if time_source == self.get_time_source():
            self.log.trace("Nothing to do -- time source already set.")
            return
        self._time_source = time_source
        self.mboard_regs_control.set_time_source(time_source,
                                                 self.get_ref_clock_freq())

    ###########################################################################
    # GPIO API
    ###########################################################################
    def get_gpio_banks(self):
        """
        Returns a list of GPIO banks over which MPM has any control
        """
        return E320_GPIO_BANKS

    def get_gpio_srcs(self, bank):
        """
        Return a list of valid GPIO sources for a given bank
        """
        assert bank in self.get_gpio_banks(), "Invalid GPIO bank: {}".format(
            bank)
        return E320_GPIO_SRCS

    def get_gpio_src(self, bank):
        """
        Return the currently selected GPIO source for a given bank. The return
        value is a list of strings. The length of the vector is identical to
        the number of controllable GPIO pins on this bank.
        """
        assert bank in self.get_gpio_banks(), "Invalid GPIO bank: {}".format(
            bank)
        gpio_master_reg = self.mboard_regs_control.get_fp_gpio_master()
        gpio_radio_src_reg = self.mboard_regs_control.get_fp_gpio_radio_src()

        def get_gpio_src_i(gpio_pin_index):
            """
            Return the current radio source given a pin index.
            """
            if gpio_master_reg & (1 << gpio_pin_index):
                return E320_GPIO_SRC_PS
            radio_src = (gpio_radio_src_reg >> (2 * gpio_pin_index)) & 0b11
            assert radio_src in (0, 1)
            return E320_GPIO_SRCS[radio_src]

        return [get_gpio_src_i(i) for i in range(E320_FPGPIO_WIDTH)]

    def set_gpio_src(self, bank, src):
        """
        Set the GPIO source for a given bank.
        """
        assert bank in self.get_gpio_banks(), "Invalid GPIO bank: {}".format(
            bank)
        assert len(src) == E320_FPGPIO_WIDTH, \
            "Invalid number of GPIO sources!"
        gpio_master_reg = 0x00
        gpio_radio_src_reg = self.mboard_regs_control.get_fp_gpio_radio_src()
        for src_index, src_name in enumerate(src):
            if src_name not in self.get_gpio_srcs(bank):
                raise RuntimeError(
                    "Invalid GPIO source name `{}' at bit position {}!".format(
                        src_name, src_index))
            gpio_master_flag = (src_name == E320_GPIO_SRC_PS)
            gpio_master_reg = gpio_master_reg | (gpio_master_flag << src_index)
            if gpio_master_flag:
                continue
            # If PS is not the master, we also need to update the radio source:
            radio_index = E320_GPIO_SRCS.index(src_name)
            gpio_radio_src_reg = gpio_radio_src_reg | (radio_index <<
                                                       (2 * src_index))
        self.log.trace(
            "Updating GPIO source: master==0x{:02X} radio_src={:04X}".format(
                gpio_master_reg, gpio_radio_src_reg))
        self.mboard_regs_control.set_fp_gpio_master(gpio_master_reg)
        self.mboard_regs_control.set_fp_gpio_radio_src(gpio_radio_src_reg)

    ###########################################################################
    # Hardware peripheral controls
    ###########################################################################
    def enable_gps(self, enable):
        """
        Turn power to the GPS (CLK_GPS_PWR_EN) off or on.
        """
        self.mboard_regs_control.enable_gps(enable)

    def enable_fp_gpio(self, enable):
        """
        Turn power to the front panel GPIO off or on and set voltage
        to 3.3V.
        """
        self.log.trace("{} power to front-panel GPIO".format(
            "Enabling" if enable else "Disabling"))
        self.mboard_regs_control.enable_fp_gpio(enable)

    def set_fp_gpio_voltage(self, value):
        """
        Set Front Panel GPIO voltage (3.3 Volts)
        """
        self.log.trace(
            "Setting front-panel GPIO voltage to {:3.1f} V".format(value))
        self.mboard_regs_control.set_fp_gpio_voltage(value)

    def get_fp_gpio_voltage(self):
        """
        Get Front Panel GPIO voltage (1.8, 2.5 or 3.3 Volts)
        """
        value = self.mboard_regs_control.get_fp_gpio_voltage()
        self.log.trace(
            "Current front-panel GPIO voltage {:3.1f} V".format(value))
        return value

    def set_channel_mode(self, channel_mode):
        "Set channel mode in FPGA and select which tx channel to use"
        self.mboard_regs_control.set_channel_mode(channel_mode)

    ###########################################################################
    # Sensors
    ###########################################################################
    def get_ref_lock_sensor(self):
        """
        Get refclk lock from CLK_MUX_OUT signal from ADF4002
        """
        self.log.trace("Querying ref lock status from adf4002.")
        lock_status = self.mboard_regs_control.get_refclk_lock()
        return {
            'name': 'ref_locked',
            'type': 'BOOLEAN',
            'unit': 'locked' if lock_status else 'unlocked',
            'value': str(lock_status).lower(),
        }

    def get_temp_sensor(self, sensor_name):
        """
        Get temperature sensor reading of the E320.
        """
        temp_sensor_map = {
            "temp_internal": 0,
            "temp_rf_channelA": 1,
            "temp_fpga": 2,
            "temp_rf_channelB": 3,
            "temp_main_power": 4
        }
        self.log.trace("Reading temperature.")
        return_val = '-1'
        sensor = temp_sensor_map[sensor_name]
        try:
            raw_val = read_thermal_sensors_value('cros-ec-thermal',
                                                 'temp')[sensor]
            return_val = str(raw_val / 1000)
        except ValueError:
            self.log.warning("Error when converting temperature value")
        except KeyError:
            self.log.warning(
                "Can't read temp on thermal_zone {}".format(sensor))
        return {
            'name': sensor_name,
            'type': 'REALNUM',
            'unit': 'C',
            'value': return_val
        }

    def get_gps_lock_sensor(self):
        """
        Get lock status of GPS as a sensor dict
        """
        gps_locked = bool(self.mboard_regs_control.get_gps_locked_val())
        return {
            'name': 'gps_lock',
            'type': 'BOOLEAN',
            'unit': 'locked' if gps_locked else 'unlocked',
            'value': str(gps_locked).lower(),
        }

    def get_fan_sensor(self):
        """
        Return a sensor dictionary containing the RPM of the cooling device/fan0
        """
        self.log.trace("Reading cooling device.")
        return_val = '-1'
        try:
            raw_val = read_thermal_sensor_value('Fan', 'cur_state')
            return_val = str(raw_val)
        except ValueError:
            self.log.warning("Error when converting fan speed value")
        except KeyError:
            self.log.warning("Can't read cur_state on Fan")
        return {
            'name': 'cooling fan',
            'unit': 'rpm',
            'type': 'INTEGER',
            'value': return_val
        }

    ###########################################################################
    # EEPROMs
    ###########################################################################
    def get_mb_eeprom(self):
        """
        Return a dictionary with EEPROM contents.

        All key/value pairs are string -> string.

        We don't actually return the EEPROM contents, instead, we return the
        mboard info again. This filters the EEPROM contents to what we think
        the user wants to know/see.
        """
        return self.mboard_info

    def set_mb_eeprom(self, eeprom_vals):
        """
        See PeriphManagerBase.set_mb_eeprom() for docs.
        """
        self.log.warn("Called set_mb_eeprom(), but not implemented!")
        raise NotImplementedError

    def get_db_eeprom(self, dboard_idx):
        """
        See PeriphManagerBase.get_db_eeprom() for docs.
        """
        if dboard_idx != E320_DBOARD_SLOT_IDX:
            self.log.warn("Trying to access invalid dboard index {}. "
                          "Using the only dboard.".format(dboard_idx))
        db_eeprom_data = copy.copy(self.dboard.device_info)
        for blob_id, blob in iteritems(self.dboard.get_user_eeprom_data()):
            if blob_id in db_eeprom_data:
                self.log.warn(
                    "EEPROM user data contains invalid blob ID "
                    "%s", blob_id)
            else:
                db_eeprom_data[blob_id] = blob
        return db_eeprom_data

    def set_db_eeprom(self, dboard_idx, eeprom_data):
        """
        Write new EEPROM contents with eeprom_map.

        Arguments:
        dboard_idx -- Slot index of dboard (can only be E320_DBOARD_SLOT_IDX)
        eeprom_data -- Dictionary of EEPROM data to be written. It's up to the
                       specific device implementation on how to handle it.
        """
        if dboard_idx != E320_DBOARD_SLOT_IDX:
            self.log.warn("Trying to access invalid dboard index {}. "
                          "Using the only dboard.".format(dboard_idx))
        safe_db_eeprom_user_data = {}
        for blob_id, blob in iteritems(eeprom_data):
            if blob_id in self.dboard.device_info:
                error_msg = "Trying to overwrite read-only EEPROM " \
                            "entry `{}'!".format(blob_id)
                self.log.error(error_msg)
                raise RuntimeError(error_msg)
            if not isinstance(blob, str) and not isinstance(blob, bytes):
                error_msg = "Blob data for ID `{}' is not a " \
                            "string!".format(blob_id)
                self.log.error(error_msg)
                raise RuntimeError(error_msg)
            assert isinstance(blob, str)
            safe_db_eeprom_user_data[blob_id] = blob.encode('ascii')
        self.dboard.set_user_eeprom_data(safe_db_eeprom_user_data)

    ###########################################################################
    # Component updating
    ###########################################################################
    # Note: Component updating functions defined by ZynqComponents
    @no_rpc
    def _update_fpga_type(self):
        """Update the fpga type stored in the updateable components"""
        fpga_type = self.mboard_regs_control.get_fpga_type()
        self.log.debug(
            "Updating mboard FPGA type info to {}".format(fpga_type))
        self.updateable_components['fpga']['type'] = fpga_type

    #######################################################################
    # Timekeeper API
    #######################################################################
    def get_clocks(self):
        """
        Gets the RFNoC-related clocks present in the FPGA design
        """
        return [{
            'name': 'radio_clk',
            'freq': str(self.dboard.get_master_clock_rate()),
            'mutable': 'true'
        }, {
            'name': 'bus_clk',
            'freq': str(200e6),
        }]
Ejemplo n.º 7
0
class n3xx(ZynqComponents, PeriphManagerBase):
    """
    Holds N3xx specific attributes and methods
    """
    # For every variant of the N3xx, add a line to the product map. If
    # it uses a new daughterboard, also import that PID from the dboard
    # manager class. The format of this map is:
    # (motherboard product code, (Slot-A DB PID, [Slot-B DB PID])) -> product
    product_map = {
        ('n300', tuple()):
        'n300',
        ('n300', (MG_PID, )):
        'n300',  # Slot B is empty
        ('n310', tuple()):
        'n310',
        ('n310', (MG_PID, MG_PID)):
        'n310',
        ('n310', (MG_PID, )):
        'n310',  # If Slot B is empty, we can
        # still use the n310.bin image.
        # We'll leave this here for
        # debugging purposes.
        ('n310', (EISCAT_PID, EISCAT_PID)):
        'eiscat',
        ('n310', (RHODIUM_PID, RHODIUM_PID)):
        'n320',
        ('n310', (RHODIUM_PID, )):
        'n320',
    }

    #########################################################################
    # Overridables
    #
    # See PeriphManagerBase for documentation on these fields
    #########################################################################
    description = "N300-Series Device"
    pids = {0x4242: 'n310', 0x4240: 'n300'}
    mboard_eeprom_addr = "e0005000.i2c"
    mboard_eeprom_offset = 0
    mboard_eeprom_max_len = 256
    mboard_info = {"type": "n3xx"}
    mboard_last_rev_compat = 5  # last known compat through dt_compat field
    mboard_sensor_callback_map = {
        'ref_locked': 'get_ref_lock_sensor',
        'gps_locked': 'get_gps_lock_sensor',
        'temp': 'get_temp_sensor',
        'fan': 'get_fan_sensor',
    }
    dboard_eeprom_addr = "e0004000.i2c"
    dboard_eeprom_offset = 0
    dboard_eeprom_max_len = 64

    # We're on a Zynq target, so the following two come from the Zynq standard
    # device tree overlay (tree/arch/arm/boot/dts/zynq-7000.dtsi)
    dboard_spimaster_addrs = ["e0006000.spi", "e0007000.spi"]
    # N3xx-specific settings
    # Label for the mboard UIO
    mboard_regs_label = "mboard-regs"
    # Label for the white rabbit UIO
    wr_regs_label = "wr-regs"
    # Override the list of updateable components
    updateable_components = {
        'fpga': {
            'callback': "update_fpga",
            'path': '/lib/firmware/{}.bin',
            'reset': True,
        },
        'dts': {
            'callback': "update_dts",
            'path': '/lib/firmware/{}.dts',
            'output': '/lib/firmware/{}.dtbo',
            'reset': False,
        },
    }

    #########################################################################
    # Others properties
    #########################################################################
    # All valid sync_sources for N3xx in the form of (clock_source, time_source)
    valid_sync_sources = {
        ('internal', 'internal'),
        ('internal', 'sfp0'),
        ('external', 'external'),
        ('external', 'internal'),
        ('gpsdo', 'gpsdo'),
    }

    @classmethod
    def generate_device_info(cls, eeprom_md, mboard_info, dboard_infos):
        """
        Hard-code our product map
        """
        # Add the default PeriphManagerBase information first
        device_info = super().generate_device_info(eeprom_md, mboard_info,
                                                   dboard_infos)
        # Then add N3xx-specific information
        mb_pid = eeprom_md.get('pid')
        lookup_key = (
            n3xx.pids.get(mb_pid, 'unknown'),
            tuple([x['pid'] for x in dboard_infos]),
        )
        device_info['product'] = cls.product_map.get(lookup_key, 'unknown')
        return device_info

    @staticmethod
    def list_required_dt_overlays(device_info):
        """
        Lists device tree overlays that need to be applied before this class can
        be used. List of strings.
        Are applied in order.

        eeprom_md -- Dictionary of info read out from the mboard EEPROM
        device_args -- Arbitrary dictionary of info, typically user-defined
        """
        # In the N3xx case, we name the dtbo file the same as the product.
        # N310 -> n310.dtbo, N300 -> n300.dtbo and so on.
        return [device_info['product']]

    ###########################################################################
    # Ctor and device initialization tasks
    ###########################################################################
    def __init__(self, args):
        self._tear_down = False
        self._status_monitor_thread = None
        self._ext_clock_freq = None
        self._clock_source = None
        self._time_source = None
        self._available_endpoints = list(range(256))
        self._bp_leds = None
        self._gpsd = None
        self._qsfp_retimer = None
        super(n3xx, self).__init__()
        try:
            # Init peripherals
            # these peripherals are specific to mboard and
            # need to configured before applying fpga overlay
            self._gpios = TCA6424(int(self.mboard_info['rev']))
            self.log.trace("Enabling power of MGT156MHZ clk")
            self._gpios.set("PWREN-CLK-MGT156MHz")
            self.enable_1g_ref_clock()
            self.enable_wr_ref_clock()
            self.enable_gps(enable=str2bool(
                args.get('enable_gps', N3XX_DEFAULT_ENABLE_GPS)))
            self.enable_fp_gpio(enable=str2bool(
                args.get('enable_fp_gpio', N3XX_DEFAULT_ENABLE_FPGPIO)))
            # Apply overlay
            self.overlay_apply()
            # Run dboards init
            self.init_dboards(args)
            if not self._device_initialized:
                # Don't try and figure out what's going on. Just give up.
                return
            self._init_peripherals(args)
        except Exception as ex:
            self.log.error("Failed to initialize motherboard: %s", str(ex))
            self._initialization_status = str(ex)
            self._device_initialized = False
        try:
            if not args.get('skip_boot_init', False):
                self.init(args)
        except Exception as ex:
            self.log.warning("Failed to initialize device on boot: %s",
                             str(ex))

    def _check_fpga_compat(self):
        " Throw an exception if the compat numbers don't match up "
        actual_compat = self.mboard_regs_control.get_compat_number()
        self.log.debug("Actual FPGA compat number: {:d}.{:d}".format(
            actual_compat[0], actual_compat[1]))
        assert_compat_number(N3XX_FPGA_COMPAT,
                             self.mboard_regs_control.get_compat_number(),
                             component="FPGA",
                             fail_on_old_minor=True,
                             log=self.log)

    def _init_ref_clock_and_time(self, default_args):
        """
        Initialize clock and time sources. After this function returns, the
        reference signals going to the FPGA are valid.
        """
        self._ext_clock_freq = float(
            default_args.get('ext_clock_freq', N3XX_DEFAULT_EXT_CLOCK_FREQ))
        if len(self.dboards) == 0:
            self.log.warning(
                "No dboards found, skipping setting clock and time source " \
                "configuration."
            )
            self._clock_source = N3XX_DEFAULT_CLOCK_SOURCE
            self._time_source = N3XX_DEFAULT_TIME_SOURCE
        else:
            self.set_sync_source({
                'clock_source':
                default_args.get('clock_source', N3XX_DEFAULT_CLOCK_SOURCE),
                'time_source':
                default_args.get('time_source', N3XX_DEFAULT_TIME_SOURCE)
            })

    def _init_meas_clock(self):
        """
        Initialize the TDC measurement clock. After this function returns, the
        FPGA TDC meas_clock is valid.
        """
        # No need to toggle reset here, simply confirm it is out of reset.
        self.mboard_regs_control.reset_meas_clk_mmcm(False)
        if not self.mboard_regs_control.get_meas_clock_mmcm_lock():
            raise RuntimeError("Measurement clock failed to init")

    def _monitor_status(self):
        """
        Status monitoring thread: This should be executed in a thread. It will
        continuously monitor status of the following peripherals:

        - GPS lock (update back-panel GPS LED)
        - REF lock (update back-panel REF LED)
        """
        self.log.trace("Launching monitor loop...")
        cond = threading.Condition()
        cond.acquire()
        while not self._tear_down:
            gps_locked = bool(self._gpios.get("GPS-LOCKOK"))
            self._bp_leds.set(self._bp_leds.LED_GPS, int(gps_locked))
            ref_locked = self.get_ref_lock_sensor()['value'] == 'true'
            self._bp_leds.set(self._bp_leds.LED_REF, int(ref_locked))
            # Now wait
            if cond.wait_for(lambda: self._tear_down,
                             N3XX_MONITOR_THREAD_INTERVAL):
                break
        cond.release()
        self.log.trace("Terminating monitor loop.")

    def _init_peripherals(self, args):
        """
        Turn on all peripherals. This may throw an error on failure, so make
        sure to catch it.

        Periphals are initialized in the order of least likely to fail, to most
        likely.
        """
        # Sanity checks
        assert self.device_info.get('product') in self.product_map.values(), \
                "Device product could not be determined!"
        self.log.trace("Initializing back panel LED controls...")
        self._bp_leds = BackpanelGPIO()
        # Init Mboard Regs
        self.mboard_regs_control = MboardRegsControl(self.mboard_regs_label,
                                                     self.log)
        self.mboard_regs_control.get_git_hash()
        self.mboard_regs_control.get_build_timestamp()
        self._check_fpga_compat()
        self.crossbar_base_port = self.mboard_regs_control.get_xbar_baseport()
        # Init clocking
        self.enable_ref_clock(enable=True)
        self._ext_clock_freq = None
        self._init_ref_clock_and_time(args)
        self._init_meas_clock()
        # Init GPSd iface and GPS sensors
        self._init_gps_sensors()
        # Init QSFP board (if available)
        qsfp_i2c = i2c_dev.of_get_i2c_adapter(N32X_QSFP_I2C_LABEL)
        if qsfp_i2c:
            self.log.debug("Creating QSFP Retimer control object...")
            self._qsfp_retimer = RetimerQSFP(qsfp_i2c)
            self._qsfp_retimer.set_rate_preset(N32X_DEFAULT_QSFP_RATE_PRESET)
            self._qsfp_retimer.set_driver_preset(
                N32X_DEFAULT_QSFP_DRIVER_PRESET)
        elif self.device_info['product'] == 'n320':
            self.log.info("No QSFP board detected: "
                          "Assuming it is disabled in the device tree overlay "
                          "(e.g., HG, XG images).")
        # Init FPGA type
        self._update_fpga_type()
        # Init CHDR transports
        self._xport_mgrs = {
            'udp': N3xxXportMgrUDP(self.log.getChild('UDP'), args),
            'liberio': N3xxXportMgrLiberio(self.log.getChild('liberio')),
        }
        # Spawn status monitoring thread
        self.log.trace("Spawning status monitor thread...")
        self._status_monitor_thread = threading.Thread(
            target=self._monitor_status,
            name="N3xxStatusMonitorThread",
            daemon=True,
        )
        self._status_monitor_thread.start()
        # Init complete.
        self.log.debug("Device info: {}".format(self.device_info))

    def _init_gps_sensors(self):
        "Init and register the GPSd Iface and related sensor functions"
        self.log.trace("Initializing GPSd interface")
        self._gpsd = GPSDIfaceExtension()
        new_methods = self._gpsd.extend(self)
        for method_name in new_methods:
            try:
                # Extract the sensor name from the getter
                sensor_name = re.search(r"get_(.*)_sensor",
                                        method_name).group(1)
                # Register it with the MB sensor framework
                self.mboard_sensor_callback_map[sensor_name] = method_name
                self.log.trace("Adding %s sensor function", sensor_name)
            except AttributeError:
                # re.search will return None is if can't find the sensor name
                self.log.warning("Error while registering sensor function: %s",
                                 method_name)

    ###########################################################################
    # Session init and deinit
    ###########################################################################
    def init(self, args):
        """
        Calls init() on the parent class, and then programs the Ethernet
        dispatchers accordingly.
        """
        if not self._device_initialized:
            self.log.error(
                "Cannot run init(), device was never fully initialized!")
            return False
        # We need to disable the PPS out during clock and dboard initialization in order
        # to avoid glitches.
        self.enable_pps_out(False)
        # if there's no clock_source or time_source params, we added here since
        # dboards init procedures need them.
        # At this point, both the self._clock_source and self._time_source global
        # properties should have been set to either the default values (first time
        # init() is run); or to the previous configured values (updated after a
        # successful clocking configuration).
        args['clock_source'] = args.get('clock_source', self._clock_source)
        args['time_source'] = args.get('time_source', self._time_source)
        self.set_sync_source(args)
        # Uh oh, some hard coded product-related info: The N300 has no LO
        # source connectors on the front panel, so we assume that if this was
        # selected, it was an artifact from N310-related code. The user gets
        # a warning and the setting is reset to internal.
        if self.device_info.get('product') == 'n300':
            for lo_source in ('rx_lo_source', 'tx_lo_source'):
                if lo_source in args and args.get(lo_source) != 'internal':
                    self.log.warning("The N300 variant does not support "
                                     "external LOs! Setting to internal.")
                    args[lo_source] = 'internal'
        # Note: The parent class takes care of calling init() on all the
        # daughterboards
        result = super(n3xx, self).init(args)
        # Now the clocks are all enabled, we can also enable PPS export:
        self.enable_pps_out(
            args.get('pps_export', N3XX_DEFAULT_ENABLE_PPS_EXPORT))
        for xport_mgr in itervalues(self._xport_mgrs):
            xport_mgr.init(args)
        return result

    def deinit(self):
        """
        Clean up after a UHD session terminates.
        """
        if not self._device_initialized:
            self.log.warning(
                "Cannot run deinit(), device was never fully initialized!")
            return
        super(n3xx, self).deinit()
        for xport_mgr in itervalues(self._xport_mgrs):
            xport_mgr.deinit()
        self.log.trace("Resetting SID pool...")
        self._available_endpoints = list(range(256))

    def tear_down(self):
        """
        Tear down all members that need to be specially handled before
        deconstruction.
        For N3xx, this means the overlay.
        """
        self.log.trace("Tearing down N3xx device...")
        self._tear_down = True
        if self._device_initialized:
            self._status_monitor_thread.join(3 * N3XX_MONITOR_THREAD_INTERVAL)
            if self._status_monitor_thread.is_alive():
                self.log.error("Could not terminate monitor thread! "
                               "This could result in resource leaks.")
        active_overlays = self.list_active_overlays()
        self.log.trace(
            "N3xx has active device tree overlays: {}".format(active_overlays))
        for overlay in active_overlays:
            dtoverlay.rm_overlay(overlay)

    ###########################################################################
    # Transport API
    ###########################################################################
    def request_xport(self, dst_address, suggested_src_address, xport_type):
        """
        See PeriphManagerBase.request_xport() for docs.
        """
        # Try suggested address first, then just pick the first available one:
        src_address = suggested_src_address
        if src_address not in self._available_endpoints:
            if len(self._available_endpoints) == 0:
                raise RuntimeError(
                    "Depleted pool of SID endpoints for this device!")
            else:
                src_address = self._available_endpoints[0]
        sid = SID(src_address << 16 | dst_address)
        # Note: This SID may change its source address!
        self.log.trace(
            "request_xport(dst=0x%04X, suggested_src_address=0x%04X, xport_type=%s): " \
            "operating on temporary SID: %s",
            dst_address, suggested_src_address, str(xport_type), str(sid))
        # FIXME token!
        assert self.device_info['rpc_connection'] in ('remote', 'local')
        if self.device_info['rpc_connection'] == 'remote':
            if self.device_info['product'] == 'n320':
                alloc_limit = 1
            else:
                alloc_limit = 2
            return self._xport_mgrs['udp'].request_xport(
                sid, xport_type, alloc_limit)
        elif self.device_info['rpc_connection'] == 'local':
            return self._xport_mgrs['liberio'].request_xport(
                sid,
                xport_type,
            )

    def commit_xport(self, xport_info):
        """
        See PeriphManagerBase.commit_xport() for docs.

        Reminder: All connections are incoming, i.e. "send" or "TX" means
        remote device to local device, and "receive" or "RX" means this local
        device to remote device. "Remote device" can be, for example, a UHD
        session.
        """
        ## Go, go, go
        assert self.device_info['rpc_connection'] in ('remote', 'local')
        sid = SID(xport_info['send_sid'])
        self._available_endpoints.remove(sid.src_ep)
        self.log.debug("Committing transport for SID %s, xport info: %s",
                       str(sid), str(xport_info))
        if self.device_info['rpc_connection'] == 'remote':
            return self._xport_mgrs['udp'].commit_xport(sid, xport_info)
        elif self.device_info['rpc_connection'] == 'local':
            return self._xport_mgrs['liberio'].commit_xport(sid, xport_info)

    ###########################################################################
    # Device info
    ###########################################################################
    def get_device_info_dyn(self):
        """
        Append the device info with current IP addresses.
        """
        if not self._device_initialized:
            return {}
        device_info = self._xport_mgrs['udp'].get_xport_info()
        device_info.update({
            'fpga_version':
            "{}.{}".format(*self.mboard_regs_control.get_compat_number()),
            'fpga_version_hash':
            "{:x}.{}".format(*self.mboard_regs_control.get_git_hash()),
            'fpga':
            self.updateable_components.get('fpga', {}).get('type', ""),
        })
        return device_info

    ###########################################################################
    # Clock/Time API
    ###########################################################################
    def get_clock_sources(self):
        " Lists all available clock sources. "
        self.log.trace("Listing available clock sources...")
        return ('external', 'internal', 'gpsdo')

    def get_clock_source(self):
        " Returns the currently selected clock source "
        return self._clock_source

    def set_clock_source(self, *args):
        " Sets a new reference clock source "
        clock_source = args[0]
        time_source = self._time_source
        assert clock_source is not None
        assert time_source is not None
        if (clock_source, time_source) not in self.valid_sync_sources:
            if clock_source == 'internal':
                time_source = 'internal'
            elif clock_source == 'external':
                time_source = 'external'
            elif clock_source == 'gpsdo':
                time_source = 'gpsdo'
        source = {"clock_source": clock_source, "time_source": time_source}
        self.set_sync_source(source)

    def get_time_sources(self):
        " Returns list of valid time sources "
        return ['internal', 'external', 'gpsdo', 'sfp0']

    def get_time_source(self):
        " Return the currently selected time source "
        return self._time_source

    def set_time_source(self, time_source):
        " Set a time source "
        clock_source = self._clock_source
        assert clock_source != None
        assert time_source != None
        if (clock_source, time_source) not in self.valid_sync_sources:
            if time_source == 'sfp0':
                clock_source = 'internal'
            elif time_source == 'internal':
                clock_source = 'internal'
            elif time_source == 'external':
                clock_source = 'external'
            elif time_source == 'gpsdo':
                clock_source = 'gpsdo'
        source = {"time_source": time_source, "clock_source": clock_source}
        self.set_sync_source(source)

    def set_sync_source(self, args):
        """
        Selects reference clock and PPS sources. Unconditionally re-applies the time
        source to ensure continuity between the reference clock and time rates.
        """

        clock_source = args.get('clock_source', self._clock_source)
        assert clock_source in self.get_clock_sources()
        time_source = args.get('time_source', self._time_source)
        assert time_source in self.get_time_sources()
        if (clock_source == self._clock_source) and (time_source
                                                     == self._time_source):
            # Nothing change no need to do anything
            self.log.trace("New sync source assignment matches"
                           "previous assignment. Ignoring update command.")
            return
        assert (clock_source, time_source) in self.valid_sync_sources
        # Start setting sync source
        self.log.debug("Setting clock source to `{}'".format(clock_source))
        # Place the DB clocks in a safe state to allow reference clock
        # transitions. This leaves all the DB clocks OFF.
        for slot, dboard in enumerate(self.dboards):
            if hasattr(dboard, 'set_clk_safe_state'):
                self.log.trace(
                    "Setting dboard %d components to safe clocking state...",
                    slot)
                dboard.set_clk_safe_state()
        # Disable the Ref Clock in the FPGA before throwing the external switches.
        self.mboard_regs_control.enable_ref_clk(False)
        # Set the external switches to bring in the new source.
        if clock_source == 'internal':
            self._gpios.set("CLK-MAINSEL-EX_B")
            self._gpios.set("CLK-MAINSEL-25MHz")
            self._gpios.reset("CLK-MAINSEL-GPS")
        elif clock_source == 'gpsdo':
            self._gpios.set("CLK-MAINSEL-EX_B")
            self._gpios.reset("CLK-MAINSEL-25MHz")
            self._gpios.set("CLK-MAINSEL-GPS")
        else:  # external
            self._gpios.reset("CLK-MAINSEL-EX_B")
            self._gpios.reset("CLK-MAINSEL-GPS")
            # SKY13350 needs to be in known state
            self._gpios.set("CLK-MAINSEL-25MHz")
        self._clock_source = clock_source
        self.log.debug("Reference clock source is: {}" \
                       .format(self._clock_source))
        self.log.debug("Reference clock frequency is: {} MHz" \
                       .format(self.get_ref_clock_freq()/1e6))
        # Enable the Ref Clock in the FPGA after giving it a chance to
        # settle. The settling time is a guess.
        time.sleep(0.100)
        self.mboard_regs_control.enable_ref_clk(True)
        self.log.debug("Setting time source to `{}'".format(time_source))
        self._time_source = time_source
        ref_clk_freq = self.get_ref_clock_freq()
        self.mboard_regs_control.set_time_source(time_source, ref_clk_freq)
        if time_source == 'sfp0':
            # This error is specific to slave and master mode for White Rabbit.
            # Grand Master mode will require the external or gpsdo
            # sources (not supported).
            if time_source in ('sfp0', 'sfp1') \
                    and self.get_clock_source() != 'internal':
                error_msg = "Time source {} requires `internal` clock source!".format(
                    time_source)
                self.log.error(error_msg)
                raise RuntimeError(error_msg)
            sfp_time_source_images = ('WX', )
            if self.updateable_components['fpga'][
                    'type'] not in sfp_time_source_images:
                self.log.error("{} time source requires FPGA types {}" \
                               .format(time_source, sfp_time_source_images))
                raise RuntimeError("{} time source requires FPGA types {}" \
                               .format(time_source, sfp_time_source_images))
            # Only open UIO to the WR core once we're guaranteed it exists.
            wr_regs_control = WhiteRabbitRegsControl(self.wr_regs_label,
                                                     self.log)
            # Wait for time source to become ready. Only applies to SFP0/1. All other
            # targets start their PPS immediately.
            self.log.debug("Waiting for {} timebase to lock..." \
                           .format(time_source))
            if not poll_with_timeout(
                    lambda: wr_regs_control.get_time_lock_status(),
                    40000,  # Try for x ms... this number is set from a few benchtop tests
                    1000,  # Poll every... second! why not?
            ):
                self.log.error("{} timebase failed to lock within 40 seconds. Status: 0x{:X}" \
                               .format(time_source, wr_regs_control.get_time_lock_status()))
                raise RuntimeError("Failed to lock SFP timebase.")
        # Update the DB with the correct Ref Clock frequency and force a re-init.
        for slot, dboard in enumerate(self.dboards):
            self.log.trace(
                "Updating reference clock on dboard %d to %f MHz...", slot,
                ref_clk_freq / 1e6)
            dboard.update_ref_clock_freq(ref_clk_freq,
                                         time_source=time_source,
                                         clock_source=clock_source,
                                         skip_rfic=args.get('skip_rfic', None))

    def set_ref_clock_freq(self, freq):
        """
        Tell our USRP what the frequency of the external reference clock is.

        Will throw if it's not a valid value.
        """
        if freq not in (10e6, 20e6, 25e6):
            self.log.error("{} is not a supported external reference clock frequency!" \
                           .format(freq/1e6))
            raise RuntimeError("{} is not a supported external reference clock " \
                               "frequency!".format(freq/1e6))
        self.log.debug("We've been told the external reference clock " \
                       "frequency is now {} MHz.".format(freq/1e6))
        if self._ext_clock_freq == freq:
            self.log.trace("New external reference clock frequency " \
                           "assignment matches previous assignment. Ignoring " \
                           "update command.")
            return
        if (freq == 20e6) and (self.get_time_source() != 'external'):
            self.log.error("Setting the external reference clock to {} MHz is only " \
                           "allowed when using 'external' time_source. Set the " \
                           "time_source to 'external' first, and then set the new " \
                           "external clock rate.".format(freq/1e6))
            raise RuntimeError("Setting the external reference clock to {} MHz is " \
                               "only allowed when using 'external' time_source." \
                               .format(freq/1e6))
        self._ext_clock_freq = freq
        # If the external source is currently selected we also need to re-apply the
        # time_source. This call also updates the dboards' rates.
        if self.get_clock_source() == 'external':
            self.set_time_source(self.get_time_source())

    def get_ref_clock_freq(self):
        " Returns the currently active reference clock frequency"
        return {
            'internal': 25e6,
            'external': self._ext_clock_freq,
            'gpsdo': 20e6,
        }[self._clock_source]

    def set_fp_gpio_master(self, value):
        """set driver for front panel GPIO
        Arguments:
            value {unsigned} -- value is a single bit bit mask of 12 pins GPIO
        """
        self.mboard_regs_control.set_fp_gpio_master(value)

    def get_fp_gpio_master(self):
        """get "who" is driving front panel gpio
           The return value is a bit mask of 12 pins GPIO.
           0: means the pin is driven by PL
           1: means the pin is driven by PS
        """
        return self.mboard_regs_control.get_fp_gpio_master()

    def set_fp_gpio_radio_src(self, value):
        """set driver for front panel GPIO
        Arguments:
            value {unsigned} -- value is 2-bit bit mask of 12 pins GPIO
           00: means the pin is driven by radio 0
           01: means the pin is driven by radio 1
           10: means the pin is driven by radio 2
           11: means the pin is driven by radio 3
        """
        self.mboard_regs_control.set_fp_gpio_radio_src(value)

    def get_fp_gpio_radio_src(self):
        """get which radio is driving front panel gpio
           The return value is 2-bit bit mask of 12 pins GPIO.
           00: means the pin is driven by radio 0
           01: means the pin is driven by radio 1
           10: means the pin is driven by radio 2
           11: means the pin is driven by radio 3
        """
        return self.mboard_regs_control.get_fp_gpio_radio_src()

    ###########################################################################
    # Hardware periphal controls
    ###########################################################################
    def enable_pps_out(self, enable):
        " Export a PPS/Trigger to the back panel "
        self.mboard_regs_control.enable_pps_out(enable)

    def enable_gps(self, enable):
        """
        Turn power to the GPS off or on.
        """
        self.log.trace(
            "{} power to GPS".format("Enabling" if enable else "Disabling"))
        self._gpios.set("PWREN-GPS", int(bool(enable)))

    def enable_fp_gpio(self, enable):
        """
        Turn power to the front panel GPIO off or on.
        """
        self.log.trace("{} power to front-panel GPIO".format(
            "Enabling" if enable else "Disabling"))
        self._gpios.set("FPGA-GPIO-EN", int(bool(enable)))

    def enable_ref_clock(self, enable):
        """
        Enables the ref clock voltage (+3.3-MAINREF). Without setting this to
        True, *no* ref clock works.
        """
        self.log.trace("{} power to reference clocks".format(
            "Enabling" if enable else "Disabling"))
        self._gpios.set("PWREN-CLK-MAINREF", int(bool(enable)))

    def enable_1g_ref_clock(self):
        """
        Enables 125 MHz refclock for 1G interface.
        """
        self.log.trace("Enable 125 MHz Clock for 1G SFP interface.")
        self._gpios.set("NETCLK-CE", 1)
        self._gpios.set("NETCLK-RESETn", 0)
        self._gpios.set("NETCLK-PR0", 1)
        self._gpios.set("NETCLK-PR1", 1)
        self._gpios.set("NETCLK-OD0", 1)
        self._gpios.set("NETCLK-OD1", 1)
        self._gpios.set("NETCLK-OD2", 0)
        self._gpios.set("PWREN-CLK-WB-25MHz", 1)
        self.log.trace("Finished configuring NETCLK CDCM.")
        self._gpios.set("NETCLK-RESETn", 1)

    def enable_wr_ref_clock(self):
        """
        Enables 20 MHz WR refclk. Note that enable_1g_ref_clock() is also required for this
        interface to work, although calling it here is redundant.
        """
        self.log.trace("Enable White Rabbit reference clock.")
        self._gpios.set("PWREN-CLK-WB-20MHz", 1)

    ###########################################################################
    # Sensors
    # Note: GPS sensors are registered at runtime
    ###########################################################################
    def get_ref_lock_sensor(self):
        """
        The N3xx has no ref lock sensor, but because the ref lock is
        historically considered a motherboard-level sensor, we will return the
        combined lock status of all daughterboards. If no dboard is connected,
        or none has a ref lock sensor, we simply return True.
        """
        self.log.trace("Querying ref lock status from %d dboards.",
                       len(self.dboards))
        lock_status = all([
            not hasattr(db, 'get_ref_lock') or db.get_ref_lock()
            for db in self.dboards
        ])
        return {
            'name': 'ref_locked',
            'type': 'BOOLEAN',
            'unit': 'locked' if lock_status else 'unlocked',
            'value': str(lock_status).lower(),
        }

    def get_temp_sensor(self):
        """
        Get temperature sensor reading of the N3xx.
        """
        self.log.trace("Reading FPGA temperature.")
        return_val = '-1'
        try:
            raw_val = read_thermal_sensor_value('fpga-thermal-zone', 'temp')
            return_val = str(raw_val / 1000)
        except ValueError:
            self.log.warning("Error when converting temperature value")
        except KeyError:
            self.log.warning("Can't read temp on fpga-thermal-zone")
        return {
            'name': 'temperature',
            'type': 'REALNUM',
            'unit': 'C',
            'value': return_val
        }

    def get_fan_sensor(self):
        """
        Get cooling device reading of N3xx. In this case the speed of fan 0.
        """
        self.log.trace("Reading FPGA cooling device.")
        return_val = '-1'
        try:
            raw_val = read_thermal_sensor_value('ec-fan0', 'cur_state')
            return_val = str(raw_val)
        except ValueError:
            self.log.warning("Error when converting fan speed value")
        except KeyError:
            self.log.warning("Can't read cur_state on ec-fan0")
        return {
            'name': 'cooling fan',
            'type': 'INTEGER',
            'unit': 'rpm',
            'value': return_val
        }

    def get_gps_lock_sensor(self):
        """
        Get lock status of GPS as a sensor dict
        """
        self.log.trace("Reading status GPS lock pin from port expander")
        gps_locked = bool(self._gpios.get("GPS-LOCKOK"))
        return {
            'name': 'gps_lock',
            'type': 'BOOLEAN',
            'unit': 'locked' if gps_locked else 'unlocked',
            'value': str(gps_locked).lower(),
        }

    ###########################################################################
    # EEPROMs
    ###########################################################################
    def get_mb_eeprom(self):
        """
        Return a dictionary with EEPROM contents.

        All key/value pairs are string -> string.

        We don't actually return the EEPROM contents, instead, we return the
        mboard info again. This filters the EEPROM contents to what we think
        the user wants to know/see.
        """
        return self.mboard_info

    def set_mb_eeprom(self, eeprom_vals):
        """
        See PeriphManagerBase.set_mb_eeprom() for docs.
        """
        self.log.warn("Called set_mb_eeprom(), but not implemented!")
        raise NotImplementedError

    def get_db_eeprom(self, dboard_idx):
        """
        See PeriphManagerBase.get_db_eeprom() for docs.
        """
        try:
            dboard = self.dboards[dboard_idx]
        except KeyError:
            error_msg = "Attempted to access invalid dboard index `{}' " \
                        "in get_db_eeprom()!".format(dboard_idx)
            self.log.error(error_msg)
            raise RuntimeError(error_msg)
        db_eeprom_data = copy.copy(dboard.device_info)
        if hasattr(dboard, 'get_user_eeprom_data') and \
                callable(dboard.get_user_eeprom_data):
            for blob_id, blob in iteritems(dboard.get_user_eeprom_data()):
                if blob_id in db_eeprom_data:
                    self.log.warn("EEPROM user data contains invalid blob ID " \
                                  "%s", blob_id)
                else:
                    db_eeprom_data[blob_id] = blob
        return db_eeprom_data

    def set_db_eeprom(self, dboard_idx, eeprom_data):
        """
        Write new EEPROM contents with eeprom_map.

        Arguments:
        dboard_idx -- Slot index of dboard
        eeprom_data -- Dictionary of EEPROM data to be written. It's up to the
                       specific device implementation on how to handle it.
        """
        try:
            dboard = self.dboards[dboard_idx]
        except KeyError:
            error_msg = "Attempted to access invalid dboard index `{}' " \
                        "in set_db_eeprom()!".format(dboard_idx)
            self.log.error(error_msg)
            raise RuntimeError(error_msg)
        if not hasattr(dboard, 'set_user_eeprom_data') or \
                not callable(dboard.set_user_eeprom_data):
            error_msg = "Dboard has no set_user_eeprom_data() method!"
            self.log.error(error_msg)
            raise RuntimeError(error_msg)
        safe_db_eeprom_user_data = {}
        for blob_id, blob in iteritems(eeprom_data):
            if blob_id in dboard.device_info:
                error_msg = "Trying to overwrite read-only EEPROM " \
                            "entry `{}'!".format(blob_id)
                self.log.error(error_msg)
                raise RuntimeError(error_msg)
            if not isinstance(blob, str) and not isinstance(blob, bytes):
                error_msg = "Blob data for ID `{}' is not a " \
                            "string!".format(blob_id)
                self.log.error(error_msg)
                raise RuntimeError(error_msg)
            assert isinstance(blob, str)
            safe_db_eeprom_user_data[blob_id] = blob.encode('ascii')
        dboard.set_user_eeprom_data(safe_db_eeprom_user_data)

    ###########################################################################
    # Component updating
    ###########################################################################
    # Note: Component updating functions defined by ZynqComponents
    @no_rpc
    def _update_fpga_type(self):
        """Update the fpga type stored in the updateable components"""
        fpga_type = self.mboard_regs_control.get_fpga_type()
        # This is ugly, but we have no elegant way of probing QSFP capabilities
        # through the mboard regs object, so we simply hardcode the options:
        if self.device_info['product'] == 'n320' and self._qsfp_retimer:
            if fpga_type == "XG":
                fpga_type = "AQ"
            if fpga_type == "WX":
                fpga_type = "XQ"
        self.log.debug(
            "Updating mboard FPGA type info to {}".format(fpga_type))
        self.updateable_components['fpga']['type'] = fpga_type

    #######################################################################
    # Claimer API
    #######################################################################
    def claim(self):
        """
        This is called when the device is claimed, in case the device needs to
        run any actions on claiming (e.g., light up an LED).
        """
        if self._bp_leds is not None:
            # Light up LINK
            self._bp_leds.set(self._bp_leds.LED_LINK, 1)

    def unclaim(self):
        """
        This is called when the device is unclaimed, in case the device needs
        to run any actions on claiming (e.g., turn off an LED).
        """
        if self._bp_leds is not None:
            # Turn off LINK
            self._bp_leds.set(self._bp_leds.LED_LINK, 0)
Ejemplo n.º 8
0
class e320(ZynqComponents, PeriphManagerBase):
    """
    Holds E320 specific attributes and methods
    """
    #########################################################################
    # Overridables
    #
    # See PeriphManagerBase for documentation on these fields
    #########################################################################
    description = "E300-Series Device"
    pids = {0xe320: 'e320'}
    mboard_eeprom_addr = "e0004000.i2c"
    mboard_eeprom_offset = 0
    mboard_eeprom_max_len = 256
    mboard_info = {"type": "e3xx", "product": "e320"}
    mboard_max_rev = 2  # RevB
    mboard_sensor_callback_map = {
        'ref_locked': 'get_ref_lock_sensor',
        'gps_locked': 'get_gps_lock_sensor',
        'temp': 'get_temp_sensor',
        'fan': 'get_fan_sensor',
    }
    max_num_dboards = 1
    crossbar_base_port = 2  # It's 2 because 0,1 are SFP,DMA

    # We're on a Zynq target, so the following two come from the Zynq standard
    # device tree overlay (tree/arch/arm/boot/dts/zynq-7000.dtsi)
    dboard_spimaster_addrs = ["e0006000.spi", "e0007000.spi"]
    # E320-specific settings
    # Label for the mboard UIO
    mboard_regs_label = "mboard-regs"
    # Override the list of updateable components
    updateable_components = {
        'fpga': {
            'callback': "update_fpga",
            'path': '/lib/firmware/{}.bin',
            'reset': True,
        },
        'dts': {
            'callback': "update_dts",
            'path': '/lib/firmware/{}.dts',
            'output': '/lib/firmware/{}.dtbo',
            'reset': False,
        },
    }

    @staticmethod
    def list_required_dt_overlays(device_info):
        """
        Lists device tree overlays that need to be applied before this class can
        be used. List of strings.
        Are applied in order.

        eeprom_md -- Dictionary of info read out from the mboard EEPROM
        device_args -- Arbitrary dictionary of info, typically user-defined
        """
        return [device_info['product']]

    ###########################################################################
    # Ctor and device initialization tasks
    ###########################################################################
    def __init__(self, args):
        super(e320, self).__init__(args)
        if not self._device_initialized:
            # Don't try and figure out what's going on. Just give up.
            return
        self._tear_down = False
        self._status_monitor_thread = None
        self._ext_clock_freq = E320_DEFAULT_EXT_CLOCK_FREQ
        self._clock_source = None
        self._time_source = None
        self._available_endpoints = list(range(256))
        self._gpsd = None
        self.dboard = self.dboards[E320_DBOARD_SLOT_IDX]
        try:
            self._init_peripherals(args)
        except Exception as ex:
            self.log.error("Failed to initialize motherboard: %s", str(ex))
            self._initialization_status = str(ex)
            self._device_initialized = False

    def _init_dboards(self, _, override_dboard_pids, default_args):
        """
        Initialize all the daughterboards

        (dboard_infos) -- N/A
        override_dboard_pids -- List of dboard PIDs to force
        default_args -- Default args
        """
        # Override the base class's implementation in order to avoid initializing our one "dboard"
        # in the same way that, for example, N310's dboards are initialized. Specifically,
        # - skip dboard EEPROM setup (we don't have one)
        # - change the way we handle SPI devices
        if override_dboard_pids:
            self.log.warning("Overriding daughterboard PIDs with: {}".format(
                override_dboard_pids))
            raise NotImplementedError("Can't override dboard pids")
        # The DBoard PID is the same as the MBoard PID
        db_pid = list(self.pids.keys())[0]
        # Set up the SPI nodes
        spi_nodes = []
        for spi_addr in self.dboard_spimaster_addrs:
            for spi_node in get_spidev_nodes(spi_addr):
                bisect.insort(spi_nodes, spi_node)
        self.log.trace("Found spidev nodes: {0}".format(spi_nodes))

        if not spi_nodes:
            self.log.warning("No SPI nodes for dboard %d.",
                             E320_DBOARD_SLOT_IDX)
        dboard_info = {
            'eeprom_md': self.mboard_info,
            'eeprom_rawdata': self._eeprom_rawdata,
            'pid': db_pid,
            'spi_nodes': spi_nodes,
            'default_args': default_args,
        }
        # This will actually instantiate the dboard class:
        self.dboards.append(Neon(E320_DBOARD_SLOT_IDX, **dboard_info))
        self.log.info("Found %d daughterboard(s).", len(self.dboards))

    def _check_fpga_compat(self):
        " Throw an exception if the compat numbers don't match up "
        actual_compat = self.mboard_regs_control.get_compat_number()
        self.log.debug("Actual FPGA compat number: {:d}.{:d}".format(
            actual_compat[0], actual_compat[1]))
        assert_compat_number(E320_FPGA_COMPAT,
                             self.mboard_regs_control.get_compat_number(),
                             component="FPGA",
                             fail_on_old_minor=True,
                             log=self.log)

    def _init_ref_clock_and_time(self, default_args):
        """
        Initialize clock and time sources. After this function returns, the
        reference signals going to the FPGA are valid.
        """
        self._ext_clock_freq = float(
            default_args.get('ext_clock_freq', E320_DEFAULT_EXT_CLOCK_FREQ))
        if not self.dboards:
            self.log.warning(
                "No dboards found, skipping setting clock and time source "
                "configuration.")
            self._clock_source = E320_DEFAULT_CLOCK_SOURCE
            self._time_source = E320_DEFAULT_TIME_SOURCE
        else:
            self.set_clock_source(
                default_args.get('clock_source', E320_DEFAULT_CLOCK_SOURCE))
            self.set_time_source(
                default_args.get('time_source', E320_DEFAULT_TIME_SOURCE))

    def _monitor_status(self):
        """
        Status monitoring thread: This should be executed in a thread. It will
        continuously monitor status of the following peripherals:

        - GPS lock
        """
        self.log.trace("Launching monitor loop...")
        cond = threading.Condition()
        cond.acquire()
        while not self._tear_down:
            gps_locked = self.get_gps_lock_sensor()['value'] == 'true'
            # Now wait
            if cond.wait_for(lambda: self._tear_down,
                             E320_MONITOR_THREAD_INTERVAL):
                break
        cond.release()
        self.log.trace("Terminating monitor loop.")

    def _init_peripherals(self, args):
        """
        Turn on all peripherals. This may throw an error on failure, so make
        sure to catch it.

        Peripherals are initialized in the order of least likely to fail, to most
        likely.
        """
        # Sanity checks
        assert self.mboard_info.get('product') in self.pids.values(), \
            "Device product could not be determined!"
        # Init Mboard Regs
        self.mboard_regs_control = MboardRegsControl(self.mboard_regs_label,
                                                     self.log)
        self.mboard_regs_control.get_git_hash()
        self.mboard_regs_control.get_build_timestamp()
        self._check_fpga_compat()
        self._update_fpga_type()
        # Init peripherals
        self.enable_gps(
            enable=str2bool(args.get('enable_gps', E320_DEFAULT_ENABLE_GPS)))
        self.enable_fp_gpio(
            enable=args.get('enable_fp_gpio', E320_DEFAULT_ENABLE_FPGPIO))
        # Init clocking
        self._init_ref_clock_and_time(args)
        # Init GPSd iface and GPS sensors
        self._init_gps_sensors()
        # Init CHDR transports
        self._xport_mgrs = {
            'udp': E320XportMgrUDP(self.log.getChild('UDP')),
            'liberio': E320XportMgrLiberio(self.log.getChild('liberio')),
        }
        # Spawn status monitoring thread
        self.log.trace("Spawning status monitor thread...")
        self._status_monitor_thread = threading.Thread(
            target=self._monitor_status,
            name="E320StatusMonitorThread",
            daemon=True,
        )
        self._status_monitor_thread.start()
        # Init complete.
        self.log.debug("mboard info: {}".format(self.mboard_info))

    def _init_gps_sensors(self):
        "Init and register the GPSd Iface and related sensor functions"
        self.log.trace("Initializing GPSd interface")
        self._gpsd = GPSDIfaceExtension()
        new_methods = self._gpsd.extend(self)
        for method_name in new_methods:
            try:
                # Extract the sensor name from the getter
                sensor_name = re.search(r"get_.*_sensor", method_name).string
                # Register it with the MB sensor framework
                self.mboard_sensor_callback_map[sensor_name] = method_name
                self.log.trace("Adding %s sensor function", sensor_name)
            except AttributeError:
                # re.search will return None is if can't find the sensor name
                self.log.warning("Error while registering sensor function: %s",
                                 method_name)

    ###########################################################################
    # Session init and deinit
    ###########################################################################
    def init(self, args):
        """
        Calls init() on the parent class, and then programs the Ethernet
        dispatchers accordingly.
        """
        if not self._device_initialized:
            self.log.warning(
                "Cannot run init(), device was never fully initialized!")
            return False
        if args.get("clock_source", "") != "":
            self.set_clock_source(args.get("clock_source"))
        if args.get("time_source", "") != "":
            self.set_time_source(args.get("time_source"))
        result = super(e320, self).init(args)
        for xport_mgr in itervalues(self._xport_mgrs):
            xport_mgr.init(args)
        return result

    def deinit(self):
        """
        Clean up after a UHD session terminates.
        """
        if not self._device_initialized:
            self.log.warning(
                "Cannot run deinit(), device was never fully initialized!")
            return
        super(e320, self).deinit()
        for xport_mgr in itervalues(self._xport_mgrs):
            xport_mgr.deinit()
        self.log.trace("Resetting SID pool...")
        self._available_endpoints = list(range(256))

    def tear_down(self):
        """
        Tear down all members that need to be specially handled before
        deconstruction.
        For E320, this means the overlay.
        """
        self.log.trace("Tearing down E320 device...")
        self._tear_down = True
        if self._device_initialized:
            self._status_monitor_thread.join(3 * E320_MONITOR_THREAD_INTERVAL)
            if self._status_monitor_thread.is_alive():
                self.log.error(
                    "Could not terminate monitor thread! This could result in resource leaks."
                )
        active_overlays = self.list_active_overlays()
        self.log.trace(
            "E320 has active device tree overlays: {}".format(active_overlays))
        for overlay in active_overlays:
            dtoverlay.rm_overlay(overlay)

    ###########################################################################
    # Transport API
    ###########################################################################
    def request_xport(self, dst_address, suggested_src_address, xport_type):
        """
        See PeriphManagerBase.request_xport() for docs.
        """
        # Try suggested address first, then just pick the first available one:
        src_address = suggested_src_address
        if src_address not in self._available_endpoints:
            if not self._available_endpoints:
                raise RuntimeError(
                    "Depleted pool of SID endpoints for this device!")
            else:
                src_address = self._available_endpoints[0]
        sid = SID(src_address << 16 | dst_address)
        # Note: This SID may change its source address!
        self.log.trace(
            "request_xport(dst=0x%04X, suggested_src_address=0x%04X, xport_type=%s): " \
            "operating on temporary SID: %s",
            dst_address, suggested_src_address, str(xport_type), str(sid))
        # FIXME token!
        assert self.mboard_info['rpc_connection'] in ('remote', 'local')
        if self.mboard_info['rpc_connection'] == 'remote':
            return self._xport_mgrs['udp'].request_xport(
                sid,
                xport_type,
            )
        elif self.mboard_info['rpc_connection'] == 'local':
            return self._xport_mgrs['liberio'].request_xport(
                sid,
                xport_type,
            )

    def commit_xport(self, xport_info):
        """
        See PeriphManagerBase.commit_xport() for docs.

        Reminder: All connections are incoming, i.e. "send" or "TX" means
        remote device to local device, and "receive" or "RX" means this local
        device to remote device. "Remote device" can be, for example, a UHD
        session.
        """
        ## Go, go, go
        assert self.mboard_info['rpc_connection'] in ('remote', 'local')
        sid = SID(xport_info['send_sid'])
        self._available_endpoints.remove(sid.src_ep)
        self.log.debug("Committing transport for SID %s, xport info: %s",
                       str(sid), str(xport_info))
        if self.mboard_info['rpc_connection'] == 'remote':
            return self._xport_mgrs['udp'].commit_xport(sid, xport_info)
        elif self.mboard_info['rpc_connection'] == 'local':
            return self._xport_mgrs['liberio'].commit_xport(sid, xport_info)

    ###########################################################################
    # Device info
    ###########################################################################
    def get_device_info_dyn(self):
        """
        Append the device info with current IP addresses.
        """
        if not self._device_initialized:
            return {}
        device_info = self._xport_mgrs['udp'].get_xport_info()
        device_info.update({
            'fpga_version':
            "{}.{}".format(*self.mboard_regs_control.get_compat_number()),
            'fpga':
            self.updateable_components.get('fpga', {}).get('type', ""),
        })
        return device_info

    ###########################################################################
    # Clock/Time API
    ###########################################################################
    def get_clock_sources(self):
        " Lists all available clock sources. "
        self.log.trace("Listing available clock sources...")
        return ('external', 'internal', 'gpsdo')

    def get_clock_source(self):
        " Returns the currently selected clock source "
        return self._clock_source

    def set_clock_source(self, *args):
        """
        Switch reference clock.

        Throws if clock_source is not a valid value.
        """
        clock_source = args[0]
        assert clock_source in self.get_clock_sources()
        self.log.debug("Setting clock source to `{}'".format(clock_source))
        if clock_source == self.get_clock_source():
            self.log.trace("Nothing to do -- clock source already set.")
            return
        self._clock_source = clock_source
        ref_clk_freq = self.get_ref_clock_freq()
        self.mboard_regs_control.set_clock_source(clock_source, ref_clk_freq)
        self.log.debug("Reference clock frequency is: {} MHz".format(
            ref_clk_freq / 1e6))
        self.dboard.update_ref_clock_freq(ref_clk_freq)

    def set_ref_clock_freq(self, freq):
        """
        Tell our USRP what the frequency of the external reference clock is.

        Will throw if it's not a valid value.
        """
        # Other frequencies have not been tested
        assert freq in (10e6, 20e6)
        self.log.debug("We've been told the external reference clock " \
                       "frequency is {} MHz.".format(freq / 1e6))
        if self._ext_clock_freq == freq:
            self.log.trace("New external reference clock frequency " \
                           "assignment matches previous assignment. Ignoring " \
                           "update command.")
            return
        self._ext_clock_freq = freq
        if self.get_clock_source() == 'external':
            for slot, dboard in enumerate(self.dboards):
                if hasattr(dboard, 'update_ref_clock_freq'):
                    self.log.trace(
                        "Updating reference clock on dboard %d to %f MHz...",
                        slot, freq / 1e6)
                    dboard.update_ref_clock_freq(freq)

    def get_ref_clock_freq(self):
        " Returns the currently active reference clock frequency"
        clock_source = self.get_clock_source()
        if clock_source == "internal" or clock_source == "gpsdo":
            return E320_DEFAULT_INT_CLOCK_FREQ
        elif clock_source == "external":
            return self._ext_clock_freq

    def get_time_sources(self):
        " Returns list of valid time sources "
        return ['internal', 'external', 'gpsdo']

    def get_time_source(self):
        " Return the currently selected time source "
        return self._time_source

    def set_time_source(self, time_source):
        " Set a time source "
        assert time_source in self.get_time_sources()
        if time_source == self.get_time_source():
            self.log.trace("Nothing to do -- time source already set.")
            return
        self._time_source = time_source
        self.mboard_regs_control.set_time_source(time_source,
                                                 self.get_ref_clock_freq())

    ###########################################################################
    # Hardware peripheral controls
    ###########################################################################

    def set_fp_gpio_master(self, value):
        """set driver for front panel GPIO
        Arguments:
            value {unsigned} -- value is a single bit bit mask of 12 pins GPIO
        """
        self.mboard_regs_control.set_fp_gpio_master(value)

    def get_fp_gpio_master(self):
        """get "who" is driving front panel gpio
           The return value is a bit mask of 8 pins GPIO.
           0: means the pin is driven by PL
           1: means the pin is driven by PS
        """
        return self.mboard_regs_control.get_fp_gpio_master()

    def set_fp_gpio_radio_src(self, value):
        """set driver for front panel GPIO
        Arguments:
            value {unsigned} -- value is 2-bit bit mask of 8 pins GPIO
           00: means the pin is driven by radio 0
           01: means the pin is driven by radio 1
        """
        self.mboard_regs_control.set_fp_gpio_radio_src(value)

    def get_fp_gpio_radio_src(self):
        """get which radio is driving front panel gpio
           The return value is 2-bit bit mask of 8 pins GPIO.
           00: means the pin is driven by radio 0
           01: means the pin is driven by radio 1
        """
        return self.mboard_regs_control.get_fp_gpio_radio_src()

    def enable_gps(self, enable):
        """
        Turn power to the GPS (CLK_GPS_PWR_EN) off or on.
        """
        self.mboard_regs_control.enable_gps(enable)

    def enable_fp_gpio(self, enable):
        """
        Turn power to the front panel GPIO off or on and set voltage
        to 3.3V.
        """
        self.log.trace("{} power to front-panel GPIO".format(
            "Enabling" if enable else "Disabling"))
        self.mboard_regs_control.enable_fp_gpio(enable)

    def set_fp_gpio_voltage(self, value):
        """
        Set Front Panel GPIO voltage (3.3 Volts)
        """
        self.log.trace(
            "Setting front-panel GPIO voltage to {:3.1f} V".format(value))
        self.mboard_regs_control.set_fp_gpio_voltage(value)

    def get_fp_gpio_voltage(self):
        """
        Get Front Panel GPIO voltage (1.8, 2.5 or 3.3 Volts)
        """
        value = self.mboard_regs_control.get_fp_gpio_voltage()
        self.log.trace(
            "Current front-panel GPIO voltage {:3.1f} V".format(value))
        return value

    def set_channel_mode(self, channel_mode):
        "Set channel mode in FPGA and select which tx channel to use"
        self.mboard_regs_control.set_channel_mode(channel_mode)

    ###########################################################################
    # Sensors
    ###########################################################################
    def get_ref_lock_sensor(self):
        """
        Get refclk lock from CLK_MUX_OUT signal from ADF4002
        """
        self.log.trace("Querying ref lock status from adf4002.")
        lock_status = self.mboard_regs_control.get_refclk_lock()
        return {
            'name': 'ref_locked',
            'type': 'BOOLEAN',
            'unit': 'locked' if lock_status else 'unlocked',
            'value': str(lock_status).lower(),
        }

    def get_temp_sensor(self):
        """
        Get temperature sensor reading of the E320.
        """
        self.log.trace("Reading FPGA temperature.")
        return_val = '-1'
        try:
            raw_val = read_thermal_sensor_value('fpga-thermal-zone', 'temp')
            return_val = str(raw_val / 1000)
        except ValueError:
            self.log.warning("Error when converting temperature value")
        except KeyError:
            self.log.warning("Can't read temp on fpga-thermal-zone")
        return {
            'name': 'temperature',
            'type': 'REALNUM',
            'unit': 'C',
            'value': return_val
        }

    def get_gps_lock_sensor(self):
        """
        Get lock status of GPS as a sensor dict
        """
        gps_locked = self.mboard_regs_control.get_gps_locked_val()
        return {
            'name': 'gps_lock',
            'type': 'BOOLEAN',
            'unit': 'locked' if gps_locked else 'unlocked',
            'value': str(gps_locked).lower(),
        }

    def get_fan_sensor(self):
        """
        Return a sensor dictionary containing the RPM of the fan
        """
        raise NotImplementedError("Fan sensor not implemented")
        # TODO implement
        # return {
        #     'name': 'rssi',
        #     'type': 'REALNUM',
        #     'unit': 'rpm',
        #     'value': XX,
        # }

    ###########################################################################
    # EEPROMs
    ###########################################################################
    def get_mb_eeprom(self):
        """
        Return a dictionary with EEPROM contents.

        All key/value pairs are string -> string.

        We don't actually return the EEPROM contents, instead, we return the
        mboard info again. This filters the EEPROM contents to what we think
        the user wants to know/see.
        """
        return self.mboard_info

    def set_mb_eeprom(self, eeprom_vals):
        """
        See PeriphManagerBase.set_mb_eeprom() for docs.
        """
        self.log.warn("Called set_mb_eeprom(), but not implemented!")
        raise NotImplementedError

    def get_db_eeprom(self, dboard_idx):
        """
        See PeriphManagerBase.get_db_eeprom() for docs.
        """
        if dboard_idx != E320_DBOARD_SLOT_IDX:
            self.log.warn("Trying to access invalid dboard index {}. "
                          "Using the only dboard.".format(dboard_idx))
        db_eeprom_data = copy.copy(self.dboard.device_info)
        for blob_id, blob in iteritems(self.dboard.get_user_eeprom_data()):
            if blob_id in db_eeprom_data:
                self.log.warn(
                    "EEPROM user data contains invalid blob ID "
                    "%s", blob_id)
            else:
                db_eeprom_data[blob_id] = blob
        return db_eeprom_data

    def set_db_eeprom(self, dboard_idx, eeprom_data):
        """
        Write new EEPROM contents with eeprom_map.

        Arguments:
        dboard_idx -- Slot index of dboard (can only be E320_DBOARD_SLOT_IDX)
        eeprom_data -- Dictionary of EEPROM data to be written. It's up to the
                       specific device implementation on how to handle it.
        """
        if dboard_idx != E320_DBOARD_SLOT_IDX:
            self.log.warn("Trying to access invalid dboard index {}. "
                          "Using the only dboard.".format(dboard_idx))
        safe_db_eeprom_user_data = {}
        for blob_id, blob in iteritems(eeprom_data):
            if blob_id in self.dboard.device_info:
                error_msg = "Trying to overwrite read-only EEPROM " \
                            "entry `{}'!".format(blob_id)
                self.log.error(error_msg)
                raise RuntimeError(error_msg)
            if not isinstance(blob, str) and not isinstance(blob, bytes):
                error_msg = "Blob data for ID `{}' is not a " \
                            "string!".format(blob_id)
                self.log.error(error_msg)
                raise RuntimeError(error_msg)
            assert isinstance(blob, str)
            safe_db_eeprom_user_data[blob_id] = blob.encode('ascii')
        self.dboard.set_user_eeprom_data(safe_db_eeprom_user_data)

    ###########################################################################
    # Component updating
    ###########################################################################
    # Note: Component updating functions defined by ZynqComponents
    @no_rpc
    def _update_fpga_type(self):
        """Update the fpga type stored in the updateable components"""
        fpga_type = self.mboard_regs_control.get_fpga_type()
        self.log.debug(
            "Updating mboard FPGA type info to {}".format(fpga_type))
        self.updateable_components['fpga']['type'] = fpga_type
Ejemplo n.º 9
0
Archivo: n3xx.py Proyecto: dkozel/uhd
class n3xx(ZynqComponents, PeriphManagerBase):
    """
    Holds N3xx specific attributes and methods
    """
    # For every variant of the N3xx, add a line to the product map. If
    # it uses a new daughterboard, also import that PID from the dboard
    # manager class. The format of this map is:
    # (motherboard product code, (Slot-A DB PID, [Slot-B DB PID])) -> product
    product_map = {
        ('n300', tuple()) : 'n300',
        ('n300', (MG_PID,       )): 'n300', # Slot B is empty
        ('n310', tuple()) : 'n310',
        ('n310', (MG_PID, MG_PID)): 'n310',
        ('n310', (MG_PID,       )): 'n310', # If Slot B is empty, we can
                                            # still use the n310.bin image.
                                            # We'll leave this here for
                                            # debugging purposes.
        ('n310', (EISCAT_PID , EISCAT_PID )): 'eiscat',
        ('n310', (RHODIUM_PID, RHODIUM_PID)): 'n320',
        ('n310', (RHODIUM_PID,            )): 'n320',
    }

    #########################################################################
    # Overridables
    #
    # See PeriphManagerBase for documentation on these fields
    #########################################################################
    description = "N300-Series Device"
    pids = {0x4242: 'n310', 0x4240: 'n300'}
    mboard_eeprom_addr = "e0005000.i2c"
    mboard_eeprom_offset = 0
    mboard_eeprom_max_len = 256
    mboard_info = {"type": "n3xx"}
    mboard_max_rev = 6 # 6 == RevG
    mboard_sensor_callback_map = {
        'ref_locked': 'get_ref_lock_sensor',
        'gps_locked': 'get_gps_lock_sensor',
        'temp': 'get_temp_sensor',
        'fan': 'get_fan_sensor',
    }
    dboard_eeprom_addr = "e0004000.i2c"
    dboard_eeprom_offset = 0
    dboard_eeprom_max_len = 64

    # We're on a Zynq target, so the following two come from the Zynq standard
    # device tree overlay (tree/arch/arm/boot/dts/zynq-7000.dtsi)
    dboard_spimaster_addrs = ["e0006000.spi", "e0007000.spi"]
    # N3xx-specific settings
    # Label for the mboard UIO
    mboard_regs_label = "mboard-regs"
    # Label for the white rabbit UIO
    wr_regs_label = "wr-regs"
    # Override the list of updateable components
    updateable_components = {
        'fpga': {
            'callback': "update_fpga",
            'path': '/lib/firmware/{}.bin',
            'reset': True,
        },
        'dts': {
            'callback': "update_dts",
            'path': '/lib/firmware/{}.dts',
            'output': '/lib/firmware/{}.dtbo',
            'reset': False,
        },
    }

    #########################################################################
    # Others properties
    #########################################################################
     # All valid sync_sources for N3xx in the form of (clock_source, time_source)
    valid_sync_sources = {
        ('internal', 'internal'),
        ('internal', 'sfp0'),
        ('external', 'external'),
        ('external', 'internal'),
        ('gpsdo', 'gpsdo'),
    }
    @classmethod
    def generate_device_info(cls, eeprom_md, mboard_info, dboard_infos):
        """
        Hard-code our product map
        """
        # Add the default PeriphManagerBase information first
        device_info = super().generate_device_info(
            eeprom_md, mboard_info, dboard_infos)
        # Then add N3xx-specific information
        mb_pid = eeprom_md.get('pid')
        lookup_key = (
            n3xx.pids.get(mb_pid, 'unknown'),
            tuple([x['pid'] for x in dboard_infos]),
        )
        device_info['product'] = cls.product_map.get(lookup_key, 'unknown')
        return device_info

    @staticmethod
    def list_required_dt_overlays(device_info):
        """
        Lists device tree overlays that need to be applied before this class can
        be used. List of strings.
        Are applied in order.

        eeprom_md -- Dictionary of info read out from the mboard EEPROM
        device_args -- Arbitrary dictionary of info, typically user-defined
        """
        # In the N3xx case, we name the dtbo file the same as the product.
        # N310 -> n310.dtbo, N300 -> n300.dtbo and so on.
        return [device_info['product']]

    ###########################################################################
    # Ctor and device initialization tasks
    ###########################################################################
    def __init__(self, args):
        self._tear_down = False
        self._status_monitor_thread = None
        self._ext_clock_freq = None
        self._clock_source = None
        self._time_source = None
        self._available_endpoints = list(range(256))
        self._bp_leds = None
        self._gpsd = None
        super(n3xx, self).__init__(args)
        if not self._device_initialized:
            # Don't try and figure out what's going on. Just give up.
            return
        try:
            self._init_peripherals(args)
        except Exception as ex:
            self.log.error("Failed to initialize motherboard: %s", str(ex))
            self._initialization_status = str(ex)
            self._device_initialized = False
        try:
            if not args.get('skip_boot_init', False):
                self.init(args)
        except Exception as ex:
            self.log.warning("Failed to initialize device on boot: %s", str(ex))

    def _check_fpga_compat(self):
        " Throw an exception if the compat numbers don't match up "
        actual_compat = self.mboard_regs_control.get_compat_number()
        self.log.debug("Actual FPGA compat number: {:d}.{:d}".format(
            actual_compat[0], actual_compat[1]
        ))
        assert_compat_number(
            N3XX_FPGA_COMPAT,
            self.mboard_regs_control.get_compat_number(),
            component="FPGA",
            fail_on_old_minor=True,
            log=self.log
        )

    def _init_ref_clock_and_time(self, default_args):
        """
        Initialize clock and time sources. After this function returns, the
        reference signals going to the FPGA are valid.
        """
        self._ext_clock_freq = float(
            default_args.get('ext_clock_freq', N3XX_DEFAULT_EXT_CLOCK_FREQ)
        )
        if len(self.dboards) == 0:
            self.log.warning(
                "No dboards found, skipping setting clock and time source " \
                "configuration."
            )
            self._clock_source = N3XX_DEFAULT_CLOCK_SOURCE
            self._time_source = N3XX_DEFAULT_TIME_SOURCE
        else:
            self.set_sync_source({
                'clock_source': default_args.get('clock_source',
                                                 N3XX_DEFAULT_CLOCK_SOURCE),
                'time_source' : default_args.get('time_source',
                                                 N3XX_DEFAULT_TIME_SOURCE)
            })

    def _init_meas_clock(self):
        """
        Initialize the TDC measurement clock. After this function returns, the
        FPGA TDC meas_clock is valid.
        """
        # No need to toggle reset here, simply confirm it is out of reset.
        self.mboard_regs_control.reset_meas_clk_mmcm(False)
        if not self.mboard_regs_control.get_meas_clock_mmcm_lock():
            raise RuntimeError("Measurement clock failed to init")

    def _monitor_status(self):
        """
        Status monitoring thread: This should be executed in a thread. It will
        continuously monitor status of the following peripherals:

        - GPS lock (update back-panel GPS LED)
        - REF lock (update back-panel REF LED)
        """
        self.log.trace("Launching monitor loop...")
        cond = threading.Condition()
        cond.acquire()
        while not self._tear_down:
            gps_locked = bool(self._gpios.get("GPS-LOCKOK"))
            self._bp_leds.set(self._bp_leds.LED_GPS, int(gps_locked))
            ref_locked = self.get_ref_lock_sensor()['value'] == 'true'
            self._bp_leds.set(self._bp_leds.LED_REF, int(ref_locked))
            # Now wait
            if cond.wait_for(
                    lambda: self._tear_down,
                    N3XX_MONITOR_THREAD_INTERVAL):
                break
        cond.release()
        self.log.trace("Terminating monitor loop.")

    def _init_peripherals(self, args):
        """
        Turn on all peripherals. This may throw an error on failure, so make
        sure to catch it.

        Periphals are initialized in the order of least likely to fail, to most
        likely.
        """
        # Sanity checks
        assert self.device_info.get('product') in self.product_map.values(), \
                "Device product could not be determined!"
        # Init peripherals
        self.log.trace("Initializing TCA6424 port expander controls...")
        self._gpios = TCA6424(int(self.mboard_info['rev']))
        self.log.trace("Initializing back panel LED controls...")
        self._bp_leds = BackpanelGPIO()
        self.log.trace("Enabling power of MGT156MHZ clk")
        self._gpios.set("PWREN-CLK-MGT156MHz")
        self.enable_1g_ref_clock()
        self.enable_wr_ref_clock()
        self.enable_gps(
            enable=str2bool(
                args.get('enable_gps', N3XX_DEFAULT_ENABLE_GPS)
            )
        )
        self.enable_fp_gpio(
            enable=str2bool(
                args.get(
                    'enable_fp_gpio',
                    N3XX_DEFAULT_ENABLE_FPGPIO
                )
            )
        )
        # Init Mboard Regs
        self.mboard_regs_control = MboardRegsControl(
            self.mboard_regs_label, self.log)
        self.mboard_regs_control.get_git_hash()
        self.mboard_regs_control.get_build_timestamp()
        self._check_fpga_compat()
        self._update_fpga_type()
        self.crossbar_base_port = self.mboard_regs_control.get_xbar_baseport()
        # Init clocking
        self.enable_ref_clock(enable=True)
        self._ext_clock_freq = None
        self._init_ref_clock_and_time(args)
        self._init_meas_clock()
        # Init GPSd iface and GPS sensors
        self._init_gps_sensors()
        # Init QSFP board (if available)
        qsfp_i2c = i2c_dev.of_get_i2c_adapter(N32X_QSFP_I2C_LABEL)
        if qsfp_i2c:
            self.log.debug("Creating QSFP Retimer control object...")
            self._qsfp_retimer = RetimerQSFP(qsfp_i2c)
            self._qsfp_retimer.set_rate_preset(N32X_DEFAULT_QSFP_RATE_PRESET)
            self._qsfp_retimer.set_driver_preset(N32X_DEFAULT_QSFP_DRIVER_PRESET)
        elif self.device_info['product'] == 'n320':
            # If we have an N320, we should also have the QSFP board, but we
            # won't freak out if we can't find it. Maybe someone removed or
            # disabled it.
            self.log.warning("No QSFP board detected!")
        # Init CHDR transports
        self._xport_mgrs = {
            'udp': N3xxXportMgrUDP(self.log.getChild('UDP')),
            'liberio': N3xxXportMgrLiberio(self.log.getChild('liberio')),
        }
        # Spawn status monitoring thread
        self.log.trace("Spawning status monitor thread...")
        self._status_monitor_thread = threading.Thread(
            target=self._monitor_status,
            name="N3xxStatusMonitorThread",
            daemon=True,
        )
        self._status_monitor_thread.start()
        # Init complete.
        self.log.debug("Device info: {}".format(self.device_info))

    def _init_gps_sensors(self):
        "Init and register the GPSd Iface and related sensor functions"
        self.log.trace("Initializing GPSd interface")
        self._gpsd = GPSDIfaceExtension()
        new_methods = self._gpsd.extend(self)
        for method_name in new_methods:
            try:
                # Extract the sensor name from the getter
                sensor_name = re.search(r"get_(.*)_sensor", method_name).group(1)
                # Register it with the MB sensor framework
                self.mboard_sensor_callback_map[sensor_name] = method_name
                self.log.trace("Adding %s sensor function", sensor_name)
            except AttributeError:
                # re.search will return None is if can't find the sensor name
                self.log.warning("Error while registering sensor function: %s", method_name)

    ###########################################################################
    # Session init and deinit
    ###########################################################################
    def init(self, args):
        """
        Calls init() on the parent class, and then programs the Ethernet
        dispatchers accordingly.
        """
        if not self._device_initialized:
            self.log.error(
                "Cannot run init(), device was never fully initialized!")
            return False
        # We need to disable the PPS out during clock and dboard initialization in order
        # to avoid glitches.
        self.enable_pps_out(False)
        # if there's no clock_source or time_source params, we added here since
        # dboards init procedures need them.
        args['clock_source'] = args.get('clock_source', N3XX_DEFAULT_CLOCK_SOURCE)
        args['time_source'] = args.get('time_source', N3XX_DEFAULT_TIME_SOURCE)
        self.set_sync_source(args)
        # Uh oh, some hard coded product-related info: The N300 has no LO
        # source connectors on the front panel, so we assume that if this was
        # selected, it was an artifact from N310-related code. The user gets
        # a warning and the setting is reset to internal.
        if self.device_info.get('product') == 'n300':
            for lo_source in ('rx_lo_source', 'tx_lo_source'):
                if lo_source in args and args.get(lo_source) != 'internal':
                    self.log.warning("The N300 variant does not support "
                                     "external LOs! Setting to internal.")
                    args[lo_source] = 'internal'
        # Note: The parent class takes care of calling init() on all the
        # daughterboards
        result = super(n3xx, self).init(args)
        # Now the clocks are all enabled, we can also enable PPS export:
        self.enable_pps_out(args.get(
            'pps_export',
            N3XX_DEFAULT_ENABLE_PPS_EXPORT
        ))
        for xport_mgr in itervalues(self._xport_mgrs):
            xport_mgr.init(args)
        return result

    def deinit(self):
        """
        Clean up after a UHD session terminates.
        """
        if not self._device_initialized:
            self.log.warning(
                "Cannot run deinit(), device was never fully initialized!")
            return
        super(n3xx, self).deinit()
        for xport_mgr in itervalues(self._xport_mgrs):
            xport_mgr.deinit()
        self.log.trace("Resetting SID pool...")
        self._available_endpoints = list(range(256))

    def tear_down(self):
        """
        Tear down all members that need to be specially handled before
        deconstruction.
        For N3xx, this means the overlay.
        """
        self.log.trace("Tearing down N3xx device...")
        self._tear_down = True
        if self._device_initialized:
            self._status_monitor_thread.join(3 * N3XX_MONITOR_THREAD_INTERVAL)
            if self._status_monitor_thread.is_alive():
                self.log.error("Could not terminate monitor thread! "
                               "This could result in resource leaks.")
        active_overlays = self.list_active_overlays()
        self.log.trace("N3xx has active device tree overlays: {}".format(
            active_overlays
        ))
        for overlay in active_overlays:
            dtoverlay.rm_overlay(overlay)

    ###########################################################################
    # Transport API
    ###########################################################################
    def request_xport(
            self,
            dst_address,
            suggested_src_address,
            xport_type
        ):
        """
        See PeriphManagerBase.request_xport() for docs.
        """
        # Try suggested address first, then just pick the first available one:
        src_address = suggested_src_address
        if src_address not in self._available_endpoints:
            if len(self._available_endpoints) == 0:
                raise RuntimeError(
                    "Depleted pool of SID endpoints for this device!")
            else:
                src_address = self._available_endpoints[0]
        sid = SID(src_address << 16 | dst_address)
        # Note: This SID may change its source address!
        self.log.trace(
            "request_xport(dst=0x%04X, suggested_src_address=0x%04X, xport_type=%s): " \
            "operating on temporary SID: %s",
            dst_address, suggested_src_address, str(xport_type), str(sid))
        # FIXME token!
        assert self.device_info['rpc_connection'] in ('remote', 'local')
        if self.device_info['rpc_connection'] == 'remote':
            return self._xport_mgrs['udp'].request_xport(
                sid,
                xport_type,
            )
        elif self.device_info['rpc_connection'] == 'local':
            return self._xport_mgrs['liberio'].request_xport(
                sid,
                xport_type,
            )

    def commit_xport(self, xport_info):
        """
        See PeriphManagerBase.commit_xport() for docs.

        Reminder: All connections are incoming, i.e. "send" or "TX" means
        remote device to local device, and "receive" or "RX" means this local
        device to remote device. "Remote device" can be, for example, a UHD
        session.
        """
        ## Go, go, go
        assert self.device_info['rpc_connection'] in ('remote', 'local')
        sid = SID(xport_info['send_sid'])
        self._available_endpoints.remove(sid.src_ep)
        self.log.debug("Committing transport for SID %s, xport info: %s",
                       str(sid), str(xport_info))
        if self.device_info['rpc_connection'] == 'remote':
            return self._xport_mgrs['udp'].commit_xport(sid, xport_info)
        elif self.device_info['rpc_connection'] == 'local':
            return self._xport_mgrs['liberio'].commit_xport(sid, xport_info)

    ###########################################################################
    # Device info
    ###########################################################################
    def get_device_info_dyn(self):
        """
        Append the device info with current IP addresses.
        """
        if not self._device_initialized:
            return {}
        device_info = self._xport_mgrs['udp'].get_xport_info()
        device_info.update({
            'fpga_version': "{}.{}".format(
                *self.mboard_regs_control.get_compat_number()),
            'fpga': self.updateable_components.get('fpga', {}).get('type', ""),
        })
        return device_info

    ###########################################################################
    # Clock/Time API
    ###########################################################################
    def get_clock_sources(self):
        " Lists all available clock sources. "
        self.log.trace("Listing available clock sources...")
        return ('external', 'internal', 'gpsdo')

    def get_clock_source(self):
        " Returns the currently selected clock source "
        return self._clock_source

    def set_clock_source(self, *args):
        " Sets a new reference clock source "
        clock_source = args[0]
        time_source = self._time_source
        assert clock_source is not None
        assert time_source is not None
        if (clock_source, time_source) not in self.valid_sync_sources:
            if clock_source == 'internal':
                time_source = 'internal'
            elif clock_source == 'external':
                time_source = 'external'
            elif clock_source == 'gpsdo':
                time_source = 'gpsdo'
        source = {"clock_source": clock_source,
                  "time_source": time_source
                 }
        self.set_sync_source(source)

    def get_time_sources(self):
        " Returns list of valid time sources "
        return ['internal', 'external', 'gpsdo', 'sfp0']

    def get_time_source(self):
        " Return the currently selected time source "
        return self._time_source

    def set_time_source(self, time_source):
        " Set a time source "
        clock_source = self._clock_source
        assert clock_source != None
        assert time_source != None
        if (clock_source, time_source) not in self.valid_sync_sources:
            if time_source == 'sfp0':
                clock_source = 'internal'
            elif time_source == 'internal':
                clock_source = 'internal'
            elif time_source == 'external':
                clock_source = 'external'
            elif time_source == 'gpsdo':
                clock_source = 'gpsdo'
        source = {"time_source": time_source,
                  "clock_source": clock_source
                 }
        self.set_sync_source(source)

    def set_sync_source(self, args):
        """
        Selects reference clock and PPS sources. Unconditionally re-applies the time
        source to ensure continuity between the reference clock and time rates.
        """

        clock_source = args.get('clock_source', self._clock_source)
        assert clock_source in self.get_clock_sources()
        time_source = args.get('time_source', self._time_source)
        assert time_source in self.get_time_sources()
        if (clock_source == self._clock_source) and (time_source == self._time_source):
            # Nothing change no need to do anything
            self.log.trace("New sync source assignment matches"
                           "previous assignment. Ignoring update command.")
            return
        assert (clock_source, time_source) in self.valid_sync_sources
        # Start setting sync source
        self.log.debug("Setting clock source to `{}'".format(clock_source))
        # Place the DB clocks in a safe state to allow reference clock
        # transitions. This leaves all the DB clocks OFF.
        for slot, dboard in enumerate(self.dboards):
            if hasattr(dboard, 'set_clk_safe_state'):
                self.log.trace(
                    "Setting dboard %d components to safe clocking state...", slot)
                dboard.set_clk_safe_state()
        # Disable the Ref Clock in the FPGA before throwing the external switches.
        self.mboard_regs_control.enable_ref_clk(False)
        # Set the external switches to bring in the new source.
        if clock_source == 'internal':
            self._gpios.set("CLK-MAINSEL-EX_B")
            self._gpios.set("CLK-MAINSEL-25MHz")
            self._gpios.reset("CLK-MAINSEL-GPS")
        elif clock_source == 'gpsdo':
            self._gpios.set("CLK-MAINSEL-EX_B")
            self._gpios.reset("CLK-MAINSEL-25MHz")
            self._gpios.set("CLK-MAINSEL-GPS")
        else: # external
            self._gpios.reset("CLK-MAINSEL-EX_B")
            self._gpios.reset("CLK-MAINSEL-GPS")
            # SKY13350 needs to be in known state
            self._gpios.set("CLK-MAINSEL-25MHz")
        self._clock_source = clock_source
        self.log.debug("Reference clock source is: {}" \
                       .format(self._clock_source))
        self.log.debug("Reference clock frequency is: {} MHz" \
                       .format(self.get_ref_clock_freq()/1e6))
        # Enable the Ref Clock in the FPGA after giving it a chance to
        # settle. The settling time is a guess.
        time.sleep(0.100)
        self.mboard_regs_control.enable_ref_clk(True)
        self.log.debug("Setting time source to `{}'".format(time_source))
        self._time_source = time_source
        ref_clk_freq = self.get_ref_clock_freq()
        self.mboard_regs_control.set_time_source(time_source, ref_clk_freq)
        if time_source == 'sfp0':
            # This error is specific to slave and master mode for White Rabbit.
            # Grand Master mode will require the external or gpsdo
            # sources (not supported).
            if time_source in ('sfp0', 'sfp1') \
                    and self.get_clock_source() != 'internal':
                error_msg = "Time source {} requires `internal` clock source!".format(
                    time_source)
                self.log.error(error_msg)
                raise RuntimeError(error_msg)
            sfp_time_source_images = ('WX',)
            if self.updateable_components['fpga']['type'] not in sfp_time_source_images:
                self.log.error("{} time source requires FPGA types {}" \
                               .format(time_source, sfp_time_source_images))
                raise RuntimeError("{} time source requires FPGA types {}" \
                               .format(time_source, sfp_time_source_images))
            # Only open UIO to the WR core once we're guaranteed it exists.
            wr_regs_control = WhiteRabbitRegsControl(
                self.wr_regs_label, self.log)
            # Wait for time source to become ready. Only applies to SFP0/1. All other
            # targets start their PPS immediately.
            self.log.debug("Waiting for {} timebase to lock..." \
                           .format(time_source))
            if not poll_with_timeout(
                    lambda: wr_regs_control.get_time_lock_status(),
                    40000, # Try for x ms... this number is set from a few benchtop tests
                    1000, # Poll every... second! why not?
                ):
                self.log.error("{} timebase failed to lock within 40 seconds. Status: 0x{:X}" \
                               .format(time_source, wr_regs_control.get_time_lock_status()))
                raise RuntimeError("Failed to lock SFP timebase.")
        # Update the DB with the correct Ref Clock frequency and force a re-init.
        for slot, dboard in enumerate(self.dboards):
            self.log.trace(
                "Updating reference clock on dboard %d to %f MHz...",
                slot, ref_clk_freq/1e6
            )
            dboard.update_ref_clock_freq(
                ref_clk_freq,
                time_source=time_source,
                clock_source=clock_source,
                skip_rfic=args.get('skip_rfic', None)
            )

    def set_ref_clock_freq(self, freq):
        """
        Tell our USRP what the frequency of the external reference clock is.

        Will throw if it's not a valid value.
        """
        if freq not in (10e6, 20e6, 25e6):
            self.log.error("{} is not a supported external reference clock frequency!" \
                           .format(freq/1e6))
            raise RuntimeError("{} is not a supported external reference clock " \
                               "frequency!".format(freq/1e6))
        self.log.debug("We've been told the external reference clock " \
                       "frequency is now {} MHz.".format(freq/1e6))
        if self._ext_clock_freq == freq:
            self.log.trace("New external reference clock frequency " \
                           "assignment matches previous assignment. Ignoring " \
                           "update command.")
            return
        if (freq == 20e6) and (self.get_time_source() != 'external'):
            self.log.error("Setting the external reference clock to {} MHz is only " \
                           "allowed when using 'external' time_source. Set the " \
                           "time_source to 'external' first, and then set the new " \
                           "external clock rate.".format(freq/1e6))
            raise RuntimeError("Setting the external reference clock to {} MHz is " \
                               "only allowed when using 'external' time_source." \
                               .format(freq/1e6))
        self._ext_clock_freq = freq
        # If the external source is currently selected we also need to re-apply the
        # time_source. This call also updates the dboards' rates.
        if self.get_clock_source() == 'external':
            self.set_time_source(self.get_time_source())

    def get_ref_clock_freq(self):
        " Returns the currently active reference clock frequency"
        return {
            'internal': 25e6,
            'external': self._ext_clock_freq,
            'gpsdo': 20e6,
        }[self._clock_source]

    def set_fp_gpio_master(self, value):
        """set driver for front panel GPIO
        Arguments:
            value {unsigned} -- value is a single bit bit mask of 12 pins GPIO
        """
        self.mboard_regs_control.set_fp_gpio_master(value)

    def get_fp_gpio_master(self):
        """get "who" is driving front panel gpio
           The return value is a bit mask of 12 pins GPIO.
           0: means the pin is driven by PL
           1: means the pin is driven by PS
        """
        return self.mboard_regs_control.get_fp_gpio_master()

    def set_fp_gpio_radio_src(self, value):
        """set driver for front panel GPIO
        Arguments:
            value {unsigned} -- value is 2-bit bit mask of 12 pins GPIO
           00: means the pin is driven by radio 0
           01: means the pin is driven by radio 1
           10: means the pin is driven by radio 2
           11: means the pin is driven by radio 3
        """
        self.mboard_regs_control.set_fp_gpio_radio_src(value)

    def get_fp_gpio_radio_src(self):
        """get which radio is driving front panel gpio
           The return value is 2-bit bit mask of 12 pins GPIO.
           00: means the pin is driven by radio 0
           01: means the pin is driven by radio 1
           10: means the pin is driven by radio 2
           11: means the pin is driven by radio 3
        """
        return self.mboard_regs_control.get_fp_gpio_radio_src()
    ###########################################################################
    # Hardware periphal controls
    ###########################################################################
    def enable_pps_out(self, enable):
        " Export a PPS/Trigger to the back panel "
        self.mboard_regs_control.enable_pps_out(enable)

    def enable_gps(self, enable):
        """
        Turn power to the GPS off or on.
        """
        self.log.trace("{} power to GPS".format(
            "Enabling" if enable else "Disabling"
        ))
        self._gpios.set("PWREN-GPS", int(bool(enable)))

    def enable_fp_gpio(self, enable):
        """
        Turn power to the front panel GPIO off or on.
        """
        self.log.trace("{} power to front-panel GPIO".format(
            "Enabling" if enable else "Disabling"
        ))
        self._gpios.set("FPGA-GPIO-EN", int(bool(enable)))

    def enable_ref_clock(self, enable):
        """
        Enables the ref clock voltage (+3.3-MAINREF). Without setting this to
        True, *no* ref clock works.
        """
        self.log.trace("{} power to reference clocks".format(
            "Enabling" if enable else "Disabling"
        ))
        self._gpios.set("PWREN-CLK-MAINREF", int(bool(enable)))

    def enable_1g_ref_clock(self):
        """
        Enables 125 MHz refclock for 1G interface.
        """
        self.log.trace("Enable 125 MHz Clock for 1G SFP interface.")
        self._gpios.set("NETCLK-CE", 1)
        self._gpios.set("NETCLK-RESETn", 0)
        self._gpios.set("NETCLK-PR0", 1)
        self._gpios.set("NETCLK-PR1", 1)
        self._gpios.set("NETCLK-OD0", 1)
        self._gpios.set("NETCLK-OD1", 1)
        self._gpios.set("NETCLK-OD2", 0)
        self._gpios.set("PWREN-CLK-WB-25MHz", 1)
        self.log.trace("Finished configuring NETCLK CDCM.")
        self._gpios.set("NETCLK-RESETn", 1)

    def enable_wr_ref_clock(self):
        """
        Enables 20 MHz WR refclk. Note that enable_1g_ref_clock() is also required for this
        interface to work, although calling it here is redundant.
        """
        self.log.trace("Enable White Rabbit reference clock.")
        self._gpios.set("PWREN-CLK-WB-20MHz", 1)

    ###########################################################################
    # Sensors
    # Note: GPS sensors are registered at runtime
    ###########################################################################
    def get_ref_lock_sensor(self):
        """
        The N3xx has no ref lock sensor, but because the ref lock is
        historically considered a motherboard-level sensor, we will return the
        combined lock status of all daughterboards. If no dboard is connected,
        or none has a ref lock sensor, we simply return True.
        """
        self.log.trace(
            "Querying ref lock status from %d dboards.",
            len(self.dboards)
        )
        lock_status = all([
            not hasattr(db, 'get_ref_lock') or db.get_ref_lock()
            for db in self.dboards
        ])
        return {
            'name': 'ref_locked',
            'type': 'BOOLEAN',
            'unit': 'locked' if lock_status else 'unlocked',
            'value': str(lock_status).lower(),
        }

    def get_temp_sensor(self):
        """
        Get temperature sensor reading of the N3xx.
        """
        self.log.trace("Reading FPGA temperature.")
        return_val = '-1'
        try:
            raw_val = read_thermal_sensor_value('fpga-thermal-zone', 'temp')
            return_val = str(raw_val/1000)
        except ValueError:
            self.log.warning("Error when converting temperature value")
        except KeyError:
            self.log.warning("Can't read temp on fpga-thermal-zone")
        return {
            'name': 'temperature',
            'type': 'REALNUM',
            'unit': 'C',
            'value': return_val
        }

    def get_fan_sensor(self):
        """
        Get cooling device reading of N3xx. In this case the speed of fan 0.
        """
        self.log.trace("Reading FPGA cooling device.")
        return_val = '-1'
        try:
            raw_val = read_thermal_sensor_value('ec-fan0', 'cur_state')
            return_val = str(raw_val)
        except ValueError:
            self.log.warning("Error when converting fan speed value")
        except KeyError:
            self.log.warning("Can't read cur_state on ec-fan0")
        return {
            'name': 'cooling fan',
            'type': 'INTEGER',
            'unit': 'rpm',
            'value': return_val
        }

    def get_gps_lock_sensor(self):
        """
        Get lock status of GPS as a sensor dict
        """
        self.log.trace("Reading status GPS lock pin from port expander")
        gps_locked = bool(self._gpios.get("GPS-LOCKOK"))
        return {
            'name': 'gps_lock',
            'type': 'BOOLEAN',
            'unit': 'locked' if gps_locked else 'unlocked',
            'value': str(gps_locked).lower(),
        }

    ###########################################################################
    # EEPROMs
    ###########################################################################
    def get_mb_eeprom(self):
        """
        Return a dictionary with EEPROM contents.

        All key/value pairs are string -> string.

        We don't actually return the EEPROM contents, instead, we return the
        mboard info again. This filters the EEPROM contents to what we think
        the user wants to know/see.
        """
        return self.mboard_info

    def set_mb_eeprom(self, eeprom_vals):
        """
        See PeriphManagerBase.set_mb_eeprom() for docs.
        """
        self.log.warn("Called set_mb_eeprom(), but not implemented!")
        raise NotImplementedError

    def get_db_eeprom(self, dboard_idx):
        """
        See PeriphManagerBase.get_db_eeprom() for docs.
        """
        try:
            dboard = self.dboards[dboard_idx]
        except KeyError:
            error_msg = "Attempted to access invalid dboard index `{}' " \
                        "in get_db_eeprom()!".format(dboard_idx)
            self.log.error(error_msg)
            raise RuntimeError(error_msg)
        db_eeprom_data = copy.copy(dboard.device_info)
        if hasattr(dboard, 'get_user_eeprom_data') and \
                callable(dboard.get_user_eeprom_data):
            for blob_id, blob in iteritems(dboard.get_user_eeprom_data()):
                if blob_id in db_eeprom_data:
                    self.log.warn("EEPROM user data contains invalid blob ID " \
                                  "%s", blob_id)
                else:
                    db_eeprom_data[blob_id] = blob
        return db_eeprom_data

    def set_db_eeprom(self, dboard_idx, eeprom_data):
        """
        Write new EEPROM contents with eeprom_map.

        Arguments:
        dboard_idx -- Slot index of dboard
        eeprom_data -- Dictionary of EEPROM data to be written. It's up to the
                       specific device implementation on how to handle it.
        """
        try:
            dboard = self.dboards[dboard_idx]
        except KeyError:
            error_msg = "Attempted to access invalid dboard index `{}' " \
                        "in set_db_eeprom()!".format(dboard_idx)
            self.log.error(error_msg)
            raise RuntimeError(error_msg)
        if not hasattr(dboard, 'set_user_eeprom_data') or \
                not callable(dboard.set_user_eeprom_data):
            error_msg = "Dboard has no set_user_eeprom_data() method!"
            self.log.error(error_msg)
            raise RuntimeError(error_msg)
        safe_db_eeprom_user_data = {}
        for blob_id, blob in iteritems(eeprom_data):
            if blob_id in dboard.device_info:
                error_msg = "Trying to overwrite read-only EEPROM " \
                            "entry `{}'!".format(blob_id)
                self.log.error(error_msg)
                raise RuntimeError(error_msg)
            if not isinstance(blob, str) and not isinstance(blob, bytes):
                error_msg = "Blob data for ID `{}' is not a " \
                            "string!".format(blob_id)
                self.log.error(error_msg)
                raise RuntimeError(error_msg)
            assert isinstance(blob, str)
            safe_db_eeprom_user_data[blob_id] = blob.encode('ascii')
        dboard.set_user_eeprom_data(safe_db_eeprom_user_data)

    ###########################################################################
    # Component updating
    ###########################################################################
    # Note: Component updating functions defined by ZynqComponents
    @no_rpc
    def _update_fpga_type(self):
        """Update the fpga type stored in the updateable components"""
        fpga_type = self.mboard_regs_control.get_fpga_type()
        self.log.debug("Updating mboard FPGA type info to {}".format(fpga_type))
        self.updateable_components['fpga']['type'] = fpga_type

    #######################################################################
    # Claimer API
    #######################################################################
    def claim(self):
        """
        This is called when the device is claimed, in case the device needs to
        run any actions on claiming (e.g., light up an LED).
        """
        if self._bp_leds is not None:
            # Light up LINK
            self._bp_leds.set(self._bp_leds.LED_LINK, 1)

    def unclaim(self):
        """
        This is called when the device is unclaimed, in case the device needs
        to run any actions on claiming (e.g., turn off an LED).
        """
        if self._bp_leds is not None:
            # Turn off LINK
            self._bp_leds.set(self._bp_leds.LED_LINK, 0)
Ejemplo n.º 10
0
class e31x(ZynqComponents, PeriphManagerBase):
    """
    Holds E310 specific attributes and methods
    """
    #########################################################################
    # Overridables
    #
    # See PeriphManagerBase for documentation on these fields
    #########################################################################
    description = "E300-Series Device"
    # 0x77d2 and 0x77d3
    pids = {
        0x77D2: 'e310_sg1',  #sg1
        0x77D3: 'e310_sg3'
    }  #sg3
    # The E310 has a single EEPROM that stores both DB and MB information
    mboard_eeprom_addr = "e0004000.i2c"
    mboard_eeprom_offset = 0
    mboard_eeprom_max_len = 64
    # We have two nvem paths on the E310.
    # This one ensures that we get the right path for the MB.
    mboard_eeprom_path_index = 1
    mboard_info = {"type": "e3xx"}
    mboard_sensor_callback_map = {
        'ref_locked': 'get_ref_lock_sensor',
        'gps_locked': 'get_gps_lock_sensor',
        'temp_fpga': 'get_fpga_temp_sensor',
        'temp_mb': 'get_mb_temp_sensor',
    }
    # The E310 has a single EEPROM that stores both DB and MB information
    dboard_eeprom_addr = "e0004000.i2c"
    dboard_eeprom_path_index = 0
    # Actual DB EEPROM bytes are just 28. Reading just a couple more.
    # Refer e300_eeprom_manager.hpp
    dboard_eeprom_max_len = 32
    max_num_dboards = 1
    # We're on a Zynq target, so the following two come from the Zynq standard
    # device tree overlay (tree/arch/arm/boot/dts/zynq-7000.dtsi)
    dboard_spimaster_addrs = ["e0006000.spi"]
    # E310-specific settings
    # Label for the mboard UIO
    mboard_regs_label = "mboard-regs"
    # Override the list of updateable components
    updateable_components = {
        'fpga': {
            'callback': "update_fpga",
            'path': '/lib/firmware/{}.bin',
            'reset': True,
        },
        'dts': {
            'callback': "update_dts",
            'path': '/lib/firmware/{}.dts',
            'output': '/lib/firmware/{}.dtbo',
            'reset': False,
        },
    }
    # This class removes the overlay in tear_down() resulting
    # in stale references to methods in the RPC server. Setting
    # this to True ensures that the RPC server clears all registered
    # methods on unclaim() and registers them on the following claim().
    clear_rpc_registry_on_unclaim = True

    @classmethod
    def generate_device_info(cls, eeprom_md, mboard_info, dboard_infos):
        """
        Generate dictionary describing the device.
        """
        # Add the default PeriphManagerBase information first
        device_info = super().generate_device_info(eeprom_md, mboard_info,
                                                   dboard_infos)
        # Then add E31x-specific information
        mb_pid = eeprom_md.get('pid')
        device_info['product'] = cls.pids.get(mb_pid, 'unknown')
        return device_info

    @staticmethod
    def list_required_dt_overlays(device_info):
        """
        Returns the name of the overlay for the regular image (not idle).
        Either returns e310_sg1 or e310_sg3.
        """
        return [device_info['product']]

    ### End of overridables ###################################################

    @staticmethod
    def get_idle_dt_overlay(device_info):
        """
        Overlay to be applied to enter low power idle state.
        """
        # e.g. e310_sg3_idle
        idle_overlay = device_info['product'] + '_idle'
        return idle_overlay

    ###########################################################################
    # Ctor and device initialization tasks
    ###########################################################################
    def __init__(self, args):
        """
        Does partial initialization which loads low power idle image
        """
        self._time_source = None
        self._gpsd = None
        self.dboards = []
        self.dboard = None
        self.mboard_regs_control = None
        self._xport_mgrs = {}
        self._initialization_status = ""
        self._device_initialized = False
        self.args_cached = args
        # This will load the regular image to obtain all FPGA info
        super(e31x, self).__init__()
        args = self._update_default_args(args)
        # Permanently store the value from mpm.conf:
        self._do_not_reload_default = \
            str2bool(args.get("no_reload_fpga", E310_DEFAULT_DONT_RELOAD_FPGA))
        # This flag can change depending on UHD args:
        self._do_not_reload = self._do_not_reload_default
        # If we don't want to reload, we'll complete initialization now:
        if self._do_not_reload:
            try:
                self.log.info("Not reloading FPGA images!")
                self._init_normal()
            except BaseException as ex:
                self.log.error("Failed to initialize motherboard: %s", str(ex))
                self._initialization_status = str(ex)
                self._device_initialized = False
        else:  # Otherwise, put the USRP into low-power mode:
            # Start clean by removing MPM-owned overlays.
            active_overlays = self.list_active_overlays()
            mpm_overlays = self.list_owned_overlays()
            for overlay in active_overlays:
                if overlay in mpm_overlays:
                    dtoverlay.rm_overlay(overlay)
            # Apply idle overlay on boot to save power until
            # an application tries to use the device.
            self.apply_idle_overlay()
            self._device_initialized = False
        self._init_gps_sensors()

    def _init_gps_sensors(self):
        """
        Init and register the GPSd Iface and related sensor functions

        Note: The GPS chip is not connected to the FPGA, so this is initialized
        regardless of the idle state
        """
        self.log.trace("Initializing GPSd interface")
        self._gpsd = GPSDIfaceExtension()
        new_methods = self._gpsd.extend(self)
        for method_name in new_methods:
            try:
                # Extract the sensor name from the getter
                sensor_name = re.search(r"get_(.*)_sensor",
                                        method_name).group(1)
                # Register it with the MB sensor framework
                self.mboard_sensor_callback_map[sensor_name] = method_name
                self.log.trace("Adding %s sensor function", sensor_name)
            except AttributeError:
                # re.search will return None is if can't find the sensor name
                self.log.warning("Error while registering sensor function: %s",
                                 method_name)

    def _init_normal(self):
        """
        Does full initialization. This gets called during claim(), because the
        E310 usually gets freshly initialized on every UHD session for power
        usage reasons, unless no_reload_fpga was provided in mpm.conf.
        """
        if self._device_initialized:
            return
        if self.is_idle():
            self.remove_idle_overlay()
        self.overlay_apply()
        self.init_dboards(self.args_cached)
        if not self._device_initialized:
            # Don't try and figure out what's going on. Just give up.
            return
        self._time_source = None
        self.dboard = self.dboards[E310_DBOARD_SLOT_IDX]
        try:
            self._init_peripherals(self.args_cached)
        except BaseException as ex:
            self.log.error("Failed to initialize motherboard: %s", str(ex))
            self._initialization_status = str(ex)
            self._device_initialized = False

    def _init_dboards(self, dboard_infos, override_dboard_pids, default_args):
        """
        Initialize all the daughterboards

        dboard_infos -- List of dictionaries as returned from
                       PeriphManagerBase._get_dboard_eeprom_info()
        override_dboard_pids -- List of dboard PIDs to force
        default_args -- Default args
        """
        # Overriding DB PIDs doesn't work here, the DB is coupled to the MB
        if override_dboard_pids:
            raise NotImplementedError("Can't override dboard pids")
        # We have only one dboard
        dboard_info = dboard_infos[0]
        # Set up the SPI nodes
        assert len(self.dboard_spimaster_addrs) == 1
        spi_nodes = get_spidev_nodes(self.dboard_spimaster_addrs[0])
        assert spi_nodes
        self.log.trace("Found spidev nodes: {0}".format(str(spi_nodes)))
        dboard_info.update({
            'spi_nodes': spi_nodes,
            'default_args': default_args,
        })
        self.dboards.append(E31x_db(E310_DBOARD_SLOT_IDX, **dboard_info))
        self.log.info("Found %d daughterboard(s).", len(self.dboards))

    def _check_fpga_compat(self):
        " Throw an exception if the compat numbers don't match up "
        actual_compat = self.mboard_regs_control.get_compat_number()
        self.log.debug("Actual FPGA compat number: {:d}.{:d}".format(
            actual_compat[0], actual_compat[1]))
        assert_compat_number(E310_FPGA_COMPAT,
                             self.mboard_regs_control.get_compat_number(),
                             component="FPGA",
                             fail_on_old_minor=True,
                             log=self.log)

    def _init_ref_clock_and_time(self, default_args):
        """
        Initialize clock and time sources. After this function returns, the
        reference signals going to the FPGA are valid.
        """
        if not self.dboards:
            self.log.warning(
                "No dboards found, skipping setting clock and time source "
                "configuration.")
            self._time_source = E310_DEFAULT_TIME_SOURCE
        else:
            self.set_clock_source(
                default_args.get('clock_source', E310_DEFAULT_CLOCK_SOURCE))
            self.set_time_source(
                default_args.get('time_source', E310_DEFAULT_TIME_SOURCE))

    def _init_peripherals(self, args):
        """
        Turn on all peripherals. This may throw an error on failure, so make
        sure to catch it.

        Peripherals are initialized in the order of least likely to fail, to most
        likely.
        """
        # Sanity checks
        assert self.mboard_info.get('product') in self.pids.values(), \
            "Device product could not be determined!"
        # Init Mboard Regs
        self.mboard_regs_control = MboardRegsControl(self.mboard_regs_label,
                                                     self.log)
        self.mboard_regs_control.get_git_hash()
        self.mboard_regs_control.get_build_timestamp()
        self._check_fpga_compat()
        self._update_fpga_type()
        # Init clocking
        self._init_ref_clock_and_time(args)
        # Init CHDR transports
        self._xport_mgrs = {
            'liberio': E310XportMgrLiberio(self.log.getChild('liberio')),
        }
        # Init complete.
        self.log.debug("mboard info: {}".format(self.mboard_info))

    def _read_mboard_eeprom(self):
        """
        Read out mboard EEPROM.
        Returns a tuple: (eeprom_dict, eeprom_rawdata), where the the former is
        a de-serialized dictionary representation of the data, and the latter
        is a binary string with the raw data.

        If no EEPROM is defined, returns empty values.
        """
        eeprom_path = \
            get_eeprom_paths(self.mboard_eeprom_addr)[self.mboard_eeprom_path_index]
        if not eeprom_path:
            self.log.error("Could not identify EEPROM path for %s!",
                           self.mboard_eeprom_addr)
            return {}, b''
        self.log.trace("MB EEPROM: Using path {}".format(eeprom_path))
        (eeprom_head, eeprom_rawdata) = e31x_legacy_eeprom.read_eeprom(
            True,  # is_motherboard
            eeprom_path,
            self.mboard_eeprom_offset,
            e31x_legacy_eeprom.MboardEEPROM.eeprom_header_format,
            e31x_legacy_eeprom.MboardEEPROM.eeprom_header_keys,
            self.mboard_eeprom_max_len)
        self.log.trace("Read %d bytes of EEPROM data.", len(eeprom_rawdata))
        return eeprom_head, eeprom_rawdata

    def _get_dboard_eeprom_info(self):
        """
        Read back EEPROM info from the daughterboards
        """
        assert self.dboard_eeprom_addr
        self.log.trace("Identifying dboard EEPROM paths from `{}'...".format(
            self.dboard_eeprom_addr))
        dboard_eeprom_path = \
            get_eeprom_paths(self.dboard_eeprom_addr)[self.dboard_eeprom_path_index]
        self.log.trace(
            "Using dboard EEPROM paths: {}".format(dboard_eeprom_path))
        self.log.debug("Reading EEPROM info for dboard...")
        dboard_eeprom_md, dboard_eeprom_rawdata = e31x_legacy_eeprom.read_eeprom(
            False,  # is not motherboard.
            dboard_eeprom_path,
            self.dboard_eeprom_offset,
            e31x_legacy_eeprom.DboardEEPROM.eeprom_header_format,
            e31x_legacy_eeprom.DboardEEPROM.eeprom_header_keys,
            self.dboard_eeprom_max_len)
        self.log.trace("Read %d bytes of dboard EEPROM data.",
                       len(dboard_eeprom_rawdata))
        db_pid = dboard_eeprom_md.get('pid')
        if db_pid is None:
            self.log.warning("No DB PID found in dboard EEPROM!")
        else:
            self.log.debug("Found DB PID in EEPROM: 0x{:04X}".format(db_pid))
        return [{
            'eeprom_md': dboard_eeprom_md,
            'eeprom_rawdata': dboard_eeprom_rawdata,
            'pid': db_pid,
        }]

    ###########################################################################
    # Session init and deinit
    ###########################################################################
    def claim(self):
        """
        Fully initializes a device when the rpc_server claim()
        gets called to revive the device from idle state to be used
        by an UHD application
        """
        super(e31x, self).claim()
        try:
            self._init_normal()
        except BaseException as ex:
            self.log.error("e31x claim() failed: %s", str(ex))

    def init(self, args):
        """
        Calls init() on the parent class, and updates time/clock source.
        """
        if not self._device_initialized:
            self.log.warning(
                "Cannot run init(), device was never fully initialized!")
            return False
        if args.get("clock_source", "") != "":
            self.set_clock_source(args.get("clock_source"))
        if args.get("time_source", "") != "":
            self.set_time_source(args.get("time_source"))
        if "no_reload_fpga" in args:
            self._do_not_reload = \
                str2bool(args.get("no_reload_fpga")) or args.get("no_reload_fpga") == ""
        result = super(e31x, self).init(args)
        for xport_mgr in itervalues(self._xport_mgrs):
            xport_mgr.init(args)
        return result

    def apply_idle_overlay(self):
        """
        Load all overlays required to go into idle power savings mode.
        """
        idle_overlay = self.get_idle_dt_overlay(self.device_info)
        self.log.debug(
            "Motherboard requests device tree overlay for Idle power savings mode: {}"
            .format(idle_overlay))
        dtoverlay.apply_overlay_safe(idle_overlay)

    def remove_idle_overlay(self):
        """
        Remove idle mode overlay.
        """
        idle_overlay = self.get_idle_dt_overlay(self.device_info)
        self.log.trace("Removing Idle overlay: {}".format(idle_overlay))
        dtoverlay.rm_overlay(idle_overlay)

    def list_owned_overlays(self):
        """
        Lists all overlays that can be possibly applied by MPM.
        """
        all_overlays = self.list_required_dt_overlays(self.device_info)
        all_overlays.append(self.get_idle_dt_overlay(self.device_info))
        return all_overlays

    def deinit(self):
        """
        Clean up after a UHD session terminates.
        """
        if not self._device_initialized:
            self.log.warning(
                "Cannot run deinit(), device was never fully initialized!")
            return
        super(e31x, self).deinit()
        for xport_mgr in itervalues(self._xport_mgrs):
            xport_mgr.deinit()
        if not self._do_not_reload:
            self.tear_down()
        # Reset back to value from _default_args (mpm.conf)
        self._do_not_reload = self._do_not_reload_default

    def tear_down(self):
        """
        Tear down all members that need to be specially handled before
        deconstruction.
        For E310, this means the overlay.
        """
        self.log.trace("Tearing down E310 device...")
        self.dboards = []
        self.dboard.tear_down()
        self.dboard = None
        self.mboard_regs_control = None
        self._device_initialized = False
        active_overlays = self.list_active_overlays()
        self.log.trace(
            "E310 has active device tree overlays: {}".format(active_overlays))
        for overlay in active_overlays:
            dtoverlay.rm_overlay(overlay)
        self.apply_idle_overlay()
        self.log.debug("Teardown complete!")

    def is_idle(self):
        """
        Determine if the device is in the idle state.
        """
        active_overlays = self.list_active_overlays()
        idle_overlay = self.get_idle_dt_overlay(self.device_info)
        is_idle = idle_overlay in active_overlays
        if is_idle:
            self.log.trace("Found idle overlay: %s", idle_overlay)
        return is_idle

    ###########################################################################
    # Transport API
    ###########################################################################
    def get_chdr_link_types(self):
        """
        See PeriphManagerBase.get_chdr_link_types() for docs.
        """
        return ['liberio']

    def get_chdr_link_options(self, xport_type):
        """
        See PeriphManagerBase.get_chdr_link_options() for docs.
        """
        assert xport_type == 'liberio', \
            "Invalid xport_type! Must be 'liberio'"
        return self._xport_mgrs['liberio'].get_chdr_link_options()

    ###########################################################################
    # Device info
    ###########################################################################
    def get_device_info_dyn(self):
        """
        Append the device info with current IP addresses.
        """
        if not self._device_initialized:
            return {}
        device_info = {}
        device_info.update({
            'fpga_version':
            "{}.{}".format(*self.mboard_regs_control.get_compat_number()),
            'fpga_version_hash':
            "{:x}.{}".format(*self.mboard_regs_control.get_git_hash()),
            'fpga':
            self.updateable_components.get('fpga', {}).get('type', ""),
        })
        return device_info

    ###########################################################################
    # Clock/Time API
    ###########################################################################
    def get_clock_sources(self):
        " Lists all available clock sources. "
        self.log.trace("Listing available clock sources...")
        return ('internal', )

    def get_clock_source(self):
        " Returns the currently selected clock source "
        return E310_DEFAULT_CLOCK_SOURCE

    def set_clock_source(self, *args):
        """
        Note: E310 only supports one clock source ('internal'), so no need to do
        an awful lot here.
        """
        clock_source = args[0]
        assert clock_source in self.get_clock_sources(), \
            "Cannot set to invalid clock source: {}".format(clock_source)

    def get_time_sources(self):
        " Returns list of valid time sources "
        return ['internal', 'external', 'gpsdo']

    def get_time_source(self):
        " Return the currently selected time source "
        return self._time_source

    def set_time_source(self, time_source):
        " Set a time source "
        assert time_source in self.get_time_sources(), \
            "Cannot set to invalid time source: {}".format(time_source)
        if time_source == self.get_time_source():
            self.log.trace("Nothing to do -- time source already set.")
            return
        self._time_source = time_source
        self.mboard_regs_control.set_time_source(time_source)

    ###########################################################################
    # Hardware peripheral controls
    ###########################################################################
    def set_fp_gpio_master(self, value):
        """set driver for front panel GPIO
        Arguments:
            value {unsigned} -- value is a single bit bit mask of 12 pins GPIO
        """
        self.mboard_regs_control.set_fp_gpio_master(value)

    def get_fp_gpio_master(self):
        """get "who" is driving front panel gpio
           The return value is a bit mask of 8 pins GPIO.
           0: means the pin is driven by PL
           1: means the pin is driven by PS
        """
        return self.mboard_regs_control.get_fp_gpio_master()

    def set_fp_gpio_radio_src(self, value):
        """set driver for front panel GPIO
        Arguments:
            value {unsigned} -- value is 2-bit bit mask of 8 pins GPIO
           00: means the pin is driven by radio 0
           01: means the pin is driven by radio 1
        """
        self.mboard_regs_control.set_fp_gpio_radio_src(value)

    def get_fp_gpio_radio_src(self):
        """get which radio is driving front panel gpio
           The return value is 2-bit bit mask of 8 pins GPIO.
           00: means the pin is driven by radio 0
           01: means the pin is driven by radio 1
        """
        return self.mboard_regs_control.get_fp_gpio_radio_src()

    def set_channel_mode(self, channel_mode):
        "Set channel mode in FPGA and select which tx channel to use"
        self.mboard_regs_control.set_channel_mode(channel_mode)

    ###########################################################################
    # Sensors
    ###########################################################################
    def get_ref_lock_sensor(self):
        """
        Return main refclock lock status. In the FPGA, this is the reflck output
        of the ppsloop module.
        """
        self.log.trace("Querying ref lock status.")
        lock_status = bool(self.mboard_regs_control.get_refclk_lock())
        return {
            'name': 'ref_locked',
            'type': 'BOOLEAN',
            'unit': 'locked' if lock_status else 'unlocked',
            'value': str(lock_status).lower(),
        }

    def get_gps_lock_sensor(self):
        """
        Get lock status of GPS as a sensor dict
        """
        gps_locked = self._gpsd.get_gps_lock()
        return {
            'name': 'gps_lock',
            'type': 'BOOLEAN',
            'unit': 'locked' if gps_locked else 'unlocked',
            'value': str(gps_locked).lower(),
        }

    def get_mb_temp_sensor(self):
        """
        Get temperature sensor reading of the E310.
        """
        self.log.trace("Reading temperature.")
        temp = '-1'
        raw_val = {}
        data_probes = ['temp1_input']
        try:
            for data_probe in data_probes:
                raw_val[data_probe] = read_sysfs_sensors_value(
                    'jc-42.4-temp', data_probe, 'hwmon', 'name')[0]
            temp = str(raw_val['temp1_input'] / 1000)
        except ValueError:
            self.log.warning("Error when converting temperature value")
        except KeyError:
            self.log.warning("Can't read MB temperature!")
        return {
            'name': 'temp_mb',
            'type': 'REALNUM',
            'unit': 'C',
            'value': temp
        }

    def get_fpga_temp_sensor(self):
        """
        Get temperature sensor reading of the E310.
        """
        self.log.trace("Reading temperature.")
        temp = '-1'
        raw_val = {}
        data_probes = ['in_temp0_raw', 'in_temp0_scale', 'in_temp0_offset']
        try:
            for data_probe in data_probes:
                raw_val[data_probe] = read_sysfs_sensors_value(
                    'xadc', data_probe, 'iio', 'name')[0]
            temp = str((raw_val['in_temp0_raw'] + raw_val['in_temp0_offset']) \
                    * raw_val['in_temp0_scale'] / 1000)
        except ValueError:
            self.log.warning("Error when converting temperature value")
        except KeyError:
            self.log.warning("Can't read FPGA temperature!")
        return {
            'name': 'temp_fpga',
            'type': 'REALNUM',
            'unit': 'C',
            'value': temp
        }

    ###########################################################################
    # EEPROMs
    ###########################################################################
    def get_mb_eeprom(self):
        """
        Return a dictionary with EEPROM contents.

        All key/value pairs are string -> string.

        We don't actually return the EEPROM contents, instead, we return the
        mboard info again. This filters the EEPROM contents to what we think
        the user wants to know/see.
        """
        return self.mboard_info

    def set_mb_eeprom(self, eeprom_vals):
        """
        See PeriphManagerBase.set_mb_eeprom() for docs.
        """
        self.log.warn("Called set_mb_eeprom(), but not implemented!")

    def get_db_eeprom(self, dboard_idx):
        """
        See PeriphManagerBase.get_db_eeprom() for docs.
        """
        if dboard_idx != E310_DBOARD_SLOT_IDX:
            self.log.warn("Trying to access invalid dboard index {}. "
                          "Using the only dboard.".format(dboard_idx))
        db_eeprom_data = copy.copy(self.dboard.device_info)
        return db_eeprom_data

    def set_db_eeprom(self, dboard_idx, eeprom_data):
        """
        See PeriphManagerBase.set_db_eeprom() for docs.
        """
        self.log.warn("Called set_db_eeprom(), but not implemented!")

    ###########################################################################
    # Component updating
    ###########################################################################
    # Note: Component updating functions defined by ZynqComponents
    @no_rpc
    def _update_fpga_type(self):
        """Update the fpga type stored in the updateable components"""
        fpga_type = ""  # FIXME
        self.log.debug(
            "Updating mboard FPGA type info to {}".format(fpga_type))
        self.updateable_components['fpga']['type'] = fpga_type

    #######################################################################
    # Timekeeper API
    #######################################################################
    def get_clocks(self):
        """
        Gets the RFNoC-related clocks present in the FPGA design
        """
        return [{
            'name': 'radio_clk',
            'freq': str(self.dboard.get_master_clock_rate()),
            'mutable': 'true'
        }, {
            'name': 'bus_clk',
            'freq': str(100e6),
        }]