Ejemplo n.º 1
1
def read_hid_device():
    global last_status
    global vervose
    while 1:
        if output_file:
            f = open(output_file,'w')
            f.write('0')
            f.close()
        print 0
        try:
            h = hid.device(VENDOR_ID, PRODUCT_ID)
            h.open(VENDOR_ID, PRODUCT_ID)
            print "Device opened..."

            ### non-blocking mode
            #h.set_nonblocking(1)

            while 1:
                d = h.read(338)
                if d:
                    last_status = process_data(d,last_status,vervose)
                    if not vervose: 
                        print last_status
                    if output_file:    
                        f = open(output_file,'w')
                        f.write(last_status)
                        f.close()
                time.sleep(0.05)

            h.close()

        except IOError, ex:
            print "Searching for device..."
            time.sleep(5)    
Ejemplo n.º 2
1
    def __init__(self,**kwargs):
        import hid

        serial = kwargs.get('serial', None)
        if serial: serial = six.text_type(serial)
        print(serial, type(serial))

        self.driver_type = 'hid'
        self.h = hid.device()
        self.h.open(0x10C4, 0xEA90, serial) # Connect HID again after enumeration
        self.h.write([0x02, 0xFF, 0x00, 0x00, 0x00])  # Set GPIO to Open-Drain
        for k in range(3):      # blinking LED
            self.h.write([0x04, 0x00, 0xFF])
            time.sleep(0.05)
            self.h.write([0x04, 0xFF, 0xFF])
            time.sleep(0.05)

        self.gpio_direction = 0x00   # 0 - input, 1 - output
        self.gpio_pushpull  = 0x00   # 0 - open-drain, 1 - push-pull
        self.gpio_special   = 0x00   # only on bits 0-2,  0 standard gpio, 1 special function as LED, CLK out
        self.gpio_clockdiv  = 0x00   # see manual for more info..

        if kwargs.get('led', True):     # Set GPIO to RX/TX LED
            self.gpio_direction = 0x02
            self.gpio_pushpull  = 0xFF
            self.gpio_special   = 0xFF

        self.h.write([0x02, self.gpio_direction, self.gpio_pushpull, self.gpio_special, self.gpio_clockdiv])  # initialize GPIO

        # Set SMB Configuration (AN 495)
        self.h.write([0x06, 0x00, 0x01, 0x86, 0xA0, 0x02, 0x00, 0x00, 0xFF, 0x00, 0xFF, 0x01, 0x00, 0x0F])
Ejemplo n.º 3
0
    def __init__(self):
        """ Initialize the CO2monitor object and retrieve basic HID info.
        """
        self._info = {'vendor_id': _CO2MON_HID_VENDOR_ID,
                      'product_id': _CO2MON_HID_PRODUCT_ID}
        self._h = hid.device()
        # Number of requests to open connection
        self._status = 0

        self._magic_word = [((w << 4) & 0xFF) | (w >> 4)
                            for w in bytearray(_CO2MON_MAGIC_WORD)]
        self._magic_table = _CO2MON_MAGIC_TABLE
        self._magic_table_int = list_to_longint(_CO2MON_MAGIC_TABLE)

        # Initialisation of continuous monitoring
        if pd is None:
            self._data = []
        else:
            self._data = pd.DataFrame()

        self._keep_monitoring = False
        self._interval = 10

        # Device info
        with self.co2hid():
            self._info['manufacturer'] = self._h.get_manufacturer_string()
            self._info['product_name'] = self._h.get_product_string()
            self._info['serial_no'] = self._h.get_serial_number_string()
Ejemplo n.º 4
0
    def open(self) -> None:
        self.handle = hid.device()
        try:
            self.handle.open_path(self.path)
        except (IOError, OSError) as e:
            if sys.platform.startswith("linux"):
                e.args = e.args + (UDEV_RULES_STR,)
            raise e

        # On some platforms, HID path stays the same over device reconnects.
        # That means that someone could unplug a Trezor, plug a different one
        # and we wouldn't even know.
        # So we check that the serial matches what we expect.
        serial = self.handle.get_serial_number_string()
        if serial != self.serial:
            self.handle.close()
            self.handle = None
            raise TransportException(
                "Unexpected device {} on path {}".format(serial, self.path.decode())
            )

        self.handle.set_nonblocking(True)

        if self.hid_version is None:
            self.hid_version = self.probe_hid_version()
Ejemplo n.º 5
0
 def __init__(self, path):
     self.path = path
     self.color = BLACK
     self.blink = 0
     self.connection = hid.device(None, None, path)
     self.connection.set_nonblocking(1)
     self.turn_off()
Ejemplo n.º 6
0
def getDongle(debug=False):
	dev = None
	hidDevicePath = None
	for hidDevice in hid.enumerate(0, 0):
		if hidDevice['vendor_id'] == 0x2581 and hidDevice['product_id'] == 0x2b7c:
			hidDevicePath = hidDevice['path']
		if hidDevice['vendor_id'] == 0x2581 and hidDevice['product_id'] == 0x1807:
			hidDevicePath = hidDevice['path']
	if hidDevicePath is not None:
		dev = hid.device()
		dev.open_path(hidDevicePath)
		dev.set_nonblocking(True)
		return HIDDongleHIDAPI(dev, debug)
	if WINUSB:
		dev = usb.core.find(idVendor=0x2581, idProduct=0x1b7c) # core application, WinUSB
		if dev is not None:
			return WinUSBDongle(dev, debug)
		dev = usb.core.find(idVendor=0x2581, idProduct=0x1808) # bootloader, WinUSB
		if dev is not None:
			return WinUSBDongle(dev, debug)
		dev = usb.core.find(idVendor=0x2581, idProduct=0x2b7c) # core application, Generic HID
		if dev is not None:
			return HIDDongle(dev, debug)
		dev = usb.core.find(idVendor=0x2581, idProduct=0x1807) # bootloader, Generic HID
		if dev is not None:
			return HIDDongle(dev, debug)
	raise BTChipException("No dongle found")
Ejemplo n.º 7
0
 def _open(self):
     self.buffer = ''
     self.hid = hid.device()
     self.hid.open_path(self.device)
     self.hid.set_nonblocking(True)
     self.hid.send_feature_report([0x41, 0x01]) # enable UART
     self.hid.send_feature_report([0x43, 0x03]) # purge TX/RX FIFOs
Ejemplo n.º 8
0
	def __init__(self):
		self.d = hid.device(0x054c,0x1000)
		self.d.open(0x054c,0x1000)
		self.d.set_nonblocking(1)
		self.ON_state = 0xFF
		self.OFF_state = 0x00
		self.lamps = [self.OFF_state,self.OFF_state,self.OFF_state,self.OFF_state]
Ejemplo n.º 9
0
    def __init__(self, vendor_id, product_id, config=None):
        self._vid = vendor_id   #Keyboard vendor id (6000 for MSI)
        self._pid = product_id  #Keyboard id (65280 for MSI gaming keyboard)

        # Creating the device instance:
        self._device = device()
        # And opening the wanted one:
        try:
            self._device.open(self._vid, self._pid)
        except IOError:
            raise IOError("Unable to open device (%x, %x)" % (self._vid, self._pid))

        # Loading the default configuration:
        if config is not None:
            self._config = config
        else:
            self._config = dict(
                mode="normal",
                left=dict(
                    color="red",
                    level="high",
                ),
                middle=dict(
                    color="sky",
                    level="high",
                ),
                right=dict(
                    color="purple",
                    level="high",
                )
            )
Ejemplo n.º 10
0
    def getAllConnectedTargets(vid, pid):
        """
        returns all the connected devices which matches HidApiUSB.vid/HidApiUSB.pid.
        returns an array of HidApiUSB (Interface) objects
        """

        devices = hid.enumerate(vid, pid)

        if not devices:
            logging.debug("No USB device connected")
            return

        targets = []

        for deviceInfo in devices:
            try:
                dev = hid.device(vendor_id=vid, product_id=pid, path=deviceInfo['path'])
            except IOError:
                logging.debug("Failed to open USB device")
                return

            # Create the USB interface object for this device.
            new_target = HidApiUSB()
            new_target.vendor_name = deviceInfo['manufacturer_string']
            new_target.product_name = deviceInfo['product_string']
            new_target.vid = deviceInfo['vendor_id']
            new_target.pid = deviceInfo['product_id']
            new_target.device = dev

            targets.append(new_target)

        return targets
