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

Save/restore WLED state and set max brightness at startup #353

Merged
merged 3 commits into from
Nov 24, 2022
Merged
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
2 changes: 2 additions & 0 deletions assets/webconfig/i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -1164,6 +1164,8 @@
"philips_option_changed_bri": "<p style = 'color: red'>First set up your Philips LED lamps using the Philips mobile app: during setup, select the ENTERTAINMENT group for your lamps (you should get the ID of this group). Otherwise, communication performance using the old json API will be very bad!</p> Remember that using other home automation systems connected to lamps can cause various side effects when running HyperHDR.",
"select_wled_intro" : "Select WLED",
"select_wled_rescan" : "Rescan network",
"wledBrightnessOverride" : "Override WLED brightness",
"wledCustomBrightnessLevel" : "Custom WLED brightness level",
"edt_conf_mqtt_heading_title" : "MQTT client",
"conf_network_mqtt_intro" : "Registration of HyperHDR services with the MQTT broker",
"edt_conf_mqtt_ip_title" : "Hostname",
Expand Down
52 changes: 0 additions & 52 deletions assets/webconfig/js/content_huebridge.js

This file was deleted.

103 changes: 49 additions & 54 deletions sources/leddevice/dev_net/LedDeviceWled.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ LedDeviceWled::LedDeviceWled(const QJsonObject& deviceConfig)
: ProviderUdp(deviceConfig)
, _restApi(nullptr)
, _apiPort(API_DEFAULT_PORT)
, _overrideBrightness(true)
, _brightnessLevel(255)
, _restoreConfig(false)
{
}

Expand All @@ -47,20 +50,32 @@ LedDevice* LedDeviceWled::construct(const QJsonObject& deviceConfig)
}

