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

Put debug messages behind a define guard to reduce binary size #135

Open
wants to merge 1 commit 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
47 changes: 46 additions & 1 deletion src/EspMQTTClient.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -116,8 +116,10 @@ void EspMQTTClient::enableHTTPWebUpdater(const char* username, const char* passw
_updateServerPassword = (char*)password;
_updateServerAddress = (char*)address;
}
#ifdef ENABLE_DEBUG_MESSAGES
else if (_enableDebugMessages)
Serial.print("SYS! You can't call enableHTTPWebUpdater() more than once !\n");
#endif
}

void EspMQTTClient::enableHTTPWebUpdater(const char* address)
Expand Down Expand Up @@ -212,9 +214,10 @@ bool EspMQTTClient::handleWiFi()
{
if(WiFi.status() == WL_CONNECT_FAILED || millis() - _lastWifiConnectionAttemptMillis >= _wifiReconnectionAttemptDelay)
{
#ifdef ENABLE_DEBUG_MESSAGES
if(_enableDebugMessages)
Serial.printf("WiFi! Connection attempt failed, delay expired. (%fs). \n", millis()/1000.0);

#endif
WiFi.disconnect(true);
MDNS.end();

Expand Down Expand Up @@ -311,14 +314,18 @@ bool EspMQTTClient::handleMQTT()
_mqttClient.disconnect();
_failedMQTTConnectionAttemptCount++;

#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
Serial.printf("MQTT!: Failed MQTT connection count: %i \n", _failedMQTTConnectionAttemptCount);
#endif

// When there is too many failed attempt, sometimes it help to reset the WiFi connection or to restart the board.
if(_handleWiFi && _failedMQTTConnectionAttemptCount == 8)
{
#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
Serial.println("MQTT!: Can't connect to broker after too many attempt, resetting WiFi ...");
#endif

WiFi.disconnect(true);
MDNS.end();
Expand All @@ -329,8 +336,10 @@ bool EspMQTTClient::handleMQTT()
}
else if(_drasticResetOnConnectionFailures && _failedMQTTConnectionAttemptCount == 12) // Will reset after 12 failed attempt (3 minutes of retry)
{
#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
Serial.println("MQTT!: Can't connect to broker after too many attempt, resetting board ...");
#endif

#ifdef ESP8266
ESP.reset();
Expand All @@ -356,8 +365,10 @@ bool EspMQTTClient::handleMQTT()

void EspMQTTClient::onWiFiConnectionEstablished()
{
#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
Serial.printf("WiFi: Connected (%fs), ip : %s \n", millis()/1000.0, WiFi.localIP().toString().c_str());
#endif

// Config of web updater
if (_httpServer != NULL)
Expand All @@ -367,8 +378,10 @@ void EspMQTTClient::onWiFiConnectionEstablished()
_httpServer->begin();
MDNS.addService("http", "tcp", 80);

#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
Serial.printf("WEB: Updater ready, open http://%s.local in your browser and login with username '%s' and password '%s'.\n", _mqttClientName, _updateServerUsername, _updateServerPassword);
#endif
}

if (_enableOTA)
Expand All @@ -377,8 +390,10 @@ void EspMQTTClient::onWiFiConnectionEstablished()

void EspMQTTClient::onWiFiConnectionLost()
{
#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
Serial.printf("WiFi! Lost connection (%fs). \n", millis()/1000.0);
#endif

// If we handle wifi, we force disconnection to clear the last connection
if (_handleWiFi)
Expand All @@ -396,11 +411,13 @@ void EspMQTTClient::onMQTTConnectionEstablished()

void EspMQTTClient::onMQTTConnectionLost()
{
#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
{
Serial.printf("MQTT! Lost connection (%fs). \n", millis()/1000.0);
Serial.printf("MQTT: Retrying to connect in %i seconds. \n", _mqttReconnectionAttemptDelay / 1000);
}
#endif
}


Expand All @@ -412,8 +429,10 @@ bool EspMQTTClient::setMaxPacketSize(const uint16_t size)

bool success = _mqttClient.setBufferSize(size);

#ifdef ENABLE_DEBUG_MESSAGES
if(!success && _enableDebugMessages)
Serial.println("MQTT! failed to set the max packet size.");
#endif

return success;
}
Expand All @@ -423,21 +442,25 @@ bool EspMQTTClient::publish(const char* topic, const uint8_t* payload, unsigned
// Do not try to publish if MQTT is not connected.
if(!isConnected())
{
#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
Serial.println("MQTT! Trying to publish when disconnected, skipping.");
#endif

return false;
}

bool success = _mqttClient.publish(topic, payload, plength, retain);

#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
{
if(success)
Serial.printf("MQTT << [%s] %s\n", topic, payload);
else
Serial.println("MQTT! publish failed, is the message too long ? (see setMaxPacketSize())"); // This can occurs if the message is too long according to the maximum defined in PubsubClient.h
}
#endif

return success;
}
Expand All @@ -453,8 +476,10 @@ bool EspMQTTClient::subscribe(const String &topic, MessageReceivedCallback messa
// Do not try to subscribe if MQTT is not connected.
if(!isConnected())
{
#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
Serial.println("MQTT! Trying to subscribe when disconnected, skipping.");
#endif

return false;
}
Expand All @@ -472,13 +497,15 @@ bool EspMQTTClient::subscribe(const String &topic, MessageReceivedCallback messa
_topicSubscriptionList.push_back({ topic, messageReceivedCallback, NULL });
}

#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
{
if(success)
Serial.printf("MQTT: Subscribed to [%s]\n", topic.c_str());
else
Serial.println("MQTT! subscribe failed");
}
#endif

return success;
}
Expand All @@ -498,8 +525,10 @@ bool EspMQTTClient::unsubscribe(const String &topic)
// Do not try to unsubscribe if MQTT is not connected.
if(!isConnected())
{
#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
Serial.println("MQTT! Trying to unsubscribe when disconnected, skipping.");
#endif

return false;
}
Expand All @@ -513,13 +542,17 @@ bool EspMQTTClient::unsubscribe(const String &topic)
_topicSubscriptionList.erase(_topicSubscriptionList.begin() + i);
i--;

#ifdef ENABLE_DEBUG_MESSAGES
if(_enableDebugMessages)
Serial.printf("MQTT: Unsubscribed from %s\n", topic.c_str());
#endif
}
else
{
#ifdef ENABLE_DEBUG_MESSAGES
if(_enableDebugMessages)
Serial.println("MQTT! unsubscribe failed");
#endif

return false;
}
Expand Down Expand Up @@ -564,8 +597,10 @@ void EspMQTTClient::connectToWifi()
#endif
WiFi.begin(_wifiSsid, _wifiPassword);

#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
Serial.printf("\nWiFi: Connecting to %s ... (%fs) \n", _wifiSsid, millis()/1000.0);
#endif
}

// Try to connect to the MQTT broker and return True if the connection is successfull (blocking)
Expand All @@ -575,25 +610,30 @@ bool EspMQTTClient::connectToMqttBroker()

if (_mqttServerIp != nullptr && strlen(_mqttServerIp) > 0)
{
#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
{
if (_mqttUsername)
Serial.printf("MQTT: Connecting to broker \"%s\" with client name \"%s\" and username \"%s\" ... (%fs)", _mqttServerIp, _mqttClientName, _mqttUsername, millis()/1000.0);
else
Serial.printf("MQTT: Connecting to broker \"%s\" with client name \"%s\" ... (%fs)", _mqttServerIp, _mqttClientName, millis()/1000.0);
}
#endif

// explicitly set the server/port here in case they were not provided in the constructor
_mqttClient.setServer(_mqttServerIp, _mqttServerPort);
success = _mqttClient.connect(_mqttClientName, _mqttUsername, _mqttPassword, _mqttLastWillTopic, 0, _mqttLastWillRetain, _mqttLastWillMessage, _mqttCleanSession);
}
else
{
#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
Serial.printf("MQTT: Broker server ip is not set, not connecting (%fs)\n", millis()/1000.0);
success = false;
#endif
}

#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
{
if (success)
Expand Down Expand Up @@ -636,6 +676,7 @@ bool EspMQTTClient::connectToMqttBroker()
Serial.printf("MQTT: Retrying to connect in %i seconds.\n", _mqttReconnectionAttemptDelay / 1000);
}
}
#endif

