summaryrefslogtreecommitdiffstats
path: root/vendor/github.com/cjbassi/battery/battery_openbsd.go
blob: 13f70d727af56c7feeb3967793e5835569dd5486 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
// battery
// Copyright (C) 2016-2017 Karol 'Kenji Takahashi' Woźniak
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE
// OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

package battery

import (
	"bytes"
	"fmt"
	"strings"
	"syscall"
	"unsafe"

	"golang.org/x/sys/unix"
)

var errValueNotFound = fmt.Errorf("Value not found")

var sensorW = [4]int32{
	2,  // SENSOR_VOLTS_DC (uV)
	5,  // SENSOR_WATTS (uW)
	7,  // SENSOR_WATTHOUR (uWh)
	10, // SENSOR_INTEGER
}

const (
	sensorA  = 6 // SENSOR_AMPS (uA)
	sensorAH = 8 // SENSOR_AMPHOUR (uAh)
)

type sensordev struct {
	num           int32
	xname         [16]byte
	maxnumt       [21]int32
	sensors_count int32
}

type sensorStatus int32

const (
	unspecified sensorStatus = iota
	ok
	warning
	critical
	unknown
)

type sensor struct {
	desc   [32]byte
	tv     [16]byte // struct timeval
	value  int64
	typ    [4]byte // enum sensor_type
	status sensorStatus
	numt   int32
	flags  int32
}

type interValue struct {
	v *float64
	s *State
	e *error
}

func sysctl(mib []int32, out unsafe.Pointer, n uintptr) syscall.Errno {
	_, _, e := unix.Syscall6(
		unix.SYS___SYSCTL,
		uintptr(unsafe.Pointer(&mib[0])),
		uintptr(len(mib)),
		uintptr(out),
		uintptr(unsafe.Pointer(&n)),
		uintptr(unsafe.Pointer(nil)),
		0,
	)
	return e
}

func readValue(s sensor, div float64) (float64, error) {
	if s.status == unknown {
		return 0, fmt.Errorf("Unknown value received")
	}

	return float64(s.value) / div, nil
}

func readValues(mib []int32, c int32, values map[string]*interValue) {
	var s sensor
	var i int32
	for i = 0; i < c; i++ {
		mib[4] = i

		if err := sysctl(mib, unsafe.Pointer(&s), unsafe.Sizeof(s)); err != 0 {
			for _, value := range values {
				if *value.e == errValueNotFound {
					*value.e = err
				}
			}
		}

		desc := string(s.desc[:bytes.IndexByte(s.desc[:], 0)])
		isState := strings.HasPrefix(desc, "battery ")

		var value *interValue
		var ok bool

		if isState {
			value, ok = values["state"]
		} else {
			value, ok = values[desc]
		}
		if !ok {
			continue
		}

		if isState {
			//TODO:battery idle(?)
			if desc == "battery critical" {
				*value.s, *value.e = Empty, nil
			} else {
				*value.s, *value.e = newState(desc[8:])
			}
			continue
		}

		if strings.HasSuffix(desc, "voltage") {
			*value.v, *value.e = readValue(s, 1000000)
		} else {
			*value.v, *value.e = readValue(s, 1000)
		}
	}
}

func sensordevIter(cb func(sd sensordev, i int, err error) bool) {
	mib := []int32{6, 11, 0}
	var sd sensordev
	var idx int
	var i int32
	for i = 0; ; i++ {
		mib[2] = i

		e := sysctl(mib, unsafe.Pointer(&sd), unsafe.Sizeof(sd))
		if e != 0 {
			if e == unix.ENXIO {
				continue
			}
			if e == unix.ENOENT {
				break
			}
		}

		if bytes.HasPrefix(sd.xname[:], []byte("acpibat")) {
			var err error
			if e != 0 {
				err = e
			}
			if cb(sd, idx, err) {
				return
			}
			idx++
		}
	}
}

func getBattery(sd sensordev) (*Battery, error) {
	b := &Battery{}
	e := ErrPartial{
		Design:        errValueNotFound,
		Full:          errValueNotFound,
		Current:       errValueNotFound,
		ChargeRate:    errValueNotFound,
		State:         errValueNotFound,
		Voltage:       errValueNotFound,
		DesignVoltage: errValueNotFound,
	}

	mib := []int32{6, 11, sd.num, 0, 0}
	for _, w := range sensorW {
		mib[3] = w

		readValues(mib, sd.maxnumt[w], map[string]*interValue{
			"rate":               {v: &b.ChargeRate, e: &e.ChargeRate},
			"design capacity":    {v: &b.Design, e: &e.Design},
			"last full capacity": {v: &b.Full, e: &e.Full},
			"remaining capacity": {v: &b.Current, e: &e.Current},
			"current voltage":    {v: &b.Voltage, e: &e.Voltage},
			"voltage":            {v: &b.DesignVoltage, e: &e.DesignVoltage},
			"state":              {s: &b.State, e: &e.State},
		})
	}

	if e.DesignVoltage != nil && e.Voltage == nil {
		b.DesignVoltage, e.DesignVoltage = b.Voltage, nil
	}

	if e.ChargeRate == errValueNotFound {
		if e.Voltage == nil {
			mib[3] = sensorA

			readValues(mib, sd.maxnumt[sensorA], map[string]*interValue{
				"rate": {v: &b.ChargeRate, e: &e.ChargeRate},
			})

			b.ChargeRate *= b.Voltage
		} else {
			e.ChargeRate = e.Voltage
		}
	}
	if e.Design == errValueNotFound || e.Full == errValueNotFound || e.Current == errValueNotFound {
		mib[3] = sensorAH

		readValues(mib, sd.maxnumt[sensorAH], map[string]*interValue{
			"design capacity":    {v: &b.Design, e: &e.Design},
			"last full capacity": {v: &b.Full, e: &e.Full},
			"remaining capacity": {v: &b.Current, e: &e.Current},
		})

		b.Design *= b.DesignVoltage
		b.Full *= b.Voltage
		b.Current *= b.Voltage
	}

	return b, e
}

func systemGet(idx int) (*Battery, error) {
	var b *Battery
	var e error

	sensordevIter(func(sd sensordev, i int, err error) bool {
		if i == idx {
			if err == nil {
				b, e = getBattery(sd)
			} else {
				e = err
			}