packet.py 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. try:
  13. parts = struct.unpack('>9L', s)
  14. return cls(parts[0], *parts[1:])
  15. except Exception:
  16. raise ValueError('Failed to unpack %r' % s)
  17. def as_float(self, i):
  18. return struct.unpack('>f', struct.pack('>L', self.data[i]))[0]
  19. def __str__(self):
  20. return struct.pack('>L'+(''.join('f' if isinstance(i, float) else 'L' for i in self.data)), self.cmd, *self.data)
  21. def __bytes__(self):
  22. return self.__str__()
  23. class CMD:
  24. KA = 0 # No important data
  25. PING = 1 # Data are echoed exactly
  26. QUIT = 2 # No important data
  27. PLAY = 3 # seconds, microseconds, frequency (Hz), amplitude (0.0 - 1.0), port, flags
  28. CAPS = 4 # ports, client type (1), user ident (2-7)
  29. PCM = 5 # 16 samples, encoded S16_LE
  30. PCMSYN = 6 # number of samples which should be buffered right now
  31. ARTP = 7 # voice (or -1 = OBLIGATE_POLYPHONE for global), index, value(f32)
  32. class PLF:
  33. SAMEPHASE = 0x1
  34. def itos(i):
  35. return struct.pack('>L', i).rstrip(b'\0')
  36. def stoi(s):
  37. return struct.unpack('>L', s.ljust(4, b'\0'))[0]
  38. OBLIGATE_POLYPHONE = 0xffffffff