github.com/Code-Hex/battery@v1.0.0/internal/macos/battery.go (about)

     1  //go:build darwin
     2  
     3  package macOS
     4  
     5  import (
     6  	"errors"
     7  )
     8  
     9  type Status struct {
    10  	Percentage int
    11  	Elapsed    int
    12  	State      string
    13  }
    14  
    15  func Battery() (*Status, error) {
    16  	powerInfo, err := IOPSCopyPowerSourcesInfo()
    17  	if err != nil {
    18  		return nil, err
    19  	}
    20  	defer CFRelease(powerInfo)
    21  
    22  	powerSrcList, err := IOPSCopyPowerSourcesList(powerInfo)
    23  	if err != nil {
    24  		return nil, err
    25  	}
    26  	defer CFRelease(powerSrcList)
    27  
    28  	powerSrcNum := CFArrayGetCount(powerSrcList)
    29  	if powerSrcNum == 0 {
    30  		return nil, errors.New("could not get power resource infomation")
    31  	}
    32  
    33  	powerSrcInfo, err := IOPSGetPowerSourceDescription(
    34  		powerInfo,
    35  		CFArrayGetValueAtIndex(powerSrcList, 0),
    36  	)
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  
    41  	percentageRef, ok := CFDictionaryGetValueIfPresent(powerSrcInfo, IOPSCurrentCapacityKey)
    42  	if !ok {
    43  		return nil, errors.New("not found IOPSCurrentCapacityKey")
    44  	}
    45  	percentage, err := CFNumberGetValue(percentageRef)
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  
    50  	elapsedRef, ok := CFDictionaryGetValueIfPresent(powerSrcInfo, IOPSTimeToEmptyKey)
    51  	if !ok {
    52  		return nil, errors.New("not found IOPSTimeToEmptyKey")
    53  	}
    54  	elapsed, err := CFNumberGetValue(elapsedRef)
    55  	if err != nil {
    56  		return nil, err
    57  	}
    58  
    59  	powerStateRef, ok := CFDictionaryGetValueIfPresent(powerSrcInfo, IOPSPowerSourceStateKey)
    60  	if !ok {
    61  		return nil, errors.New("not found IOPSPowerSourceStateKey")
    62  	}
    63  	powerState := CFStringToString(powerStateRef)
    64  
    65  	return &Status{
    66  		Percentage: int(percentage),
    67  		Elapsed:    int(elapsed),
    68  		State:      powerState,
    69  	}, nil
    70  }