Home Automation Using AWS | MQTT | NodeMCU

 


IoT based Home Automation enables to control of home appliances by using the internet. This technology allows us to control or monitor any devices at any place with our fingertips. It assures energy conservation and optimized use of money and energy.

In this article, we will learn how to design a simple home automation system for controlling ceiling lights by using an IoT development board & AWS. Let's first start with the requirements that we will need to design the IoT project.

Hardware Requirements:

  1. NodeMcu - ESP8266 12E, is a very versatile IoT development board between IoT developers. Buy from here.
  2. Relay Module - You can use 1 or 2 or 4 channel relays for this project. Buy from here.

Software Requirements:

  1. Arduino Ide: Download from here, click on "Just Download".
  2. Amazon Web Services (AWS): Visit the AWS website.
  3. Open SSL: Download it from here.
  4. Arduino Sketch Data Uploader: Download it from here.

Hardware Connection:

The connection between the NodeMCU and the Relay Module by using jumper wires involves the following steps:

  1. The Supply pin (Vcc) is connected to the 5V of the Relay module which is further connected to the Vin terminal of the NodeMCU using a Red jumper wire.

  2. The Input pin (IN) is connected to the digital pin 5 of the NodeMCU using a Yellow jumper wire.

  3. The Input pin (IN) is connected to the digital pin 5 of the NodeMCU using a Yellow jumper wire.

After connecting NodeMCU with the relay, connect the ceiling light with AC load to the Normally open and the common pin of the relay module. circuit connection will be shown like this:


Amazon Web Service Setup:

Open the AWS website by clicking the AWS Management Console link to create your account. It will charge two rupees from your debit card to create the AWS account. In AWS it includes three to four processes to control the light. They are Generation of Certificates, Creation of policy, and Attachment of policy to the Certificates. Let us understand these processes in detail step by step:

Certificates:

  1. On creating the account set the service to 'IoT Core' and click the manage icon ---> Thing option to create a new thing.

  2. Now add the device that we are going to use to the Thing registry and create the certificate.

  3. Download the Certificate and also the private key and CA certificate.

Policy:

  1. To create a policy, Click on the Secure icon ---> Policy option.

  2. Enter New Name and add the action and Resource ARN has '*' to all the IoT resources.

  3. Allow the Effect Option.

  4. Click the Create icon to create the policy.

Attachment of policy to certificates:

  1. To create a policy, Click on the Secure icon ---> Policy option.

  2. Enter New Name and add the action and Resource ARN has '*' to all the IoT resources.

  3. Allow the Effect Option.

  4. Click the Create icon to create the policy.

The downloaded Certificates are in PEM format. Hence the NodeMCU understands only the DER format, now convert it into DER format. For this conversion, the OpenSSL tool is used. To open OpenSSL click the Command prompt in the Desktop or use this link to download the OpenSSL tool.

After Downloading, Open the tool and copy-paste the following Comm

openssl x509 -in xxxxxxx-certificate.crt -out cert.der -outform DER openssl rsa -in xxxxxxx-private.pem.key -out private.der -outform DER openssl x509 -in AmazonRootCA1.pem -out ca.der -outform DER


Before copy-pasting, the commands remove the xxxxxxx and replace it with the names of the certificate that we downloaded from the AWS. Now run the commands individually the format of the certificates is changed from PEM to DER and stored in the directory where you have your project code.

The Next step is to upload these files into the file system of NodeMCU. Open the Arduino IDE now go to Tool and search for "ESP8266 Sketch Data Upload" if the tool is not available download the tool from the given ESP8266 Sketch Data Upload link. Download the tool extract it & cut it from your downloads & go to the directory where your "Arduino Ide" is installed now go to "tools" now past the extracted folder in this directory.

Now Open Arduino Ide under the tools section you will find ESP8266 Sketch Data Upload and upload the certificates to the file system of the NodeMCU. Then copy-paste the esp8266 coding attached below in the Arduino IDE. Before compiling the program select the required specifications for the NodeMCU board and enter the endpoint value in the code. To get the endpoint value go to the AWS account setting option and copy-paste the endpoint in the code.

