diff --git a/.gitignore b/.gitignore index c7c4f66..93d9338 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,7 @@ # Cache data unittests /.pytest_cache +/.coverage # proto folders/scripts /examples_development diff --git a/source/device/client.py b/source/device/client.py index b83f8ad..22ff28e 100644 --- a/source/device/client.py +++ b/source/device/client.py @@ -5,12 +5,9 @@ class O2x5xxDevice(O2x5xxPCICDevice): def __init__(self, address="192.168.0.69", port=50010, autoconnect=True, timeout=SOCKET_TIMEOUT): self._address = address - self._port = port - self._autoconnect = autoconnect - self._device_timeout = timeout + self._timeout = timeout self._rpc = None - if autoconnect: - self._rpc = O2x5xxRPCDevice(address=self._address, timeout=self._device_timeout) + self._rpc = O2x5xxRPCDevice(address=address, timeout=timeout) super(O2x5xxPCICDevice, self).__init__(address=address, port=port, autoconnect=autoconnect, timeout=timeout) def __enter__(self): @@ -25,7 +22,7 @@ def __exit__(self, exc_type, exc_val, exc_tb): @property def rpc(self) -> O2x5xxRPCDevice: if not self._rpc: - self._rpc = O2x5xxRPCDevice(address=self._address, timeout=self._device_timeout) + self._rpc = O2x5xxRPCDevice(address=self._address, timeout=self._timeout) return self._rpc @@ -33,14 +30,10 @@ class O2x5xxDeviceV2(object): def __init__(self, address="192.168.0.69", port=50010, autoconnect=True, timeout=SOCKET_TIMEOUT): self._address = address self._port = port - self.__timeout = timeout + self._timeout = timeout self._autoconnect = autoconnect - self._pcic = None - self._rpc = None - if autoconnect: - self._pcic = O2x5xxPCICDevice(address=self._address, port=self._port, - autoconnect=self._autoconnect, timeout=self.__timeout) - self._rpc = O2x5xxRPCDevice(address=self._address) + self._rpc = O2x5xxRPCDevice(address=address, timeout=timeout) + self._pcic = O2x5xxPCICDevice(address=address, port=port, autoconnect=autoconnect, timeout=timeout) def __enter__(self): return self @@ -56,12 +49,12 @@ def __exit__(self, exc_type, exc_val, exc_tb): @property def rpc(self) -> O2x5xxRPCDevice: if not self._rpc: - self._rpc = O2x5xxRPCDevice(address=self._address, timeout=self.__timeout) + self._rpc = O2x5xxRPCDevice(address=self._address, timeout=self._timeout) return self._rpc @property def pcic(self) -> O2x5xxPCICDevice: if not self._pcic: self._pcic = O2x5xxPCICDevice(address=self._address, port=self._port, - autoconnect=self._autoconnect, timeout=self.__timeout) + autoconnect=self._autoconnect, timeout=self._timeout) return self._pcic diff --git a/source/pcic/client.py b/source/pcic/client.py index b9f93fa..21b4eaf 100644 --- a/source/pcic/client.py +++ b/source/pcic/client.py @@ -33,29 +33,29 @@ def connect(self): :return: None """ if not self.connected: - self.pcicSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) - self.pcicSocket.settimeout(self.timeout) - self.pcicSocket.connect((self.address, self.port)) + self.pcicSocket = socket.create_connection((self.address, self.port), timeout=self.timeout) self.connected = True @property def timeout(self): """ - Get the current timeout value on blocking socket operations as a floating point number expressing seconds. + Get the current timeout value on blocking socket operations. If no socket instance available + the preset timeout value will be returned. :return: (float) socket timeout in seconds """ + if self.pcicSocket: + return self.pcicSocket.gettimeout() return self._timeout @timeout.setter def timeout(self, value): """ - Set a timeout on blocking socket operations. The value argument can be a non-negative floating point number - expressing seconds, or None. If a non-zero value is given, subsequent socket operations will raise a timeout - exception if the timeout period value has elapsed before the operation has completed. If zero is given, - the socket is put in non-blocking mode. If None is given, the socket is put in blocking mode. + Set a timeout on blocking socket operations. If a non-zero value is given, subsequent socket operations will + raise a timeout exception if the timeout period value has elapsed before the operation has completed. + If zero is given, the socket is put in non-blocking mode. If None is given, the socket is put in blocking mode. - :param value: (float) in seconds. + :param value: (float) non-negative socket timeout in seconds :return: None """ self._timeout = value diff --git a/source/pcic/utils.py b/source/pcic/utils.py deleted file mode 100644 index 9af92e8..0000000 --- a/source/pcic/utils.py +++ /dev/null @@ -1,18 +0,0 @@ -import functools -import multiprocessing.pool - - -def timeout(max_timeout): - """Timeout decorator, parameter in seconds.""" - def timeout_decorator(item): - """Wrap the original function.""" - @functools.wraps(item) - def func_wrapper(*args, **kwargs): - """Closure for function.""" - pool = multiprocessing.pool.ThreadPool(processes=1) - async_result = pool.apply_async(item, args, kwargs) - pool.close() - # raises a TimeoutError if execution exceeds max_timeout - return async_result.get(max_timeout) - return func_wrapper - return timeout_decorator diff --git a/source/rpc/application.py b/source/rpc/application.py index 387ecbd..86aa5d3 100644 --- a/source/rpc/application.py +++ b/source/rpc/application.py @@ -39,7 +39,7 @@ def getAllParameters(self): :return: (dict) name contains parameter-name, value the stringified parameter-value """ - result = self._applicationProxy.getAllParameters() + result = self._applicationProxy.proxy.getAllParameters() return result def getParameter(self, value): @@ -49,7 +49,7 @@ def getParameter(self, value): :param value: (str) parameter name :return: (str) """ - result = self._applicationProxy.getParameter(value) + result = self._applicationProxy.proxy.getParameter(value) return result def getAllParameterLimits(self) -> dict: @@ -60,7 +60,7 @@ def getAllParameterLimits(self) -> dict: :return: (dict) """ - result = self._applicationProxy.getAllParameterLimits() + result = self._applicationProxy.proxy.getAllParameterLimits() return result @property @@ -94,7 +94,7 @@ def Name(self, value: str) -> None: max_chars = 64 if value.__len__() > max_chars: raise ValueError("Max. {} characters".format(max_chars)) - self._applicationProxy.setParameter("Name", value) + self._applicationProxy.proxy.setParameter("Name", value) self.waitForConfigurationDone() @property @@ -118,7 +118,7 @@ def Description(self, value: str) -> None: max_chars = 500 if value.__len__() > 500: raise ValueError("Max. {} characters".format(max_chars)) - self._applicationProxy.setParameter("Description", value) + self._applicationProxy.proxy.setParameter("Description", value) self.waitForConfigurationDone() @property @@ -159,7 +159,7 @@ def TriggerMode(self, value: int) -> None: if value not in range(int(limits["min"]), int(limits["max"]), 1): raise ValueError("RPC Trigger value not available. Available range: {}\n" "For more help take a look on the docstring documentation.".format(limits)) - self._applicationProxy.setParameter("TriggerMode", value) + self._applicationProxy.proxy.setParameter("TriggerMode", value) self.waitForConfigurationDone() @property @@ -184,7 +184,7 @@ def FrameRate(self, value: float) -> None: if not float(limits["min"]) <= float(value) <= float(limits["max"]): raise ValueError("FrameRate value not available. Available range: {}" .format(self.getAllParameterLimits()["FrameRate"])) - self._applicationProxy.setParameter("FrameRate", value) + self._applicationProxy.proxy.setParameter("FrameRate", value) self.waitForConfigurationDone() @property @@ -248,7 +248,7 @@ def getValueErrorListNumber(): lower=width_lower, upper=width_upper)) if valueErrorList: raise ValueError("".join(valueErrorList)) - self._applicationProxy.setParameter("HWROI", json.dumps(value)) + self._applicationProxy.proxy.setParameter("HWROI", json.dumps(value)) self.waitForConfigurationDone() @property @@ -258,7 +258,7 @@ def Rotate180Degree(self) -> bool: :return: (bool) True / False """ - result = self._applicationProxy.getParameter("Rotate180Degree") + result = self._applicationProxy.proxy.getParameter("Rotate180Degree") if result == "false": return False return True @@ -271,7 +271,7 @@ def Rotate180Degree(self, value: bool) -> None: :param value: (bool) True / False :return: None """ - self._applicationProxy.setParameter("Rotate180Degree", value) + self._applicationProxy.proxy.setParameter("Rotate180Degree", value) self.waitForConfigurationDone() @property @@ -281,7 +281,7 @@ def FocusDistance(self) -> float: :return: (float) current focus distance in meter """ - result = float(self._applicationProxy.getParameter("FocusDistance")) + result = float(self._applicationProxy.proxy.getParameter("FocusDistance")) return result @FocusDistance.setter @@ -296,7 +296,7 @@ def FocusDistance(self, value: float) -> None: if not float(limits["min"]) <= float(value) <= float(limits["max"]): raise ValueError("FocusDistance value not available. Available range: {}" .format(self.getAllParameterLimits()["FocusDistance"])) - self._applicationProxy.setParameter("FocusDistance", value) + self._applicationProxy.proxy.setParameter("FocusDistance", value) # TODO: Wird hier geblockt? Wird der Focus Distance direkt nach dem setzen angefahren? # Edit: Kein Error, jedoch sind die Bilder unscharf wenn direkt danach das Bild angefordert wird: Fokus wird während requestImage im PCIC noch angefahren! self.waitForConfigurationDone() @@ -309,7 +309,7 @@ def ImageEvaluationOrder(self) -> str: :return: (str) """ - result = self._applicationProxy.getParameter("ImageEvaluationOrder") + result = self._applicationProxy.proxy.getParameter("ImageEvaluationOrder") return result @ImageEvaluationOrder.setter @@ -321,7 +321,7 @@ def ImageEvaluationOrder(self, value: list) -> None: :param value: (list) a whitespace separated list of ImagerConfig ids :return: None """ - self._applicationProxy.setParameter("ImageEvaluationOrder", value) + self._applicationProxy.proxy.setParameter("ImageEvaluationOrder", value) self.waitForConfigurationDone() @property @@ -330,7 +330,7 @@ def PcicTcpResultSchema(self) -> str: The PCIC TCP/IP Schema defines which result-data will be sent via TCP/IP. :return: (str) pcic tcp/ip schema config """ - return self._applicationProxy.getParameter("PcicTcpResultSchema") + return self._applicationProxy.proxy.getParameter("PcicTcpResultSchema") @PcicTcpResultSchema.setter def PcicTcpResultSchema(self, schema: str) -> None: @@ -339,7 +339,7 @@ def PcicTcpResultSchema(self, schema: str) -> None: :param schema: (str) pcic tcp/ip schema config :return: None """ - self._applicationProxy.setParameter("PcicTcpResultSchema", schema) + self._applicationProxy.proxy.setParameter("PcicTcpResultSchema", schema) validation = self.validate() if validation: warnings.warn(str(validation), UserWarning) @@ -352,7 +352,7 @@ def LogicGraph(self) -> str: JSON string describing a flow-graph which allows to program the logic between model-results and output-pins. :return: (str) JSON string flow-graph of Logic Layer """ - return self._applicationProxy.getParameter("LogicGraph") + return self._applicationProxy.proxy.getParameter("LogicGraph") @LogicGraph.setter def LogicGraph(self, schema: str) -> None: @@ -361,7 +361,7 @@ def LogicGraph(self, schema: str) -> None: :param schema: (str) JSON string flow-graph of Logic Layer :return: None """ - self._applicationProxy.setParameter("LogicGraph", schema) + self._applicationProxy.proxy.setParameter("LogicGraph", schema) validation = self.validate() if validation: warnings.warn(str(validation), UserWarning) @@ -440,7 +440,7 @@ def save(self) -> None: :return: None """ - self._applicationProxy.save() + self._applicationProxy.proxy.save() self.waitForConfigurationDone() def validate(self) -> list: @@ -449,7 +449,7 @@ def validate(self) -> list: :return: Array of fault-structs (Id: int, Text: string) """ - result = self._applicationProxy.validate() + result = self._applicationProxy.proxy.validate() return result def getImagerConfigList(self) -> list: @@ -458,7 +458,7 @@ def getImagerConfigList(self) -> list: :return: (list) Array of strings """ - result = self._applicationProxy.getImagerConfigList() + result = self._applicationProxy.proxy.getImagerConfigList() return result def availableImagerConfigTypes(self) -> list: @@ -467,7 +467,7 @@ def availableImagerConfigTypes(self) -> list: :return: (list) Array of strings """ - result = self._applicationProxy.availableImagerConfigTypes() + result = self._applicationProxy.proxy.availableImagerConfigTypes() return result def createImagerConfig(self, imagerType='normal', addToEval=True): @@ -479,7 +479,7 @@ def createImagerConfig(self, imagerType='normal', addToEval=True): not be activated for the image acquisition/evaluation run :return: (int) ID of new image-config """ - imagerIndex = self._applicationProxy.createImagerConfig(imagerType) + imagerIndex = self._applicationProxy.proxy.createImagerConfig(imagerType) if addToEval: imageEvalOrder = self.ImageEvaluationOrder imageEvalOrder += "{} ".format(imagerIndex) @@ -494,7 +494,7 @@ def copyImagerConfig(self, imagerIndex: int) -> int: :param imagerIndex: (int) ID of other Imager config :return: (int) ID of new image-config """ - imagerIndex = self._applicationProxy.copyImagerConfig(imagerIndex) + imagerIndex = self._applicationProxy.proxy.copyImagerConfig(imagerIndex) self.waitForConfigurationDone() return imagerIndex @@ -506,7 +506,7 @@ def deleteImagerConfig(self, imagerIndex: int) -> None: :param imagerIndex: (int) ID of image-config that should be removed :return: None """ - self._applicationProxy.deleteImagerConfig(imagerIndex) + self._applicationProxy.proxy.deleteImagerConfig(imagerIndex) self.waitForConfigurationDone() def isConfigurationDone(self) -> bool: @@ -516,7 +516,7 @@ def isConfigurationDone(self) -> bool: :return: (bool) True or False """ - result = self._applicationProxy.isConfigurationDone() + result = self._applicationProxy.proxy.isConfigurationDone() return result def waitForConfigurationDone(self): @@ -527,14 +527,4 @@ def waitForConfigurationDone(self): :return: None """ - self._applicationProxy.waitForConfigurationDone() - - def __getattr__(self, name): - """Pass given name to the actual xmlrpc.client.ServerProxy. - - Args: - name (str): name of attribute - Returns: - Attribute of xmlrpc.client.ServerProxy - """ - return self._editProxy.__getattr__(name) + self._applicationProxy.proxy.waitForConfigurationDone() diff --git a/source/rpc/client.py b/source/rpc/client.py index a08ebfe..ce1069a 100644 --- a/source/rpc/client.py +++ b/source/rpc/client.py @@ -3,17 +3,17 @@ from .edit import Edit from .application import Application from .imager import Imager -from .utils import timeout -from ..device.client import (O2x5xxPCICDevice, SOCKET_TIMEOUT) from ..static.devices import DevicesMeta import xmlrpc.client import json import io -import time import numpy as np import matplotlib.image as mpimg +SOCKET_TIMEOUT = 10 + + class O2x5xxRPCDevice(object): """ Main API class @@ -25,7 +25,6 @@ def __init__(self, address="192.168.0.69", api_path="/api/rpc/v1/", timeout=SOCK self.baseURL = "http://" + self.address + self.api_path self.mainURL = self.baseURL + "com.ifm.efector/" self.mainProxy = MainProxy(url=self.mainURL, timeout=self.timeout, device=self) - self.tcpIpPort = int(self.getParameter("PcicTcpPort")) self.deviceMeta = self._getDeviceMeta() self._session = None @@ -95,7 +94,7 @@ def getParameter(self, value: str) -> str: :return: (str) value of parameter """ try: - result = self.mainProxy.getParameter(value) + result = self.mainProxy.proxy.getParameter(value) return result except xmlrpc.client.Fault as e: if e.faultCode == 101000: @@ -109,7 +108,7 @@ def getAllParameters(self) -> dict: :return: (dict) name contains parameter-name, value the stringified parameter-value """ - result = self.mainProxy.getAllParameters() + result = self.mainProxy.proxy.getAllParameters() return result def getSWVersion(self) -> dict: @@ -118,7 +117,7 @@ def getSWVersion(self) -> dict: :return: (dict) struct of strings """ - result = self.mainProxy.getSWVersion() + result = self.mainProxy.proxy.getSWVersion() return result def getHWInfo(self) -> dict: @@ -127,7 +126,7 @@ def getHWInfo(self) -> dict: :return: (dict) struct of strings """ - result = self.mainProxy.getHWInfo() + result = self.mainProxy.proxy.getHWInfo() return result def getDmesgData(self) -> str: @@ -136,7 +135,7 @@ def getDmesgData(self) -> str: :return: (str) List of kernel messages """ - result = self.mainProxy.getDmesgData() + result = self.mainProxy.proxy.getDmesgData() return result def getClientCompatibilityList(self) -> list: @@ -145,7 +144,7 @@ def getClientCompatibilityList(self) -> list: :return: (list) Array of strings """ - result = self.mainProxy.getClientCompatibilityList() + result = self.mainProxy.proxy.getClientCompatibilityList() return result def getApplicationList(self) -> list: @@ -154,7 +153,7 @@ def getApplicationList(self) -> list: :return: (dict) array list of structs """ - result = self.mainProxy.getApplicationList() + result = self.mainProxy.proxy.getApplicationList() return result def reboot(self, mode: int = 0) -> None: @@ -168,7 +167,7 @@ def reboot(self, mode: int = 0) -> None: """ if mode == 0: print("Rebooting sensor {} ...".format(self.getParameter(value="Name"))) - self.mainProxy.reboot(mode) + self.mainProxy.proxy.reboot(mode) else: raise ValueError("Reboot mode {} not available.".format(str(mode))) @@ -179,7 +178,7 @@ def switchApplication(self, applicationIndex: int) -> None: :param applicationIndex: (int) Index of new application (Range 1-32) :return: None """ - self.mainProxy.switchApplication(applicationIndex) + self.mainProxy.proxy.switchApplication(applicationIndex) self.waitForConfigurationDone() def getTraceLogs(self, nLogs: int = 0) -> list: @@ -190,7 +189,7 @@ def getTraceLogs(self, nLogs: int = 0) -> list: 0: all logs are fetched :return: (list) Array of strings """ - result = self.mainProxy.getTraceLogs(nLogs) + result = self.mainProxy.proxy.getTraceLogs(nLogs) return result def getApplicationStatisticData(self, applicationIndex: int) -> dict: @@ -202,7 +201,7 @@ def getApplicationStatisticData(self, applicationIndex: int) -> dict: :param applicationIndex: (int) Index of application (Range 1-32) :return: (dict) """ - result = json.loads(self.mainProxy.getApplicationStatisticData(applicationIndex)) + result = json.loads(self.mainProxy.proxy.getApplicationStatisticData(applicationIndex)) return result def getReferenceImage(self) -> np.ndarray: @@ -212,7 +211,7 @@ def getReferenceImage(self) -> np.ndarray: :return: (np.ndarray) a JPEG decompressed image """ b = bytearray() - b.extend(map(ord, str(self.mainProxy.getReferenceImage()))) + b.extend(map(ord, str(self.mainProxy.proxy.getReferenceImage()))) result = mpimg.imread(io.BytesIO(b), format='jpg') return result @@ -223,7 +222,7 @@ def isConfigurationDone(self) -> bool: :return: (bool) True or False """ - result = self.mainProxy.isConfigurationDone() + result = self.mainProxy.proxy.isConfigurationDone() return result def waitForConfigurationDone(self): @@ -234,7 +233,7 @@ def waitForConfigurationDone(self): :return: None """ - self.mainProxy.waitForConfigurationDone() + self.mainProxy.proxy.waitForConfigurationDone() def measure(self, measureInput: dict) -> dict: """ @@ -244,29 +243,17 @@ def measure(self, measureInput: dict) -> dict: :return: (dict) measure result """ input_stringified = json.dumps(measureInput) - result = json.loads(self.mainProxy.measure(input_stringified)) + result = json.loads(self.mainProxy.proxy.measure(input_stringified)) return result - def trigger(self) -> str: + def trigger(self): """ Executes trigger and read answer. :return: (str) process interface output (TCP/IP) """ - with O2x5xxPCICDevice(address=self.address, port=self.tcpIpPort) as pcicDevice: - while self.getParameter("OperatingMode") != "0": - Warning("Sensor is not in Run Mode. Please finish parametrization first.") - time.sleep(0.1) - self.mainProxy.trigger() - # This is required since there is no lock for application evaluation process within the trigger()-method. - # After an answer is provided by the PCIC interface you can be sure, - # that the trigger count was incremented correctly and the evaluation process finished. - ticket, answer = pcicDevice.read_next_answer() - self.waitForConfigurationDone() - pcicDevice.close() - return answer.decode() - - @timeout(2) + self.mainProxy.proxy.trigger() + def doPing(self) -> str: """ Ping sensor device and check reachability in network. @@ -274,7 +261,7 @@ def doPing(self) -> str: :return: - "up" sensor is reachable through network - "down" sensor is not reachable through network """ - result = self.mainProxy.doPing() + result = self.mainProxy.proxy.doPing() return result def requestSession(self, password='', session_id='0' * 32) -> Session: @@ -288,20 +275,10 @@ def requestSession(self, password='', session_id='0' * 32) -> Session: :param session_id: (str) session ID (optional) :return: Session object """ - _sessionId = self.__getattr__('requestSession')(password, session_id) + _sessionId = self.mainProxy.proxy.requestSession(password, session_id) setattr(self, "_sessionId", _sessionId) _sessionURL = self.mainURL + 'session_' + _sessionId + '/' setattr(self, "_sessionURL", _sessionURL) _sessionProxy = SessionProxy(url=_sessionURL, device=self) setattr(self, "_sessionProxy", _sessionProxy) return self.session - - def __getattr__(self, name): - """Pass given name to the actual xmlrpc.client.ServerProxy. - - Args: - name (str): name of attribute - Returns: - Attribute of xmlrpc.client.ServerProxy - """ - return self.mainProxy.__getattr__(name) diff --git a/source/rpc/edit.py b/source/rpc/edit.py index 25f6a07..7a83ed2 100644 --- a/source/rpc/edit.py +++ b/source/rpc/edit.py @@ -16,7 +16,7 @@ def editApplication(self, app_index): Args: app_index (int): application index """ - self.__getattr__('editApplication')(app_index) + self._editProxy.proxy.editApplication(app_index) _applicationURL = self._editProxy.baseURL + "application/" setattr(self._device, "_applicationURL", _applicationURL) _applicationProxy = ApplicationProxy(url=_applicationURL, device=self._device) @@ -32,7 +32,7 @@ def createApplication(self, deviceType="WithModels") -> int: """ if deviceType not in ["Camera", "WithModels"]: raise AttributeError("Device type must be either value \"Camera\" or \"WithModels\"!") - appIndex = self._editProxy.createApplication(deviceType) + appIndex = self._editProxy.proxy.createApplication(deviceType) return appIndex def copyApplication(self, applicationIndex: int) -> int: @@ -43,7 +43,7 @@ def copyApplication(self, applicationIndex: int) -> int: :param applicationIndex: (int) Index of application which should be copied :return: (int) Index of new application """ - appIndex = self._editProxy.copyApplication(applicationIndex) + appIndex = self._editProxy.proxy.copyApplication(applicationIndex) return appIndex def deleteApplication(self, applicationIndex: int) -> None: @@ -54,7 +54,7 @@ def deleteApplication(self, applicationIndex: int) -> None: :param applicationIndex: (int) application index :return: None """ - self._editProxy.deleteApplication(applicationIndex) + self._editProxy.proxy.deleteApplication(applicationIndex) def changeNameAndDescription(self, applicationIndex: int, name: str = "", description: str = "") -> None: """ @@ -71,7 +71,7 @@ def changeNameAndDescription(self, applicationIndex: int, name: str = "", descri max_chars = 500 if description.__len__() > 500: raise ValueError("Max. {} characters for description".format(max_chars)) - self._editProxy.changeNameAndDescription(applicationIndex, name, description) + self._editProxy.proxy.changeNameAndDescription(applicationIndex, name, description) def moveApplications(self, applicationIndexFrom: int, applicationIndexTo: int) -> None: """ @@ -81,20 +81,10 @@ def moveApplications(self, applicationIndexFrom: int, applicationIndexTo: int) - :param applicationIndexTo: (int) desired application id in application list :return: None """ - app_list = self._device.mainProxy.getApplicationList() + app_list = self._device.getApplicationList() move_list = [] for app in app_list: if int(app["Index"]) == int(applicationIndexFrom): app["Index"] = int(applicationIndexTo) move_list.append({'Id': app['Id'], 'Index': app['Index']}) - self._editProxy.moveApplications(move_list) - - def __getattr__(self, name): - """Pass given name to the actual xmlrpc.client.ServerProxy. - - Args: - name (str): name of attribute - Returns: - Attribute of xmlrpc.client.ServerProxy - """ - return self._editProxy.__getattr__(name) + self._editProxy.proxy.moveApplications(move_list) diff --git a/source/rpc/imageQualityCheck.py b/source/rpc/imageQualityCheck.py index 874419a..f5751a9 100644 --- a/source/rpc/imageQualityCheck.py +++ b/source/rpc/imageQualityCheck.py @@ -27,7 +27,7 @@ def enabled(self) -> bool: :return: (bool) True / False """ - if self._imagerProxy.getAllParameters()["QualityCheckConfig"]: + if self._imagerProxy.proxy.getAllParameters()["QualityCheckConfig"]: return True return False @@ -40,9 +40,9 @@ def enabled(self, value: bool) -> None: :return: None """ if value: - self._imagerProxy.setParameter("QualityCheckConfig", True) + self._imagerProxy.proxy.setParameter("QualityCheckConfig", True) else: - self._imagerProxy.setParameter("QualityCheckConfig", "") + self._imagerProxy.proxy.setParameter("QualityCheckConfig", "") while self._device.isConfigurationDone() < 1.0: time.sleep(1) @@ -55,7 +55,7 @@ def _QualityCheckConfig(self) -> [dict, None]: """ if not self.enabled: return None - result = self._imagerProxy.getAllParameters()["QualityCheckConfig"] + result = self._imagerProxy.proxy.getAllParameters()["QualityCheckConfig"] result = ast.literal_eval(result) return result @@ -69,7 +69,7 @@ def _QualityCheckConfig(self, inputDict): """ if not self.enabled: self.enabled = True - self._imagerProxy.setParameter("QualityCheckConfig", json.dumps(inputDict)) + self._imagerProxy.proxy.setParameter("QualityCheckConfig", json.dumps(inputDict)) @property def _QualityCheckConfigSchema(self) -> dict: @@ -78,7 +78,7 @@ def _QualityCheckConfigSchema(self) -> dict: :return: (dict) schema of Image Quality Check """ - # ip = urlparse(self._imagerProxy.baseURL).netloc + # ip = urlparse(self._imagerProxy.proxy.baseURL).netloc # with urlopen("http://{}/schema/ParamImageFeatures.json".format(ip)) as url: # data = json.load(url) # return data diff --git a/source/rpc/imager.py b/source/rpc/imager.py index 7ae4faf..2967169 100644 --- a/source/rpc/imager.py +++ b/source/rpc/imager.py @@ -31,7 +31,7 @@ def getAllParameters(self): :return: (dict) name contains parameter-name, value the stringified parameter-value """ - result = self._imagerProxy.getAllParameters() + result = self._imagerProxy.proxy.getAllParameters() return result def getParameter(self, value): @@ -41,7 +41,7 @@ def getParameter(self, value): :param value: (str) parameter name :return: (str) """ - result = self._imagerProxy.getParameter(value) + result = self._imagerProxy.proxy.getParameter(value) return result def getAllParameterLimits(self): @@ -52,7 +52,7 @@ def getAllParameterLimits(self): :return: (dict) """ - result = self._imagerProxy.getAllParameterLimits() + result = self._imagerProxy.proxy.getAllParameterLimits() return result @property @@ -85,7 +85,7 @@ def Name(self, value: str) -> None: max_chars = 64 if value.__len__() > max_chars: raise ValueError("Max. {} characters".format(max_chars)) - self._imagerProxy.setParameter("Name", value) + self._imagerProxy.proxy.setParameter("Name", value) self._device.waitForConfigurationDone() @property @@ -118,7 +118,7 @@ def Illumination(self, value: int) -> None: if value not in range(int(limits["min"]), int(limits["max"]), 1): raise ValueError("Illumination value not available. Available range: {}" .format(self.getAllParameterLimits()["Illumination"])) - self._imagerProxy.setParameter("Illumination", value) + self._imagerProxy.proxy.setParameter("Illumination", value) self._device.waitForConfigurationDone() @property @@ -159,7 +159,7 @@ def IlluInternalSegments(self, inputDict: dict) -> None: value += inputDict["upper-right"] * 0x02 value += inputDict["lower-left"] * 0x04 value += inputDict["lower-right"] * 0x08 - self._imagerProxy.setParameter("IlluInternalSegments", value) + self._imagerProxy.proxy.setParameter("IlluInternalSegments", value) self._device.waitForConfigurationDone() @property @@ -196,7 +196,7 @@ def Color(self, value: int) -> None: if not int(limits["min"]) <= value <= int(limits["max"]): raise ValueError("Color value not available. Available range: {}" .format(self.getAllParameterLimits()["Color"])) - self._imagerProxy.setParameter("Color", value) + self._imagerProxy.proxy.setParameter("Color", value) else: articleNumber = self._device.getParameter(value="ArticleNumber") raise TypeError("Color attribute not available for sensor {}.".format(articleNumber)) @@ -224,7 +224,7 @@ def ExposureTime(self, value: int) -> None: if not int(limits["min"]) <= int(value) <= int(limits["max"]): raise ValueError("ExposureTime value not available. Available range: {}" .format(self.getAllParameterLimits()["ExposureTime"])) - self._imagerProxy.setParameter("ExposureTime", value) + self._imagerProxy.proxy.setParameter("ExposureTime", value) self._device.waitForConfigurationDone() @property @@ -249,7 +249,7 @@ def AnalogGainFactor(self, value: int) -> None: if str(value) not in limits["values"]: raise ValueError("AnalogGainFactor value not available. Available values: {}" .format(self.getAllParameterLimits()["AnalogGainFactor"])) - self._imagerProxy.setParameter("AnalogGainFactor", value) + self._imagerProxy.proxy.setParameter("AnalogGainFactor", value) self._device.waitForConfigurationDone() @property @@ -284,7 +284,7 @@ def FilterType(self, value: int) -> None: if not int(limits["min"]) <= int(value) <= int(limits["max"]): raise ValueError("FilterType value not available. Available range: {}" .format(self.getAllParameterLimits()["FilterType"])) - self._imagerProxy.setParameter("FilterType", value) + self._imagerProxy.proxy.setParameter("FilterType", value) self._device.waitForConfigurationDone() @property @@ -311,7 +311,7 @@ def FilterStrength(self, value: int): if not int(limits["min"]) <= int(value) <= int(limits["max"]): raise ValueError("FilterStrength value not available. Available range: {}" .format(self.getAllParameterLimits()["FilterStrength"])) - self._imagerProxy.setParameter("FilterStrength", value) + self._imagerProxy.proxy.setParameter("FilterStrength", value) self._device.waitForConfigurationDone() @property @@ -321,7 +321,7 @@ def FilterInvert(self) -> bool: :return: (bool) True or False """ - result = self._imagerProxy.getParameter("FilterInvert") + result = self._imagerProxy.proxy.getParameter("FilterInvert") if result == "false": return False return True @@ -334,7 +334,7 @@ def FilterInvert(self, value: bool) -> None: :param value: (bool) True or False :return: None """ - self._imagerProxy.setParameter("FilterInvert", value) + self._imagerProxy.proxy.setParameter("FilterInvert", value) self._device.waitForConfigurationDone() def startCalculateExposureTime(self, minAnalogGainFactor: int = None, maxAnalogGainFactor: int = None, @@ -364,7 +364,7 @@ def startCalculateExposureTime(self, minAnalogGainFactor: int = None, maxAnalogG inputAutoExposure["ROIs"] = defaultROIsZone if RODs: inputAutoExposure["RODs"] = RODs - self._imagerProxy.startCalculateExposureTime(json.dumps(inputAutoExposure)) + self._imagerProxy.proxy.startCalculateExposureTime(json.dumps(inputAutoExposure)) while self.getProgressCalculateExposureTime() < 1.0: time.sleep(1) @@ -375,7 +375,7 @@ def getProgressCalculateExposureTime(self) -> float: :return: (float) progress (0.0 to 1.0) """ - result = self._imagerProxy.getProgressCalculateExposureTime() + result = self._imagerProxy.proxy.getProgressCalculateExposureTime() return result def startCalculateAutofocus(self, ROIs: list = None, RODs: list = None) -> None: @@ -394,7 +394,7 @@ def startCalculateAutofocus(self, ROIs: list = None, RODs: list = None) -> None: inputAutoFocus["ROIs"] = defaultROIsZone if RODs: inputAutoFocus["RODs"] = RODs - self._imagerProxy.startCalculateAutofocus(json.dumps(inputAutoFocus)) + self._imagerProxy.proxy.startCalculateAutofocus(json.dumps(inputAutoFocus)) while self.getProgressCalculateAutofocus() < 1.0: time.sleep(1) @@ -406,7 +406,7 @@ def stopCalculateAutofocus(self) -> None: :return: None """ - self._imagerProxy.stopCalculateAutofocus() + self._imagerProxy.proxy.stopCalculateAutofocus() def getProgressCalculateAutofocus(self) -> float: """ @@ -415,7 +415,7 @@ def getProgressCalculateAutofocus(self) -> float: :return: (float) progress (0.0 to 1.0) """ - result = self._imagerProxy.getProgressCalculateAutofocus() + result = self._imagerProxy.proxy.getProgressCalculateAutofocus() return result def getAutofocusDistances(self) -> list: @@ -424,7 +424,7 @@ def getAutofocusDistances(self) -> list: :return: a list of floating point values, separated by comma """ - result = self._imagerProxy.getAutofocusDistances() + result = self._imagerProxy.proxy.getAutofocusDistances() if result: if "," not in result: return [float(result)] @@ -438,17 +438,7 @@ def getAutoExposureResult(self) -> [dict, None]: :return: (dict) json with algo run result as a string """ - result = self._imagerProxy.getAutoExposureResult() + result = self._imagerProxy.proxy.getAutoExposureResult() if result: data = json.loads(result) return data - - def __getattr__(self, name): - """Pass given name to the actual xmlrpc.client.ServerProxy. - - Args: - name (str): name of attribute - Returns: - Attribute of xmlrpc.client.ServerProxy - """ - return self._editProxy.__getattr__(name) diff --git a/source/rpc/proxy.py b/source/rpc/proxy.py index 28c0692..b3857f6 100644 --- a/source/rpc/proxy.py +++ b/source/rpc/proxy.py @@ -40,16 +40,6 @@ def timeout(self, value): def proxy(self): return self.__proxy - def __getattr__(self, name): - """Pass given name to the actual xmlrpc.client.ServerProxy. - - Args: - name (str): name of attribute - Returns: - Attribute of xmlrpc.client.ServerProxy - """ - return self.__proxy.__getattr__(name) - def close(self): self.__transport.close() self.__transport = None @@ -86,7 +76,7 @@ def requestSession(self, password='', session_id='0' * 32, timeout=SOCKET_TIMEOU If None, SOCKET_TIMEOUT value is used as default """ try: - self.device._sessionId = self.__getattr__('requestSession')(password, session_id) + self.device._sessionId = self.proxy.requestSession(password, session_id) self.device._sessionURL = self.baseURL + 'session_' + session_id + '/' self.device._sessionProxy = SessionProxy(url=self.device._sessionURL, device=self.device, timeout=timeout) @@ -97,7 +87,7 @@ def requestSession(self, password='', session_id='0' * 32, timeout=SOCKET_TIMEOU self.device._sessionProxy.autoHeartbeatTimer.cancel() except AttributeError: pass - self.device._sessionProxy.cancelSession() + self.device._sessionProxy.proxy.cancelSession() self.device._sessionProxy.close() self.device._sessionProxy = None self.device._sessionURL = None @@ -157,12 +147,12 @@ def setOperatingMode(self, mode, timeout=SOCKET_TIMEOUT): If None, SOCKET_TIMEOUT value is used as default """ try: - self.__getattr__('setOperatingMode')(mode) + self.proxy.setOperatingMode(mode) self.device._editURL = self.baseURL + 'edit/' self.device._editProxy = EditProxy(url=self.device._editURL, device=self.device, timeout=timeout) yield finally: - self.__getattr__('setOperatingMode')(0) + self.proxy.setOperatingMode(0) self.device._editProxy.close() self.device._editURL = None self.device._editProxy = None @@ -188,13 +178,13 @@ def editApplication(self, app_index, timeout=SOCKET_TIMEOUT): If None, SOCKET_TIMEOUT value is used as default """ try: - self.__getattr__('editApplication')(app_index) + self.proxy.editApplication(app_index) self.device._applicationURL = self.baseURL + "application/" self.device._applicationProxy = ApplicationProxy(url=self.device._applicationURL, device=self.device, timeout=timeout) yield finally: - self.__getattr__('stopEditingApplication')() + self.proxy.stopEditingApplication() self.device._applicationProxy.close() self.device._applicationURL = None self.device._applicationProxy = None diff --git a/source/rpc/session.py b/source/rpc/session.py index 4ff81a8..93fbe65 100644 --- a/source/rpc/session.py +++ b/source/rpc/session.py @@ -37,8 +37,8 @@ def stopEdit(self) -> None: :return: None """ self.setOperatingMode(0) - self.device._editURL = None - self.device._editProxy = None + self._device._editURL = None + self._device._editProxy = None def setOperatingMode(self, mode) -> [None, Edit]: """ @@ -50,7 +50,7 @@ def setOperatingMode(self, mode) -> [None, Edit]: 2: simulation mode (Not implemented!) :return: None or Edit object """ - self.__getattr__('setOperatingMode')(mode) + self._sessionProxy.proxy.setOperatingMode(mode) def exportConfig(self) -> bytearray: """ @@ -59,14 +59,14 @@ def exportConfig(self) -> bytearray: :return: (bytearray) configuration as one data-blob :binary/base64 """ # increase heartbeat interval which will prevent a closed session after the "long" export progress - self._device.sessionProxy.heartbeat(heartbeatInterval=30) - config = self._sessionProxy.exportConfig() + self._sessionProxy.heartbeat(heartbeatInterval=30) + config = self._sessionProxy.proxy.exportConfig() config_bytes = bytearray() config_bytes.extend(map(ord, str(config))) while self.getExportProgress() < 1.0: time.sleep(1) self.cleanupExport() - self._device.waitForConfigurationDone() + self._device.mainProxy.proxy.waitForConfigurationDone() return config_bytes def importConfig(self, config: str, global_settings=True, network_settings=False, applications=True) -> None: @@ -80,16 +80,16 @@ def importConfig(self, config: str, global_settings=True, network_settings=False :return: None """ # This is required due to the long import progress which may take longer than 10 seconds (default) - self._device.sessionProxy.heartbeat(heartbeatInterval=30) + self._sessionProxy.heartbeat(heartbeatInterval=30) if global_settings: - self._sessionProxy.importConfig(config, 0x0001) + self._sessionProxy.proxy.importConfig(config, 0x0001) if network_settings: - self._sessionProxy.importConfig(config, 0x0002) + self._sessionProxy.proxy.importConfig(config, 0x0002) if applications: - self._sessionProxy.importConfig(config, 0x0010) + self._sessionProxy.proxy.importConfig(config, 0x0010) while self.getImportProgress() < 1.0: time.sleep(1) - self._device.waitForConfigurationDone() + self._device.mainProxy.proxy.waitForConfigurationDone() def exportApplication(self, applicationIndex: int) -> bytearray: """ @@ -99,7 +99,7 @@ def exportApplication(self, applicationIndex: int) -> bytearray: :return: None """ - config = self._sessionProxy.exportApplication(applicationIndex) + config = self._sessionProxy.proxy.exportApplication(applicationIndex) application_bytes = bytearray() application_bytes.extend(map(ord, str(config))) while self.getExportProgress() < 1.0: @@ -116,7 +116,7 @@ def importApplication(self, application: str) -> int: :return: (int) index of new application in list """ - index = int(self._sessionProxy.importApplication(application)) + index = int(self._sessionProxy.proxy.importApplication(application)) while self.getImportProgress() < 1.0: time.sleep(1) return index @@ -129,7 +129,7 @@ def getImportProgress(self) -> float: :return: (float) progress (0.0 to 1.0) """ try: - result = self._sessionProxy.getImportProgress() + result = self._sessionProxy.proxy.getImportProgress() return result except xmlrpc.client.Fault as fault: if fault.faultCode == 101107: @@ -143,7 +143,7 @@ def getExportProgress(self) -> float: :return: (float) progress (0.0 to 1.0) """ try: - result = self._sessionProxy.getExportProgress() + result = self._sessionProxy.proxy.getExportProgress() return result except xmlrpc.client.Fault as fault: if fault.faultCode == 101110: @@ -158,7 +158,7 @@ def cleanupExport(self) -> None: :return: None """ - self._sessionProxy.cleanupExport() + self._sessionProxy.proxy.cleanupExport() def getApplicationDetails(self, applicationIndex: [int, str]) -> dict: """ @@ -168,7 +168,7 @@ def getApplicationDetails(self, applicationIndex: [int, str]) -> dict: :param applicationIndex: (int) application Index :return: (dict) json-string containing application parameters, models and image settings """ - result = json.loads(self._sessionProxy.getApplicationDetails(applicationIndex)) + result = json.loads(self._sessionProxy.proxy.getApplicationDetails(applicationIndex)) return result def resetStatistics(self) -> None: @@ -177,8 +177,8 @@ def resetStatistics(self) -> None: :return: None """ - self._sessionProxy.resetStatistics() - self._device.waitForConfigurationDone() + self._sessionProxy.proxy.resetStatistics() + self._device.mainProxy.proxy.waitForConfigurationDone() def writeApplicationConfigFile(self, applicationName: str, data: bytearray) -> None: """ @@ -247,12 +247,13 @@ def _readConfigFile(self, configFile: str) -> str: else: raise FileExistsError("File {} does not exist!".format(configFile)) - def __getattr__(self, name): - """Pass given name to the actual xmlrpc.client.ServerProxy. - - Args: - name (str): name of attribute - Returns: - Attribute of xmlrpc.client.ServerProxy + def cancelSession(self) -> None: + """ + Method for closing the session. + :return: None """ - return self._sessionProxy.__getattr__(name) + self._sessionProxy.proxy.cancelSession() + self._sessionProxy.close() + self._sessionProxy = None + self._device._sessionURL = None + self._device._sessionId = None diff --git a/source/rpc/utils.py b/source/rpc/utils.py index 5405d5d..c74473f 100644 --- a/source/rpc/utils.py +++ b/source/rpc/utils.py @@ -1,24 +1,6 @@ import zipfile import json import warnings -import multiprocessing.pool -import functools - - -def timeout(max_timeout): - """Timeout decorator, parameter in seconds.""" - def timeout_decorator(item): - """Wrap the original function.""" - @functools.wraps(item) - def func_wrapper(*args, **kwargs): - """Closure for function.""" - pool = multiprocessing.pool.ThreadPool(processes=1) - async_result = pool.apply_async(item, args, kwargs) - pool.close() - # raises a TimeoutError if execution exceeds max_timeout - return async_result.get(max_timeout) - return func_wrapper - return timeout_decorator def firmwareWarning(function): @@ -36,7 +18,7 @@ def wrapper(self, *args, **kwargs): raise ImportError("Unknown config file in zip: {}".format(str(zipFiles))) jsonData = json.loads(zipOpen.open(tmp).read()) minConfigFileFirmware = jsonData["Firmware"] - sensorFirmware = self._device.mainProxy.getSWVersion()["IFM_Software"] + sensorFirmware = self._device.getSWVersion()["IFM_Software"] if int(sensorFirmware.replace(".", "")) < int(minConfigFileFirmware.replace(".", "")): message = "Missmatch in firmware versions: Sensor firmware {} is lower than {} firmware {}. " \ "Import of may will fail!".format(sensorFirmware, tmp, minConfigFileFirmware) diff --git a/tests/test_device.py b/tests/test_device.py index 52b2e5a..f1e175c 100644 --- a/tests/test_device.py +++ b/tests/test_device.py @@ -110,6 +110,17 @@ def test_RPC_client_device_v1_client_with_wrong_ip_and_autoconnect_false_and_tim duration_secs = end_time - start_time self.assertLess(duration_secs, TIMEOUT_VALUE+1) + def test_device_v1_client_RPC_and_PCIC_client_properties_after_exit_method(self): + device = O2x5xxDevice(deviceAddress, pcicTcpPort) + with device: + device.rpc.getParameter("ActiveApplication") + device.request_device_information() + device.rpc.getParameter("ActiveApplication") + with self.assertRaises(AttributeError): + device.request_device_information() + device.connect() + device.request_device_information() + class TestDeviceV2(TestCase): device = None @@ -156,6 +167,7 @@ def test_device_v2_client_with_multiple_connects_with_autoconnect_False(self): result = device.pcic.occupancy_of_application_list() self.assertNotEqual(result, "!") self.assertNotEqual(result, "?") + device.pcic.disconnect() def test_device_v2_client_without_context_manager_with_autoconnect_False(self): device = O2x5xxDeviceV2(deviceAddress, pcicTcpPort, autoconnect=False) @@ -213,3 +225,11 @@ def test_RPC_client_device_v2_client_with_wrong_ip_and_autoconnect_false_and_tim end_time = time.time() duration_secs = end_time - start_time self.assertLess(duration_secs, TIMEOUT_VALUE+1) + + def test_device_v2_client_RPC_and_PCIC_client_properties_after_exit_method(self): + device = O2x5xxDeviceV2(deviceAddress, pcicTcpPort) + with device: + device.rpc.getParameter("ActiveApplication") + device.pcic.request_device_information() + device.rpc.getParameter("ActiveApplication") + device.pcic.request_device_information() diff --git a/tests/test_pcic.py b/tests/test_pcic.py index 560ec2b..7b37420 100644 --- a/tests/test_pcic.py +++ b/tests/test_pcic.py @@ -378,3 +378,28 @@ def test_request_current_protocol_version(self): self.assertEqual(result, "*") result = pcic.request_current_protocol_version() self.assertEqual(result, "0{} 01 02 03".format(str(initialPCICVersion))) + + def test_timeout(self): + TIMEOUT_VALUES = range(1, 5) + + # Passing timeout value to constructor + for timeout_value in TIMEOUT_VALUES: + with O2x5xxPCICDevice(deviceAddress, pcicTcpPort, timeout=timeout_value) as pcic: + self.assertEqual(pcic.timeout, timeout_value) + + # Passing timeout value to constructor with autoconnect = False + for timeout_value in TIMEOUT_VALUES: + with O2x5xxPCICDevice(deviceAddress, pcicTcpPort, timeout=timeout_value, autoconnect=False) as pcic: + self.assertEqual(pcic.timeout, timeout_value) + + # Passing timeout value to property + for timeout_value in TIMEOUT_VALUES: + with O2x5xxPCICDevice(deviceAddress, pcicTcpPort) as pcic: + pcic.timeout = timeout_value + self.assertEqual(pcic.timeout, timeout_value) + + # Passing timeout value to property with autoconnect = False + for timeout_value in TIMEOUT_VALUES: + with O2x5xxPCICDevice(deviceAddress, pcicTcpPort, autoconnect=False) as pcic: + pcic.timeout = timeout_value + self.assertEqual(pcic.timeout, timeout_value) diff --git a/tests/test_rpc.py b/tests/test_rpc.py index 8915ae4..b82b21c 100644 --- a/tests/test_rpc.py +++ b/tests/test_rpc.py @@ -47,7 +47,7 @@ def test_timeout_with_invalid_ip(self): for timeout_value in TIMEOUT_VALUES: start_time = time.time() with self.assertRaises(socket.timeout): - with O2x5xxRPCDevice("192.168.0.5", timeout=timeout_value) as device: + with O2x5xxRPCDevice("192.168.1.5", timeout=timeout_value) as device: device.rpc.getParameter("ActiveApplication") self.assertEqual(device.mainProxy.timeout, timeout_value) end_time = time.time() @@ -107,10 +107,10 @@ def test_switchApplication(self): self.assertEqual(int(rpc.getParameter("ActiveApplication")), 1) else: rpc.switchApplication(applicationIndex=2) + rpc.trigger() while rpc.getParameter("OperatingMode") != "0": time.sleep(1) self.assertEqual(int(rpc.getParameter("ActiveApplication")), 2) - time.sleep(5) # Switch back to initial application rpc.switchApplication(applicationIndex=initial_application) while rpc.getParameter("OperatingMode") != "0": @@ -198,19 +198,6 @@ def test_measure(self): self.assertIsInstance(result, dict) self.assertTrue(result) - def test_trigger(self): - with O2x5xxRPCDevice(deviceAddress) as rpc: - number_trigger = 10 - application_active = rpc.getParameter(value="ActiveApplication") - initial_application_stats = rpc.getApplicationStatisticData(applicationIndex=int(application_active)) - initial_number_of_frames = initial_application_stats['number_of_frames'] - for i in range(number_trigger): - answer = rpc.trigger() - self.assertTrue(answer) - application_stats = rpc.getApplicationStatisticData(applicationIndex=int(application_active)) - number_of_frames = application_stats['number_of_frames'] - self.assertEqual(number_of_frames, initial_number_of_frames + number_trigger) - def test_doPing(self): with O2x5xxRPCDevice(deviceAddress) as rpc: result = rpc.doPing() diff --git a/tests/test_session.py b/tests/test_session.py index 97fe9a1..814c990 100644 --- a/tests/test_session.py +++ b/tests/test_session.py @@ -1,5 +1,5 @@ from unittest import TestCase -from source import O2x5xxRPCDevice +from source import O2x5xxRPCDevice, O2x5xxPCICDevice from tests.utils import * from .config import * @@ -84,9 +84,10 @@ def test_resetStatistics(self): triggerNum = 20 self.rpc.switchApplication(applicationIndex=2) self.rpc.session.resetStatistics() - for i in range(triggerNum): - answer = self.rpc.trigger() - self.assertTrue(answer) + with O2x5xxPCICDevice(deviceAddress, pcicTcpPort) as pcic: + for i in range(triggerNum): + answer = pcic.execute_synchronous_trigger() + self.assertTrue(answer) result = self.rpc.getApplicationStatisticData(applicationIndex=2) self.assertEqual(result['number_of_frames'], triggerNum) self.rpc.session.resetStatistics()