背景描述:
使用LinkIT One基于paho的mqtt客户端,当代码执行到rc=client.connect(data);,超时然后返回rc=-1。
测试连接的服务端包括IBM Watson、中移OneNet还有自己搭建的mosquitto,都是一样的错误。查了一下paho的实现代码,把MQTTClient.h中的connect实现改了一下就connect成功了,但subscribe又超时并返回错误了(如下所示)。
在网上查到了和我类似的错误,貌似LinkIT One并不能使用paho的mqtt。但将mqtt客户端换成pubsub后却能够正常工作。
下面是我的测试代码(mqtt服务器是本地局域网的mosquitto)
#include <LWiFi.h>
#include <LWiFiClient.h>
#include <IPStack.h>
#include <Countdown.h>
#include <MQTTClient.h>
#define WIFI_AP "SSID"
#define WIFI_PASSWORD "PASSWD"
#define WIFI_AUTH LWIFI_WPA
int port = 1883;
char servername[]="10.214.149.119";
char clientName[] = "myaccount";
char topicName[] = "@tp";
char userName[] = "myaccount";
char password[] = "12345";
LWiFiClient tcpClient;
IPStack ipstack(tcpClient);
MQTT::Client<IPStack, Countdown, 200> client = MQTT::Client<IPStack, Countdown, 200>(ipstack);
void messageArrived(MQTT::MessageData& md){
MQTT::Message &message = md.message;
char res[100];
int len = message.payloadlen;
strncpy(res, (char*)message.payload, len);
res[len] = '\0';
Serial.println(res);
}
void setup(){
Serial.begin(9600);
while(!Serial.available());
InitWiFi();
if (!client.isConnected())
reconnect();
int rc = client.subscribe(topicName, MQTT::QOS0, messageArrived);
if (rc != 0)
Serial.println(String("rc from MQTT subscribe is ")+rc);
else
Serial.println(String("rc from MQTT subscribe is ")+rc);
}
void loop(){
Serial.println("loop");
client.yield(100);
delay(2000);
}
void InitWiFi(){
LWiFi.begin();
// Keep retrying until connected to AP
Serial.println("Connecting to AP");
while (0 == LWiFi.connect(WIFI_AP, LWiFiLoginInfo(WIFI_AUTH, WIFI_PASSWORD)))
{
Serial.println("Retry connect AP ... ");
delay(1000);
}
Serial.println("Connected to AP");
}
void reconnect() {
// Loop until we're reconnected
if(!client.isConnected()) {
int rc = ipstack.connect(servername, port);
if (rc == 1){
Serial.println("IPStack Success");
}else{
Serial.println("IPStack Failed");
}
Serial.print("Connecting to IOT platform ...");
MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
data.MQTTVersion = 4;
data.clientID.cstring = clientName;
data.username.cstring = userName;
data.password.cstring = password;
rc = client.connect(data);
if (rc == 0) {
Serial.println( "[DONE]" );
} else {
Serial.println( "[FAILED]");
delay(5000);
}
}
}
我的问题是:
有没有大神使用LinkIT One基于paho的mqtt实现了客户端,可以正常pub/sub话题,测试的mqtt代理可以是mosquitto或IBM Watson或中移OneNet?允许修改paho或LWiFiClient的源码?(我只要基于paho的实现)
提示:
1.通过之前在Arduino UNO、BeagleBone Black、树莓派2的实验感觉各种mqtt的代理基本都一样的,能在mosquitto上测试通过的基本都能在IBM Watson或OneNet上测试通过;
2.LinkIt One用pubsub测试没有问题,这说明LWiFiClient很大概率是没问题的,估计要修改paho的实现代码