aboutsummaryrefslogtreecommitdiff
path: root/host/server.py
blob: 3b9590cb9a47ee4115f0c092671a1f005ead6f68 (plain)
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
#!/usr/bin/env python

from socketserver import *
from time import time, strftime, sleep
from collections import namedtuple
from itertools import product, cycle
import threading
import random

from ctypes import *

import numpy as np

from matelight import sendframe, DISPLAY_WIDTH, DISPLAY_HEIGHT, FRAME_SIZE


UDP_TIMEOUT = 3.0


class COLOR(Structure):
		_fields_ = [('r', c_uint8), ('g', c_uint8), ('b', c_uint8), ('a', c_uint8)]

class FRAMEBUFFER(Structure):
		_fields_ = [('data', POINTER(COLOR)), ('w', c_size_t), ('h', c_size_t)]

bdf = CDLL('./libbdf.so')
bdf.read_bdf_file.restype = c_void_p
bdf.framebuffer_render_text.restype = POINTER(FRAMEBUFFER)
bdf.framebuffer_render_text.argtypes= [c_char_p, c_void_p, c_void_p, c_size_t, c_size_t, c_size_t]

unifont = bdf.read_bdf_file('unifont.bdf')

def compute_text_bounds(text):
	assert unifont
	textbytes = bytes(str(text), 'UTF-8')
	textw, texth = c_size_t(0), c_size_t(0)
	res = bdf.framebuffer_get_text_bounds(textbytes, unifont, byref(textw), byref(texth))
	if res:
		raise ValueError('Invalid text')
	return textw.value, texth.value

def render_text(text, offset):
	cbuf = create_string_buffer(FRAME_SIZE*sizeof(COLOR))
	textbytes = bytes(str(text), 'UTF-8')
	res = bdf.framebuffer_render_text(textbytes, unifont, cbuf, DISPLAY_WIDTH, DISPLAY_HEIGHT, offset)
	if res:
		raise ValueError('Invalid text')
	return np.ctypeslib.as_array(cast(cbuf, POINTER(c_uint8)), shape=(DISPLAY_WIDTH, DISPLAY_HEIGHT, 4))

printlock = threading.Lock()

def printframe(fb):
	w,h,_ = fb.shape
	printlock.acquire()
	print('\0337\033[H', end='')
	print('Rendering frame @{}'.format(time()))
	bdf.console_render_buffer(fb.ctypes.data_as(POINTER(c_uint8)), w, h)
	print('\033[0m\033[KCurrently rendering', current_entry.entrytype, 'from', current_entry.remote, ':', current_entry.text, '\0338', end='')
	printlock.release()

def scroll(text):
	""" Returns whether it could scroll all the text uninterrupted """
	#log('Scrolling', text)
	w,h = compute_text_bounds(text)
	for i in range(-DISPLAY_WIDTH,w+1):
		fb = render_text(text, i);
		sendframe(fb)
		printframe(fb)
	return True

QueueEntry = namedtuple('QueueEntry', ['entrytype', 'remote', 'timestamp', 'text'])
defaultlines = [ QueueEntry('text', '127.0.0.1', 0, l[:-1].replace('\\x1B', '\x1B')) for l in open('default.lines').readlines() ]
random.shuffle(defaultlines)
defaulttexts = cycle(defaultlines)
current_entry = next(defaulttexts)
conns = {}
textqueue = []

def log(*args):
	printlock.acquire()
	print(strftime('\x1B[93m[%m-%d %H:%M:%S]\x1B[0m'), ' '.join(str(arg) for arg in args), '\x1B[0m')
	printlock.release()


class MateLightUDPServer(UDPServer):
    """
    The server class for the SocketServer interface.
    """
    def __init__(self, *args, **kwargs):
        """
        Setup the deque for the frame
        """
        super(MateLightUDPServer, self).__init__(*args, **kwargs)
        self.frame_deque = collections.deque(maxlen=30)
        
    def get_next_frame(self):
        try:
            return self.frame_deque.popleft()
        except IndexError:
            return None


