deploy.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. #coding=utf-8
  2. import os
  3. import datetime
  4. import pandas as pd
  5. from LIB.BACKEND import DBManager, Log
  6. from LIB.MIDDLE.SignalMonitor import SignalMonitor
  7. from sqlalchemy import create_engine
  8. from sqlalchemy.orm import sessionmaker
  9. import time, datetime
  10. import traceback
  11. import pymysql
  12. from urllib import parse
  13. import dateutil.relativedelta
  14. dbManager = DBManager.DBManager()
  15. if __name__ == "__main__":
  16. # 时间设置
  17. now_time = datetime.datetime.now()
  18. pre_time = now_time + dateutil.relativedelta.relativedelta(days=-1)
  19. end_time=datetime.datetime.strftime(now_time,"%Y-%m-%d 00:00:00")
  20. start_time=datetime.datetime.strftime(pre_time,"%Y-%m-%d 00:00:00")
  21. # 更新sn列表
  22. host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
  23. port=3306
  24. db='qixiang_oss'
  25. user='qixiang_oss'
  26. password='Qixiang2021'
  27. conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  28. cursor = conn.cursor()
  29. cursor.execute("select sn, imei from app_device")
  30. res = cursor.fetchall()
  31. df_sn = pd.DataFrame(res, columns=['sn', 'imei'])
  32. df_sn = df_sn.reset_index(drop=True)
  33. conn.close();
  34. # 数据库配置
  35. host = 'rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  36. port = 3306
  37. user = 'qx_cas'
  38. password = parse.quote_plus('Qx@123456')
  39. database = 'qx_cas'
  40. db_engine = create_engine(
  41. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  42. user, password, host, port, database
  43. ))
  44. DbSession = sessionmaker(bind=db_engine)
  45. # 日志配置
  46. now_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()).replace(":","_")
  47. log_path = 'log/' + now_str
  48. if not os.path.exists(log_path):
  49. os.makedirs(log_path)
  50. log = Log.Mylog(log_name='signal_monitor', log_level = 'info')
  51. log.set_file_hl(file_name='{}/info.log'.format(log_path), log_level='info', size=1024* 1024 * 100)
  52. log.set_file_hl(file_name='{}/error.log'.format(log_path), log_level='error', size=1024* 1024 * 100)
  53. logger = log.get_logger()
  54. logger.info("pid is + {}. ".format(os.getpid()))
  55. # # 算法运行
  56. count = 0
  57. signalMonitor = SignalMonitor.SignalMonitor()
  58. cal_period = 24 # 计算间隔,单位h
  59. for i in range(0, len(df_sn['sn'])): # 遍历SN号
  60. count = count + 1
  61. sn = [df_sn.loc[i,'sn']]
  62. st = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
  63. et = datetime.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")
  64. df_last_state = pd.DataFrame(
  65. columns=['sn', 'current', 'Timestamp', 'PackState', 'LineState']) # 每日最后BMS数据
  66. df_last_state_gps = pd.DataFrame(
  67. columns=['sn', 'Timestamp', 'PackState', 'LineState', 'latitude', 'longitude']) # 每日最后GPS数据
  68. df_res = pd.DataFrame(columns=[
  69. 'sn', 'PackState', 'LineState', 'StartTime', 'EndTime', 'OfflineTime']) # 初始化BMS信号统计数据
  70. df_res_gps = pd.DataFrame(columns=[
  71. 'sn', 'PackState', 'LineState', 'StartTime', 'EndTime', 'OfflineTime', 'latitude', 'longitude']) # 初
  72. logger.info("pid-{} {}/{}, {} {} START!".format(os.getpid(), str(count), str(len(df_sn)), sn, str(st)))
  73. while st < et:
  74. try:
  75. df_res, df_state, df_last_state = signalMonitor.get_bms_offline_stat(
  76. sn, st, et, df_res, df_last_state, cal_period) # 计算每日BMS信号统计数据
  77. df_res_gps, df_last_state_gps = signalMonitor.get_gps_offline_stat(
  78. sn, st, et, df_state, df_res_gps, df_last_state_gps, cal_period) # 计算每日GPS信号统计数据
  79. st = st + datetime.timedelta(hours=cal_period)
  80. except Exception as e:
  81. st = st + datetime.timedelta(hours=cal_period)
  82. logger.error(traceback.format_exc)
  83. logger.error(u"{} :{},{} 任务运行错误".format(sn,st,et), exc_info=True)
  84. # 数据入库
  85. df_tosql = df_res_gps.copy()
  86. df_tosql.columns = ['sn', 'pack_state', 'line_state', 'start_time', 'end_time', 'offline_time','latitude', 'longitude']
  87. df_tosql.to_sql("signal_monitor_gps",con=db_engine, if_exists="append",index=False)
  88. df_tosql = df_res.copy()
  89. df_tosql.columns = ['sn', 'pack_state', 'line_state', 'start_time', 'end_time', 'offline_time']
  90. df_tosql.to_sql("signal_monitor_bms",con=db_engine, if_exists="append",index=False)
  91. # 数据入库
  92. df_tosql = df_last_state.copy()
  93. df_tosql.columns = ['sn', 'current', 'time_stamp', 'pack_state', 'line_state']
  94. df_tosql.to_sql("signal_monitor_bms_last_day",con=db_engine, if_exists="append",index=False)
  95. df_tosql = df_last_state_gps.copy()
  96. df_tosql.columns = ['sn', 'time_stamp', 'pack_state', 'line_state','latitude', 'longitude']
  97. df_tosql.to_sql("signal_monitor_gps_last_day",con=db_engine, if_exists="append",index=False)
  98. logger.info("{}/{}, {} {} DONE!".format(str(count), str(len(df_sn)), sn, str(st)))
  99. print(count)