Ejemplo n.º 11
0
 def raw_loopback(self, report_size):
     """Send every input report back to the device."""
     mbed_hid_path = None
     mbed_hid = hid.device()
     try:
         mbed_hid_path = retry_fun_call(
             fun=functools.partial(self.get_usb_hid_path, self.dut_usb_dev_sn),  # pylint: disable=not-callable
             num_retries=20,
             retry_delay=0.05)
         retry_fun_call(
             fun=functools.partial(mbed_hid.open_path, mbed_hid_path),  # pylint: disable=not-callable
             num_retries=10,
             retry_delay=0.05)
     except RetryError as exc:
         self.notify_error(exc)
         return
     # Notify the device it can send reports now.
     self.send_kv(MSG_KEY_HOST_READY, MSG_VALUE_DUMMY)
     try:
         for _ in range(RAW_IO_REPS):
             # There are no Report ID tags in the Report descriptor.
             # Receiving only the Report Data, Report ID is omitted.
             report_in = mbed_hid.read(report_size)
             report_out = report_in[:]
             # Set the Report ID to 0x00 (not used).
             report_out.insert(0, 0x00)
             mbed_hid.write(report_out)
     except (ValueError, IOError) as exc:
         self.notify_failure('HID Report transfer failed. {}'.format(exc))
     finally:
         mbed_hid.close()
Ejemplo n.º 12
0
	def __init__(self):
		"""Creates a HID_Comm object - initializing the underlying USB HID Generia device driver"""
		self.hiddev = hid.device()
		self.prefix = []
		if platform.system() == 'Windows':
			self.prefix=[0x80]
		self.isopen=False
def update(in_file, block_id=0x18, reset_id=0xFC, vid=0x7722, pid=0x1200, log_file_handler=None):
    with open(in_file, 'rb') as f:
        h = hid.device()
        try:
            h.open(vid, pid)
            num = 0
            while(f):
                kb = f.read(1024)
                if(len(kb) == 0):
                    break
                block = [0]*65 + [x for x in bytearray(kb)]
                block[1] = block_id
                block[4] = block_id
                block[5] = num & 0xFF
                block[6] = (num >> 8) & 0xFF
                n = h.write(block)
                if n != 1089:
                    log("block write failed", log_file_handler)
                    break
                num += 1
            block = [0]*1089
            block[1] = reset_id
            block[4] = reset_id
            n = h.write(block)
            if n != 1089:
                log("erase " + hex(reset_id) + " failed", log_file_handler)
        finally:
            h.close()
Ejemplo n.º 14
0
    def openDevice(self, serialNumber=None):
        """Open a USB-ADC2 device.

        If serialNumber is not None, the device with the given serial number is opened,
        otherwise the serial number supplied to the constructor is used.

        Args:
            serialNumber (Optional[int]): Serial number of the ADC to open. If None is given,
                                          the serial number supplied to the constructor is used.

        Raises:
            IOError: If the USB-ADC2 with the requested serial number could not be found.
        """
        if serialNumber is not None:
            self.serialNumber = serialNumber

        hidEnum = hid.enumerate()
        self.path = None
        for dev in hidEnum:
            if dev['vendor_id'] == self.vendorId and dev['product_id'] == self.productId:
                if int(dev['serial_number'], 16) == self.serialNumber:
                    self.path = dev['path']

        if self.path is None:
            raise IOError('Could not find ADC with serial number {}'.format(self.serialNumber))

        self.handle = hid.device()
        self.handle.open_path(self.path)
        self.resetDevice()
Ejemplo n.º 15
0
    def run(self):
        # 首先上报设备数据
        for device_id in self.devices_info_dict:
            device_info = self.devices_info_dict[device_id]
            device_msg = {
                "device_id": device_info["device_id"],
                "device_type": device_info["device_type"],
                "device_addr": device_info["device_addr"],
                "device_port": device_info["device_port"],
                "protocol": self.protocol.protocol_type,
                "data": ""
            }
            self.mqtt_client.publish_data(device_msg)

        # 打印hid设备信息
        for d in hid.enumerate(0, 0):
            keys = d.keys()
            keys.sort()
            for key in keys:
                logger.debug("%s : %s" % (key, d[key]))
            logger.debug("")

        # 打开设备
        try:
            hid_device = hid.device(self.vendor_id, self.product_id)
        except Exception, e:
            logger.error("hid.device exception: %r." % e)
            return
Ejemplo n.º 16
0
def open_usb_device(device_type, vendor_id, product_id):
    try:
        device = hid.device()
        device.open(vendor_id, product_id)
        return device, device_type
    except IOError:
        return None, None
Ejemplo n.º 17
0
    def __init__(self):
        TabbedPanel.__init__(self)

        self.device=hid.device()
        self.device.open(6000,65280) #MSI keyboard

        self.region_colors=[1,4,6]
        self.region_intensity=[1,1,1]
Ejemplo n.º 18
0
 def get_btchip_device(self, device):
     ledger = False
     if (device.product_key[0] == 0x2581 and device.product_key[1] == 0x3b7c) or (device.product_key[0] == 0x2581 and device.product_key[1] == 0x4b7c) or (device.product_key[0] == 0x2c97):
        ledger = True        
     dev = hid.device()
     dev.open_path(device.path)
     dev.set_nonblocking(True)
     return HIDDongleHIDAPI(dev, ledger, BTCHIP_DEBUG)
    def openDevice( self ):
        print "# Opening device"
        self.device = hid.device()
        self.device.open( self.USB_VID, self.USB_PID )

        print "Manufacturer: %s" % self.device.get_manufacturer_string()
        print "Product: %s" % self.device.get_product_string()
        print "Serial No: %s" % self.device.get_serial_number_string()
Ejemplo n.º 20
0
 def open(self, path):
     print "Opening %s" % path
     self._device = hid.device()
     self._device.open_path(path)
     if self._device is None:
         return False
     self._device.set_nonblocking(1)
     return True
Ejemplo n.º 21
0
 def __init__(self):
     if HIDAPI_AVAILABLE:
         self.device = hid.device()
     else:
         self.device = None
     self.manufacturer = None
     self.product = None
     self.serial = None
     self.ldrom = False
Ejemplo n.º 22
0
    def _connect(self):
        connected = False
        for product_id in PRODUCT_IDS:
            try:
                if hasattr(hid.device, 'open'):
                    self._machine = hid.device()
                    self._machine.open(VENDOR_ID, product_id)
                else:
                    self._machine = hid.device(VENDOR_ID, product_id)
            except IOError:
                self._machine = None
            else:
                self._machine.set_nonblocking(0)
                self._ready()
                connected = True
                break

        return connected
Ejemplo n.º 23
0
def get_hid_device():
    valid_hid_devices = hid.enumerate(vendor_id=0x03EB,
                                      product_id=0x2067)

    if len(valid_hid_devices) is 0:
        return None
    else:
        hid_device = hid.device()
        hid_device.open_path(valid_hid_devices[0]['path'])
        return hid_device
Ejemplo n.º 24
0
    def start(self):

        self.manager = Manager()
        self.dict = self.manager.dict()
        self.dict.device = hid.device()
        self.dict.device.open(0x0416, 0xFFFF)
        # self.dict.device.hid_set_nonblocking(self.device,1)
        print "start"
        self.buffer = []
        self.bufferIndex = 0
    def __init__(self, vid=0, pid=0, serial=None):
        try:
            self._device = hid.device()
            self._device.open(vid, pid)
        except OSError as error:
            sys.stderr.write("Error: {}".format(error))

        self.jtag_id = None
        self.device_revision = None
        self.bootloader_revision = None
