Archives 2021

Technical requirements – Operating and Monitoring IoT Networks

With the increasing number of connected devices and sensors, managing and monitoring IoT networks has become a critical task for organizations. Operating and monitoring IoT networks requires a comprehensive approach that includes continuous operations, setting key performance indicators (KPIs) such as the number of active users on an IoT network or the latency expected, setting/monitoring metrics to measure success, and utilizing monitoring capabilities both on-premises and on the cloud. In this chapter, we will delve into the critical aspects of operating and monitoring IoT networks. We will discuss the importance of continuous operations, exploring the challenges of keeping the system running 24/7 and techniques to ensure maximum uptime. Furthermore, we will explore the essential KPIs that organizations need to measure to ensure the success of their IoT projects, including reliability, scalability, and security.

We will examine the different monitoring capabilities available for IoT networks, including on-premises and cloud-based monitoring tools. Specifically, we will dive into the capabilities of Amazon Web Services (AWS) for monitoring IoT networks. By the end of this chapter, readers will have a comprehensive understanding of the best practices and tools for operating and monitoring IoT networks, enabling them to ensure the success of their IoT projects.

In this chapter, we’re going to cover the following main topics:

Continuous operation of IoT systems

Setting KPIs and the metrics for success

Monitoring capabilities on-premises and on the cloud

Practical – operating and monitoring a joke creator with IoT Greengrass

Technical requirements

This chapter will require you to have the following software ready for the practical. The software requirements may include items that you are already familiar with, as well as new software that you may need to acquire or install.

You will need the following software:

Diagram design software of your choice (e.g., Draw.io)

AWS account

OpenAI subscription (to use ChatGPT)

Arduino IDE

ChatGPT is built on the GPT-4 architecture, presenting a big advancement in the domain of natural language processing (NLP). This model has been trained on vast swathes of data, which allows it to generate coherent and contextually relevant textual outputs, simulating human-like conversation with impressive fluency and depth.

The ChatGPT API emerges as a pivotal bridge between different key pieces of hardware and software. The API allows developers to integrate the capabilities of ChatGPT into their own applications, platforms, or services. The implications for the Internet of Things (IoT) are profound due to this. Picture a world where your smart fridge not only tells you are out of milk but also engages in a nuanced conversation about dairy alternatives, their environmental impacts, and recipes you might try. By melding the ChatGPT API with IoT devices, we can create a seamless, intelligent, and interactive ecosystem that responds and converses with us, enhancing our daily experiences and decision-making processes. In this chapter, we will look at integrating this within one such practical.

You can access the GitHub folder for the code that is used in this chapter at https://github.com/PacktPublishing/IoT-Made-Easy-for-Beginners/tree/main/Chapter09/.

Outcome – Designing for Interoperability

You should see something like the following after you have uploaded your code and start moving in front of the PIR motion sensor. When the bot is first started up, you will get the text Bot activated, and when you make a movement, you will get the text Motion detected!:

Figure 8.10 – Expected output on the Telegram bot

And that’s it; you’ve made your interoperable solution! Now, upload the code to GitHub and see if you can also make these modifications to your hardware/code. Now, for further understanding and practice on the concepts that you have learned through this practical, you can try doing the following.

Can you add an LED bulb to the circuit to also react when you receive a movement on the PIR motion sensor?

Can you replace the motion sensor with a DHT11 sensor to send messages to Telegram when the temperature rises above 30°C?

Feel free to use the documentation from the Super Starter Kit to also help you navigate the use cases of each sensor and how to properly use them.

Summary

In this chapter, we learned about what interoperability is, why it is important for IoT, and how we can architect solutions for it while navigating through the challenges that are being posed. We then looked further into how it can be beneficial with our practical in building a Telegram chatbot that alerts you to motion detection based on your ESP32, showing how interoperability is imperative to functioning solutions.

Through the discussions and practical exercises in this chapter, readers have gained a comprehensive understanding of interoperability and its significance in IoT. This understanding forms a foundation for creating robust, scalable, and adaptable IoT solutions. Additionally, by exploring how to architect solutions and navigate challenges, readers have acquired valuable insights and strategies that can be applied to their own projects. This equips readers with a broader toolkit to address the complex demands of IoT environments, making them better prepared to contribute to projects in this domain, or even lead initiatives that require a deep understanding of interoperability.

