Skip to content
  • Home
  • Aktuell
  • Tags
  • 0 Ungelesen 0
  • Kategorien
  • Unreplied
  • Beliebt
  • GitHub
  • Docu
  • Hilfe
Skins
  • Light
  • Brite
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Standard: (Kein Skin)
  • Kein Skin
Einklappen
ioBroker Logo

Community Forum

  1. ioBroker Community Home
  2. Deutsch
  3. Skripten / Logik
  4. JavaScript
  5. Unifi WLAN Script

NEWS

  • UPDATE 31.10.: Amazon Alexa - ioBroker Skill läuft aus ?
    apollon77A
    apollon77
    48
    3
    8.3k

  • Monatsrückblick – September 2025
    BluefoxB
    Bluefox
    13
    1
    1.9k

  • Neues Video "KI im Smart Home" - ioBroker plus n8n
    BluefoxB
    Bluefox
    15
    1
    2.3k

Unifi WLAN Script

Geplant Angeheftet Gesperrt Verschoben JavaScript
380 Beiträge 13 Kommentatoren 57.1k Aufrufe 13 Watching
  • Älteste zuerst
  • Neuste zuerst
  • Meiste Stimmen
Antworten
  • In einem neuen Thema antworten
Anmelden zum Antworten
Dieses Thema wurde gelöscht. Nur Nutzer mit entsprechenden Rechten können es sehen.
  • dslraserD dslraser

    @liv-in-sky

    Ich habe im Büro eben auch mal ein wenig Zeit gehabt und habe bei mir mal etwas "aufgeräumt" im Script.
    Vielleicht magst Du mal testen ?
    Ich habe jetzt 2 WLAN Netze in einem Script bei mir, also Haupt WLAN und Gast WLAN. Um zu sehen ob es funktioniert habe ich das Aktualisierungsintervall auf 10 Sekunden. Bei mir gehen beide Netze in einem Script und sind auch schaltbar. Deine Geräteliste habe ich schon mit drinn. Die Voucherliste habe ich noch nicht drinn, nur bisher die Datenpunkte dazu.
    Angelegt wird es jetzt unter javascript.0 (ohne die bisherige Ordberstruktur.)
    sieht dann so aus:
    Bildschirmfoto 2019-08-29 um 19.05.42.png

    const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
    const unifi_username = "benutzer";
    const unifi_password = "passwort";
    const unifi_controller = "https://192.168.xxx.xxx:xxxx";
    const wifi_id_haupt = "xxxxxxxxxx";
    const wifi_id_gast = "xxxxxxxxxx";
    let cookies = [];
    let loggedIn = false;
    let debug = false;
    
    on({id:'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an'/*Unifi Haupt Wifi an*/, val: true, change: 'any'}, wifi_an_haupt);
    on({id:'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus'/*Unifi Haupt Wifi aus*/, val: true, change: 'any'}, wifi_aus_haupt);
    on({id:'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an'/*Unifi Gast Wifi an*/, val: true, change: 'any'}, wifi_an_gast);
    on({id:'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus'/*Unifi Gast Wifi aus*/, val: true, change: 'any'}, wifi_aus_gast);
    
    //##########---hier Haupt WLAN---##########
    //Datenpunkt für Haupt Wifi Status erstellen
    createState('Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status',{
       name: 'Unifi Haupt Wifi Status', 
       role: 'switch',
       type: "boolean",
       read:  true,
       write: false,
    });
    //Datenpunkt Button zum schalten für Haupt Wifi an erstellen
    createState('Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an', {
       name: 'Unifi Haupt Wifi an', 
       role: 'button',
       read:  true, 
       write: true,
       type: "boolean",
       "smartName": {
       "de": "01Haupt Wlan an",
       "smartType": "SWITCH"
    }
    });
    //Datenpunkt Button zum schalten für Haupt Wifi aus erstellen
    createState('Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus', {
       name: 'Unifi Haupt Wifi aus', 
       role: 'button',
       read:  true, 
       write: true,
       type: "boolean",
       "smartName": {
       "de": "02Haupt Wlan aus",
       "smartType": "SWITCH"
    }
    });
    //##########---hier Gast WLAN---##########
    //Datenpunkt für Gast Wifi Status erstellen
    createState('Unifi.Unifi_Wifi.02Gast_Wifi.01Gast_Wifi_Status',{
       name: 'Unifi Gast Wifi Status', 
       role: 'switch',
       type: "boolean",
       read:  true,
       write: false,
    });
    //Datenpunkt Button zum schalten für Gast Wifi an erstellen
    createState('Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an', {
       name: 'Unifi Gast Wifi an', 
       role: 'button',
       read:  true, 
       write: true,
       type: "boolean",
       "smartName": {
       "de": "01Gast Wlan an",
       "smartType": "SWITCH"
    }
    });
    //Datenpunkt Button zum schalten für Gast Wifi aus erstellen
    createState('Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus', {
       name: 'Unifi Gast Wifi aus', 
       role: 'button',
       read:  true, 
       write: true,
       type: "boolean",
       "smartName": {
       "de": "02Gast Wlan aus",
       "smartType": "SWITCH"
    }
    });
    //Datenpunkt für Anzahl Voucher erstellen
    createState('Unifi.Unifi_Wifi.02Gast_Wifi.04Gast_Wifi_Anzahl_Voucher',{ 
       name: 'Unifi Gast Wifi Anzahl Voucher',  
       role: 'number',
       min: '0', 
       max: '1000',
       read: true, 
       write: false }); 
    //Datenpunkt Liste für Voucher für Gast Wifi erstellen
    createState('Unifi.Unifi_Wifi.02Gast_Wifi.05Gast_Wifi_Voucherliste', {
       name: 'Unifi Gast Wifi Voucherliste', 
       role: 'string',
       read:  true, 
       write: false,
    });
    //##########---hier Geräteliste und Anzahl Geräte---##########
    //Datenpunkt Liste für angemeldete Geräte im Netzwerk erstellen
    createState('Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste', {
       name: 'Unifi Haupt Wifi Geräteliste', 
       role: 'string',
       read:  true, 
       write: false,
    });
    //Datenpunkt für Anzahl angemeldete Geräte erstellen
    createState('Unifi.Unifi_Wifi.01Haupt_Wifi.05Haupt_Wifi_Anzahl_Geraete',{ 
       name: 'Unifi Haupt Wifi Anzahl Clients',  
       role: 'number',
       min: '0', 
       max: '1000',
       read: true, 
       write: false }); 
     
    function dlog(message) {
      if(debug)
          console.log(message);
    }
     
    async function login() {
      return new Promise(async (resolve, reject) => {
          let resp = 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) => { dlog("login: reject"), reject(e) });
          
          if(resp != null) {
              dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies":"Ohne Cookies"));
              if(resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
                  let set_cookies = resp.headers["set-cookie"];
                  for(i = 0; i < set_cookies.length; i++) {
                      let cookie = set_cookies[i];
                      cookie = cookie.split(";")[0];
                      cookies.push(cookie);
                  }
              } else {
                  dlog("login: no cookies to set!")
              }
              loggedIn = true;
              resolve();
          } else {
              dlog("login: rejected")
              reject("resp = null");
          }
      });
    }
     
    async function getStatus_haupt() {
       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_haupt,
               headers: { Cookie: cookies.join("; ") }
           }).catch((e) => { dlog("getStatus reject " + e); reject(e) });
       
           dlog("got response " + JSON.stringify(resp));
           dlog(typeof resp);
           resp = JSON.parse(resp);
           dlog(resp.meta);
           dlog(resp.meta.rc);
           
           let wlanOn = resp.data[0].enabled;
           dlog("WLAN 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"));
               resolve(wlanOn);
           } else {
               dlog("nicht ok...")
               
               reject(JSON.stringify(resp));
           }
       });
    }
     
    async function setWifi_haupt(enabled) {
      return new Promise(async (resolve, reject) => {
          dlog("setWifi_haupt: start set Wifi_haupt");
          if(!loggedIn) { dlog("need to login"); await login().catch((e) => reject(e)); }
          dlog("setWifi_haupt: now setting Wifi_haupt");
          let resp = request.post({
              url: unifi_controller + "/api/s/default/upd/wlanconf/" + wifi_id_haupt,
              body: JSON.stringify({ enabled }),
              headers: { 'Content-Type': 'application/json', Cookie: cookies.join("; ") }
          }).catch((e) => { dlog("setWifi: rejected: " + e); reject(e) });
          dlog("setWifi: got response")
          if(resp != null) {
              dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
              dlog(resp);
              resolve();
          } else {
              dlog("setWifi: rejetced")
              dlog("resp: " + JSON.stringify(resp));
              reject("msg: " + JSON.parse(resp.body).meta.msg);
          }
      });
    }
    //########################################
    async function getStatus_gast() {
       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_gast,
               headers: { Cookie: cookies.join("; ") }
           }).catch((e) => { dlog("getStatus reject " + e); reject(e) });
       
           dlog("got response " + JSON.stringify(resp));
           dlog(typeof resp);
           resp = JSON.parse(resp);
           dlog(resp.meta);
           dlog(resp.meta.rc);
           
           let wlanOn = resp.data[0].enabled;
           dlog("WLAN 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"));
               resolve(wlanOn);
           } else {
               dlog("nicht ok...")
               
               reject(JSON.stringify(resp));
           }
       });
    }
     
    async function setWifi_gast(enabled) {
      return new Promise(async (resolve, reject) => {
          dlog("setWifi_gast: start set Wifi_gast");
          if(!loggedIn) { dlog("need to login"); await login().catch((e) => reject(e)); }
          dlog("setWifi_gast: now setting Wifi_gast");
          let resp = request.post({
              url: unifi_controller + "/api/s/default/upd/wlanconf/" + wifi_id_gast,
              body: JSON.stringify({ enabled }),
              headers: { 'Content-Type': 'application/json', Cookie: cookies.join("; ") }
          }).catch((e) => { dlog("setWifi: rejected: " + e); reject(e) });
          dlog("setWifi: got response")
          if(resp != null) {
              dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
              dlog(resp);
              resolve();
          } else {
              dlog("setWifi: rejetced")
              dlog("resp: " + JSON.stringify(resp));
              reject("msg: " + JSON.parse(resp.body).meta.msg);
          }
      });
    }
    //###################################
    //Geräteliste abrufen
    async function getClients() {
      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/stat/sta/",
              headers: { Cookie: cookies.join("; ") }
          }).catch((e) => { dlog("getStatus_haupt reject " + e); reject(e) });  
     
    dlog("got response " + JSON.stringify(resp));
    dlog(typeof resp);
    dlog("--------------------- " + resp);
    resp = JSON.parse(resp);
    //log("--------------------- " + resp);
     
    dlog(resp.meta);
    dlog(resp.meta.rc);
    dlog(resp.data[2].hostname);
    dlog(resp.data.length);
    setState("javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.05Haupt_Wifi_Anzahl_Geraete",resp.data.length);
    var clientListe = "<table>";
    for (var i = 0; i < resp.data.length; i++) { 
      dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
       clientListe = clientListe.concat("<tr><td>"+resp.data[i].hostname+"&ensp;</td><td>"+resp.data[i].essid+"&ensp;&ensp;&ensp;&ensp;</td><td>"+resp.data[i].mac+"</td></tr>");
       dlog(clientListe);
    }
    setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste", clientListe.concat(clientListe+"</table>"));
    });
    }
     
    async function wifi_an_haupt() {
       dlog("starting wifi_an_haupt");
       await setWifi_haupt(true).catch((e) => dlog("reject1: " + e));
       dlog("getting status");
       let wlan = await getStatus_haupt().catch((e) => dlog("reject2: " + e));
       console.log("fin")
       console.log(wlan);
    }
    async function wifi_aus_haupt() {
       dlog("starting wifi_aus_haupt");
       await setWifi_haupt(false).catch((e) => dlog("reject1: " + e));
       dlog("getting status");
       let wlan = await getStatus_haupt().catch((e) => dlog("reject2: " + e));
       console.log("fin")
       console.log(wlan);
    }
     
    //####################
    async function wifi_an_gast() {
       dlog("starting wifi_an_gast");
       await setWifi_gast(true).catch((e) => dlog("reject1: " + e));
       dlog("getting status");
       let wlan = await getStatus_gast().catch((e) => dlog("reject2: " + e));
       console.log("fin")
       console.log(wlan);
    }
    async function wifi_aus_gast() {
       dlog("starting wifi_aus_gast");
       await setWifi_gast(false).catch((e) => dlog("reject1: " + e));
       dlog("getting status");
       let wlan = await getStatus_gast().catch((e) => dlog("reject2: " + e));
       console.log("fin")
       console.log(wlan);
    }
    //#######################
     
    setInterval(async () => {
    let state = await getStatus_haupt();
       setState("Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status", state, true);
    }, 10000); // Aktualisiert alle 10 Sekunden.
     
    setInterval(async () => {
    let state = await getClients();
       setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Anzahl_Geraete");
       setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste", clientListe.concat(clientListe+"</table>"));
    }, 10000); // Aktualisiert alle 10 Sekunden.
     
    setInterval(async () => {
    let state = await getStatus_gast();
       setState("Unifi.Unifi_Wifi.02Gast_Wifi.01Gast_Wifi_Status", state, true);
    }, 10000); // Aktualisiert alle 10 Sekunden.
     
     
     
    //wifi_an_haupt();
    //wifi_aus_haupt();
    //getStatus_haupt();
    //getStatus_gast();
    //getClients();
    

    thewhoboxT Offline
    thewhoboxT Offline
    thewhobox
    schrieb am zuletzt editiert von
    #61

    @dslraser Entschuldige, wenn ich mich nochmal einmische, aber du hattest echt vielen unnötigen Code in deinem Skript^^
    Ich hab das mal zusammen gefasst:

    const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
    const unifi_username = "benutzer";
    const unifi_password = "passwort";
    const unifi_controller = "https://192.168.xxx.xxx:xxxx";
    const wifi_id_haupt = "xxxxxxxxxxxxxxx";
    const wifi_id_gast = "xxxxxxxxxxxxxxx";
    
    let cookies = [];
    let loggedIn = false;
    let debug = false;
    
    
    
    on({ id: 'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an'/*Unifi Haupt Wifi an*/, val: true, change: 'any' }, () => {
       setWifi(true, wifi_id_haupt);
    });
    
    on({ id: 'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus'/*Unifi Haupt Wifi aus*/, val: true, change: 'any' }, () => {
       setWifi(false, wifi_id_haupt);
    });
    
    on({ id: 'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an'/*Unifi Gast Wifi an*/, val: true, change: 'any' }, () => {
       setWifi(true, wifi_id_gast);
    });
    
    on({ id: 'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus'/*Unifi Gast Wifi aus*/, val: true, change: 'any' }, () => {
       setWifi(false, wifi_id_gast);
    });
    
    
    
    //##########---hier Haupt WLAN---##########
    
    //Datenpunkt für Haupt Wifi Status erstellen
    
    createState('Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status', {
       name: 'Unifi Haupt Wifi Status',
       role: 'switch',
       type: "boolean",
       read: true,
       write: false,
    });
    
    //Datenpunkt Button zum schalten für Haupt Wifi an erstellen
    
    createState('Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an', {
       name: 'Unifi Haupt Wifi an',
       role: 'button',
       read: true,
       write: true,
       type: "boolean",
       "smartName": {
       	"de": "01Haupt Wlan an",
       	"smartType": "SWITCH"
       }
    });
    
    //Datenpunkt Button zum schalten für Haupt Wifi aus erstellen
    
    createState('Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus', {
       name: 'Unifi Haupt Wifi aus',
       role: 'button',
       read: true,
       write: true,
       type: "boolean",
       "smartName": {
       	"de": "02Haupt Wlan aus",
       	"smartType": "SWITCH"
       }
    });
    
    //##########---hier Gast WLAN---##########
    
    //Datenpunkt für Gast Wifi Status erstellen
    
    createState('Unifi.Unifi_Wifi.02Gast_Wifi.01Gast_Wifi_Status', {
       name: 'Unifi Gast Wifi Status',
       role: 'switch',
       type: "boolean",
       read: true,
       write: false,
    });
    
    //Datenpunkt Button zum schalten für Gast Wifi an erstellen
    
    createState('Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an', {
       name: 'Unifi Gast Wifi an',
       role: 'button',
       read: true,
       write: true,
       type: "boolean",
       "smartName": {
       	"de": "01Gast Wlan an",
       	"smartType": "SWITCH"
       }
    });
    
    //Datenpunkt Button zum schalten für Gast Wifi aus erstellen
    
    createState('Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus', {
       name: 'Unifi Gast Wifi aus',
       role: 'button',
       read: true,
       write: true,
       type: "boolean",
       "smartName": {
       	"de": "02Gast Wlan aus",
       	"smartType": "SWITCH"
       }
    });
    
    //Datenpunkt für Anzahl Voucher erstellen
    
    createState('Unifi.Unifi_Wifi.02Gast_Wifi.04Gast_Wifi_Anzahl_Voucher', {
       name: 'Unifi Gast Wifi Anzahl Voucher',
       role: 'number',
       min: '0',
       max: '1000',
       read: true,
       write: false
    });
    
    //Datenpunkt Liste für Voucher für Gast Wifi erstellen
    
    createState('Unifi.Unifi_Wifi.02Gast_Wifi.005Gast_Wifi_Voucherliste', {
       name: 'Unifi Gast Wifi Voucherliste',
       role: 'string',
       read: true,
       write: false,
    });
    
    //##########---hier Geräteliste und Anzahl Geräte---##########
    
    //Datenpunkt Liste für angemeldete Geräte im Netzwerk erstellen
    
    createState('Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste', {
       name: 'Unifi Haupt Wifi Geräteliste',
       role: 'string',
       read: true,
       write: false,
    });
    
    //Datenpunkt für Anzahl angemeldete Geräte erstellen
    
    createState('Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Anzahl_Geraete', {
       name: 'Unifi Haupt Wifi Anzahl Clients',
       role: 'number',
       min: '0',
       max: '1000',
       read: true,
       write: false
    });
    
    
    
    function dlog(message) {
       if (debug)
       	console.log(message);
    }
    
    
    
    async function login() {
       return new Promise(async (resolve, reject) => {
       	let resp = 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) => { dlog("login: reject"), reject(e) });
    
       	if (resp != null) {
       		dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies" : "Ohne Cookies"));
       		if (resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
       			let set_cookies = resp.headers["set-cookie"];
       			for (i = 0; i < set_cookies.length; i++) {
       				let cookie = set_cookies[i];
       				cookie = cookie.split(";")[0];
       				cookies.push(cookie);
       			}
       		} else {
       			dlog("login: no cookies to set!")
       		}
       		loggedIn = true;
       		resolve();
       	} else {
       		dlog("login: rejected")
       		reject("resp = null");
       	}
       });
    }
    
    async function getStatus(wifi_id) {
       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) });
    
       	dlog("got response " + JSON.stringify(resp));
       	dlog(typeof resp);
       	resp = JSON.parse(resp);
       	dlog(resp.meta);
       	dlog(resp.meta.rc);
    
       	let wlanOn = resp.data[0].enabled;
       	dlog("WLAN 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"));
       		resolve(wlanOn);
       	} else {
       		dlog("nicht ok...")
       		reject(JSON.stringify(resp));
       	}
    
       });
    
    }
    
    
    
    async function setWifi(enabled, wifi_id) {
       return new Promise(async (resolve, reject) => {
       	dlog("setWifi: start set Wifi_haupt - " + wifi_id);
       	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) });
    
       	dlog("setWifi: got response")
    
       	if (resp != null) {
       		dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
       		dlog(resp);
       		resolve();
       	} else {
       		dlog("setWifi: rejetced")
       		dlog("resp: " + JSON.stringify(resp));
       		reject("msg: " + JSON.parse(resp.body).meta.msg);
       	}
       });
    }
    
    //###################################
    
    //Geräteliste abrufen
    
    async function getClients() {
       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/stat/sta/",
       		headers: { Cookie: cookies.join("; ") }
       	}).catch((e) => { dlog("getClients reject " + e); reject(e) });
    
       	dlog("got response " + JSON.stringify(resp));
       	dlog(typeof resp);
       	dlog("--------------------- " + resp);
       	resp = JSON.parse(resp);
    
       	setState("javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Anzahl_Geraete", resp.data.length);
       	var clientListe = "<table>";
       	for (var i = 0; i < resp.data.length; i++) {
       		dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
       		clientListe = clientListe.concat("<tr><td>" + resp.data[i].hostname + "&ensp;</td><td>" + resp.data[i].essid + "&ensp;&ensp;&ensp;&ensp;</td><td>" + resp.data[i].mac + "</td></tr>");
       		dlog(clientListe);
       	}
       	setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste", clientListe.concat(clientListe + "</table>"));
       });
    }
    
    
    setInterval(async () => {
       let state = await getStatus(wifi_id_haupt);
       setState("Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status", state, true);
       state = await getStatus(wifi_id_gast);
       setState("Unifi.Unifi_Wifi.01Haupt_Wifi.01Gast_Wifi_Status", state, true);
    
       await getClients();
    }, 10000); // Aktualisiert alle 10 Sekunden.
    

    Meine Adapter: emby | discovery
    Benutzt das Voting rechts unten im Beitrag wenn er euch geholfen hat.

    dslraserD liv-in-skyL ChaotC 4 Antworten Letzte Antwort
    1
    • thewhoboxT thewhobox

      @dslraser Entschuldige, wenn ich mich nochmal einmische, aber du hattest echt vielen unnötigen Code in deinem Skript^^
      Ich hab das mal zusammen gefasst:

      const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
      const unifi_username = "benutzer";
      const unifi_password = "passwort";
      const unifi_controller = "https://192.168.xxx.xxx:xxxx";
      const wifi_id_haupt = "xxxxxxxxxxxxxxx";
      const wifi_id_gast = "xxxxxxxxxxxxxxx";
      
      let cookies = [];
      let loggedIn = false;
      let debug = false;
      
      
      
      on({ id: 'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an'/*Unifi Haupt Wifi an*/, val: true, change: 'any' }, () => {
         setWifi(true, wifi_id_haupt);
      });
      
      on({ id: 'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus'/*Unifi Haupt Wifi aus*/, val: true, change: 'any' }, () => {
         setWifi(false, wifi_id_haupt);
      });
      
      on({ id: 'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an'/*Unifi Gast Wifi an*/, val: true, change: 'any' }, () => {
         setWifi(true, wifi_id_gast);
      });
      
      on({ id: 'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus'/*Unifi Gast Wifi aus*/, val: true, change: 'any' }, () => {
         setWifi(false, wifi_id_gast);
      });
      
      
      
      //##########---hier Haupt WLAN---##########
      
      //Datenpunkt für Haupt Wifi Status erstellen
      
      createState('Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status', {
         name: 'Unifi Haupt Wifi Status',
         role: 'switch',
         type: "boolean",
         read: true,
         write: false,
      });
      
      //Datenpunkt Button zum schalten für Haupt Wifi an erstellen
      
      createState('Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an', {
         name: 'Unifi Haupt Wifi an',
         role: 'button',
         read: true,
         write: true,
         type: "boolean",
         "smartName": {
         	"de": "01Haupt Wlan an",
         	"smartType": "SWITCH"
         }
      });
      
      //Datenpunkt Button zum schalten für Haupt Wifi aus erstellen
      
      createState('Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus', {
         name: 'Unifi Haupt Wifi aus',
         role: 'button',
         read: true,
         write: true,
         type: "boolean",
         "smartName": {
         	"de": "02Haupt Wlan aus",
         	"smartType": "SWITCH"
         }
      });
      
      //##########---hier Gast WLAN---##########
      
      //Datenpunkt für Gast Wifi Status erstellen
      
      createState('Unifi.Unifi_Wifi.02Gast_Wifi.01Gast_Wifi_Status', {
         name: 'Unifi Gast Wifi Status',
         role: 'switch',
         type: "boolean",
         read: true,
         write: false,
      });
      
      //Datenpunkt Button zum schalten für Gast Wifi an erstellen
      
      createState('Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an', {
         name: 'Unifi Gast Wifi an',
         role: 'button',
         read: true,
         write: true,
         type: "boolean",
         "smartName": {
         	"de": "01Gast Wlan an",
         	"smartType": "SWITCH"
         }
      });
      
      //Datenpunkt Button zum schalten für Gast Wifi aus erstellen
      
      createState('Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus', {
         name: 'Unifi Gast Wifi aus',
         role: 'button',
         read: true,
         write: true,
         type: "boolean",
         "smartName": {
         	"de": "02Gast Wlan aus",
         	"smartType": "SWITCH"
         }
      });
      
      //Datenpunkt für Anzahl Voucher erstellen
      
      createState('Unifi.Unifi_Wifi.02Gast_Wifi.04Gast_Wifi_Anzahl_Voucher', {
         name: 'Unifi Gast Wifi Anzahl Voucher',
         role: 'number',
         min: '0',
         max: '1000',
         read: true,
         write: false
      });
      
      //Datenpunkt Liste für Voucher für Gast Wifi erstellen
      
      createState('Unifi.Unifi_Wifi.02Gast_Wifi.005Gast_Wifi_Voucherliste', {
         name: 'Unifi Gast Wifi Voucherliste',
         role: 'string',
         read: true,
         write: false,
      });
      
      //##########---hier Geräteliste und Anzahl Geräte---##########
      
      //Datenpunkt Liste für angemeldete Geräte im Netzwerk erstellen
      
      createState('Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste', {
         name: 'Unifi Haupt Wifi Geräteliste',
         role: 'string',
         read: true,
         write: false,
      });
      
      //Datenpunkt für Anzahl angemeldete Geräte erstellen
      
      createState('Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Anzahl_Geraete', {
         name: 'Unifi Haupt Wifi Anzahl Clients',
         role: 'number',
         min: '0',
         max: '1000',
         read: true,
         write: false
      });
      
      
      
      function dlog(message) {
         if (debug)
         	console.log(message);
      }
      
      
      
      async function login() {
         return new Promise(async (resolve, reject) => {
         	let resp = 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) => { dlog("login: reject"), reject(e) });
      
         	if (resp != null) {
         		dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies" : "Ohne Cookies"));
         		if (resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
         			let set_cookies = resp.headers["set-cookie"];
         			for (i = 0; i < set_cookies.length; i++) {
         				let cookie = set_cookies[i];
         				cookie = cookie.split(";")[0];
         				cookies.push(cookie);
         			}
         		} else {
         			dlog("login: no cookies to set!")
         		}
         		loggedIn = true;
         		resolve();
         	} else {
         		dlog("login: rejected")
         		reject("resp = null");
         	}
         });
      }
      
      async function getStatus(wifi_id) {
         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) });
      
         	dlog("got response " + JSON.stringify(resp));
         	dlog(typeof resp);
         	resp = JSON.parse(resp);
         	dlog(resp.meta);
         	dlog(resp.meta.rc);
      
         	let wlanOn = resp.data[0].enabled;
         	dlog("WLAN 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"));
         		resolve(wlanOn);
         	} else {
         		dlog("nicht ok...")
         		reject(JSON.stringify(resp));
         	}
      
         });
      
      }
      
      
      
      async function setWifi(enabled, wifi_id) {
         return new Promise(async (resolve, reject) => {
         	dlog("setWifi: start set Wifi_haupt - " + wifi_id);
         	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) });
      
         	dlog("setWifi: got response")
      
         	if (resp != null) {
         		dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
         		dlog(resp);
         		resolve();
         	} else {
         		dlog("setWifi: rejetced")
         		dlog("resp: " + JSON.stringify(resp));
         		reject("msg: " + JSON.parse(resp.body).meta.msg);
         	}
         });
      }
      
      //###################################
      
      //Geräteliste abrufen
      
      async function getClients() {
         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/stat/sta/",
         		headers: { Cookie: cookies.join("; ") }
         	}).catch((e) => { dlog("getClients reject " + e); reject(e) });
      
         	dlog("got response " + JSON.stringify(resp));
         	dlog(typeof resp);
         	dlog("--------------------- " + resp);
         	resp = JSON.parse(resp);
      
         	setState("javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Anzahl_Geraete", resp.data.length);
         	var clientListe = "<table>";
         	for (var i = 0; i < resp.data.length; i++) {
         		dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
         		clientListe = clientListe.concat("<tr><td>" + resp.data[i].hostname + "&ensp;</td><td>" + resp.data[i].essid + "&ensp;&ensp;&ensp;&ensp;</td><td>" + resp.data[i].mac + "</td></tr>");
         		dlog(clientListe);
         	}
         	setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste", clientListe.concat(clientListe + "</table>"));
         });
      }
      
      
      setInterval(async () => {
         let state = await getStatus(wifi_id_haupt);
         setState("Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status", state, true);
         state = await getStatus(wifi_id_gast);
         setState("Unifi.Unifi_Wifi.01Haupt_Wifi.01Gast_Wifi_Status", state, true);
      
         await getClients();
      }, 10000); // Aktualisiert alle 10 Sekunden.
      

      dslraserD Offline
      dslraserD Offline
      dslraser
      Forum Testing Most Active
      schrieb am zuletzt editiert von
      #62

      @thewhobox
      Wieso einmischen ? Ist doch Dein Script !
      Ich freue mich das Du hier bist:+1:

      liv-in-skyL 1 Antwort Letzte Antwort
      0
      • thewhoboxT thewhobox

        @dslraser Entschuldige, wenn ich mich nochmal einmische, aber du hattest echt vielen unnötigen Code in deinem Skript^^
        Ich hab das mal zusammen gefasst:

        const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
        const unifi_username = "benutzer";
        const unifi_password = "passwort";
        const unifi_controller = "https://192.168.xxx.xxx:xxxx";
        const wifi_id_haupt = "xxxxxxxxxxxxxxx";
        const wifi_id_gast = "xxxxxxxxxxxxxxx";
        
        let cookies = [];
        let loggedIn = false;
        let debug = false;
        
        
        
        on({ id: 'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an'/*Unifi Haupt Wifi an*/, val: true, change: 'any' }, () => {
           setWifi(true, wifi_id_haupt);
        });
        
        on({ id: 'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus'/*Unifi Haupt Wifi aus*/, val: true, change: 'any' }, () => {
           setWifi(false, wifi_id_haupt);
        });
        
        on({ id: 'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an'/*Unifi Gast Wifi an*/, val: true, change: 'any' }, () => {
           setWifi(true, wifi_id_gast);
        });
        
        on({ id: 'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus'/*Unifi Gast Wifi aus*/, val: true, change: 'any' }, () => {
           setWifi(false, wifi_id_gast);
        });
        
        
        
        //##########---hier Haupt WLAN---##########
        
        //Datenpunkt für Haupt Wifi Status erstellen
        
        createState('Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status', {
           name: 'Unifi Haupt Wifi Status',
           role: 'switch',
           type: "boolean",
           read: true,
           write: false,
        });
        
        //Datenpunkt Button zum schalten für Haupt Wifi an erstellen
        
        createState('Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an', {
           name: 'Unifi Haupt Wifi an',
           role: 'button',
           read: true,
           write: true,
           type: "boolean",
           "smartName": {
           	"de": "01Haupt Wlan an",
           	"smartType": "SWITCH"
           }
        });
        
        //Datenpunkt Button zum schalten für Haupt Wifi aus erstellen
        
        createState('Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus', {
           name: 'Unifi Haupt Wifi aus',
           role: 'button',
           read: true,
           write: true,
           type: "boolean",
           "smartName": {
           	"de": "02Haupt Wlan aus",
           	"smartType": "SWITCH"
           }
        });
        
        //##########---hier Gast WLAN---##########
        
        //Datenpunkt für Gast Wifi Status erstellen
        
        createState('Unifi.Unifi_Wifi.02Gast_Wifi.01Gast_Wifi_Status', {
           name: 'Unifi Gast Wifi Status',
           role: 'switch',
           type: "boolean",
           read: true,
           write: false,
        });
        
        //Datenpunkt Button zum schalten für Gast Wifi an erstellen
        
        createState('Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an', {
           name: 'Unifi Gast Wifi an',
           role: 'button',
           read: true,
           write: true,
           type: "boolean",
           "smartName": {
           	"de": "01Gast Wlan an",
           	"smartType": "SWITCH"
           }
        });
        
        //Datenpunkt Button zum schalten für Gast Wifi aus erstellen
        
        createState('Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus', {
           name: 'Unifi Gast Wifi aus',
           role: 'button',
           read: true,
           write: true,
           type: "boolean",
           "smartName": {
           	"de": "02Gast Wlan aus",
           	"smartType": "SWITCH"
           }
        });
        
        //Datenpunkt für Anzahl Voucher erstellen
        
        createState('Unifi.Unifi_Wifi.02Gast_Wifi.04Gast_Wifi_Anzahl_Voucher', {
           name: 'Unifi Gast Wifi Anzahl Voucher',
           role: 'number',
           min: '0',
           max: '1000',
           read: true,
           write: false
        });
        
        //Datenpunkt Liste für Voucher für Gast Wifi erstellen
        
        createState('Unifi.Unifi_Wifi.02Gast_Wifi.005Gast_Wifi_Voucherliste', {
           name: 'Unifi Gast Wifi Voucherliste',
           role: 'string',
           read: true,
           write: false,
        });
        
        //##########---hier Geräteliste und Anzahl Geräte---##########
        
        //Datenpunkt Liste für angemeldete Geräte im Netzwerk erstellen
        
        createState('Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste', {
           name: 'Unifi Haupt Wifi Geräteliste',
           role: 'string',
           read: true,
           write: false,
        });
        
        //Datenpunkt für Anzahl angemeldete Geräte erstellen
        
        createState('Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Anzahl_Geraete', {
           name: 'Unifi Haupt Wifi Anzahl Clients',
           role: 'number',
           min: '0',
           max: '1000',
           read: true,
           write: false
        });
        
        
        
        function dlog(message) {
           if (debug)
           	console.log(message);
        }
        
        
        
        async function login() {
           return new Promise(async (resolve, reject) => {
           	let resp = 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) => { dlog("login: reject"), reject(e) });
        
           	if (resp != null) {
           		dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies" : "Ohne Cookies"));
           		if (resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
           			let set_cookies = resp.headers["set-cookie"];
           			for (i = 0; i < set_cookies.length; i++) {
           				let cookie = set_cookies[i];
           				cookie = cookie.split(";")[0];
           				cookies.push(cookie);
           			}
           		} else {
           			dlog("login: no cookies to set!")
           		}
           		loggedIn = true;
           		resolve();
           	} else {
           		dlog("login: rejected")
           		reject("resp = null");
           	}
           });
        }
        
        async function getStatus(wifi_id) {
           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) });
        
           	dlog("got response " + JSON.stringify(resp));
           	dlog(typeof resp);
           	resp = JSON.parse(resp);
           	dlog(resp.meta);
           	dlog(resp.meta.rc);
        
           	let wlanOn = resp.data[0].enabled;
           	dlog("WLAN 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"));
           		resolve(wlanOn);
           	} else {
           		dlog("nicht ok...")
           		reject(JSON.stringify(resp));
           	}
        
           });
        
        }
        
        
        
        async function setWifi(enabled, wifi_id) {
           return new Promise(async (resolve, reject) => {
           	dlog("setWifi: start set Wifi_haupt - " + wifi_id);
           	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) });
        
           	dlog("setWifi: got response")
        
           	if (resp != null) {
           		dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
           		dlog(resp);
           		resolve();
           	} else {
           		dlog("setWifi: rejetced")
           		dlog("resp: " + JSON.stringify(resp));
           		reject("msg: " + JSON.parse(resp.body).meta.msg);
           	}
           });
        }
        
        //###################################
        
        //Geräteliste abrufen
        
        async function getClients() {
           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/stat/sta/",
           		headers: { Cookie: cookies.join("; ") }
           	}).catch((e) => { dlog("getClients reject " + e); reject(e) });
        
           	dlog("got response " + JSON.stringify(resp));
           	dlog(typeof resp);
           	dlog("--------------------- " + resp);
           	resp = JSON.parse(resp);
        
           	setState("javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Anzahl_Geraete", resp.data.length);
           	var clientListe = "<table>";
           	for (var i = 0; i < resp.data.length; i++) {
           		dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
           		clientListe = clientListe.concat("<tr><td>" + resp.data[i].hostname + "&ensp;</td><td>" + resp.data[i].essid + "&ensp;&ensp;&ensp;&ensp;</td><td>" + resp.data[i].mac + "</td></tr>");
           		dlog(clientListe);
           	}
           	setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste", clientListe.concat(clientListe + "</table>"));
           });
        }
        
        
        setInterval(async () => {
           let state = await getStatus(wifi_id_haupt);
           setState("Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status", state, true);
           state = await getStatus(wifi_id_gast);
           setState("Unifi.Unifi_Wifi.01Haupt_Wifi.01Gast_Wifi_Status", state, true);
        
           await getClients();
        }, 10000); // Aktualisiert alle 10 Sekunden.
        

        liv-in-skyL Offline
        liv-in-skyL Offline
        liv-in-sky
        schrieb am zuletzt editiert von
        #63

        @thewhobox ja klasse, dass du drüber schaust - bin auch froh, dass du dabei bleibst

        nach einem gelösten Thread wäre es sinnvoll dies in der Überschrift des ersten Posts einzutragen [gelöst]-... Bitte benutzt das Voting rechts unten im Beitrag wenn er euch geholfen hat. Forum-Tools: PicPick https://picpick.app/en/download/ und ScreenToGif https://www.screentogif.com/downloads.html

        1 Antwort Letzte Antwort
        1
        • dslraserD dslraser

          @thewhobox
          Wieso einmischen ? Ist doch Dein Script !
          Ich freue mich das Du hier bist:+1:

          liv-in-skyL Offline
          liv-in-skyL Offline
          liv-in-sky
          schrieb am zuletzt editiert von
          #64

          @dslraser

          gibst du mir bitte bescheid mit welchen script ich dann weiterarbeiten soll - ich füge morgen dann die voucher sache dazu

          ich denke, ich werde das iqontrol auch mit einbauen und es mit einen marker setzen - wer es enablen will kann es dann auch

          damit bleiben wir bei einem script - bitte poste das "offizielle" script , wenn du noch was von thewhobox miteinbauen möchtest - heute ist keine zeit mehr um weiterzumachen

          nach einem gelösten Thread wäre es sinnvoll dies in der Überschrift des ersten Posts einzutragen [gelöst]-... Bitte benutzt das Voting rechts unten im Beitrag wenn er euch geholfen hat. Forum-Tools: PicPick https://picpick.app/en/download/ und ScreenToGif https://www.screentogif.com/downloads.html

          1 Antwort Letzte Antwort
          0
          • thewhoboxT thewhobox

            @dslraser Entschuldige, wenn ich mich nochmal einmische, aber du hattest echt vielen unnötigen Code in deinem Skript^^
            Ich hab das mal zusammen gefasst:

            const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
            const unifi_username = "benutzer";
            const unifi_password = "passwort";
            const unifi_controller = "https://192.168.xxx.xxx:xxxx";
            const wifi_id_haupt = "xxxxxxxxxxxxxxx";
            const wifi_id_gast = "xxxxxxxxxxxxxxx";
            
            let cookies = [];
            let loggedIn = false;
            let debug = false;
            
            
            
            on({ id: 'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an'/*Unifi Haupt Wifi an*/, val: true, change: 'any' }, () => {
               setWifi(true, wifi_id_haupt);
            });
            
            on({ id: 'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus'/*Unifi Haupt Wifi aus*/, val: true, change: 'any' }, () => {
               setWifi(false, wifi_id_haupt);
            });
            
            on({ id: 'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an'/*Unifi Gast Wifi an*/, val: true, change: 'any' }, () => {
               setWifi(true, wifi_id_gast);
            });
            
            on({ id: 'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus'/*Unifi Gast Wifi aus*/, val: true, change: 'any' }, () => {
               setWifi(false, wifi_id_gast);
            });
            
            
            
            //##########---hier Haupt WLAN---##########
            
            //Datenpunkt für Haupt Wifi Status erstellen
            
            createState('Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status', {
               name: 'Unifi Haupt Wifi Status',
               role: 'switch',
               type: "boolean",
               read: true,
               write: false,
            });
            
            //Datenpunkt Button zum schalten für Haupt Wifi an erstellen
            
            createState('Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an', {
               name: 'Unifi Haupt Wifi an',
               role: 'button',
               read: true,
               write: true,
               type: "boolean",
               "smartName": {
               	"de": "01Haupt Wlan an",
               	"smartType": "SWITCH"
               }
            });
            
            //Datenpunkt Button zum schalten für Haupt Wifi aus erstellen
            
            createState('Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus', {
               name: 'Unifi Haupt Wifi aus',
               role: 'button',
               read: true,
               write: true,
               type: "boolean",
               "smartName": {
               	"de": "02Haupt Wlan aus",
               	"smartType": "SWITCH"
               }
            });
            
            //##########---hier Gast WLAN---##########
            
            //Datenpunkt für Gast Wifi Status erstellen
            
            createState('Unifi.Unifi_Wifi.02Gast_Wifi.01Gast_Wifi_Status', {
               name: 'Unifi Gast Wifi Status',
               role: 'switch',
               type: "boolean",
               read: true,
               write: false,
            });
            
            //Datenpunkt Button zum schalten für Gast Wifi an erstellen
            
            createState('Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an', {
               name: 'Unifi Gast Wifi an',
               role: 'button',
               read: true,
               write: true,
               type: "boolean",
               "smartName": {
               	"de": "01Gast Wlan an",
               	"smartType": "SWITCH"
               }
            });
            
            //Datenpunkt Button zum schalten für Gast Wifi aus erstellen
            
            createState('Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus', {
               name: 'Unifi Gast Wifi aus',
               role: 'button',
               read: true,
               write: true,
               type: "boolean",
               "smartName": {
               	"de": "02Gast Wlan aus",
               	"smartType": "SWITCH"
               }
            });
            
            //Datenpunkt für Anzahl Voucher erstellen
            
            createState('Unifi.Unifi_Wifi.02Gast_Wifi.04Gast_Wifi_Anzahl_Voucher', {
               name: 'Unifi Gast Wifi Anzahl Voucher',
               role: 'number',
               min: '0',
               max: '1000',
               read: true,
               write: false
            });
            
            //Datenpunkt Liste für Voucher für Gast Wifi erstellen
            
            createState('Unifi.Unifi_Wifi.02Gast_Wifi.005Gast_Wifi_Voucherliste', {
               name: 'Unifi Gast Wifi Voucherliste',
               role: 'string',
               read: true,
               write: false,
            });
            
            //##########---hier Geräteliste und Anzahl Geräte---##########
            
            //Datenpunkt Liste für angemeldete Geräte im Netzwerk erstellen
            
            createState('Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste', {
               name: 'Unifi Haupt Wifi Geräteliste',
               role: 'string',
               read: true,
               write: false,
            });
            
            //Datenpunkt für Anzahl angemeldete Geräte erstellen
            
            createState('Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Anzahl_Geraete', {
               name: 'Unifi Haupt Wifi Anzahl Clients',
               role: 'number',
               min: '0',
               max: '1000',
               read: true,
               write: false
            });
            
            
            
            function dlog(message) {
               if (debug)
               	console.log(message);
            }
            
            
            
            async function login() {
               return new Promise(async (resolve, reject) => {
               	let resp = 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) => { dlog("login: reject"), reject(e) });
            
               	if (resp != null) {
               		dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies" : "Ohne Cookies"));
               		if (resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
               			let set_cookies = resp.headers["set-cookie"];
               			for (i = 0; i < set_cookies.length; i++) {
               				let cookie = set_cookies[i];
               				cookie = cookie.split(";")[0];
               				cookies.push(cookie);
               			}
               		} else {
               			dlog("login: no cookies to set!")
               		}
               		loggedIn = true;
               		resolve();
               	} else {
               		dlog("login: rejected")
               		reject("resp = null");
               	}
               });
            }
            
            async function getStatus(wifi_id) {
               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) });
            
               	dlog("got response " + JSON.stringify(resp));
               	dlog(typeof resp);
               	resp = JSON.parse(resp);
               	dlog(resp.meta);
               	dlog(resp.meta.rc);
            
               	let wlanOn = resp.data[0].enabled;
               	dlog("WLAN 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"));
               		resolve(wlanOn);
               	} else {
               		dlog("nicht ok...")
               		reject(JSON.stringify(resp));
               	}
            
               });
            
            }
            
            
            
            async function setWifi(enabled, wifi_id) {
               return new Promise(async (resolve, reject) => {
               	dlog("setWifi: start set Wifi_haupt - " + wifi_id);
               	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) });
            
               	dlog("setWifi: got response")
            
               	if (resp != null) {
               		dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
               		dlog(resp);
               		resolve();
               	} else {
               		dlog("setWifi: rejetced")
               		dlog("resp: " + JSON.stringify(resp));
               		reject("msg: " + JSON.parse(resp.body).meta.msg);
               	}
               });
            }
            
            //###################################
            
            //Geräteliste abrufen
            
            async function getClients() {
               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/stat/sta/",
               		headers: { Cookie: cookies.join("; ") }
               	}).catch((e) => { dlog("getClients reject " + e); reject(e) });
            
               	dlog("got response " + JSON.stringify(resp));
               	dlog(typeof resp);
               	dlog("--------------------- " + resp);
               	resp = JSON.parse(resp);
            
               	setState("javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Anzahl_Geraete", resp.data.length);
               	var clientListe = "<table>";
               	for (var i = 0; i < resp.data.length; i++) {
               		dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
               		clientListe = clientListe.concat("<tr><td>" + resp.data[i].hostname + "&ensp;</td><td>" + resp.data[i].essid + "&ensp;&ensp;&ensp;&ensp;</td><td>" + resp.data[i].mac + "</td></tr>");
               		dlog(clientListe);
               	}
               	setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste", clientListe.concat(clientListe + "</table>"));
               });
            }
            
            
            setInterval(async () => {
               let state = await getStatus(wifi_id_haupt);
               setState("Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status", state, true);
               state = await getStatus(wifi_id_gast);
               setState("Unifi.Unifi_Wifi.01Haupt_Wifi.01Gast_Wifi_Status", state, true);
            
               await getClients();
            }, 10000); // Aktualisiert alle 10 Sekunden.
            

            dslraserD Offline
            dslraserD Offline
            dslraser
            Forum Testing Most Active
            schrieb am zuletzt editiert von dslraser
            #65

            @thewhobox
            ich hatte das Script jetzt so gemacht, um von beiden WLAN den Status holen zu können. Das funktioniert auch, vielleicht geht es besser/kürzer ?
            Wenn ich Dein aufgeräumtes Script nehme, dann kann der Status nur für ein WLAN geholt werden. Oder habe ich was übersehen ?

            Hier noch mal meine "aufgeräumte Variante" (in der von oben hatte ich noch einige Tippfehler bei den States)

            const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
            const unifi_username = "benutzer";
            const unifi_password = "passwort";
            const unifi_controller = "https://192.168.xxx.xxx:xxxx";
            const wifi_id_haupt = "xxxxxxxxxx";
            const wifi_id_gast = "xxxxxxxxxx";
            let cookies = [];
            let loggedIn = false;
            let debug = false;
            
            on({id:'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an'/*Unifi Haupt Wifi an*/, val: true, change: 'any'}, wifi_an_haupt);
            on({id:'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus'/*Unifi Haupt Wifi aus*/, val: true, change: 'any'}, wifi_aus_haupt);
            on({id:'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an'/*Unifi Gast Wifi an*/, val: true, change: 'any'}, wifi_an_gast);
            on({id:'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus'/*Unifi Gast Wifi aus*/, val: true, change: 'any'}, wifi_aus_gast);
            
            //##########---hier Haupt WLAN---##########
            //Datenpunkt für Haupt Wifi Status erstellen
            createState('Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status',{
               name: 'Unifi Haupt Wifi Status', 
               role: 'switch',
               type: "boolean",
               read:  true,
               write: false,
            });
            //Datenpunkt Button zum schalten für Haupt Wifi an erstellen
            createState('Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an', {
               name: 'Unifi Haupt Wifi an', 
               role: 'button',
               read:  true, 
               write: true,
               type: "boolean",
               "smartName": {
               "de": "01Haupt Wlan an",
               "smartType": "SWITCH"
            }
            });
            //Datenpunkt Button zum schalten für Haupt Wifi aus erstellen
            createState('Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus', {
               name: 'Unifi Haupt Wifi aus', 
               role: 'button',
               read:  true, 
               write: true,
               type: "boolean",
               "smartName": {
               "de": "02Haupt Wlan aus",
               "smartType": "SWITCH"
            }
            });
            //##########---hier Gast WLAN---##########
            //Datenpunkt für Gast Wifi Status erstellen
            createState('Unifi.Unifi_Wifi.02Gast_Wifi.01Gast_Wifi_Status',{
               name: 'Unifi Gast Wifi Status', 
               role: 'switch',
               type: "boolean",
               read:  true,
               write: false,
            });
            //Datenpunkt Button zum schalten für Gast Wifi an erstellen
            createState('Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an', {
               name: 'Unifi Gast Wifi an', 
               role: 'button',
               read:  true, 
               write: true,
               type: "boolean",
               "smartName": {
               "de": "01Gast Wlan an",
               "smartType": "SWITCH"
            }
            });
            //Datenpunkt Button zum schalten für Gast Wifi aus erstellen
            createState('Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus', {
               name: 'Unifi Gast Wifi aus', 
               role: 'button',
               read:  true, 
               write: true,
               type: "boolean",
               "smartName": {
               "de": "02Gast Wlan aus",
               "smartType": "SWITCH"
            }
            });
            //Datenpunkt für Anzahl Voucher erstellen
            createState('Unifi.Unifi_Wifi.02Gast_Wifi.04Gast_Wifi_Anzahl_Voucher',{ 
               name: 'Unifi Gast Wifi Anzahl Voucher',  
               role: 'number',
               min: '0', 
               max: '1000',
               read: true, 
               write: false }); 
            //Datenpunkt Liste für Voucher für Gast Wifi erstellen
            createState('Unifi.Unifi_Wifi.02Gast_Wifi.05Gast_Wifi_Voucherliste', {
               name: 'Unifi Gast Wifi Voucherliste', 
               role: 'string',
               read:  true, 
               write: false,
            });
            //##########---hier Geräteliste und Anzahl Geräte---##########
            //Datenpunkt Liste für angemeldete Geräte im Netzwerk erstellen
            createState('Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste', {
               name: 'Unifi Haupt Wifi Geräteliste', 
               role: 'string',
               read:  true, 
               write: false,
            });
            //Datenpunkt für Anzahl angemeldete Geräte erstellen
            createState('Unifi.Unifi_Wifi.01Haupt_Wifi.05Haupt_Wifi_Anzahl_Geraete',{ 
               name: 'Unifi Haupt Wifi Anzahl Clients',  
               role: 'number',
               min: '0', 
               max: '1000',
               read: true, 
               write: false }); 
             
            function dlog(message) {
              if(debug)
                  console.log(message);
            }
             
            async function login() {
              return new Promise(async (resolve, reject) => {
                  let resp = 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) => { dlog("login: reject"), reject(e) });
                  
                  if(resp != null) {
                      dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies":"Ohne Cookies"));
                      if(resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
                          let set_cookies = resp.headers["set-cookie"];
                          for(i = 0; i < set_cookies.length; i++) {
                              let cookie = set_cookies[i];
                              cookie = cookie.split(";")[0];
                              cookies.push(cookie);
                          }
                      } else {
                          dlog("login: no cookies to set!")
                      }
                      loggedIn = true;
                      resolve();
                  } else {
                      dlog("login: rejected")
                      reject("resp = null");
                  }
              });
            }
             
            async function getStatus_haupt() {
               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_haupt,
                       headers: { Cookie: cookies.join("; ") }
                   }).catch((e) => { dlog("getStatus reject " + e); reject(e) });
               
                   dlog("got response " + JSON.stringify(resp));
                   dlog(typeof resp);
                   resp = JSON.parse(resp);
                   dlog(resp.meta);
                   dlog(resp.meta.rc);
                   
                   let wlanOn = resp.data[0].enabled;
                   dlog("WLAN 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"));
                       resolve(wlanOn);
                   } else {
                       dlog("nicht ok...")
                       
                       reject(JSON.stringify(resp));
                   }
               });
            }
             
            async function setWifi_haupt(enabled) {
              return new Promise(async (resolve, reject) => {
                  dlog("setWifi_haupt: start set Wifi_haupt");
                  if(!loggedIn) { dlog("need to login"); await login().catch((e) => reject(e)); }
                  dlog("setWifi_haupt: now setting Wifi_haupt");
                  let resp = request.post({
                      url: unifi_controller + "/api/s/default/upd/wlanconf/" + wifi_id_haupt,
                      body: JSON.stringify({ enabled }),
                      headers: { 'Content-Type': 'application/json', Cookie: cookies.join("; ") }
                  }).catch((e) => { dlog("setWifi: rejected: " + e); reject(e) });
                  dlog("setWifi: got response")
                  if(resp != null) {
                      dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
                      dlog(resp);
                      resolve();
                  } else {
                      dlog("setWifi: rejetced")
                      dlog("resp: " + JSON.stringify(resp));
                      reject("msg: " + JSON.parse(resp.body).meta.msg);
                  }
              });
            }
            //########################################
            async function getStatus_gast() {
               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_gast,
                       headers: { Cookie: cookies.join("; ") }
                   }).catch((e) => { dlog("getStatus reject " + e); reject(e) });
               
                   dlog("got response " + JSON.stringify(resp));
                   dlog(typeof resp);
                   resp = JSON.parse(resp);
                   dlog(resp.meta);
                   dlog(resp.meta.rc);
                   
                   let wlanOn = resp.data[0].enabled;
                   dlog("WLAN 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"));
                       resolve(wlanOn);
                   } else {
                       dlog("nicht ok...")
                       
                       reject(JSON.stringify(resp));
                   }
               });
            }
             
            async function setWifi_gast(enabled) {
              return new Promise(async (resolve, reject) => {
                  dlog("setWifi_gast: start set Wifi_gast");
                  if(!loggedIn) { dlog("need to login"); await login().catch((e) => reject(e)); }
                  dlog("setWifi_gast: now setting Wifi_gast");
                  let resp = request.post({
                      url: unifi_controller + "/api/s/default/upd/wlanconf/" + wifi_id_gast,
                      body: JSON.stringify({ enabled }),
                      headers: { 'Content-Type': 'application/json', Cookie: cookies.join("; ") }
                  }).catch((e) => { dlog("setWifi: rejected: " + e); reject(e) });
                  dlog("setWifi: got response")
                  if(resp != null) {
                      dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
                      dlog(resp);
                      resolve();
                  } else {
                      dlog("setWifi: rejetced")
                      dlog("resp: " + JSON.stringify(resp));
                      reject("msg: " + JSON.parse(resp.body).meta.msg);
                  }
              });
            }
            //###################################
            //Geräteliste abrufen
            async function getClients() {
              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/stat/sta/",
                      headers: { Cookie: cookies.join("; ") }
                  }).catch((e) => { dlog("getStatus_haupt reject " + e); reject(e) });  
             
            dlog("got response " + JSON.stringify(resp));
            dlog(typeof resp);
            dlog("--------------------- " + resp);
            resp = JSON.parse(resp);
            //log("--------------------- " + resp);
             
            dlog(resp.meta);
            dlog(resp.meta.rc);
            dlog(resp.data[2].hostname);
            dlog(resp.data.length);
            setState("javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.05Haupt_Wifi_Anzahl_Geraete",resp.data.length);
            var clientListe = "<table>";
            for (var i = 0; i < resp.data.length; i++) { 
              dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
               clientListe = clientListe.concat("<tr><td>"+resp.data[i].hostname+"&ensp;</td><td>"+resp.data[i].essid+"&ensp;&ensp;&ensp;&ensp;</td><td>"+resp.data[i].mac+"</td></tr>");
               dlog(clientListe);
            }
            setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste", clientListe.concat(clientListe+"</table>"));
            });
            }
             
            async function wifi_an_haupt() {
               dlog("starting wifi_an_haupt");
               await setWifi_haupt(true).catch((e) => dlog("reject1: " + e));
               dlog("getting status");
               let wlan = await getStatus_haupt().catch((e) => dlog("reject2: " + e));
               console.log("fin")
               console.log(wlan);
            }
            async function wifi_aus_haupt() {
               dlog("starting wifi_aus_haupt");
               await setWifi_haupt(false).catch((e) => dlog("reject1: " + e));
               dlog("getting status");
               let wlan = await getStatus_haupt().catch((e) => dlog("reject2: " + e));
               console.log("fin")
               console.log(wlan);
            }
             
            //####################
            async function wifi_an_gast() {
               dlog("starting wifi_an_gast");
               await setWifi_gast(true).catch((e) => dlog("reject1: " + e));
               dlog("getting status");
               let wlan = await getStatus_gast().catch((e) => dlog("reject2: " + e));
               console.log("fin")
               console.log(wlan);
            }
            async function wifi_aus_gast() {
               dlog("starting wifi_aus_gast");
               await setWifi_gast(false).catch((e) => dlog("reject1: " + e));
               dlog("getting status");
               let wlan = await getStatus_gast().catch((e) => dlog("reject2: " + e));
               console.log("fin")
               console.log(wlan);
            }
            //#######################
             
            setInterval(async () => {
            let state = await getStatus_haupt();
               setState("Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status", state, true);
            }, 10000); // Aktualisiert alle 10 Sekunden.
             
            setInterval(async () => {
            let state = await getClients();
               setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Anzahl_Geraete");
               setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste", clientListe.concat(clientListe+"</table>"));
            }, 10000); // Aktualisiert alle 10 Sekunden.
             
            setInterval(async () => {
            let state = await getStatus_gast();
               setState("Unifi.Unifi_Wifi.02Gast_Wifi.01Gast_Wifi_Status", state, true);
            }, 10000); // Aktualisiert alle 10 Sekunden.
             
             
             
            //wifi_an_haupt();
            //wifi_aus_haupt();
            //getStatus_haupt();
            //getStatus_gast();
            //getClients();
            

            liv-in-skyL 1 Antwort Letzte Antwort
            0
            • dslraserD dslraser

              @thewhobox
              ich hatte das Script jetzt so gemacht, um von beiden WLAN den Status holen zu können. Das funktioniert auch, vielleicht geht es besser/kürzer ?
              Wenn ich Dein aufgeräumtes Script nehme, dann kann der Status nur für ein WLAN geholt werden. Oder habe ich was übersehen ?

              Hier noch mal meine "aufgeräumte Variante" (in der von oben hatte ich noch einige Tippfehler bei den States)

              const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
              const unifi_username = "benutzer";
              const unifi_password = "passwort";
              const unifi_controller = "https://192.168.xxx.xxx:xxxx";
              const wifi_id_haupt = "xxxxxxxxxx";
              const wifi_id_gast = "xxxxxxxxxx";
              let cookies = [];
              let loggedIn = false;
              let debug = false;
              
              on({id:'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an'/*Unifi Haupt Wifi an*/, val: true, change: 'any'}, wifi_an_haupt);
              on({id:'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus'/*Unifi Haupt Wifi aus*/, val: true, change: 'any'}, wifi_aus_haupt);
              on({id:'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an'/*Unifi Gast Wifi an*/, val: true, change: 'any'}, wifi_an_gast);
              on({id:'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus'/*Unifi Gast Wifi aus*/, val: true, change: 'any'}, wifi_aus_gast);
              
              //##########---hier Haupt WLAN---##########
              //Datenpunkt für Haupt Wifi Status erstellen
              createState('Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status',{
                 name: 'Unifi Haupt Wifi Status', 
                 role: 'switch',
                 type: "boolean",
                 read:  true,
                 write: false,
              });
              //Datenpunkt Button zum schalten für Haupt Wifi an erstellen
              createState('Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an', {
                 name: 'Unifi Haupt Wifi an', 
                 role: 'button',
                 read:  true, 
                 write: true,
                 type: "boolean",
                 "smartName": {
                 "de": "01Haupt Wlan an",
                 "smartType": "SWITCH"
              }
              });
              //Datenpunkt Button zum schalten für Haupt Wifi aus erstellen
              createState('Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus', {
                 name: 'Unifi Haupt Wifi aus', 
                 role: 'button',
                 read:  true, 
                 write: true,
                 type: "boolean",
                 "smartName": {
                 "de": "02Haupt Wlan aus",
                 "smartType": "SWITCH"
              }
              });
              //##########---hier Gast WLAN---##########
              //Datenpunkt für Gast Wifi Status erstellen
              createState('Unifi.Unifi_Wifi.02Gast_Wifi.01Gast_Wifi_Status',{
                 name: 'Unifi Gast Wifi Status', 
                 role: 'switch',
                 type: "boolean",
                 read:  true,
                 write: false,
              });
              //Datenpunkt Button zum schalten für Gast Wifi an erstellen
              createState('Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an', {
                 name: 'Unifi Gast Wifi an', 
                 role: 'button',
                 read:  true, 
                 write: true,
                 type: "boolean",
                 "smartName": {
                 "de": "01Gast Wlan an",
                 "smartType": "SWITCH"
              }
              });
              //Datenpunkt Button zum schalten für Gast Wifi aus erstellen
              createState('Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus', {
                 name: 'Unifi Gast Wifi aus', 
                 role: 'button',
                 read:  true, 
                 write: true,
                 type: "boolean",
                 "smartName": {
                 "de": "02Gast Wlan aus",
                 "smartType": "SWITCH"
              }
              });
              //Datenpunkt für Anzahl Voucher erstellen
              createState('Unifi.Unifi_Wifi.02Gast_Wifi.04Gast_Wifi_Anzahl_Voucher',{ 
                 name: 'Unifi Gast Wifi Anzahl Voucher',  
                 role: 'number',
                 min: '0', 
                 max: '1000',
                 read: true, 
                 write: false }); 
              //Datenpunkt Liste für Voucher für Gast Wifi erstellen
              createState('Unifi.Unifi_Wifi.02Gast_Wifi.05Gast_Wifi_Voucherliste', {
                 name: 'Unifi Gast Wifi Voucherliste', 
                 role: 'string',
                 read:  true, 
                 write: false,
              });
              //##########---hier Geräteliste und Anzahl Geräte---##########
              //Datenpunkt Liste für angemeldete Geräte im Netzwerk erstellen
              createState('Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste', {
                 name: 'Unifi Haupt Wifi Geräteliste', 
                 role: 'string',
                 read:  true, 
                 write: false,
              });
              //Datenpunkt für Anzahl angemeldete Geräte erstellen
              createState('Unifi.Unifi_Wifi.01Haupt_Wifi.05Haupt_Wifi_Anzahl_Geraete',{ 
                 name: 'Unifi Haupt Wifi Anzahl Clients',  
                 role: 'number',
                 min: '0', 
                 max: '1000',
                 read: true, 
                 write: false }); 
               
              function dlog(message) {
                if(debug)
                    console.log(message);
              }
               
              async function login() {
                return new Promise(async (resolve, reject) => {
                    let resp = 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) => { dlog("login: reject"), reject(e) });
                    
                    if(resp != null) {
                        dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies":"Ohne Cookies"));
                        if(resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
                            let set_cookies = resp.headers["set-cookie"];
                            for(i = 0; i < set_cookies.length; i++) {
                                let cookie = set_cookies[i];
                                cookie = cookie.split(";")[0];
                                cookies.push(cookie);
                            }
                        } else {
                            dlog("login: no cookies to set!")
                        }
                        loggedIn = true;
                        resolve();
                    } else {
                        dlog("login: rejected")
                        reject("resp = null");
                    }
                });
              }
               
              async function getStatus_haupt() {
                 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_haupt,
                         headers: { Cookie: cookies.join("; ") }
                     }).catch((e) => { dlog("getStatus reject " + e); reject(e) });
                 
                     dlog("got response " + JSON.stringify(resp));
                     dlog(typeof resp);
                     resp = JSON.parse(resp);
                     dlog(resp.meta);
                     dlog(resp.meta.rc);
                     
                     let wlanOn = resp.data[0].enabled;
                     dlog("WLAN 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"));
                         resolve(wlanOn);
                     } else {
                         dlog("nicht ok...")
                         
                         reject(JSON.stringify(resp));
                     }
                 });
              }
               
              async function setWifi_haupt(enabled) {
                return new Promise(async (resolve, reject) => {
                    dlog("setWifi_haupt: start set Wifi_haupt");
                    if(!loggedIn) { dlog("need to login"); await login().catch((e) => reject(e)); }
                    dlog("setWifi_haupt: now setting Wifi_haupt");
                    let resp = request.post({
                        url: unifi_controller + "/api/s/default/upd/wlanconf/" + wifi_id_haupt,
                        body: JSON.stringify({ enabled }),
                        headers: { 'Content-Type': 'application/json', Cookie: cookies.join("; ") }
                    }).catch((e) => { dlog("setWifi: rejected: " + e); reject(e) });
                    dlog("setWifi: got response")
                    if(resp != null) {
                        dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
                        dlog(resp);
                        resolve();
                    } else {
                        dlog("setWifi: rejetced")
                        dlog("resp: " + JSON.stringify(resp));
                        reject("msg: " + JSON.parse(resp.body).meta.msg);
                    }
                });
              }
              //########################################
              async function getStatus_gast() {
                 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_gast,
                         headers: { Cookie: cookies.join("; ") }
                     }).catch((e) => { dlog("getStatus reject " + e); reject(e) });
                 
                     dlog("got response " + JSON.stringify(resp));
                     dlog(typeof resp);
                     resp = JSON.parse(resp);
                     dlog(resp.meta);
                     dlog(resp.meta.rc);
                     
                     let wlanOn = resp.data[0].enabled;
                     dlog("WLAN 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"));
                         resolve(wlanOn);
                     } else {
                         dlog("nicht ok...")
                         
                         reject(JSON.stringify(resp));
                     }
                 });
              }
               
              async function setWifi_gast(enabled) {
                return new Promise(async (resolve, reject) => {
                    dlog("setWifi_gast: start set Wifi_gast");
                    if(!loggedIn) { dlog("need to login"); await login().catch((e) => reject(e)); }
                    dlog("setWifi_gast: now setting Wifi_gast");
                    let resp = request.post({
                        url: unifi_controller + "/api/s/default/upd/wlanconf/" + wifi_id_gast,
                        body: JSON.stringify({ enabled }),
                        headers: { 'Content-Type': 'application/json', Cookie: cookies.join("; ") }
                    }).catch((e) => { dlog("setWifi: rejected: " + e); reject(e) });
                    dlog("setWifi: got response")
                    if(resp != null) {
                        dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
                        dlog(resp);
                        resolve();
                    } else {
                        dlog("setWifi: rejetced")
                        dlog("resp: " + JSON.stringify(resp));
                        reject("msg: " + JSON.parse(resp.body).meta.msg);
                    }
                });
              }
              //###################################
              //Geräteliste abrufen
              async function getClients() {
                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/stat/sta/",
                        headers: { Cookie: cookies.join("; ") }
                    }).catch((e) => { dlog("getStatus_haupt reject " + e); reject(e) });  
               
              dlog("got response " + JSON.stringify(resp));
              dlog(typeof resp);
              dlog("--------------------- " + resp);
              resp = JSON.parse(resp);
              //log("--------------------- " + resp);
               
              dlog(resp.meta);
              dlog(resp.meta.rc);
              dlog(resp.data[2].hostname);
              dlog(resp.data.length);
              setState("javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.05Haupt_Wifi_Anzahl_Geraete",resp.data.length);
              var clientListe = "<table>";
              for (var i = 0; i < resp.data.length; i++) { 
                dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
                 clientListe = clientListe.concat("<tr><td>"+resp.data[i].hostname+"&ensp;</td><td>"+resp.data[i].essid+"&ensp;&ensp;&ensp;&ensp;</td><td>"+resp.data[i].mac+"</td></tr>");
                 dlog(clientListe);
              }
              setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste", clientListe.concat(clientListe+"</table>"));
              });
              }
               
              async function wifi_an_haupt() {
                 dlog("starting wifi_an_haupt");
                 await setWifi_haupt(true).catch((e) => dlog("reject1: " + e));
                 dlog("getting status");
                 let wlan = await getStatus_haupt().catch((e) => dlog("reject2: " + e));
                 console.log("fin")
                 console.log(wlan);
              }
              async function wifi_aus_haupt() {
                 dlog("starting wifi_aus_haupt");
                 await setWifi_haupt(false).catch((e) => dlog("reject1: " + e));
                 dlog("getting status");
                 let wlan = await getStatus_haupt().catch((e) => dlog("reject2: " + e));
                 console.log("fin")
                 console.log(wlan);
              }
               
              //####################
              async function wifi_an_gast() {
                 dlog("starting wifi_an_gast");
                 await setWifi_gast(true).catch((e) => dlog("reject1: " + e));
                 dlog("getting status");
                 let wlan = await getStatus_gast().catch((e) => dlog("reject2: " + e));
                 console.log("fin")
                 console.log(wlan);
              }
              async function wifi_aus_gast() {
                 dlog("starting wifi_aus_gast");
                 await setWifi_gast(false).catch((e) => dlog("reject1: " + e));
                 dlog("getting status");
                 let wlan = await getStatus_gast().catch((e) => dlog("reject2: " + e));
                 console.log("fin")
                 console.log(wlan);
              }
              //#######################
               
              setInterval(async () => {
              let state = await getStatus_haupt();
                 setState("Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status", state, true);
              }, 10000); // Aktualisiert alle 10 Sekunden.
               
              setInterval(async () => {
              let state = await getClients();
                 setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Anzahl_Geraete");
                 setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste", clientListe.concat(clientListe+"</table>"));
              }, 10000); // Aktualisiert alle 10 Sekunden.
               
              setInterval(async () => {
              let state = await getStatus_gast();
                 setState("Unifi.Unifi_Wifi.02Gast_Wifi.01Gast_Wifi_Status", state, true);
              }, 10000); // Aktualisiert alle 10 Sekunden.
               
               
               
              //wifi_an_haupt();
              //wifi_aus_haupt();
              //getStatus_haupt();
              //getStatus_gast();
              //getClients();
              

              liv-in-skyL Offline
              liv-in-skyL Offline
              liv-in-sky
              schrieb am zuletzt editiert von
              #66

              @dslraser ok - dann nehm ich das - falls sich bis morgen was ändert - einfach mitteilen

              nach einem gelösten Thread wäre es sinnvoll dies in der Überschrift des ersten Posts einzutragen [gelöst]-... Bitte benutzt das Voting rechts unten im Beitrag wenn er euch geholfen hat. Forum-Tools: PicPick https://picpick.app/en/download/ und ScreenToGif https://www.screentogif.com/downloads.html

              1 Antwort Letzte Antwort
              0
              • thewhoboxT thewhobox

                @dslraser Entschuldige, wenn ich mich nochmal einmische, aber du hattest echt vielen unnötigen Code in deinem Skript^^
                Ich hab das mal zusammen gefasst:

                const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
                const unifi_username = "benutzer";
                const unifi_password = "passwort";
                const unifi_controller = "https://192.168.xxx.xxx:xxxx";
                const wifi_id_haupt = "xxxxxxxxxxxxxxx";
                const wifi_id_gast = "xxxxxxxxxxxxxxx";
                
                let cookies = [];
                let loggedIn = false;
                let debug = false;
                
                
                
                on({ id: 'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an'/*Unifi Haupt Wifi an*/, val: true, change: 'any' }, () => {
                   setWifi(true, wifi_id_haupt);
                });
                
                on({ id: 'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus'/*Unifi Haupt Wifi aus*/, val: true, change: 'any' }, () => {
                   setWifi(false, wifi_id_haupt);
                });
                
                on({ id: 'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an'/*Unifi Gast Wifi an*/, val: true, change: 'any' }, () => {
                   setWifi(true, wifi_id_gast);
                });
                
                on({ id: 'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus'/*Unifi Gast Wifi aus*/, val: true, change: 'any' }, () => {
                   setWifi(false, wifi_id_gast);
                });
                
                
                
                //##########---hier Haupt WLAN---##########
                
                //Datenpunkt für Haupt Wifi Status erstellen
                
                createState('Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status', {
                   name: 'Unifi Haupt Wifi Status',
                   role: 'switch',
                   type: "boolean",
                   read: true,
                   write: false,
                });
                
                //Datenpunkt Button zum schalten für Haupt Wifi an erstellen
                
                createState('Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an', {
                   name: 'Unifi Haupt Wifi an',
                   role: 'button',
                   read: true,
                   write: true,
                   type: "boolean",
                   "smartName": {
                   	"de": "01Haupt Wlan an",
                   	"smartType": "SWITCH"
                   }
                });
                
                //Datenpunkt Button zum schalten für Haupt Wifi aus erstellen
                
                createState('Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus', {
                   name: 'Unifi Haupt Wifi aus',
                   role: 'button',
                   read: true,
                   write: true,
                   type: "boolean",
                   "smartName": {
                   	"de": "02Haupt Wlan aus",
                   	"smartType": "SWITCH"
                   }
                });
                
                //##########---hier Gast WLAN---##########
                
                //Datenpunkt für Gast Wifi Status erstellen
                
                createState('Unifi.Unifi_Wifi.02Gast_Wifi.01Gast_Wifi_Status', {
                   name: 'Unifi Gast Wifi Status',
                   role: 'switch',
                   type: "boolean",
                   read: true,
                   write: false,
                });
                
                //Datenpunkt Button zum schalten für Gast Wifi an erstellen
                
                createState('Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an', {
                   name: 'Unifi Gast Wifi an',
                   role: 'button',
                   read: true,
                   write: true,
                   type: "boolean",
                   "smartName": {
                   	"de": "01Gast Wlan an",
                   	"smartType": "SWITCH"
                   }
                });
                
                //Datenpunkt Button zum schalten für Gast Wifi aus erstellen
                
                createState('Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus', {
                   name: 'Unifi Gast Wifi aus',
                   role: 'button',
                   read: true,
                   write: true,
                   type: "boolean",
                   "smartName": {
                   	"de": "02Gast Wlan aus",
                   	"smartType": "SWITCH"
                   }
                });
                
                //Datenpunkt für Anzahl Voucher erstellen
                
                createState('Unifi.Unifi_Wifi.02Gast_Wifi.04Gast_Wifi_Anzahl_Voucher', {
                   name: 'Unifi Gast Wifi Anzahl Voucher',
                   role: 'number',
                   min: '0',
                   max: '1000',
                   read: true,
                   write: false
                });
                
                //Datenpunkt Liste für Voucher für Gast Wifi erstellen
                
                createState('Unifi.Unifi_Wifi.02Gast_Wifi.005Gast_Wifi_Voucherliste', {
                   name: 'Unifi Gast Wifi Voucherliste',
                   role: 'string',
                   read: true,
                   write: false,
                });
                
                //##########---hier Geräteliste und Anzahl Geräte---##########
                
                //Datenpunkt Liste für angemeldete Geräte im Netzwerk erstellen
                
                createState('Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste', {
                   name: 'Unifi Haupt Wifi Geräteliste',
                   role: 'string',
                   read: true,
                   write: false,
                });
                
                //Datenpunkt für Anzahl angemeldete Geräte erstellen
                
                createState('Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Anzahl_Geraete', {
                   name: 'Unifi Haupt Wifi Anzahl Clients',
                   role: 'number',
                   min: '0',
                   max: '1000',
                   read: true,
                   write: false
                });
                
                
                
                function dlog(message) {
                   if (debug)
                   	console.log(message);
                }
                
                
                
                async function login() {
                   return new Promise(async (resolve, reject) => {
                   	let resp = 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) => { dlog("login: reject"), reject(e) });
                
                   	if (resp != null) {
                   		dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies" : "Ohne Cookies"));
                   		if (resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
                   			let set_cookies = resp.headers["set-cookie"];
                   			for (i = 0; i < set_cookies.length; i++) {
                   				let cookie = set_cookies[i];
                   				cookie = cookie.split(";")[0];
                   				cookies.push(cookie);
                   			}
                   		} else {
                   			dlog("login: no cookies to set!")
                   		}
                   		loggedIn = true;
                   		resolve();
                   	} else {
                   		dlog("login: rejected")
                   		reject("resp = null");
                   	}
                   });
                }
                
                async function getStatus(wifi_id) {
                   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) });
                
                   	dlog("got response " + JSON.stringify(resp));
                   	dlog(typeof resp);
                   	resp = JSON.parse(resp);
                   	dlog(resp.meta);
                   	dlog(resp.meta.rc);
                
                   	let wlanOn = resp.data[0].enabled;
                   	dlog("WLAN 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"));
                   		resolve(wlanOn);
                   	} else {
                   		dlog("nicht ok...")
                   		reject(JSON.stringify(resp));
                   	}
                
                   });
                
                }
                
                
                
                async function setWifi(enabled, wifi_id) {
                   return new Promise(async (resolve, reject) => {
                   	dlog("setWifi: start set Wifi_haupt - " + wifi_id);
                   	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) });
                
                   	dlog("setWifi: got response")
                
                   	if (resp != null) {
                   		dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
                   		dlog(resp);
                   		resolve();
                   	} else {
                   		dlog("setWifi: rejetced")
                   		dlog("resp: " + JSON.stringify(resp));
                   		reject("msg: " + JSON.parse(resp.body).meta.msg);
                   	}
                   });
                }
                
                //###################################
                
                //Geräteliste abrufen
                
                async function getClients() {
                   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/stat/sta/",
                   		headers: { Cookie: cookies.join("; ") }
                   	}).catch((e) => { dlog("getClients reject " + e); reject(e) });
                
                   	dlog("got response " + JSON.stringify(resp));
                   	dlog(typeof resp);
                   	dlog("--------------------- " + resp);
                   	resp = JSON.parse(resp);
                
                   	setState("javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Anzahl_Geraete", resp.data.length);
                   	var clientListe = "<table>";
                   	for (var i = 0; i < resp.data.length; i++) {
                   		dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
                   		clientListe = clientListe.concat("<tr><td>" + resp.data[i].hostname + "&ensp;</td><td>" + resp.data[i].essid + "&ensp;&ensp;&ensp;&ensp;</td><td>" + resp.data[i].mac + "</td></tr>");
                   		dlog(clientListe);
                   	}
                   	setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste", clientListe.concat(clientListe + "</table>"));
                   });
                }
                
                
                setInterval(async () => {
                   let state = await getStatus(wifi_id_haupt);
                   setState("Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status", state, true);
                   state = await getStatus(wifi_id_gast);
                   setState("Unifi.Unifi_Wifi.01Haupt_Wifi.01Gast_Wifi_Status", state, true);
                
                   await getClients();
                }, 10000); // Aktualisiert alle 10 Sekunden.
                

                ChaotC Offline
                ChaotC Offline
                Chaot
                schrieb am zuletzt editiert von
                #67

                @thewhobox
                Kannst du mir mal helfen was ich hier übersehe?

                javascript.0	2019-08-29 20:25:17.258	error	at Script.runInContext (vm.js:133:20)
                javascript.0	2019-08-29 20:25:17.258	error	at script.js.Unifi.WLanSchalten:1:50
                javascript.0	2019-08-29 20:25:17.258	error	TypeError: Cannot read property 'defaults' of undefined
                javascript.0	2019-08-29 20:25:17.258	error	^
                javascript.0	2019-08-29 20:25:17.257	error	const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
                javascript.0	2019-08-29 20:25:17.257	error	script.js.Unifi.WLanSchalten: script.js.Unifi.WLanSchalten:1
                javascript.0	2019-08-29 20:25:17.256	error	at Script.runInContext (vm.js:133:20)
                javascript.0	2019-08-29 20:25:17.256	error	at script.js.Unifi.WLanSchalten:1:17
                javascript.0	2019-08-29 20:25:17.256	error	script.js.Unifi.WLanSchalten: Error: Cannot find module '/opt/iobroker/node_modules/iobroker.javascript/lib/../../request-promise-native'
                

                ioBroker auf NUC unter Proxmox; VIS: 12" Touchscreen und 17" Touch; Lichtsteuerung, Thermometer und Sensoren: Tasmota (39); Ambiente Beleuchtung: WLED (9); Heizung: DECT Thermostate (9) an Fritz 6690; EMS-ESP; 1 Echo V2; 3 Echo DOT; 1 Echo Connect; 2 Echo Show 5; Unifi Ap-Ac Lite.

                liv-in-skyL 1 Antwort Letzte Antwort
                1
                • ChaotC Chaot

                  @thewhobox
                  Kannst du mir mal helfen was ich hier übersehe?

                  javascript.0	2019-08-29 20:25:17.258	error	at Script.runInContext (vm.js:133:20)
                  javascript.0	2019-08-29 20:25:17.258	error	at script.js.Unifi.WLanSchalten:1:50
                  javascript.0	2019-08-29 20:25:17.258	error	TypeError: Cannot read property 'defaults' of undefined
                  javascript.0	2019-08-29 20:25:17.258	error	^
                  javascript.0	2019-08-29 20:25:17.257	error	const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
                  javascript.0	2019-08-29 20:25:17.257	error	script.js.Unifi.WLanSchalten: script.js.Unifi.WLanSchalten:1
                  javascript.0	2019-08-29 20:25:17.256	error	at Script.runInContext (vm.js:133:20)
                  javascript.0	2019-08-29 20:25:17.256	error	at script.js.Unifi.WLanSchalten:1:17
                  javascript.0	2019-08-29 20:25:17.256	error	script.js.Unifi.WLanSchalten: Error: Cannot find module '/opt/iobroker/node_modules/iobroker.javascript/lib/../../request-promise-native'
                  
                  liv-in-skyL Offline
                  liv-in-skyL Offline
                  liv-in-sky
                  schrieb am zuletzt editiert von
                  #68

                  @Chaot probier mal "request" in zusätzlichen modulen in setting der javascript-instanz

                  Image 2.png

                  nach einem gelösten Thread wäre es sinnvoll dies in der Überschrift des ersten Posts einzutragen [gelöst]-... Bitte benutzt das Voting rechts unten im Beitrag wenn er euch geholfen hat. Forum-Tools: PicPick https://picpick.app/en/download/ und ScreenToGif https://www.screentogif.com/downloads.html

                  dslraserD ChaotC 2 Antworten Letzte Antwort
                  0
                  • liv-in-skyL liv-in-sky

                    @Chaot probier mal "request" in zusätzlichen modulen in setting der javascript-instanz

                    Image 2.png

                    dslraserD Offline
                    dslraserD Offline
                    dslraser
                    Forum Testing Most Active
                    schrieb am zuletzt editiert von
                    #69

                    @liv-in-sky
                    habe ich bei mir nicht drinn (und geht trotzdem) ?
                    Screenshot_20190829-204707_Firefox.jpg

                    1 Antwort Letzte Antwort
                    0
                    • liv-in-skyL liv-in-sky

                      @Chaot probier mal "request" in zusätzlichen modulen in setting der javascript-instanz

                      Image 2.png

                      ChaotC Offline
                      ChaotC Offline
                      Chaot
                      schrieb am zuletzt editiert von
                      #70

                      @liv-in-sky
                      Danke für den Denkanstoß.
                      Ich habe jetzt zusätzlich "request-promise-native" eingefügt und die Fehlermeldung ist weg.

                      Ich habe aber ehrlich gesagt keine Ahnung warum. Mit "request" alleine hat es nicht funktioniert.

                      ioBroker auf NUC unter Proxmox; VIS: 12" Touchscreen und 17" Touch; Lichtsteuerung, Thermometer und Sensoren: Tasmota (39); Ambiente Beleuchtung: WLED (9); Heizung: DECT Thermostate (9) an Fritz 6690; EMS-ESP; 1 Echo V2; 3 Echo DOT; 1 Echo Connect; 2 Echo Show 5; Unifi Ap-Ac Lite.

                      1 Antwort Letzte Antwort
                      0
                      • ChaotC Offline
                        ChaotC Offline
                        Chaot
                        schrieb am zuletzt editiert von
                        #71

                        Ok, jetzt habe ich doch noch eine Frage.
                        Die Datenpunkte werden korrekt erstellt.
                        Habe ich auch die Möglichkeit über einen Datenpunkte einen Voucher zu erstellen oder werden da nur die Voucher ausgelesen die ich über den Hotspot Manager erstelle?
                        Mein Gedanke war das ich in der VIS einen Button für einen Voucher einfüge (oder macht das keinen Sinn?)

                        ioBroker auf NUC unter Proxmox; VIS: 12" Touchscreen und 17" Touch; Lichtsteuerung, Thermometer und Sensoren: Tasmota (39); Ambiente Beleuchtung: WLED (9); Heizung: DECT Thermostate (9) an Fritz 6690; EMS-ESP; 1 Echo V2; 3 Echo DOT; 1 Echo Connect; 2 Echo Show 5; Unifi Ap-Ac Lite.

                        liv-in-skyL 1 Antwort Letzte Antwort
                        0
                        • ChaotC Chaot

                          Ok, jetzt habe ich doch noch eine Frage.
                          Die Datenpunkte werden korrekt erstellt.
                          Habe ich auch die Möglichkeit über einen Datenpunkte einen Voucher zu erstellen oder werden da nur die Voucher ausgelesen die ich über den Hotspot Manager erstelle?
                          Mein Gedanke war das ich in der VIS einen Button für einen Voucher einfüge (oder macht das keinen Sinn?)

                          liv-in-skyL Offline
                          liv-in-skyL Offline
                          liv-in-sky
                          schrieb am zuletzt editiert von
                          #72

                          @Chaot hab ich auch schon dran gedacht - im moment geht das nicht, da brauche ich wahrscheinlich etwas hilfe - wenn es mal gehen sollte -dann mehr info auf diesem kanal :-)

                          nach einem gelösten Thread wäre es sinnvoll dies in der Überschrift des ersten Posts einzutragen [gelöst]-... Bitte benutzt das Voting rechts unten im Beitrag wenn er euch geholfen hat. Forum-Tools: PicPick https://picpick.app/en/download/ und ScreenToGif https://www.screentogif.com/downloads.html

                          ChaotC 1 Antwort Letzte Antwort
                          1
                          • liv-in-skyL liv-in-sky

                            @Chaot hab ich auch schon dran gedacht - im moment geht das nicht, da brauche ich wahrscheinlich etwas hilfe - wenn es mal gehen sollte -dann mehr info auf diesem kanal :-)

                            ChaotC Offline
                            ChaotC Offline
                            Chaot
                            schrieb am zuletzt editiert von
                            #73

                            @liv-in-sky
                            Ok, danke für die Info.
                            Ich denke mal das das bestimmt irgendwann umsetzbar wird.
                            Zumindest für mich wäre das die perfekte Lösung.
                            Da ich mittlerweile mit mehreren Geräten für die VIS arbeite bin ich aktuell daran ein Tablet als "Multimedia" Vis einzurichten.
                            Also Musiksteuerung drauf wie bei einer Jukebox und Internetradio. Und genau da drauf wäre dann der button für den Gästezugang perfekt.

                            ioBroker auf NUC unter Proxmox; VIS: 12" Touchscreen und 17" Touch; Lichtsteuerung, Thermometer und Sensoren: Tasmota (39); Ambiente Beleuchtung: WLED (9); Heizung: DECT Thermostate (9) an Fritz 6690; EMS-ESP; 1 Echo V2; 3 Echo DOT; 1 Echo Connect; 2 Echo Show 5; Unifi Ap-Ac Lite.

                            1 Antwort Letzte Antwort
                            0
                            • thewhoboxT Offline
                              thewhoboxT Offline
                              thewhobox
                              schrieb am zuletzt editiert von
                              #74

                              @dslraser So, hier dann nochmal dein Skript in einer abgespeckten Version.
                              Du kannst von jedem WLAN den Status abfragen. Du gibst der Funktion setWifi(WiFi_id) die Wifi-Id als Parameter mit.

                              const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
                              const unifi_username = "benutzer";
                              const unifi_password = "passwort";
                              const unifi_controller = "https://192.168.xxx.xxx:xxxx";
                              const wifi_id_haupt = "xxxxxxxxxx";
                              const wifi_id_gast = "xxxxxxxxxx";
                              let cookies = [];
                              let loggedIn = false;
                              let debug = false;
                              
                              on({ id: 'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an'/*Unifi Haupt Wifi an*/, val: true, change: 'any' }, () => {
                                 setWifi(true, wifi_id_haupt);
                              });
                              on({ id: 'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus'/*Unifi Haupt Wifi aus*/, val: true, change: 'any' }, () => {
                                 setWifi(false, wifi_id_haupt);
                              });
                              on({ id: 'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an'/*Unifi Gast Wifi an*/, val: true, change: 'any' }, () => {
                                 setWifi(true, wifi_id_gast);
                              });
                              on({ id: 'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus'/*Unifi Gast Wifi aus*/, val: true, change: 'any' }, () => {
                                 setWifi(false, wifi_id_gast);
                              });
                              
                              //##########---hier Haupt WLAN---##########
                              //Datenpunkt für Haupt Wifi Status erstellen
                              createState('Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status', {
                                 name: 'Unifi Haupt Wifi Status',
                                 role: 'switch',
                                 type: "boolean",
                                 read: true,
                                 write: false,
                              });
                              
                              //Datenpunkt Button zum schalten für Haupt Wifi an erstellen
                              createState('Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an', {
                                 name: 'Unifi Haupt Wifi an',
                                 role: 'button',
                                 read: true,
                                 write: true,
                                 type: "boolean",
                                 "smartName": {
                                     "de": "01Haupt Wlan an",
                                     "smartType": "SWITCH"
                                 }
                              });
                              
                              //Datenpunkt Button zum schalten für Haupt Wifi aus erstellen
                              createState('Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus', {
                                 name: 'Unifi Haupt Wifi aus',
                                 role: 'button',
                                 read: true,
                                 write: true,
                                 type: "boolean",
                                 "smartName": {
                                     "de": "02Haupt Wlan aus",
                                     "smartType": "SWITCH"
                                 }
                              });
                              
                              //##########---hier Gast WLAN---##########
                              //Datenpunkt für Gast Wifi Status erstellen
                              createState('Unifi.Unifi_Wifi.02Gast_Wifi.01Gast_Wifi_Status', {
                                 name: 'Unifi Gast Wifi Status',
                                 role: 'switch',
                                 type: "boolean",
                                 read: true,
                                 write: false,
                              });
                              
                              //Datenpunkt Button zum schalten für Gast Wifi an erstellen
                              createState('Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an', {
                                 name: 'Unifi Gast Wifi an',
                                 role: 'button',
                                 read: true,
                                 write: true,
                                 type: "boolean",
                                 "smartName": {
                                     "de": "01Gast Wlan an",
                                     "smartType": "SWITCH"
                                 }
                              });
                              
                              //Datenpunkt Button zum schalten für Gast Wifi aus erstellen
                              createState('Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus', {
                                 name: 'Unifi Gast Wifi aus',
                                 role: 'button',
                                 read: true,
                                 write: true,
                                 type: "boolean",
                                 "smartName": {
                                     "de": "02Gast Wlan aus",
                                     "smartType": "SWITCH"
                                 }
                              });
                              
                              //Datenpunkt für Anzahl Voucher erstellen
                              createState('Unifi.Unifi_Wifi.02Gast_Wifi.04Gast_Wifi_Anzahl_Voucher', {
                                 name: 'Unifi Gast Wifi Anzahl Voucher',
                                 role: 'number',
                                 min: '0',
                                 max: '1000',
                                 read: true,
                                 write: false
                              });
                              
                              //Datenpunkt Liste für Voucher für Gast Wifi erstellen
                              createState('Unifi.Unifi_Wifi.02Gast_Wifi.05Gast_Wifi_Voucherliste', {
                                 name: 'Unifi Gast Wifi Voucherliste',
                                 role: 'string',
                                 read: true,
                                 write: false,
                              });
                              
                              //##########---hier Geräteliste und Anzahl Geräte---##########
                              //Datenpunkt Liste für angemeldete Geräte im Netzwerk erstellen
                              createState('Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste', {
                                 name: 'Unifi Haupt Wifi Geräteliste',
                                 role: 'string',
                                 read: true,
                                 write: false,
                              });
                              
                              //Datenpunkt für Anzahl angemeldete Geräte erstellen
                              createState('Unifi.Unifi_Wifi.01Haupt_Wifi.05Haupt_Wifi_Anzahl_Geraete', {
                                 name: 'Unifi Haupt Wifi Anzahl Clients',
                                 role: 'number',
                                 min: '0',
                                 max: '1000',
                                 read: true,
                                 write: false
                              });
                              
                              function dlog(message) {
                                 if (debug)
                                     console.log(message);
                              }
                              
                              async function login() {
                                 return new Promise(async (resolve, reject) => {
                                     let resp = 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) => { dlog("login: reject"), reject(e) })
                              
                                     if (resp != null) {
                                         dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies" : "Ohne Cookies"));
                                         if (resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
                                             let set_cookies = resp.headers["set-cookie"];
                                             for (i = 0; i < set_cookies.length; i++) {
                                                 let cookie = set_cookies[i];
                                                 cookie = cookie.split(";")[0];
                                                 cookies.push(cookie);
                                             }
                                         } else {
                                             dlog("login: no cookies to set!")
                                         }
                                         loggedIn = true;
                                         resolve();
                                     } else {
                                         dlog("login: rejected")
                                         reject("resp = null");
                                     }
                                 });
                              }
                              
                              async function getStatus(wifi_id) {
                                 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) });
                              
                                     dlog("got response " + JSON.stringify(resp));
                                     resp = JSON.parse(resp);
                              
                                     let wlanOn = resp.data[0].enabled;
                                     dlog("WLAN 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"));
                                         resolve(wlanOn);
                                     } else {
                                         dlog("nicht ok...")
                                         reject(JSON.stringify(resp));
                                     }
                                 });
                              }
                              
                              async function setWifi(enabled, wifi_id) {
                                 return new Promise(async (resolve, reject) => {
                                     dlog("setWifi_haupt: start set Wifi_haupt");
                                     if (!loggedIn) { dlog("need to login"); await login().catch((e) => reject(e)); }
                                     dlog("setWifi_haupt: 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) });
                                     dlog("setWifi: got response")
                              
                                     if (resp != null) {
                                         dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
                                         dlog(resp);
                                         resolve();
                                     } else {
                                         dlog("setWifi: rejetced")
                                         dlog("resp: " + JSON.stringify(resp));
                                         reject("msg: " + JSON.parse(resp.body).meta.msg);
                                     }
                                 });
                              }
                              
                              //###################################
                              
                              //Geräteliste abrufen
                              
                              async function getClients() {
                                 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/stat/sta/",
                                         headers: { Cookie: cookies.join("; ") }
                                     }).catch((e) => { dlog("getStatus_haupt reject " + e); reject(e) });
                              
                                     dlog("got response " + JSON.stringify(resp));
                                     dlog(typeof resp);
                                     dlog("--------------------- " + resp);
                                     resp = JSON.parse(resp);
                              
                                     setState("javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.05Haupt_Wifi_Anzahl_Geraete", resp.data.length);
                              
                                     var clientListe = "<table>";
                                     for (var i = 0; i < resp.data.length; i++) {
                                         dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
                                         clientListe = clientListe.concat("<tr><td>" + resp.data[i].hostname + "&ensp;</td><td>" + resp.data[i].essid + "&ensp;&ensp;&ensp;&ensp;</td><td>" + resp.data[i].mac + "</td></tr>");
                                         dlog(clientListe);
                                     }
                              
                                     setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste", clientListe.concat(clientListe + "</table>"));
                                 });
                              }
                              
                              
                              
                              setInterval(async () => {
                              
                                 let state = await getStatus(wifi_id_haupt);
                                 setState("Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status", state, true);
                              
                                 state = await getStatus(wifi_id_gast);
                                 setState("Unifi.Unifi_Wifi.02Gast_Wifi.01Gast_Wifi_Status", state, true);
                              
                                 state = await getClients();
                                 setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Anzahl_Geraete");
                                 setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste", clientListe.concat(clientListe + "</table>"));
                              
                              }, 10000); // Aktualisiert alle 10 Sekunden.
                              
                              

                              Mir ist noch mehr aufgefallen, was man verbessern könnte:
                              Du benutzt Momentan 6 States allein für An/Aus/Status.
                              Die drei Funktionen könntest du in einem einzigen Datenpunkt machen.

                              @liv-in-sky Voucher erstellen sollte mit der API funktionieren. Zumindest ist es in dem von dir verlinkten Skript im anderen Thread eingebaut.

                              Meine Adapter: emby | discovery
                              Benutzt das Voting rechts unten im Beitrag wenn er euch geholfen hat.

                              dslraserD 1 Antwort Letzte Antwort
                              0
                              • thewhoboxT Offline
                                thewhoboxT Offline
                                thewhobox
                                schrieb am zuletzt editiert von
                                #75

                                Und wer mutig ist und was testen möchte kann mal das Skript ausprobieren.
                                Ist nun noch kleiner.
                                Datenpunkte werden nun Variabel hinzugefügt.
                                Es gibt nur noch ein Datenpunkt pro WLAN! Setzen auf false schaltet es aus, auf true schaltet es an. Außerdem wird der Datenpunkt alle 15 Sekunden mit dem aktuellen Status geupdated.

                                const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
                                const unifi_username = "benutzer";
                                const unifi_password = "passwort";
                                const unifi_controller = "https://192.168.xxx.xxx:xxxx";
                                
                                const dpPrefix = "javascript.0.Unifi.Unifi_Wifi.";
                                
                                //Hier werden alle WLANS aufgelistet.
                                //Index und name müssen identisch sein!
                                //Datenpunkte werden automatisch angelegt.
                                const wifis = {
                                   "01_Haupt_Wifi": { name: "01_Haupt_Wifi", id: "xxxxxxxxxx", desc: "Unifi Haupt Wifi", smart: "01 Haut Wlan" } ,
                                   "02_Gast_Wifi": { name: "02_Gast_Wifi", id: "xxxxxxxxxx", desc: "Unifi Gast Wifi", smart: "02 Gast Wlan" }
                                }
                                
                                let cookies = [];
                                let loggedIn = false;
                                let debug = false;
                                
                                let wifiDPs = [];
                                
                                
                                function dlog(message) {
                                   if (debug)
                                       console.log(message);
                                }
                                
                                //Erstelle Datenpunkte für die WLANs automatisch
                                for(let wifi_name in wifis) {
                                   wifiDPs.push(dpPrefix + wifis[wifi_name].id);
                                
                                   createState(dpPrefix + wifi_name, {
                                       name: wifis[wifi_name].desc,
                                       role: 'state',
                                       read: true,
                                       write: true,
                                       type: "boolean",
                                       smartName: {
                                           de: wifis[wifi_name].smart,
                                           smartType: "SWITCH"
                                       }
                                   });
                                }
                                
                                //Erstelle Datenpunkte für die Geräteliste
                                createState(dpPrefix + "00_Wifi_Geraeteliste", {
                                   name: 'Unifi Haupt Wifi Geräteliste',
                                   role: 'string',
                                   read: true,
                                   write: false,
                                });
                                createState(dpPrefix + "00_Anzahl_Geraete", {
                                   name: 'Unifi Haupt Wifi Anzahl Clients',
                                   role: 'number',
                                   min: '0',
                                   max: '1000',
                                   read: true,
                                   write: false
                                });
                                
                                //Reagiert auf manuelle änderungen vom Datenpunkt
                                //ACK muss false sein!
                                on({ id: wifiDPs, ack: false }, (dp) => {
                                   let wlan_id = dp.id.substring(dp.id.lastIndexOf(".")+1)
                                   dlog("State Changed: " + wlan_id)
                                   setWifi(dp.state.val, wifis[wlan_id].id);
                                });
                                
                                //Login für die API
                                async function login() {
                                   return new Promise(async (resolve, reject) => {
                                       let resp = 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) => { dlog("login: reject"), reject(e) })
                                
                                       if (resp != null) {
                                           dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies" : "Ohne Cookies"));
                                           if (resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
                                               let set_cookies = resp.headers["set-cookie"];
                                               for (i = 0; i < set_cookies.length; i++) {
                                                   let cookie = set_cookies[i];
                                                   cookie = cookie.split(";")[0];
                                                   cookies.push(cookie);
                                               }
                                           } else {
                                               dlog("login: no cookies to set!")
                                           }
                                           loggedIn = true;
                                           resolve();
                                       } else {
                                           dlog("login: rejected")
                                           reject("resp = null");
                                       }
                                   });
                                }
                                
                                //Updatet status vom Wifi
                                //wifi: wifi object aus der konstanten wifis
                                async function getStatus(wifi) {
                                   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) });
                                
                                       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"));
                                           setState(dpPrefix + wifi.name, state, true);
                                           resolve(wlanOn);
                                       } else {
                                           dlog("nicht ok...")
                                           reject(JSON.stringify(resp));
                                       }
                                   });
                                }
                                
                                
                                //Wifi an-/ausschalten
                                //enabled: true = anschalten; false = ausschalten
                                //wifi: wifi object aus der konstanten wifis
                                async function setWifi(enabled, wifi) {
                                   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) });
                                       dlog("setWifi: got response")
                                
                                       if (resp != null) {
                                           dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
                                           dlog(resp);
                                           setState(dpPrefix + wifi.name, enabled, true);
                                           resolve();
                                       } else {
                                           dlog("setWifi: rejetced")
                                           dlog("resp: " + JSON.stringify(resp));
                                           reject("msg: " + JSON.parse(resp.body).meta.msg);
                                       }
                                   });
                                }
                                
                                //Geräteliste abrufen
                                async function getClients() {
                                   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/stat/sta/",
                                           headers: { Cookie: cookies.join("; ") }
                                       }).catch((e) => { dlog("getStatus_haupt reject " + e); reject(e) });
                                
                                       dlog("got response " + JSON.stringify(resp));
                                       dlog(typeof resp);
                                       dlog("--------------------- " + resp);
                                       resp = JSON.parse(resp);
                                
                                       setState(dpPrefix + "00_Anzahl_Geraete", resp.data.length);
                                
                                       var clientListe = "<table>";
                                       for (var i = 0; i < resp.data.length; i++) {
                                           dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
                                           clientListe = clientListe.concat("<tr><td>" + resp.data[i].hostname + "&ensp;</td><td>" + resp.data[i].essid + "&ensp;&ensp;&ensp;&ensp;</td><td>" + resp.data[i].mac + "</td></tr>");
                                           dlog(clientListe);
                                       }
                                
                                       setState(dpPrefix + "00_Geraeteliste", clientListe.concat(clientListe + "</table>"));
                                   });
                                }
                                
                                
                                
                                setInterval(async () => {
                                   for(let wifi_name in wifis) {
                                       await getStatus(wifis[wifi_name]);
                                   }
                                
                                   await getClients();
                                
                                }, 15000); // Aktualisiert alle 10 Sekunden.
                                
                                
                                // Wlan manuell abfragen:
                                // let status = await getStatus(wifis["01_Haupt_Wlan"]);
                                

                                Meine Adapter: emby | discovery
                                Benutzt das Voting rechts unten im Beitrag wenn er euch geholfen hat.

                                dslraserD 4 Antworten Letzte Antwort
                                0
                                • thewhoboxT thewhobox

                                  @dslraser So, hier dann nochmal dein Skript in einer abgespeckten Version.
                                  Du kannst von jedem WLAN den Status abfragen. Du gibst der Funktion setWifi(WiFi_id) die Wifi-Id als Parameter mit.

                                  const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
                                  const unifi_username = "benutzer";
                                  const unifi_password = "passwort";
                                  const unifi_controller = "https://192.168.xxx.xxx:xxxx";
                                  const wifi_id_haupt = "xxxxxxxxxx";
                                  const wifi_id_gast = "xxxxxxxxxx";
                                  let cookies = [];
                                  let loggedIn = false;
                                  let debug = false;
                                  
                                  on({ id: 'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an'/*Unifi Haupt Wifi an*/, val: true, change: 'any' }, () => {
                                     setWifi(true, wifi_id_haupt);
                                  });
                                  on({ id: 'javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus'/*Unifi Haupt Wifi aus*/, val: true, change: 'any' }, () => {
                                     setWifi(false, wifi_id_haupt);
                                  });
                                  on({ id: 'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an'/*Unifi Gast Wifi an*/, val: true, change: 'any' }, () => {
                                     setWifi(true, wifi_id_gast);
                                  });
                                  on({ id: 'javascript.0.Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus'/*Unifi Gast Wifi aus*/, val: true, change: 'any' }, () => {
                                     setWifi(false, wifi_id_gast);
                                  });
                                  
                                  //##########---hier Haupt WLAN---##########
                                  //Datenpunkt für Haupt Wifi Status erstellen
                                  createState('Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status', {
                                     name: 'Unifi Haupt Wifi Status',
                                     role: 'switch',
                                     type: "boolean",
                                     read: true,
                                     write: false,
                                  });
                                  
                                  //Datenpunkt Button zum schalten für Haupt Wifi an erstellen
                                  createState('Unifi.Unifi_Wifi.01Haupt_Wifi.02Haupt_Wifi_an', {
                                     name: 'Unifi Haupt Wifi an',
                                     role: 'button',
                                     read: true,
                                     write: true,
                                     type: "boolean",
                                     "smartName": {
                                         "de": "01Haupt Wlan an",
                                         "smartType": "SWITCH"
                                     }
                                  });
                                  
                                  //Datenpunkt Button zum schalten für Haupt Wifi aus erstellen
                                  createState('Unifi.Unifi_Wifi.01Haupt_Wifi.03Haupt_Wifi_aus', {
                                     name: 'Unifi Haupt Wifi aus',
                                     role: 'button',
                                     read: true,
                                     write: true,
                                     type: "boolean",
                                     "smartName": {
                                         "de": "02Haupt Wlan aus",
                                         "smartType": "SWITCH"
                                     }
                                  });
                                  
                                  //##########---hier Gast WLAN---##########
                                  //Datenpunkt für Gast Wifi Status erstellen
                                  createState('Unifi.Unifi_Wifi.02Gast_Wifi.01Gast_Wifi_Status', {
                                     name: 'Unifi Gast Wifi Status',
                                     role: 'switch',
                                     type: "boolean",
                                     read: true,
                                     write: false,
                                  });
                                  
                                  //Datenpunkt Button zum schalten für Gast Wifi an erstellen
                                  createState('Unifi.Unifi_Wifi.02Gast_Wifi.02Gast_Wifi_an', {
                                     name: 'Unifi Gast Wifi an',
                                     role: 'button',
                                     read: true,
                                     write: true,
                                     type: "boolean",
                                     "smartName": {
                                         "de": "01Gast Wlan an",
                                         "smartType": "SWITCH"
                                     }
                                  });
                                  
                                  //Datenpunkt Button zum schalten für Gast Wifi aus erstellen
                                  createState('Unifi.Unifi_Wifi.02Gast_Wifi.03Gast_Wifi_aus', {
                                     name: 'Unifi Gast Wifi aus',
                                     role: 'button',
                                     read: true,
                                     write: true,
                                     type: "boolean",
                                     "smartName": {
                                         "de": "02Gast Wlan aus",
                                         "smartType": "SWITCH"
                                     }
                                  });
                                  
                                  //Datenpunkt für Anzahl Voucher erstellen
                                  createState('Unifi.Unifi_Wifi.02Gast_Wifi.04Gast_Wifi_Anzahl_Voucher', {
                                     name: 'Unifi Gast Wifi Anzahl Voucher',
                                     role: 'number',
                                     min: '0',
                                     max: '1000',
                                     read: true,
                                     write: false
                                  });
                                  
                                  //Datenpunkt Liste für Voucher für Gast Wifi erstellen
                                  createState('Unifi.Unifi_Wifi.02Gast_Wifi.05Gast_Wifi_Voucherliste', {
                                     name: 'Unifi Gast Wifi Voucherliste',
                                     role: 'string',
                                     read: true,
                                     write: false,
                                  });
                                  
                                  //##########---hier Geräteliste und Anzahl Geräte---##########
                                  //Datenpunkt Liste für angemeldete Geräte im Netzwerk erstellen
                                  createState('Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste', {
                                     name: 'Unifi Haupt Wifi Geräteliste',
                                     role: 'string',
                                     read: true,
                                     write: false,
                                  });
                                  
                                  //Datenpunkt für Anzahl angemeldete Geräte erstellen
                                  createState('Unifi.Unifi_Wifi.01Haupt_Wifi.05Haupt_Wifi_Anzahl_Geraete', {
                                     name: 'Unifi Haupt Wifi Anzahl Clients',
                                     role: 'number',
                                     min: '0',
                                     max: '1000',
                                     read: true,
                                     write: false
                                  });
                                  
                                  function dlog(message) {
                                     if (debug)
                                         console.log(message);
                                  }
                                  
                                  async function login() {
                                     return new Promise(async (resolve, reject) => {
                                         let resp = 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) => { dlog("login: reject"), reject(e) })
                                  
                                         if (resp != null) {
                                             dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies" : "Ohne Cookies"));
                                             if (resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
                                                 let set_cookies = resp.headers["set-cookie"];
                                                 for (i = 0; i < set_cookies.length; i++) {
                                                     let cookie = set_cookies[i];
                                                     cookie = cookie.split(";")[0];
                                                     cookies.push(cookie);
                                                 }
                                             } else {
                                                 dlog("login: no cookies to set!")
                                             }
                                             loggedIn = true;
                                             resolve();
                                         } else {
                                             dlog("login: rejected")
                                             reject("resp = null");
                                         }
                                     });
                                  }
                                  
                                  async function getStatus(wifi_id) {
                                     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) });
                                  
                                         dlog("got response " + JSON.stringify(resp));
                                         resp = JSON.parse(resp);
                                  
                                         let wlanOn = resp.data[0].enabled;
                                         dlog("WLAN 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"));
                                             resolve(wlanOn);
                                         } else {
                                             dlog("nicht ok...")
                                             reject(JSON.stringify(resp));
                                         }
                                     });
                                  }
                                  
                                  async function setWifi(enabled, wifi_id) {
                                     return new Promise(async (resolve, reject) => {
                                         dlog("setWifi_haupt: start set Wifi_haupt");
                                         if (!loggedIn) { dlog("need to login"); await login().catch((e) => reject(e)); }
                                         dlog("setWifi_haupt: 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) });
                                         dlog("setWifi: got response")
                                  
                                         if (resp != null) {
                                             dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
                                             dlog(resp);
                                             resolve();
                                         } else {
                                             dlog("setWifi: rejetced")
                                             dlog("resp: " + JSON.stringify(resp));
                                             reject("msg: " + JSON.parse(resp.body).meta.msg);
                                         }
                                     });
                                  }
                                  
                                  //###################################
                                  
                                  //Geräteliste abrufen
                                  
                                  async function getClients() {
                                     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/stat/sta/",
                                             headers: { Cookie: cookies.join("; ") }
                                         }).catch((e) => { dlog("getStatus_haupt reject " + e); reject(e) });
                                  
                                         dlog("got response " + JSON.stringify(resp));
                                         dlog(typeof resp);
                                         dlog("--------------------- " + resp);
                                         resp = JSON.parse(resp);
                                  
                                         setState("javascript.0.Unifi.Unifi_Wifi.01Haupt_Wifi.05Haupt_Wifi_Anzahl_Geraete", resp.data.length);
                                  
                                         var clientListe = "<table>";
                                         for (var i = 0; i < resp.data.length; i++) {
                                             dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
                                             clientListe = clientListe.concat("<tr><td>" + resp.data[i].hostname + "&ensp;</td><td>" + resp.data[i].essid + "&ensp;&ensp;&ensp;&ensp;</td><td>" + resp.data[i].mac + "</td></tr>");
                                             dlog(clientListe);
                                         }
                                  
                                         setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste", clientListe.concat(clientListe + "</table>"));
                                     });
                                  }
                                  
                                  
                                  
                                  setInterval(async () => {
                                  
                                     let state = await getStatus(wifi_id_haupt);
                                     setState("Unifi.Unifi_Wifi.01Haupt_Wifi.01Haupt_Wifi_Status", state, true);
                                  
                                     state = await getStatus(wifi_id_gast);
                                     setState("Unifi.Unifi_Wifi.02Gast_Wifi.01Gast_Wifi_Status", state, true);
                                  
                                     state = await getClients();
                                     setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Anzahl_Geraete");
                                     setState("Unifi.Unifi_Wifi.01Haupt_Wifi.04Haupt_Wifi_Geraeteliste", clientListe.concat(clientListe + "</table>"));
                                  
                                  }, 10000); // Aktualisiert alle 10 Sekunden.
                                  
                                  

                                  Mir ist noch mehr aufgefallen, was man verbessern könnte:
                                  Du benutzt Momentan 6 States allein für An/Aus/Status.
                                  Die drei Funktionen könntest du in einem einzigen Datenpunkt machen.

                                  @liv-in-sky Voucher erstellen sollte mit der API funktionieren. Zumindest ist es in dem von dir verlinkten Skript im anderen Thread eingebaut.

                                  dslraserD Offline
                                  dslraserD Offline
                                  dslraser
                                  Forum Testing Most Active
                                  schrieb am zuletzt editiert von
                                  #76

                                  @thewhobox
                                  Danke Dir für die Mühe. Ich habe mir die andere Variante für später abgespeichert.
                                  Ich hatte mir bewußt mehrer Datenpunkte als Button gemacht, da ich die in einer Routine in der Alexa App besser/individueller verarbeiten kann. (Alexa, schalte Gastnetz an---oder eben was man sagen will, dann muss ich mich nicht an den SmartNamen für den iot Adapter halten, wenn ich was an oder ausschalten will). Aber wie ganz oben geschrieben geht das ja auch mit Schaltern und weniger Datenpunkten.

                                  Jetzt habe ich es mir noch mal anders überlegt und es noch mal für mich umstrukturiert und es erstmal bei einem WLAN (Gäste) im Script belassen.

                                  @liv-in-sky und @thewhobox
                                  Ich habe jetzt alles auf javascript.0 und mal alle Codeschnipsel von @liv-in-sky bei mir eingebaut.
                                  Die Voucher im Datenpunkt Liste werden geholt, auch die Anzahl (bei mir 9 ) stimmt

                                  Bildschirmfoto 2019-08-29 um 23.51.24.png

                                  Was ich bis jetzt nicht hinbekomme sind die "Einzel-Codes", wie oben von Dir @liv-in-sky gezeigt. Könntet Ihr @thewhobox und @liv-in-sky mal drüber schauen wo der Fehler ist ?

                                  const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
                                  const unifi_username = "user";
                                  const unifi_password = "passwort";
                                  const unifi_controller = "https://192.168.xxx.xxx:xxxx";
                                  const wifi_id = "xxxxxxxxxxxxxxxxxx";
                                  
                                  var fs = require('fs')
                                  datei = "/opt/iobroker/iobroker-data/files/iqontrol/htmlvoucher.html";
                                  datei2 = "/opt/iobroker/iobroker-data/files/iqontrol/htmlclients.html";
                                  
                                  let cookies = [];
                                  let loggedIn = false;
                                  let debug = false;
                                  
                                  on({id:'javascript.0.Unifi.01Unifi_Wifi.01Gast_Wifi.02Gast_Wifi_anschalten'/*Unifi Gast Wifi anschalten*/, val: true, change: 'any'}, wifi_an);
                                  on({id:'javascript.0.Unifi.01Unifi_Wifi.01Gast_Wifi.03Gast_Wifi_ausschalten'/*Unifi Gast Wifi ausschalten*/, val: true, change: 'any'}, wifi_aus);
                                  
                                  //##########---hier Gast WLAN---##########
                                  
                                  //Datenpunkt für Gast Wifi Status erstellen
                                  createState('Unifi.01Unifi_Wifi.01Gast_Wifi.01Gast_Wifi_Status', {
                                    name: 'Unifi Gast Wifi Status',
                                    role: 'switch',
                                    type: "boolean",
                                    read: true,
                                    write: false,
                                  });
                                  
                                  //Datenpunkt Button zum schalten für Gast Wifi an erstellen
                                  createState('Unifi.01Unifi_Wifi.01Gast_Wifi.02Gast_Wifi_anschalten', {
                                    name: 'Unifi Gast Wifi anschalten',
                                    role: 'button',
                                    read: true,
                                    write: true,
                                    type: "boolean",
                                    "smartName": {
                                    	"de": "01Gast Wlan an",
                                    	"smartType": "SWITCH"
                                    }
                                  });
                                  
                                  //Datenpunkt Button zum schalten für Gast Wifi aus erstellen
                                  createState('Unifi.01Unifi_Wifi.01Gast_Wifi.03Gast_Wifi_ausschalten', {
                                    name: 'Unifi Gast Wifi ausschalten',
                                    role: 'button',
                                    read: true,
                                    write: true,
                                    type: "boolean",
                                    "smartName": {
                                    	"de": "02Gast Wlan aus",
                                    	"smartType": "SWITCH"
                                    }
                                  });
                                  
                                  //Datenpunkt für Anzahl Voucher erstellen
                                  createState('Unifi.01Unifi_Wifi.01Gast_Wifi.04Gast_Wifi_Voucher_Anzahl', {
                                    name: 'Unifi Gast Wifi Voucher Anzahl',
                                    role: 'number',
                                    min: '0',
                                    max: '1000',
                                    read: true,
                                    write: false
                                  });
                                  
                                  //Datenpunkt Liste für Voucher für Gast Wifi erstellen
                                  createState('Unifi.01Unifi_Wifi.01Gast_Wifi.05Gast_Wifi_Voucher_Liste', {
                                    name: 'Unifi Gast Wifi Voucher Liste',
                                    role: 'string',
                                    read: true,
                                    write: false,
                                  });
                                  
                                  for (var i = 1; i < 21; i++) { 
                                     var x=i.toString();
                                     if (i<10) x="0"+x;
                                    createState("Unifi.01Unifi_Wifi.01Gast_Wifi_Vouchers-CODES.CODE"+x, {
                                     name: 'Unifi Voucher_Code'+x, 
                                     role: 'string',
                                     read:  true, 
                                     write: true,
                                     });
                                  }
                                  
                                  //##########---hier Clients Liste und Anzahl Clients---##########
                                  
                                  //Datenpunkt Liste für angemeldete Clients im Netzwerk erstellen
                                  createState('Unifi.02Unifi_Clients.01Clients_Liste', {
                                    name: 'Unifi Clients Liste',
                                    role: 'string',
                                    read: true,
                                    write: false,
                                  });
                                  
                                  //Datenpunkt für Anzahl Clients erstellen
                                  createState('Unifi.02Unifi_Clients.02Clients_Anzahl', {
                                    name: 'Unifi Clients Anzahl',
                                    role: 'number',
                                    min: '0',
                                    max: '1000',
                                    read: true,
                                    write: false
                                  });
                                  
                                  function dlog(message) {
                                    if(debug)
                                        console.log(message);
                                  }
                                  
                                  async function login() {
                                    return new Promise(async (resolve, reject) => {
                                        let resp = 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) => { dlog("login: reject"), reject(e) });
                                        
                                        if(resp != null) {
                                            dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies":"Ohne Cookies"));
                                            if(resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
                                                let set_cookies = resp.headers["set-cookie"];
                                                for(i = 0; i < set_cookies.length; i++) {
                                                    let cookie = set_cookies[i];
                                                    cookie = cookie.split(";")[0];
                                                    cookies.push(cookie);
                                                }
                                            } else {
                                                dlog("login: no cookies to set!")
                                            }
                                            loggedIn = true;
                                            resolve();
                                        } else {
                                            dlog("login: rejected")
                                            reject("resp = null");
                                        }
                                    });
                                  }
                                  
                                  async function getStatus() {
                                     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) });
                                         dlog("got response " + JSON.stringify(resp));
                                         dlog(typeof resp);
                                         resp = JSON.parse(resp);
                                         dlog(resp.meta);
                                         dlog(resp.meta.rc);
                                         let wlanOn = resp.data[0].enabled;
                                         dlog("WLAN 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"));
                                             resolve(wlanOn);
                                         } else {
                                             dlog("nicht ok...")
                                             reject(JSON.stringify(resp));
                                         }
                                     });
                                  }
                                  
                                  async function setWifi(enabled) {
                                    return new Promise(async (resolve, reject) => {
                                        dlog("setWifi: start set wifi");
                                        if(!loggedIn) { dlog("need to login"); await login().catch((e) => reject(e)); }
                                        dlog("setWifi: now setting wifi");
                                        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) });
                                        dlog("setWifi: got response")
                                        if(resp != null) {
                                            dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
                                            dlog(resp);
                                            resolve();
                                        } else {
                                            dlog("setWifi: rejetced")
                                            dlog("resp: " + JSON.stringify(resp));
                                            reject("msg: " + JSON.parse(resp.body).meta.msg);
                                        }
                                    });
                                  } 
                                  //##########---Clients Liste und Anzahl abholen---##########
                                  
                                  async function getClients() {
                                    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/stat/sta/",
                                            headers: { Cookie: cookies.join("; ") }
                                        }).catch((e) => { dlog("getStatus reject " + e); reject(e) });  
                                   
                                  dlog("got response " + JSON.stringify(resp));
                                  dlog(typeof resp);
                                  dlog("--------------------- " + resp);
                                  resp = JSON.parse(resp);
                                  //log("--------------------- " + resp);
                                  
                                  dlog(resp.meta);
                                  dlog(resp.meta.rc);
                                  dlog(resp.data[2].hostname);
                                  dlog(resp.data.length);
                                  setState("javascript.0.Unifi.02Unifi_Clients.02Clients_Anzahl",resp.data.length);
                                  fs.writeFileSync(datei2, "<table><tr><td>HOSTNAME&ensp;</td><td>SID&ensp;&ensp;&ensp;&ensp;</td><td>MAC</td></tr> ");
                                  var clientListe = "<table>";
                                  for (var i = 0; i < resp.data.length; i++) { 
                                    dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
                                     clientListe = clientListe.concat("<tr><td>"+resp.data[i].hostname+"&ensp;</td><td>"+resp.data[i].essid+"&ensp;&ensp;&ensp;&ensp;</td><td>"+resp.data[i].mac+"</td></tr>");
                                     dlog(clientListe);
                                  }
                                  fs.appendFileSync(datei2, clientListe.concat("</table>"));
                                  setState("Unifi.02Unifi_Clients.01Clients_Liste", clientListe.concat(clientListe+"</table>"));
                                  });
                                  }
                                  
                                  //##########---Vouchers Liste und Anzahl abholen---##########
                                  
                                  async function getVouchers() {
                                     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/stat/voucher",
                                             headers: { Cookie: cookies.join("; ") }
                                         }).catch((e) => { dlog("getStatus reject " + e); reject(e) });  
                                    
                                  dlog("got response " + JSON.stringify(resp));
                                  dlog(typeof resp);
                                  dlog("--------------------- " + resp);
                                  resp = JSON.parse(resp);
                                  
                                  dlog(resp.meta);
                                  dlog(resp.meta.rc);
                                  dlog(resp.data[1].code);
                                  dlog(resp.data.length);
                                  var clientListe = "<table><tr><td>DURATION&ensp;</td><td>STATUSEXPIRES&ensp;&ensp;&ensp;&ensp;</td><td>CODE</td>&ensp;&ensp;</td><td>ERSTELLT</td></tr> ";
                                  fs.writeFileSync(datei, "<table><tr><td>DURATION&ensp;</td><td>STATUSEXPIRES&ensp;&ensp;&ensp;&ensp;</td><td>CODE</td>&ensp;&ensp;</td><td>ERSTELLT</td></tr> ");
                                  for (var i = 1; i < 21; i++) { 
                                     var x=i.toString();
                                     if ( i < 10) { var yyy="0"+x;} else {yyy=x}; setState("javascript.0.Unifi.01Unifi_Wifi.01Gast_Wifi_Vouchers-CODES.CODE"+yyy, "");}
                                     
                                  for (var i = 0; i < resp.data.length; i++) { 
                                    var zeit= resp.data[i].create_time*1000
                                    var zeit1 =  formatDate(getDateObject(zeit), "TT.MM.JJJJ SS:mm").toString();
                                  
                                    clientListe = clientListe.concat("<tr><td>"+resp.data[i].duration+"&ensp;</td><td>"+resp.data[i].status_expires+"&ensp;&ensp;&ensp;&ensp;</td><td>"+resp.data[i].code+"&ensp;&ensp;</td><td>" +zeit1 + "</td></tr>");
                                    var y=i+1; 
                                    var yy=y.toString();
                                    if (y<10 )  yy="0"+yy;
                                   
                                    if (i<20  )   
                                  
                                  setState("javascript.0.Unifi.01Unifi_Wifi.01Gast_Wifi_Vouchers-CODES.CODE"+yy, resp.data[i].code );
                                  }
                                  fs.appendFileSync(datei, clientListe.concat("</table>"));
                                  setState("javascript.0.Unifi.01Unifi_Wifi.01Gast_Wifi.05Gast_Wifi_Voucher_Liste", clientListe.concat("</table>"));
                                  setState("javascript.0.Unifi.01Unifi_Wifi.01Gast_Wifi.04Gast_Wifi_Voucher_Anzahl", resp.data.length);
                                  });
                                  }
                                  
                                  //##########---WiFi anschalten---##########
                                  async function wifi_an() {
                                     dlog("starting wifi_an");
                                     await setWifi(true).catch((e) => dlog("reject1: " + e));
                                     dlog("getting status");
                                     let wlan = await getStatus().catch((e) => dlog("reject2: " + e));
                                     console.log("fin")
                                     console.log(wlan);
                                  }
                                  
                                  //##########---WiFi ausschalten---##########
                                  async function wifi_aus() {
                                     dlog("starting wifi_aus");
                                     await setWifi(false).catch((e) => dlog("reject1: " + e));
                                     dlog("getting status");
                                     let wlan = await getStatus().catch((e) => dlog("reject2: " + e));
                                     console.log("fin")
                                     console.log(wlan);
                                  }
                                  
                                  //##########---WiFi Status---##########
                                  setInterval(async () => {
                                  let state = await getStatus();
                                     setState("Unifi.01Unifi_Wifi.01Gast_Wifi.01Gast_Wifi_Status", state, true);
                                  }, 10000); // Aktualisiert alle 10 Sekunden.
                                  
                                  //##########---WiFi Clients Liste und Anzahl---##########
                                  setInterval(async () => {
                                  let state = await getClients();
                                    setState("Unifi.02Unifi_Clients.01Clients_Liste", clientListe.concat(clientListe+"</table>"));
                                    setState("Unifi.02Unifi_Clients.02Clients_Anzahl");
                                  }, 10000); // Aktualisiert alle 10 Sekunden.
                                  
                                  //##########---WiFi Vouchers Liste und Anzahl---##########
                                  setInterval(async () => {
                                  let state = await getVouchers();
                                    setState("Unifi.01Unifi_Wifi.01Gast_Wifi.05Gast_Wifi_Voucher_Liste", clientListe.concat(clientListe+"</table>"));
                                    setState("Unifi.01Unifi_Wifi.01Gast_Wifi.04Gast_Wifi_Voucher_Anzahl");
                                    setState("Unifi.01Unifi_Wifi.01Gast_Wifi_Vouchers-CODES.CODE");
                                  }, 10000); // Aktualisiert alle 10 Sekunden.
                                  
                                  //wifi_an();
                                  //wifi_aus();
                                  getStatus();
                                  getClients();
                                  getVouchers()
                                  

                                  1 Antwort Letzte Antwort
                                  0
                                  • thewhoboxT thewhobox

                                    Und wer mutig ist und was testen möchte kann mal das Skript ausprobieren.
                                    Ist nun noch kleiner.
                                    Datenpunkte werden nun Variabel hinzugefügt.
                                    Es gibt nur noch ein Datenpunkt pro WLAN! Setzen auf false schaltet es aus, auf true schaltet es an. Außerdem wird der Datenpunkt alle 15 Sekunden mit dem aktuellen Status geupdated.

                                    const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
                                    const unifi_username = "benutzer";
                                    const unifi_password = "passwort";
                                    const unifi_controller = "https://192.168.xxx.xxx:xxxx";
                                    
                                    const dpPrefix = "javascript.0.Unifi.Unifi_Wifi.";
                                    
                                    //Hier werden alle WLANS aufgelistet.
                                    //Index und name müssen identisch sein!
                                    //Datenpunkte werden automatisch angelegt.
                                    const wifis = {
                                       "01_Haupt_Wifi": { name: "01_Haupt_Wifi", id: "xxxxxxxxxx", desc: "Unifi Haupt Wifi", smart: "01 Haut Wlan" } ,
                                       "02_Gast_Wifi": { name: "02_Gast_Wifi", id: "xxxxxxxxxx", desc: "Unifi Gast Wifi", smart: "02 Gast Wlan" }
                                    }
                                    
                                    let cookies = [];
                                    let loggedIn = false;
                                    let debug = false;
                                    
                                    let wifiDPs = [];
                                    
                                    
                                    function dlog(message) {
                                       if (debug)
                                           console.log(message);
                                    }
                                    
                                    //Erstelle Datenpunkte für die WLANs automatisch
                                    for(let wifi_name in wifis) {
                                       wifiDPs.push(dpPrefix + wifis[wifi_name].id);
                                    
                                       createState(dpPrefix + wifi_name, {
                                           name: wifis[wifi_name].desc,
                                           role: 'state',
                                           read: true,
                                           write: true,
                                           type: "boolean",
                                           smartName: {
                                               de: wifis[wifi_name].smart,
                                               smartType: "SWITCH"
                                           }
                                       });
                                    }
                                    
                                    //Erstelle Datenpunkte für die Geräteliste
                                    createState(dpPrefix + "00_Wifi_Geraeteliste", {
                                       name: 'Unifi Haupt Wifi Geräteliste',
                                       role: 'string',
                                       read: true,
                                       write: false,
                                    });
                                    createState(dpPrefix + "00_Anzahl_Geraete", {
                                       name: 'Unifi Haupt Wifi Anzahl Clients',
                                       role: 'number',
                                       min: '0',
                                       max: '1000',
                                       read: true,
                                       write: false
                                    });
                                    
                                    //Reagiert auf manuelle änderungen vom Datenpunkt
                                    //ACK muss false sein!
                                    on({ id: wifiDPs, ack: false }, (dp) => {
                                       let wlan_id = dp.id.substring(dp.id.lastIndexOf(".")+1)
                                       dlog("State Changed: " + wlan_id)
                                       setWifi(dp.state.val, wifis[wlan_id].id);
                                    });
                                    
                                    //Login für die API
                                    async function login() {
                                       return new Promise(async (resolve, reject) => {
                                           let resp = 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) => { dlog("login: reject"), reject(e) })
                                    
                                           if (resp != null) {
                                               dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies" : "Ohne Cookies"));
                                               if (resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
                                                   let set_cookies = resp.headers["set-cookie"];
                                                   for (i = 0; i < set_cookies.length; i++) {
                                                       let cookie = set_cookies[i];
                                                       cookie = cookie.split(";")[0];
                                                       cookies.push(cookie);
                                                   }
                                               } else {
                                                   dlog("login: no cookies to set!")
                                               }
                                               loggedIn = true;
                                               resolve();
                                           } else {
                                               dlog("login: rejected")
                                               reject("resp = null");
                                           }
                                       });
                                    }
                                    
                                    //Updatet status vom Wifi
                                    //wifi: wifi object aus der konstanten wifis
                                    async function getStatus(wifi) {
                                       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) });
                                    
                                           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"));
                                               setState(dpPrefix + wifi.name, state, true);
                                               resolve(wlanOn);
                                           } else {
                                               dlog("nicht ok...")
                                               reject(JSON.stringify(resp));
                                           }
                                       });
                                    }
                                    
                                    
                                    //Wifi an-/ausschalten
                                    //enabled: true = anschalten; false = ausschalten
                                    //wifi: wifi object aus der konstanten wifis
                                    async function setWifi(enabled, wifi) {
                                       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) });
                                           dlog("setWifi: got response")
                                    
                                           if (resp != null) {
                                               dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
                                               dlog(resp);
                                               setState(dpPrefix + wifi.name, enabled, true);
                                               resolve();
                                           } else {
                                               dlog("setWifi: rejetced")
                                               dlog("resp: " + JSON.stringify(resp));
                                               reject("msg: " + JSON.parse(resp.body).meta.msg);
                                           }
                                       });
                                    }
                                    
                                    //Geräteliste abrufen
                                    async function getClients() {
                                       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/stat/sta/",
                                               headers: { Cookie: cookies.join("; ") }
                                           }).catch((e) => { dlog("getStatus_haupt reject " + e); reject(e) });
                                    
                                           dlog("got response " + JSON.stringify(resp));
                                           dlog(typeof resp);
                                           dlog("--------------------- " + resp);
                                           resp = JSON.parse(resp);
                                    
                                           setState(dpPrefix + "00_Anzahl_Geraete", resp.data.length);
                                    
                                           var clientListe = "<table>";
                                           for (var i = 0; i < resp.data.length; i++) {
                                               dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
                                               clientListe = clientListe.concat("<tr><td>" + resp.data[i].hostname + "&ensp;</td><td>" + resp.data[i].essid + "&ensp;&ensp;&ensp;&ensp;</td><td>" + resp.data[i].mac + "</td></tr>");
                                               dlog(clientListe);
                                           }
                                    
                                           setState(dpPrefix + "00_Geraeteliste", clientListe.concat(clientListe + "</table>"));
                                       });
                                    }
                                    
                                    
                                    
                                    setInterval(async () => {
                                       for(let wifi_name in wifis) {
                                           await getStatus(wifis[wifi_name]);
                                       }
                                    
                                       await getClients();
                                    
                                    }, 15000); // Aktualisiert alle 10 Sekunden.
                                    
                                    
                                    // Wlan manuell abfragen:
                                    // let status = await getStatus(wifis["01_Haupt_Wlan"]);
                                    

                                    dslraserD Offline
                                    dslraserD Offline
                                    dslraser
                                    Forum Testing Most Active
                                    schrieb am zuletzt editiert von
                                    #77

                                    @thewhobox sagte in Unifi WLAN Script:

                                    Und wer mutig ist und was testen möchte kann mal das Skript ausprobieren.
                                    Ist nun noch kleiner.
                                    Datenpunkte werden nun Variabel hinzugefügt.
                                    Es gibt nur noch ein Datenpunkt pro WLAN! Setzen auf false schaltet es aus, auf true schaltet es an. Außerdem wird der Datenpunkt alle 15 Sekunden mit dem aktuellen Status geupdated.

                                    const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
                                    const unifi_username = "benutzer";
                                    const unifi_password = "passwort";
                                    const unifi_controller = "https://192.168.xxx.xxx:xxxx";
                                    
                                    const dpPrefix = "javascript.0.Unifi.Unifi_Wifi.";
                                    
                                    //Hier werden alle WLANS aufgelistet.
                                    //Index und name müssen identisch sein!
                                    //Datenpunkte werden automatisch angelegt.
                                    const wifis = {
                                       "01_Haupt_Wifi": { name: "01_Haupt_Wifi", id: "xxxxxxxxxx", desc: "Unifi Haupt Wifi", smart: "01 Haut Wlan" } ,
                                       "02_Gast_Wifi": { name: "02_Gast_Wifi", id: "xxxxxxxxxx", desc: "Unifi Gast Wifi", smart: "02 Gast Wlan" }
                                    }
                                    
                                    let cookies = [];
                                    let loggedIn = false;
                                    let debug = false;
                                    
                                    let wifiDPs = [];
                                    
                                    
                                    function dlog(message) {
                                       if (debug)
                                           console.log(message);
                                    }
                                    
                                    //Erstelle Datenpunkte für die WLANs automatisch
                                    for(let wifi_name in wifis) {
                                       wifiDPs.push(dpPrefix + wifis[wifi_name].id);
                                    
                                       createState(dpPrefix + wifi_name, {
                                           name: wifis[wifi_name].desc,
                                           role: 'state',
                                           read: true,
                                           write: true,
                                           type: "boolean",
                                           smartName: {
                                               de: wifis[wifi_name].smart,
                                               smartType: "SWITCH"
                                           }
                                       });
                                    }
                                    
                                    //Erstelle Datenpunkte für die Geräteliste
                                    createState(dpPrefix + "00_Wifi_Geraeteliste", {
                                       name: 'Unifi Haupt Wifi Geräteliste',
                                       role: 'string',
                                       read: true,
                                       write: false,
                                    });
                                    createState(dpPrefix + "00_Anzahl_Geraete", {
                                       name: 'Unifi Haupt Wifi Anzahl Clients',
                                       role: 'number',
                                       min: '0',
                                       max: '1000',
                                       read: true,
                                       write: false
                                    });
                                    
                                    //Reagiert auf manuelle änderungen vom Datenpunkt
                                    //ACK muss false sein!
                                    on({ id: wifiDPs, ack: false }, (dp) => {
                                       let wlan_id = dp.id.substring(dp.id.lastIndexOf(".")+1)
                                       dlog("State Changed: " + wlan_id)
                                       setWifi(dp.state.val, wifis[wlan_id].id);
                                    });
                                    
                                    //Login für die API
                                    async function login() {
                                       return new Promise(async (resolve, reject) => {
                                           let resp = 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) => { dlog("login: reject"), reject(e) })
                                    
                                           if (resp != null) {
                                               dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies" : "Ohne Cookies"));
                                               if (resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
                                                   let set_cookies = resp.headers["set-cookie"];
                                                   for (i = 0; i < set_cookies.length; i++) {
                                                       let cookie = set_cookies[i];
                                                       cookie = cookie.split(";")[0];
                                                       cookies.push(cookie);
                                                   }
                                               } else {
                                                   dlog("login: no cookies to set!")
                                               }
                                               loggedIn = true;
                                               resolve();
                                           } else {
                                               dlog("login: rejected")
                                               reject("resp = null");
                                           }
                                       });
                                    }
                                    
                                    //Updatet status vom Wifi
                                    //wifi: wifi object aus der konstanten wifis
                                    async function getStatus(wifi) {
                                       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) });
                                    
                                           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"));
                                               setState(dpPrefix + wifi.name, state, true);
                                               resolve(wlanOn);
                                           } else {
                                               dlog("nicht ok...")
                                               reject(JSON.stringify(resp));
                                           }
                                       });
                                    }
                                    
                                    
                                    //Wifi an-/ausschalten
                                    //enabled: true = anschalten; false = ausschalten
                                    //wifi: wifi object aus der konstanten wifis
                                    async function setWifi(enabled, wifi) {
                                       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) });
                                           dlog("setWifi: got response")
                                    
                                           if (resp != null) {
                                               dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
                                               dlog(resp);
                                               setState(dpPrefix + wifi.name, enabled, true);
                                               resolve();
                                           } else {
                                               dlog("setWifi: rejetced")
                                               dlog("resp: " + JSON.stringify(resp));
                                               reject("msg: " + JSON.parse(resp.body).meta.msg);
                                           }
                                       });
                                    }
                                    
                                    //Geräteliste abrufen
                                    async function getClients() {
                                       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/stat/sta/",
                                               headers: { Cookie: cookies.join("; ") }
                                           }).catch((e) => { dlog("getStatus_haupt reject " + e); reject(e) });
                                    
                                           dlog("got response " + JSON.stringify(resp));
                                           dlog(typeof resp);
                                           dlog("--------------------- " + resp);
                                           resp = JSON.parse(resp);
                                    
                                           setState(dpPrefix + "00_Anzahl_Geraete", resp.data.length);
                                    
                                           var clientListe = "<table>";
                                           for (var i = 0; i < resp.data.length; i++) {
                                               dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
                                               clientListe = clientListe.concat("<tr><td>" + resp.data[i].hostname + "&ensp;</td><td>" + resp.data[i].essid + "&ensp;&ensp;&ensp;&ensp;</td><td>" + resp.data[i].mac + "</td></tr>");
                                               dlog(clientListe);
                                           }
                                    
                                           setState(dpPrefix + "00_Geraeteliste", clientListe.concat(clientListe + "</table>"));
                                       });
                                    }
                                    
                                    
                                    
                                    setInterval(async () => {
                                       for(let wifi_name in wifis) {
                                           await getStatus(wifis[wifi_name]);
                                       }
                                    
                                       await getClients();
                                    
                                    }, 15000); // Aktualisiert alle 10 Sekunden.
                                    
                                    
                                    // Wlan manuell abfragen:
                                    // let status = await getStatus(wifis["01_Haupt_Wlan"]);
                                    

                                    Ah, jetzt hast Du natürlich noch eine interessante Variante:+1: :blush:

                                    1 Antwort Letzte Antwort
                                    0
                                    • thewhoboxT thewhobox

                                      Und wer mutig ist und was testen möchte kann mal das Skript ausprobieren.
                                      Ist nun noch kleiner.
                                      Datenpunkte werden nun Variabel hinzugefügt.
                                      Es gibt nur noch ein Datenpunkt pro WLAN! Setzen auf false schaltet es aus, auf true schaltet es an. Außerdem wird der Datenpunkt alle 15 Sekunden mit dem aktuellen Status geupdated.

                                      const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
                                      const unifi_username = "benutzer";
                                      const unifi_password = "passwort";
                                      const unifi_controller = "https://192.168.xxx.xxx:xxxx";
                                      
                                      const dpPrefix = "javascript.0.Unifi.Unifi_Wifi.";
                                      
                                      //Hier werden alle WLANS aufgelistet.
                                      //Index und name müssen identisch sein!
                                      //Datenpunkte werden automatisch angelegt.
                                      const wifis = {
                                         "01_Haupt_Wifi": { name: "01_Haupt_Wifi", id: "xxxxxxxxxx", desc: "Unifi Haupt Wifi", smart: "01 Haut Wlan" } ,
                                         "02_Gast_Wifi": { name: "02_Gast_Wifi", id: "xxxxxxxxxx", desc: "Unifi Gast Wifi", smart: "02 Gast Wlan" }
                                      }
                                      
                                      let cookies = [];
                                      let loggedIn = false;
                                      let debug = false;
                                      
                                      let wifiDPs = [];
                                      
                                      
                                      function dlog(message) {
                                         if (debug)
                                             console.log(message);
                                      }
                                      
                                      //Erstelle Datenpunkte für die WLANs automatisch
                                      for(let wifi_name in wifis) {
                                         wifiDPs.push(dpPrefix + wifis[wifi_name].id);
                                      
                                         createState(dpPrefix + wifi_name, {
                                             name: wifis[wifi_name].desc,
                                             role: 'state',
                                             read: true,
                                             write: true,
                                             type: "boolean",
                                             smartName: {
                                                 de: wifis[wifi_name].smart,
                                                 smartType: "SWITCH"
                                             }
                                         });
                                      }
                                      
                                      //Erstelle Datenpunkte für die Geräteliste
                                      createState(dpPrefix + "00_Wifi_Geraeteliste", {
                                         name: 'Unifi Haupt Wifi Geräteliste',
                                         role: 'string',
                                         read: true,
                                         write: false,
                                      });
                                      createState(dpPrefix + "00_Anzahl_Geraete", {
                                         name: 'Unifi Haupt Wifi Anzahl Clients',
                                         role: 'number',
                                         min: '0',
                                         max: '1000',
                                         read: true,
                                         write: false
                                      });
                                      
                                      //Reagiert auf manuelle änderungen vom Datenpunkt
                                      //ACK muss false sein!
                                      on({ id: wifiDPs, ack: false }, (dp) => {
                                         let wlan_id = dp.id.substring(dp.id.lastIndexOf(".")+1)
                                         dlog("State Changed: " + wlan_id)
                                         setWifi(dp.state.val, wifis[wlan_id].id);
                                      });
                                      
                                      //Login für die API
                                      async function login() {
                                         return new Promise(async (resolve, reject) => {
                                             let resp = 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) => { dlog("login: reject"), reject(e) })
                                      
                                             if (resp != null) {
                                                 dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies" : "Ohne Cookies"));
                                                 if (resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
                                                     let set_cookies = resp.headers["set-cookie"];
                                                     for (i = 0; i < set_cookies.length; i++) {
                                                         let cookie = set_cookies[i];
                                                         cookie = cookie.split(";")[0];
                                                         cookies.push(cookie);
                                                     }
                                                 } else {
                                                     dlog("login: no cookies to set!")
                                                 }
                                                 loggedIn = true;
                                                 resolve();
                                             } else {
                                                 dlog("login: rejected")
                                                 reject("resp = null");
                                             }
                                         });
                                      }
                                      
                                      //Updatet status vom Wifi
                                      //wifi: wifi object aus der konstanten wifis
                                      async function getStatus(wifi) {
                                         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) });
                                      
                                             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"));
                                                 setState(dpPrefix + wifi.name, state, true);
                                                 resolve(wlanOn);
                                             } else {
                                                 dlog("nicht ok...")
                                                 reject(JSON.stringify(resp));
                                             }
                                         });
                                      }
                                      
                                      
                                      //Wifi an-/ausschalten
                                      //enabled: true = anschalten; false = ausschalten
                                      //wifi: wifi object aus der konstanten wifis
                                      async function setWifi(enabled, wifi) {
                                         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) });
                                             dlog("setWifi: got response")
                                      
                                             if (resp != null) {
                                                 dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
                                                 dlog(resp);
                                                 setState(dpPrefix + wifi.name, enabled, true);
                                                 resolve();
                                             } else {
                                                 dlog("setWifi: rejetced")
                                                 dlog("resp: " + JSON.stringify(resp));
                                                 reject("msg: " + JSON.parse(resp.body).meta.msg);
                                             }
                                         });
                                      }
                                      
                                      //Geräteliste abrufen
                                      async function getClients() {
                                         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/stat/sta/",
                                                 headers: { Cookie: cookies.join("; ") }
                                             }).catch((e) => { dlog("getStatus_haupt reject " + e); reject(e) });
                                      
                                             dlog("got response " + JSON.stringify(resp));
                                             dlog(typeof resp);
                                             dlog("--------------------- " + resp);
                                             resp = JSON.parse(resp);
                                      
                                             setState(dpPrefix + "00_Anzahl_Geraete", resp.data.length);
                                      
                                             var clientListe = "<table>";
                                             for (var i = 0; i < resp.data.length; i++) {
                                                 dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
                                                 clientListe = clientListe.concat("<tr><td>" + resp.data[i].hostname + "&ensp;</td><td>" + resp.data[i].essid + "&ensp;&ensp;&ensp;&ensp;</td><td>" + resp.data[i].mac + "</td></tr>");
                                                 dlog(clientListe);
                                             }
                                      
                                             setState(dpPrefix + "00_Geraeteliste", clientListe.concat(clientListe + "</table>"));
                                         });
                                      }
                                      
                                      
                                      
                                      setInterval(async () => {
                                         for(let wifi_name in wifis) {
                                             await getStatus(wifis[wifi_name]);
                                         }
                                      
                                         await getClients();
                                      
                                      }, 15000); // Aktualisiert alle 10 Sekunden.
                                      
                                      
                                      // Wlan manuell abfragen:
                                      // let status = await getStatus(wifis["01_Haupt_Wlan"]);
                                      

                                      dslraserD Offline
                                      dslraserD Offline
                                      dslraser
                                      Forum Testing Most Active
                                      schrieb am zuletzt editiert von
                                      #78

                                      @thewhobox

                                      ich habe es mal ausprobiert. Ich habe nur die ID's eingetragen, oder muß noch mehr gemacht werden ?
                                      Datenpunkte werden angelegt, aber nicht befüllt.

                                      Bildschirmfoto 2019-08-30 um 00.29.07.png

                                      1 Antwort Letzte Antwort
                                      0
                                      • thewhoboxT thewhobox

                                        Und wer mutig ist und was testen möchte kann mal das Skript ausprobieren.
                                        Ist nun noch kleiner.
                                        Datenpunkte werden nun Variabel hinzugefügt.
                                        Es gibt nur noch ein Datenpunkt pro WLAN! Setzen auf false schaltet es aus, auf true schaltet es an. Außerdem wird der Datenpunkt alle 15 Sekunden mit dem aktuellen Status geupdated.

                                        const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
                                        const unifi_username = "benutzer";
                                        const unifi_password = "passwort";
                                        const unifi_controller = "https://192.168.xxx.xxx:xxxx";
                                        
                                        const dpPrefix = "javascript.0.Unifi.Unifi_Wifi.";
                                        
                                        //Hier werden alle WLANS aufgelistet.
                                        //Index und name müssen identisch sein!
                                        //Datenpunkte werden automatisch angelegt.
                                        const wifis = {
                                           "01_Haupt_Wifi": { name: "01_Haupt_Wifi", id: "xxxxxxxxxx", desc: "Unifi Haupt Wifi", smart: "01 Haut Wlan" } ,
                                           "02_Gast_Wifi": { name: "02_Gast_Wifi", id: "xxxxxxxxxx", desc: "Unifi Gast Wifi", smart: "02 Gast Wlan" }
                                        }
                                        
                                        let cookies = [];
                                        let loggedIn = false;
                                        let debug = false;
                                        
                                        let wifiDPs = [];
                                        
                                        
                                        function dlog(message) {
                                           if (debug)
                                               console.log(message);
                                        }
                                        
                                        //Erstelle Datenpunkte für die WLANs automatisch
                                        for(let wifi_name in wifis) {
                                           wifiDPs.push(dpPrefix + wifis[wifi_name].id);
                                        
                                           createState(dpPrefix + wifi_name, {
                                               name: wifis[wifi_name].desc,
                                               role: 'state',
                                               read: true,
                                               write: true,
                                               type: "boolean",
                                               smartName: {
                                                   de: wifis[wifi_name].smart,
                                                   smartType: "SWITCH"
                                               }
                                           });
                                        }
                                        
                                        //Erstelle Datenpunkte für die Geräteliste
                                        createState(dpPrefix + "00_Wifi_Geraeteliste", {
                                           name: 'Unifi Haupt Wifi Geräteliste',
                                           role: 'string',
                                           read: true,
                                           write: false,
                                        });
                                        createState(dpPrefix + "00_Anzahl_Geraete", {
                                           name: 'Unifi Haupt Wifi Anzahl Clients',
                                           role: 'number',
                                           min: '0',
                                           max: '1000',
                                           read: true,
                                           write: false
                                        });
                                        
                                        //Reagiert auf manuelle änderungen vom Datenpunkt
                                        //ACK muss false sein!
                                        on({ id: wifiDPs, ack: false }, (dp) => {
                                           let wlan_id = dp.id.substring(dp.id.lastIndexOf(".")+1)
                                           dlog("State Changed: " + wlan_id)
                                           setWifi(dp.state.val, wifis[wlan_id].id);
                                        });
                                        
                                        //Login für die API
                                        async function login() {
                                           return new Promise(async (resolve, reject) => {
                                               let resp = 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) => { dlog("login: reject"), reject(e) })
                                        
                                               if (resp != null) {
                                                   dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies" : "Ohne Cookies"));
                                                   if (resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
                                                       let set_cookies = resp.headers["set-cookie"];
                                                       for (i = 0; i < set_cookies.length; i++) {
                                                           let cookie = set_cookies[i];
                                                           cookie = cookie.split(";")[0];
                                                           cookies.push(cookie);
                                                       }
                                                   } else {
                                                       dlog("login: no cookies to set!")
                                                   }
                                                   loggedIn = true;
                                                   resolve();
                                               } else {
                                                   dlog("login: rejected")
                                                   reject("resp = null");
                                               }
                                           });
                                        }
                                        
                                        //Updatet status vom Wifi
                                        //wifi: wifi object aus der konstanten wifis
                                        async function getStatus(wifi) {
                                           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) });
                                        
                                               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"));
                                                   setState(dpPrefix + wifi.name, state, true);
                                                   resolve(wlanOn);
                                               } else {
                                                   dlog("nicht ok...")
                                                   reject(JSON.stringify(resp));
                                               }
                                           });
                                        }
                                        
                                        
                                        //Wifi an-/ausschalten
                                        //enabled: true = anschalten; false = ausschalten
                                        //wifi: wifi object aus der konstanten wifis
                                        async function setWifi(enabled, wifi) {
                                           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) });
                                               dlog("setWifi: got response")
                                        
                                               if (resp != null) {
                                                   dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
                                                   dlog(resp);
                                                   setState(dpPrefix + wifi.name, enabled, true);
                                                   resolve();
                                               } else {
                                                   dlog("setWifi: rejetced")
                                                   dlog("resp: " + JSON.stringify(resp));
                                                   reject("msg: " + JSON.parse(resp.body).meta.msg);
                                               }
                                           });
                                        }
                                        
                                        //Geräteliste abrufen
                                        async function getClients() {
                                           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/stat/sta/",
                                                   headers: { Cookie: cookies.join("; ") }
                                               }).catch((e) => { dlog("getStatus_haupt reject " + e); reject(e) });
                                        
                                               dlog("got response " + JSON.stringify(resp));
                                               dlog(typeof resp);
                                               dlog("--------------------- " + resp);
                                               resp = JSON.parse(resp);
                                        
                                               setState(dpPrefix + "00_Anzahl_Geraete", resp.data.length);
                                        
                                               var clientListe = "<table>";
                                               for (var i = 0; i < resp.data.length; i++) {
                                                   dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
                                                   clientListe = clientListe.concat("<tr><td>" + resp.data[i].hostname + "&ensp;</td><td>" + resp.data[i].essid + "&ensp;&ensp;&ensp;&ensp;</td><td>" + resp.data[i].mac + "</td></tr>");
                                                   dlog(clientListe);
                                               }
                                        
                                               setState(dpPrefix + "00_Geraeteliste", clientListe.concat(clientListe + "</table>"));
                                           });
                                        }
                                        
                                        
                                        
                                        setInterval(async () => {
                                           for(let wifi_name in wifis) {
                                               await getStatus(wifis[wifi_name]);
                                           }
                                        
                                           await getClients();
                                        
                                        }, 15000); // Aktualisiert alle 10 Sekunden.
                                        
                                        
                                        // Wlan manuell abfragen:
                                        // let status = await getStatus(wifis["01_Haupt_Wlan"]);
                                        

                                        dslraserD Offline
                                        dslraserD Offline
                                        dslraser
                                        Forum Testing Most Active
                                        schrieb am zuletzt editiert von dslraser
                                        #79

                                        @thewhobox

                                        wenn ich in der kurzen Variante den erstellten State einsetze (bei getClients), werden die Daten abgeholt

                                        setState("javascript.0.Unifi.Unifi_Wifi.00_Anzahl_Geraete", resp.data.length);
                                        
                                        setState("javascript.0.Unifi.Unifi_Wifi.00_Wifi_Geraeteliste", clientListe.concat(clientListe + "</table>"));
                                        

                                        Also stimmt wahrscheinlich beim zusammensetzen noch was nicht, also hier

                                        setState(dpPrefix + "00_Anzahl_Geraete", resp.data.length);
                                        

                                        und hier

                                        setState(dpPrefix + "00_Geraeteliste", clientListe.concat(clientListe + "</table>"));
                                        

                                        Bildschirmfoto 2019-08-30 um 01.05.35.png

                                        1 Antwort Letzte Antwort
                                        0
                                        • thewhoboxT thewhobox

                                          Und wer mutig ist und was testen möchte kann mal das Skript ausprobieren.
                                          Ist nun noch kleiner.
                                          Datenpunkte werden nun Variabel hinzugefügt.
                                          Es gibt nur noch ein Datenpunkt pro WLAN! Setzen auf false schaltet es aus, auf true schaltet es an. Außerdem wird der Datenpunkt alle 15 Sekunden mit dem aktuellen Status geupdated.

                                          const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
                                          const unifi_username = "benutzer";
                                          const unifi_password = "passwort";
                                          const unifi_controller = "https://192.168.xxx.xxx:xxxx";
                                          
                                          const dpPrefix = "javascript.0.Unifi.Unifi_Wifi.";
                                          
                                          //Hier werden alle WLANS aufgelistet.
                                          //Index und name müssen identisch sein!
                                          //Datenpunkte werden automatisch angelegt.
                                          const wifis = {
                                             "01_Haupt_Wifi": { name: "01_Haupt_Wifi", id: "xxxxxxxxxx", desc: "Unifi Haupt Wifi", smart: "01 Haut Wlan" } ,
                                             "02_Gast_Wifi": { name: "02_Gast_Wifi", id: "xxxxxxxxxx", desc: "Unifi Gast Wifi", smart: "02 Gast Wlan" }
                                          }
                                          
                                          let cookies = [];
                                          let loggedIn = false;
                                          let debug = false;
                                          
                                          let wifiDPs = [];
                                          
                                          
                                          function dlog(message) {
                                             if (debug)
                                                 console.log(message);
                                          }
                                          
                                          //Erstelle Datenpunkte für die WLANs automatisch
                                          for(let wifi_name in wifis) {
                                             wifiDPs.push(dpPrefix + wifis[wifi_name].id);
                                          
                                             createState(dpPrefix + wifi_name, {
                                                 name: wifis[wifi_name].desc,
                                                 role: 'state',
                                                 read: true,
                                                 write: true,
                                                 type: "boolean",
                                                 smartName: {
                                                     de: wifis[wifi_name].smart,
                                                     smartType: "SWITCH"
                                                 }
                                             });
                                          }
                                          
                                          //Erstelle Datenpunkte für die Geräteliste
                                          createState(dpPrefix + "00_Wifi_Geraeteliste", {
                                             name: 'Unifi Haupt Wifi Geräteliste',
                                             role: 'string',
                                             read: true,
                                             write: false,
                                          });
                                          createState(dpPrefix + "00_Anzahl_Geraete", {
                                             name: 'Unifi Haupt Wifi Anzahl Clients',
                                             role: 'number',
                                             min: '0',
                                             max: '1000',
                                             read: true,
                                             write: false
                                          });
                                          
                                          //Reagiert auf manuelle änderungen vom Datenpunkt
                                          //ACK muss false sein!
                                          on({ id: wifiDPs, ack: false }, (dp) => {
                                             let wlan_id = dp.id.substring(dp.id.lastIndexOf(".")+1)
                                             dlog("State Changed: " + wlan_id)
                                             setWifi(dp.state.val, wifis[wlan_id].id);
                                          });
                                          
                                          //Login für die API
                                          async function login() {
                                             return new Promise(async (resolve, reject) => {
                                                 let resp = 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) => { dlog("login: reject"), reject(e) })
                                          
                                                 if (resp != null) {
                                                     dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies" : "Ohne Cookies"));
                                                     if (resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
                                                         let set_cookies = resp.headers["set-cookie"];
                                                         for (i = 0; i < set_cookies.length; i++) {
                                                             let cookie = set_cookies[i];
                                                             cookie = cookie.split(";")[0];
                                                             cookies.push(cookie);
                                                         }
                                                     } else {
                                                         dlog("login: no cookies to set!")
                                                     }
                                                     loggedIn = true;
                                                     resolve();
                                                 } else {
                                                     dlog("login: rejected")
                                                     reject("resp = null");
                                                 }
                                             });
                                          }
                                          
                                          //Updatet status vom Wifi
                                          //wifi: wifi object aus der konstanten wifis
                                          async function getStatus(wifi) {
                                             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) });
                                          
                                                 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"));
                                                     setState(dpPrefix + wifi.name, state, true);
                                                     resolve(wlanOn);
                                                 } else {
                                                     dlog("nicht ok...")
                                                     reject(JSON.stringify(resp));
                                                 }
                                             });
                                          }
                                          
                                          
                                          //Wifi an-/ausschalten
                                          //enabled: true = anschalten; false = ausschalten
                                          //wifi: wifi object aus der konstanten wifis
                                          async function setWifi(enabled, wifi) {
                                             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) });
                                                 dlog("setWifi: got response")
                                          
                                                 if (resp != null) {
                                                     dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
                                                     dlog(resp);
                                                     setState(dpPrefix + wifi.name, enabled, true);
                                                     resolve();
                                                 } else {
                                                     dlog("setWifi: rejetced")
                                                     dlog("resp: " + JSON.stringify(resp));
                                                     reject("msg: " + JSON.parse(resp.body).meta.msg);
                                                 }
                                             });
                                          }
                                          
                                          //Geräteliste abrufen
                                          async function getClients() {
                                             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/stat/sta/",
                                                     headers: { Cookie: cookies.join("; ") }
                                                 }).catch((e) => { dlog("getStatus_haupt reject " + e); reject(e) });
                                          
                                                 dlog("got response " + JSON.stringify(resp));
                                                 dlog(typeof resp);
                                                 dlog("--------------------- " + resp);
                                                 resp = JSON.parse(resp);
                                          
                                                 setState(dpPrefix + "00_Anzahl_Geraete", resp.data.length);
                                          
                                                 var clientListe = "<table>";
                                                 for (var i = 0; i < resp.data.length; i++) {
                                                     dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
                                                     clientListe = clientListe.concat("<tr><td>" + resp.data[i].hostname + "&ensp;</td><td>" + resp.data[i].essid + "&ensp;&ensp;&ensp;&ensp;</td><td>" + resp.data[i].mac + "</td></tr>");
                                                     dlog(clientListe);
                                                 }
                                          
                                                 setState(dpPrefix + "00_Geraeteliste", clientListe.concat(clientListe + "</table>"));
                                             });
                                          }
                                          
                                          
                                          
                                          setInterval(async () => {
                                             for(let wifi_name in wifis) {
                                                 await getStatus(wifis[wifi_name]);
                                             }
                                          
                                             await getClients();
                                          
                                          }, 15000); // Aktualisiert alle 10 Sekunden.
                                          
                                          
                                          // Wlan manuell abfragen:
                                          // let status = await getStatus(wifis["01_Haupt_Wlan"]);
                                          

                                          dslraserD Offline
                                          dslraserD Offline
                                          dslraser
                                          Forum Testing Most Active
                                          schrieb am zuletzt editiert von
                                          #80

                                          @thewhobox sagte in Unifi WLAN Script:

                                          Und wer mutig ist und was testen möchte kann mal das Skript ausprobieren.
                                          Ist nun noch kleiner.
                                          Datenpunkte werden nun Variabel hinzugefügt.
                                          Es gibt nur noch ein Datenpunkt pro WLAN! Setzen auf false schaltet es aus, auf true schaltet es an. Außerdem wird der Datenpunkt alle 15 Sekunden mit dem aktuellen Status geupdated.

                                          const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
                                          const unifi_username = "benutzer";
                                          const unifi_password = "passwort";
                                          const unifi_controller = "https://192.168.xxx.xxx:xxxx";
                                          
                                          const dpPrefix = "javascript.0.Unifi.Unifi_Wifi.";
                                          
                                          //Hier werden alle WLANS aufgelistet.
                                          //Index und name müssen identisch sein!
                                          //Datenpunkte werden automatisch angelegt.
                                          const wifis = {
                                             "01_Haupt_Wifi": { name: "01_Haupt_Wifi", id: "xxxxxxxxxx", desc: "Unifi Haupt Wifi", smart: "01 Haut Wlan" } ,
                                             "02_Gast_Wifi": { name: "02_Gast_Wifi", id: "xxxxxxxxxx", desc: "Unifi Gast Wifi", smart: "02 Gast Wlan" }
                                          }
                                          
                                          let cookies = [];
                                          let loggedIn = false;
                                          let debug = false;
                                          
                                          let wifiDPs = [];
                                          
                                          
                                          function dlog(message) {
                                             if (debug)
                                                 console.log(message);
                                          }
                                          
                                          //Erstelle Datenpunkte für die WLANs automatisch
                                          for(let wifi_name in wifis) {
                                             wifiDPs.push(dpPrefix + wifis[wifi_name].id);
                                          
                                             createState(dpPrefix + wifi_name, {
                                                 name: wifis[wifi_name].desc,
                                                 role: 'state',
                                                 read: true,
                                                 write: true,
                                                 type: "boolean",
                                                 smartName: {
                                                     de: wifis[wifi_name].smart,
                                                     smartType: "SWITCH"
                                                 }
                                             });
                                          }
                                          
                                          //Erstelle Datenpunkte für die Geräteliste
                                          createState(dpPrefix + "00_Wifi_Geraeteliste", {
                                             name: 'Unifi Haupt Wifi Geräteliste',
                                             role: 'string',
                                             read: true,
                                             write: false,
                                          });
                                          createState(dpPrefix + "00_Anzahl_Geraete", {
                                             name: 'Unifi Haupt Wifi Anzahl Clients',
                                             role: 'number',
                                             min: '0',
                                             max: '1000',
                                             read: true,
                                             write: false
                                          });
                                          
                                          //Reagiert auf manuelle änderungen vom Datenpunkt
                                          //ACK muss false sein!
                                          on({ id: wifiDPs, ack: false }, (dp) => {
                                             let wlan_id = dp.id.substring(dp.id.lastIndexOf(".")+1)
                                             dlog("State Changed: " + wlan_id)
                                             setWifi(dp.state.val, wifis[wlan_id].id);
                                          });
                                          
                                          //Login für die API
                                          async function login() {
                                             return new Promise(async (resolve, reject) => {
                                                 let resp = 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) => { dlog("login: reject"), reject(e) })
                                          
                                                 if (resp != null) {
                                                     dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies" : "Ohne Cookies"));
                                                     if (resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
                                                         let set_cookies = resp.headers["set-cookie"];
                                                         for (i = 0; i < set_cookies.length; i++) {
                                                             let cookie = set_cookies[i];
                                                             cookie = cookie.split(";")[0];
                                                             cookies.push(cookie);
                                                         }
                                                     } else {
                                                         dlog("login: no cookies to set!")
                                                     }
                                                     loggedIn = true;
                                                     resolve();
                                                 } else {
                                                     dlog("login: rejected")
                                                     reject("resp = null");
                                                 }
                                             });
                                          }
                                          
                                          //Updatet status vom Wifi
                                          //wifi: wifi object aus der konstanten wifis
                                          async function getStatus(wifi) {
                                             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) });
                                          
                                                 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"));
                                                     setState(dpPrefix + wifi.name, state, true);
                                                     resolve(wlanOn);
                                                 } else {
                                                     dlog("nicht ok...")
                                                     reject(JSON.stringify(resp));
                                                 }
                                             });
                                          }
                                          
                                          
                                          //Wifi an-/ausschalten
                                          //enabled: true = anschalten; false = ausschalten
                                          //wifi: wifi object aus der konstanten wifis
                                          async function setWifi(enabled, wifi) {
                                             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) });
                                                 dlog("setWifi: got response")
                                          
                                                 if (resp != null) {
                                                     dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
                                                     dlog(resp);
                                                     setState(dpPrefix + wifi.name, enabled, true);
                                                     resolve();
                                                 } else {
                                                     dlog("setWifi: rejetced")
                                                     dlog("resp: " + JSON.stringify(resp));
                                                     reject("msg: " + JSON.parse(resp.body).meta.msg);
                                                 }
                                             });
                                          }
                                          
                                          //Geräteliste abrufen
                                          async function getClients() {
                                             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/stat/sta/",
                                                     headers: { Cookie: cookies.join("; ") }
                                                 }).catch((e) => { dlog("getStatus_haupt reject " + e); reject(e) });
                                          
                                                 dlog("got response " + JSON.stringify(resp));
                                                 dlog(typeof resp);
                                                 dlog("--------------------- " + resp);
                                                 resp = JSON.parse(resp);
                                          
                                                 setState(dpPrefix + "00_Anzahl_Geraete", resp.data.length);
                                          
                                                 var clientListe = "<table>";
                                                 for (var i = 0; i < resp.data.length; i++) {
                                                     dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
                                                     clientListe = clientListe.concat("<tr><td>" + resp.data[i].hostname + "&ensp;</td><td>" + resp.data[i].essid + "&ensp;&ensp;&ensp;&ensp;</td><td>" + resp.data[i].mac + "</td></tr>");
                                                     dlog(clientListe);
                                                 }
                                          
                                                 setState(dpPrefix + "00_Geraeteliste", clientListe.concat(clientListe + "</table>"));
                                             });
                                          }
                                          
                                          
                                          
                                          setInterval(async () => {
                                             for(let wifi_name in wifis) {
                                                 await getStatus(wifis[wifi_name]);
                                             }
                                          
                                             await getClients();
                                          
                                          }, 15000); // Aktualisiert alle 10 Sekunden.
                                          
                                          
                                          // Wlan manuell abfragen:
                                          // let status = await getStatus(wifis["01_Haupt_Wlan"]);
                                          

                                          So funktioniert bei mir das abholen der Client Liste und Anzahl mit der kurzen Variante. Wifi Status und schalten noch nicht.

                                          const request = require('request-promise-native').defaults({ rejectUnauthorized: false });
                                          const unifi_username = "xxxxx";
                                          const unifi_password = "xxxxx";
                                          const unifi_controller = "https://192.168.xxx.xxx:xxxx";
                                          const dpPrefix = "javascript.0.Unifi.Unifi_Wifi.";
                                          
                                          //Hier werden alle WLANS aufgelistet.
                                          //Index und name müssen identisch sein!
                                          //Datenpunkte werden automatisch angelegt.
                                          const wifis = {
                                             "01_Haupt_Wifi": { name: "01_Haupt_Wifi", id: "xxxxxxxx", desc: "Unifi Haupt Wifi", smart: "01 Haut Wlan" } ,
                                             "02_Gast_Wifi": { name: "02_Gast_Wifi", id: "xxxxxxxx", desc: "Unifi Gast Wifi", smart: "02 Gast Wlan" }
                                          }
                                           
                                          let cookies = [];
                                          let loggedIn = false;
                                          let debug = false;
                                           
                                          let wifiDPs = [];
                                           
                                           
                                          function dlog(message) {
                                             if (debug)
                                                 console.log(message);
                                          }
                                           
                                          //Erstelle Datenpunkte für die WLANs automatisch
                                          for(let wifi_name in wifis) {
                                             wifiDPs.push(dpPrefix + wifis[wifi_name].id);
                                           
                                             createState(dpPrefix + wifi_name, {
                                                 name: wifis[wifi_name].desc,
                                                 role: 'state',
                                                 read: true,
                                                 write: true,
                                                 type: "boolean",
                                                 smartName: {
                                                     de: wifis[wifi_name].smart,
                                                     smartType: "SWITCH"
                                                 }
                                             });
                                          }
                                           
                                          //Erstelle Datenpunkte für die Geräteliste
                                          createState(dpPrefix + "00_Wifi_Geraeteliste", {
                                             name: 'Unifi Geräteliste',
                                             role: 'string',
                                             read: true,
                                             write: false,
                                          });
                                          createState(dpPrefix + "00_Anzahl_Geraete", {
                                             name: 'Unifi Anzahl Clients',
                                             role: 'number',
                                             min: '0',
                                             max: '1000',
                                             read: true,
                                             write: false
                                          });
                                           
                                          //Reagiert auf manuelle änderungen vom Datenpunkt
                                          //ACK muss false sein!
                                          on({ id: wifiDPs, ack: false }, (dp) => {
                                             let wlan_id = dp.id.substring(dp.id.lastIndexOf(".")+1)
                                             dlog("State Changed: " + wlan_id)
                                             setWifi(dp.state.val, wifis[wlan_id].id);
                                          });
                                           
                                          //Login für die API
                                          async function login() {
                                             return new Promise(async (resolve, reject) => {
                                                 let resp = 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) => { dlog("login: reject"), reject(e) })
                                           
                                                 if (resp != null) {
                                                     dlog("login: login war erfolgreich! " + ((resp.headers && resp.headers.hasOwnProperty("set-cookie")) ? "Mit Cookies" : "Ohne Cookies"));
                                                     if (resp.headers && resp.headers.hasOwnProperty("set-cookie")) {
                                                         let set_cookies = resp.headers["set-cookie"];
                                                         for (i = 0; i < set_cookies.length; i++) {
                                                             let cookie = set_cookies[i];
                                                             cookie = cookie.split(";")[0];
                                                             cookies.push(cookie);
                                                         }
                                                     } else {
                                                         dlog("login: no cookies to set!")
                                                     }
                                                     loggedIn = true;
                                                     resolve();
                                                 } else {
                                                     dlog("login: rejected")
                                                     reject("resp = null");
                                                 }
                                             });
                                          }
                                           
                                          //Updatet status vom Wifi
                                          //wifi: wifi object aus der konstanten wifis
                                          async function getStatus(wifi) {
                                             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) });
                                           
                                                 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"));
                                                     setState(dpPrefix + wifi.name, state, true);
                                                     resolve(wlanOn);
                                                 } else {
                                                     dlog("nicht ok...")
                                                     reject(JSON.stringify(resp));
                                                 }
                                             });
                                          }
                                           
                                           
                                          //Wifi an-/ausschalten
                                          //enabled: true = anschalten; false = ausschalten
                                          //wifi: wifi object aus der konstanten wifis
                                          async function setWifi(enabled, wifi) {
                                             return new Promise(async (resolve, reject) => {
                                                 dlog("setWifi: start set Wifi");
                                                 if (!loggedIn) { dlog("need to login"); await login().catch((e) => reject(e)); }
                                                 dlog("setWifi: now setting Wifi");
                                                 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) });
                                                 dlog("setWifi: got response")
                                           
                                                 if (resp != null) {
                                                     dlog("setWifi: Wifi wurde erfolgreich " + (enabled ? "eingeschaltet" : "ausgeschaltet"));
                                                     dlog(resp);
                                                     setState(dpPrefix + wifi.name, enabled, true);
                                                     resolve();
                                                 } else {
                                                     dlog("setWifi: rejetced")
                                                     dlog("resp: " + JSON.stringify(resp));
                                                     reject("msg: " + JSON.parse(resp.body).meta.msg);
                                                 }
                                             });
                                          }
                                           
                                          //Geräteliste abrufen
                                          async function getClients() {
                                             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/stat/sta/",
                                                     headers: { Cookie: cookies.join("; ") }
                                                 }).catch((e) => { dlog("getStatus_reject " + e); reject(e) });
                                           
                                                 dlog("got response " + JSON.stringify(resp));
                                                 dlog(typeof resp);
                                                 dlog("--------------------- " + resp);
                                                 resp = JSON.parse(resp);
                                           
                                                 setState(dpPrefix + '00_Anzahl_Geraete', resp.data.length);
                                           
                                                 var clientListe = "<table>";
                                                 for (var i = 0; i < resp.data.length; i++) {
                                                     dlog(resp.data[i].hostname + " --- " + resp.data[i].essid + " --- " + resp.data[i].mac);
                                                     clientListe = clientListe.concat("<tr><td>" + resp.data[i].hostname + "&ensp;</td><td>" + resp.data[i].essid + "&ensp;&ensp;&ensp;&ensp;</td><td>" + resp.data[i].mac + "</td></tr>");
                                                     dlog(clientListe);
                                                 }
                                           
                                                 setState(dpPrefix + '00_Wifi_Geraeteliste', clientListe.concat(clientListe + "</table>"));
                                             });
                                          }
                                           
                                           
                                           
                                          /*setInterval(async () => {
                                             for(let wifi_name in wifis) {
                                               await getStatus(wifis[wifi_name]);
                                             }
                                           
                                             await getClients();
                                           
                                          }, 10000); // Aktualisiert alle 10 Sekunden.*/
                                          
                                          
                                          //##########---WiFi Clients Liste und Anzahl---##########
                                          setInterval(async () => {
                                          let state = await getClients();
                                            setState(dpPrefix + '00_Wifi_Geraeteliste', clientListe.concat(clientListe + "</table>"));
                                            setState(dpPrefix + '00_Anzahl_Geraete', resp.data.length);
                                          }, 10000); // Aktualisiert alle 10 Sekunden.
                                           
                                          getClients()
                                          // Wlan manuell abfragen:
                                          // let status = await getStatus(wifis["01_Haupt_Wifi"]);
                                          // let status = await getStatus(wifis["02_Gast_Wifi"]);
                                          

                                          1 Antwort Letzte Antwort
                                          0
                                          Antworten
                                          • In einem neuen Thema antworten
                                          Anmelden zum Antworten
                                          • Älteste zuerst
                                          • Neuste zuerst
                                          • Meiste Stimmen


                                          Support us

                                          ioBroker
                                          Community Adapters
                                          Donate

                                          654

                                          Online

                                          32.4k

                                          Benutzer

                                          81.4k

                                          Themen

                                          1.3m

                                          Beiträge
                                          Community
                                          Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen | Einwilligungseinstellungen
                                          ioBroker Community 2014-2025
                                          logo
                                          • Anmelden

                                          • Du hast noch kein Konto? Registrieren

                                          • Anmelden oder registrieren, um zu suchen
                                          • Erster Beitrag
                                            Letzter Beitrag
                                          0
                                          • Home
                                          • Aktuell
                                          • Tags
                                          • Ungelesen 0
                                          • Kategorien
                                          • Unreplied
                                          • Beliebt
                                          • GitHub
                                          • Docu
                                          • Hilfe