added packet initializer and str/repr
This commit is contained in:
parent
093be0058f
commit
e4a1a374e4
3 changed files with 36 additions and 15 deletions
|
@ -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"
|
||||
|
|
|
@ -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):
|
||||
|
|
|
@ -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)})"
|
||||
|
||||
|
||||
|
|
Loading…
Reference in a new issue