Navigation

    Logo
    • Register
    • Login
    • Search
    • Recent
    • Tags
    • Unread
    • Categories
    • Unreplied
    • Popular
    • GitHub
    • Docu
    • Hilfe
    1. Home
    2. Deutsch
    3. Skripten / Logik
    4. JavaScript
    5. Kann da mal jemand drüberschauen (API-Calls/await und Co.)?

    NEWS

    • Neuer Blog: Fotos und Eindrücke aus Solingen

    • ioBroker@Smart Living Forum Solingen, 14.06. - Agenda added

    • ioBroker goes Matter ... Matter Adapter in Stable

    Kann da mal jemand drüberschauen (API-Calls/await und Co.)?

    This topic has been deleted. Only users with topic management privileges can see it.
    • S
      SvenVJ last edited by

      Hallo liebe Member,
      ich weiss nicht, ob ich das "einfach" so posten darf - als nagelt mich nicht gleich ans Kreuz weil es zu laienhaft ist.
      Seit neuestem hab ich das Lock von Switchbot und wollte das in meine Anwesenheitserkennung einbauen (wenn niemand da, absperren). Hab ich nach langem lesen, googeln und ausprobieren dann auch geschafft. Ich hänge es mal an.
      Was ich damit "erreicht" habe: ich hole mir den Status(locked/unlocked) über die Switchbot API und falls "unlocked" setze ich den auf locked.
      Aber meine (Verständnis-)Fragen dazu:

      • kann man das irgendwie schöner/runder/effizienter machen? Irgendwie bin ich nicht so recht happy damit. Ich hab mir da einen abgewürgt(zusammenkopiert) mit dieser async/promise/await Geschichte damit das funktioniert hat. Kenn ich so aus anderen Programmiersprachen halt nicht dass er da immer direkt weiterläuft ohne auf die Antwort zu warten
      • Ich hab das jetzt in diese Main-Function gepackt, ist das so ok? An sich wollte ich anfangs mal eine Function haben nur um die Stati zu holen und weitere Functions für evtl. andere Dinge (Aktionen).
      //x
      const token = "xxx";
      const secret = "xx";
      const t = Date.now();
      const nonce = "requestID";
      const data = token + t + nonce;
      const https = require("https");
      const signTerm = require('crypto').createHmac('sha256', secret).update(Buffer.from(data, 'utf-8')).digest();
      const sign = signTerm.toString("base64");
      
      var deviceId = "xx";
      
      async function apiget(device)
      {
          return new Promise(async (resolve, reject) => {
      
              const options = {
                  hostname: 'api.switch-bot.com',
                  port: 443,
                  path: `/v1.1/devices/${device}/status`,
                  //path: `/v1.1/devices/${deviceId}/commands`,
                  //path: `/v1.1/devices`,
                  method: 'GET',
                  headers: {
                      "Authorization": token,
                      "sign": sign,
                      "nonce": nonce,
                      "t": t,
                  },
              };
          
              let body = [];
          
              const req = https.request(options, res => {
                res.on('data', chunk => body.push(chunk));
                res.on('end', () => {
                  const data = Buffer.concat(body).toString();
                  resolve(data);
                });
              });
              req.on('error', e => {
                // console.log(`ERROR httpsGet: ${e}`);
                reject(e);
              });
              req.end();
          
            });
          
      };
      
      async function apiset(device)
      {
          return new Promise(async (resolve, reject) => {
              console.log(device)
              const bodylock = JSON.stringify({
                  "command": "lock",
                  "parameter": "default",
                  "commandType": "command"
              });
              const options = {
                  hostname: 'api.switch-bot.com',
                  port: 443,
                  //path: `/v1.1/devices/${device}/status`,
                  path: `/v1.1/devices/${device}/commands`,
                  //path: `/v1.1/devices`,
                  method: 'POST',
                  headers: {
                      "Authorization": token,
                      "sign": sign,
                      "nonce": nonce,
                      "t": t,
                      'Content-Type': 'application/json',
                      'Content-Length': bodylock.length,
                  },
              };
              let body = [];
          
              const req = https.request(options, res => {
                res.on('data', chunk => body.push(chunk));
                res.on('end', () => {
                  const data = Buffer.concat(body).toString();
                  resolve(data);
                });
              });
              req.on('error', e => {
                console.log(`ERROR httpsGet: ${e}`);
                reject(e);
              });
              req.write(bodylock);
              req.end();
          
            });
          
      };
      
       async function main() {
          apiget(deviceId).then((data)=>{
          var result = JSON.parse(data);
          var lockState = result.body.lockState;
          console.log(lockState); 
          if (lockState == "unlocked")
          {
              console.log("zusperren");
              apiset(deviceId);
          }
          });
        };
        
      main();
      
      
      
      

      Danke schön!!

      arteck 1 Reply Last reply Reply Quote 0
      • arteck
        arteck Developer Most Active @SvenVJ last edited by

        @svenvj sagte in Kann da mal jemand drüberschauen (API-Calls/await und Co.)?:

        request

        schau dir axios an.. anstatt request

        1 Reply Last reply Reply Quote 0
        • First post
          Last post

        Support us

        ioBroker
        Community Adapters
        Donate

        819
        Online

        31.8k
        Users

        80.0k
        Topics

        1.3m
        Posts

        2
        2
        198
        Loading More Posts
        • Oldest to Newest
        • Newest to Oldest
        • Most Votes
        Reply
        • Reply as topic
        Log in to reply
        Community
        Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen
        The ioBroker Community 2014-2023
        logo