forked from warvariuc/acdcontrol
-
Notifications
You must be signed in to change notification settings - Fork 1
/
acdcontrol.py
executable file
·301 lines (240 loc) · 10.6 KB
/
acdcontrol.py
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
#! /usr/bin/env python3
"""This program allows changing brightness on some Apple displays.
"""
__author__ = 'Victor Varvariuc <[email protected]>'
import argparse
import struct
import ctypes
import fcntl
import os
import sys
from collections import OrderedDict
import ioctl
SUPPORTED_DEVICES = {
(0x05ac, 'Apple'): (
# prod id, name, (min brightness, max brightness) or None if unknown
(0x9215, 'Apple Studio Display 15"', None),
(0x9217, 'Apple Studio Display 17"', None),
(0x9218, 'Apple Cinema Display 23"', None),
(0x9219, 'Apple Cinema Display 20"', None),
(0x921e, 'Apple Cinema Display 24"', None),
(0x9226, 'Apple Cinema HD Display 27"', None),
(0x9227, 'Apple Cinema HD Display 27" 2013', None),
(0x9232, 'Apple Cinema HD Display 30"', None),
(0x9236, 'Apple LED Cinema Display 24"', (0, 255)),
),
(0x0419, 'Samsung Electronics'): (
(0x8002, 'Samsung SyncMaster 757NF'),
),
}
# -------------------------------------------------------------------------------------------------
class StructMeta(type(ctypes.Structure)):
@classmethod
def __prepare__(metacls, cls_name, cls_bases):
"""Use this ordered dict as class dictionary during class definition.
"""
return OrderedDict()
def __new__(metacls, cls_name, cls_bases, cls_dict):
fields = []
for field_name, field in list(cls_dict.items()):
if isinstance(field, type) and issubclass(field, ctypes._SimpleCData):
fields.append((field_name, field))
del cls_dict[field_name]
cls_dict['_fields_'] = fields
result = super(StructMeta, metacls).__new__(
metacls, cls_name, cls_bases, dict(cls_dict))
return result
def __len__(self):
"""Byte length."""
_format = ''.join(field[1]._type_ for field in self._fields_)
return struct.calcsize(_format)
class Struct(ctypes.Structure, metaclass=StructMeta):
def __repr__(self):
values = []
for field_name, _ in self._fields_:
value = getattr(self, field_name)
value = hex(value) if isinstance(value, int) else repr(value)
values.append('%s=%s' % (field_name, value))
return '%s(%s)' % (self.__class__.__name__, ', '.join(values))
# /usr/src/linux-headers-3.11.0-14/include/uapi/linux/hiddev.h
# -------------------------------------------------------------------------------------------------
# Structures
class hid_version(Struct):
v3 = ctypes.c_ubyte
v2 = ctypes.c_ubyte
v1 = ctypes.c_ushort
class hiddev_devinfo(Struct):
bustype = ctypes.c_uint
busnum = ctypes.c_uint
devnum = ctypes.c_uint
ifnum = ctypes.c_uint
vendor = ctypes.c_ushort
product = ctypes.c_ushort
version = ctypes.c_ushort
num_applications = ctypes.c_uint
class hiddev_usage_ref(Struct):
report_type = ctypes.c_uint
report_id = ctypes.c_uint
field_index = ctypes.c_uint
usage_index = ctypes.c_uint
usage_code = ctypes.c_uint
value = ctypes.c_int
class hiddev_report_info(Struct):
report_type = ctypes.c_uint
report_id = ctypes.c_uint
num_fields = ctypes.c_uint
HID_REPORT_ID_UNKNOWN = 0xffffffff
HID_REPORT_ID_FIRST = 0x00000100
HID_REPORT_ID_NEXT = 0x00000200
HID_REPORT_ID_MASK = 0x000000ff
HID_REPORT_ID_MAX = 0x000000ff
HID_REPORT_TYPE_INPUT = 1
HID_REPORT_TYPE_OUTPUT = 2
HID_REPORT_TYPE_FEATURE = 3
HID_REPORT_TYPE_MIN = 1
HID_REPORT_TYPE_MAX = 3
# -------------------------------------------------------------------------------------------------
# IOCTLs (0x00 - 0x7f)
HIDIOCGVERSION = ioctl.IOR(ord('H'), 0x01, len(hid_version))
HIDIOCAPPLICATION = ioctl.IO(ord('H'), 0x02)
HIDIOCGDEVINFO = ioctl.IOR(ord('H'), 0x03, len(hiddev_devinfo))
# HIDIOCGSTRING = ioctl.IOR(ord('H'), 0x04, len(hiddev_string_descriptor))
HIDIOCINITREPORT = ioctl.IO(ord('H'), 0x05)
# HIDIOCGNAME(len) _IOC(_IOC_READ, 'H', 0x06, len)
HIDIOCGREPORT = ioctl.IOW(ord('H'), 0x07, len(hiddev_report_info))
HIDIOCSREPORT = ioctl.IOW(ord('H'), 0x08, len(hiddev_report_info))
HIDIOCGREPORTINFO = ioctl.IOWR(ord('H'), 0x09, len(hiddev_report_info))
# HIDIOCGFIELDINFO _IOWR('H', 0x0A, struct hiddev_field_info)
HIDIOCGUSAGE = ioctl.IOWR(ord('H'), 0x0B, len(hiddev_usage_ref)) # get
HIDIOCSUSAGE = ioctl.IOW(ord('H'), 0x0C, len(hiddev_usage_ref)) # set
HIDIOCGUCODE = ioctl.IOWR(ord('H'), 0x0D, len(hiddev_usage_ref))
HIDIOCGFLAG = ioctl.IOR(ord('H'), 0x0E, struct.calcsize(ctypes.c_ushort._type_))
# HIDIOCSFLAG _IOW('H', 0x0F, int)
HIDIOCGCOLLECTIONINDEX = ioctl.IOW(ord('H'), 0x10, len(hiddev_usage_ref))
# HIDIOCGCOLLECTIONINFO _IOWR('H', 0x11, struct hiddev_collection_info)
# HIDIOCGPHYS(len) _IOC(_IOC_READ, 'H', 0x12, len)
# -------------------------------------------------------------------------------------------------
BRIGHTNESS_CONTROL = 16
USAGE_CODE = 0x820010
# -------------------------------------------------------------------------------------------------
class DeviceNotSupported(Exception):
pass
class AppleCinemaDisplay:
def __init__(self, device):
self.device_handle = os.open(device, os.O_RDWR)
self.device_info = hiddev_devinfo()
fcntl.ioctl(self.device_handle, HIDIOCGDEVINFO, self.device_info)
for (vendor_id, vendor_name), products in SUPPORTED_DEVICES.items():
if self.device_info.vendor == vendor_id:
break
else:
raise DeviceNotSupported('Vendor %04x is not '
'supported.' % self.device_info.vendor)
self.vendor_name = vendor_name
self.vendor_id = vendor_id
for product_id, product_name, clamp in products:
if self.device_info.product == product_id:
break
else:
raise DeviceNotSupported('Product %04x is not '
'supported.' % self.device_info.product)
self.product_name = product_name
self.product_id = product_id
self.clamp = clamp or (-sys.maxsize, sys.maxsize)
# Now that we have the number of applications, we can retrieve them
# using the HIDIOCAPPLICATION ioctl() call
# applications are indexed from 0..{num_applications-1}
for app_num in range(self.device_info.num_applications):
application = fcntl.ioctl(self.device_handle, HIDIOCAPPLICATION,
app_num)
# The magic values come from various usage table specs
if (application >> 16) & 0xFF == 0x80:
break
else:
raise DeviceNotSupported('The device is not a USB monitor.')
# Initialise the internal report structures
if fcntl.ioctl(self.device_handle, HIDIOCINITREPORT, 0) < 0:
raise SystemExit("FATAL: Failed to initialize internal report "
"structures")
self.usage_ref = hiddev_usage_ref(report_type=HID_REPORT_TYPE_FEATURE,
report_id=BRIGHTNESS_CONTROL,
field_index=0, usage_index=0,
usage_code=USAGE_CODE)
self.rep_info = hiddev_report_info(report_type=HID_REPORT_TYPE_FEATURE,
report_id=BRIGHTNESS_CONTROL,
num_fields=1)
def get_hid_driver_version(self):
version = hid_version()
fcntl.ioctl(self.device_handle, HIDIOCGVERSION, version)
return version.v1, version.v2, version.v3
def get_product_information(self):
return {'product_id': self.product_id,
'product_name': self.product_name,
'vendor_id': self.vendor_id, 'vendor_name': self.vendor_name}
def get_brightness(self):
"""Return the current brightness value.
"""
if fcntl.ioctl(self.device_handle, HIDIOCGUSAGE, self.usage_ref) < 0:
raise SystemExit("Get usage failed")
if fcntl.ioctl(self.device_handle, HIDIOCGREPORT, self.rep_info) < 0:
raise SystemExit("Get report failed")
return int(self.usage_ref.value)
def set_brightness(self, value):
"""Set the brightness value.
"""
value = int(value)
if self.clamp:
lo, hi = self.clamp
if value > hi or value < lo:
print("Warning: value out of range [%d, %d), "
"clamping." % (lo, hi+1))
value = max(lo, min(hi, value))
self.usage_ref.value = value
if fcntl.ioctl(self.device_handle, HIDIOCSUSAGE, self.usage_ref) < 0:
raise SystemExit("Set usage failed")
if fcntl.ioctl(self.device_handle, HIDIOCSREPORT, self.rep_info) < 0:
raise SystemExit("Set report failed")
return value
def adjust_brightness(self, increment):
"""Apply a brightness adjustment relative to the current setting.
Returns the old value and the current value
"""
old = self.get_brightness()
current = old + increment
current = self.set_brightness(current)
return old, current
def main():
arg_parser = argparse.ArgumentParser(
description='Set brightness on Apple and some other USB monitors.')
arg_parser.add_argument('device', nargs='?', help='Path to the HID device')
arg_parser.add_argument('brightness', nargs='?', default='',
help='New brightness level. If starts with +/-, '
'it will be increased/decreased.')
args = arg_parser.parse_args()
if not args.device:
arg_parser.print_help()
sys.exit(1)
try:
monitor = AppleCinemaDisplay(args.device)
except DeviceNotSupported as e:
print(e)
sys.exit(1)
print('hiddev driver version: %d.%d.%d' % monitor.get_hid_driver_version())
print('Found supported product 0x{product_id:04x} ({product_name}) of '
'vendor 0x{vendor_id:04x} ({vendor_name})'
''.format(**monitor.get_product_information()))
if not args.brightness:
brightness = monitor.get_brightness()
print("Current brightness level is", brightness,
"(%.0f%%)" % (100 * brightness / 256))
sys.exit(0)
if args.brightness.startswith(('+', '-')):
# increase/decrease brightness
old, current = monitor.adjust_brightness(int(args.brightness))
print("Adjusted brightness from", old, "by", args.brightness, "to",
current)
else:
brightness = monitor.set_brightness(int(args.brightness))
print("Brightness set to %d" % brightness)
if __name__ == '__main__':
main()