return success;
}
Expand Down Expand Up @@ -726,8 +767,10 @@ void EspMQTTClient::mqttMessageReceivedCallback(char* topic, uint8_t* payload, u
{
strTerminationPos = length - 1;

#ifdef ENABLE_DEBUG_MESSAGES
if (_enableDebugMessages)
Serial.print("MQTT! Your message may be truncated, please set setMaxPacketSize() to a higher value.\n");
#endif
}
else
strTerminationPos = length;
Expand All @@ -737,9 +780,11 @@ void EspMQTTClient::mqttMessageReceivedCallback(char* topic, uint8_t* payload, u
String payloadStr((char*)payload);
String topicStr(topic);

#ifdef ENABLE_DEBUG_MESSAGES
// Logging
if (_enableDebugMessages)
Serial.printf("MQTT >> [%s] %s\n", topic, payloadStr.c_str());
#endif

// Send the message to subscribers
for (std::size_t i = 0 ; i < _topicSubscriptionList.size() ; i++)
Expand Down
4 changes: 4 additions & 0 deletions src/EspMQTTClient.h
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,10 @@

#endif

// remove macro when compiling to remove all calls to Serial.print[ln]?
// and reduce binary size
#define ENABLE_DEBUG_MESSAGES

void onConnectionEstablished(); // MUST be implemented in your sketch. Called once everythings is connected (Wifi, mqtt).

typedef std::function<void()> ConnectionEstablishedCallback;
Expand Down