Ejemplo n.º 26
0
    def readPacket(self):

        try:

            if self.hidGoGo == None:
                #print "in Read Packet - reconnecting"
                self.hidGoGo = hid.device(self.GOGO_VEDOR_ID, self.GOGO_PRODUCT_ID)


            #print "Opening device"

            #h = hid.device(0x2405, 0x000a)
            #h = hid.device(0x1941, 0x8021) # Fine Offset USB Weather Station

            #print "Manufacturer: %s" % self.hidGoGo.get_manufacturer_string()
            #print "Product: %s" % self.hidGoGo.get_product_string()
            #print "Serial No: %s" % self.hidGoGo.get_serial_number_string()

            # try non-blocking mode by uncommenting the next line
            self.hidGoGo.set_nonblocking(1) # makes read() returns 0 if input buffer is empty

            d = self.hidGoGo.read(64)

            if len(d) == 63:
                self.countNoData = 0
                output = d
                # while len(d) == 63:
                #     output = d
                #     d = self.hidGoGo.read(64)

                return output

            elif len(d) == 0:  # no data
                self.countNoData += 1
                # if error is not null, then assume connection error and attempt to re-connect
                if self.hidGoGo.error() != "":
                    self.hidGoGo.close()
                    self.hidGoGo = None
                    return -1
                elif self.countNoData > 20:
                    self.countNoData = 0
                    self.hidGoGo = None
                    return -1
                else:
                    return None

            else:
                print "unknown read packet len " + str(len(d))
                return -1

        except IOError, ex:
            #print "in Read Packet, " + str(ex)
            self.hidGoGo = None
            #return None
            return -1
Ejemplo n.º 27
0
def load_driver(**kwargs):
    device = kwargs.get("device", None)
    port = kwargs.get("port", None)
    serial = kwargs.get("serial", None)
    print(kwargs)

    if (device == "hid") or (device == None):
        try:
            LOGGER.info("Loading HID driver...")
            import hid
            LOGGER.info("Initiating HID driver...")
            try:
                if serial: serial = unicode(serial)

                h = hid.device()
                h.open(0x10C4, 0xEA90, serial) # Try Connect HID
                kwargs['serial'] = h.get_serial_number_string()
                LOGGER.info("Using HID with serial number: '%s' " %(h.get_serial_number_string()))
                h.write([0x01, 0x01]) # Reset Device for cancelling all transfers and reset configuration
                h.close()
                time.sleep(1) # wait for system HID (re)mounting
                return HIDDriver(**kwargs) # We can use this connection

            except IOError:
                LOGGER.warning("HID device does not exist, we will try SMBus directly... (1)")

        except ImportError:
            LOGGER.warning("HID driver cannot be imported, we will try SMBus driver...(2)")


    if (device == "smbus" or device == None) and (port is not None):
        try:
            import smbus
            LOGGER.info("Loading SMBus driver...")
            return SMBusDriver(port, smbus.SMBus(int(port)))
        except ImportError:
            LOGGER.warning("Failed to import 'smbus' module. SMBus driver cannot be loaded.")
    if (device == "smbus") and (port is None):
        LOGGER.error("Port of SMBus must be specified")

    if device == "serial" or device == None:
            try:
                if port == None:
                    serial_port = "/dev/ttyUSB0"
                else:
                    serial_port = str(port)
                LOGGER.info("Loading SERIAL driver...")
                import serial
                return SerialDriver(serial_port)

            except ImportError:
                    LOGGER.warning("Failed to import 'SC18IM700' driver. I2C232 driver cannot be loaded for port %s." %(serial_port))


    raise RuntimeError("Failed to load I2C driver. Enable logging for more details.")
Ejemplo n.º 28
0
def open_u2f(SN=None):
    h = hid.device()
    try:
        h.open(0x10c4,0x8acf,SN if SN is None else unicode(SN))
        print('opened ', SN)
    except IOError as ex:
        print( ex)
        if SN is None: print( 'U2F Zero not found')
        else: print ('U2F Zero %s not found' % SN)
        sys.exit(1)
    return h
Ejemplo n.º 29
0
def get_hid_device_handle():
    all_hid_devices = hid.enumerate()

    lufa_hid_devices = [d for d in all_hid_devices if d['vendor_id'] == 0x1209 and d['product_id'] == 0x8473]

    if len(lufa_hid_devices) is 0:
        return None

    device_handle = hid.device()
    device_handle.open_path(lufa_hid_devices[0]['path'])
    return device_handle
Ejemplo n.º 30
0
 def __init__(self):
     super(USBScaleMac, self).__init__()
     self.device = hid.device()
     try:
         self.device.open(self.VENDOR_ID, self.PRODUCT_ID)
     except IOError:
         sys.stdout.write("\rDevice appears to be busy, please check that "
                          "it is not in use by another process")
         sys.stdout.flush()
     self.device.set_nonblocking(1)
     self.raw_weight = self.read()
Ejemplo n.º 31
0
 def get_dbb_device(self, device):
     dev = hid.device()
     dev.open_path(device.path)
     return dev
Ejemplo n.º 32
0
 def __init__(self, device_info):
     self.hid_info = device_info
     self.hid = hid.device()
Ejemplo n.º 33
0
 def run(self):
     self.player.launcher = hid.device(0x0a81, 0x0701)
     self.player.launcher.set_nonblocking(1)
Ejemplo n.º 34
0
 def __init__(self, vid=MINIDSP_2x4HD_VID, pid=MINIDSP_2x4HD_PID):
     self._vid = vid
     self._pid = pid
     self._device = hid.device()
     self._opened = False
Ejemplo n.º 35
0
 def open(self):
     h = hid.device()
     h.open(vendor_id=__VENDORID, product_id=__PRODUCTID)
     h.set_nonblocking(False)
     self._hid = h
Ejemplo n.º 36
0
 def __init__(self):
     try:
         self.h = hid.device()
     except:
         print('Error creating hid device')
Ejemplo n.º 37
0
def connect_to_usb_bitbox(debug: bool, use_cache: bool) -> int:
    """
    Connects and runs the main menu on a BitBox02 connected
    over USB.
    """
    try:
        bitbox = devices.get_any_bitbox02()
    except devices.TooManyFoundException:
        print("Multiple bitboxes detected. Only one supported")
        return 1
    except devices.NoneFoundException:
        try:
            bootloader = devices.get_any_bitbox02_bootloader()
        except devices.TooManyFoundException:
            print("Multiple bitbox bootloaders detected. Only one supported")
            return 1
        except devices.NoneFoundException:
            print("Neither bitbox nor bootloader found.")
            return 1
        else:
            hid_device = hid.device()
            hid_device.open_path(bootloader["path"])
            bootloader_connection = bitbox02.Bootloader(
                u2fhid.U2FHid(hid_device), bootloader)
            boot_app = SendMessageBootloader(bootloader_connection)
            return boot_app.run()
    else:

        def show_pairing(code: str, device_response: Callable[[],
                                                              bool]) -> bool:
            print(
                "Please compare and confirm the pairing code on your BitBox02:"
            )
            print(code)
            if not device_response():
                return False
            return input("Accept pairing? [y]/n: ").strip() != "n"

        class NoiseConfig(util.NoiseConfigUserCache):
            """NoiseConfig extends NoiseConfigUserCache"""
            def __init__(self) -> None:
                super().__init__("shift/send_message")

            def show_pairing(self, code: str,
                             device_response: Callable[[], bool]) -> bool:
                return show_pairing(code, device_response)

            def attestation_check(self, result: bool) -> None:
                if result:
                    print("Device attestation PASSED")
                else:
                    print("Device attestation FAILED")

        class NoiseConfigNoCache(bitbox_api_protocol.BitBoxNoiseConfig):
            """NoiseConfig extends BitBoxNoiseConfig"""
            def show_pairing(self, code: str,
                             device_response: Callable[[], bool]) -> bool:
                return show_pairing(code, device_response)

            def attestation_check(self, result: bool) -> None:
                if result:
                    print("Device attestation PASSED")
                else:
                    print("Device attestation FAILED")

        if use_cache:
            config: bitbox_api_protocol.BitBoxNoiseConfig = NoiseConfig()
        else:
            config = NoiseConfigNoCache()

        hid_device = hid.device()
        hid_device.open_path(bitbox["path"])
        bitbox_connection = bitbox02.BitBox02(
            transport=u2fhid.U2FHid(hid_device),
            device_info=bitbox,
            noise_config=config)
        try:
            bitbox_connection.check_min_version()
        except FirmwareVersionOutdatedException as exc:
            print("WARNING: ", exc)

        if debug:
            print("Device Info:")
            pprint.pprint(bitbox)
        return SendMessage(bitbox_connection, debug).run()
Ejemplo n.º 38
0
 def __init__(self):
     self._hid = hid.device()
     self._hid.open(MCP2221.VID, MCP2221.PID)
     self._reset()
