-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmapping_app.py
More file actions
310 lines (251 loc) · 11 KB
/
mapping_app.py
File metadata and controls
310 lines (251 loc) · 11 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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
import os
import json
import threading
import time
from pathlib import Path
from enum import Enum
from typing import Optional
import asyncio
from ros2 import StartEverything, StopEverything, GetInitStatus
from finalize_mapping import do_finalize
# Default mapping settings with options/range format
DEFAULT_MAPPING_SETTINGS = {
"preview_voxel_size": {
"options": [5, 10, 15], # cm
"current_selection": 1
},
"file_format": {
"options": ["PLY", "PCD", "LAS", "LAZ"],
"current_selection": 1
},
"map_quality": {
"options": ["Low", "Mid", "High"],
"current_selection": 1
}
}
class MappingState(Enum):
"""
Mapping operation state machine.
Lifecycle:
IDLE → STARTING → INITIALIZING → RUNNING → STOPPING → IDLE
ERROR state can be entered from any state on failure.
"""
IDLE = "idle"
STARTING = "starting" # Creating ROS2 nodes
INITIALIZING = "initializing" # Nodes exist, waiting for IMU stabilization
RUNNING = "running" # IMU stabilized, actively mapping
STOPPING = "stopping" # Destroying nodes
ERROR = "error"
class MappingApp:
"""Handles mapping/spatial scan settings and ROS2 node lifecycle management."""
def __init__(self, data_path: str, catalog=None):
self.settings_path = os.path.join(data_path, "mapping_settings.json")
self.settings = self._load_settings()
self.active_settings = self.settings.copy()
self.catalog = catalog
# ROS2 and mapping configuration
self.artifact_dir = os.path.join(data_path, "mapping_artifact")
# State machine for start/stop operations
self.state = MappingState.IDLE
self._state_lock = asyncio.Lock()
self._process_error = None
self._polling_task = None
self._name_prefix: Optional[str] = None # Prefix for catalog item name
def _load_settings(self):
"""Load settings from disk or return defaults."""
try:
with open(self.settings_path, 'r') as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError):
return DEFAULT_MAPPING_SETTINGS.copy()
def _save_settings(self):
"""Save settings to disk."""
with open(self.settings_path, 'w') as f:
json.dump(self.settings, f, indent=2)
def get_settings(self):
"""Return current settings."""
return self.active_settings
def _validate_settings(self, settings: dict) -> tuple[dict, list]:
"""Validate and sanitize settings.
Handles two formats:
1. Full format: {"key": {"options": [...], "current_selection": N}}
2. Flat format: {"key": value} - value matched against current options
Returns:
tuple: (validated_settings, list of invalid keys)
"""
validated = {}
invalid_keys = []
for key, value in settings.items():
# Check if this is a known setting
if key not in self.settings:
invalid_keys.append(key)
continue
current_setting = self.settings[key]
if isinstance(value, dict):
# Full format: {"options": [...], "current_selection": N}
if "options" in value and "current_selection" in value:
options = value["options"]
selection = value["current_selection"]
if not isinstance(selection, int) or selection < 0 or selection >= len(options):
selection = 0 # Reset to default if invalid
validated[key] = {
"options": options,
"current_selection": selection
}
elif "range" in value and "current_selection" in value:
range_vals = value["range"]
selection = value["current_selection"]
if not isinstance(selection, (int, float)):
selection = range_vals[0]
selection = max(range_vals[0], min(range_vals[1], selection))
validated[key] = {
"range": range_vals,
"current_selection": selection
}
else:
validated[key] = value
else:
# Flat format: value to match against options
if "options" in current_setting:
options = current_setting["options"]
if value in options:
# Valid value - find its index
validated[key] = {
"options": options,
"current_selection": options.index(value)
}
else:
# Invalid value - mark as invalid, keep current setting
invalid_keys.append(key)
validated[key] = current_setting.copy()
elif "range" in current_setting:
range_vals = current_setting["range"]
if isinstance(value, (int, float)) and range_vals[0] <= value <= range_vals[1]:
validated[key] = {
"range": range_vals,
"current_selection": value
}
else:
invalid_keys.append(key)
validated[key] = current_setting.copy()
else:
validated[key] = value
# Preserve settings not in the update
for key in self.settings:
if key not in validated:
validated[key] = self.settings[key].copy() if isinstance(self.settings[key], dict) else self.settings[key]
return validated, invalid_keys
def save_settings(self, new_settings: dict):
"""Update and save settings.
When idle, active_settings is also updated immediately.
When mapping is running, active_settings updates after stop.
Raises:
ValueError: If any settings have invalid values (still updates valid ones)
"""
validated, invalid_keys = self._validate_settings(new_settings)
self.settings = validated
self._save_settings()
# When idle, sync active_settings immediately
if self.state == MappingState.IDLE:
self.active_settings = self.settings.copy()
# Raise error if there were invalid values
if invalid_keys:
raise ValueError(f"Invalid settings: {', '.join(invalid_keys)}")
return self.settings
def _get_setting_value(self, key: str):
"""Get the actual value of a setting (resolves current_selection)."""
setting = self.active_settings.get(key, {})
if "options" in setting:
idx = setting.get("current_selection", 0)
return setting["options"][idx]
elif "range" in setting:
return setting.get("current_selection", setting["range"][0])
return None
async def _poll_init_status(self):
"""Poll IMU initialization status and update state machine."""
while True:
imu_status = GetInitStatus()
async with self._state_lock:
if imu_status == "TRACKING" and self.state == MappingState.STARTING:
self.state = MappingState.INITIALIZING
elif imu_status == "STABILIZED" and self.state == MappingState.INITIALIZING:
self.state = MappingState.RUNNING
break
await asyncio.sleep(1.0)
async def _do_start(self):
os.makedirs(self.artifact_dir, exist_ok=True)
file_format = self._get_setting_value("file_format")
await StartEverything(file_format, self.artifact_dir)
self._polling_task = asyncio.create_task(self._poll_init_status())
async def start(self, name_prefix: Optional[str] = None):
"""
Start the mapping process by launching ROS2 Fast-LIO nodes.
State transition: IDLE → STARTING → INITIALIZING → RUNNING
Args:
name_prefix: Optional prefix for catalog item name. If provided,
catalog will generate names like "prefix_1", "prefix_2".
If None, uses timestamp-based naming.
Returns:
dict: Status message
Raises:
RuntimeError: If mapping is in an invalid state for starting
"""
async with self._state_lock:
# Idempotent: already running or initializing
if self.state in [MappingState.RUNNING, MappingState.INITIALIZING]:
return {"details": "already_running", "state": self.state.value}
# Reject if in transition
if self.state in [MappingState.STARTING, MappingState.STOPPING]:
raise RuntimeError(f"Cannot start: mapping is {self.state.value}")
self.state = MappingState.STARTING
self._name_prefix = name_prefix
self.active_settings = self.settings.copy()
await self._do_start()
return {"details": "started", "state": self.state.value}
def get_init_status(self):
"""
Get the IMU initialization status.
Returns:
dict: imu status
"""
return {
"imu_status": GetInitStatus()
}
async def _do_stop(self):
await StopEverything()
# Run finalization script
file_format = self._get_setting_value("file_format").lower()
preview_voxel_size = self._get_setting_value("preview_voxel_size") / 100.0 # cm to meters
await asyncio.to_thread(do_finalize, self.artifact_dir, file_format, preview_voxel_size)
if self.catalog:
self.catalog.add_item("Scan", self.artifact_dir, name_prefix=self._name_prefix)
async with self._state_lock:
self.state = MappingState.IDLE
async def stop(self):
"""
Stop the mapping process and finalize results.
Returns:
dict: Status message
Raises:
RuntimeError: If mapping is in an invalid state for stopping
"""
async with self._state_lock:
# Idempotent: already idle
if self.state == MappingState.IDLE:
return {"details": "already_stopped", "state": self.state.value}
# Reject if in transition
if self.state in [MappingState.STARTING, MappingState.INITIALIZING, MappingState.STOPPING]:
raise RuntimeError(f"Cannot stop: mapping is {self.state.value}")
self.state = MappingState.STOPPING
await self._do_stop()
self.active_settings = self.settings.copy()
return {"details": "stopped", "state": self.state.value}
def get_state(self):
"""
Get current mapping state for status monitoring.
Returns:
dict: Current state
"""
return {
"state": self.state.value,
}