state.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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.is_clearing = False
  14. self.current_theta = 0
  15. self.current_rho = 0
  16. self.speed = 350
  17. # Machine position variables
  18. self.machine_x = 0.0
  19. self.machine_y = 0.0
  20. self.STATE_FILE = "state.json"
  21. self.load()
  22. def to_dict(self):
  23. """Return a dictionary representation of the state."""
  24. return {
  25. "stop_requested": self.stop_requested,
  26. "pause_requested": self.pause_requested,
  27. "current_playing_file": self.current_playing_file,
  28. "execution_progress": self.execution_progress,
  29. "is_clearing": self.is_clearing,
  30. "current_theta": self.current_theta,
  31. "current_rho": self.current_rho,
  32. "speed": self.speed,
  33. "machine_x": self.machine_x,
  34. "machine_y": self.machine_y,
  35. }
  36. def from_dict(self, data):
  37. """Update state from a dictionary."""
  38. self.stop_requested = data.get("stop_requested", False)
  39. self.pause_requested = data.get("pause_requested", False)
  40. self.current_playing_file = data.get("current_playing_file")
  41. self.execution_progress = data.get("execution_progress")
  42. self.is_clearing = data.get("is_clearing", False)
  43. self.current_theta = data.get("current_theta", 0)
  44. self.current_rho = data.get("current_rho", 0)
  45. self.speed = data.get("speed", 300)
  46. self.machine_x = data.get("machine_x", 0.0)
  47. self.machine_y = data.get("machine_y", 0.0)
  48. def save(self):
  49. """Save the current state to a JSON file."""
  50. with open(self.STATE_FILE, "w") as f:
  51. json.dump(self.to_dict(), f)
  52. def load(self):
  53. """Load state from a JSON file. If the file doesn't exist, create it with default values."""
  54. if not os.path.exists(self.STATE_FILE):
  55. # File doesn't exist: create one with the current (default) state.
  56. self.save()
  57. return
  58. try:
  59. with open(self.STATE_FILE, "r") as f:
  60. data = json.load(f)
  61. self.from_dict(data)
  62. except Exception as e:
  63. print(f"Error loading state from {self.STATE_FILE}: {e}")
  64. # Create a singleton instance that you can import elsewhere:
  65. state = AppState()