Skip to content

Instantly share code, notes, and snippets.

@yasamoka
Last active July 1, 2019 17:02
Show Gist options
  • Save yasamoka/457c3f1695bbab6d4bb03cba807d2aad to your computer and use it in GitHub Desktop.
Save yasamoka/457c3f1695bbab6d4bb03cba807d2aad to your computer and use it in GitHub Desktop.
Change display brightness under Ubuntu using keyboard shortcuts
#!/usr/local/bin/python3
import sys
import re
from subprocess import Popen, PIPE
VCP_FEATURE_CODE = 0x10
VCP_FEATURE_NAME = "Brightness"
MIN_VALUE = 0
REGEX_RESPONSE_PATTERN = "VCP code 0x(?P<vcp_feature_code>[0-9a-f]{2}) \((?P<vcp_feature_name>.+?)\s+\)\: current value =\s+(?P<current_value>\d+)\, max value =\s+(?P<max_value>\d+)"
assert len(sys.argv) == 2
change = int(sys.argv[1])
vcp_feature_code_hex = hex(VCP_FEATURE_CODE)
get_args = ["ddcutil", "getvcp", vcp_feature_code_hex]
get_process = Popen(get_args, stdout=PIPE, stderr=PIPE)
get_process.wait()
try:
assert get_process.returncode == 0
except AssertionError:
raise Exception(get_process.stderr.read().decode('utf-8'))
stdout = get_process.stdout.read().decode('utf-8')
match_obj = re.match(REGEX_RESPONSE_PATTERN, stdout)
assert match_obj
response_vcp_feature_code = int(match_obj.group("vcp_feature_code"), 16)
assert response_vcp_feature_code == VCP_FEATURE_CODE
response_vcp_feature_name = match_obj.group("vcp_feature_name")
assert response_vcp_feature_name == VCP_FEATURE_NAME
current_value = int(match_obj.group("current_value"))
max_value = int(match_obj.group("max_value"))
next_value = current_value + change
if next_value < MIN_VALUE:
next_value = MIN_VALUE
elif next_value > max_value:
next_value = max_value
set_args = ["ddcutil", "setvcp", vcp_feature_code_hex, str(next_value)]
set_process = Popen(set_args, stdout=PIPE, stderr=PIPE)
set_process.wait()
try:
assert set_process.returncode == 0
except AssertionError:
raise Exception(set_process.stderr.read().decode('utf-8'))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment