Nestor Alejandro Ccencho Garcia
Created September 19, 2021

Monitoring of cleaning supplies

Monitoring of cleaning suppliesThe present project aims to build a monitoring system for the stock of cleaning supplies for hand cleaning.

19
Monitoring of cleaning supplies

Things used in this project

Hardware components

- HZ21WA water flow
×1
Infrared Emitter, 130 °
Infrared Emitter, 130 °
×1
PTS 645 Series Switch
C&K Switches PTS 645 Series Switch
×1
Limit Switch, 5 A
Limit Switch, 5 A
×1
M5Stack Core2 ESP32 IoT Development Kit
M5Stack Core2 ESP32 IoT Development Kit
×1

Software apps and online services

AWS IoT
Amazon Web Services AWS IoT
AWS EC2
Amazon Web Services AWS EC2
Node-RED
Node-RED
Arduino IDE
Arduino IDE
AWS DynamoDB
Amazon Web Services AWS DynamoDB

Hand tools and fabrication machines

Mini Side Cutter, 120mm Length with 25mm Jaw Capacity
Mini Side Cutter, 120mm Length with 25mm Jaw Capacity
Soldering iron (generic)
Soldering iron (generic)
Solder Wire, Lead Free
Solder Wire, Lead Free
Solder Flux, Soldering
Solder Flux, Soldering

Story

Read more

Schematics

M5Stack-Core2

Code

1.AWS_M5StackCore2_v2.ino

Arduino
Descargar librerias
/*
 AWS iot con ESP32 
 By:nccencho for www.smelpro.com 
 Versin: V2.0
 contenido privado
 */
#include <M5Core2.h>                         // Library for the M5 core2
#include <FastLED.h>                         // Library to use LEDs
#include "SPIFFS.h"                          // Library to load credential files
#include <WiFiClientSecure.h>                // Free for secure connection the M5 core2 and AWS IoT
#include <Wire.h>                            // Wire protocol free.
#include <PubSubClient.h>                    // Free for mqtt, publish and subscribe.

const char * ssid = "Smel3d";                 // SSId credentials
const char * password = "20142016";           // Pass credentials
const char * mqtt_server = "a2s70tnvueqbje-ats.iot.us-east-1.amazonaws.com"; // Replace your account endpoint
const int mqtt_port = 8883;                   // Port for MQTT

String Read_rootca;
String Read_cert;
String Read_privatekey;

//********************************
#define BUFFER_LEN  256
long lastMsg = 0;
long lastMsg2 = 0;
char msg[BUFFER_LEN];
int value = 0;
byte mac[6];
char mac_Id[18];
int i=0;
int capacity=100;
int agua=0;
int papel=100;
//********************************
String messageData;
String macIdStr,agel,sen_papel,sen_agua;
char data_digital[2]="";

//**************************************
WiFiClientSecure espClient;
PubSubClient client(espClient);

//*************************************
#define NUM_LEDS 10
#define DATA_PIN 25
// Define the array of leds
CRGB leds[NUM_LEDS];
//*************************************
int const pin_agel = 36;
int const pin_agua = 13;
int const pin_papel = 14;
int const led = 21;

//*************************************

// Variable de timer usando millis()
unsigned long lastTime = 0;
unsigned long timerDelay = 1500;



void setup_wifi() {
  delay(10);
  Serial.println();
  Serial.print("Conectando.. ");
  Serial.println(ssid);

  WiFi.begin(ssid, password);

  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  randomSeed(micros());

  Serial.println("");
  Serial.println("WiFi conectado");
  Serial.println("Direccion IP: ");
  Serial.println(WiFi.localIP());
}

void callback(String topic, byte* message, unsigned int length){
  Serial.print("Mensaje que llega del topic: ");
  Serial.print(topic);
  Serial.print(". Message: ");
  //String messageData;

  for(int i =0; i<length; i++){
    Serial.print((char)message[i]);
    messageData +=(char)message[i];
  }
  Serial.println(); 


// Enciende led
   if(messageData == "true")
      {digitalWrite(led,HIGH);}
   if(messageData == "false")
      {digitalWrite(led,LOW);}
    
   Serial.println("Recibe: " + messageData );
 
}

void reconnect() {
  
  // Loop para reconeccin
  while (!client.connected()) {
    Serial.print("Attempting MQTT connection...");
    
    // Creando un ID como ramdon
    String clientId = "ESP32-";
    clientId += String(random(0xffff), HEX);
    
    // Intentando conectarse
    if (client.connect(clientId.c_str())) {
      Serial.println("conectada");
      
    // Conectado, publicando un payload...
      client.publish("ei_out", "hello world");
    
    // ... y suscribiendo
      client.subscribe("ei_in");
    } else {
      Serial.print("failed, rc=");
      Serial.print(client.state());
      Serial.println(" Esperando 5 segundos");
      
      // Tiempo muerto de 5 segundos
      delay(5000);
    }
  }
}

void setup() {
  
  FastLED.addLeds<SK6812, DATA_PIN, RGB>(leds, NUM_LEDS);  // GRB ordering is typical 
  Serial.begin(115200);
  Serial.setDebugOutput(true);
  pinMode(pin_agel, INPUT);
  pinMode(pin_agua, INPUT);
  pinMode(pin_papel, INPUT);
  setup_wifi();
  delay(1000);
  
  //****************
  if (!SPIFFS.begin(true)) {
    Serial.println("Se ha producido un error al montar SPIFFS");
    return;
  }
  //**********************
  //Root CA leer archivo.
  File file2 = SPIFFS.open("/AmazonRootCA1.pem", "r");
  if (!file2) {
    Serial.println("No se pudo abrir el archivo para leerlo");
    return;
  }
  Serial.println("Root CA File Content:");
  while (file2.available()) {
    Read_rootca = file2.readString();
    Serial.println(Read_rootca);
  }
  //*****************************
  // Cert leer archivo
  File file4 = SPIFFS.open("/6c57eabebe-certificate.pem.crt", "r");
  if (!file4) {
    Serial.println("No se pudo abrir el archivo para leerlo");
    return;
  }
  Serial.println("Cert File Content:");
  while (file4.available()) {
    Read_cert = file4.readString();
    Serial.println(Read_cert);
  }
  //***************************************
  //Privatekey leer archivo
  File file6 = SPIFFS.open("/6c57eabebe-private.pem.key", "r");
  if (!file6) {
    Serial.println("No se pudo abrir el archivo para leerlo");
    return;
  }
  Serial.println("privateKey contenido:");
  while (file6.available()) {
    Read_privatekey = file6.readString();
    Serial.println(Read_privatekey);
  }
  //=====================================================

  char* pRead_rootca;
  pRead_rootca = (char *)malloc(sizeof(char) * (Read_rootca.length() + 1));
  strcpy(pRead_rootca, Read_rootca.c_str());

  char* pRead_cert;
  pRead_cert = (char *)malloc(sizeof(char) * (Read_cert.length() + 1));
  strcpy(pRead_cert, Read_cert.c_str());

  char* pRead_privatekey;
  pRead_privatekey = (char *)malloc(sizeof(char) * (Read_privatekey.length() + 1));
  strcpy(pRead_privatekey, Read_privatekey.c_str());

  Serial.println("================================================================================================");
  Serial.println("Certificados que pasan adjuntan al espClient");
  Serial.println();
  Serial.println("Root CA:");
  Serial.write(pRead_rootca);
  Serial.println("================================================================================================");
  Serial.println();
  Serial.println("Cert:");
  Serial.write(pRead_cert);
  Serial.println("================================================================================================");
  Serial.println();
  Serial.println("privateKey:");
  Serial.write(pRead_privatekey);
  Serial.println("================================================================================================");

  espClient.setCACert(pRead_rootca);
  espClient.setCertificate(pRead_cert);
  espClient.setPrivateKey(pRead_privatekey);

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

  //******************************************
  WiFi.macAddress(mac);
  snprintf(mac_Id, sizeof(mac_Id), "%02x:%02x:%02x:%02x:%02x:%02x",
           mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]);
  Serial.println(mac_Id);
  //****************************************
  delay(2000);
  //M5.begin();
  M5.lcd.setTextSize(3);             //Set the text size to 2. 
  M5.Lcd.setCursor(50, 20);          //Set the cursor at (50,20).  
  M5.Lcd.print("Monitoring of ");    // Print text on the screen (string) 
  M5.Lcd.setCursor(10, 50);          //Set the cursor at (10,50).  
  M5.Lcd.print("cleaning supplies"); // Print text on the screen (string) 
}
void loop() {
    
  messageData = "";
  if (!client.connected()) {
    reconnect();
  }

  client.loop();

 //============ Monitoreo de Alcohol ==============
    if(digitalRead(pin_agel)==LOW){
      leds[1] = CRGB::Blue;
      leds[3] = CRGB::Blue;
      leds[6] = CRGB::Blue;
      leds[9] = CRGB::Blue;
      FastLED.show();  
     
      long now = millis();
      if (now - lastMsg > 1000) {
        --capacity;
        lastMsg = now;}       
      }
      
    else{
      leds[1] = CRGB::Black;
      leds[3] = CRGB::Black;
      leds[6] = CRGB::Black;
      leds[9] = CRGB::Black;
      FastLED.show();
    }   

 //========= Monitoreo de Agua ======================
       agua=digitalRead(pin_agua);

 //======== Monitoreo de Papel ======================
    if(digitalRead(pin_papel)== LOW){ 
      //while(digitalRead(pin_papel)== LOW){}
      long now2 = millis();
      if (now2 - lastMsg2 > 1000) {
        --papel;
        lastMsg2 = now2;}       
      }

     
   
 // ******************************* Enviando los valores de sensores a AWS IoT Core *******************************
     
      if ((millis() - lastTime) > timerDelay) {
        lastTime = millis();
        
        macIdStr = String(mac_Id);
        agel = String(capacity);
        sen_agua = String(agua);
        sen_papel = String(papel);
        snprintf (msg, BUFFER_LEN, "{\"mac_Id\" : \"%s\", \"Alcohol\" : %s, \"Agua\" : %s,\"Papel\" : %s}", macIdStr.c_str(),agel.c_str(), sen_agua.c_str(), sen_papel.c_str());
        Serial.print("Publicando mensaje: ");        
        Serial.println(msg);
        Serial.println("Alcohol: "+ agel+"%" +" Agua: "+sen_agua+" Papel: "+sen_papel);
        client.publish("sensor", msg);
      }
                     
}

Credits

Nestor Alejandro Ccencho Garcia

Nestor Alejandro Ccencho Garcia

2 projects • 1 follower

Comments