Metadata-Version: 2.4
Name: smartrack-sdk
Version: 1.0.0
Summary: 广东浩鲸科技智能料架系统Python SDK
Home-page: https://www.gdhjtech.com/
Author: SmartRack SDK Team
Author-email: support@hjwms.com
Project-URL: Bug Reports, https://www.gdhjtech.com/
Project-URL: Source, https://github.com/smartrack/smartrack-sdk-python
Project-URL: Documentation, https://s.apifox.cn/dd344f34-40cf-4049-a2a5-7ed52a34f398
Keywords: smartrack 广东浩鲸科技 wms仓储管理 智能料架 api sdk
Classifier: Development Status :: 5 - Production/Stable
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.6
Classifier: Programming Language :: Python :: 3.7
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Topic :: Internet :: WWW/HTTP
Requires-Python: >=3.6
Description-Content-Type: text/markdown
Requires-Dist: requests>=2.25.1
Requires-Dist: urllib3>=1.26.0
Requires-Dist: certifi>=2021.5.30
Requires-Dist: python-dateutil>=2.8.2
Requires-Dist: jsonschema>=3.2.0
Provides-Extra: dev
Requires-Dist: pytest>=6.0; extra == "dev"
Requires-Dist: pytest-cov>=2.0; extra == "dev"
Requires-Dist: black>=21.0; extra == "dev"
Requires-Dist: flake8>=3.8; extra == "dev"
Requires-Dist: mypy>=0.800; extra == "dev"
Provides-Extra: flask
Requires-Dist: Flask>=2.0; extra == "flask"
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.68; extra == "fastapi"
Requires-Dist: uvicorn>=0.15; extra == "fastapi"
Dynamic: author
Dynamic: author-email
Dynamic: classifier
Dynamic: description
Dynamic: description-content-type
Dynamic: home-page
Dynamic: keywords
Dynamic: project-url
Dynamic: provides-extra
Dynamic: requires-dist
Dynamic: requires-python
Dynamic: summary

# SmartRack SDK for Python

SmartRack智能料架系统Python SDK，提供与智能料架系统Web API的集成接口。

## 特性

- ✅ 完整的API接口支持
- ✅ 强类型模型（dataclasses）
- ✅ 完善的异常处理
- ✅ 自动序列化/反序列化
- ✅ 认证支持
- ✅ 超时控制
- ✅ WebAPI回调处理
- ✅ Flask/FastAPI集成支持
- ✅ 详细日志记录
- ✅ 单元测试覆盖

## 快速开始

### 安装

```bash
pip install smartrack-sdk
```

或从源码安装：

```bash
git clone https://github.com/smartrack/smartrack-sdk-python.git
cd smartrack-sdk-python
pip install -e .
```

### 基本使用

```python
import logging
from smartrack_sdk import SmartRackClient
from smartrack_sdk.models.requests import StockInRequest
from smartrack_sdk.models.enums import LedColors

# 配置日志
logging.basicConfig(level=logging.INFO)

# 创建客户端
with SmartRackClient("https://your-smartrack-api.com") as client:
    # 创建入库请求
    request = StockInRequest("test123", "MES001")
    request.set_sheet_id("SI-20240101001")
    request.set_rack_id("A001")
    request.set_grn("PRODUCT001")
    request.set_led_color(LedColors.GREEN)
    request.set_blink(True)

    # 发送请求
    response = client.stock_in_request(request)
    print(f"入库请求结果: Code={response.code}, Message={response.message}")
```

## 功能模块

### 1. 入库管理

#### 入库请求
```python
from smartrack_sdk.models.requests import StockInRequest

request = StockInRequest("test", "MES")
request.set_sheet_id("入库单号")
request.set_rack_id("料架编号")
request.set_grn("产品朔源码")
request.set_led_color(LedColors.GREEN)
request.set_blink(True)

response = client.stock_in_request(request)
print(f"入库请求结果: {response.message}")
```

#### 入库完成
```python
from smartrack_sdk.models.requests import StockInFinishRequest

request = StockInFinishRequest("test", "MES")
request.set_sheet_id("入库单号")

response = client.stock_in_finish(request)
print(f"入库完成结果: {response.message}")
```

