Source: wlanconfig.js

/*
 * Copyright (C) 2022 Velometrik GmbH
 * <http://www.velometrik.de/>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * Contact:
 * support@velometrik.de
 *
 * wlanconfig
 *
 */

var httpScanresult = new XMLHttpRequest();
var httpIwconfig = new XMLHttpRequest();
var scanresult;


/**
 * The function "suche" hides elements with class "suche" that do not match the search parameter and
 * shows elements that do match the search parameter.
 * @param params - The `params` variable in the `suche` function is used to search for elements with a
 * specific attribute value. The function loops through all elements with the class name 'suche', hides
 * them initially, and then shows the elements whose 'suche' attribute value includes the `params`
 * value
 */
function suche (params) {
    $('.suche').each(element => {
        $('.suche')[element].classList.add('hide')
        if($('.suche')[element].getAttribute('suche').includes(params) || $('.suche')[element].getAttribute('suche').toLowerCase().includes(params))
        $('.suche')[element].classList.remove('hide')
    });
}
//let inter = setInterval(()=> {
//    httpScanresult.abort()
//    clearInterval(inter);
//  }, 30000);
let loader = setInterval( () => {
    document.getElementById('setting_list').classList.remove('hidden')
    //document.getElementById('loader').classList.add('hidden')
    UIkit.modal('#modal_load_side').hide();
    clearInterval(loader);
},500)

