Linux limit battery charge

Arch Linux

You are not logged in.

#1 2015-11-06 22:01:10

Set battery charge limit

I’ve started to experience a strange bug, laptop just keeps charging at 99%. If I plug adapter out and back, laptop stops charging, showing 100% charge. Is there a way to limit charge at 80%, for example, stopping the charging and letting the laptop use ac power then (as it usually does when reaching 100% charge)? I’ve looked through my bios settings, but unfortunately there are no power management options. I also found utility called «tp_smapi», but it’s only for lenovo thinkpad laptops.

#2 2015-11-06 22:50:25

Re: Set battery charge limit

Where are you getting the information that the battery is charging at 99%? And what does that mean? The battery reaches 99% SOC and then stays there?

The really interesting information are in the the pseudo file system /sys/class/power_supply/BAT0

Nothing is too wonderful to be true, if it be consistent with the laws of nature — Michael Faraday
Sometimes it is the people no one can imagine anything of who do the things no one can imagine. — Alan Turing

How to Ask Questions the Smart Way

#3 2015-11-06 23:37:02

Re: Set battery charge limit

I do also experience this.
In the directory ewaller mentioned, there are several files, of which are relevant:

Your 99% is most likely the quotient of the values of charge_now and charge_full.
charge_full shows the last full charge.
The maximal battery charge decreases over time and is generally not consistent (I could also imagine it being higher at a later point in time, however I am not an expert).
That is why charge_full and charge_full_design differ significantly and why charge_now may also be smaller than charge_full even though the battery is charged to its current maximum.

#4 2015-11-07 03:38:29

Re: Set battery charge limit

Where are you getting the information that the battery is charging at 99%? And what does that mean? The battery reaches 99% SOC and then stays there?

The really interesting information are in the the pseudo file system /sys/class/power_supply/BAT0

Information is from the path you specified above and also from indicator in my xfce panel.
Anyway, when charge reaches 99%, but it doesnt stop charging, just remains on that value (I’ve tried to wait for a couple of hours), the charging indicator (both hardware one on my laptop and on the screen) still on and power_now shows small values (2-3 watts), though it’s supposed to be 0 when battery is charged and switched to AC power.

#5 2015-11-08 11:23:29

Re: Set battery charge limit

Just noticed, if my laptop is off and I put it on charge, everything is ok — it stops charging when the battery is full.
So, does linux kernel control charging (and is there a way to enable/disable charging on software side), or it’s independent?

Last edited by Coriolis (2015-11-08 11:29:08)

#6 2015-11-08 17:49:37

Re: Set battery charge limit

You can’t control charging but by removing or applying power.
I don’t think, that a laptop provides such a switch which can be controlled by software.

A battery stops charging, when it is fully charged. If the software says it is not, it is simply wrong.
The software can’t analyze the chemical processes in your battery. In fact, the battery will actually never actually reach a state where it is «fully charged» because the reaction is, like almost any chemical reaction, a dynamic equilibrium reaction.
However the software can see the approximate current charge (charge_now). And it will store the maximum charge it has measured in the last time (charge_full).

Читайте также:  Создание загрузочных флешек средствами windows

#7 2015-11-08 18:56:18

Re: Set battery charge limit

Lithium batteries have more density power than traditional Ni-Cd ones (if I can still call that traditional). So you can carry more energy using less space. The problem with that technology is that they will usually explode when they are over charged. So you are literally carrying a portable bomb on your pocket. That’s mainly why you cannot control the charging state from software. This process is usually managed by a dedicated integrated circuit. It will charge the battery fast until 80% and then slowly charge your battery for the remaining 20%. That will typically improve battery life. For safety reasons explained above, you can only read the battery state and health and cannot control the charging state of this specific hardware. More info -> Battery University

#8 2015-11-08 18:58:41

Re: Set battery charge limit

Well, bomb may be a bit of a stretch. Think of it as a highly effective incendiary.

Last edited by ewaller (2015-11-08 19:21:47)

Nothing is too wonderful to be true, if it be consistent with the laws of nature — Michael Faraday
Sometimes it is the people no one can imagine anything of who do the things no one can imagine. — Alan Turing

How to Ask Questions the Smart Way

Источник

Как я могу ограничить заряд батареи до 80% емкости?

Я только что узнал, что в некоторых ноутбуках Lenovo есть утилита, которая предлагает ограничить зарядную емкость батареи до 0–80%, чтобы замедлить срок службы батареи:

Как я могу сделать это в Ubuntu?

Пороги зарядки, к сожалению, зависят от прошивки и производителя.

К счастью, пользователю Lenovo ThinkPad предоставляется решение, описанное в ThinkWiki .

