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(...

How to audit an Azure Cosmos DB

In this post, we will talk about how we can audit an Azure Cosmos DB database. Before jumping into the problem let us define the business requirement: As an Administrator I want to be able to audit all changes that were done to specific collection inside my Azure Cosmos DB. The requirement is simple, but can be a little tricky to implement fully. First of all when you are using Azure Cosmos DB or any other storage solution there are 99% odds that you’ll have more than one system that writes data to it. This means that you have or not have control on the systems that are doing any create/update/delete operations. Solution 1: Diagnostic Logs Cosmos DB allows us activate diagnostics logs and stream the output a storage account for achieving to other systems like Event Hub or Log Analytics. This would allow us to have information related to who, when, what, response code and how the access operation to our Cosmos DB was done. Beside this there is a field that specifies what was th...

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills)

Cloud Myths: Cloud is Cheaper (Pill 1 of 5 / Cloud Pills) The idea that moving to the cloud reduces the costs is a common misconception. The cloud infrastructure provides flexibility, scalability, and better CAPEX, but it does not guarantee lower costs without proper optimisation and management of the cloud services and infrastructure. Idle and unused resources, overprovisioning, oversize databases, and unnecessary data transfer can increase running costs. The regional pricing mode, multi-cloud complexity, and cost variety add extra complexity to the cost function. Cloud adoption without a cost governance strategy can result in unexpected expenses. Improper usage, combined with a pay-as-you-go model, can result in a nightmare for business stakeholders who cannot track and manage the monthly costs. Cloud-native services such as AI services, managed databases, and analytics platforms are powerful, provide out-of-the-shelve capabilities, and increase business agility and innovation. H...