Coverage for core / src / sensorkit / core / impl / device.py: 91%
89 statements
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-24 01:04 +0000
« prev ^ index » next coverage.py v7.13.5, created at 2026-11-24 01:04 +0000
1# SPDX-License-Identifier: Apache-2.0
2from __future__ import annotations
4import asyncio
5from _contextvars import ContextVar
6from typing import Callable, ClassVar, override
8from loguru import logger
9from pydantic import ValidationError
11from sensorkit.backend.request import CallContext
12from sensorkit.core.device import (
13 CommandDone,
14 CommandHandlerCallback,
15 CommandRequestMessage,
16 CommandResult,
17 CommandStarted,
18 DeviceCommand,
19 DeviceEnableState,
20 DeviceEnableStateRequest,
21 DeviceInterface,
22 DeviceState,
23 run_command_request,
24 set_enable_state_request,
25)
26from sensorkit.core.entity import DeviceDetails, EntityInfo
27from sensorkit.core.impl.entity import EntityImpl
28from sensorkit.core.trait import Archetype
31class DeviceImpl(EntityImpl, DeviceInterface):
32 """Helper for implementing server-side functionality of a Device."""
34 current: ClassVar[ContextVar[DeviceImpl | None]] = ContextVar("current_device", default=None)
36 def __init__(self, *, archetype: Archetype | None = None, **kwargs):
37 super().__init__(**kwargs)
39 self.archetype = archetype
40 self._enable_hooks: list[Callable[[], None]] = []
41 self._disable_hooks: list[Callable[[], None]] = []
42 self._handlers: dict[str, CommandHandlerCallback] = {}
44 @override
45 def on_enable(self, func: Callable[[], None]):
46 self._enable_hooks.append(func)
47 return func
49 @override
50 def on_disable(self, func: Callable[[], None]):
51 self._disable_hooks.append(func)
52 return func
54 @override
55 async def init_impl(self):
56 self._state = await DeviceState.recover_or_init(
57 self,
58 enable_state=DeviceEnableState(enabled=True),
59 )
61 @override
62 async def attach_impl(self):
63 if self._state.enable_state.enabled:
64 await self._call_with_context(self._enable_hooks)
66 await self.handle_request(set_enable_state_request, self._set_enable_state)
67 await self.handle_request(run_command_request, self._command_request)
69 async def _set_enable_state(self, request: DeviceEnableStateRequest):
70 if request.enable == self._state.enable_state.enabled:
71 return
73 await self._state.update(self, DeviceEnableState(enabled=request.enable))
75 if request.enable:
76 await self._call_with_context(self._enable_hooks)
77 else:
78 # TODO: Interrupt all ongoing commands.
80 await self._call_with_context(self._disable_hooks)
82 async def _command_request(
83 self,
84 message: CommandRequestMessage,
85 call: CallContext[CommandResult],
86 ):
87 command_id = message.command.command_id
89 # Reject if we aren't ready.
90 if not self._state.enable_state.enabled:
91 logger.warning(f"Rejecting {command_id} command: Device is disabled")
92 call.reject(reason="Device is disabled")
93 return
95 # Look for a handler for this command ID.
96 if command_id not in self._handlers:
97 logger.warning(f"Rejecting unhandled command: {command_id}")
98 call.reject(reason=f"Unhandled command {command_id}")
99 return
101 # Accept the command and invoke the configured handler func.
102 call.accept()
103 handler_func = self._handlers[command_id]
104 success = False
106 # Emit the command start event.
107 logger.debug(f"Incoming {command_id} Command: {call.call_id}")
108 await self.emit_event(CommandStarted(command_id=command_id, call_id=call.call_id))
110 try:
111 # Invoke the registered handler function in a new task and store a reference.
112 with self.enter_context():
113 task = asyncio.create_task(handler_func(message.command))
115 # Wait for the handler to return.
116 await call.progress_from_task(task, cadence=6.0, ttl=10.0)
117 success = True
118 except ValidationError:
119 logger.exception(f"Incoming {command_id} Command failed validation")
120 raise
121 except asyncio.CancelledError:
122 logger.exception(f"Execution of {command_id} Command cancelled")
123 raise
124 except Exception:
125 logger.exception(f"Error invoking {command_id} Command handler")
126 raise
127 else:
128 # The command completed successfully, so return the result including the handler func
129 # return value.
130 await call.succeed(result=CommandResult(data=task.result()))
131 finally:
132 # Emit the command end event.
133 try:
134 await self.emit_event(
135 CommandDone(
136 command_id=command_id,
137 call_id=call.call_id,
138 success=success,
139 )
140 )
141 except Exception as e:
142 logger.warning(f"Error logging command done event ({type(e).__name__})")
144 @override
145 def command_handler(self, command_type: type[DeviceCommand]):
146 key = command_type.model_tag()
148 def decorator(func: CommandHandlerCallback):
149 if key in self._handlers:
150 raise RuntimeError("multiple handlers for command type")
152 self._handlers[key] = func
153 return func
155 return decorator
157 @override
158 def entity_info(self) -> EntityInfo:
159 return EntityInfo(
160 entity_type="device",
161 details=DeviceDetails(
162 archetype=self.archetype.name if self.archetype is not None else None,
163 supported_commands=frozenset(self._handlers.keys()),
164 published_keywords=frozenset(self._published_keywords),
165 ),
166 )