Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[RSDK-5810] remove impossible-to-implement functions from digital interrupts #503

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 1 addition & 17 deletions examples/server/v1/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
from typing import AsyncIterator

from datetime import timedelta
from multiprocessing import Lock, Queue
from multiprocessing import Lock
from pathlib import Path
from typing import Any, Dict, List, Mapping, Optional, Tuple

Expand All @@ -20,7 +20,6 @@
from viam.components.audio_input import AudioInput
from viam.components.base import Base
from viam.components.board import Board
from viam.components.board.board import PostProcessor
from viam.components.camera import Camera
from viam.components.encoder import Encoder
from viam.components.gantry import Gantry
Expand Down Expand Up @@ -241,27 +240,12 @@ async def read(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> int:

class ExampleDigitalInterrupt(Board.DigitalInterrupt):
def __init__(self, name: str):
self.high = False
self.last_tick = 0
self.num_ticks = 0
self.callbacks: List[Queue] = []
self.post_processors: List[PostProcessor] = []
super().__init__(name)

async def value(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> int:
return self.num_ticks

async def tick(self, high: bool, nanos: int):
self.high = high
self.last_tick = nanos
self.num_ticks += 1

async def add_callback(self, queue: Queue):
self.callbacks.append(queue)

async def add_post_processor(self, processor: PostProcessor):
self.post_processors.append(processor)


class ExampleGPIOPin(Board.GPIOPin):
def __init__(self, name: str):
Expand Down
40 changes: 1 addition & 39 deletions src/viam/components/board/board.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,13 @@
import abc
from datetime import timedelta
from multiprocessing import Queue
from typing import Any, Callable, Dict, Final, List, Optional
from typing import Any, Dict, Final, List, Optional

from viam.proto.common import BoardStatus
from viam.proto.component.board import PowerMode
from viam.resource.types import RESOURCE_NAMESPACE_RDK, RESOURCE_TYPE_COMPONENT, Subtype

from ..component_base import ComponentBase

PostProcessor = Callable[[int], int]


class Board(ComponentBase):
"""
Expand Down Expand Up @@ -57,41 +54,6 @@ async def value(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Option
"""
...

@abc.abstractmethod
async def tick(self, high: bool, nanos: int):
"""
This method is to be called either manually if the interrupt
is a proxy to some real hardware interrupt or for tests.

Args:
high (bool): If the signal of the interrupt is high.
nanos (int): Nanoseconds from an arbitrary point in time,
but always increasing and always needs to be accurate.
Using ``time.time_ns()`` would be acceptable.
"""
...

@abc.abstractmethod
async def add_callback(self, queue: Queue):
"""
Add a callback to be sent the low/high value on ``tick()``.

Args:
queue (Queue): The receiving queue.
"""
...

@abc.abstractmethod
async def add_post_processor(self, processor: PostProcessor):
"""
Add a post processor that should be used to modify what
is returned by ``self.value()``

Args:
processor (PostProcessor): The post processor to add.
"""
...

class GPIOPin(ComponentBase):
"""
Abstract representation of an individual GPIO pin on a board
Expand Down
11 changes: 0 additions & 11 deletions src/viam/components/board/client.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from datetime import timedelta
from multiprocessing import Queue
from typing import Any, Dict, List, Mapping, Optional

from google.protobuf.duration_pb2 import Duration
Expand Down Expand Up @@ -31,7 +30,6 @@
from viam.utils import ValueTypes, dict_to_struct, get_geometries, struct_to_dict

from . import Board
from .board import PostProcessor


class AnalogReaderClient(Board.AnalogReader):
Expand Down Expand Up @@ -59,15 +57,6 @@ async def value(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Option
response: GetDigitalInterruptValueResponse = await self.board.client.GetDigitalInterruptValue(request, timeout=timeout)
return response.value

async def tick(self, high: bool, nanos: int):
raise NotImplementedError()

async def add_callback(self, queue: Queue):
raise NotImplementedError()

async def add_post_processor(self, processor: PostProcessor):
raise NotImplementedError()


class GPIOPinClient(Board.GPIOPin):
def __init__(self, name: str, board: "BoardClient"):
Expand Down
15 changes: 1 addition & 14 deletions tests/mocks/components.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

from dataclasses import dataclass
from datetime import datetime, timedelta
from multiprocessing import Queue
from secrets import choice
from typing import Any, Dict, List, Mapping, Optional, Tuple, Union

Expand All @@ -18,7 +17,6 @@
from viam.components.audio_input import AudioInput
from viam.components.base import Base
from viam.components.board import Board
from viam.components.board.board import PostProcessor
from viam.components.camera import Camera, DistortionParameters, IntrinsicParameters
from viam.components.encoder import Encoder
from viam.components.gantry import Gantry
Expand Down Expand Up @@ -262,27 +260,16 @@ def __init__(self, name: str):
self.high = False
self.last_tick = 0
self.num_ticks = 0
self.callbacks: List[Queue] = []
self.post_processors: List[PostProcessor] = []
self.timeout: Optional[float] = None
super().__init__(name)

async def value(self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs) -> int:
self.extra = extra
self.timeout = timeout
return self.num_ticks

async def tick(self, high: bool, nanos: int):
async def tick(self, high: bool, nanos: int): # Call this to get the mock interrupt to change
self.high = high
self.last_tick = nanos
self.num_ticks += 1

async def add_callback(self, queue: Queue):
self.callbacks.append(queue)

async def add_post_processor(self, processor: PostProcessor):
self.post_processors.append(processor)


class MockGPIOPin(Board.GPIOPin):
def __init__(self, name: str):
Expand Down
13 changes: 5 additions & 8 deletions tests/test_board.py
Original file line number Diff line number Diff line change
Expand Up @@ -175,21 +175,18 @@ async def test_get_digital_interrupt_value(self, board: MockBoard, service: Boar
async with ChannelFor([service]) as channel:
client = BoardServiceStub(channel)

request = GetDigitalInterruptValueRequest(
board_name=board.name, digital_interrupt_name="dne"
)
with pytest.raises(GRPCError, match=r".*Status.NOT_FOUND.*"):
request = GetDigitalInterruptValueRequest(board_name=board.name, digital_interrupt_name="dne")
await client.GetDigitalInterruptValue(request)

extra = {"foo": "bar", "baz": [1, 2, 3]}
request = GetDigitalInterruptValueRequest(
board_name=board.name, digital_interrupt_name="interrupt1", extra=dict_to_struct(extra)
board_name=board.name, digital_interrupt_name="interrupt1"
)
response: GetDigitalInterruptValueResponse = await client.GetDigitalInterruptValue(request, timeout=18.2)
response: GetDigitalInterruptValueResponse = await client.GetDigitalInterruptValue(request)
assert response.value == 0

interrupt = cast(MockDigitalInterrupt, board.digital_interrupts["interrupt1"])
assert interrupt.extra == extra
assert interrupt.timeout == loose_approx(18.2)

@pytest.mark.asyncio
async def test_set_gpio(self, board: MockBoard, service: BoardRPCService):
async with ChannelFor([service]) as channel:
Expand Down
Loading