Python Forum
Handling Multiple USB ports in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Handling Multiple USB ports in Python
#1
Hi,
I am new to python and to the forum too. In my python application I have to read from two USB ports and process the data I get from any of the USB port. For one port I am using pyUSB to read data from the device. On another USB port is attached a device for which I am using method from shared object library(.so file). If I rung the functions independently I get the desired response from each USB port. But If I run the application in a while loop alternately I can only get the response from port that I am reading using pyUsb.
Here is my sample code. Please let me know if the approach is incorrect or I have to follow some other approach.
import usb.core
import array
import usb.util
from time import sleep
import ctypes

devStatus = False
ep = None
interfaceNo = None
eaddr = None
dev = None

def hid2ascii(lst):
	assert len(lst) == 8, 'Invalid data length (needs 8 bytes)'
	conv_table = {
        0:['', ''],
        4:['a', 'A'],
        5:['b', 'B'],
        6:['c', 'C'],
        7:['d', 'D'],
        8:['e', 'E'],
        9:['f', 'F'],
        10:['g', 'G'],
        11:['h', 'H'],
        12:['i', 'I'],
        13:['j', 'J'],
        14:['k', 'K'],
        15:['l', 'L'],
        16:['m', 'M'],
        17:['n', 'N'],
        18:['o', 'O'],
        19:['p', 'P'],
        20:['q', 'Q'],
        21:['r', 'R'],
        22:['s', 'S'],
        23:['t', 'T'],
        24:['u', 'U'],
        25:['v', 'V'],
        26:['w', 'W'],
        27:['x', 'X'],
        28:['y', 'Y'],
        29:['z', 'Z'],
        30:['1', '!'],
        31:['2', '@'],
        32:['3', '#'],
        33:['4', '$'],
        34:['5', '%'],
        35:['6', '^'],
        36:['7' ,'&'],
        37:['8', '*'],
        38:['9', '('],
        39:['0', ')'],
        40:['\n', '\n'],
        41:['\x1b', '\x1b'],
        42:['\b', '\b'],
        43:['\t', '\t'],
        44:[' ', ' '],
        45:['_', '_'],
        46:['=', '+'],
        47:['[', '{'],
        48:[']', '}'],
        49:['\\', '|'],
        50:['#', '~'],
        51:[';', ':'],
        52:["'", '"'],
        53:['`', '~'],
        54:[',', '<'],
        55:['.', '>'],
        56:['/', '?'],
        100:['\\', '|'],
        103:['=', '='],
        }
	# A 2 in first byte seems to indicate to shift the key. For example
	    # a code for ';' but with 2 in first byte really means ':'.
	if lst[0] == 2:
		shift = 1
	else:
		shift = 0

	# The character to convert is in the third byte
	ch = lst[2]
	if ch not in conv_table:
		print "Warning: data not in conversion table"
		return ''
	return conv_table[ch][shift]

def getQRDevice():
	global devStatus
	global ep
	global interfaceNo
	global eaddr
	global dev
	dev = usb.core.find(idVendor=0x2dd6, idProduct=0x26c1)
	if (dev):
		ep = dev[0].interfaces()[0].endpoints()[0]
		interfaceNo = dev[0].interfaces()[0].bInterfaceNumber
		dev.reset()

		if dev.is_kernel_driver_active(interfaceNo):
			dev.detach_kernel_driver(interfaceNo)
		dev.set_configuration()
		eaddr = ep.bEndpointAddress
		print('Device connected')
		devStatus = True;
	else:
		print('Device not connected')
		return False;
def getQR():
	if (devStatus == True):
		
		data = None
		line = ''	
		while data is None:
			try:

				readData = dev.read(eaddr,1024)
				#print(readData)
				ch = hid2ascii(readData)
				line += ch

				if len(line)>0 and ch =='\n':
					print(line)
					return line;
					break
			except usb.core.USBError as e:
				data = None
				if e.args == ('Operation timed out'):
					continue

def detect():
    obj = ctypes.CDLL('/home/pramod/testpython/for_so/dualcard_main.so')
    o = obj.DualiUSBOpen()
    while(o):
        s=" "
    	s=s.rjust(128," ")
    	c = obj.DualiUSBFind(0,s)
    	print("c : " + str(c))
    	if c>=0:
            s=""
            s=s.rjust(128," ")
            card = obj.DualiUSBFind(0,s)
            print("card obj"+str(card))
            print("scard="+s)
            if card>=0:
                #submit_to_tkinter(label2,"Remove Card/QR")
                detected = "card"
                card = None
                break
        else:
            s=""
	    s = getQR()
            print("sqr="+s)
            if len(s)>0:
                #submit_to_tkinter(label2,"Remove Card/QR")
                detected = "qr"
                break
    return s,detected

if __name__=='__main__':
#check Card reader
	devNFC = usb.core.find(idVendor=0x1db2, idProduct=0x0650)
	getQRDevice()
	if (devNFC is not None and devStatus==True):
		while(1):
			dump3 = detect()
			s = dump3[0]
			detected = dump3[1]
			print("s")
			print(s)
			print("detected : "+detected)
			sleep(1)
	else:
		raise ValueError('Device not found')
Thanks
Pramod
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  python convert multiple files to multiple lists MCL169 6 1,432 Nov-25-2023, 05:31 AM
Last Post: Iqratech
Star python exception handling handling .... with traceback mg24 3 1,216 Nov-09-2022, 07:29 PM
Last Post: Gribouillis
  Handling pdf files with python. fuzzin 1 1,217 Jan-19-2022, 02:24 PM
Last Post: ThiefOfTime
  Handling Python Fatal Error richajain1785 7 5,759 Oct-14-2021, 01:34 PM
Last Post: Tails86
  Uninstall unused COM ports windows 10 adbrooker 1 1,979 Sep-22-2021, 03:16 AM
Last Post: Larz60+
  Mido and virtual midi ports dore_m 2 4,517 Dec-27-2020, 06:02 AM
Last Post: dore_m
  Handling multi-input/output audio in python bor1904 4 3,495 Nov-04-2020, 08:25 AM
Last Post: CHLOVRL
  Python Requests package: Handling xml response soumyarani 1 2,101 Sep-14-2020, 11:41 AM
Last Post: buran
  Exception handling in regex using python ShruthiLS 1 2,330 May-04-2020, 08:12 AM
Last Post: anbu23
  Python Logging and Handling phillyfa 2 4,490 Mar-20-2020, 05:13 PM
Last Post: phillyfa

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020