diff --git a/.github/config/codeql.yml b/.github/config/codeql.yml new file mode 100644 index 00000000..d1492f7c --- /dev/null +++ b/.github/config/codeql.yml @@ -0,0 +1,4 @@ +name: "CodeQL config" +paths-ignore: + - 'dependencies/external/' + - 'assets/webconfig/js/lib' diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 00000000..a2c530b1 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,76 @@ +name: "CodeQL" + +on: + push: + branches: [ "master" ] + pull_request: + branches: [ "master" ] + schedule: + - cron: "36 18 * * 4" + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + permissions: + actions: read + contents: read + security-events: write + + strategy: + fail-fast: false + matrix: + language: [ python, javascript, cpp ] + + steps: + - name: Checkout + uses: actions/checkout@v3 + with: + submodules: recursive + + - name: Install Packages (cpp) + if: ${{ matrix.language == 'cpp' }} + run: | + sudo apt-get update + sudo apt-get install --yes git cmake build-essential qtbase5-dev libqt5serialport5-dev libqt5sql5-sqlite libqt5svg5-dev libqt5x11extras5-dev libusb-1.0-0-dev python3-dev libcec-dev libxcb-image0-dev libxcb-util0-dev libxcb-shm0-dev libxcb-render0-dev libxcb-randr0-dev libxrandr-dev libxrender-dev libavahi-core-dev libavahi-compat-libdnssd-dev libturbojpeg0-dev libjpeg-dev libssl-dev + + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + queries: +security-and-quality + config-file: ./.github/config/codeql.yml + + - name: Autobuild + uses: github/codeql-action/autobuild@v2 + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 + with: + category: "/language:${{ matrix.language }}" + upload: False + output: sarif-results + + - name: Filter SARIF + uses: advanced-security/filter-sarif@v1 + with: + patterns: | + -**/dependencies/** + -**/moc_*.cpp + -**/libsrc/flatbufserver/hyperion_request_generated.h + -**/libsrc/protoserver/message.pb.cc + -**/libsrc/protoserver/message.pb.h + input: sarif-results/${{ matrix.language }}.sarif + output: sarif-results/${{ matrix.language }}.sarif + + - name: Upload SARIF + uses: github/codeql-action/upload-sarif@v2 + with: + sarif_file: sarif-results/${{ matrix.language }}.sarif + - name: Upload loc as a Build Artifact + uses: actions/upload-artifact@v2.2.0 + with: + name: sarif-results + path: sarif-results + retention-days: 1 + diff --git a/README.md b/README.md index 5afd7e7e..cf3f7d8b 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ [![Latest-Release](https://img.shields.io/github/v/release/hyperion-project/hyperion.ng?include_prereleases&label=Latest%20Release&logo=github&logoColor=white&color=0f83e7)](https://github.com/hyperion-project/hyperion.ng/releases) [![GitHub Actions](https://github.com/hyperion-project/hyperion.ng/workflows/Hyperion%20CI%20Build/badge.svg?branch=master)](https://github.com/hyperion-project/hyperion.ng/actions) -[![LGTM](https://img.shields.io/lgtm/grade/cpp/github/hyperion-project/hyperion.ng?label=Code%20Quality&logo=lgtm&logoColor=white&color=4bc51d)](https://lgtm.com/projects/g/hyperion-project/hyperion.ng/context:cpp) +[![CodeQL Analysis](https://github.com/hyperion-project/hyperion.ng/actions/workflows/codeql.yml/badge.svg)](https://github.com/hyperion-project/hyperion.ng/actions/workflows/codeql.yml) [![Forum](https://img.shields.io/website/https/hyperion-project.org.svg?label=Forum&down_color=red&down_message=offline&up_color=4bc51d&up_message=online&logo=homeadvisor&logoColor=white)](https://www.hyperion-project.org) [![Documentation](https://img.shields.io/website/https/docs.hyperion-project.org.svg?label=Documentation&down_color=red&down_message=offline&up_color=4bc51d&up_message=online&logo=read-the-docs)](https://docs.hyperion-project.org) [![Discord](https://img.shields.io/discord/785578322167463937?label=Discord&logo=discord&logoColor=white&color=4bc51d)](https://discord.gg/khkR8Vx3ff) diff --git a/assets/firmware/arduino/network_bridge/udpraw_serialadalight.py b/assets/firmware/arduino/network_bridge/udpraw_serialadalight.py old mode 100755 new mode 100644 index b46597a9..452f9dd7 --- a/assets/firmware/arduino/network_bridge/udpraw_serialadalight.py +++ b/assets/firmware/arduino/network_bridge/udpraw_serialadalight.py @@ -153,10 +153,9 @@ to this service over the network. srv = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) - srv.bind(('0.0.0.0', args.localport)) # lgtm [py/bind-socket-all-network-interfaces] + srv.bind(('0.0.0.0', args.localport)) try: - intentional_exit = False while True: try: while True: @@ -180,7 +179,7 @@ to this service over the network. # probably got disconnected break except KeyboardInterrupt: - intentional_exit = True + # intentional_exit raise except socket.error as msg: if args.develop: @@ -190,6 +189,7 @@ to this service over the network. ser_to_net.socket = None sys.stderr.write('Disconnected\n') except KeyboardInterrupt: + # do not handle exceptions pass sys.stderr.write('\n--- exit ---\n') diff --git a/assets/webconfig/js/ui_utils.js b/assets/webconfig/js/ui_utils.js index 74a27061..c20c5fc1 100644 --- a/assets/webconfig/js/ui_utils.js +++ b/assets/webconfig/js/ui_utils.js @@ -1,1340 +1,1340 @@ -var prevTag; - -function removeOverlay() { - $("#loading_overlay").removeClass("overlay"); -} - -function reload() { - location.reload(); -} - -function storageComp() { - if (typeof (Storage) !== "undefined") - return true; - return false; -} - -function getStorage(item) { - if (storageComp()) { - return localStorage.getItem(item); - } - return null; -} - -function setStorage(item, value) { - if (storageComp()) { - localStorage.setItem(item, value); - } -} - -function removeStorage(item) { - if (storageComp()) { - localStorage.removeItem(item); - } -} - -function debugMessage(msg) { - if (window.debugMessagesActive) { - console.log(msg); - } -} - -function validateDuration(d) { - if (typeof d === "undefined" || d < 0) - return ENDLESS; - else - return d *= 1000; -} - -function getHashtag() { - if (getStorage('lasthashtag') != null) - return getStorage('lasthashtag'); - else { - var tag = document.URL; - tag = tag.substr(tag.indexOf("#") + 1); - if (tag == "" || typeof tag === "undefined" || tag.startsWith("http")) - tag = "dashboard" - return tag; - } -} - -function loadContent(event, forceRefresh) { - var tag; - - var lastSelectedInstance = getStorage('lastSelectedInstance'); - - if (lastSelectedInstance && (lastSelectedInstance != window.currentHyperionInstance)) { - if (window.serverInfo.instance[lastSelectedInstance] && window.serverInfo.instance[lastSelectedInstance].running) { - instanceSwitch(lastSelectedInstance); - } else { - removeStorage('lastSelectedInstance'); - } - } - - if (typeof event != "undefined") { - tag = event.currentTarget.hash; - tag = tag.substr(tag.indexOf("#") + 1); - setStorage('lasthashtag', tag); - } - else - tag = getHashtag(); - - if (forceRefresh || prevTag != tag) { - prevTag = tag; - $("#page-content").off(); - $("#page-content").load("/content/" + tag + ".html", function (response, status, xhr) { - if (status == "error") { - tag = 'dashboard'; - console.log("Could not find page:", prevTag, ", Redirecting to:", tag); - setStorage('lasthashtag', tag); - - $("#page-content").load("/content/" + tag + ".html", function (response, status, xhr) { - if (status == "error") { - $("#page-content").html('

' + encode_utf8(tag) + '
' + $.i18n('info_404') + '

'); - removeOverlay(); - } - }); - } - updateUiOnInstance(window.currentHyperionInstance); - }); - } -} - -function getInstanceNameByIndex(index) { - var instData = window.serverInfo.instance - for (var key in instData) { - if (instData[key].instance == index) - return instData[key].friendly_name; - } - return "unknown" -} - -function updateHyperionInstanceListing() { - if (window.serverInfo.instance) { - var data = window.serverInfo.instance.filter(entry => entry.running); - $('#hyp_inst_listing').html(""); - for (var key in data) { - var currInstMarker = (data[key].instance == window.currentHyperionInstance) ? "component-on" : ""; - - var html = '
  • \ - \ -
    \ - \ - '+ data[key].friendly_name + ' \ -
    \ -
    \ -
  • ' - - if (data.length - 1 > key) - html += '
  • ' - - $('#hyp_inst_listing').append(html); - - $('#hyperioninstance_' + data[key].instance).off().on("click", function (e) { - var inst = e.currentTarget.id.split("_")[1] - instanceSwitch(inst) - }); - } - } -} - -function initLanguageSelection() { - // Initialise language selection list with languages supported - for (var i = 0; i < availLang.length; i++) { - $("#language-select").append(''); - } - - var langLocale = storedLang; - - //Test, if language is supported by hyperion - var langIdx = availLang.indexOf(langLocale); - if (langIdx > -1) { - langText = availLangText[langIdx]; - } else { - // If language is not supported by hyperion, try fallback language - langLocale = $.i18n().options.fallbackLocale.substring(0, 2); - langIdx = availLang.indexOf(langLocale); - if (langIdx > -1) { - langText = availLangText[langIdx]; - } else { - langLocale = 'en'; - langIdx = availLang.indexOf(langLocale); - if (langIdx > -1) { - langText = availLangText[langIdx]; - } - } - } - - $('#language-select').prop('title', langText); - $("#language-select").val(langIdx); - $("#language-select").selectpicker("refresh"); -} - -function updateUiOnInstance(inst) { - $("#active_instance_friendly_name").text(getInstanceNameByIndex(inst)); - if (window.serverInfo.instance.filter(entry => entry.running).length > 1) { - $('#btn_hypinstanceswitch').toggle(true); - $('#active_instance_dropdown').prop('disabled', false); - $('#active_instance_dropdown').css('cursor', 'pointer'); - $("#active_instance_dropdown").css("pointer-events", "auto"); - } else { - $('#btn_hypinstanceswitch').toggle(false); - $('#active_instance_dropdown').prop('disabled', true); - $("#active_instance_dropdown").css('cursor', 'default'); - $("#active_instance_dropdown").css("pointer-events", "none"); - } -} - -function instanceSwitch(inst) { - requestInstanceSwitch(inst) - window.currentHyperionInstance = inst; - window.currentHyperionInstanceName = getInstanceNameByIndex(inst); - setStorage('lastSelectedInstance', inst) -} - -function loadContentTo(containerId, fileName) { - $(containerId).load("/content/" + fileName + ".html"); -} - -function toggleClass(obj, class1, class2) { - if ($(obj).hasClass(class1)) { - $(obj).removeClass(class1); - $(obj).addClass(class2); - } - else { - $(obj).removeClass(class2); - $(obj).addClass(class1); - } -} - -function setClassByBool(obj, enable, class1, class2) { - if (enable) { - $(obj).removeClass(class1); - $(obj).addClass(class2); - } - else { - $(obj).removeClass(class2); - $(obj).addClass(class1); - } -} - -function showInfoDialog(type, header, message) { - if (type == "success") { - $('#id_body').html(''); - if (header == "") - $('#id_body').append('

    ' + $.i18n('infoDialog_general_success_title') + '

    '); - $('#id_footer').html(''); - } - else if (type == "warning") { - $('#id_body').html(''); - if (header == "") - $('#id_body').append('

    ' + $.i18n('infoDialog_general_warning_title') + '

    '); - $('#id_footer').html(''); - } - else if (type == "error") { - $('#id_body').html(''); - if (header == "") - $('#id_body').append('

    ' + $.i18n('infoDialog_general_error_title') + '

    '); - $('#id_footer').html(''); - } - else if (type == "select") { - $('#id_body').html(''); - $('#id_footer').html(''); - $('#id_footer').append(''); - } - else if (type == "iswitch") { - $('#id_body').html(''); - $('#id_footer').html(''); - $('#id_footer').append(''); - } - else if (type == "uilock") { - $('#id_body').html(''); - $('#id_footer').html('' + $.i18n('InfoDialog_nowrite_foottext') + ''); - } - else if (type == "import") { - $('#id_body').html(''); - $('#id_footer').html(''); - $('#id_footer').append(''); - } - else if (type == "delInst") { - $('#id_body').html(''); - $('#id_footer').html(''); - $('#id_footer').append(''); - } - else if (type == "renInst") { - $('#id_body_rename').html('
    '); - $('#id_body_rename').append('

    ' + header + '

    '); - $('#id_body_rename').append(''); - $('#id_footer_rename').html(''); - $('#id_footer_rename').append(''); - } - else if (type == "changePassword") { - $('#id_body_rename').html('
    '); - $('#id_body_rename').append('

    ' + header + '


    '); - $('#id_body_rename').append('

    ' + $.i18n('infoDialog_username_text') + - '


    '); - $('#id_body_rename').append('

    ' + $.i18n('infoDialog_password_current_text') + - '


    '); - $('#id_body_rename').append('

    ' + $.i18n('infoDialog_password_new_text') + - '

    '); - $('#id_body_rename').append('
    ' + $.i18n('infoDialog_password_minimum_length') + '
    '); - $('#id_footer_rename').html(''); - $('#id_footer_rename').append(''); - } - else if (type == "checklist") { - $('#id_body').html(''); - $('#id_body').append('

    ' + $.i18n('infoDialog_checklist_title') + '

    '); - $('#id_body').append(header); - $('#id_footer').html(''); - } - else if (type == "newToken") { - $('#id_body').html(''); - $('#id_footer').html(''); - } - else if (type == "grantToken") { - $('#id_body').html(''); - $('#id_footer').html(''); - $('#id_footer').append(''); - } - - if (type != "renInst") { - $('#id_body').append('

    ' + header + '

    '); - $('#id_body').append(message); - } - - if (type == "select" || type == "iswitch") - $('#id_body').append(''); - - if (getStorage("darkMode") == "on") - $('#id_logo').attr("src", 'img/hyperion/logo_negativ.png'); - - $(type == "renInst" || type == "changePassword" ? "#modal_dialog_rename" : "#modal_dialog").modal({ - backdrop: "static", - keyboard: false, - show: true - }); - - $(document).on('click', '[data-dismiss-modal]', function () { - var target = $(this).attr('data-dismiss-modal'); - $(target).modal('hide'); // lgtm [js/xss-through-dom] - }); -} - -function createHintH(type, text, container) { - type = String(type); - if (type == "intro") - tclass = "introd"; - - $('#' + container).prepend('

    ' + text + '


    '); -} - -function createHint(type, text, container, buttonid, buttontxt) { - var fe, tclass; - - if (type == "intro") { - fe = ''; - tclass = "intro-hint"; - } - else if (type == "info") { - fe = '
    Information
    '; - tclass = "info-hint"; - } - else if (type == "wizard") { - fe = '
    Information
    '; - tclass = "wizard-hint"; - } - else if (type == "warning") { - fe = '
    Information
    '; - tclass = "warning-hint"; - } - - if (buttonid) - buttonid = '

    '; - else - buttonid = ""; - - if (type == "intro") - $('#' + container).prepend('

    ' + $.i18n("conf_helptable_expl") + '

    ' + text + '
    '); - else if (type == "wizard") - $('#' + container).prepend('

    ' + $.i18n("wiz_wizavail") + '

    ' + $.i18n('wiz_guideyou', text) + buttonid + '
    '); - else { - createTable('', 'htb', container, true, tclass); - $('#' + container + ' .htb').append(createTableRow([fe, text], false, true)); - } -} - -function createEffHint(title, text) { - return '

    ' + title + '

    ' + text + '
    '; -} - -function valValue(id, value, min, max) { - if (typeof max === 'undefined' || max == "") - max = 999999; - - if (Number(value) > Number(max)) { - $('#' + id).val(max); - showInfoDialog("warning", "", $.i18n('edt_msg_error_maximum_incl', max)); - return max; - } - else if (Number(value) < Number(min)) { - $('#' + id).val(min); - showInfoDialog("warning", "", $.i18n('edt_msg_error_minimum_incl', min)); - return min; - } - return value; -} - -function readImg(input, cb) { - if (input.files && input.files[0]) { - var reader = new FileReader(); - // inject fileName property - reader.fileName = input.files[0].name - - reader.onload = function (e) { - cb(e.target.result, e.target.fileName); - } - reader.readAsDataURL(input.files[0]); - } -} - -function isJsonString(str) { - try { - JSON.parse(str); - } - catch (e) { - return e; - } - return ""; -} - -function createJsonEditor(container, schema, setconfig, usePanel, arrayre) { - $('#' + container).off(); - $('#' + container).html(""); - - if (typeof arrayre === 'undefined') - arrayre = true; - - var editor = new JSONEditor(document.getElementById(container), - { - theme: 'bootstrap3', - iconlib: "fontawesome4", - disable_collapse: 'true', - form_name_root: 'sa', - disable_edit_json: true, - disable_properties: true, - disable_array_reorder: arrayre, - no_additional_properties: true, - disable_array_delete_all_rows: true, - disable_array_delete_last_row: true, - access: storedAccess, - schema: { - title: '', - properties: schema - } - }); - - if (usePanel) { - $('#' + container + ' .well').first().removeClass('well well-sm'); - $('#' + container + ' h4').first().remove(); - $('#' + container + ' .well').first().removeClass('well well-sm'); - } - - if (setconfig) { - for (var key in editor.root.editors) { - editor.getEditor("root." + key).setValue(Object.assign({}, editor.getEditor("root." + key).value, window.serverConfig[key])); - } - } - - return editor; -} - -function updateJsonEditorSelection(rootEditor, path, key, addElements, newEnumVals, newTitelVals, newDefaultVal, addSelect, addCustom, addCustomAsFirst, customText) { - var editor = rootEditor.getEditor(path); - var orginalProperties = editor.schema.properties[key]; - - var orginalWatchFunctions = rootEditor.watchlist[path + "." + key]; - rootEditor.unwatch(path + "." + key); - - var newSchema = []; - newSchema[key] = - { - "type": "string", - "enum": [], - "required": true, - "options": { "enum_titles": [], "infoText": "" }, - "propertyOrder": 1 - }; - - //Add additional elements to overwrite defaults - for (var item in addElements) { - newSchema[key][item] = addElements[item]; - } - - if (orginalProperties) { - if (orginalProperties["title"]) { - newSchema[key]["title"] = orginalProperties["title"]; - } - - if (orginalProperties["options"] && orginalProperties["options"]["infoText"]) { - newSchema[key]["options"]["infoText"] = orginalProperties["options"]["infoText"]; - } - - if (orginalProperties["propertyOrder"]) { - newSchema[key]["propertyOrder"] = orginalProperties["propertyOrder"]; - } - } - - if (addCustom) { - - if (newTitelVals.length === 0) { - newTitelVals = [...newEnumVals]; - } - - if (!!!customText) { - customText = "edt_conf_enum_custom"; - } - - if (addCustomAsFirst) { - newEnumVals.unshift("CUSTOM"); - newTitelVals.unshift(customText); - } else { - newEnumVals.push("CUSTOM"); - newTitelVals.push(customText); - } - - if (newSchema[key].options.infoText) { - var customInfoText = newSchema[key].options.infoText + "_custom"; - newSchema[key].options.infoText = customInfoText; - } - } - - if (addSelect) { - newEnumVals.unshift("SELECT"); - newTitelVals.unshift("edt_conf_enum_please_select"); - newDefaultVal = "SELECT"; - } - - if (newEnumVals) { - newSchema[key]["enum"] = newEnumVals; - } - - if (newTitelVals) { - newSchema[key]["options"]["enum_titles"] = newTitelVals; - } - if (newDefaultVal) { - newSchema[key]["default"] = newDefaultVal; - } - - editor.original_schema.properties[key] = orginalProperties; - editor.schema.properties[key] = newSchema[key]; - rootEditor.validator.schema.properties[editor.key].properties[key] = newSchema[key]; - - editor.removeObjectProperty(key); - delete editor.cached_editors[key]; - editor.addObjectProperty(key); - - if (orginalWatchFunctions) { - for (var i = 0; i < orginalWatchFunctions.length; i++) { - rootEditor.watch(path + "." + key, orginalWatchFunctions[i]); - } - } - rootEditor.notifyWatchers(path + "." + key); -} - -function updateJsonEditorMultiSelection(rootEditor, path, key, addElements, newEnumVals, newTitelVals, newDefaultVal) { - var editor = rootEditor.getEditor(path); - var orginalProperties = editor.schema.properties[key]; - - var orginalWatchFunctions = rootEditor.watchlist[path + "." + key]; - rootEditor.unwatch(path + "." + key); - - var newSchema = []; - newSchema[key] = - { - "type": "array", - "format": "select", - "items": { - "type": "string", - "enum": [], - "options": { "enum_titles": [] }, - }, - "options": { "infoText": "" }, - "default": [], - "propertyOrder": 1 - }; - - //Add additional elements to overwrite defaults - for (var item in addElements) { - newSchema[key][item] = addElements[item]; - } - - if (orginalProperties) { - if (orginalProperties["title"]) { - newSchema[key]["title"] = orginalProperties["title"]; - } - - if (orginalProperties["options"] && orginalProperties["options"]["infoText"]) { - newSchema[key]["options"]["infoText"] = orginalProperties["options"]["infoText"]; - } - - if (orginalProperties["propertyOrder"]) { - newSchema[key]["propertyOrder"] = orginalProperties["propertyOrder"]; - } - } - - if (newEnumVals) { - newSchema[key]["items"]["enum"] = newEnumVals; - } - - if (newTitelVals) { - newSchema[key]["items"]["options"]["enum_titles"] = newTitelVals; - } - - if (newDefaultVal) { - newSchema[key]["default"] = newDefaultVal; - } - - editor.original_schema.properties[key] = orginalProperties; - editor.schema.properties[key] = newSchema[key]; - rootEditor.validator.schema.properties[editor.key].properties[key] = newSchema[key]; - - editor.removeObjectProperty(key); - delete editor.cached_editors[key]; - editor.addObjectProperty(key); - - if (orginalWatchFunctions) { - for (var i = 0; i < orginalWatchFunctions.length; i++) { - rootEditor.watch(path + "." + key, orginalWatchFunctions[i]); - } - } - rootEditor.notifyWatchers(path + "." + key); -} - -function updateJsonEditorRange(rootEditor, path, key, minimum, maximum, defaultValue, step, clear) { - var editor = rootEditor.getEditor(path); - - //Preserve current value when updating range - var currentValue = rootEditor.getEditor(path + "." + key).getValue(); - - var orginalProperties = editor.schema.properties[key]; - var newSchema = []; - newSchema[key] = orginalProperties; - - if (clear) { - delete newSchema[key]["minimum"]; - delete newSchema[key]["maximum"]; - delete newSchema[key]["default"]; - delete newSchema[key]["step"]; - } - - if (typeof minimum !== "undefined") { - newSchema[key]["minimum"] = minimum; - } - if (typeof maximum !== "undefined") { - newSchema[key]["maximum"] = maximum; - } - if (typeof defaultValue !== "undefined") { - newSchema[key]["default"] = defaultValue; - currentValue = defaultValue; - } - - if (typeof step !== "undefined") { - newSchema[key]["step"] = step; - } - - editor.original_schema.properties[key] = orginalProperties; - editor.schema.properties[key] = newSchema[key]; - rootEditor.validator.schema.properties[editor.key].properties[key] = newSchema[key]; - - editor.removeObjectProperty(key); - delete editor.cached_editors[key]; - editor.addObjectProperty(key); - - // Restore current (new default) value for new range - rootEditor.getEditor(path + "." + key).setValue(currentValue); -} - -function addJsonEditorHostValidation() { - - JSONEditor.defaults.custom_validators.push(function (schema, value, path) { - var errors = []; - - if (!jQuery.isEmptyObject(value)) { - switch (schema.format) { - case "hostname_or_ip": - if (!isValidHostnameOrIP(value)) { - errors.push({ - path: path, - property: 'format', - message: $.i18n('edt_msgcust_error_hostname_ip') - }); - } - break; - case "hostname_or_ip4": - if (!isValidHostnameOrIP4(value)) { - errors.push({ - path: path, - property: 'format', - message: $.i18n('edt_msgcust_error_hostname_ip4') - }); - } - break; - - //Remove, when new json-editor 2.x is used - case "ipv4": - if (!isValidIPv4(value)) { - errors.push({ - path: path, - property: 'format', - message: $.i18n('edt_msg_error_ipv4') - }); - } - break; - case "ipv6": - if (!isValidIPv6(value)) { - errors.push({ - path: path, - property: 'format', - message: $.i18n('edt_msg_error_ipv6') - }); - } - break; - case "hostname": - if (!isValidHostname(value)) { - errors.push({ - path: path, - property: 'format', - message: $.i18n('edt_msg_error_hostname') - }); - } - break; - - default: - } - } - return errors; - }); -} - -function buildWL(link, linkt, cl) { - var baseLink = "https://docs.hyperion-project.org/"; - var lang; - - if (typeof linkt == "undefined") - linkt = "Placeholder"; - - if (storedLang == "de" || navigator.locale == "de") - lang = "de"; - else - lang = "en"; - - if (cl === true) { - linkt = $.i18n(linkt); - return '

    ' + linkt + '

    ' + $.i18n('general_wiki_moreto', linkt) + ': ' + linkt + '
    ' - } - else - return ': ' + linkt + ''; -} - -function rgbToHex(rgb) { - if (rgb.length == 3) { - return "#" + - ("0" + parseInt(rgb[0], 10).toString(16)).slice(-2) + - ("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) + - ("0" + parseInt(rgb[2], 10).toString(16)).slice(-2); - } - else - debugMessage('rgbToHex: Given rgb is no array or has wrong length'); -} - -function hexToRgb(hex) { - var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); - return result ? { - r: parseInt(result[1], 16), - g: parseInt(result[2], 16), - b: parseInt(result[3], 16) - } : { - r: 0, - g: 0, - b: 0 - }; -} - -/* - Show a notification - @param type Valid types are "info","success","warning","danger" - @param message The message to show - @param title A title (optional) - @param addhtml Add custom html to the notification end - */ -function showNotification(type, message, title = "", addhtml = "") { - if (title == "") { - switch (type) { - case "info": - title = $.i18n('infoDialog_general_info_title'); - break; - case "success": - title = $.i18n('infoDialog_general_success_title'); - break; - case "warning": - title = $.i18n('infoDialog_general_warning_title'); - break; - case "danger": - title = $.i18n('infoDialog_general_error_title'); - break; - } - } - - $.notify({ - // options - title: title, - message: message - }, { - // settings - type: type, - animate: { - enter: 'animate__animated animate__fadeInDown', - exit: 'animate__animated animate__fadeOutUp' - }, - placement: { - align: 'center' - }, - mouse_over: 'pause', - template: '' - }); -} - -function createCP(id, color, cb) { - if (Array.isArray(color)) - color = rgbToHex(color); - else if (color == "undefined") - color = "#AA3399"; - - if (color.startsWith("#")) { - $('#' + id).colorpicker({ - format: 'rgb', - customClass: 'colorpicker-2x', - color: color, - sliders: { - saturation: { - maxLeft: 200, - maxTop: 200 - }, - hue: { - maxTop: 200 - }, - } - }); - $('#' + id).colorpicker().on('changeColor', function (e) { - var rgb = e.color.toRGB(); - var hex = e.color.toHex(); - cb(rgb, hex, e); - }); - } - else - debugMessage('createCP: Given color is not legit'); -} - -// Creates a table with thead and tbody ids -// @param string hid : a class for thead -// @param string bid : a class for tbody -// @param string cont : a container id to html() the table -// @param string bless: if true the table is borderless -function createTable(hid, bid, cont, bless, tclass) { - var table = document.createElement('table'); - var thead = document.createElement('thead'); - var tbody = document.createElement('tbody'); - - table.className = "table"; - if (bless === true) - table.className += " borderless"; - if (typeof tclass !== "undefined") - table.className += " " + tclass; - table.style.marginBottom = "0px"; - if (hid != "") - thead.className = hid; - tbody.className = bid; - if (hid != "") - table.appendChild(thead); - table.appendChild(tbody); - - $('#' + cont).append(table); -} - -// Creates a table row -// @param array list :innerHTML content for / -// @param bool head :if null or false it's body -// @param bool align :if null or false no alignment -// -// @return : with or as child(s) -function createTableRow(list, head, align) { - var row = document.createElement('tr'); - - for (var i = 0; i < list.length; i++) { - if (head === true) - var el = document.createElement('th'); - else - var el = document.createElement('td'); - - if (align) - el.style.verticalAlign = "middle"; - - var purifyConfig = { - ADD_TAGS: ['button'], - ADD_ATTR: ['onclick'] - }; - el.innerHTML = DOMPurify.sanitize(list[i], purifyConfig); - row.appendChild(el); - } - return row; -} - -function createRow(id) { - var el = document.createElement('div'); - el.className = "row"; - el.setAttribute('id', id); - return el; -} - -function createOptPanel(phicon, phead, bodyid, footerid, css, panelId) { - phead = '' + phead; - - var pfooter = document.createElement('button'); - pfooter.className = "btn btn-primary"; - pfooter.setAttribute("id", footerid); - pfooter.innerHTML = '' + $.i18n('general_button_savesettings'); - - return createPanel(phead, "", pfooter, "panel-default", bodyid, css, panelId); -} - -function compareTwoValues(key1, key2, order = 'asc') { - return function innerSort(a, b) { - if (!a.hasOwnProperty(key1) || !b.hasOwnProperty(key1)) { - // property key1 doesn't exist on either object - return 0; - } - - const varA1 = (typeof a[key1] === 'string') - ? a[key1].toUpperCase() : a[key1]; - const varB1 = (typeof b[key1] === 'string') - ? b[key1].toUpperCase() : b[key1]; - - let comparison = 0; - if (varA1 > varB1) { - comparison = 1; - } else { - if (varA1 < varB1) { - comparison = -1; - } else { - if (!a.hasOwnProperty(key2) || !b.hasOwnProperty(key2)) { - // property key2 doesn't exist on either object - return 0; - } - - const varA2 = (typeof a[key2] === 'string') - ? a[key2].toUpperCase() : a[key2]; - const varB2 = (typeof b[key1] === 'string') - ? b[key2].toUpperCase() : b[key2]; - - if (varA2 > varB2) { - comparison = 1; - } else { - comparison = -1; - } - } - } - return ( - (order === 'desc') ? (comparison * -1) : comparison - ); - }; -} - -function sortProperties(list) { - for (var key in list) { - list[key].key = key; - } - list = $.map(list, function (value, index) { - return [value]; - }); - return list.sort(function (a, b) { - return a.propertyOrder - b.propertyOrder; - }); -} - -function createHelpTable(list, phead, panelId) { - var table = document.createElement('table'); - var thead = document.createElement('thead'); - var tbody = document.createElement('tbody'); - list = sortProperties(list); - - phead = '' + phead + ' ' + $.i18n("conf_helptable_expl"); - - table.className = 'table table-hover borderless'; - - thead.appendChild(createTableRow([$.i18n('conf_helptable_option'), $.i18n('conf_helptable_expl')], true, false)); - - for (var key in list) { - if (list[key].access != 'system') { - // break one iteration (in the loop), if the schema has the entry hidden=true - if ("options" in list[key] && "hidden" in list[key].options && (list[key].options.hidden)) - continue; - if ("access" in list[key] && ((list[key].access == "advanced" && storedAccess == "default") || (list[key].access == "expert" && storedAccess != "expert"))) - continue; - var text = list[key].title.replace('title', 'expl'); - tbody.appendChild(createTableRow([$.i18n(list[key].title), $.i18n(text)], false, false)); - - if (list[key].items && list[key].items.properties) { - var ilist = sortProperties(list[key].items.properties); - for (var ikey in ilist) { - // break one iteration (in the loop), if the schema has the entry hidden=true - if ("options" in ilist[ikey] && "hidden" in ilist[ikey].options && (ilist[ikey].options.hidden)) - continue; - if ("access" in ilist[ikey] && ((ilist[ikey].access == "advanced" && storedAccess == "default") || (ilist[ikey].access == "expert" && storedAccess != "expert"))) - continue; - var itext = ilist[ikey].title.replace('title', 'expl'); - tbody.appendChild(createTableRow([$.i18n(ilist[ikey].title), $.i18n(itext)], false, false)); - } - } - } - } - table.appendChild(thead); - table.appendChild(tbody); - - return createPanel(phead, table, undefined, undefined, undefined, undefined, panelId); -} - -function createPanel(head, body, footer, type, bodyid, css, panelId) { - var cont = document.createElement('div'); - var p = document.createElement('div'); - var phead = document.createElement('div'); - var pbody = document.createElement('div'); - var pfooter = document.createElement('div'); - - cont.className = "col-lg-6"; - - if (typeof type == 'undefined') - type = 'panel-default'; - - p.className = 'panel ' + type; - if (typeof panelId != 'undefined') { - p.setAttribute("id", panelId); - } - - phead.className = 'panel-heading ' + css; - pbody.className = 'panel-body'; - pfooter.className = 'panel-footer'; - - phead.innerHTML = head; - - if (typeof bodyid != 'undefined') { - pfooter.style.textAlign = 'right'; - pbody.setAttribute("id", bodyid); - } - - if (typeof body != 'undefined' && body != "") - pbody.appendChild(body); - - if (typeof footer != 'undefined') - pfooter.appendChild(footer); - - p.appendChild(phead); - p.appendChild(pbody); - - if (typeof footer != 'undefined') { - pfooter.style.textAlign = "right"; - p.appendChild(pfooter); - } - - cont.appendChild(p); - - return cont; -} - -function createSelGroup(group) { - var el = document.createElement('optgroup'); - el.setAttribute('label', group); - return el; -} - -function createSelOpt(opt, title) { - var el = document.createElement('option'); - el.setAttribute('value', opt); - if (typeof title == 'undefined') - el.innerHTML = opt; - else - el.innerHTML = title; - return el; -} - -function createSel(array, group, split) { - if (array.length != 0) { - var el = createSelGroup(group); - for (var i = 0; i < array.length; i++) { - var opt; - if (split) { - opt = array[i].split(":") - opt = createSelOpt(opt[0], opt[1]) - } - else - opt = createSelOpt(array[i]) - el.appendChild(opt); - } - return el; - } -} - -function performTranslation() { - $('[data-i18n]').i18n(); -} - -function encode_utf8(s) { - return unescape(encodeURIComponent(s)); -} - -function getReleases(callback) { - $.ajax({ - url: window.gitHubReleaseApiUrl, - method: 'get', - error: function (XMLHttpRequest, textStatus, errorThrown) { - callback(false); - }, - success: function (releases) { - window.gitHubVersionList = releases; - var highestRelease = { - tag_name: '0.0.0' - }; - var highestAlphaRelease = { - tag_name: '0.0.0' - }; - var highestBetaRelease = { - tag_name: '0.0.0' - }; - var highestRcRelease = { - tag_name: '0.0.0' - }; - - for (var i in releases) { - //drafts will be ignored - if (releases[i].draft) - continue; - - if (releases[i].tag_name.includes('alpha')) { - if (sem = semverLite.gt(releases[i].tag_name, highestAlphaRelease.tag_name)) - highestAlphaRelease = releases[i]; - } - else if (releases[i].tag_name.includes('beta')) { - if (sem = semverLite.gt(releases[i].tag_name, highestBetaRelease.tag_name)) - highestBetaRelease = releases[i]; - } - else if (releases[i].tag_name.includes('rc')) { - if (semverLite.gt(releases[i].tag_name, highestRcRelease.tag_name)) - highestRcRelease = releases[i]; - } - else { - if (semverLite.gt(releases[i].tag_name, highestRelease.tag_name)) - highestRelease = releases[i]; - } - } - window.latestStableVersion = highestRelease; - window.latestBetaVersion = highestBetaRelease; - window.latestAlphaVersion = highestAlphaRelease; - window.latestRcVersion = highestRcRelease; - - if (window.serverConfig.general.watchedVersionBranch == "Beta" && semverLite.gt(highestBetaRelease.tag_name, highestRelease.tag_name)) - window.latestVersion = highestBetaRelease; - else - window.latestVersion = highestRelease; - - if (window.serverConfig.general.watchedVersionBranch == "Alpha" && semverLite.gt(highestAlphaRelease.tag_name, highestBetaRelease.tag_name)) - window.latestVersion = highestAlphaRelease; - - if (window.serverConfig.general.watchedVersionBranch == "Alpha" && semverLite.lt(highestAlphaRelease.tag_name, highestBetaRelease.tag_name)) - window.latestVersion = highestBetaRelease; - - //next two if statements are only necessary if we don't have a beta or stable release. We need one alpha release at least - if (window.latestVersion.tag_name == '0.0.0' && highestBetaRelease.tag_name != '0.0.0') - window.latestVersion = highestBetaRelease; - - if (window.latestVersion.tag_name == '0.0.0' && highestAlphaRelease.tag_name != '0.0.0') - window.latestVersion = highestAlphaRelease; - - callback(true); - } - }); -} - -function getSystemInfo() { - var sys = window.sysInfo.system; - var shy = window.sysInfo.hyperion; - - var info = "Hyperion Server:\n"; - info += '- Build: ' + shy.build + '\n'; - info += '- Build time: ' + shy.time + '\n'; - info += '- Git Remote: ' + shy.gitremote + '\n'; - info += '- Version: ' + shy.version + '\n'; - info += '- UI Lang: ' + storedLang + ' (BrowserLang: ' + navigator.language + ')\n'; - info += '- UI Access: ' + storedAccess + '\n'; - //info += '- Log lvl: ' + window.serverConfig.logger.level + '\n'; - info += '- Avail Screen Cap.: ' + window.serverInfo.grabbers.screen.available + '\n'; - info += '- Avail Video Cap.: ' + window.serverInfo.grabbers.video.available + '\n'; - info += '- Avail Services: ' + window.serverInfo.services + '\n'; - info += '- Config path: ' + shy.rootPath + '\n'; - info += '- Database: ' + (shy.readOnlyMode ? "ready-only" : "read/write") + '\n'; - - info += '\n'; - - info += 'Hyperion Server OS:\n'; - info += '- Distribution: ' + sys.prettyName + '\n'; - info += '- Architecture: ' + sys.architecture + '\n'; - - if (sys.cpuModelName) - info += '- CPU Model: ' + sys.cpuModelName + '\n'; - if (sys.cpuModelType) - info += '- CPU Type: ' + sys.cpuModelType + '\n'; - if (sys.cpuRevision) - info += '- CPU Revision: ' + sys.cpuRevision + '\n'; - if (sys.cpuHardware) - info += '- CPU Hardware: ' + sys.cpuHardware + '\n'; - - info += '- Kernel: ' + sys.kernelType + ' (' + sys.kernelVersion + ' (WS: ' + sys.wordSize + '))\n'; - info += '- Root/Admin: ' + sys.isUserAdmin + '\n'; - info += '- Qt Version: ' + sys.qtVersion + '\n'; - if (jQuery.inArray("effectengine", window.serverInfo.services) !== -1) { - info += '- Python Version: ' + sys.pyVersion + '\n'; - } - info += '- Browser: ' + navigator.userAgent; - return info; -} - -function handleDarkMode() { - $("", { - rel: "stylesheet", - type: "text/css", - href: "../css/darkMode.css" - }).appendTo("head"); - - setStorage("darkMode", "on"); - $('#btn_darkmode_icon').removeClass('fa fa-moon-o'); - $('#btn_darkmode_icon').addClass('mdi mdi-white-balance-sunny'); - $('#navbar_brand_logo').attr("src", 'img/hyperion/logo_negativ.png'); -} - -function isAccessLevelCompliant(accessLevel) { - var isOK = true; - if (accessLevel) { - if (accessLevel === 'system') { - isOK = false; - } - else if (accessLevel === 'advanced' && storedAccess === 'default') { - isOK = false; - } - else if (accessLevel === 'expert' && storedAccess !== 'expert') { - isOK = false; - } - } - return isOK -} - -function showInputOptions(path, elements, state) { - for (var i = 0; i < elements.length; i++) { - $('[data-schemapath="root.' + path + '.' + elements[i] + '"]').toggle(state); - } -} - -function showInputOptionForItem(editor, path, item, state) { - var accessLevel = editor.schema.properties[path].properties[item].access; - // Enable element only, if access level compliant - if (!state || isAccessLevelCompliant(accessLevel)) { - showInputOptions(path, [item], state); - } -} - -function showInputOptionsForKey(editor, item, showForKeys, state) { - var elements = []; - var keysToshow = []; - - if (Array.isArray(showForKeys)) { - keysToshow = showForKeys; - } else { - if (typeof showForKeys === 'string') { - keysToshow.push(showForKeys); - } else { - return - } - } - - for (var key in editor.schema.properties[item].properties) { - if ($.inArray(key, keysToshow) === -1) { - var accessLevel = editor.schema.properties[item].properties[key].access; - - //Always disable all elements, but only enable elements, if access level compliant - if (!state || isAccessLevelCompliant(accessLevel)) { - elements.push(key); - } - } - } - showInputOptions(item, elements, state); -} - -function encodeHTML(s) { - return s.replace(/&/g, '&').replace(/ 255) { - return false; - } - } - return true; -} - -function isValidIPv6(value) { - if (value.match( - '^(?:(?:(?:[a-fA-F0-9]{1,4}:){6}|(?=(?:[a-fA-F0-9]{0,4}:){2,6}(?:[0-9]{1,3}.){3}[0-9]{1,3}$)(([0-9a-fA-F]{1,4}:){1,5}|:)((:[0-9a-fA-F]{1,4}){1,5}:|:)|::(?:[a-fA-F0-9]{1,4}:){5})(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]).){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])|(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}|(?=(?:[a-fA-F0-9]{0,4}:){0,7}[a-fA-F0-9]{0,4}$)(([0-9a-fA-F]{1,4}:){1,7}|:)((:[0-9a-fA-F]{1,4}){1,7}|:)|(?:[a-fA-F0-9]{1,4}:){7}:|:(:[a-fA-F0-9]{1,4}){7})$' - )) - return true; - else - return false; -} - -function isValidHostname(value) { - if (value.match( - '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])(.([a-zA-Z0-9]|[_a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]))*$' //lgtm [js/redos] - )) - return true; - else - return false; -} - -function isValidServicename(value) { - if (value.match( - '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9 -]{0,61}[a-zA-Z0-9])(.([a-zA-Z0-9]|[_a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]))*$' //lgtm [js/redos] - )) - return true; - else - return false; -} - -function isValidHostnameOrIP4(value) { - return (isValidHostname(value) || isValidIPv4(value)); -} - -function isValidHostnameOrIP(value) { - return (isValidHostnameOrIP4(value) || isValidIPv6(value) || isValidServicename(value)); -} - +var prevTag; + +function removeOverlay() { + $("#loading_overlay").removeClass("overlay"); +} + +function reload() { + location.reload(); +} + +function storageComp() { + if (typeof (Storage) !== "undefined") + return true; + return false; +} + +function getStorage(item) { + if (storageComp()) { + return localStorage.getItem(item); + } + return null; +} + +function setStorage(item, value) { + if (storageComp()) { + localStorage.setItem(item, value); + } +} + +function removeStorage(item) { + if (storageComp()) { + localStorage.removeItem(item); + } +} + +function debugMessage(msg) { + if (window.debugMessagesActive) { + console.log(msg); + } +} + +function validateDuration(d) { + if (typeof d === "undefined" || d < 0) + return ENDLESS; + else + return d *= 1000; +} + +function getHashtag() { + if (getStorage('lasthashtag') != null) + return getStorage('lasthashtag'); + else { + var tag = document.URL; + tag = tag.substr(tag.indexOf("#") + 1); + if (tag == "" || typeof tag === "undefined" || tag.startsWith("http")) + tag = "dashboard" + return tag; + } +} + +function loadContent(event, forceRefresh) { + var tag; + + var lastSelectedInstance = getStorage('lastSelectedInstance'); + + if (lastSelectedInstance && (lastSelectedInstance != window.currentHyperionInstance)) { + if (window.serverInfo.instance[lastSelectedInstance] && window.serverInfo.instance[lastSelectedInstance].running) { + instanceSwitch(lastSelectedInstance); + } else { + removeStorage('lastSelectedInstance'); + } + } + + if (typeof event != "undefined") { + tag = event.currentTarget.hash; + tag = tag.substr(tag.indexOf("#") + 1); + setStorage('lasthashtag', tag); + } + else + tag = getHashtag(); + + if (forceRefresh || prevTag != tag) { + prevTag = tag; + $("#page-content").off(); + $("#page-content").load("/content/" + tag + ".html", function (response, status, xhr) { + if (status == "error") { + tag = 'dashboard'; + console.log("Could not find page:", prevTag, ", Redirecting to:", tag); + setStorage('lasthashtag', tag); + + $("#page-content").load("/content/" + tag + ".html", function (response, status, xhr) { + if (status == "error") { + $("#page-content").html('

    ' + encode_utf8(tag) + '
    ' + $.i18n('info_404') + '

    '); + removeOverlay(); + } + }); + } + updateUiOnInstance(window.currentHyperionInstance); + }); + } +} + +function getInstanceNameByIndex(index) { + var instData = window.serverInfo.instance + for (var key in instData) { + if (instData[key].instance == index) + return instData[key].friendly_name; + } + return "unknown" +} + +function updateHyperionInstanceListing() { + if (window.serverInfo.instance) { + var data = window.serverInfo.instance.filter(entry => entry.running); + $('#hyp_inst_listing').html(""); + for (var key in data) { + var currInstMarker = (data[key].instance == window.currentHyperionInstance) ? "component-on" : ""; + + var html = '
  • \ + \ +
    \ + \ + '+ data[key].friendly_name + ' \ +
    \ +
    \ +
  • ' + + if (data.length - 1 > key) + html += '
  • ' + + $('#hyp_inst_listing').append(html); + + $('#hyperioninstance_' + data[key].instance).off().on("click", function (e) { + var inst = e.currentTarget.id.split("_")[1] + instanceSwitch(inst) + }); + } + } +} + +function initLanguageSelection() { + // Initialise language selection list with languages supported + for (var i = 0; i < availLang.length; i++) { + $("#language-select").append(''); + } + + var langLocale = storedLang; + + //Test, if language is supported by hyperion + var langIdx = availLang.indexOf(langLocale); + if (langIdx > -1) { + langText = availLangText[langIdx]; + } else { + // If language is not supported by hyperion, try fallback language + langLocale = $.i18n().options.fallbackLocale.substring(0, 2); + langIdx = availLang.indexOf(langLocale); + if (langIdx > -1) { + langText = availLangText[langIdx]; + } else { + langLocale = 'en'; + langIdx = availLang.indexOf(langLocale); + if (langIdx > -1) { + langText = availLangText[langIdx]; + } + } + } + + $('#language-select').prop('title', langText); + $("#language-select").val(langIdx); + $("#language-select").selectpicker("refresh"); +} + +function updateUiOnInstance(inst) { + $("#active_instance_friendly_name").text(getInstanceNameByIndex(inst)); + if (window.serverInfo.instance.filter(entry => entry.running).length > 1) { + $('#btn_hypinstanceswitch').toggle(true); + $('#active_instance_dropdown').prop('disabled', false); + $('#active_instance_dropdown').css('cursor', 'pointer'); + $("#active_instance_dropdown").css("pointer-events", "auto"); + } else { + $('#btn_hypinstanceswitch').toggle(false); + $('#active_instance_dropdown').prop('disabled', true); + $("#active_instance_dropdown").css('cursor', 'default'); + $("#active_instance_dropdown").css("pointer-events", "none"); + } +} + +function instanceSwitch(inst) { + requestInstanceSwitch(inst) + window.currentHyperionInstance = inst; + window.currentHyperionInstanceName = getInstanceNameByIndex(inst); + setStorage('lastSelectedInstance', inst) +} + +function loadContentTo(containerId, fileName) { + $(containerId).load("/content/" + fileName + ".html"); +} + +function toggleClass(obj, class1, class2) { + if ($(obj).hasClass(class1)) { + $(obj).removeClass(class1); + $(obj).addClass(class2); + } + else { + $(obj).removeClass(class2); + $(obj).addClass(class1); + } +} + +function setClassByBool(obj, enable, class1, class2) { + if (enable) { + $(obj).removeClass(class1); + $(obj).addClass(class2); + } + else { + $(obj).removeClass(class2); + $(obj).addClass(class1); + } +} + +function showInfoDialog(type, header, message) { + if (type == "success") { + $('#id_body').html(''); + if (header == "") + $('#id_body').append('

    ' + $.i18n('infoDialog_general_success_title') + '

    '); + $('#id_footer').html(''); + } + else if (type == "warning") { + $('#id_body').html(''); + if (header == "") + $('#id_body').append('

    ' + $.i18n('infoDialog_general_warning_title') + '

    '); + $('#id_footer').html(''); + } + else if (type == "error") { + $('#id_body').html(''); + if (header == "") + $('#id_body').append('

    ' + $.i18n('infoDialog_general_error_title') + '

    '); + $('#id_footer').html(''); + } + else if (type == "select") { + $('#id_body').html(''); + $('#id_footer').html(''); + $('#id_footer').append(''); + } + else if (type == "iswitch") { + $('#id_body').html(''); + $('#id_footer').html(''); + $('#id_footer').append(''); + } + else if (type == "uilock") { + $('#id_body').html(''); + $('#id_footer').html('' + $.i18n('InfoDialog_nowrite_foottext') + ''); + } + else if (type == "import") { + $('#id_body').html(''); + $('#id_footer').html(''); + $('#id_footer').append(''); + } + else if (type == "delInst") { + $('#id_body').html(''); + $('#id_footer').html(''); + $('#id_footer').append(''); + } + else if (type == "renInst") { + $('#id_body_rename').html('
    '); + $('#id_body_rename').append('

    ' + header + '

    '); + $('#id_body_rename').append(''); + $('#id_footer_rename').html(''); + $('#id_footer_rename').append(''); + } + else if (type == "changePassword") { + $('#id_body_rename').html('
    '); + $('#id_body_rename').append('

    ' + header + '


    '); + $('#id_body_rename').append('

    ' + $.i18n('infoDialog_username_text') + + '


    '); + $('#id_body_rename').append('

    ' + $.i18n('infoDialog_password_current_text') + + '


    '); + $('#id_body_rename').append('

    ' + $.i18n('infoDialog_password_new_text') + + '

    '); + $('#id_body_rename').append('
    ' + $.i18n('infoDialog_password_minimum_length') + '
    '); + $('#id_footer_rename').html(''); + $('#id_footer_rename').append(''); + } + else if (type == "checklist") { + $('#id_body').html(''); + $('#id_body').append('

    ' + $.i18n('infoDialog_checklist_title') + '

    '); + $('#id_body').append(header); + $('#id_footer').html(''); + } + else if (type == "newToken") { + $('#id_body').html(''); + $('#id_footer').html(''); + } + else if (type == "grantToken") { + $('#id_body').html(''); + $('#id_footer').html(''); + $('#id_footer').append(''); + } + + if (type != "renInst") { + $('#id_body').append('

    ' + header + '

    '); + $('#id_body').append(message); + } + + if (type == "select" || type == "iswitch") + $('#id_body').append(''); + + if (getStorage("darkMode") == "on") + $('#id_logo').attr("src", 'img/hyperion/logo_negativ.png'); + + $(type == "renInst" || type == "changePassword" ? "#modal_dialog_rename" : "#modal_dialog").modal({ + backdrop: "static", + keyboard: false, + show: true + }); + + $(document).on('click', '[data-dismiss-modal]', function () { + var target = $(this).attr('data-dismiss-modal'); + $.find(target).modal('hide'); + }); +} + +function createHintH(type, text, container) { + type = String(type); + if (type == "intro") + tclass = "introd"; + + $('#' + container).prepend('

    ' + text + '


    '); +} + +function createHint(type, text, container, buttonid, buttontxt) { + var fe, tclass; + + if (type == "intro") { + fe = ''; + tclass = "intro-hint"; + } + else if (type == "info") { + fe = '
    Information
    '; + tclass = "info-hint"; + } + else if (type == "wizard") { + fe = '
    Information
    '; + tclass = "wizard-hint"; + } + else if (type == "warning") { + fe = '
    Information
    '; + tclass = "warning-hint"; + } + + if (buttonid) + buttonid = '

    '; + else + buttonid = ""; + + if (type == "intro") + $('#' + container).prepend('

    ' + $.i18n("conf_helptable_expl") + '

    ' + text + '
    '); + else if (type == "wizard") + $('#' + container).prepend('

    ' + $.i18n("wiz_wizavail") + '

    ' + $.i18n('wiz_guideyou', text) + buttonid + '
    '); + else { + createTable('', 'htb', container, true, tclass); + $('#' + container + ' .htb').append(createTableRow([fe, text], false, true)); + } +} + +function createEffHint(title, text) { + return '

    ' + title + '

    ' + text + '
    '; +} + +function valValue(id, value, min, max) { + if (typeof max === 'undefined' || max == "") + max = 999999; + + if (Number(value) > Number(max)) { + $('#' + id).val(max); + showInfoDialog("warning", "", $.i18n('edt_msg_error_maximum_incl', max)); + return max; + } + else if (Number(value) < Number(min)) { + $('#' + id).val(min); + showInfoDialog("warning", "", $.i18n('edt_msg_error_minimum_incl', min)); + return min; + } + return value; +} + +function readImg(input, cb) { + if (input.files && input.files[0]) { + var reader = new FileReader(); + // inject fileName property + reader.fileName = input.files[0].name + + reader.onload = function (e) { + cb(e.target.result, e.target.fileName); + } + reader.readAsDataURL(input.files[0]); + } +} + +function isJsonString(str) { + try { + JSON.parse(str); + } + catch (e) { + return e; + } + return ""; +} + +function createJsonEditor(container, schema, setconfig, usePanel, arrayre) { + $('#' + container).off(); + $('#' + container).html(""); + + if (typeof arrayre === 'undefined') + arrayre = true; + + var editor = new JSONEditor(document.getElementById(container), + { + theme: 'bootstrap3', + iconlib: "fontawesome4", + disable_collapse: 'true', + form_name_root: 'sa', + disable_edit_json: true, + disable_properties: true, + disable_array_reorder: arrayre, + no_additional_properties: true, + disable_array_delete_all_rows: true, + disable_array_delete_last_row: true, + access: storedAccess, + schema: { + title: '', + properties: schema + } + }); + + if (usePanel) { + $('#' + container + ' .well').first().removeClass('well well-sm'); + $('#' + container + ' h4').first().remove(); + $('#' + container + ' .well').first().removeClass('well well-sm'); + } + + if (setconfig) { + for (var key in editor.root.editors) { + editor.getEditor("root." + key).setValue(Object.assign({}, editor.getEditor("root." + key).value, window.serverConfig[key])); + } + } + + return editor; +} + +function updateJsonEditorSelection(rootEditor, path, key, addElements, newEnumVals, newTitelVals, newDefaultVal, addSelect, addCustom, addCustomAsFirst, customText) { + var editor = rootEditor.getEditor(path); + var orginalProperties = editor.schema.properties[key]; + + var orginalWatchFunctions = rootEditor.watchlist[path + "." + key]; + rootEditor.unwatch(path + "." + key); + + var newSchema = []; + newSchema[key] = + { + "type": "string", + "enum": [], + "required": true, + "options": { "enum_titles": [], "infoText": "" }, + "propertyOrder": 1 + }; + + //Add additional elements to overwrite defaults + for (var item in addElements) { + newSchema[key][item] = addElements[item]; + } + + if (orginalProperties) { + if (orginalProperties["title"]) { + newSchema[key]["title"] = orginalProperties["title"]; + } + + if (orginalProperties["options"] && orginalProperties["options"]["infoText"]) { + newSchema[key]["options"]["infoText"] = orginalProperties["options"]["infoText"]; + } + + if (orginalProperties["propertyOrder"]) { + newSchema[key]["propertyOrder"] = orginalProperties["propertyOrder"]; + } + } + + if (addCustom) { + + if (newTitelVals.length === 0) { + newTitelVals = [...newEnumVals]; + } + + if (!!!customText) { + customText = "edt_conf_enum_custom"; + } + + if (addCustomAsFirst) { + newEnumVals.unshift("CUSTOM"); + newTitelVals.unshift(customText); + } else { + newEnumVals.push("CUSTOM"); + newTitelVals.push(customText); + } + + if (newSchema[key].options.infoText) { + var customInfoText = newSchema[key].options.infoText + "_custom"; + newSchema[key].options.infoText = customInfoText; + } + } + + if (addSelect) { + newEnumVals.unshift("SELECT"); + newTitelVals.unshift("edt_conf_enum_please_select"); + newDefaultVal = "SELECT"; + } + + if (newEnumVals) { + newSchema[key]["enum"] = newEnumVals; + } + + if (newTitelVals) { + newSchema[key]["options"]["enum_titles"] = newTitelVals; + } + if (newDefaultVal) { + newSchema[key]["default"] = newDefaultVal; + } + + editor.original_schema.properties[key] = orginalProperties; + editor.schema.properties[key] = newSchema[key]; + rootEditor.validator.schema.properties[editor.key].properties[key] = newSchema[key]; + + editor.removeObjectProperty(key); + delete editor.cached_editors[key]; + editor.addObjectProperty(key); + + if (orginalWatchFunctions) { + for (var i = 0; i < orginalWatchFunctions.length; i++) { + rootEditor.watch(path + "." + key, orginalWatchFunctions[i]); + } + } + rootEditor.notifyWatchers(path + "." + key); +} + +function updateJsonEditorMultiSelection(rootEditor, path, key, addElements, newEnumVals, newTitelVals, newDefaultVal) { + var editor = rootEditor.getEditor(path); + var orginalProperties = editor.schema.properties[key]; + + var orginalWatchFunctions = rootEditor.watchlist[path + "." + key]; + rootEditor.unwatch(path + "." + key); + + var newSchema = []; + newSchema[key] = + { + "type": "array", + "format": "select", + "items": { + "type": "string", + "enum": [], + "options": { "enum_titles": [] }, + }, + "options": { "infoText": "" }, + "default": [], + "propertyOrder": 1 + }; + + //Add additional elements to overwrite defaults + for (var item in addElements) { + newSchema[key][item] = addElements[item]; + } + + if (orginalProperties) { + if (orginalProperties["title"]) { + newSchema[key]["title"] = orginalProperties["title"]; + } + + if (orginalProperties["options"] && orginalProperties["options"]["infoText"]) { + newSchema[key]["options"]["infoText"] = orginalProperties["options"]["infoText"]; + } + + if (orginalProperties["propertyOrder"]) { + newSchema[key]["propertyOrder"] = orginalProperties["propertyOrder"]; + } + } + + if (newEnumVals) { + newSchema[key]["items"]["enum"] = newEnumVals; + } + + if (newTitelVals) { + newSchema[key]["items"]["options"]["enum_titles"] = newTitelVals; + } + + if (newDefaultVal) { + newSchema[key]["default"] = newDefaultVal; + } + + editor.original_schema.properties[key] = orginalProperties; + editor.schema.properties[key] = newSchema[key]; + rootEditor.validator.schema.properties[editor.key].properties[key] = newSchema[key]; + + editor.removeObjectProperty(key); + delete editor.cached_editors[key]; + editor.addObjectProperty(key); + + if (orginalWatchFunctions) { + for (var i = 0; i < orginalWatchFunctions.length; i++) { + rootEditor.watch(path + "." + key, orginalWatchFunctions[i]); + } + } + rootEditor.notifyWatchers(path + "." + key); +} + +function updateJsonEditorRange(rootEditor, path, key, minimum, maximum, defaultValue, step, clear) { + var editor = rootEditor.getEditor(path); + + //Preserve current value when updating range + var currentValue = rootEditor.getEditor(path + "." + key).getValue(); + + var orginalProperties = editor.schema.properties[key]; + var newSchema = []; + newSchema[key] = orginalProperties; + + if (clear) { + delete newSchema[key]["minimum"]; + delete newSchema[key]["maximum"]; + delete newSchema[key]["default"]; + delete newSchema[key]["step"]; + } + + if (typeof minimum !== "undefined") { + newSchema[key]["minimum"] = minimum; + } + if (typeof maximum !== "undefined") { + newSchema[key]["maximum"] = maximum; + } + if (typeof defaultValue !== "undefined") { + newSchema[key]["default"] = defaultValue; + currentValue = defaultValue; + } + + if (typeof step !== "undefined") { + newSchema[key]["step"] = step; + } + + editor.original_schema.properties[key] = orginalProperties; + editor.schema.properties[key] = newSchema[key]; + rootEditor.validator.schema.properties[editor.key].properties[key] = newSchema[key]; + + editor.removeObjectProperty(key); + delete editor.cached_editors[key]; + editor.addObjectProperty(key); + + // Restore current (new default) value for new range + rootEditor.getEditor(path + "." + key).setValue(currentValue); +} + +function addJsonEditorHostValidation() { + + JSONEditor.defaults.custom_validators.push(function (schema, value, path) { + var errors = []; + + if (!jQuery.isEmptyObject(value)) { + switch (schema.format) { + case "hostname_or_ip": + if (!isValidHostnameOrIP(value)) { + errors.push({ + path: path, + property: 'format', + message: $.i18n('edt_msgcust_error_hostname_ip') + }); + } + break; + case "hostname_or_ip4": + if (!isValidHostnameOrIP4(value)) { + errors.push({ + path: path, + property: 'format', + message: $.i18n('edt_msgcust_error_hostname_ip4') + }); + } + break; + + //Remove, when new json-editor 2.x is used + case "ipv4": + if (!isValidIPv4(value)) { + errors.push({ + path: path, + property: 'format', + message: $.i18n('edt_msg_error_ipv4') + }); + } + break; + case "ipv6": + if (!isValidIPv6(value)) { + errors.push({ + path: path, + property: 'format', + message: $.i18n('edt_msg_error_ipv6') + }); + } + break; + case "hostname": + if (!isValidHostname(value)) { + errors.push({ + path: path, + property: 'format', + message: $.i18n('edt_msg_error_hostname') + }); + } + break; + + default: + } + } + return errors; + }); +} + +function buildWL(link, linkt, cl) { + var baseLink = "https://docs.hyperion-project.org/"; + var lang; + + if (typeof linkt == "undefined") + linkt = "Placeholder"; + + if (storedLang == "de" || navigator.locale == "de") + lang = "de"; + else + lang = "en"; + + if (cl === true) { + linkt = $.i18n(linkt); + return '

    ' + linkt + '

    ' + $.i18n('general_wiki_moreto', linkt) + ': ' + linkt + '
    ' + } + else + return ': ' + linkt + ''; +} + +function rgbToHex(rgb) { + if (rgb.length == 3) { + return "#" + + ("0" + parseInt(rgb[0], 10).toString(16)).slice(-2) + + ("0" + parseInt(rgb[1], 10).toString(16)).slice(-2) + + ("0" + parseInt(rgb[2], 10).toString(16)).slice(-2); + } + else + debugMessage('rgbToHex: Given rgb is no array or has wrong length'); +} + +function hexToRgb(hex) { + var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); + return result ? { + r: parseInt(result[1], 16), + g: parseInt(result[2], 16), + b: parseInt(result[3], 16) + } : { + r: 0, + g: 0, + b: 0 + }; +} + +/* + Show a notification + @param type Valid types are "info","success","warning","danger" + @param message The message to show + @param title A title (optional) + @param addhtml Add custom html to the notification end + */ +function showNotification(type, message, title = "", addhtml = "") { + if (title == "") { + switch (type) { + case "info": + title = $.i18n('infoDialog_general_info_title'); + break; + case "success": + title = $.i18n('infoDialog_general_success_title'); + break; + case "warning": + title = $.i18n('infoDialog_general_warning_title'); + break; + case "danger": + title = $.i18n('infoDialog_general_error_title'); + break; + } + } + + $.notify({ + // options + title: title, + message: message + }, { + // settings + type: type, + animate: { + enter: 'animate__animated animate__fadeInDown', + exit: 'animate__animated animate__fadeOutUp' + }, + placement: { + align: 'center' + }, + mouse_over: 'pause', + template: '' + }); +} + +function createCP(id, color, cb) { + if (Array.isArray(color)) + color = rgbToHex(color); + else if (color == "undefined") + color = "#AA3399"; + + if (color.startsWith("#")) { + $('#' + id).colorpicker({ + format: 'rgb', + customClass: 'colorpicker-2x', + color: color, + sliders: { + saturation: { + maxLeft: 200, + maxTop: 200 + }, + hue: { + maxTop: 200 + }, + } + }); + $('#' + id).colorpicker().on('changeColor', function (e) { + var rgb = e.color.toRGB(); + var hex = e.color.toHex(); + cb(rgb, hex, e); + }); + } + else + debugMessage('createCP: Given color is not legit'); +} + +// Creates a table with thead and tbody ids +// @param string hid : a class for thead +// @param string bid : a class for tbody +// @param string cont : a container id to html() the table +// @param string bless: if true the table is borderless +function createTable(hid, bid, cont, bless, tclass) { + var table = document.createElement('table'); + var thead = document.createElement('thead'); + var tbody = document.createElement('tbody'); + + table.className = "table"; + if (bless === true) + table.className += " borderless"; + if (typeof tclass !== "undefined") + table.className += " " + tclass; + table.style.marginBottom = "0px"; + if (hid != "") + thead.className = hid; + tbody.className = bid; + if (hid != "") + table.appendChild(thead); + table.appendChild(tbody); + + $('#' + cont).append(table); +} + +// Creates a table row +// @param array list :innerHTML content for / +// @param bool head :if null or false it's body +// @param bool align :if null or false no alignment +// +// @return : with or as child(s) +function createTableRow(list, head, align) { + var row = document.createElement('tr'); + + for (var i = 0; i < list.length; i++) { + if (head === true) + var el = document.createElement('th'); + else + var el = document.createElement('td'); + + if (align) + el.style.verticalAlign = "middle"; + + var purifyConfig = { + ADD_TAGS: ['button'], + ADD_ATTR: ['onclick'] + }; + el.innerHTML = DOMPurify.sanitize(list[i], purifyConfig); + row.appendChild(el); + } + return row; +} + +function createRow(id) { + var el = document.createElement('div'); + el.className = "row"; + el.setAttribute('id', id); + return el; +} + +function createOptPanel(phicon, phead, bodyid, footerid, css, panelId) { + phead = '' + phead; + + var pfooter = document.createElement('button'); + pfooter.className = "btn btn-primary"; + pfooter.setAttribute("id", footerid); + pfooter.innerHTML = '' + $.i18n('general_button_savesettings'); + + return createPanel(phead, "", pfooter, "panel-default", bodyid, css, panelId); +} + +function compareTwoValues(key1, key2, order = 'asc') { + return function innerSort(a, b) { + if (!a.hasOwnProperty(key1) || !b.hasOwnProperty(key1)) { + // property key1 doesn't exist on either object + return 0; + } + + const varA1 = (typeof a[key1] === 'string') + ? a[key1].toUpperCase() : a[key1]; + const varB1 = (typeof b[key1] === 'string') + ? b[key1].toUpperCase() : b[key1]; + + let comparison = 0; + if (varA1 > varB1) { + comparison = 1; + } else { + if (varA1 < varB1) { + comparison = -1; + } else { + if (!a.hasOwnProperty(key2) || !b.hasOwnProperty(key2)) { + // property key2 doesn't exist on either object + return 0; + } + + const varA2 = (typeof a[key2] === 'string') + ? a[key2].toUpperCase() : a[key2]; + const varB2 = (typeof b[key1] === 'string') + ? b[key2].toUpperCase() : b[key2]; + + if (varA2 > varB2) { + comparison = 1; + } else { + comparison = -1; + } + } + } + return ( + (order === 'desc') ? (comparison * -1) : comparison + ); + }; +} + +function sortProperties(list) { + for (var key in list) { + list[key].key = key; + } + list = $.map(list, function (value, index) { + return [value]; + }); + return list.sort(function (a, b) { + return a.propertyOrder - b.propertyOrder; + }); +} + +function createHelpTable(list, phead, panelId) { + var table = document.createElement('table'); + var thead = document.createElement('thead'); + var tbody = document.createElement('tbody'); + list = sortProperties(list); + + phead = '' + phead + ' ' + $.i18n("conf_helptable_expl"); + + table.className = 'table table-hover borderless'; + + thead.appendChild(createTableRow([$.i18n('conf_helptable_option'), $.i18n('conf_helptable_expl')], true, false)); + + for (var key in list) { + if (list[key].access != 'system') { + // break one iteration (in the loop), if the schema has the entry hidden=true + if ("options" in list[key] && "hidden" in list[key].options && (list[key].options.hidden)) + continue; + if ("access" in list[key] && ((list[key].access == "advanced" && storedAccess == "default") || (list[key].access == "expert" && storedAccess != "expert"))) + continue; + var text = list[key].title.replace('title', 'expl'); + tbody.appendChild(createTableRow([$.i18n(list[key].title), $.i18n(text)], false, false)); + + if (list[key].items && list[key].items.properties) { + var ilist = sortProperties(list[key].items.properties); + for (var ikey in ilist) { + // break one iteration (in the loop), if the schema has the entry hidden=true + if ("options" in ilist[ikey] && "hidden" in ilist[ikey].options && (ilist[ikey].options.hidden)) + continue; + if ("access" in ilist[ikey] && ((ilist[ikey].access == "advanced" && storedAccess == "default") || (ilist[ikey].access == "expert" && storedAccess != "expert"))) + continue; + var itext = ilist[ikey].title.replace('title', 'expl'); + tbody.appendChild(createTableRow([$.i18n(ilist[ikey].title), $.i18n(itext)], false, false)); + } + } + } + } + table.appendChild(thead); + table.appendChild(tbody); + + return createPanel(phead, table, undefined, undefined, undefined, undefined, panelId); +} + +function createPanel(head, body, footer, type, bodyid, css, panelId) { + var cont = document.createElement('div'); + var p = document.createElement('div'); + var phead = document.createElement('div'); + var pbody = document.createElement('div'); + var pfooter = document.createElement('div'); + + cont.className = "col-lg-6"; + + if (typeof type == 'undefined') + type = 'panel-default'; + + p.className = 'panel ' + type; + if (typeof panelId != 'undefined') { + p.setAttribute("id", panelId); + } + + phead.className = 'panel-heading ' + css; + pbody.className = 'panel-body'; + pfooter.className = 'panel-footer'; + + phead.innerHTML = head; + + if (typeof bodyid != 'undefined') { + pfooter.style.textAlign = 'right'; + pbody.setAttribute("id", bodyid); + } + + if (typeof body != 'undefined' && body != "") + pbody.appendChild(body); + + if (typeof footer != 'undefined') + pfooter.appendChild(footer); + + p.appendChild(phead); + p.appendChild(pbody); + + if (typeof footer != 'undefined') { + pfooter.style.textAlign = "right"; + p.appendChild(pfooter); + } + + cont.appendChild(p); + + return cont; +} + +function createSelGroup(group) { + var el = document.createElement('optgroup'); + el.setAttribute('label', group); + return el; +} + +function createSelOpt(opt, title) { + var el = document.createElement('option'); + el.setAttribute('value', opt); + if (typeof title == 'undefined') + el.innerHTML = opt; + else + el.innerHTML = title; + return el; +} + +function createSel(array, group, split) { + if (array.length != 0) { + var el = createSelGroup(group); + for (var i = 0; i < array.length; i++) { + var opt; + if (split) { + opt = array[i].split(":") + opt = createSelOpt(opt[0], opt[1]) + } + else + opt = createSelOpt(array[i]) + el.appendChild(opt); + } + return el; + } +} + +function performTranslation() { + $('[data-i18n]').i18n(); +} + +function encode_utf8(s) { + return unescape(encodeURIComponent(s)); +} + +function getReleases(callback) { + $.ajax({ + url: window.gitHubReleaseApiUrl, + method: 'get', + error: function (XMLHttpRequest, textStatus, errorThrown) { + callback(false); + }, + success: function (releases) { + window.gitHubVersionList = releases; + var highestRelease = { + tag_name: '0.0.0' + }; + var highestAlphaRelease = { + tag_name: '0.0.0' + }; + var highestBetaRelease = { + tag_name: '0.0.0' + }; + var highestRcRelease = { + tag_name: '0.0.0' + }; + + for (var i in releases) { + //drafts will be ignored + if (releases[i].draft) + continue; + + if (releases[i].tag_name.includes('alpha')) { + if (sem = semverLite.gt(releases[i].tag_name, highestAlphaRelease.tag_name)) + highestAlphaRelease = releases[i]; + } + else if (releases[i].tag_name.includes('beta')) { + if (sem = semverLite.gt(releases[i].tag_name, highestBetaRelease.tag_name)) + highestBetaRelease = releases[i]; + } + else if (releases[i].tag_name.includes('rc')) { + if (semverLite.gt(releases[i].tag_name, highestRcRelease.tag_name)) + highestRcRelease = releases[i]; + } + else { + if (semverLite.gt(releases[i].tag_name, highestRelease.tag_name)) + highestRelease = releases[i]; + } + } + window.latestStableVersion = highestRelease; + window.latestBetaVersion = highestBetaRelease; + window.latestAlphaVersion = highestAlphaRelease; + window.latestRcVersion = highestRcRelease; + + if (window.serverConfig.general.watchedVersionBranch == "Beta" && semverLite.gt(highestBetaRelease.tag_name, highestRelease.tag_name)) + window.latestVersion = highestBetaRelease; + else + window.latestVersion = highestRelease; + + if (window.serverConfig.general.watchedVersionBranch == "Alpha" && semverLite.gt(highestAlphaRelease.tag_name, highestBetaRelease.tag_name)) + window.latestVersion = highestAlphaRelease; + + if (window.serverConfig.general.watchedVersionBranch == "Alpha" && semverLite.lt(highestAlphaRelease.tag_name, highestBetaRelease.tag_name)) + window.latestVersion = highestBetaRelease; + + //next two if statements are only necessary if we don't have a beta or stable release. We need one alpha release at least + if (window.latestVersion.tag_name == '0.0.0' && highestBetaRelease.tag_name != '0.0.0') + window.latestVersion = highestBetaRelease; + + if (window.latestVersion.tag_name == '0.0.0' && highestAlphaRelease.tag_name != '0.0.0') + window.latestVersion = highestAlphaRelease; + + callback(true); + } + }); +} + +function getSystemInfo() { + var sys = window.sysInfo.system; + var shy = window.sysInfo.hyperion; + + var info = "Hyperion Server:\n"; + info += '- Build: ' + shy.build + '\n'; + info += '- Build time: ' + shy.time + '\n'; + info += '- Git Remote: ' + shy.gitremote + '\n'; + info += '- Version: ' + shy.version + '\n'; + info += '- UI Lang: ' + storedLang + ' (BrowserLang: ' + navigator.language + ')\n'; + info += '- UI Access: ' + storedAccess + '\n'; + //info += '- Log lvl: ' + window.serverConfig.logger.level + '\n'; + info += '- Avail Screen Cap.: ' + window.serverInfo.grabbers.screen.available + '\n'; + info += '- Avail Video Cap.: ' + window.serverInfo.grabbers.video.available + '\n'; + info += '- Avail Services: ' + window.serverInfo.services + '\n'; + info += '- Config path: ' + shy.rootPath + '\n'; + info += '- Database: ' + (shy.readOnlyMode ? "ready-only" : "read/write") + '\n'; + + info += '\n'; + + info += 'Hyperion Server OS:\n'; + info += '- Distribution: ' + sys.prettyName + '\n'; + info += '- Architecture: ' + sys.architecture + '\n'; + + if (sys.cpuModelName) + info += '- CPU Model: ' + sys.cpuModelName + '\n'; + if (sys.cpuModelType) + info += '- CPU Type: ' + sys.cpuModelType + '\n'; + if (sys.cpuRevision) + info += '- CPU Revision: ' + sys.cpuRevision + '\n'; + if (sys.cpuHardware) + info += '- CPU Hardware: ' + sys.cpuHardware + '\n'; + + info += '- Kernel: ' + sys.kernelType + ' (' + sys.kernelVersion + ' (WS: ' + sys.wordSize + '))\n'; + info += '- Root/Admin: ' + sys.isUserAdmin + '\n'; + info += '- Qt Version: ' + sys.qtVersion + '\n'; + if (jQuery.inArray("effectengine", window.serverInfo.services) !== -1) { + info += '- Python Version: ' + sys.pyVersion + '\n'; + } + info += '- Browser: ' + navigator.userAgent; + return info; +} + +function handleDarkMode() { + $("", { + rel: "stylesheet", + type: "text/css", + href: "../css/darkMode.css" + }).appendTo("head"); + + setStorage("darkMode", "on"); + $('#btn_darkmode_icon').removeClass('fa fa-moon-o'); + $('#btn_darkmode_icon').addClass('mdi mdi-white-balance-sunny'); + $('#navbar_brand_logo').attr("src", 'img/hyperion/logo_negativ.png'); +} + +function isAccessLevelCompliant(accessLevel) { + var isOK = true; + if (accessLevel) { + if (accessLevel === 'system') { + isOK = false; + } + else if (accessLevel === 'advanced' && storedAccess === 'default') { + isOK = false; + } + else if (accessLevel === 'expert' && storedAccess !== 'expert') { + isOK = false; + } + } + return isOK +} + +function showInputOptions(path, elements, state) { + for (var i = 0; i < elements.length; i++) { + $('[data-schemapath="root.' + path + '.' + elements[i] + '"]').toggle(state); + } +} + +function showInputOptionForItem(editor, path, item, state) { + var accessLevel = editor.schema.properties[path].properties[item].access; + // Enable element only, if access level compliant + if (!state || isAccessLevelCompliant(accessLevel)) { + showInputOptions(path, [item], state); + } +} + +function showInputOptionsForKey(editor, item, showForKeys, state) { + var elements = []; + var keysToshow = []; + + if (Array.isArray(showForKeys)) { + keysToshow = showForKeys; + } else { + if (typeof showForKeys === 'string') { + keysToshow.push(showForKeys); + } else { + return + } + } + + for (var key in editor.schema.properties[item].properties) { + if ($.inArray(key, keysToshow) === -1) { + var accessLevel = editor.schema.properties[item].properties[key].access; + + //Always disable all elements, but only enable elements, if access level compliant + if (!state || isAccessLevelCompliant(accessLevel)) { + elements.push(key); + } + } + } + showInputOptions(item, elements, state); +} + +function encodeHTML(s) { + return s.replace(/&/g, '&').replace(/ 255) { + return false; + } + } + return true; +} + +function isValidIPv6(value) { + if (value.match( + '^(?:(?:(?:[a-fA-F0-9]{1,4}:){6}|(?=(?:[a-fA-F0-9]{0,4}:){2,6}(?:[0-9]{1,3}.){3}[0-9]{1,3}$)(([0-9a-fA-F]{1,4}:){1,5}|:)((:[0-9a-fA-F]{1,4}){1,5}:|:)|::(?:[a-fA-F0-9]{1,4}:){5})(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9]).){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])|(?:[a-fA-F0-9]{1,4}:){7}[a-fA-F0-9]{1,4}|(?=(?:[a-fA-F0-9]{0,4}:){0,7}[a-fA-F0-9]{0,4}$)(([0-9a-fA-F]{1,4}:){1,7}|:)((:[0-9a-fA-F]{1,4}){1,7}|:)|(?:[a-fA-F0-9]{1,4}:){7}:|:(:[a-fA-F0-9]{1,4}){7})$' + )) + return true; + else + return false; +} + +function isValidHostname(value) { + if (value.match( + '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9])(.([a-zA-Z0-9]|[_a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]))*$' + )) + return true; + else + return false; +} + +function isValidServicename(value) { + if (value.match( + '^([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9 -]{0,61}[a-zA-Z0-9])(.([a-zA-Z0-9]|[_a-zA-Z0-9][a-zA-Z0-9-]{0,61}[a-zA-Z0-9]))*$' + )) + return true; + else + return false; +} + +function isValidHostnameOrIP4(value) { + return (isValidHostname(value) || isValidIPv4(value)); +} + +function isValidHostnameOrIP(value) { + return (isValidHostnameOrIP4(value) || isValidIPv6(value) || isValidServicename(value)); +} + diff --git a/effects/knight-rider.py b/effects/knight-rider.py index 821ec377..15723933 100644 --- a/effects/knight-rider.py +++ b/effects/knight-rider.py @@ -1,54 +1,54 @@ -import hyperion, time - -# Get the parameters -speed = float(hyperion.args.get('speed', 1.0)) -fadeFactor = float(hyperion.args.get('fadeFactor', 0.7)) -color = hyperion.args.get('color', (255,0,0)) - -# Check parameters -speed = max(0.0001, speed) -fadeFactor = max(0.0, min(fadeFactor, 1.0)) - -# Initialize the led data -width = 25 -imageData = bytearray(width * (0,0,0)) -imageData[0] = color[0] -imageData[1] = color[1] -imageData[2] = color[2] - -# Calculate the sleep time and rotation increment -increment = 1 -sleepTime = 1.0 / (speed * width) -while sleepTime < 0.05: - increment *= 2 - sleepTime *= 2 - -# Start the write data loop -position = 0 -direction = 1 -while not hyperion.abort(): - hyperion.setImage(width, 1, imageData) - - # Move data into next state - for i in range(increment): - position += direction - if position == -1: - position = 1 - direction = 1 - elif position == width: - position = width-2 - direction = -1 - - # Fade the old data - for j in range(width): - imageData[3*j] = int(fadeFactor * imageData[3*j]) - imageData[3*j+1] = int(fadeFactor * imageData[3*j+1]) - imageData[3*j+2] = int(fadeFactor * imageData[3*j+2]) - - # Insert new data - imageData[3*position] = color[0] - imageData[3*position+1] = color[1] - imageData[3*position+2] = color[2] - - # Sleep for a while - time.sleep(sleepTime) +import hyperion, time + +# Get the parameters +speed = float(hyperion.args.get('speed', 1.0)) +fadeFactor = float(hyperion.args.get('fadeFactor', 0.7)) +color = hyperion.args.get('color', (255,0,0)) + +# Check parameters +speed = max(0.0001, speed) +fadeFactor = max(0.0, min(fadeFactor, 1.0)) + +# Initialize the led data +width = 25 +imageData = bytearray(width * (0,0,0)) +imageData[0] = color[0] +imageData[1] = color[1] +imageData[2] = color[2] + +# Calculate the sleep time and rotation increment +increment = 1 +sleepTime = 1.0 / (speed * width) +while sleepTime < 0.05: + increment *= 2 + sleepTime *= 2 + +# Start the write data loop +position = 0 +direction = 1 +while not hyperion.abort(): + hyperion.setImage(width, 1, imageData) + + # Move data into next state + for unused in range(increment): + position += direction + if position == -1: + position = 1 + direction = 1 + elif position == width: + position = width-2 + direction = -1 + + # Fade the old data + for j in range(width): + imageData[3*j] = int(fadeFactor * imageData[3*j]) + imageData[3*j+1] = int(fadeFactor * imageData[3*j+1]) + imageData[3*j+2] = int(fadeFactor * imageData[3*j+2]) + + # Insert new data + imageData[3*position] = color[0] + imageData[3*position+1] = color[1] + imageData[3*position+2] = color[2] + + # Sleep for a while + time.sleep(sleepTime) diff --git a/effects/rainbow-mood.py b/effects/rainbow-mood.py index ddad75f2..8a48abb7 100644 --- a/effects/rainbow-mood.py +++ b/effects/rainbow-mood.py @@ -1,23 +1,23 @@ -import hyperion, time, colorsys - -# Get the parameters -rotationTime = float(hyperion.args.get('rotation-time', 30.0)) -brightness = float(hyperion.args.get('brightness', 100))/100.0 -saturation = float(hyperion.args.get('saturation', 100))/100.0 -reverse = bool(hyperion.args.get('reverse', False)) - -# Calculate the sleep time and hue increment -sleepTime = 0.1 -hueIncrement = sleepTime / rotationTime - -# Switch direction if needed -if reverse: - increment = -increment - -# Start the write data loop -hue = 0.0 -while not hyperion.abort(): - rgb = colorsys.hsv_to_rgb(hue, saturation, brightness) - hyperion.setColor(int(255*rgb[0]), int(255*rgb[1]), int(255*rgb[2])) - hue = (hue + hueIncrement) % 1.0 - time.sleep(sleepTime) +import hyperion, time, colorsys + +# Get the parameters +rotationTime = float(hyperion.args.get('rotation-time', 30.0)) +brightness = float(hyperion.args.get('brightness', 100))/100.0 +saturation = float(hyperion.args.get('saturation', 100))/100.0 +reverse = bool(hyperion.args.get('reverse', False)) + +# Calculate the sleep time and hue increment +sleepTime = 0.1 +hueIncrement = sleepTime / rotationTime + +# Switch direction if needed +if reverse: + hueIncrement = -hueIncrement + +# Start the write data loop +hue = 0.0 +while not hyperion.abort(): + rgb = colorsys.hsv_to_rgb(hue, saturation, brightness) + hyperion.setColor(int(255*rgb[0]), int(255*rgb[1]), int(255*rgb[2])) + hue = (hue + hueIncrement) % 1.0 + time.sleep(sleepTime) diff --git a/effects/running_dots.py b/effects/running_dots.py index d807d356..2fb9569b 100644 --- a/effects/running_dots.py +++ b/effects/running_dots.py @@ -1,43 +1,43 @@ -import hyperion, time - -# get options from args -sleepTime = float(hyperion.args.get('speed', 1.5)) * 0.005 -whiteLevel = int(hyperion.args.get('whiteLevel', 0)) -lvl = int(hyperion.args.get('colorLevel', 220)) - -# check value -whiteLevel = min( whiteLevel, 254 ) -lvl = min( lvl, 255 ) - -if whiteLevel >= lvl: - lvl = 255 - -# Initialize the led data -ledData = bytearray() -for i in range(hyperion.ledCount): - ledData += bytearray((0,0,0)) - -runners = [ - { "pos":0, "step": 4, "lvl":lvl}, - { "pos":1, "step": 5, "lvl":lvl}, - { "pos":2, "step": 6, "lvl":lvl}, - { "pos":0, "step": 7, "lvl":lvl}, - { "pos":1, "step": 8, "lvl":lvl}, - { "pos":2, "step": 9, "lvl":lvl}, - #{ "pos":0, "step":10, "lvl":lvl}, - #{ "pos":1, "step":11, "lvl":lvl}, - #{ "pos":2, "step":12, "lvl":lvl}, -] - -# Start the write data loop -counter = 0 -while not hyperion.abort(): - counter += 1 - for r in runners: - if counter % r["step"] == 0: - ledData[r["pos"]] = whiteLevel - r["pos"] = (r["pos"]+3) % (hyperion.ledCount*3) - ledData[r["pos"]] = r["lvl"] - - hyperion.setColor(ledData) - time.sleep(sleepTime) +import hyperion, time + +# get options from args +sleepTime = float(hyperion.args.get('speed', 1.5)) * 0.005 +whiteLevel = int(hyperion.args.get('whiteLevel', 0)) +lvl = int(hyperion.args.get('colorLevel', 220)) + +# check value +whiteLevel = min( whiteLevel, 254 ) +lvl = min( lvl, 255 ) + +if whiteLevel >= lvl: + lvl = 255 + +# Initialize the led data +ledData = bytearray() +for unused in range(hyperion.ledCount): + ledData += bytearray((0,0,0)) + +runners = [ + { "pos":0, "step": 4, "lvl":lvl}, + { "pos":1, "step": 5, "lvl":lvl}, + { "pos":2, "step": 6, "lvl":lvl}, + { "pos":0, "step": 7, "lvl":lvl}, + { "pos":1, "step": 8, "lvl":lvl}, + { "pos":2, "step": 9, "lvl":lvl}, + #{ "pos":0, "step":10, "lvl":lvl}, + #{ "pos":1, "step":11, "lvl":lvl}, + #{ "pos":2, "step":12, "lvl":lvl}, +] + +# Start the write data loop +counter = 0 +while not hyperion.abort(): + counter += 1 + for r in runners: + if counter % r["step"] == 0: + ledData[r["pos"]] = whiteLevel + r["pos"] = (r["pos"]+3) % (hyperion.ledCount*3) + ledData[r["pos"]] = r["lvl"] + + hyperion.setColor(ledData) + time.sleep(sleepTime) diff --git a/effects/swirl.py b/effects/swirl.py index 47d8944b..fa5d0ed4 100644 --- a/effects/swirl.py +++ b/effects/swirl.py @@ -42,7 +42,7 @@ def buildGradient(cc, closeCircle = True): pos = 0 if len(cc[0]) == 4: withAlpha = True - + for c in cc: if withAlpha: alpha = int(c[3]*255) @@ -50,7 +50,7 @@ def buildGradient(cc, closeCircle = True): alpha = 255 pos += posfac ba += bytearray([pos,c[0],c[1],c[2],alpha]) - + if closeCircle: # last color as first color lC = cc[-1] @@ -61,6 +61,7 @@ def buildGradient(cc, closeCircle = True): ba += bytearray([0,lC[0],lC[1],lC[2],alpha]) return ba + return bytearray() def rotateAngle( increment = 1): global angle diff --git a/effects/trails.py b/effects/trails.py index 8d074dc2..3f8ba2e0 100644 --- a/effects/trails.py +++ b/effects/trails.py @@ -1,98 +1,98 @@ -import hyperion -import time -import colorsys -import random - -min_len = int(hyperion.args.get('min_len', 3)) -max_len = int(hyperion.args.get('max_len', 3)) -#iHeight = int(hyperion.args.get('iHeight', 8)) -trails = int(hyperion.args.get('int', 8)) -sleepTime = float(hyperion.args.get('speed', 1)) / 1000.0 -color = list(hyperion.args.get('color', (255,255,255))) -randomise = bool(hyperion.args.get('random', False)) -iWidth = hyperion.imageWidth() -iHeight = hyperion.imageHeight() - -class trail: - def __init__(self): - return - - def start(self, x, y, step, color, _len, _h): - self.pos = 0.0 - self.step = step - self.h = _h - self.x = x - self.data = [] - brigtness = color[2] - step_brigtness = color[2] / _len - for i in range(0, _len): - rgb = colorsys.hsv_to_rgb(color[0], color[1], brigtness) - self.data.insert(0, (int(255*rgb[0]), int(255*rgb[1]), int(255*rgb[2]))) - brigtness -= step_brigtness - - self.data.extend([(0,0,0)]*(_h-y)) - if len(self.data) < _h: - for i in range (_h-len(self.data)): - self.data.insert(0, (0,0,0)) - - def getdata(self): - self.pos += self.step - if self.pos > 1.0: - self.pos = 0.0 - self.data.pop() - self.data.insert(0, (0,0,0)) - return self.x, self.data[-self.h:], all(x == self.data[0] for x in self.data) - -tr = [] - -for i in range(trails): - r = {'exec': trail()} - - if randomise: - col = (random.uniform(0.0, 1.0),1,1) - else: - col = colorsys.rgb_to_hsv(color[0]/255.0, color[1]/255.0, color[2]/255.0) - - r['exec'].start( - random.randint(0, iWidth), - random.randint(0, iHeight), - random.uniform(0.2, 0.8), - col, - random.randint(min_len, max_len), - iHeight - ) - tr.append(r) - -# Start the write data loop -while not hyperion.abort(): - ledData = bytearray() - - for r in tr: - r['x'], r['data'], c = r['exec'].getdata() - if c: - if randomise: - col = (random.uniform(0.0, 1.0),1,1) - else: - col = colorsys.rgb_to_hsv(color[0]/255.0, color[1]/255.0, color[2]/255.0) - - r['exec'].start( - random.randint(0, iWidth), - random.randint(0, iHeight), - random.uniform(0.2, 0.8), - col, - random.randint(min_len, max_len), - iHeight - ) - - for y in range(0, iHeight): - for x in range(0, iWidth): - for r in tr: - if x == r['x']: - led = bytearray(r['data'][y]) - break - led = bytearray((0,0,0)) - ledData += led - - hyperion.setImage(iWidth,iHeight,ledData) - time.sleep(sleepTime) - +import hyperion +import time +import colorsys +import random + +min_len = int(hyperion.args.get('min_len', 3)) +max_len = int(hyperion.args.get('max_len', 3)) +#iHeight = int(hyperion.args.get('iHeight', 8)) +trails = int(hyperion.args.get('int', 8)) +sleepTime = float(hyperion.args.get('speed', 1)) / 1000.0 +color = list(hyperion.args.get('color', (255,255,255))) +randomise = bool(hyperion.args.get('random', False)) +iWidth = hyperion.imageWidth() +iHeight = hyperion.imageHeight() + +class trail: + def __init__(self): + return + + def start(self, x, y, step, color, _len, _h): + self.pos = 0.0 + self.step = step + self.h = _h + self.x = x + self.data = [] + brigtness = color[2] + step_brigtness = color[2] / _len + for i in range(0, _len): + rgb = colorsys.hsv_to_rgb(color[0], color[1], brigtness) + self.data.insert(0, (int(255*rgb[0]), int(255*rgb[1]), int(255*rgb[2]))) + brigtness -= step_brigtness + + self.data.extend([(0,0,0)]*(_h-y)) + if len(self.data) < _h: + for i in range (_h-len(self.data)): + self.data.insert(0, (0,0,0)) + + def getdata(self): + self.pos += self.step + if self.pos > 1.0: + self.pos = 0.0 + self.data.pop() + self.data.insert(0, (0,0,0)) + return self.x, self.data[-self.h:], all(x == self.data[0] for x in self.data) + +tr = [] + +for unused in range(trails): + r = {'exec': trail()} + + if randomise: + col = (random.uniform(0.0, 1.0),1,1) + else: + col = colorsys.rgb_to_hsv(color[0]/255.0, color[1]/255.0, color[2]/255.0) + + r['exec'].start( + random.randint(0, iWidth), + random.randint(0, iHeight), + random.uniform(0.2, 0.8), + col, + random.randint(min_len, max_len), + iHeight + ) + tr.append(r) + +# Start the write data loop +while not hyperion.abort(): + ledData = bytearray() + + for r in tr: + r['x'], r['data'], c = r['exec'].getdata() + if c: + if randomise: + col = (random.uniform(0.0, 1.0),1,1) + else: + col = colorsys.rgb_to_hsv(color[0]/255.0, color[1]/255.0, color[2]/255.0) + + r['exec'].start( + random.randint(0, iWidth), + random.randint(0, iHeight), + random.uniform(0.2, 0.8), + col, + random.randint(min_len, max_len), + iHeight + ) + + for y in range(0, iHeight): + for x in range(0, iWidth): + for r in tr: + if x == r['x']: + led = bytearray(r['data'][y]) + break + led = bytearray((0,0,0)) + ledData += led + + hyperion.setImage(iWidth,iHeight,ledData) + time.sleep(sleepTime) + diff --git a/effects/waves.py b/effects/waves.py index 05299dcc..f5add15f 100644 --- a/effects/waves.py +++ b/effects/waves.py @@ -1,77 +1,71 @@ -import hyperion, time, math, random - -randomCenter = bool(hyperion.args.get('random-center', False)) -centerX = float(hyperion.args.get('center_x', -0.15)) -centerY = float(hyperion.args.get('center_y', -0.25)) -rotationTime = float(hyperion.args.get('rotation_time', 90)) -colors = hyperion.args.get('colors', ((255,0,0),(255,255,0),(0,255,0),(0,255,255),(0,0,255),(255,0,255))) -reverse = bool(hyperion.args.get('reverse', False)) -reverseTime = int(hyperion.args.get('reverse_time', 0)) -#rotate = bool(hyperion.args.get('rotate', True)) -positions = [] - -# calc center if random -if randomCenter: - centerX = random.uniform(0.0, 1.0) - centerY = random.uniform(0.0, 1.0) - -rCenterX = int(round(float(hyperion.imageWidth())*centerX)) -rCenterY = int(round(float(hyperion.imageHeight())*centerY)) - -#calc interval -sleepTime = max(1/(255/rotationTime), 0.016) - -#calc diagonal -if centerX < 0.5: - cX = 1.0-centerX -else: - cX = 0.0+centerX - -if centerY < 0.5: - cY = 1.0-centerY -else: - cY = 0.0+centerY - -diag = int(round(math.sqrt(((cX*hyperion.imageWidth())**2)+((cY*hyperion.imageHeight())**2)))) -# some diagonal overhead -diag = int(diag*1.3) - -# calc positions -pos = 0 -step = int(255/len(colors)) -for _ in colors: - positions.append(pos) - pos += step - -# target time -targetTime = time.time()+float(reverseTime) - -#hyperion.imageCOffset(int(hyperion.imageWidth()/2), int(hyperion.imageHeight()/2)) - -while not hyperion.abort(): - # verify reverseTime, randomize reverseTime based on reverseTime up to reversedTime*2 - if reverseTime >= 1: - now = time.time() - if now > targetTime: - reverse = not reverse - targetTime = time.time()+random.uniform(float(reverseTime), float(reverseTime*2.0)) - # apply rotate - #if rotate: - # hyperion.imageCRotate(1) - # prepare bytearray with colors and positions - gradientBa = bytearray() - it = 0 - for color in colors: - gradientBa += bytearray((positions[it],color[0],color[1],color[2])) - it += 1 - - hyperion.imageRadialGradient(rCenterX,rCenterY, diag, gradientBa,0) - - # increment positions - for i, pos in enumerate(positions): - if reverse: - positions[i] = pos - 1 if pos >= 1 else 255 - else: - positions[i] = pos + 1 if pos <= 254 else 0 - hyperion.imageShow() - time.sleep(sleepTime) +import hyperion, time, math, random + +randomCenter = bool(hyperion.args.get('random-center', False)) +centerX = float(hyperion.args.get('center_x', -0.15)) +centerY = float(hyperion.args.get('center_y', -0.25)) +rotationTime = float(hyperion.args.get('rotation_time', 90)) +colors = hyperion.args.get('colors', ((255,0,0),(255,255,0),(0,255,0),(0,255,255),(0,0,255),(255,0,255))) +reverse = bool(hyperion.args.get('reverse', False)) +reverseTime = int(hyperion.args.get('reverse_time', 0)) +positions = [] + +# calc center if random +if randomCenter: + centerX = random.uniform(0.0, 1.0) + centerY = random.uniform(0.0, 1.0) + +rCenterX = int(round(float(hyperion.imageWidth())*centerX)) +rCenterY = int(round(float(hyperion.imageHeight())*centerY)) + +#calc interval +sleepTime = max(1/(255/rotationTime), 0.016) + +#calc diagonal +if centerX < 0.5: + cX = 1.0-centerX +else: + cX = 0.0+centerX + +if centerY < 0.5: + cY = 1.0-centerY +else: + cY = 0.0+centerY + +diag = int(round(math.hypot(cX*hyperion.imageWidth(),cY*hyperion.imageHeight()))) +# some diagonal overhead +diag = int(diag*1.3) + +# calc positions +pos = 0 +step = int(255/len(colors)) +for _ in colors: + positions.append(pos) + pos += step + +# target time +targetTime = time.time()+float(reverseTime) +while not hyperion.abort(): + # verify reverseTime, randomize reverseTime based on reverseTime up to reversedTime*2 + if reverseTime >= 1: + now = time.time() + if now > targetTime: + reverse = not reverse + targetTime = time.time()+random.uniform(float(reverseTime), float(reverseTime*2.0)) + + # prepare bytearray with colors and positions + gradientBa = bytearray() + it = 0 + for color in colors: + gradientBa += bytearray((positions[it],color[0],color[1],color[2])) + it += 1 + + hyperion.imageRadialGradient(rCenterX,rCenterY, diag, gradientBa,0) + + # increment positions + for i, pos in enumerate(positions): + if reverse: + positions[i] = pos - 1 if pos >= 1 else 255 + else: + positions[i] = pos + 1 if pos <= 254 else 0 + hyperion.imageShow() + time.sleep(sleepTime) diff --git a/effects/x-mas.py b/effects/x-mas.py index 4ccba418..b0bf706e 100644 --- a/effects/x-mas.py +++ b/effects/x-mas.py @@ -1,30 +1,30 @@ -import hyperion, time - -# Get the parameters -sleepTime = float(hyperion.args.get('sleepTime', 1000))/1000.0 -length = hyperion.args.get('length', 1) -color1 = hyperion.args.get('color1', (255,255,255)) -color2 = hyperion.args.get('color2', (255,0,0)) - -# Initialize the led data -i = 0 -ledDataOdd = bytearray() -while i < hyperion.ledCount: - for l in range(length): - if i getAllComponents(); - - /// + /// /// @brief Check if Hyperion ist enabled /// @return True when enabled else false /// diff --git a/include/blackborder/BlackBorderDetector.h b/include/blackborder/BlackBorderDetector.h index 21f1444a..77438f4c 100644 --- a/include/blackborder/BlackBorderDetector.h +++ b/include/blackborder/BlackBorderDetector.h @@ -1,4 +1,3 @@ -//#include #pragma once // Utils includes @@ -219,7 +218,6 @@ namespace hyperion || !isBlack(image((width - x), y)) || !isBlack(image((width - x), (height - y)))) { -// std::cout << "y " << y << " lt " << int(isBlack(color1)) << " lb " << int(isBlack(color2)) << " rt " << int(isBlack(color3)) << " rb " << int(isBlack(color4)) << std::endl; firstNonBlackYPixelIndex = y; break; } diff --git a/include/mdns/MdnsBrowser.h b/include/mdns/MdnsBrowser.h index 0ac35a4e..b88a7f11 100644 --- a/include/mdns/MdnsBrowser.h +++ b/include/mdns/MdnsBrowser.h @@ -104,24 +104,6 @@ private slots: private: - // template ::value, int> = 0> - // static inline QMetaObject::Connection weakConnect(typename QtPrivate::FunctionPointer::Object* sender, - // Func1 signal, - // typename QtPrivate::FunctionPointer::Object* receiver, - // Func2 slot) - // { - // QMetaObject::Connection conn_normal = QObject::connect(sender, signal, receiver, slot); - - // QMetaObject::Connection* conn_delete = new QMetaObject::Connection(); - - // *conn_delete = QObject::connect(sender, signal, [conn_normal, conn_delete]() { - // QObject::disconnect(conn_normal); - // QObject::disconnect(*conn_delete); - // delete conn_delete; - // }); - // return conn_normal; - // } - template ::value, int> = 0> static inline QMetaObject::Connection weakConnect(typename QtPrivate::FunctionPointer::Object* sender, Func1 signal, @@ -139,25 +121,6 @@ private: return conn_normal; } - // template ::value, int> = 0> - // static inline QMetaObject::Connection weakConnect(typename QtPrivate::FunctionPointer::Object* sender, - // Func1 signal, - // typename QtPrivate::FunctionPointer::Object* receiver, - // Func2 slot) - // { - // Q_UNUSED(receiver); - // QMetaObject::Connection conn_normal = QObject::connect(sender, signal, slot); - - // QMetaObject::Connection* conn_delete = new QMetaObject::Connection(); - - // *conn_delete = QObject::connect(sender, signal, [conn_normal, conn_delete]() { - // QObject::disconnect(conn_normal); - // QObject::disconnect(*conn_delete); - // delete conn_delete; - // }); - // return conn_normal; - // } - /// The logger instance for mDNS-Service Logger* _log; diff --git a/include/utils/NetUtils.h b/include/utils/NetUtils.h index 856062a1..3b247e49 100644 --- a/include/utils/NetUtils.h +++ b/include/utils/NetUtils.h @@ -122,7 +122,7 @@ namespace NetUtils { { if (hostAddress.setAddress(hostname)) { - //Debug(log, "IP-address (%s) not required to be resolved.", QSTRING_CSTR(hostAddress.toString())); + // An IP-address is not required to be resolved isHostAddressOK = true; } else diff --git a/include/utils/RgbTransform.h b/include/utils/RgbTransform.h index d4e4bfd1..ec493a2d 100644 --- a/include/utils/RgbTransform.h +++ b/include/utils/RgbTransform.h @@ -44,7 +44,7 @@ public: int getBacklightThreshold() const; /// @param backlightThreshold New lower brightness - void setBacklightThreshold(int backlightThreshold); + void setBacklightThreshold(double backlightThreshold); /// @return The current state bool getBacklightColored() const; diff --git a/include/utils/hyperion.h b/include/utils/hyperion.h index 5349d38d..2a71c3ce 100644 --- a/include/utils/hyperion.h +++ b/include/utils/hyperion.h @@ -140,13 +140,12 @@ namespace hyperion { { // Special case for indices '*' => all leds adjustment->setAdjustmentForLed(colorAdjustment->_id, 0, ledCnt-1); - //Info(Logger::getInstance("HYPERION"), "ColorAdjustment '%s' => [0-%d]", QSTRING_CSTR(colorAdjustment->_id), ledCnt-1); continue; } if (!overallExp.match(ledIndicesStr).hasMatch()) { - //Error(Logger::getInstance("HYPERION"), "Given led indices %d not correct format: %s", i, QSTRING_CSTR(ledIndicesStr)); + // Given LED indices are not correctly formatted continue; } @@ -173,7 +172,6 @@ namespace hyperion { ss << index; } } - //Info(Logger::getInstance("HYPERION"), "ColorAdjustment '%s' => [%s]", QSTRING_CSTR(colorAdjustment->_id), ss.str().c_str()); } return adjustment; diff --git a/include/utils/jsonschema/QJsonUtils.h b/include/utils/jsonschema/QJsonUtils.h index 8626ae98..63c22d34 100644 --- a/include/utils/jsonschema/QJsonUtils.h +++ b/include/utils/jsonschema/QJsonUtils.h @@ -174,9 +174,9 @@ private: if (!path.isEmpty()) { - QJsonObject obj; - modifyValue(subValue, obj, path, newValue, property); - subValue = obj; + QJsonObject tempObj; + modifyValue(subValue, tempObj, path, newValue, property); + subValue = tempObj; } else if (newValue != QJsonValue::Null) subValue = newValue; diff --git a/libsrc/api/API.cpp b/libsrc/api/API.cpp index eaf4c04d..f255a8ea 100644 --- a/libsrc/api/API.cpp +++ b/libsrc/api/API.cpp @@ -294,13 +294,6 @@ bool API::setHyperionInstance(quint8 inst) return true; } -std::map API::getAllComponents() -{ - std::map comps; - //QMetaObject::invokeMethod(_hyperion, "getAllComponents", Qt::BlockingQueuedConnection, Q_RETURN_ARG(std::map, comps)); - return comps; -} - bool API::isHyperionEnabled() { int res; diff --git a/libsrc/api/JsonAPI.cpp b/libsrc/api/JsonAPI.cpp index 60a832b4..bfa76b0a 100644 --- a/libsrc/api/JsonAPI.cpp +++ b/libsrc/api/JsonAPI.cpp @@ -144,7 +144,6 @@ void JsonAPI::handleMessage(const QString &messageString, const QString &httpAut { const QString ident = "JsonRpc@" + _peerAddress; QJsonObject message; - //std::cout << "JsonAPI::handleMessage | [" << static_cast(_hyperion->getInstanceIndex()) << "] Received: ["<< messageString.toStdString() << "]" << std::endl; // parse the message if (!JsonUtils::parse(ident, messageString, message, _log)) @@ -553,27 +552,6 @@ void JsonAPI::handleServerInfoCommand(const QJsonObject &message, const QString info["ledDevices"] = ledDevices; QJsonObject grabbers; - - // *** Deprecated *** - //QJsonArray availableGrabbers; - //if ( GrabberWrapper::getInstance() != nullptr ) - //{ - // QStringList activeGrabbers = GrabberWrapper::getInstance()->getActive(_hyperion->getInstanceIndex()); - // QJsonArray activeGrabberNames; - // for (auto grabberName : activeGrabbers) - // { - // activeGrabberNames.append(grabberName); - // } - - // grabbers["active"] = activeGrabberNames; - //} - //for (auto grabber : GrabberWrapper::availableGrabbers(GrabberTypeFilter::ALL)) - //{ - // availableGrabbers.append(grabber); - //} - - //grabbers["available"] = availableGrabbers; - QJsonObject screenGrabbers; if (GrabberWrapper::getInstance() != nullptr) { @@ -687,7 +665,6 @@ void JsonAPI::handleServerInfoCommand(const QJsonObject &message, const QString QJsonObject obj; obj.insert("friendly_name", entry["friendly_name"].toString()); obj.insert("instance", entry["instance"].toInt()); - //obj.insert("last_use", entry["last_use"].toString()); obj.insert("running", entry["running"].toBool()); instanceInfo.append(obj); } @@ -696,7 +673,7 @@ void JsonAPI::handleServerInfoCommand(const QJsonObject &message, const QString // add leds configs info["leds"] = _hyperion->getSetting(settings::LEDS).array(); - // BEGIN | The following entries are derecated but used to ensure backward compatibility with hyperion Classic remote control + // BEGIN | The following entries are deprecated but used to ensure backward compatibility with hyperion Classic remote control // TODO Output the real transformation information instead of default // HOST NAME @@ -757,7 +734,6 @@ void JsonAPI::handleServerInfoCommand(const QJsonObject &message, const QString const Hyperion::InputInfo &priorityInfo = _hyperion->getPriorityInfo(_hyperion->getCurrentPriority()); if (priorityInfo.componentId == hyperion::COMP_COLOR && !priorityInfo.ledColors.empty()) { - QJsonObject LEDcolor; // check if LED Color not Black (0,0,0) if ((priorityInfo.ledColors.begin()->red + priorityInfo.ledColors.begin()->green + @@ -1309,8 +1285,8 @@ void JsonAPI::handleAuthorizeCommand(const QJsonObject &message, const QString & // use comment // for user authorized sessions AuthManager::AuthDefinition def; - const QString res = API::createToken(comment, def); - if (res.isEmpty()) + const QString createTokenResult = API::createToken(comment, def); + if (createTokenResult.isEmpty()) { QJsonObject newTok; newTok["comment"] = def.comment; @@ -1320,7 +1296,7 @@ void JsonAPI::handleAuthorizeCommand(const QJsonObject &message, const QString & sendSuccessDataReply(QJsonDocument(newTok), command + "-" + subc, tan); return; } - sendErrorReply(res, command + "-" + subc, tan); + sendErrorReply(createTokenResult, command + "-" + subc, tan); return; } @@ -1328,13 +1304,13 @@ void JsonAPI::handleAuthorizeCommand(const QJsonObject &message, const QString & if (subc == "renameToken") { // use id/comment - const QString res = API::renameToken(id, comment); - if (res.isEmpty()) + const QString renameTokenResult = API::renameToken(id, comment); + if (renameTokenResult.isEmpty()) { sendSuccessReply(command + "-" + subc, tan); return; } - sendErrorReply(res, command + "-" + subc, tan); + sendErrorReply(renameTokenResult, command + "-" + subc, tan); return; } @@ -1342,13 +1318,13 @@ void JsonAPI::handleAuthorizeCommand(const QJsonObject &message, const QString & if (subc == "deleteToken") { // use id - const QString res = API::deleteToken(id); - if (res.isEmpty()) + const QString deleteTokenResult = API::deleteToken(id); + if (deleteTokenResult.isEmpty()) { sendSuccessReply(command + "-" + subc, tan); return; } - sendErrorReply(res, command + "-" + subc, tan); + sendErrorReply(deleteTokenResult, command + "-" + subc, tan); return; } @@ -1356,7 +1332,6 @@ void JsonAPI::handleAuthorizeCommand(const QJsonObject &message, const QString & if (subc == "requestToken") { // use id/comment - const QString &comment = message["comment"].toString().trimmed(); const bool &acc = message["accept"].toBool(true); if (acc) API::setNewTokenRequest(comment, id, tan); @@ -1373,7 +1348,7 @@ void JsonAPI::handleAuthorizeCommand(const QJsonObject &message, const QString & if (API::getPendingTokenRequests(vec)) { QJsonArray arr; - for (const auto &entry : vec) + for (const auto &entry : qAsConst(vec)) { QJsonObject obj; obj["comment"] = entry.comment; @@ -1556,12 +1531,8 @@ void JsonAPI::handleLedDeviceCommand(const QJsonObject &message, const QString & QString full_command = command + "-" + subc; // TODO: Validate that device type is a valid one -/* if ( ! valid type ) + { - sendErrorReply("Unknown device", full_command, tan); - } - else -*/ { QJsonObject config; config.insert("type", devType); LedDevice* ledDevice = nullptr; @@ -1623,12 +1594,7 @@ void JsonAPI::handleInputSourceCommand(const QJsonObject& message, const QString QString full_command = command + "-" + subc; // TODO: Validate that source type is a valid one -/* if ( ! valid type ) { - sendErrorReply("Unknown device", full_command, tan); - } - else -*/ { if (subc == "discover") { QJsonObject inputSourcesDiscovered; @@ -2007,6 +1973,11 @@ void JsonAPI::handleInstanceStateChange(InstanceState state, quint8 instance, co handleInstanceSwitch(); } break; + + case InstanceState::H_STARTED: + case InstanceState::H_STOPPED: + case InstanceState::H_CREATED: + case InstanceState::H_DELETED: default: break; } diff --git a/libsrc/api/JsonCB.cpp b/libsrc/api/JsonCB.cpp index 5c35b77b..965abf37 100644 --- a/libsrc/api/JsonCB.cpp +++ b/libsrc/api/JsonCB.cpp @@ -148,7 +148,6 @@ void JsonCB::resetSubscriptions() void JsonCB::setSubscriptionsTo(Hyperion* hyperion) { assert(hyperion); - //std::cout << "JsonCB::setSubscriptions for instance [" << static_cast(hyperion->getInstanceIndex()) << "] " << std::endl; // get current subs QStringList currSubs(getSubscribedCommands()); @@ -179,8 +178,6 @@ void JsonCB::doCallback(const QString& cmd, const QVariant& data) else obj["data"] = data.toJsonObject(); - //std::cout << "JsonCB::doCallback | [" << static_cast(_hyperion->getInstanceIndex()) << "] Send: [" << QJsonDocument(obj).toJson(QJsonDocument::Compact).toStdString() << "]" << std::endl; - emit newCallback(obj); } @@ -398,7 +395,6 @@ void JsonCB::handleInstanceChange() QJsonObject obj; obj.insert("friendly_name", entry["friendly_name"].toString()); obj.insert("instance", entry["instance"].toInt()); - //obj.insert("last_use", entry["last_use"].toString()); obj.insert("running", entry["running"].toBool()); arr.append(obj); } diff --git a/libsrc/blackborder/BlackBorderDetector.cpp b/libsrc/blackborder/BlackBorderDetector.cpp index 67df1b16..aea8fc60 100644 --- a/libsrc/blackborder/BlackBorderDetector.cpp +++ b/libsrc/blackborder/BlackBorderDetector.cpp @@ -23,7 +23,5 @@ uint8_t BlackBorderDetector::calculateThreshold(double threshold) const uint8_t blackborderThreshold = uint8_t(rgbThreshold); - //Debug(Logger::getInstance("BLACKBORDER"), "threshold set to %f (%d)", threshold , int(blackborderThreshold)); - return blackborderThreshold; } diff --git a/libsrc/blackborder/BlackBorderProcessor.cpp b/libsrc/blackborder/BlackBorderProcessor.cpp index eadc56c2..538ee534 100644 --- a/libsrc/blackborder/BlackBorderProcessor.cpp +++ b/libsrc/blackborder/BlackBorderProcessor.cpp @@ -1,4 +1,5 @@ #include +#include #include @@ -33,6 +34,8 @@ BlackBorderProcessor::BlackBorderProcessor(Hyperion* hyperion, QObject* parent) // listen for component state changes connect(_hyperion, &Hyperion::compStateChangeRequest, this, &BlackBorderProcessor::handleCompStateChangeRequest); + + _detector = new BlackBorderDetector(_oldThreshold); } BlackBorderProcessor::~BlackBorderProcessor() @@ -60,7 +63,7 @@ void BlackBorderProcessor::handleSettingsUpdate(settings::type type, const QJson _detectionMode = obj["mode"].toString("default"); const double newThreshold = obj["threshold"].toDouble(5.0) / 100.0; - if (_oldThreshold != newThreshold) + if (fabs(_oldThreshold - newThreshold) > std::numeric_limits::epsilon()) { _oldThreshold = newThreshold; @@ -140,8 +143,6 @@ bool BlackBorderProcessor::updateBorder(const BlackBorder & newDetectedBorder) // makes it look like the border detectionn is not working - since the new 3 line detection algorithm is more precise this became a problem specialy in dark scenes // wisc -// std::cout << "c: " << setw(2) << _currentBorder.verticalSize << " " << setw(2) << _currentBorder.horizontalSize << " p: " << setw(2) << _previousDetectedBorder.verticalSize << " " << setw(2) << _previousDetectedBorder.horizontalSize << " n: " << setw(2) << newDetectedBorder.verticalSize << " " << setw(2) << newDetectedBorder.horizontalSize << " c:i " << setw(2) << _consistentCnt << ":" << setw(2) << _inconsistentCnt << std::endl; - // set the consistency counter if (newDetectedBorder == _previousDetectedBorder) { diff --git a/libsrc/boblightserver/BoblightClientConnection.cpp b/libsrc/boblightserver/BoblightClientConnection.cpp index 4610ae91..242a2bb8 100644 --- a/libsrc/boblightserver/BoblightClientConnection.cpp +++ b/libsrc/boblightserver/BoblightClientConnection.cpp @@ -106,8 +106,6 @@ QString BoblightClientConnection::readMessage(const char* data, const size_t siz const int len = end - data + 1; const QString message = QString::fromLatin1(data, len); - //std::cout << bytes << ": \"" << message.toUtf8().constData() << "\"" << std::endl; - return message; } @@ -124,7 +122,6 @@ void BoblightClientConnection::socketClosed() void BoblightClientConnection::handleMessage(const QString& message) { - //std::cout << "boblight message: " << message.toStdString() << std::endl; QStringList messageParts = QStringUtils::split(message, ' ', QStringUtils::SplitBehavior::SkipEmptyParts); if (!messageParts.isEmpty()) { @@ -340,7 +337,6 @@ float BoblightClientConnection::parseFloat(const QString& s, bool *ok) const { if (ok) { - //std::cout << "FAIL L " << q << ": " << s.toUtf8().constData() << std::endl; *ok = false; } return 0; @@ -348,7 +344,6 @@ float BoblightClientConnection::parseFloat(const QString& s, bool *ok) const if (ok) { - //std::cout << "OK " << d << ": " << s.toUtf8().constData() << std::endl; *ok = true; } diff --git a/libsrc/cec/CECHandler.cpp b/libsrc/cec/CECHandler.cpp index f33c30c8..630fe334 100644 --- a/libsrc/cec/CECHandler.cpp +++ b/libsrc/cec/CECHandler.cpp @@ -12,7 +12,7 @@ #include /* Enable to turn on detailed CEC logs */ -// #define VERBOSE_CEC +#define NO_VERBOSE_CEC CECHandler::CECHandler() { @@ -138,9 +138,9 @@ bool CECHandler::openAdapter(const CECAdapterDescriptor & descriptor) if(!_cecAdapter->Open(descriptor.strComName)) { - Error(_logger, QString("Failed to open the CEC adaper on port %1") - .arg(descriptor.strComName) - .toLocal8Bit()); + Error(_logger, "%s", QSTRING_CSTR(QString("Failed to open the CEC adaper on port %1") + .arg(descriptor.strComName)) + ); return false; } @@ -149,9 +149,9 @@ bool CECHandler::openAdapter(const CECAdapterDescriptor & descriptor) void CECHandler::printAdapter(const CECAdapterDescriptor & descriptor) const { - Info(_logger, QString("CEC Adapter:").toLocal8Bit()); - Info(_logger, QString("\tName : %1").arg(descriptor.strComName).toLocal8Bit()); - Info(_logger, QString("\tPath : %1").arg(descriptor.strComPath).toLocal8Bit()); + Info(_logger, "%s", QSTRING_CSTR(QString("CEC Adapter:"))); + Info(_logger, "%s", QSTRING_CSTR(QString("\tName : %1").arg(descriptor.strComName))); + Info(_logger, "%s", QSTRING_CSTR(QString("\tPath : %1").arg(descriptor.strComPath))); } QString CECHandler::scan() const @@ -180,12 +180,12 @@ QString CECHandler::scan() const devices << device; - Info(_logger, QString("\tCECDevice: %1 / %2 / %3 / %4") - .arg(device["name"].toString()) - .arg(device["vendor"].toString()) - .arg(device["address"].toString()) - .arg(device["power"].toString()) - .toLocal8Bit()); + Info(_logger, "%s", QSTRING_CSTR(QString("\tCECDevice: %1 / %2 / %3 / %4") + .arg(device["name"].toString(), + device["vendor"].toString(), + device["address"].toString(), + device["power"].toString())) + ); } } @@ -305,16 +305,16 @@ void CECHandler::onCecCommandReceived(void * context, const CECCommand * command { if (command->opcode == CEC::CEC_OPCODE_SET_STREAM_PATH) { - Info(handler->_logger, QString("CEC source activated: %1") - .arg(adapter->ToString(command->initiator)) - .toLocal8Bit()); + Info(handler->_logger, "%s", QSTRING_CSTR(QString("CEC source activated: %1") + .arg(adapter->ToString(command->initiator))) + ); emit handler->cecEvent(CECEvent::On); } if (command->opcode == CEC::CEC_OPCODE_STANDBY) { - Info(handler->_logger, QString("CEC source deactivated: %1") - .arg(adapter->ToString(command->initiator)) - .toLocal8Bit()); + Info(handler->_logger, "%s", QSTRING_CSTR(QString("CEC source deactivated: %1") + .arg(adapter->ToString(command->initiator))) + ); emit handler->cecEvent(CECEvent::Off); } } diff --git a/libsrc/db/DBManager.cpp b/libsrc/db/DBManager.cpp index c2f42deb..a8711c15 100644 --- a/libsrc/db/DBManager.cpp +++ b/libsrc/db/DBManager.cpp @@ -50,7 +50,7 @@ QSqlDatabase DBManager::getDB() const db.setDatabaseName(_rootPath+"/db/"+_dbn+".db"); if(!db.open()) { - Error(_log, QSTRING_CSTR(db.lastError().text())); + Error(_log, "%s", QSTRING_CSTR(db.lastError().text())); throw std::runtime_error("Failed to open database connection!"); } return db; diff --git a/libsrc/effectengine/EffectEngine.cpp b/libsrc/effectengine/EffectEngine.cpp index a2e69918..f192df99 100644 --- a/libsrc/effectengine/EffectEngine.cpp +++ b/libsrc/effectengine/EffectEngine.cpp @@ -126,12 +126,10 @@ void EffectEngine::handleUpdatedEffectList() def.args["smoothing-time_ms"].toInt(), def.args["smoothing-updateFrequency"].toDouble(), 0 ); - //Debug( _log, "Customs Settings: Update effect %s, script %s, file %s, smoothCfg [%u]", QSTRING_CSTR(def.name), QSTRING_CSTR(def.script), QSTRING_CSTR(def.file), def.smoothCfg); } else { def.smoothCfg = SmoothingConfigID::SYSTEM; - //Debug( _log, "Default Settings: Update effect %s, script %s, file %s, smoothCfg [%u]", QSTRING_CSTR(def.name), QSTRING_CSTR(def.script), QSTRING_CSTR(def.file), def.smoothCfg); } _availableEffects.push_back(def); } diff --git a/libsrc/effectengine/EffectModule.cpp b/libsrc/effectengine/EffectModule.cpp index 29531f05..bfa4a4c4 100644 --- a/libsrc/effectengine/EffectModule.cpp +++ b/libsrc/effectengine/EffectModule.cpp @@ -53,9 +53,12 @@ PyObject *EffectModule::json2python(const QJsonValue &jsonData) Py_RETURN_NOTIMPLEMENTED; case QJsonValue::Double: { - if (std::round(jsonData.toDouble()) != jsonData.toDouble()) + double doubleIntegratlPart; + double doubleFractionalPart = std::modf(jsonData.toDouble(), &doubleIntegratlPart); + if (doubleFractionalPart > std::numeric_limits::epsilon()) + { return Py_BuildValue("d", jsonData.toDouble()); - + } return Py_BuildValue("i", jsonData.toInt()); } case QJsonValue::Bool: @@ -184,7 +187,8 @@ PyObject* EffectModule::wrapSetColor(PyObject *self, PyObject *args) PyObject* EffectModule::wrapSetImage(PyObject *self, PyObject *args) { // bytearray of values - int width, height; + int width = 0; + int height = 0; PyObject * bytearray = nullptr; if (PyArg_ParseTuple(args, "iiO", &width, &height, &bytearray)) { @@ -391,8 +395,10 @@ PyObject* EffectModule::wrapImageLinearGradient(PyObject *self, PyObject *args) int startRY = 0; int startX = 0; int startY = 0; - int endX, width = getEffect()->_imageSize.width(); - int endY, height = getEffect()->_imageSize.height(); + int width = getEffect()->_imageSize.width(); + int endX {width}; + int height = getEffect()->_imageSize.height(); + int endY {height}; int spread = 0; bool argsOK = false; @@ -454,7 +460,9 @@ PyObject* EffectModule::wrapImageConicalGradient(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); PyObject * bytearray = nullptr; - int centerX, centerY, angle; + int centerX = 0; + int centerY = 0; + int angle = 0; int startX = 0; int startY = 0; int width = getEffect()->_imageSize.width(); @@ -520,7 +528,13 @@ PyObject* EffectModule::wrapImageRadialGradient(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); PyObject * bytearray = nullptr; - int centerX, centerY, radius, focalX, focalY, focalRadius, spread; + int centerX = 0; + int centerY = 0; + int radius = 0; + int focalX = 0; + int focalY = 0; + int focalRadius =0; + int spread = 0; int startX = 0; int startY = 0; int width = getEffect()->_imageSize.width(); @@ -599,7 +613,9 @@ PyObject* EffectModule::wrapImageDrawPolygon(PyObject *self, PyObject *args) PyObject * bytearray = nullptr; int argCount = PyTuple_Size(args); - int r, g, b; + int r = 0; + int g = 0; + int b = 0; int a = 255; bool argsOK = false; @@ -658,7 +674,9 @@ PyObject* EffectModule::wrapImageDrawPie(PyObject *self, PyObject *args) QString brush; int argCount = PyTuple_Size(args); - int radius, centerX, centerY; + int radius = 0; + int centerX = 0; + int centerY = 0; int startAngle = 0; int spanAngle = 360; int r = 0; @@ -749,7 +767,9 @@ PyObject* EffectModule::wrapImageDrawPie(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageSolidFill(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); - int r, g, b; + int r = 0; + int g = 0; + int b = 0; int a = 255; int startX = 0; int startY = 0; @@ -788,8 +808,10 @@ PyObject* EffectModule::wrapImageSolidFill(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageDrawLine(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); - int r, g, b; - int a = 255; + int r = 0; + int g = 0; + int b = 0; + int a = 255; int startX = 0; int startY = 0; int thick = 1; @@ -826,8 +848,12 @@ PyObject* EffectModule::wrapImageDrawLine(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageDrawPoint(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); - int r, g, b, x, y; - int a = 255; + int r = 0; + int g = 0; + int b = 0; + int x = 0; + int y = 0; + int a = 255; int thick = 1; bool argsOK = false; @@ -859,8 +885,10 @@ PyObject* EffectModule::wrapImageDrawPoint(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageDrawRect(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); - int r, g, b; - int a = 255; + int r = 0; + int g = 0; + int b = 0; + int a = 255; int startX = 0; int startY = 0; int thick = 1; @@ -898,7 +926,11 @@ PyObject* EffectModule::wrapImageDrawRect(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageSetPixel(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); - int r, g, b, x, y; + int r = 0; + int g = 0; + int b = 0; + int x = 0; + int y = 0; if ( argCount == 5 && PyArg_ParseTuple(args, "iiiii", &x, &y, &r, &g, &b ) ) { @@ -913,7 +945,8 @@ PyObject* EffectModule::wrapImageSetPixel(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageGetPixel(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); - int x, y; + int x = 0; + int y = 0; if ( argCount == 2 && PyArg_ParseTuple(args, "ii", &x, &y) ) { @@ -934,7 +967,8 @@ PyObject* EffectModule::wrapImageSave(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageMinSize(PyObject *self, PyObject *args) { int argCount = PyTuple_Size(args); - int w, h; + int w = 0; + int h = 0; int width = getEffect()->_imageSize.width(); int height = getEffect()->_imageSize.height(); @@ -994,7 +1028,8 @@ PyObject* EffectModule::wrapImageCOffset(PyObject *self, PyObject *args) PyObject* EffectModule::wrapImageCShear(PyObject *self, PyObject *args) { - int sh,sv; + int sh = 0; + int sv = 0; int argCount = PyTuple_Size(args); if ( argCount == 2 && PyArg_ParseTuple(args, "ii", &sh, &sv )) diff --git a/libsrc/forwarder/MessageForwarder.cpp b/libsrc/forwarder/MessageForwarder.cpp index 0070f2e4..e9dc40f9 100644 --- a/libsrc/forwarder/MessageForwarder.cpp +++ b/libsrc/forwarder/MessageForwarder.cpp @@ -138,7 +138,7 @@ void MessageForwarder::enableTargets(bool enable, const QJsonObject& config) else { _forwarder_enabled = false; - Warning(_log,"No JSON- nor Flatbuffer-Forwarder configured -> Forwarding disabled", _forwarder_enabled); + Warning(_log,"No JSON- nor Flatbuffer-Forwarder configured -> Forwarding disabled"); } } _hyperion->setNewComponentState(hyperion::COMP_FORWARDER, _forwarder_enabled); diff --git a/libsrc/grabber/video/EncoderThread.cpp b/libsrc/grabber/video/EncoderThread.cpp index b2ece680..1de36ff7 100644 --- a/libsrc/grabber/video/EncoderThread.cpp +++ b/libsrc/grabber/video/EncoderThread.cpp @@ -223,13 +223,11 @@ void EncoderThread::processImageMjpeg() { _xform->options = TJXOPT_CROP; _xform->r = tjregion {_cropLeft,_cropTop,transformedWidth,transformedHeight}; - //qDebug() << "processImageMjpeg() | _doTransform - Image cropped: transformedWidth: " << transformedWidth << " transformedHeight: " << transformedHeight; } else { _xform->options = 0; _xform->r = tjregion {0,0,_width,_height}; - //qDebug() << "processImageMjpeg() | _doTransform - Image not cropped: _width: " << _width << " _height: " << _height; } _xform->options |= TJXOPT_TRIM; @@ -344,11 +342,9 @@ bool EncoderThread::onError(const QString context) const #if LIBJPEG_TURBO_VERSION_NUMBER > 2000000 if (tjGetErrorCode(_tjInstance) == TJERR_FATAL) { - //qDebug() << context << "Error: " << QString(tjGetErrorStr2(_tjInstance)); treatAsError = true; } #else - //qDebug() << context << "Error: " << QString(tjGetErrorStr()); treatAsError = true; #endif diff --git a/libsrc/grabber/video/v4l2/V4L2Grabber.cpp b/libsrc/grabber/video/v4l2/V4L2Grabber.cpp index 4ae3b9f2..a0caa19d 100644 --- a/libsrc/grabber/video/v4l2/V4L2Grabber.cpp +++ b/libsrc/grabber/video/v4l2/V4L2Grabber.cpp @@ -1209,7 +1209,7 @@ void V4L2Grabber::setCecDetectionEnable(bool enable) { _cecDetectionEnabled = enable; if(_initialized) - Info(_log, QString("CEC detection is now %1").arg(enable ? "enabled" : "disabled").toLocal8Bit()); + Info(_log, "%s", QSTRING_CSTR(QString("CEC detection is now %1").arg(enable ? "enabled" : "disabled"))); } } @@ -1501,19 +1501,19 @@ void V4L2Grabber::enumVideoCaptureDevices() // Enumerate video control IDs QList deviceControlList; - for (auto it = _controlIDPropertyMap->constBegin(); it != _controlIDPropertyMap->constEnd(); it++) + for (auto itDeviceControls = _controlIDPropertyMap->constBegin(); itDeviceControls != _controlIDPropertyMap->constEnd(); itDeviceControls++) { struct v4l2_queryctrl queryctrl; CLEAR(queryctrl); - queryctrl.id = it.key(); + queryctrl.id = itDeviceControls.key(); if (xioctl(fd, VIDIOC_QUERYCTRL, &queryctrl) < 0) break; if (queryctrl.flags & V4L2_CTRL_FLAG_DISABLED) break; DeviceControls control; - control.property = it.value(); + control.property = itDeviceControls.value(); control.minValue = queryctrl.minimum; control.maxValue = queryctrl.maximum; control.step = queryctrl.step; @@ -1524,13 +1524,13 @@ void V4L2Grabber::enumVideoCaptureDevices() CLEAR(ctrl); CLEAR(ctrls); - ctrl.id = it.key(); + ctrl.id = itDeviceControls.key(); ctrls.count = 1; ctrls.controls = &ctrl; if (xioctl(fd, VIDIOC_G_EXT_CTRLS, &ctrls) == 0) { control.currentValue = ctrl.value; - DebugIf(verbose, _log, "%s: min=%i, max=%i, step=%i, default=%i, current=%i", QSTRING_CSTR(it.value()), control.minValue, control.maxValue, control.step, control.defaultValue, control.currentValue); + DebugIf(verbose, _log, "%s: min=%i, max=%i, step=%i, default=%i, current=%i", QSTRING_CSTR(itDeviceControls.value()), control.minValue, control.maxValue, control.step, control.defaultValue, control.currentValue); } else break; diff --git a/libsrc/grabber/x11/X11Grabber.cpp b/libsrc/grabber/x11/X11Grabber.cpp index bb016480..46c7faa4 100644 --- a/libsrc/grabber/x11/X11Grabber.cpp +++ b/libsrc/grabber/x11/X11Grabber.cpp @@ -170,12 +170,12 @@ bool X11Grabber::setupDisplay() XShmQueryVersion(_x11Display, &dummy, &dummy, &pixmaps_supported); _XShmPixmapAvailable = pixmaps_supported && XShmPixmapFormat(_x11Display) == ZPixmap; - Info(_log, QString("XRandR=[%1] XRender=[%2] XShm=[%3] XPixmap=[%4]") - .arg(_XRandRAvailable ? "available" : "unavailable") - .arg(_XRenderAvailable ? "available" : "unavailable") - .arg(_XShmAvailable ? "available" : "unavailable") - .arg(_XShmPixmapAvailable ? "available" : "unavailable") - .toStdString().c_str()); + Info(_log, "%s", QSTRING_CSTR(QString("XRandR=[%1] XRender=[%2] XShm=[%3] XPixmap=[%4]") + .arg(_XRandRAvailable ? "available" : "unavailable", + _XRenderAvailable ? "available" : "unavailable", + _XShmAvailable ? "available" : "unavailable", + _XShmPixmapAvailable ? "available" : "unavailable")) + ); result = (updateScreenDimensions(true) >=0); ErrorIf(!result, _log, "X11 Grabber start failed"); diff --git a/libsrc/grabber/xcb/XcbGrabber.cpp b/libsrc/grabber/xcb/XcbGrabber.cpp index 5e791fea..a5fc97f9 100644 --- a/libsrc/grabber/xcb/XcbGrabber.cpp +++ b/libsrc/grabber/xcb/XcbGrabber.cpp @@ -242,12 +242,12 @@ bool XcbGrabber::setupDisplay() setupRender(); setupShm(); - Info(_log, QString("XcbRandR=[%1] XcbRender=[%2] XcbShm=[%3] XcbPixmap=[%4]") - .arg(_XcbRandRAvailable ? "available" : "unavailable") - .arg(_XcbRenderAvailable ? "available" : "unavailable") - .arg(_XcbShmAvailable ? "available" : "unavailable") - .arg(_XcbShmPixmapAvailable ? "available" : "unavailable") - .toStdString().c_str()); + Info(_log, "%s", QSTRING_CSTR(QString("XcbRandR=[%1] XcbRender=[%2] XcbShm=[%3] XcbPixmap=[%4]") + .arg(_XcbRandRAvailable ? "available" : "unavailable", + _XcbRenderAvailable ? "available" : "unavailable", + _XcbShmAvailable ? "available" : "unavailable", + _XcbShmPixmapAvailable ? "available" : "unavailable")) + ); result = (updateScreenDimensions(true) >= 0); ErrorIf(!result, _log, "XCB Grabber start failed"); diff --git a/libsrc/hyperion/AuthManager.cpp b/libsrc/hyperion/AuthManager.cpp index 329b387d..931443a7 100644 --- a/libsrc/hyperion/AuthManager.cpp +++ b/libsrc/hyperion/AuthManager.cpp @@ -261,26 +261,24 @@ void AuthManager::checkTimeout() void AuthManager::checkAuthBlockTimeout() { // handle user auth block - for (auto it = _userAuthAttempts.begin(); it != _userAuthAttempts.end(); it++) - { + QMutableVectorIterator itUserAuth(_userAuthAttempts); + while (itUserAuth.hasNext()) { // after 10 minutes, we remove the entry - if (*it < (uint64_t)QDateTime::currentMSecsSinceEpoch()) - { - _userAuthAttempts.erase(it--); - } + if (itUserAuth.next() < static_cast(QDateTime::currentMSecsSinceEpoch())) + itUserAuth.remove(); } // handle token auth block - for (auto it = _tokenAuthAttempts.begin(); it != _tokenAuthAttempts.end(); it++) - { + QMutableVectorIterator itTokenAuth(_tokenAuthAttempts); + while (itTokenAuth.hasNext()) { // after 10 minutes, we remove the entry - if (*it < (uint64_t)QDateTime::currentMSecsSinceEpoch()) - { - _tokenAuthAttempts.erase(it--); - } + if (itTokenAuth.next() < static_cast(QDateTime::currentMSecsSinceEpoch())) + itTokenAuth.remove(); } // if the lists are empty we stop if (_userAuthAttempts.empty() && _tokenAuthAttempts.empty()) + { _authBlockTimer->stop(); + } } diff --git a/libsrc/hyperion/Hyperion.cpp b/libsrc/hyperion/Hyperion.cpp index 52216f02..7107611e 100644 --- a/libsrc/hyperion/Hyperion.cpp +++ b/libsrc/hyperion/Hyperion.cpp @@ -233,9 +233,6 @@ void Hyperion::freeObjects() void Hyperion::handleSettingsUpdate(settings::type type, const QJsonDocument& config) { -// std::cout << "Hyperion::handleSettingsUpdate" << std::endl; -// std::cout << config.toJson().toStdString() << std::endl; - if(type == settings::COLOR) { const QJsonObject obj = config.object(); diff --git a/libsrc/hyperion/LinearColorSmoothing.cpp b/libsrc/hyperion/LinearColorSmoothing.cpp index c91309b0..4cf6d4b9 100644 --- a/libsrc/hyperion/LinearColorSmoothing.cpp +++ b/libsrc/hyperion/LinearColorSmoothing.cpp @@ -406,7 +406,6 @@ void LinearColorSmoothing::performDecay(const int64_t now) { if(microsTillNextAction > SLEEP_RES_MICROS) { const int64_t wait = std::min(microsTillNextAction - SLEEP_RES_MICROS, SLEEP_MAX_MICROS); - //usleep(wait); std::this_thread::sleep_for(std::chrono::microseconds(wait)); } } @@ -542,7 +541,6 @@ void LinearColorSmoothing::queueColors(const std::vector &ledColors) void LinearColorSmoothing::clearQueuedColors() { _timer->stop(); - //QMetaObject::invokeMethod(_timer, "stop", Qt::QueuedConnection); _previousValues.clear(); _targetValues.clear(); diff --git a/libsrc/hyperion/MultiColorAdjustment.cpp b/libsrc/hyperion/MultiColorAdjustment.cpp index dabdac0c..4c761d6a 100644 --- a/libsrc/hyperion/MultiColorAdjustment.cpp +++ b/libsrc/hyperion/MultiColorAdjustment.cpp @@ -42,11 +42,8 @@ void MultiColorAdjustment::setAdjustmentForLed(const QString& id, int startLed, // Get the identified adjustment (don't care if is nullptr) ColorAdjustment * adjustment = getAdjustment(id); - - //Debug(_log,"ColorAdjustment Profile [%s], startLed[%d], endLed[%d]", QSTRING_CSTR(id), startLed, endLed); for (int iLed=startLed; iLed<=endLed; ++iLed) { - //Debug(_log,"_ledAdjustments [%d] -> [%p]", iLed, adjustment); _ledAdjustments[iLed] = adjustment; } } diff --git a/libsrc/hyperion/schema/schema-webConfig.json b/libsrc/hyperion/schema/schema-webConfig.json index 17d9e60d..15532f78 100644 --- a/libsrc/hyperion/schema/schema-webConfig.json +++ b/libsrc/hyperion/schema/schema-webConfig.json @@ -16,7 +16,7 @@ "title" : "edt_conf_general_port_title", "minimum" : 80, "maximum" : 65535, - "default" : 8090, + "default" : 8090.3, "propertyOrder" : 3 }, "sslPort" : diff --git a/libsrc/leddevice/LedDevice.cpp b/libsrc/leddevice/LedDevice.cpp index 6e1796d9..b30dd4fd 100644 --- a/libsrc/leddevice/LedDevice.cpp +++ b/libsrc/leddevice/LedDevice.cpp @@ -234,8 +234,6 @@ void LedDevice::startRefreshTimer() connect(_refreshTimer, &QTimer::timeout, this, &LedDevice::rewriteLEDs); } _refreshTimer->setInterval(_refreshTimerInterval_ms); - - //Debug(_log, "Start refresh timer with interval = %ims", _refreshTimer->interval()); _refreshTimer->start(); } else @@ -249,11 +247,9 @@ void LedDevice::stopRefreshTimer() { if (_refreshTimer != nullptr) { - //Debug(_log, "Stopping refresh timer"); _refreshTimer->stop(); delete _refreshTimer; _refreshTimer = nullptr; - } } @@ -302,7 +298,7 @@ int LedDevice::updateLeds(std::vector ledValues) int retval = 0; if (!_isEnabled || !_isOn || !_isDeviceReady || _isDeviceInError) { - //std::cout << "LedDevice::updateLeds(), LedDevice NOT ready! "; + // LedDevice NOT ready! retval = -1; } else @@ -310,7 +306,6 @@ int LedDevice::updateLeds(std::vector ledValues) qint64 elapsedTimeMs = _lastWriteTime.msecsTo(QDateTime::currentDateTime()); if (_latchTime_ms == 0 || elapsedTimeMs >= _latchTime_ms) { - //std::cout << "LedDevice::updateLeds(), Elapsed time since last write (" << elapsedTimeMs << ") ms > _latchTime_ms (" << _latchTime_ms << ") ms" << std::endl; retval = write(ledValues); _lastWriteTime = QDateTime::currentDateTime(); @@ -323,7 +318,7 @@ int LedDevice::updateLeds(std::vector ledValues) } else { - //std::cout << "LedDevice::updateLeds(), Skip write. elapsedTime (" << elapsedTimeMs << ") ms < _latchTime_ms (" << _latchTime_ms << ") ms" << std::endl; + // Skip write as elapsedTime < latchTime if (_isRefreshEnabled) { //Stop timer to allow for next non-refresh update @@ -340,14 +335,6 @@ int LedDevice::rewriteLEDs() if (_isEnabled && _isOn && _isDeviceReady && !_isDeviceInError) { - // qint64 elapsedTimeMs = _lastWriteTime.msecsTo(QDateTime::currentDateTime()); - // std::cout << "LedDevice::rewriteLEDs(): Rewrite LEDs now, elapsedTime [" << elapsedTimeMs << "] ms" << std::endl; - // //:TESTING: Inject "white" output records to differentiate from normal writes - // _lastLedValues.clear(); - // _lastLedValues.resize(static_cast(_ledCount), ColorRgb::WHITE); - // printLedValues(_lastLedValues); - // //:TESTING: - if (!_lastLedValues.empty()) { retval = write(_lastLedValues); @@ -490,12 +477,15 @@ bool LedDevice::storeState() { bool rc{ true }; +#if 0 if (_isRestoreOrigState) { // Save device's original state // _originalStateValues = get device's state; // store original power on/off state, if available } +#endif + return rc; } @@ -503,12 +493,14 @@ bool LedDevice::restoreState() { bool rc{ true }; +#if 0 if (_isRestoreOrigState) { // Restore device's original state // update device using _originalStateValues // update original power on/off state, if supported } +#endif return rc; } @@ -699,4 +691,3 @@ QString LedDevice::getColorOrder() const bool LedDevice::componentState() const { return _isEnabled; } - diff --git a/libsrc/leddevice/LedDeviceTemplate.cpp b/libsrc/leddevice/LedDeviceTemplate.cpp index 143b7277..299569ba 100644 --- a/libsrc/leddevice/LedDeviceTemplate.cpp +++ b/libsrc/leddevice/LedDeviceTemplate.cpp @@ -69,12 +69,14 @@ int LedDeviceTemplate::close() int retval = 0; _isDeviceReady = false; +#if 0 // Test, if device requires closing if ( true /*If device is still open*/ ) { // Close device // Everything is OK -> device is closed } +#endif return retval; } diff --git a/libsrc/leddevice/dev_hid/LedDeviceHyperionUsbasp.cpp b/libsrc/leddevice/dev_hid/LedDeviceHyperionUsbasp.cpp index a5f0dfb2..d96ed85c 100644 --- a/libsrc/leddevice/dev_hid/LedDeviceHyperionUsbasp.cpp +++ b/libsrc/leddevice/dev_hid/LedDeviceHyperionUsbasp.cpp @@ -63,7 +63,9 @@ bool LedDeviceHyperionUsbasp::init(const QJsonObject &deviceConfig) else { Debug(_log, "USB context initialized"); - //libusb_set_debug(_libusbContext, 3); +#if 0 + libusb_set_debug(_libusbContext, 3); +#endif // retrieve the list of USB devices libusb_device ** deviceList; diff --git a/libsrc/leddevice/dev_hid/LedDeviceLightpack.cpp b/libsrc/leddevice/dev_hid/LedDeviceLightpack.cpp index 88b9722b..08ef0f0a 100644 --- a/libsrc/leddevice/dev_hid/LedDeviceLightpack.cpp +++ b/libsrc/leddevice/dev_hid/LedDeviceLightpack.cpp @@ -331,8 +331,6 @@ const QString &LedDeviceLightpack::getSerialNumber() const int LedDeviceLightpack::writeBytes(uint8_t *data, int size) { int rc = 0; - //Debug( _log, "[%s]", QSTRING_CSTR(uint8_t_to_hex_string(data, size, 32)) ); - int error = libusb_control_transfer(_deviceHandle, static_cast( LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_CLASS | LIBUSB_RECIPIENT_INTERFACE ), 0x09, diff --git a/libsrc/leddevice/dev_hid/ProviderHID.cpp b/libsrc/leddevice/dev_hid/ProviderHID.cpp index d29c0f94..6bea6e63 100644 --- a/libsrc/leddevice/dev_hid/ProviderHID.cpp +++ b/libsrc/leddevice/dev_hid/ProviderHID.cpp @@ -73,8 +73,8 @@ int ProviderHID::open() // Failed to open the device this->setInError( "Failed to open HID device. Maybe your PID/VID setting is wrong? Make sure to add a udev rule/use sudo." ); +#if 0 // http://www.signal11.us/oss/hidapi/ - /* std::cout << "Showing a list of all available HID devices:" << std::endl; auto devs = hid_enumerate(0x00, 0x00); auto cur_dev = devs; @@ -88,7 +88,8 @@ int ProviderHID::open() cur_dev = cur_dev->next; } hid_free_enumeration(devs); - */ +#endif + } else { diff --git a/libsrc/leddevice/dev_net/LedDeviceNanoleaf.cpp b/libsrc/leddevice/dev_net/LedDeviceNanoleaf.cpp index 62ba1fe3..f895cba6 100644 --- a/libsrc/leddevice/dev_net/LedDeviceNanoleaf.cpp +++ b/libsrc/leddevice/dev_net/LedDeviceNanoleaf.cpp @@ -45,7 +45,6 @@ const char PANEL_NUM[] = "numPanels"; const char PANEL_ID[] = "panelId"; const char PANEL_POSITIONDATA[] = "positionData"; const char PANEL_SHAPE_TYPE[] = "shapeType"; -//const char PANEL_ORIENTATION[] = "0"; const char PANEL_POS_X[] = "x"; const char PANEL_POS_Y[] = "y"; @@ -72,7 +71,6 @@ const quint16 STREAM_CONTROL_DEFAULT_PORT = 60222; const int API_DEFAULT_PORT = 16021; const char API_BASE_PATH[] = "/api/v1/%1/"; const char API_ROOT[] = ""; -//const char API_EXT_MODE_STRING_V1[] = "{\"write\" : {\"command\" : \"display\", \"animType\" : \"extControl\"}}"; const char API_EXT_MODE_STRING_V2[] = "{\"write\" : {\"command\" : \"display\", \"animType\" : \"extControl\", \"extControlVersion\" : \"v2\"}}"; const char API_STATE[] = "state"; const char API_PANELLAYOUT[] = "panelLayout"; @@ -243,7 +241,6 @@ bool LedDeviceNanoleaf::initLedsConfiguration() int panelX = panelObj[PANEL_POS_X].toInt(); int panelY = panelObj[PANEL_POS_Y].toInt(); int panelshapeType = panelObj[PANEL_SHAPE_TYPE].toInt(); - //int panelOrientation = panelObj[PANEL_ORIENTATION].toInt(); DebugIf(verbose,_log, "Panel [%d] (%d,%d) - Type: [%d]", panelId, panelX, panelY, panelshapeType); @@ -613,16 +610,16 @@ bool LedDeviceNanoleaf::storeState() // effect _restApi->setPath(API_EFFECT); - httpResponse response = _restApi->get(); - if ( response.error() ) + httpResponse responseEffects = _restApi->get(); + if ( responseEffects.error() ) { - QString errorReason = QString("Storing device state failed with error: '%1'").arg(response.getErrorReason()); + QString errorReason = QString("Storing device state failed with error: '%1'").arg(responseEffects.getErrorReason()); setInError(errorReason); rc = false; } else { - QJsonObject effects = response.getBody().object(); + QJsonObject effects = responseEffects.getBody().object(); DebugIf(verbose, _log, "effects: [%s]", QString(QJsonDocument(_originalStateProperties).toJson(QJsonDocument::Compact)).toUtf8().constData() ); _originalEffect = effects[API_EFFECT_SELECT].toString(); _originalIsDynEffect = _originalEffect == "*Dynamic*" || _originalEffect == "*Solid*"; @@ -774,7 +771,7 @@ int LedDeviceNanoleaf::write(const std::vector& ledValues) } else { - // Set panels not configured to black; + // Set panels not configured to black color = ColorRgb::BLACK; DebugIf(verbose3, _log, "[%d] >= panelLedCount [%d] => Set to BLACK", panelCounter, _panelLedCount); } diff --git a/libsrc/leddevice/dev_net/LedDevicePhilipsHue.cpp b/libsrc/leddevice/dev_net/LedDevicePhilipsHue.cpp index 4ceda587..8f73ae5f 100644 --- a/libsrc/leddevice/dev_net/LedDevicePhilipsHue.cpp +++ b/libsrc/leddevice/dev_net/LedDevicePhilipsHue.cpp @@ -38,7 +38,6 @@ const char CONFIG_VERBOSE[] = "verbose"; const char DEV_DATA_BRIDGEID[] = "bridgeid"; const char DEV_DATA_MODEL[] = "modelid"; const char DEV_DATA_NAME[] = "name"; -//const char DEV_DATA_MANUFACTURER[] = "manufacturer"; const char DEV_DATA_FIRMWAREVERSION[] = "swversion"; const char DEV_DATA_APIVERSION[] = "apiversion"; @@ -65,7 +64,6 @@ const char API_STREAM_RESPONSE_FORMAT[] = "/%1/%2/%3/%4"; // List of resources const char API_XY_COORDINATES[] = "xy"; const char API_BRIGHTNESS[] = "bri"; -//const char API_SATURATION[] = "sat"; const char API_TRANSITIONTIME[] = "transitiontime"; const char API_MODEID[] = "modelid"; @@ -188,7 +186,6 @@ CiColor CiColor::rgbToCiColor(double red, double green, double blue, const CiCol } if (dBC < lowest) { - //lowest = dBC; closestPoint = pBC; } // Change the xy value to a value which is within the reach of the lamp. @@ -1089,7 +1086,7 @@ bool LedDevicePhilipsHue::init(const QJsonObject &deviceConfig) if( _groupId == 0 ) { - Error(_log, "Disabling usage of HueEntertainmentAPI: Group-ID is invalid", "%d", _groupId); + Error(_log, "Disabling usage of HueEntertainmentAPI: Group-ID [%d] is invalid", _groupId); _useHueEntertainmentAPI = false; } } diff --git a/libsrc/leddevice/dev_net/LedDeviceRazer.cpp b/libsrc/leddevice/dev_net/LedDeviceRazer.cpp index 697b5c92..6f01098b 100644 --- a/libsrc/leddevice/dev_net/LedDeviceRazer.cpp +++ b/libsrc/leddevice/dev_net/LedDeviceRazer.cpp @@ -141,10 +141,6 @@ bool LedDeviceRazer::checkApiError(const httpResponse& response) else { QString errorReason; - - QString strJson(response.getBody().toJson(QJsonDocument::Compact)); - //DebugIf(verbose, _log, "Reply: [%s]", strJson.toUtf8().constData()); - QJsonObject jsonObj = response.getBody().object(); if (!jsonObj[API_RESULT].isNull()) diff --git a/libsrc/leddevice/dev_net/LedDeviceUdpE131.cpp b/libsrc/leddevice/dev_net/LedDeviceUdpE131.cpp index 65cebf78..1be48dc3 100644 --- a/libsrc/leddevice/dev_net/LedDeviceUdpE131.cpp +++ b/libsrc/leddevice/dev_net/LedDeviceUdpE131.cpp @@ -20,15 +20,20 @@ const ushort E131_DEFAULT_PORT = 5568; /* defined parameters from http://tsp.esta.org/tsp/documents/docs/BSR_E1-31-20xx_CP-2014-1009r2.pdf */ const uint32_t VECTOR_ROOT_E131_DATA = 0x00000004; -//#define VECTOR_ROOT_E131_EXTENDED 0x00000008 + const uint8_t VECTOR_DMP_SET_PROPERTY = 0x02; const uint32_t VECTOR_E131_DATA_PACKET = 0x00000002; -//#define VECTOR_E131_EXTENDED_SYNCHRONIZATION 0x00000001 -//#define VECTOR_E131_EXTENDED_DISCOVERY 0x00000002 -//#define VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST 0x00000001 -//#define E131_E131_UNIVERSE_DISCOVERY_INTERVAL 10 // seconds -//#define E131_NETWORK_DATA_LOSS_TIMEOUT 2500 // milli econds -//#define E131_DISCOVERY_UNIVERSE 64214 + +#if 0 +#define VECTOR_ROOT_E131_EXTENDED 0x00000008 +#define VECTOR_E131_EXTENDED_SYNCHRONIZATION 0x00000001 +#define VECTOR_E131_EXTENDED_DISCOVERY 0x00000002 +#define VECTOR_UNIVERSE_DISCOVERY_UNIVERSE_LIST 0x00000001 +#define E131_E131_UNIVERSE_DISCOVERY_INTERVAL 10 // seconds +#define E131_NETWORK_DATA_LOSS_TIMEOUT 2500 // milli econds +#define E131_DISCOVERY_UNIVERSE 64214 +#endif + const int DMX_MAX = 512; // 512 usable slots } diff --git a/libsrc/leddevice/dev_net/LedDeviceUdpE131.h b/libsrc/leddevice/dev_net/LedDeviceUdpE131.h index 12ec50e2..0397eeda 100644 --- a/libsrc/leddevice/dev_net/LedDeviceUdpE131.h +++ b/libsrc/leddevice/dev_net/LedDeviceUdpE131.h @@ -20,28 +20,30 @@ **/ /* E1.31 Packet Offsets */ -//#define E131_ROOT_PREAMBLE_SIZE 0 -//#define E131_ROOT_POSTAMBLE_SIZE 2 -//#define E131_ROOT_ID 4 -//#define E131_ROOT_FLENGTH 16 -//#define E131_ROOT_VECTOR 18 -//#define E131_ROOT_CID 22 +#if 0 +#define E131_ROOT_PREAMBLE_SIZE 0 +#define E131_ROOT_POSTAMBLE_SIZE 2 +#define E131_ROOT_ID 4 +#define E131_ROOT_FLENGTH 16 +#define E131_ROOT_VECTOR 18 +#define E131_ROOT_CID 22 -//#define E131_FRAME_FLENGTH 38 -//#define E131_FRAME_VECTOR 40 -//#define E131_FRAME_SOURCE 44 -//#define E131_FRAME_PRIORITY 108 -//#define E131_FRAME_RESERVED 109 -//#define E131_FRAME_SEQ 111 -//#define E131_FRAME_OPT 112 -//#define E131_FRAME_UNIVERSE 113 +#define E131_FRAME_FLENGTH 38 +#define E131_FRAME_VECTOR 40 +#define E131_FRAME_SOURCE 44 +#define E131_FRAME_PRIORITY 108 +#define E131_FRAME_RESERVED 109 +#define E131_FRAME_SEQ 111 +#define E131_FRAME_OPT 112 +#define E131_FRAME_UNIVERSE 113 -//#define E131_DMP_FLENGTH 115 -//#define E131_DMP_VECTOR 117 -//#define E131_DMP_TYPE 118 -//#define E131_DMP_ADDR_FIRST 119 -//#define E131_DMP_ADDR_INC 121 -//#define E131_DMP_COUNT 123 +#define E131_DMP_FLENGTH 115 +#define E131_DMP_VECTOR 117 +#define E131_DMP_TYPE 118 +#define E131_DMP_ADDR_FIRST 119 +#define E131_DMP_ADDR_INC 121 +#define E131_DMP_COUNT 123 +#endif const unsigned int E131_DMP_DATA=125; /* E1.31 Packet Structure */ diff --git a/libsrc/leddevice/dev_net/LedDeviceWled.cpp b/libsrc/leddevice/dev_net/LedDeviceWled.cpp index 8c772545..9483c3d4 100644 --- a/libsrc/leddevice/dev_net/LedDeviceWled.cpp +++ b/libsrc/leddevice/dev_net/LedDeviceWled.cpp @@ -40,7 +40,6 @@ const char WLED_VERSION_DDP[] = "0.11.0"; const int API_DEFAULT_PORT = -1; //Use default port per communication scheme const char API_BASE_PATH[] = "/json/"; -//const char API_PATH_INFO[] = "info"; const char API_PATH_STATE[] = "state"; // List of State Information @@ -415,7 +414,7 @@ QJsonObject LedDeviceWled::getProperties(const QJsonObject& params) } else { - Info(_log, "DDP streaming is supported by your WLED device version [%s]. No limitation in number of LEDs.", currentVersion.getVersion().c_str(), ddpVersion.getVersion().c_str()); + Info(_log, "DDP streaming is supported by your WLED device version [%s]. No limitation in number of LEDs.", currentVersion.getVersion().c_str()); } } properties.insert("properties", propertiesDetails); diff --git a/libsrc/leddevice/dev_net/LedDeviceYeelight.cpp b/libsrc/leddevice/dev_net/LedDeviceYeelight.cpp index 55bdfdf4..8c0490ce 100644 --- a/libsrc/leddevice/dev_net/LedDeviceYeelight.cpp +++ b/libsrc/leddevice/dev_net/LedDeviceYeelight.cpp @@ -82,7 +82,6 @@ const char API_PROP_BRIGHT[] = "bright"; // List of Result Information const char API_RESULT_ID[] = "id"; const char API_RESULT[] = "result"; -//const char API_RESULT_OK[] = "OK"; // List of Error Information const char API_ERROR[] = "error"; @@ -383,8 +382,6 @@ bool YeelightLight::streamCommand( const QJsonDocument &command ) { log ( 2, "Info:", "Skip write. Device is in error"); } - - //log (2,"streamCommand() rc","%d, isON[%d], isInMusicMode[%d]", rc, _isOn, _isInMusicMode ); return rc; } @@ -392,8 +389,6 @@ YeelightResponse YeelightLight::handleResponse(int correlationID, QByteArray con { log (3,"handleResponse()","" ); - //std::cout << _name.toStdString() <<"| Response: [" << response.toStdString() << "]" << std::endl << std::flush; - YeelightResponse yeeResponse; QString errorReason; @@ -446,8 +441,6 @@ YeelightResponse YeelightLight::handleResponse(int correlationID, QByteArray con else { int id = jsonObj[API_RESULT_ID].toInt(); - //log ( 3, "Correlation ID:", "%d", id ); - if ( id != correlationID && TEST_CORRELATION_IDS) { errorReason = QString ("%1| API is out of sync, received ID [%2], expected [%3]"). @@ -528,9 +521,6 @@ QJsonObject YeelightLight::getProperties() log (3,"getProperties()","" ); QJsonObject properties; - //Selected properties - //QJsonArray propertyList = { API_PROP_NAME, API_PROP_MODEL, API_PROP_POWER, API_PROP_RGB, API_PROP_BRIGHT, API_PROP_CT, API_PROP_FWVER }; - //All properties QJsonArray propertyList = {"power","bright","ct","rgb","hue","sat","color_mode","flowing","delayoff","music_on","name","bg_power","bg_flowing","bg_ct","bg_bright","bg_hue","bg_sat","bg_rgb","nl_br","active_mode" }; @@ -579,9 +569,6 @@ bool YeelightLight::identify() */ QJsonArray colorflowParams = { API_PROP_COLORFLOW, 6, 0, "500,1,100,100,500,1,16711696,10"}; - //Blink White - //QJsonArray colorflowParams = { API_PROP_COLORFLOW, 6, 0, "500,2,4000,1,500,2,4000,50"}; - QJsonDocument command = getCommand( API_METHOD_SETSCENE, colorflowParams ); if ( writeCommand( command ) < 0 ) @@ -819,7 +806,6 @@ bool YeelightLight::setColorRGB(const ColorRgb &color) rc = false; } } - //log (2,"setColorRGB() rc","%d, isON[%d], isInMusicMode[%d]", rc, _isOn, _isInMusicMode ); return rc; } @@ -914,7 +900,7 @@ bool YeelightLight::setColorHSV(const ColorRgb &colorRGB) } else { - //log ( 3, "setColorHSV", "Skip update. Same Color as before"); + // Skip update. Same Color as before } log( 3, "setColorHSV() rc", @@ -1471,7 +1457,6 @@ void LedDeviceYeelight::identify(const QJsonObject& params) int LedDeviceYeelight::write(const std::vector & ledValues) { - //DebugIf(verbose, _log, "enabled [%d], _isDeviceReady [%d]", _isEnabled, _isDeviceReady); int rc = -1; //Update on all Yeelights by iterating through lights and set colors. @@ -1545,8 +1530,5 @@ int LedDeviceYeelight::write(const std::vector & ledValues) // Minimum one Yeelight device is working, continue updating devices rc = 0; } - - //DebugIf(verbose, _log, "rc [%d]", rc ); - return rc; } diff --git a/libsrc/leddevice/dev_net/LedDeviceYeelight.h b/libsrc/leddevice/dev_net/LedDeviceYeelight.h index ab99d0bd..4e8f3257 100644 --- a/libsrc/leddevice/dev_net/LedDeviceYeelight.h +++ b/libsrc/leddevice/dev_net/LedDeviceYeelight.h @@ -24,7 +24,6 @@ const char API_METHOD_MUSIC_MODE[] = "set_music"; const int API_METHOD_MUSIC_MODE_ON = 1; const int API_METHOD_MUSIC_MODE_OFF = 0; -const char API_METHOD_SETRGB[] = "set_rgb"; const char API_METHOD_SETSCENE[] = "set_scene"; const char API_METHOD_GETPROP[] = "get_prop"; diff --git a/libsrc/leddevice/dev_net/ProviderRestApi.cpp b/libsrc/leddevice/dev_net/ProviderRestApi.cpp index b1fe965e..0d318e56 100644 --- a/libsrc/leddevice/dev_net/ProviderRestApi.cpp +++ b/libsrc/leddevice/dev_net/ProviderRestApi.cpp @@ -16,10 +16,12 @@ namespace { const QChar ONE_SLASH = '/'; -const int HTTP_STATUS_NO_CONTENT = 204; -const int HTTP_STATUS_BAD_REQUEST = 400; -const int HTTP_STATUS_UNAUTHORIZED = 401; -const int HTTP_STATUS_NOT_FOUND = 404; +enum HttpStatusCode { + NoContent = 204, + BadRequest = 400, + UnAuthorized = 401, + NotFound = 404 +}; constexpr std::chrono::milliseconds DEFAULT_REST_TIMEOUT{ 400 }; @@ -303,13 +305,13 @@ httpResponse ProviderRestApi::getResponse(QNetworkReply* const& reply) { httpResponse response; - int httpStatusCode = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); + HttpStatusCode httpStatusCode = static_cast(reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt()); response.setHttpStatusCode(httpStatusCode); response.setNetworkReplyError(reply->error()); if (reply->error() == QNetworkReply::NoError) { - if ( httpStatusCode != HTTP_STATUS_NO_CONTENT ){ + if ( httpStatusCode != HttpStatusCode::NoContent ){ QByteArray replyData = reply->readAll(); if (!replyData.isEmpty()) @@ -320,13 +322,11 @@ httpResponse ProviderRestApi::getResponse(QNetworkReply* const& reply) if (error.error != QJsonParseError::NoError) { //Received not valid JSON response - //std::cout << "Response: [" << replyData.toStdString() << "]" << std::endl; response.setError(true); response.setErrorReason(error.errorString()); } else { - //std::cout << "Response: [" << QString(jsonDoc.toJson(QJsonDocument::Compact)).toStdString() << "]" << std::endl; response.setBody(jsonDoc); } } @@ -344,13 +344,13 @@ httpResponse ProviderRestApi::getResponse(QNetworkReply* const& reply) QString httpReason = reply->attribute(QNetworkRequest::HttpReasonPhraseAttribute).toString(); QString advise; switch ( httpStatusCode ) { - case HTTP_STATUS_BAD_REQUEST: + case HttpStatusCode::BadRequest: advise = "Check Request Body"; break; - case HTTP_STATUS_UNAUTHORIZED: + case HttpStatusCode::UnAuthorized: advise = "Check Authentication Token (API Key)"; break; - case HTTP_STATUS_NOT_FOUND: + case HttpStatusCode::NotFound: advise = "Check Resource given"; break; default: diff --git a/libsrc/leddevice/dev_other/LedDeviceFile.cpp b/libsrc/leddevice/dev_other/LedDeviceFile.cpp index 0dba14d8..cc7ddd2d 100644 --- a/libsrc/leddevice/dev_other/LedDeviceFile.cpp +++ b/libsrc/leddevice/dev_other/LedDeviceFile.cpp @@ -92,9 +92,6 @@ int LedDeviceFile::close() int LedDeviceFile::write(const std::vector & ledValues) { QTextStream out(_file); - - //printLedValues (ledValues); - if ( _printTimeStamp ) { QDateTime now = QDateTime::currentDateTime(); diff --git a/libsrc/leddevice/dev_other/LedDevicePiBlaster.cpp b/libsrc/leddevice/dev_other/LedDevicePiBlaster.cpp index 20eaf0f7..0f46d898 100644 --- a/libsrc/leddevice/dev_other/LedDevicePiBlaster.cpp +++ b/libsrc/leddevice/dev_other/LedDevicePiBlaster.cpp @@ -179,8 +179,6 @@ int LedDevicePiBlaster::write(const std::vector & ledValues) continue; } -// fprintf(_fid, "%i=%f\n", iPins[iPin], pwmDutyCycle); - if ( (fprintf(_fid, "%i=%f\n", i, pwmDutyCycle) < 0) || (fflush(_fid) < 0)) { if (_fid != nullptr) diff --git a/libsrc/leddevice/dev_serial/LedDeviceDMX.cpp b/libsrc/leddevice/dev_serial/LedDeviceDMX.cpp index 7a9e85bc..ba7a51e6 100644 --- a/libsrc/leddevice/dev_serial/LedDeviceDMX.cpp +++ b/libsrc/leddevice/dev_serial/LedDeviceDMX.cpp @@ -42,7 +42,6 @@ bool LedDeviceDMX::init(const QJsonObject &deviceConfig) } else { - //Error(_log, "unknown dmx device type %s", QSTRING_CSTR(dmxString)); QString errortext = QString ("unknown dmx device type: %1").arg(dmxTypeString); this->setInError(errortext); return false; diff --git a/libsrc/leddevice/dev_serial/LedDeviceKarate.cpp b/libsrc/leddevice/dev_serial/LedDeviceKarate.cpp index e99ccce0..56eea4cc 100644 --- a/libsrc/leddevice/dev_serial/LedDeviceKarate.cpp +++ b/libsrc/leddevice/dev_serial/LedDeviceKarate.cpp @@ -24,7 +24,6 @@ bool LedDeviceKarate::init(const QJsonObject& deviceConfig) { if (_ledCount != 8 && _ledCount != 16) { - //Error( _log, "%d channels configured. This should always be 16!", _ledCount); QString errortext = QString("%1 channels configured. This should always be 8 or 16!").arg(_ledCount); this->setInError(errortext); isInitOK = false; diff --git a/libsrc/leddevice/dev_serial/LedDeviceSedu.cpp b/libsrc/leddevice/dev_serial/LedDeviceSedu.cpp index 9468e45e..09ac92fc 100644 --- a/libsrc/leddevice/dev_serial/LedDeviceSedu.cpp +++ b/libsrc/leddevice/dev_serial/LedDeviceSedu.cpp @@ -40,7 +40,6 @@ bool LedDeviceSedu::init(const QJsonObject &deviceConfig) if (_ledBuffer.empty()) { - //Warning(_log, "More rgb-channels required then available"); QString errortext = "More rgb-channels required then available"; this->setInError(errortext); } diff --git a/libsrc/leddevice/dev_serial/ProviderRs232.cpp b/libsrc/leddevice/dev_serial/ProviderRs232.cpp index bd4349db..9b2b1197 100644 --- a/libsrc/leddevice/dev_serial/ProviderRs232.cpp +++ b/libsrc/leddevice/dev_serial/ProviderRs232.cpp @@ -273,13 +273,6 @@ void ProviderRs232::readFeedback() { //Output as received std::cout << readData.toStdString(); - - //Output as Hex -//#if (QT_VERSION >= QT_VERSION_CHECK(5, 9, 0)) -// std::cout << readData.toHex(':').toStdString(); -//#else -// std::cout << readData.toHex().toStdString(); -//#endif } } diff --git a/libsrc/leddevice/dev_spi/LedDeviceSK9822.cpp b/libsrc/leddevice/dev_spi/LedDeviceSK9822.cpp index 4562ac1b..c477946f 100644 --- a/libsrc/leddevice/dev_spi/LedDeviceSK9822.cpp +++ b/libsrc/leddevice/dev_spi/LedDeviceSK9822.cpp @@ -117,10 +117,6 @@ void LedDeviceSK9822::bufferWithAdjustedCurrent(std::vector &txBuf, con txBuf[b + 1] = red; txBuf[b + 2] = green; txBuf[b + 3] = blue; - - //if(iLed == 0) { - // std::cout << std::to_string((int)rgb.red) << "," << std::to_string((int)rgb.green) << "," << std::to_string((int)rgb.blue) << ": " << std::to_string(maxValue) << (maxValue >= threshold ? " >= " : " < ") << std::to_string(threshold) << " -> " << std::to_string((int)(level&SK9822_GBC_MAX_LEVEL))<< "@" << std::to_string((int)red) << "," << std::to_string((int)green) << "," << std::to_string((int)blue) << std::endl; - //} } } diff --git a/libsrc/leddevice/dev_spi/LedDeviceSk6822SPI.cpp b/libsrc/leddevice/dev_spi/LedDeviceSk6822SPI.cpp index df478ba3..12d050dc 100644 --- a/libsrc/leddevice/dev_spi/LedDeviceSk6822SPI.cpp +++ b/libsrc/leddevice/dev_spi/LedDeviceSk6822SPI.cpp @@ -67,8 +67,6 @@ bool LedDeviceSk6822SPI::init(const QJsonObject &deviceConfig) WarningIf(( _baudRate_Hz < 2000000 || _baudRate_Hz > 2460000 ), _log, "SPI rate %d outside recommended range (2000000 -> 2460000)", _baudRate_Hz); _ledBuffer.resize( (_ledRGBCount * SPI_BYTES_PER_COLOUR) + (_ledCount * SPI_BYTES_WAIT_TIME ) + SPI_FRAME_END_LATCH_BYTES, 0x00); - // Debug(_log, "_ledBuffer.resize(_ledRGBCount:%d * SPI_BYTES_PER_COLOUR:%d) + ( _ledCount:%d * SPI_BYTES_WAIT_TIME:%d ) + SPI_FRAME_END_LATCH_BYTES:%d, 0x00)", _ledRGBCount, SPI_BYTES_PER_COLOUR, _ledCount, SPI_BYTES_WAIT_TIME, SPI_FRAME_END_LATCH_BYTES); - isInitOK = true; } @@ -95,7 +93,7 @@ int LedDeviceSk6822SPI::write(const std::vector &ledValues) spi_ptr += SPI_BYTES_WAIT_TIME; // the wait between led time is all zeros } -/* +#if 0 // debug the whole SPI packet char debug_line[2048]; int ptr=0; @@ -114,7 +112,7 @@ int LedDeviceSk6822SPI::write(const std::vector &ledValues) ptr = 0; } } -*/ +#endif return writeBytes(_ledBuffer.size(), _ledBuffer.data()); } diff --git a/libsrc/mdns/MdnsBrowser.cpp b/libsrc/mdns/MdnsBrowser.cpp index 60bd7ee4..4c0e4b9e 100644 --- a/libsrc/mdns/MdnsBrowser.cpp +++ b/libsrc/mdns/MdnsBrowser.cpp @@ -429,7 +429,7 @@ QJsonArray MdnsBrowser::getServicesDiscoveredJson(const QByteArray& serviceType, void MdnsBrowser::printCache(const QByteArray& name, quint16 type) const { - DebugIf(verboseBrowser,_log, "for type: ", QSTRING_CSTR(QMdnsEngine::typeName(type))); + DebugIf(verboseBrowser,_log, "for type: %s", QSTRING_CSTR(QMdnsEngine::typeName(type))); QList records; if (_cache.lookupRecords(name, type, records)) { @@ -466,6 +466,6 @@ void MdnsBrowser::printCache(const QByteArray& name, quint16 type) const } else { - DebugIf(verboseBrowser,_log, "Cash is empty for type: ", QSTRING_CSTR(QMdnsEngine::typeName(type))); + DebugIf(verboseBrowser,_log, "Cash is empty for type: %s", QSTRING_CSTR(QMdnsEngine::typeName(type))); } } diff --git a/libsrc/ssdp/SSDPDiscover.cpp b/libsrc/ssdp/SSDPDiscover.cpp index 3deec6f2..45401788 100644 --- a/libsrc/ssdp/SSDPDiscover.cpp +++ b/libsrc/ssdp/SSDPDiscover.cpp @@ -73,8 +73,6 @@ QString SSDPDiscover::getFirstService(const searchType& type, const QString& st, QString data(datagram); - //Debug(_log, "_data: [%s]", QSTRING_CSTR(data)); - QMap headers; QString address; // parse request @@ -107,7 +105,7 @@ QString SSDPDiscover::getFirstService(const searchType& type, const QString& st, { _usnList << headers.value("usn"); QUrl url(headers.value("location")); - //Debug(_log, "Received msearch response from '%s:%d'. Search target: %s",QSTRING_CSTR(sender.toString()), senderPort, QSTRING_CSTR(headers.value("st"))); + if(type == searchType::STY_WEBSERVER) { Debug(_log, "Found service [%s] at: %s:%d", QSTRING_CSTR(st), QSTRING_CSTR(url.host()), url.port()); @@ -191,7 +189,6 @@ void SSDPDiscover::readPendingDatagrams() if (headers.value("st") == _searchTarget) { _usnList << headers.value("usn"); - //Debug(_log, "Received msearch response from '%s:%d'. Search target: %s",QSTRING_CSTR(sender.toString()), senderPort, QSTRING_CSTR(headers.value("st"))); QUrl url(headers.value("location")); emit newService(url.host() + ":" + QString::number(url.port())); } @@ -226,8 +223,6 @@ int SSDPDiscover::discoverServices(const QString& searchTarget, const QString& k QString data(datagram); - //Debug(_log, "_data: [%s]", QSTRING_CSTR(data)); - QMap headers; // parse request QStringList entries = QStringUtils::split(data,"\n", QStringUtils::SplitBehavior::SkipEmptyParts); @@ -250,7 +245,6 @@ int SSDPDiscover::discoverServices(const QString& searchTarget, const QString& k if ( match.hasMatch() ) { Debug(_log,"Found target [%s], plus record [%s] matches [%s:%s]", QSTRING_CSTR(_searchTarget), QSTRING_CSTR(headers[_filterHeader]), QSTRING_CSTR(_filterHeader), QSTRING_CSTR(_filter) ); - //Debug(_log, "_data: [%s]", QSTRING_CSTR(data)); QString mapKey = headers[key]; @@ -303,8 +297,6 @@ QJsonArray SSDPDiscover::getServicesDiscoveredJson() const QMultiMap::const_iterator i; for (i = _services.begin(); i != _services.end(); ++i) { - //Debug(_log, "Device discovered at [%s]", QSTRING_CSTR( i.key() )); - QJsonObject obj; obj.insert("id", i.key()); @@ -363,8 +355,6 @@ QJsonArray SSDPDiscover::getServicesDiscoveredJson() const result << obj; } - - //Debug(_log, "result: [%s]", QString(QJsonDocument(result).toJson(QJsonDocument::Compact)).toUtf8().constData() ); return result; } @@ -372,7 +362,6 @@ void SSDPDiscover::sendSearch(const QString& st) { const QString msg = QString(UPNP_DISCOVER_MESSAGE).arg(_ssdpAddr.toString()).arg(_ssdpPort).arg(_ssdpMaxWaitResponseTime).arg(st); - //Debug(_log,"Search request: [%s]", QSTRING_CSTR(msg)); _udpSocket->writeDatagram(msg.toUtf8(), _ssdpAddr, _ssdpPort); } diff --git a/libsrc/ssdp/SSDPServer.cpp b/libsrc/ssdp/SSDPServer.cpp index cd8e1d08..5fba01f3 100644 --- a/libsrc/ssdp/SSDPServer.cpp +++ b/libsrc/ssdp/SSDPServer.cpp @@ -165,7 +165,6 @@ void SSDPServer::readPendingDatagrams() if (headers.value("man") == "\"ssdp:discover\"") { - //Debug(_log, "Received msearch from '%s:%d'. Search target: %s",QSTRING_CSTR(sender.toString()), senderPort, QSTRING_CSTR(headers.value("st"))); emit msearchRequestReceived(headers.value("st"), headers.value("mx"), sender.toString(), senderPort); } } diff --git a/libsrc/utils/DefaultSignalHandler.cpp b/libsrc/utils/DefaultSignalHandler.cpp index 8a06095a..e8afa969 100644 --- a/libsrc/utils/DefaultSignalHandler.cpp +++ b/libsrc/utils/DefaultSignalHandler.cpp @@ -94,8 +94,8 @@ void print_trace() * handler and print_trace functions. */ for (int i = 2; i < size; ++i) { - std::string line = "\t" + decipher_trace(symbols[i]); - Error(log, line.c_str()); + const std::string line = "\t" + decipher_trace(symbols[i]); + Error(log, "%s", line.c_str()); } free(symbols); @@ -149,8 +149,6 @@ void signal_handler(int signum, siginfo_t * /*info*/, void * /*context*/) default: /* If the signal_handler is hit before the event loop is started, * following call will do nothing. So we queue the call. */ - - // QCoreApplication::quit(); QMetaObject::invokeMethod(qApp, "quit", Qt::QueuedConnection); // Reset signal handler to default (in case this handler is not capable of stopping) diff --git a/libsrc/utils/JsonUtils.cpp b/libsrc/utils/JsonUtils.cpp index c24d0939..d43c5bba 100644 --- a/libsrc/utils/JsonUtils.cpp +++ b/libsrc/utils/JsonUtils.cpp @@ -59,8 +59,6 @@ namespace JsonUtils { { //remove Comments in data QString cleanData = data; - //cleanData .remove(QRegularExpression("([^:]?\\/\\/.*)")); - QJsonParseError error; doc = QJsonDocument::fromJson(cleanData.toUtf8(), &error); @@ -145,7 +143,6 @@ namespace JsonUtils { obj.insert(attribute, resolveRefs(attributeValue.toObject(), obj, log)); else { - //qDebug() <<"ADD ATTR:VALUE"< #include -#include +#include // Utils-Jsonschema includes #include @@ -186,7 +186,14 @@ void QJsonSchemaChecker::checkType(const QJsonValue& value, const QJsonValue& sc else if (type == "integer") { if (value.isDouble()) //check if value type not boolean (true = 1 && false = 0) - wrongType = (rint(value.toDouble()) != value.toDouble()); + { + double valueIntegratlPart; + double valueFractionalPart = std::modf(value.toDouble(), &valueIntegratlPart); + if (valueFractionalPart > std::numeric_limits::epsilon()) + { + wrongType = true; + } + } else wrongType = true; } diff --git a/libsrc/webserver/QtHttpClientWrapper.cpp b/libsrc/webserver/QtHttpClientWrapper.cpp index 3bf2bdef..4ea3bd83 100644 --- a/libsrc/webserver/QtHttpClientWrapper.cpp +++ b/libsrc/webserver/QtHttpClientWrapper.cpp @@ -77,13 +77,13 @@ void QtHttpClientWrapper::onClientDataReceived (void) else { m_parsingStatus = ParsingError; - //qWarning () << "Error : unhandled HTTP version :" << version; + // Error : unhandled HTTP version } } else { m_parsingStatus = ParsingError; - //qWarning () << "Error : incorrect HTTP command line :" << line; + // Error : incorrect HTTP command line } break; diff --git a/libsrc/webserver/StaticFileServing.cpp b/libsrc/webserver/StaticFileServing.cpp index 898d31d8..4c550280 100644 --- a/libsrc/webserver/StaticFileServing.cpp +++ b/libsrc/webserver/StaticFileServing.cpp @@ -1,5 +1,7 @@ #include "StaticFileServing.h" + +#include "QtHttpHeader.h" #include #include @@ -9,6 +11,7 @@ #include #include #include + #include StaticFileServing::StaticFileServing (QObject * parent) diff --git a/libsrc/webserver/StaticFileServing.h b/libsrc/webserver/StaticFileServing.h index c1ec6395..b328bf16 100644 --- a/libsrc/webserver/StaticFileServing.h +++ b/libsrc/webserver/StaticFileServing.h @@ -3,10 +3,8 @@ #include -//#include "QtHttpServer.h" #include "QtHttpRequest.h" #include "QtHttpReply.h" -#include "QtHttpHeader.h" #include "CgiHandler.h" #include diff --git a/libsrc/webserver/WebSocketClient.cpp b/libsrc/webserver/WebSocketClient.cpp index ac8d77ad..555fae52 100644 --- a/libsrc/webserver/WebSocketClient.cpp +++ b/libsrc/webserver/WebSocketClient.cpp @@ -58,14 +58,12 @@ void WebSocketClient::handleWebSocketFrame() if(_socket->bytesAvailable() < (qint64)_wsh.payloadLength) { - //printf("not enough data %llu %llu\n", _socket->bytesAvailable(), _wsh.payloadLength); _notEnoughData=true; return; } _notEnoughData = false; QByteArray buf = _socket->read(_wsh.payloadLength); - //printf("opcode %x payload bytes %llu avail: %llu\n", _wsh.opCode, _wsh.payloadLength, _socket->bytesAvailable()); if (OPCODE::invalid((OPCODE::value)_wsh.opCode)) { @@ -210,10 +208,10 @@ void WebSocketClient::getWsFrameHeader(WebSocketHeader* header) } /// See http://tools.ietf.org/html/rfc6455#section-5.2 for more information -void WebSocketClient::sendClose(int status, QString reason) +void WebSocketClient::sendClose(int status, const QString& reason) { Debug(_log, "Send close to %s: %d %s", QSTRING_CSTR(_socket->peerAddress().toString()), status, QSTRING_CSTR(reason)); - ErrorIf(!reason.isEmpty(), _log, QSTRING_CSTR(reason)); + ErrorIf(!reason.isEmpty(), _log, "%s", QSTRING_CSTR(reason)); _receiveBuffer.clear(); QByteArray sendBuffer; @@ -244,8 +242,6 @@ void WebSocketClient::sendClose(int status, QString reason) void WebSocketClient::handleBinaryMessage(QByteArray &data) { - //uint8_t priority = data.at(0); - //unsigned duration_s = data.at(1); unsigned imgSize = data.size() - 4; unsigned width = ((data.at(2) << 8) & 0xFF00) | (data.at(3) & 0xFF); unsigned height = imgSize / width; @@ -260,8 +256,6 @@ void WebSocketClient::handleBinaryMessage(QByteArray &data) image.resize(width, height); memcpy(image.memptr(), data.data()+4, imgSize); - //_hyperion->registerInput(); - //_hyperion->setInputImage(priority, image, duration_s*1000); } diff --git a/libsrc/webserver/WebSocketClient.h b/libsrc/webserver/WebSocketClient.h index 0b056fb1..df5342bd 100644 --- a/libsrc/webserver/WebSocketClient.h +++ b/libsrc/webserver/WebSocketClient.h @@ -31,7 +31,7 @@ private: JsonAPI* _jsonAPI; void getWsFrameHeader(WebSocketHeader* header); - void sendClose(int status, QString reason = ""); + void sendClose(int status, const QString& reason = ""); void handleBinaryMessage(QByteArray &data); qint64 sendMessage_Raw(const char* data, quint64 size); qint64 sendMessage_Raw(QByteArray &data); diff --git a/src/hyperion-framebuffer/hyperion-framebuffer.cpp b/src/hyperion-framebuffer/hyperion-framebuffer.cpp index ba82953c..8f743d48 100644 --- a/src/hyperion-framebuffer/hyperion-framebuffer.cpp +++ b/src/hyperion-framebuffer/hyperion-framebuffer.cpp @@ -21,13 +21,6 @@ #include -// Constants -namespace { - - const char SERVICE_TYPE[] = "flatbuffer"; - -} //End of constants - using namespace commandline; // save the image as screenshot diff --git a/src/hyperion-qt/hyperion-qt.cpp b/src/hyperion-qt/hyperion-qt.cpp index 29060088..2e12f2f6 100644 --- a/src/hyperion-qt/hyperion-qt.cpp +++ b/src/hyperion-qt/hyperion-qt.cpp @@ -22,13 +22,6 @@ //flatbuf sending #include -// Constants -namespace { - -const char SERVICE_TYPE[] = "flatbuffer"; - -} //End of constants - using namespace commandline; // save the image as screenshot @@ -49,7 +42,6 @@ int main(int argc, char ** argv) << "\tVersion : " << HYPERION_VERSION << " (" << HYPERION_BUILD_ID << ")" << std::endl << "\tbuild time: " << __DATE__ << " " << __TIME__ << std::endl; - //QCoreApplication app(argc, argv); QGuiApplication app(argc, argv); try diff --git a/src/hyperion-remote/hyperion-remote.cpp b/src/hyperion-remote/hyperion-remote.cpp index e1ec2c43..37d2ec03 100644 --- a/src/hyperion-remote/hyperion-remote.cpp +++ b/src/hyperion-remote/hyperion-remote.cpp @@ -29,14 +29,6 @@ #include -// Constants -namespace { - - const char SERVICE_TYPE[] = "jsonapi"; - -} //End of constants - - using namespace commandline; /// Count the number of true values in a list of booleans diff --git a/src/hyperion-v4l2/ScreenshotHandler.cpp b/src/hyperion-v4l2/ScreenshotHandler.cpp index ed2fdbb8..a1482b66 100644 --- a/src/hyperion-v4l2/ScreenshotHandler.cpp +++ b/src/hyperion-v4l2/ScreenshotHandler.cpp @@ -1,3 +1,5 @@ +#include + // Qt includes #include #include @@ -102,7 +104,6 @@ bool ScreenshotHandler::findNoSignalSettings(const Image & image) auto itG = std::max_element(std::begin(greenCounts), std::end(greenCounts)); auto itB = std::max_element(std::begin(blueCounts), std::end(blueCounts)); - //std::cout << *itR << " " << *itG << " " << *itB << std::endl; double xOffsetSuggested = xOffset; double yOffsetSuggested = yOffset; double xMaxSuggested = xMax; @@ -138,7 +139,7 @@ bool ScreenshotHandler::findNoSignalSettings(const Image & image) if (!noSignalBlack) { unsigned xMid = (xMaxSuggested + xOffsetSuggested) / 2; - for (unsigned y = yMid; y >= yOffset && yOffsetSuggested != y; --y) + for (unsigned y = yMid; y >= yOffset && (fabs(yOffsetSuggested - y) > std::numeric_limits::epsilon()); --y) { ColorRgb rgb = image(xMid, y); if (rgb <= noSignalThresholdColor) @@ -147,7 +148,7 @@ bool ScreenshotHandler::findNoSignalSettings(const Image & image) } } - for (unsigned y = yMid; y <= yMax && yMaxSuggested != y; ++y) + for (unsigned y = yMid; y <= yMax && (fabs(yMaxSuggested - y) > std::numeric_limits::epsilon()); ++y) { ColorRgb rgb = image(xMid, y); if (rgb <= noSignalThresholdColor) diff --git a/src/hyperion-v4l2/hyperion-v4l2.cpp b/src/hyperion-v4l2/hyperion-v4l2.cpp index 7a0a09b1..73195177 100644 --- a/src/hyperion-v4l2/hyperion-v4l2.cpp +++ b/src/hyperion-v4l2/hyperion-v4l2.cpp @@ -33,13 +33,6 @@ #include -// Constants -namespace { - - const char SERVICE_TYPE[] = "flatbuffer"; - -} //End of constants - using namespace commandline; int main(int argc, char** argv) diff --git a/src/hyperion-x11/hyperion-x11.cpp b/src/hyperion-x11/hyperion-x11.cpp index 4c386310..d506bf1d 100644 --- a/src/hyperion-x11/hyperion-x11.cpp +++ b/src/hyperion-x11/hyperion-x11.cpp @@ -19,13 +19,6 @@ #endif #include -// Constants -namespace { - - const char SERVICE_TYPE[] = "flatbuffer"; - -} //End of constants - using namespace commandline; // save the image as screenshot diff --git a/src/hyperion-xcb/hyperion-xcb.cpp b/src/hyperion-xcb/hyperion-xcb.cpp index 79c885c8..06a94f8d 100644 --- a/src/hyperion-xcb/hyperion-xcb.cpp +++ b/src/hyperion-xcb/hyperion-xcb.cpp @@ -19,13 +19,6 @@ #endif #include -// Constants -namespace { - - const char SERVICE_TYPE[] = "flatbuffer"; - -} //End of constants - using namespace commandline; // save the image as screenshot diff --git a/test/jsonchecks/jsonschema.py b/test/jsonchecks/jsonschema.py index f1418dc5..8b1e4cca 100644 --- a/test/jsonchecks/jsonschema.py +++ b/test/jsonchecks/jsonschema.py @@ -11,7 +11,6 @@ instance under a schema, and will create a validator for you. from __future__ import division, unicode_literals -import collections import contextlib import datetime import itertools @@ -474,10 +473,10 @@ class _Draft34CommonMixin(object): yield error else: dependencies = _list(dependency) - for dependency in dependencies: - if dependency not in instance: + for depend in dependencies: + if depend not in instance: yield ValidationError( - "%r is a dependency of %r" % (dependency, property) + "%r is a dependency of %r" % (depend, property) ) def validate_enum(self, enums, instance, schema): @@ -512,10 +511,10 @@ class Draft3Validator(ValidatorMixin, _Draft34CommonMixin, object): elif self.is_type(type, "string"): if self.is_type(instance, type): return - else: - yield ValidationError( - _types_msg(instance, types), context=all_errors, - ) + else: + yield ValidationError( + _types_msg(instance, types), context=all_errors, + ) def validate_properties(self, properties, instance, schema): if not self.is_type(instance, "object"): @@ -694,6 +693,7 @@ class Draft4Validator(ValidatorMixin, _Draft34CommonMixin, object): yield error def validate_oneOf(self, oneOf, instance, schema): + first_valid = "" subschemas = enumerate(oneOf) all_errors = [] for index, subschema in subschemas: