-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbattery_status
executable file
·302 lines (252 loc) · 8.81 KB
/
battery_status
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
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Battery status viewer
# Show battery status (% full, remaining time, ...)
# for a battery.
# Currently GNU/Linux only!
#
# Copyright (c) 2016 Malte Bublitz
# All rights reserved
#
# For the details on the values read from
# /sys/class/power_supply/BAT0, see:
# <https://www.kernel.org/doc/Documentation/power/power_supply_class.txt>
#
# The always-needed
import os
import sys
# For platform detection
import OSDetect
# To round percent value to 2 decimal places only
from math import ceil
# Constants
OUTPUT_MODE_HUMANREADABLE = 0
OUTPUT_MODE_EVERYTHING = 1
OUTPUT_MODE_VALUE = 2
class PlatformNotSupportedException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class NoBatteryFoundException(Exception):
def __init__(self, value):
self.value = value
def __str__(self):
return repr(self.value)
class Battery(object):
currentOS = ""
_now = 0
_full = 0
_power = 0
_hours_remaining = 1.0
_percent = 0
_isCharging = False
_isDischarging = False
def __init__(self):
self.currentOS = OSDetect.info.get("OS")
if self.currentOS != "Linux":
raise PlatformNotSupportedException("Only Linux supported")
if not self.checkBatteryIsAvailable():
raise NoBatteryFoundException("No Battery found!")
self.readInfo()
def checkBatteryIsAvailable(self):
isAvailable = False
if self.currentOS == "Linux":
isAvailable = os.path.exists(
"/sys/class/power_supply/BAT0"
)
return isAvailable
def readInfoLinux(self):
dname_bat0 = "/sys/class/power_supply/BAT0"
fname_status = os.path.join(dname_bat0, "status")
fname_now = os.path.join(dname_bat0, "energy_now")
fname_full = os.path.join(dname_bat0, "energy_full")
fname_power = os.path.join(dname_bat0, "power_now")
try:
self._now = int(open(fname_now).read())
self._full = int(open(fname_full).read())
self._power = int(open(fname_power).read())
if self._power > 1:
self._hours_remaining = round(float(self._now)/float(self._power), 2)
else:
self._hours_remaining = 0.0
status = open(fname_status).read().strip()
self._isCharging = (status == "Charging")
self._isDischarging = (status == "Discharging")
except IOError as e:
if not os.path.exists("/sys"):
print("sysfs doesn't seem to be mounted...", file=sys.stderr)
print("On modern kernels, you might want to try:", file=sys.stderr)
print(" mount -t sysfs sys /sys", file=sys.stderr)
elif not os.path.exists(dname_bat0):
print("Can't find Battery 0 in /sys.", file=sys.stderr)
print("I expected a directory named "+dname_bat0+", but it doesn't exist.", file=sys.stderr)
print("Are you sure you have a battery in your computer and/or aren't on a", file=sys.stderr)
print("Desktop PC system without a battery?", file=sys.stderr)
else:
print("Error while trying to read battery status from /sys:")
print(e)
sys.exit(2)
self._percent = ceil(float(self._now)/float(self._full)*10000)/100
def readInfoLinux4(self):
dname_bat0 = "/sys/class/power_supply/BAT0"
fname_status = os.path.join(dname_bat0, "status")
fname_now = os.path.join(dname_bat0, "charge_now")
fname_full = os.path.join(dname_bat0, "charge_full")
fname_current = os.path.join(dname_bat0, "current_now")
try:
self._now = int(open(fname_now).read())
self._full = int(open(fname_full).read())
self._percent = ceil(float(self._now)/float(self._full)*100)
self._current = int(open(fname_current).read())
if self._current > 1:
self._hours_remaining = round(float(self._now)/float(self._current), 2)
else:
self._hours_remaining = 0.0
status = open(fname_status).read().strip()
self._isCharging = (status == "Charging")
self._isDischarging = (status == "Discharging")
except:
pass
def readInfo(self):
if self.currentOS == "Linux" and int(OSDetect.info.get("OSVersion").split(".")[0]) >= 4:
self.currentOS = "Linux4"
if self.currentOS == "Linux":
self.readInfoLinux()
elif self.currentOS == "Linux4":
self.readInfoLinux4()
# No else required; on unsupported systems
# __init__ raises an PlatformNotSupportedException
# before calling this function
def getChargedCurrent(self):
return self._now
def getChargedFull(self):
return self._full
def getChargedPercent(self):
return self._percent
def getPowerNow(self):
return self._power
def getCurrentNow(self):
return self._current
def getHoursRemaining(self):
return self._hours_remaining
def getIsCharging(self):
return self._isCharging
def getIsDischarging(self):
return self._isDischarging
class BatteryStatus(object):
APP_NAME = ""
APP_VERSION = ""
APP_SCRIPTNAME = ""
APP_PROJECT = ""
APP_URL = ""
APP_COPYRIGHT = ""
def __init__(self):
self.APP_NAME = "battery_status"
self.APP_VERSION = "0.20160713"
self.APP_SCRIPTNAME = os.path.basename(sys.argv[0])
self.APP_PROJECT = "malte70's scripts"
self.APP_URL = "https://github.com/malte70/scripts"
self.APP_COPYRIGHT = "Copyright (c) 2016 Malte Bublitz"
def showVersion(self):
print(self.APP_NAME + " " + self.APP_VERSION)
print(self.APP_COPYRIGHT)
print("")
print("Part of " + self.APP_PROJECT)
print(" Github: <" + self.APP_URL + ">")
def showHelp(self):
print("Usage: " + self.APP_SCRIPTNAME + " [options]")
print("Options:")
print("\t-h, --help Display this usage help")
print("\t-V, --version Display version and copyright")
print("\t-v, --verbose Verbose output (easily parsable)")
def run(self, outputMode, outputValue):
b = Battery()
output = []
remainingHours = int(b.getHoursRemaining())
remainingMinutes = int((b.getHoursRemaining()-remainingHours)*60)
remainingTenMinutes = int(remainingMinutes/10)*10
if outputMode == OUTPUT_MODE_EVERYTHING:
output.append("IS_CHARGING = " + str(b.getIsCharging()))
output.append("CAPACITY_CURRENT = " + str(b.getChargedCurrent()))
output.append("CAPACITY_FULL = " + str(b.getChargedFull()))
output.append("CAPACITY_PERCENT = " + str(b.getChargedPercent()))
output.append("HOURS_REMAINING = " + str(remainingHours))
output.append("MINUTES_REMAINING = " + str(remainingMinutes))
output.append("TEN_MINUTES_REMAINING = " + str(remainingTenMinutes))
elif outputMode == OUTPUT_MODE_VALUE:
outputValue = outputValue.upper()
if outputValue == "IS_CHARGING":
output.append(str(b.getIsCharging()))
elif outputValue == "CAPACITY_CURRENT":
output.append(str(b.getChargedCurrent()))
elif outputValue == "CAPACITY_FULL":
output.append(str(b.getChargedFull()))
elif outputValue == "CAPACITY_PERCENT":
output.append(str(b.getChargedPercent()))
elif outputValue == "HOURS_REMAINING":
output.append(str(remainingHours))
elif outputValue == "MINUTES_REMAINING":
output.append(str(remainingMinutes))
elif outputValue == "TEN_MINUTES_REMAINING":
output.append(str(remainingTenMinutes))
else:
print("Unknown value " + outputValue + ". Use one of the keys in", file=sys.stderr)
print(" " + self.APP_SCRIPTNAME + " -v", file=sys.stderr)
self.exit(1)
elif outputMode == OUTPUT_MODE_HUMANREADABLE:
msg = "Battery is "
msg += str(ceil(b.getChargedPercent()))
msg += " % charged, currently "
if not b.getIsCharging():
msg += "not "
msg += "charging."
output.append(msg)
if b.getIsDischarging():
msg = "Approx. "
if remainingHours > 0:
msg += str(remainingHours)
msg += " hours"
if remainingHours > 0 and remainingTenMinutes > 0:
msg += " and "
if remainingTenMinutes > 0:
msg += str(remainingTenMinutes)
msg += " minutes"
msg += " remaining."
else:
msg = "Under 10 minutes remaining!"
output.append(msg)
for l in output:
print(l)
def exitUnknownVersion(self, option):
print(self.APP_SCRIPTNAME + ": Error: Unknown option " + option)
self.exit(1)
def exit(self, code = 0):
sys.exit(code)
def main():
# Create application object
app = BatteryStatus()
outputMode = OUTPUT_MODE_HUMANREADABLE
outputValue = ""
if len(sys.argv) >= 2:
if sys.argv[1] in ("-v","--verbose"):
outputMode = OUTPUT_MODE_EVERYTHING
elif sys.argv[1] in ("-g","--get"):
outputMode = OUTPUT_MODE_VALUE
outputValue = sys.argv[2]
elif sys.argv[1] in ("-h","--help"):
app.showHelp()
app.exit()
elif sys.argv[1] in ("-V", "--version"):
app.showVersion()
app.exit()
else:
app.exitUnknownVersion(sys.argv[1])
# Run the application
app.run(
outputMode,
outputValue
)
if __name__ == "__main__":
main()