DBManager.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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 _get_data(urls,type_name,mode=0):
  198. data = DBManager._download_json_data(urls)
  199. if type_name == 'bms':
  200. if mode == 0:
  201. name_const = ['时间戳','GSM信号','故障等级','故障代码','总电流[A]','总电压[V]', '外电压', '总输出状态', '上锁状态', '充电状态','加热状态',
  202. '单体压差', 'SOC[%]','SOH[%]','单体均衡状态', '绝缘电阻']
  203. elif mode == 1:
  204. name_const = ['时间戳','GSM信号','故障等级', '故障代码','开关状态', '总电流[A]','总电压[V]','充电状态', '单体压差', 'SOC[%]','SOH[%]', '绝缘电阻']
  205. i=0
  206. st = time.time()
  207. # 计算本次最大电芯数量
  208. CellUNum = 0
  209. CellTNum = 0
  210. OtherTNum = 0
  211. cellUNumList = []
  212. cellTNumList = []
  213. otherTNumList = []
  214. for line in data:
  215. temp = len(line['ffBatteryStatus'].get('cellVoltageList', []))
  216. cellUNumList.append(temp)
  217. # if (temp > CellUNum):
  218. # CellUNum = temp
  219. temp = len(line['ffBatteryStatus'].get('cellTempList', []))
  220. cellTNumList.append(temp)
  221. # if (temp > CellTNum):
  222. # CellTNum = temp
  223. temp = len(line['ffBatteryStatus'].get('otherTempList', []))
  224. otherTNumList.append(temp)
  225. # if (temp > OtherTNum):
  226. # OtherTNum = temp
  227. if (len(data)>0):
  228. result = Counter(cellUNumList)
  229. CellUNum = max(result, key=result.get)
  230. result = Counter(cellTNumList)
  231. CellTNum = max(result, key=result.get)
  232. result = Counter(otherTNumList)
  233. OtherTNum = max(result, key=result.get)
  234. data_blocks = pd.DataFrame()
  235. for line in data:
  236. et = time.time()
  237. try:
  238. if i==0:
  239. data_blocks = DBManager._convert_to_dataframe_bms(line, mode, CellUNum, CellTNum, OtherTNum)
  240. if (len(data_blocks)>0):
  241. i+=1
  242. continue
  243. except Exception as e:
  244. # print(e)
  245. continue
  246. try:
  247. data_block = DBManager._convert_to_dataframe_bms(line, mode, CellUNum, CellTNum, OtherTNum)
  248. except Exception as e:
  249. # print(e)
  250. continue
  251. try:
  252. if (len(data_block)>0):
  253. data_blocks = np.concatenate((data_blocks,data_block),axis=0)
  254. except Exception as e:
  255. print(e)
  256. if 'all the input array dimensions for the concatenation axis must match exactly' in str(e) or \
  257. 'all the input array dimensions except for the concatenation axis must match exactly' in str(e):
  258. pass
  259. else:
  260. raise e
  261. i+=1
  262. name_var = DBManager._get_var_name(CellUNum,CellTNum,OtherTNum)
  263. name_const.extend(name_var)
  264. columns_name = name_const
  265. if i==0:
  266. data_blocks = []
  267. df_all = pd.DataFrame(columns=columns_name,data=data_blocks)
  268. if not df_all.empty:
  269. df_all.loc[:,'时间戳'] = df_all.loc[:,'时间戳'].apply(lambda x:time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(x)/1000)))
  270. return df_all
  271. elif type_name =='gps':
  272. if mode == 0:
  273. df_all = pd.DataFrame(columns=['时间戳','定位类型', '卫星数','纬度','经度','速度[km/h]','海拔','航向'])
  274. elif mode == 1:
  275. df_all = pd.DataFrame(columns=['时间戳','定位类型', '纬度','经度','速度[km/h]','有效位'])
  276. for line in data:
  277. df_add = DBManager._convert_to_dataframe_gps(line, mode)
  278. df_all = df_all.append(df_add,ignore_index=True)
  279. if not df_all.empty:
  280. df_all.loc[:,'时间戳'] = df_all.loc[:,'时间戳'].apply(lambda x:time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(x)/1000)))
  281. return df_all
  282. elif type_name =='system':
  283. if mode == 0:
  284. df_all = pd.DataFrame(columns=['时间戳','加热目标温度', '加热超时','租赁开始时间','租赁天数','bms上传周期','gps上传周期'])
  285. elif mode == 1:
  286. df_all = pd.DataFrame()
  287. for line in data:
  288. df_add = DBManager._convert_to_dataframe_system(line, mode)
  289. df_all = df_all.append(df_add,ignore_index=True)
  290. if not df_all.empty:
  291. df_all.loc[:,'时间戳'] = df_all.loc[:,'时间戳'].apply(lambda x:time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(x)/1000)))
  292. return df_all
  293. elif type_name =='accum':
  294. if mode == 0:
  295. df_all = pd.DataFrame(columns=['时间戳','SOH未标定时间', '累计充电电量','累计充电能量','累计放电电量','累计放电能量',
  296. '累计高温充电电量', '累计高温充电能量'])
  297. elif mode == 1:
  298. df_all = pd.DataFrame(columns=['时间戳','累计充电电量','累计充电能量','累计放电电量','累计放电能量', '累积里程'])
  299. for line in data:
  300. df_add = DBManager._convert_to_dataframe_accum(line, mode)
  301. df_all = df_all.append(df_add,ignore_index=True)
  302. if not df_all.empty:
  303. df_all.loc[:,'时间戳'] = df_all.loc[:,'时间戳'].apply(lambda x:time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(int(x)/1000)))
  304. return df_all
  305. def get_data(self, url='http://172.16.126.13/store/load?dataType={}&limit=0&sn={}', sn='', start_time='', end_time='',
  306. data_groups=['bms', 'gps']):
  307. '''
  308. 获取指定 sn 和起止日期的bms和gps数据.
  309. 添加了重试机制。
  310. --------------输入参数------------
  311. url:数据获取url, 可采用默认值
  312. sn: str, 电池sn号
  313. start_time: str, 开始时间
  314. end_time: str, 结束时间
  315. data_groups: 选择需要获取的数据组,可填入多个字符串(默认只获取bms和gps数据)
  316. bms: bms数据
  317. gps:gps数据
  318. system:system数据
  319. accum:accum数据
  320. --------------输出参数------------
  321. df_data: {'bms':dataframe, 'gps':dataframe, 'system':dataframe, ;accum':dataframe}
  322. '''
  323. if len(set(data_groups) - (set(data_groups) and set(['bms', 'gps', 'system', 'accum']))) > 0:
  324. raise Exception("data_groups 参数错误")
  325. # mode: 0:正常取数; 1:7255 取数
  326. if sn[0:2] == 'UD' or sn[0:2] == 'MG':
  327. mode = 1
  328. else:
  329. mode = 0
  330. bms_all_data = pd.DataFrame()
  331. gps_all_data = pd.DataFrame()
  332. system_all_data = pd.DataFrame()
  333. accum_all_data = pd.DataFrame()
  334. 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
  335. print("### start to get data {} from {} to {}".format(sn, start_time, end_time))
  336. # 为避免chunkEncodingError错误,数据每天获取一次,然后将每天的数据合并,得到最终的数据
  337. for j in range(int(maxnum)):
  338. timefrom = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")+ datetime.timedelta(days=j)
  339. timeto = datetime.datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")+ datetime.timedelta(days=j+1)
  340. #滴滴的数据sub=0
  341. if timefrom.strftime('%Y-%m-%d %H:%M:%S') >= end_time:
  342. break
  343. elif timeto.strftime('%Y-%m-%d %H:%M:%S') > end_time:
  344. timeto = datetime.datetime.strptime(end_time, '%Y-%m-%d %H:%M:%S')
  345. #print('{}_{}_----getting data----'.format(sn, timefrom))
  346. bms_data = pd.DataFrame()
  347. gps_data = pd.DataFrame()
  348. system_data = pd.DataFrame()
  349. accum_data = pd.DataFrame()
  350. while True:
  351. try:
  352. print('\r' + "# get data from {} to {}.........".format(str(timefrom), str(timeto)), end=" ")
  353. for data_group in data_groups:
  354. if data_group == 'bms':
  355. file_url = url.format(12, sn) + "&from="+timefrom.strftime('%Y-%m-%d %H:%M:%S')+"&to="+timeto.strftime('%Y-%m-%d %H:%M:%S')
  356. bms_data = DBManager._get_data(file_url,'bms',mode)
  357. if data_group == 'gps':
  358. file_url = url.format(16, sn) + "&from="+timefrom.strftime('%Y-%m-%d %H:%M:%S')+"&to="+timeto.strftime('%Y-%m-%d %H:%M:%S')
  359. gps_data = DBManager._get_data(file_url,'gps',mode)
  360. if data_group == 'system':
  361. file_url = url.format(13, sn) + "&from="+timefrom.strftime('%Y-%m-%d %H:%M:%S')+"&to="+timeto.strftime('%Y-%m-%d %H:%M:%S')
  362. system_data = DBManager._get_data(file_url,'system',mode)
  363. if data_group == 'accum':
  364. file_url = url.format(23, sn) + "&from="+timefrom.strftime('%Y-%m-%d %H:%M:%S')+"&to="+timeto.strftime('%Y-%m-%d %H:%M:%S')
  365. accum_data = DBManager._get_data(file_url,'accum',mode)
  366. except Exception as e:
  367. if 'Connection broken' in str(e):
  368. continue
  369. elif 'Number of manager items must equal union of block items' in str(e):
  370. break
  371. else:
  372. raise Exception
  373. else:
  374. bms_all_data = pd.concat([bms_all_data, bms_data], ignore_index=True)
  375. gps_all_data = pd.concat([gps_all_data, gps_data], ignore_index=True)
  376. system_all_data = pd.concat([system_all_data, system_data], ignore_index=True)
  377. accum_all_data = pd.concat([accum_all_data, accum_data], ignore_index=True)
  378. break
  379. bms_all_data = bms_all_data.reset_index(drop=True)
  380. gps_all_data = gps_all_data.reset_index(drop=True)
  381. system_all_data = system_all_data.reset_index(drop=True)
  382. accum_all_data = accum_all_data.reset_index(drop=True)
  383. print('\nall data-getting done, bms_count is {}, gps_count is {}, system_count is {}, accum_count is {} \n'.format(
  384. str(len(bms_all_data)), str(len(gps_all_data)), str(len(system_all_data)), str(len(accum_all_data))))
  385. return {'bms':bms_all_data, 'gps':gps_all_data, 'system':system_all_data, 'accum':accum_all_data}