Está en la página 1de 5

/*

Este código inicializa la conexión WiFi entre el micro Esp32 y la red local
Además establece conexión serial vía telegram a través de un bot previamente
creado, cuyo token o código de registro único se coloca en el código
y permite que solo el usuario que lo creó sea el que pueda interactuar con este
bot.
Este programa de prueba permite mediante comandos activar o desactivar un led que
en futuro sería el sensor MAX30102 y además envía mensajes al usuario
sin necesidad de un comando previo al detectar una señal alta en un pin de
referencia. Esto más tarde se usará para mandar los datos del sensor cuando tengan
niveles
anormales.
*/

#ifdef ESP32
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif
#include <WiFiClientSecure.h>
#include <UniversalTelegramBot.h> // Universal Telegram Bot Library written by
Brian Lough: https://github.com/witnessmenow/Universal-Arduino-Telegram-Bot
#include <ArduinoJson.h>
//////////////////////////////////////////////////////////////////
#include <Wire.h>
#include "MAX30105.h"

#include "heartRate.h"

MAX30105 particleSensor;

const byte RATE_SIZE = 10; //Increase this for more averaging. 4 is good.
byte rates[RATE_SIZE]; //Array of heart rates
byte rateSpot = 0;
long lastBeat = 0; //Time at which the last beat occurred
int i=0;
int z=0;
float beatsPerMinute;
int beatAvg;
//////////////////////////////////////////////////////////////////
// Replace with your network credentials
const char* ssid = "INFINITUMu5sp";
const char* password = "1f2ef358c3";

// Initialize Telegram BOT


#define BOTtoken "1797688318:AAGDBq16iLEGsjDb9mC7idlo0mLgclY_-lw" // your Bot
Token (Get from Botfather)

// Use @myidbot to find out the chat ID of an individual or a group


// Also note that you need to click "start" on a bot before it can
// message you
#define CHAT_ID "1751196097"

#ifdef ESP8266
X509List cert(TELEGRAM_CERTIFICATE_ROOT);
#endif

