-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig_manager.py
More file actions
258 lines (208 loc) Β· 8.41 KB
/
Copy pathconfig_manager.py
File metadata and controls
258 lines (208 loc) Β· 8.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
"""
BabySynth - Configuration Manager
Handles loading, saving, validating, and hot-reloading of YAML configurations.
Supports advanced features like animations, chord progressions, themes, and macros.
"""
import yaml
import os
import time
import threading
from pathlib import Path
class ConfigManager:
"""Manages BabySynth YAML configurations with hot-reload support"""
def __init__(self, default_config='config.yaml'):
self.default_config = default_config
self.current_config = None
self.config_path = default_config
self.last_modified = 0
self.watch_thread = None
self.watching = False
self.on_reload_callback = None
def load(self, config_path=None):
"""Load a configuration file"""
if config_path:
self.config_path = config_path
try:
with open(self.config_path, 'r') as file:
self.current_config = yaml.safe_load(file)
self.last_modified = os.path.getmtime(self.config_path)
self._validate_config()
print(f"β
Config loaded: {self.config_path}")
return self.current_config
except Exception as e:
print(f"β Error loading config: {e}")
return None
def save(self, config, config_path=None):
"""Save a configuration to file"""
if config_path:
self.config_path = config_path
try:
# Ensure directory exists
Path(self.config_path).parent.mkdir(parents=True, exist_ok=True)
with open(self.config_path, 'w') as file:
yaml.safe_dump(config, file, default_flow_style=False, sort_keys=False)
self.current_config = config
self.last_modified = os.path.getmtime(self.config_path)
print(f"πΎ Config saved: {self.config_path}")
return True
except Exception as e:
print(f"β Error saving config: {e}")
return False
def _validate_config(self):
"""Validate configuration structure"""
if not self.current_config:
raise ValueError("Configuration is empty")
required_keys = ['models', 'scales', 'colors']
for key in required_keys:
if key not in self.current_config:
print(f"β οΈ Warning: Missing required key '{key}' in config")
# Validate models
if 'models' in self.current_config:
for model_name, model_data in self.current_config['models'].items():
if 'layout' not in model_data:
raise ValueError(f"Model '{model_name}' missing layout")
return True
def start_watching(self, callback=None):
"""Start watching config file for changes (hot-reload)"""
self.on_reload_callback = callback
self.watching = True
self.watch_thread = threading.Thread(target=self._watch_file, daemon=True)
self.watch_thread.start()
print(f"π Watching {self.config_path} for changes...")
def stop_watching(self):
"""Stop watching config file"""
self.watching = False
if self.watch_thread:
self.watch_thread.join(timeout=1)
def _watch_file(self):
"""Watch file for modifications and reload"""
while self.watching:
try:
current_mtime = os.path.getmtime(self.config_path)
if current_mtime > self.last_modified:
print(f"π Config file changed, reloading...")
old_config = self.current_config
self.load()
if self.on_reload_callback:
self.on_reload_callback(self.current_config, old_config)
except Exception as e:
print(f"β οΈ Error watching file: {e}")
time.sleep(1) # Check every second
def get_animation(self, name):
"""Get an animation sequence by name"""
if 'animations' in self.current_config:
return self.current_config['animations'].get(name)
return None
def get_chord_progression(self, name):
"""Get a chord progression by name"""
if 'chord_progressions' in self.current_config:
return self.current_config['chord_progressions'].get(name)
return None
def get_theme(self, name):
"""Get a color theme by name"""
if 'themes' in self.current_config:
return self.current_config['themes'].get(name)
return None
def get_macro(self, name):
"""Get a macro by name"""
if 'macros' in self.current_config:
return self.current_config['macros'].get(name)
return None
def list_configs(self, directory='configs'):
"""List all available configuration files"""
configs = []
# Main config
if os.path.exists('config.yaml'):
configs.append('config.yaml')
# Configs directory
if os.path.exists(directory):
for filename in os.listdir(directory):
if filename.endswith('.yaml') or filename.endswith('.yml'):
configs.append(os.path.join(directory, filename))
return configs
def apply_theme(self, theme_name):
"""Apply a theme to the current config colors"""
theme = self.get_theme(theme_name)
if theme:
self.current_config['colors'] = theme
print(f"π¨ Applied theme: {theme_name}")
return True
return False
class AnimationPlayer:
"""Plays LED animations defined in YAML"""
def __init__(self, launchpad, web_broadcaster=None):
self.lp = launchpad
self.web_broadcaster = web_broadcaster
self.playing = False
self.play_thread = None
def play(self, animation_data):
"""Play an animation sequence"""
if not animation_data:
return
self.playing = True
self.play_thread = threading.Thread(
target=self._play_animation,
args=(animation_data,),
daemon=True
)
self.play_thread.start()
def _play_animation(self, animation_data):
"""Animation playback loop"""
duration = animation_data.get('duration', 2.0)
loop = animation_data.get('loop', False)
frames = animation_data.get('frames', [])
while self.playing:
for frame in frames:
if not self.playing:
break
delay = frame.get('delay', 0.1)
pattern = frame.get('pattern', [])
# Apply pattern to grid
for y, row in enumerate(pattern):
for x, color in enumerate(row):
if x < 9 and y < 9:
self.lp.panel.led(x, y).color = tuple(color)
if self.web_broadcaster:
self.web_broadcaster.update_led(x, y, color)
time.sleep(delay)
if not loop:
break
def stop(self):
"""Stop animation playback"""
self.playing = False
if self.play_thread:
self.play_thread.join(timeout=1)
class ChordPlayer:
"""Plays chord progressions"""
def __init__(self, synth):
self.synth = synth
def play_progression(self, progression):
"""Play a chord progression"""
# progression is a list of note names like ['C', 'F', 'G', 'C']
print(f"π΅ Playing chord progression: {progression}")
# Implementation would trigger multiple notes at once
# This is a placeholder for the actual implementation
# Example usage
if __name__ == '__main__':
manager = ConfigManager()
config = manager.load('config.yaml')
print("\nπ Current Configuration:")
print(f"Name: {config.get('name')}")
print(f"Models: {list(config.get('models', {}).keys())}")
print(f"Scales: {list(config.get('scales', {}).keys())}")
# List all configs
print("\nπ Available Configurations:")
for cfg in manager.list_configs():
print(f" - {cfg}")
# Test hot-reload
def on_reload(new_config, old_config):
print("π₯ Hot reload triggered!")
print(f"Old: {old_config.get('name')}")
print(f"New: {new_config.get('name')}")
manager.start_watching(callback=on_reload)
try:
while True:
time.sleep(1)
except KeyboardInterrupt:
manager.stop_watching()
print("\nπ Stopped watching")