Qt基于开源MQTT自主接入阿里云IoT平台
一、下载qmqtt源码
下载地址:https://github.com/emqtt/qmqtt
二、qmqtt库安装,不想自己编译的,可以直接下载:https://download.youkuaiyun.com/download/miaoliang_happy/11181273
三、代码示例
1、根据三元组信息计算登录阿里云Iot平台的必要参数 代码片
.
// 三元组信息设置
ProductKey="xxxxxxxx";//需要跟阿里云Iot平台一致;
DeviceName="xxxxxxxx";//需要跟阿里云Iot平台一致;
DeviceSecret="xxxxxxxx";//需要跟阿里云Iot平台一致;
RegionId="cn-shanghai";
PubTopic = "/sys/" + ProductKey + "/" + DeviceName + "/thing/event/property/post";//发布topic
SubTopic = "/sys/" + ProductKey + "/" + DeviceName + "/thing/service/property/set";//订阅topic
QString targetServer = ProductKey + ".iot-as-mqtt." + RegionId + ".aliyuncs.com";//域名
QString clientId="ts1234";//这里随便写,最好是设备的Mac地址
QString signmethod = "hmacsha1";
QString timestamp ="789";//这里随便写,表示当前时间毫秒值
QString message ="clientId"+clientId+"deviceName"+DeviceName+"productKey"+ProductKey+"timestamp"+timestamp;
2、连接阿里云 `代码片`.
client = new QMQTT::Client(targetServer, 1883,0,false);//连接阿里云
connect(client, SIGNAL(connected()), this, SLOT(mqttConnectSuccess()));//连接成功,打印SUCCESS
connect(client, SIGNAL(disconnected()), this, SLOT(mqttDisconnect()));//连接失败,打印Disconnect
client->setUsername(DeviceName + "&" + ProductKey);
client->setClientId(clientId + "|securemode=3,signmethod=" + signmethod + ",timestamp="+timestamp+ "|");
//QMessageAuthenticationCode::hash()加密计算,获取用户登录密码
client->setPassword(QMessageAuthenticationCode::hash(message.toLocal8Bit(), DeviceSecret.toLocal8Bit(), QCryptographicHash::Sha1).toHex());
client->connectToHost();//连接阿里云
3、发布消息 `代码片`.
QMQTT::Message msg;
QString payload="{'params':{'Temperature':20.9,'Humidity':42}}";//测试Temperature=20.9 ,Humidity=42
msg.setTopic(PubTopic);
msg.setPayload(payload.toLocal8Bit());
client->publish(msg);