Ejemplo n.º 39
0
#
# testing the I2C response to the PIC16High Bootloader
#
import hid

h = hid.device(1240, 0x3f)

h.write([0x20])  #initialize the I2C port
if (h.read(64)[0] == 0x20):
    print "I2C init ok"

print "sending Info command"
h.write([0x22, 0x90, 2, 2, 0])  # command 2 -> info
r = h.read(64)
if (r[0] == 254):
    print "Nack"
elif (r[0] == 255):
    print "Stuck"
elif (r[0] == 0x22):
    print "Command OK"

# now send the read command to get the Info block
print "Sending a read command"
h.write([0x21, 0x91, 60])
r = h.read(64)

if (r[0] == 0x21):
    print r
elif (r[0] == 254):
    print "Nack"
elif (r[0] == 255):
Ejemplo n.º 40
0
def initialize():
    global hidhandle
    hidhandle = hid.device()
    hidhandle.open(0x1200, 0x001)
    hidhandle.set_nonblocking(1)
Ejemplo n.º 41
0
#
# graph.py
#
# reads "potentiometer" value from  HID Simple demo
#
import hid
import time

# clear screen
print "\x1b[2J\x1b[1;1H"   

try:
    h = hid.device(0x4d8, 0x3f)
   
    while True:
        # test the button status
	    h.write( [0x37])
        d = h.read(3)
        if d:
            print "*".rjust( (d[1]+d[2]*256) >> 4 )
            time.sleep(0.1)

    print "Closing device"
    h.close()

except IOError, ex:
    print ex
    print "You probably don't have the hard coded test hid. Update the hid.device line"
    print "in this script with one from the enumeration list output above and try again."

print "Done"
Ejemplo n.º 42
0
def run_hid_process():

    paths = []

    for d in hid.enumerate(VENDOR_ID, PRODUCT_ID):
        if int(d['interface_number']) == 2:
            paths.append(d['path'])
            print(d['path'])
        # keys = list(d.keys())
        # keys.sort()
        # print(d['path'])
        # for key in keys:
        #     print("%s : %s" % (key, d[key]))
        # print()
    #

    # device = hid.device()
    # # device.open(VENDOR_ID, PRODUCT_ID)
    #
    #
    # print(dir(device))
    # print(device)
    #
    # device.close()
    #
    # import sys
    # sys.exit()

    devices = [hid.device(), hid.device()]
    # devices = [hid.device()]
    devices[0].open_path(paths[0])
    devices[1].open_path(paths[1])

    for device in devices:
        # device = hid.device()
        # device.open(VENDOR_ID, PRODUCT_ID)
        print('Connected to ecam {}\n'.format(PRODUCT_ID))

        timeout = 0

        # First just read LED Control status, as a test.

        g_out_packet_buf = [0, 0]
        g_out_packet_buf[0] = CAMERA_CONTROL_FSCAM_CU135
        g_out_packet_buf[1] = GET_LED_CONTROL_FSCAM_CU135

        device.write(g_out_packet_buf)
        time.sleep(0.5)

        data = device.read(BUFFER_LENGTH, timeout)
        print(data)

        # if data[6]==GET_SUCCESS:
        if data[0] == CAMERA_CONTROL_FSCAM_CU135 and data[
                1] == GET_LED_CONTROL_FSCAM_CU135 and data[6] == GET_SUCCESS:
            ledstatus = data[2]
            powerctl = data[3]
            stream = data[4]
            trigger = data[5]
            print("ledstatus {}, powerctl {}, stream {}, trigger {}".format(
                ledstatus, powerctl, stream, trigger))
        else:
            print("GET_FAILED")

        # Now set LED control to indicate when hardware trigger has activated.

        g_out_packet_buf = [0, 0, 0, 0, 0, 0]
        # /* set camera control code */
        g_out_packet_buf[0] = CAMERA_CONTROL_FSCAM_CU135
        # /* set led control code */
        g_out_packet_buf[1] = SET_LED_CONTROL_FSCAM_CU135
        g_out_packet_buf[2] = ENABLE_LED_CONTROL_FSCAM_CU135
        g_out_packet_buf[3] = DISABLE_STREAMING_CONTROL_FSCAM_CU135
        g_out_packet_buf[4] = ENABLE_TRIGGERACK_CONTROL_FSCAM_CU135
        g_out_packet_buf[5] = DISABLE_POWERON_CONTROL_FSCAM_CU135
        device.write(g_out_packet_buf)
        time.sleep(0.5)

        data = device.read(BUFFER_LENGTH, timeout)
        # print(data)

        # Finally set trigger control.

        g_out_packet_buf = [0, 0, 0, 0]
        # /* set camera control code */
        g_out_packet_buf[1] = CAMERA_CONTROL_FSCAM_CU135
        # /* set stream mode code */
        g_out_packet_buf[2] = SET_STREAM_MODE_FSCAM_CU135
        # /* actual stream mode */
        g_out_packet_buf[3] = STREAM_HARDWARE_TRIGGER
        # g_out_packet_buf[3] = STREAM_MASTER_CONTINUOUS  # NOTE: Uncomment this to select auto trigger.

        device.write(g_out_packet_buf)

        time.sleep(2)

        data = device.read(BUFFER_LENGTH, timeout)
        if data[0] == CAMERA_CONTROL_FSCAM_CU135 and data[
                1] == SET_STREAM_MODE_FSCAM_CU135 and data[6] == SET_SUCCESS:
            print("SUCCESS")
        else:
            print("FAILED")

        time.sleep(2)

    print("RUNNING HID FRAME GRAB")
    while True:
        sample_time = time.time()
        for device in devices:
            # In hardware trigger mode we must continually request the next frame.
            # // camera control id
            g_out_packet_buf[1] = CAMERA_CONTROL_FSCAM_CU135
            g_out_packet_buf[2] = GRAB_PREVIEW_FRAME  # // query frame
            # // query next frame - 0x01 , query prev frame - 0x02
            g_out_packet_buf[3] = QUERY_NEXT_FRAME
            device.write(g_out_packet_buf)
            time.sleep(0.001)
            # data = device.read(BUFFER_LENGTH, timeout)
            # if data[6] == GET_SUCCESS and device == devices[0]:
            #     print(time.time() - sample_time)
            #     sample_time = time.time()
            # print(time.time())
        time.sleep(0.001)
Ejemplo n.º 43
0
 def open(self, path):
     self._device = hid.device()
     self._device.open_path(path)
Ejemplo n.º 44
0
#!/usr/bin/env python3

import hid

REPORT_ID = 1
VENDOR_ID = 0x27b8
PRODUCT_ID = 0x01ed

devs = hid.enumerate( VENDOR_ID, PRODUCT_ID)
#print(devs)
serials = []
for d in devs:
    print(d)
    serials.append(d.get('serial_number'))

serialz = map(lambda d:d.get('serial_number'), devs)

serial_number = None

#devs = map(lambda d: print(d), devs)
print("serials:", serials)
print("serialz:", serialz)

