1

How to create a unit from WLP file using javascript api in kit?

Topic: How to create a unit from WLP file using javascript api in kit?

I am trying to a unit from WLP file using javascript api in kit

I have Successfully created a unit using javascript with following code

 

  var name=$("#nm").val();
        var hwid=$("#hw").val();
        var sess = wialon.core.Session.getInstance();
        var user=sess.getCurrUser();
       
        wialon.core.Session.getInstance().createUnit(user,name, hwid,1152921504606846975,function (code,obj) { // login callback
              
                if (code){ alert(wialon.core.Errors.getErrorText(code)); return; }
               
                oid=obj.getId();
               
        });

Then i tried to update the unit parameters using the following code

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Wialon Playground - Import resource props</title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="https://kit-api.wialon.com/wsdk/script/wialon.js"></script>
   
</head>
<body>
<style>
.btn {
  cursor:pointer;
}
div {
    margin-bottom:20px;
}
#log_cont {
    background-color: #EEEEEE;
    height: 150px;
    overflow-y: scroll;
    font-size:75%;
}
#log_cont table {
    width:100%;
}


</style>


<div id="base">
    <div>
        Append resource props to: <select id="resource" name="resource"><option value="">-- select resource --</option></select><br/>
        From file: <input class="btn" type="file" name="import_file" id="import_file"><br/>
        <input class="btn" id="btn_import_wlp" type="submit" value="Upload & Import">
    </div>
    Data to import:
    <div id="prop_types"></div>
    Log:
    <div id="log_cont">
        <table>
            <tbody id="log"></tbody>
        </table>
    </div>
</div>



<script type="text/javascript">
var importWLP = {
    // generate needed res props system data
      prop_types: {
          poi: {
              library: "resourcePois",
              dataFlag: wialon.item.Resource.dataFlag.poi,
              editFlag: wialon.item.Resource.accessFlag.editPoi,
              methodCreateItem: "createPoi",
              printName: "POIs"
          },
          zones: {
              library: "resourceZones",
              dataFlag: wialon.item.Resource.dataFlag.zones,
              editFlag: wialon.item.Resource.accessFlag.editZones,
              methodCreateItem: "createZone",
              printName: "Geofences"
          },
          jobs: {
              library: "resourceJobs",
              dataFlag: wialon.item.Resource.dataFlag.jobs,
              editFlag: wialon.item.Resource.accessFlag.editJobs,
              methodCreateItem: "createJob",
              printName: "Jobs"
          },
          notifications: {
              library: "resourceNotifications",
              dataFlag: wialon.item.Resource.dataFlag.notifications,
              editFlag: wialon.item.Resource.accessFlag.editNotifications,
              methodCreateItem: "createNotification",
              printName: "Notifications"
          },
          drivers: {
              library: "resourceDrivers",
              dataFlag: wialon.item.Resource.dataFlag.drivers,
              editFlag: wialon.item.Resource.accessFlag.editDrivers,
              methodCreateItem: "createDriver",
              printName: "Drivers"
          },
          trailers: {
              library: "resourceTrailers",
              dataFlag: wialon.item.Resource.dataFlag.trailers,
              editFlag: wialon.item.Resource.accessFlag.editTrailers,
              methodCreateItem: "createTrailer",
              printName: "Trailers"
          },
          reports: {
              library: "resourceReports",
              dataFlag: wialon.item.Resource.dataFlag.reports,
              editFlag: wialon.item.Resource.accessFlag.editReports,
              methodCreateItem: "createReport",
              printName: "Reports"
          }
      },
    init: function () {
        var sess = wialon.core.Session.getInstance();
          
          // flags to specify what kind of data should be returned
          var flags = wialon.item.Item.dataFlag.base;
          for (var i in this.prop_types) {
              sess.loadLibrary( this.prop_types[i].library );
            flags =  wialon.util.Number.or(flags, this.prop_types[i].dataFlag); // 64 bit OR
            $('#prop_types').append('<input type="checkbox" checked="checked" name="'+i+'"> '+this.prop_types[i].printName+'<br>');    // construct prop types checkboxes
          }
          
          // Subscribe on resource data
        sess.updateDataFlags( // load items to current session
            [{type: "type", data: "avl_unit", flags: flags, mode: 0}], // Items specification
            function (code){ // updateDataFlags callback 
                if (code) {
                    importWLP.log("Error: "+wialon.core.Errors.getErrorText(code));
                    return; // exit if error code 
                }
                
                importWLP.res = sess.getItems("avl_unit"); // get loaded 'avl_resource's items
                for (var i = 0; i < importWLP.res.length; i++) {
                    $('#resource').append('<option value="'+ importWLP.res[i].getId() +'">'+ importWLP.res[i].getName() +'</option>');
                }
            });
    
        $('#btn_import_wlp').click( function(){ importWLP.importFromFile.apply( $('#import_file')[0] ) } );
    },
    importFromFile: function (event) {
        var res_id = $('#resource').val(),
            filter = [];

        if ( !res_id ) {
            alert('Select resource to import to');
            return false;
        }
        
        $('#prop_types input[type="checkbox"]:checked').each(function(){
            filter.push( $(this).attr('name') );
        });
        if ( !filter.length ) {
            alert('Select prop types to import');
            return false;
        }
        alert(res_id);
    
        importWLP.log('Import start...');
        
        // this - is input type="file"
        
        
        wialon.exchange.Exchange.importJson([this], function(code, fileData){
            if (code) {
                importWLP.log('Error('+code+')');
                return;
            }
            
            var res = wialon.core.Session.getInstance().getItem(res_id); // get resource by id  
            
            var user_access = res.getUserAccess();
            
            
            // iterate through uploaded files
            wialon.core.Remote.getInstance().startBatch();
            for (var f in fileData.files) {
                // iterate through props
                for (var res_type in importWLP.prop_types) {
                                
                    // check resProp exists and items are in array
                    if ( typeof fileData.files[f][res_type] != 'undefined' && $.isArray( fileData.files[f][res_type] ) && fileData.files[f][res_type].length ) {
                        if ( !wialon.util.Number.and(user_access, importWLP.prop_types[res_type].editFlag) ) {
                            importWLP.log('You don\'t have access to edit '+ res_type +' in ' + res.getName());
                            continue;
                        }
                                                    
                        // iterate through prop items
                        for (var i in fileData.files[f][res_type]) {
                            // create needed prop
                            res[ importWLP.prop_types[res_type].methodCreateItem ]( fileData.files[f][res_type][i], function(code, data) {
                                importWLP.log('Created ' + ( (data && typeof data.n != 'undefined') ? "'" + data.n + "'" : 'prop') + ' ' + (code ? 'Error('+code+')' : 'Ok'));
                            });
                        }
                    }
                }
            }
            wialon.core.Remote.getInstance().finishBatch(function(){
                importWLP.log('Import completed successfully');
                $('#resource').val('');
            });
        });
    },
    log: function(msg) {
        var $log = $('#log'),
            $log_cont = $('#log_cont');
        
        $log.append('<tr><td>' + msg + '</td></tr>');

        $log_cont.animate({
            scrollTop: $log_cont[0].scrollHeight
        }, 300);
    }
}

// execute when DOM ready
$(document).ready(function () {
    wialon.core.Session.getInstance().initSession("https://kit-api.wialon.com"); // init session
    // For more info about how to generate token check
    // http://sdk.wialon.com/playground/demo/app_auth_token
    wialon.core.Session.getInstance().loginToken("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", "", // try to login
    function (code) { // login callback
        if (code) {
            importWLP.log(wialon.core.Errors.getErrorText(code));
            return; // exit if error code
        }
        importWLP.init(); // when login suceed then run init() function
    });
});



</script>
</body>
</html>

but it stops while importing WLP and does not respond afterwards

Please help me with this
i am attaching the WLP file i used

Thanks

Post's attachments

Attachment icon Unit.wlp 2.96 kb, 428 downloads since 2016-05-23 

2

How to create a unit from WLP file using javascript api in kit?

Re: How to create a unit from WLP file using javascript api in kit?

ameen, first of all You are trying to operate with resource's prop_items (zones, poi, jobs, ...) but talking about unit.

Head of Wialon Local Department
Gurtam
3

How to create a unit from WLP file using javascript api in kit?

Re: How to create a unit from WLP file using javascript api in kit?

that was a code to import resources from wlp . and it works fine.

i tried to edit it and i failed to figure out how to import a unit from wlp file. sorry for misleading with that code. please help me to find out a way to import unit parameters from a wlp file and update a unit with that using js api.

thanks

4

How to create a unit from WLP file using javascript api in kit?

(edited by deal 24/05/2016 16:21:35)

Re: How to create a unit from WLP file using javascript api in kit?

It is not so trivial to import unit's properties compared to resource's ones.

At first You can replace resource's propitems with unit's ones: sensors (createSensor), fields (createCustomField), afields (createAdminField), aliases (createCommandDefinition), intervals (createServiceInterval), profile (updateProfileField).
The rest of unit's properties like counters, general, hwConfig, reportProps, advProps, trip, fuel need specific realization.

counters: updateCalcFlags, updateMileageCounter, updateEngineHoursCounter, updateTrafficCounter
general: updateName, updateDeviceSettings, updateUniqueId2, updatePhoneNumber, updatePhoneNumber2, updateAccessPassword
hwConfig: updateHwParams
reportProps: updateReportSettings, updateDriverActivitySettings
advProps: updateMessagesFilter, updateCustomProperty
trip: updateTripDetector
fuel: updateFuelCalcTypes , updateFuelLevelParams, updateFuelConsMath, updateFuelConsRates, updateFuelConsImpulse

More info about each of this methods you can find in docs http://sdk.wialon.com/wiki/en/sidebar/r … /unit/unit

Head of Wialon Local Department
Gurtam
5

How to create a unit from WLP file using javascript api in kit?

Re: How to create a unit from WLP file using javascript api in kit?

thank you deal