Metadata-Version: 2.5
Name: py-tjbrhk-toolkit
Version: 5.0.0
Summary: 天津博瑞皓科博瑞云音箱官方 API 现代化 Python 工具包，支持同步 / 异步语音播报
Project-URL: Homepage, https://gitee.com/guolei19850528/py_tjbrhk_toolkit
Project-URL: Repository, https://gitee.com/guolei19850528/py_tjbrhk_toolkit
Author-email: Guo Lei <174000902@qq.com>
License: MIT
License-File: LICENSE
Keywords: tjbrhk,云音箱接口,博瑞云音箱,支付播报,语音播报
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Internet :: WWW/HTTP
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27.0
Requires-Dist: pydantic>=2.7.0
Provides-Extra: all
Requires-Dist: mypy>=1.13.0; extra == 'all'
Requires-Dist: pre-commit>=4.0.0; extra == 'all'
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'all'
Requires-Dist: pytest-cov>=5.0.0; extra == 'all'
Requires-Dist: pytest>=8.3.0; extra == 'all'
Requires-Dist: python-dotenv>=1.0.0; extra == 'all'
Requires-Dist: ruff>=0.9.0; extra == 'all'
Provides-Extra: dev
Requires-Dist: mypy>=1.13.0; extra == 'dev'
Requires-Dist: pre-commit>=4.0.0; extra == 'dev'
Requires-Dist: python-dotenv>=1.0.0; extra == 'dev'
Requires-Dist: ruff>=0.9.0; extra == 'dev'
Provides-Extra: test
Requires-Dist: pytest-asyncio>=0.24.0; extra == 'test'
Requires-Dist: pytest-cov>=5.0.0; extra == 'test'
Requires-Dist: pytest>=8.3.0; extra == 'test'
Requires-Dist: python-dotenv>=1.0.0; extra == 'test'
Description-Content-Type: text/markdown

# py-tjbrhk-toolkit

天津博瑞皓科博瑞云音箱官方 API 现代化 Python 工具包 —— 类型安全、同步 / 异步一致、开箱即用的语音播报客户端。

