element14 Community
element14 Community
    Register Log In
  • Site
  • Search
  • Log In Register
  • About Us
  • Community Hub
    Community Hub
    • What's New on element14
    • Feedback and Support
    • Benefits of Membership
    • Personal Blogs
    • Members Area
    • Achievement Levels
  • Learn
    Learn
    • Ask an Expert
    • eBooks
    • element14 presents
    • Learning Center
    • Tech Spotlight
    • STEM Academy
    • Webinars, Training and Events
    • Learning Groups
  • Technologies
    Technologies
    • 3D Printing
    • FPGA
    • Industrial Automation
    • Internet of Things
    • Power & Energy
    • Sensors
    • Technology Groups
  • Challenges & Projects
    Challenges & Projects
    • Design Challenges
    • element14 presents Projects
    • Project14
    • Arduino Projects
    • Raspberry Pi Projects
    • Project Groups
  • Products
    Products
    • Arduino
    • Avnet Boards Community
    • Dev Tools
    • Manufacturers
    • Multicomp Pro
    • Product Groups
    • Raspberry Pi
    • RoadTests & Reviews
  • Store
    Store
    • Visit Your Store
    • Choose another store...
      • Europe
      •  Austria (German)
      •  Belgium (Dutch, French)
      •  Bulgaria (Bulgarian)
      •  Czech Republic (Czech)
      •  Denmark (Danish)
      •  Estonia (Estonian)
      •  Finland (Finnish)
      •  France (French)
      •  Germany (German)
      •  Hungary (Hungarian)
      •  Ireland
      •  Israel
      •  Italy (Italian)
      •  Latvia (Latvian)
      •  
      •  Lithuania (Lithuanian)
      •  Netherlands (Dutch)
      •  Norway (Norwegian)
      •  Poland (Polish)
      •  Portugal (Portuguese)
      •  Romania (Romanian)
      •  Russia (Russian)
      •  Slovakia (Slovak)
      •  Slovenia (Slovenian)
      •  Spain (Spanish)
      •  Sweden (Swedish)
      •  Switzerland(German, French)
      •  Turkey (Turkish)
      •  United Kingdom
      • Asia Pacific
      •  Australia
      •  China
      •  Hong Kong
      •  India
      •  Korea (Korean)
      •  Malaysia
      •  New Zealand
      •  Philippines
      •  Singapore
      •  Taiwan
      •  Thailand (Thai)
      • Americas
      •  Brazil (Portuguese)
      •  Canada
      •  Mexico (Spanish)
      •  United States
      Can't find the country/region you're looking for? Visit our export site or find a local distributor.
  • Translate
  • Profile
  • Settings
In the Air Design Challenge
  • Challenges & Projects
  • Design Challenges
  • In the Air Design Challenge
  • More
  • Cancel
In the Air Design Challenge
Blog Carbon Footprint Monitoring - AirVantage REST Library
  • Blog
  • Forum
  • Documents
  • Polls
  • Files
  • Events
  • Mentions
  • Sub-Groups
  • Tags
  • More
  • Cancel
  • New
  • Share
  • More
  • Cancel
Group Actions
  • Group RSS
  • More
  • Cancel
Engagement
  • Author Author: xever
  • Date Created: 18 Feb 2015 6:29 PM Date Created
  • Views 827 views
  • Likes 3 likes
  • Comments 2 comments
  • csharp
  • sierra_wireless
  • iot_footprint
  • airvantage
  • in_the_air_design_challenge_2014
  • sierra-wireless
  • in_the_air
Related
Recommended

Carbon Footprint Monitoring - AirVantage REST Library

xever
xever
18 Feb 2015

Introduction

 

For those of you who have been following this post, I had experienced some difficulty accessing data from Sierra Wireless' AirVantage Cloud platform.  Most of the topics posted in this challenge used MQTT protocol to send data to their AirVantage application.  However, it is not possible to use MQTT in retrieving data from AirVantage, and the only way to get retrieve data back is by using AirVantage's REST API. Some very good post from amgalbu and tomaja have covered on how to do this in their posts AirMobile - 12 - AirVantage REST API and In the Air Design Challenge - Pollen & Allergen Sensing – Post 3 (AirVantage Intro).  Again, thanks to you guys who helped me out during that time.  They did a great job and actually offered their helper classes (available in Java, JavaScript and C++).  I now feel its my time to share the love by sharing my versions.  A node.js implementation, that can be used on the BeagleBoneBlack and a C# .NET implementation that can be used in almost all applications using the C# .NET 4.5 Framework.  However though, this library is at its infancy stage and only the basic REST API to send and retrieve data has been implemented, but should make things a lot easier.

 

