Udara

Software Application

Blog Post

Arduino IoT Cloud with Node.js | A Comprehensive Guide to Sending IoT Device Data to Arduino IoT Cloud with Node Js 2024

A Comprehensive Guide to Sending IoT Device Data to Arduino IoT Cloud with Node.js
Embark on a journey into the heart of the Internet of Things (IoT) with Arduino as we guide you through the intricacies of connecting and transmitting data from your IoT devices to the Arduino IoT Cloud. In this comprehensive blog post, we delve into the seamless integration of Node.js and the “arduino-iot-js” library, offering a step-by-step roadmap to set up a robust server, establish a secure connection, and handle incoming data with finesse.
The adventure begins with the creation of a Node.js server using Express.js, laying the foundation for a responsive and scalable IoT application. Harnessing the power of the “arduino-iot-js” library, our guide walks you through the intricacies of connecting to the Arduino IoT Cloud, ensuring a secure conduit for your device data.
But the exploration doesn’t end there – we extend our journey to the IoT Cloud platform itself. Learn how to set up a project, create a new “Thing” (device), and obtain the coveted Device ID and Secret Key. These credentials become the golden keys to unlock the potential of your IoT device, providing secure access to the IoT Cloud.
To ensure a smooth implementation, we include detailed installation and execution instructions. Discover how to effortlessly install required npm packages and run your Node.js server, setting the stage for robust testing using tools like Postman or curl.
Whether you’re a seasoned IoT enthusiast or a newcomer to the realm of connected devices, this guide empowers you to navigate the intricacies of IoT development. Uncover the secrets of establishing a secure connection, handling diverse data streams, and contributing to the evolution of responsive and scalable IoT applications.
Join us on this Node.js journey to the IoT Cloud – where innovation meets connectivity, and your IoT projects come to life. Happy coding!

Table of content

1.Introduction

In the dynamic landscape of the Internet of Things (IoT), efficiently collecting and managing data from devices is essential. This blog post explores the process of sending IoT device data to the Arduino IoT Cloud using Node.js. Leveraging the power of the “arduino-iot-js” library, this guide provides a step-by-step approach to set up a Node.js server, connect it to the Arduino IoT Cloud, handle incoming data, and obtain the necessary credentials.

2. Prerequisites

Before delving into the implementation, ensure you have the following prerequisites:
  • Node.js installed on your server.
  • An Arduino IoT Cloud account.
  • Basic knowledge of JavaScript and Node.js.

3. Setting Up a Project in Arduino IoT Cloud

Now, let’s guide you through setting up a project in the Arduino IoT Cloud to obtain the Device ID and Secret Key.

3.1 Create an Arduino IoT Cloud Account

If you don’t have an Arduino IoT Cloud account, start by creating one: Visit the Arduino IoT Cloud website: https://create.arduino.cc/iot. Click on “Get Started for Free” or “Sign Up” to create a new account. Follow the on-screen instructions to complete the account creation process.

3.2 Create a New Thing (Device)

Once you have an account, log in to the Arduino IoT Cloud: In the Arduino IoT Cloud dashboard, click on “Things” in the left-hand menu. Click the “+ CREATE THING” button.

3.3 Configure Your Device

Thing Type: Choose a suitable thing type for your project (e.g., “MKR WiFi 1010” or any other compatible device). Thing Name: Provide a unique and descriptive name for your device. Properties: Define the properties (variables) that your device will send to the cloud. For example, you can add properties like “temperature,” “humidity,” etc. Events: Optionally, define events to trigger actions based on certain conditions. Webhooks: Configure webhooks if you want to integrate external services.

3.4 Save and Deploy

After configuring your device, click the “SAVE” button. Once saved, click the “DEPLOY” button to deploy your configuration.

3.5 Get Device ID and Secret Key

After deployment, click on the “SETTINGS” tab for your thing. You will find the “Device ID” and “MQTT API Key” (Secret Key) under the “Connect your devices” section. Note down the Device ID and Secret Key, as you will use them in your Node.js application.
Now, your Node.js application is set up to send data to the Arduino IoT Cloud using the specific Device ID and Secret Key associated with your device.

4. Setting Up the Node.js Server

Installing Required Packages

Before running the server, install the required npm packages:
npm install express body-parser arduino-iot-js
We’ll begin by setting up a Node.js server to handle incoming data from IoT devices. The server, created using Express.js, includes the necessary modules for JSON data parsing.
// Include necessary libraries and modules
const express = require("express");
const bodyParser = require("body-parser");
const { ArduinoIoTCloud } = require("arduino-iot-js");

// Create an Express app
const app = express();
const port = 3001;

// Use bodyParser for JSON parsing
app.use(bodyParser.json());

