Coverage for core / src / sensorkit / sensor / impl.py: 94%

147 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-11-24 01:04 +0000

1# SPDX-License-Identifier: Apache-2.0 

2"""Serve a sensor definition as a controller. 

3 

4Tasks run as workflows planned and executed by a `Sensor`. Site policies 

5supply the lifecycle tables and deadline rules. 

6""" 

7 

8from __future__ import annotations 

9 

10import asyncio 

11import contextlib 

12from collections.abc import AsyncIterator, Mapping 

13from datetime import UTC, datetime 

14 

15from loguru import logger 

16from pydantic import BaseModel 

17 

18import sensorkit.api as sk 

19from sensorkit.astro.common import SitePosition 

20from sensorkit.sensor.autofocus import ( 

21 Focuser, 

22 final_focus_position, 

23 first_sweep_analysis, 

24 focus_source, 

25 translate_autofocus, 

26) 

27from sensorkit.sensor.client import Sensor 

28from sensorkit.sensor.definition import SensorDefinition 

29from sensorkit.sensor.dispatch import DeviceContexts, Dispatcher 

30from sensorkit.sensor.execution import WorkflowError, WorkflowReport 

31from sensorkit.sensor.lifecycle import LifecycleWorkflow 

32from sensorkit.sensor.policies import ( 

33 SensorPolicies, 

34 compose_deadlines, 

35 compose_tables, 

36) 

37from sensorkit.sensor.standard_task import translate 

38from sensorkit.sensor.topology import Placement, Structure 

39from sensorkit.sensor.workflow import ExecutableWorkflow 

40from sensorkit.std.collect import StandardCollectTask 

41from sensorkit.std.focus import AutoFocus, FocusSweepAnalysis 

42 

43 

44class SensorConfig(BaseModel): 

45 """A sensor's structure and the site policies it runs under.""" 

46 

47 model: Structure 

48 policies: SensorPolicies 

49 

50 

51@sk.declare_controller 

52class SensorController: 

53 """Run lifecycle, collect, and autofocus tasks as sensor workflows.""" 

54 

55 stopping: bool = False 

56 instruments: Mapping[str, Placement] = {} 

57 """Collection targets by instrument name.""" 

58 running_autofocus: asyncio.Task | None = None 

59 """Running autofocus task canceled by controller disable.""" 

60 

61 @sk.on_attach 

62 async def on_attach(self): 

63 controller = sk.controller() 

64 config = await controller.kv_get_model(SensorConfig) 

65 self.site = await controller.kv_get_model(SitePosition) 

66 self.policies = config.policies 

67 controller.on_disable(self.on_disable) 

68 

69 definition = compose_deadlines( 

70 SensorDefinition(sensor=config.model), config.policies.deadlines() 

71 ) 

72 self.sensor = await Sensor.connect(definition, controller.sensorkit()) 

73 

74 # Tables compose after binding so generated entries are pruned to the 

75 # equipment actually present. 

76 bound = self.sensor.sensor 

77 self.tables: Mapping[str, LifecycleWorkflow] = { 

78 table.name: table 

79 for table in compose_tables(definition, config.policies.tables(), bound) 

80 } 

81 

82 # Subscriptions start after attach. Only keywords named by a matched trait 

83 # are subscribed, so custom keywords are never subscribed implicitly. 

84 placements = bound.topology.placements() 

85 self.devices = tuple(placement.device for placement in placements) 

86 

87 for placement in placements: 

88 controller.use_device(placement.device) 

89 controller.get_device(placement.device).subscription.add_trait_keywords( 

90 bound.details[placement.device] 

91 ) 

92 

93 self.instruments = {target.device: target for target in bound.topology.instruments()} 

94 

95 for name, target in self.instruments.items(): 

96 chain = bound.topology.chain(target) 

97 controller.register_instrument(name, devices=[p.device for p in chain]) 

98 

99 @sk.on_detach 

100 async def on_detach(self): 

101 self.stopping = True 

102 

103 async def on_disable(self): 

104 if self.running_autofocus is not None: 

105 self.running_autofocus.cancel("Controller disabled") 

106 

107 def device_contexts(self) -> Mapping[str, sk.Context]: 

108 """Return each device's latest subscribed keywords, unmerged. 

109 

110 Dispatch merges only the contexts along an instrument's chain. 

111 """ 

112 controller = sk.controller() 

113 

114 return {key: controller.get_device(key).subscription.snapshot() for key in self.devices} 

115 

