Metadata-Version: 2.5
Name: py-tiehu-sdk
Version: 0.3.2
Summary: 铁虎道闸平台 Python SDK - 同步接口调用（官方文档: https://www.showdoc.com.cn/1735808258920310/9467753400037587）
Project-URL: Homepage, https://gitee.com/guolei19850528/py_tiehu_sdk
Project-URL: Repository, https://gitee.com/guolei19850528/py_tiehu_sdk.git
Project-URL: Issues, https://gitee.com/guolei19850528/py_tiehu_sdk/issues
Author-email: guolei <174000902@qq.com>
License-File: LICENSE
Requires-Python: >=3.10
Requires-Dist: httpx[http2]>=0.27
Requires-Dist: pydantic>=2.7
Description-Content-Type: text/markdown

# py-tiehu-sdk

[![PyPI version](https://img.shields.io/pypi/v/py-tiehu-sdk.svg)](https://pypi.org/project/py-tiehu-sdk/)
[![Python versions](https://img.shields.io/pypi/pyversions/py-tiehu-sdk.svg)](https://pypi.org/project/py-tiehu-sdk/)
[![License](https://img.shields.io/pypi/l/py-tiehu-sdk.svg)](https://pypi.org/project/py-tiehu-sdk/)

铁虎道闸平台 Python SDK。提供 32 个完整业务接口的签名 + HTTP 封装，支持同步调用。

官方接口文档：https://www.showdoc.com.cn/1735808258920310/9467753400037587

---

## 功能特性

| 特性 | 说明 |
|------|------|
| ✅ 完整接口覆盖 | 32 个下行接口：车位、车类、闸机、临停、月卡、储值、访客、黑名单、商家、锁车 |
| ✅ 自动签名 | 6 步签名规则（parkingId + timestamp + appKey + params 按 ASCII 排序 + MD5 大写） |
| ✅ 签名排除 | `applicationId` 等字段按平台规则自动排除出签名 |
| ✅ 响应模型 | Pydantic BaseModel，`resp.ok` 判断成功，`resp.Data` 承载业务数据 |
| ✅ 不自动抛异常 | status=2（如"车辆不在场"）为正常业务状态，由调用方判断 |
| ✅ 测试分级 | query 默认执行、modify 需显式 `--run-modify` 避免误操作线上数据 |

---

## 安装

```bash
pip install py-tiehu-sdk
# 或
uv add py-tiehu-sdk
```

最低支持 Python 3.10。

---

## 快速开始

```python
from py_tiehu_sdk.provider import PklotAPIProvider, PklotAPIConfig

config = PklotAPIConfig(
    base_url="http://ykt.test.cxyun.net.cn:7303/cxzn",
    app_key="your_app_key",
    parking_id="your_parking_id",
)
provider = PklotAPIProvider(config)

# 车位总览
resp = provider.downstream_api.query_pklot()
print(f"车场: {resp.Data.get('parkingId')}, 总车位: {resp.Data.get('totalLot')}, 空闲: {resp.Data.get('emptyLot')}")

# 闸机列表
resp = provider.downstream_api.get_park_gate()
for gate in resp.Data:
    print(f"  {gate['gateName']}: iostate={gate['iostate']}")

# 车辆在场查询
resp = provider.downstream_api.get_vehicle_information(plate_number="湘A12345")
if resp.ok:
    print(f"入场时间: {resp.Data.get('startTime')}")
elif resp.status == 2:
    print("车辆不在场（正常业务状态）")
else:
    print(f"查询失败: {resp.message}")
```

---

## 项目结构

```
py_tiehu_sdk/
├── README.md
├── pyproject.toml
├── .env.example               # 测试环境变量模板
├── tests/
│   ├── conftest.py            # pytest 配置 + .env 加载 + query/modify 分类
│   ├── test_provider.py       # Provider / Config / 签名单元测试
│   ├── test_signature.py      # 签名算法单元测试
│   ├── test_models.py         # 响应模型单元测试
│   └── test_integration.py    # 32 个集成测试（query 默认执行，modify 需 --run-modify）
└── src/py_tiehu_sdk/
    ├── __init__.py            # 只导出 provider + __version__
    ├── _version.py            # 版本号（pyproject.toml 动态读取）
    ├── provider.py            # ★ 主入口：PklotAPIProvider + 所有公共类导出
    └── core/pklot/
        ├── base/
        │   ├── api.py         # PklotBaseAPI（签名 + HTTP POST + 响应解析）
        │   ├── config.py      # PklotAPIConfig（base_url / app_key / parking_id / timeout）
        │   ├── models.py      # PklotCommonResponse（status / message / Data / ok / raise_for_status）
        │   ├── exceptions.py  # PklotError / PklotAPIError / PklotTimeoutError / PklotValidationError / PklotSignatureError
        │   └── signature.py   # generate_sign / md5_uppercase / sort_params（内部模块）
        └── downstream/
            └── api.py         # ★ DownstreamAPI — 32 个业务方法
```

---

## 架构设计

```
PklotAPIProvider(PklotBaseAPI)
  │
  ├─ .client = httpx.Client              # 底层 HTTP client（继承自 BaseAPI）
  ├─ .config = PklotAPIConfig            # 全局配置（继承自 BaseAPI）
  ├─ ._build_signed_payload()            # 自动注入 parkingId / timestamp / sign
  ├─ ._post_json(endpoint, params)       # 发送 JSON POST
  │
  └─ .downstream_api = DownstreamAPI(self)   # 挂载的业务容器
        │
        └─ .base_api = PklotAPIProvider      # 反向持有 Provider
              └─ .query_pklot() / .open_gate() / ...
```

调用链路：`provider.downstream_api.query_pklot()` → `DownstreamAPI.query_pklot()` → `self.base_api._post_json("queryPklot", {})` → `PklotBaseAPI._post_json()` → 签名 → httpx POST → 解析为 `PklotCommonResponse`。

---

## API 接口分组

全部通过 `provider.downstream_api.<method>()` 调用。

### 车位查询（3 个）

| 方法 | Endpoint | 说明 |
|------|----------|------|
| `query_pklot()` | queryPklot | 车位总览（总车位 / 空闲车位 / 区域列表） |
| `get_parkinfo()` | getParkinfo | 车场详情（名称 / 车位 / 收费规则 / 地址） |
| `get_park_device_state()` | getParkDeviceState | 设备在线状态（掉线 / 在线） |

### 车类车型（2 个）

| 方法 | Endpoint | 说明 |
|------|----------|------|
| `get_park_car_type()` | getParkCarType | 车类列表（月租车 / 储值车 / 临时车 等） |
| `get_park_car_model()` | getParkCarModel | 车型列表（小车 / 大车 / 新能源车 等） |

### 闸机控制（3 个）

| 方法 | Endpoint | 说明 |
|------|----------|------|
| `get_park_gate()` | getParkGate | 通道列表（只读查询） |
| `open_gate(gate_id, status)` | openGate | 远程开闸 |
| `no_plate_qrcode(lane_no, open_id)` | noPlateQrcode | 无牌车扫码放行 |

### 临停缴费（4 个）

| 方法 | Endpoint | 说明 |
|------|----------|------|
| `calculating_temp_cost(plate_number, application_id)` | calculatingTempCost | 计算临停应缴金额 |
| `pay_temp_cost(...)` | payTempCost | 支付成功后通知道闸放车 |
| `get_vehicle_information(plate_number)` | getVehicleInformation | 查询车辆在场信息 |
| `simulate_cla_fee(during_time)` | simulateClaFee | 根据时长（分钟）模拟计算费用 |

### 月卡储值（7 个）

| 方法 | Endpoint | 说明 |
|------|----------|------|
| `pay_monthly(...)` | payMonthly | 月卡续费 |
| `save_monthly_rent(...)` | saveMonthlyRent | 月卡新增 |
| `del_monthly_rent(plate_number)` | delMonthlyRent | 月卡删除（按月卡号） |
| `get_monthly_rent(plate_number)` | getMonthlyRent | 查询车牌月卡信息 |
| `get_monthly_rent_list(page_index, page_size)` | getMonthlyRentList | 月卡列表分页 |
| `del_monthly_rent_list(plate_numbers)` | delMonthlyRentList | 批量删除月卡 |
| `recharge_stored_value(...)` | rechargeStoredValue | 储值卡充值 |

### 访客（2 个）

| 方法 | Endpoint | 说明 |
|------|----------|------|
| `add_visit(...)` | addVisit | 新增访客 |
| `delete_visit(plate_number)` | deleteVisit | 删除访客 |

### 黑名单（3 个）

| 方法 | Endpoint | 说明 |
|------|----------|------|
| `add_park_black(...)` | addParkBlack | 黑名单新增 |
| `del_park_blacklist(plate_number)` | delParkBlacklist | 黑名单删除 |
| `get_park_black_list(plate_number, page_index, page_size)` | getParkBlackList | 黑名单分页查询 |

### 商家（5 个）

| 方法 | Endpoint | 说明 |
|------|----------|------|
| `discount_rules(seller_no, pwd)` | discountRules | 商家打折规则 |
| `discount_pay(...)` | discountPay | 商家打折支付 |
| `seller_charge(seller_id, money)` | sellerCharge | 商家收款 |
| `seller_charge_list(seller_id, parking_nume)` | sellerChargeList | 商家收款记录查询 |
| `get_park_seller_list(page_index, page_size)` | getParkSellerList | 车场商家列表 |

### 其他辅助（3 个）

| 方法 | Endpoint | 说明 |
|------|----------|------|
| `lock_car(plate_number)` | lockCar | 车场锁车 |
| `upate_plate_info(...)` | upatePlateInfo | 更新车牌信息 |
| `parking_invoice(...)` | parkingInvoice | 获取停车发票 |

---

## 响应模型

所有接口返回 `PklotCommonResponse`：

```python
@dataclass
class PklotCommonResponse:
    status: int | str       # 1=成功, 2=正常业务状态, 0=失败
    message: str            # 消息
    Data: dict | list | None  # 业务数据

    @property
    def ok(self) -> bool:   # status == 1 时为 True
        ...
    def raise_for_status(self):  # status != 1 时抛 PklotAPIError
        ...
```

道闸平台 status 语义：

| status | 含义 | 处理方式 |
|--------|------|---------|
| **1** | 成功 | 正常读取 `resp.Data` |
| **2** | 正常业务状态（车辆不在场、不是月卡车 等） | 按业务逻辑处理，不算异常 |
| **0** | 失败（参数错误、白名单、网络） | 通过 `resp.message` 排查 |

SDK **不自动抛异常**。推荐调用模式：

```python
resp = provider.downstream_api.get_monthly_rent(plate_number="测试00001")

if resp.ok:
    print(f"月卡信息: {resp.Data}")
elif resp.status == 2:
    print("该车牌不是月卡车（正常业务状态）")
else:
    print(f"查询失败: {resp.message}")
```

如果希望失败时自动抛异常，主动调用：

```python
resp.raise_for_status()   # status != 1 时抛 PklotAPIError
```

---

## 异常体系

SDK 异常全部继承自 `PklotError`，在 `provider.py` 导出：

```python
from py_tiehu_sdk.provider import (
    PklotError,              # 所有 SDK 异常基类（可统一捕获）
    PklotAPIError,           # HTTP 非 200 / raise_for_status()
    PklotTimeoutError,       # 请求超时
    PklotValidationError,    # 响应 JSON 解析 / Pydantic 验证失败
    PklotSignatureError,     # 签名算法错误（内部使用）
)
```

---

## 测试

### 运行方式

```bash
# 默认：只跑单元测试（20 个）
pytest

# 跑集成测试 + 查询类（15 个 query，真实网络请求）
pytest --integration -m query

# 跑集成测试 + 查询类 + 修改类（⚠️ 会调用 open_gate / add_park_black 等写操作）
pytest --integration --run-modify
```

### 测试分类

| 分类 | Marker | 默认行为 | 数量 |
|------|--------|---------|------|
| 单元测试 | 无 | 始终执行 | 20 |
| 集成测试 - query | `integration -m query` | 需 `--integration` | 15 |
| 集成测试 - modify | `integration -m modify` | 需 `--integration --run-modify` | 17 |

### .env 配置

集成测试通过 `.env` 加载真实车场参数：

```bash
cp .env.example .env
# 填入测试车场参数
PKLOT_BASE_URL=http://your-park.cxyun.net.cn:7303/cxzn
PKLOT_APP_KEY=your_app_key
PKLOT_PARKING_ID=your_parking_id
```

---

## 外部调用入口

所有公共类统一从 `py_tiehu_sdk.provider` 导入：

```python
from py_tiehu_sdk.provider import (
    PklotAPIProvider,        # 主入口
    PklotAPIConfig,          # 配置
    DownstreamAPI,           # 业务容器（provider.downstream_api 的类型）
    PklotError,              # 异常基类
    PklotAPIError,
    PklotTimeoutError,
    PklotValidationError,
    PklotSignatureError,
    PklotCommonResponse,     # 响应模型
    PklotBaseResponse,
)
```

根包 `py_tiehu_sdk.__version__` 可单独导入：

```python
from py_tiehu_sdk import __version__
```

---

## 版本历史

### v0.3.1 (2026-11-18)

- 重构：文件去掉 `_` 前缀（`_api.py` → `api.py` 等）
- 重构：`PklotAPIProvider` 继承 `PklotBaseAPI`，自身具备签名 + HTTP 能力
- 重构：`__init__.py` 瘦身，所有公共类统一从 `py_tiehu_sdk.provider` 导入
- 统一注释风格为 py_wecom_sdk 风格

### v0.2.1 / v0.2.2

- 新增签名排除参数 `sign_exclude`（`applicationId` 不参与签名）
- `PklotConfig` → `PklotAPIConfig`
- 移除自动抛异常，保留 `status=2` 正常业务状态

### v0.1.0

- 初始版本
- 32 个下行接口完整实现
