deploy_old2.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150
  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 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. dbManager = DBManager.DBManager()
  14. if __name__ == "__main__":
  15. # 更新sn列表
  16. host='rm-bp10j10qy42bzy0q7.mysql.rds.aliyuncs.com'
  17. port=3306
  18. db='qixiang_oss'
  19. user='qixiang_oss'
  20. password='Qixiang2021'
  21. conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  22. cursor = conn.cursor()
  23. cursor.execute("select sn, imei from app_device")
  24. res = cursor.fetchall()
  25. df_sn = pd.DataFrame(res, columns=['sn', 'imei'])
  26. df_sn = df_sn.reset_index(drop=True)
  27. conn.close();
  28. # 读取结果
  29. host='rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  30. port=3306
  31. db='qx_cas'
  32. user='qx_read'
  33. password='Qx@123456'
  34. conn = pymysql.connect(host=host, port=port, user=user, password=password, database=db)
  35. cursor = conn.cursor()
  36. cursor.execute("select sn, end_time from signal_monitor_bms")
  37. res = cursor.fetchall()
  38. df_res_old = pd.DataFrame(res, columns=["sn", "end_time"])
  39. df_res_old = df_res_old.reset_index(drop=True)
  40. conn.close();
  41. # 数据库配置
  42. host = 'rm-bp10j10qy42bzy0q77o.mysql.rds.aliyuncs.com'
  43. port = 3306
  44. user = 'qx_cas'
  45. password = parse.quote_plus('Qx@123456')
  46. database = 'qx_cas'
  47. db_engine = create_engine(
  48. "mysql+pymysql://{}:{}@{}:{}/{}?charset=utf8".format(
  49. user, password, host, port, database
  50. ))
  51. DbSession = sessionmaker(bind=db_engine)
  52. # 日志配置
  53. now_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()).replace(":","_")
  54. if not os.path.exists('log/' + now_str):
  55. os.makedirs('log/' + now_str)
  56. log = Log.Mylog(log_name='signal_monitor_新增sn统一运行至0812', log_level = 'info')
  57. log.set_file_hl(file_name='log/{}/info.log'.format(now_str), log_level='info', size=1024* 1024 * 100)
  58. log.set_file_hl(file_name='log/{}/error.log'.format(now_str), log_level='error', size=1024* 1024 * 100)
  59. logger = log.get_logger()
  60. logger.info("pid is + {}".format(os.getpid()))
  61. # 读取sn列表
  62. df_sn_excel = pd.read_csv('./sn_list.csv')
  63. df_sn_excel = df_sn_excel.reset_index(drop=True)
  64. # df_sn['StartTime'] = pd.to_datetime(df_sn['StartTime'])
  65. # df_sn['EndTime'] = pd.to_datetime(df_sn['EndTime'])
  66. # df_sn['ExitTime'] = pd.to_datetime(df_sn['ExitTime'])
  67. signalMonitor = SignalMonitor.SignalMonitor()
  68. cal_period = 24 # 计算间隔,单位h
  69. count = 0
  70. for i in range(0, len(df_sn['sn'])): # 遍历SN号
  71. sn = [df_sn.loc[i,'sn']]
  72. if sn[0] not in df_sn_excel['sn'].tolist():
  73. print (count)
  74. count = count + 1
  75. st = datetime.datetime.strptime("2018-08-12 00:00:00", "%Y-%m-%d %H:%M:%S")
  76. et = datetime.datetime.strptime("2021-08-12 00:00:00", "%Y-%m-%d %H:%M:%S")
  77. else:
  78. continue
  79. # else:
  80. # count = count + 1
  81. # continue
  82. # st = datetime.datetime.strptime("2018-08-12 00:00:00", "%Y-%m-%d %H:%M:%S")
  83. # et = datetime.datetime.strptime("2021-08-12 00:00:00", "%Y-%m-%d %H:%M:%S")
  84. # st = time.strftime("%Y-%m-%d 00:00:00", time.localtime(time.time()-86400))
  85. # et = time.strftime("%Y-%m-%d 00:00:00", time.localtime(time.time()))
  86. # st = time.strftime("%Y-%m-%d 00:00:00", time.localtime(time.time()-86400))
  87. # et = time.strftime("%Y-%m-%d 00:00:00", time.localtime(time.time()))
  88. # if df_sn.loc[i, 'Service'] == 0:
  89. # if pd.isnull(df_sn.loc[i, 'EndTime']) and pd.isnull(df_sn.loc[i, 'ExitTime']):
  90. # continue
  91. # elif pd.isnull(df_sn.loc[i, 'ExitTime']):
  92. # et = df_sn.loc[i, 'EndTime']
  93. # else:
  94. # et = df_sn.loc[i, 'ExitTime']
  95. # elif pd.isnull(df_sn.loc[i, 'EndTime']):
  96. # otherStyleTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
  97. # et = pd.to_datetime(otherStyleTime)
  98. # else:
  99. # et = df_sn.loc[i, 'EndTime']
  100. df_last_state = pd.DataFrame(
  101. columns=['sn', 'current', 'Timestamp', 'PackState', 'LineState']) # 每日最后BMS数据
  102. df_last_state_gps = pd.DataFrame(
  103. columns=['sn', 'Timestamp', 'PackState', 'LineState', 'latitude', 'longitude']) # 每日最后GPS数据
  104. df_res = pd.DataFrame(columns=[
  105. 'sn', 'PackState', 'LineState', 'StartTime', 'EndTime', 'OfflineTime']) # 初始化BMS信号统计数据
  106. df_res_gps = pd.DataFrame(columns=[
  107. 'sn', 'PackState', 'LineState', 'StartTime', 'EndTime', 'OfflineTime', 'latitude', 'longitude']) # 初
  108. logger.info("{} {} START!".format(sn, str(st)))
  109. while st < et:
  110. try:
  111. df_res, df_state, df_last_state = signalMonitor.get_bms_offline_stat(
  112. sn, st, et, df_res, df_last_state, cal_period) # 计算每日BMS信号统计数据
  113. df_res_gps, df_last_state_gps = signalMonitor.get_gps_offline_stat(
  114. sn, st, et, df_state, df_res_gps, df_last_state_gps, cal_period) # 计算每日GPS信号统计数据
  115. st = st + datetime.timedelta(hours=cal_period)
  116. except Exception as e:
  117. st = st + datetime.timedelta(hours=cal_period)
  118. logger.error(traceback.format_exc)
  119. logger.error(u"{} :{},{} 任务运行错误".format(sn,st,et), exc_info=True)
  120. # 数据入库
  121. df_tosql = df_res_gps.copy()
  122. df_tosql.columns = ['sn', 'pack_state', 'line_state', 'start_time', 'end_time', 'offline_time','latitude', 'longitude']
  123. df_tosql.to_sql("signal_monitor_gps",con=db_engine, if_exists="append",index=False)
  124. df_tosql = df_res.copy()
  125. df_tosql.columns = ['sn', 'pack_state', 'line_state', 'start_time', 'end_time', 'offline_time']
  126. df_tosql.to_sql("signal_monitor_bms",con=db_engine, if_exists="append",index=False)
  127. # 数据入库
  128. df_tosql = df_last_state.copy()
  129. df_tosql.columns = ['sn', 'current', 'time_stamp', 'pack_state', 'line_state']
  130. df_tosql.to_sql("signal_monitor_bms_last_day",con=db_engine, if_exists="append",index=False)
  131. df_tosql = df_last_state_gps.copy()
  132. df_tosql.columns = ['sn', 'time_stamp', 'pack_state', 'line_state','latitude', 'longitude']
  133. df_tosql.to_sql("signal_monitor_gps_last_day",con=db_engine, if_exists="append",index=False)
  134. logger.info("{} {} DONE!".format(sn, str(st)))
  135. # print(count)