/* A function that is called when the result of the scan is received. */
httpScanresult.onreadystatechange = async function() {
    document.getElementById('setting_list').classList.add('hidden')
    document.getElementById('loader2').classList.remove('hidden')
    console.log(httpScanresult.readyState);
    if (httpScanresult.readyState == 4) {
        console.log(`%c iwscan.tcls beendet mit Status ${httpScanresult.status}`,'background: #222;color:#e17a0c ;padding:1em');
        if (httpScanresult.status == 200) {
            console.log(httpScanresult)
            scanresult = JSON.parse(httpScanresult.responseText);
            var essids = new Set();
            console.log(scanresult);

            if (scanresult.length == 0) {
                document.getElementById("scanresult").innerHTML = "<tr><td colspan=\"6\"><span class=\"badge badge-warning\" key=\"netzwerk_keinen_accesspoint\"><!--Keinen Accesspoint gefunden--></span></td></tr>";
                let loader = setInterval( () => {
                    document.getElementById('setting_list').classList.remove('hidden')
                    //document.getElementById('loader').classList.add('hidden')
                    UIkit.modal('#modal_load_side').hide();
                    clearInterval(loader);
                },500)
            } else {
                var thead = ['#','ssid','staerke','mac','passwort']//,'new Session','']
                var append = $('#wlan-list')[0]
                append.innerHTML ="";
                //var container = newElement({element:'div',cls:['uk-container']},append)
                var container = document.createElement('div')
                container.classList.add('uk-container')
                append.append(container)
                //var table = newElement({element:'table',cls:['uk-table','uk-table-middle','uk-table-divider','uk-table-hover']},container)
                var table = document.createElement('table')
                table.classList.add('uk-table','uk-table-middle','uk-table-divider','uk-table-hover')
                container.append(table);
                //var table_head = newElement({element:'thead'},table)
                var table_head= document.createElement('thead')
                table.append(table_head);
                //var tr_head = newElement({element:'tr'},table_head)
                var tr_head = document.createElement('tr');
                table_head.append(tr_head);
                thead.forEach(element => {
                    //var head = newElement({element:'th'},tr_head).innerHTML = element
                    var head = document.createElement('th');
                    head.innerHTML = element
                    if(element!='#'){
                        head.setAttribute('key',`netzwerk_${element}`)
                    }
                    tr_head.append(head);
                })
                //var tbody = newElement({element:'tbody'},table)
                var tbody = document.createElement('tbody');
                table.append(tbody);
                scanresult.forEach(element => {
                    var x = new Object();
                    x = element;
                    var essid = element.essid;
                    var tr_body = document.createElement('tr');
                    tr_body.classList.add('suche')
                    tr_body.setAttribute('suche',`${x.essid}`)

                    tbody.append(tr_body);
                    tr_body.innerHTML =  `<td>${x.cell}</td>`
                    if(!x.essid){
                        tr_body.innerHTML += `<td><input class="uk-input" id="h_essid" type="text" placeholder="hidden essid"></td>`
                    } else {
                    tr_body.innerHTML += `<td>${x.essid}</td>`
                    }
                    tr_body.innerHTML += `<td>${x.level}</td>`
                    tr_body.innerHTML += `<td>${x.address}</td>`
                    if (!essids.has(essid) && essid != essid_connected) {
                        var ap = gespeichert[essid];
                        var psk = (ap === undefined) ? "" : ap.psk;

                        tr_body.innerHTML += `<td><input type="password" class="uk-input" value="${psk}" id="psk_${essid}"></td>`
                        tr_body.innerHTML += `<td><button type="button" class="uk-button uk-button-default uk-button-small mdi mdi-24px mdi-eye" key-title="wlan_schow_pass" onclick='umschalten("psk_${essid}")'></button></td>` //<i class="fa fa-eye"></i>
                        if(x.essid)
                        tr_body.innerHTML += `<td><button type="button" class="uk-button uk-button-default uk-button-small mdi mdi-24px mdi-link" key-title="wlan_connect" onclick='wlanconnect("${essid}")'></button></td>` //<i class="fa fa-plug"></i>
                        else
                        tr_body.innerHTML += `<td><button type="button" class="uk-button uk-button-default uk-button-small mdi mdi-24px mdi-link" key-title="wlan_connect" id="hidden_SSID" onclick='hiddenSSID(this)'></button></td>` //<i class="fa fa-plug"></i>
                        essids.add(essid);
                    } else {
                        tr_body.innerHTML += `<td colspan="3"><span class="badge badge-warning" key="netzwerk_verbunden"><!--Netzwerk bereits verbunden--></span></td>`;
                    }
                });
                var html = "";
                scanresult.forEach(element => {
                    console.log(`%c     WIFI scan result -> ${JSON.stringify(element)}`,'background: #222;color: white;padding:1em');
                });
                let loader = setInterval( () => {
                    document.getElementById('setting_list').classList.remove('hidden')
                    UIkit.modal('#modal_load_side').hide();
                    //document.getElementById('loader').classList.add('hidden')
                    document.getElementById('loader2').classList.add('hidden')
                    clearInterval(loader);
                },1000)
                //document.getElementById('loader').classList.add('hidden')
                //UIkit.modal('#modal-wlan').hide()
            }
        } else {
            console.log("HTTP-Fehler " + httpScanresult.status, " bei iwscan.tcls.");
        }
    }
};

/**
 * The function `hiddenSSID` logs the value of an input field with the ID 'h_essid' and then calls the
 * `wlanconnect` function with that value as an argument.
 */
function hiddenSSID (){
    console.log(`wlanconnect("${document.getElementById('h_essid').value}")`);
    wlanconnect(document.getElementById('h_essid').value)
}

/* A function that is called when the result of the scan is received. */
httpIwconfig.onreadystatechange = async function() {
    if (httpIwconfig.readyState == 4) {
        console.log("iwscan.tcls beenden mit Status " + httpIwconfig.status);
        if (httpIwconfig.status == 200) {
            var response = httpIwconfig.responseText;
            console.log(response);
            if (response.substr(0, 5) == "Error") {
                document.getElementById("wlanstatus").innerHTML = "<div class=\"alert alert-warning alert-dismissible\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">×</span></button><strong><span class=\"tr\" key=\"netzwerk_nichtverbunden\"><!--Nicht verbunden--></span></strong></div>";
            } else {
                var connection = JSON.parse(response);

                document.getElementById("wlanstatus").innerHTML = "<div class=\"alert alert-warning alert-dismissible\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">×</span></button><strong><span class=\"tr\" key=\"netzwerk_verbunden\">Verbunden mit </span> " + connection.essid + " (IP: " + connection.inet + ")</strong></div>";
                essid_connected = connection.essid;
                refreshWLAN();
            }
        }
    }
     translatejs();
};

