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.

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