Navigation

    Logo
    • Register
    • Login
    • Search
    • Recent
    • Tags
    • Unread
    • Categories
    • Unreplied
    • Popular
    • GitHub
    • Docu
    • Hilfe
    1. Home
    2. Deutsch
    3. Skripten / Logik
    4. Regex liefert falschen Wert

    NEWS

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

    • ioBroker goes Matter ... Matter Adapter in Stable

    • Monatsrückblick - April 2025

    Regex liefert falschen Wert

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

      Hallo zusammen,

      ich habe ein paar (Anfänger)-Schwierigkeiten mit einer Regex und könnte etwas Hilfe gebrauchen.

      Folgendes ist das Ergebnis:

      javascript.0	22:24:00.130	info	script.js.common.Balkonkraftwerk_Shelly_Cloud_API: Found match, group 0: "total_power":-43.36,
      javascript.0	22:24:00.130	info	script.js.common.Balkonkraftwerk_Shelly_Cloud_API: Found match, group 1: -43.36
      javascript.0	22:24:00.130	info	script.js.common.Balkonkraftwerk_Shelly_Cloud_API: Found match, group 2: .36
      javascript.0	22:24:00.130	info	script.js.common.Balkonkraftwerk_Shelly_Cloud_API: {"isok":true,"data":{"online":true,"device_status":{"has_update":false,"fs_free":155118,"unixtime":1725530007,"emeter_n":{"current":0,"ixsum":0.9,"mismatch":false,"is_valid":false},"wifi_sta":{"connected":true,"ssid":"....","ip":"192.168.178.52","rssi":-72},"total_power":-43.36,"ct_calst":0,"relays":[{"ison":true,"has_timer":false,"timer_started":0,"timer_duration":0,"timer_remaining":0,"overpower":false,"is_valid":true,"source":"cloud"}],"v_data":1,"uptime":885115,"fs_size":233681,"_updated":"2024-09-05 20:16:00","cloud":{"enabled":true,"connected":true},"fs_mounted":true,"ram_free":32500,"actions_stats":{"skipped":0},"emeters":[{"power":-9.73,"pf":-0.1,"current":0.44,"voltage":233.55,"is_valid":true,"total":0,"total_returned":7844.1},{"power":-33.63,"pf":-0.62,"current":0.23,"voltage":235.21,"is_valid":true,"total":2419,"total_returned":28747.5},{"power":0,"pf":0,"current":0.44,"voltage":234.18,"is_valid":true,"total":10489.3,"total_returned":0.1}],"mac":"483FDAC3902E","mqtt":{"connected":false},"cfg_changed_cnt":0,"serial":62007,"getinfo":{"fw_info":{"device":"shellyem3-483FDAC3902E","fw":"20230913-114244/v1.14.0-gcb84623"}},"time":"22:16","update":{"status":"idle","has_update":false,"new_version":"20230913-114244/v1.14.0-gcb84623","old_version":"20230913-114244/v1.14.0-gcb84623","beta_version":"20231107-165007/v1.14.1-rc1-g0617c15"},"ram_total":49920}}} - % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0 100 1500 100 1383 100 117 15896 1344 --:--:-- --:--:-- --:--:-- 17441
      javascript.0	22:24:00.130	info	script.js.common.Balkonkraftwerk_Shelly_Cloud_API: Leistung: 3
      

      So habe ich mir das Ganze zusammengebastelt:

      schedule("*/1 * * * *", function () {
      
          exec('curl -X POST https://shelly-89-eu.shelly.cloud/device/status -d "id=483fdac3902e&auth_key=MjBjN2JjdWlkB12AE36D401E9C6EC6573933F664EA9B25923B90241D5720122CC428B8........."',
      
      		function (error, stdout, stderr) {
      
                  const regex = /"total_power":(-?\d+(\.\d+)?),/gm;
      
                  const str = stdout;
      
                  let m;
      
                  while ((m = regex.exec(str)) !== null) {
      
                      // This is necessary to avoid infinite loops with zero-width matches
      
                      if (m.index === regex.lastIndex) {
      
                          regex.lastIndex++;
      
                      }
      
                      // The result can be accessed through the `m`-variable.
      
                      m.forEach((match, groupIndex) => {
      
                          console.log(`Found match, group ${groupIndex}: ${match}`);
                              if (groupIndex=1) {
      
                  P = match[1] // im match stehen die aktuelle parser ergebnisse ich brauch aber nur das der gruppe 1
      
                  }               
      
                      });
      
                      
      
                  }
      
                  log(stdout + " - " + stderr);
                  console.log('Leistung: ' + P);
              });
      
      });
      
      

      Die regex scheint wie man sieht zu funktionieren nur wird nicht das richtige verwendet.
      Ich hätte gerne group 1 als "Ergebnis". Wie bekomme ich das hin?

      Homoran M haus-automatisierung 3 Replies Last reply Reply Quote 0
      • Homoran
        Homoran Global Moderator Administrators @ck_coke last edited by

        @ck_coke sagte in Regex liefert falschen Wert:

        Ich hätte gerne group 1 als "Ergebnis".

        ist das nicht [0]?

        kenne nich mit regex in js nicht aus

        1 Reply Last reply Reply Quote 0
        • M
          MCU @ck_coke last edited by

          @ck_coke

          const regex = /"total_power":(-?\d+(\.\d+)?)/gm;     /* , entfernt */
          ....
          let m;
          m = regex.exec(str)  /* m ist ja "total_power":-43.36 */
          P = m.split(':')[1]
          ....
          
          C 1 Reply Last reply Reply Quote 0
          • C
            ck_coke @MCU last edited by ck_coke

            @mcu

            Error in callback: TypeError: m.split is not a function
            
            M F 2 Replies Last reply Reply Quote 0
            • M
              MCU @ck_coke last edited by

              @ck_coke Dann muss man vorher noch aus m einen String machen.

              m = String(m)
              P= m.split ......
              
              1 Reply Last reply Reply Quote 0
              • F
                fastfoot @ck_coke last edited by

                @ck_coke

                let m;
                if ((m = regex.exec(str)) != null)
                    log('Leistung: ' + m[1])
                
                1 Reply Last reply Reply Quote 0
                • haus-automatisierung
                  haus-automatisierung Developer Most Active @ck_coke last edited by

                  @ck_coke sagte in Regex liefert falschen Wert:

                  ich habe ein paar (Anfänger)-Schwierigkeiten mit einer Regex

                  Warum überhaupt JSON-Strings mit einem regex auseinander nehmen?!

                  haus-automatisierung 1 Reply Last reply Reply Quote 0
                  • haus-automatisierung
                    haus-automatisierung Developer Most Active @haus-automatisierung last edited by haus-automatisierung

                    Hier mal ein Beispiel-Script. Ohne exec, curl und regex 🙂

                    const server = 'https://shelly-67-eu.shelly.cloud';
                    const authKey = 'MTk3YjZhdWlkE6CD....';
                    const deviceId = 'b0b21c18d700';
                    
                    httpPost(`${server}/device/status`,
                        {
                            id: deviceId,
                            auth_key: authKey,
                        },
                        (error, response) => {
                            if (!error) {
                                try {
                                    const obj = JSON.parse(response.data);
                    
                                    // Daten extrahieren
                    
                                } catch (e) {
                                    console.error(e);
                                }
                            } else {
                                console.error(error);
                            }
                        }
                    );
                    
                    

                    Du suchst ja scheinbar: obj.data.device_status.total_power.

                    C 1 Reply Last reply Reply Quote 2
                    • C
                      ck_coke @haus-automatisierung last edited by

                      @haus-automatisierung

                      Vielen Dank! So ist es natürlich noch besser gelöst.

                      C 1 Reply Last reply Reply Quote 0
                      • C
                        ck_coke @ck_coke last edited by ck_coke

                        Jetzt habe ich das Problem, dass es bei einem Gerät funktioniert und bei einem anderen

                        {"ack":true}
                        

                        als Wert gesetzt wird.

                        So sieht das Skript aus:

                        schedule("*/10 * * * * *", function () {
                        
                        
                        const server = 'https://shelly-89-eu.shelly.cloud';
                        const authKey = 'XjBjN2JjdWlkB12AE36D401E9C6EC6573933F664EA9B25923B90241D5720122CC428B82EF7477624E84B517133E2';
                        const deviceId = 'a0a3b3e7d67c';
                         
                        httpPost(`${server}/device/status`,
                            {
                                id: deviceId,
                                auth_key: authKey,
                            },
                            (error, response) => {
                                if (!error) {
                                    try {
                                        const obj = JSON.parse(response.data);
                         
                                        // Daten extrahieren
                        
                                        console.log(obj.data);
                                        
                                                   setState('0_userdata.0.Leistung-Entladen', obj.data.device_status.voltage, true);
                        
                        
                         
                                    } catch (e) {
                                        console.error(e);
                                    }
                                } else {
                                    console.error(error);
                                }
                            }
                        );
                         
                        });
                        
                        
                        
                        

                        Folgendes bekomme ich im Log angezeigt:

                        javascript.0
                        	2024-09-09 20:34:40.074	info	script.js.common.Balkonkraftwerk.Skript_1: setForeignState(id=0_userdata.0.Leistung-Entladen, state={"val":{"ack":true},"ack":true,"ts":1725906880074,"q":0,"from":"system.adapter.javascript.0","lc":1725906880074,"c":"script.js.common.Balkonkraftwerk.Skript_1"})
                        javascript.0
                        	2024-09-09 20:34:40.074	info	script.js.common.Balkonkraftwerk.Skript_1: { online: true, device_status: { sys: { available_updates: [Object], mac: 'A0A3B3E7D67C', restart_required: false, time: '11:48', unixtime: 1725788939, uptime: 3, ram_size: 246876, ram_free: 134944, fs_size: 458752, fs_free: 122880, cfg_rev: 19, kvs_rev: 0, schedule_rev: 10, webhook_rev: 0, reset_reason: 1 }, ts: 1725906873.77, plugs_ui: {}, id: 'a0a3b3e7d67c', code: 'SNPL-00112EU', ws: { connected: false }, wifi: { sta_ip: '192.168.33.67', status: 'got ip', ssid: 'ShellyPlusPlugS-E465B8B3A57C', rssi: -29, ap_client_count: 0 }, mqtt: { connected: false }, serial: 3566, ffs: { ts: 0 }, 'switch:0': { id: 0, current: 0.021, source: 'SHC', output: true, apower: 0, voltage: 232.9, aenergy: [Object], temperature: [Object] }, cloud: { connected: true }, _updated: '2024-09-09 18:34:34', ble: {} } }
                        javascript.0
                        	2024-09-09 20:34:40.074	info	script.js.common.Balkonkraftwerk.Skript_1: httpPost(url=https://shelly-89-eu.shelly.cloud/device/status, responseTime=66ms)
                        javascript.0
                        	2024-09-09 20:34:40.007	info	script.js.common.Balkonkraftwerk.Skript_1: httpPost(config={"method":"post","url":"https://shelly-89-eu.shelly.cloud/device/status","responseType":"text","responseEncoding":"utf8","timeout":2000,"headers":{"User-Agent":"Mozilla/5.0 (X11; Linux i686; rv:109.0) Gecko/20100101 Firefox/121.0"},"data":{"id":"a0a3b3e7d67c","auth_key":"XjBjN2JjdWlkB12AE36D401E9C6EC6573933F664EA9B25923B90241D5720122CC428B82EF7477624E84B517133E2"}}, data=[object Object])
                        ```z
                        haus-automatisierung 1 Reply Last reply Reply Quote 0
                        • haus-automatisierung
                          haus-automatisierung Developer Most Active @ck_coke last edited by

                          @ck_coke In deinem Scripts sind Klammerfehler. Das kann so gar nicht klappen. Da fehlt etwas.

                          voltage, true);

                          1 Reply Last reply Reply Quote 0
                          • C
                            ck_coke last edited by

                            @haus-automatisierung

                            Das ist wohl beim hier ins Forum kopieren passiert.

                            Die Zeile sieht so aus:

                                                       setState('0_userdata.0.Leistung-Entladen', obj.data.device_status.voltage, true);
                            
                            
                            1 Reply Last reply Reply Quote 0
                            • C
                              ck_coke last edited by

                              Kann es daran liegen das der Datenpunkt hinter switch:0, also eine Ebene tiefer liegt?

                              Zumindest habe ich das nach Internetrechersche in anderen Foren so gesehen.

                              haus-automatisierung 1 Reply Last reply Reply Quote 0
                              • haus-automatisierung
                                haus-automatisierung Developer Most Active @ck_coke last edited by haus-automatisierung

                                @ck_coke sagte in Regex liefert falschen Wert:

                                Zumindest habe ich das nach Internetrechersche in anderen Foren so gesehen.

                                Ich hab das Thema JSON vs. Objekt in zig kostenlosen Inhalten super ausführlich erklärt.

                                Du musst schon den kompletten Pfad angeben. Im Falle von switch:0 muss das dann aber in eckige Klammern und kann nicht mit der einfachen Punkt-Notation erreicht werden.

                                obj.data.device_status['switch:0'].voltage

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

                                Support us

                                ioBroker
                                Community Adapters
                                Donate

                                608
                                Online

                                31.7k
                                Users

                                79.7k
                                Topics

                                1.3m
                                Posts

                                5
                                14
                                490
                                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