116 def instrument_context(self, target: Placement) -> sk.Context: 

117 """Read registered context for the assigned capture target.""" 

118 # Sensor instrument names are camera device IDs. 

119 return sk.controller().instrument_context(target.device) 

120 

121 async def execute( 

122 self, 

123 workflow: ExecutableWorkflow, 

124 *, 

125 contexts: DeviceContexts | None = None, 

126 base: sk.Context | None = None, 

127 ) -> WorkflowReport: 

128 """Execute a workflow, treating cancellation as a domain abort unless 

129 the service is stopping. 

130 

131 Raises: 

132 WorkflowError: Required work or cleanup failed. 

133 asyncio.CancelledError: The workflow was aborted, once its cleanup 

134 ends, or the service is stopping. 

135 """ 

136 report = await self.sensor.execute( 

137 workflow, 

138 contexts=contexts, 

139 instrument_contexts=self.instrument_context, 

140 base=base, 

141 in_domain=lambda _: not self.stopping, 

142 ) 

143 

144 # Core records a task as aborted only if the handler is cancelled. 

145 if report.outcome == "aborted": 

146 raise asyncio.CancelledError(report.reason) 

147 

148 return report 

149 

150 async def run_table(self, name: str): 

151 """Plan and execute a lifecycle table, attempting Abort on every 

152 device after failure. 

153 

154 Raises: 

155 WorkflowError: Required work or cleanup failed. 

156 asyncio.CancelledError: The table was aborted. 

157 """ 

158 try: 

159 await self.execute(self.sensor.plan_lifecycle(self.tables[name])) 

160 except WorkflowError: 

161 # Failed lifecycle commands may leave hardware running after responding. 

162 dispatcher = Dispatcher(self.sensor.sensor, self.sensor.executor.clients) 

163 await asyncio.gather( 

164 *(dispatcher.abort(device, lambda _: None) for device in self.devices) 

165 ) 

166 raise 

167 

168 @sk.task_handler 

169 async def init_task(self, task: sk.InitTask): 

170 """Bring the sensor up to operate.""" 

171 await self.run_table("init") 

172 logger.info(f"Sensor '{sk.controller().entity}' is ready to operate") 

173 

174 @sk.task_handler 

175 async def standby_task(self, task: sk.StandbyTask): 

176 """Put the sensor in standby.""" 

177 await self.run_table("standby") 

178 logger.info(f"Sensor '{sk.controller().entity}' is standing by") 

179 

180 @sk.task_handler 

181 async def shutdown_task(self, task: sk.ShutdownTask): 

182 """Shut the sensor down.""" 

183 await self.run_table("shutdown") 

184 

185 @sk.task_handler 

186 async def recover_task(self, task: sk.RecoverTask): 

187 """Attempt to reconnect every device, then stop motion.""" 

188 await self.run_table("recover") 

189 

190 @sk.task_handler 

191 async def collect_task(self, execution: sk.TaskExecution[StandardCollectTask]): 

192 """Capture the task's exposures, following its target if it has one. 

193 

194 Named parameter sets keep their instrument throughout the collect. 

195 Planning uses one snapshot of subscribed device keywords. Frame headers 

196 sample them again at dispatch, along with the assigned instrument's 

197 registered context. 

198 """ 

199 workflow = self.sensor.plan_collect( 

200 translate(execution.task, instruments=self.instruments), 

201 device_keywords=self.device_contexts(), 

202 ) 

203 base = sk.Context(execution.context, self.site) 

204 

205 await self.execute(workflow, contexts=self.device_contexts, base=base) 

206 

207 @sk.task_handler 

208 async def autofocus_task(self, execution: sk.TaskExecution[AutoFocus]): 

209 """Execute one fixed sweep and apply a best-focus estimate. 

210 

211 The task ID identifies the sweep. Analysis comes from the configured 

212 `FocusAnalysisSource` and is retained in the task's working context. 

213 Pointing and tracking are preserved. Requested camera and filter 

214 settings remain applied. 

215 

216 If best focus lies beyond the sweep, leave the focuser at the nearer 

217 sampled boundary and fail the task. A later sweep can start there. 

218 Capture, analysis, and final-move failures attempt to restore the starting 

219 focus position. Cancellation, expiry, controller disable, and service 

220 shutdown cancel active work without a return move. 

221 """ 

222 task = execution.task 

223 

224 async with self._autofocus_lifetime(execution): 

