/**
 * @name Create the MQTT client
 * @brief Create and initialize the mqtt plugin.
 * @param[in] servQuery is the service query being queried for
 * @return boolean, which specifies whether the connection is successfully established or not
 *
 * Establishes the connection with an MQTT broker.
 */
int init(void *servQuery) {
    ServiceQuery *serviceQuery = (ServiceQuery *) servQuery;
    MQTTAsync_SSLOptions sslopts = MQTTAsync_SSLOptions_initializer;
    int rc = 0;
    char uri[256];

    if (serviceQuery->address != NULL) {
        sprintf(uri, "tcp://%s:%d", serviceQuery->address, serviceQuery->port);
    } else {
        sprintf(uri, "tcp://localhost:%d", serviceQuery->port);
    }

    // Default settings:
    int i = 0;

    MQTTAsync_token token;

    quietMode = 0;

    char clientID[256];
    sprintf(clientID, "%s%d", CLIENTID, clientInstanceNumber++);

    MQTTAsync_create(&client, uri, clientID, MQTTCLIENT_PERSISTENCE_NONE, NULL);

    #if DEBUG
        MQTTAsync_setTraceCallback(handleTrace);
        MQTTAsync_setTraceLevel(MQTTASYNC_TRACE_ERROR);
    #endif

    MQTTAsync_setCallbacks(client, client, connectionLost, messageArrived, deliveryComplete);

    conn_opts.cleansession = 0;
    conn_opts.onSuccess = onConnect;
    conn_opts.onFailure = onConnectFailure;
    conn_opts.context = client;
    conn_opts.keepAliveInterval = 0;
    conn_opts.retryInterval = 0;

    if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS) {
        printf("Failed to start connect, return code %d\n", rc);
        exit(1);
    }

    #if DEBUG
        printf("Waiting for connect\n");
    #endif

    while (connected == 0 && finished == 0 && toStop == 0) {
        #if DEBUG
            printf("Waiting for connect: %d %d %d\n", connected, finished, toStop);
        #endif

        sleep(1);
    }

    return rc;
}
Exemple #2
0
int main(int argc, char** argv)
{
	int rc = 0;
 	int (*tests[])() = {NULL, test1, test2, test3, test4, test5, test6}; /* indexed starting from 1 */
	MQTTAsync_nameValue* info;
	int i;

	xml = fopen("TEST-test4.xml", "w");
	fprintf(xml, "<testsuite name=\"test4\" tests=\"%d\">\n", (int)(ARRAY_SIZE(tests)) - 1);
	
	getopts(argc, argv);

	MQTTAsync_setTraceCallback(trace_callback);

	info = MQTTAsync_getVersionInfo();
	while (info->name)
	{
	  MyLog(LOGA_INFO, "%s: %s", info->name, info->value);
	  info++;
	}

	for (i = 0; i < options.iterations; ++i)
	{
	 	if (options.test_no == -1)
		{ /* run all the tests */
			for (options.test_no = 1; options.test_no < ARRAY_SIZE(tests); ++options.test_no)
			{
				failures = 0;
				MQTTAsync_setTraceLevel(MQTTASYNC_TRACE_ERROR);
				rc += tests[options.test_no](options); /* return number of failures.  0 = test succeeded */	
			}
		}
		else
		{
			MQTTAsync_setTraceLevel(MQTTASYNC_TRACE_ERROR);
			rc = tests[options.test_no](options); /* run just the selected test */
		}
	}

	if (rc == 0)
		MyLog(LOGA_INFO, "verdict pass");
	else
		MyLog(LOGA_INFO, "verdict fail");

	fprintf(xml, "</testsuite>\n");
	fclose(xml);
	
	return rc;
}
Exemple #3
0
int main(int argc, char** argv)
{
	int* numtests = &tests;
	int rc = 0;
	int (*tests[])() = { NULL, test1, test2, test3, test4, test5};
	
	sprintf(unique, "%u", rand());
	MyLog(LOGA_INFO, "Random prefix/suffix is %s", unique);

	xml = fopen("TEST-test9.xml", "w");
	fprintf(xml, "<testsuite name=\"test9\" tests=\"%lu\">\n", ARRAY_SIZE(tests) - 1);

	MQTTAsync_setTraceCallback(handleTrace);
	getopts(argc, argv);

	if (options.test_no == 0)
	{ /* run all the tests */
		for (options.test_no = 1; options.test_no < ARRAY_SIZE(tests); ++options.test_no)
		{
			failures = 0;
			MQTTAsync_setTraceLevel(MQTTASYNC_TRACE_ERROR);
			rc += tests[options.test_no](options); /* return number of failures.  0 = test succeeded */
		}
	}
	else
	{
		MQTTAsync_setTraceLevel(MQTTASYNC_TRACE_ERROR);
		rc = tests[options.test_no](options); /* run just the selected test */
	}

	MyLog(LOGA_INFO, "Total tests run: %d", *numtests);
	if (rc == 0)
		MyLog(LOGA_INFO, "verdict pass");
	else
		MyLog(LOGA_INFO, "verdict fail");

	fprintf(xml, "</testsuite>\n");
	fclose(xml);

	return rc;
}
Exemple #4
0
/**
 * The main entry point of the sample.
 *
 * This method handles parsing the arguments specified on the
 * command-line before performing the specified action.
 */
 int main(int argc, char** argv)
 {
 	int rc = 0;
 	int ch;
 	char url[256];

	// Default settings:
 	int i=0;

 	MQTTAsync client;
 	MQTTAsync_connectOptions conn_opts = MQTTAsync_connectOptions_initializer;
 	MQTTAsync_message pubmsg = MQTTAsync_message_initializer;
 	MQTTAsync_token token;

 	signal(SIGINT, handleSignal);
 	signal(SIGTERM, handleSignal);

 	quietMode = 0;
	// Parse the arguments -
 	for (i=1; i<argc; i++)
 	{
		// Check this is a valid argument
 		if (strlen(argv[i]) == 2 && argv[i][0] == '-')
 		{
 			char arg = argv[i][1];
			// Handle the no-value arguments
 			if (arg == 'h' || arg == '?')
 			{
 				printHelp();
 				return 255;
 			}
 			else if (arg == 'q')
 			{
 				quietMode = 1;
 				continue;
 			}

			// Validate there is a value associated with the argument
 			if (i == argc - 1 || argv[i+1][0] == '-')
 			{
 				printf("Missing value for argument: %s\n", argv[i]);
 				printHelp();
 				return 255;
 			}
 			switch(arg)
 			{
 				case 'a': options.action = argv[++i];      break;
 				case 't': options.topic = argv[++i];       break;
 				case 'm': options.message = argv[++i];     break;
 				case 's': options.qos = atoi(argv[++i]);   break;
 				case 'c': options.message_count = atoi(argv[++i]);   break;
 				case 'b': options.broker = argv[++i];      break;
 				case 'p': options.port = argv[++i];  break;
 				default:
 				printf("Unrecognised argument: %s\n", argv[i]);
 				printHelp();
 				return 255;
 			}
 		}
 		else
 		{
 			printf("Unrecognised argument: %s\n", argv[i]);
 			printHelp();
 			return 255;
 		}
 	}

	// Validate the provided arguments
 	if (strcmp(options.action, "publish") != 0 && strcmp(options.action, "subscribe") != 0)
 	{
 		printf("Invalid action: %s\n", options.action);
 		printHelp();
 		return 255;
 	}
 	if (options.qos < 0 || options.qos > 2)
 	{
 		printf("Invalid QoS: %d\n", options.qos);
 		printHelp();
 		return 255;
 	}
 	if (options.topic == NULL || ( options.topic != NULL && strlen(options.topic) == 0) )
 	{
		// Set the default topic according to the specified action
 		if (strcmp(options.action, "publish") == 0)
 			options.topic = "MQTTV3ASample/C/v3";
 		else
 			options.topic = "MQTTV3ASample/#";
 	}

	// Construct the full broker URL and clientId
 	sprintf(url, "tcp://%s:%s", options.broker, options.port);
 	sprintf(clientId, "SampleCV3A_%s", options.action);


 	MQTTAsync_create(&client, url, clientId, MQTTCLIENT_PERSISTENCE_NONE, NULL);

	MQTTAsync_setTraceCallback(handleTrace);
	MQTTAsync_setTraceLevel(MQTTASYNC_TRACE_ERROR);

 	MQTTAsync_setCallbacks(client, client, connectionLost, messageArrived, deliveryComplete);

 	conn_opts.cleansession = 0;
 	conn_opts.onSuccess = onConnect;
 	conn_opts.onFailure = onConnectFailure;
 	conn_opts.context = client;
 	conn_opts.keepAliveInterval = 0;
 	conn_opts.retryInterval = 0;
 	//conn_opts.maxInflight= 30;

 	if ((rc = MQTTAsync_connect(client, &conn_opts)) != MQTTASYNC_SUCCESS)
 	{
 		printf("Failed to start connect, return code %d\n", rc);
 		goto exit;
 	}
 	printf("Waiting for connect\n");
 	while (connected == 0 && finished == 0 && toStop == 0) {
 		printf("Waiting for connect: %d %d %d\n", connected, finished, toStop);
 		usleep(10000L);
 	}

 	MQTTAsync_responseOptions opts = MQTTAsync_responseOptions_initializer;
 		printf("Waiting for connect: %d %d %d\n", connected, finished, toStop);

 	printf("Successful connection\n");

 	if (connected == 1 && strcmp(options.action, "publish") == 0)
	{	
 		unsigned long i; 
 		struct timeval tv;
 		gettimeofday(&tv,NULL);
 		printf("start seconds : %ld\n",tv.tv_sec); 
 		for (i = 0; i < options.message_count; i++)
 		{
 			opts.onSuccess = onSend;
			opts.onFailure = onSendFailure;
 			opts.context = client;
 			pubmsg.payload = options.message;
 			pubmsg.payloadlen = strlen(options.message);
 			pubmsg.qos = options.qos;
 			pubmsg.retained = 0;
 			deliveredtoken = 0;
 			usleep(100);

 			if ((rc = MQTTAsync_sendMessage(client, options.topic, &pubmsg, &opts))
 				!= MQTTASYNC_SUCCESS)
 			{
 				printf("Failed to start sendMessage, return code %d\n", rc);
 				exit(-1);
 			}
 		}

 		gettimeofday(&tv,NULL);

 		printf("end seconds : %ld\n",tv.tv_sec); 
 	} else if (strcmp(options.action, "subscribe") == 0) {
 		opts.onSuccess = onSubscribe;
 		opts.onFailure = onSubscribeFailure;
 		opts.context = client;
 		if ((rc = MQTTAsync_subscribe(client, options.topic, options.qos, &opts)) != MQTTASYNC_SUCCESS) {
 			printf("Failed to subscribe, return code %d\n", rc);
 			exit(-1);
 		}
 	}

 	while (!finished)
 	{
#if defined(WIN32)
 		Sleep(100);
#else
 		usleep(1000L);
#endif
 		if (toStop == 1)
 		{
 			MQTTAsync_disconnectOptions opts = MQTTAsync_disconnectOptions_initializer;

 			opts.onSuccess = onDisconnect;
 			opts.context = client;
 			printf("Entering disconnection phase\n");
 			if ((rc = MQTTAsync_disconnect(client, &opts)) != MQTTASYNC_SUCCESS)
 			{
 				printf("Failed to start disconnect, return code %d\n", rc);
 				exit(-1);
 			}
 			toStop = 0;
 		}
 	}

 	exit:
	printf("calling destroy\n");
 	MQTTAsync_destroy(&client);
 	return rc;
 }