packet.py 832 B

123456789101112131415161718192021222324252627282930
  1. #Simple packet type for the simple protocol
  2. import struct
  3. class Packet(object):
  4. def __init__(self, cmd, *data):
  5. self.cmd = cmd
  6. self.data = data
  7. if len(data) > 8:
  8. raise ValueError('Too many data')
  9. self.data = list(self.data) + [0] * (8-len(self.data))
  10. @classmethod
  11. def FromStr(cls, s):
  12. parts = struct.unpack('>9L', s)
  13. return cls(parts[0], *parts[1:])
  14. def __str__(self):
  15. return struct.pack('>L'+('L'*len(self.data)), self.cmd, *self.data)
  16. class CMD:
  17. KA = 0 # No important data
  18. PING = 1 # Data are echoed exactly
  19. QUIT = 2 # No important data
  20. PLAY = 3 # seconds, microseconds, frequency (Hz), amplitude (0-255), port
  21. CAPS = 4 # ports, client type (1), user ident (2-7)
  22. def itos(i):
  23. return struct.pack('>L', i)
  24. def stoi(s):
  25. return struct.unpack('>L', s)[0]