bool PublishToTopic(mqttMessageType &mqttMessage, const char* topic, MQTT::QoS qos)
{
	MQTT::Message message;
	message.qos = qos;
	message.retained = false;
	message.dup = false;

	mqttMessage.host = "XYZ";
	mqttMessage.shortMessage = "This is a short_message";
	char buffer[250];
	sprintf(buffer,
			"{\"host\": \"%s\", "
			"\"short_message\": \"%s\", "
			"\"Lattitude\": \"%f\", "
			"\"Longitude\": \"%f\", "
			"\"Message Title\": \"%s\", "
			"\"Message\": \"%s\" "
			"}",
			mqttMessage.host, mqttMessage.shortMessage.c_str(),
			mqttMessage.lattitude, mqttMessage.longitude,
			mqttMessage.messageTitle.c_str(), mqttMessage.message.c_str()
			);

	cout << buffer;
	message.payload = (void*)buffer;
	message.payloadlen = strlen(buffer) + 1;

	rc = client.publish(topic, message);
	if (rc != 0) {
		printf("Error %d from sending QoS 0 message\n", rc);
	}
	else
	{
		cout << "Message published successfully to " << topic << endl;
	}

	return true;
}
Esempio n. 2
0
int main(int argc, char* argv[])
{   
    IPStack ipstack = IPStack();
    float version = 0.3;
    const char* topic = "mbed-sample";
    
    printf("Version is %f\n", version);
              
    MQTT::Client<IPStack, Countdown> client = MQTT::Client<IPStack, Countdown>(ipstack);
    
    client.setConnectionLostHandler(connect);

    MQTT::Client<IPStack, Countdown>::connectionLostInfo info = {&client, &ipstack};
    int rc = connect(&info);
    
    rc = client.subscribe(topic, MQTT::QOS2, messageArrived);   
    if (rc != 0)
        printf("rc from MQTT subscribe is %d\n", rc);

    MQTT::Message message;

    // QoS 0
    char buf[100];
    sprintf(buf, "Hello World!  QoS 0 message from app version %f", version);
    message.qos = MQTT::QOS0;
    message.retained = false;
    message.dup = false;
    message.payload = (void*)buf;
    message.payloadlen = strlen(buf)+1;
    rc = client.publish(topic, &message);
    while (arrivedcount == 0)
        client.yield(100);
        
    // QoS 1
	printf("Now QoS 1\n");
    sprintf(buf, "Hello World!  QoS 1 message from app version %f", version);
    message.qos = MQTT::QOS1;
    message.payloadlen = strlen(buf)+1;
    rc = client.publish(topic, &message);
    while (arrivedcount == 1)
        client.yield(100);
        
    // QoS 2
    sprintf(buf, "Hello World!  QoS 2 message from app version %f", version);
    message.qos = MQTT::QOS2;
    message.payloadlen = strlen(buf)+1;
    rc = client.publish(topic, &message);
    while (arrivedcount == 2)
        client.yield(100);
    
    rc = client.unsubscribe(topic);
    if (rc != 0)
        printf("rc from unsubscribe was %d\n", rc);
    
    rc = client.disconnect();
    if (rc != 0)
        printf("rc from disconnect was %d\n", rc);
    
    ipstack.disconnect();
    
    printf("Finishing with %d messages received\n", arrivedcount);
    
    return 0;
}