state.py 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. # state.py
  2. import threading
  3. import json
  4. import os
  5. import logging
  6. logger = logging.getLogger(__name__)
  7. class AppState:
  8. def __init__(self):
  9. # Private variables for properties
  10. self._current_playing_file = None
  11. self._pause_requested = False
  12. self._speed = 150
  13. self._current_playlist = None
  14. self._current_playlist_name = None # New variable for playlist name
  15. # Regular state variables
  16. self.stop_requested = False
  17. self.pause_condition = threading.Condition()
  18. self.execution_progress = None
  19. self.is_clearing = False
  20. self.current_theta = 0
  21. self.current_rho = 0
  22. self.current_playlist_index = 0
  23. self.playlist_mode = "loop"
  24. # Machine position variables
  25. self.machine_x = 0.0
  26. self.machine_y = 0.0
  27. self.x_steps_per_mm = 0.0
  28. self.y_steps_per_mm = 0.0
  29. self.gear_ratio = 10
  30. # 0 for crash homing, 1 for auto homing
  31. self.homing = 0
  32. self.STATE_FILE = "state.json"
  33. self.mqtt_handler = None # Will be set by the MQTT handler
  34. self.conn = None
  35. self.port = None
  36. self.wled_ip = None
  37. self._playlist_mode = "loop"
  38. self._pause_time = 0
  39. self._clear_pattern = "none"
  40. self.load()
  41. @property
  42. def current_playing_file(self):
  43. return self._current_playing_file
  44. @current_playing_file.setter
  45. def current_playing_file(self, value):
  46. self._current_playing_file = value
  47. # force an empty string (and not None) if we need to unset
  48. if value == None:
  49. value = ""
  50. if self.mqtt_handler:
  51. is_running = bool(value and not self._pause_requested)
  52. self.mqtt_handler.update_state(current_file=value, is_running=is_running)
  53. @property
  54. def pause_requested(self):
  55. return self._pause_requested
  56. @pause_requested.setter
  57. def pause_requested(self, value):
  58. self._pause_requested = value
  59. if self.mqtt_handler:
  60. is_running = bool(self._current_playing_file and not value)
  61. self.mqtt_handler.update_state(is_running=is_running)
  62. @property
  63. def speed(self):
  64. return self._speed
  65. @speed.setter
  66. def speed(self, value):
  67. self._speed = value
  68. if self.mqtt_handler and self.mqtt_handler.is_enabled:
  69. self.mqtt_handler.client.publish(f"{self.mqtt_handler.speed_topic}/state", value, retain=True)
  70. @property
  71. def current_playlist(self):
  72. return self._current_playlist
  73. @current_playlist.setter
  74. def current_playlist(self, value):
  75. self._current_playlist = value
  76. # force an empty string (and not None) if we need to unset
  77. if value == None:
  78. value = ""
  79. # Also clear the playlist name when playlist is cleared
  80. self._current_playlist_name = None
  81. if self.mqtt_handler:
  82. self.mqtt_handler.update_state(playlist=value, playlist_name=None)
  83. @property
  84. def current_playlist_name(self):
  85. return self._current_playlist_name
  86. @current_playlist_name.setter
  87. def current_playlist_name(self, value):
  88. self._current_playlist_name = value
  89. if self.mqtt_handler:
  90. self.mqtt_handler.update_state(playlist_name=value)
  91. @property
  92. def playlist_mode(self):
  93. return self._playlist_mode
  94. @playlist_mode.setter
  95. def playlist_mode(self, value):
  96. self._playlist_mode = value
  97. @property
  98. def pause_time(self):
  99. return self._pause_time
  100. @pause_time.setter
  101. def pause_time(self, value):
  102. self._pause_time = value
  103. @property
  104. def clear_pattern(self):
  105. return self._clear_pattern
  106. @clear_pattern.setter
  107. def clear_pattern(self, value):
  108. self._clear_pattern = value
  109. def to_dict(self):
  110. """Return a dictionary representation of the state."""
  111. return {
  112. "stop_requested": self.stop_requested,
  113. "pause_requested": self._pause_requested,
  114. "current_playing_file": self._current_playing_file,
  115. "execution_progress": self.execution_progress,
  116. "is_clearing": self.is_clearing,
  117. "current_theta": self.current_theta,
  118. "current_rho": self.current_rho,
  119. "speed": self._speed,
  120. "machine_x": self.machine_x,
  121. "machine_y": self.machine_y,
  122. "x_steps_per_mm": self.x_steps_per_mm,
  123. "y_steps_per_mm": self.y_steps_per_mm,
  124. "gear_ratio": self.gear_ratio,
  125. "homing": self.homing,
  126. "current_playlist": self._current_playlist,
  127. "current_playlist_name": self._current_playlist_name,
  128. "current_playlist_index": self.current_playlist_index,
  129. "playlist_mode": self._playlist_mode,
  130. "pause_time": self._pause_time,
  131. "clear_pattern": self._clear_pattern,
  132. "port": self.port,
  133. "wled_ip": self.wled_ip
  134. }
  135. def from_dict(self, data):
  136. """Update state from a dictionary."""
  137. self.stop_requested = data.get("stop_requested", False)
  138. self._pause_requested = data.get("pause_requested", False)
  139. self._current_playing_file = data.get("current_playing_file")
  140. self.execution_progress = data.get("execution_progress")
  141. self.is_clearing = data.get("is_clearing", False)
  142. self.current_theta = data.get("current_theta", 0)
  143. self.current_rho = data.get("current_rho", 0)
  144. self._speed = data.get("speed", 150)
  145. self.machine_x = data.get("machine_x", 0.0)
  146. self.machine_y = data.get("machine_y", 0.0)
  147. self.x_steps_per_mm = data.get("x_steps_per_mm", 0.0)
  148. self.y_steps_per_mm = data.get("y_steps_per_mm", 0.0)
  149. self.gear_ratio = data.get('gear_ratio', 10)
  150. self.homing = data.get('homing', 0)
  151. self._current_playlist = data.get("current_playlist")
  152. self._current_playlist_name = data.get("current_playlist_name")
  153. self.current_playlist_index = data.get("current_playlist_index")
  154. self._playlist_mode = data.get("playlist_mode", "loop")
  155. self._pause_time = data.get("pause_time", 0)
  156. self._clear_pattern = data.get("clear_pattern", "none")
  157. self.port = data.get("port", None)
  158. self.wled_ip = data.get('wled_ip', None)
  159. def save(self):
  160. """Save the current state to a JSON file."""
  161. try:
  162. with open(self.STATE_FILE, "w") as f:
  163. json.dump(self.to_dict(), f)
  164. except Exception as e:
  165. print(f"Error saving state to {self.STATE_FILE}: {e}")
  166. def load(self):
  167. """Load state from a JSON file. If the file doesn't exist, create it with default values."""
  168. if not os.path.exists(self.STATE_FILE):
  169. # File doesn't exist: create one with the current (default) state.
  170. self.save()
  171. return
  172. try:
  173. with open(self.STATE_FILE, "r") as f:
  174. data = json.load(f)
  175. self.from_dict(data)
  176. except Exception as e:
  177. print(f"Error loading state from {self.STATE_FILE}: {e}")
  178. def update_steps_per_mm(self, x_steps, y_steps):
  179. """Update and save steps per mm values."""
  180. self.x_steps_per_mm = x_steps
  181. self.y_steps_per_mm = y_steps
  182. self.save()
  183. def reset_state(self):
  184. """Reset all state variables to their default values."""
  185. self.__init__() # Reinitialize the state
  186. self.save()
  187. def cleanup(self):
  188. """Clean up AppState resources."""
  189. try:
  190. # Notify all waiting threads and clean up the condition
  191. if self.pause_condition:
  192. try:
  193. with self.pause_condition:
  194. self.pause_condition.notify_all()
  195. # Release the underlying lock resources
  196. self.pause_condition._lock._release_save()
  197. self.pause_condition._lock = None
  198. except Exception as e:
  199. logger.error(f"Error cleaning up pause condition: {e}")
  200. finally:
  201. self.pause_condition = None
  202. # Clean up other resources
  203. if self.conn:
  204. try:
  205. self.conn.close()
  206. except Exception as e:
  207. logger.error(f"Error closing connection: {e}")
  208. finally:
  209. self.conn = None
  210. self.mqtt_handler = None
  211. logger.info("AppState resources cleaned up")
  212. except Exception as e:
  213. logger.error(f"Error during AppState cleanup: {e}")
  214. raise
  215. # Create a singleton instance that you can import elsewhere:
  216. state = AppState()