diff --git a/Common/Libraries/IRALibrary/src/IRAPy/Connection.py b/Common/Libraries/IRALibrary/src/IRAPy/Connection.py new file mode 100644 index 0000000000000000000000000000000000000000..0294b49907eadc7647932788861f1655f9d62cc5 --- /dev/null +++ b/Common/Libraries/IRALibrary/src/IRAPy/Connection.py @@ -0,0 +1,45 @@ +# Author: +# Giuseppe Carboni, + +import socket +import time +from contextlib import contextmanager + +import ComponentErrorsImpl + + +class Connection(object): + """This class implements a contextmanager for a socket. + Usage example: + + with Connection(('127.0.0.1', 10000)) as s: + s.sendall('COMMAND\n') + answer = s.recv(1024) + + :param: address, a tuple containing IP address and PORT for the socket + :param: timeout, connection timeout, in seconds + """ + + def __init__(self, address, timeout=2): + self.address = address + + def __enter__(self): + self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) + connected = 1 + t0 = time.time() + while time.time() - t0 < timeout: + connected = self.s.connect_ex(self.address) + if connected == 0: + break + time.sleep(0.01) + if connected: + reason = 'Could not reach the device!' + from IRAPy import logger + logger.logError(reason) + exc = ComponentErrorsImpl.SocketErrorExImpl() + exc.setData('Reason', reason) + raise exc + return self.s + + def __exit__(self, type, value, traceback): + self.s.close() diff --git a/Common/Libraries/IRALibrary/src/IRAPy/__init__.py b/Common/Libraries/IRALibrary/src/IRAPy/__init__.py index f5b3d9a6aa39b3433f7e69c83fa6beec4f9a4567..dfae5e20669b8890b5dfbcf8b81e1b3348093feb 100644 --- a/Common/Libraries/IRALibrary/src/IRAPy/__init__.py +++ b/Common/Libraries/IRALibrary/src/IRAPy/__init__.py @@ -6,10 +6,12 @@ C{from IRAPy import logger} list of modules: - customlogging: custom logging functionalities to replace standard logging - bsqueue: BoundedSortedQueue class implements a priority queue structure + - Connection: Connection class implements a contextmanager for a socket """ import customlogging import ACSLog +import Connection #Some comments required here. The custom logger mechanism is not working in python. #do the way to separate the system logs to the ones do be shown to the user is to use different