class WialonManager: def __init__(self): self.token = '1e3f50514d35becfaf1b9ec8ff42f80014125DD4DBEADF212ED7DC3ED42D71466C71DF06' # Основной # self.token = '290a6913b07b4afce549894ab74c1d87913BAACC55F364819505234D43FAB9FA89FC72A6' #ССК(п) Подрядчики_api # self.token = 'eac53c387a819eb667e4e3fa967276ed55DE297F7272B45494FAE6F694E20D4C312F9907' #ССК(РС) Подрядчики_api # self.token = '526cdec32ecf25b664182796a38c3c665D97F79D99283A9CA9F4B7A1AA40E8D449D356FE' #ССК(Т) Подрядчики_api self.wialon = Wialon() try: login = self.wialon.token_login(token=self.token) except WialonError as e: print("Error while login") time.sleep(5) return self.wialon.sid = login['eid'] self.wialon.render_set_locale({ "tzOffset": 18000, "language": 'ru', "formatDate": "%Y-%m-%E %H:%M:%S" }) self.res_id = 21922430 self.base_group = {} def api_get_groups(self): spec = { 'itemsType': 'avl_unit_group', 'propName': 'sys_name', 'propValueMask': '*', 'sortType': 'sys_name' } interval = {"from": 0, "to": 0} custom_flag = flags.ITEM_RESOURCE_DATAFLAG_DRIVERS + flags.ITEM_DATAFLAG_BASE + \ flags.ITEM_RESOURCE_DATAFLAG_NOTIFICATIONS + 0x00001000 units = self.wialon.core_search_items(spec=spec, force=1, flags=custom_flag, **interval) groups = units['items'] for group in groups: if group['nm'] != 'ССК Подрядчики': self.base_group[group['nm']] = [ group['id'], len(group['u']), group['u'] ] return self.base_group def api_get_obj(self, id): obj = self.wialon.core_search_item({'id': int(id), 'flags': 1}) return obj['item']['nm'] def exec_report(self, group, smena, from_time, to_time): # tz = 0 tz = 7200 result_rep = {} report = self.wialon.report_exec_report({ 'reportResourceId': self.res_id, 'reportTemplateId': smena, 'reportObjectId': group[0], 'reportObjectSecId': 0, 'interval': { 'from': from_time, 'to': to_time, 'flags': 0 } }) rows_obj = report['reportResult']['tables'][0]['rows'] rep_row = self.wialon.report_get_result_rows({ "tableIndex": 0, "indexFrom": 0, "indexTo": rows_obj }) # pprint(rep_row) for n in range(0, rows_obj): rep_sub_row = self.wialon.report_get_result_subrows({ "tableIndex": 0, "rowIndex": n }) obj_name = rep_row[n]['c'][1] result_rep[obj_name] = defaultdict(list) for row1 in rep_sub_row: # pprint(row1) if 'Outside shifts' not in row1['c']: unix_key = int(row1['c'][3][:-3]) + tz if smena == 12: work_h = round(float(row1['c'][9]), 2) time_start = int( datetime.datetime.fromtimestamp( int(row1['c'][3][:-3]) + tz).hour) time_end = int( datetime.datetime.fromtimestamp( int(row1['c'][5][:-3]) + tz).hour) duty_h = time_end - time_start else: work_h = round(float(row1['c'][9]), 2) duty_h = round(float(row1['c'][10]), 2) result_rep[obj_name][unix_key] = [ row1['c'][0], # номер строки row1['c'][1], # имя int(row1['c'][3][:-3]) + tz, # начало int(row1['c'][5][:-3]) + tz, # конец row1['c'][6], # часы в работе row1['c'][7], # часы в дежурстве row1['c'][8], # пробег work_h, # часы в работе (коррк) duty_h, # часы в дежурстве (коррк) round(float(row1['c'][8]), 2), # пробег (коррк) row1['c'][11]['t'].replace('Road', 'Трасса').replace( 'km', 'км').replace('from', 'от'), # нач. положение row1['c'][12]['t'].replace('Road', 'Трасса').replace( 'km', 'км').replace('from', 'от'), # кон. положение ] return result_rep
def main(): """ Main Execution Loop """ global wln_handle wln_handle = Wialon() print('-- Login and set SID --') res = login() wln_handle.sid = res['eid'] wln_handle.avl_evts() print('-- Set session flags --') print('------ Set avl_resource flag ') # reports resource avl_resource = wln_handle.core_update_data_flags( spec=[{ 'type': 'type', 'data': 'avl_resource', 'mode': 1, 'flags': flags.ITEM_RESOURCE_DATAFLAG_REPORTS }]) print('------ Set avl_unit_group ') # unit group info avl_u_groups = wln_handle.core_update_data_flags(spec=[{ 'type': 'type', 'data': 'avl_unit_group', 'mode': 1, 'flags': flags.ITEM_RESOURCE_DATAFLAG_REPORTS | flags.ITEM_DATAFLAG_BASE }]) print('------ Set avl_unit ') # unit info avl_unit_res = wln_handle.core_update_data_flags(spec=[{ 'type': 'type', 'data': 'avl_unit', 'mode': 1, 'flags': flags.ITEM_RESOURCE_DATAFLAG_REPORTS | flags.ITEM_DATAFLAG_BASE }]) # TODO : need set date interval by days #st_range = 1421002800 #fin_range = 1421089140 report_running_date = datetime.strptime(sys.argv[1], "%d/%m/%y %H:%M") st_range = int(mktime(report_running_date.timetuple()) + cl_tmz_offset_req) fin_range = int( mktime(datetime.strptime(sys.argv[2], "%d/%m/%y %H:%M").timetuple()) + cl_tmz_offset_req) print('-- Report run : ' + sys.argv[1] + " : " + sys.argv[2]) rep_exec = wln_handle.report_exec_report(reportResourceId=12122660, reportTemplateId=1, reportObjectId=12244464, reportObjectSecId=0, interval={ 'from': st_range, 'to': fin_range, 'flags': 0 }) report_table_list = list() i = 0 for tab in rep_exec['reportResult']['tables']: report_table_list.append( dict(tabIndex=i, lbl=tab['label'], rows=tab['rows'])) i = i + 1 report_table_data = list() for t_rec in report_table_list: res = wln_handle.report_get_result_rows(tableIndex=t_rec['tabIndex'], indexFrom=0, indexTo=t_rec['rows']) report_table_data.append(dict(tabIndex=t_rec['tabIndex'], data=res)) # get 'moto_rashod_virobotka' for i in report_table_data: if 0 == i['tabIndex']: refills = i['data'] if 1 == i['tabIndex']: moto_rate = i['data'] if 2 == i['tabIndex']: remain_fuel = i['data'] if 3 == i['tabIndex']: q_table = i['data'] # list of units of unit group with description and id, fuel_in, fuel_start_per and fuel_end_per u_of_group = dict() for u in avl_u_groups[1]['d']['u']: d = '' f_in = '' r_fl_st = '' r_fl_fn = '' q_start = '' q_end = '' # find WLN_ID, WLN_UNIT_NAME by unit id's list from unit_group for i in avl_unit_res: if u == i['d']['id']: d = i['d']['nm'] # find FUEL_IN param by unit NAME in Zapravki table resul for k in refills: if d == k['c'][1]: f_in = k['c'][3].replace(' lt', '') break # find FUEL_START_PREIOD and FUELD_END_PERIOD by unit NAME for x in remain_fuel: if d == x['c'][1]: r_fl_st = x['c'][3].replace(' lt', '') r_fl_fn = x['c'][4].replace(' lt', '') break # find Q_START and Q_END for z in q_table: if d == z['c'][1]: q_start = z['c'][3] q_end = z['c'][4] break u_of_group[d] = [str(u), f_in, [r_fl_st, r_fl_fn], [q_start, q_end]] # create a result records list to save in database db_table = list() for rec in moto_rate: if rec['c'][2] == '': rec['c'][2] = report_running_date.strftime('%Y-%m-%d') db_rec = dict( place_work=avl_u_groups[1]['d']['nm'], date=rec['c'][2], object_name=rec['c'][1], object_type='', # non fill object_wln_id=u_of_group.get(rec['c'][1])[0], start_time_int=str(int(rec['t1']) + cl_tmz_offset_resp), end_time_int=str(int(rec['t2']) + cl_tmz_offset_resp), motohours=rec['c'][5], energy_p=rec['c'][6].replace(' km', ''), ph_sred='', # non fill nagruzka='', # non fill energy_q='', # non fill fuel_density='', fuel_used=rec['c'][7].replace(' lt', ''), fuel_rate=rec['c'][8].replace(' lt/100 km', ''), fuel_in=u_of_group.get(rec['c'][1])[1], fuel_start_period=u_of_group.get(rec['c'][1])[2][0], fuel_end_period=u_of_group.get(rec['c'][1])[2][1], p_start=rec['c'][9], p_end=rec['c'][10], q_start=u_of_group.get(rec['c'][1])[3][0], q_end=u_of_group.get(rec['c'][1])[3][1], s_start='', # non fill s_end='', # non fill cos_fi=rec['c'][11], local_energy='', # non fill trans_param='') # db_rec db_table.append(db_rec) print('-- Saving results into database') # save into database db_records_saving(db_table) # end report session logout()