-
Notifications
You must be signed in to change notification settings - Fork 33
/
power
executable file
·245 lines (219 loc) · 8.04 KB
/
power
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
#!/usr/bin/env python3
import os, sys, select, time, signal, subprocess as sp
import pyudev
### Example systemd unit file:
#
# ### NOTE: only suitable as a systemd --user unit!
#
# [Service]
# ExecStart=/usr/local/bin/notify-power
#
# [Install]
# WantedBy=default.target
#
# ### Optional udev start rule:
# # SUBSYSTEM=="power_supply", TAG+="systemd", \
# # ENV{SYSTEMD_USER_WANTS}="notify-power.service"
def get_dbus_notify_func(**defaults):
import ctypes as ct
class sd_bus(ct.Structure): pass
class sd_bus_error(ct.Structure):
_fields_ = [('name', ct.c_char_p), ('message', ct.c_char_p), ('need_free', ct.c_int)]
class sd_bus_msg(ct.Structure): pass
lib = ct.CDLL('libsystemd.so')
def run(call, *args, sig=None, check=True):
func = getattr(lib, call)
if sig: func.argtypes = sig
res = func(*args)
if check and res < 0: raise OSError(-res, os.strerror(-res))
return res
bus, error, reply = (
ct.POINTER(sd_bus)(), sd_bus_error(), ct.POINTER(sd_bus_msg)() )
kws, defaults = defaults, dict(
app='', replaces_id=0, icon='',
summary='', body='', actions=None, hints=None, timeout=-1 )
for k in defaults:
if k in kws: defaults[k] = kws.pop(k)
assert not kws, kws
bb = lambda v: v.encode() if isinstance(v, str) else v
def encode_array(k, v):
if not v: sig, args = [ct.c_void_p], [None]
elif k == 'actions':
sig, args = [ct.c_int, [ct.c_char_p] * len(v)], [len(v), *map(bb, v)]
elif k == 'hints':
sig, args = [ct.c_int], [len(v)]
for ak, av in v.items():
sig.extend([ct.c_char_p, ct.c_char_p]) # key, type
args.append(bb(ak))
if isinstance(av, (str, bytes)):
av_sig, av_args = [ct.c_char_p], [b's', bb(av)]
elif isinstance(av, int): av_sig, av_args = [ct.c_int32], [b'i', av]
else: av_sig, av_args = av
args.extend(av_args)
sig.extend(av_sig)
else: raise ValueError(k)
return sig, args
def notify_func(
summary=None, body=None, app=None, icon=None,
replaces_id=None, actions=None, hints=None, timeout=None ):
args, kws, sig_arrays = list(), locals(), list()
for k, default in defaults.items():
v = kws.get(k)
if v is None: v = default
if k in ['actions', 'hints']:
arr_sig, arr_args = encode_array(k, v)
sig_arrays.extend(arr_sig)
args.extend(arr_args)
else: args.append(bb(v))
run( 'sd_bus_open_user', ct.byref(bus),
sig=[ct.POINTER(ct.POINTER(sd_bus))] )
try:
run( 'sd_bus_call_method',
bus,
b'org.freedesktop.Notifications', # dst
b'/org/freedesktop/Notifications', # path
b'org.freedesktop.Notifications', # iface
b'Notify', # method
ct.byref(error),
ct.byref(reply),
b'susssasa{sv}i', *args,
sig=[
ct.POINTER(sd_bus),
ct.c_char_p, ct.c_char_p, ct.c_char_p, ct.c_char_p,
ct.POINTER(sd_bus_error),
ct.POINTER(ct.POINTER(sd_bus_msg)),
ct.c_char_p,
ct.c_char_p, ct.c_uint32,
ct.c_char_p, ct.c_char_p, ct.c_char_p,
*sig_arrays, ct.c_int32 ] )
note_id = ct.c_uint32()
n = run( 'sd_bus_message_read', reply, b'u', ct.byref(note_id),
sig=[ct.POINTER(sd_bus_msg), ct.c_char_p, ct.POINTER(ct.c_uint32)] )
assert n > 0, n
finally: run('sd_bus_flush_close_unref', bus, check=False)
return note_id.value
return notify_func
class PowerMonitor:
notify_opts = dict(icon='nwn', timeout=0, app='power', hints=dict(urgency=2))
notify_cmd = None
# notify_cmd = ( 'notify-net -d 0.0.0.0:8158'
# ' -u critical -t0 -i nwn -n power -s' ).split()
udev = udev_mon = poller = notify_func = None
def __init__(self, debounce_delay=1.0, unplugged_repeat=0):
self.debounce_delay, self.unplugged_repeat = debounce_delay, unplugged_repeat
def __enter__(self):
self.open()
return self
def __exit__(self, *err): self.close()
def __del__(self): self.close()
def open(self):
self.udev = pyudev.Context()
self.udev_mon = pyudev.Monitor.from_netlink(self.udev)
self.udev_mon.filter_by(subsystem='power_supply')
self.poller, self.poller_hooks = select.epoll(), dict()
for pipe, hook in [(self.udev_mon, self.udev_event)]:
fd = pipe.fileno()
self.poller.register(fd, select.EPOLLIN)
self.poller_hooks[fd] = hook
self.udev_mon.start()
if self.notify_opts or not self.notify_cmd:
self.notify_func = get_dbus_notify_func(**(self.notify_opts or dict()))
self.plugged_init = self.plugged = self.ts_notify = None
self.power_percent = None
def close(self):
if self.notify_func: self.notify_func = None
if self.poller: self.poller = self.poller.close()
if self.udev_mon: self.udev_mon = None
if self.udev: self.udev = None
def run(self):
err_mask = select.EPOLLHUP | select.EPOLLERR
while True:
ts = time.monotonic()
if self.ts_notify:
poll_time = max(0, self.ts_notify - ts)
if poll_time <= 0:
self.notify()
continue
else: poll_time = 2**30
if self.unplugged_repeat > 0:
poll_time = min(self.unplugged_repeat, poll_time)
ev_list = self.poller.poll(poll_time)
if ev_list:
for fd, ev in ev_list:
if ev & err_mask != 0: return
self.poller_hooks[fd]()
elif not self.ts_notify: self.force_unplugged_check()
def udev_handle(self, dev):
plugged = None
# dev_info = dict( (k, getattr(dev, k)) for k in
# 'sys_name device_path driver device_type device_node'.split() )
# print(f'--- dev [{dev.action}]: {dev_info}')
# for k, v in dev.items(): print(f' {k} {v!r}')
if dev.sys_name.startswith('ADP'):
status = dev.get('POWER_SUPPLY_ONLINE')
if status: plugged = bool(int(status))
elif dev.sys_name.startswith('BAT'):
pw = dev.get('POWER_SUPPLY_CAPACITY')
if pw: self.power_percent = float(pw)
# status = dev.get('POWER_SUPPLY_STATUS')
# if not status: return
# plugged = status.lower() in ['charging', 'full']
return plugged
def udev_event(self):
ev, dev = self.udev_mon.receive_device()
plugged = self.udev_handle(dev)
if plugged is None or plugged == self.plugged: return
if not self.ts_notify: self.plugged_init = self.plugged
self.ts_notify = time.monotonic() + self.debounce_delay
self.plugged = plugged
def force_unplugged_check(self):
for dev in self.udev.list_devices(subsystem='power_supply'):
plugged = self.udev_handle(dev)
if plugged is not False: continue
self.plugged_init = self.plugged = plugged
self.notify(force=True)
def notify(self, force=False):
if force or self.plugged_init != self.plugged:
state_head = ( 'online' if self.plugged else
'<span color="red">UNPLUGGED</span>' )
state_head = f'Charger state: {state_head}'
state_body = ( f'{self.power_percent:.0f}%'
if self.power_percent is not None else 'unknown' )
state_body = f'Battery state: <b>{state_body}</b>'
if self.notify_cmd:
cmd = self.notify_cmd.copy()
cmd.append(state_head)
cmd = sp.run(cmd, input=state_body)
if cmd.returnstatus:
print( f'ERROR: notification cmd exited'
f' with code {cmd.returnstatus}', file=sys.stderr )
if self.notify_func: self.notify_func(state_head, state_body)
self.ts_notify = None
def main(args=None):
import argparse
parser = argparse.ArgumentParser(
description='Notification script for power supply events.')
parser.add_argument('-t', '--debounce-delay',
type=float, metavar='seconds', default=2.0,
help='Time to wait for any follow-up changes before issuing notification.')
parser.add_argument('-r', '--unplugged-repeat',
type=float, metavar='seconds', default=113.0,
help='Check/repeat "unplugged" warnings with specified interval.'
' Use values <=0 to disable. Default: %(default)s')
parser.add_argument('--print-systemd-unit', action='store_true',
help='Print example systemd unit file to stdout and exit.')
opts = parser.parse_args(sys.argv[1:] if args is None else args)
if opts.print_systemd_unit:
import re
with open(__file__) as src:
echo = False
for line in iter(src.readline, ''):
if echo: print(re.sub(r'^#+\s*', '', line.strip()))
if re.search('^### Example systemd unit file:', line):
echo = True
continue
elif echo and not line.strip(): return
with PowerMonitor(opts.debounce_delay, opts.unplugged_repeat) as app: app.run()
if __name__ == '__main__':
signal.signal(signal.SIGINT, signal.SIG_DFL)
sys.exit(main())