### 2. 出库管理

#### 出库请求
```python
from smartrack_sdk.models.requests import StockOutRequest

request = StockOutRequest("test", "MES")
request.set_sheet_id("出库单号")
request.add_grn("朔源码1")
request.add_grn("朔源码2")
request.set_led_color(LedColors.RED)
request.set_blink(True)

response = client.stock_out_request(request)
for item in response.result_data:
    print(f"储位: {item.cell}, GRN: {item.grn}")
```

#### 单号出库请求
```python
from smartrack_sdk.models.requests import StockOutSheetRequest

request = StockOutSheetRequest("test", "MES")
request.set_sheet_id("工单号/领料单号")
request.add_grn("朔源码1")
request.add_grn("朔源码2")

response = client.stock_out_sheet_request(request)
print(f"亮灯颜色: {response.led_color}")
print(f"颜色名称: {response.color_name}")
```

#### 单号出库完成
```python
from smartrack_sdk.models.requests import StockOutSheetFinishRequest

request = StockOutSheetFinishRequest("test", "MES")
request.set_sheet_id("工单号/领料单号")

response = client.stock_out_sheet_finish(request)
print(f"单号出库完成结果: {response.message}")
```

#### 单号出库取消
```python
from smartrack_sdk.models.requests import StockOutSheetCancelRequest

request = StockOutSheetCancelRequest("test", "MES")
request.set_sheet_id("工单号/领料单号")

response = client.stock_out_sheet_cancel(request)
```

### 3. 库存查询

#### 查询库存数据
```python
response = client.get_stock_data(
    grn="PRODUCT001",          # GRN
    rack_id="A001",           # 料架号
    cell_id="A0010001",       # 储位号
    led_color=LedColors.GREEN,  # LED颜色
    is_blink=False,            # 是否闪烁
    skip_count=0,              # 跳过数量
    max_result_count=50         # 最大结果数量
)

print(f"查询到 {response.total} 条库存记录")
for stock in response.result_data:
    print(f"料架: {stock.rack_id}, 储位: {stock.cell_id}, GRN: {stock.grn}")
```

#### 通过GRN列表查询库存
```python
from smartrack_sdk.models.requests import GetStockByGRNListRequest

request = GetStockByGRNListRequest("test", "MES")
request.add_grn("GRN001")
request.add_grn("GRN002")
request.add_grn("GRN003")

response = client.get_stock_by_grn_list(request)
print(f"查询到 {response.total} 条库存记录")
```

### 4. 料架管理

#### 料架测试
```python
from smartrack_sdk.models.requests import RackTestRequest
from smartrack_sdk.models.enums import RackTestMode

request = RackTestRequest("test", "MES")
request.set_rack_id("A001")
request.set_test_mode(RackTestMode.RGB_TEST)
request.set_blink(False)

response = client.rack_test(request)
print(f"料架测试结果: {response.message}")
```

#### 重置储位状态
```python
from smartrack_sdk.models.requests import ResetCellRequest

request = ResetCellRequest("test", "MES")
request.add_cell("A0010001")
request.add_cell("A0010002")
request.add_cell("A0010003")

response = client.reset_cell(request)
print(f"重置储位状态结果: {response.message}")
```

#### 清除错误
```python
from smartrack_sdk.models.requests import ClearErrorRequest

request = ClearErrorRequest("test", "MES")
request.set_cell_id("A0010001")  # 或者使用 set_rack_id("A001")

response = client.clear_error(request)
for item in response.result_data:
    status_text = "空" if item.is_empty() else "非空"
    print(f"储位: {item.cell}, GRN: {item.grn}, 状态: {status_text}")
```

### 5. WebAPI回调处理

#### 使用Flask（推荐）
```python
from smartrack_sdk.callback import FlaskCellEventHandler, CellEventCallbackService
from flask import Flask

# 创建Flask应用
app = Flask(__name__)

# 创建回调处理器
handler = CellEventCallbackService()
flask_handler = FlaskCellEventHandler(app, handler)

# 启动服务器
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=8080)
```