hidraw = hid.device( VENDOR_ID, PRODUCT_ID, serial_number )
hidraw.open( VENDOR_ID, PRODUCT_ID, serial_number )
#hidraw.send_feature_report([0x02, 0x10, 0x00,0x00,0x00,0x00,0x00,0x00])
featureReport = [REPORT_ID, 99, 255, 0, 255, 0, 11, 0, 0];
hidraw.send_feature_report( featureReport )
Ejemplo n.º 45
0
    def __init__(self, parent=None):
        super(Display, self).__init__(parent)

        hbox = QtGui.QHBoxLayout()
        grid_left = QtGui.QGridLayout()
        grid_right = QtGui.QGridLayout()

        self.red = QtGui.QPixmap("images/statusRed.png").scaled(
            QtCore.QSize(30, 30))
        self.green = QtGui.QPixmap("images/statusGreen.png").scaled(
            QtCore.QSize(30, 30))

        self.colors = [self.red, self.green]

        self.pins = [
            "GND1", "D-", "D+", "GND4", "RC0", "RC1", "RC2", "RC3", "RC4",
            "RC5", "RA3", "RA4", "RA5", "VDD"
        ]

        self.button_toggle = {
            'RC0': QtGui.QPushButton("TOGGLE"),
            'RC1': QtGui.QPushButton("TOGGLE"),
            'RC2': QtGui.QPushButton("TOGGLE"),
            'RC3': QtGui.QPushButton("TOGGLE"),
            'RC4': QtGui.QPushButton("TOGGLE"),
            'RC5': QtGui.QPushButton("TOGGLE"),
            'RA3': QtGui.QPushButton("TOGGLE"),
            'RA4': QtGui.QPushButton("TOGGLE"),
            'RA5': QtGui.QPushButton("TOGGLE")
        }

        self.button_pulse = {
            'RC0': QtGui.QPushButton("PULSE"),
            'RC1': QtGui.QPushButton("PULSE"),
            'RC2': QtGui.QPushButton("PULSE"),
            'RC3': QtGui.QPushButton("PULSE"),
            'RC4': QtGui.QPushButton("PULSE"),
            'RC5': QtGui.QPushButton("PULSE"),
            'RA3': QtGui.QPushButton("PULSE"),
            'RA4': QtGui.QPushButton("PULSE"),
            'RA5': QtGui.QPushButton("PULSE")
        }

        self.status = {
            'RC0': QtGui.QLabel(self),
            'RC1': QtGui.QLabel(self),
            'RC2': QtGui.QLabel(self),
            'RC3': QtGui.QLabel(self),
            'RC4': QtGui.QLabel(self),
            'RC5': QtGui.QLabel(self),
            'RA3': QtGui.QLabel(self),
            'RA4': QtGui.QLabel(self),
            'RA5': QtGui.QLabel(self),
            'GND1': None,
            'GND4': None,
            'D-': None,
            'D+': None,
            'VDD': None
        }

        self.label = {
            'GND1': QtGui.QLabel("GROUND"),
            'D-': QtGui.QLabel("D-"),
            'D+': QtGui.QLabel("D+"),
            'GND4': QtGui.QLabel("GROUND"),
            'RC0': QtGui.QLabel("RC0"),
            'RC1': QtGui.QLabel("RC1"),
            'RC2': QtGui.QLabel("RC2"),
            'RC3': QtGui.QLabel("RC3"),
            'RC4': QtGui.QLabel("RC4"),
            'RC5': QtGui.QLabel("RC5"),
            'RA3': QtGui.QLabel("RA3"),
            'RA4': QtGui.QLabel("RA4"),
            'RA5': QtGui.QLabel("RA5"),
            'VDD': QtGui.QLabel("VDD")
        }

        for key in self.label:
            self.label[key].setMinimumHeight(30)

        # #### LEFT GRID #### #

        grid_left.setRowStretch(0, 1)
        # Pin 1: GND
        for i in range(7):
            key = self.pins[i]
            j = i + 1
            if (self.status[key] is not None):
                grid_left.addWidget(self.button_pulse[key], j, 1)
                self.button_pulse[key].clicked.connect(
                    lambda key=key: self.sendPulse(key))
                grid_left.addWidget(self.button_toggle[key], j, 2)
                self.button_toggle[key].clicked.connect(
                    lambda key=key: self.sendToggle(key))
                grid_left.addWidget(self.label[key], j, 3)
                grid_left.addWidget(self.status[key], j, 4)
                self.status[key].setPixmap(self.red)
            else:
                grid_left.addWidget(self.label[key], j, 3, 1, 2)

        # #### CENTER IMAGE #### #
        vbox = QtGui.QVBoxLayout()
        QI = QtGui.QImage("images/board.png").scaled(QtCore.QSize(380, 380))
        boardImg = QtGui.QLabel(self)
        boardImg.setPixmap(QtGui.QPixmap.fromImage(QI))
        vbox.addStretch(1)
        vbox.addWidget(boardImg)

        # #### RIGHT GRID #### #
        grid_right.setRowStretch(0, 1)

        for i in range(7):
            key = self.pins[i + 7]
            j = 14 - i
            if (self.status[key] is not None):
                grid_right.addWidget(self.status[key], j, 1)
                self.status[key].setPixmap(self.red)
                grid_right.addWidget(self.label[key], j, 2)
                grid_right.addWidget(self.button_toggle[key], j, 3)
                self.button_toggle[key].clicked.connect(
                    lambda key=key: self.sendToggle(key))
                grid_right.addWidget(self.button_pulse[key], j, 4)
                self.button_pulse[key].clicked.connect(
                    lambda key=key: self.sendPulse(key))
            else:
                grid_right.addWidget(self.label[key], j, 1, 1, 4)

        hbox.addLayout(grid_left)
        hbox.addLayout(vbox)
        hbox.addLayout(grid_right)

        self.setLayout(hbox)

        self.setWindowTitle("USBreadboardIT")
        # -self.setWindowState(QtCore.Qt.WindowMaximized)

        self.offset = {
            'RC0': 30,
            'RC1': 31,
            'RC2': 32,
            'RC3': 33,
            'RC4': 34,
            'RC5': 35,
            'RA3': 13,
            'RA4': 14,
            'RA5': 15
        }

        self.g = hid.device()
        self.g.open(vendor_id=0xA0A0, product_id=0x0009)
        self.g.write([0x00, 0x02, 0x00, 0x00, 0x00])  # Set mode
        self.g.write([0x00, 0x03])  # Get value
        x = self.g.read(4)
        print(x)

        for i in range(14):
            key = self.pins[i]
            if self.status[key] is not None:
                status = (x[self.offset[key] / 10] >>
                          (self.offset[key] % 10)) & 0x01
                self.status[key].setPixmap(self.colors[status])
Ejemplo n.º 46
0
            print('Requested device not found.')
            sys.exit()
        else:
            print('Available devices:')
            for d in devices:
                print('\t%s' % d['path'].decode('utf-8'))
                for k in sorted(d.keys()):
                    h = k.replace('_', ' ').capitalize()
                    v = d[k].decode('utf-8') if isinstance(d[k],
                                                           bytes) else d[k]
                    print('\t\t%s: %s' % (h, v))
            device = devices[0]
            d_path = device['path'].decode('utf-8')

        print('Reading: %s' % d_path)
        d = hid.device()
        d.open(device['vendor_id'], device['product_id'])
        if args.descriptor:
            pass  # TODO
        while True:
            # TODO: set max packet size based on descriptor
            try:
                data = bytes(d.read(hid_max_pkt_size))
                dout = binascii.hexlify(data).upper()
                dout = b' '.join(dout[i:i + 2]
                                 for i in range(0, len(dout), 2)).strip()
                #dout = ' '.join("{:02x}".format(c) for c in dout)
                print(dout.decode('utf-8'), end='\r')
            except OSError as e:
                print('%s: %s' % (type(e).__name__, e))
                sys.exit()
Ejemplo n.º 47
0
 def open(self):
     if self.count == 0:
         self.handle = hid.device()
         self.handle.open_path(self.path)
         self.handle.set_nonblocking(True)
     self.count += 1
