Ankündigung

Einklappen
Keine Ankündigung bisher.

Plotly_graph mit State-Attributen befüllen

Einklappen
X
 
  • Filter
  • Zeit
  • Anzeigen
Alles löschen
neue Beiträge

    Plotly_graph mit State-Attributen befüllen

    Tom Bombadil

    Ich habe dann mal einen neuen Thread aufgemacht.

    tatsächlich ist es gar nicht so kompliziert, die Werte in State_Attribute zu schreiben.

    HTML-Code:
    mqtt:
    sensor:
    - name: "vitocal_energy_dhw_monthly"
        state_topic: "open3e/0x680_680_1311_EnergyConsumptionDomesticHotWaterMonthMatrix"
        unit_of_measurement: "kWh"
        value_template: "{{ value_json.CurrentMonth.values() | sum }}"
        state_class: total_increasing
        json_attributes_topic: "open3e/0x680_680_1311_EnergyConsumptionDomesticHotWaterMonthMatrix"
        json_attributes_template: '{{ value }}'
        unique_id: vitocal_energy_dhw_monthly
        device:
          identifiers: ["vitocal_200s"]
          name: "Vitocal 200S"
          manufacturer: "Viessmann"
          model: "Vitocal 200S"​

    Ergebnis:
    grafik.png
    soweit so gut...

    dann habe ich es so versucht.
    Code:
    const the_entity = state['sensor.vitocal_200s_energyconsumptiondomestichotwatermonthmatrix'].state_attr
    das ist aber nicht das korrekte Mittel der Wahl...


    grafik.png

    #2
    Das sieht so aus, als wenn die gewünschten Daten nicht in 'State' stehen, sondern in den Zusatzattributen 'CurrentMonth' und 'LastMonth'. Deshalb klappt's auch, weil eben nicht das auf 255 Zeichen begrenzte Attribut 'State' verwendet wird (da steht ganz offensichtlich '31.6' drin).

    Das macht es einfacher (musst nicht mehr selbst auslesen) und gleichzeitig komplizierter (musst im JavaScript zwei separate Inhalte zu einer Variablen kombinieren).

    Der Zugriff erfolgt dann ungefähr so (kann es grad nicht testen):
    Code:
    const _current = states['sensor.vitocal_200s_energyconsumptiondomestichotwatermonthmatrix'].attributes.CurrentMonth;
    console.log("Current Month: ", _current);
    
    const _last = states['sensor.vitocal_200s_energyconsumptiondomestichotwatermonthmatrix'].attributes.LastMonth;
    console.log("Last Month: ", _last);
    
    const _combined = { CurrentMonth: _current, LastMonth: _last };
    console.log("Combined: ", _combined);
    
    const theJSON = JSON.stringify(_combined);
    console.log("JSON:", theJSON);
    Die Log-Ausgaben findest Du in der Developer-Konsole (meist F12). Kann wie geschrieben grad nicht testen, aber ungefähr so müsste es passen.

    Viel Erfolg!

    /tom

    Kommentar


      #3
      hm... irgendwie gibt es einen Fehler, der State wird nicht erkannt.

      Error: at [entities.0.fn]: states is not defined
      Error: at [entities.0.fn]: state

      Kommentar


        #4
        Uff, mein Fehler - das Obige würde z.B. bei der custom:button-card funtionieren; bei Plotly jedoch nicht, weil dort das JavaScript 'sandboxed' ist und somit keinen Zugriff auf das globale states-Objekt von Home Assistant​ hat. Das ist einer der Gründe, warum bei mir fast alles auf einer unsichtbaren Hintergrundkarte vom Typ custom:button-card liegt, das macht vieles einfacher.

        In plotly muss man die Dinge explizit in die Sandbox reinreichen. Das geschieht über 'vars:'.

        Schritt 1: Die 'vars' definieren:
        Code:
        type: custom:plotly-graph
        [...]
        entities:
          - name: AT
            entity: ""
            [...]
        vars:
          _current: $fn ({ states }) => states['sensor.vitocal_200s_energyconsumptiondomestichotwatermonthmatrix'].attributes.CurrentMonth
          _last: $fn ({ states }) => states['sensor.vitocal_200s_energyconsumptiondomestichotwatermonthmatrix'].attributes.LastMonth

        Schritt 2: Auf die 'vars' im JavaScript zugreifen:
        Code:
        fn: |
          $fn ({ vars, state }) => {
        
            const _current = vars._current;
            console.log("Current Month: ", _current);
        
            const _last = vars._last;
            console.log("Last Month: ", _last);
        
            const _combined = { CurrentMonth: _current, LastMonth: _last };
            console.log("Combined: ", _combined);
        
            const theJSON = JSON.stringify(_combined);
            console.log("JSON:", theJSON);
        
            [...]
        
          }
        Ich hab für die Nachvollziehbarkeit bewusst wieder eine etwas längere Schreibweise benutzt; das alles ließe sich natürlich auch viel kompakter schreiben. Alles wieder ungetestet, hab von unterwegs keinen Zugriff auf mein Testsystem. Viel Erfolg!

        /tom

        Kommentar


          #5
          hat leider auch noch nicht der erwünschten Effekt erzielt.

          HTML-Code:
          entities:
            - name: AT
              entity: ""
              fillcolor: rgba(168, 216, 234, 0.1)
              fill: tozeroy
              type: bar
              vars:
                _current: >-
                  $fn ({ states }) =>
                  states['sensor.vitocal_200s_energyconsumptiondomestichotwatermonthmatrix'].attributes.CurrentMonth
                _last: >-
                  $fn ({ states }) =>
                  states['sensor.vitocal_200s_energyconsumptiondomestichotwatermonthmatrix'].attributes.LastMonth
              fn: |
                $fn ({ vars, state }) => {
          
                  // hier später statt der untenstehenden festen Definition aus der Entität lesen:
          
                  const _current = vars._current;
                  console.log("Current Month: ", _current);
          
                  const _last = vars._last;
                  console.log("Last Month: ", _last);
          
                  const _combined = { CurrentMonth: _current, LastMonth: _last };
                  console.log("Combined: ", _combined);
          
                  const theJSON = JSON.stringify(_combined);
                  console.log("JSON:", theJSON);​
          Es kommt der Fehler im Log:

          PHP-Code:
          Current Month:  undefined
          VM997
          :9 Last Month:  undefined
          VM997
          :12 Combined:  {CurrentMonthundefinedLastMonthundefined}
          VM997:15 JSON: {}​ 

          Kommentar


            #6
            Hmmm, kann leider grad nicht rumprobieren - gib ihm mal probeweise das hass Objekt rüber:

            Code:
            vars:
              _current: |-
                $fn ({hass}) =>
                  hass.states['sensor.vitocal_200s_energyconsumptiondomestichotwatermonthmatrix'].attributes.CurrentMonth;
              _last: |-
                $fn ({hass}) =>
                  hass.states['sensor.vitocal_200s_energyconsumptiondomestichotwatermonthmatrix'].attributes.LastMonth;
            Viele Beispiele für ähnliche Szenarien findest Du im Repo mit dem Suchfilter "$fn ({hass}) =>": Klick.

            /tom

            Kommentar


              #7
              gibt keine Änderung an der Fehlermeldung in der Console

              Kommentar


                #8
                Hmpf, plotly ist mal wieder zickig und 'speziell' heute. Normalerweise würde ich jetzt einfach eine custom:button-card hinter den Plotly Graph legen und an derselben Stelle mit `[[[ JavaScript ]]]` statt mit `fn:` arbeiten; da funktionieren die Aktualisierungen auch besser/sicherer, und man hat Vollzugriff auf sämtliche Entitäten und ihre Attribute.

                Egal, lass uns noch eine andere Version versuchen (Holzhammermethode - die beiden Attribute innerhalb von Plotly als Entitäten bereitstellen, aber nicht zeichnen lassen - dabei kann man ihnen id's verpassen, mit denen man auch arbeiten kann):

                Code:
                type: custom:plotly-graph
                
                [...]
                
                entities:
                
                  - entity: sensor.vitocal_200s_energyconsumptiondomestichotwatermonthmatrix
                    attribute: CurrentMonth
                    name: current
                    id: current
                
                  - entity: sensor.vitocal_200s_energyconsumptiondomestichotwatermonthmatrix
                    attribute: LastMonth
                    name: last
                    id: last
                
                  - name: AT     // hier der alte code, nur leicht andere Zuweisung
                    type: bar
                    entity: ''
                    fn: |
                      $fn ({ vars }) => {
                
                        const _current = vars.current;
                        console.log("Current Month: ", _current);
                
                        const _last = vars.last;
                        console.log("Last Month: ", _last);
                
                        const _combined = { CurrentMonth: _current, LastMonth: _last };
                        console.log("Combined: ", _combined);
                
                        const theJSON = JSON.stringify(_combined);
                        console.log("JSON:", theJSON);​
                
                        [...]
                Viel Erfolg!

                /tom

                Kommentar


                  #9
                  es wird besser (hoffe ich)

                  folgende Fehlermeldung im Log

                  HTML-Code:
                  plotly-graph-card.js…g=413812496335:2227  
                  Plotly Graph Card: Error parsing [entities.2.fn] SyntaxError: Invalid or unexpected token  
                  at eval (<anonymous>)  
                  at l6.evalNode (plotly-graph-card.js…812496335:2227:3982)  
                  at async l6.evalNode (plotly-graph-card.js…812496335:2227:4207)  
                  at async l6.evalNode (plotly-graph-card.js…812496335:2227:4207)  
                  at async l6._update (plotly-graph-card.js…812496335:2227:3110)  
                  at asyncplotly-graph-card.js…812496335:2228:2808  
                  at async NN.plot (plotly-graph-card.js…812496335:2228:2193)​

                  Kommentar


                    #10
                    Hmm, kann man aus der Ferne nur raten - sind bei copy/paste irgendwelche Sonderzeichen eingefügt worden, die vielleicht wie Leerzeichen aussehen?

                    Code:
                    console.log("JSON:", theJSON);​   ← sowas hier - unsichtbares, ungültiges Zeichen hinter dem Semikolon nach copy/paste; oft gern z.B. \u200b
                    Tauchen denn jetzt irgendwelche Werte im Konsolenlog auf?

                    Ansonsten einfach mal ein paar `console.log("Schritt 1");`, `console.log("Schritt 2");`, `console.log("Schritt 3");` im Code platzieren, damit wir die Zeile eingrenzen können. Die dann mal hier posten.

                    /tom
                    Zuletzt geändert von Tom Bombadil; 22.07.2025, 15:12.

                    Kommentar


                      #11
                      nein... irgendwie immer noch

                      PHP-Code:
                      Current Month:  undefined
                      VM3304
                      :7 Last Month:  undefined
                      VM3304
                      :10 Combined:  {CurrentMonthundefinedLastMonthundefined}
                      VM3304:13 JSON: {}
                      plotly-graph-card.js?hacstag=413812496335:2227  Plotly Graph CardError parsing [entities.2.fn] ReferenceErrorthe_JSON is not defined
                          at 
                      eval (eval at evalNode (plotly-graph-card.js?hacstag=413812496335:2227:3982), <anonymous>:56:28)
                          
                      at l6.evalNode (plotly-graph-card.js?hacstag=413812496335:2227:4083)
                          
                      at async l6.evalNode (plotly-graph-card.js?hacstag=413812496335:2227:4207)
                          
                      at async l6.evalNode (plotly-graph-card.js?hacstag=413812496335:2227:4207)
                          
                      at async l6._update (plotly-graph-card.js?hacstag=413812496335:2227:3110)
                          
                      at async plotly-graph-card.js?hacstag=413812496335:2228:2808
                          at async NN
                      .plot (plotly-graph-card.js?hacstag=413812496335:2228:2193)
                      evalNode plotly-graph-card.js?hacstag=413812496335:2227
                      await in evalNode
                      evalNode 
                      plotly-graph-card.js?hacstag=413812496335:2227
                      await in evalNode
                      _update 
                      plotly-graph-card.js?hacstag=413812496335:2227
                      await in _update
                      update 
                      plotly-graph-card.js?hacstag=413812496335:2227
                      (anonymous) @ plotly-graph-card.js?hacstag=413812496335:2228
                      (anonymous) @ plotly-graph-card.js?hacstag=413812496335:2219
                      requestAnimationFrame
                      (anonymous) @ plotly-graph-card.js?hacstag=413812496335:2219
                      (anonymous) @ plotly-graph-card.js?hacstag=413812496335:2219
                      Promise
                      .then
                      (anonymous) @ plotly-graph-card.js?hacstag=413812496335:2219
                      NN
                      .plot plotly-graph-card.js?hacstag=413812496335:2228
                      plotly-graph-card.js?hacstag=413812496335:2283​ 

                      Kommentar


                        #12
                        tl;dr: Habs, und gleich ordentlich gebaut mit strippen ungültiger Tage (31.04., 30.02.) sowie Berücksichtigung Jahreswechsel und Schaltjahre.

                        Ok, die Nummer hat mich jetzt so grantig gemacht, dass ich mir einen Template Sensor mit Deinem Sensornamen und dessen Attributen gebastelt habe: 😠😂

                        Code:
                        ​  - platform: template
                          
                            sensors:
                        
                              vitocal_200s_energyconsumptiondomestichotwatermonthmatrix:
                                friendly_name: "vitocal_200s_energyconsumptiondomestichotwatermonthmatrix"
                                unique_id: "vitocal_200s_energyconsumptiondomestichotwatermonthmatrix"
                                value_template: >
                                  {{ 31.6 }}
                                attribute_templates:
                                  CurrentMonth: >
                                    {{ '{"10": 1.3, "11": 1.4, "12": 1.2, "13": 3.4, "14": 0, "15": 1.3, "16": 1.3, "17": 1.4, "18": 1.5,"19": 0, "20": 0, "21": 0, "22": 0, "23": 0, "24": 0, "25": 0, "26": 0, "27": 0, "28": 0,"29": 0, "30": 0, "31": 0, "01": 1.6, "02": 2, "03": 1.2, "04": 1.3, "05": 1.9, "06": 1.4, "07": 1.6, "08": 1.6, "09": 1.9}' }}
                                  LastMonth: >
                                    {{ '{"10": 0, "11": 0, "12": 0, "13": 0, "14": 0, "15": 0, "16": 0, "17": 0, "18": 0, "19": 0, "20": 0, "21": 0, "22": 0, "23": 1.3, "24": 2.7, "25": 1.6, "26": 1.8, "27": 0, "28": 1.2, "29": 3.2, "30": 0, "31": 0, "01": 0, "02": 0, "03": 0, "04": 0, "05": 0, "06": 0, "07": 0, "08": 0, "09": 0 }' }}
                        Damit sieht der Sensor dann 1:1 so aus wie bei Dir:



                        Danach noch 'ein wenig' den Code angepasst, und schwupps: wird obiger Template Sensor zu folgendem Graphen:

                        ​​

                        Den Code der Karte findest Du hier, ich will ihn hier nicht noch einmal komplett einfügen und damit das Forum zumüllen.

                        Wenn es jetzt nicht geht, kann es nur noch daran liegen, dass Deine Daten in den Attributen kein echtes JSON oder leicht anders sind, obwohl der Screenshot ja genauso aussieht - zum Vergleich und Testen hast Du ja den Template Sensor oben.
                        Den Rest (Plotly-Optionen, Achsen usw) kriegst sicher auch so hin, da kann man tagelang spielen.

                        Viel Spaß!

                        /tom
                        Zuletzt geändert von Tom Bombadil; 22.07.2025, 19:10.

                        Kommentar


                          #13
                          Hi Tom,

                          danke für die von Dir investierte Zeit. Ich habe keine Ahnung woran es liegt aber es klappt nicht.
                          Ich bekomme immer Fehlermeldungen.

                          grafik.png

                          Es scheint also kein JSON zu sein...


                          nebenbei, wenn dein Standort stimmt, sind wir fast Nachbarn 😉

                          Kommentar


                            #14
                            Die beiden ersten Plotly-Entitäten bekommen 'undefined' oder ein leeres Objekt. Mal prüfen, ob der Name der Entität und der Attribute wirklich passt, und dass die Attribute nicht leer sind.

                            Ansonsten wieder log-Einträge in die drei Plotly-Entitäten ThisMonth, LastMonth und Combined hinzufügen:
                            Code:
                                  $fn ({ ys }) => {
                                    const raw = ys[0];
                                    console.log("ThisMonth: |", raw, "|");
                            Die Ausgabe im Log sollte dann etwa so aussehen:
                            image.png

                            Sofern Du Zugriff auf ChatGPT, Copilot & Co hast, gib der AI mal den Code und die Log-Ausgaben sowie nen Screenshot der Vitocal-Entität in HA zur Analyse.

                            /tom

                            Kommentar


                              #15
                              ich habe jetzt den MQTT Sensor gelöscht und noch einmal neu eingefügt.
                              Und obwohl MQTT ja schon einen json Wert liefert habe ich für das Scheiben der Attribute noch einmal ein "konvertieren zu json" eingebaut

                              HTML-Code:
                               json_attributes_template: '{{ value_json | tojson }}' ​
                              so klappt es jetzt...

                              wenn ich mir nun aber nur 7 Tage oder 10 Tage anzeigen lassen möchte alsu
                              HTML-Code:
                               hours_to_show: 15d
                              kommt ein Fehler
                              grafik.png

                              Kommentar

                              Lädt...
                              X