1
0

state.py 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. # state.py
  2. import threading
  3. import json
  4. import os
  5. class AppState:
  6. def __init__(self):
  7. # Execution state variables
  8. self.stop_requested = False
  9. self.pause_requested = False
  10. self.pause_condition = threading.Condition()
  11. self.current_playing_file = None
  12. self.execution_progress = None
  13. self.current_playing_index = None
  14. self.current_playlist = None
  15. self.is_clearing = False
  16. self.current_theta = 0
  17. self.current_rho = 0
  18. self.speed = 350
  19. # Machine position variables
  20. self.machine_x = 0.0
  21. self.machine_y = 0.0
  22. self.STATE_FILE = "state.json"
  23. self.load()
  24. def to_dict(self):
  25. """Return a dictionary representation of the state."""
  26. return {
  27. "stop_requested": self.stop_requested,
  28. "pause_requested": self.pause_requested,
  29. "current_playing_file": self.current_playing_file,
  30. "execution_progress": self.execution_progress,
  31. "current_playing_index": self.current_playing_index,
  32. "current_playlist": self.current_playlist,
  33. "is_clearing": self.is_clearing,
  34. "current_theta": self.current_theta,
  35. "current_rho": self.current_rho,
  36. "speed": self.speed,
  37. "machine_x": self.machine_x,
  38. "machine_y": self.machine_y,
  39. }
  40. def from_dict(self, data):
  41. """Update state from a dictionary."""
  42. self.stop_requested = data.get("stop_requested", False)
  43. self.pause_requested = data.get("pause_requested", False)
  44. self.current_playing_file = data.get("current_playing_file")
  45. self.execution_progress = data.get("execution_progress")
  46. self.current_playing_index = data.get("current_playing_index")
  47. self.current_playlist = data.get("current_playlist")
  48. self.is_clearing = data.get("is_clearing", False)
  49. self.current_theta = data.get("current_theta", 0)
  50. self.current_rho = data.get("current_rho", 0)
  51. self.speed = data.get("speed", 300)
  52. self.machine_x = data.get("machine_x", 0.0)
  53. self.machine_y = data.get("machine_y", 0.0)
  54. def save(self):
  55. """Save the current state to a JSON file."""
  56. with open(self.STATE_FILE, "w") as f:
  57. json.dump(self.to_dict(), f)
  58. def load(self):
  59. """Load state from a JSON file. If the file doesn't exist, create it with default values."""
  60. if not os.path.exists(self.STATE_FILE):
  61. # File doesn't exist: create one with the current (default) state.
  62. self.save()
  63. return
  64. try:
  65. with open(self.STATE_FILE, "r") as f:
  66. data = json.load(f)
  67. self.from_dict(data)
  68. except Exception as e:
  69. print(f"Error loading state from {self.STATE_FILE}: {e}")
  70. # Create a singleton instance that you can import elsewhere:
  71. state = AppState()