Ejemplo n.º 48
0
class EvtExchanger:
    """
    desc: |
    """
    SelectedDevice = hid.device()
    ListOfDevices = []

    def __init__(self):
        try:
            EvtExchanger.Attached()
            oslogger.info("EventExchanger Initialized")
        except Exception as e:
            raise Exception('EventExchanger (LibUSB) Initialisation Error')

    @staticmethod
    def Device():
        return EvtExchanger

    @staticmethod
    def Attached(matchingkey="EventExchanger"):
        EvtExchanger.ListOfDevices = []
        EvtExchanger.SelectedDevice.close()
        for d in hid.enumerate():
            longname = d["product_string"] + " SN## " + d["serial_number"]
            if matchingkey in longname:
                if EvtExchanger.ListOfDevices == []:
                    EvtExchanger.SelectedDevice.open_path(d['path'])
                    EvtExchanger.SelectedDevice.set_nonblocking(True)
                EvtExchanger.ListOfDevices.append(longname)
        return EvtExchanger.ListOfDevices

    @staticmethod
    def Select(deviceName):
        EvtExchanger.Attached(deviceName)
        return [EvtExchanger.Device()]

    @staticmethod
    def WaitForDigEvents(AllowedEventLines, TimeoutMSecs):
        # flush the buffer!
        while (EvtExchanger.SelectedDevice.read(1) != []):
            continue

        TimeoutSecs = TimeoutMSecs / 1000
        startTime = time.time()

        while 1:
            ElapsedSecs = (time.time() - startTime)
            lastbtn = EvtExchanger.SelectedDevice.read(1)
            if (lastbtn != []):
                if (lastbtn[0] & AllowedEventLines > 0):
                    break
            # break for timeout:
            if (TimeoutMSecs != -1):
                if (ElapsedSecs >= (TimeoutSecs)):
                    lastbtn = [-1]
                    ElapsedSecs = TimeoutSecs
                    break
        return lastbtn[0], round(1000.0 * ElapsedSecs)

    def GetAxis():
        while (EvtExchanger.SelectedDevice.read(1) != []):
            pass
        time.sleep(.01)
        valueList = EvtExchanger.SelectedDevice.read(3)
        if (valueList == []):
            return EvtExchanger.__AxisValue
        EvtExchanger.__AxisValue = valueList[1] + (256 * valueList[2])

        return EvtExchanger.__AxisValue

    '''
        Functions that only require a single USB command to be sent to the device.
    '''

    @staticmethod
    def SetLines(OutValue):
        EvtExchanger.SelectedDevice.write([
            0, EvtExchanger.__SETOUTPUTLINES, OutValue, 0, 0, 0, 0, 0, 0, 0, 0
        ])

    @staticmethod
    def PulseLines(OutValue, DurationInMillisecs):
        EvtExchanger.SelectedDevice.write([
            0, EvtExchanger.__PULSEOUTPUTLINES, OutValue,
            DurationInMillisecs & 255, DurationInMillisecs >> 8, 0, 0, 0, 0, 0,
            0
        ])

    @staticmethod
    def SetAnalogEventStepSize(NumberOfSamplesPerStep):
        EvtExchanger.SelectedDevice.write([
            0, EvtExchanger.__SETANALOGEVENTSTEPSIZE, NumberOfSamplesPerStep,
            0, 0, 0, 0, 0, 0, 0, 0
        ])

    @staticmethod
    def RENC_SetUp(Range, MinimumValue, Position, InputChange,
                   PulseInputDivider):
        EvtExchanger.__AxisValue = Position
        EvtExchanger.SelectedDevice.write([
            0, EvtExchanger.__SETUPROTARYCONTROLLER, Range & 255, Range >> 8,
            MinimumValue & 255, MinimumValue >> 8, Position & 255,
            Position >> 8, InputChange, PulseInputDivider, 0
        ])

    @staticmethod
    def RENC_SetPosition(Position):
        EvtExchanger.__AxisValue = Position
        EvtExchanger.SelectedDevice.write([
            0, EvtExchanger.__SETROTARYCONTROLLERPOSITION, Position & 255,
            Position >> 8, 0, 0, 0, 0, 0, 0, 0
        ])

    @staticmethod
    def SetLedColor(RedValue, GreenValue, BlueValue, LedNumber, Mode):
        EvtExchanger.SelectedDevice.write([
            0, EvtExchanger.__SETWS2811RGBLEDCOLOR, RedValue, GreenValue,
            BlueValue, LedNumber, Mode, 0, 0, 0, 0
        ])

    @staticmethod
    def SendColors(NumberOfLeds, Mode):
        EvtExchanger.SelectedDevice.write([
            0, EvtExchanger.__SENDLEDCOLORS, NumberOfLeds, Mode, 0, 0, 0, 0, 0,
            0, 0
        ])

    __AxisValue = 0

    # CONSTANTS:
    __CLEAROUTPUTPORT = 0  # 0x00
    __SETOUTPUTPORT = 1  # 0x01
    __SETOUTPUTLINES = 2  # 0x02
    __SETOUTPUTLINE = 3  # 0x03
    __PULSEOUTPUTLINES = 4  # 0x04
    __PULSEOUTPUTLINE = 5  # 0x05

    __SENDLASTOUTPUTBYTE = 10  # 0x0A

    __CONVEYEVENT2OUTPUT = 20  # 0x14
    __CONVEYEVENT2OUTPUTEX = 21  # 0x15
    __CANCELCONVEYEVENT2OUTPUT = 22  # 0x16

    __CANCELEVENTREROUTES = 30  # 0x1E
    __REROUTEEVENTINPUT = 31  # 0x1F

    __SETUPROTARYCONTROLLER = 40  # 0x28
    __SETROTARYCONTROLLERPOSITION = 41  # 0x29

    __CONFIGUREDEBOUNCE = 50  # 0x32

    __SETWS2811RGBLEDCOLOR = 60  # 0x3C
    __SENDLEDCOLORS = 61  # 0x3D

    __SWITCHALLLINESEVENTDETECTION = 100  # 0x64
    __SWITCHLINEEVENTDETECTION = 101  # 0x65

    __SETANALOGINPUTDETECTION = 102  # 0x66
    __REROUTEANALOGINPUT = 103  # 0X67
    __SETANALOGEVENTSTEPSIZE = 104  # 0X68

    __SWITCHDIAGNOSTICMODE = 200  # 0xC8
    __SWITCHEVENTTEST = 201  # 0xC9
Ejemplo n.º 49
0
 def findCWSPI(self, VID=0x03EB, PID=0xBAED):
     logging.info('Detecting HID device...')
     self.hdev = hid.device(VID, PID)
     logging.info('Manufacturer: %s' % self.hdev.get_manufacturer_string())
     logging.info('Product: %s' % self.hdev.get_product_string())
Ejemplo n.º 50
0
 def __init__(self, device_path: bytes):
     self._device = hid.device()
     self._device.open_path(device_path)
     # 0 and 0xffffffff are reserved
     self._cid = random.randrange(1, 0xFFFFFFFF)
     self.debug = False
