Skip to main content

[IoT Home Project] Part 4 - Sending temperature data from Raspberry PI to Azure IoT Hub

Previous post:
GitHub source code:

This post focus on the communication between Raspberry PI and Azure IoT Hub. Until now we developed the Raspberry PI application that is able to read sensors data from GrovePI using Node.JS libraries. Now is the moment to write the Node.JS module that sends temperature data from Raspberry PI to Azure IoT Hub.

Creating Azure IoT Hub instance
The first step is to create a new instance of Azure IoT Hub. Don't worry about Azure costs. There is a free tire of Azure IoT Hub that allows us to send 8.000 messages per day for free. For testing and home use scenarios, I think that this is more than enough.
A nice tutorial on how you can create a new instance of Azure IoT Hub can be found here. Once you create the instace, you'll need the access tokens that can be taken from 'Shared Access Policies' tab.

Node.JS module
There are two modules that are required to install on the device:
  • azure-iothub: used to register a device
  • azure-iot-device: used to communicate between device and Azure IoT Hub instance
Below are the install commands that can be runned from terminal (Integrated Terminal) of Visual Studio code.
npm install azure-iothub
npm install azure-iot-device

Register your device
Each device that is allowed to communicate with Azure IoT Hub needs to be registered. In normal scenarios, this step is done in a management portal or from another system. To simplify the flow, we will register automatically any device, using the device name.
// Register the given device or retrives the device key. In a real scenario, this shall never be run on the same system
// The device key shall be provided from an external source
DeviceCommunication.prototype.createDevice = function () {
  var device = new AzureIoTHub.Device(null);
  device.deviceId = this.deviceId;

  this.registry.create(device, function (err, deviceInfo, res) {
    if (err) {
      this.registry.get(device.deviceId, this.updateDeviceInfo.bind(this));
    if (deviceInfo) {
      this.updateDeviceInfo(err, deviceInfo)

Our 'createDevice' function will register a new device using the provided deviceId. DeviceId is just a string that we can specify in constructor. If the device is already registered, the access token (primary key) is stored for later use.

As you can see, in constructor, you can specify the connection string to your Azure Iot Hub instance, host name and device id. I specified the default value for my setup. Later on, we will extract this information in a configuration file.

Sending a message to Azure IoT Hub
To be able to send a message to Azure IoT Hub you need the connection string of the device. This string can be easily constructed from information that we already have from the previous step.
var deviceConnectionString = `HostName=${this.azureIoTHubHostName};DeviceId=${this.deviceInfo.deviceId};SharedAccessKey=${this.deviceInfo.authentication.SymmetricKey.primaryKey}`;
The message that needs to be send is in JSON format. It is important at this step to specify the deviceID as a property of the message. This will be used later on to identify the source of the message.
Because device registration is an action that can takes a few seconds (based on internet connection quality), the constructor accept as parameter an 'onInit' function that is called after the registration is done with success and device access token are available.
var deviceCommunication = new DeviceCommunication(onInit = () => {
    var board = new Board({
        debug: true,
        onError: function (err) {
            console.log('!!!! Error occurred !!!!')
        onInit: function (res) {
            if (res) {
                console.log('GrovePi Version :: ' + board.version())

                var grovePiSensors = new GrovePiSensors();
                while (true) {
                    var sensorsData = grovePiSensors.getAllSensorsData();

                    var dataToSend = JSON.stringify({
                        deviceId: 'vunvulearaspberry',
                        temperature: sensorsData.temp

As you can see above, on 'onInit' we are initialize the GrovePi board, read sensor information and send the temperature to Azure IoT Hub.

Validating the code
Because in this moment we don't have yet a way to check if the messages where send with success or not we can take a look on the Usage panel of Azure Iot Hub portal. There, the counter that display the number of messages that were send in the current day shall increase.
See below:

In this post we wrote a module that register a device to Azure IoT Hub and sends temperature information that are collected from GrovePI sensor. Now, we have a system that is able to collect information from hardware sensors and send them to Azure backend.

Next step
The next step is to collect all the sensor information and push them to Azure. On top of this we shall be able to specify the interval of data collection.

Next post: [IoT Home Project] Part 5 - Send data to Azure IoT Hub, control time interval and refac the configuration information


Popular posts from this blog

ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded

Today blog post will be started with the following error when running DB tests on the CI machine:
threw exception: System.InvalidOperationException: The Entity Framework provider type 'System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer' registered in the application config file for the ADO.NET provider with invariant name 'System.Data.SqlClient' could not be loaded. Make sure that the assembly-qualified name is used and that the assembly is available to the running application. See for more information. at System.Data.Entity.Infrastructure.DependencyResolution.ProviderServicesFactory.GetInstance(String providerTypeName, String providerInvariantName) This error happened only on the Continuous Integration machine. On the devs machines, everything has fine. The classic problem – on my machine it’s working. The CI has the following configuration:

TeamCity.NET 4.51EF 6.0.2VS2013
It seems that there …

Entity Framework (EF) TransactionScope vs Database.BeginTransaction

In today blog post we will talk a little about a new feature that is available on EF6+ related to Transactions.
Until now, when we had to use transaction we used ‘TransactionScope’. It works great and I would say that is something that is now in our blood.
using (var scope = new TransactionScope(TransactionScopeOption.Required)) { using (SqlConnection conn = new SqlConnection("...")) { conn.Open(); SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = conn; sqlCommand.CommandText = ... sqlCommand.ExecuteNonQuery(); ... } scope.Complete(); } Starting with EF6.0 we have a new way to work with transactions. The new approach is based on Database.BeginTransaction(), Database.Rollback(), Database.Commit(). Yes, no more TransactionScope.
In the followi…

GET call of REST API that contains '/'-slash character in the value of a parameter

Let’s assume that we have the following scenario: I have a public HTTP endpoint and I need to post some content using GET command. One of the parameters contains special characters like “\” and “/”. If the endpoint is an ApiController than you may have problems if you encode the parameter using the http encoder.
using (var httpClient = new HttpClient()) { httpClient.BaseAddress = baseUrl; Task<HttpResponseMessage> response = httpClient.GetAsync(string.Format("api/foo/{0}", "qwert/qwerqwer"))); response.Wait(); response.Result.EnsureSuccessStatusCode(); } One possible solution would be to encode the query parameter using UrlTokenEncode method of HttpServerUtility class and GetBytes method ofUTF8. In this way you would get the array of bytes of the parameter and encode them as a url token.
The following code show to you how you could write the encode and decode methods.