Deprecated This team is no longer maintained, please use: https://github.com/ARMmbed/mbed-mqtt instead.

Subscribe to a topic and receive the message

04 Jan 2018

I want to subscribe to an specific topic and capture the message that the server sends. Im using the HelloMqtt right now im able to connect to the server and publish a topic .

int main( void )
{ 
  thread1.start(Push); 
  char buf[500];
  char messageArrived[500];
  char* topic = MQTT_TOPIC;
  unsigned int index = 0;
  const char* hostname = MQTT_URL_BROKER;
  int port = 1883;
  
while(1)
{
  MQTT::Message message;
  
  printf("Liditek Mbed Ubidots\r\n");

  NetworkInterface* network = easy_connect(true);
  if(network == NULL) {
    printf("\nConnection to Network Failed - exiting application...\n");
    //return -1;
  }

  MQTTNetwork mqttNetwork(network);
  MQTT::Client<MQTTNetwork, Countdown, MAX_MQTT_PACKET_SIZE> client(mqttNetwork);
  printf("Connecting to %s:%d\r\n", hostname, port);
  int rc = mqttNetwork.connect(hostname, port);
  if (rc != 0) {
   printf("rc from TCP connect is %d\r\n", rc);
   // return -1;
  }
  MQTTPacket_connectData data = MQTTPacket_connectData_initializer;
  data.MQTTVersion = 3;
   data.clientID.cstring = MQTT_CLIENT_ID;
  data.username.cstring = MQTT_USERNAME;
  data.password.cstring = MQTT_PASSWORD;

   printf( "Connecting with Client Id:  %s\r\n", MQTT_CLIENT_ID );
  if ((rc = client.connect(data)) != 0) {
     printf("rc from MQTT connect is %d\r\n", rc);
   // return -1;
  }

  printf("Sending [QoS0], topic: %s\n\r", topic );

  while( rc == 0 ) {    

    printf("Sending payload #%d\n\r", index);
    sprintf(buf,  "{\"temperatura\": {\"value\":%2.1f, \"context\":{\"lat\":0, \"lng\":0}}}\n\r",average);
    message.qos = MQTT::QOS0;
    message.retained = false;
    message.dup = false;
    message.payload = (void*)buf;
    message.payloadlen = strlen(buf);
    if( (message.payloadlen + strlen(topic)+1) >= MAX_MQTT_PACKET_SIZE )
        logMessage("message too long!\r\n");
    rc = client.publish(topic, message);
    if (rc==-1){break;}
    printf( "Sent: %d, rc: %d, payload: %s reset: %i \r\n", index, rc, buf,reset );
    index++;
    

    wait(1);
  }
  
  printf("Server connection closed. (rc = %d)\n", rc);
  client.disconnect();
  mqttNetwork.disconnect(); 
  printf("Restarting\r\n");
  reset++;
 // return -1;
}
}