Complete Code:

# include <FS.h>
# include <ESP8266WiFi.h>
# include <PubSubClient.h>
# include <NTPClient.h>
# include <WiFiUdp.h>

# define Relay D5

// Your network.

const char* ssid =   "xxxxxxxxx";
const char* password = "xxxxxxxxxx";

WiFiUDP ntpUDP;
NTPClient timeClient(ntpUDP, "pool.ntp.org");

const char* AWS_endpoint = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

void callback(char* topic, byte* payload, unsigned int length)
{
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  for (int i = 0; i < length; i++)
  {
    Serial.print((char)payload[i]); //printing payload content
  }
    // Extracting the controlling command from the Payload to 
Controlling LED from AWS
char relay = (char)payload[63]; Serial.print("Relay Status= "); Serial.println(relay); if (relay == 49) // 49 is the ASCII value of 1 { digitalWrite(Relay, HIGH); Serial.println("LED_State changed to HIGH"); } else if (relay == 48) // 48 is tge ASCII value of 0 { digitalWrite(Relay, LOW); Serial.println("LED_State changed to LOW"); } Serial.println(); } WiFiClientSecure espClient; PubSubClient client(AWS_endpoint, 8883, callback, espClient); long lastMsg = 0; char msg[50]; int value = 0; void setup_wifi() { delay(10); espClient.setBufferSizes(512, 512); // We start by connecting to a network Serial.println(); Serial.println("Connecting to.."); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { delay(500); Serial.print("."); } Serial.println(""); Serial.println("WiFi Connected"); Serial.print("IP address: "); Serial.println(WiFi.localIP()); timeClient.begin(); while (!timeClient.update()) { timeClient.forceUpdate(); } espClient.setX509Time(timeClient.getEpochTime()); } void reconnect() { // Loop until we're reconnected while (!client.connected()) { Serial.print("Attempting MQTT connection..."); // Attempt to connect if (client.connect("ESPthing")) { Serial.println("connected"); // Once connected, publish an announcement... client.publish("Status", "Relay status"); // ... and resubscribe client.subscribe("Relay State"); } else { Serial.print("failed, rc="); Serial.print(client.state()); Serial.println(" try again in 5 seconds"); char buf[256]; espClient.getLastSSLError(buf,256); Serial.print("WiFiClientSecure SSL error: "); Serial.println(buf); // Wait 5 seconds before retrying delay(5000); } } } void setup() { Serial.begin(9600); Serial.setDebugOutput(true); // initialize digital pin as an output. pinMode(Relay, OUTPUT); setup_wifi(); delay(1000); if (!SPIFFS.begin()) { Serial.println("Failed to mount file system"); return; } Serial.print("Heap: "); Serial.println(ESP.getFreeHeap()); // Load Certifacates file File cert = SPIFFS.open("/cert.der", "r"); //replace cert.crt eith your uploaded file name if (!cert) { Serial.println("Failed to open cert file"); } else { Serial.println("Success to open cert file"); } delay(1000); if (espClient.loadCertificate(cert)) { Serial.println("Certificate Loaded"); } else { Serial.println("Certificate not Loaded"); } // Load Private Key File private_key = SPIFFS.open("/private.der", "r"); if (!private_key) { Serial.println("Failed to open Private key"); } else { Serial.println("Success to open Private key"); } delay(1000); if (espClient.loadPrivateKey(private_key)) { Serial.println("Private Key Loaded"); } else { Serial.println("Private Key not Loaded"); } // Load CA Files File ca = SPIFFS.open("/ca.der", "r"); if (!ca) { Serial.println("Failed to open ca"); } else { Serial.println("Success to open ca"); } delay(1000); if (espClient.loadCACert(ca)) { Serial.println("ca Loaded"); } else { Serial.println("ca not Loaded"); } Serial.println("Heap"); Serial.println(ESP.getFreeHeap()); } void loop() { if (!client.connected()) { reconnect(); } client.loop(); }


Comments

Popular posts from this blog

Tinkercad - DC Motor Speed Control