Skip to content

Instantly share code, notes, and snippets.

@DiegoAscanio
Created August 14, 2024 16:31
Show Gist options
  • Save DiegoAscanio/8c513756031861a818560a1ba60ec059 to your computer and use it in GitHub Desktop.
Save DiegoAscanio/8c513756031861a818560a1ba60ec059 to your computer and use it in GitHub Desktop.
// inlude the necessary libraries
#include "Adafruit_MQTT.h"
#include "Adafruit_MQTT_Client.h"
#include "secrets.h"
#include <ESP8266WiFi.h>
#include <SoftwareSerial.h>
// define the pins for the software serial
#define RX 2
#define TX 0
// create the software serial object
SoftwareSerial mySerial(RX, TX);
// create the wifi client object
WiFiClient client;
// Create an Adafruit IO MQTT client object to connect to the Adafruit IO
// MQTT server
Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY);
// Create a RFIDPublisher to report RFID tags read through software serial
Adafruit_MQTT_Publish RFIDPublisher = Adafruit_MQTT_Publish(&mqtt, AIO_USERNAME "/feeds/rfid");
void connectToWifi() {
// connect to the WiFi network
Serial.println("Connecting to WiFi...");
WiFi.begin(WIFI_SSID, WIFI_PASS);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("Connected to WiFi");
Serial.println("IP address: " + WiFi.localIP().toString());
}
void MQTT_connect() {
int8_t ret;
// Stop if already connected.
if (mqtt.connected()) {
return;
}
Serial.print("Connecting to MQTT... ");
uint8_t retries = 3;
while ((ret = mqtt.connect()) != 0) { // connect will return 0 for connected
Serial.println(mqtt.connectErrorString(ret));
Serial.println("Retrying MQTT connection in 5 seconds...");
mqtt.disconnect();
delay(5000); // wait 5 seconds
retries--;
if (retries == 0) {
// basically die and wait for WDT to reset me
while (1);
}
}
Serial.println("MQTT Connected!");
}
void setup() {
// start the serial communication
Serial.begin(115200);
mySerial.begin(9600);
// add a delay to allow the serial communication to start
delay(500);
// connect to the wifi network
connectToWifi();
// perform the MQTT connection
MQTT_connect();
}
void forwardSerialMessageThroughMQTT() {
// read the serial message
if (mySerial.available()) {
String message = mySerial.readStringUntil('\n');
Serial.println("Received message: " + message);
// publish the message to the MQTT topic
if (!RFIDPublisher.publish(message.c_str())) {
Serial.println("Failed to publish message");
}
}
}
void loop() {
// Ensure the connection to the MQTT server is alive (this will make the first
// connection and automatically reconnect when disconnected). See the MQTT_connect
MQTT_connect();
// forward read RFID tags from SoftwareSerial through MQTT
forwardSerialMessageThroughMQTT();
// ping the server to keep the mqtt connection alive
if (! mqtt.ping()) {
mqtt.disconnect();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment