DBManager.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. '''
  2. 暂时采用http方式获取历史数据。
  3. 预留:后期若改用通过访问数据库的形式进行数据的获取,则本文件负责数据库的连接,sql指令的执行,数据获取等功能。
  4. '''
  5. __author__ = 'lmstack'
  6. import time
  7. import datetime
  8. import time
  9. import pandas as pd
  10. import numpy as np
  11. import json
  12. import requests
  13. import pymysql
  14. import pdb
  15. from collections import Counter
  16. class DBManager():
  17. def __init__(self, host='', port='', auth='', db='', username='', password=''):
  18. self.host = host
  19. self.port = port
  20. self.auth = auth
  21. self.db = db
  22. self.username = username
  23. self.password = password
  24. pass
  25. def __enter__(self):
  26. self.connect()
  27. return self
  28. def __exit__(self, exc_type, exc_val, exc_tb):
  29. self.close()
  30. def connect(self):
  31. conn_success_flag = 0
  32. while not conn_success_flag:
  33. try:
  34. self.conn = pymysql.connect(host=self.host, port=self.port, user=self.user, password=self.password, database=self.db)
  35. except Exception as e:
  36. conn_success_flag = 0
  37. print("数据库连接失败 :{}".format(e))
  38. time.sleep(5)
  39. else:
  40. conn_success_flag = 1
  41. self.cursor = self.conn.cursor()
  42. def close(self):
  43. try:
  44. self.conn.close()
  45. except Exception as e:
  46. print(e)
  47. else:
  48. print('数据库已断开连接')
  49. def add(table, keyvalue):
  50. fields_str = ''
  51. values_str = ''
  52. for k,v in keyvalue.items():
  53. fields_str += k+' '
  54. sql = 'insert into table {} ({}) values ({})'.format(table, fields_str, values_str)
  55. # 以下各个函数实现 通过http方式获取数据
  56. @staticmethod
  57. def _get_var_name(cellnum,Tempnum,Othernum):
  58. temp = []
  59. for i in range(cellnum):
  60. temp.append('单体电压'+str(i+1))
  61. for i in range(Tempnum):
  62. temp.append('单体温度'+str(i+1))
  63. for i in range(Othernum):
  64. temp.append('其他温度'+str(i+1))
  65. return temp
  66. @staticmethod
  67. def _download_json_data(url):
  68. '''
  69. 返回json数据的生成器,一次一行
  70. '''
  71. i = 0
  72. while 1:
  73. try:
  74. r = requests.get(url, stream=True, timeout=(0.1, 1000), headers={'Connection':'keep-alive', 'Accept':'*/*', 'Accept-Encoding':'gzip,deflate,br'})
  75. break
  76. except requests.exceptions.RequestException as e:
  77. # if (i == 0):
  78. # print()
  79. # print('\r' + 'Server Error, retry {}......'.format(str(i)), end=" ")
  80. time.sleep(0.1)
  81. i+=1
  82. # print(r.content)
  83. # pdb.set_trace()
  84. data = []
  85. for line in r.iter_lines():
  86. if line:
  87. data.append(json.loads(line))
  88. # yield json.loads(line)
  89. return data
  90. @staticmethod
  91. def _convert_to_dataframe_bms(data, mode=0, CellUNum=0, CellTNum=0, OtherTNum=0):
  92. CellU = []
  93. CellT = []
  94. OtherT = []
  95. CellU_Num = CellUNum
  96. CellT_Num = CellTNum
  97. OtherT_Num = OtherTNum
  98. # try:
  99. # CellU_Num = len(data['ffBatteryStatus']['cellVoltageList'])
  100. # CellU = np.array(data['ffBatteryStatus']['cellVoltageList']) * 1000
  101. # CellU = CellU.tolist()
  102. # except:
  103. # CellU_Num = 0
  104. # try:
  105. # CellT_Num = len(data['ffBatteryStatus']['cellTempList'])
  106. # CellU.extend(data['ffBatteryStatus']['cellTempList'])
  107. # except:
  108. # CellT_Num = 0
  109. # try:
  110. # OtherT_Num = len(data['ffBatteryStatus']['otherTempList'])
  111. # CellU.extend(data['ffBatteryStatus']['otherTempList'])
  112. # except:
  113. # OtherT_Num = 0
  114. CellU = np.array(data['ffBatteryStatus'].get('cellVoltageList',[]))
  115. CellT = data['ffBatteryStatus'].get('cellTempList',[])
  116. OtherT = data['ffBatteryStatus'].get('otherTempList',[])
  117. if (len(CellU) != CellU_Num or len(CellT) != CellT_Num or len(OtherT) != OtherT_Num):
  118. return pd.DataFrame()
  119. CellU = CellU * 1000
  120. # for i in range(CellU_Num):
  121. # CellU.append(data['ffBatteryStatus']['cellVoltageList'][i]*1000)
  122. # for i in range(CellT_Num):
  123. # CellU.append(data['ffBatteryStatus']['cellTempList'][i])
  124. # for i in range(OtherT_Num):
  125. # CellU.append(data['ffBatteryStatus']['otherTempList'][i])
  126. if mode == 0:
  127. data_len = 16
  128. # data_block = np.array([data['info']['obdTime'],data['ffBatteryStatus']['rssi'],data['ffBatteryStatus']['errorLevel'],data['ffBatteryStatus']['errorCode']
  129. # ,data['ffBatteryStatus']['current'],data['ffBatteryStatus']['voltageInner'],data['ffBatteryStatus']['voltageOutter'],
  130. # data['ffBatteryStatus']['totalOutputState'],data['ffBatteryStatus']['lockedState'],
  131. # data['ffBatteryStatus']['chargeState'],data['ffBatteryStatus']['heatState'],data['ffBatteryStatus']['cellVoltageDiff']
  132. # ,data['ffBatteryStatus']['soc'],data['ffBatteryStatus']['soh'],data['ffBatteryStatus']['cellVolBalance']]).reshape(1,data_len)
  133. data_block = np.array([data['info']['obdTime'],data['ffBatteryStatus'].get('rssi',None),data['ffBatteryStatus'].get('errorLevel', None),data['ffBatteryStatus'].get('errorCode', None),
  134. data['ffBatteryStatus'].get('current',None),data['ffBatteryStatus'].get('voltageInner', None),data['ffBatteryStatus'].get('voltageOutter', None),
  135. data['ffBatteryStatus'].get('totalOutputState', None),data['ffBatteryStatus'].get('lockedState', None),
  136. data['ffBatteryStatus'].get('chargeState', None),data['ffBatteryStatus'].get('heatState', None),data['ffBatteryStatus'].get('cellVoltageDiff', None)
  137. ,data['ffBatteryStatus'].get('soc', None),data['ffBatteryStatus'].get('soh', None),data['ffBatteryStatus'].get('cellVolBalance', None),data['ffBatteryStatus'].get('insResis', None)]).reshape(1,data_len)
  138. elif mode == 1:
  139. data_len = 12
  140. data_block = np.array([data['info']['obdTime'],data['ffBatteryStatus'].get('rssi',None)
  141. ,data['ffBatteryStatus'].get('errorLevel', None),data['ffBatteryStatus'].get('errorCode', None),data['ffBatteryStatus'].get('switchState', None)
  142. ,data['ffBatteryStatus'].get('current',None),data['ffBatteryStatus'].get('voltageInner', None),data['ffBatteryStatus'].get('chargeState', None),
  143. data['ffBatteryStatus'].get('cellVoltageDiff', None),data['ffBatteryStatus'].get('soc', None),data['ffBatteryStatus'].get('soh', None),data['ffBatteryStatus'].get('insResis', None)]).reshape(1,data_len)
  144. data_block = np.append(data_block,CellU)
  145. data_block = np.append(data_block,CellT)
  146. data_block = np.append(data_block,OtherT)
  147. data_block = data_block.reshape(1,len(data_block))
  148. return data_block
  149. @staticmethod
  150. def _convert_to_dataframe_gps(data, mode=0):
  151. if mode == 0:
  152. # if data['info']['subType'] == 1:
  153. data_block = np.array([data['info'].get('obdTime',None),data['ffGps'].get('locationType',None), data['ffGps'].get('satellites',None),
  154. data['ffGps'].get('latitude',None),data['ffGps'].get('longitude',None),data['ffGps'].get('speed',None),
  155. data['ffGps'].get('altitude',None), data['ffGps'].get('direction', None), data['ffGps'].get('mileage',None)]).reshape(1,9)
  156. df = pd.DataFrame(
  157. columns=['时间戳','定位类型', '卫星数','纬度','经度','速度[km/h]','海拔','航向', '里程/m'],data=data_block)
  158. # elif data['info']['subType'] == 2:
  159. # df = pd.DataFrame(
  160. # columns=['时间戳','定位类型', '卫星数','纬度','经度','速度[km/h]','海拔','航向'])
  161. if mode == 1:
  162. data_block = np.array([data['info']['obdTime'],data['ffGps']['locationType'],data['ffGps']['latitude'],data['ffGps']['longitude']
  163. ,data['ffGps']['speed'], data['ffGps']['isValid']]).reshape(1,6)
  164. df = pd.DataFrame(
  165. columns=['时间戳','定位类型', '纬度','经度','速度[km/h]','有效位'],data=data_block)
  166. return df
  167. @staticmethod
  168. def _convert_to_dataframe_system(data, mode=0):
  169. if mode == 0:
  170. data_block = np.array([data['info'].get('obdTime', None),data['ffSystemInfo'].get('heatTargetTemp', None), data['ffSystemInfo'].get('heatTimeout',None),
  171. time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(data['ffSystemInfo'].get('rentalStartTime'))/1000)),
  172. data['ffSystemInfo'].get('rentalPeriodDays',None),data['ffSystemInfo'].get('bmsInterval',None),
  173. data['ffSystemInfo'].get('gpsInterval', None)]).reshape(1,7)
  174. df = pd.DataFrame(
  175. columns=['时间戳','加热目标温度', '加热超时','租赁开始时间','租赁天数','bms上传周期','gps上传周期'],data=data_block)
  176. if mode == 1:
  177. df = pd.DataFrame()
  178. return df
  179. @staticmethod
  180. def _convert_to_dataframe_accum(data, mode=0):
  181. if mode == 0:
  182. data_block = np.array([data['info'].get('obdTime',None),data['ffBatteryAccum'].get('SOH_AlgUnexTime',None), data['ffBatteryAccum'].get('CHG_AHaccum',None),
  183. data['ffBatteryAccum'].get('CHG_PHaccum',None), data['ffBatteryAccum'].get('DSG_AHaccum',None),
  184. data['ffBatteryAccum'].get('DSG_PHaccum',None),data['ffBatteryAccum'].get('OverTemp_CHG_AHaccum',None),
  185. data['ffBatteryAccum'].get('OverTemp_CHG_PHaccum',None)]).reshape(1,8)
  186. df = pd.DataFrame(
  187. columns=['时间戳','SOH未标定时间', '累计充电电量','累计充电能量','累计放电电量','累计放电能量',
  188. '累计高温充电电量', '累计高温充电能量'],data=data_block)
  189. if mode == 1:
  190. data_block = np.array([data['info'].get('obdTime',None), data['ffBatteryAccum'].get('CHG_AHaccum',None),
  191. data['ffBatteryAccum'].get('CHG_PHaccum',None), data['ffBatteryAccum'].get('DSG_AHaccum',None),
  192. data['ffBatteryAccum'].get('DSG_PHaccum',None),data['ffBatteryAccum'].get('totalMileage',None)]).reshape(1,6)
  193. df = pd.DataFrame(
  194. columns=['时间戳','累计充电电量','累计充电能量','累计放电电量','累计放电能量', '累积里程'],data=data_block)
  195. return df
  196. @staticmethod
  197. def _convert_to_dataframe_storage_accum(data, mode=0):
  198. if mode == 0:
  199. data_block = np.array([data['info'].get('obdTime',None),data['ffEnergyStoreStat'].get('usedEnergy',None), data['ffEnergyStoreStat'].get('inputEnergy',None),
  200. data['ffEnergyStoreStat'].get('outputEnergy',None), data['ffEnergyStoreStat'].get('usedEnergy2',None), data['ffEnergyStoreStat'].get('inputEnergy2',None),
  201. data['ffEnergyStoreStat'].get('outputEnergy2',None)]).reshape(1,7)
  202. df = pd.DataFrame(
  203. columns=['时间戳','累计用电kWh数1', '累计正向输入kWh1','累计反向输出kWh数1',
  204. '累计用电kWh数2', '累计正向输入kWh2','累计反向输出kWh数2'],data=data_block)
  205. if mode == 1:
  206. data_block = np.array([data['info'].get('obdTime',None),data['ffEnergyStoreStat'].get('usedEnergy',None), data['ffEnergyStoreStat'].get('inputEnergy',None),
  207. data['ffEnergyStoreStat'].get('outputEnergy',None), data['ffEnergyStoreStat'].get('usedEnergy2',None), data['ffEnergyStoreStat'].get('inputEnergy2',None),
  208. data['ffEnergyStoreStat'].get('outputEnergy2',None)]).reshape(1,7)
  209. df = pd.DataFrame(
  210. columns=['时间戳','累计用电kWh数1', '累计正向输入kWh1','累计反向输出kWh数1',
  211. '累计用电kWh数2', '累计正向输入kWh2','累计反向输出kWh数2'],data=data_block)
  212. return df
  213. @staticmethod
  214. def _get_data(urls,type_name,mode=0):
  215. data = DBManager._download_json_data(urls)
  216. if type_name == 'bms':
  217. if mode == 0:
  218. name_const = ['时间戳','GSM信号','故障等级','故障代码','总电流[A]','总电压[V]', '外电压', '总输出状态', '上锁状态', '充电状态','加热状态',
  219. '单体压差', 'SOC[%]','SOH[%]','单体均衡状态', '绝缘电阻']
  220. elif mode == 1:
  221. name_const = ['时间戳','GSM信号','故障等级', '故障代码','开关状态', '总电流[A]','总电压[V]','充电状态', '单体压差', 'SOC[%]','SOH[%]', '绝缘电阻']
  222. i=0
  223. st = time.time()
  224. # 计算本次最大电芯数量
  225. CellUNum = 0
  226. CellTNum = 0
  227. OtherTNum = 0
  228. cellUNumList = []
  229. cellTNumList = []
  230. otherTNumList = []
  231. for line in data:
  232. temp = len(line['ffBatteryStatus'].get('cellVoltageList', []))
  233. cellUNumList.append(temp)
  234. # if (temp > CellUNum):
  235. # CellUNum = temp
  236. temp = len(line['ffBatteryStatus'].get('cellTempList', []))
  237. cellTNumList.append(temp)
  238. # if (temp > CellTNum):
  239. # CellTNum = temp
  240. temp = len(line['ffBatteryStatus'].get('otherTempList', []))
  241. otherTNumList.append(temp)
  242. # if (temp > OtherTNum):
  243. # OtherTNum = temp
  244. if (len(data)>0):
  245. result = Counter(cellUNumList)
  246. CellUNum = max(result, key=result.get)
  247. result = Counter(cellTNumList)
  248. CellTNum = max(result, key=result.get)
  249. result = Counter(otherTNumList)
  250. OtherTNum = max(result, key=result.get)
  251. data_blocks = pd.DataFrame()
  252. for line in data:
  253. et = time.time()
  254. try:
  255. if i==0:
  256. data_blocks = DBManager._convert_to_dataframe_bms(line, mode, CellUNum, CellTNum, OtherTNum)
  257. if (len(data_blocks)>0):
  258. i+=1
  259. continue
  260. except Exception as e:
  261. # print(e)
  262. continue
  263. try:
  264. data_block = DBManager._convert_to_dataframe_bms(line, mode, CellUNum, CellTNum, OtherTNum)
  265. except Exception as e:
  266. # print(e)
  267. continue
  268. try:
  269. if (len(data_block)>0):
  270. data_blocks = np.concatenate((data_blocks,data_block),axis=0)
  271. except Exception as e:
  272. print(e)
  273. if 'all the input array dimensions for the concatenation axis must match exactly' in str(e) or \
  274. 'all the input array dimensions except for the concatenation axis must match exactly' in str(e):
  275. pass
  276. else:
  277. raise e
  278. i+=1
  279. name_var = DBManager._get_var_name(CellUNum,CellTNum,OtherTNum)
  280. name_const.extend(name_var)
  281. columns_name = name_const
  282. if i==0:
  283. data_blocks = []
  284. df_all = pd.DataFrame(columns=columns_name,data=data_blocks)
  285. if not df_all.empty:
  286. df_all.loc[:,'时间戳'] = df_all.loc[:,'时间戳'].apply(lambda x:time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(x)/1000)))
  287. return df_all
  288. elif type_name =='gps':
  289. if mode == 0:
  290. df_all = pd.DataFrame(columns=['时间戳','定位类型', '卫星数','纬度','经度','速度[km/h]','海拔','航向'])
  291. elif mode == 1:
  292. df_all = pd.DataFrame(columns=['时间戳','定位类型', '纬度','经度','速度[km/h]','有效位'])
  293. for line in data:
  294. df_add = DBManager._convert_to_dataframe_gps(line, mode)
  295. df_all = df_all.append(df_add,ignore_index=True)
  296. if not df_all.empty:
  297. df_all.loc[:,'时间戳'] = df_all.loc[:,'时间戳'].apply(lambda x:time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(x)/1000)))
  298. return df_all
  299. elif type_name =='system':
  300. if mode == 0:
  301. df_all = pd.DataFrame(columns=['时间戳','加热目标温度', '加热超时','租赁开始时间','租赁天数','bms上传周期','gps上传周期'])
  302. elif mode == 1:
  303. df_all = pd.DataFrame()
  304. for line in data:
  305. df_add = DBManager._convert_to_dataframe_system(line, mode)
  306. df_all = df_all.append(df_add,ignore_index=True)
  307. if not df_all.empty:
  308. df_all.loc[:,'时间戳'] = df_all.loc[:,'时间戳'].apply(lambda x:time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(x)/1000)))
  309. return df_all
  310. elif type_name =='accum':
  311. if mode == 0:
  312. df_all = pd.DataFrame(columns=['时间戳','SOH未标定时间', '累计充电电量','累计充电能量','累计放电电量','累计放电能量',
  313. '累计高温充电电量', '累计高温充电能量'])
  314. elif mode == 1:
  315. df_all = pd.DataFrame(columns=['时间戳','累计充电电量','累计充电能量','累计放电电量','累计放电能量', '累积里程'])
  316. for line in data:
  317. df_add = DBManager._convert_to_dataframe_accum(line, mode)
  318. df_all = df_all.append(df_add,ignore_index=True)
  319. if not df_all.empty:
  320. df_all.loc[:,'时间戳'] = df_all.loc[:,'时间戳'].apply(lambda x:time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(x)/1000)))
  321. return df_all
  322. elif type_name =='storage_accum':
  323. if mode == 0:
  324. df_all = pd.DataFrame(columns=['时间戳','累计用电kWh数1', '累计正向输入kWh1','累计反向输出kWh数1',
  325. '累计用电kWh数2', '累计正向输入kWh2','累计反向输出kWh数2'])
  326. elif mode == 1:
  327. df_all = pd.DataFrame()
  328. for line in data:
  329. df_add = DBManager._convert_to_dataframe_storage_accum(line, mode)
  330. df_all = df_all.append(df_add,ignore_index=True)
  331. if not df_all.empty:
  332. df_all.loc[:,'时间戳'] = df_all.loc[:,'时间戳'].apply(lambda x:time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(x)/1000)))
  333. return df_all
  334. def get_data(self, url='http://172.16.126.13/store/load?dataType={}&limit=0&sn={}', sn='', start_time='', end_time='',
  335. data_groups=['bms', 'gps']):
  336. '''
  337. 获取指定 sn 和起止日期的bms和gps数据.
  338. 添加了重试机制。
  339. --------------输入参数------------
  340. url:数据获取url, 可采用默认值
  341. sn: str, 电池sn号
  342. start_time: str, 开始时间
  343. end_time: str, 结束时间
  344. data_groups: 选择需要获取的数据组,可填入多个字符串(默认只获取bms和gps数据)
  345. bms: bms数据
  346. gps:gps数据
  347. system:system数据
  348. accum:accum数据
  349. --------------输出参数------------
  350. df_data: {'bms':dataframe, 'gps':dataframe, 'system':dataframe, ;accum':dataframe}
  351. '''
  352. if len(set(data_groups) - (set(data_groups) and set(['bms', 'gps', 'system', 'accum', 'storage_accum']))) > 0:
  353. raise Exception("data_groups 参数错误")
  354. # mode: 0:正常取数; 1:7255 取数
  355. if sn[0:2] == 'UD' or sn[0:2] == 'MG':
  356. mode = 1
  357. else:
  358. mode = 0
  359. bms_all_data = pd.DataFrame()
  360. gps_all_data = pd.DataFrame()
  361. system_all_data = pd.DataFrame()
  362. accum_all_data = pd.DataFrame()
  363. storage_accum_all_data = pd.DataFrame()
  364. maxnum = (datetime.datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S") - datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")).days +1
  365. print("### start to get data {} from {} to {}".format(sn, start_time, end_time))
  366. # 为避免chunkEncodingError错误,数据每天获取一次,然后将每天的数据合并,得到最终的数据
  367. for j in range(int(maxnum)):
  368. timefrom = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")+ datetime.timedelta(days=j)
  369. timeto = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")+ datetime.timedelta(days=j+1)
  370. #滴滴的数据sub=0
  371. if timefrom.strftime('%Y-%m-%d %H:%M:%S') >= end_time:
  372. break
  373. elif timeto.strftime('%Y-%m-%d %H:%M:%S') > end_time:
  374. timeto = datetime.datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
  375. #print('{}_{}_----getting data----'.format(sn, timefrom))
  376. bms_data = pd.DataFrame()
  377. gps_data = pd.DataFrame()
  378. system_data = pd.DataFrame()
  379. accum_data = pd.DataFrame()
  380. storage_accum_all_data = pd.DataFrame()
  381. while True:
  382. try:
  383. print('\r' + "# get data from {} to {}.........".format(str(timefrom), str(timeto)), end=" ")
  384. for data_group in data_groups:
  385. if data_group == 'bms':
  386. file_url = url.format(12, sn) + "&from="+timefrom.strftime('%Y-%m-%d %H:%M:%S')+"&to="+timeto.strftime('%Y-%m-%d %H:%M:%S')
  387. bms_data = DBManager._get_data(file_url,'bms',mode)
  388. if data_group == 'gps':
  389. file_url = url.format(16, sn) + "&from="+timefrom.strftime('%Y-%m-%d %H:%M:%S')+"&to="+timeto.strftime('%Y-%m-%d %H:%M:%S')
  390. gps_data = DBManager._get_data(file_url,'gps',mode)
  391. if data_group == 'system':
  392. file_url = url.format(13, sn) + "&from="+timefrom.strftime('%Y-%m-%d %H:%M:%S')+"&to="+timeto.strftime('%Y-%m-%d %H:%M:%S')
  393. system_data = DBManager._get_data(file_url,'system',mode)
  394. if data_group == 'accum':
  395. file_url = url.format(23, sn) + "&from="+timefrom.strftime('%Y-%m-%d %H:%M:%S')+"&to="+timeto.strftime('%Y-%m-%d %H:%M:%S')
  396. accum_data = DBManager._get_data(file_url,'accum',mode)
  397. if data_group == 'storage_accum':
  398. file_url = url.format(29, sn) + "&from="+timefrom.strftime('%Y-%m-%d %H:%M:%S')+"&to="+timeto.strftime('%Y-%m-%d %H:%M:%S')
  399. storage_accum_data = DBManager._get_data(file_url,'storage_accum',mode)
  400. except Exception as e:
  401. if 'Connection broken' in str(e):
  402. continue
  403. elif 'Number of manager items must equal union of block items' in str(e):
  404. break
  405. else:
  406. raise Exception
  407. else:
  408. bms_all_data = pd.concat([bms_all_data, bms_data], ignore_index=True)
  409. gps_all_data = pd.concat([gps_all_data, gps_data], ignore_index=True)
  410. system_all_data = pd.concat([system_all_data, system_data], ignore_index=True)
  411. accum_all_data = pd.concat([accum_all_data, accum_data], ignore_index=True)
  412. storage_accum_all_data = pd.concat([storage_accum_all_data, storage_accum_data], ignore_index=True)
  413. break
  414. bms_all_data = bms_all_data.reset_index(drop=True)
  415. gps_all_data = gps_all_data.reset_index(drop=True)
  416. system_all_data = system_all_data.reset_index(drop=True)
  417. accum_all_data = accum_all_data.reset_index(drop=True)
  418. storage_accum_all_data = storage_accum_all_data.reset_index(drop=True)
  419. print('\nall data-getting done, bms_count is {}, gps_count is {}, system_count is {}, accum_count is {} ,storage_accum_count is {}\n'.format(
  420. str(len(bms_all_data)), str(len(gps_all_data)), str(len(system_all_data)), str(len(accum_all_data)), str(len(storage_accum_all_data))))
  421. return {'bms':bms_all_data, 'gps':gps_all_data, 'system':system_all_data, 'accum':accum_all_data,'storage_accum':storage_accum_all_data}