Python Library Socket Protocol
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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. """
  5. socket_protocol (Socket Protocol)
  6. =================================
  7. **Author:**
  8. * Dirk Alders <sudo-dirk@mount-mockery.de>
  9. **Description:**
  10. This Module supports point to point communication for client-server issues.
  11. **Submodules:**
  12. * :class:`socket_protocol.data_storage`
  13. * :class:`socket_protocol.pure_json_protocol`
  14. * :class:`socket_protocol.struct_json_protocol`
  15. **Unittest:**
  16. See also the :download:`unittest <socket_protocol/_testresults_/unittest.pdf>` documentation.
  17. **Module Documentation:**
  18. """
  19. __DEPENDENCIES__ = ['stringtools']
  20. import stringtools
  21. import binascii
  22. import hashlib
  23. import json
  24. import logging
  25. import os
  26. import struct
  27. import sys
  28. import time
  29. try:
  30. from config import APP_NAME as ROOT_LOGGER_NAME
  31. except ImportError:
  32. ROOT_LOGGER_NAME = 'root'
  33. logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__)
  34. __DESCRIPTION__ = """The Module {\\tt %s} is designed for point to point communication for client-server issues.
  35. For more Information read the sphinx documentation.""" % __name__.replace('_', '\_')
  36. """The Module Description"""
  37. __INTERPRETER__ = (2, 3)
  38. """The Tested Interpreter-Versions"""
  39. SID_AUTH_REQUEST = 0
  40. """SID for authentification request"""
  41. SID_AUTH_RESPONSE = 1
  42. """SID for authentification response"""
  43. DID_AUTH_SEED = 0
  44. """DID for authentification (seed)"""
  45. DID_AUTH_KEY = 1
  46. """DID for authentification (key)"""
  47. SID_CHANNEL_NAME_REQUEST = 8
  48. """SID for channel name exchange request """
  49. SID_CHANNEL_NAME_RESPONSE = 9
  50. """SID for channel name exchange response"""
  51. DID_CHANNEL_NAME = 0
  52. """DID for channel name """
  53. SID_READ_REQUEST = 10
  54. """SID for a read data request"""
  55. SID_READ_RESPONSE = 11
  56. """SID for read data response"""
  57. SID_WRITE_REQUEST = 20
  58. """SID for a write data request"""
  59. SID_WRITE_RESPONSE = 21
  60. """SID for a write data response"""
  61. SID_EXECUTE_REQUEST = 30
  62. """SID for a execute request"""
  63. SID_EXECUTE_RESPONSE = 31
  64. """SID for a execute response"""
  65. STATUS_OKAY = 0
  66. """Status for 'okay'"""
  67. STATUS_BUFFERING_UNHANDLED_REQUEST = 1
  68. """Status for 'unhandled request'"""
  69. STATUS_CALLBACK_ERROR = 2
  70. """Status for 'callback errors'"""
  71. STATUS_AUTH_REQUIRED = 3
  72. """Status for 'authentification is required'"""
  73. STATUS_SERVICE_OR_DATA_UNKNOWN = 4
  74. """Status for 'service or data unknown'"""
  75. STATUS_CHECKSUM_ERROR = 5
  76. """Status for 'checksum error'"""
  77. STATUS_OPERATION_NOT_PERMITTED = 6
  78. """Status for 'operation not permitted'"""
  79. AUTH_STATE_UNTRUSTED_CONNECTION = 0
  80. """Authentification Status for an 'Untrusted Connection'"""
  81. AUTH_STATE_SEED_REQUESTED = 1
  82. """Authentification Status for 'Seed was requested'"""
  83. AUTH_STATE_SEED_TRANSFERRED = 2
  84. """Authentification Status for 'Seed has been sent'"""
  85. AUTH_STATE_KEY_TRANSFERRED = 3
  86. """Authentification Status for 'Key has been sent'"""
  87. AUTH_STATE_TRUSTED_CONNECTION = 4
  88. """Authentification Status for a 'Trusted Connection'"""
  89. AUTH_STATE__NAMES = {AUTH_STATE_UNTRUSTED_CONNECTION: 'Untrusted Connection',
  90. AUTH_STATE_SEED_REQUESTED: 'Seed was requested',
  91. AUTH_STATE_SEED_TRANSFERRED: 'Seed has been sent',
  92. AUTH_STATE_KEY_TRANSFERRED: 'Key has been sent',
  93. AUTH_STATE_TRUSTED_CONNECTION: 'Trusted Connection'}
  94. """Authentification Status names for previous defined authentification states"""
  95. class RequestSidExistsError(Exception):
  96. pass
  97. class ResponseSidExistsError(Exception):
  98. pass
  99. class _callback_storage(dict):
  100. DEFAULT_CHANNEL_NAME = 'all_others'
  101. def __init__(self, channel_name, log_prefix):
  102. self.init_channel_name(channel_name)
  103. self.__log_prefix__ = log_prefix
  104. dict.__init__(self)
  105. def init_channel_name(self, channel_name):
  106. if channel_name is None:
  107. self.logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__ + '.' + self.DEFAULT_CHANNEL_NAME)
  108. else:
  109. self.logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__ + '.' + channel_name)
  110. def get(self, service_id, data_id):
  111. if dict.get(self, service_id, {}).get(data_id, None) is not None:
  112. return self[service_id][data_id]
  113. elif dict.get(self, service_id, {}).get(None, None) is not None:
  114. return self[service_id][None]
  115. elif dict.get(self, None, {}).get(data_id, None) is not None:
  116. return self[None][data_id]
  117. elif dict.get(self, None, {}).get(None, None) is not None:
  118. return self[None][None]
  119. else:
  120. return (None, None, None)
  121. def add(self, service_id, data_id, callback, *args, **kwargs):
  122. cb_data = self.get(service_id, data_id)
  123. if dict.get(self, service_id, {}).get(data_id, None) is not None:
  124. if callback is None:
  125. self.logger.warning("%s Deleting existing callback %s for service_id (%s) and data_id (%s)!", self.__log_prefix__(), repr(cb_data[0].__name__), repr(service_id), repr(data_id))
  126. del(self[service_id][data_id])
  127. return
  128. else:
  129. self.logger.warning("%s Overwriting existing callback %s for service_id (%s) and data_id (%s) to %s!", self.__log_prefix__(), repr(cb_data[0].__name__), repr(service_id), repr(data_id), repr(callback.__name__))
  130. else:
  131. self.logger.debug("%s Adding callback %s for SID=%s and DID=%s", self.__log_prefix__(), repr(callback.__name__), repr(service_id), repr(data_id))
  132. if service_id not in self:
  133. self[service_id] = {}
  134. self[service_id][data_id] = (callback, args, kwargs)
  135. class data_storage(dict):
  136. """
  137. This is a storage object for socket_protocol messages.
  138. :param status: The message status.
  139. :type status: int
  140. :param service_id: The Service-ID.
  141. :type service_id: int
  142. :param data_id: The Data-ID.
  143. :type data_id: int
  144. :param data: The transfered data.
  145. :type data: any
  146. """
  147. KEY_STATUS = 'status'
  148. KEY_SERVICE_ID = 'service_id'
  149. KEY_DATA_ID = 'data_id'
  150. KEY_DATA = 'data'
  151. ALL_KEYS = [KEY_DATA, KEY_DATA_ID, KEY_SERVICE_ID, KEY_STATUS]
  152. def __init__(self, *args, **kwargs):
  153. dict.__init__(self, *args, **kwargs)
  154. for key in self.ALL_KEYS:
  155. if key not in self:
  156. self[key] = None
  157. def get_status(self, default=None):
  158. """
  159. This Method returns the message status.
  160. :param default: The default value, if no data is available.
  161. """
  162. return self.get(self.KEY_STATUS, default)
  163. def get_service_id(self, default=None):
  164. """
  165. This Method returns the message Service-ID.
  166. :param default: The default value, if no data is available.
  167. """
  168. return self.get(self.KEY_SERVICE_ID, default)
  169. def get_data_id(self, default=None):
  170. """
  171. This Method returns the message Data-ID.
  172. :param default: The default value, if no data is available.
  173. """
  174. return self.get(self.KEY_DATA_ID, default)
  175. def get_data(self, default=None):
  176. """
  177. This Method returns the message data.
  178. :param default: The default value, if no data is available.
  179. """
  180. return self.get(self.KEY_DATA, default)
  181. class pure_json_protocol(object):
  182. """
  183. This `class` supports to transfer a message and it's data.
  184. :param comm_instance: A communication instance.
  185. :type comm_instance: instance
  186. :param secret: An optinal secret (e.g. created by ``binascii.hexlify(os.urandom(24))``).
  187. :type secret: str
  188. :param auto_auth: An optional parameter to enable (True) automatic authentification, otherwise you need to do it manually, if needed.
  189. :type auto_auth: bool
  190. :param channel_name: An optional parameter to set a channel name for logging of the communication.
  191. :type channel_name: str
  192. .. hint::
  193. * The Service-ID is designed to identify the type of the communication (e.g. :const:`READ_REQUEST`, :const:`WRITE_REQUEST`, :const:`READ_RESPONSE`, :const:`WRITE_RESPONSE`, ...)
  194. * The Data-ID is designed to identify the requests / responses using the same Service_ID.
  195. .. note:: The :class:`comm_instance` needs to have at least the following interface:
  196. * A Method :func:`comm_instance.init_channel_name` to set the channel name.
  197. * A Constant :const:`comm_instance.IS_CLIENT` to identify that the :class:`comm_instance` is a client (True) or a server (False).
  198. * A Method :func:`comm_instance.is_connected` to identify if the instance is connected (True) or not (False).
  199. * A Method :func:`comm_instance.reconnect` to initiate a reconnect.
  200. * A Method :func:`comm_instance.register_callback` to register a data available callback.
  201. * A Method :func:`comm_instance.register_connect_callback` to register a connect callback.
  202. * A Method :func:`comm_instance.register_disconnect_callback` to register a disconnect callback.
  203. * A Method :func:`comm_instance.send` to send data via the :class:`comm_instance`.
  204. .. note:: The parameter :const:`auto_auth` is only relevant, if a secret is given and the :class:`comm_instance` is a client. The authentification is initiated directly after the connection is established.
  205. .. note:: The :const:`channel_name`-exchange will be initiated by the client directly after the the connection is established.
  206. * If a channel_name is given at both communication sides and they are different, the client name is taken over and the server will log a warning message.
  207. """
  208. DEFAULT_CHANNEL_NAME = 'all_others'
  209. def __init__(self, comm_instance, secret=None, auto_auth=False, channel_name=None):
  210. self.__comm_inst__ = comm_instance
  211. self.__secret__ = secret
  212. self.__auto_auth__ = auto_auth
  213. #
  214. self.__auth_whitelist__ = {}
  215. self.__sid_response_dict__ = {}
  216. self.__sid_name_dict__ = {}
  217. self.__did_name_dict__ = {}
  218. #
  219. self.__status_name_dict = {}
  220. self.add_status(STATUS_OKAY, 'okay')
  221. self.add_status(STATUS_BUFFERING_UNHANDLED_REQUEST, 'no callback for service, data buffered.')
  222. self.add_status(STATUS_CALLBACK_ERROR, 'callback error.')
  223. self.add_status(STATUS_AUTH_REQUIRED, 'authentification required')
  224. self.add_status(STATUS_SERVICE_OR_DATA_UNKNOWN, 'service or data unknown')
  225. self.add_status(STATUS_CHECKSUM_ERROR, 'checksum error')
  226. self.add_status(STATUS_OPERATION_NOT_PERMITTED, 'operation not permitted')
  227. #
  228. self.__callbacks__ = _callback_storage(channel_name, self.__log_prefix__)
  229. self.__init_channel_name__(channel_name)
  230. #
  231. self.__clean_receive_buffer__()
  232. self.add_service(SID_AUTH_REQUEST, SID_AUTH_RESPONSE, 'authentification request', 'authentification response')
  233. self.add_data((SID_AUTH_REQUEST, SID_AUTH_RESPONSE), DID_AUTH_SEED, 'seed')
  234. self.add_data(SID_AUTH_REQUEST, DID_AUTH_KEY, 'key')
  235. self.add_data(SID_AUTH_RESPONSE, DID_AUTH_KEY, 'key')
  236. self.add_msg_to_auth_whitelist_(SID_AUTH_REQUEST, DID_AUTH_SEED)
  237. self.add_msg_to_auth_whitelist_(SID_AUTH_RESPONSE, DID_AUTH_SEED)
  238. self.add_msg_to_auth_whitelist_(SID_AUTH_REQUEST, DID_AUTH_KEY)
  239. self.add_msg_to_auth_whitelist_(SID_AUTH_RESPONSE, DID_AUTH_KEY)
  240. self.__callbacks__.add(SID_AUTH_REQUEST, DID_AUTH_SEED, self.__authentificate_create_seed__)
  241. self.__callbacks__.add(SID_AUTH_RESPONSE, DID_AUTH_SEED, self.__authentificate_create_key__)
  242. self.__callbacks__.add(SID_AUTH_REQUEST, DID_AUTH_KEY, self.__authentificate_check_key__)
  243. self.__callbacks__.add(SID_AUTH_RESPONSE, DID_AUTH_KEY, self.__authentificate_process_feedback__)
  244. self.__authentification_state_reset__()
  245. self.add_service(SID_CHANNEL_NAME_REQUEST, SID_CHANNEL_NAME_RESPONSE, 'channel name request', 'channel name response')
  246. self.add_data((SID_CHANNEL_NAME_REQUEST, SID_CHANNEL_NAME_RESPONSE), DID_CHANNEL_NAME, 'name')
  247. self.add_msg_to_auth_whitelist_(SID_CHANNEL_NAME_REQUEST, DID_CHANNEL_NAME)
  248. self.add_msg_to_auth_whitelist_(SID_CHANNEL_NAME_RESPONSE, DID_CHANNEL_NAME)
  249. self.__callbacks__.add(SID_CHANNEL_NAME_REQUEST, DID_CHANNEL_NAME, self.__channel_name_request__)
  250. self.__callbacks__.add(SID_CHANNEL_NAME_RESPONSE, DID_CHANNEL_NAME, self.__channel_name_response__)
  251. self.add_service(SID_READ_REQUEST, SID_READ_RESPONSE, 'read data request', 'read data response')
  252. self.add_service(SID_WRITE_REQUEST, SID_WRITE_RESPONSE, 'write data request', 'write data response')
  253. self.add_service(SID_EXECUTE_REQUEST, SID_EXECUTE_RESPONSE, 'execute request', 'execute response')
  254. self.__seed__ = None
  255. self.__comm_inst__.register_callback(self.__data_available_callback__)
  256. self.__comm_inst__.register_connect_callback(self.__connection_established__)
  257. self.__comm_inst__.register_disconnect_callback(self.__authentification_state_reset__)
  258. logger.info('%s Initialisation finished.', self.__log_prefix__())
  259. def __analyse_frame__(self, frame):
  260. if sys.version_info >= (3, 0):
  261. return data_storage(json.loads(frame[:-4].decode('utf-8')))
  262. else:
  263. return data_storage(json.loads(frame[:-4]))
  264. def __authentificate_check_key__(self, msg):
  265. key = msg.get_data()
  266. if key == self.__authentificate_salt_and_hash__(self.__seed__):
  267. self.__authentification_state__ = AUTH_STATE_TRUSTED_CONNECTION
  268. return STATUS_OKAY, True
  269. else:
  270. self.__authentification_state__ = AUTH_STATE_UNTRUSTED_CONNECTION
  271. return STATUS_OKAY, False
  272. def __authentificate_create_key__(self, msg):
  273. self.__authentification_state__ = AUTH_STATE_KEY_TRANSFERRED
  274. seed = msg.get_data()
  275. key = self.__authentificate_salt_and_hash__(seed)
  276. self.send(SID_AUTH_REQUEST, DID_AUTH_KEY, key)
  277. def __authentificate_create_seed__(self, msg):
  278. self.__authentification_state__ = AUTH_STATE_SEED_TRANSFERRED
  279. if sys.version_info >= (3, 0):
  280. self.__seed__ = binascii.hexlify(os.urandom(32)).decode('utf-8')
  281. else:
  282. self.__seed__ = binascii.hexlify(os.urandom(32))
  283. return STATUS_OKAY, self.__seed__
  284. def __authentificate_process_feedback__(self, msg):
  285. feedback = msg.get_data()
  286. if feedback:
  287. self.__authentification_state__ = AUTH_STATE_TRUSTED_CONNECTION
  288. self.logger.info("%s Got positive authentification feedback", self.__log_prefix__())
  289. else:
  290. self.__authentification_state__ = AUTH_STATE_UNTRUSTED_CONNECTION
  291. self.logger.warning("%s Got negative authentification feedback", self.__log_prefix__())
  292. return STATUS_OKAY, None
  293. def __authentificate_salt_and_hash__(self, seed):
  294. if sys.version_info >= (3, 0):
  295. return hashlib.sha512(bytes(seed, 'utf-8') + self.__secret__).hexdigest()
  296. else:
  297. return hashlib.sha512(seed.encode('utf-8') + self.__secret__.encode('utf-8')).hexdigest()
  298. def __authentification_state_reset__(self):
  299. self.logger.info("%s Resetting authentification state to AUTH_STATE_UNTRUSTED_CONNECTION", self.__log_prefix__())
  300. self.__authentification_state__ = AUTH_STATE_UNTRUSTED_CONNECTION
  301. def __authentification_required__(self, service_id, data_id):
  302. return data_id not in self.__auth_whitelist__.get(service_id, [])
  303. def __buffer_received_data__(self, msg):
  304. if not msg.get_service_id() in self.__msg_buffer__:
  305. self.__msg_buffer__[msg.get_service_id()] = {}
  306. if not msg.get_data_id() in self.__msg_buffer__[msg.get_service_id()]:
  307. self.__msg_buffer__[msg.get_service_id()][msg.get_data_id()] = []
  308. self.__msg_buffer__[msg.get_service_id()][msg.get_data_id()].append(msg)
  309. self.logger.debug("%s Message data is stored in buffer and is now ready to be retrieved by receive method", self.__log_prefix__())
  310. def __build_frame__(self, service_id, data_id, data, status=STATUS_OKAY):
  311. data_frame = json.dumps(self.__mk_msg__(status, service_id, data_id, data))
  312. if sys.version_info >= (3, 0):
  313. data_frame = bytes(data_frame, 'utf-8')
  314. checksum = self.__calc_chksum__(data_frame)
  315. return data_frame + checksum
  316. def __calc_chksum__(self, raw_data):
  317. return struct.pack('>I', binascii.crc32(raw_data) & 0xffffffff)
  318. @property
  319. def __channel_name__(self):
  320. cn = self.logger.name.split('.')[-1]
  321. if cn != self.DEFAULT_CHANNEL_NAME:
  322. return cn
  323. def __channel_name_response__(self, msg):
  324. data = msg.get_data()
  325. if self.__channel_name__ is None and data is not None:
  326. self.__init_channel_name__(data)
  327. self.logger.info('%s channel name is now %s', self.__log_prefix__(), repr(self.__channel_name__))
  328. return STATUS_OKAY, None
  329. def __channel_name_request__(self, msg):
  330. data = msg.get_data()
  331. if data is None:
  332. return STATUS_OKAY, self.__channel_name__
  333. else:
  334. prev_channel_name = self.__channel_name__
  335. self.__init_channel_name__(data)
  336. if prev_channel_name is not None and prev_channel_name != data:
  337. self.logger.warning('%s overwriting user defined channel name from %s to %s', self.__log_prefix__(), repr(prev_channel_name), repr(data))
  338. elif prev_channel_name is None:
  339. self.logger.info('%s channel name is now %s', self.__log_prefix__(), repr(self.__channel_name__))
  340. return STATUS_OKAY, None
  341. def __check_frame_checksum__(self, frame):
  342. return self.__calc_chksum__(frame[:-4]) == frame[-4:]
  343. def __clean_receive_buffer__(self):
  344. self.logger.debug("%s Cleaning up receive-buffer", self.__log_prefix__())
  345. self.__msg_buffer__ = {}
  346. def __connection_established__(self):
  347. self.__clean_receive_buffer__()
  348. if self.__comm_inst__.IS_CLIENT:
  349. self.send(SID_CHANNEL_NAME_REQUEST, 0, self.__channel_name__)
  350. if self.__auto_auth__ and self.__comm_inst__.IS_CLIENT and self.__secret__ is not None:
  351. self.authentificate()
  352. def __data_available_callback__(self, comm_inst):
  353. frame = comm_inst.receive()
  354. msg = self.__analyse_frame__(frame)
  355. if not self.__check_frame_checksum__(frame):
  356. # Wrong Checksum
  357. self.logger.warning("%s RX <- Received message has a wrong checksum. Message will be ignored.", self.__log_prefix__())
  358. return # No response needed
  359. elif not self.check_authentification_state() and self.__authentification_required__(msg.get_service_id(), msg.get_data_id()):
  360. # Authentification required
  361. if msg.get_service_id() in self.__sid_response_dict__.keys():
  362. self.logger.warning("%s RX <- Authentification is required. Just sending negative response.", self.__log_prefix__())
  363. status = STATUS_AUTH_REQUIRED
  364. data = None
  365. else:
  366. self.logger.warning("%s RX <- Authentification is required. Message will be ignored.", self.__log_prefix__())
  367. return # No response needed
  368. else:
  369. # Valid message
  370. self.logger.info(
  371. '%s RX <- %s, %s, data: "%s"',
  372. self.__log_prefix__(),
  373. self.__get_message_name__(msg.get_service_id(), msg.get_data_id()),
  374. self.__get_status_name__(msg.get_status()),
  375. repr(msg.get_data())
  376. )
  377. if msg.get_status() not in [STATUS_OKAY]:
  378. self.logger.warning("%s RX <- Message has a peculiar status: %s", self.__log_prefix__(), self.__get_status_name__(msg.get_status()))
  379. callback, args, kwargs = self.__callbacks__.get(msg.get_service_id(), msg.get_data_id())
  380. if msg.get_service_id() in self.__sid_response_dict__.keys():
  381. #
  382. # REQUEST RECEIVED
  383. #
  384. if callback is None:
  385. self.logger.warning("%s RX <- Message with no registered callback. Sending negative response.", self.__log_prefix__())
  386. status = STATUS_BUFFERING_UNHANDLED_REQUEST
  387. data = None
  388. else:
  389. try:
  390. self.logger.debug("%s RX <- Executing callback %s to process received data", self.__log_prefix__(), callback.__name__)
  391. status, data = callback(msg, *args, **kwargs)
  392. except Exception:
  393. logger.error('{lp} RX <- Exception raised. Check callback {callback_name} and it\'s return values for service_id {service_id} and data_id {data_id}'.format(lp=self.__log_prefix__(), callback_name=callback.__name__, service_id=repr(msg.get_service_id()), data_id=repr(msg.get_data_id())))
  394. status = STATUS_CALLBACK_ERROR
  395. data = None
  396. else:
  397. #
  398. # RESPONSE RECEIVED
  399. #
  400. if callback is None:
  401. self.__buffer_received_data__(msg)
  402. else:
  403. self.logger.debug("%s Executing callback %s to process received data", self.__log_prefix__(), callback.__name__)
  404. callback(msg, *args, **kwargs)
  405. return # No response needed
  406. self.send(self.__sid_response_dict__[msg.get_service_id()], msg.get_data_id(), data, status=status)
  407. def __get_message_name__(self, service_id, data_id):
  408. return 'service: %s, data_id: %s' % (
  409. self.__sid_name_dict__.get(service_id, repr(service_id)),
  410. self.__did_name_dict__.get(service_id, {}).get(data_id, repr(data_id)),
  411. )
  412. def __get_status_name__(self, status):
  413. return 'status: %s' % (self.__status_name_dict.get(status, 'unknown status: %s' % repr(status)))
  414. def __init_channel_name__(self, channel_name):
  415. self.__comm_inst__.init_channel_name(channel_name)
  416. self.__callbacks__.init_channel_name(channel_name)
  417. if channel_name is None:
  418. self.logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__ + '.' + self.DEFAULT_CHANNEL_NAME)
  419. else:
  420. self.logger = logging.getLogger(ROOT_LOGGER_NAME).getChild(__name__ + '.' + channel_name)
  421. def __log_prefix__(self):
  422. return 'SP client:' if self.__comm_inst__.IS_CLIENT else 'SP server:'
  423. def __mk_msg__(self, status, service_id, data_id, data):
  424. return data_storage({data_storage.KEY_DATA_ID: data_id, data_storage.KEY_SERVICE_ID: service_id, data_storage.KEY_STATUS: status, data_storage.KEY_DATA: data})
  425. def add_data(self, service_id, data_id, name):
  426. """
  427. Method to add a name for a specific message.
  428. :param service_id: The Service-ID of the message. See class definitions starting with ``SID_``.
  429. :type service_id: int or list of ints
  430. :param data_id: The Data-ID of the message.
  431. :type data_id: int
  432. :param name: The Name for the transfered message.
  433. :type name: str
  434. """
  435. try:
  436. iter(service_id)
  437. except Exception:
  438. service_id = (service_id, )
  439. for sid in service_id:
  440. if sid not in self.__did_name_dict__:
  441. self.__did_name_dict__[sid] = {}
  442. self.__did_name_dict__[sid][data_id] = name
  443. def add_msg_to_auth_whitelist_(self, service_id, data_id):
  444. """
  445. Method to add a specific message to the list, where no authentification is required.
  446. :param service_id: The Service-ID of the message. See class definitions starting with ``SID_``.
  447. :type service_id: int
  448. :param data_id: The Data-ID of the message.
  449. :type data_id: int
  450. """
  451. if service_id not in self.__auth_whitelist__:
  452. self.__auth_whitelist__[service_id] = []
  453. self.__auth_whitelist__[service_id].append(data_id)
  454. logger.debug('%s Adding Message (%s) to the authentification whitelist', self.__log_prefix__(), self.__get_message_name__(service_id, data_id))
  455. def add_service(self, req_sid, resp_sid, req_name=None, resp_name=None):
  456. """
  457. Method to add a Service defined by Request- and Response Serivce-ID.
  458. :param req_sid: The Request Service-ID.
  459. :type req_sid: int
  460. :param resp_sid: The Response Service-ID.
  461. :type resp_sid: int
  462. """
  463. if req_sid in self.__sid_response_dict__:
  464. logger.error('%s Service with Request-SID=%d and Response-SID=%d not added, because request SID is already registered', self.__log_prefix__(), req_sid, resp_sid)
  465. raise RequestSidExistsError("Request for this Service is already registered")
  466. elif resp_sid in self.__sid_response_dict__.values():
  467. logger.error('%s Service with Request-SID=%d and Response-SID=%d not added, because response SID is already registered', self.__log_prefix__(), req_sid, resp_sid)
  468. raise ResponseSidExistsError("Response for this Service is already registered")
  469. else:
  470. self.__sid_response_dict__[req_sid] = resp_sid
  471. if req_name is not None:
  472. self.__sid_name_dict__[req_sid] = req_name
  473. if resp_name is not None:
  474. self.__sid_name_dict__[resp_sid] = resp_name
  475. logger.debug('%s Adding Service with Request=%s and Response=%s', self.__log_prefix__(), req_name or repr(req_sid), resp_name or repr(resp_sid))
  476. def add_status(self, status, name):
  477. """
  478. Method to add a name for a status.
  479. :param status: The Status. See class definitions starting with ``STATUS_``.
  480. :type status: int
  481. :param name: The Name for the Status.
  482. :type name: str
  483. """
  484. self.__status_name_dict[status] = name
  485. def authentificate(self, timeout=2):
  486. """
  487. This method authetificates the client at the server.
  488. :param timeout: The timeout for the authentification (requesting seed, sending key and getting authentification_feedback).
  489. :type timeout: float
  490. :returns: True, if authentification was successfull; False, if not.
  491. :rtype: bool
  492. .. note:: An authentification will only processed, if a secret had been given on initialisation.
  493. .. note:: Client and Server needs to use the same secret.
  494. """
  495. if self.__secret__ is not None:
  496. self.__authentification_state__ = AUTH_STATE_SEED_REQUESTED
  497. self.send(SID_AUTH_REQUEST, DID_AUTH_SEED, None)
  498. cnt = 0
  499. while cnt < timeout * 10:
  500. time.sleep(0.1)
  501. if self.__authentification_state__ == AUTH_STATE_TRUSTED_CONNECTION:
  502. return True
  503. elif self.__authentification_state__ == AUTH_STATE_UNTRUSTED_CONNECTION:
  504. break
  505. cnt += 1
  506. return False
  507. def check_authentification_state(self):
  508. """
  509. This Method return the Authitification State as boolean value.
  510. :return: True, if authentification state is okay, otherwise False
  511. :rtype: bool
  512. """
  513. return self.__secret__ is None or self.__authentification_state__ == AUTH_STATE_TRUSTED_CONNECTION
  514. def connection_established(self):
  515. """
  516. This Method returns the Connection state including authentification as a boolean value.
  517. :return: True, if the connection is established (incl. authentification, if a secret has been given)
  518. :rtype: bool
  519. """
  520. return self.is_connected() and (self.__secret__ is None or self.check_authentification_state())
  521. def is_connected(self):
  522. """
  523. This Methods returns Connection state of the Communication Instance :func:`comm_instance.is_connected`.
  524. :return: True if the :class:`comm_instance` is connected, otherwise False..
  525. :rtype: bool
  526. """
  527. return self.__comm_inst__.is_connected()
  528. def receive(self, service_id, data_id, timeout=1):
  529. """
  530. This Method returns a message object for a defined message or None, if this message is not available after the given timout.
  531. :param service_id: The Service-ID for the message. See class definitions starting with ``SID_``.
  532. :type service_id: int
  533. :param data_id: The Data-ID for the message.
  534. :type data_id: int
  535. :param timeout: The timeout for receiving.
  536. :type timeout: float
  537. :returns: The received data storage object or None, if no data was received.
  538. :rtype: data_storage
  539. """
  540. data = None
  541. cnt = 0
  542. while data is None and cnt < timeout * 10:
  543. try:
  544. data = self.__msg_buffer__.get(service_id, {}).get(data_id, []).pop(0)
  545. except IndexError:
  546. data = None
  547. cnt += 1
  548. time.sleep(0.1)
  549. if data is None and cnt >= timeout * 10:
  550. self.logger.warning('%s TIMEOUT (%ss): Requested data (service_id: %s; data_id: %s) not in buffer.', self.__log_prefix__(), repr(timeout), repr(service_id), repr(data_id))
  551. return data
  552. def reconnect(self):
  553. """
  554. This methods initiates a reconnect by calling :func:`comm_instance.reconnect`.
  555. """
  556. return self.__comm_inst__.reconnect()
  557. def register_callback(self, service_id, data_id, callback, *args, **kwargs):
  558. """
  559. This method registers a callback for the given parameters. Giving ``None`` means, that all Service-IDs or all Data-IDs are used.
  560. If a message hitting these parameters has been received, the callback will be executed.
  561. :param service_id: The Service-ID for the message. See class definitions starting with ``SID_``.
  562. :type service_id: int
  563. :param data_id: The Data-ID for the message.
  564. :type data_id: int
  565. .. note:: The :func:`callback` is priorised in the following order:
  566. * Callbacks with defined Service-ID and Data-ID.
  567. * Callbacks with a defined Service-ID and all Data-IDs.
  568. * Callbacks with a defined Data-ID and all Service-IDs.
  569. * Unspecific Callbacks.
  570. .. note:: The :func:`callback` is executed with these arguments:
  571. **Parameters given at the callback call:**
  572. * The first Arguments is the received message as :class:`data_storage` object.
  573. * Further arguments given at registration.
  574. * Further keyword arguments given at registration.
  575. **Return value of the callback:**
  576. If the Callback is a Request Callback for a registered Service, the return value has to be a tuple or list with
  577. * :const:`response_status`: The response status (see class definitions starting with :const:`STA_*`.
  578. * :const:`response_data`: A JSON iterable object to be used as data for the response.
  579. .. note:: Only registered services will respond via the callbacks return values with the same data_id.
  580. """
  581. self.__callbacks__.add(service_id, data_id, callback, *args, **kwargs)
  582. def send(self, service_id, data_id, data, status=STATUS_OKAY, timeout=2):
  583. """
  584. This methods sends out a message with the given content.
  585. :param service_id: The Service-ID for the message. See class definitions starting with ``SERVICE_``.
  586. :type service_id: int
  587. :param data_id: The Data-ID for the message.
  588. :type data_id: int
  589. :param data: The data to be transfered. The data needs to be json compatible.
  590. :type data: str
  591. :param status: The Status for the message. All requests should have ``STATUS_OKAY``.
  592. :type status: int
  593. :param timeout: The timeout for sending data (e.g. time to establish new connection).
  594. :type timeout: float
  595. :return: True if data had been sent, otherwise False.
  596. :rtype: bool
  597. """
  598. if (self.check_authentification_state() or not self.__authentification_required__(service_id, data_id)) or (service_id in self.__sid_response_dict__.values() and status == STATUS_AUTH_REQUIRED and data is None):
  599. self.logger.info(
  600. '%s TX <- %s, %s, data: "%s"',
  601. self.__log_prefix__(),
  602. self.__get_message_name__(service_id, data_id),
  603. self.__get_status_name__(status),
  604. repr(data)
  605. )
  606. return self.__comm_inst__.send(self.__build_frame__(service_id, data_id, data, status), timeout=timeout, log_lvl=logging.DEBUG)
  607. else:
  608. # Authentification required
  609. self.logger.warning("%s TX -> Authentification is required. Message %s, %s, data: %s will be ignored.", self.__log_prefix__(), self.__get_message_name__(service_id, data_id), self.__get_status_name__(status), repr(data))
  610. return False
  611. class struct_json_protocol(pure_json_protocol):
  612. """
  613. This Class has the same functionality like :class:`pure_json_protocol`. The message length is less than for :class:`pure_json_protocol`, but the functionality and compatibility is reduced.
  614. .. note::
  615. This class is depreceated and here for compatibility reasons (to support old clients or servers). Usage of :class:`pure_json_protocol` is recommended.
  616. """
  617. def __init__(self, *args, **kwargs):
  618. pure_json_protocol.__init__(self, *args, **kwargs)
  619. def __analyse_frame__(self, frame):
  620. status, service_id, data_id = struct.unpack('>III', frame[0:12])
  621. if sys.version_info >= (3, 0):
  622. data = json.loads(frame[12:-1].decode('utf-8'))
  623. else:
  624. data = json.loads(frame[12:-1])
  625. return self.__mk_msg__(status, service_id, data_id, data)
  626. def __build_frame__(self, service_id, data_id, data, status=STATUS_OKAY):
  627. frame = struct.pack('>III', status, service_id, data_id)
  628. if sys.version_info >= (3, 0):
  629. frame += bytes(json.dumps(data), 'utf-8')
  630. frame += self.__calc_chksum__(frame)
  631. else:
  632. frame += json.dumps(data)
  633. frame += self.__calc_chksum__(frame)
  634. return frame
  635. def __calc_chksum__(self, raw_data):
  636. chksum = 0
  637. for b in raw_data:
  638. if sys.version_info >= (3, 0):
  639. chksum ^= b
  640. else:
  641. chksum ^= ord(b)
  642. if sys.version_info >= (3, 0):
  643. return bytes([chksum])
  644. else:
  645. return chr(chksum)
  646. def __check_frame_checksum__(self, frame):
  647. return self.__calc_chksum__(frame[:-1]) == frame[-1:]