WiFiClientSecure client;
UniversalTelegramBot bot(BOTtoken, client);
// Checks for new messages every 1 second.
int botRequestDelay = 1000;
unsigned long lastTimeBotRan;
bool ledState = LOW;
///////////////////////////////////////////////////////////////////////////////////
////
// Handle what happens when you receive new messages
void handleNewMessages(int numNewMessages) {
Serial.println("handleNewMessages");
Serial.println(String(numNewMessages));

for (int i=0; i<numNewMessages; i++) {


// Chat id of the requester
String chat_id = String(bot.messages[i].chat_id);
if (chat_id != CHAT_ID){
bot.sendMessage(chat_id, "Unauthorized user", "");
continue;
}

// Print the received message


String text = bot.messages[i].text;
Serial.println(text);

String from_name = bot.messages[i].from_name;

if (text == "/iniciar") {
String welcome = "Bienvenido, " + from_name + ".\n";
welcome += "Lista de comandos.\n\n";
welcome += "/avg para obtener un promedio de los últimos 10 bpm \n";
welcome += "/estado para verificar el estado del usuario\n";
welcome += "/IR para verificar si el sensor está puesto adecuadamente \n";
welcome += "Coloca tu dedo índice en el sensor para obtener una lectura \n";
bot.sendMessage(chat_id, welcome, "");
}
if (text == "/avg") {
String funciona=String(beatAvg)+"bpm";
bot.sendMessage(chat_id,funciona, "");
}
if (text == "/estado") {
if (beatAvg<=40){
String funciona="Pulso por debajo de los 40bpm, verifique estado del usuario
o espere estabilización del sensor";
bot.sendMessage(chat_id,funciona, "");
}
if(beatAvg>=100){
String funciona="Pulso por encima de los 100bpm, verifique estado del usuario
o espere estabilización del sensor";
bot.sendMessage(chat_id,funciona, "");
}
if(beatAvg<100 && beatAvg>40){
String funciona="Paciente estable";
bot.sendMessage(chat_id,funciona, "");
}

}
if (text == "/IR") {
long irValue = particleSensor.getIR();
if (irValue < 50000){
String funciona="No hay dedo en el sensor, o está mal colocado";
bot.sendMessage(chat_id,funciona, "");
}
if(irValue > 50000){
String funciona="Sensor colocado adecuadamente";
bot.sendMessage(chat_id,funciona, "");
}
}
}
}
///////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////
void setup() {
Serial.begin(115200);
#ifdef ESP8266
configTime(0, 0, "pool.ntp.org"); // get UTC time via NTP
client.setTrustAnchors(&cert); // Add root certificate for api.telegram.org
#endif

// Connect to Wi-Fi
WiFi.mode(WIFI_STA);
WiFi.begin(ssid, password);
#ifdef ESP32
client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for
api.telegram.org
#endif
while (WiFi.status() != WL_CONNECTED) {
delay(1000);
Serial.println("Conectando a WiFi...");
}
// Print ESP32 Local IP Address
Serial.println(WiFi.localIP());
/////////////////////////////////////////////////////////////////////////////////
///////////
Serial.println("Inicializando sensor...");
// Initialize sensor
if (!particleSensor.begin(Wire, I2C_SPEED_FAST)) //Use default I2C port, 400kHz
speed
{
Serial.println("MAX30102 was not found. Please check wiring/power. ");
while (1);
}
Serial.println("Place your index finger on the sensor with steady pressure.");

particleSensor.setup(); //Configure sensor with default settings


particleSensor.setPulseAmplitudeRed(0x0A); //Turn Red LED to low to indicate
sensor is running
particleSensor.setPulseAmplitudeGreen(0); //Turn off Green LED

void loop() {
//Aquí va el código del sensor max//
long irValue = particleSensor.getIR();
if (checkForBeat(irValue) == true)
{
//We sensed a beat!
long delta = millis() - lastBeat;
lastBeat = millis();
beatsPerMinute = 60 / (delta / 1000.0);

if (beatsPerMinute < 255 && beatsPerMinute > 20)


{
rates[rateSpot++] = (byte)beatsPerMinute; //Store this reading in the array
rateSpot %= RATE_SIZE; //Wrap variable

//Take average of readings


beatAvg = 0;
for (byte x = 0 ; x < RATE_SIZE ; x++)
beatAvg += rates[x];
beatAvg /= RATE_SIZE;
}
}

Serial.print("IR=");
Serial.print(irValue);
Serial.print(", BPM=");
Serial.print(beatsPerMinute);
Serial.print(", Avg BPM=");
Serial.print(beatAvg);
Serial.print(", i=");
Serial.print(i);
if (irValue < 50000)
Serial.print(" No hay dedo?");
Serial.println();
/////////////////////////////////

if (millis() > lastTimeBotRan + botRequestDelay) {


int numNewMessages = bot.getUpdates(bot.last_message_received + 1);
while(numNewMessages) {
Serial.println("Respondiendo...");
handleNewMessages(numNewMessages);
numNewMessages = bot.getUpdates(bot.last_message_received + 1);
}
lastTimeBotRan = millis();
}
////////////////////////////////////////////////////////////////////////////
if (beatAvg<=40 && i>=1000){
String chat_id = String(bot.messages[i].chat_id);
bot.sendMessage(CHAT_ID,"Valor de pulso anormal, bajo", "");
z++;
}
if (beatAvg>=100&& i>=1000){
bot.sendMessage(CHAT_ID,"Valor de pulso anormal, alto", "");
z++;
}
i++;
if (z>=3){
z=0;
i=0;
}
if (i>=5000){
i=0;
}
//if (irValue < 50000)
//{
//String funciona= "Coloca el dedo índice en el sensor";
//bot.sendMessage(CHAT_ID, funciona, "");
//}
//if(irValue>50000){
//if (beatAvg<50){
//if (i=50){
//String funciona= "Alerta! valores de pulso muy bajos, verificar estado del
usuario";
//bot.sendMessage(CHAT_ID, funciona, "");
//i=0;
// }
//i++;
//}
//if (beatAvg>100){
//String funciona= "Alerta! valores de pulso muy altos, verificar estado del
usuario";
//bot.sendMessage(CHAT_ID, funciona, "");
//}
//}
}
//////////////////////////////////////////////////////////////////////////

También podría gustarte