GithubHelp home page GithubHelp logo

battery's Introduction

battery Build Status Go Report Card GoDoc

Cross-platform, normalized battery information library.

Gives access to a system independent, typed battery state, capacity, charge and voltage values recalculated as necessary to be returned in mW, mWh or V units.

Currently supported systems:

  • Linux 2.6.39+
  • OS X 10.10+
  • Windows XP+
  • FreeBSD
  • DragonFlyBSD
  • NetBSD
  • OpenBSD
  • Solaris

Installation

$ go get -u github.com/distatus/battery

Code Example

package main

import (
	"fmt"

	"github.com/distatus/battery"
)

func main() {
	batteries, err := battery.GetAll()
	if err != nil {
		fmt.Println("Could not get battery info!")
		return
	}
	for i, battery := range batteries {
		fmt.Printf("Bat%d: ", i)
		fmt.Printf("state: %s, ", battery.State.String())
		fmt.Printf("current capacity: %f mWh, ", battery.Current)
		fmt.Printf("last full capacity: %f mWh, ", battery.Full)
		fmt.Printf("design capacity: %f mWh, ", battery.Design)
		fmt.Printf("charge rate: %f mW, ", battery.ChargeRate)
		fmt.Printf("voltage: %f V, ", battery.Voltage)
		fmt.Printf("design voltage: %f V\n", battery.DesignVoltage)
	}
}

CLI

There is also a little utility which - more or less - mimicks the GNU/Linux acpi -b command.

Installation

$ go install github.com/distatus/battery/cmd/battery@latest

Usage

$ battery
BAT0: Full, 95.61% [Voltage: 12.15V (design: 12.15V)]

battery's People

Contributors

alext2594 avatar cjbassi avatar creatcodebuild avatar dmitshur avatar itchyny avatar kenjitakahashi avatar mattn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

battery's Issues

No such device error

When I run the battery.GetAll() function, it gives me the following error:

panic: [{ChargeRate:read /sys/class/power_supply/BAT1/power_now: no such device}]

While I was tinkering, I found out that the ls command did show a file named power_now but opening it with cat gives the same error as above. On the other hand, I found out that there is another file called capacity which gives the battery level.

I am on Arch Linux and using go 1.21.6.

Expose voltage info.

Most implementations already gather it in some cases for Amp->Watt conversion anyway (with the exception of Windows).
Some systems differentiate between "current voltage" and "design voltage", but some (e.g. OS X) seem not to do so, will need to investigate how to handle that.

CLI doesn't work with Solaar?

I ran go get -u github.com/distatus/battery/cmd/battery from README and ranbattery command, and I've got output as below.

[{Current:open /sys/class/power_supply/hidpp_battery_0/voltage_now: no such file or directory Full:open /sys/class/power_supply/hidpp_battery_0/voltage_now: no such file or directory Design:open /sys/class/power_supply/hidpp_battery_0/voltage_min_design: no such file or directory ChargeRate:open /sys/class/power_supply/hidpp_battery_0/voltage_now: no such file or directory Voltage:open /sys/class/power_supply/hidpp_battery_0/voltage_now: no such file or directory DesignVoltage:open /sys/class/power_supply/hidpp_battery_0/voltage_min_design: no such file or directory}]

uname -a

Linux kaguya 4.14.83-1-MANJARO #1 SMP PREEMPT Fri Nov 23 18:20:11 UTC 2018 x86_64 GNU/Linux

ls -1 /sys/class/power_supply/

AC@
BAT1@
hidpp_battery_0@

ls -1 /sys/class/power_supply/hidpp_battery_0/

capacity_level
device@
manufacturer
model_name
online
power/
powers@
scope
serial_number
status
subsystem@
type
uevent

Not Working โ€“ Possible Issue with Windows 11??

I've recently installed oh-my-posh on my laptop, and when creating a custom theme to include the battery charging status, it gives me the following error: {State:Unknown Current:0 Full:0 Design:0 ChargeRate:0 Voltage:0 DesignVoltage:0}.

I did some digging and saw that oh-my-posh uses this library for getting those values, and so I downloaded Go installed the cmd utility on my laptop and tried running that, to see if it was an issue with oh-my-posh, but when I ran the battery command, it returned the following output Error getting info for BAT0: {ChargeRate:Unknown value received}.

I am running Windows 11 on this laptop, so there may be a compatibility issue there?

If there is any more information I can provide to help debug this issue, please let me know. I do not personally have any experience with Go, but am willing to help in whatever way I can.

Thanks!

tagged releases?

hi,

first, thank you for this software, it looks quite useful and is used in a tool I am packaging for debian (gotop).

one problem with this dependency is that it doesn't have official releases. it makes it hard to find out when changes happen in the code base. it also makes tracking module dependencies with the new golang module system harder.

would you consider using official, tagged releases for your software?

again thank you for your time.

Aggregate multiple batteries into one state

I feel like many apps will only want to display a single battery indicator -- it's unlikely the user cares whether their laptop hardware has a single battery controller, or multiple. To avoid lots of (bad) copies of this logic, or probably more likely apps reporting just the first battery, perhaps provide a func Summarize() (*Battery, error)?

New version coming with a breaking change!

Current master includes a redoing of the State field that can be potentially breaking some use cases. See https://github.com/distatus/battery/blob/master/BREAKING.md for more details.
In a couple of days I will have to go offline again for a few weeks, that's why I do not want to make a release at this time.
In the meantime, users of the library are encouraged to give current master branch a try and report problems, if any.

I plan to cut the next release ~mid June. After addressing possible bugs, of course.

Support "NotCharging" status on MacOS

Recent MacOS versions have a feature called "optimized battery charging" which holds the battery charge at ~80% until the OS anticipates a full charge is necessary (or the user requests it).

In this state, the library reports an "Unknown" status as shown by the battery command:

BAT0: Unknown, 75.95% [Voltage: 12.02V (design: 12.02V)]

In this state ioreg -n AppleSmartBattery -r looks like the below. I'm not sure if there's a property in there which specifically indicates the OS is holding the charge, but I suppose it could be inferred by the 3 flags IsCharging = No, ExternalConnected = Yes, and FullyCharged = No.

    {
      "TimeRemaining" = 0
      "AvgTimeToEmpty" = 65535
      "AdapterDetails" = {"IsWireless"=No,"AdapterID"=0,"FamilyCode"=18446744073172697098,"Watts"=87,"Current"=4350,"PMUConfiguration"=4344,"Voltage"=20000,"Description"="pd charger"}
      "ChargingOverride" = 2
      "AppleRawCurrentCapacity" = 6469
      "InstantTimeToEmpty" = 65535
      "AppleRawMaxCapacity" = 8518
      "ExternalChargeCapable" = Yes
      "FullPathUpdated" = 1628628343
      "Voltage" = 12017
      "PermanentFailureStatus" = 0
      "BatteryInvalidWakeSeconds" = 30
      "AdapterInfo" = 0
      "MaxCapacity" = 8518
      "DesignCycleCount70" = 13
      "UpdateTime" = 1628628523
      "Manufacturer" = "DSY"
      "AppleRawAdapterDetails" = ({"IsWireless"=No,"AdapterID"=0,"FamilyCode"=18446744073172697098,"Watts"=87,"Current"=4350,"PMUConfiguration"=4344,"Voltage"=20000,"Description"="pd charger"})
      "Location" = 0
      "CurrentCapacity" = 6469
      "LegacyBatteryInfo" = {"Amperage"=0,"Flags"=5,"Capacity"=8518,"Current"=6469,"Voltage"=12017,"Cycle Count"=10}
      "BatteryInstalled" = Yes
      "FirmwareSerialNumber" = 1
      "CycleCount" = 10
      "ChargerData" = {"ChargingCurrent"=0,"NotChargingReason"=24,"ChargingVoltage"=12780,"VacVoltageLimit"=4260}
      "AvgTimeToFull" = 65535
      "BatteryData" = {"PMUConfigured"=0,"FccComp2"=8518,"ResScale"=244,"SystemPower"=1109912294,"Qmax"=(9406,9421,9425),"DesignCapacity"=8790,"CellVoltage"=(4006,4005,4006),"PassedCharge"=1,"RaTableRaw"=(<0055005c00330037003b004400370039003a003d003e003e0043007000c80152>,<005500640037003b003e00460037003a003c003f003f0040004a006b00d1014f>,<0000005e0033003a003d004b0039003b003c003e003e003d0046007400d5015b>),"StateOfCharge"=76,"PresentDOD"=(27,27,27),"Flags"=557318657,"DataFlashWriteCount"=2251,"DOD0"=(4448,4456,4448),"ChemID"=9017,"AdapterPower"=1110845221,"CycleCount"=10,"Voltage"=12017,"GaugeFlagRaw"=192,"FccComp1"=8811,"BatteryState"=<0000000000000000c3e40002c0030000>,"ManufactureDate"=52987937437746,"LifetimeData"={"TotalOperatingTime"=6932,"UpdateTime"=1628628523,"AverageTemperature"=0,"TimeAtHighSoc"=<0000000045010000a20200000900000009000000000000000000000000000000400100001b00000002000000000000000000000000000000000000000d0100004f00000001000000000000000000000000000000000000001e1400003c00000000000000010000000000000000000000>},"Serial"="F5D02741160K7LRCV"}
      "OperationStatus" = 58563
      "PackReserve" = 244
      "BestAdapterIndex" = 1
      "DesignCapacity" = 8790
      "BootPathUpdated" = 1628261058
      "PostDischargeWaitSeconds" = 120
      "Serial" = "F5D02741160K7LRCV"
      "Temperature" = 3082
      "UserVisiblePathUpdated" = 1628628523
      "IOReportLegendPublic" = Yes
      "InstantAmperage" = 0
      "ManufacturerData" = <000000000b00030023090000043133373703303042035344490002>
      "FullyCharged" = No
      "MaxErr" = 3
      "DeviceName" = "bq40z651"
      "IOGeneralInterest" = "IOCommand is not serializable"
      "IOReportLegend" = ({"IOReportChannels"=((7167869599145487988,6460407809,"BatteryCycleCount")),"IOReportGroupName"="Battery","IOReportChannelInfo"={"IOReportChannelUnit"=0}})
      "Amperage" = 0
      "IsCharging" = No
      "DesignCycleCount9C" = 1000
      "PostChargeWaitSeconds" = 120
      "ExternalConnected" = Yes
    }

