first implementation of protobuf
restructure in client server model loads of work still missing
This commit is contained in:
62
ledd/client.py
Normal file
62
ledd/client.py
Normal file
@@ -0,0 +1,62 @@
|
||||
import asyncio
|
||||
import socket
|
||||
|
||||
from ledd import VERSION
|
||||
from ledd.protobuf import client_pb2
|
||||
from ledd.protobuf.ledd_pb2 import WrapperMsg, LedD
|
||||
|
||||
|
||||
class LedDClientProtocol(asyncio.Protocol):
|
||||
def connection_made(self, transport):
|
||||
print("Connected to client!")
|
||||
|
||||
def data_received(self, data):
|
||||
print('Data received: {!r}'.format(data.decode()))
|
||||
|
||||
def connection_lost(self, exc):
|
||||
print('The client closed the connection')
|
||||
|
||||
|
||||
class Client:
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
self.msg = client_pb2.Client()
|
||||
self.proto = None
|
||||
self.transport = None
|
||||
|
||||
def init_from_db(self, row):
|
||||
self.msg.name = row['name']
|
||||
self.msg.addr = row['addr']
|
||||
self.msg.id = row['id']
|
||||
self.msg.options = row['options']
|
||||
self.msg.resolution = row['reso']
|
||||
self.msg.port = row['port']
|
||||
|
||||
def init_from_msg(self, msg):
|
||||
client = client_pb2.Client()
|
||||
self.msg = client.ParseFromString(msg)
|
||||
|
||||
def connect(self):
|
||||
ledd = LedD()
|
||||
ledd.version = VERSION
|
||||
ledd.hostname = socket.gethostname()
|
||||
|
||||
wrapper = WrapperMsg()
|
||||
wrapper.type = WrapperMsg.Type.DISCOVER
|
||||
wrapper.ledd = ledd
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
coro = loop.create_connection(LedDClientProtocol, self.msg.addr, self.msg.port)
|
||||
loop.run_until_complete(coro)
|
||||
self.transport = coro[0]
|
||||
self.proto = coro[1]
|
||||
|
||||
self.send_to_client(wrapper.SerializeToString())
|
||||
|
||||
def is_connected(self):
|
||||
return not self.transport.is_closing()
|
||||
|
||||
def send_to_client(self, data):
|
||||
if self.is_connected() and data:
|
||||
self.transport.write(data)
|
Reference in New Issue
Block a user