battery

package module
v0.11.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 23, 2023 License: MIT Imports: 5 Imported by: 56

README

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)]

Documentation

Overview

Package battery provides cross-platform, normalized battery information.

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

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrAllNotNil = fmt.Errorf("All fields had not nil errors")

ErrAllNotNil variable says that backend returned ErrPartial with all fields having not nil values, hence it was converted to ErrFatal.

Only ever returned wrapped in ErrFatal.

View Source
var ErrNotFound = fmt.Errorf("Not found")

ErrNotFound variable represents battery not found error.

Only ever returned wrapped in ErrFatal.

Functions

This section is empty.

Types

type AgnosticState added in v0.11.0

type AgnosticState int8

AgnosticState type enumerates possible battery states, using platform agnostic naming.

const (
	// Undefined specifies a state that was returned by the controller, but there is no
	// platform agnostic mapping for it.
	// This generally shouldn't happen, if it does consider opening a report for the library
	// (ideally with the contents of `State.Explain()` call as well).
	Undefined AgnosticState = -1
	// Unknown specifies a literal unknown state returned by the controller.
	// This state is also considered the "default", therefore it will be set when an Error
	// was returned from the Get/GetAll call.
	Unknown AgnosticState = iota - 1
	Empty
	Full
	Charging
	Discharging
	// Idle specifies a state where battery is in "capacity saving" mode.
	// It usually means that it sits idle at around 80% charge while power source is plugged in.
	Idle
)

func (AgnosticState) String added in v0.11.0

func (s AgnosticState) String() string

type Battery

type Battery struct {
	// Current battery state.
	State State
	// Current (momentary) capacity (in mWh).
	Current float64
	// Last known full capacity (in mWh).
	Full float64
	// Reported design capacity (in mWh).
	Design float64
	// Current (momentary) charge rate (in mW).
	// It is always non-negative, consult .State field to check
	// whether it means charging or discharging.
	ChargeRate float64
	// Current voltage (in V).
	Voltage float64
	// Design voltage (in V).
	// Some systems (e.g. macOS) do not provide a separate
	// value for this. In such cases, or if getting this fails,
	// but getting `Voltage` succeeds, this field will have
	// the same value as `Voltage`, for convenience.
	DesignVoltage float64
}

Battery type represents a single battery entry information.

func Get

func Get(idx int) (*Battery, error)

Get returns battery information for given index.

Note that index taken here is normalized, such that GetAll()[idx] == Get(idx). It does not necessarily represent the "name" or "position" a battery was given by the underlying system.

If error != nil, it will be either ErrFatal or ErrPartial.

Example
battery, err := Get(0)
if err != nil {
	fmt.Println("Could not get battery info")
	return
}

fmt.Printf("Bat%d: ", 0)
fmt.Printf("state: %s, ", battery.State)
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\n", battery.ChargeRate)
Output:

Example (Errors)
_, err := Get(0)
if err == nil {
	fmt.Println("Got battery info")
	return
}

switch perr := err.(type) {
case ErrFatal:
	fmt.Println("Fatal error! No info retrieved")
case ErrPartial:
	if perr.Current != nil {
		fmt.Println("Could not get current battery capacity")
		return
	}

	fmt.Println("Got current battery capacity")
}
Output:

func GetAll

func GetAll() ([]*Battery, error)

GetAll returns information about all batteries in the system.

If error != nil, it will be either ErrFatal or Errors. If error is of type Errors, it is guaranteed that length of both returned slices is the same and that i-th error coresponds with i-th battery structure.

Example
batteries, err := GetAll()
if err != nil {
	fmt.Println("Could not get batteries info")
	return
}

for i, battery := range batteries {
	fmt.Printf("Bat%d: ", i)
	fmt.Printf("state: %s, ", battery.State)
	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\n", battery.ChargeRate)
}
Output:

Example (Errors)
_, err := GetAll()
if err == nil {
	fmt.Println("Got batteries info")
	return
}

switch perr := err.(type) {
case ErrFatal:
	fmt.Println("Fatal error! No info retrieved")
case Errors:
	for i, err := range perr {
		if err != nil {
			fmt.Printf("Could not get battery info for `%d`\n", i)
			continue
		}

		fmt.Printf("Got battery info for `%d`\n", i)
	}
}
Output:

func (*Battery) String

func (b *Battery) String() string

type ErrFatal

type ErrFatal struct {
	Err error // The actual error that happened.
}

ErrFatal type represents a fatal error.

It indicates that either the library was not able to perform some kind of operation critical to retrieving any data, or all partials have failed at once (which would be equivalent to returning a ErrPartial with no nils).

As such, the caller should assume that no meaningful data was returned alongside the error and act accordingly.

func (ErrFatal) Error

func (f ErrFatal) Error() string

type ErrPartial

type ErrPartial struct {
	State         error
	Current       error
	Full          error
	Design        error
	ChargeRate    error
	Voltage       error
	DesignVoltage error
}

ErrPartial type represents a partial error.

It indicates that there were problems retrieving some of the data, but some was also retrieved successfully. If there would be all nils, nil is returned instead. If there would be all not nils, ErrFatal is returned instead.

The fields represent fields in the Battery type.

func (ErrPartial) Error

func (p ErrPartial) Error() string

type Errors

type Errors []error

Errors type represents an array of ErrFatal, ErrPartial or nil values.

Can only possibly be returned by GetAll() call.

func (Errors) Error

func (e Errors) Error() string

type State

type State struct {
	Raw AgnosticState
	// contains filtered or unexported fields
}

func (State) Explain added in v0.11.0

func (s State) Explain() string

func (State) GoString added in v0.11.0

func (s State) GoString() string

func (State) String

func (s State) String() string

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL