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

Tried to replace Any w/ Callable.. but Coro aren't Callable

parent 87fb86ee
No related branches found
No related tags found
1 merge request!1First try of type hints
......@@ -6,14 +6,14 @@ import time
import typing
from enum import Enum
from pprint import pprint
from typing import Any, Optional, Union
from typing import Any, Optional
from uuid import UUID
import aioconsole
from tabulate import tabulate
from .config import config
from . import core, tools
from . import core
from .aionetwork import AsyncNetworkConnector
from .exceptions import CallbackError, XAALError
from .messages import MessageParserError
......@@ -36,7 +36,8 @@ class HookType(Enum):
class Hook(object):
__slots__ = ['type', 'func', 'args', 'kwargs']
def __init__(self, type_, func, *args, **kwargs):
def __init__(self, type_:HookType, func: Any, *args, **kwargs):
# func has to be a callable, but it can be a coroutine or a function
self.type = type_
self.func = func
self.args = args
......@@ -82,11 +83,11 @@ class AsyncEngine(core.EngineMixin):
#####################################################
# Hooks
#####################################################
def on_start(self, func, *args, **kwargs):
def on_start(self, func: Any, *args, **kwargs):
hook = Hook(HookType.start, func, *args, **kwargs)
self._hooks.append(hook)
def on_stop(self, func, *args, **kwargs):
def on_stop(self, func: Any, *args, **kwargs):
hook = Hook(HookType.stop, func, *args, **kwargs)
self._hooks.append(hook)
......@@ -155,7 +156,8 @@ class AsyncEngine(core.EngineMixin):
request for each targets identied in the engine
"""
if not msg.is_request():
return
return # should not happen, but pyright need this check
targets = core.filter_msg_for_devices(msg, self.devices)
for target in targets:
if msg.is_request_isalive():
......@@ -164,6 +166,9 @@ class AsyncEngine(core.EngineMixin):
self.new_task(self.handle_action_request(msg, target))
async def handle_action_request(self, msg: 'Message', target: 'Device'):
if msg.action is None:
return # should not happen, but pyright need this check
try:
result = await run_action(msg, target)
if result is not None:
......@@ -334,8 +339,8 @@ class AsyncEngine(core.EngineMixin):
self.dump_timers()
self.dump_hooks()
def get_device(self, uuid: Union[UUID, str]) -> Optional['Device']:
uuid = tools.get_uuid(uuid)
def get_device(self, uuid: UUID) -> Optional['Device']:
# TODO:Check if this method is usefull
for dev in self.devices:
if dev.address == uuid:
return dev
......
......@@ -22,7 +22,7 @@ import inspect
import logging
import time
import typing
from typing import Any, Optional, List
from typing import Any, Optional, List, Callable
from .exceptions import EngineError, XAALError
from .messages import ALIVE_ADDR, MessageAction, MessageFactory, MessageType
......@@ -39,7 +39,8 @@ logger = logging.getLogger(__name__)
# Timer class
#####################################################
class Timer(object):
def __init__(self, func, period, counter):
def __init__(self, func: Any, period: int, counter: int):
# Timer function should a Callable[[],None], but it can be a coroutine too
self.func = func
self.period = period
self.counter = counter
......@@ -136,7 +137,7 @@ class EngineMixin(object):
#####################################################
# Messages filtering
#####################################################
def enable_msg_filter(self, func: Any = None):
def enable_msg_filter(self, func: Optional[Callable[['Message'], bool]] = None):
"""enable message filter"""
self.msg_filter = func or self.default_msg_filter
......@@ -198,6 +199,7 @@ class EngineMixin(object):
# xAAL messages subscribers
#####################################################
def subscribe(self, func: Any):
# func should be a Callable[[Message],None], but it can be a coroutine too
self.subscribers.append(func)
def unsubscribe(self, func: Any):
......@@ -245,7 +247,7 @@ class EngineMixin(object):
#####################################################
# Usefull functions to Engine developpers
#####################################################
def filter_msg_for_devices(msg: 'Message', devices: List['Device']):
def filter_msg_for_devices(msg: 'Message', devices: List['Device']) -> List['Device']:
"""
loop throught the devices, to find which are expected w/ the msg
- Filter on dev_types for is_alive broadcast request.
......
......@@ -21,7 +21,7 @@
import logging
import time
import typing
from typing import Any, Optional, Union
from typing import Any, Optional, Union, Callable
from tabulate import tabulate
......@@ -215,9 +215,13 @@ class Device(object):
else:
raise DeviceError("Invalid attributes list, use class Attributes)")
def add_method(self, name: str, func: Any):
def add_method(self, name: str, func: Callable[..., Any]):
self.methods.update({name: func})
def del_method(self, name: str):
if name in self.methods:
del self.methods[name]
def get_methods(self) -> dict:
return self.methods
......
......@@ -23,7 +23,7 @@ import logging
import time
import typing
from enum import Enum
from typing import Any, Optional
from typing import Optional
from .config import config
from . import core
......@@ -115,7 +115,7 @@ class Engine(core.EngineMixin):
request for each targets identied in the engine
"""
if not msg.is_request():
return
return # should not happen, but pyright need this check
targets = core.filter_msg_for_devices(msg, self.devices)
for target in targets:
......@@ -127,15 +127,17 @@ class Engine(core.EngineMixin):
def handle_action_request(self, msg: 'Message', target: 'Device'):
"""
Run method (xAAL exposed method) on device:
- None is returned if device method do not return anything
- result is returned if device method gives a response
- Errors are raised if an error occured:
* Internal error
* error returned on the xAAL bus
"""
if msg.action is None:
return # should not happen, but pyright need this check
try:
result = run_action(msg, target)
if result is not None:
if result:
self.send_reply(dev=target, targets=[msg.source], action=msg.action, body=result)
except CallbackError as e:
self.send_error(target, e.code, e.description)
......@@ -222,7 +224,7 @@ class Engine(core.EngineMixin):
return False
def run_action(msg: 'Message', device: 'Device') -> Optional[Any]:
def run_action(msg: 'Message', device: 'Device') -> Optional[dict]:
"""
Extract an action & launch it
Return:
......
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