deploy.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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.BatDiag.V1_0_0 import CBMSBatDiag
  13. from LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import DBDownload
  14. from urllib import parse
  15. import pymysql
  16. import pdb
  17. from apscheduler.schedulers.blocking import BlockingScheduler
  18. import datacompy
  19. import logging
  20. import multiprocessing
  21. #...................................电池包电芯安全诊断函数......................................................................................................................
  22. def diag_cal():
  23. global df_sn, df_bms_ram
  24. start=time.time()
  25. now_time=datetime.datetime.now()
  26. start_time=now_time-datetime.timedelta(seconds=310)
  27. start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
  28. end_time=now_time.strftime('%Y-%m-%d %H:%M:%S')
  29. #数据库配置
  30. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  31. port=3306
  32. db='safety_platform'
  33. user='qx_read'
  34. password='Qx@123456'
  35. #读取故障结果库中当前故障......................................................
  36. param='start_time,end_time,product_id,code,level,info,advice'
  37. tablename='all_fault_info'
  38. mysql = pymysql.connect (host=host, user=user, password=password, port=port, database=db)
  39. cursor = mysql.cursor()
  40. sql = "select %s from %s where end_time='0000-00-00 00:00:00'" %(param,tablename)
  41. cursor.execute(sql)
  42. res = cursor.fetchall()
  43. df_diag_ram= pd.DataFrame(res,columns=param.split(','))
  44. db_res_engine = create_engine(
  45. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  46. user, parse.quote_plus(password), host, port, db
  47. ))
  48. for i in range(0, len(df_sn)):
  49. factory = "骑享"
  50. try:
  51. if df_sn.loc[i, 'imei'][5:9] == 'N640':
  52. celltype=1 #6040三元电芯
  53. elif df_sn.loc[i, 'imei'][5:9] == 'N440':
  54. celltype=2 #4840三元电芯
  55. elif df_sn.loc[i, 'imei'][5:9] == 'L660':
  56. celltype=99 # 6060锂电芯
  57. elif df_sn.loc[i, 'imei'][3:5] == 'LX' and df_sn.loc[i, 'imei'][5:9] == 'N750':
  58. celltype=3 #力信 50ah三元电芯
  59. elif df_sn.loc[i, 'imei'][3:5] == 'CL' and df_sn.loc[i, 'imei'][5:9] == 'N750':
  60. celltype=4 #CATL 50ah三元电芯
  61. elif df_sn.loc[i, 'imei'][3:9] == 'CLL128':
  62. celltype=100 # 重卡
  63. factory = "金茂换电"
  64. elif df_sn.loc[i, 'imei'][5:9] == 'L420':
  65. celltype=101 #20ah磷酸铁锂电芯
  66. else:
  67. logger.info("pid-{} celltype-{} SN: {} SKIP!".format(os.getpid(), "未知", sn))
  68. continue
  69. sn = df_sn.loc[i, 'sn']
  70. logger.info("pid-{} celltype-{} SN: {} START!".format(os.getpid(), celltype, sn))
  71. #读取原始数据库数据........................................................................................................................................................
  72. dbManager = DBManager.DBManager()
  73. df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
  74. df_bms = df_data['bms']
  75. #读取结果数据库数据........................................................................................................................................................
  76. db='qx_cas'
  77. mode=1
  78. tablename1='cellstateestimation_soh'
  79. tablename2='cellstateestimation_uniform_socvoltdiff'
  80. # tablename3='cellstateestimation_soc'
  81. DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
  82. with DBRead as DBRead:
  83. print(sn,start_time,end_time)
  84. df_soh=DBRead.getdata('time_st,sn,soh,cellsoh', tablename=tablename1, sn=sn, timename='time_sp', st=start_time, sp=end_time)
  85. df_uniform=DBRead.getdata('time,sn,cellsoc_diff,cellmin_num,cellmax_num', tablename=tablename2, sn=sn, timename='time', st=start_time, sp=end_time)
  86. # df_soc=DBRead.getdata('time','sn','packsoc', tablename=tablename3, sn=sn)
  87. #电池诊断................................................................................................................................................................
  88. if not df_bms.empty:
  89. df_diag_ram_sn=df_diag_ram[df_diag_ram['product_id']==sn]
  90. df_diag_ram_sn.reset_index(inplace=True,drop=True)
  91. df_bms_ram_sn=df_bms_ram[df_bms_ram['sn']==sn]
  92. df_bms_ram_sn.reset_index(inplace=True,drop=True)
  93. df_bms=df_bms.dropna(axis=0,subset=['总电流[A]','SOH[%]','SOC[%]','总电压[V]']) #去除有空值的行
  94. df_bms.reset_index(inplace=True,drop=True) #重置索引
  95. batquality=CBMSBatDiag.BatDiag(sn,celltype,df_bms,df_diag_ram_sn,df_bms_ram_sn,df_soh,df_uniform)
  96. df_diag_res, df_bms_res=batquality.diag() #获取电池故障结果和电池评分结果
  97. #更新bms的ram数据
  98. sn_index=df_bms_ram.loc[df_bms_ram['sn']==sn].index
  99. df_bms_ram=df_bms_ram.drop(index=sn_index)
  100. df_bms_ram=df_bms_ram.append(df_bms_res)
  101. #历史故障筛选并更改数据库故障结束时间.........................................................
  102. if not df_diag_res.empty:
  103. df_diag_new = pd.concat([df_diag_res,df_diag_ram_sn,df_diag_ram_sn]).drop_duplicates(subset=['start_time','code'],keep=False)#此次判断中新增故障
  104. df_diag_new.reset_index(inplace=True,drop=True) #重置索引
  105. df_diag_end=pd.concat([df_diag_res,df_diag_new,df_diag_new]).drop_duplicates(subset=['start_time','code'],keep=False)#此次判断中新增故障
  106. df_diag_end=df_diag_end[df_diag_end['end_time'] != '0000-00-00 00:00:00']
  107. df_diag_end.reset_index(inplace=True,drop=True) #重置索引
  108. if not df_diag_end.empty: #变为历史故障更改数据库
  109. for j in range(len(df_diag_end)):
  110. cursor.execute('''
  111. update all_fault_info set update_time='{}',end_time='{}', Batpos={} where product_id='{}' and end_time='0000-00-00 00:00:00' and code='{}'
  112. '''.format(datetime.datetime.now(), df_diag_end.loc[j,'end_time'], 1 ,sn, df_diag_end.loc[j,'code']))
  113. mysql.commit()
  114. #新增故障筛选并存入数据库.....................................................................
  115. if not df_diag_new.empty: #新增写入数据库
  116. df_diag_new.to_sql("all_fault_info",con=db_res_engine, if_exists="append",index=False)
  117. end=time.time()
  118. print(end-start)
  119. except Exception as e:
  120. logger.error(traceback.format_exc)
  121. logger.error(u"{} :{},{} 任务运行错误\n".format(sn,start_time,end_time), exc_info=True)
  122. cursor.close()
  123. mysql.close()
  124. if __name__ == "__main__":
  125. # 时间设置
  126. # now_time = datetime.datetime.now()
  127. # pre_time = now_time + dateutil.relativedelta.relativedelta(days=-1)# 前一日
  128. # end_time=datetime.datetime.strftime(now_time,"%Y-%m-%d 00:00:00")
  129. # start_time=datetime.datetime.strftime(pre_time,"%Y-%m-%d 00:00:00")
  130. history_run_flag = False # 历史数据运行标志
  131. # # 更新sn列表
  132. host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
  133. port=3306
  134. db='qixiang_oss'
  135. user='qixiang_oss'
  136. password='Qixiang2021'
  137. conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  138. cursor = conn.cursor()
  139. cursor.execute("select sn, imei, add_time from app_device where status in (1,2,3)")
  140. res = cursor.fetchall()
  141. df_sn = pd.DataFrame(res, columns=['sn', 'imei', 'add_time'])
  142. df_sn = df_sn.reset_index(drop=True)
  143. conn.close();
  144. # # 数据库配置
  145. # host = 'rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  146. # port = 3306
  147. # user = 'qx_cas'
  148. # password = parse.quote_plus('Qx@123456')
  149. # database = 'qx_cas'
  150. # db_engine = create_engine(
  151. # "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  152. # user, password, host, port, database
  153. # ))
  154. # DbSession = sessionmaker(bind=db_engine)
  155. # # 运行历史数据配置
  156. # df_first_data_time = pd.read_sql("select * from bat_first_data_time", db_engine)
  157. # 日志配置
  158. now_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()).replace(":","_")
  159. log_path = 'log/' + now_str
  160. if not os.path.exists(log_path):
  161. os.makedirs(log_path)
  162. log = Log.Mylog(log_name='batDiag', log_level = 'info')
  163. log.set_file_hl(file_name='{}/info.log'.format(log_path), log_level='info', size=1024* 1024 * 100)
  164. log.set_file_hl(file_name='{}/error.log'.format(log_path), log_level='error', size=1024* 1024 * 100)
  165. logger = log.get_logger()
  166. logger.info("pid is {}".format(os.getpid()))
  167. # # 算法参数
  168. # host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  169. # port=3306
  170. # db='safety_platform'
  171. # user='qx_read'
  172. # password=parse.quote_plus('Qx@123456')
  173. # tablename='all_fault_info'
  174. # db_res_engine = create_engine(
  175. # "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  176. # user, password, host, port, db
  177. # ))
  178. #............................模块运行前,先读取数据库中所有结束时间为0的数据,需要从数据库中读取................
  179. # print("select start_time, end_time, product_id, code, level, info, advice, factory from {}".format(tablename))
  180. # result=pd.read_sql("select start_time, end_time, product_id, code, level, info, advice from all_fault_info where factory = '{}'".format('骑享'), db_res_engine)
  181. # result = result[['start_time', 'end_time', 'product_id', 'code', 'level', 'info', 'advice']]
  182. # df_diag_ram=result[(result['end_time']=='0000-00-00 00:00:00') & (result['code']==119)]
  183. df_bms_ram=pd.DataFrame(columns=['time', 'sn', 'packvolt', 'cellvolt', 'celltemp'])
  184. diag_cal()
  185. #定时任务.......................................................................................................................................................................
  186. scheduler = BlockingScheduler()
  187. scheduler.add_job(diag_cal, 'interval', seconds=300, id='diag_job')
  188. try:
  189. scheduler.start()
  190. except Exception as e:
  191. scheduler.shutdown()
  192. logger.error(str(e))