Coverage for core / src / sensorkit / core / device.py: 100%

70 statements  

« 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 

3 

4import uuid 

5from abc import abstractmethod 

6from collections.abc import Coroutine, Iterable 

7from typing import TYPE_CHECKING, Any, Callable, ClassVar 

8 

9from pydantic import BaseModel 

10 

11from sensorkit.backend.event import Event 

12from sensorkit.backend.request import Call, declare_long_request, declare_request 

13from sensorkit.common.model import ModelRegistry, RegistryBaseModel 

14from sensorkit.core.entity import ( 

15 DeviceDetails, 

16 EntityClient, 

17 EntityInterface, 

18 EntityRef, 

19) 

20from sensorkit.core.state import EventSourcedState 

21from sensorkit.core.trait import Archetype, Trait, match_traits 

22 

23if TYPE_CHECKING: 

24 from sensorkit.core.client import SensorKit 

25 

26type CommandHandlerCallback = Callable[[DeviceCommand], Coroutine[Any, Any, BaseModel | None]] 

27 

28 

29class DeviceCommand(RegistryBaseModel): 

30 """Base Device Command model.""" 

31 command_id: str = None 

32 

33 registry: ClassVar[ModelRegistry[DeviceCommand]] = ModelRegistry(discriminator="command_id") 

34 

35 @classmethod 

36 def model_registry(cls): 

37 return cls.registry 

38 

39 

40class Abort(DeviceCommand): 

41 """Built-in abort command.""" 

42 

43 

44class CommandStarted(Event): 

45 """Event indicating a Command has been accepted and execution has begun.""" 

46 command_id: str 

47 call_id: uuid.UUID 

48 

49 

50class CommandDone(Event): 

51 """Event indicating a Command has finished execution.""" 

52 command_id: str 

53 call_id: uuid.UUID 

54 success: bool 

55 

56 

57class DeviceEnableState(Event): 

58 """Event indicating the Device enable state has changed.""" 

59 enabled: bool 

60 

61 

62class DeviceState(EventSourcedState): 

63 """Device state.""" 

64 enable_state: DeviceEnableState 

65 

66 

67class DeviceEnableStateRequest(BaseModel): 

68 """Request that a Device enable or disable its command handlers.""" 

69 enable: bool 

70 

71 

72set_enable_state_request = declare_request( 

73 "set_enable_state", 

74 message=DeviceEnableStateRequest, 

75) 

76 

77 

78class CommandRequestMessage(BaseModel): 

79 """Message model representing a Command execution request.""" 

80 command: DeviceCommand 

81 

82 

83class CommandResult(BaseModel): 

84 """Message model representing a response to a Command execution request.""" 

85 data: Any 

86 

87 

88run_command_request = declare_long_request( 

89 "command", 

90 message=CommandRequestMessage, 

91 result=CommandResult, 

92) 

93 

94 

95class DeviceClient(EntityClient): 

96 """Object that exposes client-side functionality of a Device.""" 

97 

98 async def enable(self): 

99 """Enable device command handlers.""" 

100 return await self.call( 

101 set_enable_state_request, 

102 DeviceEnableStateRequest(enable=True) 

103 ) 

104 

105 async def disable(self): 

106 """Disable device command handlers.""" 

107 return await self.call( 

108 set_enable_state_request, 

109 DeviceEnableStateRequest(enable=False) 

110 ) 

111 

112 def command(self, command: DeviceCommand) -> Call[None, CommandResult]: 

113 """Send a command to the device and return a Call tracking the result.""" 

114 return self.call( 

115 run_command_request, 

116 CommandRequestMessage(command=command), 

117 ) 

118 

119 async def get_details(self) -> DeviceDetails: 

120 """Fetch the device's current advertised details. 

121 

122 Raises: 

123 KeyNotFound: The entity has no stored metadata. 

124 ValueError: The metadata has no device details. 

125 """ 

126 details = await super().get_details() 

127 

128 if not isinstance(details, DeviceDetails): 

129 raise ValueError(f"'{self.entity}' is not a device") 

130 

131 return details 

132 

133 async def has_trait(self, trait: Trait) -> bool: 

134 """Return True if this device satisfies the given trait.""" 

135 details = await self.get_details() 

136 return trait.match(details) 

137 

138 async def get_traits(self, traits: Iterable[Trait]) -> list[Trait]: 

139 """Return all matching traits from the given iterable.""" 

140 details = await self.get_details() 

141 return match_traits(details, traits) 

142 

143 async def get_archetype(self) -> Archetype | None: 

144 """Return the declared archetype if registered locally, otherwise None.""" 

145 details = await self.get_details() 

146 return details.get_archetype() 

147 

148 

149class DeviceRef(EntityRef[DeviceClient]): 

150 """A serializable reference to a device client.""" 

151 

152 def _get_client(self, kit: SensorKit) -> DeviceClient: 

153 return kit.device(self.name) 

154 

155 

156class DeviceInterface(EntityInterface): 

157 """Interface describing an implementation of a device.""" 

158 

159 @abstractmethod 

160 def on_enable(self, func: Callable[[], None]): 

161 """Register a callback to invoke when the device is enabled.""" 

162 ... 

163 

164 @abstractmethod 

165 def on_disable(self, func: Callable[[], None]): 

166 """Register a callback to invoke when the device is disabled.""" 

167 ... 

168 

169 @abstractmethod 

170 def command_handler( 

171 self, 

172 command_type: type[DeviceCommand], 

173 ) -> Callable[..., CommandHandlerCallback]: 

174 """Return a decorator that registers the handler for a command type. 

175 

176 Raises: 

177 RuntimeError: If the decorator is applied when the command type already has a handler. 

178 """ 

179 ...