git.haldean.org bitpic / master screen.py
master

Tree @master (Download .tar.gz)

screen.py @masterraw · history · blame

DEFAULT_SID = "__default"
HOST = "pic.so3.group"

class Screen:
    DATA_VERSION = 0
    W = 8
    H = 8
    DATA_LENGTH_BYTES = 2 + 1 + 2 + 1 + (2 * 3 * W * H)

    def __init__(self, colordata, brightness):
        self.colordata = colordata

        if brightness < 0 or brightness > 255:
            raise ValueError("brightness must be in [0, 255]")
        self.brightness = brightness

    def __eq__(self, other):
        if other is None:
            return False
        if self.brightness != other.brightness:
            return False
        for r1, r2 in zip(self.colordata, other.colordata):
            for c1, c2 in zip(r1, r2):
                for ch1, ch2 in zip(c1, c2):
                    if ch1 != ch2:
                        return False
        return True

    def encode(self):
        return "{:02x}/{:02x}/{}".format(
            self.DATA_VERSION,
            self.brightness,
            "".join("".join("{:02x}{:02x}{:02x}".format(*c) for c in row)
                    for row in self.colordata))

    @classmethod
    def decode(cls, screenstr):
        screenstr = screenstr.strip()
        if len(screenstr) != cls.DATA_LENGTH_BYTES:
            raise ValueError("bad screenstr length {}: {}".format(len(screenstr), screenstr))
        data_bits = screenstr.split('/')
        if len(data_bits) != 3:
            raise ValueError("bad screenstr format: wrong number of /'s")
        vstr, bstr, cstr = data_bits
        
        version = int(vstr, 16)
        if version != cls.DATA_VERSION:
            raise ValueError("unsupported data version {}".format(version))

        brightness = int(bstr, 16)

        color_triples = (cstr[i:i+6] for i in range(0, len(cstr), 6))
        color_triples = [
            (int(c[0:2], 16), int(c[2:4], 16), int(c[4:6], 16))
            for c in color_triples]
        colordata = [color_triples[i:i+cls.W]
                     for i in range(0, cls.W * cls.H, cls.W)]
        return cls(colordata=colordata, brightness=brightness)