# 公車 (https://nolantw.github.io/tdx/guides/bus/)

## 查詢一條路線

`bus_route()` 以完整的路線名稱選擇一條路線，取得資料時才發出請求：

```python
route = client.bus_route("Taipei", "307")

for board in route.board():
    print(board.route_name, board.direction)
    for item in board.stops:
        print(item.stop.name, item.estimate_seconds)
```

`board()` 合併站序與到站預估，`estimate_seconds` 是最短的預估到站秒數，沒有預估時為 `None`。同一個物件還提供：

| 方法 | 內容 |
| --- | --- |
| `info()` | 路線資料 |
| `stops()` | 各方向與附屬路線的站序 |
| `schedules()` | 定期班表 |
| `shapes()` | 路線線型 |
| `fares()` | 票價 |
| `arrivals()` | 到站預估 |
| `vehicles()` | 車輛位置 |
| `stop_events()` | 到離站動態 |

## 批次取得資料

`client.bus` 取得整個縣市的資料。縣市使用 TDX 的英文名稱，傳入 `None` 則查詢公路客運：

```python
for stop in client.bus.stops("Tainan", limit=100):
    print(stop.uid, stop.name, stop.position)

for row in client.bus.routes(None, route_name="1728"):
    print(row.name, row.departure, row.destination)
```

| 類別 | 方法 |
| --- | --- |
| 路線 | `routes`、`subroutes`、`route_stops`、`display_stops`、`shapes`、`route_networks`、`network_maps` |
| 站牌 | `stops`、`stations`、`station_groups` |
| 班表 | `schedules`、`daily_timetables`、`daily_stop_timetables`、`first_last_trips`、`travel_times` |
| 動態 | `arrivals`、`vehicle_positions`、`stop_events`、`alerts` |
| 票價 | `fares`、`pass_routes` |
| 營運 | `operators`、`vehicles`、`depots`、`depot_vehicles`、`vehicle_routes`、`news`、`data_version` |

## 查詢一個站位

`client.advanced` 以站位代碼取得行經該站位的資料，縣市傳入 `None` 則為公路客運站位：

```python
station = client.bus.stations("Taipei", limit=1)[0]
for arrival in client.advanced.station_arrivals("Taipei", station.id):
    print(arrival.route_name, arrival.estimate_seconds)
```

| 方法 | 內容 |
| --- | --- |
| `station_stops` | 站牌 |
| `station_routes` | 路線 |
| `station_route_stops` | 路線站序 |
| `station_schedules` | 路線班表 |
| `station_shapes` | 路線線型 |
| `station_arrivals` | 到站預估 |
| `station_vehicle_positions` | 路線車輛位置 |
| `station_stop_events` | 到離站動態 |

## 動態資料的更新方式

`arrivals`、`vehicle_positions` 與 `stop_events` 的 `update_mode` 可選擇 `"batch"`（定時整批更新）或 `"record"`（逐筆更新，支援公路客運與部分縣市）：

```python
arrivals = client.bus.arrivals("Hsinchu", update_mode="record")
```

## 接駁車與需求反應式公車

接駁車以 `"hospital"`（醫療接駁）或 `"science_park"`（科學園區）區分，方法以 `shuttle_` 開頭。科學園區的動態資料使用 `science_park_` 開頭的方法。需求反應式公車（DRTS）的方法以 `drts_` 開頭：

```python
for route in client.bus.drts_routes("Taichung", limit=20):
    print(route)
for authority in client.bus.shuttle_authorities("hospital"):
    print(client.bus.shuttle_routes("hospital", authority.code))
```

所有參數與欄位見[公車 API](/reference/bus)。