#!/usr/bin/env python3 """Bounded RGB checks on an operator-selected disposable Linux VT.""" import argparse from contextlib import contextmanager import ctypes import fcntl import json import os from pathlib import Path import signal import statistics import struct import termios import time RELEASE = '5.15.86-n810-console-rgb1+' BG, FG = (17, 57, 89), (245, 210, 104) def rgb565(rgb): r, g, b = rgb return (r >> 3) << 11 | (g >> 2) << 5 | b >> 3 def sgr(rgb, background=True): return '\x1b[%d;2;%d;%d;%dm' % ((48 if background else 38,) + rgb) class FontOp(ctypes.Structure): _fields_ = [(x, ctypes.c_uint) for x in ('op', 'flags', 'width', 'height', 'charcount')] + [('data', ctypes.c_void_p)] class Console: def __init__(self, vt): self.vt = vt self.control = os.open('/dev/tty0', os.O_RDWR | os.O_NOCTTY) self.fd = os.open('/dev/tty%d' % vt, os.O_RDWR | os.O_NOCTTY) def close(self): os.close(self.fd) os.close(self.control) def active(self): return struct.unpack('HHH', fcntl.ioctl(self.control, 0x5603, b'\0'*6))[0] def switch(self, vt): fcntl.ioctl(self.control, 0x5606, vt) fcntl.ioctl(self.control, 0x5607, vt) def size(self): return struct.unpack('HHHH', fcntl.ioctl(self.fd, termios.TIOCGWINSZ, b'\0'*8))[:2] def font(self, saved=None, height=None): data = ctypes.create_string_buffer(saved['data'] if saved else b'\0'*65536) op = FontOp(0 if saved else 1, 0, saved['width'] if saved else 32, height or (saved['height'] if saved else 32), saved['charcount'] if saved else 512, ctypes.addressof(data)) raw = bytearray(ctypes.string_at(ctypes.byref(op), ctypes.sizeof(op))) fcntl.ioctl(self.fd, 0x4B72, raw, True) ctypes.memmove(ctypes.byref(op), bytes(raw), len(raw)) count = ((op.width+7)//8)*32*op.charcount return dict(width=op.width, height=op.height, charcount=op.charcount, data=data.raw[:count]) def write(self, text): if self.active() != self.vt: raise RuntimeError('Active VT changed; stopping test writes') data = text.encode('ascii') while data: data = data[os.write(self.fd, data):] def frame(self): time.sleep(.06) if self.active() != self.vt: raise RuntimeError('Foreground changed before framebuffer read') with open('/dev/fb0', 'rb', buffering=0) as stream: data = stream.read(800*480*2) if self.active() != self.vt: raise RuntimeError('Foreground changed during framebuffer read') if len(data) != 800*480*2: raise RuntimeError('Incomplete framebuffer read') return data def cell(self, row, col): rows, cols = self.size() font = self.font() w, h = font['width'], font['height'] if not (0 <= row < rows and 0 <= col < cols and (col+1)*w <= 800 and (row+1)*h <= 480): raise RuntimeError('Cell outside visible framebuffer') frame = self.frame() return [struct.unpack_from('