deploy_saftywarning.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. __author__ = 'lmstack'
  2. #coding=utf-8
  3. import os
  4. import datetime
  5. import pandas as pd
  6. from LIB.BACKEND import DBManager
  7. from sqlalchemy import create_engine
  8. from sqlalchemy.orm import sessionmaker
  9. import datetime
  10. import traceback
  11. from LIB.MIDDLE.CellStateEstimation.BatSafetyWarning.V1_0_1 import CBMSSafetyWarning
  12. from LIB.MIDDLE.CellStateEstimation.BatSafetyWarning.V1_0_1 import CBMSBatInterShort
  13. from LIB.MIDDLE.CellStateEstimation.BatSafetyWarning.V1_0_1 import CBMSBatUniform
  14. # from LIB.MIDDLE.CellStateEstimation.BatSafetyWarning.V1_0_1 import VoltStray
  15. from urllib import parse
  16. import pymysql
  17. import logging
  18. import logging.handlers
  19. import re
  20. from apscheduler.schedulers.blocking import BlockingScheduler
  21. #...................................电池包电芯安全诊断函数......................................................................................................................
  22. def saftywarning_cal():
  23. global df_sn
  24. global df_warning_ram
  25. global df_warning_ram1
  26. global df_warning_ram2
  27. global df_warning_ram3
  28. global df_lfp_ram
  29. global df_lfp_ram1
  30. global df_chrgvolt_ram
  31. # 读取结果数据库
  32. host2='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  33. port2=3306
  34. db2='safety_platform'
  35. user2='qx_algo_rw'
  36. password2='qx@123456'
  37. db_safety_platform_engine = create_engine(
  38. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  39. user2, parse.quote_plus(password2), host2, port2, db2
  40. ))
  41. conn_platform = pymysql.connect(host=host2, port=port2, user=user2, password=password2, database=db2)
  42. cursor_platform = conn_platform.cursor()
  43. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  44. port=3306
  45. db='qx_cas'
  46. user='qx_algo_rw'
  47. password='qx@123456'
  48. db_qxcas_engine = create_engine(
  49. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  50. user, parse.quote_plus(password), host, port, db
  51. ))
  52. conn_cas = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  53. cursor_cas = conn_cas.cursor()
  54. df_fault_ram=pd.read_sql("select start_time, end_time, product_id, code, level, info, advice from all_fault_info where end_time='{}' and code='{}'".format('0000-00-00 00:00:00','C490'), db_safety_platform_engine)
  55. # result = result[['start_time', 'end_time', 'product_id', 'code', 'level', 'info', 'advice']]
  56. # df_fault_ram=result[(result['end_time']=='0000-00-00 00:00:00') & (result['code']=='C490')]
  57. now_time=datetime.datetime.now()
  58. start_time=now_time-datetime.timedelta(hours=6)
  59. start_time1=now_time-datetime.timedelta(days=7)
  60. start_time2=now_time-datetime.timedelta(days=3)
  61. start_time3=now_time-datetime.timedelta(days=1)
  62. start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
  63. start_time1=start_time1.strftime('%Y-%m-%d %H:%M:%S')
  64. start_time2=start_time2.strftime('%Y-%m-%d %H:%M:%S')
  65. start_time3=start_time3.strftime('%Y-%m-%d %H:%M:%S')
  66. end_time=now_time.strftime('%Y-%m-%d %H:%M:%S')
  67. for i in range(0, len(df_sn)):
  68. factory = "骑享"
  69. try:
  70. sn = df_sn.loc[i, 'sn']
  71. if df_sn.loc[i, 'imei'][5:9] == 'N640':
  72. celltype=1 #6040三元电芯
  73. elif df_sn.loc[i, 'imei'][5:9] == 'N440':
  74. celltype=2 #4840三元电芯
  75. elif df_sn.loc[i, 'imei'][5:9] == 'L660':
  76. celltype=99 # 6060锂电芯
  77. elif df_sn.loc[i, 'imei'][3:5] == 'LX' and df_sn.loc[i, 'imei'][5:9] == 'N750':
  78. celltype=3 #力信 50ah三元电芯
  79. elif df_sn.loc[i, 'imei'][3:5] == 'CL' and df_sn.loc[i, 'imei'][5:9] == 'N750':
  80. celltype=4 #CATL 50ah三元电芯
  81. elif df_sn.loc[i, 'imei'][3:9] == 'CLL128':
  82. celltype=100 # 重卡
  83. factory = "金茂换电"
  84. elif df_sn.loc[i, 'imei'][5:9] == 'L420':
  85. celltype=101 #20ah磷酸铁锂电芯
  86. else:
  87. logger.info("pid-{} celltype-{} SN: {} SKIP!".format(os.getpid(), "未知", sn))
  88. continue
  89. logger.info("pid-{} celltype-{} SN: {} START!".format(os.getpid(), celltype, sn))
  90. # 读取soh数据
  91. df_soh = pd.read_sql("select time_st,sn,soh,cellsoh from cellstateestimation_soh where sn = '{}' order by id desc limit 1".format(sn), db_qxcas_engine)
  92. df_uniform = pd.read_sql("select time,sn,cellsoc_diff,cellvolt_diff,cellmin_num,cellmax_num,cellvolt_rank from cellstateestimation_uniform_socvoltdiff where sn = '{}' order by id desc limit 1".format(sn), db_qxcas_engine)
  93. df_uniform.loc[0,'cellvolt_rank']=str([1]*20)
  94. # df_voltsigma=pd.DataFrame()
  95. #读取原始数据库数据................................................................................id........................................................................
  96. dbManager = DBManager.DBManager()
  97. df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
  98. df_bms = df_data['bms']
  99. # print(df_bms)
  100. #电池诊断................................................................................................................................................................
  101. if not df_bms.empty:
  102. #电池内短路计算................................................................................................................................................................
  103. df_warning_ram_sn=df_warning_ram[df_warning_ram['sn']==sn]
  104. df_warning_ram_sn1=df_warning_ram1[df_warning_ram1['sn']==sn]
  105. df_warning_ram_sn2=df_warning_ram2[df_warning_ram2['sn']==sn]
  106. df_warning_ram_sn3=df_warning_ram3[df_warning_ram3['sn']==sn]
  107. df_chrgvolt_ram_sn=df_chrgvolt_ram[df_chrgvolt_ram['sn']==sn]
  108. df_warning_ram_sn.reset_index(inplace=True,drop=True) #重置索引
  109. df_warning_ram_sn1.reset_index(inplace=True,drop=True) #重置索引
  110. df_warning_ram_sn2.reset_index(inplace=True,drop=True) #重置索引
  111. df_warning_ram_sn3.reset_index(inplace=True,drop=True) #重置索引
  112. df_chrgvolt_ram_sn.reset_index(inplace=True,drop=True)
  113. if not df_lfp_ram.empty:
  114. df_lfp_ram_sn=df_lfp_ram[df_lfp_ram['sn']==sn]
  115. df_lfp_ram_sn.reset_index(inplace=True,drop=True) #重置索引
  116. else:
  117. df_lfp_ram_sn=pd.DataFrame()
  118. df_lfp_ram=pd.DataFrame(columns=df_bms.columns.tolist()+['sn'])
  119. if celltype>50 and (not df_lfp_ram1.empty):
  120. df_lfp_ram_sn1=df_lfp_ram1[df_lfp_ram1['sn']==sn]
  121. df_lfp_ram_sn1.reset_index(inplace=True,drop=True) #重置索引
  122. else:
  123. df_lfp_ram_sn1=pd.DataFrame()
  124. df_lfp_ram1=pd.DataFrame(columns=df_bms.columns.tolist()+['sn'])
  125. #内短路计算..................................................................................................................................................
  126. BatShort=CBMSBatInterShort.BatInterShort(sn,celltype,df_bms,df_soh,df_warning_ram_sn,df_warning_ram_sn1,df_warning_ram_sn2,df_warning_ram_sn3,df_lfp_ram_sn,df_chrgvolt_ram_sn)
  127. df_short_res, df_ram_res, df_ram_res1, df_ram_res2, df_ram_res3, df_ram_res4, df_chrgvolt_ram_sn=BatShort.intershort()
  128. if not df_short_res.empty:
  129. df_short_res.columns = ['time_st', 'time_sp', 'sn', 'method', 'short_current', 'baltime']
  130. df_short_res.to_sql("cellStateEstimation_interShort",con=db_qxcas_engine, if_exists="append",index=False)
  131. #静置电压排名..................................................................................................................................................
  132. BatUniform=CBMSBatUniform.BatUniform(sn,celltype,df_bms,df_uniform,df_ram_res3,df_lfp_ram_sn1)
  133. df_rank_res, df_ram_res3, df_ram_res5=BatUniform.batuniform()
  134. if not df_rank_res.empty:
  135. df_uniform=df_rank_res
  136. df_rank_res.to_sql("cellstateestimation_uniform_socvoltdiff",con=db_qxcas_engine, if_exists="append",index=False)
  137. #电压离群.....................................................................................................................................................
  138. # df_voltsigma=VoltStray.main(sn,df_bms,celltype)
  139. # if not df_voltsigma.empty:
  140. # df_voltsigma.to_sql("outlier_voltchangeratio",con=db_qxcas_engine, if_exists="append",index=False)
  141. #内短路ram处理.........................................................
  142. df_warning_ram=df_warning_ram.drop(df_warning_ram[df_warning_ram.sn==sn].index)
  143. df_warning_ram1=df_warning_ram1.drop(df_warning_ram1[df_warning_ram1.sn==sn].index)
  144. df_warning_ram2=df_warning_ram2.drop(df_warning_ram2[df_warning_ram2.sn==sn].index)
  145. df_warning_ram3=df_warning_ram3.drop(df_warning_ram3[df_warning_ram3.sn==sn].index)
  146. df_chrgvolt_ram=df_chrgvolt_ram.drop(df_chrgvolt_ram[df_chrgvolt_ram.sn==sn].index)
  147. df_warning_ram=pd.concat([df_warning_ram,df_ram_res],ignore_index=True)
  148. df_warning_ram1=pd.concat([df_warning_ram1,df_ram_res1],ignore_index=True)
  149. df_warning_ram2=pd.concat([df_warning_ram2,df_ram_res2],ignore_index=True)
  150. df_warning_ram3=pd.concat([df_warning_ram3,df_ram_res3],ignore_index=True)
  151. df_chrgvolt_ram=pd.concat([df_chrgvolt_ram,df_chrgvolt_ram_sn],ignore_index=True)
  152. df_lfp_ram=df_lfp_ram.drop(df_lfp_ram[df_lfp_ram.sn==sn].index)
  153. df_lfp_ram=pd.concat([df_lfp_ram,df_ram_res4],ignore_index=True)
  154. if celltype>50:
  155. df_lfp_ram1=df_lfp_ram1.drop(df_lfp_ram1[df_lfp_ram1.sn==sn].index)
  156. df_lfp_ram1=pd.concat([df_lfp_ram1,df_ram_res5],ignore_index=True)
  157. #电池热安全预警..............................................................................................................................................................
  158. #读取内短路、析锂和一致性结果数据库数据
  159. df_short = pd.read_sql("select time_st,time_sp,sn,method,short_current from cellstateestimation_intershort where sn = '{}' and time_sp between '{}' and '{}'".format(sn,start_time1,end_time), db_qxcas_engine)
  160. # df_liplated = pd.read_sql("select time,sn,liplated,liplated_amount from mechanism_liplated where sn = '{}' and time between '{}' and '{}'".format(sn,start_time2,end_time), db_qxcas_engine)
  161. df_uniform = pd.read_sql("select time,sn,cellsoc_diff,cellvolt_diff,cellmin_num,cellmax_num,cellvolt_rank from cellstateestimation_uniform_socvoltdiff where sn = '{}' and time between '{}' and '{}'".format(sn,start_time2,end_time), db_qxcas_engine)
  162. # df_voltsigma = pd.read_sql("select time,sn,VolOl_Uni,VolChng_Uni from outlier_voltchangeratio where sn = '{}' and time between '{}' and '{}'".format(sn,start_time3,end_time), db_qxcas_engine)
  163. #获取sn的故障RAM
  164. df_fault_ram_sn=df_fault_ram[df_fault_ram['product_id']==sn]
  165. df_fault_ram_sn.reset_index(inplace=True, drop=True)
  166. #热安全预警
  167. BatWarning=CBMSSafetyWarning.SafetyWarning(sn,celltype,df_short,df_uniform,df_soh,df_fault_ram_sn)
  168. df_res_new, df_res_chg=BatWarning.diag()
  169. #新增内短路故障写入数据库
  170. if not df_res_new.empty:
  171. df_res_new['add_time'] = datetime.datetime.now()
  172. df_res_new['factory'] = factory
  173. df_res_new.to_sql("all_fault_info",con=db_safety_platform_engine, if_exists="append",index=False)
  174. conn_platform.commit()
  175. #内短路结束故障更新数据库
  176. if not df_res_chg.empty:
  177. df_res_chg['Batpos']=1
  178. cursor_platform.execute('''
  179. update all_fault_info set update_time='{}',end_time='{}', Batpos={} where product_id='{}' and code='{}' and end_time='0000-00-00 00:00:00'
  180. '''.format(datetime.datetime.now(), df_res_chg.iloc[-1]['end_time'], df_res_chg.iloc[-1]['Batpos'],sn, 'C490'))
  181. conn_platform.commit()
  182. except Exception as e:
  183. logger.error(traceback.format_exc)
  184. logger.error(u"{} :{},{} 任务运行错误\n".format(sn,start_time,end_time), exc_info=True)
  185. cursor_platform.close()
  186. conn_platform.close()
  187. cursor_cas.close()
  188. conn_cas.close()
  189. db_qxcas_engine.dispose()
  190. db_safety_platform_engine.dispose()
  191. logger.info("pid-{} Done!".format(os.getpid()))
  192. #...................................................主进程...........................................................................................................
  193. if __name__ == "__main__":
  194. # 日志
  195. log_path = 'log/'
  196. if not os.path.exists(log_path):
  197. os.makedirs(log_path)
  198. logger = logging.getLogger("main")
  199. logger.setLevel(logging.DEBUG)
  200. # 根据日期滚动(每天产生1个文件)
  201. fh = logging.handlers.TimedRotatingFileHandler(filename='{}/main_info.log'.format(log_path), when="D", interval=1, backupCount=30,
  202. encoding="utf-8")
  203. formatter = logging.Formatter("%(asctime)s - %(name)s-%(levelname)s %(message)s")
  204. fh.suffix = "%Y-%m-%d_%H-%M-%S"
  205. fh.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}")
  206. fh.setFormatter(formatter)
  207. fh.setLevel(logging.INFO)
  208. logger.addHandler(fh)
  209. fh = logging.handlers.TimedRotatingFileHandler(filename='{}/main_error.log'.format(log_path), when="D", interval=1, backupCount=30,
  210. encoding="utf-8")
  211. formatter = logging.Formatter("%(asctime)s - %(name)s-%(levelname)s %(message)s")
  212. fh.suffix = "%Y-%m-%d_%H-%M-%S"
  213. fh.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}")
  214. fh.setFormatter(formatter)
  215. fh.setLevel(logging.ERROR)
  216. logger.addHandler(fh)
  217. logger.info("pid is {}".format(os.getpid()))
  218. # 时间设置
  219. # now_time = datetime.datetime.now()
  220. # pre_time = now_time + dateutil.relativedelta.relativedelta(days=-1)# 前一日
  221. # end_time=datetime.datetime.strftime(now_time,"%Y-%m-%d 00:00:00")
  222. # start_time=datetime.datetime.strftime(pre_time,"%Y-%m-%d 00:00:00")
  223. history_run_flag = False # 历史数据运行标志
  224. # # 更新sn列表
  225. host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
  226. port=3306
  227. db='qixiang_oss'
  228. user='qixiang_oss'
  229. password='Qixiang2021'
  230. conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  231. cursor = conn.cursor()
  232. cursor.execute("select sn, imei, add_time from app_device where status in (1,2,3)")
  233. res = cursor.fetchall()
  234. df_sn = pd.DataFrame(res, columns=['sn', 'imei', 'add_time'])
  235. df_sn = df_sn.reset_index(drop=True)
  236. conn.close();
  237. # 数据库配置
  238. host = 'rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  239. port = 3306
  240. user = 'qx_cas'
  241. password = parse.quote_plus('Qx@123456')
  242. database = 'qx_cas'
  243. db_engine = create_engine(
  244. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  245. user, password, host, port, database
  246. ))
  247. DbSession = sessionmaker(bind=db_engine)
  248. # 运行历史数据配置
  249. df_first_data_time = pd.read_sql("select * from bat_first_data_time", db_engine)
  250. # 算法参数
  251. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  252. port=3306
  253. db='safety_platform'
  254. user='qx_read'
  255. password=parse.quote_plus('Qx@123456')
  256. tablename='all_fault_info'
  257. db_res_engine = create_engine(
  258. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  259. user, password, host, port, db
  260. ))
  261. #............................模块运行前,先读取数据库中所有结束时间为0的数据,需要从数据库中读取................
  262. df_warning_ram=pd.DataFrame(columns=['sn','time','deltsoc','cellsoc'])
  263. df_warning_ram1=pd.DataFrame(columns=['sn','time1','deltsoc1'])
  264. df_warning_ram2=pd.DataFrame(columns=['sn','time2','deltAs2'])
  265. df_warning_ram3=pd.DataFrame(columns=['sn','time3','standingtime','standingtime1','standingtime2'])
  266. df_lfp_ram=pd.DataFrame()
  267. df_lfp_ram1=pd.DataFrame()
  268. df_chrgvolt_ram=pd.DataFrame(columns=['sn','time','deltvolt','packcrnt_avg','temp_avg'])
  269. # now_time='2021-10-15 00:00:00'
  270. # now_time=datetime.datetime.strptime(now_time,'%Y-%m-%d %H:%M:%S')
  271. saftywarning_cal()
  272. #定时任务.......................................................................................................................................................................
  273. scheduler = BlockingScheduler()
  274. scheduler.add_job(saftywarning_cal, 'interval', hours=6, id='saftywarning_cal')
  275. try:
  276. scheduler.start()
  277. except Exception as e:
  278. scheduler.shutdown()
  279. logger.error(str(e))