diff --git a/src/viam/components/power_sensor/client.py b/src/viam/components/power_sensor/client.py index 0f5829105..0b68eee07 100644 --- a/src/viam/components/power_sensor/client.py +++ b/src/viam/components/power_sensor/client.py @@ -12,10 +12,14 @@ GetStatusResponse, ) from viam.proto.component.powersensor import ( + GetBatteryPercentRequest, + GetBatteryPercentResponse, GetCurrentRequest, GetCurrentResponse, GetPowerRequest, GetPowerResponse, + GetPropertiesRequest, + GetPropertiesResponse, GetVoltageRequest, GetVoltageResponse, PowerSensorServiceStub, @@ -80,6 +84,30 @@ async def get_readings( response: GetReadingsResponse = await self.client.GetReadings(request, timeout=timeout, metadata=md) return sensor_readings_value_to_native(response.readings) + async def get_battery_percent( + self, + *, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ) -> float: + md = kwargs.get("metadata", self.Metadata()).proto + request = GetBatteryPercentRequest(name=self.name, extra=dict_to_struct(extra)) + response: GetBatteryPercentResponse = await self.client.GetBatteryPercent(request, timeout=timeout, metadata=md) + return response.percent + + async def get_properties( + self, + *, + extra: Optional[Dict[str, Any]] = None, + timeout: Optional[float] = None, + **kwargs, + ) -> PowerSensor.Properties: + md = kwargs.get("metadata", self.Metadata()).proto + request = GetPropertiesRequest(name=self.name, extra=dict_to_struct(extra)) + response: GetPropertiesResponse = await self.client.GetProperties(request, timeout=timeout, metadata=md) + return response + async def do_command( self, command: Mapping[str, ValueTypes], diff --git a/src/viam/components/power_sensor/power_sensor.py b/src/viam/components/power_sensor/power_sensor.py index 545a7c8d6..3b308d66e 100644 --- a/src/viam/components/power_sensor/power_sensor.py +++ b/src/viam/components/power_sensor/power_sensor.py @@ -1,7 +1,8 @@ import abc -from typing import Any, Dict, Final, Mapping, Optional, Tuple +from typing import Any, Dict, Final, Mapping, Optional, Tuple, TypeAlias from viam.components.component_base import ComponentBase +from viam.proto.component.powersensor import GetPropertiesResponse from viam.resource.types import API, RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT from viam.utils import SensorReading @@ -23,6 +24,8 @@ class PowerSensor(ComponentBase): RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, "power_sensor" ) + Properties: "TypeAlias" = GetPropertiesResponse + @abc.abstractmethod async def get_voltage(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs) -> Tuple[float, bool]: """Return the voltage reading of a specified device and whether it is AC or DC. @@ -102,3 +105,42 @@ async def get_readings( For more information, see `Power Sensor component `_. """ ... + + @abc.abstractmethod + async def get_battery_percent(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs) -> float: + """Return the remaining battery charge, from 0 to 100. + + :: + + my_power_sensor = PowerSensor.from_robot(robot=machine, name='my_power_sensor') + + # Get the remaining battery charge from the power sensor + percent = await my_power_sensor.get_battery_percent() + print("The battery charge remaining is", percent, "%") + + Returns: + float: The remaining battery charge, from 0 to 100. + + For more information, see `Power Sensor component + `_. + """ + ... + + @abc.abstractmethod + async def get_properties(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs) -> Properties: + """Return a dictionary of the optional methods this power sensor supports. + + :: + + my_power_sensor = PowerSensor.from_robot(robot=machine, name='my_power_sensor') + + # Get whether the power sensor supports GetBatteryPercent. + properties = await my_power_sensor.get_properties() + + Returns: + PowerSensor.Properties: Map of optional properties to supported status. + + For more information, see `Power Sensor component + `_. + """ + ... diff --git a/src/viam/components/power_sensor/service.py b/src/viam/components/power_sensor/service.py index 1320122eb..bab28b59e 100644 --- a/src/viam/components/power_sensor/service.py +++ b/src/viam/components/power_sensor/service.py @@ -10,10 +10,14 @@ GetStatusResponse, ) from viam.proto.component.powersensor import ( + GetBatteryPercentRequest, + GetBatteryPercentResponse, GetCurrentRequest, GetCurrentResponse, GetPowerRequest, GetPowerResponse, + GetPropertiesRequest, + GetPropertiesResponse, GetVoltageRequest, GetVoltageResponse, PowerSensorServiceBase, @@ -69,6 +73,25 @@ async def GetPower(self, stream: Stream[GetPowerRequest, GetPowerResponse]) -> N response = GetPowerResponse(watts=power) await stream.send_message(response) + async def GetBatteryPercent(self, stream: Stream[GetBatteryPercentRequest, GetBatteryPercentResponse]) -> None: + request = await stream.recv_message() + assert request is not None + name = request.name + sensor = self.get_resource(name) + timeout = stream.deadline.time_remaining() if stream.deadline else None + percent = await sensor.get_battery_percent(extra=struct_to_dict(request.extra), timeout=timeout, metadata=stream.metadata) + response = GetBatteryPercentResponse(percent=percent) + await stream.send_message(response) + + async def GetProperties(self, stream: Stream[GetPropertiesRequest, GetPropertiesResponse]) -> None: + request = await stream.recv_message() + assert request is not None + name = request.name + sensor = self.get_resource(name) + timeout = stream.deadline.time_remaining() if stream.deadline else None + properties = await sensor.get_properties(extra=struct_to_dict(request.extra), timeout=timeout, metadata=stream.metadata) + await stream.send_message(properties) + async def DoCommand(self, stream: Stream[DoCommandRequest, DoCommandResponse]) -> None: request = await stream.recv_message() assert request is not None diff --git a/tests/mocks/components.py b/tests/mocks/components.py index 67913673b..855407f99 100644 --- a/tests/mocks/components.py +++ b/tests/mocks/components.py @@ -1222,13 +1222,23 @@ async def get_status(self, *, timeout: Optional[float] = None, **kwargs) -> Mapp class MockPowerSensor(PowerSensor): - def __init__(self, name: str, voltage: float, current: float, is_ac: bool, power: float, readings: Mapping[str, float]): + def __init__( + self, + name: str, + voltage: float, + current: float, + is_ac: bool, + power: float, + readings: Mapping[str, float], + battery_percent: float = 0, + ): super().__init__(name) self.voltage = voltage self.current = current self.is_ac = is_ac self.power = power self.readings = readings + self.battery_percent = battery_percent self.geometries = GEOMETRIES self.extra: Optional[Dict[str, Any]] = None self.timeout: Optional[float] = None @@ -1255,6 +1265,18 @@ async def get_readings( self.timeout = timeout return self.readings + async def get_battery_percent(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs) -> float: + self.extra = extra + self.timeout = timeout + return self.battery_percent + + async def get_properties( + self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs + ) -> PowerSensor.Properties: + self.extra = extra + self.timeout = timeout + return PowerSensor.Properties(is_battery_percent_supported=True) + async def do_command(self, command: Mapping[str, ValueTypes], *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]: return {"command": command} diff --git a/tests/test_power_sensor.py b/tests/test_power_sensor.py index 52575bc0b..52bf7e8bb 100644 --- a/tests/test_power_sensor.py +++ b/tests/test_power_sensor.py @@ -12,10 +12,14 @@ GetStatusResponse, ) from viam.proto.component.powersensor import ( + GetBatteryPercentRequest, + GetBatteryPercentResponse, GetCurrentRequest, GetCurrentResponse, GetPowerRequest, GetPowerResponse, + GetPropertiesRequest, + GetPropertiesResponse, GetVoltageRequest, GetVoltageResponse, PowerSensorServiceStub, @@ -31,12 +35,13 @@ WATTS = 1.0 IS_AC = True READINGS = {"a": 1, "b": 2, "c": 3} +BATTERY_PERCENT = 42.0 EXTRA_PARAMS = {"foo": "bar", "baz": [1, 2, 3]} @pytest.fixture(scope="function") def power_sensor() -> PowerSensor: - return MockPowerSensor("power_sensor", VOLTS, AMPERES, IS_AC, WATTS, READINGS) + return MockPowerSensor("power_sensor", VOLTS, AMPERES, IS_AC, WATTS, READINGS, BATTERY_PERCENT) @pytest.fixture(scope="function") @@ -78,6 +83,18 @@ async def test_get_readings(self, power_sensor: MockPowerSensor): assert value == READINGS assert power_sensor.extra == EXTRA_PARAMS + async def test_get_battery_percent(self, power_sensor: MockPowerSensor): + assert power_sensor.extra is None + percent = await power_sensor.get_battery_percent(extra=EXTRA_PARAMS) + assert percent == BATTERY_PERCENT + assert power_sensor.extra == EXTRA_PARAMS + + async def test_get_properties(self, power_sensor: MockPowerSensor): + assert power_sensor.extra is None + properties = await power_sensor.get_properties(extra=EXTRA_PARAMS) + assert properties.is_battery_percent_supported is True + assert power_sensor.extra == EXTRA_PARAMS + async def test_timeout(self, power_sensor: MockPowerSensor): assert power_sensor.timeout is None @@ -93,6 +110,12 @@ async def test_timeout(self, power_sensor: MockPowerSensor): await power_sensor.get_readings(timeout=8.90) assert power_sensor.timeout == expected_grpc_timeout(8.90) + await power_sensor.get_battery_percent(timeout=1.23) + assert power_sensor.timeout == expected_grpc_timeout(1.23) + + await power_sensor.get_properties(timeout=4.56) + assert power_sensor.timeout == expected_grpc_timeout(4.56) + async def test_do(self, power_sensor: PowerSensor): command = {"command": "args"} resp = await power_sensor.do_command(command) @@ -146,6 +169,26 @@ async def test_get_readings(self, power_sensor: MockPowerSensor, service: PowerS assert power_sensor.extra == EXTRA_PARAMS assert power_sensor.timeout == expected_grpc_timeout(8.90) + async def test_get_battery_percent(self, power_sensor: MockPowerSensor, service: PowerSensorRPCService): + async with ChannelFor([service]) as channel: + client = PowerSensorServiceStub(channel) + request = GetBatteryPercentRequest(name=power_sensor.name, extra=dict_to_struct(EXTRA_PARAMS)) + assert power_sensor.extra is None + response: GetBatteryPercentResponse = await client.GetBatteryPercent(request, timeout=8.90) + assert response.percent == BATTERY_PERCENT + assert power_sensor.extra == EXTRA_PARAMS + assert power_sensor.timeout == expected_grpc_timeout(8.90) + + async def test_get_properties(self, power_sensor: MockPowerSensor, service: PowerSensorRPCService): + async with ChannelFor([service]) as channel: + client = PowerSensorServiceStub(channel) + request = GetPropertiesRequest(name=power_sensor.name, extra=dict_to_struct(EXTRA_PARAMS)) + assert power_sensor.extra is None + response: GetPropertiesResponse = await client.GetProperties(request, timeout=8.90) + assert response.is_battery_percent_supported is True + assert power_sensor.extra == EXTRA_PARAMS + assert power_sensor.timeout == expected_grpc_timeout(8.90) + async def test_do(self, power_sensor: MockPowerSensor, service: PowerSensorRPCService): async with ChannelFor([service]) as channel: client = PowerSensorServiceStub(channel) @@ -202,6 +245,24 @@ async def test_get_readings(self, power_sensor: MockPowerSensor, service: PowerS assert power_sensor.extra == EXTRA_PARAMS assert power_sensor.timeout == expected_grpc_timeout(2.34) + async def test_get_battery_percent(self, power_sensor: MockPowerSensor, service: PowerSensorRPCService): + async with ChannelFor([service]) as channel: + client = PowerSensorClient(power_sensor.name, channel) + assert power_sensor.extra is None + percent = await client.get_battery_percent(extra=EXTRA_PARAMS, timeout=1.45) + assert percent == BATTERY_PERCENT + assert power_sensor.extra == EXTRA_PARAMS + assert power_sensor.timeout == expected_grpc_timeout(1.45) + + async def test_get_properties(self, power_sensor: MockPowerSensor, service: PowerSensorRPCService): + async with ChannelFor([service]) as channel: + client = PowerSensorClient(power_sensor.name, channel) + assert power_sensor.extra is None + properties = await client.get_properties(extra=EXTRA_PARAMS, timeout=1.45) + assert properties.is_battery_percent_supported is True + assert power_sensor.extra == EXTRA_PARAMS + assert power_sensor.timeout == expected_grpc_timeout(1.45) + async def test_do(self, power_sensor: PowerSensor, service: PowerSensorRPCService): async with ChannelFor([service]) as channel: client = PowerSensorClient(power_sensor.name, channel)