Skip to content

Instantly share code, notes, and snippets.

@mk-fg
Created January 5, 2020 19:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mk-fg/1c6170baadc85c62e1d113da6063cd4b to your computer and use it in GitHub Desktop.
Save mk-fg/1c6170baadc85c62e1d113da6063cd4b to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import os, sys, re, time, signal, subprocess as sp
tvs = '/opt/vc/bin/tvservice'
def get_hdmi_res():
# state 0x120006 [DVI DMT (82) RGB full 16:9], 1920x1080 @ 60.00Hz, progressive
# state 0x40001 [NTSC 4:3], 720x480 @ 60.00Hz, interlaced
proc = sp.run([tvs, '-s'], check=True, stdout=sp.PIPE)
mode = proc.stdout.decode().strip()
print(f'Display mode: {mode}')
m = re.search(
r'^state (?P0x[\da-fA-F]+) \[(?P[^\]]+)\].*?'
r'\s+(?P\d+)x(?P\d+)\s+@\s+(?P[\d.]+)Hz\b', mode )
if not m: return
if 'NTSC' in m.group('m'): return
return int(m.group('w')), int(m.group('h'))
def main():
import argparse
parser = argparse.ArgumentParser(
description='Script to wait until HDMI display is plugged-in and configured.')
opts = parser.parse_args(sys.argv[1:])
signal.signal(signal.SIGINT, lambda *s: sys.exit())
try:
ev, mon = None, sp.Popen( [tvs, '-M'],
stdout=sp.PIPE, stderr=sp.STDOUT )
while True:
res = get_hdmi_res()
if res:
if ev is None: return # everything already setup
break
ev = mon.stdout.readline().decode().strip()
print(f'Display event: {ev}')
time.sleep(0.5) # trivial debounce
if 'HDMI is attached' in ev:
sp.run([tvs, '--preferred'])
time.sleep(0.5) # to let display catch-up, if necessary
# elif 'HDMI cable is unplugged' in ev: sp.run([tvs, '--off'])
finally:
mon.terminate()
try: mon.wait(2)
except sp.TimeoutExpired: mon.kill()
w, h = res
time.sleep(1) # just in case
print(f'Resizing framebuffer to {w}x{h}')
sp.run(f'fbset -xres {w} -yres {h}'.split(), check=True)
mode = sp.run(['fbset'], stdout=sp.PIPE, check=True)
print(mode.stdout.decode().strip())
if __name__ == '__main__': sys.exit(main())
[Unit]
DefaultDependencies=no
Requires=local-fs.target
After=local-fs.target
[Service]
Type=oneshot
ExecStart=hdmi-boot-delay
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment