Custom button-card - defining a common JS function to use in multiple places in the same card?

Hi good peeps!

Been extending my HA with the excellent custom button-card. Added a button to warn me if any of my 25 battery devices is running low or disappeared (Code below - you don’t need to read it for this question, just to share if anyone else is interested).

I need to use that in maybe 3-4 places to change icon colour, animate the icon, change the State text (which is all it does now). It’s a long bit of code to be copying and pasting.

Just wondered if there was a way to define it as a function once and call.

The thought is vaguely occurring to me to maybe make a full blown JS lib and include it as a resource like I did for the sprintf lib. But I’m just trying to see what my options are here…

Cheers Tim

  state_display: |
    [[[
      const warnlevel = 70; // Warn if battery level is below this
      const errorlevel = 50;  // Critical if battery level is below this
      const unseen_time = 600;  // Warn if device seen more than seconds ago

      let bc = 0; // Battery sensor count
      let lc = 0; // Low count
      let cc = 0; // Critical count
      let uc = 0; // Unseen count

      let now = (new Date()).getTime() / 1000; // now

      for (const k in states)
      {
        if ( k.match( /^sensor\.[^\.]+battery_level$/ ) )
        {
          let level = states[k].state;

          if (level < errorlevel)
          {
            cc++;
          }
          else if (level < warnlevel)
          {
            lc++;
          }

        // Check last_updated time too...
          let seen = (new Date(states[k].last_updated)).getTime() / 1000;
          let when = Math.floor(now - seen);
          if (when > unseen_time)
          {
            uc++;
          }

          bc++;
        }
      }

      if (lc == 0 && cc == 0 && uc == 0)
      {
        return sprintf("%d OK", bc);
      }

      let retval = "";
      retval += sprintf("%02d OK", bc - lc - cc);
      if (lc != 0)
      {
        retval += sprintf("<BR/>%02d Low", lc);        
      }
      if (cc != 0)
      {
        retval += sprintf("<BR/>%02d Crit", cc);      
      }
      if (uc != 0)
      {
        retval += sprintf("<BR/>%02d Fail", uc);      
      }
      return retval;
    ]]]

What about button_card_templates ?

1 Like

Thanks - I’ll have a look at those :+1: