deploy.py 16 KB

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