Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

src: add basic mqtt support #265

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
83 changes: 83 additions & 0 deletions marquee/MqttClient.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/** The MIT License (MIT)

Copyright (c) 2023 Michael Dawson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "MqttClient.h"

WiFiClient wclient;

char lastMqttMessage[128] = {0};
bool lastMqttMessageNew = true;

void callback(char* topic, uint8_t* message, unsigned int length) {
memcpy(lastMqttMessage, message, length);
lastMqttMessage[length] = 0;
lastMqttMessageNew = true;
}

MqttClient::MqttClient(String passedServer, int port, String passedTopic):
client("", 0, callback, wclient) {
updateMqttClient(passedServer, port, passedTopic);
}

void MqttClient::updateMqttClient(String passedServer, int port, String passedTopic) {
this->port = port;
passedServer.toCharArray(server, MAX_SERVER_LEN);
passedTopic.toCharArray(topic, MAX_TOPIC_LEN);
client.setServer(server, port);
client.disconnect();
}

char* MqttClient::getLastMqttMessage() {
if (strlen(lastMqttMessage) != 0) {
return lastMqttMessage;
}
return "";
};

char* MqttClient::getNewMqttMessage() {
if (lastMqttMessageNew == true) {
lastMqttMessageNew = false;
return getLastMqttMessage();
}
return "";
};


String MqttClient::getError() {
return failMessage;
}

void MqttClient::loop() {
if (!client.connected()) {
if (client.connect("marquee")) {
failMessage[0] = 0;
if (!client.subscribe(topic))
sprintf(failMessage, "Failed to connect to topic:%s", topic);
} else {
sprintf(failMessage, "Failed to connect to: %s:%d, reason: %d", server, port, client.state());
}
}
if (client.connected()) {
client.loop();
}
}
53 changes: 53 additions & 0 deletions marquee/MqttClient.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
/** The MIT License (MIT)

Copyright (c) 2023 Michael Dawson

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#pragma once
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
#include <WiFiClient.h>
#include <PubSubClient.h>

#define MAX_TOPIC_LEN 128
#define MAX_SERVER_LEN 128


class MqttClient {

private:
WiFiClient wclient;
String lastMessage = "";
PubSubClient client;
char topic[MAX_TOPIC_LEN] = {0};
char server[MAX_SERVER_LEN] = {0};
int port = 0;
char failMessage[MAX_TOPIC_LEN + 100] = {0};

public:
MqttClient(String passedServer, int port, String passedTopic);
String getError();
char* getLastMqttMessage();
char* getNewMqttMessage();
void updateMqttClient(String passedServer, int port, String passedTopic);

void loop();
};
7 changes: 7 additions & 0 deletions marquee/Settings.h
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,7 @@ SOFTWARE.
#include "NewsApiClient.h"
#include "OctoPrintClient.h"
#include "PiHoleClient.h"
#include "MqttClient.h"

//******************************
// Start Settings
Expand Down Expand Up @@ -111,6 +112,12 @@ boolean USE_PIHOLE = false; // Set true to display your Pi-hole details
String PiHoleServer = ""; // IP or Address only (DO NOT include http://)
int PiHolePort = 80; // Port of your Pi-hole address (default 80)
String PiHoleApiKey = ""; // Optional -- only needed to see top blocked clients

// Mqtt add scrolling messages with Mqtt
boolean USE_MQTT = false; // Set true to display mqtt messages
String MqttServer = ""; // IP or Address only (DO NOT include http://)
int MqttPort = 1883; // Port of your mqtt server (default 1883)
String MqttTopic = "display/message"; // Topic on which to listen

boolean ENABLE_OTA = true; // this will allow you to load firmware to the device over WiFi (see OTA for ESP8266)
String OTA_Password = ""; // Set an OTA password here -- leave blank if you don't want to be prompted for password
Expand Down
115 changes: 115 additions & 0 deletions marquee/marquee.ino
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,9 @@ int printerCount = 0;
// Pi-hole Client
PiHoleClient piholeClient;

// Mqtt Client
MqttClient mqttClient(MqttServer, MqttPort, MqttTopic);

ESP8266WebServer server(WEBSERVER_PORT);
ESP8266HTTPUpdateServer serverUpdater;

Expand All @@ -99,6 +102,7 @@ static const char WEB_ACTIONS1[] PROGMEM = "<a class='w3-bar-item w3-button' hre
"<a class='w3-bar-item w3-button' href='/configureoctoprint'><i class='fas fa-cube'></i> OctoPrint</a>";

static const char WEB_ACTIONS2[] PROGMEM = "<a class='w3-bar-item w3-button' href='/configurepihole'><i class='fas fa-network-wired'></i> Pi-hole</a>"
"<a class='w3-bar-item w3-button' href='/configuremqtt'><i class='fas fa-network-wired'></i> Mqtt</a>"
"<a class='w3-bar-item w3-button' href='/pull'><i class='fas fa-cloud-download-alt'></i> Refresh Data</a>"
"<a class='w3-bar-item w3-button' href='/display'>";

Expand Down Expand Up @@ -155,6 +159,14 @@ static const char PIHOLE_FORM[] PROGMEM = "<form class='w3-container' action='/s
"<button class='w3-button w3-block w3-green w3-section w3-padding' type='submit'>Save</button></form>"
"<script>function isNumberKey(e){var h=e.which?e.which:event.keyCode;return!(h>31&&(h<48||h>57))}</script>";

static const char MQTT_FORM[] PROGMEM = "<form class='w3-container' action='/savemqtt' method='get'><h2>Mqtt Configuration:</h2>"
"<p><input name='displaymqtt' class='w3-check w3-margin-top' type='checkbox' %MQTTCHECKED%> Show Mqtt Statistics</p>"
"<label>Mqtt Address (do not include http://)</label><input class='w3-input w3-border w3-margin-bottom' type='text' name='mqttAddress' id='mqttAddress' value='%MQTTADDRESS%' maxlength='60'>"
"<label>Mqtt Port</label><input class='w3-input w3-border w3-margin-bottom' type='text' name='mqttPort' id='mqttPort' value='%MQTTPORT%' maxlength='5' onkeypress='return isNumberKey(event)'>"
"<label>Mqtt Topic</label><input class='w3-input w3-border w3-margin-bottom' type='text' name='mqttTopic' id='mqttTopic' value='%MQTTTOPIC%' maxlength='128'>"
"<button class='w3-button w3-block w3-green w3-section w3-padding' type='submit'>Save</button></form>"
"<script>function isNumberKey(e){var h=e.which?e.which:event.keyCode;return!(h>31&&(h<48||h>57))}</script>";

static const char PIHOLE_TEST[] PROGMEM = "<script>function testPiHole(){var e=document.getElementById(\"PiHoleTest\"),t=document.getElementById(\"piholeAddress\").value,"
"n=document.getElementById(\"piholePort\").value,api=document.getElementById(\"piApiToken\").value;;"
"if(e.innerHTML=\"\",\"\"==t||\"\"==n)return e.innerHTML=\"* Address and Port are required\","
Expand Down Expand Up @@ -319,13 +331,15 @@ void setup() {
server.on("/savenews", handleSaveNews);
server.on("/saveoctoprint", handleSaveOctoprint);
server.on("/savepihole", handleSavePihole);
server.on("/savemqtt", handleSaveMqtt);
server.on("/systemreset", handleSystemReset);
server.on("/forgetwifi", handleForgetWifi);
server.on("/configure", handleConfigure);
server.on("/configurewideclock", handleWideClockConfigure);
server.on("/configurenews", handleNewsConfigure);
server.on("/configureoctoprint", handleOctoprintConfigure);
server.on("/configurepihole", handlePiholeConfigure);
server.on("/configuremqtt", handleMqttConfigure);
server.on("/display", handleDisplay);
server.onNotFound(redirectHome);
serverUpdater.setup(&server, "/update", www_username, www_password);
Expand All @@ -348,6 +362,15 @@ void setup() {
// Main Looop
//************************************************************
void loop() {
// allow the mqtt client to do its thing
if (USE_MQTT) {
mqttClient.loop();
String newMqttMessage = mqttClient.getNewMqttMessage();
if (newMqttMessage != "") {
scrollMessage(newMqttMessage);
}
}

//Get some Weather Data to serve
if ((getMinutesFromLastRefresh() >= minutesBetweenDataRefresh) || lastEpoch == 0) {
getWeatherData();
Expand Down Expand Up @@ -436,6 +459,11 @@ void loop() {
}
}

if (USE_MQTT) {
// add mqtt message if there is one
msg += String(mqttClient.getLastMqttMessage());
}

scrollMessage(msg);
drawPiholeGraph();
}
Expand Down Expand Up @@ -565,6 +593,19 @@ void handleSavePihole() {
redirectHome();
}

void handleSaveMqtt() {
if (!athentication()) {
return server.requestAuthentication();
}
USE_MQTT = server.hasArg("displaymqtt");
MqttServer = server.arg("mqttAddress");
MqttPort = server.arg("mqttPort").toInt();
MqttTopic = server.arg("mqttTopic");

writeCityIds();
redirectHome();
}

void handleLocations() {
if (!athentication()) {
return server.requestAuthentication();
Expand Down Expand Up @@ -763,6 +804,41 @@ void handlePiholeConfigure() {
digitalWrite(externalLight, HIGH);
}

void handleMqttConfigure() {
if (!athentication()) {
return server.requestAuthentication();
}
digitalWrite(externalLight, LOW);

server.sendHeader("Cache-Control", "no-cache, no-store");
server.sendHeader("Pragma", "no-cache");
server.sendHeader("Expires", "-1");
server.setContentLength(CONTENT_LENGTH_UNKNOWN);
server.send(200, "text/html", "");

sendHeader();

String form = FPSTR(MQTT_FORM);
String isMqttDisplayedChecked = "";
if (USE_MQTT) {
isMqttDisplayedChecked = "checked='checked'";
}
form.replace("%MQTTCHECKED%", isMqttDisplayedChecked);
form.replace("%MQTTADDRESS%", MqttServer);
form.replace("%MQTTPORT%", String(MqttPort));
form.replace("%MQTTTOPIC%", String(MqttTopic));


server.sendContent(form);
form = "";

sendFooter();

server.sendContent("");
server.client().stop();
digitalWrite(externalLight, HIGH);
}

void handleConfigure() {
if (!athentication()) {
return server.requestAuthentication();
Expand Down Expand Up @@ -1146,6 +1222,21 @@ void displayWeatherData() {
html = "";
}

if (USE_MQTT) {
if (mqttClient.getError() == "") {
html = "<div class='w3-cell-row'><b>Mqtt</b><br>"
"Last Message: <b>" + String(mqttClient.getLastMqttMessage()) + "</b><br>"
"</div><br><hr>";
} else {
html = "<div class='w3-cell-row'> Mqtt Error";
html += "Please <a href='/configuremqtt' title='Configure'>Configure</a> for Mqtt <a href='/configuremqtt' title='Configure'><i class='fas fa-cog'></i></a><br>";
html += "Status: Error Connecting<br>";
html += "Reason: " + mqttClient.getError() + "<br></div><br><hr>";
}
server.sendContent(html);
html = "";
}

if (NEWS_ENABLED) {
html = "<div class='w3-cell-row' style='width:100%'><h2>News (" + NEWS_SOURCE + ")</h2></div>";
if (newsClient.getTitle(0) == "") {
Expand Down Expand Up @@ -1355,6 +1446,10 @@ String writeCityIds() {
f.println("PiHoleServer=" + PiHoleServer);
f.println("PiHolePort=" + String(PiHolePort));
f.println("PiHoleApiKey=" + String(PiHoleApiKey));
f.println("USE_MQTT=" + String(USE_MQTT));
f.println("MqttServer=" + MqttServer);
f.println("MqttPort=" + String(MqttPort));
f.println("MqttTopic=" + String(MqttTopic));
f.println("themeColor=" + themeColor);
}
f.close();
Expand Down Expand Up @@ -1552,6 +1647,25 @@ void readCityIds() {
PiHoleApiKey.trim();
Serial.println("PiHoleApiKey=" + String(PiHoleApiKey));
}
if (line.indexOf("USE_MQTT=") >= 0) {
USE_MQTT = line.substring(line.lastIndexOf("USE_MQTT=") + 9).toInt();
Serial.println("USE_MQTT=" + String(USE_MQTT));
}
if (line.indexOf("MqttServer=") >= 0) {
MqttServer = line.substring(line.lastIndexOf("MqttServer=") + 11);
MqttServer.trim();
Serial.println("MqttServer=" + String(MqttServer));
}
if (line.indexOf("MqttPort=") >= 0) {
MqttPort = line.substring(line.lastIndexOf("MqttPort=") + 9).toInt();
Serial.println("MqttPort=" + String(MqttPort));
}
if (line.indexOf("MqttTopic=") >= 0) {
MqttTopic = line.substring(line.lastIndexOf("MqttTopic=") + 10);
MqttTopic.trim();
Serial.println("MqttTopic=" + String(MqttTopic));
}

if (line.indexOf("themeColor=") >= 0) {
themeColor = line.substring(line.lastIndexOf("themeColor=") + 11);
themeColor.trim();
Expand All @@ -1565,6 +1679,7 @@ void readCityIds() {
weatherClient.setMetric(IS_METRIC);
weatherClient.updateCityIdList(CityIDs, 1);
printerClient.updateOctoPrintClient(OctoPrintApiKey, OctoPrintServer, OctoPrintPort, OctoAuthUser, OctoAuthPass);
mqttClient.updateMqttClient(MqttServer, MqttPort, MqttTopic);
}

void scrollMessage(String msg) {
Expand Down