php服務(wù)端,下發(fā)消息到設(shè)備
<?php
header("Content-Type: text/html; charset=utf-8");
include_once './aliyun-openapi-php-sdk/aliyun-php-sdk-core/Config.php';
use \Iot\Request\V20170420 as Iot;
//設(shè)置你的AccessKeyId,AccessSecret,ProductKey,
$accessKeyId = "";
$accessSecret = "";
$ProductKey='';
// 這倆傳過來就行
$deviceName='';
$DeviceSecret="";
$iClientProfile = DefaultProfile::getProfile("cn-shanghai", $accessKeyId, $accessSecret);
$client = new DefaultAcsClient($iClientProfile);
// 發(fā)布消息到設(shè)備并同步返回?cái)?shù)據(jù)
// 文檔: https://help.aliyun.com/document_detail/57241.html?spm=5176.doc57166.2.6.9sc6US
function sendMsg($msg,$callback){
global $client;
global $ProductKey;
global $deviceName;
global $DeviceSecret;
$request = new Iot\RRpcRequest();
$request->setProductKey($ProductKey);
$request->setDeviceName($deviceName);
$request->setRequestBase64Byte(base64_encode($msg));
$request->setTimeout(1000);
$response =$client->getAcsResponse($request);
// print_r(json_encode($response));
//返回格式:{"MessageId":1,"RequestId":"123","PayloadBase64Byte":"base64格式","Success":true,"RrpcCode":"SUCCESS"}
if($response&&$response->Success==true){
$callback(json_decode(base64_decode($response->PayloadBase64Byte)));
}else{
// 返回錯誤消息
echo '{"errno":-1,"msg":"獲取消息失敗"}';
}
}
sendMsg('{"act":1,"channel":1,"Sn":1}',function($data){
print_f($data);
});
?>
node模擬設(shè)備端
var mqtt = require('mqtt');
var crypto = require('crypto'); //加密模塊
var device = {
name: "",
secret: ''
};
var timestamp = Date.now(); //時(shí)間戳
var obj = {
productKey: '', //一個項(xiàng)目只有一個
deviceName: device.name, //需要服務(wù)端 單獨(dú)/批量 注冊到阿里云侨核,
clientId: device.name, //客戶端自表示Id,64字符內(nèi)撼唾,建議是MAC或SN
timestamp: timestamp //時(shí)間戳
};
//---------以下部分生成sign---------------------//
var hmac = crypto.createHmac('sha1', device.secret.toString('ascii'));
function signFn(objs) {
var arr = [];
var str = '';
for (const key in objs) {
if (objs.hasOwnProperty(key)) {
arr.push(key);
}
}
arr.sort(); //按字母排序
arr.map(function (d) {
str += (d + objs[d]); //拼接為:keyvaluekeyvalue
});
hmac.update(encodeURI(str)); //添加需要的加密數(shù)據(jù)
return hmac.digest('hex'); //加密,(hex表示16進(jìn)制)
}
var sign = signFn(obj);
//------以下部分連接mqtt-----------------------------//
var client = mqtt.connect(`mqtt://${obj.productKey}.iot-as-mqtt.cn-shanghai.aliyuncs.com:1883`, {
username: obj.deviceName + "&" + obj.productKey,
password: sign,
clientId: `${obj.clientId}|securemode=3,signmethod=hmacsha1,timestamp=${timestamp}|` //TCP直連模式hmacsha1加密
});
client.on('connect', function () {
client.subscribe(`/sys/${obj.productKey}/${obj.deviceName}/rrpc/request/+`);//+號是通配符,表示消息id
console.log('連接');
});
client.on('message', function (topic, message) {
var msg = JSON.parse(message.toString());// message 是 Buffer
var msgId = topic.split('/').pop(); //需要從取topic中的消息id
console.log('topic:', topic);
console.log('消息id:', msgId);
console.log('消息:',message.toString());
var json=JSON.stringify({
"act":3,
"channel":msg.channel,
"result":0,
"Sn":12345
});
// 發(fā)布,消息id是變化的
client.publish(`/sys/${obj.productKey}/${obj.deviceName}/rrpc/response/${msgId}`, json);
});