import numpy as np import pandas as pd import datetime,time from sqlalchemy import create_engine from sqlalchemy.orm import sessionmaker from urllib import parse import pymysql def offline_alarm_sta(df_sns, db_iotp_engine, db_qxcas_engine, conn, db_sp_engine): cursor = conn.cursor() sql = "select sn, DATE_FORMAT(add_time, '%Y-%m-%d %H:%i:%s') as time, level, last_time from offline_info where add_time >= DATE_FORMAT( DATE_SUB(CURDATE(), INTERVAL 0 DAY), '%Y-%m-%d 00:00:00')"+ \ " and add_time <= DATE_FORMAT( DATE_SUB(CURDATE(), INTERVAL 0 DAY), '%Y-%m-%d 23:59:59')" df_offlinealarm_lastday = pd.read_sql(sql, db_qxcas_engine) sn_offline = df_offlinealarm_lastday['sn'].tolist() sql = "select * from all_fault_info where end_time='{}' and code={}".format('0000-00-00 00:00:00', 59) df_all_alarm_info = pd.read_sql(sql, db_sp_engine) sn_allalarm = df_all_alarm_info['product_id'].tolist() # 遍历昨日报警和报警列表,如果 1:sn存在于昨日报警,但不存在与报警allinfo里,则添加一条新的报警记录到allinfo里; # 2:如果sn存在于allinfo但不存在于昨日报警,则记录故障为结束; # 3: 如果sn在两个表中都存在,但级别不同,则更新级别(离线暂时不考虑级别)。 sn_new = list(set(sn_offline)-set(sn_allalarm)) sn_close = list(set(sn_allalarm)-set(sn_offline)) # sn_cross = list(set(sn_offline) & set(sn_allalarm)) # 新增 df_new = pd.DataFrame(columns=['add_time', 'product_id', 'start_time', 'end_time', 'code', 'level', 'info']) now = datetime.datetime.now() for sn in sn_new: df = df_offlinealarm_lastday[df_offlinealarm_lastday['sn']==sn] sql = "select * from ff_battery_status where devcode = '{}'".format(sn) df_on = pd.read_sql(sql, db_iotp_engine) <<<<<<< HEAD factory = df_sns[df_sns['sn']==sn]['factory'].values[0] df_new = df_new.append({'add_time':now, 'product_id':sn, 'factory':factory, 'start_time':pd.to_datetime(df_on['status_time'].values[0]), 'end_time':'0000-00-00 00:00:00', 'info':'离线报警','code':59, 'level':1}, ignore_index=True) ======= if len(df_sns[df_sns['sn']==sn]) > 0: factory = df_sns[df_sns['sn']==sn]['factory'].values[0] df_new = df_new.append({'add_time':now, 'product_id':sn, 'factory':factory, 'start_time':pd.to_datetime(df_on['status_time'].values[0]), 'end_time':'0000-00-00 00:00:00', 'info':'离线报警','code':59, 'level':1}, ignore_index=True) >>>>>>> master if not df_new.empty: df_new.to_sql('all_fault_info', db_sp_engine, if_exists='append', index=False) # 修改 now = datetime.datetime.now() for sn in sn_close: df = df_offlinealarm_lastday[df_offlinealarm_lastday['sn']==sn] df1 = df_all_alarm_info[df_all_alarm_info['product_id']==sn] sql = "select * from ff_battery_status where devcode = '{}'".format(sn) df_on = pd.read_sql(sql, db_iotp_engine) sql = ''' update all_fault_info set update_time='{}', end_time='{}' where product_id = '{}' and start_time = '{}' and code = {}'''.format \ (now, pd.to_datetime(df_on['status_time'].values[0]), sn, pd.to_datetime(df1['start_time'].values[0]), df1['code'].values[0]) cursor.execute(sql) conn.commit()