-
Notifications
You must be signed in to change notification settings - Fork 124
Expand file tree
/
Copy pathDisplaySwitch.py
More file actions
53 lines (40 loc) · 1.58 KB
/
DisplaySwitch.py
File metadata and controls
53 lines (40 loc) · 1.58 KB
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
# An Accessory for viewing/controlling the status of a Mac display.
import asyncio
import subprocess
from pyhap.accessory import Accessory, Category
import pyhap.loader as loader
def get_display_state():
result = subprocess.check_output(['pmset', '-g', 'powerstate', 'IODisplayWrangler'])
return int(result.strip().split(b'\n')[-1].split()[1]) >= 4
def set_display_state(state):
if state:
subprocess.call(['caffeinate', '-u', '-t', '1'])
else:
subprocess.call(['pmset', 'displaysleepnow'])
class DisplaySwitch(Accessory):
"""
An accessory that will display, and allow setting, the display status
of the Mac that this code is running on.
"""
category = Category.SWITCH
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.display = self.get_service("Switch")\
.get_characteristic("On")
self.display.setter_callback = self.set_display
def _set_services(self):
super()._set_services()
self.add_service(
loader.get_serv_loader().get("Switch"))
async def run(self, stop_event, loop=None):
while not stop_event.is_set():
await asyncio.sleep(1)
# We can't just use .set_value(state), because that will
# trigger our listener.
state = get_display_state()
if self.display.value != state:
self.display.value = state
self.display.notify()
def set_display(self, state):
if get_display_state() != state:
set_display_state(state)