class MateLightUDPHandler(BaseRequestHandler):
    """
    Handles one UDP connection to the matelight
    """
	def handle(self):
		try:
			# Housekeeping - FIXME: This is *so* the wrong place for this.
			for k,v in conns.items():
				if time() - v.timestamp > UDP_TIMEOUT:
					del conns[k]

			global current_entry, conns
			data = self.request[0].strip()
			if len(data) != FRAME_SIZE*3+4:
				#raise ValueError('Invalid frame size: Expected {}, got {}'.format(FRAME_SIZE+4, len(data)))
				return
			frame = data[:-4]
			#crc1, = struct.unpack('!I', data[-4:])
			#crc2, = zlib.crc32(frame, 0),
			#if crc1 != crc2:
			#	raise ValueError('Invalid frame CRC checksum: Expected {}, got {}'.format(crc2, crc1))
			#socket.sendto(b'ACK', self.client_address)
			a = np.array(list(frame), dtype=np.uint8)
			timestamp = time()
			addr = self.client_address[0]
			conn = QueueEntry('udp', addr, timestamp, '')
			if addr not in conns:
				log('\x1B[91mNew UDP connection from\x1B[0m', addr)
				current_entry = conn
			conns[addr] = current_entry
			if current_entry.entrytype == 'udp' and current_entry.remote == addr:
				current_entry = conn
				frame = a.reshape((DISPLAY_HEIGHT, DISPLAY_WIDTH, 3))
                self.server.frame_deque.append(frame)
				#sendframe(frame)
                #printframe(np.pad(frame, ((0,0),(0,0),(0,1)), 'constant', constant_values=(0,0)))
		except Exception as e:
			log('Error receiving UDP frame:', e)

class MateLightTCPTextHandler(BaseRequestHandler):
	def handle(self):
		global current_entry, conns
		data = str(self.request.recv(1024).strip(), 'UTF-8')
		addr = self.client_address[0]
		timestamp = time()
		if len(data) > 140:
			self.request.sendall('TOO MUCH INFORMATION!\n')
			return
		log('\x1B[95mText from\x1B[0m {}: {}\x1B[0m'.format(addr, data))
		textqueue.append(QueueEntry('text', addr, timestamp, data))
		self.request.sendall(b'KTHXBYE!\n')

#TCPServer.allow_reuse_address = True
#server = TCPServer(('', 1337), MateLightTCPTextHandler)
#t = threading.Thread(target=server.serve_forever)
#t.daemon = True
#t.start()

UDPServer.allow_reuse_address = True
userver = MateLightUDPServer(('', 1337), MateLightUDPHandler)
t = threading.Thread(target=userver.serve_forever)
t.daemon = True
t.start()

if __name__ == '__main__':
    while True:
        millis = int(round(time.time() * 1000))
        
        next_frame = userver.get_next_frame()
        if next_frame:
            sendframe(next_frame)
            
        while int(round(time.time() * 1000)) - millis < 50:
            // do nothing
            pass
        
    
def bla():
	print('\033[2J'+'\n'*9)
	while True:
		if current_entry.entrytype == 'text':
			if scroll(current_entry.text):
				if current_entry in textqueue:
					textqueue.remove(current_entry)
				if textqueue:
					current_entry = textqueue[0]
				else:
					if conns:
						current_entry = random.choice(list(conns.values()))
					else:
						current_entry = next(defaulttexts)
			if current_entry.entrytype != 'udp' and textqueue:
				current_entry = textqueue[0]
				log('\x1B[92mScrolling\x1B[0m', current_entry.text)
		if current_entry.entrytype == 'udp':
			if time() - current_entry.timestamp > UDP_TIMEOUT:
				current_entry = next(defaulttexts)
			else:
				sleep(0.1)