123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161 |
- __author__ = 'ERIC'
- #coding=utf-8
- import os
- import datetime
- import pandas as pd
- from LIB.BACKEND import DBManager
- from sqlalchemy import create_engine
- from LIB.MIDDLE.PingFeng.SOC.V1_0_0 import soc
- import datetime
- import traceback
- from urllib import parse
- import pymysql
- from apscheduler.schedulers.blocking import BlockingScheduler
- import logging
- import logging.handlers
- import re
- #...................................电池包SOC计算......................................................................................................................
- def SOC_cal():
- now_time=datetime.datetime.now()
- start_time=now_time-datetime.timedelta(seconds=300)
- start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
- end_time=now_time.strftime('%Y-%m-%d %H:%M:%S')
- #数据库配置
- host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
- port=3306
- db='safety_platform'
- user='qx_algo_rw'
- password='qx@123456'
- db_res_engine = create_engine(
- "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
- user, parse.quote_plus(password), host, port, db
- ))
- for i in range(0, len(df_sn)):
- factory = "骑享"
- sn = df_sn.loc[i, 'sn']
- try:
- if df_sn.loc[i, 'imei'][5:9] == 'N640':
- celltype=1 #6040三元电芯
- elif df_sn.loc[i, 'imei'][5:9] == 'N440':
- celltype=2 #4840三元电芯
- elif df_sn.loc[i, 'imei'][5:9] == 'L660':
- celltype=99 # 6060锂电芯
- elif df_sn.loc[i, 'imei'][3:5] == 'LX' and df_sn.loc[i, 'imei'][5:9] == 'N750':
- celltype=3 #力信 50ah三元电芯
- elif df_sn.loc[i, 'imei'][3:5] == 'CL' and df_sn.loc[i, 'imei'][5:9] == 'N750':
- celltype=4 #CATL 50ah三元电芯
- elif df_sn.loc[i, 'imei'][3:9] == 'CLL128':
- celltype=100 # 重卡
- factory = "金茂换电"
- elif df_sn.loc[i, 'imei'][0:6] == 'SPFPFL':
- celltype=200#储能电站
- factory = "平峰"
- else:
- logger.info("pid-{} celltype-{} SN: {} SKIP!".format(os.getpid(), "未知", sn))
- continue
- #读取原始数据库数据........................................................................................................................................................
- dbManager = DBManager.DBManager()
- df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
- df_bms = df_data['bms']
- #电池诊断................................................................................................................................................................
- if not df_bms.empty:
- logger.info("pid-{} celltype-{} SN: {} START!".format(os.getpid(), celltype, sn))
- SOC_result=soc.soc_test(sn,df_bms)
- SOC_result.columns=['sn','soc','time']
- SOC_result.reset_index(inplace=True,drop=True)
- #新增故障筛选并存入数据库.....................................................................
- if not SOC_result.empty: #新增写入数据库
- SOC_result.to_sql('pingfeng_soc_cal',con=db_res_engine, if_exists='append',index=False)
- logger.info("算法运行完成,结果入库")
- else:
- logger.info("算法运行完成,无结果入库")
- else:
- logger.info("pid-{} celltype-{} SN: {} 无数据无需运算".format(os.getpid(), celltype, sn))
-
- except Exception as e:
- logger.error(traceback.format_exc)
- logger.error(u"{} :{},{} 任务运行错误\n".format(sn,start_time,end_time), exc_info=True)
- if __name__ == "__main__":
-
- # 时间设置
- # now_time = datetime.datetime.now()
- # pre_time = now_time + dateutil.relativedelta.relativedelta(days=-1)# 前一日
- # end_time=datetime.datetime.strftime(now_time,"%Y-%m-%d 00:00:00")
- # start_time=datetime.datetime.strftime(pre_time,"%Y-%m-%d 00:00:00")
-
- history_run_flag = False # 历史数据运行标志
-
- def get_sn():
- global df_sn
- # # 更新sn列表
- host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
- port=3306
- db='qixiang_oss'
- user='qixiang_oss'
- password='Qixiang2021'
- conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
- cursor = conn.cursor()
- cursor.execute("select sn, imei, add_time from app_device where status in (1,2,3)")
- res = cursor.fetchall()
- df_sn = pd.DataFrame(res, columns=['sn', 'imei', 'add_time'])
- df_sn = df_sn[df_sn['sn'].str.contains('SPFPFL')]
- #df_sn = df_sn[df_sn['sn'].str.contains('PK500A20100000941')]
-
- df_sn = df_sn.reset_index(drop=True)
- conn.close()
-
- # 日志
- log_path = 'log/'
- if not os.path.exists(log_path):
- os.makedirs(log_path)
- logger = logging.getLogger("main")
- logger.setLevel(logging.DEBUG)
-
- # 根据日期滚动(每天产生1个文件)
- fh = logging.handlers.TimedRotatingFileHandler(filename='{}/main_info.log'.format(log_path), when="D", interval=1, backupCount=30,
- encoding="utf-8")
- formatter = logging.Formatter("%(asctime)s - %(name)s-%(levelname)s %(message)s")
- fh.suffix = "%Y-%m-%d_%H-%M-%S"
- fh.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}")
- fh.setFormatter(formatter)
- fh.setLevel(logging.INFO)
- logger.addHandler(fh)
- fh = logging.handlers.TimedRotatingFileHandler(filename='{}/main_error.log'.format(log_path), when="D", interval=1, backupCount=30,
- encoding="utf-8")
- formatter = logging.Formatter("%(asctime)s - %(name)s-%(levelname)s %(message)s")
- fh.suffix = "%Y-%m-%d_%H-%M-%S"
- fh.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}")
- fh.setFormatter(formatter)
- fh.setLevel(logging.ERROR)
- logger.addHandler(fh)
- logger.info("pid is {}".format(os.getpid()))
-
- get_sn()
- SOC_cal()
- #定时任务.......................................................................................................................................................................
- scheduler = BlockingScheduler()
- scheduler.add_job(get_sn, 'interval', days=1, id='get_sn')
- scheduler.add_job(SOC_cal, 'interval', seconds=300, id='SOC_cal')
-
- try:
- scheduler.start()
- except Exception as e:
- scheduler.shutdown()
- logger.error(str(e))
-
|