AUTOMATRIX: A Comprehensive Home Automation System

Published  December 13, 2023   0
Home Automation System using NodeMCU

Automatrix is a cutting-edge home automation app that empowers users to seamlessly control and manage their smart devices through an intuitive and user-friendly interface. Leveraging the MQTT protocol, Automatrix establishes a secure and reliable connection between the user's smartphone and the connected devices, enabling effortless remote control and automation capabilities.

Key Features:

  1. Comprehensive Device Management: Automatrix provides a centralized hub for managing a wide range of smart devices, including lights, thermostats, switches, and security systems. Users can easily organize devices by room or function, ensuring effortless navigation and control.
  2. Intuitive Scene Creation: Automatrix simplifies scene creation, allowing users to establish automated routines for various scenarios. Manual scenes enable users to activate multiple devices with a single tap, while scheduled scenes trigger device actions based on predetermined times or conditions.
  3. Personalized User Experience: Automatrix greets users with personalized messages based on the time of day, creating a welcoming and engaging experience. Additionally, the app provides users with the ability to switch between dark and light modes to suit their preferences.

Components Used:

  • NodeMCU(ESP8266)
  • 2-Channel Relay Module
  • MCT 2E
  • MOC 3021
  • BT-136 Triac
  • W04 Bridge Rectifier
  • 47K Resistors (x2)
  • 10K Resistor (x1)
  • 1K Resistor (x1)
  • 330e Resistors (x3)
  • 2-pin Terminal Connector

Home Automation Circuit

Technical Architecture:

Automatrix employs a robust and scalable architecture, encompassing three primary components:

  1.  Android App: The Automatrix app serves as the central command center for managing your smart home ecosystem. Its intuitive and user-friendly interface provides seamless access to a range of features, empowering you to effortlessly control your connected devices, create automated routines, and personalize your app experience. With its intuitive interface, comprehensive features, and user-centric design, the Automatrix app stands as an indispensable tool for managing your smart home ecosystem. By empowering you to control your connected devices, create automated routines, and personalize your app experience, Automatrix puts your smart home management in the palm of your hand.
  2. MQTT Server: At the heart of Automatrix's robust functionality lies a dedicated MQTT server, the unsung hero that orchestrates seamless communication between the Android app and the connected devices. This lightweight yet powerful protocol ensures real-time data exchange, enabling timely and reliable device control.   Unlike traditional client-server architectures, MQTT employs a publish-subscribe model, where devices publish their status updates to the server, and the server, in turn, broadcasts these updates to subscribed clients. This efficient and scalable approach minimizes network traffic and ensures that only interested parties receive relevant information.
  3.  APIs: The Automatrix app's seamless interaction with the MQTT server is made possible by a set of meticulously crafted APIs, which serve as intermediaries between the app's user-facing interface and the server's communication protocols. These APIs act as translators, converting user actions into MQTT commands and interpreting device status updates into meaningful app notifications.

Functional Overview:

Automatrix has 5 tabs:

  1. Home
  2. Devices
  3. Add Device
  4. Automation
  5. Menu

1. Home:

Automatrix Home Tab Image

Upon launching the Automatrix app, users are greeted by the Home tab, a vibrant and informative display showcasing the current time, real-time weather conditions, and a personalized greeting tailored to the time of day. This welcoming interface sets the stage for an effortless home automation experience.

2. Devices:

Automatrix Device Tab Image1Automatrix Device Tab Image2Automatrix Device Tab Image3

The Devices tab serves as the epicenter of Automatrix's device management capabilities, providing users with an organized and comprehensive overview of their connected smart home devices. The categorized device list, responsive toggle switches, and visual device icons empower users to effortlessly control and manage their smart home appliances, ensuring a seamless and intuitive experience. It also provides the feature of changing the intensity of the device, like the brightness of the bulb or the speed of the fan.

3. Add Device:

Automatrix Add Device Tab

Expanding the Automatrix ecosystem is made effortless with the Add Devices tab. This user-friendly interface simplifies the process of pairing new devices, meticulously guiding users through the connection procedure. Gone are the days of complex manuals and confusing troubleshooting steps. Automatrix streamlines the process, ensuring even novice users can seamlessly integrate new smart home appliances into their Automatrix network.
Upon navigating to the Add Devices tab, users are greeted by a clear and concise set of instructions, accompanied by visual aids and prompts. The intuitive interface guides users through each step of the pairing process, ensuring seamless device integration. Whether it's scanning QR codes, entering device IDs, or connecting through Wi-Fi, Automatrix anticipates potential user queries and provides contextual assistance throughout the pairing process, minimizing the need for technical expertise.

4. Automation:

Automation Tab 1Automation Tab 2

Automation Tab 3Automation Tab 4

The Automation tab empowers users to orchestrate their smart home environment through the creation and management of scenes. Whether it's setting the ambiance for a relaxing evening or ensuring a well-lit morning wake-up, scenes provide the power to automate daily tasks and enhance the overall living experience.

