本技能提供 大华云开放平台基础通用套件 的统一客户端实现,采用单文件设计:
共 43 个接口 全部支持,详见 API_COVERAGE.md。
add_device() / addverify_device_password() / verifydelete_device() / deleteget_device_list() / listget_device_online() / onlinelist_device_details() / detailscheck_device_bind() / bindget_category() / categoryget_device_channel_info() / channelsmodify_device_name()modify_dev_code()get_sip_info() / sip-infolist_gb_code() / gb-codeadd_gb_device() / add-gbmodify_gb_device() / modify-gblist_gb_device_details() / gb-detailsget_sd_card_status()get_sd_card_storage()list_sd_card_storage()format_sd_card()get_ability_status() / abilityset_ability_status()set_current_utc()list_custom_ring()add_custom_ring()delete_custom_ring()set_custom_ring()current_device_wifi()wifi_around()control_device_wifi()get_sim_signal_strength()image_decrypt()add_callback_config()message_subscribe()get_all_callback_config()update_subscribe_by_callback_config()update_callback_config()delete_callback_config()get_callback_config_info()get_subscribe_info_by_callback_config()get_subscribe_info_by_device()get_message_type_page()需要设置 Cloud 凭证(ProductId、AK、SK)!
最适合初学者和不想用命令行的用户!
Win + R 键,输入 sysdm.cpl 并回车在 "当前用户的变量(U)" 区域(窗口上半部分),点击 "新建(W)...":
变量名变量值说明DAHUA_CLOUD_PRODUCT_ID你的 AppID应用 IDDAHUA_CLOUD_AK你的 AccessKey访问密钥DAHUA_CLOUD_SK你的 SecretKey保密密钥
示例:
text
变量名:DAHUA_CLOUD_PRODUCT_ID
变量值:138XXXX731
变量名:DAHUA_CLOUD_AK
变量值:196XXXXXXXXXXXXX808
变量名:DAHUA_CLOUD_SK
变量值:naumXXXXXXXXXXXXXXXXyHxh
如需更详细的图文教程,请参考以下操作要点:
Windows PowerShell:
powershell
[Environment]::SetEnvironmentVariable("DAHUA_CLOUD_PRODUCT_ID", "your_app_id", "User")
[Environment]::SetEnvironmentVariable("DAHUA_CLOUD_AK", "your_access_key", "User")
[Environment]::SetEnvironmentVariable("DAHUA_CLOUD_SK", "your_secret_key", "User")
Linux/Mac:
bash
export DAHUA_CLOUD_PRODUCT_ID='your_app_id'
export DAHUA_CLOUD_AK='your_access_key'
export DAHUA_CLOUD_SK='your_secret_key'
Windows PowerShell (临时):
powershell
$env:DAHUA_CLOUD_PRODUCT_ID='your_app_id'
$env:DAHUA_CLOUD_AK='your_access_key'
$env:DAHUA_CLOUD_SK='your_secret_key'
注意: 仅在当前窗口有效,关闭后失效
Linux/Mac:
bash
echo $DAHUA_CLOUD_PRODUCT_ID
echo $DAHUA_CLOUD_AK
# 注意:不要打印 SK,避免泄露
Windows PowerShell:
powershell
$env:DAHUA_CLOUD_PRODUCT_ID
$env:DAHUA_CLOUD_AK
bash
# 查看帮助
python scripts/dahua_iot_client.py --help
# 添加设备
python scripts/dahua_iot_client.py add -d <设备序列号> -p admin123 -c IPC
# 查询设备列表
python scripts/dahua_iot_client.py list -p 1 -s 10
# 查询设备在线状态
python scripts/dahua_iot_client.py online -d <设备序列号>
# 校验设备密码(验证密码是否正确)
python scripts/dahua_iot_client.py verify -d <设备序列号> -p admin123 -e aes256
# 删除设备
python scripts/dahua_iot_client.py delete -d <设备序列号>
bash
# 完整设备接入流程(仅需 Cloud 凭证)
cd scripts
python dahua_iot_client.py add -d <设备序列号> -p admin123 -c IPC -e aes256
python dahua_iot_client.py online -d <设备序列号>
python dahua_iot_client.py list -p 1 -s 20 -d <设备序列号前缀>
导入说明:在
scripts/目录下运行,或将scripts/加入PYTHONPATH后使用。
python
from dahua_iot_client import DahuaIoTClient, create_client_from_env
# 方式1: 从环境变量创建客户端(verbose=True 打印API日志)
client = create_client_from_env()
# SDK 集成时建议关闭日志:create_client_from_env(verbose=False)
# 方式2: 手动创建客户端
client = DahuaIoTClient(
app_id='your_product_id',
access_key='your_access_key',
secret_key='your_secret_key'
)
# 添加设备
result = client.add_device(
device_id='<设备序列号>',
device_password='admin123',
category_code='IPC',
encrypt_method='aes256' # 推荐
)
print(f"Add device result: {result}")
# 校验设备密码(验证密码是否正确)
verify_result = client.verify_device_password('<设备序列号>', 'admin123', encrypt_method='aes256')
print(f"Password verify: {verify_result.get('success', False)}")
# 查询设备在线状态
status = client.get_device_online('<设备序列号>')
print(f"Online status: {status}")
# 查询设备列表
devices = client.get_device_list(page_num=1, page_size=10)
print(f"Device list: {devices}")
# 获取SD卡状态
sd_status = client.get_sd_card_status('<设备序列号>')
print(f"SD card status: {sd_status}")
# 设置设备使能开关
result = client.set_ability_status(
device_id='<设备序列号>',
ability_type='localRecord',
status='on',
channel_id='0'
)
text
┌─────────────────────┐
│ 1. 初始化客户端 │
│ (配置凭证) │
└──────────┬──────────┘
▼
┌─────────────────────┐
│ 2. 自动获取 Token │
│ (AppAccessToken) │
└──────────┬──────────┘
▼
┌─────────────────────┐
│ 3. 调用业务API │
│ (设备管理/配置) │
└──────────┬──────────┘
▼
┌─────────────────────┐
│ 4. 返回结果 │
│ (JSON格式) │
└─────────────────────┘
模块路径前缀说明认证/open-api/api-base/auth/getAppAccessToken获取 AppAccessToken设备管理/open-api/api-iot/device/*addDevice、deleteDevice、verifyDevCode、getDeviceList、deviceOnline、listDeviceDetailsByIds、checkDeviceBindInfo、getCategory、modifyDeviceName、modifyDevCode、getDeviceChannelInfo国标设备/open-api/api-iot/device/*getSipInfo、listGbCode、addGbDevice、modifyGbDevice、deviceInfoDetailAllSD卡/铃音/WiFi/open-api/api-aiot/device/*getSDCardStatus、getSDCardStorage、listSDCardStorage、formatSDCard、listCustomRing、addCustomRing、deleteCustomRing、setCustomRing、wifiAround、currentDeviceWifi、controlDeviceWifi设备配置/open-api/api-aiot/device/*getAbilityStatus、setAbilityStatus、setCurrentUTC其他/open-api/api-aiot/device/getSimSignalStrength获取 SIM 信号强度图片解密/open-api/api-decrypto/image/decrypto图片解密消息订阅/open-api/api-message/*addCallbackConfig、getAllCallbackConfigId、messageSubscribeByDeviceIds、getMessageTypePage、getMessageSubscribeInfoByDeviceId、updateSubscribeByCallbackConfigId、updateByCallbackConfigId、deleteCallbackId、getInfoByCallbackConfigId、getSubscribeInfoByCallbackConfigId
完整 API 参考见 references/api_reference.md。
SHA512 HMAC 签名 - 两种签名方式:
get_token_sign() - 获取 Token 签名 text
签名因子: access_key + timestamp + nonce
business_api_sign() - 业务 API 签名 text
签名因子: access_key + app_access_token + timestamp + nonce
认证请求头 (获取 Token):
python
{
"Content-Type": "application/json",
"AccessKey": access_key,
"Timestamp": timestamp,
"Nonce": nonce,
"X-TraceId-Header": trace_id,
"Sign": signature, # get_token_sign() 生成
"ProductId": app_id,
"Version": "V1",
"Sign-Type": "simple"
}
业务请求头 (所有设备管理API):
python
{
"Content-Type": "application/json",
"AccessKey": access_key,
"Timestamp": timestamp,
"Nonce": nonce,
"X-TraceId-Header": trace_id,
"Sign": signature, # business_api_sign() 生成
"Version": "V1",
"Sign-Type": "simple",
"AppAccessToken": app_token,
"ProductId": app_id
}
text
┌──────────────────────────────────────────────────────────────────┐
│ 常量配置层 (Constants) │
│ - API 端点、超时时间、环境变量名 │
└──────────────────────────────────────────────────────────────────┘
│
┌──────────────────────────────────────────────────────────────────┐
│ 工具函数层 (Utilities) │
│ - get_token_sign() 获取 Token 签名 │
│ - business_api_sign() 业务 API 签名 │
│ - DeviceCodeEncryptor 设备密码加密(Base64/AES256) │
└──────────────────────────────────────────────────────────────────┘
│
┌──────────────────────────────────────────────────────────────────┐
│ DahuaIoTClient 类 (43个接口) │
│ 设备: add/verify/delete/list/details/online/bind/category/channel │
│ 国标: get_sip_info/add_gb/list_gb_code/modify_gb/gb_details │
│ SD卡: get_status/storage/list/format 铃音: list/add/delete/set │
│ 配置: get/set_ability_status/set_current_utc │
│ WiFi: wifi_around/current/control SIM: get_sim_signal_strength │
│ 消息: callback/message_subscribe/update/delete/query │
│ 其他: image_decrypt 图片解密 │
└──────────────────────────────────────────────────────────────────┘
│
┌──────────────────────────────────────────────────────────────────┐
│ 辅助函数层 │
│ - create_client_from_env() 从环境变量创建客户端 │
└──────────────────────────────────────────────────────────────────┘
python
格式:"Dolynk_" + Base64(设备密码)
例如:若设备密码为 admin123
Base64(admin123) = YWRtaW4xMjM=
加密后字符串 = Dolynk_YWRtaW4xMjM=
python
格式:Base64(Aes256(待加密内容, AesKey, IV初始向量))
加密算法:Aes256/CBC/PKCS7
初始化向量IV:86E2DB6D77B5E9CD
AesKey:Cut32(UpperCase(MD5-32位(UpperCase(sk))))
示例代码:
python
from dahua_iot_client import DeviceCodeEncryptor
encryptor = DeviceCodeEncryptor(
secret_access_key="your_sk",
device_id="your_device_id"
)
# AES256加密(推荐)
dev_code = encryptor.encrypt_aes256("admin123")
# Base64加密
dev_code = encryptor.encrypt_base64("admin123")
DahuaIoTClient 类#统一客户端类,封装所有设备管理API。
参数类型必填说明app_id``str✅产品ID (ProductId)access_key``str✅访问密钥 (AccessKey)secret_key``str✅密钥 (SecretKey)api_base_url``str❌API基础地址(默认: https://open.cloud-dahua.com/)verbose``bool❌是否打印API调用日志(默认:True,SDK集成时建议False)
分类方法说明CLI设备add_device()添加设备add设备verify_device_password()校验设备密码verify设备delete_device()删除设备delete设备get_device_list()查询设备列表list设备get_device_online()查询设备在线状态online设备list_device_details()批量查询设备详细信息details设备check_device_bind()查询设备绑定状态bind设备get_category()查询设备品类category设备get_device_channel_info()获取设备通道信息channels设备modify_device_name()修改设备/通道名称-设备modify_dev_code()修改设备密码-国标get_sip_info()获取国标设备注册信息sip-info国标list_gb_code()获取国标码列表gb-code国标add_gb_device()添加国标设备add-gb国标modify_gb_device()修改国标设备信息modify-gb国标list_gb_device_details()国标设备查询详细信息gb-detailsSD卡get_sd_card_status()获取SD卡状态-SD卡get_sd_card_storage()查询SD卡容量-SD卡list_sd_card_storage()获取SD卡列表-SD卡format_sd_card()格式化SD卡-配置get_ability_status()获取设备使能状态ability配置set_ability_status()设置设备使能状态-配置set_current_utc()设备校时-铃音list_custom_ring()获取铃声列表-铃音add_custom_ring()新增自定义铃声-铃音delete_custom_ring()删除自定义铃声-铃音set_custom_ring()设置铃声-WiFicurrent_device_wifi()获取设备当前连接热点-WiFiwifi_around()获取设备周边热点-WiFicontrol_device_wifi()修改设备连接热点-其他get_sim_signal_strength()获取SIM信号强度-其他image_decrypt()图片解密-消息add_callback_config()添加回调配置-消息message_subscribe()按设备ID订阅消息-消息get_all_callback_config()分页获取回调配置-消息update_subscribe_by_callback_config()根据回调配置更新订阅-消息update_callback_config()更新回调配置-消息delete_callback_config()删除回调配置-消息get_callback_config_info()搜索回调配置信息-消息get_subscribe_info_by_callback_config()搜索已订阅设备消息-消息get_subscribe_info_by_device()按设备ID查询订阅信息-消息get_message_type_page()按设备类别获取消息类型-
DeviceCodeEncryptor 类#设备密码加密工具类。
方法说明encrypt_base64(password)Base64加密encrypt_aes256(password)AES256加密(推荐)
参数简写类型必填说明--help``-h-❌显示帮助信息
子命令说明add添加设备add-gb添加国标设备delete删除设备verify校验设备密码list查询设备列表details查询设备详细信息online查询设备在线状态bind查询设备绑定状态category查询设备品类channels获取设备通道信息ability获取设备使能状态gb-code获取国标码列表sip-info获取国标设备注册信息gb-details查询国标设备详细信息modify-gb修改国标设备信息encrypt加密设备密码
add - 添加设备参数简写类型必填说明--device-id``-d``str✅设备序列号--password``-p``str✅设备密码--category``-c``str❌设备品类编码(默认:IPC)--encrypt``-e``str❌加密方式(base64/aes256,默认:base64)
delete - 删除设备参数简写类型必填说明--device-id``-d``str✅设备序列号
list - 查询设备列表参数简写类型必填说明--page``-p``int❌页码(默认:1)--size``-s``int❌每页条数(默认:10)--device-id``-d``str❌设备序列号(模糊查询)
online - 查询设备在线状态参数简写类型必填说明--device-id``-d``str✅设备序列号
verify - 校验设备密码验证指定设备的密码是否正确(调用 verifyDevCode 接口)。
参数简写类型必填说明--device-id``-d``str✅设备序列号--password``-p``str✅设备密码(明文)--encrypt``-e``str❌加密方式(base64/aes256,默认:base64)bash
# 校验设备密码
python scripts/dahua_iot_client.py verify -d <设备序列号> -p admin123 -e aes256
details - 查询设备详细信息参数说明device_ids设备序列号(可多个,位置参数)bash
python scripts/dahua_iot_client.py details <设备序列号> <设备序列号2>
category - 查询设备品类参数简写说明--primary``-p1级设备类别代码--second``-s2级设备类别代码(如 IPC)--model``-m设备型号
bind - 查询设备绑定状态参数简写必填说明--device-id``-d✅设备序列号
channels - 获取设备通道信息参数简写必填说明--device-id``-d✅设备序列号
ability - 获取设备使能状态参数简写必填说明--device-id``-d✅设备序列号--ability-type``-a✅使能类型(如 localRecord、motionDetect、faceCapture)--channel-id``-c❌通道号(通道级使能需传)
add-gb - 添加国标设备参数简写必填说明--gb-code``-g✅国标码--password``-p✅设备注册密码--channels``-c✅通道总数--encrypt``-e❌加密方式(base64/aes256,默认 base64)--manufacturer``-m❌厂商(Dahua、HIKVSION、UNKNOW)--stream-model``-s❌拉流协议(TCP/UDP)--device-class``-d❌设备类型(NVR/IPC)
gb-code - 获取国标码列表参数简写说明--count``-c查询数量(1-10000,默认 10)--prefix``-p国标码前缀(长度必须 13 位)
sip-info - 获取国标设备注册信息无需参数,返回 Sip 服务器 IP 和端口。
gb-details - 查询国标设备详细信息参数说明device_ids设备序列号(可多个,位置参数)
modify-gb - 修改国标设备信息参数简写必填说明--device-id``-d✅设备序列号--password``-p❌新设备密码--encrypt``-e❌密码加密方式(base64/aes256,默认:base64)--stream-model``-s❌拉流协议(TCP/UDP)
encrypt - 加密设备密码参数简写类型必填说明--password``-p``str✅设备密码--secret-key``-s``str✅SecretKey--device-id``-d``str❌设备序列号--method``-m``str❌加密方式(base64/aes256,默认:base64)
所有 API 响应遵循统一格式:
python
{
"code": "200", # 响应状态码
"success": true, # 响应状态
"data": {}, # 响应数据
"msg": "操作成功" # 响应消息
}
python
{
"success": True,
"code": "200",
"msg": "操作成功",
"data": {
"deviceId": "<设备序列号>",
"deviceName": "",
"channelNum": 1,
"status": 1
}
}
python
{
"success": True,
"code": "200",
"msg": "操作成功",
"data": {
"deviceId": "<设备序列号>",
"online": True
}
}
错误码说明:
200: 成功msg 字段了解错误原因常量名默认值说明DEFAULT_API_BASE_URL``https://open.cloud-dahua.com/API 基础地址TOKEN_EXPIRY_SECONDS``604800Token 有效期(秒) - 7天TIMEOUT_AUTH``60认证超时(秒)TIMEOUT_DEVICE``60设备管理超时(秒)TIMEOUT_CONFIG``60配置超时(秒)TIMEOUT_SD_CARD``60SD卡管理超时(秒)TIMEOUT_FORMAT_SD``120SD卡格式化超时(秒)
安装依赖:
bash
pip install requests pycryptodome
bash
# 添加设备
python scripts/dahua_iot_client.py add -d <设备序列号> -p admin123 -c IPC
# 校验设备密码(验证密码是否正确)
python scripts/dahua_iot_client.py verify -d <设备序列号> -p admin123 -e aes256
# 查询设备在线状态
python scripts/dahua_iot_client.py online -d <设备序列号>
# 查询设备列表/详细信息
python scripts/dahua_iot_client.py list -d <设备序列号前缀>
python scripts/dahua_iot_client.py details <设备序列号>
python
# Python SDK
client = create_client_from_env()
# 获取设备列表
devices = client.get_device_list(page_num=1, page_size=100)
# 批量查询设备详情
device_ids = ['<设备序列号1>', '<设备序列号2>']
details = client.list_device_details(device_ids)
# 删除设备
client.delete_device('<设备序列号>')
python
# 查询SD卡状态
status = client.get_sd_card_status('<设备序列号>')
# 查询SD卡容量
storage = client.get_sd_card_storage('<设备序列号>')
# 格式化SD卡
result = client.format_sd_card('<设备序列号>')
python
# 修改设备名称
client.modify_device_name('<设备序列号>', 'My Camera')
# 启用本地录像
client.set_ability_status(
device_id='<设备序列号>',
ability_type='localRecord',
status='on',
channel_id='0'
)
python
# 添加回调配置(返回的 data 为回调配置ID)
callback = client.add_callback_config(
callback_url='https://your-server.com/callback',
is_push=True
)
callback_config_id = callback['data'] # API 返回的 data 即为 callbackConfigId
# 订阅设备消息
client.message_subscribe(
device_ids=['<设备序列号>'],
message_type_codes=['online', 'offline', 'videoMotion'],
category_code='IPC',
callback_config_id=callback_config_id
)
bash
# 获取国标码
python scripts/dahua_iot_client.py gb-code -c 5
# 获取 Sip 注册信息
python scripts/dahua_iot_client.py sip-info
# 添加国标设备
python scripts/dahua_iot_client.py add-gb -g 34020000001320000001 -p admin123 -c 4 -e aes256
python
# Python SDK
gb_codes = client.list_gb_code(count=10)
sip_info = client.get_sip_info()
result = client.add_gb_device(gb_code='34020000001320000001', device_password='admin123', channel_number=4)
python
# 铃音管理
rings = client.list_custom_ring(device_id, relate_type='device') # relate_type: device/channel
client.add_custom_ring(device_id, name='my_ring', url='https://...', ring_type='custom')
# WiFi 管理
wifi_info = client.current_device_wifi(device_id)
around = client.wifi_around(device_id)
client.control_device_wifi(device_id, ssid='MyWiFi', password='wifi_password')
# 图片解密(image_url 为待解密的图片地址)
decrypted = client.image_decrypt(device_id, image_url='https://...')
⚠️ 不要将真实的 Cloud 凭证提交到 Git!
本项目包含 .gitignore 文件,会自动忽略敏感配置文件。建议:
text
dahua-cloud-open-iot-basic-general-kit/
├── README.md # 快速说明
├── QUICKSTART.md # 5分钟快速入门
├── SKILL.md # 本文件(完整指南)
├── FAQ.md # 常见问题解答
├── .gitignore # Git 忽略规则
├── references/
│ └── api_reference.md # 完整API参考文档(43个接口)
└── scripts/
├── dahua_iot_client.py # 统一客户端(推荐使用)
├── sign_helper.py # 签名工具(旧版,保留兼容)
├── device_code_encrypt.py # 密码加密工具(旧版,保留兼容)
└── requirements.txt # Python依赖
✅ 极简配置 - 仅需要 3 个环境变量 (ProductId, AK, SK)
✅ 单文件实现 - 所有功能集中在一个文件,易于维护
✅ 统一客户端 - 封装所有API,无需关心签名细节
✅ 自动Token管理 - Token自动刷新,无需手动处理
✅ 命令行支持 - 快速操作无需编写代码
✅ Python SDK - 可轻松集成到其他应用
✅ 跨平台支持 - Windows/Linux/Mac 完美运行
✅ GUI 友好 - Windows 图形界面设置环境变量
✅ 轻量依赖 - 仅依赖 requests 和 pycryptodome
✅ 安全可靠 - 标准 API 认证,无密码泄露风险
如果你之前使用 sign_helper.py 和 device_code_encrypt.py,可以这样迁移:
旧版代码:
python
from sign_helper import DahuaAPISigner
from device_code_encrypt import DeviceCodeEncryptor
signer = DahuaAPISigner(access_key, secret_key, product_id)
encryptor = DeviceCodeEncryptor(secret_key, device_id)
# 手动管理Token
auth_headers = signer.sign_for_auth_api()
# ... 手动获取Token ...
# 手动构造请求
business_headers = signer.sign_for_business_api(app_token)
# ... 手动调用API ...
新版代码:
python
from dahua_iot_client import create_client_from_env
# 自动从环境变量读取配置
client = create_client_from_env()
# 自动管理Token,直接调用API
result = client.add_device(
device_id='<设备序列号>',
device_password='admin123'
)
解决方案: 客户端会自动管理Token,在过期前自动刷新,无需手动处理。
检查清单:
可能原因:
方法: 调用 list_device_details() 接口,查看返回的 deviceAbility 或 channelAbility 字段,检查是否包含相应的能力集标识。
方法: 使用 verify 子命令或 verify_device_password() 方法调用 verifyDevCode 接口:
bash
# 命令行
python scripts/dahua_iot_client.py verify -d <设备ID> -p <密码> -e aes256
python
# Python SDK
result = client.verify_device_password(device_id, password, encrypt_method='aes256')
# result['success'] 为 True 表示密码正确
更多常见问题请参阅 FAQ.md。
MIT License