Wiring Up the Spark Core to Azure

So in the last post, I wrote about getting my Spark Core to provide temperature and humidity values through variables that are then exposed via the Spark API to pull on demand.

This time, I wanted to take the data on the Core and push it to Azure on a regular basis. This gives me the flexibility to now what the temperature and humidity are without polling for it and allows me to collect the data long term. Also, if I deploy this code to more Spark Core devices, I don’t have to have a process to reach out and grab the data from all of them…they will just send it to me.

The good thing, this isn’t all that difficult when you take advantage of the TCPClient API exposed on the Spark API. It makes it super simple to do an HTTP Get like this:

And to do an HTTP Post is not much different:

I initially had some challenges with sending data to a “plain jane” Web API where the value expected was a string. I thought sending “value=Hello World” would have given me the expected results when debugging, but it kept coming up as “null”. After some investigation, I found this post by Dave Ward to be very helpful in debugging my situation.

So now what I needed was to create a web API that would accept some structured data coming from the Spark Core. There are a number of ways of doing this, but to keep things simple, I  just set up an ASP.NET Web API controller to take in some JSON data. The point of this post isn’t to do anything with the data just yet…just get a hold of it so I can start to do something with it. I haven’t decided whether I just want to have a “real-time” weather station or historical data, so I’m just going to let that go for now.

So here’s my API Controller for the Weather Data:

And here’s the code for posting:

The snprintf on line 31 was probably my biggest roadblock. I haven’t done C++ for a really long time, and figuring how I was going to get the content length while concatenating strings and numbers into a giant JSON string took a bit of work. I finally figured it out, but if there is a better way to do it, I’d love to hear it.

I have a couple of “Hack Tools” posts in the works to publish next week, but I will come back to this to get my Spark Core sending data to the “ConnectTheDots” Azure IoT project.