ENGLISH VERSION OF THE LORA TRANSMITING BOARD CODE
#include <SoftwareSerial.h>
SoftwareSerial mySerial(2, 3); // RX, TX
int lastLluvia = -1; // Variable para almacenar el último valor leído
const String securityKey = "SECURE123"; // Clave de seguridad
void setup() {
Serial.begin(115200); // Asegúrate de que el monitor serie esté configurado con la misma velocidad IMPORTANTE QUE ESTÉ ACTIVA LA PESTAÑA Ambos NL & CR
mySerial.begin(115200); // Configura el SoftwareSerial con la misma velocidad IMPORTANTE QUE ESTÉ ACTIVA LA PESTAÑA Ambos NL & CR
// Configuración del módulo RYLR998
mySerial.println("AT+ADDRESS=1"); // Dirección del transmisor
delay(100);
mySerial.println("AT+NETWORKID=20"); // ID de red
delay(100);
mySerial.println("AT+BAND=868000000"); // Frecuencia 868 MHz
delay(100);
mySerial.println("AT+PARAMETER=9,7,1,7"); // Configuración de parámetros LoRa
delay(100);
}
void loop() {
int lluvia = analogRead(A0); // Leer sensor de lluvia
// Enviar solo si el valor cambia significativamente (para evitar spam)
if (abs(lluvia - lastLluvia) > 10) {
lastLluvia = lluvia;
Serial.print("Level of water: ");
Serial.println(lluvia);
String message = securityKey + "|Very high water level in the upper part of the ravine 15 km from the town: " + String(lluvia);
mySerial.print("AT+SEND=2,");
mySerial.print(message.length());
mySerial.print(",");
mySerial.println(message); // Enviar dato por LoRa
}
// Advertencia si hay lluvia alta
if (lluvia > 100) {
Serial.println("SENDING WARNING: VERY DANGEROUS WATER LEVEL! In the upper part of the ravine, 15 km from the town.");
// Mensaje detallado con ubicación y descripción
String alerta = securityKey + "|ALERT: VERY DANGEROUS WATER LEVEL \n";
alerta += "Location: 39.4167°N, -0.4333°W\n";
alerta += "Upper part of the ravine 15 km from the town\n";
alerta += "Water level detected: " + String(lluvia);
mySerial.print("AT+SEND=2,");
mySerial.print(alerta.length());
mySerial.print(",");
mySerial.println(alerta); // Enviar alerta por LoRa
}
delay(2000);
}
ENGLISH VERSION OF THE LORA RECEIVER BOARD CODE
#include <SoftwareSerial.h>
#include <WiFiS3.h>
#include <ArduinoHttpClient.h>
// Datos WiFi
const char* SSID = "--------------";//WIFI NETWORK NAME
const char* PASSWORD = "--------";//WIFI NETWORK PASSWORD
// Datos de Telegram
const char* BOT_TOKEN = "----------------------------";// ID OF THE BOT THAT WILL SEND THE MESSAGES TO THE TELEGRAM GROUP
const char* CHAT_ID = "-------------";// TELEGRAM GROUP ID WHERE MESSAGES ARE SENT
const char* TELEGRAM_HOST = "api.telegram.org";
const int TELEGRAM_PORT = 443; // Usar HTTPS
WiFiSSLClient wifi;
HttpClient client = HttpClient(wifi, TELEGRAM_HOST, TELEGRAM_PORT);
SoftwareSerial mySerial(2, 3); // RX, TX
bool advertenciaRecibida = false; // Variable para saber si se ha recibido una advertencia
const String securityKey = "SECURE123"; // Clave de seguridad
String incomingMessage = ""; // Variable para acumular el mensaje entrante
// Función para codificar caracteres en URL correctamente, cuando se envían los mensajes por Telegram se envían correctamente
String urlEncode(String str) {
String encoded = "";
const char *hex = "0123456789ABCDEF";
for (size_t i = 0; i < str.length(); i++) {
char c = str.charAt(i);
if (isalnum(c) || c == '-' || c == '_' || c == '.' || c == '~') {
encoded += c;
} else if (c == ' ') {
encoded += "%20";
} else {
encoded += '%';
encoded += hex[(c >> 4) & 0xF];
encoded += hex[c & 0xF];
}
}
return encoded;
}
// Enviar mensaje a Telegram
void enviarMensajeTelegram(String mensaje) {
String encodedMessage = urlEncode(mensaje);
String url = "/bot" + String(BOT_TOKEN) + "/sendMessage?chat_id=" + String(CHAT_ID) + "&text=" + encodedMessage;
Serial.println("Sending message to Telegram...");
client.get(url);
int statusCode = client.responseStatusCode();
String response = client.responseBody();
Serial.print("Código de respuesta: ");
Serial.println(statusCode);
Serial.println("Respuesta: " + response);
if (statusCode != 200) {
Serial.println("ERROR: Verify that the BOT_TOKEN and CHAT_ID are correct.");
}
}
// Procesar mensaje recibido
void processMessage(String message) {
Serial.println("Processing message: " + message);
if (message.startsWith("+RCV=")) {
int startComma = message.indexOf(',', message.indexOf(',') + 1) + 1;
int endIndex = message.indexOf('|');
if (startComma != -1 && endIndex != -1) {
String receivedSecurityKey = message.substring(startComma, endIndex);
Serial.println("Security key received: " + receivedSecurityKey);
if (receivedSecurityKey.equals(securityKey)) {
advertenciaRecibida = true; // Se ha recibido una advertencia
String verifiedMessage = message.substring(endIndex + 1);
Serial.println("Message received and verified: " + verifiedMessage);
// Revisar el nivel de agua localmente
int humedad = analogRead(A0); // Lectura del sensor de humedad local
if (humedad > 100) { // Doble positivo: advertencia recibida y nivel de agua alto
Serial.println("Very high water level detected locally after receiving a warning! Connecting to Wi-Fi...");
// Conectar a WiFi
Serial.print("Connecting to WiFi:");
Serial.println(SSID);
WiFi.begin(SSID, PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500);
}
Serial.println("\nConnected to WiFi!");
// Enviar múltiples mensajes de alerta
delay(10000);
for (int i = 0; i < 6; i++) {
String mensajeTelegram;
if (i == 5) {
mensajeTelegram = "🚨 VERY DANGEROUS SITUATION 🚨 \n";
mensajeTelegram += "🌧️ Sensor 1: Very dangerous level in (39.4699, -0.3763), Upper section of the ravine located 15 km from the village.\n";
mensajeTelegram += "💧Sensor 2: Very dangerous level in (39.4701, -0.3767), Middle section of the ravine located 12,5 km from the village.\n";
mensajeTelegram += "⚠️VERY DANGEROUS SITUATION! GO QUICKLY TO A HIGH PLACE, MORE THAN 6 meters above the ground";
} else {
mensajeTelegram = "⚠️ALERT: WATER LEVEL VERY HIGH! VERY DANGEROUS SITUATION\n";
mensajeTelegram += "📍Sensor 1: (39.4699, -0.3763) - Upper section of the ravine located 15 km from the village.\n";
mensajeTelegram += "📍Sensor 2: (39.4701, -0.3767) - Middle section of the ravine located 12,5 km from the village.";
}
enviarMensajeTelegram(mensajeTelegram);
delay(30000); // Esperar 30 segundos entre mensajes
}
}
} else {
Serial.println("Unverified message. Incorrect security key.");
}
} else {
Serial.println("Warning received:" + message);
}
} else {
Serial.println("Message received:" + message);
}
}
void setup() {
Serial.begin(115200); // Asegúrate de que el monitor serie esté configurado con la misma velocidad IMPORTANTE QUE ESTÉ ACTIVA LA PESTAÑA Ambos NL & CR
mySerial.begin(115200); // Configura el SoftwareSerial con la misma velocidad IMPORTANTE QUE ESTÉ ACTIVA LA PESTAÑA Ambos NL & CR
// Configuración del módulo RYLR998
Serial.println("Configuring the LoRa receiver module...");
mySerial.println("AT+ADDRESS=2"); // Dirección del receptor
delay(100);
mySerial.println("AT+NETWORKID=20"); // ID de red
delay(100);
mySerial.println("AT+BAND=868000000"); // Frecuencia 868 MHz
delay(100);
mySerial.println("AT+PARAMETER=9,7,1,7"); // Configuración de parámetros LoRa
delay(100);
Serial.println("Setup complete. Waiting for messages...");
}
void loop() {
while (mySerial.available()) {
char ch = mySerial.read();
incomingMessage += ch;
// Verificar si el mensaje completo ha sido recibido
if (ch == '\n') {
processMessage(incomingMessage);
incomingMessage = ""; // Reiniciar el mensaje entrante
}
}
}