adio.py 9.71 KB
Newer Older
lcn's avatar
lcn committed
1 2 3
# -*- coding:utf-8 -*-
import json
import time
4 5 6

import pendulum

lcn's avatar
lcn committed
7 8 9
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
10
from pot_libs.settings import SETTING
lcn's avatar
lcn committed
11
from pot_libs.logger import log
lcn's avatar
lcn committed
12
from unify_api.modules.adio.service.adio_card import adio_index_service
lcn's avatar
lcn committed
13
from unify_api.utils import time_format
14
from unify_api.utils.time_format import CST, YMD_Hms, timestamp2dts
lcn's avatar
lcn committed
15 16 17 18 19 20 21 22 23 24 25 26
from unify_api import constants
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
27
from pot_libs.common.components.query import PageRequest
ZZH's avatar
ZZH committed
28
from unify_api.modules.adio.dao.adio_dao import get_location_dao
lcn's avatar
lcn committed
29 30 31 32 33 34 35 36 37 38 39 40


@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
41 42
        return AdioHistoryResponse(temperature=[], residual_current=[],
                                   time_slots=[])
lcn's avatar
lcn committed
43
    
lcn's avatar
lcn committed
44 45 46 47 48
    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
49 50
        return AdioHistoryResponse(temperature=[], residual_current=[],
                                   time_slots=[])
lcn's avatar
lcn committed
51
    
lcn's avatar
lcn committed
52 53 54 55
    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
56 57
        return AdioHistoryResponse(temperature=[], residual_current=[],
                                   time_slots=slots)
lcn's avatar
lcn committed
58
    
lcn's avatar
lcn committed
59 60
    if not location_group:
        log.warning("para exception, in_groups is NULL, no location_id")
ZZH's avatar
ZZH committed
61 62
        return AdioHistoryResponse(temperature=[], residual_current=[],
                                   time_slots=slots)
lcn's avatar
lcn committed
63
    
lcn's avatar
lcn committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
    # 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
83
        datas = await conn.fetchall(sql, args=(location_group,))
lcn's avatar
lcn committed
84 85 86 87 88 89 90 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
    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
125
    
lcn's avatar
lcn committed
126 127 128 129 130
    # 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
131
    
lcn's avatar
lcn committed
132 133 134 135 136
    # 读取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
137
    
138 139 140 141 142 143 144 145
    # 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
146
        return AdioCurrentResponse(temperature=[], residual_current=[])
lcn's avatar
lcn committed
147
    
148 149 150 151 152 153 154 155 156 157 158 159 160
    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
161
        else:
162 163 164 165 166
            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
167 168 169 170 171 172 173 174 175 176 177


@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
178
    
lcn's avatar
lcn committed
179 180 181 182 183
    # 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
184
    
lcn's avatar
lcn committed
185 186 187 188 189 190 191 192 193 194 195 196
    # 读取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
197
        
lcn's avatar
lcn committed
198 199 200 201 202 203 204 205 206 207 208
        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
209
        
lcn's avatar
lcn committed
210 211
        if item_info.get("type") == "residual_current":
            adio_current = AdioCurrent(
ZZH's avatar
ZZH committed
212 213
                type="residual_current", item="漏电流", real_time=time_str,
                value=adio_value
lcn's avatar
lcn committed
214 215 216 217 218 219 220 221 222 223
            )
            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
224
    
ZZH's avatar
ZZH committed
225 226
    return AdioCurrentResponse(temperature=temperature,
                               residual_current=residual_current)
lcn's avatar
lcn committed
227 228 229 230 231 232 233 234 235 236 237


@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
238
    
lcn's avatar
lcn committed
239 240 241
    if not location_group:
        log.warning("para exception, in_groups is NULL, no location_id")
        return AdioIndexResponse(adio_indexes=[])
lcn's avatar
lcn committed
242
    
lcn's avatar
lcn committed
243 244 245 246 247 248 249
    # 获取时间
    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
250
    adio_indexes = await adio_index_service(location_group, start, end)
lcn's avatar
lcn committed
251
    return AdioIndexResponse(adio_indexes=adio_indexes)