deploy.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  1. __author__ = 'lmstack'
  2. #coding=utf-8
  3. import os
  4. import datetime
  5. import pandas as pd
  6. from LIB.BACKEND import DBManager
  7. from sqlalchemy import create_engine
  8. import time, datetime
  9. import traceback
  10. from LIB.MIDDLE.InfoChrgDrive.Charge.V1_0_0.coreV0 import *
  11. from urllib import parse
  12. import pymysql
  13. from apscheduler.schedulers.blocking import BlockingScheduler
  14. import logging
  15. import logging.handlers
  16. #...................................电池包电芯安全诊断函数......................................................................................................................
  17. def info_charge():
  18. # 日志
  19. log_path = 'log/'
  20. if not os.path.exists(log_path):
  21. os.makedirs(log_path)
  22. logger = logging.getLogger("main")
  23. logger.setLevel(logging.DEBUG)
  24. # 根据日期滚动(每天产生1个文件)
  25. fh = logging.handlers.TimedRotatingFileHandler(filename='{}/main_info.log'.format(log_path), when="D", interval=1, backupCount=30,
  26. encoding="utf-8")
  27. formatter = logging.Formatter("%(asctime)s - %(name)s-%(levelname)s %(message)s")
  28. fh.suffix = "%Y-%m-%d_%H-%M-%S"
  29. fh.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}")
  30. fh.setFormatter(formatter)
  31. fh.setLevel(logging.INFO)
  32. logger.addHandler(fh)
  33. fh = logging.handlers.TimedRotatingFileHandler(filename='{}/main_error.log'.format(log_path), when="D", interval=1, backupCount=30,
  34. encoding="utf-8")
  35. formatter = logging.Formatter("%(asctime)s - %(name)s-%(levelname)s %(message)s")
  36. fh.suffix = "%Y-%m-%d_%H-%M-%S"
  37. fh.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}")
  38. fh.setFormatter(formatter)
  39. fh.setLevel(logging.ERROR)
  40. logger.addHandler(fh)
  41. logger.info(os.getpid())
  42. # 更新sn列表
  43. host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
  44. port=3306
  45. db='qixiang_oss'
  46. user='qixiang_oss'
  47. password='Qixiang2021'
  48. conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  49. cursor = conn.cursor()
  50. cursor.execute("select sn, imei, add_time from app_device where status in (1,2,3)")
  51. res = cursor.fetchall()
  52. df_sn = pd.DataFrame(res, columns=['sn', 'imei', 'add_time'])
  53. df_sn = df_sn.reset_index(drop=True)
  54. cursor.close()
  55. conn.close()
  56. SNnums = list(df_sn['sn'])
  57. host2='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  58. port2=3306
  59. db2='safety_platform'
  60. user2='qx_algo_rw'
  61. password2='qx@123456'
  62. db_res_engine = create_engine(
  63. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  64. user2, parse.quote_plus(password2), host2, port2, db2
  65. ))
  66. conn = pymysql.connect(host=host2, port=port2, user=user2, password=password2, database=db2)
  67. cursor = conn.cursor()
  68. df_diag_ram=pd.read_sql("select * from algo_charge_info", db_res_engine)
  69. now_time=datetime.datetime.now()
  70. start_time=now_time-datetime.timedelta(hours=24)
  71. start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
  72. end_time=now_time.strftime('%Y-%m-%d %H:%M:%S')
  73. for sn in SNnums:
  74. try:
  75. logger.info("pid-{} SN: {} START!".format(os.getpid(), sn))
  76. #读取原始数据库数据........................................................................................................................................................
  77. dbManager = DBManager.DBManager()
  78. df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms','gps'])
  79. df_bms = df_data['bms']
  80. df_gps = df_data['gps']
  81. #读取城市天气数据........................................................................................................................................................
  82. gpscity=pd.read_csv('gps.csv')
  83. #调用主函数................................................................................................................................................................
  84. if not df_bms.empty: #BMS数据非空
  85. df_merge=pd.merge(df_bms,df_gps,how='outer',sort=True)
  86. df_merge['sn']=sn
  87. chrg_last=pd.Series()
  88. if not df_diag_ram.empty: #结果库非空
  89. df_diag_ram_sn=df_diag_ram[df_diag_ram['sn']==sn]
  90. if not df_diag_ram_sn.empty:
  91. df_diag_ram_sn['time_end']=list(map(lambda x: datetime.datetime.strptime(str(x),'%Y-%m-%d %H:%M:%S'),list(df_diag_ram_sn['time_end'])))
  92. df_diag_ram_sn = df_diag_ram_sn.sort_values(by = 'time_end')
  93. df_diag_ram_sn.reset_index(inplace=True,drop=True)
  94. chrg_last=df_diag_ram_sn.iloc[-1]
  95. time_end=chrg_last['time_end']
  96. df_diag_new,df_diag_change=pro_output(df_merge,sn,gpscity,chrg_last)
  97. kmeans1 = joblib.load('kmeans1.pkl')
  98. kmeans2 = joblib.load('kmeans2.pkl')
  99. kmeans3 = joblib.load('kmeans3.pkl')
  100. df_diag_new=prediction(df_diag_new,kmeans1,kmeans2,kmeans3)
  101. df_diag_change=prediction(df_diag_change,kmeans1,kmeans2,kmeans3)
  102. if not df_diag_change.empty: #需变更的结果非空
  103. cursor.execute("DELETE FROM algo_charge_info WHERE time_end = '{}' and sn='{}'".format(time_end,sn))
  104. df_diag_change.to_sql("algo_charge_info",con=db_res_engine, if_exists="append",index=False)
  105. logger.info(u"{} 更新成功!!!\n".format(sn), exc_info=True)
  106. #新增结果存入结果库.....................................................................
  107. if not df_diag_new.empty: #需新增的结果非空
  108. df_diag_new.to_sql("algo_charge_info",con=db_res_engine, if_exists="append",index=False)
  109. logger.info(u"{} 写入成功!!!\n".format(sn), exc_info=True)
  110. except Exception as e:
  111. logger.error(u"{} :{},{} 任务运行错误\n".format(sn,start_time,end_time), exc_info=True)
  112. logger.error(traceback.format_exc)
  113. cursor.close()
  114. conn.close()
  115. if __name__ == "__main__":
  116. info_charge()
  117. #定时任务.......................................................................................................................................................................
  118. scheduler = BlockingScheduler()
  119. scheduler.add_job(info_charge, 'interval', hours=24)
  120. try:
  121. scheduler.start()
  122. except Exception as e:
  123. scheduler.shutdown()
  124. print(e)