This commit is contained in:
yumoqing 2022-11-09 23:06:46 +08:00
parent 4af076798a
commit 8eea5b6882
2 changed files with 138 additions and 134 deletions

View File

@ -1,133 +1,137 @@
try: try:
import ujson as json import ujson as json
except: except:
import json import json
import time import time
import zlib import zlib
from kivy.logger import Logger from kivy.logger import Logger
from kivy.event import EventDispatcher from kivy.event import EventDispatcher
from kivy.clock import Clock from kivy.clock import Clock
from appPublic.udp_comm import UdpComm from appPublic.udp_comm import UdpComm
from appPublic.dataencoder import DataEncoder from appPublic.dataencoder import DataEncoder
class UdpWidget(EventDispatcher): class UdpWidget(EventDispatcher):
def __init__(self, udp_port=55000, cert_file=None, commands=[], def __init__(self, udp_port=55000, cert_file=None, commands=[],
**kw): **kw):
super(UdpWidget, self).__init__(**kw) super(UdpWidget, self).__init__(**kw)
self.udp_port = udp_port self.udp_port = udp_port
self.commands = commands self.commands = commands
self.block_commands = [] self.block_commands = []
self.udp_transport = UdpComm(udp_port, self.comm_callback) self.udp_transport = UdpComm(udp_port, self.comm_callback)
host = self.udp_transport.host host = self.udp_transport.host
self.dataencoder = DataEncoder(host, self.get_peer_pubkey) self.dataencoder = DataEncoder(host, self.get_peer_pubkey)
self.inner_handlers = { self.inner_handlers = {
'get_pubkey':self.resp_pubkey, 'get_pubkey':self.resp_pubkey,
'set_pubkey':self.set_pubkey 'set_pubkey':self.set_pubkey
} }
for cmd in self.commands: for cmd in self.commands:
evt_name = 'on_%s' % cmd evt_name = 'on_%s' % cmd
setattr(self, evt_name, self.my_event_handler) setattr(self, evt_name, self.my_event_handler)
self.register_event_type(evt_name) self.register_event_type(evt_name)
# print('udp_widget.py:register', evt_name, self.my_event_handler) # print('udp_widget.py:register', evt_name, self.my_event_handler)
self.get_peer_pubkey() self.get_peer_pubkey()
Clock.schedule_once(self.get_peer_pubkey_loop, 2) Clock.schedule_once(self.get_peer_pubkey_loop, 2)
def block_command(self, cmd): def block_command(self, cmd):
if cmd not in self.command: if cmd not in self.command:
return return
if cmd in self.block_command: if cmd in self.block_command:
return return
self.block_commands.append(cmd) self.block_commands.append(cmd)
def unblock_command(self, cmd): def unblock_command(self, cmd):
if cmd not in self.block_command: if cmd not in self.block_command:
return return
self.block_commands = [ c for c in self.block_command if c!=cmd ] self.block_commands = [ c for c in self.block_command if c!=cmd ]
def get_peer_pubkey_loop(self, t): def get_peer_pubkey_loop(self, t):
self.get_peer_pubkey() self.get_peer_pubkey()
def get_peer_pubkey(self, peer_id=None, timeout=1): def get_peer_pubkey(self, peer_id=None, timeout=1):
# print('get_peer_pubkey(), called..') # print('get_peer_pubkey(), called..')
d = { d = {
'c':'get_pubkey', 'c':'get_pubkey',
'd':{ 'd':{
'pubkey':self.dataencoder.my_text_publickey() 'pubkey':self.dataencoder.my_text_publickey()
} }
} }
bd = self.dataencoder.pack('none', d, uncrypt=True) bd = self.dataencoder.pack('none', d, uncrypt=True)
self.udp_transport.broadcast(bd) self.udp_transport.broadcast(bd)
if peer_id is None: return
# print('get_peer_pubkey():return') """
return # seem to not need to wait
t = t1 = time.time() if peer_id is None:
t1 += timeout # print('get_peer_pubkey():return')
while t1 > t: return
time.sleep(0.1) t = t1 = time.time()
t = time.time() t1 += timeout
if self.dataencoder.exist_peer_publickeys(peer_id): while t1 > t:
return self.dataencder.public_keys[peer_id] time.sleep(0.1)
raise Exception('timeout') t = time.time()
if self.dataencoder.exist_peer_publickeys(peer_id):
def comm_callback(self, data, addr): return self.dataencder.public_keys[peer_id]
# print('comm_callback():', data, 'addr=', addr) raise Exception('timeout')
d = self.dataencoder.unpack(addr[0], data) """
if d is None:
# print('comm_callback(): d is None') def comm_callback(self, data, addr):
return # print('comm_callback():', data, 'addr=', addr)
if not isinstance(d, dict): d = self.dataencoder.unpack(addr[0], data)
# print('comm_callback(): d is not a dict data') if d is None:
return # print('comm_callback(): d is None')
# print('received: data=', d) return
cmd = d['c'] if not isinstance(d, dict):
f = self.inner_handlers.get(cmd) # print('comm_callback(): d is not a dict data')
if f: return
f(d, addr) # print('received: data=', d)
# print('comm_callback():inner callback called(),', cmd) cmd = d['c']
return f = self.inner_handlers.get(cmd)
if cmd in self.block_commands: if f:
# print('comm_callback():', cmd, 'is blocked') f(d, addr)
return # print('comm_callback():inner callback called(),', cmd)
evt_name = 'on_%s' % cmd return
evt_data = { if cmd in self.block_commands:
'd': d, # print('comm_callback():', cmd, 'is blocked')
'addr': addr return
} evt_name = 'on_%s' % cmd
# print('udp_widget.py dispatch', evt_name, evt_data) evt_data = {
self.dispatch(evt_name, evt_data) 'd': d,
'addr': addr
def my_event_handler(self, *args): }
pass # print('udp_widget.py dispatch', evt_name, evt_data)
self.dispatch(evt_name, evt_data)
def set_pubkey(self, data, addr):
pk = data['d']['pubkey'] def my_event_handler(self, *args):
id = addr[0] pass
# print('set_pubkey(): ', id, pk)
self.dataencoder.set_peer_text_pubkey(id, pk) def set_pubkey(self, data, addr):
pk = data['d']['pubkey']
def resp_pubkey(self, data, addr): id = addr[0]
self.set_pubkey(data, addr) # print('set_pubkey(): ', id, pk)
# print('resp_pubkey():', addr[0]) self.dataencoder.set_peer_text_pubkey(id, pk)
data = {
'c':'set_pubkey', def resp_pubkey(self, data, addr):
'd':{ self.set_pubkey(data, addr)
'pubkey':self.dataencoder.my_text_publickey() # print('resp_pubkey():', addr[0])
} data = {
} 'c':'set_pubkey',
self.send(addr[0], data, uncrypt=True) 'd':{
'pubkey':self.dataencoder.my_text_publickey()
def broadcast(self, data): }
for peer in self.dataencoder.public_keys.keys(): }
self.send(peer, data) self.send(addr[0], data, uncrypt=True)
def send(self, peer_id, data, uncrypt=False): def broadcast(self, data):
# print('send():', peer_id, data) for peer in self.dataencoder.public_keys.keys():
d = self.dataencoder.pack(peer_id, data, uncrypt=uncrypt) self.send(peer, data)
addr = (peer_id, self.udp_port)
self.udp_transport.send(d, addr) def send(self, peer_id, data, uncrypt=False):
# print('send():', peer_id, data)
def stop(self): d = self.dataencoder.pack(peer_id, data, uncrypt=uncrypt)
self.udp_transport.stop() addr = (peer_id, self.udp_port)
self.udp_transport.send(d, addr)
def stop(self):
self.udp_transport.stop()

View File

@ -1 +1 @@
__version__ = '0.4.1' __version__ = '0.4.2'