adio.py 9.85 KB
Newer Older
lcn's avatar
lcn committed
1 2 3 4
# -*- coding:utf-8 -*-
#
# Author:jing
# Date: 2020/7/9
lcn's avatar
lcn committed
5
import asyncio
lcn's avatar
lcn committed
6 7
import json
import time
8 9 10

import pendulum

lcn's avatar
lcn committed
11 12 13
from pot_libs.aredis_util.aredis_utils import RedisUtils
from pot_libs.sanic_api import summary, description, examples
from pot_libs.mysql_util.mysql_util import MysqlUtil
14
from pot_libs.settings import SETTING
lcn's avatar
lcn committed
15
from pot_libs.logger import log
lcn's avatar
lcn committed
16
from unify_api.modules.adio.service.adio_card import adio_index_service
lcn's avatar
lcn committed
17
from unify_api.utils import time_format
18
from unify_api.utils.time_format import CST, YMD_Hms, timestamp2dts
lcn's avatar
lcn committed
19 20 21 22 23 24 25 26 27 28 29 30 31
from unify_api import constants
from unify_api.utils.common_utils import round_2
from unify_api.modules.adio.components.adio import (
    AdioHistoryResponse,
    AdioCurrentResponse,
    AdioIndexResponse,
    AdioIndex,
    adio_index_example,
    adio_history_example,
    AdioHistory,
    AdioCurrent,
    adio_current_example,
)
ZZH's avatar
ZZH committed
32 33 34 35
from pot_libs.common.components.query import PageRequest
from unify_api.modules.adio.dao.adio_dao import (
    get_location_dao, get_location_15min_dao, get_adio_current_data
)
lcn's avatar
lcn committed
36 37 38 39 40 41 42 43 44 45 46 47


@summary("返回安全监测历史曲线")
@description("包含温度曲线和漏电流曲线,取最大值")
@examples(adio_history_example)
async def post_adio_history(req, body: PageRequest) -> AdioHistoryResponse:
    #  1.获取intervel和时间轴
    try:
        date_start = body.filter.ranges[0].start
        date_end = body.filter.ranges[0].end
    except:
        log.error("para error, ranges is NULL")
ZZH's avatar
ZZH committed
48 49
        return AdioHistoryResponse(temperature=[], residual_current=[],
                                   time_slots=[])
lcn's avatar
lcn committed
50
    
lcn's avatar
lcn committed
51 52 53 54 55
    try:
        # 形如 interval = 900 slots=['00:00', '00:15', '00:30'
        intervel, slots = time_format.time_pick_transf(date_start, date_end)
    except:
        log.error("para error, date format error")
ZZH's avatar
ZZH committed
56 57
        return AdioHistoryResponse(temperature=[], residual_current=[],
                                   time_slots=[])
lcn's avatar
lcn committed
58
    
lcn's avatar
lcn committed
59 60 61 62
    try:
        location_group = body.filter.in_groups[0].group
    except:
        log.warning("para exception, in_groups is NULL, no location_id")
ZZH's avatar
ZZH committed
63 64
        return AdioHistoryResponse(temperature=[], residual_current=[],
                                   time_slots=slots)
lcn's avatar
lcn committed
65
    
lcn's avatar
lcn committed
66 67
    if not location_group:
        log.warning("para exception, in_groups is NULL, no location_id")
ZZH's avatar
ZZH committed
68 69
        return AdioHistoryResponse(temperature=[], residual_current=[],
                                   time_slots=slots)
lcn's avatar
lcn committed
70
    
lcn's avatar
lcn committed
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
    # 3.获取温度曲线和漏电流曲线数据
    # 动态漏电流阈值
    sql = "select threshold from soe_config_record where lid in %s " \
          "and etype = %s limit 1"
    async with MysqlUtil() as conn:
        settings = await conn.fetchall(sql, args=(tuple(location_group),
                                                  "overResidualCurrent"))
    residual_current_threhold = settings[0]["threshold"] if settings else 30
    if intervel == 24 * 3600:
        table_name = "location_1day_aiao"
        date_format = "%%m-%%d"
    else:
        table_name = "location_15min_aiao"
        date_format = "%%H:%%i"
    sql = f"SELECT lid,value_max,DATE_FORMAT(create_time, '{date_format}') " \
          f"date_time,ad_field FROM {table_name} WHERE lid in %s and " \
          f"create_time BETWEEN '{date_start}' and '{date_end}' " \
          f"order by create_time"
    async with MysqlUtil() as conn:
