state.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. """What the screen shows, shared by the MPD client, the log and the renderer."""
  2. import time
  3. LOG_ROWS = 7
  4. LOG_COLS = 44
  5. PLAY_UNKNOWN, PLAY_PLAYING, PLAY_PAUSED, PLAY_STOPPED = range(4)
  6. # Key identifiers, as the C version's enum radio_key; the names are what
  7. # --press and the help text use.
  8. KEYS = ("esc", "next", "stop", "menu", "list", "up", "prev",
  9. "right", "down", "pause", "ok", "left", "play")
  10. def monotonic_ms():
  11. return int(time.monotonic() * 1000)
  12. class QueueEntry(object):
  13. """One song of the MPD queue, as the playlist screen shows it"""
  14. __slots__ = ("artist", "title", "fallback", "duration_s")
  15. def __init__(self, artist, title, fallback, duration_s):
  16. self.artist = artist # both set, or the line shows the fallback
  17. self.title = title
  18. self.fallback = fallback # the main screen's title text
  19. self.duration_s = duration_s # -1: unknown, e.g. a stream
  20. class RadioState(object):
  21. def __init__(self, server=""):
  22. self.connected = False
  23. self.server = server
  24. self.state = PLAY_UNKNOWN
  25. self.title = ""
  26. self.song_pos = -1 # -1: none
  27. self.queue_len = 0
  28. self.elapsed_ms = 0
  29. self.elapsed_stamp_ms = 0 # monotonic time elapsed_ms was read
  30. self.total_ms = 0 # 0: unknown, e.g. a stream
  31. self.volume = -1 # -1: unknown
  32. self.repeat = False
  33. self.random = False
  34. self.log = [""] * LOG_ROWS # wrapped rows, oldest first
  35. self.playlist = None # list of QueueEntry; None: not fetched
  36. self.list_open = False # the playlist screen is shown
  37. self.list_sel = -1 # selected queue position; -1: not yet set
  38. def current_elapsed_ms(self):
  39. """Position, advanced locally between MPD updates while playing"""
  40. ms = self.elapsed_ms
  41. # with the link down the player's position is unknown, so hold it
  42. if not self.connected or self.state != PLAY_PLAYING or not self.elapsed_stamp_ms:
  43. return ms
  44. ms += monotonic_ms() - self.elapsed_stamp_ms
  45. return min(ms, self.total_ms) if self.total_ms else ms
  46. def log_append(self, text):
  47. """Wrap text into rows of LOG_COLS characters and scroll them in"""
  48. text = text.replace("\n", " ").replace("\t", " ")
  49. while True:
  50. row, text = text[:LOG_COLS], text[LOG_COLS:]
  51. self.log = self.log[1:] + [row]
  52. if not text:
  53. break