Python Library TCP Socket
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

__init__.py 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. #!/usr/bin/env python
  2. # -*- coding: UTF-8 -*-
  3. """
  4. tcp_socket (TCP Socket)
  5. =======================
  6. **Author:**
  7. * Dirk Alders <sudo-dirk@mount-mockery.de>
  8. **Description:**
  9. This Module supports a client/ server tcp socket connection.
  10. **Submodules:**
  11. * :class:`tcp_socket.tcp_client`
  12. * :class:`tcp_socket.tcp_client_stp`
  13. * :class:`tcp_socket.tcp_server`
  14. * :class:`tcp_socket.tcp_server_stp`
  15. **Unittest:**
  16. See also the :download:`unittest <tcp_socket/_testresults_/unittest.pdf>` documentation.
  17. **Module Documentation:**
  18. """
  19. __DEPENDENCIES__ = ['stringtools', 'task', ]
  20. import stringtools
  21. import task
  22. import logging
  23. import socket
  24. import time
  25. try:
  26. from config import APP_NAME as ROOT_LOGGER_NAME
  27. except ImportError:
  28. ROOT_LOGGER_NAME = 'root'
  29. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
  30. __DESCRIPTION__ = """The Module {\\tt %s} is designed to help with client / server tcp socket connections.
  31. For more Information read the documentation.""" % __name__.replace('_', '\_')
  32. """The Module Description"""
  33. __INTERPRETER__ = (2, 3)
  34. """The Tested Interpreter-Versions"""
  35. class tcp_base(object):
  36. """
  37. This is the base class for other classes in this module.
  38. :param host: The host IP for the TCP socket functionality
  39. :type host: str
  40. :param port: The port for the TCP socket functionality
  41. :type port: int
  42. :param channel_name: The name for the logging channel
  43. :type channel_name: str
  44. .. note:: This class is not designed for direct usage.
  45. """
  46. DEFAULT_CHANNEL_NAME = 'all_others'
  47. RX_LENGTH = 0xff
  48. COM_TIMEOUT = 0.5
  49. IS_CLIENT = False
  50. def __init__(self, host, port, channel_name=None):
  51. self.host = host
  52. self.port = port
  53. self.init_channel_name(channel_name)
  54. self.__socket__ = None
  55. self.__data_available_callback__ = None
  56. self.__supress_data_available_callback__ = False
  57. self.__connect_callback__ = None
  58. self.__disconnect_callback__ = None
  59. self.__clean_receive_buffer__()
  60. self.__connection__ = None
  61. self.__listening_message_displayed__ = False
  62. self.__client_address__ = None
  63. self.__queue__ = task.threaded_queue()
  64. self.__queue__.enqueue(5, self.__receive_task__)
  65. self.__queue__.run()
  66. def __call_data_available_callback__(self):
  67. if len(self.__receive_buffer__) > 0 and not self.__supress_data_available_callback__ and self.__data_available_callback__ is not None:
  68. self.__supress_data_available_callback__ = True
  69. self.__data_available_callback__(self)
  70. self.__supress_data_available_callback__ = False
  71. def __clean_receive_buffer__(self):
  72. self.logger.debug("Cleaning up receive-buffer")
  73. self.__receive_buffer__ = b''
  74. def __connection_lost__(self):
  75. self.__listening_message_displayed__ = False
  76. self.__connection__.close()
  77. self.__connection__ = None
  78. self.__client_address__ = None
  79. self.logger.info('Connection lost...')
  80. if self.__disconnect_callback__ is not None:
  81. self.__disconnect_callback__()
  82. def __del__(self):
  83. self.close()
  84. def __receive_task__(self, queue_inst):
  85. if self.__connection__ is not None:
  86. try:
  87. data = self.__connection__.recv(self.RX_LENGTH)
  88. except socket.error as e:
  89. if e.errno != 11:
  90. raise
  91. else:
  92. time.sleep(.05)
  93. else:
  94. if len(data) > 0:
  95. self.logger.info('RX <- "%s"', stringtools.hexlify(data))
  96. self.__receive_buffer__ += data
  97. else:
  98. self.__connection_lost__()
  99. self.__call_data_available_callback__()
  100. else:
  101. self.__connect__()
  102. queue_inst.enqueue(5, self.__receive_task__)
  103. def client_address(self):
  104. """
  105. This method returns the address of the connected client.
  106. :return: The client address.
  107. :rtype: str
  108. """
  109. return self.__client_address__[0]
  110. def close(self):
  111. """
  112. This method closes the connected communication channel, if exists.
  113. """
  114. self.__queue__.stop()
  115. self.__queue__.join()
  116. if self.__connection__ is not None:
  117. self.__connection_lost__()
  118. if self.__socket__ is not None:
  119. self.__socket__.close()
  120. def init_channel_name(self, channel_name=None):
  121. """
  122. With this Method, the channel name for logging can be changed.
  123. :param channel_name: The name for the logging channel
  124. :type channel_name: str
  125. """
  126. if channel_name is None:
  127. self.logger = logger.getChild(self.DEFAULT_CHANNEL_NAME)
  128. else:
  129. self.logger = logger.getChild(channel_name)
  130. def is_connected(self):
  131. """
  132. With this Method the connection status can be identified.
  133. :return: True, if a connection is established, otherwise False.
  134. :rtype: bool
  135. """
  136. return self.__connection__ is not None
  137. def receive(self, timeout=1, num=None):
  138. """
  139. This method returns received data.
  140. :param timeout: The timeout for receiving data (at least after the timeout the method returns data or None).
  141. :type timeout: float
  142. :param num: the number of bytes to receive (use None to get all available data).
  143. :type num: int
  144. :return: The received data.
  145. :rtype: bytes
  146. """
  147. rv = None
  148. if self.__connection__ is not None:
  149. tm = time.time()
  150. while (num is not None and len(self.__receive_buffer__) < num) or (num is None and len(self.__receive_buffer__) < 1):
  151. if self.__connection__ is None:
  152. return None
  153. if time.time() > tm + timeout:
  154. self.logger.warning('TIMEOUT (%ss): Not enough data in buffer. Requested %s and buffer size is %d.', repr(timeout), repr(num or 'all'), len(self.__receive_buffer__))
  155. return None
  156. time.sleep(0.05)
  157. if num is None:
  158. rv = self.__receive_buffer__
  159. self.__clean_receive_buffer__()
  160. else:
  161. rv = self.__receive_buffer__[:num]
  162. self.__receive_buffer__ = self.__receive_buffer__[num:]
  163. return rv
  164. def register_callback(self, callback):
  165. """
  166. This method stores the callback which is executed, if data is available. You need to execute :func:`receive` of this instance
  167. given as first argument.
  168. :param callback: The callback which will be executed, when data is available.
  169. :type callback:
  170. """
  171. self.__data_available_callback__ = callback
  172. def register_connect_callback(self, callback):
  173. """
  174. This method stores the callback which is executed, if a connection is established.
  175. :param callback: The callback which will be executed, when a connection is established.
  176. :type callback:
  177. """
  178. self.__connect_callback__ = callback
  179. def register_disconnect_callback(self, callback):
  180. """
  181. This method stores the callback which is executed, after the connection is lost.
  182. :param callback: The callback which will be executed, after the connection is lost.
  183. :type callback:
  184. """
  185. self.__disconnect_callback__ = callback
  186. def send(self, data, timeout=1, log_lvl=logging.INFO):
  187. """
  188. This method sends data via the initiated communication channel.
  189. :param data: The data to be send over the communication channel.
  190. :type data: bytes
  191. :param timeout: The timeout for sending data (e.g. time to establish new connection).
  192. :type timeout: float
  193. :param log_lvl: The log level to log outgoing TX-data
  194. :type log_lvl: int
  195. :return: True if data had been sent, otherwise False.
  196. :rtype: bool
  197. """
  198. tm = time.time()
  199. while time.time() - tm < timeout:
  200. if self.__connection__ is not None:
  201. try:
  202. self.__connection__.sendall(data)
  203. except BlockingIOError:
  204. time.sleep(.1) # try again till timeout exceeds
  205. except BrokenPipeError:
  206. self.logger.exception('Exception while sending data')
  207. self.__connection_lost__()
  208. return False
  209. else:
  210. self.logger.log(log_lvl, 'TX -> "%s"', stringtools.hexlify(data))
  211. return True
  212. else:
  213. time.sleep(.1) # give some time to establish the connection
  214. self.logger.warning('Cound NOT send -> "%s"', stringtools.hexlify(data))
  215. return False
  216. class tcp_server(tcp_base):
  217. """
  218. This class creates a tcp-server for transfering a serial stream of bytes (characters). See also parent :class:`tcp_base`.
  219. :param host: The host IP for the TCP socket functionality
  220. :type host: str
  221. :param port: The port for the TCP socket functionality
  222. :type port: int
  223. :param channel_name: The name for the logging channel
  224. :type channel_name: str
  225. .. note:: You need a :class:`tcp_client` to communicate with the server.
  226. **Example:**
  227. .. literalinclude:: tcp_socket/_examples_/tcp_socket__tcp_server.py
  228. .. literalinclude:: tcp_socket/_examples_/tcp_socket__tcp_server.log
  229. """
  230. def __connect__(self):
  231. if self.__socket__ is None:
  232. # Create a TCP/IP socket
  233. self.__socket__ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  234. # Bind the socket to the port
  235. server_address = (self.host, self.port)
  236. self.__socket__.bind(server_address)
  237. # Listen for incoming connections
  238. self.__socket__.listen(1)
  239. self.__socket__.settimeout(self.COM_TIMEOUT)
  240. self.__socket__.setblocking(False)
  241. if not self.__listening_message_displayed__:
  242. self.logger.info('Server listening to %s:%d', self.host, self.port)
  243. self.__listening_message_displayed__ = True
  244. try:
  245. self.__connection__, self.__client_address__ = self.__socket__.accept()
  246. except socket.error as e:
  247. if e.errno != 11:
  248. raise
  249. else:
  250. time.sleep(.05)
  251. else:
  252. self.logger.info('Connection established... (from %s)', self.client_address())
  253. self.__clean_receive_buffer__()
  254. self.__connection__.setblocking(False)
  255. if self.__connect_callback__ is not None:
  256. self.__connect_callback__()
  257. class tcp_client(tcp_base):
  258. """
  259. This class creates a tcp-client for transfering a serial stream of bytes (characters). See also parent :class:`tcp_base`.
  260. :param host: The host IP for the TCP socket functionality
  261. :type host: str
  262. :param port: The port for the TCP socket functionality
  263. :type port: int
  264. :param channel_name: The name for the logging channel
  265. :type channel_name: str
  266. .. note:: You need a running :class:`tcp_server` listening at the given IP and Port to be able to communicate.
  267. **Example:**
  268. .. literalinclude:: tcp_socket/_examples_/tcp_socket__tcp_client.py
  269. .. literalinclude:: tcp_socket/_examples_/tcp_socket__tcp_client.log
  270. """
  271. IS_CLIENT = True
  272. def __connect__(self):
  273. if self.__socket__ is None:
  274. # Create a TCP/IP socket
  275. self.__socket__ = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  276. self.__socket__.setblocking(False)
  277. # Connect the socket to the port where the server is listening
  278. try:
  279. self.__socket__.connect((self.host, self.port))
  280. except socket.error as e:
  281. if e.errno == 9:
  282. self.__socket__.close()
  283. elif e.errno != 115 and e.errno != 111 and e.errno != 114:
  284. raise
  285. else:
  286. self.__connection__ = None
  287. time.sleep(.05)
  288. else:
  289. self.logger.info('Connection to %s:%s established', self.host, self.port)
  290. self.__clean_receive_buffer__()
  291. self.__connection__ = self.__socket__
  292. if self.__connect_callback__ is not None:
  293. self.__connect_callback__()
  294. def __connection_lost__(self):
  295. self.__socket__ = None
  296. tcp_base.__connection_lost__(self)
  297. def reconnect(self):
  298. self.__connect__()
  299. class tcp_base_stp(tcp_base):
  300. """
  301. This is the base class for other classes in this module. See also parent :class:`tcp_base`.
  302. :param host: The host IP for the TCP socket functionality
  303. :type host: str
  304. :param port: The port for the TCP socket functionality
  305. :type port: int
  306. :param channel_name: The name for the logging channel
  307. :type channel_name: str
  308. .. note:: This class is not designed for direct usage.
  309. """
  310. def __init__(self, host, port, channel_name=None):
  311. tcp_base.__init__(self, host, port, channel_name=channel_name)
  312. self.__stp__ = stringtools.stp.stp()
  313. def __clean_receive_buffer__(self):
  314. self.logger.debug("Cleaning up receive-buffer")
  315. self.__receive_buffer__ = []
  316. def __receive_task__(self, queue_inst):
  317. if self.__connection__ is not None:
  318. try:
  319. data = self.__connection__.recv(self.RX_LENGTH)
  320. except socket.error as e:
  321. if e.errno == 104:
  322. self.__connection_lost__()
  323. elif e.errno != 11:
  324. raise
  325. else:
  326. time.sleep(.05)
  327. else:
  328. if len(data) > 0:
  329. self.logger.debug('RX <- "%s"', stringtools.hexlify(data))
  330. content = self.__stp__.process(data)
  331. for msg in content:
  332. self.logger.info('RX <- "%s"', stringtools.hexlify(msg))
  333. self.__receive_buffer__.append(msg)
  334. else:
  335. self.__connection_lost__()
  336. self.__call_data_available_callback__()
  337. else:
  338. self.__connect__()
  339. queue_inst.enqueue(5, self.__receive_task__)
  340. def receive(self, timeout=1):
  341. """
  342. This method returns one received messages via the initiated communication channel.
  343. :param timeout: The timeout for receiving data (at least after the timeout the method returns data or None).
  344. :type timeout: float
  345. :return: The received data.
  346. :rtype: bytes
  347. """
  348. try:
  349. return tcp_base.receive(self, timeout=timeout, num=1)[0]
  350. except TypeError:
  351. return None
  352. def send(self, data, timeout=1, log_lvl=logging.INFO):
  353. """
  354. This method sends one stp message via the initiated communication channel.
  355. :param data: The message to be send over the communication channel.
  356. :type data: bytes
  357. :param timeout: The timeout for sending data (e.g. time to establish new connection).
  358. :type timeout: float
  359. :param log_lvl: The log level to log outgoing TX-data
  360. :type log_lvl: int
  361. :return: True if data had been sent, otherwise False.
  362. :rtype: bool
  363. """
  364. if tcp_base.send(self, stringtools.stp.build_frame(data), timeout=timeout, log_lvl=logging.DEBUG):
  365. self.logger.log(log_lvl, 'TX -> "%s"', stringtools.hexlify(data))
  366. return True
  367. else:
  368. return False
  369. class tcp_server_stp(tcp_server, tcp_base_stp):
  370. """
  371. This class creates a tcp-server for transfering a message. The bytes will be packed on send and unpacked on receive. See also parents :class:`tcp_server` and :class:`tcp_base_stp`.
  372. See :mod:`stringtools.stp` for more information on packing and unpacking.
  373. :param host: The host IP for the TCP socket functionality
  374. :type host: str
  375. :param port: The port for the TCP socket functionality
  376. :type port: int
  377. :param channel_name: The name for the logging channel
  378. :type channel_name: str
  379. .. note:: You need a :class:`tcp_client_stp` to communicate with the server.
  380. **Example:**
  381. .. literalinclude:: tcp_socket/_examples_/tcp_socket__stp_server.py
  382. .. literalinclude:: tcp_socket/_examples_/tcp_socket__stp_server.log
  383. """
  384. pass
  385. class tcp_client_stp(tcp_client, tcp_base_stp):
  386. """
  387. This class creates a tcp-client for transfering a message. The bytes will be packed on send and unpacked on receive. See also parents :class:`tcp_client` and :class:`tcp_base_stp`.
  388. See :mod:`stringtools.stp` for more information on packing and unpacking.
  389. :param host: The host IP for the TCP socket functionality
  390. :type host: str
  391. :param port: The port for the TCP socket functionality
  392. :type port: int
  393. :param channel_name: The name for the logging channel
  394. :type channel_name: str
  395. .. note:: You need a running :class:`tcp_server_stp` listening at the given IP and Port to be able to communicate.
  396. **Example:**
  397. .. literalinclude:: tcp_socket/_examples_/tcp_socket__stp_client.py
  398. .. literalinclude:: tcp_socket/_examples_/tcp_socket__stp_client.log
  399. """
  400. pass