В основном это говорит о том, что вам нужно установить и загрузить tp_smapi модуль ядра:

и записать желаемые пороги зарядки в виртуальные файлы в /sys/devices/platform/smapi :

Затем он прекратит зарядку, когда он достигнет 80%, и начнет заряжаться только тогда, когда он опустится ниже 40%.

Toshiba и другие могут иметь аналогичный модуль ядра, который предоставляет функциональные возможности встроенного программного обеспечения /sys или /proc пространства, но это маловероятно для проблем с патентами. По тем же причинам приложение, которое могло бы справиться с этим, будет либо ориентировано на Thinkpad, либо адресовано только нескольким избранным поставщикам.

$ sudo modprobe tp_smapi FATAL: Error inserting tp_smapi (/lib/modules/3.5.0-17-generic/updates/dkms/tp_smapi.ko): No such device . Я что-то пропустил? Я собираюсь открыть новый вопрос, если я не получу ответ.

Принятый ответ не работает на моем новом Lenovo T440s. Видимо прошивка изменилась. После http://www.thinkwiki.org/wiki/Tpacpi-bat я сделал

Для справки, я сделал это при тестировании Debian, но я уверен, что он работает и в Ubuntu.

Для Ubuntu (и других дистрибутивов) теперь доступно несколько более приятное приложение:

TLP предоставляет вам преимущества расширенного управления питанием для Linux без необходимости разбираться во всех технических деталях. TLP поставляется с конфигурацией по умолчанию, уже оптимизированной для работы от батареи, так что вы можете просто установить ее и забыть о ней. Тем не менее, TLP легко настраивается в соответствии с вашими требованиями.

Одним из параметров, которыми он управляет, является поддержание пределов зарядки аккумулятора. Он по- прежнему работает только для Thinkpads , но с учетом характера проекта — если соответствующие драйверы для других устройств станут доступными, вероятно, они также будут интегрированы в этот проект. Поэтому, если вы читаете этот комментарий через несколько лет, проверьте документацию, возможно, ваше устройство действительно поддерживается.

На моем Toshiba R830 под управлением Windows 8.1 я установил приложение Toshiba Power Saver, чтобы ограничить заряд батареи до 80%.

Когда я загружаюсь в Linux (Ubuntu, Mint и т. Д.), Максимальный заряд по-прежнему ограничен 80%.

Следовательно, Toshiba Power Saver, похоже, сохраняет свою конфигурацию в BIOS.

Читайте также:  Cmak windows 10 что это такое

Единственным недостатком является то, что если я хочу путешествовать с полностью заряженным аккумулятором, я должен перезагрузить Windows и изменить конфигурацию энергосбережения.

Источник

How To Limit Battery Charging (Set A Charge Threshold) For ASUS Laptops On Linux

Newer ASUS laptops support limiting the battery charge level, which helps prolong battery life. This article explains how to set a battery charge threshold for ASUS laptops on Linux.

Battery lifespan is affected by age, high temperatures, the number of charge cycles, and the amount of time at full charge. A battery charge threshold reduces the amount of time at full charge (100%), and thus improves battery health / life.

ASUS laptops support setting a charge threshold starting with Linux 5.4. The kernel WMI method to set the charge threshold does not provide a way to specify a battery, assuming it’s the first battery ( BAT0 ). However, for some newer ASUS laptops, the primary battery is not called BAT0 , but BATT (e.g. Zenbook UM431DA) and BAT1 (e.g. ASUS TUF Gaming FX706II). [Edit] And There’s also BATC.

So while ASUS laptops support limiting battery charging starting with Linux 5.4, that’s only for laptops having BAT0 . For ASUS laptops using BATT as the primary battery name, you’ll need kernel 5.7, while for BAT1 you’ll need the 5.8 kernel (in the instructions below you’ll see exactly how to check the battery name). [Edit] For ASUS laptops using BATC battery name, you’ll need to use Linux 5.9 or newer.

Also, not all ASUS laptops support setting a battery charge threshold so depending on your ASUS laptop model, this may or may not work for you; there’s no list of supported devices that I could find.

It’s important to mention that the kernel WMI method of setting the battery charge threshold for ASUS notebooks can only set the stop value ( charge_control_end_threshold ) (it can’t also set the start threshold). Also, with AC connected, if the battery level is higher than the charge stop threshold, it will not be discharged to the stop threshold.

