Update requestWriteConfig to new API format

This commit is contained in:
LordGrey 2024-11-08 16:34:06 +01:00
parent 8cf894bc4e
commit 075204482d
3 changed files with 255 additions and 290 deletions

View File

@ -34,34 +34,28 @@ tokenList = {};
const ENDLESS = -1;
function initRestart()
{
function initRestart() {
$(window.hyperion).off();
window.watchdog = 10;
connectionLostDetection('restart');
}
function connectionLostDetection(type)
{
if ( window.watchdog > 2 )
{
function connectionLostDetection(type) {
if (window.watchdog > 2) {
var interval_id = window.setInterval(function () { clearInterval(interval_id); }, 9999); // Get a reference to the last
for (var i = 1; i < interval_id; i++)
window.clearInterval(i);
if(type == 'restart')
{
if (type == 'restart') {
$("body").html($("#container_restart").html());
// setTimeout delay for probably slower systems, some browser don't execute THIS action
setTimeout(restartAction, 250);
}
else
{
else {
$("body").html($("#container_connection_lost").html());
connectionLostAction();
}
}
else
{
else {
$.get("/cgi/cfg_jsonserver", function () { window.watchdog = 0 }).fail(function () { window.watchdog++; });
}
}
@ -70,12 +64,9 @@ setInterval(connectionLostDetection, 3000);
// init websocket to hyperion and bind socket events to jquery events of $(hyperion) object
function initWebSocket()
{
if ("WebSocket" in window)
{
if (window.websocket == null)
{
function initWebSocket() {
if ("WebSocket" in window) {
if (window.websocket == null) {
window.jsonPort = '';
if (document.location.port == '' && document.location.protocol == "http:")
window.jsonPort = '80';
@ -96,8 +87,7 @@ function initWebSocket()
window.websocket.onclose = function (event) {
// See http://tools.ietf.org/html/rfc6455#section-7.4.1
var reason;
switch(event.code)
{
switch (event.code) {
case 1000: reason = "Normal closure, meaning that the purpose for which the connection was established has been fulfilled."; break;
case 1001: reason = "An endpoint is \"going away\", such as a server going down or a browser having navigated away from a page."; break;
case 1002: reason = "An endpoint is terminating the connection due to a protocol error"; break;
@ -119,18 +109,15 @@ function initWebSocket()
};
window.websocket.onmessage = function (event) {
try
{
try {
var response = JSON.parse(event.data);
var success = response.success;
var cmd = response.command;
var tan = response.tan
if (success || typeof(success) == "undefined")
{
if (success || typeof (success) == "undefined") {
$(window.hyperion).trigger({ type: "cmd-" + cmd, response: response });
}
else
{
else {
// skip tan -1 error handling
if (tan != -1) {
var error = response.hasOwnProperty("error") ? response.error : "unknown";
@ -144,8 +131,7 @@ function initWebSocket()
}
}
}
catch(exception_error)
{
catch (exception_error) {
$(window.hyperion).trigger({ type: "error", reason: exception_error });
console.log("[window.websocket::onmessage] ", exception_error)
}
@ -157,16 +143,14 @@ function initWebSocket()
};
}
}
else
{
else {
$(window.hyperion).trigger("error");
alert("Websocket is not supported by your browser");
return;
}
}
function sendToHyperion(command, subcommand, msg)
{
function sendToHyperion(command, subcommand, msg) {
if (typeof subcommand != 'undefined' && subcommand.length > 0)
subcommand = ',"subcommand":"' + subcommand + '"';
else
@ -232,38 +216,31 @@ async function __sendAsync (data) {
// wrapped server commands
// Test if admin requires authentication
function requestRequiresAdminAuth()
{
function requestRequiresAdminAuth() {
sendToHyperion("authorize", "adminRequired");
}
// Test if the default password needs to be changed
function requestRequiresDefaultPasswortChange()
{
function requestRequiresDefaultPasswortChange() {
sendToHyperion("authorize", "newPasswordRequired");
}
// Change password
function requestChangePassword(oldPw, newPw)
{
function requestChangePassword(oldPw, newPw) {
sendToHyperion("authorize", "newPassword", '"password": "' + oldPw + '", "newPassword":"' + newPw + '"');
}
function requestAuthorization(password)
{
function requestAuthorization(password) {
sendToHyperion("authorize", "login", '"password": "' + password + '"');
}
function requestTokenAuthorization(token)
{
function requestTokenAuthorization(token) {
sendToHyperion("authorize", "login", '"token": "' + token + '"');
}
function requestToken(comment)
{
function requestToken(comment) {
sendToHyperion("authorize", "createToken", '"comment": "' + comment + '"');
}
function requestTokenInfo()
{
function requestTokenInfo() {
sendToHyperion("authorize", "getTokenList", "");
}
@ -271,115 +248,94 @@ function requestGetPendingTokenRequests (id, state) {
sendToHyperion("authorize", "getPendingTokenRequests", "");
}
function requestHandleTokenRequest(id, state)
{
function requestHandleTokenRequest(id, state) {
sendToHyperion("authorize", "answerRequest", '"id":"' + id + '", "accept":' + state);
}
function requestTokenDelete(id)
{
function requestTokenDelete(id) {
sendToHyperion("authorize", "deleteToken", '"id":"' + id + '"');
}
function requestInstanceRename(inst, name)
{
function requestInstanceRename(inst, name) {
sendToHyperion("instance", "saveName", '"instance": ' + inst + ', "name": "' + name + '"');
}
function requestInstanceStartStop(inst, start)
{
function requestInstanceStartStop(inst, start) {
if (start)
sendToHyperion("instance", "startInstance", '"instance": ' + inst);
else
sendToHyperion("instance", "stopInstance", '"instance": ' + inst);
}
function requestInstanceDelete(inst)
{
function requestInstanceDelete(inst) {
sendToHyperion("instance", "deleteInstance", '"instance": ' + inst);
}
function requestInstanceCreate(name)
{
function requestInstanceCreate(name) {
sendToHyperion("instance", "createInstance", '"name": "' + name + '"');
}
function requestInstanceSwitch(inst)
{
function requestInstanceSwitch(inst) {
sendToHyperion("instance", "switchTo", '"instance": ' + inst);
}
function requestServerInfo()
{
function requestServerInfo() {
sendToHyperion("serverinfo", "", '"subscribe":["components-update", "priorities-update", "imageToLedMapping-update", "adjustment-update", "videomode-update", "effects-update", "settings-update", "instance-update"]');
}
function requestSysInfo()
{
function requestSysInfo() {
sendToHyperion("sysinfo");
}
function requestSystemSuspend()
{
function requestSystemSuspend() {
sendToHyperion("system", "suspend");
}
function requestSystemResume()
{
function requestSystemResume() {
sendToHyperion("system", "resume");
}
function requestSystemRestart()
{
function requestSystemRestart() {
sendToHyperion("system", "restart");
}
function requestServerConfigSchema()
{
function requestServerConfigSchema() {
sendToHyperion("config", "getschema");
}
function requestServerConfig()
{
function requestServerConfig() {
sendToHyperion("config", "getconfig");
}
function requestServerConfigOld()
{
function requestServerConfigOld() {
sendToHyperion("config", "getconfig-old");
}
function requestServerConfigReload()
{
function requestServerConfigReload() {
sendToHyperion("config", "reload");
}
function requestLedColorsStart()
{
function requestLedColorsStart() {
window.ledStreamActive = true;
sendToHyperion("ledcolors", "ledstream-start");
}
function requestLedColorsStop()
{
function requestLedColorsStop() {
window.ledStreamActive = false;
sendToHyperion("ledcolors", "ledstream-stop");
}
function requestLedImageStart()
{
function requestLedImageStart() {
window.imageStreamActive = true;
sendToHyperion("ledcolors", "imagestream-start");
}
function requestLedImageStop()
{
function requestLedImageStop() {
window.imageStreamActive = false;
sendToHyperion("ledcolors", "imagestream-stop");
}
function requestPriorityClear(prio)
{
function requestPriorityClear(prio) {
if (typeof prio !== 'number')
prio = window.webPrio;
@ -387,123 +343,145 @@ function requestPriorityClear(prio)
sendToHyperion("clear", "", '"priority":' + prio + '');
}
function requestClearAll()
{
function requestClearAll() {
$(window.hyperion).trigger({ type: "stopBrowerScreenCapture" });
requestPriorityClear(-1)
}
function requestPlayEffect(effectName, duration)
{
function requestPlayEffect(effectName, duration) {
$(window.hyperion).trigger({ type: "stopBrowerScreenCapture" });
sendToHyperion("effect", "", '"effect":{"name":"' + effectName + '"},"priority":' + window.webPrio + ',"duration":' + validateDuration(duration) + ',"origin":"' + window.webOrigin + '"');
}
function requestSetColor(r,g,b,duration)
{
function requestSetColor(r, g, b, duration) {
$(window.hyperion).trigger({ type: "stopBrowerScreenCapture" });
sendToHyperion("color", "", '"color":[' + r + ',' + g + ',' + b + '], "priority":' + window.webPrio + ',"duration":' + validateDuration(duration) + ',"origin":"' + window.webOrigin + '"');
}
function requestSetImage(data,duration,name)
{
function requestSetImage(data, duration, name) {
sendToHyperion("image", "", '"imagedata":"' + data + '", "priority":' + window.webPrio + ',"duration":' + validateDuration(duration) + ', "format":"auto", "origin":"' + window.webOrigin + '", "name":"' + name + '"');
}
function requestSetComponentState(comp, state)
{
function requestSetComponentState(comp, state) {
var state_str = state ? "true" : "false";
sendToHyperion("componentstate", "", '"componentstate":{"component":"' + comp + '","state":' + state_str + '}');
}
function requestSetSource(prio)
{
function requestSetSource(prio) {
if (prio == "auto")
sendToHyperion("sourceselect", "", '"auto":true');
else
sendToHyperion("sourceselect", "", '"priority":' + prio);
}
function requestWriteConfig(config, full)
{
if(full === true)
window.serverConfig = config;
else
{
jQuery.each(config, function(i, val) {
window.serverConfig[i] = val;
});
// Function to transform the legacy config into thee new API format
function transformConfig(configInput, instanceId = 0) {
const globalConfig = {};
const instanceSettings = {};
// Populate globalConfig and instanceSettings based on the specified properties
for (const [key, value] of Object.entries(configInput)) {
if (window.schema.propertiesTypes.globalProperties.includes(key)) {
globalConfig[key] = value;
} else if (window.schema.propertiesTypes.instanceProperties.includes(key)) {
instanceSettings[key] = value;
}
}
sendToHyperion("config","setconfig", '"config":'+JSON.stringify(window.serverConfig));
// Initialize the final transformed configuration
const transformedConfig = {};
// Add `global` only if it has properties
if (Object.keys(globalConfig).length > 0) {
transformedConfig.global = { settings: globalConfig };
}
// Add `instance` only if there are instance settings
if (Object.keys(instanceSettings).length > 0) {
transformedConfig.instances = [
{
id: instanceId,
settings: instanceSettings
}
];
}
return transformedConfig;
}
function requestWriteConfig(singleInstanceConfig, full) {
let newConfig = "";
const instance = Number(window.currentHyperionInstance);
if (full === true) {
window.serverConfig = singleInstanceConfig;
newConfig = transformConfig(window.serverConfig, instance);
}
else {
jQuery.each(singleInstanceConfig, function (i, val) {
window.serverConfig[i] = val;
});
newConfig = transformConfig(singleInstanceConfig, instance);
}
sendToHyperion("config", "setconfig", '"config":' + JSON.stringify(newConfig));
}
function requestRestoreConfig(config) {
sendToHyperion("config", "restoreconfig", '"config":' + JSON.stringify(config));
}
function requestWriteEffect(effectName,effectPy,effectArgs,data)
{
function requestWriteEffect(effectName, effectPy, effectArgs, data) {
var cutArgs = effectArgs.slice(1, -1);
sendToHyperion("create-effect", "", '"name":"' + effectName + '", "script":"' + effectPy + '", ' + cutArgs + ',"imageData":"' + data + '"');
}
function requestTestEffect(effectName,effectPy,effectArgs,data)
{
function requestTestEffect(effectName, effectPy, effectArgs, data) {
sendToHyperion("effect", "", '"effect":{"name":"' + effectName + '", "args":' + effectArgs + '}, "priority":' + window.webPrio + ', "origin":"' + window.webOrigin + '", "pythonScript":"' + effectPy + '", "imageData":"' + data + '"');
}
function requestDeleteEffect(effectName)
{
function requestDeleteEffect(effectName) {
sendToHyperion("delete-effect", "", '"name":"' + effectName + '"');
}
function requestLoggingStart()
{
function requestLoggingStart() {
window.loggingStreamActive = true;
sendToHyperion("logging", "start");
}
function requestLoggingStop()
{
function requestLoggingStop() {
window.loggingStreamActive = false;
sendToHyperion("logging", "stop");
}
function requestMappingType(type)
{
function requestMappingType(type) {
sendToHyperion("processing", "", '"mappingType": "' + type + '"');
}
function requestVideoMode(newMode)
{
function requestVideoMode(newMode) {
sendToHyperion("videomode", "", '"videoMode": "' + newMode + '"');
}
function requestAdjustment(type, value, complete)
{
function requestAdjustment(type, value, complete) {
if (complete === true)
sendToHyperion("adjustment", "", '"adjustment": ' + type + '');
else
sendToHyperion("adjustment", "", '"adjustment": {"' + type + '": ' + value + '}');
}
async function requestLedDeviceDiscovery(type, params)
{
async function requestLedDeviceDiscovery(type, params) {
let data = { ledDeviceType: type, params: params };
return sendAsyncToHyperion("leddevice", "discover", data);
}
async function requestLedDeviceProperties(type, params)
{
async function requestLedDeviceProperties(type, params) {
let data = { ledDeviceType: type, params: params };
return sendAsyncToHyperion("leddevice", "getProperties", data);
}
function requestLedDeviceIdentification(type, params)
{
function requestLedDeviceIdentification(type, params) {
let data = { ledDeviceType: type, params: params };
return sendAsyncToHyperion("leddevice", "identify", data);

View File

@ -43,9 +43,7 @@
},
"config": {
"required": false,
"$ref": "schema-settings-full-relaxed.json",
"required": false,
"$ref": "schema-settings-ui.json"
"$ref": "schema-settings-full-relaxed.json"
}
},
"additionalProperties": false

View File

@ -736,8 +736,12 @@ void JsonAPI::handleConfigSetCommand(const QJsonObject &message, const JsonApiCo
}
QJsonObject config = message["config"].toObject();
if (config.contains("global") || config.contains("instances"))
if (config.isEmpty())
{
sendErrorReply("Update configuration failed", {"No configuration data provided!"}, cmd);
return;
}
QStringList errorDetails;
QMap<quint8, QJsonObject> instancesNewConfigs;
@ -790,36 +794,6 @@ void JsonAPI::handleConfigSetCommand(const QJsonObject &message, const JsonApiCo
}
sendSuccessReply(cmd);
return;
}
if (config.isEmpty())
{
sendErrorReply("Update configuration failed", {"No configuration data provided!"}, cmd);
return;
}
//Backward compatability until UI mesages are updated
if (API::isHyperionEnabled())
{
QStringList errorDetails;
QPair<bool, QStringList> isSaved = _hyperion->saveSettings(config);
errorDetails.append(isSaved.second);
if (!errorDetails.isEmpty())
{
sendErrorReply("Save settings failed", errorDetails, cmd);
return;
}
sendSuccessReply(cmd);
}
else
{
sendErrorReply("Updating the configuration while Hyperion is disabled is not possible", cmd);
}
}
void JsonAPI::handleConfigGetCommand(const QJsonObject &message, const JsonApiCommand& cmd)
@ -943,6 +917,21 @@ void JsonAPI::handleSchemaGetCommand(const QJsonObject& /*message*/, const JsonA
alldevices = LedDeviceWrapper::getLedDeviceSchemas();
properties.insert("alldevices", alldevices);
// Add infor about the type of setting elements
QJsonObject settingTypes;
QJsonArray globalSettingTypes;
for (const QString &type : SettingsTable().getGlobalSettingTypes()) {
globalSettingTypes.append(type);
}
settingTypes.insert("globalProperties", globalSettingTypes);
QJsonArray instanceSettingTypes;
for (const QString &type : SettingsTable().getInstanceSettingTypes()) {
instanceSettingTypes.append(type);
}
settingTypes.insert("instanceProperties", instanceSettingTypes);
properties.insert("propertiesTypes", settingTypes);
#if defined(ENABLE_EFFECTENGINE)
// collect all available effect schemas
QJsonArray schemaList;