In the next chapter, we will look at operating and monitoring IoT networks.

Further reading

For more information about what was covered in this chapter, please refer to the following links:

Read more on smart home and how interoperability can support it: https://www.iotforall.com/smart-home-interoperability-fragmented-landscape

Explore more insights in IoT interoperability from a governance perspective: https://www2.gov.bc.ca/assets/gov/british-columbians-our-governments/services-policies-for-government/information-management-technology/information-security/information-security-awareness/its_7am_do_you_know_whats_on_your_network_forescout.pdf

Explore more on the passive infrared sensor from the Adafruit documentation: https://cdn-learn.adafruit.com/downloads/pdf/pir-passive-infrared-proximity-motion-sensor.pdf

Learn more on how to use Telegram from its official website: https://core.telegram.org/

Working with the Arduino IDE – Designing for Interoperability

Interaction with the Telegram bot will be facilitated using the Universal Arduino Telegram Bot Library, a tool created by Brian Lough that simplifies access to the Telegram Bot API. We will ensure that our Arduino IDE has these libraries and procure them if not. Proceeding from here, we can follow the following steps:

First, we need to download the Universal Arduino Telegram Bot library. We can find it at https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot/archive/master.zip.

We then need to include the library. We need to navigate to Sketch > Include Library > Add. Zip the library and add the library:

Figure 8.7 – Pop-up window to add in the Universal Arduino Telegram Bot library

Important note

You should not be installing the library with the Arduino Library Manager, as a deprecated version may be installed instead.

We then must install the ArduinoJson library. To do this, we navigate to Sketch > Include Library > Manage Libraries.

We then search for arduinojson and install its latest version:

Figure 8.8 – Adding in the ArduinoJson library

With the libraries installed, we can now prepare the hardware.

Hardware setup

We will connect the ESP32 to the PIR motion sensor according to the following diagram. It is a motion sensor that detects movement by sensing changes in infrared radiation emitted by warm objects, such as humans or animals, in its field of view:

Figure 8.9 – Circuit diagram for PIR motion sensor

On the PIR to the ESP32, we will connect the negative terminal to GND, the positive terminal to 5V, and the supply terminal to GPIO 27.

Coding it up

We are now ready to start coding up the necessary code to run the program on our Arduino IDE.

We first declare the necessary libraries for the program. The WiFi.h library is used to connect to the internet over Wi-Fi. The WiFiClientSecure.h library establishes a secure client connection to ensure the data communication is encrypted. The UniversalTelegramBot.h library is for controlling the bot on Telegram, and the ArduinoJson.h library handles the JSON data format used by the Telegram bot:
#include <ArduinoJson.h>
#include <UniversalTelegramBot.h>
#include <WiFiClientSecure.h>
#include <WiFi.h>

We then create a struct to hold our network credentials (SSID and password), and you need to replace the “YOUR_SSID_HERE” and “YOUR_PASSWORD_HERE” placeholder values with your own values. Afterward, a TelegramBot class is defined that encapsulates the functionality of the UniversalTelegramBot library, simplifying our use of it later in the code. After this, we instantiate a NetworkCredentials object with bot_token and chat_id values that you need to replace with the personalized token you received for your bot and the user ID you received for your telegram account respectively, wifi_client as an instance of WiFiClientSecure to handle secure connections, and telegramBot as an instance of our TelegramBot class using the bot token and the secure client:
typedef struct {
    const char* network_id = “YOUR_SSID_HERE”;
    const char* network_pass = “YOUR_PASSWORD_HERE”;
} NetworkCredentials;
class TelegramBot {
public:
    TelegramBot(const char* botToken, WiFiClientSecure& client) : bot(botToken, client) {}
    void sendMessage(const char* chatId, const char* msg) {
        bot.sendMessage(chatId, msg, “”);}
private:
    UniversalTelegramBot bot;};
