register.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from app import log
  2. from app.app_config import *
  3. import json
  4. import threading
  5. import traceback
  6. import sys
  7. """
  8. desc:
  9. 线程封装类,便于更好的捕获子线程跑出的异常
  10. """
  11. class runFunctionThread(threading.Thread):
  12. def __init__(self, funcName, *args):
  13. threading.Thread.__init__(self)
  14. self.args = args
  15. self.funcName = funcName
  16. self.exitcode = 0
  17. self.exception = None
  18. self.exc_traceback = ''
  19. def run(self): #Overwrite run() method, put what you want the thread do here
  20. try:
  21. self._run()
  22. except Exception as e:
  23. self.exitcode = 1 # 如果线程异常退出,将该标志位设置为1,正常退出为0
  24. self.exception = e
  25. self.exc_traceback = ''.join(traceback.format_exception(*sys.exc_info())) #在改成员变量中记录异常信息
  26. def _run(self):
  27. try:
  28. self.funcName(*(self.args))
  29. except Exception as e:
  30. raise e
  31. """
  32. desc:
  33. 用于mqtt指令到达时匹配相应的control函数
  34. """
  35. class Register(object):
  36. def __init__(self):
  37. self.func_dict = {}
  38. def action(self, action):
  39. def wrapper(func):
  40. self.func_dict.setdefault(action, func)
  41. return func
  42. return wrapper
  43. def recieve_run(self, client, userdata, message):
  44. try:
  45. data = json.loads(str(message.payload.decode("utf-8")))
  46. log.logger.info(data)
  47. except:
  48. log.logger.error("Recieve data is not json format:%s" % (str(message.payload.decode("utf-8"))))
  49. if data.get(ACTION_NAME) in self.func_dict:
  50. try:
  51. td = runFunctionThread(self.func_dict.get(data.get(ACTION_NAME)), data)
  52. td.start()
  53. td.join()
  54. if td.exitcode != 0:
  55. log.logger.error('Exception in ' + td.getName() + ' (catch by main)')
  56. log.logger.error(td.exc_traceback)
  57. except Exception as e:
  58. log.logger.error(td.exc_traceback)
  59. else:
  60. log.logger.error("Not support this action: %s" % (data.get(ACTION_NAME)))