Skip to content

Commit 63c03d8

Browse files
RSDK-5936: change return type for get readings (#506)
1 parent fb09410 commit 63c03d8

File tree

19 files changed

+59
-42
lines changed

19 files changed

+59
-42
lines changed

docs/examples/example.ipynb

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -272,13 +272,14 @@
272272
"\n",
273273
"from viam.components.sensor import Sensor\n",
274274
"from viam.logging import getLogger\n",
275+
"from viam.utils import SensorReading\n",
275276
"\n",
276277
"LOGGER = getLogger(__name__)\n",
277278
"\n",
278279
"\n",
279280
"class MySensor(Sensor):\n",
280281
" # Subclass the Viam Sensor component and implement the required functions\n",
281-
" async def get_readings(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, Any]:\n",
282+
" async def get_readings(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, SensorReading]:\n",
282283
" with open(\"/proc/net/wireless\") as wifi_stats:\n",
283284
" content = wifi_stats.readlines()\n",
284285
" wifi_signal = [x for x in content[2].split(\" \") if x != \"\"]\n",
@@ -368,6 +369,8 @@
368369
"# ADD `Sequence` FROM `typing`.\n",
369370
"from typing import Sequence\n",
370371
"\n",
372+
"from viam.utils import SensorReading\n",
373+
"\n",
371374
"class MySensor(Sensor):\n",
372375
" # ADD A VALIDATOR FUNCTION \n",
373376
" @classmethod\n",
@@ -395,7 +398,7 @@
395398
" multiplier = 1.0\n",
396399
" self.multiplier = multiplier\n",
397400
"\n",
398-
" async def get_readings(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, Any]:\n",
401+
" async def get_readings(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, SensorReading]:\n",
399402
" with open(\"/proc/net/wireless\") as wifi_stats:\n",
400403
" content = wifi_stats.readlines()\n",
401404
" result = [x for x in content[2].split(\" \") if x != \"\"]\n",
@@ -1031,10 +1034,11 @@
10311034
"\n",
10321035
"from viam.components.sensor import Geometry, Sensor\n",
10331036
"from viam.rpc.server import Server\n",
1037+
"from viam.utils import SensorReading\n",
10341038
"\n",
10351039
"\n",
10361040
"class MySensor(Sensor):\n",
1037-
" async def get_readings(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, Any]:\n",
1041+
" async def get_readings(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, SensorReading]:\n",
10381042
" with open(\"/proc/net/wireless\") as wifi_stats:\n",
10391043
" content = wifi_stats.readlines()\n",
10401044
" wifi_signal = [x for x in content[2].split(\" \") if x != \"\"]\n",
@@ -1485,7 +1489,7 @@
14851489
"name": "python",
14861490
"nbconvert_exporter": "python",
14871491
"pygments_lexer": "ipython3",
1488-
"version": "3.11.4 (main, Jun 20 2023, 17:23:00) [Clang 14.0.3 (clang-1403.0.22.14.1)]"
1492+
"version": "3.11.6 (main, Oct 2 2023, 20:46:14) [Clang 14.0.3 (clang-1403.0.22.14.1)]"
14891493
},
14901494
"vscode": {
14911495
"interpreter": {

docs/examples/module_step2.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from viam.resource.base import ResourceBase
1212
from viam.resource.registry import Registry, ResourceCreatorRegistration
1313
from viam.resource.types import Model, ModelFamily
14+
from viam.utils import SensorReading
1415

1516
LOGGER = getLogger(__name__)
1617

@@ -24,7 +25,7 @@ def new(cls, config: ComponentConfig, dependencies: Mapping[ResourceName, Resour
2425
sensor = cls(config.name)
2526
return sensor
2627

27-
async def get_readings(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, Any]:
28+
async def get_readings(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, SensorReading]:
2829
with open("/proc/net/wireless") as wifi_stats:
2930
content = wifi_stats.readlines()
3031
wifi_signal = [x for x in content[2].split(" ") if x != ""]

docs/examples/module_step2_optional.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from viam.resource.base import ResourceBase
1212
from viam.resource.registry import Registry, ResourceCreatorRegistration
1313
from viam.resource.types import Model, ModelFamily
14+
from viam.utils import SensorReading
1415

1516
LOGGER = getLogger(__name__)
1617

@@ -35,7 +36,7 @@ def validate_config(cls, config: ComponentConfig) -> Sequence[str]:
3536
raise Exception("Multiplier cannot be 0.")
3637
return []
3738

38-
async def get_readings(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, Any]:
39+
async def get_readings(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, SensorReading]:
3940
with open("/proc/net/wireless") as wifi_stats:
4041
content = wifi_stats.readlines()
4142
result = [x for x in content[2].split(" ") if x != ""]

docs/examples/module_step3.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
from viam.resource.base import ResourceBase
1313
from viam.resource.registry import Registry, ResourceCreatorRegistration
1414
from viam.resource.types import Model, ModelFamily
15+
from viam.utils import SensorReading
1516

1617
LOGGER = getLogger(__name__)
1718

@@ -25,7 +26,7 @@ def new(cls, config: ComponentConfig, dependencies: Mapping[ResourceName, Resour
2526
sensor = cls(config.name)
2627
return sensor
2728

28-
async def get_readings(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, Any]:
29+
async def get_readings(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, SensorReading]:
2930
with open("/proc/net/wireless") as wifi_stats:
3031
content = wifi_stats.readlines()
3132
wifi_signal = [x for x in content[2].split(" ") if x != ""]

examples/server/v1/components.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@
5353
from viam.proto.component.arm import JointPositions
5454
from viam.proto.component.audioinput import AudioChunk, AudioChunkInfo, SampleFormat
5555
from viam.proto.component.encoder import PositionType
56+
from viam.utils import SensorReading
5657

5758
GEOMETRIES = [
5859
Geometry(center=Pose(x=1, y=2, z=3, o_x=2, o_y=3, o_z=4, theta=20), sphere=Sphere(radius_mm=2)),
@@ -645,7 +646,7 @@ def __init__(
645646
self.properties = properties
646647
self.accuracy = accuracy
647648

648-
async def get_readings(self, **kwargs) -> Mapping[str, Any]:
649+
async def get_readings(self, **kwargs) -> Mapping[str, SensorReading]:
649650
return {"abcdefghij"[idx]: random.random() for idx in range(self.num_readings)}
650651

651652
async def get_position(self, **kwargs) -> Tuple[GeoPoint, float]:
@@ -693,7 +694,7 @@ def __init__(self, name: str):
693694
self.num_readings = random.randint(1, 10)
694695
super().__init__(name)
695696

696-
async def get_readings(self, **kwargs) -> Mapping[str, Any]:
697+
async def get_readings(self, **kwargs) -> Mapping[str, SensorReading]:
697698
return {"abcdefghij"[idx]: random.random() for idx in range(self.num_readings)}
698699

699700
async def get_geometries(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[Geometry]:

examples/simple_module/src/main.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111
from viam.resource.base import ResourceBase
1212
from viam.resource.registry import Registry, ResourceCreatorRegistration
1313
from viam.resource.types import Model, ModelFamily
14-
from viam.utils import ValueTypes
14+
from viam.utils import SensorReading, ValueTypes
1515

1616
LOGGER = getLogger(__name__)
1717

@@ -39,7 +39,7 @@ def validate_config(cls, config: ComponentConfig) -> Sequence[str]:
3939
raise Exception("Multiplier cannot be 0.")
4040
return []
4141

42-
async def get_readings(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, Any]:
42+
async def get_readings(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, SensorReading]:
4343
return {"signal": 1 * self.multiplier}
4444

4545
async def do_command(self, command: Mapping[str, ValueTypes], *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]:

src/viam/components/movement_sensor/client.py

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@
2424
MovementSensorServiceStub,
2525
)
2626
from viam.resource.rpc_client_base import ReconfigurableResourceRPCClientBase
27-
from viam.utils import ValueTypes, dict_to_struct, get_geometries, struct_to_dict
27+
from viam.utils import SensorReading, ValueTypes, dict_to_struct, get_geometries, sensor_readings_value_to_native, struct_to_dict
2828

2929
from . import GeoPoint, Orientation, Vector3
3030

@@ -93,12 +93,13 @@ async def get_accuracy(self, *, extra: Optional[Dict[str, Any]] = None, timeout:
9393
response: GetAccuracyResponse = await self.client.GetAccuracy(request, timeout=timeout)
9494
return response.accuracy
9595

96-
async def get_readings(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None) -> Mapping[str, Any]:
96+
async def get_readings(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None) -> Mapping[str, SensorReading]:
9797
if extra is None:
9898
extra = {}
9999
request = GetReadingsRequest(name=self.name, extra=dict_to_struct(extra))
100100
response: GetReadingsResponse = await self.client.GetReadings(request, timeout=timeout)
101-
return response.readings
101+
102+
return sensor_readings_value_to_native(response.readings)
102103

103104
async def do_command(self, command: Mapping[str, ValueTypes], *, timeout: Optional[float] = None) -> Mapping[str, ValueTypes]:
104105
request = DoCommandRequest(name=self.name, command=dict_to_struct(command))

src/viam/components/movement_sensor/movement_sensor.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
from viam.components.component_base import ComponentBase
88
from viam.proto.component.movementsensor import GetPropertiesResponse
99
from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype
10+
from viam.utils import SensorReading
1011

1112
from . import GeoPoint, Orientation, Vector3
1213

@@ -129,7 +130,9 @@ async def get_accuracy(
129130
"""
130131
...
131132

132-
async def get_readings(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs) -> Mapping[str, Any]:
133+
async def get_readings(
134+
self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs
135+
) -> Mapping[str, SensorReading]:
133136
"""Obtain the measurements/data specific to this sensor.
134137
If a sensor is not configured to have a measurement or fails to read a piece of data, it will not appear in the readings dictionary.
135138

src/viam/components/power_sensor/client.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
PowerSensorServiceStub,
1515
)
1616
from viam.resource.rpc_client_base import ReconfigurableResourceRPCClientBase
17-
from viam.utils import ValueTypes, dict_to_struct, struct_to_dict
17+
from viam.utils import SensorReading, ValueTypes, dict_to_struct, sensor_readings_value_to_native, struct_to_dict
1818

1919

2020
class PowerSensorClient(PowerSensor, ReconfigurableResourceRPCClientBase):
@@ -46,12 +46,12 @@ async def get_power(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Op
4646
response: GetPowerResponse = await self.client.GetPower(request, timeout=timeout)
4747
return response.watts
4848

49-
async def get_readings(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None) -> Mapping[str, Any]:
49+
async def get_readings(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None) -> Mapping[str, SensorReading]:
5050
if extra is None:
5151
extra = {}
5252
request = GetReadingsRequest(name=self.name, extra=dict_to_struct(extra))
5353
response: GetReadingsResponse = await self.client.GetReadings(request, timeout=timeout)
54-
return response.readings
54+
return sensor_readings_value_to_native(response.readings)
5555

5656
async def do_command(self, command: Mapping[str, ValueTypes], *, timeout: Optional[float] = None) -> Mapping[str, ValueTypes]:
5757
request = DoCommandRequest(name=self.name, command=dict_to_struct(command))

src/viam/components/power_sensor/power_sensor.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
from viam.components.component_base import ComponentBase
55
from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype
6+
from viam.utils import SensorReading
67

78

89
class PowerSensor(ComponentBase):
@@ -41,7 +42,9 @@ async def get_power(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Op
4142
"""
4243
...
4344

44-
async def get_readings(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs) -> Mapping[str, Any]:
45+
async def get_readings(
46+
self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs
47+
) -> Mapping[str, SensorReading]:
4548
"""Obtain the measurements/data specific to this sensor.
4649
If a sensor is not configured to have a measurement or fails to read a piece of data, it will not appear in the readings dictionary.
4750

0 commit comments

Comments
 (0)