diff --git a/emulator.py b/emulator.py index 6050ec4..5973e0b 100755 --- a/emulator.py +++ b/emulator.py @@ -1,4 +1,4 @@ -#!/usr/bin/env python2 +#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ @@ -32,6 +32,7 @@ __email__ = 'email@ricardo.band' __status__ = 'Development' +import select import sys import socket @@ -60,6 +61,7 @@ def __init__(self, width=40, height=16, ip='127.0.0.1', port=1337, dotsize=10): self.matrix.append(0) self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + self.sock.setblocking(0) self.sock.bind((ip, port)) # size is width * height * 3 (rgb) + 4 (checksum) self.packetsize = self.width * self.height * 3 + 4 @@ -68,10 +70,14 @@ def recv_data(self): """ Grab the next frame and put it on the matrix. """ - data, addr = self.sock.recvfrom(self.packetsize) - matrix = map(ord, data.strip()) - if len(matrix) == self.packetsize: - self.matrix = matrix[:-4] + select.select([], [self.sock], []) + try: + data, addr = self.sock.recvfrom(self.packetsize) + except socket.error: + pass + else: + self.matrix = list(data.strip())[:self.packetsize-4] + def update(self): """ @@ -81,8 +87,7 @@ def update(self): for x in range(self.width): for y in range(self.height): pixel = y * self.width * 3 + x * 3 - #TODO: sometimes the matrix is not as big as it should - if pixel < pixels: + if pixel < pixels - 2: pygame.draw.circle(self.screen, (self.matrix[pixel], self.matrix[pixel + 1], self.matrix[pixel + 2]), (x * self.dotsize + self.dotsize / 2, y * self.dotsize + self.dotsize / 2), self.dotsize / 2, 0) @@ -93,6 +98,7 @@ def render(self): """ pygame.display.update() pygame.display.flip() + self.clock.tick(60) def gameloop(self): """