-
Notifications
You must be signed in to change notification settings - Fork 3
/
acpi-listener
executable file
·93 lines (70 loc) · 2.01 KB
/
acpi-listener
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
#!/usr/bin/env python3
import os
import socket
import subprocess
import stat
import syslog
import time
DEBUG = True
SOCKET_PATH = '/tmp/acpi.sock'
COMMANDS = ('xrandr-setup', 'hello')
def log( level, msg, *parts):
syslog.syslog(level, msg % parts)
def debug( msg, *parts):
if DEBUG:
log(syslog.LOG_DEBUG, msg, *parts)
class ACPIListener:
def __init__(self, path, hooks):
self.path = path
self.event_hooks = hooks
if os.path.exists(self.path):
os.remove(self.path)
self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
self.socket.bind(self.path)
os.chmod(self.path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP | stat.S_IROTH | stat.S_IWOTH)
def serve_forever(self):
with self.socket as sock:
sock.listen(1)
while True:
connection, client_address = sock.accept()
buff = []
data = connection.recv(1024)
if data:
self.handle(data.decode())
connection.sendall( b'recieved: %s' % data )
def handle(self, event):
if not event:
return
if event in self.event_hooks:
self.event_hooks[self.event_hooks.index(event)](event)
debug( 'handled event: %s', event )
else:
debug('event %s not handled', event)
class Hook:
name = None
command = 'echo no command'
def __call__(self, event_):
self.do_action()
debug('Hook: %s', self.name)
def do_action(self):
process = subprocess.Popen(self.command, stderr=subprocess.PIPE, stdout=subprocess.PIPE)
try:
stdout, stderr = process.communicate()
except subprocess.CalledProcessError as err:
stdout = err.output
stderr = -1
debug('Command: %s\nSTDOUT: %s\nSTDERR: %s', self.command, stdout, stderr)
def __eq__(self, event):
return self.name in event
class Lid(Hook):
name = 'button/lid LID'
command = '/usr/local/bin/xrandr-setup'
class Dock(Hook):
name = 'docked'
command = '/usr/local/bin/xrandr-setup'
def __call__(self, event):
time.sleep(1)
super().__call__(event)
if __name__ == '__main__':
server = ACPIListener(SOCKET_PATH, [Lid(), Dock()])
server.serve_forever()