ZZH's avatar
ZZH committed
90
        datas = await conn.fetchall(sql, args=(location_group,))
lcn's avatar
lcn committed
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    type_name = {
        "residual_current": "漏电流", "temp1": "A相", "temp2": "B相",
        "temp3": "C相", "temp4": "N线",
    }
    location_info, location_type_name = {}, {}
    temp_list, residual_currents = [], []
    for lid in location_group:
        location_info[lid] = ["" for _ in slots]
    for data in datas:
        lid = data.get("lid")
        value = data.get("value_max")
        mid_slot = data.get("date_time")
        if lid not in location_type_name.keys():
            ad_field = data.get("ad_field")
            location_type_name[lid] = ad_field
        slot_index = slots.index(mid_slot)
        location_info[lid][slot_index] = value
    for key, value in location_info.items():
        item_name = location_type_name.get(key)
        item = type_name.get(item_name)
        adio_his = AdioHistory(item=item, value_slots=value)
        if item_name == "residual_current":
            adio_his.threhold = residual_current_threhold
            residual_currents.append(adio_his)
        else:
            temp_list.append(adio_his)
    return AdioHistoryResponse(
        temperature=temp_list, residual_current=residual_currents,
        time_slots=slots
    )


@summary("返回安全监测实时参数")
@description("包含温度和漏电流")
@examples(adio_current_example)
async def post_adio_current(req, body: PageRequest) -> AdioCurrentResponse:
    try:
        in_group = body.filter.in_groups[0]
    except:
        log.warning("para exception, in_groups is NULL, no location_id")
        return AdioCurrentResponse(temperature=[], residual_current=[])
lcn's avatar
lcn committed
132
    
lcn's avatar
lcn committed
133 134 135 136 137
    # location_ids
    location_group = in_group.group
    if not location_group:
        log.warning("para exception, in_groups is NULL, no location_id")
        return AdioCurrentResponse(temperature=[], residual_current=[])
lcn's avatar
lcn committed
138
    
lcn's avatar
lcn committed
139 140 141 142 143
    # 读取location表信息
    location_info = await get_location_dao(location_group)
    if not location_info:
        log.warning("location_id error location_info empty")
        return AdioCurrentResponse(temperature=[], residual_current=[])
lcn's avatar
lcn committed
144
    
145 146 147 148 149 150 151 152
    # load real time adio
    lids = list(location_info.keys())
    prefix = f"real_time:adio:{SETTING.mysql_db}"
    keys = [f"{prefix}:{lid}" for lid in lids]
    rt_rlts = await RedisUtils().mget(keys)
    rt_adios = [json.loads(r) for r in rt_rlts if r]
    d_rt_adio = {adio["lid"]: adio for adio in rt_adios}
    if not d_rt_adio:
lcn's avatar
lcn committed
153
        return AdioCurrentResponse(temperature=[], residual_current=[])
lcn's avatar
lcn committed
154
    
155 156 157 158 159 160 161 162 163 164 165 166 167
    temp_lst = []
    rc_lst = []
    for lid, loc_info in location_info.items():
        if lid not in d_rt_adio:
            ts = pendulum.now(tz=CST).int_timestamp
            ad_value = ""
        else:
            ts, ad_value = d_rt_adio[lid]["ts"], d_rt_adio[lid]["v"]
        time_str = timestamp2dts(ts, YMD_Hms)
        if loc_info.get("type") == "residual_current":
            adio_current = AdioCurrent(type="residual_current", item="漏电流",
                                       real_time=time_str, value=ad_value)
            rc_lst.append(adio_current)
lcn's avatar
lcn committed
168
        else:
169 170 171 172 173
            adio_current = AdioCurrent(type="temperature",
                                       item=loc_info.get("item", ""),
                                       real_time=time_str, value=ad_value, )
            temp_lst.append(adio_current)
    return AdioCurrentResponse(temperature=temp_lst, residual_current=rc_lst)