Prerequisites

 

If you do not have an AirVantage REST application yet, follow the tutorial Using REST API for devices.

 

Using node.js

 

Add the attached airvantage.connection.js file in your workspace.  This particular implementation requires restler, so install it using the npm package manager.  This can be done by typing npm install restler in the bash window.  Once that is installed, modify the airvantage.connection.js file with your credentials.

/* set system credentials here */
var username = "username";      /* username used to log in AirVantage */
var password = "password";      /* password used to log in AirVantage */
var client_id = "use_api_client_id";
var client_secret = "use_api_client_secret";


var serialNo = "SERIAL_NO";     /* this is the SN set when creating a new Gateway */
var connPassword = "CONNECTION_PASSWORD";   /* credential set when creating new System */


/* systems uid */
var system_uid = "system_unique_id";    /* UID found in Systems Details */
var machine_name = "asset_id";          /* as defined in model.app */

 

There are three main functions to use this library.  (1) connect, (2) send_data and (3) get_data.  These exported functions are self-explanatory, refer to snippet below on how to use these functions.

 

var airvantage = require('./airvantage.connection.js');
airvantage.connect(airvantage_connected);
function airvantage_connected()
{
    /* comment/uncomment lines of code to test */   
   
    /* retrieve data from the AirVantage platform */
    airvantage.get_data("machine.temperature");
   
    /* upload data to the AirVantage platform */
    //airvantage.send_data("temperature", 22.4);
    //airvantage.send_data("threshold", 10);
}

 

image

image

image

 

Using C# .NET

 

This particular implementation is a bit more advance and magical than the node.js implementation.  I created this helper library for use with the planned mobile application. Nice features of this version includes:

  • support asynchronous calls
  • built-in serialization and deserialization
  • portable (just one file) although, it requires references to RestSharp.Portable and NewtonSoft.Json  which can be installed using NuGet package manager

 

To use this library, add it to your C# project then refer to Program.cs file (as attached) for usage. The key to serialization/deserialization lies within the representation of the AirVantage Application model into a C# class.  Given the sample model.app below:

 

<?xml version="1.0" encoding="ISO-8859-1"?>
<app:application xmlns:app="http://www.sierrawireless.com/airvantage/application/1.0" 
        type="com.demo.application"
        name="DEMO Application"
        revision="0.0.1">
<capabilities>

  <communication>
   <protocol comm-id="SERIAL" type="REST" />
  </communication>
  
  <data>
   <encoding type="REST">
    <asset default-label="Demo Machine" id="machine">
     <variable default-label="Temperature" path="temperature" type="double"/>
      <setting default-label="Threshold" path="threshold" type="int"/>
     </asset>
   </encoding>
  </data> 


</capabilities>
</app:application>

 

This has been translated into the following C# class:

[DataContract]
public class DemoMachine : SierraWireless.AirVantage.IAppModel
{
    [DataMember(Name = "machine.temperature")]
    public List<AirVantage.DataPoint> Temperature { get; set; }
    [DataMember(Name = "machine.threshold")]
    public List<AirVantage.DataPoint> Threshold { get; set; }


    public DemoMachine()
    {
        Temperature = new List<AirVantage.DataPoint>();
        Threshold = new List<AirVantage.DataPoint>();
    }
}

 

The important things in this class are, and should be observed when using this library:

  1. Class must inherit from SierraWireless.AirVantage.IAppModel interface
  2. Add [DataContract] class attribute
  3. Add [DataMember] property attribute and ensure that the Name value matches the asset id and data path as defined in the model application.

image

 

Conclusion

Sierra Wireless AirVantage data can only be retrieved using REST API.  The two implementations presented in this post are bare minimum but provides a good starting point.

 

Disclaimer

The code presented (attached) in this post has been shared as is, and is meant for educational purposes only.  I have not thoroughly tested the code and is not intended for any production use.

Attachments:
Fullscreen airvantage.connection.js Download
/* set system credentials here */
var username = "username";      /* username used to log in AirVantage */
var password = "password";      /* password used to log in AirVantage */
var client_id = "use_api_client_id";
var client_secret = "use_api_client_secret";

var serialNo = "SERIAL_NO";     /* this is the SN set when creating a new Gateway */
var connPassword = "CONNECTION_PASSWORD";   /* credential set when creating new System */

