const apName = { "b4:xx:xx:f3:xx:63" : { aname: "AP-LongR"},
"18:xx:29:xx:xx:e2" : { aname: "AP-Light"}
}
const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
var fs = require('fs')
const datei = "/opt/iobroker/iobroker-data/files/iqontrol/htmlvoucher.html";
const datei2 = "/opt/iobroker/iobroker-data/files/iqontrol/htmlclients.html";
// Datenpunkte Hauptpfad wählen - WICHTIG muss mit der javascript instanz, ind er das script läuft zusammenpassen
const dpPrefix = "javascript.2.";
//Pause bei Umschalten der WLANnetze, damit Netzanmeldungen der clients wieder normal
const clientPauseConst = 200000; //1000 bedeutet 1 Sekunde - das braucht Zeit !!!
// Abfragezyklus definieren
const abfragezyklus =20000; // es ist nicht zu empfehlen unter 20000 (20 sekunden) zu gehen
const abfageoffset = 15000; // zu schnelle Abmeldungen können hier eingestellt weren - > erhöhen (15000 = 15 sek.)
//HIER Einstellungen : EIN-AUSSCHALTEN Vouchers, iqontrol-Datei erstellen, anwesenheitskontrolle-clientpflege
let iqontrol = true;
let anwesenheit = true; // beim setzen von true auf false die verzeichnisstruktur unter iobroker-objects "von hand" löschen
let vouchers = true;
let health = true; // Angaben zum Systemstatus - die Healtdaten werden nur alle 5 Abfragezyklen geholt
let aliasname=false; //benutzt alias namen, die im controller hinterlegt sind - anstatt hostname - VORSICHT kein ALIAS definiert - keine Anzeige des Clients!!!
// es funktioniren auch die Anwesenheitserkennung nicht !!!!, wenn kein Alias im
// Hier Definition iqontrol-Style für Popup
const format = "<!DOCTYPE html><html><head><title>Voucher</title></head><body><table style=\"color:black;text-align:center; font-family:Helvetica;background-image: linear-gradient(42deg,transparent, lightblue);\">";
const format2 = "<!DOCTYPE html><html><head><title>Clients</title></head><body><table style=\"color:black; font-family:Helvetica;background-image: linear-gradient(42deg,transparent, lightblue);\">";
const format3 = "<table style=\"color:#848484; font-family:Helvetica;\">";
//-----------------AB HIER NICHTS MEHR ÄNDERN------------------------
let cookies = [];
let loggedIn = false;
let debug = false;
let mylogs = false;
let clientPause = false;
let clientPauseVal;
let wifiDPs = [];
let myname = 'hostname';
let respv;
let respc;
let respw;
let resph;
let respgv;
let statusarr=[];
let versuch;
let listeDatenpunkte = [];
let lastChange=[];
let testerrc=false;
let testerrl=false;
let testerrv=false;
let testerrs=false;
let testerrh=false;
let testerrcv=false;
let testerrws=false;
var scriptCounter=0;
let alarmSwitch =false;
let alarmCounter =0;
let firstTime=0;
let mybodyVouchers;
var wifiLength=0;
for(let wifi_name in wifis) {
wifiLength++; }
if (aliasname) myname="name";
if ( !anwesenheit) fs.writeFileSync(datei2,("variable anwesenheit und/oder iqontrol ist nicht im unifiscript aktiviert - auf true setzen"));
if ( !vouchers) fs.writeFileSync(datei,("variable vouchers und/oder iqontrol ist nicht im unifiscript aktiviert - auf true setzen"));
//if (aliasname) realname="name";
//Erstelle Datenpunkte für die WLANs automatisch
for(let wifi_name in wifis) {
wifiDPs.push(dpPrefix + "WLANUnifi." + wifis[wifi_name].name);
createState(dpPrefix + "WLANUnifi."+ wifi_name, {
name: wifis[wifi_name].desc,
role: 'switch',
read: true,
write: true,
type: "boolean",
smartName: {
de: wifis[wifi_name].smart,
smartType: "SWITCH"
} });}
createState(dpPrefix + "WLANUnifi.Wifi_Clients", {
name: 'Unifi Wifi Clients Table',
role: 'string',
read: true,
write: true,
});
var foo = (aliasname) ? true : false;
createState(dpPrefix + "WLANUnifi.AliasName", foo, {
name: ' AliasName',
desc: 'schaltet Aliasnamen ein',
role: 'switch',
type: 'boolean',
read: true,
write: true,
} , function() {setStateDelayed(dpPrefix + "WLANUnifi.AliasName", foo, 200)});
createState(dpPrefix + "WLANUnifi.Aussortiert", {
name: 'Aussortiert',
role: 'string',
read: true,
write: true,
});
if (vouchers) {
createState(dpPrefix + "WLANUnifi.Wifi_Vouchers", {
name: 'Unifi Wifi Vouchers_Table',
role: 'string',
read: true,
write: true,
});
createState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Create", false, {
name: ' A_New_Voucher_Create',
role: 'switch',
type: 'boolean',
read: true,
write: true,
});
createState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Dauer", "must be set",{
name: ' A_New_Voucher_Dauer',
role: 'string',
read: true,
write: true,
});
createState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.MultiUse", "must be set",{
name: ' A_New_Voucher_MultiUse',
role: 'string',
read: true,
write: true,
});
createState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Anzahl", "must be set",{
name: ' A_New_Voucher_Anzahl',
role: 'string',
read: true,
write: true,
});
createState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Notiz", "",{
name: ' A_New_Voucher_Notiz',
role: 'string',
read: true,
write: true,
});
createState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Upload", "",{
name: ' A_New_Voucher_Uplaod',
role: 'string',
read: true,
write: true,
});
createState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Download", "",{
name: ' A_New_Voucher_Download',
role: 'string',
read: true,
write: true,
});
createState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Mb_Begrenzung", "", {
name: ' A_New_Voucher_Mb_Begrenzung',
role: 'string',
read: true,
write: true,
});
for (var i = 1; i < 21; i++) {
var x=i.toString();
if (i<10) x="0"+x;
createState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.CODE"+x, {
name: 'Unifi Voucher_Code'+x,
role: 'string',
read: true,
write: true,
});
createState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.CODE"+x+".code"+x, {
name: 'Unifi Voucher_Code_code'+x,
role: 'string',
read: true,
write: true,
});
createState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.CODE"+x+".erstellt", {
name: 'Unifi Voucher_Code_erstellt'+x,
role: 'string',
read: true,
write: true,
});
createState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.CODE"+x+".dauer", {
name: 'Unifi Voucher_Code_duration'+x,
role: 'string',
read: true,
write: true,
});
createState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.CODE"+x+".abgelaufen", {
name: 'Unifi Voucher_Code_expires'+x,
role: 'string',
read: true,
write: true,
});
}}
createState(dpPrefix + "WLANUnifi.Wifi_Clients_Anzahl", { name: 'Wifi_Clients_Anzahl', desc: 'Wifi_Clients_Anzahl', type: 'number', unit: '', min: '0', max: '100', role: '',read: true, write: true });
if (vouchers) createState(dpPrefix + "WLANUnifi.Wifi_Vouchers_Anzahl", { name: 'Wifi_Vouchers_Anzahl', desc: 'Wifi_Vouchers_Anzahl', type: 'number', unit: '', min: '0', max: '100', role: '',read: true, write: true });
if (health) {createState(dpPrefix + "WLANUnifi.Health.WLAN.Status", { name: 'Health_Status', desc: 'Health_Status', type: 'string', unit: '', role: '',read: true, write: true });
createState(dpPrefix + "WLANUnifi.Health.WLAN.Users", { name: 'Health_Users', desc: 'Health_Users', type: 'number', unit: '', min: '0', max: '1000', role: '',read: true, write: true });
createState(dpPrefix + "WLANUnifi.Health.WLAN.Guests", { name: 'Health_Guests', desc: 'Health_Guests', type: 'number', unit: '', min: '0', max: '100', role: '',read: true, write: true });
createState(dpPrefix + "WLANUnifi.Health.WLAN.TXBytes", { name: 'Health_TXBytes', desc: 'Health_TXBytes', type: 'number', unit: '', min: '0', max: '9999999', role: '',read: true, write: true });
createState(dpPrefix + "WLANUnifi.Health.WLAN.RXBytes", { name: 'Health_RXBytes', desc: 'Health_RXBytes', type: 'number', unit: '', min: '0', max: '9999999', role: '',read: true, write: true });
createState(dpPrefix + "WLANUnifi.Health.WLAN.Adopted", { name: 'Health_Adopted', desc: 'Health_Adopted', type: 'number', unit: '', min: '0', max: '100', role: '',read: true, write: true });
createState(dpPrefix + "WLANUnifi.Health.WLAN.Disabled", { name: 'Health_Disabled', desc: 'Health_Disabled', type: 'number', unit: '', min: '0', max: '100', role: '',read: true, write: true });
createState(dpPrefix + "WLANUnifi.Health.WLAN.Disconnected", { name: 'Health_Disconnected', desc: 'Health_Disconnected', type: 'number', unit: '', min: '0', max: '100', role: '',read: true, write: true }); }
function dlog(message) {
if(debug)
console.log(message);
}
function mylog(message) {
if(mylogs)
console.log(message);
}
//-----------------------------------------LOGIN---------------------------------------------------------------
async function login() {
return new Promise(async (resolve, reject) => {
cookies=[];
let respl = await request.post({
resolveWithFullResponse: true,
url: unifi_controller + "/api/login",
body: JSON.stringify({ username: unifi_username, password: unifi_password }),
headers: { 'Content-Type': 'application/json' }
}).catch((e) => { log("login: reject"), reject(e); loggedIn =false;return respl=[];});
if(respl != null) {
mylog("login: login war erfolgreich! " + ((respl.headers && respl.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies":"Ohne Cookies"));
if(respl.headers && respl.headers.hasOwnProperty("set-cookie")) {
let set_cookies = respl.headers["set-cookie"];
for(i = 0; i < set_cookies.length; i++) {
let cookie = set_cookies[i];
//log(set_cookies[i]);
cookie = cookie.split(";")[0];
cookies.push(cookie);
}
} else {
log("login: no cookies to set!")
}
loggedIn = true;
resolve();
} else {
log("login: rejected")
loggedIn = false;
reject("respl = null");
}
});
}
//-----------------------------------------LOGOUT---------------------------------------------------------------
async function logout() {
log("BIN IN LOGOUT");
return new Promise(async (resolve, reject) => {
let respo = await request.get({
url: unifi_controller + "/logout",
headers: { Cookie: cookies.join("; ") }
}).catch((e) => { log("logout fehler" + e)/*reject(e)*/ ;return testerrl=true;} );
if (!testerrl) {
if(respo != null) {
log("Du bist nun ausgedloggt.");
dlog(respo);
log("BIN raus aus LOGOUT");
loggedIn = true;
resolve();
} else {
reject("resp = null");
}
} else {log("reject weil resplogin ist 00"); log("BIN raus aus LOGOUT"); reject();}
log("BIN raus aus LOGOUT");
});
}
//-----------------------------------------STATUS WIFI ---------------------------------------------------------
//Updatet status vom Wifi
//wifi: wifi object aus der konstanten wifis
function getStatus(wifi) {
mylog("BIN IN STATUS");
return new Promise(async (resolve, reject) => {
dlog("nur mal so");
if (!loggedIn) await login().catch((e) => reject(e));
let resp = await request.get({
url: unifi_controller + "/api/s/default/rest/wlanconf/" + wifi.id,
headers: { Cookie: cookies.join("; ") }
}).catch((e) => { dlog("getStatus reject " + e); /*reject(e)*/ return testerrs=true; });
if (!testerrs) {
dlog("got response " + JSON.stringify(resp));
resp = JSON.parse(resp);
let wlanOn = resp.data[0].enabled;
dlog("WLAN " + wifi.name + " ist: " + (wlanOn ? "an" : "aus"));
if (resp != null && resp.meta && resp.meta.rc == "ok") {
dlog("Status erfolgreich geholt!");
dlog(resp);
let wlanOn = resp.data[0].enabled;
dlog("WLAN ist: " + (wlanOn ? "an" : "aus"));
setStateDelayed(dpPrefix + "WLANUnifi." + wifi.name, wlanOn, 200);
resolve(wlanOn);
} else {
log("nicht ok... getStatusWifi")
reject(JSON.stringify(resp));
}
} else {mylog("reject weil respslogin ist 00"); mylog("BIN raus aus LOGOUT"); reject();}
mylog("BIN aus STATUS raus");
});
}
//-----------------------------------------GETCLIENTS---------------------------------------------------------------
async function getClients() {
mylog("BIN IN getclients");
return new Promise(async (resolve, reject) => {
dlog("getclient nur mal so" + loggedIn);
if(!loggedIn) await login().catch((e) => reject(e));
respc = await request.get({
url: unifi_controller + "/api/s/default/stat/sta",
headers: { Cookie: cookies.join("; ") }
}).catch((e) => { log("getStatus reject " + e); /*reject(e)*/ return testerrc=true; });
if (!testerrc) {
dlog("got respconse nach log in getclient " + JSON.stringify(respc));
dlog(typeof respc);
dlog("--------------------- " + respc);
//respc = JSON.parse(respc);
//Sortierung Daten und Verwandlung Json
var unfiltered = [];
unfiltered = JSON.parse(respc).data;
dlog("bin da");
dlog(unfiltered[5][myname] + unfiltered[2].mac);
versuch = [];
let trash="";
for(var index in unfiltered) {
let device = unfiltered[index];
if(device[myname] !== undefined && device.essid !== undefined) {versuch.push(device); } /*else {if (aliasname) {trash = trash+unfiltered[index].hostname+","}
else {trash = trash+device[name]+","}}*/
//if(device[myname] !== undefined) {trash = trash+unfiltered[index].hostname+","}
}
setState(dpPrefix + "WLANUnifi.Aussortiert", trash);
versuch.sort(function (alpha, beta) {
if (alpha[myname].toLowerCase() < beta[myname].toLowerCase())
return -1;
if (alpha[myname].toLowerCase() > beta[myname].toLowerCase())
return 1;
return 0;
});
resolve();
} else {log("reject weil respc 00"); reject() } mylog("bin raus aus getclients");
}); //new promise
} //getclientend
//-----------------------------------------workCLIENTS---------------------------------------------------------------
function workClients() {
mylog("BIN IN workclients");
dlog("got respconse " + JSON.stringify(respc));
dlog(typeof respc);
dlog("--------------------- " + respc);
let writeFile = true;
let writeFileVar = 0;
let writeClientTable = true;
let writeAnwesenheit = true;
var anzahlClients = versuch.length;
setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Clients_Anzahl",anzahlClients,100);
var clientListe = "";
getExistingClients();
mylog("Status1");
var listeDatenpunkteNew=[]; //erstelle aktuelles array von controller daten
for (var i = 0; i < versuch.length; i++) {
listeDatenpunkteNew[i] = versuch[i][myname];
}
dlog (listeDatenpunkteNew[3]);
let notSeen=[];
// sind clients von controller in verzeichnisliste ?
for (var z = 0; z < listeDatenpunkteNew.length; z++)
{
if ( listeDatenpunkte.indexOf(listeDatenpunkteNew[z]) == -1 ){ //ist controller-client existent nicht in verzeichnis-list
mylog("Datenpunktanlegen" + listeDatenpunkteNew[z] +"index:"+ listeDatenpunkte.indexOf(listeDatenpunkteNew[z]).toString());
var ipWandler= versuch[z].ip;
var data = dpPrefix + "WLANUnifi.Wifi_Client_States."+listeDatenpunkteNew[z];
createState(data, true, {name: ipWandler, role: 'boolean',read: true, write: true, }, function() {mylog("created"); });
//setState(dpPrefix + "WLANUnifi.Wifi_Client_States."+ versuch[z][myname], true);
mylog("Datenpunktanlegen fertig" + listeDatenpunkteNew[z] + listeDatenpunkte[z]) ;
}
}
mylog("Status2");
//sind datenpunkte noch in controller vorhanden
if (anwesenheit) {
for (var z = 0; z < listeDatenpunkte.length; z++) {
if ( listeDatenpunkteNew.indexOf(listeDatenpunkte[z]) == -1 ){ //ist datenpunkt-verzeihnis existent und nicht in controller liste
notSeen.push(listeDatenpunkte[z]);//log(listeDatenpunkte[z]); //array der notSeen datenpunkte sind nicht im controller
if (getState(dpPrefix + "WLANUnifi.Wifi_Client_States."+listeDatenpunkte[z]).val) { // setze datenpunkt auf false - nur wenn true war
setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Client_States."+listeDatenpunkte[z], false, 500);
mylog("Datenpunkt ist falsch zu setzen"+listeDatenpunkte[z]);}
} else {dlog("ist noch im controller" + listeDatenpunkte[z]); }
} }
//sind datenpunkte nicht in controller vorhanden
mylog("Status3");
// setze datenpunkte nach last_seen_by_uap - ausnahme: controller-clients sind nicht mehr connectet aber in vereichnis
let lastChangeList;
if (anwesenheit) {
timeout = setTimeout(function () { //wegen createstate und zu schnelles setstate
for (var z = 0; z < listeDatenpunkteNew.length; z++) {
var tester = parseInt((new Date().getTime())) - (versuch[z]._last_seen_by_uap*1000);
dlog(tester.toString() + "laenge : " +listeDatenpunkteNew.length);
if (parseInt((new Date().getTime())) - (versuch[z]._last_seen_by_uap*1000) > abfragezyklus+abfageoffset && getState(dpPrefix + "WLANUnifi.Wifi_Client_States."+versuch[z][myname]).val) {
// if (!aliasname) {setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Client_States."+versuch[i].name, false, 100);} else {setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Client_States."+versuch[z][myname], false, 100)}
setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Client_States."+versuch[z][myname], false, 100);
mylog("abgesetzt: " +listeDatenpunkteNew[z] + " um " +formatDate(getDateObject((parseFloat((new Date().getTime())) - tester)), "SS:mm:ss") + " Uhr");
if (lastChange.length>=10) lastChange.shift()
lastChange.push("<tr><td>"+listeDatenpunkteNew[z]+"  </td><td>"+formatDate(getDateObject((parseFloat((new Date().getTime())) - tester)), "SS:mm:ss")+"    </td><td>out</td><td>  vor: "+tester/1000+" Sek</td></tr>");
mylog(lastChange[0]);
}
if (parseFloat((new Date().getTime())) - (versuch[z]._last_seen_by_uap*1000) < abfragezyklus && !getState(dpPrefix + "WLANUnifi.Wifi_Client_States."+versuch[z][myname]).val || getState(dpPrefix + "WLANUnifi.Wifi_Client_States."+versuch[z][myname]).val ==null ) {
// if (!aliasname) {setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Client_States."+versuch[i].name, true, 100);} else {setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Client_States."+versuch[z][myname], true, 100)}
setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Client_States."+versuch[z][myname], true, 100);
mylog("gesetzt" +listeDatenpunkteNew[z]+" " +formatDate(getDateObject((parseFloat((new Date().getTime())) - tester)), "SS:mm:ss") + " Uhr");
if (lastChange.length>=10) lastChange.shift()
lastChange.push("<tr><td>"+listeDatenpunkteNew[z]+"  </td><td>"+formatDate(getDateObject((parseFloat((new Date().getTime())) - tester)), "SS:mm:ss")+"    </td><td>in</td><td>  vor: " + tester/1000+" Sek</td></tr>");
}
}
mylog("Status4");
// erstelle htmlclientliste
for (var i = 0; i < versuch.length; i++) {
dlog(versuch[i][myname] + " --- " + versuch[i].essid + " --- " + versuch[i].ip);
if (parseInt((new Date().getTime())) - (versuch[i]._last_seen_by_uap*1000) < abfragezyklus+15000) {
for(let device_name in apName) { //Abfrage welcher AP
dlog(versuch[i].ap_mac +" - " + device_name +" - " + apName[device_name].aname);
if (versuch[i].ap_mac==device_name) var apTransfer = apName[device_name].aname};
clientListe = clientListe.concat("<tr><td>"+versuch[i][myname]+" </td><td>"+versuch[i].essid+"    </td><td>"+versuch[i].ip+"  </td><td>"+apTransfer+"</td></tr>");
dlog(clientListe);}
else {anzahlClients=anzahlClients-1; clientListe = clientListe.concat("<tr style=\"color:#01A9DB; font-family:Helvetica;font-style: italic;\" ><td>"+versuch[i][myname]+" </td><td>"+versuch[i].essid+"    </td><td>"+versuch[i].ip+"  </td><td>noConn</td></tr>");}
}
setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Clients_Anzahl",anzahlClients,100); //korrigiert
for (var h =0; h<notSeen.length;h++){
if (notSeen.indexOf(versuch[i]) == -1 )
clientListe = clientListe.concat("<tr style=\"color:#01A9DB; font-family:Helvetica;font-style: italic;\" ><td>"+notSeen[h]+
" </td><td>noConn    </td><td>noConn  </td><td>noConn</td></tr>");
}
mylog("Status5");
if (iqontrol && anwesenheit ) {
lastChangeList=format3;
for (var g = lastChange.length-1; g >= 0 ; g--) {
lastChangeList=lastChangeList.concat(lastChange[g]/*+"</table>"*/);
lastChangeList.concat(lastChange[g]+"</table>");
}
fs.writeFileSync(datei2, format2+clientListe.concat("</table><p style=\"color:#01A9DB; font-family:Helvetica;\">Geamtanzahl angemeldeter Clients:"+anzahlClients+"<br>Insgesamt Clients registriert: "+ listeDatenpunkte.length+
"</p><p style=\"color:#848484; font-family:Helvetica;\">Letzter Wechsel im Netzwerk:<br>"+lastChangeList+"</p>"
));
//if (lastChange.length>10) lastChange=[];
}
dlog("ClientFile schreibt! "+iqontrol.toString()+writeClientTable.toString());
if (true) setState(dpPrefix + "WLANUnifi.Wifi_Clients", "<table>"+clientListe.concat("</table>")); //schreibe client table
mylog("bin raus aus workclients");
}, 2500);}
} //workclientend
//-----------------------------------------EXISTING CLIENTS---------------------------------------------------------------
function getExistingClients() {
dlog("BIN IN EXISTING CLIENTS");
listeDatenpunkte = [];
var cacheSelectorState = $("state[state.id=" + dpPrefix + "WLANUnifi.Wifi_Client_States.*]");
cacheSelectorState.each(function (id, c) {
if (!id.includes("undefined")) {
listeDatenpunkte[c] = id.replace(dpPrefix + "WLANUnifi.Wifi_Client_States.", "");}
});
dlog("bin raus a existing clients");
}
//-----------------------------------------GET--VOUCHERS---------------------------------------------------------------
async function getVouchers() {
if (vouchers) {
mylog("BIN IN getvouchers");
return new Promise(async (resolve, reject) => {
dlog("nur mal so");
if(!loggedIn) await login().catch((e) => reject(e));
respv = await request.get({
url: unifi_controller + "/api/s/default/stat/voucher",
headers: { Cookie: cookies.join("; ") }
}).catch((e) => { dlog("getStatus reject " + e); /*reject(e)*/ return testerrv=true; });
if (!testerrv) {
dlog("got response " + JSON.stringify(respv));
dlog(typeof respv);
dlog("--------------------- " + respv);
resolve("done");
} else {log("reject weil respv ist 00"); reject();}
mylog("bin raus a GET vouchers");
});
}}
//-----------------------------------------WORK--VOUCHERS---------------------------------------------------------------
function workVouchers() {
if (vouchers) {
// mylog("BIN IN workvouchers");
dlog("got response " + JSON.stringify(respv));
dlog(typeof respv);
dlog("--------------------- " + respv);
respv = JSON.parse(respv);
dlog("--------------------- " + respv);
dlog(respv.meta);
dlog(respv.meta.rc);
dlog(respv.data[1].code);
dlog(respv.data.length);
dlog(JSON.stringify(respv).length.toString());
var writeFile;
var laengeMessage=JSON.stringify(respv).length;
if (laengeMessage==writeFileVar) {writeFile = false;} else {writeFile=true}
var writeFileVar=JSON.stringify(respv).length;
if (writeFile) {
var clientListe = "<tr><td>DAUER </td><td>FERTIG    </td><td>CODE</td>  </td><td>ERSTELLT</td>  <td>NOTIZ</td></tr> ";
for (var i = 1; i < 21; i++) {
var x=i.toString();
if ( i < 10) { var yyy="0"+x;} else {yyy=x}; setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.CODE"+yyy, "", 100);}
for (var i = 0; i < respv.data.length; i++) {
var zeit= respv.data[i].create_time*1000
let zeit1 = formatDate(getDateObject(zeit), "TT.MM.JJJJ SS:mm").toString();
let notizen;
if (respv.data[i].note !== null) { notizen=respv.data[i].note} else {notizen= "   -     ";}
clientListe = clientListe.concat("<tr><td>"+respv.data[i].duration+" </td><td>"+respv.data[i].status_expires+"    </td><td>"+respv.data[i].code+"  </td><td>" +zeit1 + "  </td><td>"+notizen+"</td></tr>");
var y=i+1;
var yy=y.toString();
if (y<10 ) yy="0"+yy;
if (i<20 ) {
dlog(zeit1);
setState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.CODE"+yy+".code"+yy, respv.data[i].code );
setState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.CODE"+yy+".erstellt", zeit1 );
setState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.CODE"+yy+".dauer", respv.data[i].duration );
setState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.CODE"+yy+".abgelaufen", respv.data[i].status_expires );
}}
}
//Datenpunkteäalt löschen
var w = respv.data.length;
for (i = w; i < 20; i++) {
var y=i+1;
var yy=y.toString();
if (y<10 ) yy="0"+yy;
setState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.CODE"+yy+".code"+yy, " na " );
setState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.CODE"+yy+".erstellt", " na " );
setState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.CODE"+yy+".dauer", " na " );
setState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.CODE"+yy+".abgelaufen", " na " );
}
}
if (iqontrol && writeFile) {fs.writeFileSync(datei, format + clientListe.concat("</table></style></body></html><p style=\"color:blue; font-family:Helvetica;\">Geamtanzahl Vouchers:"+respv.data.length+"</p>"));}
if (writeFile) setState(dpPrefix + "WLANUnifi.Wifi_Vouchers", "<table>"+clientListe.concat("</table></style></body></html>"));
if (writeFile) setState(dpPrefix + "WLANUnifi.Wifi_Vouchers_Anzahl", respv.data.length);
//mylog("BIN RAUS AUS workvouchers");
}
//-----------------------------------------GET--Health---------------------------------------------------------------
async function getHealth() {
if (vouchers) {
mylog("BIN IN gethealth");
return new Promise(async (resolve, reject) => {
dlog("nur mal so");
if(!loggedIn) await login().catch((e) => reject(e));
resph = await request.get({
url: unifi_controller + "/api/s/default/stat/health",
headers: { Cookie: cookies.join("; ") }
}).catch((e) => { log("getStatus reject " + e); /*reject(e)*/ return testerrh=true; });
if (!testerrh) {
dlog("got response " + JSON.stringify(resph));
dlog(typeof resph);
mylog("--------------------- " + resph);
resolve("done");
} else {log("reject weil resph ist 00"); reject();}
mylog("bin raus a GET health");
});
}}
//-----------------------------------------WORK--HEALTH---------------------------------------------------------------
function workHealth() {
mylog("BIN IN workhealth");
dlog("got response " + JSON.stringify(resph));
dlog(typeof resph);
dlog("--------------------- " + resph);
resph=resph.replace(/-r/g, "_r")
resph = JSON.parse(resph);
setState(dpPrefix + "WLANUnifi.Health.WLAN.Status",resph.data[0].status );
setState(dpPrefix + "WLANUnifi.Health.WLAN.Users",resph.data[0].num_user);
setState(dpPrefix + "WLANUnifi.Health.WLAN.Guests",resph.data[0].num_guest );
setState(dpPrefix + "WLANUnifi.Health.WLAN.TXBytes",resph.data[0].tx_bytes_r );
setState(dpPrefix + "WLANUnifi.Health.WLAN.RXBytes",resph.data[0].rx_bytes_r );
setState(dpPrefix + "WLANUnifi.Health.WLAN.Adopted",resph.data[0].num_adopted );
setState(dpPrefix + "WLANUnifi.Health.WLAN.Disabled",resph.data[0].num_disabled );
setState(dpPrefix + "WLANUnifi.Health.WLAN.Disconnected",resph.data[0].num_disconnected );
mylog("bin raus a work health");
}
//-----------------------------------------SET WIFIS - WIFI EIN-AUSSCHALTEN----------------------------------------------
//Wifi an-/ausschalten
//enabled: true = anschalten; false = ausschalten
//wifi: wifi object aus der konstanten wifis
async function setWifi(enabled, wifi) {
if (!clientPause) {
return new Promise(async (resolve, reject) => {
dlog("setWifi: start set Wifi_haupt");
if (!loggedIn) { dlog("need to login"); await login().catch((e) => reject(e)); }
dlog("setWifi: now setting Wifi_haupt");
let resp = request.post({
url: unifi_controller + "/api/s/default/upd/wlanconf/" + wifi.id,
body: JSON.stringify({ enabled }),
headers: { 'Content-Type': 'application/json', Cookie: cookies.join("; ") }
}).catch((e) => { dlog("setWifi: rejected: " + e); /*reject(e)*/ return testerrws=true; });
dlog("setWifi: got response")
if (resp != null) {
dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
dlog(resp);
// getclient() Pause für umschalten
if (firstTime>=wifiLength) {
// if (true) {
clientPause = true;
clientPauseVal=parseInt((new Date().getTime()));
}
setState(dpPrefix + "WLANUnifi." + wifi.name, enabled, enabled);
resolve();
} else {
dlog("setWifi: rejetced")
dlog("resp: " + JSON.stringify(resp));
reject("msg: " + JSON.parse(resp.body).meta.msg);}
});
} else { log("WLAN wird gerade umgeschaltet"); }
}
//-----------------------------------------CREATE VOUCHERS----------------------------------------------
//Wifi an-/ausschalten
//enabled: true = anschalten; false = ausschalten
//wifi: wifi object aus der konstanten wifis
async function createVoucher (mybody) {
mylog(JSON.stringify( mybody ));
return new Promise(async (resolve, reject) => {
log("createVoucher in aktion");
if (!loggedIn) { mylog("need to login"); await login().catch((e) => reject(e)); }
mylog("do it !");
let respcv = request.post({
url: unifi_controller + "/api/s/default/cmd/hotspot/" ,
body: JSON.stringify( mybody ),
// body: mybody,
headers: { 'Content-Type': 'application/json', Cookie: cookies.join("; ") }
}).catch((e) => { log("setWifi: rejected: " + e); /*reject(e)*/ return testerrcv=true; });
log("setWifi: got response")
log("------------: "+respcv);
});
}
//-----------------------------------------------SCHALTER------------------------------------------------
on({id: wifiDPs, ack: false, change: "ne"}, function (obj) {
var value = obj.state.val;
var dp2 = obj.name
setWifi(value, wifis[dp2]);
dlog(wifis[dp2])
if (firstTime<wifiLength+1) firstTime++;
});
//-----------------------------------------------Aliasnamen schalten------------------------------------------------
on({id: dpPrefix + "WLANUnifi.AliasName", change: "any"}, function (obj) {
(getState(dpPrefix + "WLANUnifi.AliasName").val) ? myname='name' : myname='hostname'
});
//-----------------------------------------------SCHALTER Create Voucher------------------------------------------------
on({id: dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Create", val: true}, function (obj) {
var mybodyVouchers;
var expire_var = getState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Dauer").val;
var n_var = getState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Anzahl").val ;
var quota_var = getState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.MultiUse").val ;
var note_var = getState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Notiz").val;
var up_var = getState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Upload").val ;
var down_var = getState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Download").val;
var MBytes_var = getState(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Mb_Begrenzung").val ;
if (expire_var !="must be set" && n_var!="must be set" && quota_var!="must be set" && !clientPause) {
// Orginal JSON Daten
/* mybodyVouchers = {cmd:'create-voucher',expire:expire_var,
n:n_var,
quota:quota_var,
note:note_var,
up:up_var,
down:down_var,
MBytes:MBytes_var };*/
var x = "{cmd:'create-voucher',expire:"+expire_var+", n:"+n_var+", quota:"+quota_var+","
if (note_var != "") x= x.concat('note:\"'+note_var+'\",')
if (up_var != "") x= x.concat("up:"+up_var+",")
if (down_var != "") x= x.concat("down:"+down_var+",")
if (MBytes_var != "") x= x.concat("MBytes:"+MBytes_var+",")
x=x.substr(0, x.length-1);
x=x.concat("}");
//log (x);
eval('var mybodyVouchers='+x);
log(mybodyVouchers);
createVoucher(mybodyVouchers);
} else {log("FEHLER IN createVoucher - sind die 'must be set' Werte gesetzt?","error")}
setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Create",false, 4000);
setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Dauer", "must be set" , 2000);
setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Anzahl", "must be set", 2000);
setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.MultiUse", "must be set", 2000);
setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Notiz", "", 2000);
setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Upload", "", 2000);
setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Download", "", 2000);
setStateDelayed(dpPrefix + "WLANUnifi.Wifi_Vouchers-CODES.A_New_Voucher.Mb_Begrenzung", "", 2000);
});
//-----------------------------------------------MAIN LOOP------------------------------------------------
setInterval(async () => {
// for (let suche in wifis) {
// if ( getState(dpPrefix + "WLANUnifi."+suche).val == null ) {log("datanpunkt ist null")} else {log("datanpunkt ist geschrieben - nicht null")};}
scriptCounter++
mylog("-----------------------SCRIPTCOUNTER------------------ ist : " + scriptCounter );
mylog(loggedIn.toString())
await login().catch(alarm1)
// log("------------------------------------------------Werte Alarme: " + testerrl + " - " + testerrc+ " - " +testerrv + " - "+testerrs + " - "+testerrh);
if (loggedIn) {
if (alarmCounter > 5) {log("Unifi Sript funktioniert wieder - Verbindung wieder hergestellt","error");}
if (alarmCounter > 0) {alarmCounter=0; }
await getClients().catch(alarm3) ;
if (vouchers) await getVouchers().catch(alarm4);
if (health) await getHealth().catch(alarm7);
if ( !testerrl && !testerrc && !testerrv && !testerrs && !testerrh ) {
workVouchers();
if (!clientPause) workClients();
if (health && scriptCounter==5) {scriptCounter=0;workHealth();}
}
for(let wifi_name in wifis) {
if ( firstTime == 3 && getState(dpPrefix + "WLANUnifi."+wifi_name).val !== null ) firstTime = 3;
await getStatus(wifis[wifi_name]).catch(alarm6)}
} else { alarmCounter++;
if (alarmCounter > 5) {log("Unifi Sript hat 'Problem mit Einloggen - Prüfe Unifi Controller, Port, Einlog-Daten","error");
if (!testerrv) log("evtl. Vouchers deaktivieren","warn");}}
if (clientPause) {
var interim=parseInt(new Date().getTime());
log("Unifi Script ist in Pause wegen WLAN Umschalteung- bis: " + formatDate(clientPauseVal + clientPauseConst, "SS:mm:ss"),"warn");
if (interim - clientPauseVal > clientPauseConst) {clientPause=false;log("Unifi Script hat Pause beendet" );} }
testerrc=false;
testerrv=false;
testerrs=false;
testerrl=false;
testerrc=false;
testerrh=false;
}, abfragezyklus); // wird oben definiert
function alarm12() {log("Im Unifi Script stimmte etwas nicht - Alarm12 - Create Voucher","warn"); loggedIn=false; testerrcv=false;cookies=[];}
function alarm11() {log("Im Unifi Script stimmte etwas nicht - Alarm11 - WLAN schalten","warn"); loggedIn=false; testerrws=false;cookies=[];}
function alarm7() {log("Im Unifi Script stimmte etwas nicht - Alarm7 - Health","warn"); loggedIn=false; testerrh=false;cookies=[];}
function alarm6() {log("Im Unifi Script stimmte etwas nicht - Alarm6 - Statusabfrage","warn"); loggedIn=false; testerrs=false;cookies=[];}
function alarm5() {log("Im Unifi Script stimmte etwas nicht - Alarm5 - logout","warn"); loggedIn=false; testerrl=false;cookies=[];}
function alarm4() {log("Im Unifi Script stimmte etwas nicht - Alarm4 - getVouchers-Login","warn"); loggedIn=false; testerrv=false;cookies=[];}
function alarm3() {log("Im Unifi Script stimmte etwas nicht - Alarm3 - getClient-Login","warn"); loggedIn=false; testerrc=false;cookies=[];}
function alarm1() {log("Im Unifi Script stimmte etwas nicht - Alarm1 - Login fehlgeschlagen","warn"); loggedIn=false; ;alarmSwitch=true }
// Beispiel für
//setWifi(true, wifis.WLAN_DragonGuest);