DBManager.py 21 KB

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