diff --git a/libs/lib/xaal/lib/aioengine.py b/libs/lib/xaal/lib/aioengine.py index cd2c700b4adc7e0360a01878461b9c58d8cdd6cb..1e6f3603ac8723ef2a7fe5e10235163ed08b2e58 100644 --- a/libs/lib/xaal/lib/aioengine.py +++ b/libs/lib/xaal/lib/aioengine.py @@ -33,7 +33,7 @@ class HookType(Enum): class Hook(object): - __slots__ = ["type", "func", "args", "kwargs"] + __slots__ = ['type', 'func', 'args', 'kwargs'] def __init__(self, type_, func, *args, **kwargs): self.type = type_ @@ -44,15 +44,15 @@ class Hook(object): class AsyncEngine(core.EngineMixin): __slots__ = [ - "__txFifo", - "_loop", - "_tasks", - "_hooks", - "_watchdog_task", - "_kill_counter", - "running_event", - "watchdog_event", - "started_event", + '__txFifo', + '_loop', + '_tasks', + '_hooks', + '_watchdog_task', + '_kill_counter', + 'running_event', + 'watchdog_event', + 'started_event', ] def __init__( @@ -129,7 +129,7 @@ class AsyncEngine(core.EngineMixin): """Send an encoded message to the bus, use queue_msg instead""" self.network.send(msg) - async def receive_msg(self) -> Optional["Message"]: + async def receive_msg(self) -> Optional['Message']: """return new received message or None""" data = await self.network.get_data() if data: @@ -149,7 +149,7 @@ class AsyncEngine(core.EngineMixin): await run_func(func, msg) self.process_attributes_change() - def handle_request(self, msg: "Message"): + def handle_request(self, msg: 'Message'): """Filter msg for devices according default xAAL API then process the request for each targets identied in the engine """ @@ -162,7 +162,7 @@ class AsyncEngine(core.EngineMixin): else: 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'): try: result = await run_action(msg, target) if result is not None: @@ -240,11 +240,11 @@ class AsyncEngine(core.EngineMixin): logger.warning("Engine already started") return self.started_event.set() - self.new_task(self.boot_task(), name="Boot") - self.new_task(self.receive_task(), name="RecvQ") - self.new_task(self.send_task(), name="SendQ") - self.new_task(self.timer_task(), name="Timers") - self.new_task(console(locals()), name="Console") + self.new_task(self.boot_task(), name='Boot') + self.new_task(self.receive_task(), name='RecvQ') + self.new_task(self.send_task(), name='SendQ') + self.new_task(self.timer_task(), name='Timers') + self.new_task(console(locals()), name='Console') def setup_alives_timer(self): # needed on stop-start sequence @@ -294,38 +294,38 @@ class AsyncEngine(core.EngineMixin): # Debugging tools ##################################################### def dump_timers(self): - headers = ["Func", "Period", "Counter", "Deadline"] + headers = ['Func', 'Period', 'Counter', 'Deadline'] rows = [] now = time.time() for t in self.timers: remain = round(t.deadline - now, 1) rows.append([str(t.func), t.period, t.counter, remain]) print("= Timers") - print(tabulate(rows, headers=headers, tablefmt="fancy_grid")) + print(tabulate(rows, headers=headers, tablefmt='fancy_grid')) def dump_tasks(self): - headers = ["Name", "Coro", "Loop ID"] + headers = ['Name', 'Coro', 'Loop ID'] rows = [] for t in self.all_tasks(): rows.append([t.get_name(), str(t.get_coro()), id(t.get_loop())]) print("= Tasks") - print(tabulate(rows, headers=headers, tablefmt="fancy_grid")) + print(tabulate(rows, headers=headers, tablefmt='fancy_grid')) def dump_devices(self): - headers = ["addr", "dev_type", "info"] + headers = ['addr', 'dev_type', 'info'] rows = [] for d in self.devices: rows.append([d.address, d.dev_type, d.info]) print("= Devices") - print(tabulate(rows, headers=headers, tablefmt="fancy_grid")) + print(tabulate(rows, headers=headers, tablefmt='fancy_grid')) def dump_hooks(self): - headers = ["Type", "Hook"] + headers = ['Type', 'Hook'] rows = [] for h in self._hooks: rows.append([h.type, str(h.func)]) print("= Hooks") - print(tabulate(rows, headers=headers, tablefmt="fancy_grid")) + print(tabulate(rows, headers=headers, tablefmt='fancy_grid')) def dump(self): self.dump_devices() @@ -333,7 +333,7 @@ class AsyncEngine(core.EngineMixin): self.dump_timers() self.dump_hooks() - def get_device(self, uuid: Union[str, UUID]) -> Optional["Device"]: + def get_device(self, uuid: Union[UUID, str]) -> Optional['Device']: uuid = tools.get_uuid(uuid) for dev in self.devices: if dev.address == uuid: @@ -352,7 +352,7 @@ async def run_func(func, *args, **kwargs): return func(*args, **kwargs) -async def run_action(msg: "Message", device: "Device"): +async def run_action(msg: 'Message', device: 'Device'): """ Extract an action & launch it Return: @@ -386,7 +386,7 @@ async def console(locals=locals(), port: Optional[int] = None): def find_free_port(): import socketserver - with socketserver.TCPServer(("localhost", 0), None) as s: + with socketserver.TCPServer(('localhost', 0), None) as s: return s.server_address[1] port = find_free_port() @@ -394,7 +394,7 @@ async def console(locals=locals(), port: Optional[int] = None): logger.debug(f"starting debug console on port {port}") sys.ps1 = "[xAAL] >>> " banner = "=" * 78 + "\nxAAL remote console\n" + "=" * 78 - locals.update({"pprint": pprint}) + locals.update({'pprint': pprint}) def factory(streams): return aioconsole.AsynchronousConsole(locals=locals, streams=streams) diff --git a/libs/lib/xaal/lib/aiohelpers.py b/libs/lib/xaal/lib/aiohelpers.py index 51c40841617b8961116fed8b4858a5b801570192..cd85e247d1af233c73a0842a686b594784b582aa 100644 --- a/libs/lib/xaal/lib/aiohelpers.py +++ b/libs/lib/xaal/lib/aiohelpers.py @@ -22,12 +22,12 @@ def run_async_package(pkg_name, pkg_setup, console_log=True, file_log=False): setup_console_logger() if file_log: setup_file_logger(pkg_name) - - from .aioengine import AsyncEngine + + from .aioengine import AsyncEngine eng = AsyncEngine() eng.start() logger = logging.getLogger(pkg_name) - logger.info('starting xaal package: %s'% pkg_name ) + logger.info("starting xaal package: %s"% pkg_name ) result = pkg_setup(eng) if result is not True: logger.critical("something goes wrong with package: %s" % pkg_name) diff --git a/libs/lib/xaal/lib/bindings.py b/libs/lib/xaal/lib/bindings.py index 6af87aa545614fdc6ec0111cb6d8ada60490d3df..42e6b8dda3d1aa4a497a23753f929a600705ea32 100644 --- a/libs/lib/xaal/lib/bindings.py +++ b/libs/lib/xaal/lib/bindings.py @@ -8,27 +8,27 @@ class UUID: self.__uuid = uuid.UUID(*args, **kwargs) @staticmethod - def random_base(digit=2) -> "UUID": + def random_base(digit=2) -> 'UUID': """zeros the last digits of a random uuid, usefull w/ you want to forge some addresses two digit is great. """ if (digit > 0) and (digit < 13): tmp = str(uuid.uuid1()) - st = "%s%s" % (tmp[:-digit], "0" * digit) + st = "%s%s" % (tmp[:-digit], '0' * digit) return UUID(st) else: raise UUIDError @staticmethod - def random() -> "UUID": + def random() -> 'UUID': tmp = uuid.uuid1().int return UUID(int=tmp) - def __add__(self, value: int) -> "UUID": + def __add__(self, value: int) -> 'UUID': tmp = self.__uuid.int + value return UUID(int=tmp) - def __sub__(self, value: int) -> "UUID": + def __sub__(self, value: int) -> 'UUID': tmp = self.__uuid.int - value return UUID(int=tmp) diff --git a/libs/lib/xaal/lib/core.py b/libs/lib/xaal/lib/core.py index aa449a520fea1f22cd1b032ea4a31580a5733416..c6f122948c02595adf013e686bcd574b85095315 100644 --- a/libs/lib/xaal/lib/core.py +++ b/libs/lib/xaal/lib/core.py @@ -47,7 +47,7 @@ class Timer(object): class EngineMixin(object): - __slots__ = ["devices", "timers", "subscribers", "msg_filter", "_attributesChange", "network", "msg_factory"] + __slots__ = ['devices', 'timers', 'subscribers', 'msg_filter', '_attributesChange', 'network', 'msg_factory'] def __init__(self, address: str, port: int, hops: int, key: bytes): self.devices = [] # list of devices / use (un)register_devices() @@ -67,7 +67,7 @@ class EngineMixin(object): ##################################################### # Devices management ##################################################### - def add_device(self, dev: "Device"): + def add_device(self, dev: 'Device'): """register a new device""" if dev not in self.devices: self.devices.append(dev) @@ -75,12 +75,12 @@ class EngineMixin(object): if self.is_running(): self.send_alive(dev) - def add_devices(self, devs: List["Device"]): + def add_devices(self, devs: List['Device']): """register new devices""" for dev in devs: self.add_device(dev) - def remove_device(self, dev: "Device"): + def remove_device(self, dev: 'Device'): """unregister a device""" dev.engine = None # Remove dev from devices list @@ -93,44 +93,44 @@ class EngineMixin(object): def queue_msg(self, msg: bytes): logger.critical("To be implemented queue_msg: %s", msg) - def send_request(self, dev: "Device", targets: list, action: str, body: Optional[dict] = None): + def send_request(self, dev: 'Device', targets: list, action: str, body: Optional[dict] = None): """queue a new request""" msg = self.msg_factory.build_msg(dev, targets, MessageType.REQUEST, action, body) self.queue_msg(msg) - def send_reply(self, dev: "Device", targets: list, action: str, body: Optional[dict] = None): + def send_reply(self, dev: 'Device', targets: list, action: str, body: Optional[dict] = None): """queue a new reply""" msg = self.msg_factory.build_msg(dev, targets, MessageType.REPLY, action, body) self.queue_msg(msg) - def send_error(self, dev: "Device", errcode: int, description: Optional[str] = None): + def send_error(self, dev: 'Device', errcode: int, description: Optional[str] = None): """queue a error message""" msg = self.msg_factory.build_error_msg(dev, errcode, description) self.queue_msg(msg) - def send_get_description(self, dev: "Device", targets: list): + def send_get_description(self, dev: 'Device', targets: list): """queue a get_description request""" self.send_request(dev, targets, MessageAction.GET_DESCRIPTION.value) - def send_get_attributes(self, dev: "Device", targets: list): + def send_get_attributes(self, dev: 'Device', targets: list): """queue a get_attributes request""" self.send_request(dev, targets, MessageAction.GET_ATTRIBUTES.value) - def send_notification(self, dev: "Device", action: str, body: Optional[dict] = None): + def send_notification(self, dev: 'Device', action: str, body: Optional[dict] = None): """queue a notificaton""" msg = self.msg_factory.build_msg(dev, [], MessageType.NOTIFY, action, body) self.queue_msg(msg) - def send_alive(self, dev: "Device"): + def send_alive(self, dev: 'Device'): """Send a Alive message for a given device""" timeout = dev.get_timeout() msg = self.msg_factory.build_alive_for(dev, timeout) self.queue_msg(msg) dev.update_alive() - def send_is_alive(self, dev: "Device", targets: list = [ALIVE_ADDR,], dev_types: list = ["any.any", ] ): + def send_is_alive(self, dev: 'Device', targets: list = [ALIVE_ADDR,], dev_types: list = ["any.any", ] ): """Send a is_alive message, w/ dev_types filtering""" - body = {"dev_types": dev_types} + body = {'dev_types': dev_types} self.send_request(dev, targets, MessageAction.IS_ALIVE.value, body) ##################################################### @@ -144,7 +144,7 @@ class EngineMixin(object): """disable message filter""" self.msg_filter = None - def default_msg_filter(self, msg: "Message"): + def default_msg_filter(self, msg: 'Message'): """ Filter messages: - check if message has alive request address @@ -173,11 +173,11 @@ class EngineMixin(object): ##################################################### # xAAL attributes changes ##################################################### - def add_attributes_change(self, attr: "Attribute"): + def add_attributes_change(self, attr: 'Attribute'): """add a new attribute change to the list""" self._attributesChange.append(attr) - def get_attributes_change(self) -> List["Attribute"]: + def get_attributes_change(self) -> List['Attribute']: """return the pending attributes changes list""" return self._attributesChange @@ -245,7 +245,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']): """ loop throught the devices, to find which are expected w/ the msg - Filter on dev_types for is_alive broadcast request. @@ -255,8 +255,8 @@ def filter_msg_for_devices(msg: "Message", devices: List["Device"]): if msg.is_request_isalive() and (ALIVE_ADDR in msg.targets): # if we receive a broadcast is_alive request, we reply # with filtering on dev_tyes. - if "dev_types" in msg.body.keys(): - dev_types = msg.body["dev_types"] + if 'dev_types' in msg.body.keys(): + dev_types = msg.body['dev_types'] if "any.any" in dev_types: results = devices else: @@ -276,7 +276,7 @@ def filter_msg_for_devices(msg: "Message", devices: List["Device"]): return results -def search_action(msg: "Message", device: "Device"): +def search_action(msg: 'Message', device: 'Device'): """ Extract an action (match with methods) from a msg on the device. Return: @@ -311,7 +311,7 @@ def get_args_method(method: Any) -> List[str]: """return the list on arguments for a given python method""" spec = inspect.getfullargspec(method) try: - spec.args.remove("self") + spec.args.remove('self') except Exception: pass return spec.args diff --git a/libs/lib/xaal/lib/devices.py b/libs/lib/xaal/lib/devices.py index 34f62af1936d91527b21dc33315d875b99b2c964..89b75b8b90573dbd6a386a0c92671cade5776dde 100644 --- a/libs/lib/xaal/lib/devices.py +++ b/libs/lib/xaal/lib/devices.py @@ -30,17 +30,17 @@ from .exceptions import DeviceError if typing.TYPE_CHECKING: from .aioengine import AsyncEngine - from .devices import Device from .engine import Engine + from .core import EngineMixin logger = logging.getLogger(__name__) class Attribute(object): - def __init__(self, name, dev: Optional["Device"] = None, default: Any = None): + def __init__(self, name, dev: Optional['Device'] = None, default: Any = None): self.name = name self.default = default - self.device: Optional["Device"] = dev + self.device: Optional['Device'] = dev self.__value = default @property @@ -83,31 +83,31 @@ class Attributes(list): class Device(object): __slots__ = [ - "__dev_type", - "__address", - "group_id", - "vendor_id", - "product_id", - "hw_id", - "__version", - "__url", - "schema", - "info", - "unsupported_attributes", - "unsupported_methods", - "unsupported_notifications", - "alive_period", - "next_alive", - "__attributes", - "methods", - "engine", + '__dev_type', + '__address', + 'group_id', + 'vendor_id', + 'product_id', + 'hw_id', + '__version', + '__url', + 'schema', + 'info', + 'unsupported_attributes', + 'unsupported_methods', + 'unsupported_notifications', + 'alive_period', + 'next_alive', + '__attributes', + 'methods', + 'engine', ] def __init__( self, dev_type: str, addr: Optional[bindings.UUID] = None, - engine: Union["Engine", "AsyncEngine", None] = None, + engine: Union['AsyncEngine', 'Engine', 'EngineMixin', None] = None, ): # xAAL internal attributes for a device self.dev_type = dev_type # xaal dev_type @@ -131,8 +131,8 @@ class Device(object): # Default attributes & methods self.__attributes = Attributes() self.methods = { - "get_attributes": self._get_attributes, - "get_description": self._get_description, + 'get_attributes': self._get_attributes, + 'get_description': self._get_description, } self.engine = engine @@ -236,25 +236,25 @@ class Device(object): print("= Device: %s" % self) # info & description r = [] - r.append(["dev_type", self.dev_type]) - r.append(["address", self.address]) + r.append(['dev_type', self.dev_type]) + r.append(['address', self.address]) for k, v in self._get_description().items(): r.append([k, v]) - print(tabulate(r, tablefmt="fancy_grid")) + print(tabulate(r, tablefmt='fancy_grid')) # attributes if len(self._get_attributes()) > 0: r = [] for k, v in self._get_attributes().items(): r.append([k, str(v)]) - print(tabulate(r, tablefmt="fancy_grid")) + print(tabulate(r, tablefmt='fancy_grid')) # methods if len(self.methods) > 0: r = [] for k, v in self.methods.items(): r.append([k, v.__name__]) - print(tabulate(r, tablefmt="fancy_grid")) + print(tabulate(r, tablefmt='fancy_grid')) def __repr__(self) -> str: return f"<xaal.Device {id(self):x} {self.address} {self.dev_type}>" @@ -265,27 +265,27 @@ class Device(object): def _get_description(self) -> dict: result = {} if self.vendor_id: - result["vendor_id"] = self.vendor_id + result['vendor_id'] = self.vendor_id if self.product_id: - result["product_id"] = self.product_id + result['product_id'] = self.product_id if self.version: - result["version"] = self.version + result['version'] = self.version if self.url: - result["url"] = self.url + result['url'] = self.url if self.schema: - result["schema"] = self.schema + result['schema'] = self.schema if self.info: - result["info"] = self.info + result['info'] = self.info if self.hw_id: - result["hw_id"] = self.hw_id + result['hw_id'] = self.hw_id if self.group_id: - result["group_id"] = self.group_id + result['group_id'] = self.group_id if self.unsupported_methods: - result["unsupported_methods"] = self.unsupported_methods + result['unsupported_methods'] = self.unsupported_methods if self.unsupported_notifications: - result["unsupported_notifications"] = self.unsupported_notifications + result['unsupported_notifications'] = self.unsupported_notifications if self.unsupported_attributes: - result["unsupported_attributes"] = self.unsupported_attributes + result['unsupported_attributes'] = self.unsupported_attributes return result def _get_attributes(self, _attributes=None): diff --git a/libs/lib/xaal/lib/engine.py b/libs/lib/xaal/lib/engine.py index af3ec03af883f669bdf5722873e129f6ad7af543..b3c639fd10f9b5966a8627812aa88a6780711a16 100644 --- a/libs/lib/xaal/lib/engine.py +++ b/libs/lib/xaal/lib/engine.py @@ -44,7 +44,7 @@ class EngineState(Enum): class Engine(core.EngineMixin): - __slots__ = ["__last_timer", "__txFifo", "state", "network"] + __slots__ = ['__last_timer', '__txFifo', 'state', 'network'] def __init__( self, address: str = config.address, port: int = config.port, hops: int = config.hops, key: bytes = config.key @@ -87,7 +87,7 @@ class Engine(core.EngineMixin): ##################################################### # xAAL messages subscribers ##################################################### - def receive_msg(self) -> Optional["Message"]: + def receive_msg(self) -> Optional['Message']: """return new received message or None""" result = None data = self.network.get_data() @@ -108,7 +108,7 @@ class Engine(core.EngineMixin): func(msg) self.process_attributes_change() - def handle_request(self, msg: "Message"): + def handle_request(self, msg: 'Message'): """ Filter msg for devices according default xAAL API then process the request for each targets identied in the engine @@ -123,7 +123,7 @@ class Engine(core.EngineMixin): else: self.handle_action_request(msg, target) - 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: - None is returned if device method do not return anything @@ -221,7 +221,7 @@ class Engine(core.EngineMixin): return False -def run_action(msg: "Message", device: "Device") -> Optional[Any]: +def run_action(msg: 'Message', device: 'Device') -> Optional[Any]: """ Extract an action & launch it Return: diff --git a/libs/lib/xaal/lib/exceptions.py b/libs/lib/xaal/lib/exceptions.py index ec8f0b4b1b5c2e4ea6b51ed63e094e4bffdc7b0a..e958eed0f4a128357832cffa0fd5053dcca0396c 100644 --- a/libs/lib/xaal/lib/exceptions.py +++ b/libs/lib/xaal/lib/exceptions.py @@ -26,11 +26,11 @@ class UUIDError(Exception): pass __all__ = [ - "DeviceError", - "EngineError", - "XAALError", - "CallbackError", - "MessageParserError", - "MessageError", - "UUIDError", + 'DeviceError', + 'EngineError', + 'XAALError', + 'CallbackError', + 'MessageParserError', + 'MessageError', + 'UUIDError', ] diff --git a/libs/lib/xaal/lib/helpers.py b/libs/lib/xaal/lib/helpers.py index d65bb5d0c957ff8a278aa1182c438f8558c9da18..3d9197eb6dc9e74fef3fa0f40ec944db9c6dfeb5 100644 --- a/libs/lib/xaal/lib/helpers.py +++ b/libs/lib/xaal/lib/helpers.py @@ -56,7 +56,7 @@ def setup_file_logger(name: str, level: str = config.log_level, filename: Option # register the new handler logger = logging.getLogger(name) logger.root.addHandler(handler) - logger.root.setLevel("DEBUG") + logger.root.setLevel('DEBUG') # --------------------------------------------------------------------------- @@ -88,4 +88,4 @@ def run_package(pkg_name: str, pkg_setup: Any, console_log: bool = True, file_lo logger.info("exit") -__all__ = ["singleton", "timeit", "set_console_title", "setup_console_logger", "setup_file_logger", "run_package"] +__all__ = ['singleton', 'timeit', 'set_console_title', 'setup_console_logger', 'setup_file_logger', 'run_package'] diff --git a/libs/lib/xaal/lib/messages.py b/libs/lib/xaal/lib/messages.py index 6c2f555a701c7636545d519726ed23d3430c6df8..2166e80da1a6a54e577a29e7d16ea544beb2424d 100644 --- a/libs/lib/xaal/lib/messages.py +++ b/libs/lib/xaal/lib/messages.py @@ -50,17 +50,17 @@ class MessageType(Enum): class MessageAction(Enum): - ALIVE = "alive" - IS_ALIVE = "is_alive" - ATTRIBUTES_CHANGE = "attributes_change" - GET_ATTRIBUTES = "get_attributes" - GET_DESCRIPTION = "get_description" + ALIVE = 'alive' + IS_ALIVE = 'is_alive' + ATTRIBUTES_CHANGE = 'attributes_change' + GET_ATTRIBUTES = 'get_attributes' + GET_DESCRIPTION = 'get_description' class Message(object): """Message object used for incomming & outgoint message""" - __slots__ = ["version", "timestamp", "source", "dev_type", "msg_type", "action", "body", "__targets"] + __slots__ = ['version', 'timestamp', 'source', 'dev_type', 'msg_type', 'action', 'body', '__targets'] def __init__(self): self.version = config.STACK_VERSION # message API version @@ -90,13 +90,13 @@ class Message(object): def dump(self): r = [] - r.append(["version", self.version]) - r.append(["targets", str(self.targets)]) - r.append(["timestamp", str(self.timestamp)]) - r.append(["source", self.source]) - r.append(["dev_type", self.dev_type]) - r.append(["msg_type", MessageType(self.msg_type)]) - r.append(["action", self.action]) + r.append(['version', self.version]) + r.append(['targets', str(self.targets)]) + r.append(['timestamp', str(self.timestamp)]) + r.append(['source', self.source]) + r.append(['dev_type', self.dev_type]) + r.append(['msg_type', MessageType(self.msg_type)]) + r.append(['action', self.action]) if self.body: tmp = "" for k, v in self.body.items(): @@ -104,8 +104,8 @@ class Message(object): v = pprint.pformat(v, width=55) tmp = tmp + "- %-12s %s\n" % (k, v) # tmp = tmp.strip() - r.append(["body", tmp]) - print(tabulate(r, headers=["Fied", "Value"], tablefmt="psql")) + r.append(['body', tmp]) + print(tabulate(r, headers=['Fied', 'Value'], tablefmt='psql')) def __repr__(self) -> str: return f"<xaal.Message {id(self):x} {self.source} {self.dev_type} {self.msg_type} {self.action}>" @@ -276,7 +276,7 @@ class MessageFactory(object): ##################################################### def build_msg( self, - dev: Optional["Device"] = None, + dev: Optional['Device'] = None, targets: list = [], msg_type: Optional[MessageType] = None, action: Optional[str] = None, @@ -308,25 +308,25 @@ class MessageFactory(object): data = self.encode_msg(message) return data - def build_alive_for(self, dev: "Device", timeout: int = 0) -> bytes: + def build_alive_for(self, dev: 'Device', timeout: int = 0) -> bytes: """Build Alive message for a given device timeout = 0 is the minimum value """ body = {} - body["timeout"] = timeout + body['timeout'] = timeout message = self.build_msg( dev=dev, targets=[], msg_type=MessageType.NOTIFY, action=MessageAction.ALIVE.value, body=body ) return message - def build_error_msg(self, dev: "Device", errcode: int, description: Optional[str] = None): + def build_error_msg(self, dev: 'Device', errcode: int, description: Optional[str] = None): """Build a Error message""" message = Message() body = {} - body["code"] = errcode + body['code'] = errcode if description: - body["description"] = description - message = self.build_msg(dev, [], MessageType.NOTIFY, "error", body) + body['description'] = description + message = self.build_msg(dev, [], MessageType.NOTIFY, 'error', body) return message diff --git a/libs/lib/xaal/lib/test.py b/libs/lib/xaal/lib/test.py index 9e9857cf0269d2b24615f6348c9a091921a28b76..d93002495e57d8270df7b653c897e89215591392 100644 --- a/libs/lib/xaal/lib/test.py +++ b/libs/lib/xaal/lib/test.py @@ -7,8 +7,8 @@ from xaal.lib import tools import logging -ADDR="b8bec7ca-f955-11e6-9031-82ed25e6aaaa" -ADDR=tools.get_random_uuid() +ADDR='b8bec7ca-f955-11e6-9031-82ed25e6aaaa' +ADDR=tools.get_random_uuid() def dump_hex(name,data): print("%s : " % name,end='=') @@ -23,30 +23,30 @@ def test_pysodium(): from xaal.lib import messages import pysodium - payload = "FooBar".encode("utf-8") + payload = 'FooBar'.encode("utf-8") ad = '[]' data = messages.build_timestamp() nonce = messages.build_nonce(data) key = tools.pass2key("My Friend Goo") - - dump_hex("Payload",payload) - dump_hex("Key",key) + + dump_hex('Payload',payload) + dump_hex('Key',key) ciph = pysodium.crypto_aead_chacha20poly1305_encrypt(payload, ad, nonce, key) - dump_hex("Ciph",ciph) - + dump_hex('Ciph',ciph) + pjson = pysodium.crypto_aead_chacha20poly1305_decrypt(ciph, ad, nonce, key) print(pjson) - + def test_device(): from xaal.lib.devices import Device addr = ADDR dev = Device("foo.basic",addr) - dev.vendor_id = "ACME" + dev.vendor_id = 'ACME' dev.url="http://acmefactory.blogspot.fr/" - dev.hw_id = "0x201" + dev.hw_id = '0x201' print(dev.getDescription()) return dev @@ -59,7 +59,7 @@ def test_msg(): def test_encode(): from xaal.lib.messages import MessageFactory - key = tools.pass2key("FooBar") + key = tools.pass2key('FooBar') factory = MessageFactory(key) m2 = factory.build_msg() print(factory.decode_msg(m2)) @@ -68,10 +68,10 @@ def test_log(): logger = logging.getLogger(__name__) logger.info("This is an INFO msg") logger.debug("This is an DEBUG msg") - + def test_engine(): - from xaal.lib.core import Engine + from xaal.lib.engine import Engine engine = Engine() engine.run() @@ -87,7 +87,7 @@ def test_crypto_decoding_error(): dev = xaal.lib.Device("test.basic",addr) eng = xaal.lib.Engine() eng.add_devices([dev,]) - eng.msg_factory.cipher_key = tools.pass2key("FakeKey") + eng.msg_factory.cipher_key = tools.pass2key('FakeKey') eng.start() eng.loop() @@ -95,14 +95,14 @@ def test_crypto_decoding_error(): def test_attr(): dev = xaal.lib.Device("test.basic",ADDR) dev.url = "http://linux.org" - dev.vendor_id = "ACME" + dev.vendor_id = 'ACME' dev.product_id = "Full Fake Device" - dev.info = "FooBar" - dev.hw_id = "ffd0001" + dev.info = 'FooBar' + dev.hw_id = 'ffd0001' #dev.alive_period = 100 - attr0 = dev.new_attribute("attr0",10) - attr1 = dev.new_attribute("attr1",False) + attr0 = dev.new_attribute('attr0',10) + attr1 = dev.new_attribute('attr1',False) eng = xaal.lib.Engine() eng.add_devices([dev,]) @@ -111,12 +111,12 @@ def test_attr(): attr0.value = attr0.value + 1 eng.add_timer(update,60) - + #eng.loop() eng.run() - - + + def run(): logger = tools.get_logger(__name__,logging.DEBUG,"%s.log" % __name__) @@ -128,13 +128,11 @@ def run(): #test_alive() #test_crypto_decoding_error() test_attr() - - + + if __name__ == '__main__': try: run() except KeyboardInterrupt: print("Bye bye...") - - diff --git a/libs/lib/xaal/lib/tools.py b/libs/lib/xaal/lib/tools.py index 2c46feb7d2cf3f15cb05776a8e9346f3f84ccb38..0c4cbac6096bc261cabb7d1774b9125b45b3095a 100644 --- a/libs/lib/xaal/lib/tools.py +++ b/libs/lib/xaal/lib/tools.py @@ -45,7 +45,7 @@ def get_cfg_filename(name: str, cfg_dir: str = config.conf_dir) -> str: def load_cfg_file(filename: str) -> Optional[ConfigObj]: """load .ini file and return it as dict""" if os.path.isfile(filename): - return ConfigObj(filename, indent_type=" ", encoding="utf8") + return ConfigObj(filename, indent_type=" ", encoding='utf8') return None @@ -65,8 +65,8 @@ def load_cfg_or_die(app_name: str) -> ConfigObj: def new_cfg(app_name: str) -> ConfigObj: filename = get_cfg_filename(app_name) cfg = ConfigObj(filename, indent_type=" ") - cfg["config"] = {} - cfg["config"]["addr"] = get_random_uuid().str + cfg['config'] = {} + cfg['config']['addr'] = get_random_uuid().str return cfg @@ -130,7 +130,7 @@ def pass2key(passphrase: str) -> bytes: # this should be: # salt = bytes(KEY_BYTES) # but due to bytes() stupid stuff in py2 we need this awfull stuff - salt = ("\00" * KEY_BYTES).encode("utf-8") + salt = ('\00' * KEY_BYTES).encode('utf-8') opslimit = pysodium.crypto_pwhash_scryptsalsa208sha256_OPSLIMIT_INTERACTIVE memlimit = pysodium.crypto_pwhash_scryptsalsa208sha256_MEMLIMIT_INTERACTIVE key = pysodium.crypto_pwhash_scryptsalsa208sha256(KEY_BYTES, buf, salt, opslimit, memlimit) @@ -141,4 +141,4 @@ def pass2key(passphrase: str) -> bytes: def reduce_addr(addr: UUID) -> str: """return a string based addred without all digits""" tmp = addr.str - return tmp[:5] + ".." + tmp[-5:] + return tmp[:5] + '..' + tmp[-5:]