Skip to content
Snippets Groups Projects
Commit cfb24b52 authored by KERDREUX Jerome's avatar KERDREUX Jerome
Browse files

Patching several old test

- This should works w/ new Python, and xAAL libs
- Formatting done
parent ffb76bf0
No related branches found
No related tags found
No related merge requests found
from xaal.aiolib.core import Hook,HookType
from xaal.lib.aioengine import Hook, HookType
import asyncio
async def test1(foo,bar=None):
print('='*78)
async def test1(foo, bar=None):
print('=' * 78)
print('Foo: %s' % foo)
print('Bar: %s' % bar)
async def test2(*args,**kwargs):
print('='*78)
async def test2(*args, **kwargs):
print('=' * 78)
print('Args: %s' % str(args))
print('Kwargs: %s' % str(kwargs))
async def goo(func,*args,**kwargs):
async def goo(func, *args, **kwargs):
print("Args: %s" % args)
print("kwarrgs: %s" % kwargs)
h = Hook(HookType.start,func,*args,**kwargs)
print('*'*78)
h = Hook(HookType.start, func, *args, **kwargs)
print('*' * 78)
print("Args: %s" % h.args)
print("kwarrgs: %s" % h.kwargs)
await h.func(*h.args,**h.kwargs)
await h.func(*h.args, **h.kwargs)
asyncio.run(goo(test1,'Foo',bar=12))
asyncio.run(goo(test2,'Foo',bar=12))
\ No newline at end of file
asyncio.run(goo(test1, 'Foo', bar=12))
asyncio.run(goo(test2, 'Foo', bar=12))
from xaal.lib import core,helpers
from xaal.lib import aiohelpers
from xaal.lib import core, helpers
from xaal.lib import aiohelpers
import asyncio
import time
......@@ -9,17 +8,20 @@ import logging
logger = logging.getLogger(__name__)
helpers.setup_console_logger()
def foo(arg0,arg1):
def foo(arg0, arg1):
print(f"{arg0} {arg1}")
async def goo(arg0,arg1):
async def goo(arg0, arg1):
print(f"{arg0} {arg1}")
@aiohelpers.spawn
def bar(arg0,arg1):
def bar(arg0, arg1):
print(f"{arg0} {arg1}")
logger.warning('sleep')
time.sleep(10)
time.sleep(5)
logger.warning('eof sleep')
......@@ -30,11 +32,11 @@ if __name__ == '__main__':
print(f" {core.get_args_method(goo)}")
print(f" {core.get_args_method(bar)}")
t1=asyncio.ensure_future(goo('goo1','goo2'))
#t2=asyncio.ensure_future(bar('goo1','goo2'))
t2=bar('goo1','goo2')
t1 = asyncio.ensure_future(goo('goo1', 'goo2'))
# t2=asyncio.ensure_future(bar('goo1','goo2'))
t2 = bar('goo1', 'goo2')
futures = asyncio.wait([t1,])
futures = asyncio.wait([t1])
logger.debug('Waiting..')
asyncio.get_event_loop().run_until_complete(futures)
from xaal.lib.core import Engine
from xaal.lib import Engine
from xaal.lib.network import NetworkConnector
from xaal.lib.helpers import setup_console_logger
from xaal.schemas import devices
......@@ -6,24 +6,27 @@ import functools
import asyncio
from decorator import decorator
@decorator
def spawn(func,*args,**kwargs):
def spawn(func, *args, **kwargs):
print(f"Calling {func.__name__}")
asyncio.ensure_future(func(*args,**kwargs))
asyncio.ensure_future(func(*args, **kwargs))
def spawn0(func):
@functools.wraps(func)
def spawn_future(*args,**kwargs):
def spawn_future(*args, **kwargs):
print(f"Calling {func.__name__}")
asyncio.ensure_future(func(*args,**kwargs))
asyncio.ensure_future(func(*args, **kwargs))
return spawn_future
class AioNetworkConnector(NetworkConnector):
async def receive(self):
data=NetworkConnector.receive(self)
#print(data)
data = NetworkConnector.receive(self)
# print(data)
print("receive")
return data
......@@ -38,17 +41,19 @@ class AioEngine(Engine):
def handler(data):
#print(data)
# print(data)
print("hanlder")
@spawn
async def toggle(dev):
print("Toggle")
await asyncio.sleep(2)
dev.attributes['light']=False if dev.attributes['light'] else True
dev.attributes['light'] = False if dev.attributes['light'] else True
@spawn
async def test(dev,_foo):
async def test(dev, _foo):
print(f"test.... {dev} {_foo}")
......@@ -57,8 +62,9 @@ async def foo():
print("Foo")
await asyncio.sleep(30)
async def test_receive():
net = AioNetworkConnector('224.0.29.200',1236,10)
net = AioNetworkConnector('224.0.29.200', 1236, 10)
net.connect()
while True:
await net.receive()
......@@ -66,29 +72,28 @@ async def test_receive():
def main():
setup_console_logger()
#loop = asyncio.new_event_loop()
# loop = asyncio.new_event_loop()
eng = AioEngine()
#eng.add_rx_handler(handler)
# eng.add_rx_handler(handler)
import sys
from xaal.lib import tools
dev = devices.lamp_toggle(tools.get_uuid(sys.argv[1]))
dev = devices.lamp_toggle(tools.get_random_uuid())
dev.info = 'FooBar'
eng.add_device(dev)
ptr = functools.partial(toggle,dev)
ptr = functools.partial(toggle, dev)
dev.methods['toggle'] = ptr
eng.add_timer(ptr,10)
eng.add_timer(ptr, 10)
ptr = functools.partial(test,dev)
ptr = functools.partial(test, dev)
dev.methods['test'] = ptr
tasks = [ asyncio.ensure_future(eng.run()),
# asyncio.ensure_future(foo()),
# asyncio.ensure_future(test_receive()),
]
tasks = [
asyncio.ensure_future(eng.run()),
# asyncio.ensure_future(foo()),
# asyncio.ensure_future(test_receive()),
]
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.wait(tasks))
......@@ -99,4 +104,3 @@ if __name__ == '__main__':
main()
except KeyboardInterrupt:
print("Bye bye")
class Foo:
def __init__(self):
self.goo = 'Goo'
......@@ -9,7 +8,7 @@ class Foo:
return self.__bar
@bar.setter
def bar(self,value):
def bar(self, value):
self.__bar = value
def __setattr__(self, name, value):
......@@ -18,18 +17,22 @@ class Foo:
propobj.fset(self, value)
return
if name not in ['goo','_Foo__bar']:
if name not in ['goo', '_Foo__bar', 'foo']:
raise AttributeError(f'unknow attribute {name}')
self.__dict__[name] = value
def dump(self):
print(self.__dict__)
a = Foo()
print(a.bar)
a.bar = 'boo'
a.goo = 'goo'
a.foo = 'foo'
try:
a.baz = 'baz'
except AttributeError as e:
print(e)
a.dump()
from xaal.lib import AsyncEngine,helpers
from xaal.lib import AsyncEngine, helpers
import functools
helpers.setup_console_logger()
def shutdown(eng):
eng.shutdown()
eng = AsyncEngine()
ptr = functools.partial(shutdown,eng)
eng.add_timer(ptr,2)
ptr = functools.partial(shutdown, eng)
eng.add_timer(ptr, 2)
eng.run()
# from gevent import monkey
# monkey.patch_all()
def is_gevent_monkey_patched():
try:
from gevent import monkey
except ImportError:
print("gevent is not installed")
return False
else:
return monkey.is_module_patched('__builtin__')
\ No newline at end of file
return monkey.is_module_patched('__builtin__')
print(is_gevent_monkey_patched())
......@@ -2,17 +2,20 @@ import asyncio
event = asyncio.Event()
async def test1():
await event.wait()
print('Test1')
async def test2():
await event.wait()
print('Test2')
async def run():
print('running')
await asyncio.sleep(10)
await asyncio.sleep(5)
event.set()
print('event set')
await asyncio.sleep(1)
......@@ -21,8 +24,11 @@ async def run():
loop = asyncio.get_event_loop()
t1=loop.create_task(test1())
t2=loop.create_task(test2())
t3=loop.create_task(run())
t1 = loop.create_task(test1())
t2 = loop.create_task(test2())
t3 = loop.create_task(run())
loop.run_forever()
try:
loop.run_forever()
except KeyboardInterrupt:
print('done')
"""
Simple test to study the death the engine with a running thread.
"""
import asyncio
from xaal.lib import AsyncEngine,helpers
from xaal.lib import AsyncEngine, helpers
import time
@helpers.spawn
def test1(event):
while not event.is_set():
time.sleep(1)
print('test1')
async def test2():
while 1:
await asyncio.sleep(1)
print('test2')
eng = AsyncEngine()
print(eng.new_task(test2()))
......@@ -24,5 +28,3 @@ test1(ev)
eng.on_stop(ev.set)
# hit ctrl-c now
eng.run()
from gevent import monkey;monkey.patch_all(thread=False)
from gevent import monkey
monkey.patch_all(thread=False)
import gevent
from xaal.lib import AsyncEngine,helpers
from xaal.lib import AsyncEngine, helpers
helpers.setup_console_logger()
def loop():
while 1:
print('loop')
gevent.sleep(1)
eng = AsyncEngine()
gevent.spawn(loop)
eng.run()
......@@ -2,7 +2,7 @@ from xaal.lib import helpers
class Goo:
def test(self,name):
def test(self, name):
self.test.counter = getattr(self.test, 'counter', 0) + 1
print(f"{name} => {self.test.counter}")
......@@ -12,6 +12,7 @@ def test_func(name='Foo'):
print(f"{name} => {test_func.counter}")
test_func.counter += 1
test_func()
test_func('Bar')
test_func('Baz')
......@@ -22,4 +23,3 @@ try:
goo.test('Goo')
except AttributeError as e:
print(f"AttributeError: {e}")
from xaal.aiolib import Engine,helpers
from xaal.lib import AsyncEngine, helpers
from xaal.lib.aioengine import console
import asyncio
import logging
import functools
helpers.setup_console_logger()
logger = logging.getLogger('test-timer')
async def sleep1():
logger.warning('Sleep1 start')
await asyncio.sleep(15)
logger.warning('Sleep1 done')
async def sleep2():
logger.warning('Sleep2 start')
await asyncio.sleep(20)
logger.warning('Sleep2 done')
async def _console(locals):
await console(locals=locals)
async def test(foo,bar=None):
print('='*78)
async def test(foo, bar=None):
print('=' * 78)
print('Foo: %s' % foo)
print('Bar: %s' % bar)
eng = Engine()
eng.add_timer(sleep1,1,1)
eng.add_timer(sleep2,1,1)
eng.on_start(test,'Foo',bar=12)
eng = AsyncEngine()
eng.add_timer(sleep1, 1, 1)
eng.add_timer(sleep2, 1, 1)
eng.on_start(test, 'Foo', bar=12)
#ptr = functools.partial(_console,locals())
#eng.add_timer(ptr,1,2)
ptr = functools.partial(_console, locals())
eng.add_timer(ptr, 1, 2)
#asyncio.ensure_future(console(locals()))
# asyncio.ensure_future(console(locals()))
try:
eng.run()
......
......@@ -16,6 +16,7 @@ class EchoClientProtocol:
print("Received:", data.decode())
print("Close the socket")
assert self.transport is not None
self.transport.close()
def error_received(self, exc):
......@@ -35,8 +36,8 @@ async def main():
message = "Hello World!"
transport, protocol = await loop.create_datagram_endpoint(
lambda: EchoClientProtocol(message, on_con_lost),
remote_addr=('127.0.0.1', 9999))
lambda: EchoClientProtocol(message, on_con_lost), remote_addr=('127.0.0.1', 9999)
)
try:
await on_con_lost
......@@ -44,4 +45,4 @@ async def main():
transport.close()
asyncio.run(main())
\ No newline at end of file
asyncio.run(main())
......@@ -6,9 +6,10 @@ import uuid
ADDR = '224.0.29.200'
PORT = 1230
class EchoServerProtocol(asyncio.Protocol):
def __init__(self,on_con_lost):
#self.on_con_lost = on_con_lost
def __init__(self, on_con_lost):
# self.on_con_lost = on_con_lost
pass
def connection_made(self, transport):
......@@ -19,23 +20,24 @@ class EchoServerProtocol(asyncio.Protocol):
def connection_lost(self, exc):
print("Connection closed")
#self.on_con_lost.set_result(True)
def datagram_send(self,data):
self.transport.sendto(data,(ADDR,PORT))
# self.on_con_lost.set_result(True)
def datagram_send(self, data):
self.transport.sendto(data, (ADDR, PORT))
def datagram_received(self, data, addr):
print('Received %r from %s' % (data, addr))
async def test_send(protocol,uid):
async def test_send(protocol, uid):
while True:
msg = f"msg from {uid}"
protocol.datagram_send(msg.encode("utf-8"))
await asyncio.sleep(5)
def new_sock():
sock = socket.socket(socket.AF_INET,socket.SOCK_DGRAM,socket.IPPROTO_UDP)
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
try:
# Linux + MacOS + BSD
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1)
......@@ -43,19 +45,20 @@ def new_sock():
# Windows
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('0.0.0.0', PORT))
mreq = struct.pack('4sl',socket.inet_aton(ADDR),socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP,socket.IP_ADD_MEMBERSHIP,mreq)
sock.setsockopt(socket.IPPROTO_IP,socket.IP_MULTICAST_TTL,10)
mreq = struct.pack('4sl', socket.inet_aton(ADDR), socket.INADDR_ANY)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, 10)
return sock
async def main():
loop = asyncio.get_running_loop()
print("Starting UDP server")
on_con_lost = loop.create_future()
transport, protocol = await loop.create_datagram_endpoint( lambda: EchoServerProtocol(on_con_lost,), sock=new_sock())
#transport, protocol = await loop.create_datagram_endpoint( lambda: EchoServerProtocol(on_con_lost), local_addr=(ADDR, PORT),reuse_port=True)
asyncio.ensure_future(test_send(protocol,uuid.uuid1()))
transport, protocol = await loop.create_datagram_endpoint(lambda: EchoServerProtocol(on_con_lost), sock=new_sock())
# transport, protocol = await loop.create_datagram_endpoint( lambda: EchoServerProtocol(on_con_lost), local_addr=(ADDR, PORT),reuse_port=True)
asyncio.ensure_future(test_send(protocol, uuid.uuid1()))
try:
await asyncio.sleep(3600) # Serve for 1 hour.
......@@ -67,4 +70,4 @@ if __name__ == '__main__':
try:
asyncio.run(main())
except KeyboardInterrupt:
print("Bye Bye")
\ No newline at end of file
print("Bye Bye")
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment