Chroscielski

Just another programming blog

Internet of Things, Microsoft Azure, Node.js

Azure IoT Hub: Node.js sender and receiver (part 1)

Preface

Internet of Things – usually we deal with this phrase doubly while writing software. First, in terms of some hardware effect like: move that servo 15 degrees right. Second (and that’s what we’ll focus on in this article), with regard to communication between devices or services. Today we are going to develop a simple program in Node.js sending messages to another program via Azure IoT Hub. This solution will be highly scalable and secure thanks to cloud architecture.

If you are already familiar with Azure Event Hub, you may think why use Azure IoT Hub instead of it. Here’s why.

Azure IoT Hub Overview

Why Azure IoT Hub?

Azure IoT Hub is a highly scalable, secure solution. It supports MQTT, AMQP and HTTP communication protocols. As you can see in the picture, Azure IoT Hub allows us (not only, but we’ll focus on that) to send and receive messages from IoT devices. You can deploy your application on any Node.js-ready IoT device of course, but we are not going to discuss it in this article. Instead, we’ll build a pure Node.js application simulating such a device. It is not required to write in Node.js, but it is my preferred language. If you want to use some other language, e.g. C#, you can do it as well using this documentation.

Deploying Azure IoT Hub

  1. Go to the Azure Portal and log in
  2. Click on the plus in the left upper corner, to deploy a new service. Select Internet of Things label, then IoT Hub.
  3. Type in a name for your service. Type a name for a new resource group or an select existing one – it is a storage for your services, helping you keep your Azure account clean and tidy. If it comes to the resource groups, you should usually have one resource group, for each project services.
  4. Hit the create button, then you should get a success notification:

 

That’s it! Your cloud service is ready!

If you want to know more about Azure IoT Hub check out the documentation.

Why Node.js?

Couple of reasons:

  • We are going to need it anyway, to use IoT Hub Explorer CLI Tool
  • It is easy to configure and run
  • It runs smoothly on Windows (also Windows 10 IoT Core), Mac and Linux (e.g. Raspbian, Ubuntu)
  • NPM
  • Simplicity
  • I just like it 😉

I assume this in not a Node.js course, but in case: you can download Node.js environment here.

IoT Hub Explorer

Iothub-explorer is an open source tool written in Node.js, which will allow us to use some features of Azure IoT Hub not available from Azure Portal.

To install it, simply type npm install -g iothub-explorer  in your command line tool.

You can also check the source of this tool under: https://github.com/Azure/iothub-explorer.

Ok. So what exactly do we need iothub-explorer for? We’re going to create a device identity in our cloud service. To achieve that:

  1. Copy your connection string from iothubowner policy
  2. Open your command line tool
  3. Type iothub-explorer login <connection_string>
  4. Type iothub-explorer create <name_for_device>
  5. Type iothub-explorer logout

You can check out your devices list via Azure Portal:

Here you can also get a device unique connection string.

Sender

Sender, as the name suggests will be an application responsible for sending messages to the cloud. This is a module which simulates our IoT-enabled device. You can have as many of these modules as you want (of course, if your IoT Hub Service plan allows it).

To create the project:

  1. Open your command line tool
  2. Make an empty directory, which will be your project directory (e.g. C:/Projects/Sender)
  3. Go to this directory
  4. Make a new file named main.js
  5. Type npm init  to create an empty project
  6. Type npm install --save azure-iot-device
  7. Type npm install --save azure-iot-device-mqtt
  8. Paste the code below into main.js file

I find this code simple enough not to comment on it. In short: every second it takes randomized temperature for specified (hard-coded) coordinates and sends this data into Azure IoT Hub. Anyway, if you have any questions write a comment, I will respond for sure.

To run a project type node main.js  in a command line while being in your project directory. Press Ctrl+C to stop.

Receiver

Receiver will be an independent program receiving messages from our sender module. All messages will go through our Azure IoT Hub service. The quantity of receivers can be huge. Every receiver can do a different  task, depending on the message. Number of receivers is also not limited by your service plan.

To create the receivers project:

  1. Open your command line tool
  2. Make an empty directory, which will be your project directory (e.g. C:/Projects/Reveiver)
  3. Go to this directory
  4. Make a new file named main.js
  5. Type npm init  to create an empty project
  6. Type npm install --save azure-event-hubs
  7. Paste the code below into main.js file

In the code above there is something that may concern you – what are partitions? Well, you can think of them as message pipes. Messages from one device always go to the same partition. That’s why we’re using a map function to produce a message receiver for each separate partition.

Up and running:

  1. Open two entities of your command line tool
  2. In the first one go to your receivers project directory and type node main.js
  3. In the second one go to your senders project directory and again type node main.js
  4. You should be able to see in the command line window that some communication occurs
  5. To kill this processes simply press Ctrl+C in each window

Sample session:

If everything went well, you should have the number of overall sent messages displayed in your IoT Hub dashboard (it appears after a while):

Summary

As you can see, making two scalable application modules with Node.js and Azure IoT Hub is pretty simple. With just a couple lines of code, we were able to communicate our sender and receiver services.  Thanks to high reliability of Azure, we don’t have to worry about our communication hub server.

If something is unclear or you’ve got some difficulties/opinions, don’t be shy to leave a comment. I’ll try to help you.

We are going to expand the functionality of this system using Azure Stream Analytics, SQL Database and Power BI in the next tutorial.

Further reading

IoT Hub Learning Path


//Grammar checked by Dorota Jasińska

Related Posts

7 Comments

  1. Jonathan Salazar

    Excellent explanation, thank you sou much!!

  2. iceiceice

    I have a question. The sender sends messages to the Azure IoT Hub. The receiver receives them. Now, why the receiver is dependant on sender? What i mean to say is that no matter if sender is closed and the receiver is started after the sender has stopped, the receiver must receive the messages that the sender just sent to the cloud before it was stopped. In this case, this doesn’t happen.

    • Chroscielski

      Check out the receivers source code. There is an invocation of createReceiver function which takes couple of parameters. What you are asking about is the third parameter (“options”) with startAfterTime property. In the example it’s been set to Date.now(), just change it to the time you want (for example current time minus the offset you want to receive) and you will get older messages as well.

  3. Mei

    We used the Receiver code (with our own specific information). It runs fine for sometime (can be minutes or 1 or 2 hours), then stops receiving messages. It doesn’t recover unless we stop and restart again.

    Is it a known issue?
    We installed node v8.4.0.

    • Chroscielski

      This code was intended to be as short as possible to make it more understandable. Answering your question: yes, there may occur an exception (like this: “the message container is being closed”). This happens, because message container (internal Azure microservice dedicated to host event hub) instances are sometimes restarted, so you have to simply handle that case in your logic (just reconnect). Let me know if that was the case. Good luck!

  4. Mei

    Thank you very much for the information.
    On some occasions I did get “the message container is being closed” exception.  But most of the time where the receiver stopped receiving messages, there is no exception or warning.  I wonder if it’s a different problem?

Leave a Reply

Theme by Anders Norén