Metadata-Version: 2.4
Name: py-hikvision
Version: 0.2.1
Summary: 一个用于与海康威视 iSecure Center (ISC) API 交互的 Python 客户端库
Author-email: Guolei <174000902@qq.com>
License: MIT License
        
        Copyright (c) 2026 郭磊
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://gitee.com/guolei19850528/py_hikvision
Project-URL: Repository, https://gitee.com/guolei19850528/py_hikvision.git
Keywords: isc,hikvision,python,client,api,海康威视,iSecure Center
Classifier: License :: OSI Approved :: MIT License
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
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: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: httpx>=0.27.0
Requires-Dist: pydantic>=2.0
Requires-Dist: jsonpath-ng>=1.5.3
Requires-Dist: jsonschema>=4.21.0
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: setuptools>=61.0; extra == "dev"
Requires-Dist: twine>=4.0; extra == "dev"
Dynamic: license-file

# py-hikvision

一个用于与海康威视 iSecure Center (ISC) API 交互的 Python 客户端库。

## 功能特性

- 🔐 **API 认证**: 支持 HMAC-SHA256 签名认证机制
- 🚀 **同步/异步请求**: 支持同步和异步两种 HTTP 请求方式
- 📋 **响应模型**: 使用 Pydantic 进行响应数据校验和解析
- 🔧 **工具函数**: 提供时间戳、UUID、JSONPath 查询等实用工具

## 安装

```bash
pip install py_hikvision
```

## 快速开始

### 基本使用

```python
from py_hikvision.isc import Isc
from py_hikvision.isc.utils import convert_to_code_eq_0

# 初始化客户端
isc_inst = Isc(
    host="https://your-isc-server.com",
    ak="your-access-key",
    sk="your-secret-key"
)

# 发送同步请求
response = isc_inst.request(
    method="POST",
    url="/api/parking/info",
    json={"plateNo": "京A12345"}
)
print(convert_to_code_eq_0(response))


# 发送异步请求
async def fetch_data():
    response = await isc_inst.async_request(
        method="GET",
        url="/api/parking/list"
    )
    return convert_to_code_eq_0(response)
```

### 使用自定义客户端

```python
import httpx
from py_hikvision.isc import Isc
from py_hikvision.isc.utils import convert_to_code_eq_0

# 创建自定义客户端
custom_client = httpx.Client(
    base_url="https://your-isc-server.com",
    timeout=120,
    verify=False
)

isc_inst = Isc(
    host="https://your-isc-server.com",
    ak="your-access-key",
    sk="your-secret-key"
)

# 使用自定义客户端发送请求
response = isc_inst.request(
    method="GET",
    url="/api/parking/list"
)
print(convert_to_code_eq_0(response))
print(response.json())
```

### 工具函数示例

```python
from py_hikvision.isc.utils import (
    timestamp,
    nonce,
    json_find_first,
    url_add_artemis_prefix
)

# 生成时间戳（毫秒）
ts = timestamp()
print(f"当前时间戳: {ts}")

# 生成随机 UUID
random_nonce = nonce()
print(f"随机 UUID: {random_nonce}")

# JSONPath 查询
data = {
    "code": 0,
    "msg": "success",
    "data": {
        "list": [
            {"id": 1, "name": "设备1"},
            {"id": 2, "name": "设备2"}
        ]
    }
}
first_name = json_find_first("$.data.list[0].name", data)
print(f"第一个设备名称: {first_name}")

# 添加 Artemis 前缀
url = "/api/parking/info"
prefixed_url = url_add_artemis_prefix(url)
print(f"带前缀的 URL: {prefixed_url}")  # 输出: /artemis/api/parking/info
```

### 响应模型使用

```python
from py_hikvision.isc import Isc
from py_hikvision.isc.responses import CODE_EQ_0
from py_hikvision.isc.utils import convert_to_code_eq_0

isc_inst = Isc(
    host="https://your-isc-server.com",
    ak="your-access-key",
    sk="your-secret-key"
)

response = isc_inst.request(method="GET", url="/api/parking/list")

# 转换为 CODE_EQ_0 模型
code_eq_0_response = convert_to_code_eq_0(response)

# 访问响应数据
print(f"状态码: {code_eq_0_response.code}")
print(f"消息: {code_eq_0_response.msg}")
print(f"数据: {code_eq_0_response.data.data}")
```

## API 文档

### Isc 类

#### 初始化

```python
isc_inst = Isc(
    host: Optional[str] = None,  # ISC 服务器地址
ak: Optional[str] = None,  # Access Key
sk: Optional[str] = None,  # Secret Key
client_kwargs: Optional[dict] = None  # httpx 客户端配置
)
```

#### 方法

| 方法                               | 说明                |
|----------------------------------|-------------------|
| `client()`                       | 创建同步 HTTP 客户端     |
| `async_client()`                 | 创建异步 HTTP 客户端     |
| `signature(string)`              | 生成 HMAC-SHA256 签名 |
| `headers(method, path, headers)` | 生成请求头（包含签名）       |
| `request(**kwargs)`              | 发送同步请求            |
| `async_request(**kwargs)`        | 发送异步请求            |

### 工具函数

```python
from py_hikvision.isc.utils import (
    timestamp,  # 生成毫秒时间戳
    nonce,  # 生成 UUID
    json_find_first,  # JSONPath 查询
    json_is_valid,  # JSON Schema 校验
    url_add_artemis_prefix,  # 添加 Artemis 前缀
    image_to_base64_and_md5,  # 图片编码
    convert_to_code_eq_0  # 转换为 CODE_EQ_0 模型
)
```

## 响应模型

```python
from py_hikvision.isc.responses import CODE_EQ_0

# 响应结构
code_eq_0 = CODE_EQ_0(
    code=0,  # 错误码，0 表示成功
    msg="success",  # 错误信息
    data={...}  # 响应数据
)
```

## 安全说明

1. **签名机制**: 使用 HMAC-SHA256 算法确保请求完整性
2. **防止重放攻击**: 通过 nonce（随机 UUID）和 timestamp（时间戳）实现
3. **密钥管理**: Access Key 和 Secret Key 应妥善保管，避免泄露

## 依赖

- `httpx`: HTTP 客户端
- `pydantic`: 数据验证
- `jsonpath-ng`: JSONPath 查询
- `jsonschema`: JSON Schema 校验

## 主页

[https://gitee.com/guolei19850528/py_hikvision](https://gitee.com/guolei19850528/py_hikvision)

## 许可证

MIT License

## 贡献

欢迎提交 Issue 和 Pull Request！

## 作者

Guolei<174000902@qq.com>
