Howto monitor battery from laptop with HA installed as OS

Hi,

I’ve managed to install HA as a dedicated OS on a spare laptop (Acer Aspire).
I’m trying to figure out how to have HA check the battery state (and maybe even the power incoming power from the adapter)

For example, when disconnecting the adapter, i would like to have HA detect it. When it is running on battery power i would like to have HA monitor the state of the battery like; x % power left or x % discharged. And when power restores same for like battery fully charged.

Is there a way to accomplish this task(s)?

Best Regards,
Patrick

As i have visited HA on Facebook, it got me the following useful feedback.

Enable / Install SSH on Home Assistant so you can access the CLI (command line interface) of Home Assistant.

Because this HA is Linux based you can navigate to the /sys/class/ directory and find all kinds of hardware related directories and files

Use cat command to read specific files. In my case:

cd /sys/class/power-supply/BAT1
cat capacity

Result
100

Meaning, the battery is fully charged

As im not aware of how this BAT1 file looks like, im not sure … but if Result: 100 is, “Added” in the end each time, … you can use -tail command( in a template-sensor ) / (command-line-sensor)

Install Glances and you receive all info from the notebook :slight_smile:

Hey,
Did you ever get anywhere with this? I’ve had my HA set up on a old laptop for a few days now and would love a way to easily monitor the battery and even set an alert if it gets low. I’ll dig into the code tomorrow if not.

OK, that was actually much easier than I expected!

If anyone else is using an old laptop and is interested in doing this you just need to add this code to your configuration.yaml:

sensor:
  - platform: command_line
    name: Battery Percentage
    command: "cat /sys/class/power_supply/BAT0/capacity"
    # If errors occur, make sure configuration file is encoded as UTF-8
    unit_of_measurement: "%"

Save the .yaml and reboot (not sure if completely necessary).

Now you can add a gauge card to your overview page and select ‘Battery Percentage’ from the drop down. I added the ‘define severity’ option and set it to Green: 75, Yellow: 25 and Red: 0 to make it easier to see when it getting low.

2 Likes

Hi,

as I asked, here is solution.

alias: HA PC Battery Power
description: ""
trigger:
  - platform: state
    entity_id:
      - sensor.battery_percentage
condition: []
action:
  - choose:
      - conditions:
          - condition: template
            value_template: |-
              {% if states('sensor.battery_percentage') | int > 80 %}
                true
              {%- else -%}
                false
              {%- endif %}
        sequence:
          - type: turn_off
            device_id: yourID
            entity_id: switch.sonoff_10006cc88f
            domain: switch
      - conditions:
          - condition: template
            value_template: |-
              {% if states('sensor.battery_percentage') | int < 40 %}
                true
              {%- else -%}
                false
              {%- endif %}
        sequence:
          - type: turn_on
            device_id: yourID
            entity_id: switch.sonoff_10006cc88f
            domain: switch
mode: single
1 Like

Not working for me. Just says battery unknown. I had the battery removed for a while and recently put it back in. Restarted home assistant thinking maybe it would need it, still showing unknown. Did you run into that? Any tips if so?

EDIT: After multiple restarts it seems to be working.

check this github repo GitHub - Indian-Techie09/linuxlaptopstat2mqtt: it is a docker container for sending linux computer stats to mqtt broker

This worked great! Thanks!

Looks nice, but you can’t add docker containers to HAOS. A Supervisor add-on would be great.

I get an error about this no longer working in the newest version of HA but the sensor card does show on the Overview page withe Battery Percentage?

Ok I fixed this and this is how for future me… or anyone else that stumbles across it.

You have to create (if you do not have one already) a “integration” file and put the:

command_line:
sensor:

  • platform: command_line
    name: Battery Percentage
    command: “cat /sys/class/power_supply/BAT0/capacity”

    If errors occur, make sure configuration file is encoded as UTF-8

    unit_of_measurement: “%”

into that file. It should show as: /homeassistant/integration at the top above the 7 lines of code listed.

Thanks for the update!

I was fiddeling with this to get it to work.
To clarify, you need to create a file called “command_line.yaml” and include it in the “configuration.yaml” -file. Add “command_line: !include command_line.yaml” to the configuration-file.

In the file “command_line.yaml” Add the following.

- sensor:
    name: Battery percentage
    unique_id: "[WHATEVER YOU WANT]"
    command: 'cat /sys/class/power_supply/BAT0/capacity'
    unit_of_measurement: "%"
    device_class: battery
  
- sensor:
    name: Battery status
    unique_id: "[WHATEVER YOU WANT2]"
    command: 'cat /sys/class/power_supply/BAT0/status'
    device_class: battery_charging


Works like a charm :slight_smile:

The first part worked for me on my HA server running on a ThinkPad laptop but the second sensor part gave an error when I tried to restart my HA server so I had to remove that section from the yaml file, but the Battery percentage is working great!

Have you defined “battery_charging” as its own device class somewhere?

I get this error:

Invalid config for ‘command_line’ at command_line.yaml, line 12: expected SensorDeviceClass or one of ‘date’, ‘enum’, ‘timestamp’, ‘apparent_power’, ‘aqi’, ‘atmospheric_pressure’, ‘battery’, ‘carbon_monoxide’, ‘carbon_dioxide’, ‘current’, ‘data_rate’, ‘data_size’, ‘distance’, ‘duration’, ‘energy’, ‘energy_storage’, ‘frequency’, ‘gas’, ‘humidity’, ‘illuminance’, ‘irradiance’, ‘moisture’, ‘monetary’, ‘nitrogen_dioxide’, ‘nitrogen_monoxide’, ‘nitrous_oxide’, ‘ozone’, ‘ph’, ‘pm1’, ‘pm10’, ‘pm25’, ‘power_factor’, ‘power’, ‘precipitation’, ‘precipitation_intensity’, ‘pressure’, ‘reactive_power’, ‘signal_strength’, ‘sound_pressure’, ‘speed’, ‘sulphur_dioxide’, ‘temperature’, ‘volatile_organic_compounds’, ‘volatile_organic_compounds_parts’, ‘voltage’, ‘volume’, ‘volume_storage’, ‘water’, ‘weight’, ‘wind_speed’ for dictionary value ‘command_line->1->sensor->device_class’, got ‘battery_charging’

When I set the class to battery then it gives this error:

Error adding entities for domain sensor with platform command_line
Traceback (most recent call last):
File “/usr/src/homeassistant/homeassistant/components/sensor/init.py”, line 616, in state
numerical_value = int(value)
^^^^^^^^^^
ValueError: invalid literal for int() with base 10: ‘Not charging’

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File “/usr/src/homeassistant/homeassistant/components/sensor/init.py”, line 619, in state
numerical_value = float(value)
^^^^^^^^^^^^
ValueError: could not convert string to float: ‘Not charging’

Seems like it expects a numeric value, is there a way to set up a command-line sensor with a string?

I solved by entering enum instead of battery_charging in the command_line.yaml file.

It now shows the status.

That’s a great solution.

I actually moved my setup from bare metal to Proxmox (so I can potentially run other things in the future), so I set up a script that sends the battery info to mqtt. At the moment I’m just using battery level to allow for battery conditioning, but I may add the charging status later if needed.
Using PROXMOX on a laptop with a battery
Ran into a problem with the cron task running too many threads, and I’m not experienced enough with Python to troubleshoot it right now.

I set up a NetData server on the Proxmox box, and pulled the battery sensor into Home Assistant with the integration: Netdata - Home Assistant