And another note. With my ASUS ZenBook 14 UX433FAC running Ubuntu 20.04 with GNOME Shell, when limiting battery charging while the battery level is equal or greater than the charge threshold, and then connect the laptop to AC, the battery indicator from the top panel changes from the time remaining until the battery discharges to the time remaining until the battery is charged. This happens even though the battery is not charging. After a while (so this is not instant when you connect your laptop to AC), the battery indicator changes to say «Not charging», as it should.

Besides ASUS, some Lenovo and Huawei (with the latter getting support with Linux 5.5) laptops also have support for limiting battery charging. But since I only own an ASUS laptop and I can’t test it on other devices, this guide is for ASUS only. Lenovo has had support for this for quite a while, and TLP has support for setting this built-in (only for IBM/Lenovo ThinkPads). As a side note, here’s a GUI for TLP to easily configure it, in case you’re not using it already.

How to set a battery charge stop threshold for ASUS laptops on Linux

1. Find out your ASUS’ laptop battery name.

Let’s start by figuring out the battery name for your ASUS laptop. This can be done by using the following command:

This command should output something like this:

In this example (from my ASUS notebook), the name of the battery is BAT0 , but like I mentioned above, for you it may also be BAT1 or BATT , these being the only supported battery names by the kernel for ASUS laptops.

2. Create a systemd service to set the battery charge stop threshold on boot.

Before creating the systemd service, check if your laptop actually has charge_control_end_threshold in /sys/class/power_supply/BAT* (without it, this won’t work):

Читайте также:  Linux диагностика сетевой карты

If this command returns the path to charge_control_end_threshold , then your ASUS notebook supports limiting battery charging. If the command returns an error, saying there’s no such file or directory, then your laptop doesn’t support setting a charge threshold.

If your ASUS laptop has this file, we can continue. Create a file which we’ll call battery-charge-threshold.service in /etc/systemd/system .

You can open this file with your default console text editor using:

Or use Gedit or whatever graphical editor you want to use (e.g. for Gedit to open this file as root: gedit admin:///etc/systemd/system/battery-charge-threshold.service )

In this file you’ll need to paste the following:

Here, change BATTERY_NAME with the name of the battery ( BAT0 , BAT1 or BATT ), and CHARGE_STOP_THRESHOLD with the battery charge stop threshold you want to use (ranging between 1 and 100). Note that I’ve read that one user couldn’t set the charge threshold to any value, but only to 60, 80 and 100.

From what I’ve read, for best battery lifespan when the laptop is connected to AC most of the time, set the battery charge stop threshold at around 50 or 60. If the battery is used somewhat frequently, set the battery charge stop threshold at about 90.

3. Enable and start the battery-charge-threshold systemd service.

Now let’s enable and start the newly created battery-charge-threshold systemd service:

With systemd 220, it’s possible to enable and start a service directly using systemctl enable —now , but I prefer to use 2 commands in case some readers use an older systemd version.

If you want to change the battery charge stop threshold level, you’ll need to edit the /etc/systemd/system/battery-charge-threshold.service file, and change the number from the ExecStart line (after echo ) to the new value you want to use, then reload systemd (because the file contents have changed) and restart the systemd service using the following commands:

4. Verify that the battery charge stop threshold is working.

If your ASUS laptop supports it, the battery charging limit should now be set to the value you’ve used in step 2.

You can check this by charging your laptop to the threshold set in battery-charge-threshold.service , and then use this command:

Replace BATTERY_NAME with the name of the battery, as explained under step 1.

If the battery charge stop threshold is working, the command should show the following output:

If it says «Discharging», make sure your ASUS laptop is actually on AC power, and not running on battery. However, if it says «Charging», well. then your laptop is charging past the charge stop threshold, so this is not working for you, either because your ASUS laptop doesn’t support it (which is weird if you have charge_control_end_threshold as mentioned in step 2), you’re using a Linux version that’s too old for limiting battery charging on your ASUS notebook, or because of human error 😁️.

Extra: In case you don’t use systemd, you can also do this by using cron, by running sudo crontab -e and then pasting the following line (this is a single line, triple-click the line to select the whole line), although this is not reliable in all cases from what I’ve read (I’m not sure why):

Replacing CHARGE_STOP_THRESHOLD with the battery charge stop threshold you want to use and BATTERY_NAME with the battery name as seen in step 1.

Why use a systemd service or a cron job? According to u/esrevartb, from whom I’ve adapted these instructions, «it seems the udev rule isn’t working either because the battery sysfs path isn’t yet initialized when the rule gets applied, or because this specific charge_control_end_threshold attribute cannot be modified this way«.

[[Edit] To easily set a charge threshold for ASUS laptops (automatic setup of the systemd service and the ability to change the charge threshold using a command), as well as check the current charging threshold, see bat.

Источник

Оцените статью