From e4a1a374e4917adae955b1c73d4f65bd22c80cfd Mon Sep 17 00:00:00 2001 From: alemi Date: Tue, 12 Oct 2021 01:46:03 +0200 Subject: [PATCH] added packet initializer and str/repr --- aiocraft/__init__.py | 2 +- aiocraft/mc/mctypes.py | 2 +- aiocraft/mc/packet.py | 47 ++++++++++++++++++++++++++++++------------ 3 files changed, 36 insertions(+), 15 deletions(-) diff --git a/aiocraft/__init__.py b/aiocraft/__init__.py index 70a7d58..acaa292 100644 --- a/aiocraft/__init__.py +++ b/aiocraft/__init__.py @@ -1,5 +1,5 @@ """aiocraft is an asyncio-driven headless minecraft client""" -from .session import Session +from .client import Client from .mc import * __version__ = "0.0.1" diff --git a/aiocraft/mc/mctypes.py b/aiocraft/mc/mctypes.py index 6151466..6adeefa 100644 --- a/aiocraft/mc/mctypes.py +++ b/aiocraft/mc/mctypes.py @@ -12,7 +12,7 @@ class Type(object): return struct.pack(cls._fmt, data) @classmethod - def unserialize(cls, data:bytes) -> Any: + def deserialize(cls, data:bytes) -> Any: return struct.unpack(cls._fmt, data)[0] class Boolean(Type): diff --git a/aiocraft/mc/packet.py b/aiocraft/mc/packet.py index 3b7dac9..0b5fb67 100644 --- a/aiocraft/mc/packet.py +++ b/aiocraft/mc/packet.py @@ -1,21 +1,42 @@ -from typing import Tuple +import json +from typing import Tuple, Dict -from .mctypes import Type +from .mctypes import Type, VarInt class Packet: id : int - _slots : Tuple[Tuple[str, Type]] + slots : Tuple[Tuple[str, Type]] - def serialize(self) -> bytes: - return b''.join( - slot[1].serialize(getattr(self, slot[0])) - for slot in self._slots - ) + _ids : Dict[int, int] # definitions are compiled at install time + _slots : Dict[int, Tuple[Tuple[str, Type]]] # definitions are compiled at install time + + def __init__(self, proto:int, **kwargs): + self._protocol = proto + self.slots = self._slots[proto] + self.id = self._ids[proto] + for name, t in self.slots: + setattr(self, name, t._pytype(kwargs[name]) if name in kwargs else None) @classmethod - def deserialize(cls, data:bytes): - pkt = cls() - for slot in cls._slots: - setattr(pkt, slot[0], slot[1].deserialize(data)) - return pkt + def deserialize(cls, proto:int, data:bytes): + return cls(proto, **{ name : t.deserialize(data) for (name, t) in cls._slots[proto] }) + + def serialize(self) -> bytes: + return VarInt.serialize(self.id) + b''.join( + slot[1].serialize(getattr(self, slot[0], None)) + for slot in self.slots + ) + + def __str__(self) -> str: + obj = {} # could be done with dict comp but the _ key gets put last :( + obj["_"] = self.__class__.__name__ + obj["_proto"] = self._protocol + for key, t in self.slots: + obj[key] = getattr(self, key, None) + return json.dumps(obj, indent=2, default=str) + + def __repr__(self) -> str: + attrs = (f"{key}={repr(getattr(self, key, None))}" for (key, t) in self.slots) + return f"{self.__class__.__name__}({self._protocol}, {', '.join(attrs)})" +