lcn's avatar
lcn committed
174 175 176 177 178 179 180 181 182 183 184


@summary("返回安全监测实时参数(老的)")
@description("包含温度和漏电流(老的)")
@examples(adio_current_example)
async def post_adio_current_bak(req, body: PageRequest) -> AdioCurrentResponse:
    try:
        in_group = body.filter.in_groups[0]
    except:
        log.warning("para exception, in_groups is NULL, no location_id")
        return AdioCurrentResponse(temperature=[], residual_current=[])
lcn's avatar
lcn committed
185
    
lcn's avatar
lcn committed
186 187 188 189 190
    # location_ids
    location_group = in_group.group
    if not location_group:
        log.warning("para exception, in_groups is NULL, no location_id")
        return AdioCurrentResponse(temperature=[], residual_current=[])
lcn's avatar
lcn committed
191
    
lcn's avatar
lcn committed
192 193 194 195 196 197 198 199 200 201 202 203
    # 读取location表信息
    location_info = await get_location_dao(location_group)
    temperature = []
    residual_current = []
    for location_id, item_info in location_info.items():
        try:
            adio_info = await RedisUtils().hget("adio_current", location_id)
            if adio_info:
                adio_info = json.loads(adio_info)
        except Exception:
            log.error("redis error")
            return AdioCurrentResponse().db_error()
lcn's avatar
lcn committed
204
        
lcn's avatar
lcn committed
205 206 207 208 209 210 211 212 213 214 215
        time_now = int(time.time())
        if adio_info:
            real_tt = adio_info.get("timestamp", 0)
            if (time_now - real_tt) <= constants.REAL_EXP_TIME:
                adio_value = round(adio_info.get("value", 0), 2)
            else:
                adio_value = ""  # 超过4小时的值直接丢弃
            time_str = time_format.get_datetime_str(real_tt)
        else:
            adio_value = ""
            time_str = time_format.get_datetime_str(time_now)
lcn's avatar
lcn committed
216
        
lcn's avatar
lcn committed
217 218
        if item_info.get("type") == "residual_current":
            adio_current = AdioCurrent(
ZZH's avatar
ZZH committed
219 220
                type="residual_current", item="漏电流", real_time=time_str,
                value=adio_value
lcn's avatar
lcn committed
221 222 223 224 225 226 227 228 229 230
            )
            residual_current.append(adio_current)
        else:
            adio_current = AdioCurrent(
                type="temperature",
                item=item_info.get("item", ""),
                real_time=time_str,
                value=adio_value,
            )
            temperature.append(adio_current)
lcn's avatar
lcn committed
231
    
ZZH's avatar
ZZH committed
232 233
    return AdioCurrentResponse(temperature=temperature,
                               residual_current=residual_current)
lcn's avatar
lcn committed
234 235 236 237 238 239 240 241 242 243 244


@summary("返回安全监测指标统计")
@description("温度和漏电流的最高、最低、平均值")
@examples(adio_index_example)
async def post_adio_index(req, body: PageRequest) -> AdioIndexResponse:
    try:
        location_group = body.filter.in_groups[0].group
    except:
        log.warning("para exception, in_groups is NULL, no location_id")
        return AdioIndexResponse(adio_indexes=[])
lcn's avatar
lcn committed
245
    
lcn's avatar
lcn committed
246 247 248
    if not location_group:
        log.warning("para exception, in_groups is NULL, no location_id")
        return AdioIndexResponse(adio_indexes=[])
lcn's avatar
lcn committed
249
    
lcn's avatar
lcn committed
250 251 252 253 254 255 256
    # 获取时间
    try:
        start = body.filter.ranges[0].start
        end = body.filter.ranges[0].end
    except:
        log.error("para error, ranges is NULL")
        return AdioIndexResponse(adio_indexes=[])
lcn's avatar
lcn committed
257
    adio_indexes = await adio_index_service(location_group, start, end)
lcn's avatar
lcn committed
258
    return AdioIndexResponse(adio_indexes=adio_indexes)