deploy_soc.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. __author__ = 'ERIC'
  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. from LIB.MIDDLE.PingFeng.SOC.V1_0_0 import soc
  9. import datetime
  10. import traceback
  11. from urllib import parse
  12. import pymysql
  13. from apscheduler.schedulers.blocking import BlockingScheduler
  14. import logging
  15. import logging.handlers
  16. import re
  17. #...................................电池包SOC计算......................................................................................................................
  18. def SOC_cal():
  19. now_time=datetime.datetime.now()
  20. start_time=now_time-datetime.timedelta(seconds=300)
  21. start_time=start_time.strftime('%Y-%m-%d %H:%M:%S')
  22. end_time=now_time.strftime('%Y-%m-%d %H:%M:%S')
  23. #数据库配置
  24. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  25. port=3306
  26. db='safety_platform'
  27. user='qx_algo_rw'
  28. password='qx@123456'
  29. db_res_engine = create_engine(
  30. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  31. user, parse.quote_plus(password), host, port, db
  32. ))
  33. for i in range(0, len(df_sn)):
  34. factory = "骑享"
  35. sn = df_sn.loc[i, 'sn']
  36. try:
  37. if df_sn.loc[i, 'imei'][5:9] == 'N640':
  38. celltype=1 #6040三元电芯
  39. elif df_sn.loc[i, 'imei'][5:9] == 'N440':
  40. celltype=2 #4840三元电芯
  41. elif df_sn.loc[i, 'imei'][5:9] == 'L660':
  42. celltype=99 # 6060锂电芯
  43. elif df_sn.loc[i, 'imei'][3:5] == 'LX' and df_sn.loc[i, 'imei'][5:9] == 'N750':
  44. celltype=3 #力信 50ah三元电芯
  45. elif df_sn.loc[i, 'imei'][3:5] == 'CL' and df_sn.loc[i, 'imei'][5:9] == 'N750':
  46. celltype=4 #CATL 50ah三元电芯
  47. elif df_sn.loc[i, 'imei'][3:9] == 'CLL128':
  48. celltype=100 # 重卡
  49. factory = "金茂换电"
  50. elif df_sn.loc[i, 'imei'][0:6] == 'SPFPFL':
  51. celltype=200#储能电站
  52. factory = "平峰"
  53. else:
  54. logger.info("pid-{} celltype-{} SN: {} SKIP!".format(os.getpid(), "未知", sn))
  55. continue
  56. #读取原始数据库数据........................................................................................................................................................
  57. dbManager = DBManager.DBManager()
  58. df_data = dbManager.get_data(sn=sn, start_time=start_time, end_time=end_time, data_groups=['bms'])
  59. df_bms = df_data['bms']
  60. #电池诊断................................................................................................................................................................
  61. if not df_bms.empty:
  62. logger.info("pid-{} celltype-{} SN: {} START!".format(os.getpid(), celltype, sn))
  63. SOC_result=soc.soc_test(sn,df_bms)
  64. SOC_result.columns=['sn','soc','time']
  65. SOC_result.reset_index(inplace=True,drop=True)
  66. #新增故障筛选并存入数据库.....................................................................
  67. if not SOC_result.empty: #新增写入数据库
  68. SOC_result.to_sql('pingfeng_soc_cal',con=db_res_engine, if_exists='append',index=False)
  69. logger.info("算法运行完成,结果入库")
  70. else:
  71. logger.info("算法运行完成,无结果入库")
  72. else:
  73. logger.info("pid-{} celltype-{} SN: {} 无数据无需运算".format(os.getpid(), celltype, sn))
  74. except Exception as e:
  75. logger.error(traceback.format_exc)
  76. logger.error(u"{} :{},{} 任务运行错误\n".format(sn,start_time,end_time), exc_info=True)
  77. if __name__ == "__main__":
  78. # 时间设置
  79. # now_time = datetime.datetime.now()
  80. # pre_time = now_time + dateutil.relativedelta.relativedelta(days=-1)# 前一日
  81. # end_time=datetime.datetime.strftime(now_time,"%Y-%m-%d 00:00:00")
  82. # start_time=datetime.datetime.strftime(pre_time,"%Y-%m-%d 00:00:00")
  83. history_run_flag = False # 历史数据运行标志
  84. def get_sn():
  85. global df_sn
  86. # # 更新sn列表
  87. host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
  88. port=3306
  89. db='qixiang_oss'
  90. user='qixiang_oss'
  91. password='Qixiang2021'
  92. conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  93. cursor = conn.cursor()
  94. cursor.execute("select sn, imei, add_time from app_device where status in (1,2,3)")
  95. res = cursor.fetchall()
  96. df_sn = pd.DataFrame(res, columns=['sn', 'imei', 'add_time'])
  97. df_sn = df_sn[df_sn['sn'].str.contains('SPFPFL')]
  98. #df_sn = df_sn[df_sn['sn'].str.contains('PK500A20100000941')]
  99. df_sn = df_sn.reset_index(drop=True)
  100. conn.close()
  101. # 日志
  102. log_path = 'log/'
  103. if not os.path.exists(log_path):
  104. os.makedirs(log_path)
  105. logger = logging.getLogger("main")
  106. logger.setLevel(logging.DEBUG)
  107. # 根据日期滚动(每天产生1个文件)
  108. fh = logging.handlers.TimedRotatingFileHandler(filename='{}/main_info.log'.format(log_path), when="D", interval=1, backupCount=30,
  109. encoding="utf-8")
  110. formatter = logging.Formatter("%(asctime)s - %(name)s-%(levelname)s %(message)s")
  111. fh.suffix = "%Y-%m-%d_%H-%M-%S"
  112. fh.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}")
  113. fh.setFormatter(formatter)
  114. fh.setLevel(logging.INFO)
  115. logger.addHandler(fh)
  116. fh = logging.handlers.TimedRotatingFileHandler(filename='{}/main_error.log'.format(log_path), when="D", interval=1, backupCount=30,
  117. encoding="utf-8")
  118. formatter = logging.Formatter("%(asctime)s - %(name)s-%(levelname)s %(message)s")
  119. fh.suffix = "%Y-%m-%d_%H-%M-%S"
  120. fh.extMatch = re.compile(r"^\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}")
  121. fh.setFormatter(formatter)
  122. fh.setLevel(logging.ERROR)
  123. logger.addHandler(fh)
  124. logger.info("pid is {}".format(os.getpid()))
  125. get_sn()
  126. SOC_cal()
  127. #定时任务.......................................................................................................................................................................
  128. scheduler = BlockingScheduler()
  129. scheduler.add_job(get_sn, 'interval', days=1, id='get_sn')
  130. scheduler.add_job(SOC_cal, 'interval', seconds=300, id='SOC_cal')
  131. try:
  132. scheduler.start()
  133. except Exception as e:
  134. scheduler.shutdown()
  135. logger.error(str(e))