gateway.py 6.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  1. import asyncio
  2. import datetime
  3. import sys
  4. import time
  5. import os
  6. import wmi
  7. from sanic import Sanic
  8. from sanic_cors import CORS
  9. from sanic import response
  10. # device import
  11. from event_storage import EventStorage
  12. from configuration import Configuration
  13. from utility import Utility
  14. from alarm import Alarm
  15. from historical_data_storage import HistoricalDataStorage
  16. from api_context import ApiContext
  17. from AES_crypt import decrypt
  18. from logging_config import LOGGING_CONFIG
  19. import logging.config
  20. # logging config
  21. logging.config.dictConfig(LOGGING_CONFIG)
  22. # handlers = LOGGING_CONFIG['handlers']
  23. # for handler in handlers:
  24. # item = handlers[handler]
  25. # if 'filename' in item:
  26. # filename = item['filename']
  27. # dirname = os.path.dirname(filename)
  28. # if not os.path.exists(dirname):
  29. # os.makedirs(dirname)
  30. # --------------------------
  31. gateway_storage = EventStorage()
  32. connector_config = gateway_storage.get_connector_config()
  33. Utility.start_connectors(connector_config)
  34. app = Sanic(__name__)
  35. # app.config.CORS_ORIGINS = "*"
  36. CORS(app)
  37. @app.route('/readReal', methods=['POST'])
  38. async def read_point_data(request):
  39. list = request.json['pointList']
  40. dict = gateway_storage.get_real_data(list)
  41. return response.json(dict)
  42. @app.route('/readHistorical', methods=['POST'])
  43. async def read_table_data(request):
  44. dict = request.json
  45. data_list = gateway_storage.get_historical_data(dict)
  46. data_json = Utility.data_encoder(data_list)
  47. return response.text(data_json)
  48. # 历史数据库分页查询接口--------------------------------------------\\
  49. @app.post('/getTotalNumber')
  50. async def get_total_number(request):
  51. dict = request.json
  52. data_list = gateway_storage.get_total_count_and_first_id(dict)
  53. return response.json(data_list)
  54. @app.post("/getItem")
  55. def get_one_page_content(request):
  56. dict = request.json
  57. data_list = gateway_storage.get_item_by_id_offset(dict)
  58. data_json = Utility.data_encoder(data_list)
  59. return response.text(data_json)
  60. # 历史数据导出接口--------------------------------------------\\
  61. @app.post('/quary')
  62. async def quary_table_data(request):
  63. dict = request.json
  64. res = gateway_storage.quary_table_data(dict)
  65. if not res:
  66. return response.text("查询参数错误")
  67. return response.json({"filename": res})
  68. @app.route("/download")
  69. async def downlod_file(request):
  70. filename = request.args.get("filename")
  71. if sys.platform == 'win32':
  72. filepath = './' + filename
  73. elif sys.platform == 'linux':
  74. filepath = filename
  75. return await response.file_stream(
  76. filepath,
  77. chunk_size=1024,
  78. filename=filename
  79. )
  80. @app.route('/readPointInfo', methods=['POST'])
  81. async def read_point_info(request):
  82. data_list = gateway_storage.get_point_info(None)
  83. return response.json(data_list)
  84. # @app.route('/readStatistics', methods=['POST'])
  85. # async def read_statistics_data(request):
  86. # list = request.json['pointList']
  87. # dict = gateway_storage.get_real_data(list)
  88. # return response.json(dict)
  89. #
  90. #
  91. # @app.route('/write', methods=['POST'])
  92. # async def write_data(request):
  93. # id = request.json["id"]
  94. # value = request.json["value"]
  95. # connector = request.json["device"]
  96. # connector.send_command("zz")
  97. @app.route('/api', methods=['POST'])
  98. async def read_statistics_data(request):
  99. if len(request.json) > 0:
  100. list = []
  101. for index in range(len(request.json)):
  102. api_object = request.json[index]['apiObject']
  103. parameter = request.json[index]['parameter']
  104. api = ApiContext()
  105. api.set_api_object(api_object)
  106. result = api.operation(parameter)
  107. list.append(result)
  108. return response.json(list)
  109. # def verify_cpu_code():
  110. # # 获取配置文件中CPU序列号
  111. # config_handle = Configuration()
  112. # config = config_handle.get_system_config()
  113. # cpu_code_from_config_file = config['code']
  114. # # 获取当前设备CPU序列号
  115. #
  116. #
  117. # # 判断是否匹配
  118. # if cpu_code == cpu_code_from_config_file:
  119. # return True
  120. # else:
  121. # return False
  122. @app.post('/verify')
  123. def verify_app(request):
  124. config = Configuration().get_config()
  125. for cpu in wmi.WMI().Win32_Processor():
  126. cpu_code = cpu.ProcessorId.strip()
  127. de_cpu_code = decrypt(config['activation_code'])
  128. if cpu_code == de_cpu_code:
  129. return response.json({'status': 'yes'})
  130. else:
  131. return response.json({'status': 'no'})
  132. @app.post('/activate')
  133. def acvivate(request):
  134. activate_code = request.json['code']
  135. for cpu in wmi.WMI().Win32_Processor():
  136. cpu_code = cpu.ProcessorId.strip()
  137. de_activate_code = decrypt(activate_code)
  138. if de_activate_code == cpu_code:
  139. config = Configuration()
  140. res = config.set_config(**{"activation_code": activate_code})
  141. if res:
  142. return response.json({'status': 'yes'})
  143. return response.json({'status': 'no'})
  144. # def overrun_alarm(alarms):
  145. # print('async overrun_alarm')
  146. # await asyncio.sleep(.1)
  147. # alarms.overrun_alarm()
  148. #
  149. #
  150. # async def displacement_alarm(app, alarms):
  151. # print('async displacement_alarm')
  152. # # await asyncio.sleep(.2)
  153. # alarms.displacement_alarm()
  154. async def notify_server_started_after_five_seconds():
  155. while True:
  156. await asyncio.sleep(10)
  157. if 'wxt536' not in Utility.available_connectors:
  158. break
  159. connector = Utility.available_connectors["wxt536"]
  160. data = "0XZRU\r\n"
  161. # 8:00:00-8:01:00 everyday
  162. a = datetime.datetime.now().strftime("%Y-%m-%d") + " %2d:00:00" % 8
  163. timeArray = time.strptime(a, "%Y-%m-%d %H:%M:%S")
  164. timeStampA = int(time.mktime(timeArray))
  165. timeStampB = timeStampA + 60
  166. if timeStampA <= int(time.time()) <= timeStampB:
  167. time.sleep(10)
  168. connector.send_command(data)
  169. if __name__ == "__main__":
  170. Alarm().start()
  171. HistoricalDataStorage().start()
  172. # 气象仪降雨量每日清零:一号打开,二号关闭,三号关闭
  173. app.add_task(notify_server_started_after_five_seconds())
  174. app.run(host="0.0.0.0", port=8000)