Skip to content
  • Home
  • Recent
  • Tags
  • 0 Unread 0
  • Categories
  • Unreplied
  • Popular
  • 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

  • Default (No Skin)
  • No Skin
Collapse
ioBroker Logo

Community Forum

donate donate
  1. ioBroker Community Home
  2. Deutsch
  3. Skripten / Logik
  4. JavaScript
  5. Kann da mal jemand drüberschauen (API-Calls/await und Co.)?

NEWS

  • Monatsrückblick Januar/Februar 2026 ist online!
    BluefoxB
    Bluefox
    18
    1
    702

  • Jahresrückblick 2025 – unser neuer Blogbeitrag ist online! ✨
    BluefoxB
    Bluefox
    18
    1
    5.8k

  • Neuer Blogbeitrag: Monatsrückblick - Dezember 2025 🎄
    BluefoxB
    Bluefox
    13
    1
    1.5k

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

Scheduled Pinned Locked Moved JavaScript
2 Posts 2 Posters 291 Views 2 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • S Offline
    S Offline
    SvenVJ
    wrote on last edited by
    #1

    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!!

    arteckA 1 Reply Last reply
    0
    • S SvenVJ

      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!!

      arteckA Offline
      arteckA Offline
      arteck
      Developer Most Active
      wrote on last edited by
      #2

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

      request

      schau dir axios an.. anstatt request

      zigbee hab ich, zwave auch, nuc's genauso und HA auch

      1 Reply Last reply
      0

      Hello! It looks like you're interested in this conversation, but you don't have an account yet.

      Getting fed up of having to scroll through the same posts each visit? When you register for an account, you'll always come back to exactly where you were before, and choose to be notified of new replies (either via email, or push notification). You'll also be able to save bookmarks and upvote posts to show your appreciation to other community members.

      With your input, this post could be even better 💗

      Register Login
      Reply
      • Reply as topic
      Log in to reply
      • Oldest to Newest
      • Newest to Oldest
      • Most Votes


      Support us

      ioBroker
      Community Adapters
      Donate

      623

      Online

      32.7k

      Users

      82.6k

      Topics

      1.3m

      Posts
      Community
      Impressum | Datenschutz-Bestimmungen | Nutzungsbedingungen | Einwilligungseinstellungen
      ioBroker Community 2014-2025
      logo
      • Login

      • Don't have an account? Register

      • Login or register to search.
      • First post
        Last post
      0
      • Home
      • Recent
      • Tags
      • Unread 0
      • Categories
      • Unreplied
      • Popular
      • GitHub
      • Docu
      • Hilfe