edu-robot-api 0.6.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,20 @@
1
+ """Typed robot, sensor and actuator interfaces for educational programs."""
2
+ # Resolve package modules across Python search-path entries.
3
+ from pkgutil import extend_path as _extend_path
4
+
5
+ __path__ = _extend_path(__path__, __name__)
6
+ del _extend_path
7
+
8
+ from .components import (Actuator, Backend, Buzzer, Camera, CapabilityUnavailable,
9
+ Component, ContactSensor, DCMotor, DistanceSensor,
10
+ FunctionBackend, Kicker, LEDMatrix, LineSensor, Motor,
11
+ RGBLights, Robot, Sensor, SensorReadings, ServoMotor,
12
+ motor_pair, percent)
13
+ from .components import Bridge, WorkbenchBridge
14
+ from .connection import connect_robot
15
+
16
+ __version__ = "0.6.0"
17
+ __all__ = ["Robot", "connect_robot", "Bridge", "WorkbenchBridge", "Sensor", "DistanceSensor", "LineSensor",
18
+ "ContactSensor", "Camera", "SensorReadings", "Component", "Actuator", "Motor", "DCMotor",
19
+ "ServoMotor", "RGBLights", "LEDMatrix", "Buzzer", "Kicker", "Backend", "FunctionBackend",
20
+ "CapabilityUnavailable", "motor_pair", "percent"]
@@ -0,0 +1,467 @@
1
+ """Portable component API (CPython and Pyodide). No transport dependencies."""
2
+ from __future__ import annotations
3
+
4
+ from collections.abc import Callable, Iterator, Mapping, Sequence
5
+ from copy import deepcopy
6
+ from typing import Any, Generic, Protocol, TypeVar, overload
7
+
8
+ T = TypeVar("T")
9
+
10
+
11
+ class CapabilityUnavailable(Exception):
12
+ """The connected robot does not provide this component or operation."""
13
+
14
+
15
+ class Backend(Protocol):
16
+ def call(self, operation: str, *args: Any) -> Any: ...
17
+
18
+
19
+ class FunctionBackend:
20
+ """Boundary adapter for existing device and simulator drivers."""
21
+ def __init__(self, functions: Mapping[str, Callable[..., Any]]) -> None:
22
+ self.functions = functions
23
+
24
+ def call(self, operation: str, *args: Any) -> Any:
25
+ if operation not in self.functions:
26
+ raise CapabilityUnavailable(operation)
27
+ try:
28
+ return self.functions[operation](*args)
29
+ except Exception as error:
30
+ if type(error).__name__ == "CapabilityUnavailable":
31
+ raise CapabilityUnavailable(str(error)) from error
32
+ raise
33
+
34
+
35
+ def percent(value: float) -> float:
36
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not -float("inf") < value < float("inf"):
37
+ raise ValueError("Motorleistung muss eine endliche Zahl sein.")
38
+ return max(-100, min(100, value))
39
+
40
+
41
+ def motor_pair(linear: float, turn: float) -> tuple[float, float]:
42
+ linear, turn = percent(linear), percent(turn)
43
+ return percent(linear + turn), percent(linear - turn)
44
+
45
+
46
+ class Component:
47
+ def __init__(self, robot: Robot, identifier: str, name: str, *, position: str | None = None) -> None:
48
+ self._robot, self._channel, self._name = robot, identifier, name
49
+ self._id = ("sensor:" if isinstance(self, Sensor) else "actuator:") + identifier
50
+ self.position = position
51
+
52
+ @property
53
+ def id(self) -> str:
54
+ """Stable within a connection, independent of the editable display name."""
55
+ return self._id
56
+
57
+ @property
58
+ def name(self) -> str:
59
+ return self._name
60
+
61
+ @name.setter
62
+ def name(self, value: str) -> None:
63
+ self._robot.rename(self, value)
64
+
65
+ def __str__(self) -> str:
66
+ return self.name
67
+
68
+ def __repr__(self) -> str:
69
+ return f"{type(self).__name__}({self.name!r})"
70
+
71
+
72
+ class Sensor(Component, Generic[T]):
73
+ def read(self) -> T | None:
74
+ return self._robot.read_sensors([self])[self]
75
+
76
+
77
+ class DistanceSensor(Sensor[float]):
78
+ """Distance in centimetres; None means no usable measurement."""
79
+ def obstacle_ahead(self, threshold_cm: float = 30) -> bool | None:
80
+ if isinstance(threshold_cm, bool) or not isinstance(threshold_cm, (int, float)) or not 0 <= threshold_cm < float("inf"):
81
+ raise ValueError("Abstand muss endlich und nicht negativ sein.")
82
+ value = self.read()
83
+ return None if value is None else value < threshold_cm
84
+
85
+
86
+ class LineSensor(Sensor[bool]):
87
+ """Digital line detector: True means the dark line is detected."""
88
+
89
+
90
+ class ContactSensor(Sensor[bool]):
91
+ pass
92
+
93
+
94
+ class Camera(Sensor[dict[str, Any]]):
95
+ """RGB image: width, height, row-major pixels packed as 0xRRGGBB."""
96
+ def read(self, *, full_resolution: bool = True) -> dict[str, Any] | None:
97
+ return self._robot._call("camera_image" if full_resolution else "camera")
98
+
99
+ def start(self) -> None:
100
+ self._robot._call("start_camera")
101
+
102
+ def stop(self) -> None:
103
+ self._robot._call("stop_camera")
104
+
105
+
106
+ class SensorReadings(Mapping[Sensor[Any] | str | int, Any]):
107
+ """A measurement snapshot. Iteration uses the names at capture time."""
108
+ def __init__(self, sensors: Sequence[Sensor[Any]], values: Sequence[Any]) -> None:
109
+ self._sensors = tuple(sensors)
110
+ self._names = tuple(sensor.name for sensor in sensors)
111
+ self._values = deepcopy(tuple(values))
112
+
113
+ @overload
114
+ def __getitem__(self, key: Sensor[T]) -> T | None: ...
115
+ @overload
116
+ def __getitem__(self, key: str | int) -> Any: ...
117
+ def __getitem__(self, key: object) -> Any:
118
+ if isinstance(key, bool):
119
+ raise KeyError(key)
120
+ if isinstance(key, int):
121
+ return deepcopy(self._values[key])
122
+ keys = self._names if isinstance(key, str) else self._sensors
123
+ try:
124
+ index = keys.index(key)
125
+ except ValueError:
126
+ raise KeyError(key) from None
127
+ return deepcopy(self._values[index])
128
+
129
+ def __iter__(self) -> Iterator[str]:
130
+ return iter(self._names)
131
+
132
+ def __len__(self) -> int:
133
+ return len(self._values)
134
+
135
+
136
+ class Actuator(Component):
137
+ pass
138
+
139
+
140
+ class Motor(Actuator):
141
+ pass
142
+
143
+
144
+ class DCMotor(Motor):
145
+ def set_power(self, power: float) -> None:
146
+ self._robot._set_motor(self, percent(power))
147
+
148
+ def stop(self) -> None:
149
+ self.set_power(0)
150
+
151
+
152
+ class ServoMotor(Motor):
153
+ def __init__(self, *args: Any, minimum: float = 0, maximum: float = 180, **kwargs: Any) -> None:
154
+ super().__init__(*args, **kwargs)
155
+ self.minimum, self.maximum = minimum, maximum
156
+
157
+ def set_angle(self, angle: float) -> None:
158
+ if isinstance(angle, bool) or not isinstance(angle, (int, float)) or not self.minimum <= angle <= self.maximum:
159
+ raise ValueError(f"Servowinkel muss zwischen {self.minimum} und {self.maximum} Grad liegen.")
160
+ self._robot._set_servo(self, angle)
161
+
162
+
163
+ class RGBLights(Actuator):
164
+ def set_color(self, index: int | str, red: int, green: int, blue: int) -> None:
165
+ if index == "all":
166
+ index = -1
167
+ if isinstance(index, bool) or not isinstance(index, int) or not -1 <= index < self._robot._led_count:
168
+ raise ValueError("Ungültiger LED-Index.")
169
+ if any(isinstance(v, bool) or not isinstance(v, int) or not 0 <= v <= 255 for v in (red, green, blue)):
170
+ raise ValueError("RGB-Werte müssen ganze Zahlen von 0 bis 255 sein.")
171
+ self._robot._call("rgb_led", index, red, green, blue)
172
+
173
+ def set_mode(self, mode: int) -> None:
174
+ _mode(mode, 5)
175
+ self._robot._call("rgb_mode", mode)
176
+
177
+
178
+ def _mode(value: int, maximum: int) -> None:
179
+ if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= maximum:
180
+ raise ValueError(f"Modus muss eine ganze Zahl von 0 bis {maximum} sein.")
181
+
182
+
183
+ class LEDMatrix(Actuator):
184
+ def set_mode(self, mode: int) -> None:
185
+ _mode(mode, 3)
186
+ self._robot._call("matrix_mode", mode)
187
+
188
+
189
+ class Buzzer(Actuator):
190
+ def set(self, enabled: bool = True, frequency: int = 2000) -> None:
191
+ if not isinstance(enabled, bool) or isinstance(frequency, bool) or not isinstance(frequency, int) or not 20 <= frequency <= 20000:
192
+ raise ValueError("Summer: bool und Frequenz 20 bis 20000 Hz erwartet.")
193
+ self._robot._call("buzzer", enabled, frequency)
194
+
195
+ def stop(self) -> None:
196
+ self.set(False)
197
+
198
+
199
+ class Kicker(Actuator):
200
+ def kick(self, power: float = 75) -> None:
201
+ self._robot._call("kick", max(0, percent(power)))
202
+
203
+
204
+ class SimulationView:
205
+ """Optional observations; never advertised by a physical bridge."""
206
+ def __init__(self, robot: Robot) -> None:
207
+ self._robot = robot
208
+
209
+ def position(self) -> dict[str, float]:
210
+ return self._robot._call("position")
211
+
212
+ def ball_position(self) -> dict[str, float]:
213
+ return self._robot._call("ball_position")
214
+
215
+ def opponent_position(self) -> dict[str, float] | None:
216
+ return self._robot._call("opponent_position")
217
+
218
+ def goal_position(self) -> dict[str, float]:
219
+ return self._robot._call("goal_position")
220
+
221
+ def ball_distance(self) -> float:
222
+ return self._robot._call("ball_distance")
223
+
224
+ def ball_angle(self) -> float:
225
+ return self._robot._call("ball_angle")
226
+
227
+ def kickoff_wait(self) -> bool:
228
+ return self._robot._call("kickoff_wait")
229
+
230
+ def kickoff_time(self) -> float:
231
+ return self._robot._call("kickoff_time")
232
+
233
+
234
+ class Robot:
235
+ """One named connection, composed of components; operations delegate to a backend."""
236
+ @staticmethod
237
+ def connect(name: str | None = None, *, bridge: Bridge | None = None,
238
+ speed: float = 60, **options: Any) -> Robot:
239
+ """Create a connected robot; release it with disconnect()."""
240
+ if bridge is not None:
241
+ if name is not None or options:
242
+ raise ValueError("Bei bridge= nur die Bridge und optional speed angeben.")
243
+ return bridge._connect(speed=speed)
244
+ from edu_robot_api import connect_robot
245
+ return connect_robot(name, speed=speed, **options)
246
+
247
+ def __init__(self, backend: Backend, *, name: str, model: str, speed: float = 60,
248
+ components: Sequence[Mapping[str, Any]] | None = None) -> None:
249
+ self._backend, self.name, self.model = backend, name, model
250
+ self.id = name
251
+ self.memory: dict[str, Any] = {}
252
+ self._closed = False
253
+ self._speed = abs(percent(speed))
254
+ self._capabilities = backend.call("capabilities")
255
+ self.simulation = SimulationView(self)
256
+ self._sensors: dict[str, Sensor[Any]] = {}
257
+ self._actuators: dict[str, Actuator] = {}
258
+ for key in self._capabilities["sensors"]:
259
+ cls: type[Sensor[Any]] = DistanceSensor if key.startswith("distance_") else LineSensor if key.startswith("line_") and key != "line_raw" else ContactSensor if key.startswith("bumper_") else Sensor
260
+ self._sensors[key] = cls(self, key, key, position=key.split("_", 1)[1] if "_" in key else None)
261
+ count = self._capabilities.get("motor_count", 2)
262
+ wheel_names = ["motor_left", "motor_right"] if count == 2 else ["motor_front_left", "motor_rear_left", "motor_front_right", "motor_rear_right"]
263
+ self._wheels = [DCMotor(self, key, key, position=key.removeprefix("motor_")) for key in wheel_names]
264
+ self._powers = [0.0] * count
265
+ self._angles = {"camera_pan": 90.0, "camera_tilt": 90.0}
266
+ self._led_count = 4 if count == 2 else 12
267
+ self._actuators.update((motor.name, motor) for motor in self._wheels)
268
+ commands = self._capabilities["commands"]
269
+ if "camera" in commands:
270
+ self._sensors["camera"] = Camera(self, "camera", "camera", position="front")
271
+ for command, key, actuator_cls in [("rgb_led", "rgb_leds", RGBLights), ("buzzer", "buzzer", Buzzer), ("matrix_mode", "matrix", LEDMatrix), ("kick", "kicker", Kicker)]:
272
+ if command in commands:
273
+ self._actuators[key] = actuator_cls(self, key, key)
274
+ if "camera_orientation" in commands:
275
+ for key in self._angles:
276
+ self._actuators[key] = ServoMotor(self, key, key, minimum=80 if key == "camera_tilt" else 0)
277
+ if components is not None:
278
+ known = {component.id: component for component in [*self._sensors.values(), *self._actuators.values()]}
279
+ sensors: dict[str, Sensor[Any]] = {}
280
+ actuators: dict[str, Actuator] = {}
281
+ seen: set[str] = set()
282
+ for spec in components:
283
+ identifier, label = spec.get("id"), spec.get("name")
284
+ if identifier not in known or identifier in seen or not isinstance(label, str) or not label.strip():
285
+ raise ValueError("Ungültige Bauteilbeschreibung der Bridge.")
286
+ seen.add(identifier)
287
+ component = known[identifier]
288
+ if spec.get("type") != type(component).__name__:
289
+ raise ValueError("Bauteiltyp passt nicht zum Modell: " + identifier)
290
+ registry: dict[str, Any] = sensors if isinstance(component, Sensor) else actuators
291
+ if label in registry:
292
+ raise ValueError("Doppelter Bauteilname: " + label)
293
+ component._name, component.position = label, spec.get("position")
294
+ registry[label] = component
295
+ if any(wheel.id not in seen for wheel in self._wheels):
296
+ raise ValueError("Die Beschreibung enthält nicht alle Antriebsmotoren.")
297
+ self._sensors, self._actuators = sensors, actuators
298
+
299
+ def _call(self, operation: str, *args: Any) -> Any:
300
+ if self._closed:
301
+ raise RuntimeError("Verbindung ist geschlossen.")
302
+ return self._backend.call(operation, *args)
303
+
304
+ def sensors(self) -> dict[str, Sensor[Any]]:
305
+ return dict(self._sensors)
306
+
307
+ def actuators(self) -> dict[str, Actuator]:
308
+ return dict(self._actuators)
309
+
310
+ def rename(self, component: Component, name: str) -> None:
311
+ registry: dict[str, Any] = self._sensors if isinstance(component, Sensor) else self._actuators
312
+ if component._robot is not self or registry.get(component.name) is not component:
313
+ raise ValueError("Bauteil gehört nicht zu diesem Roboter.")
314
+ if not isinstance(name, str) or not name.strip():
315
+ raise ValueError("Bauteilname darf nicht leer sein.")
316
+ if name in registry and registry[name] is not component:
317
+ raise ValueError("Bauteilname ist bereits vergeben: " + name)
318
+ # Rebuild in place to preserve mounting/selection order.
319
+ entries = [(name if value is component else key, value) for key, value in registry.items()]
320
+ registry.clear()
321
+ registry.update(entries)
322
+ component._name = name
323
+
324
+ def read_sensors(self, selection: Sequence[Sensor[Any] | str] | None = None) -> SensorReadings:
325
+ if isinstance(selection, (str, bytes)):
326
+ raise TypeError("Sensoren als Liste übergeben, zum Beispiel ['line_left'].")
327
+ selected = list(self._sensors.values()) if selection is None else [self._sensors[s] if isinstance(s, str) else s for s in selection]
328
+ if any(not isinstance(s, Sensor) or s._robot is not self or self._sensors.get(s.name) is not s for s in selected):
329
+ raise ValueError("Sensor gehört nicht zu diesem Roboter.")
330
+ if len(set(selected)) != len(selected):
331
+ raise ValueError("Sensor wurde mehrfach angefordert.")
332
+ if not selected:
333
+ return SensorReadings([], [])
334
+ # One telemetry refresh for all requested non-camera values. Never call read() in a loop.
335
+ values = self._call("update_sensors") if any(not isinstance(s, Camera) for s in selected) else {}
336
+ return SensorReadings(selected, [self._call("camera_image") if isinstance(s, Camera) else values.get(s._channel) for s in selected])
337
+
338
+ def _set_motor(self, motor: DCMotor, power: float) -> None:
339
+ powers = self._powers.copy()
340
+ powers[self._wheels.index(motor)] = power
341
+ self.set_motors(*powers)
342
+
343
+ def _set_servo(self, servo: ServoMotor, angle: float) -> None:
344
+ angles = dict(self._angles)
345
+ angles[servo._channel] = angle
346
+ self._call("camera_orientation", angles["camera_pan"], angles["camera_tilt"])
347
+ self._angles = angles
348
+
349
+ def set_motors(self, *powers: float) -> None:
350
+ if len(powers) != len(self._wheels):
351
+ raise ValueError("Anzahl der Motorwerte passt nicht zum Modell.")
352
+ values = [percent(p) for p in powers]
353
+ self._call("set_motors", *values)
354
+ self._powers = values
355
+
356
+ def drive(self, linear: float, turn: float = 0) -> None:
357
+ left, right = motor_pair(linear, turn)
358
+ self.set_motors(*([left, right] if len(self._wheels) == 2 else [left, left, right, right]))
359
+
360
+ def forward(self, power: float | None = None) -> None:
361
+ self.drive(self._speed if power is None else percent(power))
362
+
363
+ def backward(self, power: float | None = None) -> None:
364
+ self.drive(-(self._speed if power is None else abs(percent(power))))
365
+
366
+ def turn_left(self, power: float | None = None) -> None:
367
+ self.drive(0, -(self._speed if power is None else abs(percent(power))))
368
+
369
+ def turn_right(self, power: float | None = None) -> None:
370
+ self.drive(0, self._speed if power is None else abs(percent(power)))
371
+
372
+ def stop(self) -> None:
373
+ self._call("stop")
374
+ self._powers = [0.0] * len(self._wheels)
375
+
376
+ def speed(self) -> float:
377
+ return self._speed
378
+
379
+ def set_speed(self, speed: float) -> None:
380
+ self._speed = abs(percent(speed))
381
+
382
+ def capabilities(self) -> dict[str, Any]:
383
+ result = deepcopy(self._capabilities)
384
+ result["sensors"] = list(self._sensors)
385
+ result["actuators"] = list(self._actuators)
386
+ result["commands"] = ["sensors", "actuators", "read_sensors", "rename", "drive", "set_motors",
387
+ "forward", "backward", "turn_left", "turn_right", "stop", "speed",
388
+ "set_speed", "time", "log", "disconnect", "close", "capabilities"]
389
+ return result
390
+
391
+ def time(self) -> float:
392
+ return self._call("time")
393
+
394
+ def log(self, message: object) -> None:
395
+ self._call("log", str(message))
396
+
397
+ def disconnect(self) -> None:
398
+ """Stop motors and release this control connection; idempotent."""
399
+ if self._closed:
400
+ return
401
+ try:
402
+ self.stop()
403
+ finally:
404
+ try:
405
+ self._backend.call("close")
406
+ finally:
407
+ self._closed = True
408
+
409
+ def close(self) -> None:
410
+ """Compatibility alias for disconnect()."""
411
+ self.disconnect()
412
+
413
+ def __enter__(self) -> Robot:
414
+ if self._closed:
415
+ raise RuntimeError("Verbindung ist geschlossen.")
416
+ return self
417
+
418
+ def __exit__(self, exc_type: Any, exc_value: Any, traceback: Any) -> None:
419
+ self.close()
420
+
421
+
422
+ class Bridge:
423
+ """Lifecycle of an explicitly selected robot endpoint. Factories do no I/O."""
424
+ def __init__(self) -> None:
425
+ self._started = False
426
+ self._connection: Robot | None = None
427
+
428
+ def start(self) -> None:
429
+ raise NotImplementedError
430
+
431
+ def stop(self) -> None:
432
+ self._started = False
433
+
434
+ def _require_ready(self) -> None:
435
+ if not self._started:
436
+ raise RuntimeError("Zuerst bridge.start() aufrufen.")
437
+ if self._connection is not None and not self._connection._closed:
438
+ raise RuntimeError("Diese Bridge hat bereits eine Steuerverbindung.")
439
+
440
+ def _connect(self, *, speed: float = 60) -> Robot:
441
+ raise NotImplementedError
442
+
443
+
444
+ class WorkbenchBridge(Bridge):
445
+ """Select a robot in the current Workbench world; no native process."""
446
+ robot_name: str
447
+ @classmethod
448
+ def create(cls, *, robot_name: str) -> WorkbenchBridge:
449
+ if not isinstance(robot_name, str) or not robot_name.strip():
450
+ raise ValueError("Ein Robotername aus dem Welteditor ist erforderlich.")
451
+ instance = cls()
452
+ instance.robot_name = robot_name
453
+ return instance
454
+
455
+ def start(self) -> None:
456
+ import edu_robot_api
457
+ prepare = getattr(edu_robot_api, "_prepare_workbench_bridge", None)
458
+ if prepare is None:
459
+ raise RuntimeError("WorkbenchBridge ist nur in RoboWorkbench verfügbar.")
460
+ prepare(self.robot_name)
461
+ self._started = True
462
+
463
+ def _connect(self, *, speed: float = 60) -> Robot:
464
+ self._require_ready()
465
+ import edu_robot_api
466
+ self._connection = edu_robot_api.connect_robot(self.robot_name, speed=speed)
467
+ return self._connection
@@ -0,0 +1,12 @@
1
+ """Optional legacy connection hook. Explicit Bridge objects need no discovery."""
2
+ from importlib.metadata import entry_points
3
+
4
+
5
+ def connect_robot(name=None, **options):
6
+ connectors = list(entry_points(group="edu_robot_api.connectors", name="default"))
7
+ if len(connectors) != 1:
8
+ raise RuntimeError(
9
+ "No unambiguous default connection is configured. "
10
+ "Use Robot.connect(bridge=...) with a bridge supplied by your application."
11
+ )
12
+ return connectors[0].load()(name, **options)
edu_robot_api/core.py ADDED
@@ -0,0 +1,219 @@
1
+ """Portable Python API. This same source is also executed by RoboWorkbench.
2
+
3
+ The backend is a dictionary of callables; no transport, device or browser globals
4
+ are exposed to learning programs. Distances are cm, angles degrees, motor power %.
5
+ """
6
+
7
+
8
+ from edu_robot_api.components import CapabilityUnavailable
9
+
10
+
11
+ def percent(value):
12
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
13
+ raise ValueError("Motorleistung muss eine endliche Zahl sein.")
14
+ if value != value or abs(value) == float("inf"):
15
+ raise ValueError("Motorleistung muss eine endliche Zahl sein.")
16
+ return max(-100, min(100, value))
17
+
18
+
19
+ def motor_pair(linear, turn):
20
+ """Positive turn turns right: the left wheels run faster than the right."""
21
+ linear, turn = percent(linear), percent(turn)
22
+ return percent(linear + turn), percent(linear - turn)
23
+
24
+
25
+ class Robot:
26
+ def __init__(self, backend, name="Robot", model="simulation", speed=60):
27
+ self._backend = backend
28
+ self.id = name
29
+ self.model = model
30
+ self.memory = {}
31
+ self._speed = abs(percent(speed))
32
+
33
+ def capabilities(self):
34
+ return self._backend["capabilities"]()
35
+
36
+ def has_sensor(self, name):
37
+ return name in self.capabilities()["sensors"]
38
+
39
+ def supports(self, name):
40
+ capabilities = self.capabilities()
41
+ return name in capabilities["commands"] or name in capabilities["sensors"]
42
+
43
+ def _require(self, name):
44
+ if not self.supports(name):
45
+ raise CapabilityUnavailable("Fähigkeit nicht verfügbar: " + name)
46
+
47
+ def drive(self, linear, turn=0):
48
+ return self._backend["drive"](percent(linear), percent(turn))
49
+
50
+ def forward(self, speed=None):
51
+ return self.drive(self._speed if speed is None else speed, 0)
52
+
53
+ def backward(self, speed=None):
54
+ return self.drive(-abs(self._speed if speed is None else percent(speed)), 0)
55
+
56
+ def turn_left(self, speed=None):
57
+ return self.drive(0, -abs(self._speed if speed is None else percent(speed)))
58
+
59
+ def turn_right(self, speed=None):
60
+ return self.drive(0, abs(self._speed if speed is None else percent(speed)))
61
+
62
+ def stop(self):
63
+ return self._backend["stop"]()
64
+
65
+ def set_motors(self, *values):
66
+ """Individual motor outputs in percent, in the model's motor order."""
67
+ self._require("set_motors")
68
+ if len(values) != self.capabilities()["motor_count"]:
69
+ raise ValueError("Anzahl der Motorwerte passt nicht zum Modell.")
70
+ return self._backend["set_motors"](*(percent(value) for value in values))
71
+
72
+ def speed(self):
73
+ return self._speed
74
+
75
+ def set_speed(self, speed):
76
+ self._speed = abs(percent(speed))
77
+
78
+ def update_sensors(self):
79
+ """Refresh once, then read a consistent snapshot using read_sensor()."""
80
+ return self._backend["update_sensors"]()
81
+
82
+ def sensors(self):
83
+ return self._backend["sensors"]()
84
+
85
+ def read_sensor(self, name):
86
+ if not self.has_sensor(name):
87
+ raise CapabilityUnavailable("Sensor nicht verfügbar: " + name)
88
+ return self.sensors().get(name)
89
+
90
+ def distance_front(self):
91
+ return self.read_sensor("distance_front")
92
+
93
+ def distance_left(self):
94
+ return self.read_sensor("distance_left")
95
+
96
+ def distance_right(self):
97
+ return self.read_sensor("distance_right")
98
+
99
+ def line_left(self):
100
+ return self.read_sensor("line_left")
101
+
102
+ def line_right(self):
103
+ return self.read_sensor("line_right")
104
+
105
+ def bumper_left(self):
106
+ return self.read_sensor("bumper_left")
107
+
108
+ def bumper_right(self):
109
+ return self.read_sensor("bumper_right")
110
+
111
+ def obstacle_ahead(self, threshold_cm=30):
112
+ if isinstance(threshold_cm, bool) or not isinstance(threshold_cm, (int, float)) or not 0 <= threshold_cm < float("inf"):
113
+ raise ValueError("Abstand muss eine endliche, nicht negative Zahl sein.")
114
+ value = self.distance_front()
115
+ return None if value is None else value < threshold_cm
116
+
117
+ def set_rgb(self, index, red, green, blue):
118
+ self._require("rgb_led")
119
+ for value in (red, green, blue):
120
+ if isinstance(value, bool) or not isinstance(value, int) or not 0 <= value <= 255:
121
+ raise ValueError("RGB-Werte müssen ganze Zahlen von 0 bis 255 sein.")
122
+ return self._backend["rgb_led"](index, red, green, blue)
123
+
124
+ def camera_frame(self):
125
+ self._require("camera")
126
+ return self._backend["camera"]()
127
+
128
+ def camera_image(self):
129
+ """Full-resolution image, using the same portable RGB format as camera_frame."""
130
+ self._require("camera_image")
131
+ return self._backend["camera_image"]()
132
+
133
+ def start_camera(self):
134
+ self._require("start_camera")
135
+ return self._backend["start_camera"]()
136
+
137
+ def stop_camera(self):
138
+ self._require("stop_camera")
139
+ return self._backend["stop_camera"]()
140
+
141
+ def set_rgb_mode(self, mode):
142
+ self._require("rgb_mode")
143
+ if isinstance(mode, bool) or not isinstance(mode, int) or not 0 <= mode <= 5:
144
+ raise ValueError("LED-Modus muss eine ganze Zahl von 0 bis 5 sein.")
145
+ return self._backend["rgb_mode"](mode)
146
+
147
+ def set_matrix_mode(self, mode):
148
+ self._require("matrix_mode")
149
+ if isinstance(mode, bool) or not isinstance(mode, int) or not 0 <= mode <= 3:
150
+ raise ValueError("Matrix-Modus muss eine ganze Zahl von 0 bis 3 sein.")
151
+ return self._backend["matrix_mode"](mode)
152
+
153
+ def set_camera_orientation(self, pan, tilt):
154
+ self._require("camera_orientation")
155
+ for value in (pan, tilt):
156
+ if isinstance(value, bool) or not isinstance(value, (int, float)) or not 0 <= value <= 180:
157
+ raise ValueError("Servowinkel muss zwischen 0 und 180 Grad liegen.")
158
+ return self._backend["camera_orientation"](pan, tilt)
159
+
160
+ def buzzer(self, enabled=True, frequency=2000):
161
+ self._require("buzzer")
162
+ if not isinstance(enabled, bool) or isinstance(frequency, bool) or not isinstance(frequency, int) or not 20 <= frequency <= 20000:
163
+ raise ValueError("Summer: bool und Frequenz von 20 bis 20000 Hz erwartet.")
164
+ return self._backend["buzzer"](enabled, frequency)
165
+
166
+ def time(self):
167
+ return self._backend["time"]()
168
+
169
+ def log(self, message):
170
+ return self._backend["log"](str(message))
171
+
172
+ def close(self):
173
+ try:
174
+ self.stop()
175
+ finally:
176
+ self._backend["close"]()
177
+
178
+ def __enter__(self):
179
+ return self
180
+
181
+ def __exit__(self, exc_type, exc_value, traceback):
182
+ self.close()
183
+
184
+ # Explicit simulation capabilities: these are never claimed by real hardware.
185
+ def position(self):
186
+ self._require("position")
187
+ return self._backend["position"]()
188
+
189
+ def ball_position(self):
190
+ self._require("ball_position")
191
+ return self._backend["ball_position"]()
192
+
193
+ def opponent_position(self):
194
+ self._require("opponent_position")
195
+ return self._backend["opponent_position"]()
196
+
197
+ def goal_position(self):
198
+ self._require("goal_position")
199
+ return self._backend["goal_position"]()
200
+
201
+ def ball_distance(self):
202
+ self._require("ball_distance")
203
+ return self._backend["ball_distance"]()
204
+
205
+ def ball_angle(self):
206
+ self._require("ball_angle")
207
+ return self._backend["ball_angle"]()
208
+
209
+ def kick(self, power=75):
210
+ self._require("kick")
211
+ return self._backend["kick"](max(0, percent(power)))
212
+
213
+ def kickoff_wait(self):
214
+ self._require("kickoff_wait")
215
+ return self._backend["kickoff_wait"]()
216
+
217
+ def kickoff_time(self):
218
+ self._require("kickoff_time")
219
+ return self._backend["kickoff_time"]()
@@ -0,0 +1,21 @@
1
+ """Optional native image helpers; the public camera data remains portable RGB."""
2
+
3
+ def camera_rgb(robot):
4
+ """Full camera image as a portable RGB dictionary (width, height, pixels).
5
+
6
+ The same learner call works in CPython and the browser. NumPy is not needed.
7
+ """
8
+ return robot.sensors()["camera"].read() if hasattr(robot, "read_sensors") else robot.camera_image()
9
+
10
+
11
+ def rgb_array(image):
12
+ import numpy as np
13
+ if image is None:
14
+ return None
15
+ pixels = np.asarray(image["pixels"], dtype=np.uint32).reshape(image["height"], image["width"])
16
+ return np.stack(((pixels >> 16) & 255, (pixels >> 8) & 255, pixels & 255), axis=-1).astype(np.uint8)
17
+
18
+
19
+ def camera_bgr(robot):
20
+ image = rgb_array(camera_rgb(robot))
21
+ return None if image is None else image[:, :, ::-1].copy()
edu_robot_api/py.typed ADDED
File without changes
@@ -0,0 +1,106 @@
1
+ Metadata-Version: 2.4
2
+ Name: edu_robot_api
3
+ Version: 0.6.0
4
+ Summary: A typed Python robot API for education, independent of hardware and transport
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Documentation, https://github.com/henningmattes/edu_robot_api#readme
7
+ Project-URL: Repository, https://github.com/henningmattes/edu_robot_api
8
+ Project-URL: Issues, https://github.com/henningmattes/edu_robot_api/issues
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Typing :: Typed
11
+ Classifier: Intended Audience :: Education
12
+ Classifier: Topic :: Education
13
+ Requires-Python: >=3.11
14
+ Description-Content-Type: text/markdown
15
+ License-File: LICENSE
16
+ Provides-Extra: images
17
+ Requires-Dist: numpy; extra == "images"
18
+ Requires-Dist: pillow; extra == "images"
19
+ Dynamic: license-file
20
+
21
+ # edu_robot_api
22
+
23
+ A small, typed Python API for educational robotics. It represents robots,
24
+ sensors and actuators as Python objects and provides a consistent interface
25
+ for reading measurements and issuing movement commands.
26
+
27
+ RoboWorkbench uses the API for independent virtual learning robots. Their
28
+ behavior is defined by the learning environment. Available components,
29
+ measurements and motion depend on the selected model and world.
30
+
31
+ ## Installation
32
+
33
+ Requires Python 3.11 or later. Install from PyPI with pip:
34
+
35
+ ```sh
36
+ python -m pip install edu_robot_api
37
+ ```
38
+
39
+ Alternatively, install a downloaded wheel:
40
+
41
+ ```sh
42
+ python -m pip install edu_robot_api-0.6.0-py3-none-any.whl
43
+ ```
44
+
45
+ In the RoboWorkbench web app, no local installation is needed.
46
+
47
+ ## Documentation
48
+
49
+ See the [user guide and API overview](https://github.com/henningmattes/edu_robot_api#readme)
50
+ for examples and the class diagram. The
51
+ [source repository](https://github.com/henningmattes/edu_robot_api)
52
+ also provides the library source code.
53
+
54
+ ## Programming in RoboWorkbench
55
+
56
+ The web app provides the connected robot for the current editor as `rob`.
57
+ Each robot program controls its own robot. The environment stops the robot
58
+ and releases the connection when the program finishes, fails or is aborted.
59
+
60
+ ```python
61
+ import time
62
+
63
+
64
+ def program(robot):
65
+ sensor = robot.sensors()["distance_front"]
66
+ while True:
67
+ distance = sensor.read()
68
+ if distance is None or distance < 25:
69
+ robot.stop()
70
+ else:
71
+ robot.forward(30)
72
+ time.sleep(0.03)
73
+
74
+
75
+ program(rob)
76
+ ```
77
+
78
+ This example requires a front distance sensor. In a standalone Python
79
+ application, the application must supply the robot object and its backend;
80
+ installing the API alone does not create a robot or a running simulation.
81
+
82
+ ## Components and readings
83
+
84
+ `robot.sensors()` and `robot.actuators()` return dictionaries of component
85
+ objects. Use `sensor.read()` for an individual reading or
86
+ `robot.read_sensors()` for a snapshot. Snapshot values can be selected by
87
+ sensor object, captured name or position in the selection.
88
+
89
+ ```python
90
+ left = rob.sensors()["line_left"]
91
+ right = rob.sensors()["line_right"]
92
+ values = rob.read_sensors([left, right])
93
+ print(values[left], values[right])
94
+ ```
95
+
96
+ The package exports `Robot`, `Sensor`, `Actuator`, typed component classes,
97
+ `SensorReadings`, `Bridge`, `Backend` and `FunctionBackend`. Python applications
98
+ can implement the backend contract to provide measurements and execute commands.
99
+
100
+ Motor power is expressed as a percentage, distance in centimeters and angles
101
+ in degrees. Motor power is not a guaranteed speed. `None` indicates an unavailable
102
+ measurement; missing capabilities and connection failures can raise exceptions.
103
+
104
+ ## License
105
+
106
+ The library is licensed under the Apache License, Version 2.0. See LICENSE.
@@ -0,0 +1,11 @@
1
+ edu_robot_api/__init__.py,sha256=oo3YjmHUclU_DoAg5M5pMQHUT0kbm7aHM-O6UBVPzh0,1112
2
+ edu_robot_api/components.py,sha256=-lKMdeUKXgBfQzKwwsl5rz6CSKZ3Je29FhS8Aqa9-K0,19634
3
+ edu_robot_api/connection.py,sha256=x5Lw0kZD9eRuWgfngVa1D777cygT4xgAXDAQvFsIaQQ,535
4
+ edu_robot_api/core.py,sha256=W6R12l_Av-Rgfge09d-KX24evBUEVFkfjTSb4BfxHmM,7744
5
+ edu_robot_api/imaging.py,sha256=NBXeperorZV6KWG_bth-5WrlMNSTIVvXs5rRZIm_6uE,801
6
+ edu_robot_api/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
7
+ edu_robot_api-0.6.0.dist-info/licenses/LICENSE,sha256=Pd-b5cKP4n2tFDpdx27qJSIq0d1ok0oEcGTlbtL6QMU,11560
8
+ edu_robot_api-0.6.0.dist-info/METADATA,sha256=0rQIQqjrpOseADrYinSuLWTjfQt4chzDoUF7wjJdCeE,3671
9
+ edu_robot_api-0.6.0.dist-info/WHEEL,sha256=aeYiig01lYGDzBgS8HxWXOg3uV61G9ijOsup-k9o1sk,91
10
+ edu_robot_api-0.6.0.dist-info/top_level.txt,sha256=JpDu0udUdXMJYeVepD4WWC7hbjcNEQg48iN0rC9xjkQ,14
11
+ edu_robot_api-0.6.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (82.0.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1 @@
1
+ edu_robot_api