物联网PHP SDK使用指南
1. SDK简介
物联网PHP SDK是一个用于访问DDIOT物联网平台的PHP开发工具包,提供了简单易用的接口,帮助开发者快速集成DDIOT平台的功能。
1.1 主要功能
- 设备管理:添加、删除、修改、查询设备
- 数据上报:设备状态数据上报
- 命令下发:向设备发送控制命令
- 状态查询:查询设备实时状态
- 临时秘钥管理:自动获取和管理临时秘钥
1.2 技术特点
- 支持RESTful API调用
- 自动签名和认证
- 环境切换(测试/生产)
- 错误处理和异常捕获
- 与Yii2框架深度集成
2. 安装和配置
2.1 安装方式
2.1.1 直接集成
将SDK目录复制到项目中,通常放在common/components/ddiot目录下。
2.1.2 Composer安装
composer require ddiot/sdk
2.2 配置项
SDK需要以下配置项:
| 配置项 | 描述 | 必填 | 默认值 |
|---|---|---|---|
app_id | 应用ID | 是 | - |
project_sn | 项目编号 | 是 | - |
is_dev | 是否开发环境 | 否 | true |
api_url | 生产环境地址 | 否 | https://iot.ddicms.com |
api_test_url | 测试环境地址 | 否 | https://testiot.ddicms.cn |
2.3 环境变量配置
在Yii2项目中,可以通过环境变量配置SDK:
// .env 文件
DDIOT_APP_ID=your_app_id
DDIOT_PROJECT_SN=your_project_sn
DDIOT_PROJECT_DEV=1 // 1为测试环境,0为生产环境
3. 基础使用
3.1 初始化客户端
use ddiot\http\AipBase;
// 初始化客户端
$client = new AipBase('1.0.0');
// 设置配置
$config = [
'app_id' => 'your_app_id',
'project_sn' => 'your_project_sn',
'is_dev' => true, // 测试环境
];
$client->setConfig($config);
3.2 发送请求
3.2.1 POST请求
try {
$data = [
'device_id' => 'test_device',
'status' => 'online'
];
$result = $client->post('/api/device/update', $data);
print_r($result);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
3.2.2 GET请求
try {
$params = [
'device_id' => 'test_device'
];
$result = $client->get('/api/device/info', $params);
print_r($result);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
3.2.3 PUT请求
try {
$data = [
'device_id' => 'test_device',
'name' => '新设备名称'
];
$result = $client->put('/api/device/update', $data);
print_r($result);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
3.2.4 DELETE请求
try {
$params = [
'device_id' => 'test_device'
];
$result = $client->delete('/api/device/delete', $params);
print_r($result);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
4. 与Yii2框架集成
4.1 使用DdiotTrait
SDK提供了DdiotTrait,可以快速集成到Yii2控制器中:
<?php
namespace app\controllers;
use yii\web\Controller;
use common\traits\DdiotTrait;
class IotController extends Controller
{
use DdiotTrait;
// 控制器方法
}
4.2 自动初始化
DdiotTrait会在控制器的beforeAction方法中自动初始化SDK:
- 从缓存中获取临时秘钥
- 如果缓存中没有秘钥,自动请求新的临时秘钥
- 设置SDK配置
- 处理异常并返回错误信息
4.3 控制器示例
<?php
namespace addons\diandi_mall\api;
use common\controllers\addons\ApiController;
use common\traits\DdiotTrait;
use Yii;
class DeviceController extends ApiController
{
use DdiotTrait;
/**
* 获取设备列表
* @return array
*/
public function actionIndex()
{
$Res = $this->client->post('/device/getAll', Yii::$app->request->queryParams);
return $this->success($Res);
}
/**
* 获取设备详情
* @param int $id
* @return array
*/
public function actionView($id)
{
$Res = $this->client->get('/device/getOne', [
'id' => $id,
]);
return $this->success($Res);
}
/**
* 创建设备
* @return array
*/
public function actionCreate()
{
$data = Yii::$app->request->post();
$Res = $this->client->post('/device/create', $data);
return $this->success($Res);
}
/**
* 更新设备
* @param int $id
* @return array
*/
public function actionUpdate($id)
{
$data = Yii::$app->request->post();
$data['id'] = $id;
$Res = $this->client->post('/device/update', $data);
return $this->success($Res);
}
/**
* 删除设备
* @param int $id
* @return array
*/
public function actionDelete($id)
{
$Res = $this->client->post('/device/delete', [
'id' => $id,
]);
return $this->success($Res);
}
}
5. 高级功能
5.1 临时秘钥管理
SDK会自动管理临时秘钥,包括获取、缓存和过期处理:
// 获取临时秘钥
$tempSecret = $this->getTempSecret($config);
// 临时秘钥会被缓存,有效期由服务端返回
// 当秘钥过期时,SDK会自动重新获取
5.2 环境切换
可以通过配置项切换测试环境和生产环境:
// 测试环境
$config['is_dev'] = true;
// 生产环境
$config['is_dev'] = false;
5.3 超时设置
可以设置请求超时时间:
// 设置连接超时时间(毫秒)
$client->setConnectionTimeoutInMillis(5000);
// 设置响应超时时间(毫秒)
$client->setSocketTimeoutInMillis(10000);
5.4 代理设置
可以设置HTTP代理:
// 设置代理
$client->setProxies([
'http' => 'http://proxy.example.com:8080',
'https' => 'https://proxy.example.com:8080'
]);
6. 错误处理
6.1 异常捕获
SDK使用异常机制处理错误,建议使用try-catch捕获异常:
try {
$result = $client->post('/api/device/status', $data);
// 处理成功响应
} catch (Exception $e) {
// 处理错误
echo "Error: " . $e->getMessage() . "\n";
// 记录错误日志
Yii::error($e->getMessage(), 'iot');
}
6.2 常见错误
| 错误码 | 描述 | 解决方案 |
|---|---|---|
| 400 | 请求参数错误 | 检查请求参数是否正确 |
| 401 | 认证失败 | 检查app_id和app_secret是否正确 |
| 403 | 权限不足 | 检查用户权限 |
| 404 | 接口不存在 | 检查API路径是否正确 |
| 500 | 服务器内部错误 | 联系物联网平台技术支持 |
| 90012 | 临时秘钥过期 | SDK会自动重新获取秘钥 |
| 90005 | 签名错误 | 检查app_secret是否正确 |
7. 性能优化
7.1 缓存策略
SDK会缓存临时秘钥,减少网络请求:
- 临时秘钥缓存时间由服务端返回
- 当秘钥即将过期时,SDK会自动重新获取
- 当秘钥过期时,会清除缓存并重新获取
7.2 批量操作
对于多个设备的操作,建议使用批量接口:
// 批量获取设备状态
$data = [
'device_ids' => ['dev1', 'dev2', 'dev3']
];
$result = $client->post('/device/batchStatus', $data);
7.3 异步请求
对于非实时操作,可以使用异步请求:
// 异步发送命令
$data = [
'device_id' => 'dev1',
'command' => 'restart',
'async' => true
];
$result = $client->post('/device/sendCommand', $data);
8. 最佳实践
8.1 代码组织
- 将SDK配置放在配置文件中
- 使用Trait统一管理SDK实例
- 按功能模块组织控制器
- 封装常用操作为服务层
8.2 安全建议
- 不要在代码中硬编码app_secret
- 使用环境变量或配置文件存储敏感信息
- 定期更新app_secret
- 限制API访问权限
8.3 调试建议
- 使用测试环境进行开发和调试
- 开启日志记录
- 使用Postman等工具测试API
- 检查网络连接和防火墙设置
9. 常见问题
9.1 连接失败
问题:无法连接到物联网平台
解决方案:
- 检查网络连接
- 检查防火墙设置
- 确认环境配置正确
- 检查API地址是否可访问
9.2 认证失败
问题:收到401错误
解决方案:
- 检查app_id是否正确
- 检查app_secret是否正确
- 确认临时秘钥是否过期
- 检查签名是否正确
9.3 设备无响应
问题:设备不响应命令
解决方案:
- 检查设备是否在线
- 检查设备网络连接
- 检查命令格式是否正确
- 检查设备是否支持该命令
9.4 数据上报失败
问题:设备数据上报失败
解决方案:
- 检查数据格式是否正确
- 检查设备是否有上报权限
- 检查网络连接
- 检查数据大小是否超过限制
10. 示例代码
10.1 基础使用示例
<?php
use ddiot\http\AipBase;
use Exception;
// 初始化SDK
$client = new AipBase('1.0.0');
// 配置
$config = [
'app_id' => 'your_app_id',
'project_sn' => 'your_project_sn',
'is_dev' => true,
];
$client->setConfig($config);
// 设置app_secret(临时秘钥)
$client->setAppSecret('your_app_secret');
// 发送请求
try {
// 获取设备列表
$devices = $client->get('/device/getAll', []);
print_r($devices);
// 获取设备详情
$device = $client->get('/device/getOne', ['id' => 1]);
print_r($device);
// 创建设备
$newDevice = $client->post('/device/create', [
'name' => '测试设备',
'device_type' => 'temperature',
'location' => '办公室'
]);
print_r($newDevice);
} catch (Exception $e) {
echo "Error: " . $e->getMessage() . "\n";
}
10.2 Yii2集成示例
<?php
namespace addons\diandi_mall\api;
use common\controllers\addons\ApiController;
use common\traits\DdiotTrait;
use Yii;
class IotController extends ApiController
{
use DdiotTrait;
/**
* 获取设备列表
* @return array
*/
public function actionDeviceList()
{
$params = Yii::$app->request->queryParams;
$Res = $this->client->post('/device/getAll', $params);
return $this->success($Res);
}
/**
* 发送设备命令
* @return array
*/
public function actionSendCommand()
{
$data = Yii::$app->request->post();
$Res = $this->client->post('/device/sendCommand', $data);
return $this->success($Res);
}
/**
* 获取设备数据
* @param int $deviceId
* @return array
*/
public function actionDeviceData($deviceId)
{
$Res = $this->client->get('/device/getData', [
'device_id' => $deviceId,
'start_time' => Yii::$app->request->get('start_time'),
'end_time' => Yii::$app->request->get('end_time'),
]);
return $this->success($Res);
}
}
11. 技术支持
11.1 联系我们
- 官方网站:https://iot.ddicms.com
- 技术支持邮箱:support@ddicms.com
- 技术支持电话:400-123-4567
11.2 反馈问题
当遇到问题时,请提供以下信息:
- SDK版本
- 错误信息和堆栈跟踪
- 请求参数和响应结果
- 环境信息(PHP版本、操作系统等)
- 复现步骤
12. 版本历史
| 版本 | 日期 | 变更内容 |
|---|---|---|
| 1.0.0 | 2025-01-01 | 初始版本 |
| 1.0.1 | 2025-02-15 | 修复临时秘钥管理问题 |
| 1.0.2 | 2025-03-30 | 优化错误处理和日志记录 |
| 1.1.0 | 2025-05-10 | 添加批量操作接口 |
13. 许可证
MIT License
Copyright (c) 2025 DDICMS
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.