Ejemplo n.º 51
0
def main():
    # Create argument parser to document script use
    parser = argparse.ArgumentParser(description='Set the WiFi connection settings on the demo board.')
    parser.add_argument(
        '--ssid',
        dest='ssid',
        nargs=1,
        required=True,
        metavar='name',
        help='WiFi network name')
    parser.add_argument(
        '--password',
        dest='password',
        nargs=1,
        default=[None],
        metavar='pw',
        help='WiFi network password')
    args = parser.parse_args()

    print('\nOpening AWS Zero-touch Kit Device')
    device = MchpAwsZTKitDevice(hid.device())
    #device = MchpAwsZTKitDevice(SimMchpAwsZTHidDevice())
    device.open()

    print('\nInitializing Kit')
    resp = device.init()
    print('    ATECC508A SN: %s' % resp['deviceSn'])
    
    time.sleep(3)
    
    print('\nSetting WiFi Information')
    device.set_wifi(ssid=args.ssid[0], psk=args.password[0])

    kit_info = read_kit_info()
    kit_info['wifi_ssid'] = args.ssid[0]
    kit_info['wifi_password'] = args.password[0]
    save_kit_info(kit_info)

    print('\nDone setting WiFi')
    
    time.sleep(2)


    # Create argument parser to document script use
    #parser = argparse.ArgumentParser(description='Provisions the kit by requesting a CSR and returning signed certificates.')
    #args = parser.parse_args()

    kit_info = read_kit_info()

    print('\nOpening AWS Zero-touch Kit Device')
    device = MchpAwsZTKitDevice(hid.device())
    #device = MchpAwsZTKitDevice(SimMchpAwsZTHidDevice())
    device.open()

    print('\nInitializing Kit')
    #resp = device.init()
    print('    ATECC508A SN: %s' % resp['deviceSn'])
    print('    ATECC508A Public Key:')
    int_size = int(len(resp['devicePublicKey']) / 2)
    print('        X: %s' % resp['devicePublicKey'][:int_size])
    print('        Y: %s' % resp['devicePublicKey'][int_size:])

    kit_info['device_sn'] = resp['deviceSn']
    save_kit_info(kit_info)

    print('\nLoading root CA certificate')
    if not os.path.isfile(ROOT_CA_CERT_FILENAME):
        raise AWSZTKitError('Failed to find root CA certificate file, ' + ROOT_CA_CERT_FILENAME + '. Have you run ca_create_root first?')
    with open(ROOT_CA_CERT_FILENAME, 'rb') as f:
        print('    Loading from ' + f.name)
        root_ca_cert = x509.load_pem_x509_certificate(f.read(), crypto_be)

    print('\nLoading signer CA key')
    if not os.path.isfile(SIGNER_CA_KEY_FILENAME):
        raise AWSZTKitError('Failed to find signer CA key file, ' + SIGNER_CA_KEY_FILENAME + '. Have you run ca_create_signer_csr first?')
    with open(SIGNER_CA_KEY_FILENAME, 'rb') as f:
        print('    Loading from ' + f.name)
        signer_ca_priv_key = serialization.load_pem_private_key(
            data=f.read(),
            password=None,
            backend=crypto_be)

    print('\nLoading signer CA certificate')
    if not os.path.isfile(SIGNER_CA_CERT_FILENAME):
        raise AWSZTKitError('Failed to find signer CA certificate file, ' + SIGNER_CA_CERT_FILENAME + '. Have you run ca_create_signer first?')
    with open(SIGNER_CA_CERT_FILENAME, 'rb') as f:
        print('    Loading from ' + f.name)
        signer_ca_cert = x509.load_pem_x509_certificate(f.read(), crypto_be)

    if 'endpointAddress' not in kit_info:
        raise AWSZTKitError('endpointAddress not found in %s. Have you run aws_register_signer yet?' % KIT_INFO_FILENAME)

    if 'wifi_ssid' not in kit_info:
        raise AWSZTKitError('wifi_ssid not found in %s. Have you run kit_set_wifi yet?' % KIT_INFO_FILENAME)

    if 'wifi_password' not in kit_info:
        raise AWSZTKitError('wifi_password not found in %s. Have you run kit_set_wifi yet?' % KIT_INFO_FILENAME)

    print('\nRequesting device CSR')
    time.sleep(2)
    resp = device.gen_csr()
    device_csr = x509.load_der_x509_csr(binascii.a2b_hex(resp['csr']), crypto_be)
    if not device_csr.is_signature_valid:
        raise AWSZTKitError('Device CSR has invalid signature.')
    with open(DEVICE_CSR_FILENAME, 'wb') as f:
        print('    Saving to ' + f.name)
        f.write(device_csr.public_bytes(encoding=serialization.Encoding.PEM))

    print('\nGenerating device certificate from CSR')
    # Build certificate
    builder = x509.CertificateBuilder()
    builder = builder.issuer_name(signer_ca_cert.subject)
    builder = builder.not_valid_before(datetime.datetime.now(tz=pytz.utc).replace(minute=0,second=0)) # Device cert must have minutes and seconds set to 0
    builder = builder.not_valid_after(datetime.datetime(3000, 12, 31, 23, 59, 59)) # Should be year 9999, but this doesn't work on windows
    builder = builder.subject_name(device_csr.subject)
    builder = builder.public_key(device_csr.public_key())
    # Device certificate is generated from certificate dates and public key
    builder = builder.serial_number(device_cert_sn(16, builder))
    # Add in extensions specified by CSR
    for extension in device_csr.extensions:
        builder = builder.add_extension(extension.value, extension.critical)
    # Subject Key ID is used as the thing name and MQTT client ID and is required for this demo
    builder = builder.add_extension(
        x509.SubjectKeyIdentifier.from_public_key(builder._public_key),
        critical=False)
    issuer_ski = signer_ca_cert.extensions.get_extension_for_class(x509.SubjectKeyIdentifier)
    builder = builder.add_extension(
        x509.AuthorityKeyIdentifier.from_issuer_subject_key_identifier(issuer_ski),
        critical=False)

    # Sign certificate 
    device_cert = builder.sign(
        private_key=signer_ca_priv_key,
        algorithm=hashes.SHA256(),
        backend=crypto_be)

    # Find the subject key ID for use as the thing name
    is_subject_key_id_found = False
    for extension in device_cert.extensions:
        if extension.oid._name != 'subjectKeyIdentifier':
            continue # Not the extension we're looking for, skip
        kit_info['thing_name'] = binascii.b2a_hex(extension.value.digest).decode('ascii')
        save_kit_info(kit_info)
        is_subject_key_id_found = True
    if not is_subject_key_id_found:
        raise RuntimeError('Could not find the subjectKeyIdentifier extension in the device certificate.')

    # Save certificate for reference
    with open(DEVICE_CERT_FILENAME, 'wb') as f:
        print('    Saving to ' + f.name)
        f.write(device_cert.public_bytes(encoding=serialization.Encoding.PEM))

    print('\nProvisioning device with AWS IoT credentials')
    pub_nums = root_ca_cert.public_key().public_numbers()
    pubkey =  pub_nums.x.to_bytes(32, byteorder='big', signed=False)
    pubkey += pub_nums.y.to_bytes(32, byteorder='big', signed=False)
    time.sleep(2)
    device.save_credentials(
        host_name=kit_info['endpointAddress'],
        device_cert=device_cert.public_bytes(encoding=serialization.Encoding.DER),
        signer_cert=signer_ca_cert.public_bytes(encoding=serialization.Encoding.DER),
        signer_ca_public_key=pubkey)

    print('\nDone')
Ejemplo n.º 52
0
    return (h[:len(h) / 2], h[len(h) / 2:])


# ----------------------------------------------------------------------------------
# HID
#
def getHidPath():
    for d in hid.enumerate(0, 0):
        if d['vendor_id'] == 0x03eb and d['product_id'] == 0x2402:
            if d['interface_number'] == 0 or d['usage_page'] == 0xffff:
                # hidapi is not consistent across platforms
                # usage_page works on Windows/Mac; interface_number works on Linux
                return d['path']


dbb_hid = hid.device()


def openHid():
    print("\nOpening device")
    try:
        dbb_hid.open_path(getHidPath())
        print("\tManufacturer: %s" % dbb_hid.get_manufacturer_string())
        print("\tProduct: %s" % dbb_hid.get_product_string())
        print("\tSerial No: %s\n\n" % dbb_hid.get_serial_number_string())
    except:
        print("\nDevice not found\n")
        sys.exit()


# ----------------------------------------------------------------------------------
Ejemplo n.º 53
0
import datetime

vendor_id  = 0x444E
product_id = 0x4450

usage_page = 0xFF60
usage      = 0x61

device_interfaces = hid.enumerate(vendor_id, product_id)
raw_hid_interfaces = [i for i in device_interfaces if i['usage_page'] == usage_page and i['usage'] == usage]

if len(raw_hid_interfaces) == 0:
    print('Couldnt find any interfaces')
    exit()

interface = hid.device()
interface.open_path(raw_hid_interfaces[0]['path'])
print("Manufacturer: %s" % interface.get_manufacturer_string())
print("Product: %s" % interface.get_product_string())
time.sleep(0.05)
while True:
    time.sleep(0.75)
    cpufreq = psutil.cpu_freq()
    currFreq = int(cpufreq.current)
    svmem = psutil.virtual_memory()
    memPerc = int(svmem.percent * 10)
    gpus = GPUtil.getGPUs()
    gpu = gpus[0]
    load = int(gpu.load*100)
    temp = int(gpu.temperature)
    data = [0]
