Quick Thing, To The Cloud!

Posted by The World According to Marc on October 14, 2014

A recently wrote about a little side-project I’ve been working on called Iotiva - a lightweight IoT backend using free and low-cost Azure resources. Here I’ll cover the basics of getting data from your “Thing” to the cloud. Wait. That sounded dirty. How about getting data from your “Device” to the cloud? Hmmm, not much better. I know, my wife refers to my ever-growing collection of microcontrollers and single-board-computers as my “Junk” what about… Ugh. So what if there isn’t way to say it without it sounding like celebrity photo leak. Let’s just get to some code.

Most of the devices I work with have fairly limited capabilities when it comes to pushing bits around a network. In the many cases they have literally zero networking capabilities and I end up using some flavor of serial over wireless to push my bits to a more robust proxy. We’ll gloss over those devices for the time being and assume your device has a least rudimentary network and HTTP support. If you’re interested in hardware options that fit the bill, I highly recommend the Spark.io Core or the <a href=”http://www.amazon.com/gp/product/B00LPESRUK/ref=as_li_tl?ie=UTF8&camp=1789&creative=390957&creativeASIN=B00LPESRUK&linkCode=as2&tag=soapb30-20&linkId=LCABE5KBPNFINAXY”>Raspberry%20Pi</a><img src=”http://ir-na.amazon-adsystem.com/e/ir?t=soapb30-20&l=as2&o=1&a=B00LPESRUK” target=”_blank”>Raspberry Pi</a>, both have robust network and HTTP support with a great community behind them. That said, since every platform is a little different I’m going to use JQuery for my examples here.

Repositories

Iotiva segments user data by Repository ID. Each user gets a unique Repository and it is the associated with all of the user’s data and event queues. Iotiva also supports the concept of a Public Repository which requires no authentication (so please don’t push your home security systems data to it, thanks).

##

Posting Data

Each “Thing” in Iotiva contains a set of “native properties” and a collection of key-value pairs. The native properties represent data that is used by Iotiva itself while the key-value property bag holds a user-defined collection of named strings.

```json { "Id": "Unique ID", "Name": "Thing Name (optional)", "Agent": "Thing Agent (optional)", "Title": "Thing Name or ID if null", "LastChanged": "UNC Date / Time of Last Change", "Properties": { "Prop1": "Val1", "Prop2": "Val2", "Prop3": "Val3" } } ```

Data sent to Iotiva is supplied in application/x-www-form-urlencoded format. I chose this format for it’s simplicity as few devices are capable of natively serializing or parsing JSON. The data in this format looks very similar to URL parameters with each param containing “<property>=<value>” delimited by ampersands.  In our token example above the data sent looks like “grant_type=password&username=user%40domain.com&password=somepassword”.

When posting a Thing the only required property is ID. This is a unique value used to identify a given Thing in a Repository. It can be any string value and is the only value not editable (i.e. changing an ID and posting will create a new Thing). It is also case-sensitive so keep that in mind when formatting your IDs.

Posting also non-destructive, when you supply data it will add or change  values but never delete them. This allows you to make multiple Posts to a Thing with each post updating a single property (useful for seriously memory constrained devices). It also allows you to augment a Thing from another source. This allows you to have an app that reads data from a Thing store app-specific data with the Thing itself (I’ll go into detail when I cover command-and-control scenarios).

Let’s use JQuery to post some data to the Public Repository:

```javascript $.post('https://iotiva.azurewebsites.net//api/thing/MyFirstThing', { Name: "My First Thing", SaySomething: "Hello World" }, function (data) { console.log(JSON.stringify(data, undefined, 2)); }); ```

###

Posting Double-Super-Secret Private Data

We just created our first Thing in the Public Repository with an ID of “MyFirstThing”. This is nice but is isn’t typically what I’m interested in doing, the last thing I need is someone anonymously mucking with my Things. To prevent that we need to use the retrieve an authentication token.  Iotiva uses OAUTH Bearer Tokens for this purpose. Before you can make secure calls to your repository, you generate a Bearer Token by passing a username and password to https://iotiva.azurewebsites.net/token. If the credentials are valid Iotiva will return a JSON object containing the following information:

```json { "access_token": "crazy long encrypted token", "token_type": "bearer", "expires_in": 1209599, "userName": "user@domain.com", ".issued": "Tue, 14 Oct 2014 15:44:37 GMT", ".expires": "Tue, 28 Oct 2014 15:44:37 GMT" } ```

Tokens live for 14 days, after which they must be discarded and a new token generated. This token is passed back to Iotiva in the Authorization header prefaced with the token_type (“bearer”). Once this is included, Iotiva will be able to identify the correct Repository to store the data in.  Let’s take a look at this call using JQuery’s Ajax method:

```javascript var authToken; $.ajax({ type: "POST", url: https://iotiva.azurewebsites.net/token, data: { "grant_type":"password", "username":"user@domain.com", "password":"somepassword" }, success: (data, status) => { authToken = data; console.log(authToken.access_token); }, dataType: 'json' }); ```

Now that we have a valid token (stored in the authToken variable) we need to manipulate the HTTP Headers to include the encrypted token.  With JQuery we can add this header by leveraging the beforeSend feature of the JQuery.Ajax() method. Assuming we already have the token in the authToken variable, we can make a post to JQuery like this:

```javascript $.ajax({ type: "POST", beforeSend: (xhr) => { xhr.setRequestHeader("Authorization", "Bearer " + authToken.access_token) }, url: 'https://iotiva.azurewebsites.net/api/thing/MyFirstThing', data: { Name: "My First Thing", SaySomething: "Hello World" }, success: function (data, status) { console.log(JSON.stringify(data, undefined, 2)); } }); ```

Now that we have the data up in Iotiva, you can see the results at http://iotiva.azurewebsites.net/Home/RepoItems. If you would like to see the actual JSON then fire up your favorite REST tool (I’m partial to PostMan myself) and point it at https://iotiva.azurewebsites.net/api/thing/MyFirstThing.

The examples here are using JQuery and works well for my purpose here but for a more robust JavaScript implementation I would suggest Node.js. Aside from being available just about everywhere, it has an easy to use package manager that makes adding SDKs trivial.  If you are interested in using Node, I recently published the first draft of an Iotiva SDK for Node on GitHub.