#!   /usr/bin/env   python
#    coding: utf8

import  glob
import  os
import  re


class CttyUSB:

    def __init__(self):
        pass

    def find_usb_tty(self, vendor_id = None, product_id = None) :
        tty_devs    = []

        for dn in glob.glob('/sys/bus/usb/devices/*') :
            try     :
                vid = int(open(os.path.join(dn, "idVendor" )).read().strip(), 16)
                pid = int(open(os.path.join(dn, "idProduct")).read().strip(), 16)
                #print "dn:%s vid:%s pid:%s" % (dn,vid,pid)
                if  ((vendor_id is None) or (vid == vendor_id)) and ((product_id is None) or (pid == product_id)) :
                    dns = glob.glob(os.path.join(dn, os.path.basename(dn) + "*"))
                    for sdn in dns :
                        for fn in glob.glob(os.path.join(sdn, "*")) :
                            if  re.search(r"\/ttyUSB[0-9]+$", fn) :
                                tty_devs.append("/dev/" + os.path.basename(fn))
                                pass
                            pass
                        pass
                    pass
            except ( ValueError, TypeError, AttributeError, OSError, IOError ) :
                pass
            pass

        return tty_devs


#print find_usb_tty()
#print find_usb_tty(0x10c4,0xea60)
#print find_usb_tty(0x0403,0x6001)
