-
Notifications
You must be signed in to change notification settings - Fork 1
Refactor commands #13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Draft
PaulMarisOUMary
wants to merge
20
commits into
main
Choose a base branch
from
refactor-commands
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
+1,650
−883
Conversation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- Allow GroupCommands to access command via name - len(GroupCommands) should be more efficient - Comparing two GroupCommands instance more permissive - Support x in GroupCommands -> bool - Small __iter__ refactor in GroupCommands - Fixed __repr__ naming
- Fix repr class name for subclasses - Selfregister every Modes0X
- Update usage of Mode enum to consistently use the get_from
Owner
Author
|
For reference, the following GroupMode/GroupCommand alternative was considered: from __future__ import annotations
from enum import Enum, unique
from typing import Container, Dict, Generator, Iterable, Optional, Type, Union, overload
@unique
class Mode(Enum):
REQUEST = 0x01
...
VEHICLE_INFO = 0x09
class Command:
def __init__(
self,
mode: Union[Mode, int, str],
pid: Union[int, str],
expected_bytes: Optional[int]=None,
) -> None:
self.mode = mode
self.pid = pid
...
class GroupCommandsMeta(type, Iterable[Command], Container[Command]):
def __iter__(cls) -> Generator[Command, None, None]:
for attr_name in dir(cls):
if attr_name.startswith('_'):
continue
attr = getattr(cls, attr_name)
if isinstance(attr, Command):
yield attr
def __len__(cls) -> int:
return sum(1 for _ in cls)
def __contains__(cls, item: Union[Command, str]) -> bool:
if isinstance(item, str):
return isinstance(getattr(cls, item.upper(), None), Command)
elif isinstance(item, Command):
return any(item is cmd for cmd in cls)
return False
def __getitem__(cls, key: Union[int, str]) -> Command:
if isinstance(key, str):
key_upper = key.upper()
item = getattr(cls, key_upper, None)
if not isinstance(item, Command):
raise KeyError(f"Command '{key}' not found in {cls.__name__}")
return item
elif isinstance(key, int):
for cmd in cls:
if cmd.pid == key:
return cmd
raise KeyError(f"No command found with PID {hex(key)} in {cls.__name__}")
raise TypeError(f"Invalid key type: {type(key).__name__}. Expected str or int")
class GroupCommands(metaclass=GroupCommandsMeta):
__abstract__ = True
_registry: Dict[str, Type[GroupCommands]] = {}
def __init_subclass__(cls, registry_key: Optional[Union[int, Mode]] = None, **kwargs) -> None:
super().__init_subclass__(**kwargs)
if registry_key is not None and not cls.__dict__.get("__abstract__", False):
value = registry_key.value if isinstance(registry_key, Mode) else registry_key
if value is not None:
cls._registry[str(value)] = cls
class Mode01(GroupCommands, registry_key=Mode.REQUEST):
ENGINE_SPEED = Command("01", 0x0C, 4)
...
class Mode09(GroupCommands, registry_key=Mode.VEHICLE_INFO):
SUPPORTED_PIDS_9 = Command("09", 0x00, 0x04)
...
... # More modes defined similarly
class Modes(Mode01,Mode09):
__abstract__ = True
class GroupModesMeta(GroupCommandsMeta):
"""Metaclass for GroupModes that handles both Command and Mode lookups."""
@overload
def __getitem__(cls, key: str) -> Command: ...
@overload
def __getitem__(cls, key: Union[Mode, int]) -> Type[GroupCommands]: ...
def __getitem__(cls, key: Union[Mode, int, str]) -> Union[Command, Type[GroupCommands]]:
"""Allows Class[key] syntax for both commands (str) and modes (Mode/int)."""
if isinstance(key, str):
return super().__getitem__(key)
mode_value = key.value if isinstance(key, Mode) else key
mode_cls = getattr(cls, "_registry", {}).get(str(mode_value))
if mode_cls is None:
raise KeyError(f"Mode '{hex(mode_value) if isinstance(mode_value, int) else mode_value}' not found in registry")
return mode_cls
class GroupModes(Modes, metaclass=GroupModesMeta): ...
if __name__ == "__main__":
# Allowed syntax
print(GroupModes)
print(GroupModes[1], GroupModes[Mode.REQUEST])
print(GroupModes[9], GroupModes[Mode.VEHICLE_INFO])
print(GroupModes["ENGINE_SPEED"], GroupModes.ENGINE_SPEED, Mode01["ENGINE_SPEED"], Mode01.ENGINE_SPEED)
# iterating through GroupModes[MODE_VALUE] or GroupModes[Mode.X] will also work
for cmd in GroupModes:
print(f"{cmd}")
print(len(GroupModes))
print(GroupModes._registry)
print(GroupModes["ENGINE_SPEED"] in Mode01)
print(GroupModes["ENGINE_SPEED"] in Mode09) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Summary
Templateclass for Command's pids parameterizationCommandclassCommand.descriptionCommand.formula->Command.resolverCommand.n_bytes->Command.expected_bytescommand_args,nameanddescriptionhas been removed from__init__GroupCommandclassregistry_idfor registering (e.g.class Mode01(GroupCommands, registry_id=Mode.REQUEST): ...)GroupModeclassBaseEnumparent classget_fromclassmethodhasclassmethodChecklist