metacar-multiagent 0.1.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,80 @@
1
+ """MetaCar 多车协同扩展接口。"""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from metacar import (
6
+ BorderInfo,
7
+ DrivingType,
8
+ GearMode,
9
+ LaneInfo,
10
+ LineType,
11
+ ObstacleInfo,
12
+ ObstacleType,
13
+ PoseGnss,
14
+ RoadInfo,
15
+ TrafficSignType,
16
+ Vector2,
17
+ Vector3,
18
+ VehicleControl,
19
+ )
20
+
21
+ from .api import (
22
+ ScenarioAPIError,
23
+ ScenarioCommandError,
24
+ ScenarioConnectionError,
25
+ ScenarioProtocolError,
26
+ ScenarioTaskAPI,
27
+ )
28
+ from .build_info import SDK_BUILD_ID, SDK_CONTRACT
29
+ from .models import (
30
+ MultiVehicleSceneStaticData,
31
+ ScenarioEvent,
32
+ ScenarioInteractionResult,
33
+ ScenarioObservation,
34
+ ScenarioObservedTaskObject,
35
+ ScenarioSharedTaskObject,
36
+ ScenarioTaskDefinition,
37
+ ScenarioTaskObjective,
38
+ ScenarioTaskState,
39
+ ScenarioUncertaintyRegion,
40
+ ScenarioVehicleInfo,
41
+ ScenarioVehicleState,
42
+ StaticObjectInfo,
43
+ )
44
+
45
+ __all__ = [
46
+ "__version__",
47
+ "SDK_BUILD_ID",
48
+ "SDK_CONTRACT",
49
+ "ScenarioTaskAPI",
50
+ "ScenarioAPIError",
51
+ "ScenarioConnectionError",
52
+ "ScenarioProtocolError",
53
+ "ScenarioCommandError",
54
+ "MultiVehicleSceneStaticData",
55
+ "ScenarioVehicleInfo",
56
+ "StaticObjectInfo",
57
+ "ScenarioTaskDefinition",
58
+ "ScenarioTaskObjective",
59
+ "ScenarioSharedTaskObject",
60
+ "ScenarioUncertaintyRegion",
61
+ "ScenarioTaskState",
62
+ "ScenarioVehicleState",
63
+ "ScenarioObservation",
64
+ "ScenarioObservedTaskObject",
65
+ "ScenarioInteractionResult",
66
+ "ScenarioEvent",
67
+ "VehicleControl",
68
+ "GearMode",
69
+ "PoseGnss",
70
+ "RoadInfo",
71
+ "LaneInfo",
72
+ "BorderInfo",
73
+ "LineType",
74
+ "DrivingType",
75
+ "TrafficSignType",
76
+ "ObstacleInfo",
77
+ "ObstacleType",
78
+ "Vector2",
79
+ "Vector3",
80
+ ]
@@ -0,0 +1,602 @@
1
+ """面向多车任务场景的正式 Python 客户端。"""
2
+
3
+ import json
4
+ from pathlib import Path
5
+ import socket
6
+ from threading import Lock
7
+ from typing import Any, Iterable, Mapping
8
+
9
+ from metacar import (
10
+ GearMode,
11
+ ObstacleInfo,
12
+ ObstacleType,
13
+ PoseGnss,
14
+ RoadInfo,
15
+ Vector3,
16
+ VehicleControl,
17
+ )
18
+ from pydantic import TypeAdapter, ValidationError
19
+
20
+ from .models import (
21
+ JsonObject,
22
+ MultiVehicleSceneStaticData,
23
+ ScenarioEvent,
24
+ ScenarioInteractionResult,
25
+ ScenarioObservation,
26
+ ScenarioObservedTaskObject,
27
+ ScenarioTaskDefinition,
28
+ ScenarioTaskState,
29
+ ScenarioVehicleInfo,
30
+ ScenarioVehicleState,
31
+ StaticObjectInfo,
32
+ )
33
+
34
+
35
+ class ScenarioAPIError(RuntimeError):
36
+ """多车任务 API 错误基类。"""
37
+
38
+
39
+ class ScenarioConnectionError(ScenarioAPIError):
40
+ """连接建立、连接断开或网络传输失败。"""
41
+
42
+
43
+ class ScenarioProtocolError(ScenarioAPIError):
44
+ """Player 返回无效 JSON 或不符合公开模型的数据。"""
45
+
46
+
47
+ class ScenarioCommandError(ScenarioAPIError):
48
+ """Player 拒绝执行公开命令。"""
49
+
50
+
51
+ class ScenarioTaskAPI:
52
+ """通过换行分隔 JSON 协议连接多车任务 Player。"""
53
+
54
+ ALLOWED_ACTIONS = (
55
+ "submit_key",
56
+ "report_observation",
57
+ "scan",
58
+ "request_entry",
59
+ "release",
60
+ "deliver",
61
+ )
62
+
63
+ def __init__(
64
+ self,
65
+ host: str = "127.0.0.1",
66
+ port: int = 9100,
67
+ timeout: float = 3.0,
68
+ ) -> None:
69
+ self.host = host
70
+ self.port = port
71
+ self.timeout = timeout
72
+ self._connection: socket.socket | None = None
73
+ self._response_stream: Any = None
74
+ self._request_lock = Lock()
75
+
76
+ def __enter__(self) -> "ScenarioTaskAPI":
77
+ return self.connect()
78
+
79
+ def __exit__(self, exc_type, exc_value, traceback) -> None:
80
+ self.close()
81
+
82
+ def connect(self) -> "ScenarioTaskAPI":
83
+ if self._connection is not None:
84
+ return self
85
+ try:
86
+ self._connection = socket.create_connection(
87
+ (self.host, self.port), timeout=self.timeout
88
+ )
89
+ self._response_stream = self._connection.makefile(
90
+ "r", encoding="utf-8"
91
+ )
92
+ except OSError as error:
93
+ self.close()
94
+ raise ScenarioConnectionError(
95
+ f"无法连接 MetaCar 多车任务服务 {self.host}:{self.port}:{error}"
96
+ ) from error
97
+ return self
98
+
99
+ def close(self) -> None:
100
+ if self._response_stream is not None:
101
+ try:
102
+ self._response_stream.close()
103
+ finally:
104
+ self._response_stream = None
105
+ if self._connection is not None:
106
+ try:
107
+ self._connection.close()
108
+ finally:
109
+ self._connection = None
110
+
111
+ def get_scene_static_data(self) -> MultiVehicleSceneStaticData:
112
+ response = self._request({"command": "get_scene_static_data"})
113
+ static_payload = self._mapping(response, "scene_static_data")
114
+ roads = self._load_roads(response, static_payload)
115
+ return self._validate(
116
+ MultiVehicleSceneStaticData,
117
+ {
118
+ "coordinate_system": self._required_non_empty_string(
119
+ static_payload,
120
+ "coordinate_system",
121
+ "静态数据坐标系",
122
+ ),
123
+ "roads": roads,
124
+ "vehicles": self._required(
125
+ static_payload,
126
+ "vehicles",
127
+ "静态数据任务车辆列表",
128
+ ),
129
+ "static_objects": self._required(
130
+ static_payload,
131
+ "static_objects",
132
+ "静态数据固定布景列表",
133
+ ),
134
+ },
135
+ "静态场景数据",
136
+ )
137
+
138
+ def get_task(self) -> ScenarioTaskDefinition:
139
+ response = self._request({"command": "get_task"})
140
+ payload = dict(self._mapping(response, "task"))
141
+ payload["allowed_actions"] = list(self.ALLOWED_ACTIONS)
142
+ return self._validate(ScenarioTaskDefinition, payload, "任务定义")
143
+
144
+ def get_task_state(self) -> ScenarioTaskState:
145
+ response = self._request({"command": "get_task_state"})
146
+ return self._validate(
147
+ ScenarioTaskState,
148
+ self._mapping(response, "task_state"),
149
+ "任务状态",
150
+ )
151
+
152
+ def get_vehicle_ids(self) -> list[str]:
153
+ response = self._request({"command": "get_vehicles"})
154
+ vehicle_ids = response.get("vehicle_ids", [])
155
+ if not isinstance(vehicle_ids, list) or not all(
156
+ isinstance(vehicle_id, str) for vehicle_id in vehicle_ids
157
+ ):
158
+ raise ScenarioProtocolError("车辆标识列表格式无效。")
159
+ return vehicle_ids
160
+
161
+ def get_vehicle_state(self, vehicle_id: str) -> ScenarioVehicleState:
162
+ self._require_id(vehicle_id, "vehicle_id")
163
+ response = self._request(
164
+ {"command": "get_vehicle_state", "vehicle_id": vehicle_id}
165
+ )
166
+ return self._vehicle_state(self._mapping(response, "vehicle_state"))
167
+
168
+ def get_vehicle_states(self) -> list[ScenarioVehicleState]:
169
+ response = self._request({"command": "get_all_vehicle_states"})
170
+ payload = self._required(response, "vehicle_states", "多车状态列表")
171
+ if not isinstance(payload, list):
172
+ raise ScenarioProtocolError("多车状态列表格式无效。")
173
+ return [
174
+ self._vehicle_state(self._as_mapping(item, "车辆状态"))
175
+ for item in payload
176
+ ]
177
+
178
+ def set_vehicle_control(
179
+ self,
180
+ vehicle_id: str,
181
+ control: VehicleControl,
182
+ ) -> None:
183
+ self._require_id(vehicle_id, "vehicle_id")
184
+ self._request(
185
+ {
186
+ "command": "set_vehicle_control",
187
+ "vehicle_id": vehicle_id,
188
+ "vehicle_control": self._control_payload(control),
189
+ }
190
+ )
191
+
192
+ def set_vehicle_controls(
193
+ self,
194
+ controls: Mapping[str, VehicleControl],
195
+ ) -> list[str]:
196
+ if not controls:
197
+ raise ValueError("controls 不能为空。")
198
+ payload = []
199
+ for vehicle_id, control in controls.items():
200
+ self._require_id(vehicle_id, "vehicle_id")
201
+ payload.append(
202
+ {
203
+ "vehicle_id": vehicle_id,
204
+ "vehicle_control": self._control_payload(control),
205
+ }
206
+ )
207
+ response = self._request(
208
+ {"command": "set_vehicle_controls", "vehicle_controls": payload}
209
+ )
210
+ vehicle_ids = response.get("vehicle_ids", list(controls))
211
+ if not isinstance(vehicle_ids, list):
212
+ raise ScenarioProtocolError("批量控制响应中的车辆标识格式无效。")
213
+ return [str(vehicle_id) for vehicle_id in vehicle_ids]
214
+
215
+ def stop_vehicles(self, vehicle_ids: Iterable[str]) -> list[str]:
216
+ controls = {
217
+ vehicle_id: VehicleControl(brake=1.0, gear=GearMode.PARKING)
218
+ for vehicle_id in vehicle_ids
219
+ }
220
+ if not controls:
221
+ raise ValueError("vehicle_ids 不能为空。")
222
+ return self.set_vehicle_controls(controls)
223
+
224
+ def get_observation(self, vehicle_id: str) -> ScenarioObservation:
225
+ self._require_id(vehicle_id, "vehicle_id")
226
+ response = self._request(
227
+ {"command": "get_observation", "vehicle_id": vehicle_id}
228
+ )
229
+ payload = dict(self._mapping(response, "observation"))
230
+ visible_payload = payload.get("visible_objects", [])
231
+ if not isinstance(visible_payload, list):
232
+ raise ScenarioProtocolError("可见对象列表格式无效。")
233
+ visible_objects = [
234
+ self._validate(
235
+ ScenarioObservedTaskObject,
236
+ self._as_mapping(item, "可见对象"),
237
+ "可见对象",
238
+ )
239
+ for item in visible_payload
240
+ ]
241
+ payload["visible_objects"] = visible_objects
242
+ payload["obstacles"] = [
243
+ self._obstacle_info(item)
244
+ for item in visible_objects
245
+ if item.numeric_id > 0 and item.position is not None
246
+ ]
247
+ return self._validate(ScenarioObservation, payload, "车辆观测")
248
+
249
+ def interact(
250
+ self,
251
+ vehicle_id: str,
252
+ object_id: str,
253
+ action: str,
254
+ payload: str | Mapping[str, Any] | None = None,
255
+ ) -> ScenarioInteractionResult:
256
+ self._require_id(vehicle_id, "vehicle_id")
257
+ self._require_id(object_id, "object_id")
258
+ if action not in self.ALLOWED_ACTIONS:
259
+ raise ValueError(f"不允许的任务动作:{action}")
260
+ encoded_payload = self._interaction_payload(action, payload)
261
+ response = self._request(
262
+ {
263
+ "command": "interact",
264
+ "vehicle_id": vehicle_id,
265
+ "object_id": object_id,
266
+ "action": action,
267
+ "payload": encoded_payload,
268
+ }
269
+ )
270
+ return self._validate(
271
+ ScenarioInteractionResult,
272
+ {
273
+ "message": response.get("message", ""),
274
+ "vehicle_id": response.get("vehicle_id", vehicle_id),
275
+ "object_id": response.get("object_id", object_id),
276
+ "object_state": response.get("object_state", ""),
277
+ "granted": response.get("granted", False),
278
+ },
279
+ "交互结果",
280
+ )
281
+
282
+ @staticmethod
283
+ def _interaction_payload(
284
+ action: str,
285
+ payload: str | Mapping[str, Any] | None,
286
+ ) -> str:
287
+ if payload is None:
288
+ return ""
289
+ if isinstance(payload, str):
290
+ return payload
291
+ if not isinstance(payload, Mapping):
292
+ raise TypeError("payload 必须是字符串、字典或 None。")
293
+ field_name = {
294
+ "report_observation": "observation_token",
295
+ "submit_key": "key",
296
+ }.get(action)
297
+ if field_name is None:
298
+ raise ValueError(f"动作 {action} 不接受字典 payload。")
299
+ value = payload.get(field_name)
300
+ if not isinstance(value, str) or not value.strip():
301
+ raise ValueError(
302
+ f"{action} 的字典 payload 必须包含非空 {field_name}。"
303
+ )
304
+ return value
305
+
306
+ def get_events(self, after_sequence: int = 0) -> list[ScenarioEvent]:
307
+ response = self._request(
308
+ {"command": "get_events", "after_sequence": max(0, after_sequence)}
309
+ )
310
+ return self._validate(
311
+ list[ScenarioEvent], response.get("events", []), "任务事件"
312
+ )
313
+
314
+ def _request(self, command: Mapping[str, Any]) -> JsonObject:
315
+ self.connect()
316
+ encoded = (json.dumps(command, ensure_ascii=False) + "\n").encode("utf-8")
317
+ with self._request_lock:
318
+ try:
319
+ assert self._connection is not None
320
+ assert self._response_stream is not None
321
+ self._connection.sendall(encoded)
322
+ response_line = self._response_stream.readline()
323
+ except (OSError, ValueError) as error:
324
+ self.close()
325
+ raise ScenarioConnectionError(
326
+ f"多车任务服务通信失败:{error}"
327
+ ) from error
328
+ if not response_line:
329
+ self.close()
330
+ raise ScenarioConnectionError("多车任务服务已断开,未返回响应。")
331
+ try:
332
+ response = json.loads(response_line)
333
+ except json.JSONDecodeError as error:
334
+ raise ScenarioProtocolError(
335
+ "多车任务服务返回了无效 JSON。"
336
+ ) from error
337
+ if not isinstance(response, dict):
338
+ raise ScenarioProtocolError("多车任务服务响应必须是 JSON 对象。")
339
+ if not response.get("ok"):
340
+ raise ScenarioCommandError(
341
+ str(response.get("message", "命令执行失败。"))
342
+ )
343
+ return response
344
+
345
+ @staticmethod
346
+ def _load_roads(
347
+ response: JsonObject,
348
+ static_payload: Mapping[str, Any],
349
+ ) -> list[RoadInfo]:
350
+ if "roads" in static_payload:
351
+ return ScenarioTaskAPI._validate(
352
+ list[RoadInfo],
353
+ static_payload["roads"],
354
+ "静态道路数据",
355
+ )
356
+ map_path_value = response.get("map_path") or static_payload.get("map_path")
357
+ if not isinstance(map_path_value, str) or not map_path_value:
358
+ raise ScenarioProtocolError("静态数据响应缺少 roads 或 map_path。")
359
+ map_path = Path(map_path_value)
360
+ try:
361
+ return TypeAdapter(list[RoadInfo]).validate_json(map_path.read_bytes())
362
+ except (OSError, ValidationError) as error:
363
+ raise ScenarioProtocolError(
364
+ f"无法读取正式道路数据 {map_path}:{error}"
365
+ ) from error
366
+
367
+ @staticmethod
368
+ def _vehicle_state(payload: Mapping[str, Any]) -> ScenarioVehicleState:
369
+ position = ScenarioTaskAPI._vector(
370
+ ScenarioTaskAPI._required(payload, "position", "车辆位置"),
371
+ "车辆位置",
372
+ )
373
+ orientation = ScenarioTaskAPI._vector(
374
+ ScenarioTaskAPI._required(payload, "orientation", "车辆姿态"),
375
+ "车辆姿态",
376
+ )
377
+ velocity = ScenarioTaskAPI._vector(
378
+ ScenarioTaskAPI._required(payload, "velocity", "车辆速度"),
379
+ "车辆速度",
380
+ )
381
+ pose = PoseGnss.model_validate(
382
+ {
383
+ "posX": position.x,
384
+ "posY": position.y,
385
+ "posZ": position.z,
386
+ "velX": velocity.x,
387
+ "velY": velocity.y,
388
+ "velZ": velocity.z,
389
+ "oriX": orientation.x,
390
+ "oriY": orientation.y,
391
+ "oriZ": orientation.z,
392
+ }
393
+ )
394
+ return ScenarioTaskAPI._validate(
395
+ ScenarioVehicleState,
396
+ {
397
+ "vehicle_id": ScenarioTaskAPI._required_non_empty_string(
398
+ payload,
399
+ "vehicle_id",
400
+ "车辆标识",
401
+ ),
402
+ "state": ScenarioTaskAPI._required_non_empty_string(
403
+ payload,
404
+ "state",
405
+ "车辆运行状态",
406
+ ),
407
+ "pose": pose,
408
+ "speed_mps": ScenarioTaskAPI._required_number(
409
+ payload,
410
+ "speed_mps",
411
+ "车辆纵向速度",
412
+ ),
413
+ "control": ScenarioTaskAPI._control_from_payload(
414
+ ScenarioTaskAPI._as_mapping(
415
+ ScenarioTaskAPI._required(
416
+ payload,
417
+ "vehicle_control",
418
+ "车辆控制状态",
419
+ ),
420
+ "车辆控制状态",
421
+ )
422
+ ),
423
+ },
424
+ "车辆状态",
425
+ )
426
+
427
+ @staticmethod
428
+ def _control_payload(control: VehicleControl) -> JsonObject:
429
+ if not isinstance(control, VehicleControl):
430
+ raise TypeError("control 必须是 metacar.VehicleControl。")
431
+ return {
432
+ "throttle": control.throttle,
433
+ "brake": control.brake,
434
+ "steering": control.steering,
435
+ "gear": control.gear.value,
436
+ "front_light": control.headlights_on,
437
+ "left_blinker": control.left_blinker_on,
438
+ "right_blinker": control.right_blinker_on,
439
+ "double_flash": control.hazard_lights_on,
440
+ }
441
+
442
+ @staticmethod
443
+ def _control_from_payload(payload: Mapping[str, Any]) -> VehicleControl:
444
+ gear_value = ScenarioTaskAPI._required_integer(
445
+ payload,
446
+ "gear",
447
+ "车辆挡位",
448
+ )
449
+ try:
450
+ gear = GearMode(gear_value)
451
+ except ValueError as error:
452
+ raise ScenarioProtocolError("车辆挡位格式无效。") from error
453
+ return VehicleControl(
454
+ throttle=ScenarioTaskAPI._required_number(
455
+ payload, "throttle", "车辆油门"
456
+ ),
457
+ brake=ScenarioTaskAPI._required_number(
458
+ payload, "brake", "车辆制动"
459
+ ),
460
+ steering=ScenarioTaskAPI._required_number(
461
+ payload, "steering", "车辆转向"
462
+ ),
463
+ gear=gear,
464
+ left_blinker_on=ScenarioTaskAPI._required_boolean_alias(
465
+ payload,
466
+ "left_blinker",
467
+ "Signal_Light_LeftBlinker",
468
+ "车辆左转向灯",
469
+ ),
470
+ right_blinker_on=ScenarioTaskAPI._required_boolean_alias(
471
+ payload,
472
+ "right_blinker",
473
+ "Signal_Light_RightBlinker",
474
+ "车辆右转向灯",
475
+ ),
476
+ hazard_lights_on=ScenarioTaskAPI._required_boolean_alias(
477
+ payload,
478
+ "double_flash",
479
+ "Signal_Light_DoubleFlash",
480
+ "车辆双闪灯",
481
+ ),
482
+ headlights_on=ScenarioTaskAPI._required_boolean_alias(
483
+ payload,
484
+ "front_light",
485
+ "Signal_Light_FrontLight",
486
+ "车辆前灯",
487
+ ),
488
+ )
489
+
490
+ @staticmethod
491
+ def _obstacle_info(item: ScenarioObservedTaskObject) -> ObstacleInfo:
492
+ assert item.position is not None
493
+ orientation = item.orientation or Vector3(0.0, 0.0, 0.0)
494
+ velocity = item.velocity or Vector3(0.0, 0.0, 0.0)
495
+ return ObstacleInfo.model_validate(
496
+ {
497
+ "id": item.numeric_id,
498
+ "type": ObstacleType.STATIC.value,
499
+ "posX": item.position.x,
500
+ "posY": item.position.y,
501
+ "posZ": item.position.z,
502
+ "velX": velocity.x,
503
+ "velY": velocity.y,
504
+ "velZ": velocity.z,
505
+ "oriX": orientation.x,
506
+ "oriY": orientation.y,
507
+ "oriZ": orientation.z,
508
+ "length": item.length_m,
509
+ "width": item.width_m,
510
+ "height": item.height_m,
511
+ "RedundantValue": None,
512
+ }
513
+ )
514
+
515
+ @staticmethod
516
+ def _vector(value: Any, label: str) -> Vector3:
517
+ try:
518
+ return TypeAdapter(Vector3).validate_python(value)
519
+ except ValidationError as error:
520
+ raise ScenarioProtocolError(f"{label}格式无效:{error}") from error
521
+
522
+ @staticmethod
523
+ def _validate(type_: Any, value: Any, label: str):
524
+ try:
525
+ return TypeAdapter(type_).validate_python(value)
526
+ except ValidationError as error:
527
+ raise ScenarioProtocolError(f"{label}格式无效:{error}") from error
528
+
529
+ @staticmethod
530
+ def _mapping(container: Mapping[str, Any], key: str) -> Mapping[str, Any]:
531
+ return ScenarioTaskAPI._as_mapping(container.get(key), key)
532
+
533
+ @staticmethod
534
+ def _as_mapping(value: Any, label: str) -> Mapping[str, Any]:
535
+ if not isinstance(value, Mapping):
536
+ raise ScenarioProtocolError(f"{label}必须是 JSON 对象。")
537
+ return value
538
+
539
+ @staticmethod
540
+ def _required(
541
+ container: Mapping[str, Any],
542
+ key: str,
543
+ label: str,
544
+ ) -> Any:
545
+ if key not in container:
546
+ raise ScenarioProtocolError(f"响应缺少{label}。")
547
+ return container[key]
548
+
549
+ @staticmethod
550
+ def _required_non_empty_string(
551
+ container: Mapping[str, Any],
552
+ key: str,
553
+ label: str,
554
+ ) -> str:
555
+ value = ScenarioTaskAPI._required(container, key, label)
556
+ if not isinstance(value, str) or not value.strip():
557
+ raise ScenarioProtocolError(f"{label}必须是非空字符串。")
558
+ return value
559
+
560
+ @staticmethod
561
+ def _required_number(
562
+ container: Mapping[str, Any],
563
+ key: str,
564
+ label: str,
565
+ ) -> float:
566
+ value = ScenarioTaskAPI._required(container, key, label)
567
+ if isinstance(value, bool) or not isinstance(value, (int, float)):
568
+ raise ScenarioProtocolError(f"{label}必须是数值。")
569
+ return float(value)
570
+
571
+ @staticmethod
572
+ def _required_integer(
573
+ container: Mapping[str, Any],
574
+ key: str,
575
+ label: str,
576
+ ) -> int:
577
+ value = ScenarioTaskAPI._required(container, key, label)
578
+ if isinstance(value, bool) or not isinstance(value, int):
579
+ raise ScenarioProtocolError(f"{label}必须是整数。")
580
+ return value
581
+
582
+ @staticmethod
583
+ def _required_boolean_alias(
584
+ container: Mapping[str, Any],
585
+ key: str,
586
+ legacy_key: str,
587
+ label: str,
588
+ ) -> bool:
589
+ if key in container:
590
+ value = container[key]
591
+ elif legacy_key in container:
592
+ value = container[legacy_key]
593
+ else:
594
+ raise ScenarioProtocolError(f"响应缺少{label}。")
595
+ if not isinstance(value, bool):
596
+ raise ScenarioProtocolError(f"{label}必须是布尔值。")
597
+ return value
598
+
599
+ @staticmethod
600
+ def _require_id(value: str, label: str) -> None:
601
+ if not isinstance(value, str) or not value.strip():
602
+ raise ValueError(f"{label} 不能为空。")
@@ -0,0 +1,4 @@
1
+ """扩展包构建身份。"""
2
+
3
+ SDK_BUILD_ID = "simcar.portfog.multiagent.1"
4
+ SDK_CONTRACT = "R-A1B-API-01"
@@ -0,0 +1,183 @@
1
+ """多车任务场景的公开数据模型。"""
2
+
3
+ from typing import Any
4
+
5
+ from metacar import (
6
+ ObstacleInfo,
7
+ PoseGnss,
8
+ RoadInfo,
9
+ Vector3,
10
+ VehicleControl,
11
+ )
12
+ from pydantic import BaseModel, ConfigDict, Field
13
+
14
+
15
+ class ScenarioModel(BaseModel):
16
+ """忽略 Player 的向后兼容附加字段,只暴露正式模型字段。"""
17
+
18
+ model_config = ConfigDict(extra="ignore")
19
+
20
+
21
+ class ScenarioVehicleInfo(ScenarioModel):
22
+ """多车任务中一辆车辆的静态公开信息。"""
23
+
24
+ vehicle_id: str
25
+ display_name: str
26
+ role: str
27
+ length_m: float
28
+ width_m: float
29
+ height_m: float
30
+ maximum_speed_mps: float
31
+
32
+
33
+ class StaticObjectInfo(ScenarioModel):
34
+ """场景初始化时一次性公开的固定可碰撞物。"""
35
+
36
+ id: str
37
+ category: str
38
+ display_name: str
39
+ position: Vector3
40
+ orientation_degrees: Vector3
41
+ length_m: float
42
+ width_m: float
43
+ height_m: float
44
+
45
+
46
+ class MultiVehicleSceneStaticData(ScenarioModel):
47
+ """多车任务场景的静态信息。"""
48
+
49
+ coordinate_system: str
50
+ roads: list[RoadInfo]
51
+ vehicles: list[ScenarioVehicleInfo]
52
+ static_objects: list[StaticObjectInfo]
53
+
54
+
55
+ class ScenarioTaskObjective(ScenarioModel):
56
+ objective_id: str
57
+ objective_type: str
58
+ required_role: str = ""
59
+ state: str = ""
60
+ description: str = ""
61
+
62
+
63
+ class ScenarioUncertaintyRegion(ScenarioModel):
64
+ shape: str = ""
65
+ minimum: Vector3 | None = None
66
+ maximum: Vector3 | None = None
67
+ center: Vector3 | None = None
68
+ radius_m: float = 0.0
69
+ diameter_m: float = 0.0
70
+
71
+
72
+ class ScenarioSharedTaskObject(ScenarioModel):
73
+ object_id: str
74
+ object_type: str
75
+ display_name: str = ""
76
+ state: str = ""
77
+ information_level: str = "lv0"
78
+ information_level_index: int = 0
79
+ uncertainty_region: ScenarioUncertaintyRegion | None = None
80
+ valid_observation_count: int = 0
81
+ required_observation_count: int = 0
82
+ position: Vector3 | None = None
83
+ orientation: Vector3 | None = None
84
+ orientation_unit: str = "degrees"
85
+ length_m: float = 0.0
86
+ width_m: float = 0.0
87
+ height_m: float = 0.0
88
+ road_ids: list[str] = Field(default_factory=list)
89
+ lane_ids: list[str] = Field(default_factory=list)
90
+
91
+
92
+ class ScenarioObservedTaskObject(ScenarioModel):
93
+ object_id: str
94
+ object_type: str
95
+ display_name: str = ""
96
+ state: str = ""
97
+ distance_m: float = 0.0
98
+ position: Vector3 | None = None
99
+ relative_position: Vector3 | None = None
100
+ hint: str = ""
101
+ numeric_id: int = 0
102
+ orientation: Vector3 | None = None
103
+ orientation_unit: str = "degrees"
104
+ velocity: Vector3 | None = None
105
+ length_m: float = 0.0
106
+ width_m: float = 0.0
107
+ height_m: float = 0.0
108
+ observation_token: str = ""
109
+ observed_at_seconds: float = 0.0
110
+ uncertainty_region: ScenarioUncertaintyRegion | None = None
111
+
112
+
113
+ class ScenarioTaskDefinition(ScenarioModel):
114
+ """本局公开任务定义;固定规则不属于该模型。"""
115
+
116
+ scenario_id: str
117
+ scenario_name: str
118
+ api_version: str
119
+ problem_type: str
120
+ instance_seed: int
121
+ coordinate_system: str
122
+ control_mode: str
123
+ observation_model: str
124
+ vehicles: list[ScenarioVehicleInfo] = Field(default_factory=list)
125
+ objectives: list[ScenarioTaskObjective] = Field(default_factory=list)
126
+ shared_task_objects: list[ScenarioSharedTaskObject] = Field(default_factory=list)
127
+ allowed_actions: list[str] = Field(default_factory=list)
128
+
129
+
130
+ class ScenarioTaskState(ScenarioModel):
131
+ phase: str = ""
132
+ instance_seed: int = 0
133
+ shared_task_objects: list[ScenarioSharedTaskObject] = Field(default_factory=list)
134
+ verified_signal_count: int = 0
135
+ total_signal_count: int = 0
136
+ unlocked_destination_count: int = 0
137
+ total_destination_count: int = 0
138
+ roadblock_active: bool = False
139
+ intersection_owner: str = ""
140
+
141
+
142
+ class ScenarioVehicleState(ScenarioModel):
143
+ vehicle_id: str
144
+ state: str
145
+ pose: PoseGnss
146
+ speed_mps: float
147
+ control: VehicleControl
148
+
149
+
150
+ class ScenarioObservation(ScenarioModel):
151
+ vehicle_id: str
152
+ role: str = ""
153
+ phase: str = ""
154
+ position: Vector3
155
+ visible_objects: list[ScenarioObservedTaskObject] = Field(default_factory=list)
156
+ obstacles: list[ObstacleInfo] = Field(default_factory=list)
157
+ shared_task_objects: list[ScenarioSharedTaskObject] = Field(default_factory=list)
158
+ verified_signal_count: int = 0
159
+ total_signal_count: int = 0
160
+ unlocked_destination_count: int = 0
161
+ total_destination_count: int = 0
162
+ roadblock_active: bool = False
163
+ intersection_owner: str = ""
164
+
165
+
166
+ class ScenarioInteractionResult(ScenarioModel):
167
+ message: str
168
+ vehicle_id: str
169
+ object_id: str
170
+ object_state: str = ""
171
+ granted: bool = False
172
+
173
+
174
+ class ScenarioEvent(ScenarioModel):
175
+ sequence: int
176
+ elapsed_seconds: float
177
+ event_type: str
178
+ message: str
179
+ vehicle_id: str = ""
180
+ object_id: str = ""
181
+
182
+
183
+ JsonObject = dict[str, Any]
@@ -0,0 +1,95 @@
1
+ Metadata-Version: 2.5
2
+ Name: metacar-multiagent
3
+ Version: 0.1.0
4
+ Summary: MetaCar 多车协同场景 Python 扩展接口
5
+ Project-URL: Repository, https://github.com/YDL-Simulation/metacar-multiagent
6
+ Project-URL: Issues, https://github.com/YDL-Simulation/metacar-multiagent/issues
7
+ Author-email: YDL-Simulation <connie.ma@i-mylab.com>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3
12
+ Requires-Python: >=3.10
13
+ Requires-Dist: metacar==0.4.0
14
+ Requires-Dist: pydantic>=2.0.0
15
+ Provides-Extra: dev
16
+ Requires-Dist: build>=1.2; extra == 'dev'
17
+ Requires-Dist: pytest>=8.0; extra == 'dev'
18
+ Requires-Dist: sphinx>=8.0; extra == 'dev'
19
+ Requires-Dist: twine>=5.0; extra == 'dev'
20
+ Description-Content-Type: text/markdown
21
+
22
+ # metacar-multiagent
23
+
24
+ `metacar-multiagent` 是基于 `metacar 0.4.0` 的多车协同场景扩展包。它不修改、
25
+ 覆盖或替换原 `metacar`;旧场景继续使用 `metacar.SceneAPI`,多车任务场景使用
26
+ `metacar_multiagent.ScenarioTaskAPI`。
27
+
28
+ 本项目独立维护、独立测试和独立发布。`metacar` 是基础依赖,不是本项目的源码
29
+ 组成部分。
30
+
31
+ ## 安装
32
+
33
+ 使用正式学生资料包提供的两个 wheel,在它们所在目录执行:
34
+
35
+ ```bash
36
+ python -m pip install ./metacar-0.4.0-py3-none-any.whl ./metacar_multiagent-0.1.0-py3-none-any.whl
37
+ ```
38
+
39
+ 扩展包固定依赖 `metacar==0.4.0`。基础包还需要 numpy、opencv-python、pydantic 等依赖,
40
+ 安装时应能访问依赖源或已备齐相应文件;仅这两个 wheel 不代表完整的离线安装环境。
41
+
42
+ PyPI 版本发布后,也可执行 `python -m pip install metacar-multiagent==0.1.0`。
43
+ 发行状态和安装文件以本仓库的 Release 页面为准。
44
+
45
+ ## 最小示例
46
+
47
+ 源码仓库和源码发行包提供 `examples/minimal_control.py`;wheel 不会将示例安装到当前目录。
48
+ 通过客户端启动场景后,在下载的源码目录执行 `python examples/minimal_control.py`。
49
+ 港口开发站试用使用开发版客户端。示例仅检查连接和停车,不完成运输任务。
50
+
51
+ ```python
52
+ from metacar_multiagent import GearMode, ScenarioTaskAPI, VehicleControl
53
+
54
+ with ScenarioTaskAPI() as api:
55
+ scene = api.get_scene_static_data()
56
+ task = api.get_task()
57
+ vehicle_ids = api.get_vehicle_ids()
58
+
59
+ try:
60
+ api.set_vehicle_controls({
61
+ vehicle_id: VehicleControl(brake=1.0, gear=GearMode.PARKING)
62
+ for vehicle_id in vehicle_ids
63
+ })
64
+ finally:
65
+ api.stop_vehicles(vehicle_ids)
66
+ ```
67
+
68
+ 道路、车辆、固定布景和已感知障碍通过接口读取。固定任务规则和评分规则以正式文档
69
+ 为准。
70
+
71
+ ## 开发
72
+
73
+ 先准备 Python 3.10 或更高版本,再安装本项目及开发依赖:
74
+
75
+ ```powershell
76
+ python -m venv .venv
77
+ .venv\Scripts\python -m pip install -e ".[dev]"
78
+ ```
79
+
80
+ 运行测试:
81
+
82
+ ```powershell
83
+ .venv\Scripts\python -m unittest discover -s tests -p "test_*.py" -v
84
+ ```
85
+
86
+ 构建文档和发布包:
87
+
88
+ ```powershell
89
+ .venv\Scripts\sphinx-build -W --keep-going -b html docs docs/_build/html
90
+ .venv\Scripts\python -m build
91
+ ```
92
+
93
+ 发布新版本前,应同步检查 `pyproject.toml`、`metacar_multiagent/__init__.py`、
94
+ `docs/conf.py` 和 `scripts/validate_release.py` 中的版本及构建标识,并在全新环境中
95
+ 验证 wheel 和 sdist 均可与 `metacar 0.4.0` 共存。完整流程见 [发布手册](RELEASING.md)。
@@ -0,0 +1,8 @@
1
+ metacar_multiagent/__init__.py,sha256=C6_165K8-iOTrB9R-HbdEppY1VnzOqqAZgqc2SZp5nw,1689
2
+ metacar_multiagent/api.py,sha256=HcfNOPqANvbEyIN6em_ZBuI_EeqVhomKjLCtJGzLxuQ,21410
3
+ metacar_multiagent/build_info.py,sha256=jgwaKpuSML5Gd8YCjPqawI7WI2kAEIV2lGadjVwzU-I,107
4
+ metacar_multiagent/models.py,sha256=SGixnde1QEfYg_J26rgWjyUfAkrlkf3tsuSb2xFkyYk,4870
5
+ metacar_multiagent-0.1.0.dist-info/METADATA,sha256=bM4d9mUX7MEIY6JYrvQbAFqRjCluDVy7f-Ow2z5OCu8,3408
6
+ metacar_multiagent-0.1.0.dist-info/WHEEL,sha256=zOwg4jB6zX2kU910N-cMawjivD6tO8NEWvE12je1bVk,87
7
+ metacar_multiagent-0.1.0.dist-info/licenses/LICENSE,sha256=fuNo9VBfkdzb9A_J-E5Gk-djnE-IRIqBHomP7IMa8_s,1071
8
+ metacar_multiagent-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.32.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 YDL-Simulation
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.