5. Menu:

Automatrix Menu Tab

The Menu tab serves as a centralized hub for managing user preferences and accessing important app information. Nestled within this tab, users can effortlessly navigate to their user profile settings, where they can update their personal details, review app version information, and access the app's privacy policy. Additionally, a dedicated contact section provides users with direct access to the app's developers, enabling them to seek assistance or provide feedback.

Working Process:  

Automatrix Working Process

The working process is as follows:

The user must first ‘Login’ in to the ‘Automatrix’ app.

Then the user will be redirected to the ‘Home’ tab of the app. Here, the user will get an overview of the current timing, weather conditions, and a greeting according to the time.

Then, to control a device, the user must visit the ‘Devices’ tab, and there he or she will see all paired devices according to the room along with their status, i.e., whether the device is ‘ON’ or ‘OFF’. The user will have a button to toggle the state between ‘ON’ and ‘OFF’ of the device, and if the user long presses on that device, two options will be shown: ‘Delete Device’ and ‘More Options’. Through ‘Delete Device', the user can delete any paired device, and the view will be updated according to the updated data. If the user chooses the ‘More Options’, then all details of the device will be shown in a new window. From that window, the user can change the intensity level of that device, like the brightness of the bulb or the speed of the fan. Here, the user only has to change the slider value, and that value will be sent to the corresponding device via the Mosquitto MQTT Broker running on my cloud server, allowing them to easily communicate with the device. The intensity value will be changed by using the ZVC circuit attached to the microcontroller. 

The next is the ‘Add Device’ tab. Here, the user can pair new devices. To pair a new device, the user has to follow the below steps:

  1. Connect the appliance to the power source and wait for 10 seconds for the device to start its own server.
  2. Open the Automatrix app, navigate to the Add Device tab, and click on that tab.
  3. Follow the instructions shown there, i.e., first turn on the mobile’s Wi-Fi and connect to the appliance’s hotspot network.
  4. Provide the SSID and Password of your home Wi-Fi network and select the room. If the room is not available, the user can add one, then click OK.
  5. After that, the user will be redirected to the tab, Home and on visiting the Devices tab again, the user will see that the device has been added.

The next tab is the ‘Automations’ tab. Here, the user can create different scenes, like ‘Good morning scene', and this scene will turn on the light bulb and turn off the fan simultaneously. These scenes are of two types.

  1. Manual Scenes: To add a Manual scene, the user has to provide the name of the scene and select the devices that will be turned ON, when switching on the scene. Here, all the devices configured with that scene will get the message to turn on or off via my cloud MQTT Broker
  2. Scheduled Scenes: To add a scheduled scene, the user has to first provide the name of the scene and then confirm the name. Scenes with the same name are not allowed. Then the user has to select the weekdays on which the scene will be turned on, select the time at which the scene will be turned on, choose the devices, and then choose if the scene will be repeated or not, then submit these details. The information will be saved in the MongoDB running on my server, and when the time comes, the scene will be turned ON automatically without user interruption. 

The last is the Menu tab. Here, the user will get some information related to himself/herself. The user can switch between the Dark Mode and the Light Mode by toggling a switch available, and they can also get information about the Privacy Policy and Developers. 

**Note: This app is still under development, and some features may or may not work properly, but they will be fixed very soon.

Conclusion:

Automatrix stands as a testament to the power of home automation, revolutionizing the way users interact with and control their smart devices. Its intuitive interface, comprehensive device management, and personalized user experience make it an indispensable tool for modern living.

Code
#include <ArduinoJson.h>
#include <ESP8266WiFi.h>
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <EEPROM.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>

ESP8266WebServer server(80);

HTTPClient http;
WiFiClient wifiClient;
const int BUFFER_SIZE = 256;

#define triacPulse D2 //D2
#define ZVC D6 //D6

int Slider_Value;
int dimming;
int x = 0;

struct settings {
  char ssid[30];
  char password[30];
  char email[30];
} user_credentials = {};

uint32_t chipId = ESP.getChipId();
String deviceId = String(chipId);

const char* mqtt_server = "64.227.137.47";
const char* mqtt_username = "jarvis";
const char* mqtt_password = "me-Mosquitto123";

const char* willTopic = "subscriber/status";
int willQos = 1;
const char* willMessage = "I'm offline";
const bool willRetain = true; // Set to true if you want the broker to retain the last will message

String topic = deviceId + "/deviceStatus"; // Concatenate deviceId and "/deviceStatus"
String intensityTopic = deviceId + "/intensityLevel";

// Convert subTopic to const char*
const char* subTopic = topic.c_str();
const char* intensitySubTopic = intensityTopic.c_str();

PubSubClient client(wifiClient);
unsigned long lastMsg = 0;
#define MSG_BUFFER_SIZE  (50)
char msg[MSG_BUFFER_SIZE];
int value = 0;

bool isOn = false;

