#include #include #include #include #include #include #include "Adafruit_MQTT.h" #include "Adafruit_MQTT_Client.h" #include "credentials.h" #include "webserver.h" #include "socketserver.h" #include "util.h" static ESP8266WiFiMulti wifiMulti; static SocketServer socketServer; #define AIO_SERVER credentials::mqtt_hostname.c_str() #define AIO_SERVERPORT credentials::mqtt_port #define AIO_USERNAME credentials::mqtt_username.c_str() #define AIO_KEY credentials::mqtt_password.c_str() WiFiClient client; Adafruit_MQTT_Client mqtt(&client, AIO_SERVER, AIO_SERVERPORT, AIO_USERNAME, AIO_KEY); Adafruit_MQTT_Subscribe mqtt_subscribe_topic = Adafruit_MQTT_Subscribe(&mqtt, "homeassistant/marquee_sign/text/set"); Adafruit_MQTT_Publish mqtt_publish_topic = Adafruit_MQTT_Publish(&mqtt, "homeassistant/marquee_sign/text/status"); void MQTT_connect(); void setup() { // serial console, for use via USB (also exposed to TXD0/RXD0 GPIOs) Serial.begin(115200); // transmit-only UART port, used for communication with the LED sign // the BAUD rate was deducued from the communication sent to the USB 12V UART adapter by the available Windows // software Serial1.begin(9600); // configure WiFi and connect to the network WiFi.mode(WIFI_STA); WiFi.hostname(credentials::mdnsHostname); wifiMulti.addAP(credentials::ssid.c_str(), credentials::psk.c_str()); Serial.println("Connecting to Wi-Fi network..."); while (wifiMulti.run() != WL_CONNECTED) { delay(1000); Serial.print("."); } Serial.println(); Serial.print("Connected to "); Serial.print(WiFi.SSID()); Serial.print(", IP address: "); Serial.println(WiFi.localIP()); ArduinoOTA.begin(); mqtt.subscribe(&mqtt_subscribe_topic); // might be handy to have the IP written on the sign sendTextToSign(WiFi.localIP().toString()); // configure HTTP endpoints configureWebServer(); // don't forget to start all the services webServer.begin(); socketServer.begin(); } void loop() { webServer.handleClient(); socketServer.handleClient(); ArduinoOTA.handle(); MQTT_connect(); Adafruit_MQTT_Subscribe *subscription; while ((subscription = mqtt.readSubscription(5000))) { const char* signText = (char *)mqtt_subscribe_topic.lastread; sendTextToSign(signText); mqtt_publish_topic.publish(signText); } } void MQTT_connect() { int8_t ret; // Stop if already connected. if (mqtt.connected()) { return; } uint8_t retries = 6; // connect will return 0 for connected while ((ret = mqtt.connect()) != 0) { mqtt.disconnect(); // wait 10s till next try for (int i = 0; i < 10000; i += 5) { ArduinoOTA.handle(); delay(5); } retries--; if (retries == 0) { ESP.restart(); } } }