使用SDK接入
KLink MQTT基于MQTT协议之上进行数据格式定义,设备开发者可以参考KLink与MQTT协议开源实现Eclipse Paho自主开发。
准备工作: 在IoT OS后台创建MQTT协议登录不校验产品并创建设备。
- 1.用户可在github获取paho.mqtt.c开源实现,使用gcc编译客户端,操作如下:
git clone https://github.com/eclipse/paho.mqtt.c.git
cd paho.mqtt.c
make
2.进入samples文件夹编辑修改MQTTClient_publish.c文件(修改连接IP、clientid、topic见注释)
/******************************************************************************* * Copyright (c) 2012, 2017 IBM Corp. * * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * and Eclipse Distribution License v1.0 which accompany this distribution. * * The Eclipse Public License is available at * http://www.eclipse.org/legal/epl-v10.html * and the Eclipse Distribution License is available at * http://www.eclipse.org/org/documents/edl-v10.php. * * Contributors: *Ian Craggs - initial contribution *******************************************************************************/ #include <stdio.h> #include <stdlib.h> #include <string.h> #include "MQTTClient.h" #define ADDRESS "test-mqtt.hekr.me:1883"//定义MQTT设备对接域名与端口 #define CLIENTID"dev:{pk}:{devId}"//定义客户端链接识别码,参数之间用:隔开,括号中填入平台上创建的产品PK和设备ID,括号为占位符,参数填入后请删除括号 #define TOPIC "up/dev/{pk}/{devId}"//定义数据发布主题,括号中填入平台上创建的产品PK和设备ID,括号为占位符,参数填入后请删除括号 #define PAYLOAD "Hello World!"//定义上报内容 #define QOS 1 #define TIMEOUT 10000L int main(int argc, char* argv[]) { MQTTClient client; MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer; MQTTClient_message pubmsg = MQTTClient_message_initializer; MQTTClient_deliveryToken token; int rc; MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL); conn_opts.keepAliveInterval = 20; conn_opts.cleansession = 1; if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) { printf("Failed to connect, return code %d\n", rc); exit(EXIT_FAILURE); } pubmsg.payload = PAYLOAD; pubmsg.payloadlen = (int)strlen(PAYLOAD); pubmsg.qos = QOS; pubmsg.retained = 0; MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token); printf("Waiting for up to %d seconds for publication of %s\n" "on topic %s for client with ClientID: %s\n", (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID); rc = MQTTClient_waitForCompletion(client, token, TIMEOUT); printf("Message with delivery token %d delivered\n", token); MQTTClient_disconnect(client, 10000); MQTTClient_destroy(&client); return rc; }
3.在sample目录用以下命令进行编译:
gcc -I../ -L../../../paho.mqtt.c/build/output/ MQTTClient_subscribe.c -lpaho-mqtt3c -o MQTTTest -lrt
4.编译完成后运行可执行文件:
./MQTTTest
5.成功运行后可在IoT OS后台上下行数据中查询到相关设备的登录信息和数据上报信息。
注: 若在IoT OS后台创建的是MQTT协议登录需校验产品,则2.2中的代码需要在44行后增加两行:
conn_opts.username = &USERNAME;//定义MQTT登录用户名
conn_opts.password = &PASSWORD;//定义MQTT登录用户密码
【注】其中的USERNAME与PASSWORD需根据对应校验规则进行拼接计算,计算方式参考。