base.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. # -*- coding: utf-8 -*-
  2. """
  3. Basis-Klasse für Netzwerk-Befehle.
  4. """
  5. import uuid
  6. from dataclasses import dataclass, field
  7. from datetime import datetime
  8. from typing import Any
  9. @dataclass
  10. class CommandMessage:
  11. """
  12. Basisklasse für alle Netzwerk-Befehle.
  13. Jeder Befehl hat eine eindeutige ID und einen Zeitstempel
  14. für Tracking und Debugging.
  15. """
  16. message_id: str = field(default_factory=lambda: str(uuid.uuid4()))
  17. timestamp: datetime = field(default_factory=datetime.now)
  18. def to_dict(self) -> dict[str, Any]:
  19. """Konvertiert die Nachricht in ein Dictionary."""
  20. result: dict[str, Any] = {}
  21. for key, value in self.__dict__.items():
  22. if isinstance(value, datetime):
  23. result[key] = value.isoformat()
  24. else:
  25. result[key] = value
  26. return result
  27. @classmethod
  28. def from_dict(cls, data: dict[str, Any]) -> "CommandMessage":
  29. """Erstellt eine Nachricht aus einem Dictionary."""
  30. if "timestamp" in data and isinstance(data["timestamp"], str):
  31. data["timestamp"] = datetime.fromisoformat(data["timestamp"])
  32. return cls(**data)