packet.py 670 B

1234567891011121314151617181920212223
  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)