#### 使用FastAPI
```python
from smartrack_sdk.callback import FastAPICellEventHandler
import uvicorn

# 创建FastAPI应用
app = FastAPICellEventHandler()
uvicorn.run(app, host="0.0.0.0", port=8080)
```

#### 自定义回调处理器
```python
from smartrack_sdk.callback import CellEventHandler
from smartrack_sdk.models.callback import CellEventHandleRequest, CellEventHandleResponse

class CustomCellEventHandler(CellEventHandler):
    def handle(self, request: CellEventHandleRequest) -> CellEventHandleResponse:
        # 自定义处理逻辑
        print(f"收到储位事件回调: {request.user_id}")

        # 处理事件数据
        for event_data in request.data:
            print(f"储位: {event_data.cell_id}, GRN: {event_data.grn}")

        # 返回成功响应
        return CellEventHandleResponse.success(request.session_id)

# 使用自定义处理器
handler = CustomCellEventHandler()
```

## 枚举类型

### LedColors (LED灯颜色)
```python
from smartrack_sdk.models.enums import LedColors

# 颜色值
LedColors.OFF           # 0 - 关闭
LedColors.RED           # 1 - 红色
LedColors.GREEN         # 2 - 绿色
LedColors.YELLOW        # 3 - 黄色
LedColors.BLUE          # 4 - 蓝色
LedColors.MAGENTA       # 5 - 洋红色
LedColors.CYAN          # 6 - 青色
LedColors.WHITE         # 7 - 白色
LedColors.BLINK         # 128 - 闪烁
LedColors.RED_BLINK     # 129 - 红色闪烁
LedColors.GREEN_BLINK   # 130 - 绿色闪烁
LedColors.YELLOW_BLINK  # 131 - 黄色闪烁
LedColors.BLUE_BLINK    # 132 - 蓝色闪烁
LedColors.MAGENTA_BLINK # 133 - 洋红色闪烁
LedColors.CYAN_BLINK    # 134 - 青色闪烁
LedColors.WHITE_BLINK   # 135 - 白色闪烁
```

### CellStatus (储位状态)
```python
from smartrack_sdk.models.enums import CellStatus

CellStatus.EMPTY             # 0 - 空
CellStatus.HOLD              # 1 - 非空
CellStatus.LOCKED            # 2 - 预定状态
CellStatus.TAKE_OUT          # 3 - 已取料
CellStatus.CHECKED           # 4 - 已复核
CellStatus.MOVE              # 5 - 移库已取出
CellStatus.ILLEGAL_TAKE_OUT # -3 - 非法取料
CellStatus.ILLEGAL_TAKE_IN  # -2 - 非法上料
CellStatus.DISABLED          # -1 - 禁用储位
```

### RackTestMode (料架测试模式)
```python
from smartrack_sdk.models.enums import RackTestMode

RackTestMode.ALL_OFF           # 0 - 全部灭灯
RackTestMode.RGB_TEST          # 1 - RGB测试
RackTestMode.LIGHT_SEQUENCE_TEST # 2 - 灯序测试
RackTestMode.WARNING_LIGHT_TEST # 3 - 警示灯测试
RackTestMode.EMPTY_LIGHT       # 4 - 空位亮灯
RackTestMode.NON_EMPTY_LIGHT   # 5 - 非空亮灯
```

## 异常处理

### SmartRackException
所有SDK异常的基类。

### SmartRackApiException
API调用返回错误时抛出：
```python
try:
    response = client.stock_in_request(request)
except SmartRackApiException as e:
    print(f"API错误: {e.message}")
    print(f"错误代码: {e.api_code}")
    print(f"会话ID: {e.session_id}")
```

### SmartRackNetworkException
网络相关错误时抛出：
```python
try:
    response = client.stock_in_request(request)
except SmartRackNetworkException as e:
    print(f"网络错误: {e.message}")
    print(f"HTTP状态码: {e.status_code}")

    if e.is_timeout:
        print("请求超时")
    elif e.is_connection_error:
        print("连接错误")
```

