美文网首页
阿里云php同步方式获取mqtt消息

阿里云php同步方式获取mqtt消息

作者: adtk | 来源:发表于2017-12-05 18:20 被阅读0次

    php服务端,下发消息到设备

    <?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;
    
    //设置你的AccessKeyId,AccessSecret,ProductKey,
        $accessKeyId = "";
        $accessSecret = "";
        $ProductKey='';
        
        // 这俩传过来就行
        $deviceName='';
        $DeviceSecret="";
        
        $iClientProfile = DefaultProfile::getProfile("cn-shanghai", $accessKeyId, $accessSecret);
        $client = new DefaultAcsClient($iClientProfile);
        
        // 发布消息到设备并同步返回数据
        // 文档: 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模拟设备端

    var mqtt = require('mqtt');
    var crypto = require('crypto'); //加密模块
    var device = {
        name: "",
        secret: ''
    };
    var timestamp = Date.now(); //时间戳
    var obj = {
        productKey: '', //一个项目只有一个
        deviceName: device.name, //需要服务端 单独/批量 注册到阿里云,
        clientId: device.name, //客户端自表示Id,64字符内,建议是MAC或SN
        timestamp: timestamp //时间戳
    };
    
    //---------以下部分生成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)); //添加需要的加密数据
        return hmac.digest('hex'); //加密,(hex表示16进制)
    }
    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
            });
            // 发布,消息id是变化的
            client.publish(`/sys/${obj.productKey}/${obj.deviceName}/rrpc/response/${msgId}`, json);
    
    });
    

    相关文章

      网友评论

          本文标题:阿里云php同步方式获取mqtt消息

          本文链接:https://www.haomeiwen.com/subject/figcixtx.html