第一步:机器添加到阿里云物联网平台 确保设备在线
第二步:测试给机器发送指令(可以先用阿里云提供的openAPI 进行测试)
阿里云OPENAPI
阿里云的composer
composer require alibabacloud/iot-20180120 3.0.10
发送指令代码
<?php
/*
* @s: ========{================================================>
* @version: 1.1.1
* @Name: 文件:
* @Author: Fcy
* @Date: 2022-10-20 16:13:04
* @FilePath: /CarWash/application/api/controller/Order.php
* @E: ========{================================================>
*/
namespace app\api\controller;
use AlibabaCloud\SDK\Iot\V20180120\Iot;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Iot\V20180120\Models\RRpcRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use app\common\controller\Api;
use think\Db;
class Order extends Api
{
// 无需登录的接口,*表示全部
protected $noNeedLogin = ['*'];
// 无需鉴权的接口,*表示全部
protected $noNeedRight = ['*'];
/**
* @S: ----{--------------------------->
* @Name: 方法: 创建订单
* @Author: Fcy
* @return {*}
* @Date: 2022-10-22 10:45:02
* @D: ----{--------------------------->
*/
public function creaetOrder()
{
$order_id = "CX".date('YmdHis',time()).rand(00000,99999).getRandChar(8);
$member_balance = 0;//会员余额(单位分,仅在界面上显示,不参与任何业务处理),可选
$prepay_money = 0;//会员折扣比例(95表示9.5折优惠,默认100表示没有优惠),可选。
//这里一定要是json字符串 不然报错
$orderRequestBase64Byte = '{"version":"2.0","method":"create_order","params":{"order_id": "'.$order_id.'","member_balance": '.$member_balance.',"prepay_money": '.$prepay_money.'}}';
//这里 ProductKey 和 DeviceName是你添加设备到阿里云上 自动生成的
//base64_encode($orderRequestBase64Byte) 这里一定要base64加密
$resOrder = $this->main('ProductKey','DeviceName',base64_encode($orderRequestBase64Byte));
//返回的是个对象
$dataOrder = get_object_vars($resOrder);
//进行解密 json 转数组处理数据
$results = json_decode(base64_decode($dataOrder['payloadBase64Byte'],true),true);
if($results['code'] == 200){
if($results['data']['created'] == 1){
$this->success('成功',['order'=>$order_id]);
}else{
$this->error('创建订单失败3',[]);
}
}
}
//下面就是阿里云的demo
/**
* 使用AK&SK初始化账号Client
* @param string $accessKeyId
* @param string $accessKeySecret
* @return Iot Client
*/
public static function createClient($accessKeyId, $accessKeySecret){
$config = new Config([
// 您的 AccessKey ID
"accessKeyId" => $accessKeyId,
// 您的 AccessKey Secret
"accessKeySecret" => $accessKeySecret
]);
// 访问的域名 根据自己阿里云进行修改
$config->endpoint = "iot.cn-shanghai.aliyuncs.com";
return new Iot($config);
}
/**
* @param string[] $args
* @return void
*/
public static function main($productKey,$deviceName,$requestBase64Byte){
$client = self::createClient($accessKeyId, $accessKeySecret);
$RRpcRequest = new RRpcRequest([
"iotInstanceId" => "iot-06z00gw53d0sa7k",
"productKey" => $productKey,
"deviceName" => $deviceName,
"timeout" => 1000,
"requestBase64Byte" => $requestBase64Byte
]);
$runtime = new RuntimeOptions([]);
try {
// 复制代码运行请自行打印 API 的返回值
$res = $client->rRpcWithOptions($RRpcRequest, $runtime);
return $res->body;
}
catch (Exception $error) {
if (!($error instanceof TeaError)) {
$error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
return $error;
}
// 如有需要,请打印 error
Utils::assertAsString($error->message);
return $error->message;
}
}
}
第三步:接口机器上行的消息
这里一定要添加一个自定义的topic 用于接收设备消息
我是用的AMQP接收的
PHP SDK 参考文档
这里的sdk 阿里云没有参考的OPENAPI
完全要按照SDK 进行编写
composer require stomp-php/stomp-php 5.0.0
这里可以直接composer sdk。然后测试运行
式例:
然后直接在终端 直接 php new.php
具体代码体现
<?php
/*
* @s: ========{================================================>
* @version: 1.1.1
* @Name: 文件:
* @Author: Fcy
* @Date: 2022-10-24 16:30:26
* @FilePath: /CarWash/application/command/AliSub.php
* @E: ========{================================================>
*/
namespace app\command;
use think\console\Command;
use think\console\Input;
use think\console\Output;
use Stomp\Client;
use Stomp\Network\Observer\Exception\HeartbeatException;
use Stomp\Network\Observer\ServerAliveObserver;
use Stomp\StatefulStomp;
use think\Db;
class AliSub extends Command
{
protected $accessKey = "";
protected $accessSecret = "";
protected $consumerGroupId = "";
protected $clientId = "";//这里这个值随意写
protected $iotInstanceId = "";
//签名方法:支持hmacmd5,hmacsha1和hmacsha256。
protected $signMethod = "hmacsha1";
protected function configure()
{
// 指令配置
$this->setName('alisub');
// 设置参数
}
protected function execute(Input $input, Output $output)
{
// 指令输出
$timeStamp =round(microtime(true) * 1000);
$userName = $this->clientId . "|authMode=aksign"
. ",signMethod=" . $this->signMethod
. ",timestamp=" . $timeStamp
. ",authId=" . $this->accessKey
. ",iotInstanceId=" . $this->iotInstanceId
. ",consumerGroupId=" . $this->consumerGroupId
. "|";
$signContent = "authId=" . $this->accessKey . "×tamp=" . $timeStamp;
$password = base64_encode(hash_hmac("sha1", $signContent, $this->accessSecret, $raw_output = TRUE));
//接入域名,请参见AMQP客户端接入说明文档。 有不知道的可以问我
$client = new Client('ssl://iot-06z00gw53d0sa7k.amqp.iothub.aliyuncs.com:61614');
$sslContext = ['ssl' => ['verify_peer' => true, 'verify_peer_name' => false], ];
$client->getConnection()->setContext($sslContext);
$observer = new ServerAliveObserver();
$client->getConnection()->getObservers()->addObserver($observer);
//心跳设置,需要云端每30s发送一次心跳包。
$client->setHeartbeat(0, 30000);
$client->setLogin($userName, $password);
try {
$client->connect();
}
catch(StompException $e) {
echo "failed to connect to server, msg:" . $e->getMessage() , PHP_EOL;
}
//无异常时继续执行。
$stomp = new StatefulStomp($client);
$stomp->subscribe('/topic/#');
echo "创建链接".'_cx';
while (true) {
try {
// 检查连接状态
if (!$client->isConnected()) {
echo "connection not exists, will reconnect after 10s.", PHP_EOL;
sleep(10);
$client->connect();
$stomp->subscribe('/topic/#');
echo "connect success", PHP_EOL;
}
//处理消息业务逻辑。
// 接收 $stomp->read()的返回值 就是机器消息
echo $stomp->read();
}
catch(HeartbeatException $e) {
echo 'The server failed to send us heartbeats within the defined interval.', PHP_EOL;
$stomp->getClient()->disconnect();
} catch(\Exception $e) {
echo 'process message occurs error: '. $e->getMessage() , PHP_EOL;
$stomp->getClient()->disconnect();
}
}
}
}
到这里接收指令 和发送指定就全部搞定了
说真的 石斑鱼那边技术就是一个屎 什么都不告诉你 只要问技术问题 就装死不回话
这是我在对接期间 和他们技术的部分对话 真的全程在装死 很气人