0

I have json file as follows

{
   "devices"  :[
                 {
                 "Manufacturer name": "Sony",
                 "vendor_id":"8087" ,
                 "product_id" : "07da"
                 },
                 {
                 "Manufacturer name": "Sandisk",
                 "vendor_id": "1d6b",
                 "product_id" : "0002"
                 },
                 {
                 "Manufacturer name": "Chicony Electronics",
                 "vendor_id": "04f2",
                 "product_id" : "b381"
                 }
               ]

}

This json file contains the vendor and product id of the usb devices connected to my laptop. I am checking whether usb device is connected to laptop or not using this json file. The vendor and product id are in hex. Since json is cannot use hex, I have written these value in string format. I am actually using python's pyusb module for checking the connectivity of the devices as follow

import usb.core
def get_hex(hex_str):
    hex_int = int(hex_str, 16)
    return hex(hex_int)

vendor_id = get_hex("8087")
product_id = get_hex("07da")
dev = usb.core.find(idVendor=vendor_id, idProduct=product_id)

if dev is None:
    print "Disconnected"
else:
    print "Connected"

But when I am running this code I am getting print message as "Disconnected" Here actually problem is that usb.core.find() function needs value in int but value get_hex() function returns is string. Once change line dev = usb.core.find(idVendor=vendor_id, idProduct=product_id) in above code to dev = usb.core.find(idVendor=0x8087, idProduct=0x07da). The above code works properly. Please let me know how to return value from get_hex() in int.

cgoma
  • 47
  • 2
  • 13
  • 3
    Possible duplicate of [Convert hex string to int in Python](https://stackoverflow.com/questions/209513/convert-hex-string-to-int-in-python) – Thomas Francois Aug 30 '18 at 07:05

1 Answers1

2

The problem is that you are converting the hex string to int and then then back to a hex string. Just return after converting it to int. And it would be better to rename the function as get_int as your are just converting it to int

def get_int(hex_str):
    return int(hex_str, 16)

vendor_id = get_int("8087")
product_id = get_int("07da")
dev = usb.core.find(idVendor=vendor_id, idProduct=product_id)
Sunitha
  • 11,777
  • 2
  • 20
  • 23