NetworkCredentials networkCredentials;
const char* bot_token = “6344540752:AAHN_xoPfRipHbAf2d5cbceWLnYvxd2uRiI”;
const char* chat_id = “6394755694”;
WiFiClientSecure wifi_client;
TelegramBot telegramBot(bot_token, wifi_client);

Following that, we set up the PIR sensor pin and a Boolean flag to track whether motion is detected. The detectMotion function will be called whenever the sensor pin detects a rising voltage (that is, motion), setting movementDetected to true:
constexpr int PIR_SENSOR_PIN = 27;
volatile bool movementDetected = false;
void IRAM_ATTR detectMotion() {
    movementDetected = true;}

We then need to create a connectWiFi function that sets the ESP32 to operate in Station (STA) mode and then attempts to connect it to the Wi-Fi network using the credentials we provided earlier. It also sets the certificate root on the secure client. It then waits until the ESP32 is connected before continuing the program:
void connectWiFi() {
    WiFi.mode(WIFI_STA);
    WiFi.begin(networkCredentials.network_id, networkCredentials.network_pass);
    wifi_client.setCACert(TELEGRAM_CERTIFICATE_ROOT);
    while (WiFi.status() != WL_CONNECTED) {
        delay(500);}}

Finally, we create setup() and loop() functions. The setup() function initializes serial communication, sets the PIR sensor pin as an input with a pull-up resistor, and attaches an interrupt to it. It then connects to the Wi-Fi and sends a message indicating that the bot is active. The loop() function is the main loop of the program, which constantly checks if motion has been detected. If so, it sends a message and resets the flag:
void setup() {
    Serial.begin(115200);
    pinMode(PIR_SENSOR_PIN, INPUT_PULLUP);
   attachInterrupt(digitalPinToInterrupt(PIR_SENSOR_PIN), detectMotion, RISING);
    connectWiFi();
    telegramBot.sendMessage(chat_id, “Bot activated”);}
void loop() {
    if (movementDetected) {
        telegramBot.sendMessage(chat_id, “Motion detected!”);
        movementDetected = false;}}

As per usual, verify the code to ensure that you have entered everything correctly. Remember that there are four fields you must personally modify with your own information. If everything is done correctly, you should see the upload be successfully completed and your Telegram bot start churning messages after you have clicked Start on it.

And with that, we are ready to test our implementation.

Creating a chatbot – Designing for Interoperability

To receive messages sent from the ESP32 based on the motion caught by the motion sensor, we have to first create a chatbot on the Telegram app:

To start off, we need to download the Telegram app. We can go to Google Play or the App Store and download and install Telegram from there:

Figure 8.3 – Downloading the Telegram app from the App Store

Open Telegram after it has finished installing, search for Botfather, and click on it. Alternatively, you can also open the t.me/botfather link on your smartphone:

Figure 8.4 – Searching for BotFather on the Telegram app

You will then have a window open and be prompted to click the Start button. Click on it accordingly.

To create your bot, follow the steps by typing /newbot and then completing the required information such as the bot’s name and username. Upon successful creation of your bot, a message including a link and bot token will be sent to you. It’s crucial to save the bot token as it will be required for the ESP32 to communicate with the bot. Navigate to the link to get to your bot on Telegram and click Start to prepare to receive messages on your app:

Figure 8.5 – Typing in /newbot to create a new bot

With that, we have created our bot! Now, we need to get a Telegram user ID.

Getting a Telegram user ID

By obtaining your Telegram user ID, you can ensure that your bot only interacts with authorized users. The ESP32 can compare the sender ID of incoming messages to your user ID and either process the message or disregard it, depending on the match. This way, you can filter out any messages that are not from your Telegram account or other approved sources:

To locate IDBot in your Telegram account, either conduct a search through Telegram’s search bar at the top or access this link, t.me/myidbot, through your smartphone.

To obtain your user ID, initiate a conversation with IDBot and enter /getid. You will then receive a response containing your user ID, which should be saved for future reference in this tutorial:

Figure 8.6 – Entering in /getid to see your ID with IDBot

Now that we have obtained our user ID, we can start working on the Arduino segment of the practical.