是不是还在为找源码而痛苦,这里就要现成,正所谓:前人栽树后人乘凉,估计老铁这会已经找累了吧(哈哈哈哈);
废话不多说,上源码,稍等!!!这不点一个赞支持一下吗???
这两个例子都可以;建议使用第一个,别问为什么,因为我使用的是第一个;
MQTT连接平台的关键代码:很关键
mqtt_params.handle_event.h_fp = example_event_handle;//example_event_handle 这个函数是回调函数,当你订阅平台后,平台会给你返回一个订阅响应 SUB_ACK对应一个数字;可以跳到这里面自己看一下
mqtt_params.handle_event.pcontext = NULL;
pclient = IOT_MQTT_Construct(&mqtt_params);//IOT_MQTT_Construct 特别关键 ,里面进行了SSL加密 对mqtt 进行初始化,连接服务器
if (NULL == pclient) {
EXAMPLE_TRACE("MQTT construct failed");
return -1;
}
res = example_subscribe(pclient);//订阅你需要的主题
if (res < 0) {
IOT_MQTT_Destroy(&pclient);
return -1;
}
while (1) {
if (0 == loop_cnt % 20) {
example_publish(pclient);//发送你想要发送的消息嘿嘿
}
IOT_MQTT_Yield(pclient, 200);
loop_cnt += 1;
}
example_subscribe
这个函数的重要性不仅仅是 订阅这么简单,他还负责接收来自平台的消息;看代码!!!
int example_subscribe(void *handle)
{
int res = 0;
char product_key[IOTX_PRODUCT_KEY_LEN] = {0};
char device_name[IOTX_DEVICE_NAME_LEN] = {0};
const char *fmt = "/%s/%s/user/get";
char *topic = NULL;
int topic_len = 0;
HAL_GetProductKey(product_key);
HAL_GetDeviceName(device_name);
topic_len = strlen(fmt) + strlen(product_key) + strlen(device_name) + 1;
if (topic_len > CONFIG_MQTT_TOPIC_MAXLEN) {
HAL_Printf("topic too long\n");
return -1;
}
topic = g_topic_name;
memset(topic, 0, CONFIG_MQTT_TOPIC_MAXLEN);
HAL_Snprintf(topic, topic_len, fmt, product_key, device_name);
res = IOT_MQTT_Subscribe(handle, topic, IOTX_MQTT_QOS0, example_message_arrive, NULL);
if (res < 0) {
HAL_Printf("subscribe failed\n");
return -1;
}
return 0;
}
void example_message_arrive(void *pcontext, void *pclient, iotx_mqtt_event_msg_pt msg)
{
iotx_mqtt_topic_info_t *topic_info = (iotx_mqtt_topic_info_pt) msg->msg;
switch (msg->event_type) {
case IOTX_MQTT_EVENT_PUBLISH_RECEIVED:
/* print topic name and topic message */
HAL_Printf("Message Arrived: \n");
HAL_Printf("Topic : %.*s\n", topic_info->topic_len, topic_info->ptopic);
HAL_Printf("Payload: %.*s\n", topic_info->payload_len, topic_info->payload);
HAL_Printf("\n");
break;
default:
break;
}
}
example_message_arrive ()这个函数就是接收来自平台的消息,ok打完收工;