(This output is from an x86 MacBook Pro running 11.5.1.)

Gomobile

I wonder how easy it is to also do this on android ios ?
Would be interesting to also see the effects on the code.

Possible panic on x86 systems

https://github.com/distatus/battery/blob/master/battery_windows.go#L197 could cause a panic on x86 systems. This happens because, if cbRequired < 3, then cbRequired/2-1 will be a negative value, which for a uint will cause wrapping to happen. An x64 system will be able to allocate enough memory, but not an x86 system.

Thus I suggest changing didd := make([]uint16, cbRequired/2-1) to didd := make([]uint16, cbRequired/2).

Another reason for this change is because

	errno = setupDiCall(
		setupDiGetDeviceInterfaceDetailW,
		6,
		hdev,
		uintptr(unsafe.Pointer(&did)),
		uintptr(unsafe.Pointer(&didd[0])),
		uintptr(cbRequired),
		uintptr(unsafe.Pointer(&cbRequired)),
		0,
	)

is called, where we inform the call that cbRequired bytes can be written, but the memory allocated is less than that. The null terminator is still written and used subsequently, but the above behavior is not correct.

Doesn't work on my Ubuntu installation

Uname:

$ uname -a
Linux hippo 3.13.0-85-generic #129-Ubuntu SMP Thu Mar 17 20:50:15 UTC 2016 x86_64 x86_64 x86_64 GNU/Linux

lsb-release:

$ lsb_release -a
LSB Version:    core-2.0-amd64:core-2.0-noarch:core-3.0-amd64:core-3.0-noarch:core-3.1-amd64:core-3.1-noarch:core-3.2-amd64:core-3.2-noarch:core-4.0-amd64:core-4.0-noarch:core-4.1-amd64:core-4.1-noarch
Distributor ID: Ubuntu
Description:    Ubuntu 14.04.4 LTS
Release:    14.04
Codename:   trusty

Execution:

$ battery
[{Current:open /sys/class/power_supply/BAT0/energy_now: no such file or directory}]

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.