Joa0712

Desafío 18/09/25

Sep 18th, 2025 (edited)
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 5.40 KB | Software | 0 0
  1. /*Respetando TODOS los conceptos vistos en clase, realizar un código en Arduino utilizando el ESP32 o ESP8266.
  2.  
  3. Requerimientos MÍNIMOS:
  4. Blink que realice un destello de 100ms cada 2000ms.
  5. Mensajes por el puerto serie
  6. Cuando inicia el sistema: Apellido y nombre del programador.
  7. Cuando se conecta al WiFi, IP que se le fué asignado.
  8. Conectarse al Wifi que tenga salida a internet (puede ser Alumnos)
  9. Conectarse a un Broker MQTT según las indicaciones del docente
  10. IP: broker.hivemq.com
  11. Puerto: 1883
  12. Publicar en el tópico ites/`apellido`/ini
  13. Mensaje con el Nombre y Apellido
  14. MAC del dispositivo
  15. Suscribirse al tópico ites/‘apellido’/msg
  16. Mostrar en el puerto serie, los mensajes provenientes del tópico ites/‘apellido’/msg*/
  17.  
  18.  
  19.  
  20. #include <ESP8266WiFi.h>
  21. #include <PubSubClient.h>
  22.  
  23. #define APELLIDO            "Soberon"
  24. #define NOMBRE              "Joaquin"
  25.  
  26. // === WIFI / MQTT ===
  27. #define WIFI_SSID           "Alumnos"
  28. #define WIFI_PASS           ""                
  29. #define MQTT_HOST           "broker.hivemq.com"
  30. #define MQTT_PORT           1883
  31.  
  32. // === TOPICS REQUERIDOS ===
  33. #define TOPIC_PUB_INI       "ites/soberon/ini"  
  34. #define TOPIC_SUB_MSG       "ites/soberon/msg"  
  35.  
  36. // (opcionales útiles)
  37. #define TOPIC_LWT           "ites/soberon/esp8266/lwt"
  38.  
  39. // === TIEMPOS (ms) ===
  40. #define REINTENTO_WIFI_MS   3000
  41. #define REINTENTO_MQTT_MS   3000
  42.  
  43. // === BLINK: 100 ms ON cada 2000 ms ===
  44. #define BLINK_PERIOD_MS     2000UL
  45. #define BLINK_ON_MS         100UL
  46.  
  47. // === LED integrado (ESP8266 activo LOW) ===
  48. #define PIN_LED             LED_BUILTIN
  49. #define LED_ACTIVO_LOW      1
  50.  
  51. #define CONFIG_LED          pinMode(PIN_LED, OUTPUT)
  52. #define _LED_ON()           digitalWrite(PIN_LED, (LED_ACTIVO_LOW ? LOW  : HIGH))
  53. #define _LED_OFF()          digitalWrite(PIN_LED, (LED_ACTIVO_LOW ? HIGH : LOW))
  54. #define AJUSTAR_LED(x)      do { if (x) _LED_ON(); else _LED_OFF(); } while (0)
  55.  
  56. // === Objetos del sistema ===
  57. WiFiClient      NET;
  58. PubSubClient    MQTT(NET);
  59.  
  60. static bool wifiReported = false;    
  61. static bool blinkOn = false;        
  62. static unsigned long tBlink = 0;    
  63.  
  64. // === Declaraciones ===
  65. void TaskWiFi(void);
  66. void TaskMQTT(void);
  67. void TaskBlink(void);
  68. void OnMqttMessage(char* topic, byte* payload, unsigned int length);
  69.  
  70. // Callback MQTT
  71. void OnMqttMessage(char* topic, byte* payload, unsigned int length) {
  72.   String t = String(topic);
  73.   String msg; msg.reserve(length);
  74.   for (unsigned int i = 0; i < length; i++) msg += (char)payload[i];
  75.  
  76.   if (t == String(TOPIC_SUB_MSG)) {
  77.     Serial.print("[MQTT] Mensaje en ");
  78.     Serial.print(TOPIC_SUB_MSG);
  79.     Serial.print(": ");
  80.     Serial.println(msg);
  81.   }
  82. }
  83.  
  84. void TaskWiFi(void) {
  85.   static unsigned long t_last = 0;
  86.  
  87.   if (WiFi.status() == WL_CONNECTED) {
  88.     if (!wifiReported) {
  89.       wifiReported = true;
  90.       Serial.print("[WiFi] Conectado. IP asignada: ");
  91.       Serial.println(WiFi.localIP());
  92.     }
  93.     return;
  94.   }
  95.  
  96.   wifiReported = false;
  97.  
  98.   if (millis() - t_last < REINTENTO_WIFI_MS) return;
  99.   t_last = millis();
  100.  
  101.   Serial.print("[WiFi] Conectando a SSID: ");
  102.   Serial.println(WIFI_SSID);
  103.   WiFi.mode(WIFI_STA);
  104.   WiFi.begin(WIFI_SSID, WIFI_PASS);
  105. }
  106.  
  107. void TaskMQTT(void) {
  108.   static unsigned long t_last = 0;
  109.  
  110.   if (WiFi.status() != WL_CONNECTED) return;
  111.  
  112.   if (!MQTT.connected()) {
  113.     if (millis() - t_last < REINTENTO_MQTT_MS) return;
  114.     t_last = millis();
  115.  
  116.     String clientId = "esp8266-" + String(ESP.getChipId(), HEX);
  117.  
  118.     Serial.print("[MQTT] Conectando a ");
  119.     Serial.print(MQTT_HOST);
  120.     Serial.print(":");
  121.     Serial.print(MQTT_PORT);
  122.     Serial.print(" como ");
  123.     Serial.println(clientId);
  124.  
  125.     if (MQTT.connect(clientId.c_str(),
  126.                      TOPIC_LWT, 1, true,
  127.                      "offline")) {
  128.  
  129.       MQTT.publish(TOPIC_LWT, "online", true);
  130.       Serial.println("[MQTT] Conectado. LWT=online");
  131.  
  132.       MQTT.subscribe(TOPIC_SUB_MSG, 1);
  133.       Serial.print("[MQTT] Suscripto a: ");
  134.       Serial.println(TOPIC_SUB_MSG);
  135.  
  136.       String mac = WiFi.macAddress();
  137.       String payload = String("Nombre y Apellido: ") + NOMBRE + " " + APELLIDO + " | MAC: " + mac;
  138.       MQTT.publish(TOPIC_PUB_INI, payload.c_str(), false);
  139.       Serial.print("[MQTT] Publicado en ");
  140.       Serial.print(TOPIC_PUB_INI);
  141.       Serial.print(": ");
  142.       Serial.println(payload);
  143.     } else {
  144.       Serial.print("[MQTT] Falló conexión, rc=");
  145.       Serial.println(MQTT.state());
  146.     }
  147.     return;
  148.   }
  149.  
  150.   MQTT.loop();
  151. }
  152.  
  153. void TaskBlink(void) {
  154.   unsigned long now = millis();
  155.  
  156.   if (!blinkOn) {
  157.  
  158.     if (now - tBlink >= BLINK_PERIOD_MS) {
  159.       blinkOn = true;
  160.       tBlink = now;    
  161.       _LED_ON();
  162.     }
  163.   } else {
  164.      if (now - tBlink >= BLINK_ON_MS) {
  165.       blinkOn = false;
  166.       _LED_OFF();
  167.     }
  168.   }
  169. }
  170.  
  171. void setup() {
  172.   CONFIG_LED;
  173.   _LED_OFF();
  174.  
  175.   Serial.begin(115200);
  176.   delay(50);
  177.  
  178.   Serial.println("=======================================");
  179.   Serial.print("Programador: ");
  180.   Serial.print(APELLIDO);
  181.   Serial.print(", ");
  182.   Serial.println(NOMBRE);
  183.   Serial.println("Dispositivo: ESP8266");
  184.   Serial.println("=======================================");
  185.  
  186.   // MQTT
  187.   MQTT.setServer(MQTT_HOST, MQTT_PORT);
  188.   MQTT.setCallback(OnMqttMessage);
  189.  
  190.   MQTT.setKeepAlive(30);
  191.   MQTT.setBufferSize(1024);
  192.   MQTT.setSocketTimeout(10);
  193.  
  194.   tBlink = millis();    
  195.   blinkOn = false;      
  196. }
  197.  
  198. void loop() {
  199.   TaskWiFi();
  200.   TaskMQTT();
  201.   TaskBlink();
  202. }
Advertisement
Add Comment
Please, Sign In to add comment