How to use toEventDeviceName method in fMBT

Best Python code snippet using fMBT_python

fmbtuinput.py

Source:fmbtuinput.py Github

copy

Full Screen

...545 re.findall('[ =](event[0-9]+)\s', d)[0])546 _g_filenames[_g_deviceNames[_name]] = _name547def toEventFilename(deviceName):548 return _g_deviceNames[deviceName]549def toEventDeviceName(filename):550 return _g_filenames[filename]551class InputDevice(object):552 def __init__(self):553 if not "_g_devices" in globals():554 refreshDeviceInfo()555 self._fd = -1556 self._filename = None557 self._uidev = None558 self._created = False559 self._opened = False560 self._name = None561 def __del__(self):562 if self._created:563 self.destroy()564 def __str__(self):565 return "%s(name=%s, filename=%s, created=%s, opened=%s, fd=%s)" % (566 self.__class__.__name__,567 repr(self._name),568 repr(self._filename),569 repr(self._created),570 repr(self._opened),571 repr(self._fd))572 def startCreating(self, name, vendor, product, version,573 absmin=None, absmax=None):574 if self._fd > 0:575 raise InputDeviceError("InputDevice is already open")576 self._fd = os.open("/dev/uinput", os.O_WRONLY | os.O_NONBLOCK)577 if absmin == None:578 absmin = [0 for _ in xrange(abs_count)]579 if absmax == None:580 absmax = [0 for _ in xrange(abs_count)]581 absfuzz = [0 for _ in xrange(abs_count)]582 absflat = [0 for _ in xrange(abs_count)]583 self._name = name584 self._uidev = struct.pack(struct_uinput_user_dev,585 name, # name586 BUS_USB, # id.bus_type587 vendor, # id.vendor588 product, # id.product589 version, # id.version590 0, # ff_effects_max591 # TODO: why absmin + absmax gives592 # error for touch?593 *(absmax + absmin + absfuzz + absflat)594 )595 def finishCreating(self):596 if self._fd < 1:597 raise InputDeviceError("startCreating() not called")598 bytes_written = os.write(self._fd, self._uidev)599 if bytes_written != sizeof_uinput_user_dev:600 raise InputDeviceError(601 "Writing to /dev/uinput failed, wrote %s/%s bytes"602 % (bytes_written, sizeof_uinput_user_dev))603 rv = fcntl.ioctl(self._fd, UI_DEV_CREATE)604 if rv != 0:605 raise InputDeviceError(606 "Creating device failed, ioctl UI_DEV_CREATE returned %s"607 % (rv,))608 self._created = True609 return True610 def destroy(self):611 if self._created:612 fcntl.ioctl(self._fd, UI_DEV_DESTROY)613 self._created = False614 self.close()615 def open(self, filename):616 if self._fd > 0:617 raise InputDeviceError("InputDevice is already open")618 if not filename.startswith("/dev/input"):619 filename = toEventFilename(filename)620 self._fd = os.open(filename, os.O_WRONLY | os.O_NONBLOCK)621 self._filename = filename622 self._created = False623 self._name = toEventDeviceName(self._filename)624 return self625 def close(self):626 if self._fd > 0:627 os.close(self._fd)628 self._fd = -1629 def filename(self):630 return self._filename631 def addCap(self, capBit, capCodeOrName, capCode2Name):632 if self._fd < 1:633 raise InputDeviceError("startCreating() not called")634 if self._created or self._opened:635 raise InputDeviceError("Cannot add capabilities after creation")636 if isinstance(capCodeOrName, int):637 capCode = capCodeOrName638 elif capCodeOrName in capCode2Name:639 capCode = capCode2Name[capCodeOrName]640 else:641 raise InputDeviceError('Unknown name "%s"' % (capCodeOrName,))642 return fcntl.ioctl(self._fd, capBit, capCode)643 def addEvent(self, eventCodeOrName):644 return self.addCap(UI_SET_EVBIT, eventCodeOrName, eventTypes)645 def addKey(self, keyCodeOrName):646 return self.addCap(UI_SET_KEYBIT, keyCodeOrName, keyCodes)647 def addRel(self, relCodeOrName):648 return self.addCap(UI_SET_RELBIT, relCodeOrName, relCodes)649 def addAbs(self, absCodeOrName):650 return self.addCap(UI_SET_ABSBIT, absCodeOrName, absCodes)651 def send(self, type_, code, value):652 if self._fd < 1:653 raise InputDeviceError("InputDevice is not open")654 if isinstance(type_, str):655 typeCode = eventTypes[type_]656 else:657 typeCode = type_658 if isinstance(code, str):659 codeCode = event_codetables[typeCode][code]660 else:661 codeCode = code662 return sendInputEvent(self._fd, typeCode, codeCode, value)663 def sync(self):664 if self._fd < 1:665 raise InputDeviceError("InputDevice is not open")666 return sendInputSync(self._fd)667class InputDeviceError(Exception):668 pass669class Mouse(InputDevice):670 def __init__(self, absoluteMove=False):671 """672 Parameters:673 absoluteMove (boolean, optional)674 force move(x,y) to send absolute coordinates instead675 of standard relative movement. This helps avoiding676 mouse pointer drift in some occasions. The default677 is False.678 """679 InputDevice.__init__(self)680 self._x = 0681 self._y = 0682 self._sendAbs = absoluteMove683 def create(self, name="Virtual fMBT Mouse",684 vendor=0xf4b7, product=0x4053, version=1):685 self.startCreating(name, vendor, product, version)686 self.addEvent("EV_KEY")687 self.addEvent("EV_REL")688 if self._sendAbs:689 self.addEvent("EV_ABS")690 self.addEvent("EV_SYN")691 self.addRel("REL_X")692 self.addRel("REL_Y")693 self.addRel("REL_HWHEEL")694 self.addRel("REL_WHEEL")695 self.addKey("BTN_LEFT")696 self.addKey("BTN_RIGHT")697 self.addKey("BTN_MIDDLE")698 self.addKey("BTN_SIDE")699 self.addKey("BTN_EXTRA")700 self.addKey("BTN_FORWARD")701 self.addKey("BTN_BACK")702 self.addKey("BTN_TASK")703 if self._sendAbs:704 self.addAbs("ABS_X")705 self.addAbs("ABS_Y")706 self.finishCreating()707 return self708 def move(self, x, y):709 """710 Move mouse cursor to coordinates x, y.711 """712 if self._sendAbs:713 self.send("EV_ABS", "ABS_X", x)714 self.send("EV_ABS", "ABS_Y", y)715 else:716 deltaX = x - self._x717 deltaY = y - self._y718 self.send("EV_REL", "REL_X", deltaX)719 self.send("EV_REL", "REL_Y", deltaY)720 self.sync()721 self.setXY(x, y)722 def moveRel(self, deltaX, deltaY):723 self.send("EV_REL", "REL_X", deltaX)724 self.send("EV_REL", "REL_Y", deltaY)725 self.sync()726 self.setXY(self._x + deltaX, self._y + deltaY)727 def press(self, button):728 buttonCode = toButtonCode(button)729 self.send("EV_KEY", buttonCode, 1)730 self.sync()731 def release(self, button):732 buttonCode = toButtonCode(button)733 self.send("EV_KEY", buttonCode, 0)734 self.sync()735 def setXY(self, x, y):736 """737 Resets relative mouse position to (x, y), does not synthesize738 event. Example: disable possible mouse pointer drift:739 mouse.moveRel(-4096, -4096) # move to the top-left corner740 mouse.setXY(0, 0) # set current pointer coordinates to 0, 0741 After this, mouse.move(x, y) will synthesize relative mouse742 move event which will drive cursor to coordinates x, y.743 """744 self._x = x745 self._y = y746 def xy(self):747 return (self._x, self._y)748 def tap(self, x, y, button):749 self.move(x, y)750 self.press(button)751 self.release(button)752class Touch(InputDevice):753 """754 Simulates touchpanel and touchpad755 """756 def __init__(self, maxX = None, maxY = None,757 screenWidth = None, screenHeight = None, screenAngle = None):758 InputDevice.__init__(self)759 self._maxX = maxX760 self._maxY = maxY761 self._screenW = screenWidth762 self._screenH = screenHeight763 self._screenA = screenAngle764 self._maxPressure = None765 self._multiTouch = True766 self._mtTrackingId = 0767 self._mtTracking = {}768 self._hoover = (0, 0)769 def create(self, name="Virtual fMBT Touch",770 vendor=0xf4b7, product=0x70c5, version=1,771 maxX=0xffff, maxY=0xffff, maxPressure=None,772 multiTouch = True):773 if maxX != None:774 self._maxX = maxX775 else:776 self._maxX = 0xffff777 if maxY != None:778 self._maxY = maxY779 else:780 self._maxY = 0xffff781 absmin = [0 for _ in xrange(abs_count)]782 absmax = [0 for _ in xrange(abs_count)]783 absmax[absCodes["ABS_X"]] = self._maxX784 absmax[absCodes["ABS_Y"]] = self._maxY785 if maxPressure != None:786 self._maxPressure = maxPressure787 absmax[absCodes["ABS_PRESSURE"]] = self._maxPressure788 absmax[absCodes["ABS_MT_SLOT"]] = 16789 absmax[absCodes["ABS_MT_TRACKING_ID"]] = 0x0fffffff790 absmax[absCodes["ABS_MT_POSITION_X"]] = self._maxX791 absmax[absCodes["ABS_MT_POSITION_Y"]] = self._maxY792 self._multiTouch = multiTouch793 self.startCreating(name, vendor, product, version,794 absmin=absmin, absmax=absmax)795 self.addEvent("EV_KEY")796 self.addEvent("EV_ABS")797 self.addEvent("EV_SYN")798 self.addKey("BTN_TOUCH")799 self.addAbs("ABS_X")800 self.addAbs("ABS_Y")801 if self._maxPressure != None:802 self.addAbs("ABS_PRESSURE")803 if self._multiTouch:804 self.addAbs("ABS_MT_SLOT")805 self.addAbs("ABS_MT_TRACKING_ID")806 self.addAbs("ABS_MT_POSITION_X")807 self.addAbs("ABS_MT_POSITION_Y")808 self.finishCreating()809 return self810 def open(self, filename):811 InputDevice.open(self, filename)812 # detect touch device capabilities and max values813 # nfo is struct input_absinfo814 nfo = array.array('i', range(6))815 fcntl.ioctl(self._fd, EVIOCGABS(absCodes["ABS_X"]), nfo, 1)816 self._maxX = nfo[2]817 fcntl.ioctl(self._fd, EVIOCGABS(absCodes["ABS_Y"]), nfo, 1)818 self._maxY = nfo[2]819 return self820 def setScreenSize(self, (width, height)):821 self._screenW, self._screenH = (width, height)822 def setScreenAngle(self, angle):823 self._screenA = angle824 def _angleXY(self, x, y, angle=None):825 """return x, y in screen without rotation"""826 if angle == None:827 angle = self._screenA828 sw, sh = self._screenW, self._screenH829 if angle:830 while angle < 0:831 angle += 360832 while angle > 360:833 angle -= 360834 if angle == 90:835 ax = self._screenH - y836 ay = x837 sw, sh = self._screenH, self._screenW838 elif angle == 180:839 ax = self._screenH - x840 ay = self._screenW - y841 elif angle == 270:842 ax = y843 ay = self._screenW - x844 sw, sh = self._screenH, self._screenW845 else:846 raise ValueError('Illegal screen rotation angle %s' %847 (self._screenA,))848 else:849 ax, ay = x, y850 return (sw, sh, ax, ay)851 def _tXY(self, x, y):852 """convert x, y to touch screen coordinates"""853 if self._screenW and self._maxX and self._screenH and self._maxY:854 w, h, x, y = self._angleXY(x, y)855 x = int((self._maxX * x) / w)856 y = int((self._maxY * y) / h)857 return (x, y)858 else:859 return (x, y)860 def absToScreenXY(self, absX, absY):861 if self._screenW and self._maxX and self._screenH and self._maxY:862 x = int(self._screenW * absX / self._maxX)863 y = int(self._screenH * absY / self._maxY)864 if self._screenA:865 _, _, x, y = self._angleXY(x, y, -self._screenA)866 return (x, y)867 else:868 return (absX, absY)869 def _startTracking(self, finger, x, y):870 self._mtTrackingId += 1871 usedSlots = set([self._mtTracking[fngr][0]872 for fngr in self._mtTracking])873 for freeSlot in xrange(16):874 if not freeSlot in usedSlots:875 break876 else:877 raise ValueError("No free slots for multitouch")878 self._mtTracking[finger] = [freeSlot, self._mtTrackingId, x, y]879 self._sendSlot(finger)880 self.send("EV_ABS", "ABS_MT_TRACKING_ID", self._mtTrackingId)881 tx, ty = self._tXY(x, y)882 self.send("EV_ABS", "ABS_MT_POSITION_X", tx)883 self.send("EV_ABS", "ABS_MT_POSITION_Y", ty)884 return self._mtTrackingId885 def _stopTracking(self, finger):886 self._sendSlot(finger)887 self.send("EV_ABS", "ABS_MT_TRACKING_ID", -1)888 del self._mtTracking[finger]889 def _sendSlot(self, finger):890 slot = self._mtTracking[finger][0]891 self.send("EV_ABS", "ABS_MT_SLOT", slot)892 def tap(self, x, y, pressure=None):893 self.pressFinger(-1, x, y, pressure)894 self.releaseFinger(-1)895 # Compatibility API to allow using a Touch almost like a Mouse896 def move(self, x, y):897 if len(self._mtTracking.keys()) == 0:898 self._hoover = (x, y)899 else:900 finger = sorted(self._mtTracking.keys())[0]901 return self.moveFinger(finger, x, y)902 def press(self, finger):903 return self.pressFinger(finger, *self._hoover)904 def release(self, finger):905 return self.releaseFinger(finger)906 # end of compatibility API907 # Multi-touch API908 def pressFinger(self, finger, x, y, pressure=None):909 """Add a finger to current multitouch gesture. If multitouch gesture910 is not started, it starts automatically.911 """912 if self._multiTouch and not finger in self._mtTracking:913 self._startTracking(finger, x, y)914 if pressure != None and self._maxPressure != None:915 self.send("EV_ABS", "ABS_PRESSURE", pressure)916 self.send("EV_KEY", "BTN_TOUCH", 1)917 tx, ty = self._tXY(x, y)918 self.send("EV_ABS", "ABS_X", tx)919 self.send("EV_ABS", "ABS_Y", ty)920 self.sync()921 def releaseFinger(self, finger):922 """Remove a finger from current multitouch gesture. When last finger923 is raised from the screen, multitouch gesture ends."""924 if self._multiTouch:925 self._stopTracking(finger)926 self.send("EV_KEY", "BTN_TOUCH", 0)927 for fngr in self._mtTracking:928 # still some finger pressed, non-multitouch reader gets929 # coordinates from one of those930 tx, ty = self._tXY(self._mtTracking[fngr][2],931 self._mtTracking[fngr][3])932 self.send("EV_ABS", "ABS_X", tx)933 self.send("EV_ABS", "ABS_Y", ty)934 break # only one coordinates will be sent.935 self.sync()936 def moveFinger(self, finger, x, y):937 """Move a finger in current multitouch gesture"""938 self._sendSlot(finger)939 tx, ty = self._tXY(x, y)940 if self._multiTouch:941 self.send("EV_ABS", "ABS_MT_POSITION_X", tx)942 self.send("EV_ABS", "ABS_MT_POSITION_Y", ty)943 self.send("EV_ABS", "ABS_X", tx)944 self.send("EV_ABS", "ABS_Y", ty)945 self._mtTracking[finger][2] = x # last X946 self._mtTracking[finger][3] = y # last Y947 self.sync()948class Keyboard(InputDevice):949 def __init__(self):950 InputDevice.__init__(self)951 def create(self, name="Virtual fMBT Keyboard",952 vendor=0xf4b7, product=0x4ebd, version=1):953 self.startCreating(name, vendor, product, version)954 self.addEvent("EV_KEY")955 self.addEvent("EV_SYN")956 for keyName in keyCodes:957 if keyName.startswith("KEY_"):958 self.addKey(keyCodes[keyName])959 self.finishCreating()960 return self961 def press(self, keyCodeOrName):962 # TODO: there should be different MSC_SCAN matrix location for each key963 self.send("EV_MSC", mscCodes["MSC_SCAN"], 458793)964 self.send("EV_KEY", toKeyCode(keyCodeOrName), 1)965 self.sync()966 def release(self, keyCodeOrName):967 # TODO: there should be different MSC_SCAN matrix location for each key968 self.send("EV_MSC", mscCodes["MSC_SCAN"], 458793)969 self.send("EV_KEY", toKeyCode(keyCodeOrName), 0)970 self.sync()971 def tap(self, keyCodeOrName):972 keyCode = toKeyCode(keyCodeOrName)973 self.press(keyCode)974 self.release(keyCode)975def sendInputSync(devFd):976 return sendInputEvent(devFd, 0, 0, 0)977def sendInputEvent(devFd, type_, code, value):978 t = time.time()979 t_sec = int(t)980 t_usec = int(1000000*(t-t_sec))981 rv = os.write(devFd,982 struct.pack(struct_input_event,983 t_sec, t_usec,984 type_,985 code,986 value))987 return rv == sizeof_input_event988def eventToString(inputEvent):989 tim, tus, typ, cod, val = struct.unpack(struct_input_event, inputEvent)990 styp = eventTypesInv.get(typ, "?")991 if styp == "EV_KEY":992 scod = keyCodesInv.get(cod, "?")993 elif styp == "EV_REL":994 scod = relCodesInv.get(cod, "?")995 elif styp == "EV_ABS":996 scod = absCodesInv.get(cod, "?")997 else:998 scod = "N/A"999 if typ == 0:1000 return styp1001 else:1002 return "%8s.%s type: %4s (%5s), code: %5s (%15s) value: %8s" % \1003 (tim, str(tus).zfill(6), typ, styp, cod, scod, val)1004def queueEventsFromFile(filename, queue, lock, filterOpts):1005 if isinstance(filterOpts, dict) and "type" in filterOpts:1006 allowedTypes = set()1007 for t in filterOpts["type"]:1008 if isinstance(t, str):1009 allowedTypes.add(eventTypes[t])1010 else:1011 allowedTypes.add(t)1012 else:1013 allowedTypes = set(eventTypes.values())1014 if ("touchScreen" in filterOpts and1015 filename == filterOpts["touchScreen"].filename()):1016 touchScreen = filterOpts["touchScreen"]1017 absXCodes = set([absCodes["ABS_X"], absCodes["ABS_MT_POSITION_X"]])1018 absYCodes = set([absCodes["ABS_Y"], absCodes["ABS_MT_POSITION_Y"]])1019 absType = eventTypes["EV_ABS"]1020 else:1021 touchScreen = None1022 fd = os.open(filename, os.O_RDONLY)1023 try:1024 while 1:1025 eventData = os.read(fd, sizeof_input_event)1026 if not lock.locked():1027 return1028 if not eventData:1029 break1030 (ts, tus, typ, cod, val) = struct.unpack(struct_input_event, eventData)1031 if touchScreen and typ == absType:1032 if cod in absXCodes:1033 val, _ = touchScreen.absToScreenXY(val, 0)1034 elif cod in absYCodes:1035 _, val = touchScreen.absToScreenXY(0, val)1036 if typ in allowedTypes:1037 queue.put((ts, tus, typ, cod, val))1038 finally:1039 os.close(fd)1040# _g_recQL dictionary contains events being actively recorded1041# - key: filename, like "/dev/input/event0"1042# - value: (eventQueue, lock)1043# A thread is filling eventQueue with events from filename.1044# Once the lock is released, the thread will quit without writing1045# anything to the eventQueue anymore.1046_g_recQL = {}1047_g_unfetchedEvents = []1048def queueEventsFromFiles(listOfFilenames, filterOpts):1049 global _g_recQL1050 for filename in listOfFilenames:1051 q = Queue.Queue()1052 l = thread.allocate_lock()1053 l.acquire()1054 if filename in _g_recQL:1055 # previous reader thread should quit1056 _g_recQL[filename][1].release()1057 thread.start_new_thread(1058 queueEventsFromFile, (filename, q, l, filterOpts))1059 _g_recQL[filename] = (q, l)1060def startQueueingEvents(filterOpts):1061 refreshDeviceInfo()1062 if len(_g_recQL) > 0:1063 # already queueing, restart1064 stopQueueingEvents()1065 if "device" in filterOpts:1066 deviceFiles = []1067 for n in filterOpts["device"]:1068 if n in _g_deviceNames:1069 deviceFiles.append(_g_deviceNames[n])1070 elif os.access(n, os.R_OK):1071 deviceFiles.append(n)1072 del filterOpts["device"]1073 else:1074 deviceFiles = glob.glob("/dev/input/event[0-9]*")1075 queueEventsFromFiles(deviceFiles, filterOpts)1076def stopQueueingEvents():1077 global _g_recQL1078 global _g_unfetchedEvents1079 for filename in _g_recQL:1080 _g_recQL[filename][1].release()1081 _g_unfetchedEvents = fetchQueuedEvents()1082 _g_recQL = {}1083def fetchQueuedEvents():1084 global _g_unfetchedEvents1085 if len(_g_recQL) == 0: # no active recording1086 rv = _g_unfetchedEvents1087 _g_unfetchedEvents = []1088 return rv1089 else: # events are being recorded1090 events = []1091 for filename in _g_recQL:1092 events.extend(fetchQueuedEventsFromFile(filename))1093 return events1094def fetchQueuedEventsFromFile(filename):1095 events = []1096 q = _g_recQL[filename][0]1097 deviceName = toEventDeviceName(filename)1098 while 1:1099 try:1100 ts, tus, typ, cod, val = q.get_nowait()1101 events.append((deviceName, ts + tus/1000000.0, typ, cod, val))1102 except Queue.Empty:1103 break1104 return events1105def printEventsFromFile(filename):1106 fd = os.open(filename, os.O_RDONLY)1107 sdev = filename.split("/")[-1]1108 try:1109 while 1:1110 inputEvent = os.read(fd, sizeof_input_event)1111 if not inputEvent:...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run fMBT automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful