deploy.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502
  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 LIB.MIDDLE.CellStateEstimation.Common.V1_0_1 import DBDownload as DBDownload
  14. import time, datetime
  15. from pandas.core.frame import DataFrame
  16. from apscheduler.schedulers.blocking import BlockingScheduler
  17. from LIB.MIDDLE.SaftyCenter.DataDiag_Static.DataStatistics import DataSta
  18. from LIB.MIDDLE.SaftyCenter.DataDiag_Static.SC_CtrlSafty import CtrlSafty
  19. from LIB.MIDDLE.SaftyCenter.DataDiag_Static.DiagDataMerge import DiagDataMerge
  20. from LIB.MIDDLE.SaftyCenter.DataDiag_Static.SC_SamplingSafty import SamplingSafty
  21. from LIB.MIDDLE.SaftyCenter.DataDiag_Static import CBMSBatDiag
  22. from LIB.MIDDLE.SaftyCenter.Common import DBDownload as DBDw
  23. from LIB.MIDDLE.SaftyCenter.Common import QX_BatteryParam
  24. from urllib import parse
  25. import pymysql
  26. #...................................电池包电芯安全诊断函数......................................................................................................................
  27. def diag_cal():
  28. task_on=1
  29. global SNnums
  30. # global df_Diag_Ram
  31. global start
  32. global df_sn
  33. # 算法参数
  34. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  35. port=3306
  36. db='safety_platform'
  37. user='qx_algo_rw'
  38. password=parse.quote_plus('qx@123456')
  39. db_engine = create_engine(
  40. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  41. user, password, host, port, db
  42. ))
  43. #............................模块运行前,先读取数据库中所有结束时间为0的数据,需要从数据库中读取................``
  44. # print("select start_time, end_time, product_id, code, level, info, advice, factory from {}".format(tablename))
  45. try:
  46. df_Diag_Ram=pd.read_sql("select start_time, end_time, product_id, code, level, info, advice, Batpos from all_fault_info_copy where end_time='0000-00-00 00:00:00'", db_engine)
  47. finally:
  48. db_engine.dispose()
  49. # df_Diag_Ram=df_Diag_Ram.dropna(axis=1,how='any')
  50. # df_Diag_Ram=df_Diag_Ram.reset_index(drop=True)
  51. #读取结果数据库数据........................................................................................................................................................
  52. host1='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  53. port1=3306
  54. db1='qx_cas'
  55. user1='qx_algo_rw'
  56. password1='qx@123456'
  57. mode=1
  58. tablename1='cellstateestimation_soh'
  59. tablename2='cellstateestimation_uniform_socvoltdiff'
  60. DBRead=DBDownload.DBDownload(host1, port1, db1, user1, password1,mode)
  61. DBRead.connect()
  62. #读取电池当前运营状态.....................................................................................................................................................
  63. host2='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
  64. port2=3306
  65. db2='qixiang_manage'
  66. user2='qx_algo_rw'
  67. password2='qx@123456'
  68. mode=4
  69. tablename3='py_battery'
  70. DBReadOpe=DBDw.DBDownload(host2, port2, db2, user2, password2,mode)
  71. DBReadOpe.connect()
  72. host3='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  73. port3=3306
  74. db3='safety_platform'
  75. user3='qx_algo_rw'
  76. password3='qx@123456'
  77. db_engine = create_engine(
  78. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  79. user3, parse.quote_plus(password3), host3, port3, db3
  80. ))
  81. conn_platform = pymysql.connect(host=host3, port=port3, user=user3, password=password3, database=db3)
  82. cursor_platform = conn_platform.cursor()
  83. #..................................设置时间..........................................................
  84. start=time.time()
  85. end_time=datetime.datetime.now()
  86. start_time=end_time-datetime.timedelta(seconds=900)#15分钟跑一次,一次取15分钟数据
  87. start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
  88. end_time=end_time.strftime('%Y-%m-%d %H:%M:%S')
  89. logger.info(" diag_cal START!")
  90. for i in range(0, len(df_sn)):
  91. print(df_sn.loc[i, 'imei'])
  92. try:
  93. if df_sn.loc[i, 'imei'][5:9] == 'N640':
  94. celltype=1 #6040三元电芯
  95. elif df_sn.loc[i, 'imei'][5:9] == 'N440':
  96. celltype=2 #4840三元电芯
  97. elif df_sn.loc[i, 'imei'][5:9] == 'L660':
  98. celltype=99 # 6060锂电芯
  99. elif df_sn.loc[i, 'imei'][3:5] == 'LX' and df_sn.loc[i, 'imei'][5:9] == 'N750':
  100. celltype=3 #力信 50ah三元电芯
  101. elif df_sn.loc[i, 'imei'][3:5] == 'CL' and df_sn.loc[i, 'imei'][5:9] == 'N750':
  102. celltype=4 #CATL 50ah三元电芯
  103. elif 'TJMCL'in sn: # 金茂
  104. celltype=100 #CATL 50ah三元电芯
  105. else:
  106. logger.info("pid-{} celltype-{} SN: {} SKIP!".format(os.getpid(), "未知", sn))
  107. continue
  108. sn = df_sn.loc[i, 'sn']
  109. factory = df_sn.loc[i, 'factory']
  110. logger.info("pid-{} celltype-{} SN: {} START!".format(os.getpid(), celltype, sn))
  111. # sys.exit()
  112. param=QX_BatteryParam.BatteryInfo(celltype)
  113. #读取原始数据库数据........................................................................................................................................................
  114. dbManager = DBManager.DBManager()
  115. df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
  116. df_bms = df_data['bms']
  117. df_bms=df_bms.dropna(subset=['总电流[A]'])
  118. df_bms=df_bms.reset_index(drop=True)
  119. # with DBRead as DBRead:
  120. df_soh=DBRead.getdata('time_st,sn,soh,cellsoh', tablename=tablename1, sn=sn, timename='time_sp', st=start_time, sp=end_time)
  121. df_uniform=DBRead.getdata('time,sn,cellsoc_diff,cellmin_num,cellmax_num', tablename=tablename2, sn=sn, timename='time', st=start_time, sp=end_time)
  122. # with DBReadOpe as DBReadOpe:
  123. df_OprtnSta=DBReadOpe.getdata('qrcode','status', tablename=tablename3, sn=sn, timename='', st='', sp='',factory='')#取最后一条运营状态
  124. #电池诊断.....................................................................................................................................................................
  125. CellFltInfo=DataFrame(columns=['start_time', 'end_time', 'product_id', 'code', 'level', 'info','advice'])
  126. df_Diag_Ram_sn = df_Diag_Ram.loc[df_Diag_Ram['product_id']==sn]#历史故障
  127. df_Diag_Ram_sn_else = df_Diag_Ram.loc[df_Diag_Ram['product_id']!=sn]#sn之外的故障
  128. CellFltInfo = df_Diag_Ram_sn.drop('Batpos',axis=1)
  129. #获取当前故障电池的历史故障信息↑↑↑↑↑↑↑↑↑↑↑.......................................................................................................................................
  130. if not df_bms.empty:
  131. df_Diag_Batdiag_update_xq=SamplingSafty.main(sn,param,df_bms,CellFltInfo)#采样安全
  132. df_Diag_Batdiag_update_xq2=CtrlSafty.main(sn,param,df_bms,df_Diag_Batdiag_update_xq)#控制安全
  133. batDiag=CBMSBatDiag.BatDiag(sn,celltype,df_bms, df_soh, df_uniform, df_Diag_Batdiag_update_xq2)#鹏飞计算
  134. df_Diag_Batdiag_update=batDiag.diag()
  135. # df_Diag_Batdiag_update=BatDiag.diag()
  136. else:
  137. df_Diag_Batdiag_update_xq=DataFrame(columns=['start_time','end_time','product_id','code','level','info','advice','Batpos'])
  138. df_Diag_Batdiag_update_xq2=DataFrame(columns=['start_time','end_time','product_id','code','level','info','advice','Batpos'])
  139. df_Diag_Batdiag_update=DataFrame(columns=['start_time','end_time','product_id','code','level','info','advice','Batpos'])
  140. df_Diag_Ram_add,df_Diag_Ram_Update=DiagDataMerge.DetaMerge(df_Diag_Ram_sn,df_Diag_Batdiag_update,df_OprtnSta,df_Diag_Ram_sn_else)
  141. # df_Diag_Ram.to_csv('df_Diag_Ram.csv')
  142. # df_Diag_Ram_add.to_csv('df_Diag_Ram_add.csv')
  143. # df_Diag_Ram_Update.to_csv('df_Diag_Ram_add.csv')
  144. if len(df_Diag_Ram_add) > 0:#新增故障
  145. df_Diag_Ram_add.columns = ['start_time', 'end_time', 'product_id', 'code', 'level', 'info','advice', 'Batpos']
  146. df_Diag_Ram_add['factory'] = factory
  147. df_Diag_Ram_add['add_time'] = datetime.datetime.now()
  148. df_Diag_Ram_add.to_sql("all_fault_info_copy",con=db_engine, if_exists="append",index=False)
  149. df_Diag_Ram_add.to_csv(r'D:\Work\Code_write\data_analyze_platform\USER\01Screen_Problem\result_add.csv',index=False,encoding='GB18030')
  150. if len(df_Diag_Ram_Update) > 0:#更改故障
  151. df_Diag_Ram_Update = df_Diag_Ram_Update.reset_index(drop=True)
  152. try:
  153. logger.info(df_Diag_Ram_Update)
  154. for i in range(0,len(df_Diag_Ram_Update)):
  155. sql = '''
  156. update all_fault_info_copy set update_time='{}', end_time='{}', Batpos={} where product_id='{}' and code={} and start_time='{}'
  157. '''.format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), df_Diag_Ram_Update.loc[i,'end_time'], df_Diag_Ram_Update.loc[i, 'Batpos'],
  158. df_Diag_Ram_Update.loc[i,'product_id'], df_Diag_Ram_Update.loc[i,'code'],
  159. df_Diag_Ram_Update.loc[i,'start_time'])
  160. cursor_platform.execute(sql)
  161. conn_platform.commit()
  162. except:
  163. logger.error(traceback.format_exc)
  164. logger.error(u"{} :{},{} 任务运行错误\n".format(sn,start_time,end_time), exc_info=True)
  165. # df_Diag_Ram_Update_change.to_csv(r'D:\Work\Code_write\data_analyze_platform\USER\01Screen_Problemm\result_change.csv',index=False,encoding='GB18030')
  166. end=time.time()
  167. logger.info("pid-{} celltype-{} SN: {} DONE!".format(os.getpid(), celltype, sn))
  168. except Exception as e :
  169. logger.error(traceback.format_exc)
  170. logger.error(str(e))
  171. logger.error(u"{} :{},{} 任务运行错误\n".format(sn,start_time,end_time), exc_info=True)
  172. DBReadOpe.close()
  173. DBRead.close()
  174. cursor_platform.close()
  175. conn_platform.close()
  176. db_engine.dispose()
  177. logger.info(" diag_cal Done!")
  178. task_on=0
  179. #.................................统计程序...............................
  180. def DaTa_Sta_Week_Task():
  181. task_on=1
  182. factory_info=['骑享','金茂换电']
  183. all_period_fault_info=DataFrame(columns=['factory','week','level1_count','level2_count','level3_count','level4_count','level5_count','solve_rate'])
  184. #............................获取数据................................
  185. toweek='Week'+time.strftime('%W')
  186. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  187. port=3306
  188. db='safety_platform'
  189. user='qx_algo_rw'
  190. password='qx@123456'
  191. mode=2
  192. tablename1='all_fault_info_copy'
  193. db_engine = create_engine(
  194. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  195. user, parse.quote_plus(password), host, port, db
  196. ))
  197. try:
  198. logger.info("DaTa_Sta_Week_Task START!")
  199. DBRead=DBDw.DBDownload(host, port, db, user, password,mode)
  200. with DBRead as DBRead:
  201. df_fltinfo=DBRead.getdata('product_id','level','code','start_time','end_time','batpos','factory',tablename=tablename1,factory='',sn='',timename='',st='',sp='')#dbdownload经过了改编
  202. for j in range(0,len(factory_info)):
  203. df_fltinfo=df_fltinfo[df_fltinfo['factory']==factory_info[j]]
  204. #............................获取时间................................
  205. end_time=datetime.datetime.now()
  206. # end_time=datetime.datetime.strptime(end_time,'%Y-%m-%d')
  207. start_time_week=end_time-datetime.timedelta(days=7)
  208. start_time_week=start_time_week.strftime('%Y-%m-%d')
  209. end_time=end_time.strftime('%Y-%m-%d')
  210. FltAlarmInfo,Celltype=DataSta.SaftyWarningSta(df_fltinfo,start_time_week,end_time,factory_info[j])
  211. FaultLvlCount=DataSta.WeekInfoSta(df_fltinfo,start_time_week,end_time)
  212. for i in range(1,6):
  213. if not FaultLvlCount[FaultLvlCount['level']==i]['product_id'].empty:
  214. all_period_fault_info.loc[j,'level'+str(i)+'_count']=int(FaultLvlCount[FaultLvlCount['level']==i]['product_id'].values)
  215. else:
  216. all_period_fault_info.loc[j,'level'+str(i)+'_count']=int(0)
  217. all_period_fault_info.loc[j,'factory']=factory_info[j]
  218. all_period_fault_info.loc[j,'week']=toweek
  219. all_period_fault_info.loc[j,'solve_rate']=FltAlarmInfo.loc[0,'OprationManageRate']
  220. all_period_fault_info.fillna(0,inplace=False)
  221. if not all_period_fault_info.empty:
  222. all_period_fault_info.loc[j].to_sql('all_period_fault_info', db_engine, if_exists='append', index=False)
  223. logger.info("DaTa_Sta_Week_Task DONE!")
  224. except Exception as e:
  225. logger.error(traceback.format_exc)
  226. logger.error(u" 任务运行错误\n".format(), exc_info=True)
  227. finally:
  228. db_engine.dispose()
  229. task_on=0
  230. # all_period_fault_info.to_csv('all_period_fault_info.csv')
  231. def DaTa_Sta_Minutes_Task():
  232. task_on=1
  233. factory_info=['骑享','金茂换电']
  234. #............................获取数据................................
  235. host='172.16.121.236'
  236. port=3306
  237. db='fastfun'
  238. user='readonly'
  239. password='Fast1234'
  240. mode=3
  241. tablename1='ff_battery_accum'
  242. tablename2='ff_location'
  243. DBRead=DBDw.DBDownload(host, port, db, user, password,mode)
  244. with DBRead as DBRead:
  245. df_last_accum=DBRead.getdata('devcode','dsg_phaccum','dsg_ahaccum',tablename=tablename1,factory='',sn='',timename='',st='',sp='')#dbdownload经过了改编
  246. df_last_pos=DBRead.getdata('devcode','latitude','longitude',tablename=tablename2,factory='',sn='',timename='',st='',sp='')#dbdownload经过了改编
  247. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  248. port=3306
  249. db='qx_cas'
  250. user='qx_algo_rw'
  251. password='qx@123456'
  252. mode=3
  253. tablename2='bat_first_data_time'
  254. DBRead=DBDw.DBDownload(host, port, db, user, password,mode)
  255. with DBRead as DBRead:
  256. df_FirstDataTime=DBRead.getdata('sn','first_data_time',tablename=tablename2,factory='',sn='',timename='',st='',sp='')#dbdownload经过了改编
  257. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  258. port=3306
  259. db='safety_platform'
  260. user='qx_algo_rw'
  261. password='qx@123456'
  262. mode=2
  263. tablename1='all_fault_info_copy'
  264. db_engine = create_engine(
  265. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  266. user, parse.quote_plus(password), host, port, db
  267. ))
  268. DBRead=DBDw.DBDownload(host, port, db, user, password,mode)
  269. #............................获取时间................................
  270. end_time=datetime.datetime.now()
  271. # end_time=datetime.datetime.strptime(end_time,'%Y-%m-%d')
  272. start_time=end_time-datetime.timedelta(days=1)
  273. start_time=start_time.strftime('%Y-%m-%d')
  274. end_time=end_time.strftime('%Y-%m-%d')
  275. #............................执行程序................................
  276. all_statistic_info=DataFrame(columns=['factory','total_alarm','alarm_total_today','alarm_not_close_today','alarm_close_today','alarm_uregent_total_today','alarm_uregent_close_today','alarm_uregent_not_close_today','run_time_total','dischrg_total','odo_total','max_dischrg_one','max_runtime_one','max_cycle_one','max_odo_one','alarm_close_total','alarm_total','cell_type','cell_type_count','cell_safety_risk_count','data_safety_risk_count','status_safety_risk_count','hv_safety_risk_count','system_safety_risk_count','sample_safety_risk_count','controller_safety_risk_count','design_safety_risk_count'])
  277. for j in range(0,len(factory_info)):
  278. with DBRead as DBRead:
  279. df_fltinfo=DBRead.getdata('product_id','level','code','start_time','batpos',tablename=tablename1,factory=factory_info[j],sn='',timename='',st='',sp='')#dbdownload经过了改编
  280. #............................执行程序................................
  281. FltAlarmInfo,Celltype=DataSta.SaftyWarningSta(df_fltinfo,start_time,end_time,factory_info[j])
  282. SatftyCount=DataSta.SftyWrngClsfy(df_fltinfo)
  283. MaxAccumAh,TotalAccumAh,MaxCycle,MaxRunningHour,TotalRunHour=DataSta.AccumInfo(df_last_accum,df_FirstDataTime,end_time,factory_info[j])
  284. all_location_info=DataSta.FltBatPosition(df_last_pos,df_fltinfo,factory_info[j])
  285. all_statistic_info.loc[j,'factory']=factory_info[j]
  286. all_statistic_info.loc[j,'total_alarm']=FltAlarmInfo.loc[0,'SftyPlt_Data_Total']
  287. all_statistic_info.loc[j,'alarm_total_today']=FltAlarmInfo.loc[0,'SftyPlt_Data_day']
  288. all_statistic_info.loc[j,'alarm_close_today']=FltAlarmInfo.loc[0,'CS_Warning_day_Finish_Count']
  289. all_statistic_info.loc[j,'alarm_not_close_today']=FltAlarmInfo.loc[0,'SftyPlt_Data_day']-FltAlarmInfo.loc[0,'CS_Warning_day_Finish_Count']
  290. all_statistic_info.loc[j,'alarm_uregent_total_today']=FltAlarmInfo.loc[0,'SftyPlt_EmgcyData_day']
  291. all_statistic_info.loc[j,'alarm_uregent_close_today']=FltAlarmInfo.loc[0,'SftyPlt_EmgcyData_day_Finish_Count']
  292. all_statistic_info.loc[j,'alarm_uregent_not_close_today']=FltAlarmInfo.loc[0,'SftyPlt_EmgcyData_day']-FltAlarmInfo.loc[0,'SftyPlt_EmgcyData_day_Finish_Count']
  293. all_statistic_info.loc[j,'run_time_total']=TotalRunHour
  294. all_statistic_info.loc[j,'dischrg_total']=TotalAccumAh
  295. all_statistic_info.loc[j,'odo_total']=0
  296. all_statistic_info.loc[j,'max_dischrg_one']=MaxAccumAh
  297. all_statistic_info.loc[j,'max_runtime_one']=MaxRunningHour
  298. all_statistic_info.loc[j,'max_cycle_one']=MaxCycle
  299. all_statistic_info.loc[j,'max_odo_one']=0
  300. all_statistic_info.loc[j,'alarm_close_total']=FltAlarmInfo.loc[0,'CS_Warning_Total_Finish_Count']
  301. all_statistic_info.loc[j,'alarm_total']=FltAlarmInfo.loc[0,'SftyPlt_Data_Total']
  302. CellType=Celltype.columns.tolist()
  303. CellType=','.join(CellType)
  304. all_statistic_info.loc[0,'cell_type']=str(CellType)
  305. CellTypeCount=Celltype.loc[0].tolist()
  306. CellTypeCount=[str(x) for x in CellTypeCount]
  307. CellTypeCount=','.join(CellTypeCount)
  308. all_statistic_info.loc[j,'cell_type_count']=str(CellTypeCount)
  309. all_statistic_info.loc[j,'cell_safety_risk_count']=SatftyCount.loc[0,'CellSaftyCount']
  310. all_statistic_info.loc[j,'data_safety_risk_count']=SatftyCount.loc[0,'DataSaftyCodeCount']
  311. all_statistic_info.loc[j,'status_safety_risk_count']=SatftyCount.loc[0,'StateSaftyCodeCount']
  312. all_statistic_info.loc[j,'hv_safety_risk_count']=SatftyCount.loc[0,'HvSaftyCodeCount']
  313. all_statistic_info.loc[j,'system_safety_risk_count']=SatftyCount.loc[0,'SysSaftyCodeCount']
  314. all_statistic_info.loc[j,'sample_safety_risk_count']=SatftyCount.loc[0,'SamplingSatyCount']
  315. all_statistic_info.loc[j,'controller_safety_risk_count']=SatftyCount.loc[0,'CtrlSaftyCodeCount']
  316. all_statistic_info.loc[j,'design_safety_risk_count']=SatftyCount.loc[0,'DsnSaftyCodeCount']
  317. # all_statistic_info.to_csv('all_statistic_info.csv')
  318. #
  319. try:
  320. logger.info("DaTa_Sta_Minutes_Task START!")
  321. # 更新统计信息
  322. conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  323. cursor = conn.cursor()
  324. sql = ''' update all_statistic_info set update_time='{}', total_alarm={}, alarm_total_today={}, alarm_close_today={}, alarm_not_close_today={},
  325. alarm_uregent_total_today={}, alarm_uregent_close_today={},alarm_uregent_not_close_today={},run_time_total={},dischrg_total={},
  326. odo_total={},max_dischrg_one={},max_runtime_one={},max_cycle_one={},max_odo_one={},alarm_close_total={},alarm_total={},cell_type='{}',
  327. cell_type_count='{}',cell_safety_risk_count={}, data_safety_risk_count={},status_safety_risk_count={},hv_safety_risk_count={},
  328. system_safety_risk_count={},sample_safety_risk_count={},controller_safety_risk_count={},design_safety_risk_count={}
  329. where factory='{}'
  330. '''.format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), all_statistic_info.loc[j,'total_alarm'], all_statistic_info.loc[j,'alarm_total_today'],all_statistic_info.loc[j,'alarm_close_today'],
  331. all_statistic_info.loc[j,'alarm_not_close_today'],all_statistic_info.loc[j,'alarm_uregent_total_today'],all_statistic_info.loc[j,'alarm_uregent_close_today'],
  332. all_statistic_info.loc[j,'alarm_uregent_not_close_today'],all_statistic_info.loc[j,'run_time_total'],all_statistic_info.loc[j,'dischrg_total'],
  333. all_statistic_info.loc[j,'odo_total'],all_statistic_info.loc[j,'max_dischrg_one'],all_statistic_info.loc[j,'max_runtime_one'],
  334. all_statistic_info.loc[j,'max_cycle_one'],all_statistic_info.loc[j,'max_odo_one'],all_statistic_info.loc[j,'alarm_close_total'],
  335. all_statistic_info.loc[j,'alarm_total'],all_statistic_info.loc[j,'cell_type'],all_statistic_info.loc[j,'cell_type_count'],
  336. all_statistic_info.loc[j,'cell_safety_risk_count'],all_statistic_info.loc[j,'data_safety_risk_count'],all_statistic_info.loc[j,'status_safety_risk_count'],
  337. all_statistic_info.loc[j,'hv_safety_risk_count'],all_statistic_info.loc[j,'system_safety_risk_count'],all_statistic_info.loc[j,'sample_safety_risk_count'],
  338. all_statistic_info.loc[j,'controller_safety_risk_count'],all_statistic_info.loc[j,'design_safety_risk_count'],all_statistic_info.loc[j,'factory'])
  339. cursor.execute(sql)
  340. conn.commit()
  341. # 更新故障位置信息
  342. if not all_location_info.empty:
  343. sql = "delete from all_fault_location_info where factory='{}'".format(all_statistic_info.loc[j,'factory'])
  344. cursor.execute(sql)
  345. all_location_info.to_sql('all_fault_location_info', db_engine, if_exists='append', index=False)
  346. conn.commit()
  347. logger.info("DaTa_Sta_Minutes_Task DONE!")
  348. except:
  349. logger.error(traceback.format_exc)
  350. logger.error(u"{},{} 任务运行错误\n".format(start_time,end_time), exc_info=True)
  351. finally:
  352. conn.close();
  353. db_engine.dispose();
  354. task_on=0
  355. if __name__ == "__main__":
  356. # # 时间设置
  357. # now_time = datetime.datetime.now()
  358. # pre_time = now_time + dateutil.relativedelta.relativedelta(hours=-1)#上小时时间
  359. # end_time=datetime.datetime.strftime(now_time,"%Y-%m-%d %H:00:00")
  360. # start_time=datetime.datetime.strftime(pre_time,"%Y-%m-%d %H:00:00")
  361. # history_run_flag = False # 历史数据运行标志
  362. # 更新sn列表
  363. host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
  364. port=3306
  365. db='qixiang_oss'
  366. user='qx_algo_rw'
  367. password='qx@123456'
  368. conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  369. cursor = conn.cursor()
  370. cursor.execute("select sn, imei, add_time from app_device where status in (1,2,3)")
  371. res = cursor.fetchall()
  372. df_sn = pd.DataFrame(res, columns=['sn', 'imei', 'add_time'])
  373. df_sn = df_sn.reset_index(drop=True)
  374. cursor.close()
  375. conn.close();
  376. df_sn['factory'] = '骑享'
  377. db = 'qx_cas'
  378. conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  379. cursor = conn.cursor()
  380. cursor.execute("select sn, factory from sn_list")
  381. res = cursor.fetchall()
  382. df_sn2 = pd.DataFrame(res, columns=['sn', 'factory'])
  383. df_sn2['imei'] = ""
  384. df_sn = pd.concat([df_sn, df_sn2], axis=0)
  385. df_sn = df_sn.reset_index(drop=True)
  386. df_sn=df_sn[df_sn['sn']=='PK504B00100004103']
  387. df_sn.reset_index(inplace=True,drop=True)
  388. # # 数据库配置
  389. # host = 'rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  390. # port = 3306
  391. # user = 'qx_cas'
  392. # password = parse.quote_plus('Qx@123456')
  393. # database = 'qx_cas'
  394. # db_engine = create_engine(
  395. # "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  396. # user, password, host, port, database
  397. # ))
  398. # DbSession = sessionmaker(bind=db_engine)
  399. # # 运行历史数据配置
  400. # df_first_data_time = pd.read_sql("select * from bat_first_data_time", db_engine)
  401. # 日志配置
  402. now_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()).replace(":","_")
  403. log_path = 'log/' + now_str
  404. if not os.path.exists(log_path):
  405. os.makedirs(log_path)
  406. log = Log.Mylog(log_name='saftyCenter_DataSta&Static', log_level = 'info')
  407. log.set_file_hl(file_name='{}/info.log'.format(log_path), log_level='info', size=1024* 1024 * 100)
  408. log.set_file_hl(file_name='{}/error.log'.format(log_path), log_level='error', size=1024* 1024 * 100)
  409. logger = log.get_logger()
  410. logger.info("pid is {}".format(os.getpid()))
  411. # 算法参数
  412. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  413. port=3306
  414. db='safety_platform'
  415. user='qx_algo_rw'
  416. password=parse.quote_plus('qx@123456')
  417. tablename='all_fault_info_copy'
  418. db_engine = create_engine(
  419. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  420. user, password, host, port, db
  421. ))
  422. #............................模块运行前,先读取数据库中所有结束时间为0的数据,需要从数据库中读取................``
  423. # print("select start_time, end_time, product_id, code, level, info, advice, factory from {}".format(tablename))
  424. try:
  425. df_Diag_Ram=pd.read_sql("select start_time, end_time, product_id, code, level, info, advice, Batpos from all_fault_info_copy", db_engine)
  426. finally:
  427. db_engine.dispose()
  428. # result = result[['start_time', 'end_time', 'product_id', 'code', 'level', 'info', 'advice']]
  429. # df_Diag_Ram=result[result['end_time']=='0000-00-00 00:00:00']
  430. global task_on
  431. task_on=0
  432. diag_cal()
  433. # DaTa_Sta_Minutes_Task()
  434. # DaTa_Sta_Week_Task()
  435. #定时任务.......................................................................................................................................................................
  436. scheduler = BlockingScheduler()
  437. if task_on==0:
  438. scheduler.add_job(diag_cal, 'interval', seconds=900, id='diag_job')
  439. scheduler.add_job(DaTa_Sta_Week_Task, 'interval',start_date='2021-11-15 08:00:00', days=7, id='Week_Task')
  440. scheduler.add_job(DaTa_Sta_Minutes_Task, 'interval', seconds=180, id='Minutes_Task')
  441. try:
  442. scheduler.start()
  443. except Exception as e:
  444. scheduler.shutdown()
  445. logger.error(str(e))