deploy - 副本.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248
  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. import CBMSSafetyAlarm
  13. from LIB.MIDDLE.CellStateEstimation.Common 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(df_sn, df_bms_ram, log_name):
  23. # 日志
  24. logger = logging.getLogger()
  25. fh = logging.FileHandler(log_name + ".log", encoding="utf-8",mode="a")
  26. formatter = logging.Formatter("%(asctime)s - %(name)s-%(levelname)s %(message)s")
  27. fh.setFormatter(formatter)
  28. logger.addHandler(fh)
  29. logger.setLevel(logging.INFO)
  30. logger.info("pid is {}".format(os.getpid()))
  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_res_engine = create_engine(
  38. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  39. user2, parse.quote_plus(password2), host2, port2, db2
  40. ))
  41. conn = pymysql.connect(host=host2, port=port2, user=user2, password=password2, database=db2)
  42. cursor = conn.cursor()
  43. 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)
  44. result = result[['start_time', 'end_time', 'product_id', 'code', 'level', 'info', 'advice']]
  45. df_diag_ram=result[(result['end_time']=='0000-00-00 00:00:00') & (result['code']==119)]
  46. df_bms_ram=pd.DataFrame(columns=['time', 'sn', 'packvolt', 'cellvolt', 'celltemp'])
  47. start=time.time()
  48. now_time=datetime.datetime.now()
  49. start_time=now_time-datetime.timedelta(seconds=70)
  50. start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
  51. end_time=now_time.strftime('%Y-%m-%d %H:%M:%S')
  52. for i in range(0, len(df_sn)):
  53. try:
  54. sn = df_sn.loc[i, 'sn']
  55. if 'PK500' in sn:
  56. celltype=1 #6040三元电芯
  57. elif 'PK502' in sn:
  58. celltype=2 #4840三元电芯
  59. elif 'K504B' in sn:
  60. celltype=99 #60ah林磷酸铁锂电芯
  61. elif 'MGMLXN750' in sn:
  62. celltype=3 #力信50ah三元电芯
  63. elif 'MGMCLN750' or 'UD' in sn:
  64. celltype=4 #CATL 50ah三元电芯
  65. else:
  66. print('SN:{},未找到对应电池类型!!!'.format(sn))
  67. continue
  68. logger.info("pid-{} celltype-{} SN: {} START!".format(os.getpid(), celltype, sn))
  69. #读取原始数据库数据........................................................................................................................................................
  70. dbManager = DBManager.DBManager()
  71. df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
  72. df_bms = df_data['bms']
  73. # print(df_bms)
  74. #电池诊断................................................................................................................................................................
  75. df_diag_ram_sn=df_diag_ram[df_diag_ram['product_id']==sn]
  76. df_bms_ram_sn=df_bms_ram[df_bms_ram['sn']==sn]
  77. if df_diag_ram_sn.empty:
  78. if not df_bms.empty:
  79. SafetyAlarm=CBMSSafetyAlarm.SafetyAlarm(sn,celltype,df_bms, df_bms_ram_sn)
  80. df_diag_res, df_bms_res=SafetyAlarm.diag()
  81. #更新bms的ram数据
  82. sn_index=df_bms_ram.loc[df_bms_ram['sn']==sn].index
  83. df_bms_ram=df_bms_ram.drop(index=sn_index)
  84. df_bms_ram=df_bms_ram.append(df_bms_res)
  85. # sn_index=df_diag_ram.loc[df_diag_ram['product_id']==sn].index
  86. # df_diag_ram=df_diag_ram.drop(index=sn_index)
  87. # df_diag_ram=df_diag_ram.append(df_diag_res)
  88. # df_diag_ram.reset_index(inplace=True,drop=True) #重置索引
  89. #当前热失控故障写入数据库
  90. if not df_diag_res.empty:
  91. df_diag_res.columns = ['start_time', 'end_time', 'product_id', 'code', 'level', 'info', 'advice']
  92. df_diag_res['add_time'] = datetime.datetime.now()
  93. df_diag_res['factory'] = '骑享'
  94. df_diag_res.to_sql("all_fault_info",con=db_res_engine, if_exists="append",index=False)
  95. #当前热失控已超过1天变为历史故障并写入数据库,并删除原有数据库中的当前故障和ram中的当前故障
  96. else:
  97. fault_time=datetime.datetime.strptime(df_diag_ram_sn.iloc[-1]['start_time'], '%Y-%m-%d %H:%M:%S')
  98. if (now_time-fault_time).total_seconds()>24*3600:
  99. df_diag_ram_sn['end_time']=end_time
  100. df_diag_ram_sn['Batpos']=1
  101. try:
  102. cursor.execute('''
  103. update all_fault_info set update_time='{}',end_time='{}', Batpos={} where product_id='{}' and end_time='0000-00-00 00:00:00' and code={} and factory='骑享'
  104. '''.format(datetime.datetime.now(), end_time, 1,sn, 119))
  105. conn.commit()
  106. conn.close();
  107. except:
  108. logger.error(traceback.format_exc)
  109. logger.error(u"{} :{},{} 任务运行错误\n".format(sn,start_time,end_time), exc_info=True)
  110. conn.close();
  111. except:
  112. logger.error(traceback.format_exc)
  113. logger.error(u"{} :{},{} 任务运行错误\n".format(sn,start_time,end_time), exc_info=True)
  114. cursor.close()
  115. conn.close()
  116. db_res_engine.dispose()
  117. logger.info("pid-{} Done!".format(os.getpid()))
  118. #...................................................主进程...........................................................................................................
  119. def mainprocess():
  120. global df_bms_ram
  121. global log_path
  122. # 更新sn列表
  123. # host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
  124. # port=3306
  125. # db='qixiang_oss'
  126. # user='qixiang_oss'
  127. # password='Qixiang2021'
  128. # conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  129. # cursor = conn.cursor()
  130. # cursor.execute("select sn, imei, add_time from app_device")
  131. # res = cursor.fetchall()
  132. # df_sn = pd.DataFrame(res, columns=['sn', 'imei', 'add_time'])
  133. # df_sn = df_sn.reset_index(drop=True)
  134. # cursor.close()
  135. # conn.close();
  136. df_sn=pd.DataFrame(columns=['sn'])
  137. df_sn['sn']=['PK504B10100004434', 'MGMCLN750N215N205', 'PK504B10100004447', 'PK504B10100004379', 'PK504B10100004483']
  138. process = 2
  139. pool = multiprocessing.Pool(processes = process)
  140. for i in range(process):
  141. sn_list = df_sn[int(len(df_sn)*i/process):int(len(df_sn)*(i+1)/process)]
  142. sn_list = sn_list.reset_index(drop=True)
  143. log_name = log_path + '/log_' + str(i)
  144. pool.apply_async(diag_cal, (sn_list,df_bms_ram,log_name))
  145. pool.close()
  146. pool.join()
  147. if __name__ == "__main__":
  148. # 时间设置
  149. # now_time = datetime.datetime.now()
  150. # pre_time = now_time + dateutil.relativedelta.relativedelta(days=-1)# 前一日
  151. # end_time=datetime.datetime.strftime(now_time,"%Y-%m-%d 00:00:00")
  152. # start_time=datetime.datetime.strftime(pre_time,"%Y-%m-%d 00:00:00")
  153. history_run_flag = False # 历史数据运行标志
  154. # # 更新sn列表
  155. # host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
  156. # port=3306
  157. # db='qixiang_oss'
  158. # user='qixiang_oss'
  159. # password='Qixiang2021'
  160. # conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  161. # cursor = conn.cursor()
  162. # cursor.execute("select sn, imei, add_time from app_device")
  163. # res = cursor.fetchall()
  164. # df_sn = pd.DataFrame(res, columns=['sn', 'imei', 'add_time'])
  165. # df_sn = df_sn.reset_index(drop=True)
  166. # conn.close();
  167. # 数据库配置
  168. host = 'rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  169. port = 3306
  170. user = 'qx_cas'
  171. password = parse.quote_plus('Qx@123456')
  172. database = 'qx_cas'
  173. db_engine = create_engine(
  174. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  175. user, password, host, port, database
  176. ))
  177. DbSession = sessionmaker(bind=db_engine)
  178. # 运行历史数据配置
  179. df_first_data_time = pd.read_sql("select * from bat_first_data_time", db_engine)
  180. # 日志配置
  181. now_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()).replace(":","_")
  182. log_path = 'log/' + now_str
  183. if not os.path.exists(log_path):
  184. os.makedirs(log_path)
  185. log = Log.Mylog(log_name='batsafetyAlarm', log_level = 'info')
  186. log.set_file_hl(file_name='{}/info.log'.format(log_path), log_level='info', size=1024* 1024 * 100)
  187. log.set_file_hl(file_name='{}/error.log'.format(log_path), log_level='error', size=1024* 1024 * 100)
  188. logger = log.get_logger()
  189. logger.info("pid is {}".format(os.getpid()))
  190. # 算法参数
  191. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  192. port=3306
  193. db='safety_platform'
  194. user='qx_read'
  195. password=parse.quote_plus('Qx@123456')
  196. tablename='all_fault_info'
  197. db_res_engine = create_engine(
  198. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  199. user, password, host, port, db
  200. ))
  201. #ram参数初始化........................................................................................................
  202. df_bms_ram=pd.DataFrame(columns=['time', 'sn', 'packvolt', 'cellvolt', 'celltemp'])
  203. #定时任务.......................................................................................................................................................................
  204. scheduler = BlockingScheduler()
  205. scheduler.add_job(mainprocess, 'interval', seconds=60, id='diag_job')
  206. try:
  207. scheduler.start()
  208. except Exception as e:
  209. scheduler.shutdown()
  210. logger.error(str(e))