Clean up some code, add __del__ handler, make methods and names more clear for inexperienced users, handle keyboard exits, add server autodiscovery questions if multiple servers are found

This commit is contained in:
Jan Klopper 2017-06-16 15:14:11 +02:00
parent 52adfbbe66
commit a001e41a8b
3 changed files with 58 additions and 167 deletions

View file

@ -183,140 +183,6 @@ class Canvas(object):
"""Clean up any sockets we created"""
self.broadcastsocket.close()
class PixelVloedClient(object):
"""Sets up a client
Arguments:
firstserver: (bool) False, select the first server immediately
debug: (bool) False
ip: (str) None
port: (int) None
width: (int) 640
height: (int) 480
Listens for servers if no ip is given
"""
def __init__(self, firstserver=False, debug=False,
ip=None, port=None,
width=640, height=480):
self.sleep = 0.01
self.debug = debug
if not ip:
servers = False
while servers == False:
servers = self.DiscoverServers(firstserver)
self.ipaddress = servers[0]['ip']
self.port = servers[0]['port']
self.width = servers[0]['width']
self.height = servers[0]['height']
if self.debug:
print ('displaying on %(ip)s:%(port)d, %(width)d*%(height)dpx' %
servers[0])
else:
self.ipaddress = ip
self.port = port if port else UDP_PORT
self.width = width
self.height = height
if self.debug:
print ('displaying on %(ip)s:%(port)d, %(width)d*%(height)dpx' %
self)
self.sock = socket.socket(socket.AF_INET, # Internet
socket.SOCK_DGRAM) # UDP
def Sleep(self, duration=None):
"""Sleeps the designated amount of time"""
time.sleep(duration if duration else self.sleep)
def SendPacket(self, message, sleep=0.01):
"""Sends the message to the udp server
Arguments:
message: (str, 140)
sleep: (float) 0.01, duration of time the client should sleep
"""
self.sock.sendto(message, (self.ipaddress, self.port))
if sleep:
self.Sleep(duration=sleep)
@staticmethod
def DiscoverServers(returnfirst=False, timeout=5):
"""Discover servers that send out the pixelvloed preample"""
discoverysock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
discoverysock.bind(('', DISCOVER_PORT))
starttime = time.time()
servers = []
foundhash = {}
while (time.time() - timeout) < starttime:
data, _addr = discoverysock.recvfrom(1024)
try:
if data.startswith(PROTOCOL_PREAMBLE):
dataset = data.split(' ')
if float(dataset[0].split(':')[1]) <= MAX_PROTOCOL_VERSION:
ipaddress = dataset[1].split(':')[0]
port = int(dataset[1].split(':')[1])
width = int(dataset[2].split('*')[0])
height = int(dataset[2].split('*')[1])
if data not in foundhash:
newserver = {'ip': ipaddress,
'port': port,
'width': width,
'height': height}
foundhash[data] = True
print 'New pixelvloed screen found: %r' % newserver
servers.append(newserver)
if returnfirst:
return servers
except:
pass
if servers:
return servers
return False
def NewMessage():
"""Creates a new message with the correct max size, rgb mode and version"""
message = MaxSizeList(MAX_PIXELS+2)
message.append(SetRGBAMode(False))
message.append(SetVersionBit())
return message
def RGBPixel(x, y, r, g, b, a=None): # pylint: disable=C0103
"""Generates the packed data for a pixel"""
if a is not None:
return struct.pack("<2H4B", x, y, r, g, b, a)
return struct.pack("<2H3B", x, y, r, g, b)
def SetRGBAMode(mode):
"""Generate the rgb/rgba bit"""
return struct.pack("<?", mode)
def SetVersionBit(protocol=1):
"""Generate the Version bit"""
return struct.pack("<B", protocol)
class MaxSizeList(list):
"""A list that raises an indexError when it reaches the designated max size"""
def __init__(self, maxcount=100):
"""Inits a list with a maxcount
Arguments:
maxcount: (int) 100
"""
self.maxsize = maxcount
super(MaxSizeList, self).__init__()
def append(self, item):
"""Appends an item to the list"""
if self.__len__() == self.maxsize:
raise IndexError('max size reached')
super(MaxSizeList, self).append(item)
def RunServer(options):
"""Runs a pixelvloed server"""
PixelVloedServer('%s:%d' %(options.ip, options.port),
options=options).serve_forever()
if __name__ == '__main__':
import sdl2.ext