### SmartRackConfigurationException
配置错误时抛出：
```python
try:
    client = SmartRackClient("")  # 空的URL
except SmartRackConfigurationException as e:
    print(f"配置错误: {e.message}")
```

## 高级配置

### 自定义HTTP客户端
```python
import requests

# 创建自定义session
session = requests.Session()
session.timeout = 60  # 60秒超时
session.verify = False  # 跳过SSL验证

# 使用自定义session创建客户端
client = SmartRackClient("https://api.smartrack.com", timeout=60)
```

### 设置认证Token
```python
client = SmartRackClient("https://api.smartrack.com")
client.set_auth_token("your-auth-token")
```

### 日志配置
```python
import logging

# 配置详细日志
logging.basicConfig(
    level=logging.DEBUG,
    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)

# SDK会自动使用配置的logger
```

### 使用上下文管理器
```python
with SmartRackClient("https://api.smartrack.com") as client:
    # 使用client...
    response = client.stock_in_request(request)
    # 客户端会自动关闭
```

## 测试

### 运行基本示例
```bash
python examples/basic_usage.py
```

### 运行测试客户端
```bash
# 测试所有API
python examples/test_client.py

# 测试单个API
python examples/test_client.py stock_in
python examples/test_client.py rack_test
python examples/test_client.py clear_error
```

### 启动回调服务器
```bash
# 使用Flask启动WebAPI回调服务器
python examples/callback_server.py --server

# 查看手动设置说明
python examples/callback_server.py --manual
```

### 运行单元测试
```bash
python -m pytest smartrack_sdk/tests/
```

## 项目结构

```
smartrack-sdk-python/
├── smartrack_sdk/                 # 主包
│   ├── __init__.py
│   ├── client/                    # 客户端
│   │   ├── __init__.py
│   │   └── smart_rack_client.py
│   ├── models/                    # 数据模型
│   │   ├── __init__.py
│   │   ├── enums.py              # 枚举定义
│   │   ├── requests.py           # 请求模型
│   │   ├── responses.py          # 响应模型
│   │   └── callback.py            # 回调模型
│   ├── exceptions/               # 异常类
│   │   ├── __init__.py
│   │   ├── base.py               # 基础异常
│   │   ├── api.py                # API异常
│   │   ├── network.py            # 网络异常
│   │   ├── configuration.py      # 配置异常
│   │   └── validation.py         # 验证异常
│   └── callback/                  # 回调处理
│       ├── __init__.py
│       ├── handler.py            # 回调处理器
│       ├── service.py            # 默认回调服务
│       ├── flask_handler.py      # Flask处理器
│       └── fastapi_handler.py    # FastAPI处理器
├── examples/                      # 使用示例
│   ├── basic_usage.py          # 基本使用示例
│   ├── callback_server.py      # 回调服务器示例
│   └── test_client.py          # 测试客户端
├── smartrack_sdk/tests/           # 单元测试
├── setup.py                      # 安装配置
├── requirements.txt              # 依赖文件
└── README.md                     # 文档
```

## 依赖项

### 核心依赖
- `requests` >= 2.25.1 - HTTP客户端
- `urllib3` >= 1.26.0 - URL处理
- `python-dateutil` >= 2.8.2 - 日期处理

### 可选依赖
- `Flask` >= 2.0.0 - Web框架（用于回调处理）
- `FastAPI` >= 0.68 - Web框架（用于回调处理）
- `uvicorn` >= 0.15 - ASGI服务器（用于FastAPI）

## 开发依赖
- `pytest` >= 6.0 - 测试框架
- `pytest-cov` >= 2.0 - 测试覆盖率
- `black` >= 21.0 - 代码格式化
- `flake8` >= 3.8 - 代码检查
- `mypy` >= 0.800 - 类型检查

## 许可证

本项目基于MIT许可证开源。

## 支持

如有问题或建议，请提交Issue或联系开发团队。

---

**SmartRack SDK Team**
版本: 1.0.0
最后更新: 2024年11月