/**
 * It sends a request to the server to execute the iwscan.tcls script
 * @returns The result of the iwscan.tcls script.
 */
async function refreshWLAN() {
    if (httpScanresult.readyState == 4) {
        //UIkit.modal('#modal-wlan').show()

        // document.getElementById("scanresult").innerHTML = "<td colspan=\"6\"><div class=\"alert alert-warning alert-dismissible\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">×</span></button><strong><span class=\"tr\" key=\"netzwerk_netzwerkwirdgesucht\"><!--Suche nach Wlan Netzwerken...--></span></strong></div></td>";
    } else if (httpScanresult.readyState != 0) {
        return;
    }

    /* Sending a request to the server to execute the iwscan.tcls script. */
    httpScanresult.open("GET", "iwscan.tcls?rnd=" + (new Date).getTime(), true);
    httpScanresult.send();
    translatejs();

}

/**
 * If the type of the element with the id "id" is "password", then change it to "text", otherwise
 * change it to "password"
 * @param {string} id - The id of the password field.
 */
function umschalten(id) {
    var x = document.getElementById(id);
    if (x.type === "password") {
        x.type = "text";
    } else {
        x.type = "password";
    }
}

/**
 * It sends a request to the server to connect to a WLAN with the given ESSID and the given key
 * @param {string} essid - The name of the network you want to connect to.
 * @returns The return value is the result of the last command executed in the function.
 */
function wlanconnect(essid) {
    var x = document.getElementById("psk_" + essid);
    var key = x.value;
    var url = "/production/wlanconnect.tcls?essid=" + essid + "&key=" + key;

    if (key.length === 0) {
        document.getElementById("wlanstatus").innerHTML = "<div class=\"alert alert-danger alert-dismissible\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">×</span></button><strong>Verbindungen zu offenen WLANs sind nicht erlaubt! </strong></div>";
        return;
    }

    document.getElementById("wlanstatus").innerHTML = "<div class=\"alert alert-warning alert-dismissible\" role=\"alert\"><button type=\"button\" class=\"close\" data-dismiss=\"alert\" aria-label=\"Close\"><span aria-hidden=\"true\">×</span></button><strong>Verbinde mit " + essid + " ...</strong></div>";
    httpIwconfig.open("GET", url, true);
    httpIwconfig.send();
}

                // Umrechnung in MB
                var speicherInMb = {
                    total: (speicher.total / 1024).toFixed(2),
                    used: (speicher.used / 1024).toFixed(2),
                    avail: (speicher.avail / 1024).toFixed(2)
                };
        
                // ECharts-Instance erstellen
                var chart = echarts.init(document.getElementById('Speicher'));
        
                // Daten für das Kreisdiagramm
                var option = {
                    title: {
                        text: 'Speicherbelegung (MB)',
                        subtext: 'Daten von /dev/root',
                        left: 'center'
                    },
                    tooltip: {
                        trigger: 'item',
                        formatter: '{a} <br/>{b}: {c} MB ({d}%)'
                    },
                    legend: {
                        orient: 'vertical',
                        left: 'left',
                        data: ['Verwendet', 'Verfügbar']
                    },
                    series: [
                        {
                            name: 'Speicher',
                            type: 'pie',
                            radius: '50%',
                            data: [
                                { value: speicherInMb.used, name: 'Verwendet', itemStyle: { color: '#ee395b' } },
                                { value: speicherInMb.avail, name: 'Verfügbar', itemStyle: { color: '#5cbc40' } }
                            ],
                            emphasis: {
                                itemStyle: {
                                    shadowBlur: 10,
                                    shadowOffsetX: 0,
                                    shadowColor: 'rgba(0, 0, 0, 0.5)'
                                }
                            }
                        }
                    ]
                };

        // Option anwenden
        chart.setOption(option);

/* Calling the function `refreshWLAN()` which is defined above. */
//refreshWLAN();