/* systems uid */
var system_uid = "system_unique_id";    /* UID found in Systems Details */
var machine_name = "asset_id";          /* as defined in model.app */

/* airvantage using rest */
var https = require('https');
var rest = require('restler');
var access_token, token_type, refresh_token;
var time_token_received;

function post(msg)
{
    rest.post('https://na.airvantage.net/device/messages', {
        username: serialNo,
        password: connPassword,
        data : msg
    }).on('complete', function (response) {
        console.log(response);
    });
}

function send(label, value)
{
    var payload = '[{"' + machine_name + "." + label + '" : [{ "value": "' + value + '" }]}]';
    console.log(payload);
    post(payload);
}

function send_multiple(labels, values, count)
{
    var payload = '[';
    
    for(var i=0; i<count; i++)
    {
        payload += '{"' + labels[i] + '":';
        payload += '[{"value":"' + values[i] + '"}]';
        payload += '}';
        
        if(i+1 != count)
            payload += ',';
    }
    
    payload += ']';
    
    console.log(payload);
    post(payload);
}

function request_access_token(callback)
{
    var request = "https://na.airvantage.net/api/oauth/token?grant_type=password&username=";
    request += username;
    request += ("&password=");
    request += password;
    request += ("&client_id=" + client_id + "&client_secret=" + client_secret);
    
    https.get(request, function (result) {
        
        result.on('data', function (d) {
            var json = JSON.parse(d);
            
            if (json.hasOwnProperty('access_token')) {
                access_token = json["access_token"];
                token_type = json["token_type"];
                refresh_token = json["refresh_token"];
                
                console.log("got token");
                
                time_token_received = new Date().getTime();
                
                if(callback != null)
                    callback();
            }
            else {
                access_token = null;
                token_type = null;
                refresh_token = null;
                
                var err = "";
                if (json.hasOwnProperty('error_description'))
                    err += json["error_description"];
                
                console.log("failed getting token " + err);
            }
        });
    });
}


module.exports =
{
    connect : function (callback)
    {
        request_access_token(callback); 
    },
    
    send_multiple_data : function (labels, values, count)
    {
        var thisTime = new Date().getTime();
        
        if ((thisTime - time_token_received) < 1000)
            access_token = null;
        
        if (access_token == null)
            request_access_token(function () { send_multiple(labels, values, count) });
        else
            send_multiple(labels, values, count);
    },

    send_data : function (label, value)
    {
        var thisTime = new Date().getTime();
        
        if ((thisTime - time_token_received) < 1000)
            access_token = null;
        
        if (access_token == null)
            request_access_token(function () { send(label, value) });
        else
            send(label, value);
    },

    get_data : function (data) 
    {
        var request = "https://na.airvantage.net/api/v1/systems/" + system_uid + "/data?access_token="
        request += access_token;
        request += "&ids=" + data;

        console.log("getting " + data);

        https.get(request, function (result) {
            console.log("statusCode: ", result.statusCode);
            console.log("headers: ", result.headers);    

            result.on('data', function (d) 
            {
                process.stdout.write(d); 
            });
        });
    },
}
AirVantage.cs.zip
Program.cs.zip
  • Sign in to reply
  • xever
    xever over 10 years ago in reply to DAB

    C# is pretty straightforward to learn, if you know C then you have the basics sorted.  If you know Java or C++ then it makes it easier, since you will have the concepts of OOP.  But once you get the hang of it all, it becomes a really powerful tool in your arsenal. image  It just so happened I've been using it since version 1.1 and been always my preferred language.

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
  • DAB
    DAB over 10 years ago

    Nice update.

    Good detail.

     

    How hard was it to learn C#?

     

    DAB

    • Cancel
    • Vote Up 0 Vote Down
    • Sign in to reply
    • More
    • Cancel
element14 Community

element14 is the first online community specifically for engineers. Connect with your peers and get expert answers to your questions.

  • Members
  • Learn
  • Technologies
  • Challenges & Projects
  • Products
  • Store
  • About Us
  • Feedback & Support
  • FAQs
  • Terms of Use
  • Privacy Policy
  • Legal and Copyright Notices
  • Sitemap
  • Cookies

An Avnet Company © 2025 Premier Farnell Limited. All Rights Reserved.

Premier Farnell Ltd, registered in England and Wales (no 00876412), registered office: Farnell House, Forge Lane, Leeds LS12 2NE.

ICP 备案号 10220084.

Follow element14

  • X
  • Facebook
  • linkedin
  • YouTube