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

Windows Docker Containers can make WIN32 API calls, use COM and ASP.NET WebForms

After the last post , I received two interesting questions related to Docker and Windows. People were interested if we do Win32 API calls from a Docker container and if there is support for COM. WIN32 Support To test calls to WIN32 API, let’s try to populate SYSTEM_INFO class. [StructLayout(LayoutKind.Sequential)] public struct SYSTEM_INFO { public uint dwOemId; public uint dwPageSize; public uint lpMinimumApplicationAddress; public uint lpMaximumApplicationAddress; public uint dwActiveProcessorMask; public uint dwNumberOfProcessors; public uint dwProcessorType; public uint dwAllocationGranularity; public uint dwProcessorLevel; public uint dwProcessorRevision; } ... [DllImport("kernel32")] static extern void GetSystemInfo(ref SYSTEM_INFO pSI); ... SYSTEM_INFO pSI = new SYSTEM_INFO(...

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.51 EF 6.0.2 VS2013 It see...

Navigating Cloud Strategy after Azure Central US Region Outage

 Looking back, July 19, 2024, was challenging for customers using Microsoft Azure or Windows machines. Two major outages affected customers using CrowdStrike Falcon or Microsoft Azure computation resources in the Central US. These two outages affected many people and put many businesses on pause for a few hours or even days. The overlap of these two issues was a nightmare for travellers. In addition to blue screens in the airport terminals, they could not get additional information from the airport website, airline personnel, or the support line because they were affected by the outage in the Central US region or the CrowdStrike outage.   But what happened in reality? A faulty CrowdStrike update affected Windows computers globally, from airports and healthcare to small businesses, affecting over 8.5m computers. Even if the Falson Sensor software defect was identified and a fix deployed shortly after, the recovery took longer. In parallel with CrowdStrike, Microsoft provi...