deploy.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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.SaftyCenter.Common import FeiShuData
  14. from LIB.MIDDLE.SaftyCenter.Common import DBDownload
  15. import time, datetime
  16. from pandas.core.frame import DataFrame
  17. from apscheduler.schedulers.blocking import BlockingScheduler
  18. from LIB.MIDDLE.SaftyCenter.DataSta.DataStatistics import DataSta
  19. from urllib import parse
  20. import pymysql
  21. from LIB.BACKEND import DBManager
  22. #............................主程序...................................
  23. def Week_Task():
  24. all_period_fault_info=DataFrame(columns=['factory','week','level1_count','level2_count','level3_count','level4_count','level5_count','solve_rate'])
  25. #............................获取数据................................
  26. toweek='Week'+time.strftime('%W')
  27. CS_Data=FeiShuData.getFeiShuDATA()
  28. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  29. port=3306
  30. db='safety_platform'
  31. user='qx_read'
  32. password='Qx@123456'
  33. mode=2
  34. tablename1='all_fault_info'
  35. db_engine = create_engine(
  36. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  37. user, parse.quote_plus(password), host, port, db
  38. ))
  39. try:
  40. DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
  41. with DBRead as DBRead:
  42. df_fltinfo=DBRead.getdata('product_id','level','code','start_time',tablename=tablename1,factory='骑享',sn='',timename='',st='',sp='')#dbdownload经过了改编
  43. #............................获取时间................................
  44. end_time=datetime.datetime.now()
  45. # end_time=datetime.datetime.strptime(end_time,'%Y-%m-%d')
  46. start_time=end_time-datetime.timedelta(days=7)
  47. start_time=start_time.strftime('%Y-%m-%d')
  48. end_time=end_time.strftime('%Y-%m-%d')
  49. FltAlarmInfo,Celltype=DataSta.SaftyWarningSta(CS_Data,df_fltinfo,start_time,end_time)
  50. FaultLvlCount=DataSta.WeekInfoSta(df_fltinfo,start_time,end_time)
  51. for i in range(1,6):
  52. if not FaultLvlCount[FaultLvlCount['level']==i]['product_id'].empty:
  53. all_period_fault_info.loc[0,'level'+str(i)+'_count']=int(FaultLvlCount[FaultLvlCount['level']==i]['product_id'].values)
  54. else:
  55. all_period_fault_info.loc[0,'level'+str(i)+'_count']=int(0)
  56. all_period_fault_info.loc[0,'factory']='骑享'
  57. all_period_fault_info.loc[0,'week']=toweek
  58. all_period_fault_info.loc[0,'solve_rate']=FltAlarmInfo.loc[0,'OprationManageRate']
  59. all_period_fault_info.fillna(0,inplace=False)
  60. all_period_fault_info.to_sql('all_period_fault_info', db_engine, if_exists='append', index=False)
  61. except Exception as e:
  62. logger.error(traceback.format_exc)
  63. logger.error(u" 任务运行错误\n".format(), exc_info=True)
  64. def Minutes_Task():
  65. #............................获取数据................................
  66. host='172.16.121.236'
  67. port=3306
  68. db='fastfun'
  69. user='readonly'
  70. password='Fast1234'
  71. mode=3
  72. tablename1='ff_battery_accum'
  73. DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
  74. with DBRead as DBRead:
  75. df_last_accum=DBRead.getdata('devcode','dsg_phaccum','dsg_ahaccum',tablename=tablename1,factory='',sn='',timename='',st='',sp='')#dbdownload经过了改编
  76. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  77. port=3306
  78. db='qx_cas'
  79. user='qx_read'
  80. password='Qx@123456'
  81. mode=3
  82. tablename2='bat_first_data_time'
  83. DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
  84. with DBRead as DBRead:
  85. df_FirstDataTime=DBRead.getdata('sn','first_data_time',tablename=tablename2,factory='',sn='',timename='',st='',sp='')#dbdownload经过了改编
  86. CS_Data=FeiShuData.getFeiShuDATA()
  87. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  88. port=3306
  89. db='safety_platform'
  90. user='qx_read'
  91. password='Qx@123456'
  92. mode=2
  93. tablename1='all_fault_info'
  94. # db_engine = create_engine(
  95. # "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  96. # user, parse.quote_plus(password), host, port, db
  97. # ))
  98. DBRead=DBDownload.DBDownload(host, port, db, user, password,mode)
  99. with DBRead as DBRead:
  100. df_fltinfo=DBRead.getdata('product_id','level','code','start_time',tablename=tablename1,factory='骑享',sn='',timename='',st='',sp='')#dbdownload经过了改编
  101. #............................获取时间................................
  102. end_time=datetime.datetime.now()
  103. # end_time=datetime.datetime.strptime(end_time,'%Y-%m-%d')
  104. start_time=end_time-datetime.timedelta(days=1)
  105. start_time=start_time.strftime('%Y-%m-%d')
  106. end_time=end_time.strftime('%Y-%m-%d')
  107. #............................执行程序................................
  108. FltAlarmInfo,Celltype=DataSta.SaftyWarningSta(CS_Data,df_fltinfo,start_time,end_time)
  109. SatftyCount=DataSta.SftyWrngClsfy(df_fltinfo)
  110. MaxAccumAh,TotalAccumAh,MaxCycle,MaxRunningHour,TotalRunHour=DataSta.AccumInfo(df_last_accum,df_FirstDataTime,end_time)
  111. 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'])
  112. all_statistic_info.loc[0,'factory']='骑享'
  113. all_statistic_info.loc[0,'total_alarm']=FltAlarmInfo.loc[0,'SftyPlt_Data_Total']
  114. all_statistic_info.loc[0,'alarm_total_today']=FltAlarmInfo.loc[0,'SftyPlt_Data_day']
  115. all_statistic_info.loc[0,'alarm_close_today']=FltAlarmInfo.loc[0,'CS_Warning_day_Finish_Count']
  116. all_statistic_info.loc[0,'alarm_not_close_today']=FltAlarmInfo.loc[0,'SftyPlt_Data_day']-FltAlarmInfo.loc[0,'CS_Warning_day_Finish_Count']
  117. all_statistic_info.loc[0,'alarm_uregent_total_today']=FltAlarmInfo.loc[0,'SftyPlt_EmgcyData_day']
  118. all_statistic_info.loc[0,'alarm_uregent_close_today']=FltAlarmInfo.loc[0,'SftyPlt_EmgcyData_day_Finish_Count']
  119. all_statistic_info.loc[0,'alarm_uregent_not_close_today']=FltAlarmInfo.loc[0,'SftyPlt_EmgcyData_day']-FltAlarmInfo.loc[0,'SftyPlt_EmgcyData_day_Finish_Count']
  120. all_statistic_info.loc[0,'run_time_total']=TotalRunHour
  121. all_statistic_info.loc[0,'dischrg_total']=TotalAccumAh
  122. all_statistic_info.loc[0,'odo_total']=0
  123. all_statistic_info.loc[0,'max_dischrg_one']=MaxAccumAh
  124. all_statistic_info.loc[0,'max_runtime_one']=MaxRunningHour
  125. all_statistic_info.loc[0,'max_cycle_one']=MaxCycle
  126. all_statistic_info.loc[0,'max_odo_one']=0
  127. all_statistic_info.loc[0,'alarm_close_total']=FltAlarmInfo.loc[0,'CS_Warning_Total_Finish_Count']
  128. all_statistic_info.loc[0,'alarm_total']=FltAlarmInfo.loc[0,'SftyPlt_Data_Total']
  129. CellType=Celltype.columns.tolist()
  130. CellType=','.join(CellType)
  131. all_statistic_info.loc[0,'cell_type']=str(CellType)
  132. CellTypeCount=Celltype.loc[0].tolist()
  133. CellTypeCount=[str(x) for x in CellTypeCount]
  134. CellTypeCount=','.join(CellTypeCount)
  135. all_statistic_info.loc[0,'cell_type_count']=str(CellTypeCount)
  136. all_statistic_info.loc[0,'cell_safety_risk_count']=SatftyCount.loc[0,'CellSaftyCount']
  137. all_statistic_info.loc[0,'data_safety_risk_count']=SatftyCount.loc[0,'DataSaftyCodeCount']
  138. all_statistic_info.loc[0,'status_safety_risk_count']=SatftyCount.loc[0,'StateSaftyCodeCount']
  139. all_statistic_info.loc[0,'hv_safety_risk_count']=SatftyCount.loc[0,'HvSaftyCodeCount']
  140. all_statistic_info.loc[0,'system_safety_risk_count']=SatftyCount.loc[0,'SysSaftyCodeCount']
  141. all_statistic_info.loc[0,'sample_safety_risk_count']=SatftyCount.loc[0,'SamplingSatyCount']
  142. all_statistic_info.loc[0,'controller_safety_risk_count']=SatftyCount.loc[0,'CtrlSaftyCodeCount']
  143. all_statistic_info.loc[0,'design_safety_risk_count']=SatftyCount.loc[0,'DsnSaftyCodeCount']
  144. try:
  145. conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  146. cursor = conn.cursor()
  147. sql = ''' update all_statistic_info set update_time='{}', total_alarm={}, alarm_total_today={}, alarm_close_today={}, alarm_not_close_today={},
  148. alarm_uregent_total_today={}, alarm_uregent_close_today={},alarm_uregent_not_close_today={},run_time_total={},dischrg_total={},
  149. odo_total={},max_dischrg_one={},max_runtime_one={},max_cycle_one={},max_odo_one={},alarm_close_total={},alarm_total={},cell_type='{}',
  150. cell_type_count='{}',cell_safety_risk_count={}, data_safety_risk_count={},status_safety_risk_count={},hv_safety_risk_count={},
  151. system_safety_risk_count={},sample_safety_risk_count={},controller_safety_risk_count={},design_safety_risk_count={}
  152. where factory='{}'
  153. '''.format(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), all_statistic_info.loc[0,'total_alarm'], all_statistic_info.loc[0,'alarm_total_today'],all_statistic_info.loc[0,'alarm_close_today'],
  154. all_statistic_info.loc[0,'alarm_not_close_today'],all_statistic_info.loc[0,'alarm_uregent_total_today'],all_statistic_info.loc[0,'alarm_uregent_close_today'],
  155. all_statistic_info.loc[0,'alarm_uregent_not_close_today'],all_statistic_info.loc[0,'run_time_total'],all_statistic_info.loc[0,'dischrg_total'],
  156. all_statistic_info.loc[0,'odo_total'],all_statistic_info.loc[0,'max_dischrg_one'],all_statistic_info.loc[0,'max_runtime_one'],
  157. all_statistic_info.loc[0,'max_cycle_one'],all_statistic_info.loc[0,'max_odo_one'],all_statistic_info.loc[0,'alarm_close_total'],
  158. all_statistic_info.loc[0,'alarm_total'],all_statistic_info.loc[0,'cell_type'],all_statistic_info.loc[0,'cell_type_count'],
  159. all_statistic_info.loc[0,'cell_safety_risk_count'],all_statistic_info.loc[0,'data_safety_risk_count'],all_statistic_info.loc[0,'status_safety_risk_count'],
  160. all_statistic_info.loc[0,'hv_safety_risk_count'],all_statistic_info.loc[0,'system_safety_risk_count'],all_statistic_info.loc[0,'sample_safety_risk_count'],
  161. all_statistic_info.loc[0,'controller_safety_risk_count'],all_statistic_info.loc[0,'design_safety_risk_count'],'骑享')
  162. cursor.execute(sql)
  163. conn.commit()
  164. conn.close();
  165. except:
  166. logger.error(traceback.format_exc)
  167. logger.error(u"{},{} 任务运行错误\n".format(start_time,end_time), exc_info=True)
  168. conn.close();
  169. if __name__ == "__main__":
  170. # # 时间设置
  171. # now_time = datetime.datetime.now()
  172. # pre_time = now_time + dateutil.relativedelta.relativedelta(hours=-1)#上小时时间
  173. # end_time=datetime.datetime.strftime(now_time,"%Y-%m-%d %H:00:00")
  174. # start_time=datetime.datetime.strftime(pre_time,"%Y-%m-%d %H:00:00")
  175. # history_run_flag = False # 历史数据运行标志
  176. # # 更新sn列表
  177. # host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
  178. # port=3306
  179. # db='qixiang_oss'
  180. # user='qixiang_oss'
  181. # password='Qixiang2021'
  182. # conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  183. # cursor = conn.cursor()
  184. # cursor.execute("select sn, imei, add_time from app_device")
  185. # res = cursor.fetchall()
  186. # df_sn = pd.DataFrame(res, columns=['sn', 'imei', 'add_time'])
  187. # df_sn = df_sn.reset_index(drop=True)
  188. # conn.close();
  189. # # 数据库配置
  190. # host = 'rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  191. # port = 3306
  192. # user = 'qx_cas'
  193. # password = parse.quote_plus('Qx@123456')
  194. # database = 'qx_cas'
  195. # db_engine = create_engine(
  196. # "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  197. # user, password, host, port, database
  198. # ))
  199. # DbSession = sessionmaker(bind=db_engine)
  200. # # 运行历史数据配置
  201. # df_first_data_time = pd.read_sql("select * from bat_first_data_time", db_engine)
  202. # 日志配置
  203. now_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()).replace(":","_")
  204. log_path = 'log/' + now_str
  205. if not os.path.exists(log_path):
  206. os.makedirs(log_path)
  207. log = Log.Mylog(log_name='saftyCenter_DataSta', log_level = 'info')
  208. log.set_file_hl(file_name='{}/info.log'.format(log_path), log_level='info', size=1024* 1024 * 100)
  209. log.set_file_hl(file_name='{}/error.log'.format(log_path), log_level='error', size=1024* 1024 * 100)
  210. logger = log.get_logger()
  211. logger.info("pid is {}".format(os.getpid()))
  212. # # 算法参数
  213. # host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  214. # port=3306
  215. # db='safety_platform'
  216. # user='qx_read'
  217. # password=parse.quote_plus('Qx@123456')
  218. # db_res_engine = create_engine(
  219. # "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  220. # user, password, host, port, db
  221. # ))
  222. # dbManager = DBManager.DBManager()
  223. # charge_count = 0
  224. # drive_count = 0
  225. # stand_count = 0
  226. # for sn in df_sn['sn'].tolist():
  227. Week_Task()
  228. Minutes_Task()
  229. scheduler = BlockingScheduler()
  230. scheduler.add_job(Week_Task, 'interval', days=7, id='Week_Task')
  231. scheduler.add_job(Minutes_Task, 'interval', seconds=300, id='Hour_Task')
  232. try:
  233. logger.info("周期任务 START!")
  234. scheduler.start()
  235. # df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms', 'gps'])
  236. # df_bms = df_data['bms']
  237. # df_gps = df_data['gps']
  238. # charge_count, drive_count, stand_count = status_sta.status_sta(df_bms, df_gps, start_time, charge_count, drive_count, stand_count)
  239. # df_result = pd.DataFrame({'factory':['骑享'], 'time':[start_time], 'charge_count':[charge_count], 'drive_count':[drive_count], 'stand_count':stand_count})
  240. # logger.info("pid-{} SN: {} DONE!".format(os.getpid(), sn))
  241. except:
  242. logger.info("周期任务 ERROR!")
  243. scheduler.shutdown()
  244. logger.error(traceback.format_exc)