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)
print('Foo: %s' % foo)
......@@ -14,7 +14,6 @@ async def test2(*args,**kwargs):
print('Kwargs: %s' % str(kwargs))
async def goo(func, *args, **kwargs):
print("Args: %s" % args)
print("kwarrgs: %s" % kwargs)
......@@ -24,5 +23,6 @@ async def goo(func,*args,**kwargs):
print("kwarrgs: %s" % h.kwargs)
await h.func(*h.args, **h.kwargs)
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
......@@ -9,17 +8,20 @@ import logging
logger = logging.getLogger(__name__)
helpers.setup_console_logger()
def foo(arg0, arg1):
print(f"{arg0} {arg1}")
async def goo(arg0, arg1):
print(f"{arg0} {arg1}")
@aiohelpers.spawn
def bar(arg0, arg1):
print(f"{arg0} {arg1}")
logger.warning('sleep')
time.sleep(10)
time.sleep(5)
logger.warning('eof sleep')
......@@ -34,7 +36,7 @@ if __name__ == '__main__':
# 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,6 +6,7 @@ import functools
import asyncio
from decorator import decorator
@decorator
def spawn(func, *args, **kwargs):
print(f"Calling {func.__name__}")
......@@ -17,8 +18,10 @@ def spawn0(func):
def spawn_future(*args, **kwargs):
print(f"Calling {func.__name__}")
asyncio.ensure_future(func(*args, **kwargs))
return spawn_future
class AioNetworkConnector(NetworkConnector):
async def receive(self):
......@@ -41,12 +44,14 @@ def handler(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
@spawn
async def test(dev, _foo):
print(f"test.... {dev} {_foo}")
......@@ -57,6 +62,7 @@ async def foo():
print("Foo")
await asyncio.sleep(30)
async def test_receive():
net = AioNetworkConnector('224.0.29.200', 1236, 10)
net.connect()
......@@ -70,11 +76,9 @@ def main():
eng = AioEngine()
# 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)
......@@ -85,7 +89,8 @@ def main():
ptr = functools.partial(test, dev)
dev.methods['test'] = ptr
tasks = [ asyncio.ensure_future(eng.run()),
tasks = [
asyncio.ensure_future(eng.run()),
# asyncio.ensure_future(foo()),
# asyncio.ensure_future(test_receive()),
]
......@@ -99,4 +104,3 @@ if __name__ == '__main__':
main()
except KeyboardInterrupt:
print("Bye bye")
class Foo:
def __init__(self):
self.goo = 'Goo'
......@@ -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()
......@@ -3,9 +3,11 @@ import functools
helpers.setup_console_logger()
def shutdown(eng):
eng.shutdown()
eng = AsyncEngine()
ptr = functools.partial(shutdown, eng)
eng.add_timer(ptr, 2)
......
# 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__')
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)
......@@ -25,4 +28,7 @@ t1=loop.create_task(test1())
t2 = loop.create_task(test2())
t3 = loop.create_task(run())
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
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
helpers.setup_console_logger()
def loop():
while 1:
print('loop')
gevent.sleep(1)
eng = AsyncEngine()
gevent.spawn(loop)
eng.run()
......@@ -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)
......@@ -27,13 +31,13 @@ async def test(foo,bar=None):
print('Bar: %s' % bar)
eng = Engine()
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()))
......
......@@ -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
......
......@@ -6,6 +6,7 @@ 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
......@@ -34,6 +35,7 @@ async def test_send(protocol,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)
try:
......@@ -48,12 +50,13 @@ def new_sock():
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), 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()))
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment