<file_sep># Chika-CA-SS

My Graduate Thesis project work co-operate with Chika Corporation 智家 (チカ).

📍 With 4 members (<NAME>, <NAME>, <NAME>, Hoai Phuc), Chika Smart Home Joint Stock Company - 智 家 (チ カ) specializes in developing  solutions and devices for smart homes.

👉 Some product list:

- Infrared controller: CA - IRX.

- Touch switch: CA - SWW and CA - SWR

- Central control unit: CA - HC.

- Sensors system: CA - SS.

![93224958_2582388615361445_2680312884105314304_o](https://user-images.githubusercontent.com/48848418/82010978-dc672300-969d-11ea-8afe-408d4ac53319.jpg)
![System](https://user-images.githubusercontent.com/48848418/82010508-7c23b180-969c-11ea-9d99-2828714f36b0.png)

⚙️ My sample product's schematics - CA-SS 💎

![CA-SS01](https://user-images.githubusercontent.com/48848418/80554266-c51a0b80-89f6-11ea-86e3-54642cd17d30.png)

![CA-SS01](https://user-images.githubusercontent.com/48848418/77226211-273a5200-6ba9-11ea-8625-c65f81f064c0.png)

![CA-SS01](https://user-images.githubusercontent.com/48848418/78026736-55c4e380-7386-11ea-8e63-e8457d32dbdf.png)

![image](https://user-images.githubusercontent.com/48848418/80554325-ff83a880-89f6-11ea-9435-c32b392c4374.png)

![CA-SS02](https://user-images.githubusercontent.com/48848418/80554268-c9462900-89f6-11ea-8e9b-edd3d0b6d3ae.png)

![CA-SS02](https://user-images.githubusercontent.com/48848418/77226213-2acdd900-6ba9-11ea-9aae-31755f4da163.png)

![CA-SS02](https://user-images.githubusercontent.com/48848418/78026744-58bfd400-7386-11ea-89e4-1b81ee4b5879.png)

![image](https://user-images.githubusercontent.com/48848418/80554358-1629ff80-89f7-11ea-89c2-25f5cb66aa4e.png)

![CA-SS03](https://user-images.githubusercontent.com/48848418/80554272-cba88300-89f6-11ea-8199-fa54737e8b57.png)

![CA-SS03](https://user-images.githubusercontent.com/48848418/77226219-302b2380-6ba9-11ea-965a-808891f18759.png)

![CA-SS03](https://user-images.githubusercontent.com/48848418/78026746-5b222e00-7386-11ea-9688-af8ff13a3178.png)

![image](https://user-images.githubusercontent.com/48848418/80554329-03172f80-89f7-11ea-8f35-9b3fedb753c0.png)

![image](https://user-images.githubusercontent.com/48848418/80554419-47a2cb00-89f7-11ea-9e45-e6b3367e09bf.png)

![CA-SS04](https://user-images.githubusercontent.com/48848418/77226220-33261400-6ba9-11ea-8122-54c7a23afb1c.png)

![CA-SS04](https://user-images.githubusercontent.com/48848418/78026752-5cebf180-7386-11ea-9095-89e000118d05.png)

![image](https://user-images.githubusercontent.com/48848418/80554336-08747a00-89f7-11ea-878f-1a9ef603aa6e.png)

    Author: <NAME>
<file_sep>#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Ticker.h>
#include <ArduinoJson.h>
#include <SPI.h>

/*
****** From SS01 to MQTT ******
+ Topic MQTT: CA-SS01’s id.
+ Message format:
{"alert":boolean, "state":boolean}

****** From MQTT callback to SS01 ******
+ Topic MQTT: CA-SS01’s id.
+ Message format: 1/0     
1: turn alert on and if state door == 1 --> turn on warning
0: turn alert off and dont care about state door --> just send to MQTT state of door
*/

#define ledR 16
#define ledB 5
#define btn_config 4
#define mc35 9        //SD2
#define btn_allow 14
#define alarm 12
#define alarmLed 13

uint32_t timer = 0;
uint16_t longPressTime = 6000;

boolean buttonActive = false;
boolean sensorVal = false;
boolean sensorLoop = false;
boolean initialSensor = false;

boolean allowAlarm = false;
boolean buttonValue = false;
boolean door = false;
boolean doorLoop = false;

const char *mqtt_server = "chika.gq";
const int mqtt_port = 2502;
const char *mqtt_user = "chika";
const char *mqtt_pass = "<PASSWORD>";

const char *SS01_id = "bc84a8b9-e11a-4cd1-bc5c-b6d957880cbe";
//const char *doorState = "CA-Security";
//const char *doorCommand = "CA-Security/control";

Ticker ticker;
WiFiClient esp;
PubSubClient client(esp);

void tick();
void tick2();
void exitSmartConfig();
boolean startSmartConfig();
void longPress();
void callback(char *topic, byte *payload, unsigned int length);
void reconnect();
boolean checkSensor();
void checkButton();
void tickAlarm();

void setup()
{
  Serial.begin(115200);

  WiFi.setAutoConnect(true);   // auto connect when start
  WiFi.setAutoReconnect(true); // auto reconnect the old WiFi when leaving internet

  pinMode(ledR, OUTPUT);            // led red set on
  pinMode(ledB, OUTPUT);            // led blue set on
  pinMode(btn_config, INPUT);       // btn_config is ready
  
  pinMode(btn_allow, INPUT_PULLUP); // button allow alarm ready
  pinMode(alarm, OUTPUT);
  pinMode(alarmLed, OUTPUT);

  ticker.attach(1, tick2); // initial led show up

  Serial.println("Waiting for Internet ...");
  uint16_t i = 0;
  digitalWrite(alarm, LOW);
  digitalWrite(alarmLed, LOW);
  while (!WiFi.isConnected()) // check WiFi is connected
  {
    i++;
    delay(100);
    if (i >= 100) // timeout and break while loop
      break;
  }

  if (!WiFi.isConnected()) // still not connected
  {
    startSmartConfig();
  }
  else
  {
    ticker.detach();         // shutdown ticker
    digitalWrite(ledR, LOW); // show led
    digitalWrite(ledB, HIGH);
    Serial.println("WIFI CONNECTED");
    Serial.println(WiFi.SSID());
    Serial.print("IP: ");
    Serial.println(WiFi.localIP());
  }

  delay(1000);
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
  pinMode(mc35, INPUT_PULLUP);      // sensor is ready
}

void loop()
{
  longPress();
  if (WiFi.status() == WL_CONNECTED)
  {
    digitalWrite(ledB, HIGH);
    digitalWrite(ledR, LOW);
    if (client.connected())
    {
      client.loop();
      // do something here
      checkButton();        // Turn on or off alert?!
      door = checkSensor(); // Check state of door?!
      Serial.print("Door state: ");
      Serial.println(door);

      if (allowAlarm)
      {

        digitalWrite(alarmLed, HIGH); //turn on led
        if (door || doorLoop)
        {
          doorLoop = true;
          digitalWrite(alarm, HIGH);
          delay(200);
        }
      }
      else
      {
        doorLoop = false;
        ticker.detach();
        digitalWrite(alarm, LOW);
        digitalWrite(alarmLed, LOW); //turn off led
      }
    }
    else
     {
       reconnect();
     }
  }
  else
  {
    Serial.println("WiFi Connected Fail");
    WiFi.reconnect();
    digitalWrite(ledB, LOW);
    boolean state = digitalRead(ledR);
    digitalWrite(ledR, !state);
    delay(500);
  }
  delay(100);
}

void tickAlarm()
{
  boolean state = digitalRead(alarm);
  digitalWrite(alarm, !state);
}

boolean checkSensor()
{
  String sendMQTT;
  char payload_sendMQTT[300];
  StaticJsonDocument<300> JsonDoc;

  sensorVal = digitalRead(mc35);

  if (sensorVal != sensorLoop)
  {
    if (sensorVal)
    {
      JsonDoc["alert"] = allowAlarm;
      JsonDoc["state"] = true;
      serializeJson(JsonDoc, sendMQTT);
      sendMQTT.toCharArray(payload_sendMQTT, sendMQTT.length() + 1);
      client.publish(SS01_id, payload_sendMQTT, true);
      sensorLoop = sensorVal;
      return true;
    }
    else
    {
      JsonDoc["alert"] = allowAlarm;
      JsonDoc["state"] = false;
      serializeJson(JsonDoc, sendMQTT);
      sendMQTT.toCharArray(payload_sendMQTT, sendMQTT.length() + 1);
      client.publish(SS01_id, payload_sendMQTT, true);
      sensorLoop = sensorVal;
      return false;
    }
  }
  else
  {
    return sensorVal;
  }
}

void checkButton()
{
  buttonValue = digitalRead(btn_allow);
  //Serial.println(buttonValue);
  if (!buttonValue)
  {
    while (!buttonValue)
    {
      buttonValue = digitalRead(btn_allow);
      delay(100);
    }
    allowAlarm = !allowAlarm;
    String sendMQTT;
    char payload_sendMQTT[300];
    StaticJsonDocument<300> JsonDoc;
    JsonDoc["state"] = door;
    JsonDoc["alert"] = allowAlarm;
    serializeJson(JsonDoc, sendMQTT);
    sendMQTT.toCharArray(payload_sendMQTT, sendMQTT.length() + 1);
    client.publish(SS01_id, payload_sendMQTT, true);
  }
}

void reconnect()
{
  Serial.println("Attempting MQTT connection ...");
  String clientId = "ESP8266Client-testX";
  clientId += String(random(0xffff), HEX);
  if (client.connect(clientId.c_str(), mqtt_user, mqtt_pass))
  {
    Serial.println("connected");
    client.subscribe(SS01_id);
  }
  else
  {
    Serial.print("MQTT Connected Fail, rc = ");
    Serial.print(client.state());
    Serial.println("try again in 5 seconds");
  }
}

void callback(char *topic, byte *payload, unsigned int length)
{
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String payload_toStr;
  Serial.println(payload_toStr);
  String mtopic = (String)topic;

  for (uint16_t i = 0; i < length; i++)
  {
    payload_toStr += (char)payload[i];
  }
  Serial.println(payload_toStr);

  if (String(topic).equals(SS01_id))
  {
    if (payload[0] == '1')
    {
      allowAlarm = true;
    }
    else if (payload[0] == '0')
    {
      allowAlarm = false;
    }
  }
}

void tick()
{
  boolean state = digitalRead(ledR);
  digitalWrite(ledR, !state);
}

void tick2()
{
  boolean state = digitalRead(ledR);
  digitalWrite(ledR, !state);
  digitalWrite(ledB, !state);
}

void exitSmartConfig()
{
  WiFi.stopSmartConfig();
  ticker.detach();
  digitalWrite(ledR, LOW);
  digitalWrite(ledB, HIGH);
}

boolean startSmartConfig()
{
  uint16_t t = 0;
  Serial.println("On SmartConfig ");
  WiFi.beginSmartConfig();
  delay(500);
  ticker.attach(0.1, tick);
  while (WiFi.status() != WL_CONNECTED)
  {
    t++;
    Serial.print(".");
    delay(500);
    if (t > 100)
    {
      Serial.println("Smart Config fail");
      ticker.attach(0.5, tick);
      delay(3000);
      exitSmartConfig();
      return false;
    }
  }
  Serial.println("WiFi connected ");
  Serial.print("IP :");
  Serial.println(WiFi.localIP());
  Serial.println(WiFi.SSID());
  exitSmartConfig();
  return true;
}

void longPress()
{
  // Serial.println(digitalRead(btn_config));
  if (digitalRead(btn_config) == HIGH)
  {
    if (buttonActive == false)
    {
      buttonActive = true;
      timer = millis();
      Serial.println(timer);
    }

    if (millis() - timer > longPressTime)
    {
      Serial.println("SmartConfig Start");
      digitalWrite(ledB, LOW);
      startSmartConfig();
    }
  }
  else
  {
    buttonActive = false;
  }
}<file_sep>#include <Arduino.h>
#include <MQ135.h>
#include <Adafruit_Sensor.h>
#include <DHT.h>
#include <SPI.h>
#include <RF24.h>

#define MQ135_pin A2
#define dht_pin A1
#define dht_type DHT11
#define ledR 3
#define ledG 5
#define ledB 6
#define CE 9
#define CSN 10

RF24 radio(CE, CSN);
MQ135 mq135_sensor = MQ135(MQ135_pin);
DHT dht(dht_pin, dht_type);

const uint64_t address = 1002502019005;
// const byte address[6] = "00008";

float sensorValue[3];
uint16_t timer = 0;

void showBlue()
{
  analogWrite(ledR, 0);
  analogWrite(ledG, 255);
  analogWrite(ledB, 0);
  for (int i = 0; i <= 255; i++)
  {
    analogWrite(ledB, i);
    analogWrite(ledG, 255 - i);
    delay(3);
  }
}

void showRed()
{
  analogWrite(ledR, 0);
  analogWrite(ledG, 255);
  analogWrite(ledB, 0);
  for (int i = 0; i <= 255; i++)
  {
    analogWrite(ledR, i);
    analogWrite(ledG, 255 - i);
    delay(3);
  }
}

void showRed2Green()
{
  analogWrite(ledR, 255);
  analogWrite(ledG, 0);
  analogWrite(ledB, 0);
  for (int i = 0; i <= 255; i++)
  {
    analogWrite(ledG, i);
    analogWrite(ledR, 255 - i);
    analogWrite(ledB, 0);
    delay(3);
  }
}

void showBlue2Green()
{
  analogWrite(ledR, 0);
  analogWrite(ledG, 0);
  analogWrite(ledB, 255);
  for (int i = 0; i <= 255; i++)
  {
    analogWrite(ledG, i);
    analogWrite(ledB, 255 - i);
    analogWrite(ledR, 0);
    delay(3);
  }
}

void setup()
{
  Serial.begin(9600);
  dht.begin();
  pinMode(ledR, OUTPUT);
  pinMode(ledG, OUTPUT);
  pinMode(ledB, OUTPUT);
  //=================RF=====================
  SPI.begin();
  radio.begin();
  radio.setRetries(15, 15);
  radio.setPALevel(RF24_PA_MAX);
  radio.openWritingPipe(address);
  //========================================
}

void loop()
{
  float h = dht.readHumidity();
  float t = dht.readTemperature();
  String output;
  output += F("temperature : ");
  output += t;
  output += F("\t");
  output += F("humidity :");
  output += h;

  Serial.println(output);

  float rzero = mq135_sensor.getRZero();                       // Hệ số trung bình
  float correctedRZero = mq135_sensor.getCorrectedRZero(t, h); // Hệ số từ nhiệt độ độ ẩm
  float resistance = mq135_sensor.getResistance();             // khoảng cách tối đa
  float ppm = mq135_sensor.getPPM();                           // lấy giá trị ppm thường
  float correctedPPM = mq135_sensor.getCorrectedPPM(t, h);     // lấy giá trị ppm sau khi tính với nhiệt độ độ ẩm

  Serial.print("MQ135 RZero: ");
  Serial.print(rzero);
  Serial.print("\t Corrected RZero: ");
  Serial.print(correctedRZero);
  Serial.print("\t Resistance: ");
  Serial.print(resistance);
  Serial.print("\t PPM: ");
  Serial.print(ppm);
  Serial.print("\t Corrected PPM: ");
  Serial.print(correctedPPM);
  Serial.println("ppm");
  Serial.println();

  sensorValue[0] = t;
  sensorValue[1] = h;
  sensorValue[2] = correctedPPM;

  timer++;
  if(timer > 80){
    Serial.println("send ...");
    radio.write(sensorValue, sizeof(sensorValue));
    timer = 0;
    delay(1000);
  }


  if (correctedPPM < 1.5)
  {
    if (!digitalRead(ledB))
    {
      radio.write(sensorValue, sizeof(sensorValue));
      showBlue();
    }
  }
  else if (correctedPPM >= 1.5 && correctedPPM < 4.2)
  {
    if (!digitalRead(ledG))
    {
      radio.write(sensorValue, sizeof(sensorValue));
      if (!digitalRead(ledR))
        showBlue2Green();
      else if (!digitalRead(ledB))
        showRed2Green();
    }
  }
  else if (correctedPPM >= 4.2)
  {
    if (!digitalRead(ledR))
    {
      radio.write(sensorValue, sizeof(sensorValue));
      showRed();
    }
  }

  delay(100);
}
<file_sep>#include <Arduino.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Ticker.h>

#define ledR 16
#define ledB 5
#define btn_config 4
#define mc35 0
#define btn_allow 14
#define alarm 12
#define alarmLed 13

uint32_t timer = 0;
uint16_t longPressTime = 6000;

boolean buttonActive = false;
boolean sensorVal = false;
boolean sensorLoop = false;
boolean initialSensor = false;
boolean allowAlarm = false;
boolean buttonValue = false;
boolean door = false;
boolean doorLoop = false;

const char *mqtt_server = "chika.gq";
const int mqtt_port = 2502;
const char *mqtt_user = "chika";
const char *mqtt_pass = "<PASSWORD>";

const char *doorState = "CA-Security";
const char *doorCommand = "CA-Security/control";

Ticker ticker;
WiFiClient esp;
PubSubClient client(esp);

void tick();
void tick2();
void exitSmartConfig();
boolean startSmartConfig();
void longPress();
void callback(char *topic, byte *payload, unsigned int length);
void reconnect();
boolean checkSensor();
void checkButton();
void tickAlarm();

void setup()
{
  Serial.begin(115200);

  WiFi.setAutoConnect(true);   // auto connect when start
  WiFi.setAutoReconnect(true); // auto reconnect the old WiFi when leaving internet

  pinMode(ledR, OUTPUT);            // led red set on
  pinMode(ledB, OUTPUT);            // led blue set on
  pinMode(btn_config, INPUT);       // btn_config is ready
  pinMode(mc35, INPUT_PULLUP);      // sensor is ready
  pinMode(btn_allow, INPUT_PULLUP); // button allow alarm ready
  pinMode(alarm, OUTPUT);
  pinMode(alarmLed, OUTPUT);

  ticker.attach(1, tick2); // initial led show up

  Serial.println("Waiting for Internet");
  uint16_t i = 0;
  digitalWrite(alarm, HIGH);
  digitalWrite(alarmLed, HIGH);
  while (!WiFi.isConnected()) // check WiFi is connected
  {
    i++;
    delay(100);
    if (i >= 100) // timeout and break while loop
      break;
  }

  if (!WiFi.isConnected()) // still not connected
  {
    startSmartConfig(); // start Smartconfig
  }
  else
  {
    ticker.detach();         // shutdown ticker
    digitalWrite(ledR, LOW); // show led
    digitalWrite(ledB, HIGH);
    Serial.println("WIFI CONNECTED");
    Serial.println(WiFi.SSID());
    Serial.print("IP: ");
    Serial.println(WiFi.localIP());
  }

  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
}

void loop()
{
  longPress();
  if (WiFi.status() == WL_CONNECTED)
  {
    digitalWrite(ledB, HIGH);
    digitalWrite(ledR, LOW);
    if (client.connected())
    {
      client.loop();
      // do something here
      door = checkSensor();
      checkButton();
      if (allowAlarm)
      {
        digitalWrite(alarmLed, LOW); //turn on led
        if (door || doorLoop)
        {
          doorLoop = true;
          tickAlarm();
          delay(200);
        }
      }
      else
      {
        doorLoop = false;
        ticker.detach();
        digitalWrite(alarm, HIGH);
        digitalWrite(alarmLed, HIGH); //turn off led
      }
    }
    else
    {
      reconnect();
    }
  }
  else
  {
    Serial.println("WiFi Connected Fail");
    WiFi.reconnect();
    digitalWrite(ledB, LOW);
    boolean state = digitalRead(ledR);
    digitalWrite(ledR, !state);
    delay(500);
  }

  delay(100);
}

void tickAlarm()
{
  boolean state = digitalRead(alarm);
  digitalWrite(alarm, !state);
}

boolean checkSensor()
{
  sensorVal = digitalRead(mc35);
  if (!initialSensor)
  {
    if (sensorVal)
    {
      sensorLoop = true;
      client.publish(doorState, "OPEN");
      return true;
    }
    else
    {
      sensorLoop = false;
      client.publish(doorState, "CLOSE");
      return false;
    }
    initialSensor = true;
  }
  if (sensorVal && !sensorLoop)
  {
    client.publish(doorState, "OPEN");
    sensorLoop = true;
    return true;
  }
  else if (!sensorVal && sensorLoop)
  {
    client.publish(doorState, "CLOSE");
    sensorLoop = false;
    return false;
  }
}

void checkButton()
{
  buttonValue = digitalRead(btn_allow);
  Serial.println(buttonValue);
  if (!buttonValue)
  {
    while (!buttonValue)
    {
      buttonValue = digitalRead(btn_allow);
      delay(100);
    }
    allowAlarm = !allowAlarm;
  }
}

void reconnect()
{
  Serial.println("Attempting MQTT connection ...");
  String clientId = "ESP8266Client-testX";
  clientId += String(random(0xffff), HEX);
  if (client.connect(clientId.c_str(), mqtt_user, mqtt_pass))
  {
    Serial.println("connected");
    client.subscribe(doorCommand);
  }
  else
  {
    Serial.print("MQTT Connected Fail, rc = ");
    Serial.print(client.state());
    Serial.println("try again in 5 seconds");
  }
}

void callback(char *topic, byte *payload, unsigned int length)
{
  Serial.print("Message arrived [");
  Serial.print(topic);
  Serial.print("] ");
  String data;
  String mtopic = (String)topic;

  for (uint16_t i = 0; i < length; i++)
  {
    data += (char)payload[i];
  }
  Serial.println(data);

  if(topic == doorCommand){
    if(data == "ON")  allowAlarm = true;
    else  allowAlarm = false;
  }
}

void tick()
{
  boolean state = digitalRead(ledR);
  digitalWrite(ledR, !state);
}

void tick2()
{
  boolean state = digitalRead(ledR);
  digitalWrite(ledR, !state);
  digitalWrite(ledB, !state);
}

void exitSmartConfig()
{
  WiFi.stopSmartConfig();
  ticker.detach();
  digitalWrite(ledR, LOW);
  digitalWrite(ledB, HIGH);
}

boolean startSmartConfig()
{
  uint16_t t = 0;
  Serial.println("On SmartConfig ");
  WiFi.beginSmartConfig();
  delay(500);
  ticker.attach(0.1, tick);
  while (WiFi.status() != WL_CONNECTED)
  {
    t++;
    Serial.print(".");
    delay(500);
    if (t > 100)
    {
      Serial.println("Smart Config fail");
      ticker.attach(0.5, tick);
      delay(3000);
      exitSmartConfig();
      return false;
    }
  }
  Serial.println("WiFi connected ");
  Serial.print("IP :");
  Serial.println(WiFi.localIP());
  Serial.println(WiFi.SSID());
  exitSmartConfig();
  return true;
}

void longPress()
{
  if (digitalRead(btn_config) == HIGH)
  {
    if (buttonActive == false)
    {
      buttonActive = true;
      timer = millis();
      Serial.println(timer);
    }

    if (millis() - timer > longPressTime)
    {
      Serial.println("SmartConfig Start");
      digitalWrite(ledB, LOW);
      startSmartConfig();
    }
  }
  else
  {
    buttonActive = false;
  }
}<file_sep>#include <Arduino.h>
#include <RF24.h>
#include <SPI.h>

#define PIR_sensor 3
#define control_Device 4
#define signal_Led 5
#define default_delayTime 3000

RF24 radio(9, 10);                      //nRF24L01 (CE,CSN) connections PIN
const uint64_t address = 1002502019004; //CA-SS02: 40 + Timestamp

uint16_t delayTime = default_delayTime;
uint32_t data[3]; //data[0]: ON/OFF - data[1]: new_delayTime - data[2]: state_Device

void setup()
{
  SPI.begin();
  Serial.println("\nCA-SS02 say hello to your home <3 ! ");
  Serial.begin(9600);

  pinMode(PIR_sensor, INPUT);
  pinMode(control_Device, OUTPUT);
  pinMode(signal_Led, OUTPUT);

  radio.begin();
  radio.setRetries(15, 15);
  radio.setPALevel(RF24_PA_MAX);
}

void checkCommand()
{
  radio.openReadingPipe(1, address);
  radio.startListening();
  if (radio.available())
  {
	boolean state = digitalRead(signal_Led);
    memset(&data, ' ', sizeof(data));
    radio.read(&data, sizeof(data));

    delayTime = data[1];
    Serial.println("__________________");
    Serial.print("Mode: ");
    Serial.println(data[0]);
    Serial.print("New delay time: ");
    Serial.println(data[1]);
    Serial.print("State device: ");
    Serial.println(data[2]);
    digitalWrite(signal_Led, !state);
    delay(500);
    digitalWrite(signal_Led, state);
  }
}

void sendData()
{
  radio.stopListening();
  radio.openWritingPipe(address);
  radio.write(&data, sizeof(data));
  Serial.print("Data sent - State of device: ");
  Serial.println(data[2]);
}

void loop()
{
  checkCommand();
  if (data[0])
  {
	digitalWrite(signal_Led, HIGH);
    checkCommand();
    boolean check_PIRSensor = digitalRead(PIR_sensor);
    if (check_PIRSensor)
    {
      digitalWrite(control_Device, HIGH);
      data[2] = 1;
      sendData();
      while (check_PIRSensor)
      {
        check_PIRSensor = digitalRead(PIR_sensor);
        checkCommand();
        delay(50);
      }
      delay(delayTime);
    }
    else
    {
      digitalWrite(control_Device, LOW);
      if (digitalRead(control_Device) != data[2])
      {
        data[2] = 0;
        sendData();
      }
    }
    checkCommand();
  }
  else
  {
    digitalWrite(control_Device, LOW);
	digitalWrite(signal_Led, LOW);
    if (digitalRead(control_Device) != data[2])
    {
      data[2] = 0;
      sendData();
    }
  }
  delay(100);
}<file_sep>#include <Arduino.h>
#include <SPI.h>
#include <RF24.h>

#define pinFlame A0
#define pinGas  A1
#define CE 9
#define CSN 10

RF24 radio(CE, CSN);

const uint64_t address = 1002502019006;

float sensorValue[2];
float flame, gas;

uint16_t timer = 0;

void setup() {
  Serial.begin(9600);
  //=================RF=====================
  SPI.begin();
  radio.begin();
  radio.setRetries(15, 15);
  radio.setPALevel(RF24_PA_MAX);
  radio.openWritingPipe(address);
  //========================================
  
}

void loop() {
  flame = analogRead(A0);
  gas = analogRead(A1);

  String output;
  output += F("Flame : ");
  output += flame;
  output += F("\t");
  output += F("gas :");
  output += gas;

  Serial.println(output);

  sensorValue[0] = flame;
  sensorValue[1] = gas;

  timer++;
  if(timer > 50){
    Serial.println("send ...");
    radio.write(sensorValue, sizeof(sensorValue));
    timer = 0;
  }
  delay(100);
}<file_sep>#include <Arduino.h>
#include <RF24.h>
#include <SPI.h>
#include <ESP8266WiFi.h>
#include <PubSubClient.h>
#include <Ticker.h>

Ticker ticker;
RF24 radio(2, 15);                      //nRF24L01 (CE,CSN) connections PIN
const uint64_t address = 1002502019004; //CA-SS02: 40 + Timestamp
boolean smartConfigStart = false;

const char *ssid = "username wifi";
const char *password = "<PASSWORD>";

//data[0]: ON/OFF - data[1]: new_delayTime - data[2]: device_State
uint32_t data[3];
uint32_t data_SS02[3];
const int smartConfig_LED = 16;

//Topic: product_id/button_id     char[10] = "l" / "O"
const char *CA_SS02_delayTime = "CA-SS02/delayTime";
const char *CA_SS02_deviceState = "CA-SS02/deviceState";
const char *CA_SS02_ONOFF = "CA-SS02/ONOFF";

//Config MQTT broker information:
const char *mqtt_server = "chika.gq";
const int mqtt_port = 2502;
const char *mqtt_user = "chika";
const char *mqtt_pass = "<PASSWORD>";

//Setup MQTT - Wifi ESP12F:
WiFiClient esp_12F;
PubSubClient client(esp_12F);

void setup_Wifi()
{
  delay(100);
  Serial.println();
  Serial.print("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.println("IP address: ");
  Serial.println(WiFi.localIP());
}

/*--------------NEEDED FUNCTIONS--------------*/
void blinking()
{
  bool state = digitalRead(smartConfig_LED);
  digitalWrite(smartConfig_LED, !state);
}

void exitSmartConfig()
{
  WiFi.stopSmartConfig();
  ticker.detach();
}

boolean startSmartConfig()
{
  int t = 0;
  Serial.println("Smart Config Start");
  WiFi.beginSmartConfig();
  delay(500);
  ticker.attach(0.1, blinking);
  while (WiFi.status() != WL_CONNECTED)
  {
    t++;
    Serial.print(".");
    delay(500);
    if (t > 120)
    {
      Serial.println("Smart Config Fail");
      smartConfigStart = false;
      ticker.attach(0.5, blinking);
      delay(3000);
      exitSmartConfig();
      return false;
    }
  }
  smartConfigStart = true;
  Serial.println("WIFI CONNECTED");
  Serial.print("IP: ");
  Serial.println(WiFi.localIP());
  Serial.println(WiFi.SSID());
  exitSmartConfig();
  return true;
}

void reconnect_mqtt()
{
  while (!client.connected())
  {
    Serial.print("Attempting MQTT connection...");
    String clientId = "CA-SS02 - ";
    clientId += String(random(0xffff), HEX);
    Serial.println(clientId);

    if (client.connect(clientId.c_str(), mqtt_user, mqtt_pass))
    {
      Serial.println("Connected");
      client.subscribe(CA_SS02_delayTime);
      client.subscribe(CA_SS02_ONOFF);
    }
    else
    {
      Serial.print("Failed, rc=");
      Serial.print(client.state());
      Serial.println("Try again in 1 second");
      delay(1000);
    }
  }
}

void callback(char *topic, byte *payload, unsigned int length)
{
  //Topic list test is the value of variables: CA_HC_SS02
  Serial.print("Topic [");
  Serial.print(topic);
  Serial.print("]: ");

  uint16_t calculate_delayTime = 0;
  for (unsigned int i = 0; i < length; i++)
  {
    Serial.print((char)payload[i]);
    calculate_delayTime += ((uint16_t)payload[i] - 48) * (uint16_t)(pow(10, length - 1));
  }

  if ((char)topic[10] == 'l')
  {
    data[1] = calculate_delayTime * 1000;
    Serial.print("\n\nNew delay time send to CA-SS02: ");
    Serial.println(data[1]);
    radio.stopListening();
    radio.openWritingPipe(address);
    radio.write(&data, sizeof(data));
  }

  if ((char)topic[10] == 'O')
  {
    if ((char)payload[0] == '1')
    {
      data[0] = true;
    }
    else
    {
      data[0] = false;
    }

    radio.stopListening();
    radio.openWritingPipe(address);
    radio.write(&data, sizeof(data));
  }
}

void setup()
{
  SPI.begin();
  Serial.begin(115200);
  pinMode(smartConfig_LED, OUTPUT);

  WiFi.setAutoConnect(true);
  WiFi.setAutoReconnect(true);
  WiFi.mode(WIFI_STA);

  //      setup_Wifi();
  delay(6000);

  if (WiFi.status() != WL_CONNECTED)
  {
    startSmartConfig();
  }

  radio.begin();
  radio.setRetries(15, 15);
  radio.setPALevel(RF24_PA_MAX);

  Serial.println("WIFI CONNECTED");
  Serial.println(WiFi.SSID());
  Serial.print("IP: ");
  Serial.println(WiFi.localIP());

  Serial.println("\nCA-HC-SS02 say hello to your home <3 !");

  Serial.println("Trying connect MQTT ...");
  client.setServer(mqtt_server, mqtt_port);
  client.setCallback(callback);
  data[1] = 0;
}

void loop()
{
  if (WiFi.status() == WL_CONNECTED)
  {
    if (!client.connected())
    {
      reconnect_mqtt();
    }
    else
      client.loop();
  }

  radio.openReadingPipe(1, address);
  radio.startListening();
  if (radio.available())
  {
    memset(&data_SS02, ' ', sizeof(data_SS02));
    radio.read(&data_SS02, sizeof(data_SS02));
    
    data[2] = data_SS02[2];

    Serial.println("__________________");
    Serial.print("Mode: ");
    Serial.println(data[0]);
    Serial.print("New delay time: ");
    Serial.println(data[1]);
    Serial.print("State device: ");
    Serial.println(data[2]);

    if (data[2])
      client.publish(CA_SS02_deviceState, "1", true);
    else
      client.publish(CA_SS02_deviceState, "0", true);
  }
  delay(100);
}