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