Repository navigation
Expand file tree
/
Copy pathcomponents.py
More file actions
853 lines (684 loc) · 29.4 KB
/
Copy pathcomponents.py
File metadata and controls
853 lines (684 loc) · 29.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
import asyncio
import math
import random
import struct
import sys
if sys.version_info >= (3, 9):
from collections.abc import AsyncIterator
else:
from typing import AsyncIterator
from datetime import datetime, timedelta
from io import BytesIO
from multiprocessing import Lock
from pathlib import Path
from typing import Any, AsyncIterable, Dict, List, Mapping, Optional, Sequence, Tuple
from google.protobuf.timestamp_pb2 import Timestamp
from PIL import Image
from viam.components.arm import Arm
from viam.components.audio_out import AudioOut
from viam.components.base import Base
from viam.components.board import Board, TickStream
from viam.components.camera import Camera
from viam.components.encoder import Encoder
from viam.components.gantry import Gantry
from viam.components.gripper import Gripper
from viam.components.input import Control, ControlFunction, Controller, Event, EventType
from viam.components.motor import Motor
from viam.components.movement_sensor import MovementSensor
from viam.components.pose_tracker import PoseTracker
from viam.components.sensor import Sensor
from viam.components.servo import Servo
from viam.errors import ResourceNotFoundError
from viam.media.video import CameraMimeType, NamedImage, ViamImage
from viam.operations import run_with_operation
from viam.proto.common import (
AudioInfo,
Capsule,
Geometry,
GeoPoint,
KinematicsFileFormat,
Orientation,
Pose,
PoseInFrame,
ResponseMetadata,
Sphere,
Vector3,
Mesh,
)
from viam.proto.component.arm import JointPositions, MoveOptions
from viam.proto.component.encoder import PositionType
from viam.streams import StreamWithIterator
from viam.utils import SensorReading, ValueTypes
GEOMETRIES = [
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)),
Geometry(center=Pose(x=1, y=2, z=3, o_x=2, o_y=3, o_z=4, theta=20), capsule=Capsule(radius_mm=3, length_mm=8)),
]
class ExampleArm(Arm):
def __init__(self, name: str):
self.position = Pose(
x=1,
y=2,
z=3,
o_x=2,
o_y=3,
o_z=4,
theta=20,
)
self.joint_positions = JointPositions(values=[0, 0, 0, 0, 0, 0])
self.is_stopped = True
self.kinematics = (KinematicsFileFormat.KINEMATICS_FILE_FORMAT_SVA, b"\x00\x01\x02", {})
super().__init__(name)
async def get_end_position(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Pose:
return self.position
async def move_to_position(
self,
pose: Pose,
extra: Optional[Dict[str, Any]] = None,
**kwargs,
):
self.is_stopped = False
self.position = pose
async def get_joint_positions(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> JointPositions:
return self.joint_positions
async def move_to_joint_positions(self, positions: JointPositions, extra: Optional[Dict[str, Any]] = None, **kwargs):
self.is_stopped = False
self.joint_positions = positions
async def move_through_joint_positions(
self,
positions: List[JointPositions],
options: Optional[MoveOptions] = None,
extra: Optional[Dict[str, Any]] = None,
**kwargs,
):
self.is_stopped = False
for position in positions:
self.joint_positions = position
async def move_through_joint_positions_streamed( # type: ignore
self,
batches: AsyncIterator[List[Arm.TrajectoryPoint]],
*,
extra: Optional[Dict[str, Any]] = None,
timeout: Optional[float] = None,
**kwargs,
) -> AsyncIterator[Arm.TrajectoryUpdate]:
self.is_stopped = False
async for batch in batches:
for point in batch:
self.joint_positions = JointPositions(values=point.positions)
yield Arm.TrajectoryUpdate()
self.is_stopped = True
async def get_3d_models(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Mapping[str, Mesh]:
return {}
async def set_manual_mode(self, manual_mode: bool, enabled_for: int = 0, extra: Optional[Dict[str, Any]] = None, **kwargs):
raise NotImplementedError()
async def get_manual_mode(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> bool:
raise NotImplementedError()
async def get_properties(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Arm.Properties:
return Arm.Properties(support_manual_mode=False, support_cartesian_commands=True)
async def stop(self, extra: Optional[Dict[str, Any]] = None, **kwargs):
self.is_stopped = True
async def is_moving(self):
return not self.is_stopped
async def get_kinematics(
self, extra: Optional[Dict[str, Any]] = None, **kwargs
) -> Tuple[KinematicsFileFormat.ValueType, bytes, Mapping[str, Mesh]]:
return self.kinematics
async def get_geometries(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[Geometry]:
return GEOMETRIES
async def get_status(self, *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]:
return {}
class ExampleAudioOut(AudioOut):
def __init__(self, name: str):
super().__init__(name)
self.sample_rate = 44100
self.num_channels = 2
self.supported_codecs = ["pcm16", "mp3", "wav"]
self.volume = 1.0
self.is_playing = False
async def play(
self,
data: bytes,
info: Optional[AudioInfo] = None,
*,
extra: Optional[Dict[str, Any]] = None,
timeout: Optional[float] = None,
**kwargs,
) -> None:
"""Play the given audio data."""
# Simulate playing audio
self.is_playing = True
if info:
print(f"Playing audio: {len(data)} bytes, codec={info.codec}, sample_rate={info.sample_rate_hz}, channels={info.num_channels}")
else:
print(f"Playing audio: {len(data)} bytes (no audio info provided)")
await asyncio.sleep(0.1)
self.is_playing = False
async def play_stream(
self,
info: AudioInfo,
chunks: AsyncIterable[bytes],
*,
extra: Optional[Dict[str, Any]] = None,
timeout: Optional[float] = None,
**kwargs,
) -> None:
"""Play streamed audio chunks."""
self.is_playing = True
print(f"Streaming audio: codec={info.codec}, sample_rate={info.sample_rate_hz}, channels={info.num_channels}")
total = 0
async for chunk in chunks:
total += len(chunk)
await asyncio.sleep(0)
print(f"Stream complete: {total} bytes")
self.is_playing = False
async def get_properties(
self, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs
) -> AudioOut.Properties:
"""Return the audio output device properties."""
return AudioOut.Properties(supported_codecs=self.supported_codecs, sample_rate_hz=self.sample_rate, num_channels=self.num_channels)
async def play_stream(
self,
chunks: AsyncIterator[bytes],
info: Optional[AudioInfo] = None,
*,
extra: Optional[Dict[str, Any]] = None,
timeout: Optional[float] = None,
**kwargs,
) -> None:
"""Play audio data from a stream of chunks."""
self.is_playing = True
if info:
print(f"Streaming audio: codec={info.codec}, sample_rate={info.sample_rate_hz}, channels={info.num_channels}")
async for chunk in chunks:
print(f"Streaming audio chunk: {len(chunk)} bytes")
self.is_playing = False
async def get_geometries(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[Geometry]:
return GEOMETRIES
async def get_status(self, *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]:
return {}
class ExampleBase(Base):
def __init__(self, name: str):
self.position = 0
self.angle = 0
self.is_stopped = True
self.linear_pwr = Vector3(x=0, y=0, z=0)
self.angular_pwr = Vector3(x=0, y=0, z=0)
self.linear_vel = Vector3(x=0, y=0, z=0)
self.angular_vel = Vector3(x=0, y=0, z=0)
self.props = Base.Properties(1.0, 1.0, 1.0)
super().__init__(name)
async def move_straight(self, distance: int, velocity: float, extra: Optional[Dict[str, Any]] = None, **kwargs):
if distance == 0 or velocity == 0:
return await self.stop()
if velocity > 0:
self.position += distance
else:
self.position -= distance
self.is_stopped = False
async def spin(self, angle: float, velocity: float, extra: Optional[Dict[str, Any]] = None, **kwargs):
if angle == 0 or velocity == 0:
return await self.stop()
if velocity > 0:
self.angle += angle
else:
self.angle -= angle
self.is_stopped = False
async def set_power(self, linear: Vector3, angular: Vector3, extra: Optional[Dict[str, Any]] = None, **kwargs):
self.linear_pwr = linear
self.angular_pwr = angular
async def set_velocity(self, linear: Vector3, angular: Vector3, extra: Optional[Dict[str, Any]] = None, **kwargs):
self.linear_vel = linear
self.angular_vel = angular
async def stop(self, extra: Optional[Dict[str, Any]] = None, **kwargs):
self.is_stopped = True
async def is_moving(self):
return not self.is_stopped
async def get_properties(self, *, timeout: Optional[float] = None, **kwargs) -> Base.Properties:
return self.props
async def get_geometries(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[Geometry]:
return GEOMETRIES
async def get_status(self, *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]:
return {}
class ExampleAnalog(Board.Analog):
def __init__(self, name: str, value: int):
self.value = value
super().__init__(name)
async def read(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> int:
return self.value
async def write(self, value: int, *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float], **kwargs):
self.value = value
class ExampleDigitalInterrupt(Board.DigitalInterrupt):
def __init__(self, name: str):
self.num_ticks = 0
super().__init__(name)
async def value(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> int:
return self.num_ticks
class ExampleGPIOPin(Board.GPIOPin):
def __init__(self, name: str):
self.high = False
self.pwm = 0.0
self.pwm_freq = 0
super().__init__(name)
async def get(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> bool:
return self.high
async def set(self, high: bool, extra: Optional[Dict[str, Any]] = None, **kwargs):
self.high = high
async def get_pwm(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> float:
return self.pwm
async def set_pwm(self, duty_cycle: float, extra: Optional[Dict[str, Any]] = None, **kwargs):
self.pwm = duty_cycle
async def get_pwm_frequency(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> int:
return self.pwm_freq
async def set_pwm_frequency(self, frequency: int, extra: Optional[Dict[str, Any]] = None, **kwargs):
self.pwm_freq = frequency
class ExampleBoard(Board):
def __init__(
self,
name: str,
analogs: Dict[str, Board.Analog],
digital_interrupts: Dict[str, Board.DigitalInterrupt],
gpio_pins: Dict[str, Board.GPIOPin],
):
self.analogs = analogs
self.digital_interrupts = digital_interrupts
self.gpios = gpio_pins
super().__init__(name)
async def analog_by_name(self, name: str) -> Board.Analog:
try:
return self.analogs[name]
except KeyError:
raise ResourceNotFoundError("Board.Analog", name)
async def digital_interrupt_by_name(self, name: str) -> Board.DigitalInterrupt:
try:
return self.digital_interrupts[name]
except KeyError:
raise ResourceNotFoundError("Board.DigitalInterrupt", name)
async def gpio_pin_by_name(self, name: str) -> Board.GPIOPin:
try:
return self.gpios[name]
except KeyError:
raise ResourceNotFoundError("Board.GPIOPin", name)
async def set_power_mode(self, **kwargs):
raise NotImplementedError()
async def stream_ticks(self, interrupts: List[Board.DigitalInterrupt], *, timeout: Optional[float] = None, **kwargs) -> TickStream:
raise NotImplementedError()
async def get_geometries(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[Geometry]:
return GEOMETRIES
async def get_status(self, *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]:
return {}
class ExampleCamera(Camera):
def __init__(self, name: str):
p = Path(__file__)
img = Image.open(p.parent.absolute().joinpath("viam.jpeg"))
buf = BytesIO()
img.copy().save(buf, format="JPEG")
self.image = ViamImage(buf.getvalue(), CameraMimeType.JPEG)
img.close()
super().__init__(name)
async def get_images(
self,
*,
filter_source_names: Optional[Sequence[str]] = None,
extra: Optional[Dict[str, Any]] = None,
timeout: Optional[float] = None,
**kwargs,
) -> Tuple[List[NamedImage], ResponseMetadata]:
ts = Timestamp()
ts.FromDatetime(datetime.now())
metadata = ResponseMetadata(captured_at=ts)
return [NamedImage(self.name, self.image.data, self.image.mime_type)], metadata
async def get_point_cloud(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Tuple[bytes, str]:
raise NotImplementedError()
async def get_properties(self, **kwargs) -> Camera.Properties:
raise NotImplementedError()
async def get_geometries(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[Geometry]:
return GEOMETRIES
async def get_status(self, *, timeout: Optional[float] = None, **kwargs) -> Dict[str, Any]:
return {}
class ExampleController(Controller):
CONTROL_MAP: Dict[int, Control] = {
0: Control.ABSOLUTE_X,
1: Control.ABSOLUTE_Y,
2: Control.ABSOLUTE_Z,
3: Control.ABSOLUTE_RX,
4: Control.ABSOLUTE_RY,
5: Control.ABSOLUTE_RZ,
16: Control.ABSOLUTE_HAT0_X,
17: Control.ABSOLUTE_HAT0_Y,
304: Control.BUTTON_SOUTH,
305: Control.BUTTON_EAST,
307: Control.BUTTON_WEST,
308: Control.BUTTON_NORTH,
310: Control.BUTTON_LT,
311: Control.BUTTON_RT,
314: Control.BUTTON_SELECT,
315: Control.BUTTON_START,
317: Control.BUTTON_L_THUMB,
318: Control.BUTTON_R_THUMB,
316: Control.BUTTON_MENU,
}
def __init__(self, name: str):
super().__init__(name)
self.last_events: Dict[Control, Event] = {}
self.callbacks: Dict[Control, Dict[EventType, Optional[ControlFunction]]] = {}
self.lock = Lock()
self.f = open("/dev/input/event0", "rb")
asyncio.get_running_loop().add_reader(self.f, self._read_input)
def _read_input(self):
data = self.f.read(24)
raw = struct.unpack("4IHHI", data)
if raw[4:] == (0, 0, 0):
return
secs = raw[0]
nanos = raw[2]
control = ExampleController.CONTROL_MAP[raw[5]]
value = raw[6]
e_type: EventType
if raw[5] < 20:
e_type = EventType.POSITION_CHANGE_ABSOLUTE
else:
e_type = EventType.BUTTON_RELEASE
if value == 1:
e_type = EventType.BUTTON_PRESS
if value == 4294967295:
value = -1
event = Event(time=float(((secs * 1e9) + nanos) / 1e9), control=control, event=e_type, value=value)
with self.lock:
self.last_events[control] = event
self._execute_callback(event)
def _execute_callback(self, event):
with self.lock:
callback = self.callbacks.get(event.control, {}).get(event.event, None)
if callback:
callback(event)
callback = self.callbacks.get(event.control, {}).get(EventType.ALL_EVENTS, None)
if callback:
callback(event)
async def get_controls(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[Control]:
return [
Control.ABSOLUTE_X,
Control.ABSOLUTE_Y,
Control.ABSOLUTE_Z,
Control.ABSOLUTE_RX,
Control.ABSOLUTE_RY,
Control.ABSOLUTE_RZ,
Control.ABSOLUTE_HAT0_X,
Control.ABSOLUTE_HAT0_Y,
Control.BUTTON_SOUTH,
Control.BUTTON_EAST,
Control.BUTTON_WEST,
Control.BUTTON_NORTH,
Control.BUTTON_LT,
Control.BUTTON_RT,
Control.BUTTON_L_THUMB,
Control.BUTTON_R_THUMB,
Control.BUTTON_SELECT,
Control.BUTTON_START,
Control.BUTTON_MENU,
]
async def get_events(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Dict[Control, Event]:
with self.lock:
return {key: value for (key, value) in self.last_events.items()}
def register_control_callback(self, control: Control, triggers: List[EventType], function: Optional[ControlFunction]):
with self.lock:
callbacks = self.callbacks.get(control, {})
for trigger in triggers:
if trigger == EventType.BUTTON_CHANGE:
callbacks[EventType.BUTTON_PRESS] = function
callbacks[EventType.BUTTON_RELEASE] = function
else:
callbacks[trigger] = function
self.callbacks[control] = callbacks
async def get_geometries(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[Geometry]:
return GEOMETRIES
async def get_status(self, *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]:
return {}
class ExampleEncoder(Encoder):
def __init__(self, name: str):
self.position: float = 0
self.position_type = PositionType.POSITION_TYPE_TICKS_COUNT
self.powered = False
self.task = None
super().__init__(name)
async def reset_position(self, extra: Optional[Dict[str, Any]] = None, **kwargs):
self.position = 0
async def get_position(
self, position_type: Optional[PositionType.ValueType], extra: Optional[Dict[str, Any]] = None, **kwargs
) -> Tuple[float, PositionType.ValueType]:
return self.position, self.position_type
async def get_properties(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Encoder.Properties:
return Encoder.Properties(ticks_count_supported=True, angle_degrees_supported=False)
async def get_geometries(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[Geometry]:
return GEOMETRIES
async def get_status(self, *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]:
return {}
class ExampleGantry(Gantry):
def __init__(self, name: str, position: List[float], lengths: List[float]):
self.position = position
self.lengths = lengths
self.is_stopped = True
super().__init__(name)
async def get_position(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[float]:
return self.position
async def move_to_position(
self,
positions: List[float],
speeds: List[float],
extra: Optional[Dict[str, Any]] = None,
**kwargs,
):
self.position = positions
self.is_stopped = False
async def get_lengths(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[float]:
return self.lengths
async def home(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> bool:
return True
async def stop(self, extra: Optional[Dict[str, Any]] = None, **kwargs):
self.is_stopped = True
async def is_moving(self):
return not self.is_stopped
async def get_geometries(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[Geometry]:
return GEOMETRIES
async def get_kinematics(
self, *, extra=None, timeout=None, **kwargs
) -> Tuple[KinematicsFileFormat.ValueType, bytes, Mapping[str, Mesh]]:
return (KinematicsFileFormat.KINEMATICS_FILE_FORMAT_UNSPECIFIED, b"abc", {})
async def get_status(self, *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]:
return {}
class ExampleGripper(Gripper):
def __init__(self, name: str):
self.opened = False
self.is_stopped = True
self.holding_something = False
self.kinematics = (KinematicsFileFormat.KINEMATICS_FILE_FORMAT_SVA, b"\x00\x01\x02", {})
self.current_inputs = []
super().__init__(name)
async def open(self, extra: Optional[Dict[str, Any]] = None, **kwargs):
self.opened = True
self.is_stopped = False
self.holding_something = False
async def grab(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> bool:
self.opened = False
self.is_stopped = False
self.holding_something = random.choice([True, False])
return self.holding_something
async def is_holding_something(self, *, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Gripper.HoldingStatus:
return Gripper.HoldingStatus(self.holding_something)
async def stop(self, extra: Optional[Dict[str, Any]] = None, **kwargs):
self.is_stopped = True
async def is_moving(self):
return not self.is_stopped
async def get_geometries(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[Geometry]:
return GEOMETRIES
async def get_kinematics(
self, extra: Optional[Dict[str, Any]] = None, **kwargs
) -> Tuple[KinematicsFileFormat.ValueType, bytes, Mapping[str, Mesh]]:
return self.kinematics
async def get_status(self, *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]:
return {}
async def get_current_inputs(
self,
*,
extra: Optional[Dict[str, Any]] = None,
timeout: Optional[float] = None,
**kwargs,
) -> List[float]:
return self.current_inputs
async def go_to_inputs(self, values: List[float], *, extra: Optional[Dict[str, Any]] = None, timeout: Optional[float] = None, **kwargs):
self.current_inputs = values
class ExampleMotor(Motor):
def __init__(self, name: str):
self.position: float = 0
self.power = 0
self.powered = False
self.task = None
super().__init__(name)
async def run_continuously(self, rpm: float):
rps = rpm / 60
while True:
await asyncio.sleep(1)
self.position += rps
async def set_power(self, power: float, extra: Optional[Dict[str, Any]] = None, **kwargs):
self.power = power
self.powered = power != 0
if self.powered:
self.task = asyncio.create_task(self.run_continuously(power))
else:
if self.task:
self.task.cancel()
async def go_for(self, rpm: float, revolutions: float, extra: Optional[Dict[str, Any]] = None, **kwargs):
if self.task:
self.task.cancel()
target = 0
rps = rpm / 60
if rpm > 0:
target = self.position + revolutions
if rpm < 0:
target = self.position - revolutions
self.powered = True
while abs(self.position - target) > 0.01:
await asyncio.sleep(1)
self.position += rps
self.powered = False
async def go_to(self, rpm: float, position_revolutions: float, extra: Optional[Dict[str, Any]] = None, **kwargs):
if self.task:
self.task.cancel()
distance = position_revolutions - self.position
rps = rpm / 60
self.powered = True
while distance > 0:
await asyncio.sleep(1)
distance -= abs(rps)
self.position += rps
self.powered = False
async def set_rpm(self, rpm: float, extra: Optional[Dict[str, Any]] = None, **kwargs):
if self.task:
self.task.cancel()
self.powered = True
self.task = asyncio.create_task(self.run_continuously(rpm))
async def reset_zero_position(self, offset: float, extra: Optional[Dict[str, Any]] = None, **kwargs):
if (self.position > 0 and offset > 0) or (self.position < 0 and offset < 0):
self.position = offset
else:
self.position += offset
self.powered = False
async def get_position(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> float:
return self.position
async def get_properties(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Motor.Properties:
return Motor.Properties(position_reporting=True)
async def stop(self, extra: Optional[Dict[str, Any]] = None, **kwargs):
await self.set_power(0)
async def is_powered(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> Tuple[bool, float]:
return self.powered, self.power
async def is_moving(self):
return self.powered
async def get_geometries(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[Geometry]:
return GEOMETRIES
async def get_status(self, *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]:
return {}
class ExampleMovementSensor(MovementSensor):
def __init__(
self,
name: str,
coordinates: GeoPoint,
altitude: float,
lin_vel: Vector3,
ang_vel: Vector3,
lin_acc: Vector3,
heading: float,
orientation: Orientation,
properties: MovementSensor.Properties,
accuracy: Mapping[str, float],
):
super().__init__(name)
self.num_readings = random.randint(1, 10)
self.coordinates = coordinates
self.altitude = altitude
self.lin_vel = lin_vel
self.ang_vel = ang_vel
self.lin_acc = lin_acc
self.heading = heading
self.orientation = orientation
self.properties = properties
self.accuracy = accuracy
async def get_readings(self, **kwargs) -> Mapping[str, SensorReading]:
return {"abcdefghij"[idx]: random.random() for idx in range(self.num_readings)}
async def get_position(self, **kwargs) -> Tuple[GeoPoint, float]:
return (self.coordinates, self.altitude)
async def get_linear_velocity(self, **kwargs) -> Vector3:
return self.lin_vel
async def get_angular_velocity(self, **kwargs) -> Vector3:
return self.ang_vel
async def get_linear_acceleration(self, **kwargs) -> Vector3:
return self.lin_acc
async def get_compass_heading(self, **kwargs) -> float:
return self.heading
async def get_orientation(self, **kwargs) -> Orientation:
return self.orientation
async def get_properties(self, **kwargs) -> MovementSensor.Properties:
return self.properties
async def get_accuracy(self, **kwargs) -> Mapping[str, float]:
return self.accuracy
async def get_geometries(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[Geometry]:
return GEOMETRIES
async def get_status(self, *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]:
return {}
class ExamplePoseTracker(PoseTracker):
async def get_poses(self, body_names: List[str], **kwargs) -> Dict[str, PoseInFrame]:
all_poses = {
"body1": PoseInFrame(reference_frame="0", pose=Pose(x=1, y=2, z=3, o_x=2, o_y=3, o_z=4, theta=20)),
"body2": PoseInFrame(reference_frame="0", pose=Pose(x=3, y=2, z=3, o_x=4, o_y=3, o_z=4, theta=40)),
}
return {k: v for k, v in all_poses.items() if k in body_names}
async def get_geometries(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[Geometry]:
return GEOMETRIES
async def get_status(self, *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]:
return {}
class ExampleSensor(Sensor):
def __init__(self, name: str):
self.num_readings = random.randint(1, 10)
super().__init__(name)
async def get_readings(self, **kwargs) -> Mapping[str, SensorReading]:
return {"abcdefghij"[idx]: random.random() for idx in range(self.num_readings)}
async def get_geometries(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[Geometry]:
return GEOMETRIES
async def get_status(self, *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]:
return {}
class ExampleServo(Servo):
def __init__(self, name: str):
self.angle = 0
self.is_stopped = True
super().__init__(name)
async def move(self, angle: int, **kwargs):
self.angle = angle
self.is_stopped = False
async def get_position(self, **kwargs) -> int:
return self.angle
async def stop(self, **kwargs):
self.is_stopped = True
async def is_moving(self):
return not self.is_stopped
async def get_geometries(self, extra: Optional[Dict[str, Any]] = None, **kwargs) -> List[Geometry]:
return GEOMETRIES
async def get_status(self, *, timeout: Optional[float] = None, **kwargs) -> Mapping[str, ValueTypes]:
return {}