gateway.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. #!/usr/bin/env python
  2. # -*- coding:utf-8 -*-
  3. """
  4. @desc: 连接器:可读,可写
  5. """
  6. import time
  7. import threading
  8. from sanic import Sanic
  9. from sanic_cors import CORS, cross_origin
  10. from sanic import response
  11. from event_storage import EventStorage
  12. from utility import Utility
  13. from historical_data_storage import HistoricalDataStorage
  14. from feeding_statistics import FeedingStatistics
  15. from auto_feeding import AutoFeeding
  16. from auto_charge import AutoCharge
  17. from alarm import Alarm
  18. from api_context import ApiContext
  19. from update_maintenance_info import UpdateMaintenanceInfo
  20. from auto_switch_device import AutoSwitchDevice
  21. from alarm_buzzer import AlarmBuzzer
  22. from alarm_record import AlarmRecord
  23. from auto_switch_juyudeng import AutoSwitchJuyudeng
  24. from auto_switch_yuntaideng import AutoSwitchYuntaideng
  25. from auto_profile_1501 import AutoProfile1501
  26. from reset_remote_control import ResetRemoteControl
  27. from get_laliji_param import GetLalijiParam
  28. from datetime import datetime
  29. app = Sanic(__name__)
  30. CORS(app)
  31. gateway_storage = EventStorage()
  32. connector_config = gateway_storage.get_connector_config(read_write=0)
  33. Utility.start_connectors(connector_config)
  34. @app.route('/readRealText', methods=['POST'])
  35. async def read_point_data_text(request):
  36. list = request.json['pointList']
  37. dict = gateway_storage.get_real_data(list)
  38. point_list = gateway_storage.get_point_info(list)
  39. data_list = {}
  40. for info in point_list:
  41. data_list[info['io_point_name']] = str(dict["c"+str(info['serial_number'])]) + " " +str(info['unit'])
  42. return response.json(data_list)
  43. @app.route('/readReal', methods=['POST'])
  44. async def read_point_data(request):
  45. list = request.json['pointList']
  46. dict = gateway_storage.get_real_data(list)
  47. '''
  48. data_list = gateway_storage.get_point_info(list)
  49. for info in data_list:
  50. info['value'] = dict["c"+str(info['serial_number'])]
  51. '''
  52. return response.json(dict)
  53. @app.route('/api', methods=['POST'])
  54. async def read_statistics_data(request):
  55. if len(request.json) > 0:
  56. list = []
  57. for index in range(len(request.json)):
  58. api_object = request.json[index]['apiObject']
  59. parameter = request.json[index]['parameter']
  60. api = ApiContext()
  61. api.set_api_object(api_object)
  62. result = api.operation(parameter)
  63. list.append(result)
  64. data_json = Utility.data_encoder(list)
  65. return response.text(data_json)
  66. @app.route('/write',methods=['POST'])
  67. async def write_data(request):
  68. t1 = time.time()
  69. station_name = request.json["station_name"]
  70. command = request.json["command"]
  71. try:
  72. result = Utility.available_connectors[station_name].send_command(command)
  73. return response.json({'message': result})
  74. except Exception as e:
  75. print(station_name+"write[ERROR]:" + str(e))
  76. return response.json({'message': result})
  77. @app.route('/modbus/fdj', methods=['POST'])
  78. async def write_data(request):
  79. """
  80. 远程控制发电机启停
  81. @param request: {"device":"1", "deviceStatus":"start"}
  82. @return:
  83. """
  84. device = request.json["device"] # 1=主发电机,2=应急发电机
  85. device_status = request.json["deviceStatus"] # start和stop
  86. # 判断设备能否远程控制
  87. if device in ["1", "2"] and device_status in ["start", "stop"]:
  88. device_status, real_data_dict = judge_fdj_status(device, device_status)
  89. if device_status is True:
  90. station_name, command = get_station_name_command(device, device_status)
  91. try:
  92. # 测试,先注释
  93. # result = Utility.available_connectors[station_name].send_command(command)
  94. result = "success"
  95. res = "success"
  96. log_info = f"result={result}"
  97. except Exception as e:
  98. res = "failure"
  99. log_info = f"contorl error, e={e}"
  100. else:
  101. res = "failure"
  102. log_info = f"device_status={device_status}, real_data_dict={real_data_dict}"
  103. else:
  104. res = "failure"
  105. log_info = "传参错误"
  106. save_log("control", f"fdj: request={request.json}, res={res}, {log_info}")
  107. return response.json({'message': res})
  108. def judge_fdj_status(device, operation):
  109. """
  110. 判断设备状态
  111. c411 主发电机 系统工作模式(0:本地模式,1:遥控模式,2:自动模式)
  112. c815 主发电机 备车信号(0=否,1=是)
  113. c402 主发电机 运行(0=否,1=是)
  114. c432 应急发电机 系统工作模式(0:本地模式,1:遥控模式,2:自动模式)
  115. c817 应急发电机 备车信号(0=否,1=是)
  116. c423 应急发电机 运行(0=否,1=是)
  117. @param device: 1=主发电机 2=应急发电机
  118. @param operation:start=启动 stop=停止
  119. @return:
  120. """
  121. point_list = ["c411", "c815", "c402", "c432", "c817", "c423"]
  122. real_data_dict = gateway_storage.get_real_data(point_list)
  123. # real_data_dict = {"c411": "2", "c815": "1", "c402": "1", "c432": "2", "c817": "0", "c423": "0"}
  124. if device == "1":
  125. # 控制主发电机:自动模式(c411)
  126. control_mode = real_data_dict["c411"]
  127. bc_status = real_data_dict["c815"]
  128. run_status = real_data_dict["c402"]
  129. elif device == "2":
  130. # 控制应急发电机:自动模式(c432)
  131. control_mode = real_data_dict["c432"]
  132. bc_status = real_data_dict["c817"]
  133. run_status = real_data_dict["c423"]
  134. if operation == "start":
  135. # 主发启动:自动模式(c411)、备车信号(c815)、未运行(c402)
  136. # 应发启动:自动模式(c432)、备车信号(c817)、未运行(c423)
  137. if control_mode == "2" and bc_status == "1" and run_status == "0":
  138. res = True
  139. else:
  140. res = f"Failed: 设备状态错误"
  141. elif operation == "stop":
  142. # 主发停止:自动模式(c411)、正在运行(c402)
  143. # 应发停止:自动模式(c432)、正在运行(c423)
  144. if control_mode == "2" and run_status == "1":
  145. res = True
  146. else:
  147. res = f"Failed: 设备状态错误"
  148. return res, real_data_dict
  149. def get_station_name_command(device, operation):
  150. """
  151. 查询指令
  152. @param device:1=主发电机 2=应急发电机
  153. @param operation:start=启动 stop=停止
  154. @return:
  155. """
  156. if device == "1" and operation == "start":
  157. station_name = "remote_control"
  158. command = [{"device_id": 1, "start_addr": 3, "output_value": 65280, "function_code": 5, "res": 65280}]
  159. elif device == "1" and operation == "stop":
  160. station_name = "remote_control"
  161. command = [{"device_id": 1, "start_addr": 3, "output_value": 0, "function_code": 5, "res": 0}]
  162. elif device == "2" and operation == "start":
  163. station_name = "remote_control"
  164. command = [{"device_id": 1, "start_addr": 4, "output_value": 65280, "function_code": 5, "res": 65280}]
  165. elif device == "2" and operation == "stop":
  166. station_name = "remote_control"
  167. command = [{"device_id": 1, "start_addr": 4, "output_value": 0, "function_code": 5, "res": 0}]
  168. return station_name, command
  169. def save_log(file, message):
  170. """
  171. 日志存储
  172. @param message:
  173. @return:
  174. """
  175. month = datetime.now().strftime('%Y%m')
  176. path = f"./gateway-Log/{file}_{month}.txt"
  177. print_log = open(path, 'a+')
  178. # print(message)
  179. message = f"{datetime.now()} {message}"
  180. print(message, file=print_log)
  181. print_log.close()
  182. if __name__ == "__main__":
  183. historicalDataStorage = HistoricalDataStorage(read_write=0)
  184. threading.Thread(target=historicalDataStorage.run, daemon=True, name='historicalDataStorage').start()
  185. # 投饵建议
  186. threading.Thread(target=FeedingStatistics().run, daemon=True, name=FeedingStatistics).start()
  187. # 自动投喂
  188. threading.Thread(target=AutoFeeding().run, daemon=True, name=AutoFeeding).start()
  189. # 配电板的相关维保信息(使用功率、运行时间等)
  190. threading.Thread(target=UpdateMaintenanceInfo().update_info, daemon=True, name=UpdateMaintenanceInfo()).start()
  191. # # 电池电量低时,自启发电机
  192. # threading.Thread(target=AutoCharge().run, daemon=True, name=AutoCharge).start()
  193. # 根据存储的报警信息来控制蜂鸣器
  194. threading.Thread(target=AlarmBuzzer().run, daemon=True, name=AlarmBuzzer).start()
  195. # 判断实时值是否异常,并记录
  196. threading.Thread(target=AlarmRecord().run, daemon=True, name=AlarmRecord).start()
  197. # 自动控制聚鱼灯
  198. threading.Thread(target=AutoSwitchJuyudeng().run, daemon=True, name=AutoSwitchJuyudeng).start()
  199. # 自动控制水下云台灯
  200. threading.Thread(target=AutoSwitchYuntaideng().run, daemon=True, name=AutoSwitchYuntaideng).start()
  201. # # 根据当前流速自动开关1501的PLC剖面功能
  202. # threading.Thread(target=AutoProfile1501().run, daemon=True, name=AutoProfile1501).start()
  203. # 远程开关量模块的复位逻辑
  204. threading.Thread(target=ResetRemoteControl().run, daemon=True, name=ResetRemoteControl).start()
  205. # 实时更新拉力计的计算参数,存入redis
  206. threading.Thread(target=GetLalijiParam().run, daemon=True, name=GetLalijiParam).start()
  207. app.run(host="0.0.0.0", port=18080, workers=1)