81 lines
1.8 KiB
PHP
81 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace app\common\service\iot;
|
|
|
|
use think\facade\Config;
|
|
use app\common\service\HttpService;
|
|
|
|
class IotService
|
|
{
|
|
/**
|
|
* @var HttpService HTTP服务
|
|
*/
|
|
protected $httpService;
|
|
|
|
/**
|
|
* @var array 配置
|
|
*/
|
|
protected $config;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->httpService = new HttpService();
|
|
$this->config = $this->getConfig();
|
|
}
|
|
|
|
/**
|
|
* 控制设备开关
|
|
*/
|
|
public function controlDevice(string $deviceId, int $powerState)
|
|
{
|
|
// 验证参数
|
|
if (empty($deviceId)) {
|
|
throw new \Exception('未配置空开设备');
|
|
}
|
|
|
|
if (!in_array($powerState, [0, 1])) {
|
|
throw new \Exception('电源状态值无效');
|
|
}
|
|
|
|
// 生成签名
|
|
$timestamp = time();
|
|
$sign = $this->generateSign($timestamp);
|
|
|
|
// 构建URL
|
|
$url = "{$this->config['base_url']}/{$this->config['app_key']}/device/control/?sign={$sign}&ts={$timestamp}";
|
|
|
|
// 构建请求数据
|
|
$data = [
|
|
'device' => $deviceId,
|
|
'power' => $powerState
|
|
];
|
|
|
|
// 发送请求
|
|
return $this->httpService->json($url, 'POST', $data);
|
|
}
|
|
|
|
/**
|
|
* 生成签名
|
|
*/
|
|
protected function generateSign(int $timestamp): string
|
|
{
|
|
$appSecret = $this->config['app_secret'];
|
|
return md5(md5($appSecret) . $timestamp);
|
|
}
|
|
|
|
/**
|
|
* 获取配置
|
|
*/
|
|
protected function getConfig(): array
|
|
{
|
|
|
|
$config = Config::get('door.other', []);
|
|
|
|
// 优先从配置读取,没有则使用默认值
|
|
return [
|
|
'base_url' => 'https://iot-api.unisoft.cn',
|
|
'app_key' => 'ptyVWcgl9p',
|
|
'app_secret' => 'c9fc117f9ec942449c7e61812cd245b4',
|
|
];
|
|
}
|
|
} |