gateway.py 6.1 KB

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