Skip to content
Snippets Groups Projects
hardware.py 1.87 KiB
Newer Older
# -*- encoding: utf-8 -*-

import re
import subprocess
import sys
import os
import logging

class Hardware(object):
    """
    Inspect system for supported via USB connected devices.

    Currently supportd devices:
        * HackRF One
        * LTR-SDR DVB-T stick
    """
    SUPPORTED_HARDWARE = {
        "hackrfone": "1d50:cc15", # rad1o and hackrf one has the same id :/
        "rtlsdr": "0bda:2838"     # Realtek Semiconductor Corp. RTL2838 DVB-T
    }

    def get_usb_devices(self):
        """
        Parse lsusb output and return a list of dictionaries.
        """
        devices = []

        lsusb_output = subprocess.check_output("lsusb", shell=True)
        for line in lsusb_output.split("\n"):
            if re.match("^Bus", line):
                device = self._parse_lsusb_line(line)
                devices.append(device)
            else:
                continue

        return devices

    def get_connected_supported_devices(self):
        """
        Get all connected devices
        """
        devices = self.get_usb_devices()

        connected_devices = []
        for device in devices:
            if self._supported_device(self, device):
                connected_devices.append(device)
            else:
                continue

        return connected_devices

    @staticmethod
    def _parse_lsusb_line(line):
        """
        Splitt lsusb line in useful key values.
        """
        device = {}
        device_unsorted = line.split(" ")

        device['bus'] = device_unsorted[1]
        device['device'] = device_unsorted[3]
        device['id'] = device_unsorted[5]
        device['name'] = " ".join(device_unsorted[6:])

        return device

    @staticmethod
    def _supported_device(self, device):
        """
        Check if a given device is supported.
        """
        return device['id'] in self.SUPPORTED_HARDWARE.values()