Ejemplo n.º 54
0
    def __init__(self):

        self.version = 2

        self.GOGO_VEDOR_ID = 0x461
        self.GOGO_PRODUCT_ID = 0x20
        self.ENDPOINT_ID = 0

        # board types
        self.GOGOBOARD = 1
        self.PITOPPING = 2
        self.WIRELESSGOGO = 3

        # category names
        self.CATEGORY_OUTPUT_CONTROL = 0
        self.CATEGORY_MEMORY_CONTROL = 1
        self.CATEGORY_RASPBERRY_PI_CONTROL = 2

        # Output contorl command names
        self.CMD_PING = 1
        self.CMD_MOTOR_ON_OFF = 2
        self.CMD_MOTOR_DIRECTION = 3
        self.CMD_MOTOR_RD = 4
        self.CMD_SET_POWER = 6
        self.CMD_SET_ACTIVE_PORTS = 7
        self.CMD_TOGGLE_ACTIVE_PORT = 8
        self.CMD_SET_SERVO_DUTY = 9
        self.CMD_LED_CONTROL = 10
        self.CMD_BEEP = 11
        self.CMD_AUTORUN_STATE = 12
        self.CMD_LOGO_CONTROL = 13
        self.CMD_SYNC_RTC = 50
        self.CMD_READ_RTC = 51
        self.CMD_SHOW_SHORT_TEXT = 60
        self.CMD_SHOW_LONG_TEXT = 61
        self.CMD_CLEAR_SCREEN = 62

        self.CMD_VOICE_PLAY_PAUSE = 70
        self.CMD_VOICE_NEXT_TRACK = 71
        self.CMD_VOICE_PREV_TRACK = 72
        self.CMD_VOICE_GOTO_TRACK = 73
        self.CMD_VOICE_ERASE_ALL_TRACKS = 74

        self.CMD_I2C_WRITE = 14
        self.CMD_I2C_READ = 15

        self.CMD_REBOOT = 100

        # Memory control command names
        self.MEM_LOGO_SET_POINTER = 1
        self.MEM_SET_POINTER = 2
        self.MEM_WRITE = 3
        self.MEM_READ = 4

        # Raspberry Pi Commands

        self.RPI_SHUTDOWN = 1
        self.RPI_REBOOT = 2
        self.RPI_CAMERA_CONTROL = 10
        self.RPI_FIND_FACE_CONTROL = 11
        self.RPI_TAKE_SNAPSHOT = 12

        self.RPI_WIFI_CONNECT = 15
        self.RPI_WIFI_DISCONNECT = 16

        self.RPI_EMAIL_CONFIG = 17
        self.RPI_EMAIL_SEND = 18
        self.RPI_SMS_SEND = 19

        self.RPI_SET_TX_BUFFER = 20

        self.RPI_RFID_INIT = 25
        self.RPI_RFID_COMMAND = 26

        # output buffer location names
        self.ENDPOINT = 0
        self.CATEGORY_ID = 1
        self.CMD_ID = 2
        self.PARAMETER1 = 3
        self.PARAMETER2 = 4
        self.PARAMETER3 = 5
        self.PARAMETER4 = 6
        self.PARAMETER5 = 7
        self.PARAMETER6 = 8
        self.PARAMETER7 = 9

        self.TX_PACKET_SIZE = 64
        self.RX_PACKET_SIZE = 64

        self.RETRIES_ALLOWED = 5  # number of attempts to connect to HID device

        self.countNoData = 0

        # self.hidGoGo will be NULL if connection error
        try:
            self.hidGoGo = hid.device()
            self.hidGoGo.open(self.GOGO_VEDOR_ID, self.GOGO_PRODUCT_ID)

            # self.hidGoGo = hid.device(self.GOGO_VEDOR_ID, self.GOGO_PRODUCT_ID)
        except IOError as ex:
            print(ex)
            self.hidGoGo = None
Ejemplo n.º 55
0
#!/usr/bin/env python

import hid

#Get the list of all devices matching this vendor_id/product_id
vendor_id = 0x1a86
product_id = 0xe008
device_list = hid.enumerate(vendor_id, product_id)

for dev in device_list:
  for key, value in dev.items():
    print("{0}:{1}".format(key,value))
    if key == 'path':
      device = hid.device()
      if device.open_path(value):
      	print(device)
      else:
        print("Error!")



# some stuff
dev = hid.device()
dev.open(vendor_id,product_id)
Ejemplo n.º 56
0
    def pairing_dialog(self):
        def pairing_step(code: str, device_response: Callable[[],
                                                              bool]) -> bool:
            msg = "Please compare and confirm the pairing code on your BitBox02:\n" + code
            self.handler.show_message(msg)
            try:
                res = device_response()
            except:
                # Close the hid device on exception
                hid_device.close()
                raise
            finally:
                self.handler.finished()
            return res

        def exists_remote_static_pubkey(pubkey: bytes) -> bool:
            bitbox02_config = self.config.get("bitbox02")
            noise_keys = bitbox02_config.get("remote_static_noise_keys")
            if noise_keys is not None:
                if pubkey.hex() in [noise_key for noise_key in noise_keys]:
                    return True
            return False

        def set_remote_static_pubkey(pubkey: bytes) -> None:
            if not exists_remote_static_pubkey(pubkey):
                bitbox02_config = self.config.get("bitbox02")
                if bitbox02_config.get("remote_static_noise_keys") is not None:
                    bitbox02_config["remote_static_noise_keys"].append(
                        pubkey.hex())
                else:
                    bitbox02_config["remote_static_noise_keys"] = [
                        pubkey.hex()
                    ]
                self.config.set_key("bitbox02", bitbox02_config)

        def get_noise_privkey() -> Optional[bytes]:
            bitbox02_config = self.config.get("bitbox02")
            privkey = bitbox02_config.get("noise_privkey")
            if privkey is not None:
                return bytes.fromhex(privkey)
            return None

        def set_noise_privkey(privkey: bytes) -> None:
            bitbox02_config = self.config.get("bitbox02")
            bitbox02_config["noise_privkey"] = privkey.hex()
            self.config.set_key("bitbox02", bitbox02_config)

        def attestation_warning() -> None:
            self.handler.show_error(
                "The BitBox02 attestation failed.\nTry reconnecting the BitBox02.\nWarning: The device might not be genuine, if the\n problem persists please contact Shift support.",
                blocking=True)

        class NoiseConfig(bitbox_api_protocol.BitBoxNoiseConfig):
            """NoiseConfig extends BitBoxNoiseConfig"""
            def show_pairing(self, code: str,
                             device_response: Callable[[], bool]) -> bool:
                return pairing_step(code, device_response)

            def attestation_check(self, result: bool) -> None:
                if not result:
                    attestation_warning()

            def contains_device_static_pubkey(self, pubkey: bytes) -> bool:
                return exists_remote_static_pubkey(pubkey)

            def add_device_static_pubkey(self, pubkey: bytes) -> None:
                return set_remote_static_pubkey(pubkey)

            def get_app_static_privkey(self) -> Optional[bytes]:
                return get_noise_privkey()

            def set_app_static_privkey(self, privkey: bytes) -> None:
                return set_noise_privkey(privkey)

        if self.bitbox02_device is None:
            hid_device = hid.device()
            hid_device.open_path(self.bitbox_hid_info["path"])

            bitbox02_device = bitbox02.BitBox02(
                transport=u2fhid.U2FHid(hid_device),
                device_info=self.bitbox_hid_info,
                noise_config=NoiseConfig(),
            )
            try:
                bitbox02_device.check_min_version()
            except FirmwareVersionOutdatedException:
                raise
            self.bitbox02_device = bitbox02_device

        self.fail_if_not_initialized()
Ejemplo n.º 57
0
 def get_dbb_device(self, device):
     with self.device_manager().hid_lock:
         dev = hid.device()
         dev.open_path(device.path)
     return dev
Ejemplo n.º 58
0
 def get_secalot_device(self, path):
     dev = hid.device()
     dev.open_path(path)
     dev.set_nonblocking(True)
     return HIDDongleHIDAPI(dev, True, False)
Ejemplo n.º 59
0
    pin_behaviour = 0x08

    send_report(dev, [report_id] + unlock_key + [
        suspend_behaviour, usb_interface_id, cable_flags_function_id,
        pin_behaviour
    ] + flags_mask)


def configure_a3_as_debug_accessory_flag(dev):
    configure_pin_as_flag_output(dev, 0x03,
                                 [0x02, 0x00, 0x00, 0x00, 0x00, 0x00])


if __name__ == "__main__":
    core_interface_path = get_path_to_device_interface(CORE_INTERFACE)
    if not core_interface_path:
        print("Device is not connected.")
        exit(1)

    dev = hid.device()
    dev.open_path(core_interface_path)
    try:
        print("Manufacturer :", dev.get_manufacturer_string())
        print("Product      :", dev.get_product_string())
        print("Serial Number:", dev.get_serial_number_string())

        configure_a3_as_debug_accessory_flag(dev)

    finally:
        dev.close()
Ejemplo n.º 60
0
#!/usr/bin/env python
import hid
from at_kit_base import *
import base64

# Initialize the Kit Instance
dev = KitDevice(hid.device())
dev.open()

id = dev.kit_list(0)

# Select the device to communicate with
dev.kit_select(id)

# Send the command
resp = dev.kit_command(64, 0, 0, timeout_ms=5000)

public_key = bytearray.fromhex(
    '3059301306072A8648CE3D020106082A8648CE3D03010703420004'
) + bytearray.fromhex(resp['data'][2:-4])
public_key = '-----BEGIN PUBLIC KEY-----\n' + base64.b64encode(
    public_key).decode('ascii') + '\n-----END PUBLIC KEY-----'

print(public_key)