This post is to understand the Node.js code used to connect to Azure IOT Hub…the complete code can be found This post is just to explain in detail for beginners to understand this quickly.
Navigate to this link…https://azure-samples.github.io/raspberry-pi-web-simulator/
Now we will understand the code in the integrated console window as highlighted below…

So let’s understand each piece of it…
Firstly we need to understand about controlling the GPIO pins of the Raspberry PI…for high performance C language should be preferred language used but most developers are more comfortable with JS/Node…node.js is used.
So in order to read the pins, we should be using package require(‘wiring-pi’);
Next we will be requiring Azure IOT Device Client SDK’s to create a client for interaction with the Raspberry PI and to send messages
require(‘azure-iot-device’)
Based on the protocol being used, we need to import the respective package..
The following table provides the high-level recommendations for your choice of protocol:
Protocol | When you should choose this protocol |
---|---|
MQTT MQTT over WebSocket | Use on all devices that do not require to connect multiple devices (each with its own per-device credentials) over the same TLS connection. |
AMQP AMQP over WebSocket | Use on field and cloud gateways to take advantage of connection multiplexing across devices. |
HTTPS | Use for devices that cannot support other protocols. |
MQTT and AMQP are binary protocols, which result in more compact payloads than HTTPS, this sample uses MQTT Protocol for communication, hence below package is used
require(‘azure-iot-device-mqtt’).Mqtt;
For bme280-sensor, a Node.js I2C module for the Bosch BME280 Humidity, Barometric Pressure, Temperature Sensor, used below
require(‘bme280-sensor’);
Regarding the connection string, you can follow my previous post on getting this from Azure Portal, however there is also an alternative to use SDK’s
There is a function in azure-iot-device
npm (IoT Hub Device SDK for Node.js) to generate device connection string:
import { ConnectionString as DeviceConnectionString } from "azure-iot-device";
const deviceConnectionString = DeviceConnectionString.createWithSharedAccessKey(hostName, device.deviceId, device.authentication.SymmetricKey.primaryKey);
You could also refer to full code here to see how Azure IoT Toolkit generates the device connection string.
The next part is the custom logic on sending messages based on the temperature sensor to Azure IOT Hub and switching on the LED based conditions which is completely based on the needs…
Hope this helps…
Cheers,
PMDY