bool LedDeviceWled::init(const QJsonObject& deviceConfig)
{
Debug(_log, "");
{
bool isInitOK = false;

Debug(_log, "Initializing WLED");

_configBackup = QJsonDocument();

// Initialise LedDevice sub-class, ProviderUdp::init will be executed later, if connectivity is defined
if (LedDevice::init(deviceConfig))
{
// Initialise LedDevice configuration and execution environment
int configuredLedCount = this->getLedCount();
Debug(_log, "DeviceType : %s", QSTRING_CSTR(this->getActiveDeviceType()));
Debug(_log, "LedCount : %d", configuredLedCount);
Debug(_log, "DeviceType : %s", QSTRING_CSTR(this->getActiveDeviceType()));
Debug(_log, "LedCount : %d", configuredLedCount);

_overrideBrightness = deviceConfig["brightnessMax"].toBool(true);
Debug(_log, "Override brightness : %s", (_overrideBrightness) ? "true" : "false");

_brightnessLevel = deviceConfig["brightnessMaxLevel"].toInt(255);
Debug(_log, "Set brightness level: %i", _brightnessLevel);

_restoreConfig = deviceConfig["restoreOriginalState"].toBool(false);
Debug(_log, "Restore WLED : %s", (_restoreConfig) ? "true" : "false");

_maxRetry = deviceConfig["maxRetry"].toInt(60);
Debug(_log, "Max retry : %d", _maxRetry);
Debug(_log, "Max retry : %d", _maxRetry);

//Set hostname as per configuration
QString address = deviceConfig[CONFIG_ADDRESS].toString();
Expand Down Expand Up @@ -119,21 +134,45 @@ bool LedDeviceWled::initRestAPI(const QString& hostname, int port)

QString LedDeviceWled::getOnOffRequest(bool isOn) const
{
QString state = isOn ? STATE_VALUE_TRUE : STATE_VALUE_FALSE;
return QString("{\"on\":%1,\"live\":%1}").arg(state);
if (!isOn && _restoreConfig && !_configBackup.isEmpty())
{
return QString(_configBackup.toJson(QJsonDocument::Compact));
}
else
{
QString state = isOn ? STATE_VALUE_TRUE : STATE_VALUE_FALSE;
QString bri = (_overrideBrightness && isOn) ? QString(",\"bri\":%1").arg(_brightnessLevel) : "";
return QString("{\"on\":%1,\"live\":%1%2}").arg(state).arg(bri);
}
}

bool LedDeviceWled::powerOn()
{
Debug(_log, "");
bool on = false;
auto current = QDateTime::currentMSecsSinceEpoch();

if (!_retryMode)
{
//Power-on WLED device
_restApi->setPath(API_PATH_STATE);
httpResponse response = _restApi->put(getOnOffRequest(true));

bool readConfig = _restoreConfig && _configBackup.isEmpty();
httpResponse response = (readConfig) ? _restApi->get() : _restApi->put(getOnOffRequest(true));

if (readConfig && !response.error())
{
_configBackup = response.getBody();

if (_configBackup.isObject())
{
auto copy = _configBackup.object();
copy["live"] = false;
_configBackup.setObject(copy);
}

response = _restApi->put(getOnOffRequest(true));
}

if (response.error())
{
this->setInError(response.getErrorReason());
Expand All @@ -152,15 +191,10 @@ bool LedDeviceWled::powerOn()
else
Error(_log, "The WLED device is not ready... give up.");


auto delta = QDateTime::currentMSecsSinceEpoch() - current;

delta = qMin(qMax(1000ll - delta, 50ll), 1000ll);

if (_currentRetry > 0)
{
_retryMode = true;
QTimer::singleShot(delta, [this]() { _retryMode = false; if (_currentRetry > 0) enableDevice(true); });
QTimer::singleShot(1000, [this]() { _retryMode = false; if (_currentRetry > 0) enableDevice(true); });
}
}
}
Expand Down Expand Up @@ -271,45 +305,6 @@ QJsonObject LedDeviceWled::getProperties(const QJsonObject& params)
return properties;
}

void LedDeviceWled::identify(const QJsonObject& /*params*/)
{
#if 0
Debug(_log, "params: [%s]", QString(QJsonDocument(params).toJson(QJsonDocument::Compact)).toUtf8().constData());

QString host = params["host"].toString("");
if (!host.isEmpty())
{
// Resolve hostname and port (or use default API port)
QStringList addressparts = QStringUtils::split(host, ":", QStringUtils::SplitBehavior::SkipEmptyParts);
QString apiHost = addressparts[0];
int apiPort;

if (addressparts.size() > 1)
apiPort = addressparts[1].toInt();
else
apiPort = API_DEFAULT_PORT;

// TODO: WLED::identify - Replace with valid identification code

// initRestAPI(apiHost, apiPort);

// QString resource = QString("%1/%2/%3").arg( API_LIGHTS ).arg( lightId ).arg( API_STATE);
// _restApi->setPath(resource);

// QString stateCmd;
// stateCmd += QString("\"%1\":%2,").arg( API_STATE_ON ).arg( API_STATE_VALUE_TRUE );
// stateCmd += QString("\"%1\":\"%2\"").arg( "alert" ).arg( "select" );
// stateCmd = "{" + stateCmd + "}";

// // Perform request
// httpResponse response = _restApi->put(stateCmd);
// if ( response.error() )
// {
// Warning (_log, "%s identification failed with error: '%s'", QSTRING_CSTR(_activeDeviceType), QSTRING_CSTR(response.getErrorReason()));
// }
}
#endif
}

int LedDeviceWled::write(const std::vector<ColorRgb>& ledValues)
{
Expand Down
18 changes: 4 additions & 14 deletions sources/leddevice/dev_net/LedDeviceWled.h
Original file line number Diff line number Diff line change
Expand Up @@ -60,20 +60,6 @@ class LedDeviceWled : public ProviderUdp
///
QJsonObject getProperties(const QJsonObject& params) override;

///
/// @brief Send an update to the WLED device to identify it.
///
/// Following parameters are required
/// @code
/// {
/// "host" : "hostname or IP [:port]",
/// }
///@endcode
///
/// @param[in] params Parameters to address device
///
void identify(const QJsonObject& params) override;

protected:

///
Expand Down Expand Up @@ -130,6 +116,10 @@ class LedDeviceWled : public ProviderUdp

QString _hostname;
int _apiPort;
bool _overrideBrightness;
int _brightnessLevel;
bool _restoreConfig;
QJsonDocument _configBackup;
};

#endif // LEDDEVICEWLED_H
33 changes: 32 additions & 1 deletion sources/leddevice/schemas/schema-wled.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,37 @@
"title":"edt_dev_spec_targetIpHost_title",
"propertyOrder" : 1
},
"brightnessMax": {
"type": "boolean",
"title":"wledBrightnessOverride",
"format": "checkbox",
"default" : true,
"propertyOrder" : 2
},
"brightnessMaxLevel":
{
"type" : "integer",
"format" : "stepper",
"step" : 1,
"title" : "wledCustomBrightnessLevel",
"minimum" : 1,
"maximum" : 255,
"default" : 255,
"options": {
"dependencies": {
"brightnessMax": true
}
},
"required" : true,
"propertyOrder" : 3
},
"restoreOriginalState": {
"type": "boolean",
"format": "checkbox",
"title":"edt_dev_spec_restoreOriginalState_title",
"default" : false,
"propertyOrder" : 4
},
"maxRetry":
{
"type" : "integer",
Expand All @@ -17,7 +48,7 @@
"maximum" : 300,
"default" : 60,
"required" : true,
"propertyOrder" : 2
"propertyOrder" : 5
}
},
"additionalProperties": true
Expand Down