Add bluetooth device battery module

This commit is contained in:
akp 2024-05-10 15:41:27 +01:00
parent a4a91801ee
commit 4749cf4e38
No known key found for this signature in database
GPG key ID: CF8D58F3DEB20755
3 changed files with 96 additions and 6 deletions

View file

@ -51,6 +51,7 @@ func run() error {
providers.NewMemory(7, 5),
providers.NewCPU(20, 50),
providers.NewDisk("/", 30, 10),
providers.NewBluetoothBattery(80, 30, 20),
providers.NewBattery("BAT0", 80, 30, 20),
providers.NewWiFi("wlp0s20f3", 75),
providers.NewIPAddress("wlp0s20f3"),

View file

@ -131,12 +131,12 @@ func (b *I3bar) tick(override bool) error {
TextColor: defaultColorSet.Bad,
}
}
if block == nil {
block = &Block{
FullText: "MISSING",
TextColor: defaultColorSet.Warning,
}
}
// if block == nil {
// block = &Block{
// FullText: "MISSING",
// TextColor: defaultColorSet.Warning,
// }
// }
if block != gen.Last {
gen.Last = block

View file

@ -0,0 +1,89 @@
package providers
import (
"bytes"
"fmt"
"strconv"
"github.com/codemicro/bar/internal/i3bar"
)
type BluetoothBattery struct {
FullThreshold float32
OkThreshold float32
WarningThreshold float32
name string
previousWasBackgroundWarning bool
isAlert bool
}
func NewBluetoothBattery(fullThreshold, okThreshold, warningThreshold float32) i3bar.BlockGenerator {
return &BluetoothBattery{
FullThreshold: fullThreshold,
OkThreshold: okThreshold,
WarningThreshold: warningThreshold,
name: "btbattery",
}
}
func (g *BluetoothBattery) Frequency() uint8 {
if g.isAlert {
return 1
}
return 5
}
type btBatteryState struct {
DeviceName string
Percentage uint
}
func (g *BluetoothBattery) getDevicePercentage() (*btBatteryState, error) {
rawInfo, err := runCommand("bluetoothctl", "info")
if err != nil {
return nil, nil
}
s := new(btBatteryState)
for i, line := range bytes.Split(rawInfo, []byte("\n")) {
if i != 0 && !bytes.HasPrefix(line, []byte{'\t'}) {
break
}
if bytes.HasPrefix(line, []byte("\tName:")) {
s.DeviceName = string(bytes.TrimPrefix(line, []byte("\tName: ")))
} else if bytes.HasPrefix(line, []byte("\tBattery Percentage:")) {
b := bytes.TrimPrefix(bytes.Fields(bytes.TrimPrefix(line, []byte("\tBattery Percentage: ")))[0], []byte("0x"))
ui, err := strconv.ParseUint(string(b), 16, 8)
if err != nil {
return nil, err
}
s.Percentage = uint(ui)
}
}
return s, nil
}
func (g *BluetoothBattery) Block(colors *i3bar.ColorSet) (*i3bar.Block, error) {
percentage, err := g.getDevicePercentage()
if err != nil {
return nil, err
}
if percentage == nil {
return nil, nil
}
return &i3bar.Block{
Name: g.name,
Instance: percentage.DeviceName,
FullText: fmt.Sprintf("BT BAT %d%%", percentage.Percentage),
ShortText: fmt.Sprintf("BT %d%%", percentage.Percentage),
}, nil
}
func (g *BluetoothBattery) GetNameAndInstance() (string, string) {
return g.name, ""
}