Example #1
0
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 []
Example #2
0
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()