Skip to main content

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

Previous post: http://vunvulearadu.blogspot.ro/2016/12/iot-home-project-part-3-nodejs-module.html
GitHub source code: https://github.com/vunvulear/IoTHomeProject/tree/master/nodejs-grovepi-azureiot

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)
    }
  }.bind(this));
}

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 !!!!')
            console.log(err)
        },
        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
                    });
                    deviceCommunication.sendMessage(dataToSend);
                }
            }
        }
    })

    board.init();
});
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:

Conclusion
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

Comments

Popular posts from this blog

How to check in AngularJS if a service was register or not

There are cases when you need to check in a service or a controller was register in AngularJS.
For example a valid use case is when you have the same implementation running on multiple application. In this case, you may want to intercept the HTTP provider and add a custom step there. This step don’t needs to run on all the application, only in the one where the service exist and register.
A solution for this case would be to have a flag in the configuration that specify this. In the core you would have an IF that would check the value of this flag.
Another solution is to check if a specific service was register in AngularJS or not. If the service was register that you would execute your own logic.
To check if a service was register or not in AngularJS container you need to call the ‘has’ method of ‘inhector’. It will return TRUE if the service was register.
if ($injector.has('httpInterceptorService')) { $httpProvider.interceptors.push('httpInterceptorService&#…

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 http://go.microsoft.com/fwlink/?LinkId=260882 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 …

Run native .NET application in Docker (.NET Framework 4.6.2)

Scope
The main scope of this post is to see how we can run a legacy application written in .NET Framework in Docker.

Context
First of all, let’s define what is a legacy application in our context. By a legacy application we understand an application that runs .NET Framework 3.5 or higher in a production environment where we don’t have any more the people or documentation that would help us to understand what is happening behind the scene.
In this scenarios, you might want to migrate the current solution from a standard environment to Docker. There are many advantages for such a migration, like:

Continuous DeploymentTestingIsolationSecurity at container levelVersioning ControlEnvironment Standardization
Until now, we didn’t had the possibility to run a .NET application in Docker. With .NET Core, there was support for .NET Core in Docker, but migration from a full .NET framework to .NET Core can be costly and even impossible. Not only because of lack of features, but also because once you…