deploy.py 30 KB

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