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,35 +34,29 @@ tokenList = {};
const ENDLESS = -1; const ENDLESS = -1;
function initRestart() function initRestart() {
{
$(window.hyperion).off(); $(window.hyperion).off();
window.watchdog = 10; window.watchdog = 10;
connectionLostDetection('restart'); connectionLostDetection('restart');
} }
function connectionLostDetection(type) function connectionLostDetection(type) {
{ if (window.watchdog > 2) {
if ( window.watchdog > 2 ) var interval_id = window.setInterval(function () { clearInterval(interval_id); }, 9999); // Get a reference to the last
{
var interval_id = window.setInterval(function(){clearInterval(interval_id);}, 9999); // Get a reference to the last
for (var i = 1; i < interval_id; i++) for (var i = 1; i < interval_id; i++)
window.clearInterval(i); window.clearInterval(i);
if(type == 'restart') if (type == 'restart') {
{
$("body").html($("#container_restart").html()); $("body").html($("#container_restart").html());
// setTimeout delay for probably slower systems, some browser don't execute THIS action // setTimeout delay for probably slower systems, some browser don't execute THIS action
setTimeout(restartAction,250); setTimeout(restartAction, 250);
} }
else else {
{
$("body").html($("#container_connection_lost").html()); $("body").html($("#container_connection_lost").html());
connectionLostAction(); connectionLostAction();
} }
} }
else else {
{ $.get("/cgi/cfg_jsonserver", function () { window.watchdog = 0 }).fail(function () { window.watchdog++; });
$.get( "/cgi/cfg_jsonserver", function() {window.watchdog=0}).fail(function() {window.watchdog++;});
} }
} }
@ -70,25 +64,22 @@ setInterval(connectionLostDetection, 3000);
// init websocket to hyperion and bind socket events to jquery events of $(hyperion) object // init websocket to hyperion and bind socket events to jquery events of $(hyperion) object
function initWebSocket() function initWebSocket() {
{ if ("WebSocket" in window) {
if ("WebSocket" in window) if (window.websocket == null) {
{
if (window.websocket == null)
{
window.jsonPort = ''; window.jsonPort = '';
if(document.location.port == '' && document.location.protocol == "http:") if (document.location.port == '' && document.location.protocol == "http:")
window.jsonPort = '80'; window.jsonPort = '80';
else if (document.location.port == '' && document.location.protocol == "https:") else if (document.location.port == '' && document.location.protocol == "https:")
window.jsonPort = '443'; window.jsonPort = '443';
else else
window.jsonPort = document.location.port; window.jsonPort = document.location.port;
window.websocket = (document.location.protocol == "https:") ? new WebSocket('wss://'+document.location.hostname+":"+window.jsonPort) : new WebSocket('ws://'+document.location.hostname+":"+window.jsonPort); window.websocket = (document.location.protocol == "https:") ? new WebSocket('wss://' + document.location.hostname + ":" + window.jsonPort) : new WebSocket('ws://' + document.location.hostname + ":" + window.jsonPort);
window.websocket.onopen = function (event) { window.websocket.onopen = function (event) {
$(window.hyperion).trigger({type:"open"}); $(window.hyperion).trigger({ type: "open" });
$(window.hyperion).on("cmd-serverinfo", function(event) { $(window.hyperion).on("cmd-serverinfo", function (event) {
window.watchdog = 0; window.watchdog = 0;
}); });
}; };
@ -96,8 +87,7 @@ function initWebSocket()
window.websocket.onclose = function (event) { window.websocket.onclose = function (event) {
// See http://tools.ietf.org/html/rfc6455#section-7.4.1 // See http://tools.ietf.org/html/rfc6455#section-7.4.1
var reason; 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 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 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; case 1002: reason = "An endpoint is terminating the connection due to a protocol error"; break;
@ -113,72 +103,66 @@ function initWebSocket()
case 1015: reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified)."; break; case 1015: reason = "The connection was closed due to a failure to perform a TLS handshake (e.g., the server certificate can't be verified)."; break;
default: reason = "Unknown reason"; default: reason = "Unknown reason";
} }
$(window.hyperion).trigger({type:"close", reason:reason}); $(window.hyperion).trigger({ type: "close", reason: reason });
window.watchdog = 10; window.watchdog = 10;
connectionLostDetection(); connectionLostDetection();
}; };
window.websocket.onmessage = function (event) { window.websocket.onmessage = function (event) {
try try {
{
var response = JSON.parse(event.data); var response = JSON.parse(event.data);
var success = response.success; var success = response.success;
var cmd = response.command; var cmd = response.command;
var tan = response.tan var tan = response.tan
if (success || typeof(success) == "undefined") if (success || typeof (success) == "undefined") {
{ $(window.hyperion).trigger({ type: "cmd-" + cmd, response: response });
$(window.hyperion).trigger({type:"cmd-"+cmd, response:response});
} }
else else {
{ // skip tan -1 error handling
// skip tan -1 error handling if (tan != -1) {
if(tan != -1){ var error = response.hasOwnProperty("error") ? response.error : "unknown";
var error = response.hasOwnProperty("error")? response.error : "unknown"; if (error == "Service Unavailable") {
if (error == "Service Unavailable") { window.location.reload();
window.location.reload(); } else {
} else { $(window.hyperion).trigger({ type: "error", reason: error });
$(window.hyperion).trigger({type:"error", reason:error});
}
let errorData = response.hasOwnProperty("errorData")? response.errorData : "";
console.log("[window.websocket::onmessage] ",error, ", Description:", errorData);
} }
let errorData = response.hasOwnProperty("errorData") ? response.errorData : "";
console.log("[window.websocket::onmessage] ", error, ", Description:", errorData);
}
} }
} }
catch(exception_error) catch (exception_error) {
{ $(window.hyperion).trigger({ type: "error", reason: exception_error });
$(window.hyperion).trigger({type:"error",reason:exception_error}); console.log("[window.websocket::onmessage] ", exception_error)
console.log("[window.websocket::onmessage] ",exception_error)
} }
}; };
window.websocket.onerror = function (error) { window.websocket.onerror = function (error) {
$(window.hyperion).trigger({type:"error",reason:error}); $(window.hyperion).trigger({ type: "error", reason: error });
console.log("[window.websocket::onerror] ",error) console.log("[window.websocket::onerror] ", error)
}; };
} }
} }
else else {
{
$(window.hyperion).trigger("error"); $(window.hyperion).trigger("error");
alert("Websocket is not supported by your browser"); alert("Websocket is not supported by your browser");
return; return;
} }
} }
function sendToHyperion(command, subcommand, msg) function sendToHyperion(command, subcommand, msg) {
{
if (typeof subcommand != 'undefined' && subcommand.length > 0) if (typeof subcommand != 'undefined' && subcommand.length > 0)
subcommand = ',"subcommand":"'+subcommand+'"'; subcommand = ',"subcommand":"' + subcommand + '"';
else else
subcommand = ""; subcommand = "";
if (typeof msg != 'undefined' && msg.length > 0) if (typeof msg != 'undefined' && msg.length > 0)
msg = ","+msg; msg = "," + msg;
else else
msg = ""; msg = "";
window.wsTan = Math.floor(Math.random() * 1000) window.wsTan = Math.floor(Math.random() * 1000)
window.websocket.send('{"command":"'+command+'", "tan":'+window.wsTan+subcommand+msg+'}'); window.websocket.send('{"command":"' + command + '", "tan":' + window.wsTan + subcommand + msg + '}');
} }
// Send a json message to Hyperion and wait for a matching response // Send a json message to Hyperion and wait for a matching response
@ -188,9 +172,9 @@ function sendToHyperion(command, subcommand, msg)
// data: The json data as Object // data: The json data as Object
// tan: The optional tan, default 1. If the tan is -1, we skip global response error handling // tan: The optional tan, default 1. If the tan is -1, we skip global response error handling
// Returns data of response or false if timeout // Returns data of response or false if timeout
async function sendAsyncToHyperion (command, subcommand, data, tan = Math.floor(Math.random() * 1000) ) { async function sendAsyncToHyperion(command, subcommand, data, tan = Math.floor(Math.random() * 1000)) {
let obj = { command, tan } let obj = { command, tan }
if (subcommand) {Object.assign(obj, {subcommand})} if (subcommand) { Object.assign(obj, { subcommand }) }
if (data) { Object.assign(obj, data) } if (data) { Object.assign(obj, data) }
//if (process.env.DEV || sstore.getters['common/getDebugState']) console.log('SENDAS', obj) //if (process.env.DEV || sstore.getters['common/getDebugState']) console.log('SENDAS', obj)
@ -200,7 +184,7 @@ async function sendAsyncToHyperion (command, subcommand, data, tan = Math.floor(
// Send a json message to Hyperion and wait for a matching response // Send a json message to Hyperion and wait for a matching response
// A response matches, when command(+subcommand) of request and response is the same // A response matches, when command(+subcommand) of request and response is the same
// Returns data of response or false if timeout // Returns data of response or false if timeout
async function __sendAsync (data) { async function __sendAsync(data) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
let cmd = data.command let cmd = data.command
let subc = data.subcommand let subc = data.subcommand
@ -213,7 +197,7 @@ async function __sendAsync (data) {
try { try {
rdata = JSON.parse(e.data) rdata = JSON.parse(e.data)
} catch (error) { } catch (error) {
console.error("[window.websocket::onmessage] ",error) console.error("[window.websocket::onmessage] ", error)
resolve(false) resolve(false)
} }
if (rdata.command == cmd && rdata.tan == tan) { if (rdata.command == cmd && rdata.tan == tan) {
@ -232,279 +216,273 @@ async function __sendAsync (data) {
// wrapped server commands // wrapped server commands
// Test if admin requires authentication // Test if admin requires authentication
function requestRequiresAdminAuth() function requestRequiresAdminAuth() {
{ sendToHyperion("authorize", "adminRequired");
sendToHyperion("authorize","adminRequired");
} }
// Test if the default password needs to be changed // Test if the default password needs to be changed
function requestRequiresDefaultPasswortChange() function requestRequiresDefaultPasswortChange() {
{ sendToHyperion("authorize", "newPasswordRequired");
sendToHyperion("authorize","newPasswordRequired");
} }
// Change password // Change password
function requestChangePassword(oldPw, newPw) function requestChangePassword(oldPw, newPw) {
{ sendToHyperion("authorize", "newPassword", '"password": "' + oldPw + '", "newPassword":"' + newPw + '"');
sendToHyperion("authorize","newPassword",'"password": "'+oldPw+'", "newPassword":"'+newPw+'"');
} }
function requestAuthorization(password) function requestAuthorization(password) {
{ sendToHyperion("authorize", "login", '"password": "' + password + '"');
sendToHyperion("authorize","login",'"password": "' + password + '"');
} }
function requestTokenAuthorization(token) function requestTokenAuthorization(token) {
{ sendToHyperion("authorize", "login", '"token": "' + token + '"');
sendToHyperion("authorize","login",'"token": "' + token + '"');
} }
function requestToken(comment) function requestToken(comment) {
{ sendToHyperion("authorize", "createToken", '"comment": "' + comment + '"');
sendToHyperion("authorize","createToken",'"comment": "'+comment+'"');
} }
function requestTokenInfo() function requestTokenInfo() {
{ sendToHyperion("authorize", "getTokenList", "");
sendToHyperion("authorize","getTokenList","");
} }
function requestGetPendingTokenRequests (id, state) { function requestGetPendingTokenRequests(id, state) {
sendToHyperion("authorize", "getPendingTokenRequests", ""); sendToHyperion("authorize", "getPendingTokenRequests", "");
} }
function requestHandleTokenRequest(id, state) function requestHandleTokenRequest(id, state) {
{ sendToHyperion("authorize", "answerRequest", '"id":"' + id + '", "accept":' + state);
sendToHyperion("authorize","answerRequest",'"id":"'+id+'", "accept":'+state);
} }
function requestTokenDelete(id) function requestTokenDelete(id) {
{ sendToHyperion("authorize", "deleteToken", '"id":"' + id + '"');
sendToHyperion("authorize","deleteToken",'"id":"'+id+'"');
} }
function requestInstanceRename(inst, name) function requestInstanceRename(inst, name) {
{ sendToHyperion("instance", "saveName", '"instance": ' + inst + ', "name": "' + name + '"');
sendToHyperion("instance", "saveName",'"instance": '+inst+', "name": "'+name+'"');
} }
function requestInstanceStartStop(inst, start) function requestInstanceStartStop(inst, start) {
{ if (start)
if(start) sendToHyperion("instance", "startInstance", '"instance": ' + inst);
sendToHyperion("instance","startInstance",'"instance": '+inst);
else else
sendToHyperion("instance","stopInstance",'"instance": '+inst); sendToHyperion("instance", "stopInstance", '"instance": ' + inst);
} }
function requestInstanceDelete(inst) function requestInstanceDelete(inst) {
{ sendToHyperion("instance", "deleteInstance", '"instance": ' + inst);
sendToHyperion("instance","deleteInstance",'"instance": '+inst);
} }
function requestInstanceCreate(name) function requestInstanceCreate(name) {
{ sendToHyperion("instance", "createInstance", '"name": "' + name + '"');
sendToHyperion("instance","createInstance",'"name": "'+name+'"');
} }
function requestInstanceSwitch(inst) function requestInstanceSwitch(inst) {
{ sendToHyperion("instance", "switchTo", '"instance": ' + 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"]');
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"); sendToHyperion("sysinfo");
} }
function requestSystemSuspend() function requestSystemSuspend() {
{ sendToHyperion("system", "suspend");
sendToHyperion("system","suspend");
} }
function requestSystemResume() function requestSystemResume() {
{ sendToHyperion("system", "resume");
sendToHyperion("system","resume");
} }
function requestSystemRestart() function requestSystemRestart() {
{ sendToHyperion("system", "restart");
sendToHyperion("system","restart");
} }
function requestServerConfigSchema() function requestServerConfigSchema() {
{ sendToHyperion("config", "getschema");
sendToHyperion("config","getschema");
} }
function requestServerConfig() function requestServerConfig() {
{
sendToHyperion("config", "getconfig"); sendToHyperion("config", "getconfig");
} }
function requestServerConfigOld() function requestServerConfigOld() {
{
sendToHyperion("config", "getconfig-old"); sendToHyperion("config", "getconfig-old");
} }
function requestServerConfigReload() function requestServerConfigReload() {
{
sendToHyperion("config", "reload"); sendToHyperion("config", "reload");
} }
function requestLedColorsStart() function requestLedColorsStart() {
{ window.ledStreamActive = true;
window.ledStreamActive=true;
sendToHyperion("ledcolors", "ledstream-start"); sendToHyperion("ledcolors", "ledstream-start");
} }
function requestLedColorsStop() function requestLedColorsStop() {
{ window.ledStreamActive = false;
window.ledStreamActive=false;
sendToHyperion("ledcolors", "ledstream-stop"); sendToHyperion("ledcolors", "ledstream-stop");
} }
function requestLedImageStart() function requestLedImageStart() {
{ window.imageStreamActive = true;
window.imageStreamActive=true;
sendToHyperion("ledcolors", "imagestream-start"); sendToHyperion("ledcolors", "imagestream-start");
} }
function requestLedImageStop() function requestLedImageStop() {
{ window.imageStreamActive = false;
window.imageStreamActive=false;
sendToHyperion("ledcolors", "imagestream-stop"); sendToHyperion("ledcolors", "imagestream-stop");
} }
function requestPriorityClear(prio) function requestPriorityClear(prio) {
{ if (typeof prio !== 'number')
if(typeof prio !== 'number')
prio = window.webPrio; prio = window.webPrio;
$(window.hyperion).trigger({type:"stopBrowerScreenCapture"}); $(window.hyperion).trigger({ type: "stopBrowerScreenCapture" });
sendToHyperion("clear", "", '"priority":'+prio+''); sendToHyperion("clear", "", '"priority":' + prio + '');
} }
function requestClearAll() function requestClearAll() {
{ $(window.hyperion).trigger({ type: "stopBrowerScreenCapture" });
$(window.hyperion).trigger({type:"stopBrowerScreenCapture"});
requestPriorityClear(-1) requestPriorityClear(-1)
} }
function requestPlayEffect(effectName, duration) function requestPlayEffect(effectName, duration) {
{ $(window.hyperion).trigger({ type: "stopBrowerScreenCapture" });
$(window.hyperion).trigger({type:"stopBrowerScreenCapture"}); sendToHyperion("effect", "", '"effect":{"name":"' + effectName + '"},"priority":' + window.webPrio + ',"duration":' + validateDuration(duration) + ',"origin":"' + window.webOrigin + '"');
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" });
$(window.hyperion).trigger({type:"stopBrowerScreenCapture"}); sendToHyperion("color", "", '"color":[' + r + ',' + g + ',' + b + '], "priority":' + window.webPrio + ',"duration":' + validateDuration(duration) + ',"origin":"' + window.webOrigin + '"');
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 + '"');
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"; var state_str = state ? "true" : "false";
sendToHyperion("componentstate", "", '"componentstate":{"component":"'+comp+'","state":'+state_str+'}'); sendToHyperion("componentstate", "", '"componentstate":{"component":"' + comp + '","state":' + state_str + '}');
} }
function requestSetSource(prio) function requestSetSource(prio) {
{ if (prio == "auto")
if ( prio == "auto" )
sendToHyperion("sourceselect", "", '"auto":true'); sendToHyperion("sourceselect", "", '"auto":true');
else else
sendToHyperion("sourceselect", "", '"priority":'+prio); sendToHyperion("sourceselect", "", '"priority":' + prio);
} }
function requestWriteConfig(config, full) // Function to transform the legacy config into thee new API format
{ function transformConfig(configInput, instanceId = 0) {
if(full === true) const globalConfig = {};
window.serverConfig = config; const instanceSettings = {};
else
{ // Populate globalConfig and instanceSettings based on the specified properties
jQuery.each(config, function(i, val) { for (const [key, value] of Object.entries(configInput)) {
window.serverConfig[i] = val; 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) { function requestRestoreConfig(config) {
sendToHyperion("config", "restoreconfig", '"config":' + JSON.stringify(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); var cutArgs = effectArgs.slice(1, -1);
sendToHyperion("create-effect", "", '"name":"'+effectName+'", "script":"'+effectPy+'", '+cutArgs+',"imageData":"'+data+'"'); 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 + '"');
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 + '"');
sendToHyperion("delete-effect", "", '"name":"'+effectName+'"');
} }
function requestLoggingStart() function requestLoggingStart() {
{ window.loggingStreamActive = true;
window.loggingStreamActive=true;
sendToHyperion("logging", "start"); sendToHyperion("logging", "start");
} }
function requestLoggingStop() function requestLoggingStop() {
{ window.loggingStreamActive = false;
window.loggingStreamActive=false;
sendToHyperion("logging", "stop"); sendToHyperion("logging", "stop");
} }
function requestMappingType(type) function requestMappingType(type) {
{ sendToHyperion("processing", "", '"mappingType": "' + type + '"');
sendToHyperion("processing", "", '"mappingType": "'+type+'"');
} }
function requestVideoMode(newMode) function requestVideoMode(newMode) {
{ sendToHyperion("videomode", "", '"videoMode": "' + newMode + '"');
sendToHyperion("videomode", "", '"videoMode": "'+newMode+'"');
} }
function requestAdjustment(type, value, complete) function requestAdjustment(type, value, complete) {
{ if (complete === true)
if(complete === true) sendToHyperion("adjustment", "", '"adjustment": ' + type + '');
sendToHyperion("adjustment", "", '"adjustment": '+type+'');
else else
sendToHyperion("adjustment", "", '"adjustment": {"'+type+'": '+value+'}'); sendToHyperion("adjustment", "", '"adjustment": {"' + type + '": ' + value + '}');
} }
async function requestLedDeviceDiscovery(type, params) async function requestLedDeviceDiscovery(type, params) {
{
let data = { ledDeviceType: type, params: params }; let data = { ledDeviceType: type, params: params };
return sendAsyncToHyperion("leddevice", "discover", data); return sendAsyncToHyperion("leddevice", "discover", data);
} }
async function requestLedDeviceProperties(type, params) async function requestLedDeviceProperties(type, params) {
{
let data = { ledDeviceType: type, params: params }; let data = { ledDeviceType: type, params: params };
return sendAsyncToHyperion("leddevice", "getProperties", data); return sendAsyncToHyperion("leddevice", "getProperties", data);
} }
function requestLedDeviceIdentification(type, params) function requestLedDeviceIdentification(type, params) {
{ let data = { ledDeviceType: type, params: params };
let data = { ledDeviceType: type, params: params };
return sendAsyncToHyperion("leddevice", "identify", data); return sendAsyncToHyperion("leddevice", "identify", data);
} }
@ -528,9 +506,9 @@ async function requestServiceDiscovery(type, params) {
} }
async function requestConfig(globalTypes, instances, instanceTypes) { async function requestConfig(globalTypes, instances, instanceTypes) {
let globalFilter = { "global": { "types": globalTypes } }; let globalFilter = { "global": { "types": globalTypes } };
let instanceFilter = { "instances": { "ids": instances, "types": instanceTypes } }; let instanceFilter = { "instances": { "ids": instances, "types": instanceTypes } };
let filter = { "configFilter" : { globalFilter, instanceFilter} }; let filter = { "configFilter": { globalFilter, instanceFilter } };
return sendAsyncToHyperion("config", "getconfig", filter); return sendAsyncToHyperion("config", "getconfig", filter);
} }

View File

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

View File

@ -736,90 +736,64 @@ void JsonAPI::handleConfigSetCommand(const QJsonObject &message, const JsonApiCo
} }
QJsonObject config = message["config"].toObject(); QJsonObject config = message["config"].toObject();
if (config.contains("global") || config.contains("instances"))
{
QStringList errorDetails;
QMap<quint8, QJsonObject> instancesNewConfigs;
const QJsonArray instances = config["instances"].toArray();
if (!instances.isEmpty())
{
QList<quint8> configuredInstanceIds = _instanceManager->getInstanceIds();
for (const auto &instance : instances)
{
QJsonObject instanceObject = instance.toObject();
const QJsonValue idx = instanceObject["id"];
if (idx.isDouble())
{
quint8 instanceId = static_cast<quint8>(idx.toInt());
if (configuredInstanceIds.contains(instanceId))
{
instancesNewConfigs.insert(instanceId,instanceObject.value("settings").toObject());
}
else
{
errorDetails.append(QString("Given instance id '%1' does not exist. Configuration item will be ignored").arg(instanceId));
}
}
}
}
const QJsonObject globalSettings = config["global"].toObject().value("settings").toObject();
if (!globalSettings.isEmpty())
{
const QJsonObject instanceZeroConfig = instancesNewConfigs.value(0);
instancesNewConfigs.insert(0, JsonUtils::mergeJsonObjects(instanceZeroConfig, globalSettings));
}
QMapIterator<quint8, QJsonObject> i (instancesNewConfigs);
while (i.hasNext()) {
i.next();
quint8 idx = i.key();
Hyperion* instance = HyperionIManager::getInstance()->getHyperionInstance(idx);
QPair<bool, QStringList> isSaved = instance->saveSettings(i.value());
errorDetails.append(isSaved.second);
}
if (!errorDetails.isEmpty())
{
sendErrorReply("Update configuration failed", errorDetails, cmd);
return;
}
sendSuccessReply(cmd);
return;
}
if (config.isEmpty()) if (config.isEmpty())
{ {
sendErrorReply("Update configuration failed", {"No configuration data provided!"}, cmd); sendErrorReply("Update configuration failed", {"No configuration data provided!"}, cmd);
return; return;
} }
//Backward compatability until UI mesages are updated QStringList errorDetails;
if (API::isHyperionEnabled())
QMap<quint8, QJsonObject> instancesNewConfigs;
const QJsonArray instances = config["instances"].toArray();
if (!instances.isEmpty())
{ {
QStringList errorDetails; QList<quint8> configuredInstanceIds = _instanceManager->getInstanceIds();
for (const auto &instance : instances)
QPair<bool, QStringList> isSaved = _hyperion->saveSettings(config);
errorDetails.append(isSaved.second);
if (!errorDetails.isEmpty())
{ {
sendErrorReply("Save settings failed", errorDetails, cmd); QJsonObject instanceObject = instance.toObject();
return; const QJsonValue idx = instanceObject["id"];
if (idx.isDouble())
{
quint8 instanceId = static_cast<quint8>(idx.toInt());
if (configuredInstanceIds.contains(instanceId))
{
instancesNewConfigs.insert(instanceId,instanceObject.value("settings").toObject());
}
else
{
errorDetails.append(QString("Given instance id '%1' does not exist. Configuration item will be ignored").arg(instanceId));
}
}
} }
}
sendSuccessReply(cmd); const QJsonObject globalSettings = config["global"].toObject().value("settings").toObject();
} if (!globalSettings.isEmpty())
else
{ {
sendErrorReply("Updating the configuration while Hyperion is disabled is not possible", cmd); const QJsonObject instanceZeroConfig = instancesNewConfigs.value(0);
instancesNewConfigs.insert(0, JsonUtils::mergeJsonObjects(instanceZeroConfig, globalSettings));
} }
QMapIterator<quint8, QJsonObject> i (instancesNewConfigs);
while (i.hasNext()) {
i.next();
quint8 idx = i.key();
Hyperion* instance = HyperionIManager::getInstance()->getHyperionInstance(idx);
QPair<bool, QStringList> isSaved = instance->saveSettings(i.value());
errorDetails.append(isSaved.second);
}
if (!errorDetails.isEmpty())
{
sendErrorReply("Update configuration failed", errorDetails, cmd);
return;
}
sendSuccessReply(cmd);
} }
void JsonAPI::handleConfigGetCommand(const QJsonObject &message, const JsonApiCommand& 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(); alldevices = LedDeviceWrapper::getLedDeviceSchemas();
properties.insert("alldevices", alldevices); 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) #if defined(ENABLE_EFFECTENGINE)
// collect all available effect schemas // collect all available effect schemas
QJsonArray schemaList; QJsonArray schemaList;