[![Python](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/)
[![httpx](https://img.shields.io/badge/httpx-0.27%2B-lightgray.svg)](https://www.python-httpx.org/)
[![pydantic](https://img.shields.io/badge/pydantic-2.7%2B-e96462.svg)](https://docs.pydantic.dev/)
[![License](https://img.shields.io/badge/license-MIT-green.svg)](./LICENSE)


---

## ✨ 特性

| 能力 | 说明 |
|------|------|
| **云音箱通知** | 通过 Token + ID 调用 `notify.php` 提交语音播报，支持支付播报、语音提醒等场景 |
| **同步 + 异步** | `Tjbrhk` / `AsyncTjbrhk` API 签名完全一致，可自由切换 |
| **连接池复用** | 基于 httpx，支持 context manager 自动关闭连接，也可手动 `close()` |
| **错误分层** | `ConfigError` / `ValidationError` / `HTTPError` 统一继承 `TjbrhkError` |
| **类型安全** | Pydantic v2 响应建模 + mypy strict（`disallow_untyped_defs` / `warn_return_any`） |
| **现代化** | Python 3.10+，`X \| Y` 联合类型、`slots` dataclass、PEP 561 类型标记 |

## 📦 安装

推荐使用 [uv](https://docs.astral.sh/uv/)：

```bash
uv add py-tjbrhk-toolkit
```

使用 pip 亦可：

```bash
pip install py-tjbrhk-toolkit
```

开发模式：

```bash
git clone <your-repo>
cd py_tjbrhk_toolkit
uv sync                          # 创建 venv + 安装依赖 + 安装本包
uv run pytest tests -v
```

## 🚀 五分钟上手

`Tjbrhk` / `AsyncTjbrhk` 是顶层组合客户端：持有底层连接池，并通过 `client.speaker`
暴露云音箱服务，后续可平滑扩展更多服务。

### 同步播报

```python
from py_tjbrhk_toolkit import Tjbrhk

with Tjbrhk(
    token="你的云音箱 Token",
    id="你的云音箱 ID",
) as client:
    response = client.speaker.notify("您好，欢迎光临", vol=80)
    print(response.errcode, response.errmsg, response.ok)
```

### 异步播报（FastAPI / asyncio）

```python
from py_tjbrhk_toolkit import AsyncTjbrhk

async def handler() -> None:
    async with AsyncTjbrhk(
        token="你的云音箱 Token",
        id="你的云音箱 ID",
    ) as client:
        response = await client.speaker.notify("收到一笔新的付款", vol=80)
        print(response.ok)
```

同步客户端用 `with`、异步客户端用 `async with` 管理连接；也可分别调用
`Tjbrhk.close()` 与 `AsyncTjbrhk.close()` 手动关闭。

也可以直接传入完整配置 `Tjbrhk(config=SpeakerConfig(...))`，此时其余便捷参数被忽略。

## 🏗️ 架构总览

```
py_tjbrhk_toolkit/
├── __init__.py            包根导出（客户端 / 模型 / 异常 / 配置）
├── client.py              顶层 Tjbrhk / AsyncTjbrhk 组合客户端
├── core/                  底层基础设施（不直接使用）
│   ├── base.py            BaseClient / AsyncBaseClient（httpx + 错误转换）
│   ├── config.py          SpeakerConfig dataclass
│   ├── exceptions.py      TjbrhkError 异常族
│   └── models.py          Pydantic v2 响应模型
└── services/              业务服务层（每个 API 领域一个子包）
    ├── __init__.py        子包说明
    └── speaker/           云音箱通知服务
        ├── __init__.py    导出 SpeakerService / AsyncSpeakerService
        └── client.py      notify.php 服务实现（组合 BaseClient）
```

## ⚙️ 客户端配置

`Tjbrhk` 与 `AsyncTjbrhk` 使用相同的构造参数：

| 参数 | 必填 | 默认值 | 说明 |
|------|------|--------|------|
| `token` | 是 | — | 云音箱 Token。 |
| `id` | 是 | — | 云音箱 ID。 |
| `base_url` | 否 | `https://speaker.17laimai.cn` | 云音箱服务接口地址。 |
| `version` | 否 | `1` | 接口版本。 |
| `timeout` | 否 | `30.0` | HTTP 请求超时时间，单位为秒。 |
| `httpx_kwargs` | 否 | `{}` | 透传给 `httpx.Client` / `httpx.AsyncClient` 的额外参数（代理、TLS、传输器等）。 |

需要更细粒度控制时，也可以直接构造 `SpeakerConfig`：

```python
from py_tjbrhk_toolkit import SpeakerConfig

config = SpeakerConfig(token="...", id="...", timeout=10.0)
print(config.url("/notify.php"))
```

## 📢 notify 接口

```python
notify(
    message,
    *,
    seq=None,
    vol=None,
    speed=None,
    trace_no=None,
    id=None,
    token=None,
    version=None,
)
```

| 参数 | 类型 | 必填 | 说明 |
|------|------|------|------|
| `message` | `str` | 是 | 播报内容，最长 128 个 UTF-8 字节 |
| `seq` | `int \| str` | 否 | 通讯去重顺序号 |
| `vol` | `int \| str` | 否 | 音量设置 |
| `speed` | `int \| str` | 否 | 语速设置 |
| `trace_no` | `str` | 否 | 请求追踪字符串 |
| `id` | `str` | 否 | 覆盖客户端配置的云音箱 ID |
| `token` | `str` | 否 | 覆盖客户端配置的 Token |
| `version` | `str` | 否 | 覆盖客户端配置的接口版本 |

接口返回 `SpeakerNotifyResponse`，字段 `errcode`、`errmsg`、`detail` 与接口响应一致；
`response.ok` 在 `errcode` 等于 `0` 或 `"0"` 时为 `True`。

消息中的数字默认按金额播报；如需按号码或编号播报，可按接口约定使用方括号，例如 `"[123]"`。
音箱型号和接口版本对 `speed` 等参数的支持可能不同，请以官方接口文档为准。

## 🔐 环境变量与示例

[examples/](./examples) 目录下提供两个可直接运行的示例，凭证全部从环境变量读取：

| 文件 | 场景 | 依赖 |
|------|------|------|
| `01_speaker_sync.py` | 同步发送播报 | SPEAKER_ID / SPEAKER_TOKEN |
| `02_speaker_async.py` | 异步发送播报 | SPEAKER_ID / SPEAKER_TOKEN |

复制配置模板并填写真实凭证：

```bash
cp tests/.env.example .env
```

| 环境变量 | 必填 | 默认值 | 说明 |
|----------|------|--------|------|
| `SPEAKER_ID` | 是 | — | 云音箱 ID。 |
| `SPEAKER_TOKEN` | 是 | — | 云音箱 Token。 |
| `SPEAKER_BASE_URL` | 否 | `https://speaker.17laimai.cn` | 接口地址。 |
| `SPEAKER_VERSION` | 否 | `1` | 接口版本。 |

示例会从**仓库根目录**加载 `.env`，系统中已有的环境变量优先。运行：

```bash
uv run python examples/01_speaker_sync.py
uv run python examples/02_speaker_async.py
```

`.env` 包含设备凭据，请勿提交到版本控制。

## ⚠️ 异常体系

```python
from py_tjbrhk_toolkit import ConfigError, HTTPError, TjbrhkError, ValidationError

try:
    with Tjbrhk(token="...", id="...") as client:
        client.speaker.notify("您好")
except ValidationError:
    # 参数不符合接口约定，例如 message 超过 128 个 UTF-8 字节
    ...
except ConfigError:
    # token / id / base_url 为空
    ...
except HTTPError as exc:
    # 网络异常、非 2xx 状态码或响应不是 JSON 对象
    print(f"云音箱请求失败: {exc}（status={exc.status_code}）")
except TjbrhkError:
    # 兜底：所有本包错误
    ...
```

## 🧪 测试

测试全部为**真实网络请求**，会向真实云音箱推送语音播报。凭证从环境变量读取，
缺少 `SPEAKER_ID` / `SPEAKER_TOKEN` 时相关用例自动 skip，不会中断其它用例。

```bash
cp tests/.env.example .env   # 填写真实凭证
uv run pytest tests -v
```

测试矩阵：

```
tests/
├── conftest.py                 fixtures + python-dotenv 加载 .env
└── speaker/
    ├── test_notify_sync.py     同步播报 + 本地参数校验
    └── test_notify_async.py    异步播报 + 本地参数校验
```

> **注意：** 默认测试会触发真实设备语音播报。请勿在不适合播报的设备或环境中执行。

## 🔧 开发

```bash
uv sync
uv run ruff check src tests      # Lint
uv run ruff format src tests     # Format
uv run mypy src/py_tjbrhk_toolkit # 类型检查（strict 模式）
uv run pytest tests -v           # 测试
```

pyproject.toml 关键配置：

```toml
[tool.mypy]
disallow_untyped_defs = true
warn_return_any = true
strict_optional = true

[tool.ruff]
select = ["E", "F", "I", "N", "W", "B", "UP", "RUF"]
ignore = ["RUF001", "RUF002", "RUF003"]   # 中文全角标点不强制
```

## 👤 作者

- 作者：郭磊
- 邮箱：174000902@qq.com

## 📄 License

MIT —— [LICENSE](./LICENSE)