app.post("/endpoint", (req, res) => {

  let type = req.body.type;
  let Device_ID = req.body.did;
  let s_Keys = req.body.skey;
  let latitude = req.body.lat;
  let longitude = req.body.lon;

  let location = {
    lat: latitude,
    lon: longitude,
  };


  let TL = req.body.tl;
  let SG = req.body.sg;
  let CT = req.body.ct;

  let response = {
    id: type,
    type: "0",
  };

  sendData(type,Device_ID,s_Keys,location,TL,SG,CT).then((value)=>{
    console.log(response);
    res.send(response);
  });

});

// ... Rest of the server setup ...

5. Connecting to Arduino IoT Cloud

To establish a connection to the Arduino IoT Cloud, utilize the “arduino-iot-js” library within the sendData function.
// ... Previous code ...

const sendData = async (type, Device_ID, s_Keys, location, TL, SG, CT) => {
 // Connect to Arduino IoT Cloud
    const client = await ArduinoIoTCloud.connect({
        deviceId: Device_ID,
        secretKey: s_Keys,
        onDisconnect: (message) => console.log(message),
      });

      if(type == 0 ){
        client.sendProperty("gps_location", location);
        client.sendProperty("level_sensor", TL);
        client.sendProperty("signal_strength", SG);
        client.sendProperty("temperature", CT);
  
      }else if( type == 1 ){
        client.sendProperty("signal_strength", SG);
        client.sendProperty("temperature", CT);
      }else if( type == 2 ){
        client.sendProperty("gps_location", location);
      }else if( type == 3 ){
        client.sendProperty("level_sensor", TL);
      }
};

// ... Rest of the server code ...
Full Server.js
//in server/server.js
const express = require("express");
const bodyParser = require("body-parser");
const { ArduinoIoTCloud } = require("arduino-iot-js");

const app = express();
const port = 3001;

app.use(bodyParser.json());

app.get("/", (req, res) => {
  res.send("Welcome to my server!");
});

const sendData = async (type , Device_ID , s_Keys , location , TL , SG , CT  ) => {

      const client = await ArduinoIoTCloud.connect({
        deviceId: Device_ID,
        secretKey: s_Keys,
        onDisconnect: (message) => console.log(message),
      });

      if(type == 0 ){
        client.sendProperty("gps_location", location);
        client.sendProperty("level_sensor", TL);
        client.sendProperty("signal_strength", SG);
        client.sendProperty("temperature", CT);
  
      }else if( type == 1 ){
        client.sendProperty("signal_strength", SG);
        client.sendProperty("temperature", CT);
      }else if( type == 2 ){
        client.sendProperty("gps_location", location);
      }else if( type == 3 ){
        client.sendProperty("level_sensor", TL);
      }

};

app.post("/endpoint", (req, res) => {

  let type = req.body.type;
  let Device_ID = req.body.did;
  let s_Keys = req.body.skey;
  let latitude = req.body.lat;
  let longitude = req.body.lon;

  let location = {
    lat: latitude,
    lon: longitude,
  };


  let TL = req.body.tl;
  let SG = req.body.sg;
  let CT = req.body.ct;

  let response = {
    id: type,
    type: "0",
  };

  sendData(type,Device_ID,s_Keys,location,TL,SG,CT).then((value)=>{
    console.log(response);
    res.send(response);
  });

});

app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

6. Execution Instructions

Now you can run the Node.js server. In the terminal, use the following command:
node server.js
This will start the server, and you should see a message indicating that it is running on the specified port (in this case, port 3001).
To test the application, you can use a tool like Postman or simply send HTTP requests using a script or a tool like curl. Here’s an example using curl to simulate a POST request:
curl -X POST -H "Content-Type: application/json" -d '{
  "type": 0,
  "did": "your_device_id",
  "skey": "your_secret_key",
  "lat": 123.456,
  "lon": 789.012,
  "tl": "your_level_sensor_data",
  "sg": "your_signal_strength_data",
  "ct": "your_temperature_data"
}' http://localhost:3001/endpoint
Make sure to replace placeholders like “your_device_id,” “your_secret_key,” and others with your actual data. You should receive a response from the server indicating the success of the operation. Feel free to explore more advanced testing and automation options based on your preferences and project requirements.With these instructions, you should be able to install, run, and test the Node.js server for sending IoT device data to the Arduino IoT Cloud.

7. Conclusion

In this comprehensive guide, we explored the process of setting up a Node.js server to send IoT device data to the Arduino IoT Cloud. By leveraging the “arduino-iot-js” library and creating an Express.js server, we established a seamless connection between IoT devices and the cloud.
We covered essential steps such as initializing the server, connecting to the Arduino IoT Cloud, handling incoming data, and providing clear installation and execution instructions. The flexibility of the code allows for customization to suit specific project requirements, making it a solid foundation for building scalable and responsive IoT applications.
As you embark on your IoT journey, remember the importance of security and scalability. Ensure that your device IDs and secret keys are handled securely, and consider implementing additional features and optimizations as your project evolves
By following this guide and adapting the provided code to your needs, you’ll be well-equipped to create powerful IoT solutions that leverage the capabilities of the Arduino IoT Cloud. Happy coding, and may your IoT endeavors bring innovation and efficiency to the connected world!