deploy.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234
  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 dateutil.relativedelta
  11. import traceback
  12. from LIB.MIDDLE.CellStateEstimation.Common import log
  13. from pandas.core.frame import DataFrame
  14. from LIB.MIDDLE.SaftyCenter.Common import QX_BatteryParam
  15. from LIB.MIDDLE.SaftyCenter.CellValueDiag.V1_0_0.SC_SamplingSafty import SamplingSafty
  16. from LIB.MIDDLE.CellStateEstimation.Common import DBDownload
  17. from urllib import parse
  18. import pymysql
  19. import pdb
  20. from apscheduler.schedulers.blocking import BlockingScheduler
  21. import datacompy
  22. def fun():
  23. global df_sn
  24. global db_res_engine
  25. global logger
  26. global df_Diag_Ram
  27. # 读取结果数据库
  28. host2='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  29. port2=3306
  30. db2='safety_platform'
  31. user2='qx_read'
  32. password2='Qx@123456'
  33. start=time.time()
  34. end_time=datetime.datetime.now()
  35. start_time=end_time-datetime.timedelta(seconds=120)
  36. start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
  37. end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
  38. logger.info("cycle start !!!!!!!!!!!!!!!!!!!!")
  39. for i in range(0, len(df_sn)):
  40. try:
  41. if df_sn.loc[i, 'imei'][5:9] == 'N640':
  42. celltype=1 #6040三元电芯
  43. elif df_sn.loc[i, 'imei'][5:9] == 'N440':
  44. celltype=2 #4840三元电芯
  45. elif df_sn.loc[i, 'imei'][5:9] == 'L660':
  46. celltype=99 # 6060锂电芯
  47. elif df_sn.loc[i, 'imei'][3:5] == 'LX' and df_sn.loc[i, 'imei'][5:9] == 'N750':
  48. celltype=3 #力信 50ah三元电芯
  49. elif df_sn.loc[i, 'imei'][3:5] == 'CL' and df_sn.loc[i, 'imei'][5:9] == 'N750':
  50. celltype=4 #CATL 50ah三元电芯
  51. elif df_sn.loc[i, 'imei'][5:9] == 'L420':
  52. celltype=101 #20ah磷酸铁锂电芯
  53. else:
  54. logger.info("pid-{} celltype-{} SN: {} SKIP!".format(os.getpid(), "未知", sn))
  55. continue
  56. sn = df_sn.loc[i, 'sn']
  57. logger.info("pid-{} celltype-{} SN: {} START!".format(os.getpid(), celltype, sn))
  58. param=QX_BatteryParam.BatteryInfo(celltype)
  59. # sn='PK50201A000002039'
  60. # celltype=2
  61. # start_time='2021-05-02 09:12:26'
  62. # end_time='2021-06-03 19:12:26'
  63. # # df_bms= pd.read_csv(r'D:\Platform\platform_python\data_analyze_platform\USER\01qixiang\98Download\\'+'BMS_'+sn+'.csv',encoding='GB18030')
  64. #读取原始数据库数据........................................................................................................................................................
  65. dbManager = DBManager.DBManager()
  66. df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
  67. df_bms = df_data['bms']
  68. # df_bms.to_csv(r'D:\Platform\platform_python\data_analyze_platform\USER\01qixiang\99Result\\''BMS_'+sn+'.csv',encoding='GB18030')
  69. #读取结果数据库数据........................................................................................................................................................
  70. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  71. port=3306
  72. db='qx_cas'
  73. user='qx_read'
  74. password='Qx@123456'
  75. mode=1
  76. # 读取结果数据库
  77. host2='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  78. port2=3306
  79. db2='safety_platform'
  80. user2='qx_read'
  81. password2='Qx@123456'
  82. tablename1='cellstateestimation_soh'
  83. tablename2='cellstateestimation_uniform_socvoltdiff'
  84. tablename3='cellstateestimation_soc'
  85. DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
  86. with DBRead as DBRead:
  87. df_soh=DBRead.getdata('time_st','sn','soh', 'cellsoh', tablename=tablename1, sn=sn, timename='time_sp', st=start_time, sp=end_time)
  88. df_uniform=DBRead.getdata('time','sn','cellsoc_diff','cellmin_num','cellmax_num', tablename=tablename2, sn=sn, timename='time', st=start_time, sp=end_time)
  89. # df_soc=DBRead.getdata('time','sn','packsoc', tablename=tablename3, sn=sn)
  90. #电池诊断................................................................................................................................................................
  91. #BatDiag=CBMSBatDiag.BatDiag(sn,celltype,df_bms, df_soh, df_uniform)
  92. #df_res=BatDiag.diag()
  93. #df_Diag_Ram_old=df_Diag_Ram
  94. df_Diag_Ram_Update=DataFrame(columns=['start_time', 'end_time', 'product_id', 'code', 'level', 'info','advice'])
  95. CellFltInfo=DataFrame(columns=['start_time', 'end_time', 'product_id', 'code', 'level', 'info','advice'])
  96. if not df_bms.empty:
  97. CellFltInfo=df_Diag_Ram[df_Diag_Ram['product_id']==sn]
  98. df_Diag_Ram_Update=SamplingSafty.main(sn,param,df_bms,CellFltInfo)
  99. if not df_Diag_Ram_Update.empty:
  100. sn_index=df_Diag_Ram[df_Diag_Ram['product_id']==sn].index
  101. df_Diag_Ram=df_Diag_Ram.drop(index=sn_index)
  102. df_Diag_Ram=df_Diag_Ram.append(df_Diag_Ram_Update)
  103. df_Diag_Ram.reset_index(inplace=True,drop=True)
  104. Diag_Ram_Dif=datacompy.Compare(df_Diag_Ram_Update,CellFltInfo,join_columns=['product_id','end_time', 'code'])
  105. Diag_Ram_Dif=Diag_Ram_Dif.df1_unq_rows
  106. if len(Diag_Ram_Dif)>0:
  107. Diag_Ram_Dif_New=Diag_Ram_Dif[Diag_Ram_Dif['end_time']=='0000-00-00 00:00:00']
  108. Diag_Ram_Dif_Finish=df_Diag_Ram[df_Diag_Ram['end_time']!='0000-00-00 00:00:00']
  109. if len(Diag_Ram_Dif_New)>0: # 新增
  110. Diag_Ram_Dif_New.columns = ['start_time', 'end_time', 'product_id', 'code', 'level', 'info', 'advice']
  111. Diag_Ram_Dif_New['factory'] = '骑享'
  112. Diag_Ram_Dif_New.to_sql("all_fault_info",con=db_res_engine, if_exists="append",index=False)
  113. if len(Diag_Ram_Dif_Finish)>0: # 修改
  114. Diag_Ram_Dif_Finish=Diag_Ram_Dif_Finish.reset_index(drop=True)
  115. try:
  116. conn = pymysql.connect(host=host2, port=port2, user=user2, password=password2, database=db2)
  117. cursor = conn.cursor()
  118. for i in range(0,len(Diag_Ram_Dif_Finish)):
  119. cursor.execute('''
  120. update all_fault_info set end_time={} where product_id='{}' and code={}
  121. '''.format(Diag_Ram_Dif_Finish.loc[i,'end_time'], Diag_Ram_Dif_Finish.loc[i,'product_id'], Diag_Ram_Dif_Finish.loc[i,'code']))
  122. conn.commit()
  123. conn.close();
  124. except:
  125. logger.error(traceback.format_exc)
  126. logger.error(u"{} :{},{} 任务运行错误\n".format(sn,start_time,end_time), exc_info=True)
  127. conn.close();
  128. end=time.time()
  129. logger.info("pid-{} SN: {} DONE!".format(os.getpid(), sn))
  130. except:
  131. logger.error(traceback.format_exc)
  132. logger.error(u"{} :{},{} 任务运行错误\n".format(sn,start_time,end_time), exc_info=True)
  133. if __name__ == "__main__":
  134. # 时间设置
  135. # now_time = datetime.datetime.now()
  136. # pre_time = now_time + dateutil.relativedelta.relativedelta(days=-1)# 前一日
  137. # end_time=datetime.datetime.strftime(now_time,"%Y-%m-%d 00:00:00")
  138. # start_time=datetime.datetime.strftime(pre_time,"%Y-%m-%d 00:00:00")
  139. history_run_flag = False # 历史数据运行标志
  140. # 更新sn列表
  141. host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
  142. port=3306
  143. db='qixiang_oss'
  144. user='qixiang_oss'
  145. password='Qixiang2021'
  146. conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  147. cursor = conn.cursor()
  148. cursor.execute("select sn, imei, add_time from app_device")
  149. res = cursor.fetchall()
  150. df_sn = pd.DataFrame(res, columns=['sn', 'imei', 'add_time'])
  151. df_sn = df_sn.reset_index(drop=True)
  152. conn.close();
  153. # 数据库配置
  154. host = 'rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  155. port = 3306
  156. user = 'qx_cas'
  157. password = parse.quote_plus('Qx@123456')
  158. database = 'qx_cas'
  159. db_engine = create_engine(
  160. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  161. user, password, host, port, database
  162. ))
  163. DbSession = sessionmaker(bind=db_engine)
  164. # 运行历史数据配置
  165. df_first_data_time = pd.read_sql("select * from bat_first_data_time", db_engine)
  166. # 日志配置
  167. now_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()).replace(":","_")
  168. log_path = 'log/' + now_str
  169. if not os.path.exists(log_path):
  170. os.makedirs(log_path)
  171. log = Log.Mylog(log_name='saftyCenter_cellvaluediag', log_level = 'info')
  172. log.set_file_hl(file_name='{}/info.log'.format(log_path), log_level='info', size=1024* 1024 * 100)
  173. log.set_file_hl(file_name='{}/error.log'.format(log_path), log_level='error', size=1024* 1024 * 100)
  174. logger = log.get_logger()
  175. logger.info("pid is {}".format(os.getpid()))
  176. # 算法参数
  177. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  178. port=3306
  179. db='safety_platform'
  180. user='qx_read'
  181. password=parse.quote_plus('Qx@123456')
  182. tablename='all_fault_info'
  183. db_res_engine = create_engine(
  184. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  185. user, password, host, port, db
  186. ))
  187. #............................模块运行前,先读取数据库中所有结束时间为0的数据,需要从数据库中读取................
  188. # print("select start_time, end_time, product_id, code, level, info, advice, factory from {}".format(tablename))
  189. 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)
  190. result = result[['start_time', 'end_time', 'product_id', 'code', 'level', 'info', 'advice']]
  191. df_Diag_Ram=result[result['end_time']=='0000-00-00 00:00:00']
  192. #定时任务.......................................................................................................................................................................
  193. scheduler = BlockingScheduler()
  194. scheduler.add_job(fun, 'interval', seconds=120, id='diag_job')
  195. try:
  196. scheduler.start()
  197. except Exception as e:
  198. scheduler.shutdown()
  199. logger.error(str(e))