123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260 |
- #!/usr/bin/env python
- # -*- coding:utf-8 -*-
- """
- @desc: 连接器:可读,可写
- """
- import time
- import threading
- from sanic import Sanic
- from sanic_cors import CORS, cross_origin
- from sanic import response
- from event_storage import EventStorage
- from utility import Utility
- from historical_data_storage import HistoricalDataStorage
- from feeding_statistics import FeedingStatistics
- from auto_feeding import AutoFeeding
- from auto_charge import AutoCharge
- from alarm import Alarm
- from api_context import ApiContext
- from update_maintenance_info import UpdateMaintenanceInfo
- from auto_switch_device import AutoSwitchDevice
- from alarm_buzzer import AlarmBuzzer
- from alarm_record import AlarmRecord
- from auto_switch_juyudeng import AutoSwitchJuyudeng
- from auto_switch_yuntaideng import AutoSwitchYuntaideng
- from auto_profile_1501 import AutoProfile1501
- from reset_remote_control import ResetRemoteControl
- from get_laliji_param import GetLalijiParam
- from datetime import datetime
- app = Sanic(__name__)
- CORS(app)
- gateway_storage = EventStorage()
- connector_config = gateway_storage.get_connector_config(read_write=0)
- Utility.start_connectors(connector_config)
- @app.route('/readRealText', methods=['POST'])
- async def read_point_data_text(request):
- list = request.json['pointList']
- dict = gateway_storage.get_real_data(list)
- point_list = gateway_storage.get_point_info(list)
- data_list = {}
- for info in point_list:
- data_list[info['io_point_name']] = str(dict["c"+str(info['serial_number'])]) + " " +str(info['unit'])
- return response.json(data_list)
- @app.route('/readReal', methods=['POST'])
- async def read_point_data(request):
- list = request.json['pointList']
- dict = gateway_storage.get_real_data(list)
- '''
- data_list = gateway_storage.get_point_info(list)
- for info in data_list:
- info['value'] = dict["c"+str(info['serial_number'])]
- '''
- return response.json(dict)
- @app.route('/api', methods=['POST'])
- async def read_statistics_data(request):
- if len(request.json) > 0:
- list = []
- for index in range(len(request.json)):
- api_object = request.json[index]['apiObject']
- parameter = request.json[index]['parameter']
- api = ApiContext()
- api.set_api_object(api_object)
- result = api.operation(parameter)
- list.append(result)
- data_json = Utility.data_encoder(list)
- return response.text(data_json)
- @app.route('/write',methods=['POST'])
- async def write_data(request):
- t1 = time.time()
- station_name = request.json["station_name"]
- command = request.json["command"]
- try:
- result = Utility.available_connectors[station_name].send_command(command)
- return response.json({'message': result})
- except Exception as e:
- print(station_name+"write[ERROR]:" + str(e))
- return response.json({'message': result})
- @app.route('/modbus/fdj', methods=['POST'])
- async def write_data(request):
- """
- 远程控制发电机启停
- @param request: {"device":"1", "deviceStatus":"start"}
- @return:
- """
- device = request.json["device"] # 1=主发电机,2=应急发电机
- device_status = request.json["deviceStatus"] # start和stop
- # 判断设备能否远程控制
- if device in ["1", "2"] and device_status in ["start", "stop"]:
- device_status, real_data_dict = judge_fdj_status(device, device_status)
- if device_status is True:
- station_name, command = get_station_name_command(device, device_status)
- try:
- # 测试,先注释
- # result = Utility.available_connectors[station_name].send_command(command)
- result = "success"
- res = "success"
- log_info = f"result={result}"
- except Exception as e:
- res = "failure"
- log_info = f"contorl error, e={e}"
- else:
- res = "failure"
- log_info = f"device_status={device_status}, real_data_dict={real_data_dict}"
- else:
- res = "failure"
- log_info = "传参错误"
- save_log("control", f"fdj: request={request.json}, res={res}, {log_info}")
- return response.json({'message': res})
- def judge_fdj_status(device, operation):
- """
- 判断设备状态
- c411 主发电机 系统工作模式(0:本地模式,1:遥控模式,2:自动模式)
- c815 主发电机 备车信号(0=否,1=是)
- c402 主发电机 运行(0=否,1=是)
- c432 应急发电机 系统工作模式(0:本地模式,1:遥控模式,2:自动模式)
- c817 应急发电机 备车信号(0=否,1=是)
- c423 应急发电机 运行(0=否,1=是)
- @param device: 1=主发电机 2=应急发电机
- @param operation:start=启动 stop=停止
- @return:
- """
- point_list = ["c411", "c815", "c402", "c432", "c817", "c423"]
- real_data_dict = gateway_storage.get_real_data(point_list)
- # real_data_dict = {"c411": "2", "c815": "1", "c402": "1", "c432": "2", "c817": "0", "c423": "0"}
- if device == "1":
- # 控制主发电机:自动模式(c411)
- control_mode = real_data_dict["c411"]
- bc_status = real_data_dict["c815"]
- run_status = real_data_dict["c402"]
- elif device == "2":
- # 控制应急发电机:自动模式(c432)
- control_mode = real_data_dict["c432"]
- bc_status = real_data_dict["c817"]
- run_status = real_data_dict["c423"]
- if operation == "start":
- # 主发启动:自动模式(c411)、备车信号(c815)、未运行(c402)
- # 应发启动:自动模式(c432)、备车信号(c817)、未运行(c423)
- if control_mode == "2" and bc_status == "1" and run_status == "0":
- res = True
- else:
- res = f"Failed: 设备状态错误"
- elif operation == "stop":
- # 主发停止:自动模式(c411)、正在运行(c402)
- # 应发停止:自动模式(c432)、正在运行(c423)
- if control_mode == "2" and run_status == "1":
- res = True
- else:
- res = f"Failed: 设备状态错误"
- return res, real_data_dict
- def get_station_name_command(device, operation):
- """
- 查询指令
- @param device:1=主发电机 2=应急发电机
- @param operation:start=启动 stop=停止
- @return:
- """
- if device == "1" and operation == "start":
- station_name = "remote_control"
- command = [{"device_id": 1, "start_addr": 3, "output_value": 65280, "function_code": 5, "res": 65280}]
- elif device == "1" and operation == "stop":
- station_name = "remote_control"
- command = [{"device_id": 1, "start_addr": 3, "output_value": 0, "function_code": 5, "res": 0}]
- elif device == "2" and operation == "start":
- station_name = "remote_control"
- command = [{"device_id": 1, "start_addr": 4, "output_value": 65280, "function_code": 5, "res": 65280}]
- elif device == "2" and operation == "stop":
- station_name = "remote_control"
- command = [{"device_id": 1, "start_addr": 4, "output_value": 0, "function_code": 5, "res": 0}]
- return station_name, command
- def save_log(file, message):
- """
- 日志存储
- @param message:
- @return:
- """
- month = datetime.now().strftime('%Y%m')
- path = f"./gateway-Log/{file}_{month}.txt"
- print_log = open(path, 'a+')
- # print(message)
- message = f"{datetime.now()} {message}"
- print(message, file=print_log)
- print_log.close()
- if __name__ == "__main__":
- historicalDataStorage = HistoricalDataStorage(read_write=0)
- threading.Thread(target=historicalDataStorage.run, daemon=True, name='historicalDataStorage').start()
- # 投饵建议
- threading.Thread(target=FeedingStatistics().run, daemon=True, name=FeedingStatistics).start()
- # 自动投喂
- threading.Thread(target=AutoFeeding().run, daemon=True, name=AutoFeeding).start()
- # 配电板的相关维保信息(使用功率、运行时间等)
- threading.Thread(target=UpdateMaintenanceInfo().update_info, daemon=True, name=UpdateMaintenanceInfo()).start()
- # # 电池电量低时,自启发电机
- # threading.Thread(target=AutoCharge().run, daemon=True, name=AutoCharge).start()
- # 根据存储的报警信息来控制蜂鸣器
- threading.Thread(target=AlarmBuzzer().run, daemon=True, name=AlarmBuzzer).start()
-
- # 判断实时值是否异常,并记录
- threading.Thread(target=AlarmRecord().run, daemon=True, name=AlarmRecord).start()
-
- # 自动控制聚鱼灯
- threading.Thread(target=AutoSwitchJuyudeng().run, daemon=True, name=AutoSwitchJuyudeng).start()
-
- # 自动控制水下云台灯
- threading.Thread(target=AutoSwitchYuntaideng().run, daemon=True, name=AutoSwitchYuntaideng).start()
- # # 根据当前流速自动开关1501的PLC剖面功能
- # threading.Thread(target=AutoProfile1501().run, daemon=True, name=AutoProfile1501).start()
- # 远程开关量模块的复位逻辑
- threading.Thread(target=ResetRemoteControl().run, daemon=True, name=ResetRemoteControl).start()
- # 实时更新拉力计的计算参数,存入redis
- threading.Thread(target=GetLalijiParam().run, daemon=True, name=GetLalijiParam).start()
- app.run(host="0.0.0.0", port=18080, workers=1)
|