STM32移植 MQTT
阿新 • • 發佈:2019-01-24
stm32移植mqtt
- 將MQTTPacket\src目錄下的檔案新增到工程
- MQTTPacket\samples下的transport.c、transport.h新增到工程。
//接收資料,recv函式僅僅是copy資料,真正的接收資料是協議來完成的), recv函式返回其實際copy的位元組數。
int transport_getdata(unsigned char* buf, int count)
{
int rc = 0;
u16 len = 0;
u8 *data = 0;
while(1)
{
if (UART7_RX_STA&0X8000) //接收到一次資料了
{
memcpy(buf, (void*)&UART7_RX_BUF[read_buf_len], count);
read_buf_len += count;
break;
}
delay_ms(10);
}
return count;
}
在需要呼叫的地方實現訂閱釋出和讀取訂閱。
//開啟網路連線
mysock = transport_open(host, port);
if(mysock < 0)
return mysock;
printf("Sending to hostname %s port %d\n", host, port);
//現在將連線字串格式化一下,現在還沒有傳送
len = MQTTSerialize_connect(buf, buflen, &data);
printf("%s",buf);
//現在是資料的傳送
rc = transport_sendPacketBuffer(mysock, buf, len);
/* 等待connack */ //傳送後接收伺服器返回的資料,這裡使用了一個函式的指標,要定義這個指標
if (MQTTPacket_read(buf, buflen, transport_getdata) == CONNACK)//CONNACK – 確認連線請求
{
unsigned char sessionPresent, connack_rc
if (MQTTDeserialize_connack(&sessionPresent, &connack_rc, buf, buflen) != 1 || connack_rc != 0)
{
printf("Unable to connect, return code %d\n", connack_rc);
goto exit;
}
}
else
goto exit;
/* 訂閱 */
topicString.cstring = "substopic";
len = MQTTSerialize_subscribe(buf, buflen, 0, msgid, 1, &topicString, &req_qos);
rc = transport_sendPacketBuffer(mysock, buf, len);
//等待伺服器答覆
//SUBACK 訂閱確認 報文包含一個返回碼清單, 它們指定了 SUBSCRIBE 請求的每個訂閱被授予的最大 QoS 等級。
if (MQTTPacket_read(buf, buflen, transport_getdata) == SUBACK) /* 等待 suback */
{
unsigned short submsgid;
int subcount;
int granted_qos;
rc = MQTTDeserialize_suback(&submsgid, 1, &subcount, &granted_qos, buf, buflen);
if (granted_qos != 0)
{
printf("granted qos != 0, %d\n", granted_qos);
goto exit;
}
}
else
goto exit;
/* 迴圈獲取訊息 on subscribed topic */
// topicString.cstring = "pubtopic";
// while (1)
{
/* transport_getdata() has a built-in 1 second timeout,
your mileage will vary */
if (MQTTPacket_read(buf, buflen, transport_getdata) == PUBLISH)//qos 響應報文,當qos>0時才有響應
{
unsigned char dup;
int qos;
unsigned char retained;
unsigned short msgid;
int payloadlen_in;
unsigned char* payload_in;
int rc;
MQTTString receivedTopic;
rc = MQTTDeserialize_publish(&dup, &qos, &retained, &msgid, &receivedTopic,
&payload_in, &payloadlen_in, buf, buflen);
printf("message arrived %.*s\n", payloadlen_in, payload_in); //訊息到達
}
printf("publishing reading\n");//讀取釋出
//下面兩行是用來發布訊息。這裡釋出,上面訂閱,就形成了一個迴圈。
len = MQTTSerialize_publish(buf, buflen, 0, 0, 0, 0, topicString, (unsigned char*)payload, payloadlen);
rc = transport_sendPacketBuffer(mysock, buf, len);
delay_ms(1000);
}
while(1)
{
len = MQTTSerialize_pingreq(buf, buflen);//傳送心跳
rc = transport_sendPacketBuffer(mysock, buf, len);//傳送
delay_s(55);
printf("心跳");
}
exit:
transport_close(mysock);