def main(ide, flag): wialon = Wialon() try: login = wialon.token_login(token='5ed8fe38981e59aa088f19b358849ddc3FD03E8E9549E2CB60A4380A13FC1AB97ECBB73C') except WialonError as e: print(e) return wialon.sid = login['eid'] parm = { "id": ide # "itemsType": "avl_unit", # "propName": "id", # "propValueMask": f"{valuemask}", # "sortType": "sys_name", # "propType": "sys_name, sys_unique_id", } interval = {"from": 0, "to": 0} try: units = wialon.core_search_items(, force=1, flags=flag, **interval) except WialonError as e: print(e) return return units
def get_data_cars(carid, dtfrom, dtto): wialon = Wialon() array = [] params = params_get_report(carid, dtfrom, dtto) # print(params) try: login = wialon.token_login(token=TOKEN) except WialonError as e: print("Error while login:"******"Error while execturing report:", e) # logout is necessary, for preventing error with a lot of session from one ip try: wialon.core_logout() except WialonError as e: print("Error while logout")
def get_drivers(): wialon = Wialon() array = [] try: login = wialon.token_login(token=TOKEN) except WialonError as e: print("Error while login:"******"Error while execturing report:", e) # logout is necessary, for preventing error with a lot of session from one ip try: wialon.core_logout() except WialonError as e: print("Error while logout")
def test(requestbot): req_b = str(requestbot) token, ID, TimeFrom, TimeTo = req_b.split(';') if token == 'db1cee3b1f964df20f8d163a1423b6c6286A919144720D152383E5DD77C6113AD31CDC9A': token = 'db1cee3b1f964df20f8d163a1423b6c67D562ED72C4E60F2797A1247C61C9B977DBC7DCA' y, m, d, h, min, s = TimeFrom.split('-') y1, m1, d1, h1, min1, s1 = TimeTo.split('-') t1 = datetime.datetime(int(y), int(m), int(d), int(h), int(min), int(s)) from_time = int(str(time.mktime(t1.timetuple()))[:-2]) - 25200 t2 = datetime.datetime(int(y1), int(m1), int(d1), int(h1), int(min1), int(s1)) to_time = int(str(time.mktime(t2.timetuple()))[:-2]) - 25200 wialon = Wialon() try: login = wialon.token_login(token=str(token)) except WialonError as e: return ('Error while login') wialon.sid = login['eid'] res_id = api_wialon_dwnData(wialon) if res_id: calb1, pr_count, pr_dist, units4, units5 = execute_report(res_id, wialon, ID, from_time, to_time) else: return 'No API resourses' milleage = int(str(calb1[1][1])[:calb1[1][1].find("."):]) callback_retr = '' callback_retr += str(calb1[1][1])[:calb1[1][1].find(" "):] + ';' probeg = calb1[1][1].replace("km", 'км.') callback_retr += str(calb1[2][1]) + ';' motoh = calb1[2][1] callback_retr += str(calb1[4][1])[:calb1[4][1].find(" "):] + ';' start_fuel = calb1[4][1].replace("l", 'л.') callback_retr += str(calb1[3][1])[:calb1[3][1].find(" "):] + ';' end_fuel = calb1[3][1].replace("l", 'л.') callback_retr += str(calb1[5][1])[:calb1[5][1].find(" "):] + ';' fuel_up = calb1[5][1].replace("l", 'л.') callback_retr += str(calb1[6][1])[:calb1[6][1].find(" "):] + ';' fuel_down = calb1[6][1].replace("l", 'л.') callback = handler1(calb1, milleage, pr_count, pr_dist, from_time, to_time, wialon, units4, units5, res_id, ID) callback_retr += str(callback.data_status) + ';' + str(callback.track_status) \ + ';' + str(callback.dut_status) + ';' + str(callback.ign_status) + ';' data_obj = wialon.core_search_item({"id": ID, "flags": 0x00000001}) name_obj = data_obj['item']['nm'] start_period = "{}.{}.{}. {}:{}:{}".format(d, m, y, h, min, s) end_period = '{}.{}.{}. {}:{}:{}'.format(d1, m1, y1, h1, min1, s1) return render_template('test_first.html', name=name_obj, probeg=probeg, motoh=motoh, start_fuel=start_fuel, end_fuel=end_fuel, fuel_up=fuel_up, fuel_down=fuel_down, start_period=start_period, end_period=end_period, data_status=callback.data_status, data_info=callback.data_info, track_status=callback.track_status, track_info=callback.track_info, dut_status=callback.dut_info, ign_status=callback.ign_info, callback=callback_retr)
def get_id_report(): wialon = Wialon() array = [] params_getid_report = { "spec": { "itemsType": "avl_resource", "propName": "reporttemplates", "propValueMask": "*", "sortType": "reporttemplates" }, "force": 1, "flags": "0x00002001", "from": 0, "to": 0 } try: login = wialon.token_login(token=TOKEN) except WialonError as e: print("Error while login:"******"Error while execturing report:", e) # logout is necessary, for preventing error with a lot of session from one ip try: wialon.core_logout() except WialonError as e: print("Error while logout")
def index(requestbot): req_b = str(requestbot) token, ID, TimeFrom, TimeTo = req_b.split(';') if token == 'db1cee3b1f964df20f8d163a1423b6c6286A919144720D152383E5DD77C6113AD31CDC9A': token = 'db1cee3b1f964df20f8d163a1423b6c67D562ED72C4E60F2797A1247C61C9B977DBC7DCA' y, m, d, h, min, s = TimeFrom.split('-') y1, m1, d1, h1, min1, s1 = TimeTo.split('-') t1 = datetime.datetime(int(y), int(m), int(d), int(h), int(min), int(s)) from_time = int(str(time.mktime(t1.timetuple()))[:-2]) - 25200 t2 = datetime.datetime(int(y1), int(m1), int(d1), int(h1), int(min1), int(s1)) to_time = int(str(time.mktime(t2.timetuple()))[:-2]) - 25200 wialon = Wialon() login = None try: login = wialon.token_login(token=str(token)) except WialonError as e: return ('Error while login') wialon.sid = login['eid'] res_id = api_wialon_dwnData(wialon) if res_id: calb1, pr_count, pr_dist, units4, units5 = execute_report(res_id, wialon, ID, from_time, to_time) else: return 'No API resourses' milleage = int(str(calb1[1][1])[:calb1[1][1].find("."):]) callback_retr = '' callback_retr += str(calb1[1][1])[:calb1[1][1].find(" "):] + ';' callback_retr += str(calb1[2][1]) + ';' callback_retr += str(calb1[4][1])[:calb1[4][1].find(" "):] + ';' callback_retr += str(calb1[3][1])[:calb1[3][1].find(" "):] + ';' callback_retr += str(calb1[5][1])[:calb1[5][1].find(" "):] + ';' callback_retr += str(calb1[6][1])[:calb1[6][1].find(" "):] + ';' callback = handler1(calb1, milleage, pr_count, pr_dist, from_time, to_time, wialon, units4, units5, res_id, ID) callback_retr += str(callback.data_status) + ';' + str(callback.track_status) \ + ';' + str(callback.dut_status) + ';' + str(callback.ign_status) + ';' return callback_retr
def logon_session(): wialon = Wialon() try: login = wialon.token_login(token=TOKEN) except WialonError as e: print("Error while login:"******"Error while execturing report:", e) # logout is necessary, for preventing error with a lot of session from one ip try: wialon.core_logout() except WialonError as e: print("Error while logout")
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 norm(requesthandler): req_b = str(requesthandler) token, ID, TimeFrom, TimeTo, start_fuel_n, consumption_n, fuel_up = req_b.split(';') if token == 'db1cee3b1f964df20f8d163a1423b6c6286A919144720D152383E5DD77C6113AD31CDC9A': token = 'db1cee3b1f964df20f8d163a1423b6c67D562ED72C4E60F2797A1247C61C9B977DBC7DCA' start_fuel_n.replace(',', '.') consumption_n.replace(',', '.') fuel_up.replace(',', '.') start_fuel_n, consumption_n, fuel_up = float(start_fuel_n), float(consumption_n), float(fuel_up) y, m, d, h, min, s = TimeFrom.split('-') y1, m1, d1, h1, min1, s1 = TimeTo.split('-') t1 = datetime.datetime(int(y), int(m), int(d), int(h), int(min), int(s)) from_time = int(str(time.mktime(t1.timetuple()))[:-2]) - 25200 t2 = datetime.datetime(int(y1), int(m1), int(d1), int(h1), int(min1), int(s1)) to_time = int(str(time.mktime(t2.timetuple()))[:-2]) - 25200 callback_consum_info = "" wialon = Wialon() login = None try: login = wialon.token_login(token=str(token)) except WialonError as e: return ('Error while login') wialon.sid = login['eid'] res_id = api_wialon_dwnData(wialon) if res_id: volume_tank, end_fuel_f, fuel_up_f, fuel_down, start_fuel_f = execute_report2(res_id, wialon, ID, from_time, to_time) else: return 'No API resourses' consum_f = round(start_fuel_n + fuel_up - end_fuel_f, 2) callback = handler2(volume_tank, consum_f, fuel_up_f, fuel_down, fuel_up, consumption_n, start_fuel_n, start_fuel_f) callback_retr = '' if callback.fuel_up: callback_retr += "Заправка не сходится:" + str(round(fuel_up_f - fuel_up, 2)) + ";" callback_consum_info += "Заправка не сходится:" + str(round(fuel_up_f - fuel_up, 2)) + '\n' elif callback.nedoliv: callback_retr += "Недолив:" + str(round((fuel_up - fuel_up_f), 2)) + ";" callback_consum_info += "Недолив:" + str(round((fuel_up - fuel_up_f), 2)) + '\n' else: callback_retr += "Ok;" # Заправка ОК if callback.fuel_down: callback_retr += str(round(fuel_down, 2)) + ";" else: callback_retr += "0;" # Слив ОК if callback.fuel_start: callback_retr += "Нач ур. не сходится!;" callback_consum_info += "Нач ур. не сходится! \n" else: callback_retr += "Ok;" # Нач ур. ОК """Дальше один из 4 вариантов""" if callback.short: callback_retr += "Короткая поездка, списание по норме;" callback_consum_info += "Короткая поездка, списание по норме \n" elif callback.perejog: callback_retr += "Пережог топлива:" + str(round(consum_f - consumption_n, 2)) + ", списание по факту;" callback_consum_info += "Пережог топлива:" + str(round(consum_f - consumption_n, 2)) + ", списание по факту" elif callback.economy: callback_retr += "Экономия топлива:" + str(round(consumption_n - consum_f, 2)) + ", списание по факту;" callback_consum_info += "Экономия топлива:" + str(round(consumption_n - consum_f, 2)) + ", списание по факту" else: callback_retr += "Расход сходится;" callback_consum_info += "Расход сходится" callback_retr += str(consum_f) + ';' end_fuel_n = float(start_fuel_n) - float(consumption_n) + float(fuel_up) data_obj = wialon.core_search_item({"id": ID, "flags": 0x00000001}) name_obj = data_obj['item']['nm'] start_period = '{}.{}.{}. {}:{}:{}'.format(d, m, y, h, min, s) end_period = '{}.{}.{}. {}:{}:{}'.format(d1, m1, y1, h1, min1, s1) consum_smt = float(start_fuel_f) + (fuel_up_f) - (end_fuel_f) consum_smt = round(consum_smt, 2) write_db(ID, name_obj, start_period, end_period, start_fuel_n, start_fuel_f, end_fuel_n, end_fuel_f, fuel_up, fuel_up_f, fuel_down, consumption_n, consum_smt, consum_f, callback_consum_info) return callback_retr
def test_norm(requesthandler): req_b = str(requesthandler) token, ID, TimeFrom, TimeTo, start_fuel_n, consumption_n, fuel_up = req_b.split(';') if token == 'db1cee3b1f964df20f8d163a1423b6c6286A919144720D152383E5DD77C6113AD31CDC9A': token = 'db1cee3b1f964df20f8d163a1423b6c67D562ED72C4E60F2797A1247C61C9B977DBC7DCA' start_fuel_n.replace(',', '.') consumption_n.replace(',', '.') fuel_up.replace(',', '.') start_fuel_n, consumption_n, fuel_up = float(start_fuel_n), float(consumption_n), float(fuel_up) y, m, d, h, min, s = TimeFrom.split('-') y1, m1, d1, h1, min1, s1 = TimeTo.split('-') t1 = datetime.datetime(int(y), int(m), int(d), int(h), int(min), int(s)) from_time = int(str(time.mktime(t1.timetuple()))[:-2]) - 25200 t2 = datetime.datetime(int(y1), int(m1), int(d1), int(h1), int(min1), int(s1)) to_time = int(str(time.mktime(t2.timetuple()))[:-2]) - 25200 wialon = Wialon() login = None try: login = wialon.token_login(token=str(token)) except WialonError as e: return ('Error while login') wialon.sid = login['eid'] res_id = api_wialon_dwnData(wialon) if res_id: volume_tank, end_fuel_f, fuel_up_f, fuel_down, start_fuel_f = execute_report2(res_id, wialon, ID, from_time, to_time) else: return 'No API resourses' consum_f = round(start_fuel_n + fuel_up - end_fuel_f, 2) callback = handler2(volume_tank, consum_f, fuel_up_f, fuel_down, fuel_up, consumption_n, start_fuel_n, start_fuel_f) callback_retr = '' if callback.fuel_up: diff = round(fuel_up_f - fuel_up, 2) callback_retr += "Заправка не сходится:" + str(round(fuel_up_f - fuel_up, 2)) + ";" callback_fuel_info = "Заправка не сходится, разница = {}".format(diff) elif callback.nedoliv: diff = round((fuel_up - fuel_up_f), 2) callback_retr += "Недолив:" + str(round((fuel_up - fuel_up_f), 2)) + ";" callback_fuel_info = "Недолив, объемом = {}".format(diff) else: callback_retr += "Ok;" # Заправка ОК callback_fuel_info = "Заправка ОК" if callback.fuel_down: callback_retr += str(round(fuel_down, 2)) + ";" else: callback_retr += "0;" # Слив ОК diff_start = round(float(start_fuel_n) - float(start_fuel_f)) if callback.fuel_start: callback_retr += "Нач ур. не сходится!;" callback_start_info = "Нач ур. не сходится! Разница в {} л.".format(diff_start) else: callback_retr += "Ok;" # Нач ур. ОК callback_start_info = "Нач. уровень сходится" """Дальше один из 4 вариантов""" if callback.short: pr_volume_consum = round((float(consumption_n) / float(volume_tank)) * 100, 2) callback_retr += "Короткая поездка, списание по норме;" callback_consum_info = "Короткая поездка, потрачено {}% от бака, списание по норме".format(pr_volume_consum) elif callback.perejog: diff = round(consum_f - consumption_n, 2) callback_retr += "Пережог топлива:" + str(round(consum_f - consumption_n, 2)) + ", списание по факту;" callback_consum_info = "Пережог топлива, объем = {}, списание по факту".format(diff) elif callback.economy and not callback.nedoliv and not callback.fuel_down: diff = round(consumption_n - consum_f, 2) callback_retr += "Экономия топлива:" + str(round(consumption_n - consum_f, 2)) + ", списание по факту;" callback_consum_info = "Экономия топлива, объем = {}, списание по факту".format(diff) else: callback_retr += "Расход сходится" callback_consum_info = 'Расход сходится (В пределах погрешности)' if float(fuel_down) > 0: fuel_down_info = 'Слито {}! Необходимо провести служебное расследование'.format(fuel_down) else: fuel_down_info = 'Cливов не зафиксировано' end_fuel_n = float(start_fuel_n) - float(consumption_n) + float(fuel_up) data_obj = wialon.core_search_item({"id": ID, "flags": 0x00000001}) name_obj = data_obj['item']['nm'] start_period = '{}.{}.{}. {}:{}:{}'.format(d, m, y, h, min, s) end_period = '{}.{}.{}. {}:{}:{}'.format(d1, m1, y1, h1, min1, s1) consum_smt = float(start_fuel_f) + (fuel_up_f) - (end_fuel_f) consum_smt = round(consum_smt, 2) write_db(ID, name_obj, start_period, end_period, start_fuel_n, start_fuel_f, end_fuel_n, end_fuel_f, fuel_up, fuel_up_f, fuel_down, consumption_n, consum_smt, consum_f, callback_consum_info, Test=True) return render_template('test_norm.html', name=name_obj, start_p=start_period, end_period=end_period, start_fuel_n=start_fuel_n, start_fuel_f=start_fuel_f, consumption_n=consumption_n, consum_f=consum_f, fuel_up=fuel_up, fuel_up_f=fuel_up_f, fuel_down=fuel_down, callback=callback_retr, callback_fuel_info=callback_fuel_info, callback_consum_info=callback_consum_info, volume_tank=volume_tank, end_fuel_n=end_fuel_n, end_fuel_f=end_fuel_f, callback_start_info=callback_start_info, fuel_down_info=fuel_down_info, consum_smt=consum_smt)
from pprint import pprint from wialon import Wialon, WialonError, flags wialon = Wialon() login = None token = 'cc06cce5395ef07d3e3407ae05e79a9808EC7AC81B47A18DA69B534A43958D265B22FB46' try: login = wialon.token_login(token=token) except WialonError as e: print("Error while login") wialon.sid = login['eid'] def api_wialon_dwnObj(name): custom_flag = flags.ITEM_DATAFLAG_BASE spec = { 'itemsType': 'avl_unit', 'propName': 'sys_name', 'propValueMask': '*' + name + '*', 'sortType': 'sys_name' } interval = {"from": 0, "to": 0} units = wialon.core_search_items(spec=spec, force=1, flags=custom_flag,
def get_engine_hours(reportResourceId=14587158, reportTemplateId=29, start_timestamp=1604174400, end_timestamp=1604519999, reportObjectId=15021052): try: logger.debug('Creating wialon instance') wialon_api = Wialon() # old username and password login is deprecated, use token login result = wialon_api.token_login( token= '8ad9141cc16c305ffa5f0fff9df4e273BFE4CB6398F53061F6315C002FAD111C8271BD93' ) wialon_api.sid = result['eid'] result = wialon_api.avl_evts() logger.debug('Eval events %s', result) # exit() result = wialon_api.report_cleanup_result({}) logger.debug('report_cleanup_result %s', result) result = wialon_api.report_exec_report({ "reportResourceId": reportResourceId, "reportTemplateId": reportTemplateId, "reportTemplate": None, "reportObjectId": reportObjectId, "reportObjectSecId": 0, "interval": { "flags": 117440512, "from": start_timestamp, "to": end_timestamp }, "remoteExec": 1, "reportObjectIdList": [] }) # print("report_exec_report ", result) # {"remoteExec":1} logger.debug('report_exec_report %s', result) all_units_rows = [] if result.get('remoteExec') == 1: """ Wait until result response comes back to you """ while True: result = wialon_api.report_get_report_status({}) # print("report_get_report_status", result) logger.debug('report_get_report_status %s', result) if result.get('status') == "4": result = wialon_api.report_apply_report_result({}) logger.debug('report_apply_report_result %s', result) # print("report_apply_report_result", result) break result = wialon_api.report_select_result_rows({ "tableIndex": 0, "config": { "type": "range", "data": { "from": 0, "to": 0xfffff, "level": 0, "unitInfo": 1 } } }) # print("Select Top Level: ", result) logger.debug('report_select_result_rows %s', result) index = 0 batch_rows = [] for r in result: # print("Top Level Rows: ", r) batch_rows.append({ "svc": "report/select_result_rows", "params": { "tableIndex": 0, "config": { "type": "row", "data": { "rows": [f"{index}"], "level": 0, "unitInfo": 1 } } } }) index += 1 # print("core/batch", batch_rows) unit_rows = wialon_api.core_batch(batch_rows) # logger.debug('core_batch %s', len(unit_rows)) for unit_data in unit_rows: all_units_rows += unit_data logger.debug('All Rows: %s', len(all_units_rows)) # print("All Rows: ", len(all_units_rows)) wialon_api.core_logout() return all_units_rows except WialonError as e: logger.error('Wialon Error %s', e) return []