void ICACHE_RAM_ATTR acon ();

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  EEPROM.begin(sizeof(struct settings) );
  EEPROM.get( 0, user_credentials );
   
  WiFi.mode(WIFI_AP_STA);
  WiFi.begin(user_credentials.ssid, user_credentials.password);
  
  
  byte tries = 0;
  while (WiFi.status() != WL_CONNECTED) {
    Serial.println(tries);
    delay(1000);
    if (tries++ > 10) {
      WiFi.mode(WIFI_AP_STA);
      Serial.println("NodeMCU hotspot started");
      WiFi.softAP("ESP8266", "");
      Serial.println(deviceId);
      break;
    }
  }
  
  Serial.println("Wifi Connected");
  if(WiFi.status() != WL_CONNECTED){
    server.on("/",  handlePortal);
    server.begin();  
  }
  if(WiFi.status() == WL_CONNECTED){
      client.setServer(mqtt_server, 1883);
      client.setCallback(callback);
  }
  
  pinMode(LED_BUILTIN,OUTPUT);
  pinMode(ZVC, INPUT_PULLUP);
  pinMode(triacPulse, OUTPUT);
  
  attachInterrupt(digitalPinToInterrupt(ZVC), acon, FALLING); // attach Interrupt at PIN2
 
}

void loop(){
  server.handleClient();
  if(WiFi.status() == WL_CONNECTED){
    digitalWrite(LED_BUILTIN, HIGH); // Turn on the LED
    delay(1000); // Wait for half a second
    digitalWrite(LED_BUILTIN, LOW); // Turn off the LED
    delay(1000); // Wait for half a second

    if (!client.connected()) {
      reconnect();
    }
  } 
  
  client.loop();
}

void handlePortal() {

  if (server.method() == HTTP_POST) {

    strncpy(user_credentials.ssid,     server.arg("ssid").c_str(),     sizeof(user_credentials.ssid) );
    strncpy(user_credentials.password, server.arg("password").c_str(), sizeof(user_credentials.password) );
    strncpy(user_credentials.email, server.arg("email").c_str(), sizeof(user_credentials.email) );
    user_credentials.ssid[server.arg("ssid").length()] = user_credentials.password[server.arg("password").length()] = user_credentials.email[server.arg("email").length()] = '\0';
    EEPROM.put(0, user_credentials);
    EEPROM.commit();

    StaticJsonDocument<BUFFER_SIZE> doc;
   
    doc["name"] = "Node Bulb";
    doc["id"] = deviceId;
    doc["type"] = "bulb";

    String jsonString;
    serializeJson(doc,jsonString);
    server.send(200,   "text/html",  jsonString);
    Serial.print("SSID from server");
    Serial.println(server.arg("ssid"));
    Serial.print("Password from server");
    Serial.println(server.arg("password"));
    Serial.print("email from server");
    Serial.println(server.arg("email"));
    
  } else {

    server.send(200,   "text/html", "Something wrong happened" );
  }
}

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]);
  }
  Serial.println();
  char messageBuffer[30];  //somewhere to put the message
  memcpy(messageBuffer, payload, length);  //copy in the payload
  messageBuffer[length] = '\0';
  Serial.print("Message Buffer");
  Serial.println(messageBuffer);

  if (strcmp(messageBuffer, "on") == 0) {
    Serial.println("on");   
    isOn = true;
  }
  else if(strcmp(messageBuffer, "off") == 0){
    Serial.println("off");
    isOn = false;
  }
  else {  
      int dimmingValue = atoi((char*)payload);

//      // Assign the dimming value to Slider_Value
      Slider_Value = dimmingValue;
//
//      // Update the AC dimming based on the Slider_Value
      dimming = map(Slider_Value, 0, 100, 7200, 200);
      
  }
}

void acon()
{
  if(isOn){
      delayMicroseconds(dimming); // read AD0
      digitalWrite(triacPulse, HIGH);

      delayMicroseconds(200);  //delay 50 uSec on output pulse to turn on triac
      digitalWrite(triacPulse, LOW); 
    } 
   else {
      digitalWrite(triacPulse, LOW);
   }

//   Serial.println(digitalRead(triacPulse));
}

void reconnect() {
  // Loop until we're reconnected
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    // Create a random client ID
    String clientId = "ESP8266Client-";
    clientId += String(random(0xffff), HEX);
    // Attempt to connect with username and password
    if (client.connect(clientId.c_str(), mqtt_username, mqtt_password, willTopic, willQos, willRetain, willMessage)) {
      Serial.println("connected");
      // Once connected, publish an announcement...
      client.publish("subscriber/status", "hello world");
      // ... and resubscribe
      Serial.println(subTopic);
      Serial.println(intensitySubTopic);
      client.subscribe(subTopic);
      client.subscribe(intensitySubTopic);
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" try again in 5 seconds");
      // Wait 5 seconds before retrying
      delay(5000);
    }
  }
}
Video