225 focuser = Focuser.on( 

226 self.sensor.sensor, task.instrument, self.instruments, self.device_contexts() 

227 ) 

228 positions = task.positions(focuser.start) 

229 workflow = self.sensor.plan_collect( 

230 translate_autofocus( 

231 task, 

232 positions, 

233 sweep_id=execution.task_id, 

234 focuser=focuser.device, 

235 instruments=self.instruments, 

236 ), 

237 device_keywords=self.device_contexts(), 

238 ) 

239 source = await focus_source(sk.controller()) 

240 

241 try: 

242 analysis = await self._run_focus_sweep(execution, workflow, source) 

243 execution.context.set(analysis) 

244 await self._move_focus(focuser.move(final_focus_position(analysis, positions))) 

245 except Exception as failure: 

246 await self._restore_focus(focuser, failure) 

247 raise 

248 

249 if analysis.disposition != "equals": 

250 raise RuntimeError( 

251 f"Best focus is {analysis.disposition.replace('_', ' ')} " 

252 f"{analysis.position}, beyond the swept range; the focuser is left there" 

253 ) 

254 

255 @contextlib.asynccontextmanager 

256 async def _autofocus_lifetime(self, execution: sk.TaskExecution) -> AsyncIterator[None]: 

257 """Bound autofocus by execution expiry and controller disable.""" 

258 expiry = execution.expiry_time 

259 seconds = None if expiry is None else (expiry - datetime.now(UTC)).total_seconds() 

260 self.running_autofocus = asyncio.current_task() 

261 

262 try: 

263 async with asyncio.timeout(seconds) as lifetime: 

264 yield 

265 except TimeoutError: 

266 if lifetime.expired(): 

267 raise TimeoutError(f"The task expired at {expiry}") from None 

268 

269 raise 

270 finally: 

271 self.running_autofocus = None 

272 

273 async def _run_focus_sweep( 

274 self, 

275 execution: sk.TaskExecution[AutoFocus], 

276 workflow: ExecutableWorkflow, 

277 source: sk.EntityClient, 

278 ) -> FocusSweepAnalysis: 

279 """Capture the sweep and wait for matching analysis. 

280 

281 Subscribe before capturing the first frame. After the last capture, 

282 allow the default command timeout for matching analysis. 

283 Task expiry can shorten this wait. 

284 

285 Raises: 

286 WorkflowError: Required work failed. 

287 TimeoutError: No matching analysis arrived in time. 

288 """ 

289 async with first_sweep_analysis( 

290 source, 

291 controller=execution.controller_id, 

292 instrument=execution.task.instrument, 

293 sweep_id=execution.task_id, 

294 ) as analysis: 

295 base = sk.Context(execution.context, self.site) 

296 await self.execute(workflow, contexts=self.device_contexts, base=base) 

297 seconds = self.policies.default_timeout 

298 

299 try: 

300 async with asyncio.timeout(seconds): 

301 return await analysis 

302 except TimeoutError: 

303 raise TimeoutError( 

304 f"'{source.entity}' published no analysis of sweep {execution.task_id} " 

305 f"within {seconds} s" 

306 ) from None 

307 

308 async def _move_focus(self, move: LifecycleWorkflow) -> None: 

309 """Move the focuser under its command deadline. 

310 

311 Raises: 

312 WorkflowError: The move failed. 

313 """ 

314 await self.execute(self.sensor.plan_lifecycle(move)) 

315 

316 async def _restore_focus(self, focuser: Focuser, failure: Exception) -> None: 

317 """Attempt to restore starting focus after a capture, analysis, or move failure. 

318 

319 Raises: 

320 RuntimeError: Restoration failed. The message includes both failures, 

321 with the original failure retained as the cause. 

322 """ 

323 # Expiry and absorbed aborts also leave the task cancelling. 

324 if asyncio.current_task().cancelling(): 

325 return 

326 

327 try: 

328 await self._move_focus(focuser.move(focuser.start)) 

329 except Exception as error: 

330 raise RuntimeError( 

331 f"{failure}; returning focuser '{focuser.device}' to {focuser.start} " 

332 f"also failed: {error}" 

333 ) from failure 

334 

335 

336sk.declare_config_section( 

337 "sensors", 

338 list[SensorConfig], 

339 id_source="by_subkey", 

340 service_path=__name__, 

341) 

342 

343 

344@sk.service_entrypoint(version=sk.VERSION) 

345async def sensor_service(service: sk.Service): 

346 service.include(SensorController) 

347 await service.run()