蚊子C ++客户端未将数据发送到AWS IOT

时间:2018-08-16 20:59:34

标签: c++ amazon-web-services mosquitto aws-iot libmosquitto

我已经创建了一个简单的c ++应用程序,用于将数据从树莓派发送到AWS IoT通道。我从来没有从树莓派发布数据的主题中收到任何消息。
代码如下:

int main(int argc, char* argv[]) {
  int res = 0;
  NRMKMqttWrapper * mqttHdl;
  mqttHdl = new NRMKMqttWrapper("clientid1");
  res = mqttHdl->tls_opts_set(1, "tlsv1.2", NULL);
  std::cout<<"tls_opts_set response: "<<res<<::std::endl;
  std::cout<<"Initialize tls"<<std::endl;
  res = mqttHdl->tls_set("tls/ca/Public-Primary-Certification-Authority-G5.pem", NULL, "tls/xxxx-certificate.pem", "tls/xxxx-private.pem", NULL);
  std::cout<<"TLS set certificate response: "<<res<<::std::endl;
  res = mqttHdl->connect("xxxx.iot.eu-west-1.amazonaws.com", 8883);
  std::cout<<"Connect response: "<<res<<std::endl;
  std::cout<<"Connection estabilished"<<std::endl;
  while(1) {
    auto tstr = "Hello world, this is a enode from mqtt";
    mqttHdl->publish(NULL, "enode/data", strlen(tstr), tstr);
    std::cout<<"Message sent"<<std::endl;
    std::cout<<"Response of publish is: "<<res<<std::endl;
    res = mqttHdl->loop();            // Keep MQTT connection  
    std::cout<<"Response of loop is: "<<res<<std::endl;
    if (res)
      mqttHdl->reconnect();
    sleep(5);
  }
  return 0;
}

NRMKMqttWrapper.cpp

NRMKMqttWrapper::NRMKMqttWrapper(const char *id) : mosquittopp(id)
{
    mosqpp::lib_init();         // Initialize libmosquitto
    std::cout<<"Lib initialized"<<std::endl;
    //int keepalive = 120; // seconds
    //connect(host, port, keepalive);       // Connect to MQTT Broker
}

void NRMKMqttWrapper::on_connect(int rc)
{
    std::cout<<"Connected with code "<<rc<<std::endl;;
    if (rc == 0)
    {
        subscribe(NULL, "command/IGot");
    }
}

void NRMKMqttWrapper::on_subcribe(int mid, int qos_count, const int *granted_qos)
{
    std::cout<<"Subscription succeeded."<<std::endl;
}

void NRMKMqttWrapper::on_message(const struct mosquitto_message *message)
{
    std::cout<<(const char *)message->payload<<std::endl;

}

当它进入循环时,它会打印一会儿0,据我所知第一次被强制返回0,然后返回代码7(连接丢失),它会重新连接并在下一个循环中丢失连接。 br /> 但是,如果我使用mosquitto_pub从控制台运行命令,则该命令会正常工作,并且会收到来自树莓派的消息。

mosquitto_pub --cafile tls/ca/Public-Primary-Certification-Authority-G5.pem --cert tls/xxxx-certificate.pem --key tls/xxxx-private.pem -h xxxx.iot.eu-west-1.amazonaws.com -p 8883 -q 1 -d -t "enode/data" -i clientid1 -m "Hello World"

有什么建议吗?

0 个答案:

没有答案