Example #1
0
void PICNTRL::listenForMessages(char* topic) {
   this->_topic = (char*) malloc(strlen(topic) + 1);
   if (NULL == this->_topic) {
      printf("Error, failed to allocation string for topic\n");
      return;
   }
   strcpy(this->_topic, topic);

   MQTTClient_create(&_myClient, _mqttBroker, "PICntrl", MQTTCLIENT_PERSISTENCE_NONE, (void*) this);
   MQTTClient_setCallbacks(_myClient, (void*) this, &(PICNTRL::connectionLost), &(PICNTRL::messageArrived), NULL);

   _mqttOptions.keepAliveInterval = 10;
   _mqttOptions.cleansession = 1;
   _mqttOptions.reliable = 0;

   int connectResult = MQTTClient_connect(_myClient, &_mqttOptions);
   if(MQTTCLIENT_SUCCESS != connectResult) {
      printf("Failed to connect to MQTT broker, exiting\n");
      return;
   }

   MQTTClient_subscribe(_myClient, this->_topic, QOS_AT_MOST_ONCE_0);

   while(1) {
      usleep(1000 * 1000);
      MQTTClient_yield();
   }
}
Example #2
0
int main(int argc, char* argv[])
{
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    int rc;
    int ch;

    lw_setup();

    MQTTClient_create(&client, ADDRESS, CLIENTID,
        MQTTCLIENT_PERSISTENCE_NONE, NULL);
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;

    MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);

    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        exit(-1);       
    }
    printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
           "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
    MQTTClient_subscribe(client, TOPIC, QOS);

    do 
    {
        ch = getchar();
    } while(ch!='Q' && ch != 'q');

    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;
}
Example #3
0
MQTTAPI_TOPIC_HANDLE MQTTAPI_Subscribe(MQTTAPI_HANDLE instance, const char* topic)
{
	PMQTTTAPI_HANDLE_DATA handle = instance;
	PMQTTAPI_TOPIC_HANDLE_DATA result;

	/* Codes_SRS_MQTTAPI_04_029: [If any of the parameters instance or topic is NULL MQTTAPI_Subscribe shall return NULL.]  */
	if (instance == NULL || topic == NULL || strlen(topic) == 0)
	{
		result = NULL;
	}
	else
	{
		if ((result = (PMQTTAPI_TOPIC_HANDLE_DATA)malloc(sizeof(MQTTAPI_TOPIC_HANDLE_DATA))) == NULL)
		{
			LogError("Memory Allocation failure to store Topic Handle Data.\r\n");
			handle->subscribed = false;
		}
		else if (checkAndTryToConnect(handle))
		{
			int rc;
			/* Codes_SRS_MQTTAPI_04_031: [MQTTAPI_Subscribe shall call underlying library methods to subscribe to the topic on the topic parameter.] */
			if ((rc = MQTTClient_subscribe(handle->client, topic, SUBSCRIBEQOS)) != MQTTCLIENT_SUCCESS)
			{
				/* Codes_SRS_MQTTAPI_04_032: [If the underlying library fails MQTTAPI_Subscribe shall return NULL] */
				LogError("Error subscribing to topic. Code is:%d \r\n", rc);
				free(result);
				result = NULL;
				handle->subscribed = false;
			}
			else
			{
				/* Codes_SRS_MQTTAPI_04_033: [Otherwise MQTTAPI_Subscribe shall return a non-NULL MQTTAPI_TOPIC_HANDLE] */
				result->mqttApiInstance = handle;
				if ((result->topicName = STRING_construct(topic)) == NULL)
				{
					LogError("Problem to save topic name.\r\n");
					free(result);
					result = NULL;
					handle->subscribed = false;
				}
				else
				{
					handle->subscribedTopicHandleData = result;
					handle->subscribed = true;
				}
			}
		}
		else
		{
			LogError("MQTT Client Not Connected. Error trying to reconect.\r\n");
			free(result);
			result = NULL;
		}
	}

	return result;
}
Example #4
0
/**
 * @name Subscribes to a topic
 * @brief Subscribes to a topic with an MQTT broker.
 * @param[in] topic which needs to be subscribed to
 * @return boolean, which specifies whether successfully subscribed or not
 */
int subscribe(char *topic) {
    int rc = 0;

    if ((rc = MQTTClient_subscribe(client, topic, QOS)) != MQTTCLIENT_SUCCESS) {
        printf("Failed to subscribe, return code %d\n", rc);
        exit(-1);
    }

    return rc;
}
Example #5
0
void PICNTRL::connectionLost(void *context, char *cause) {
   PICNTRL* myThis = (PICNTRL*)context;

   while (true) {
      if (MQTTCLIENT_SUCCESS == MQTTClient_connect(myThis->_myClient, &(myThis->_mqttOptions))) {
         MQTTClient_subscribe(myThis->_myClient, myThis->_topic, QOS_AT_MOST_ONCE_0);
         break;
      }
      // wait 5 seconds and then try to reconnect
      usleep(MQTT_CONNECT_RETRY_SECONDS*1000*1000);
   }
}
Example #6
0
int mainSubASync(int argc, char* argv[])
{

	initializeObjects();
	readFile();
	printf("\n Broker URL is := %s \n",brokerUrl);

	initiliazeMQTT(argc,argv);

    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    int rc;
    int ch;

    MQTTClient_create(&client, ADDRESS, CLIENTID,
        MQTTCLIENT_PERSISTENCE_NONE, NULL);
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;

    MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);

    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        exit(-1);
    }
    printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
           "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
    MQTTClient_subscribe(client, TOPIC, QOS);

//    do
//    {
//        ch = getchar();
//    } while(ch!='Q' && ch != 'q');

    while(1){
    	ch = getchar();
    	if(ch=='Q'){
    		printf("\n Quit! \n");
    	} else {
    		if(ch != '\n'){
    		ch=='0';
    		printf("\n Sending Message to publish \n");
    			publishMessage(userid);
    		}
    	}
    }

    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;
}
Example #7
0
static PyObject* mqttv3_subscribe(PyObject* self, PyObject *args)
{
	MQTTClient c;
	char* topic;
	int qos = 2;
	int rc;

	if (!PyArg_ParseTuple(args, "ks|i", &c, &topic, &qos))
		return NULL;
	Py_BEGIN_ALLOW_THREADS rc = MQTTClient_subscribe(c, topic, qos);
	Py_END_ALLOW_THREADS
	return Py_BuildValue("i", rc);
}
Example #8
0
int main(int argc, char* argv[])
//int mainSubasync(int argc, char* argv[])
{

	initializeObjects();
	readFile();
	initiliazeMQTT(argc,argv);

    MQTTClient client;
    MQTTClient_connectOptions conn_opts_sub = MQTTClient_connectOptions_initializer;
    int rc;
    int ch;
    //ADDRESS =	brokerUrl;
    MQTTClient_create(&client, brokerUrl, CLIENTID,
        MQTTCLIENT_PERSISTENCE_NONE, NULL);
    conn_opts_sub.keepAliveInterval = 20;
    conn_opts_sub.cleansession = 1;

    MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);

    if ((rc = MQTTClient_connect(client, &conn_opts_sub)) != MQTTCLIENT_SUCCESS)
    {
        if(SUBASYNCLOGGER){
        	printf("Failed to connect, return code %d\n", rc);
        }
        exit(-1);
    }
//    if(SUBASYNCLOGGER){
//		printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
//			   "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
//    }
    MQTTClient_subscribe(client, TOPIC, QOS);

//    if(SUBASYNCLOGGER){
//    	printf("In Main pthread_create getpid: %d getpthread_self: %lu \n",getpid(), pthread_self());
//    }
    argv[1]	=	serialPort;
    argv[2]	=	"mon";
    mainGW(argc,argv);
    //mainGWMyHub(argc,argv);
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;
}
Example #9
0
static void connectionLost(void *context, char *cause)
{
	PMQTTTAPI_HANDLE_DATA transportState = (PMQTTTAPI_HANDLE_DATA)context;
	LogError("Lost Connection, reseting Connection State. Cause: %s \r\n", cause);

	if (transportState != NULL)
	{
		transportState->connected = false;
	}

	LogInfo("Trying to connect again\r\n");

	if (!checkAndTryToConnect(transportState))
	{
		LogError("Could not connect again. \r\n");
	}
	else
	{
		LogInfo("Connected.\r\n");
		if (transportState->subscribed)
		{
			int rc;
			LogInfo("Trying to Subscribe after reconnect.\r\n");

			if ((rc = MQTTClient_subscribe(transportState->client, STRING_c_str(transportState->subscribedTopicHandleData->topicName), SUBSCRIBEQOS)) != MQTTCLIENT_SUCCESS)
			{
				LogError("Could not subscribe again. Won't be able to receive messages. Error Code: %d.\r\n", rc);
			}
			else
			{
				LogInfo("Subscribed succesfully after reconnect..\r\n");
			}
		}
	}

	if (cause != NULL)
	{
		MQTTClient_free(cause);
	}
}
Example #10
0
// 通信の開始
bool CConMQTT::bConnect(const char* szAddress)
{
	//MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;

	MQTTClient_create(&m_client, szAddress, CLIENT_ID,
		MQTTCLIENT_PERSISTENCE_NONE, NULL);
	//conn_opts.keepAliveInterval = 20;
	//conn_opts.cleansession = 1;
	//conn_opts.connectTimeout = 0;
	//conn_opts.retryInterval = 3;

	// 非同期通信におけるコールバックの設定
	MQTTClient_setCallbacks(m_client, this, connlost, msgarrvd, delivered);

	//int iWaitTime = 10;
	//_beginthread(waitConnect, 0x200, &iWaitTime);
	HANDLE hThread;
	DWORD dwRet;
	hThread = CreateThread(NULL, 0, startConnect, &m_client, 0, NULL);

	// MQTTClient_connectOptionsのconnectTimeoutの使い方が分からなかったので
	// スレッドの終了まちで対応
	dwRet = WaitForSingleObject(hThread, 3000);
	if (WAIT_TIMEOUT == dwRet) {
		TerminateThread(hThread, -1);

		return false;
	}


	printf("Subscribing to topic %s\nfor client %s using QoS%d\n", 
		TOPIC, CLIENT_ID, QOS);
	MQTTClient_subscribe(m_client, TOPIC, QOS);

	return true;
}
Example #11
0
int main(int argc, char** argv)
{
	//MQTTClient client;
//	MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
	char topic[200] = "";
	char* buffer = NULL;
	int rc = 0;
	char url[100];
	char broker[100];

	if (argc < 2)
		usage();
	
	getopts(argc, argv);
	
//	sprintf(url, "%s:%s", opts.host, opts.port);
//  if (opts.verbose)
//		printf("URL is %s\n", url);

//	char a[200] = "55e6ba684a481fa955f3912e";
//	char b[200] = "hello";
	strcpy(topic, argv[1]);
	//opts.appkey = a;
	//topic = b;
	printf("Using topic %s\n", topic);

	int res = MQTTClient_setup_with_appkey_and_deviceid(opts.appkey, opts.deviceid, &my_reg_info);
	if (res < 0) {
		printf("can't get reg info\n");
		return 0;
	}

	printf("Get reg info: client_id:%s,username:%s,password:%s, devide_id:%s\n", my_reg_info.client_id, my_reg_info.username, my_reg_info.password, my_reg_info.device_id);

	res = MQTTClient_get_host(opts.appkey, url);
	if (res < 0) {
		printf("can't get host info\n");
		return 0;
	}
	printf("Get url info: %s\n", url);

	rc = MQTTClient_create(&client, url, my_reg_info.client_id, MQTTCLIENT_PERSISTENCE_NONE, NULL);
	MQTTClient_get_broker(&client, broker);
	printf("get broker:%s\n", broker);

//	MQTTClient_set_broker(&client, "localhost");

	if (opts.authkey != NULL) {
		printf("set authkey\r\n");
		int status;
		rc = MQTTClient_set_authkey(my_reg_info.client_id, opts.appkey, opts.authkey, &status);
		if (rc >= 0)
			printf("set authkey result: status:%i\r\n", status);
		char auth[80];
		rc = MQTTClient_get_authkey(my_reg_info.client_id, opts.appkey, auth, &status);
		if (rc >= 0)
			printf("get authkey result: status:%i, authkey:%s\r\n", status, auth);
	}

	MQTTClient_get_broker(&client, broker);
	printf("get broker:%s\n", broker);

	signal(SIGINT, cfinish);
	signal(SIGTERM, cfinish);

	rc = MQTTClient_setCallbacks(client, NULL, connectionLost, messageArrived, NULL, extendedCmdArrive);

	conn_opts.keepAliveInterval = 300;
	conn_opts.reliable = 0;
	conn_opts.cleansession = 0;
	conn_opts.username = my_reg_info.username;
	conn_opts.password = my_reg_info.password;
	
	myconnect(&client, &conn_opts);

	buffer = malloc(opts.maxdatalen);

	rc = MQTTClient_subscribe(client, topic, 1);
	printf("subscribe topic:%s, %i\n", topic, rc);

	if (opts.alias != NULL) {
		printf("set alias: %s\n", opts.alias);
		MQTTClient_set_alias(client, opts.alias);
	}
	//MQTTClient_presence(client, topic);
	int ret;
	ret = MQTTClient_get_aliaslist(client, topic);
	printf("get aliaslist:%i, topic:%s\n", ret, topic);
	ret = MQTTClient_get_topic(client, "band1111");
	printf("get topic:%i\n", ret);
	ret = MQTTClient_get_status(client, "band1111");
	printf("get status:%i\n", ret);

	ret = MQTTClient_report(client, "domytest", "abc");
	printf("report status:%i\n", ret);

	ret = MQTTClient_get_status2(client, "baidu");
	printf("get status2:%i\n", ret);
	ret = MQTTClient_get_topiclist2(client, topic);
	printf("get topic list2:%i\n", ret);
	ret = MQTTClient_get_aliaslist2(client, topic);
	printf("get aliaslist2:%i\n", ret);
	sleep(7);
	cJSON *apn_json, *aps;
	cJSON *Opt = cJSON_CreateObject();
	cJSON_AddStringToObject(Opt,"time_to_live",  "120");
	cJSON_AddStringToObject(Opt,"time_delay",  "1100");
	cJSON_AddStringToObject(Opt,"apn_json",  "{\"aps\":{\"alert\":\"FENCE alarm\", \"sound\":\"alarm.mp3\"}}");
	ret = MQTTClient_publish2(client, topic, strlen("test") + 1, "test", Opt);
	cJSON_Delete(Opt);
	printf("publish2 status:%i\n", ret);
	
	while (!toStop)
	{
		int data_len = 0;
		int delim_len = 0;
		
		delim_len = strlen(opts.delimiter);
		do
		{
			buffer[data_len++] = getchar();
			if (data_len > delim_len)
			{
			//printf("comparing %s %s\n", opts.delimiter, &buffer[data_len - delim_len]);
			if (strncmp(opts.delimiter, &buffer[data_len - delim_len], delim_len) == 0)
				break;
			}
		} while (data_len < opts.maxdatalen);
				
		if (opts.verbose)
				printf("Publishing data of length %d\n", data_len);

		rc = MQTTClient_publish(client, topic, data_len, buffer);
		if (rc != 0)
		{
			myconnect(&client, &conn_opts);
			rc = MQTTClient_publish(client, topic, data_len, buffer);
			printf("reconnect %i\n", rc);
		}
		if (opts.qos > 0)
			MQTTClient_yield();
	}
	
	printf("Stopping\n");
	
	free(buffer);

	MQTTClient_disconnect(client, 0);

 	MQTTClient_destroy(&client);

	return 0;
}
Example #12
0
int test4_s(struct Options options)
{
	char* testname = "test4_s";
	char* test_topic = "C client test4_s";
	int subsqos = 2;
	MQTTClient c;
	MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
	MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
    MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
	int rc = 0;

	failures = 0;
	MyLog(LOGA_INFO, "Starting test 4_s - accept invalid server certificates - single threaded");
	
	if (!(assert("good rc from create", (rc = MQTTClient_create(&c, options.connection, "test4_s", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
		goto exit;

	opts.keepAliveInterval = 20;
	opts.cleansession = 1;
	opts.username = "******";
	opts.password = "******";
	if (options.haconnections != NULL)
	{
		opts.serverURIs = options.haconnections;
		opts.serverURIcount = options.hacount;
	}

    opts.ssl = &sslopts;
    //if (options.server_key_file != NULL) opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
    //opts.ssl->keyStore = options.client_key_file;  /*file of certificate for client to present to server*/
	//if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
    //opts.ssl->enabledCipherSuites = "DEFAULT";
    opts.ssl->enableServerCertAuth = 0;

	MyLog(LOGA_DEBUG, "Connecting");

	if (!(assert("Good rc from connect", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;
	if (!(assert("Good rc from subscribe", (rc = MQTTClient_subscribe(c, test_topic, subsqos)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

	singleThread_sendAndReceive(c, 0, test_topic);
	singleThread_sendAndReceive(c, 1, test_topic);
	singleThread_sendAndReceive(c, 2, test_topic);

	MyLog(LOGA_DEBUG, "Stopping\n");

	if (!(assert("Unsubscribe successful", (rc = MQTTClient_unsubscribe(c, test_topic)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;
	if (!(assert("Disconnect successful", (rc = MQTTClient_disconnect(c, 0)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

	/* Just to make sure we can connect again */

	if (!(assert("Connect successful", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;
	if (!(assert("Disconnect successful", (rc = MQTTClient_disconnect(c, 0)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

exit:
	MQTTClient_destroy(&c);
	MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
			(failures == 0) ? "passed" : "failed", testname, tests, failures);

	return failures;
}
Example #13
0
int test2a_m(struct Options options)
{
	char* testname = "test2a_m";
	char* test_topic = "C client test2a_m";
	int subsqos = 2;
	/* TODO - usused - remove ? MQTTClient_deliveryToken* dt = NULL; */
	MQTTClient c;
	MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
	MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
    MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
	int rc = 0;

	failures = 0;
	MyLog(LOGA_INFO, "Starting test 2a_m - Mutual SSL authentication - multi-threaded client using callbacks");

	if (!(assert("good rc from create", (rc = MQTTClient_create(&c, options.connection, "test2a_m", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore)) == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
		goto exit;

	opts.keepAliveInterval = 20;
	opts.cleansession = 1;
	opts.username = "******";
	opts.password = "******";
	if (options.haconnections != NULL)
	{
		opts.serverURIs = options.haconnections;
		opts.serverURIcount = options.hacount;
	}

    opts.ssl = &sslopts;
    if (options.server_key_file != NULL) opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
    opts.ssl->keyStore = options.client_key_file;  /*file of certificate for client to present to server*/
	if (options.client_key_pass != NULL) opts.ssl->privateKeyPassword = options.client_key_pass;
    //opts.ssl->enabledCipherSuites = "DEFAULT";
    //opts.ssl->enabledServerCertAuth = 1;

	if (!(assert("Good rc from setCallbacks", (rc = MQTTClient_setCallbacks(c, NULL, NULL, multiThread_messageArrived, multiThread_deliveryComplete)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

	MyLog(LOGA_DEBUG, "Connecting");

	if (!(assert("Good rc from connect", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

	if (!(assert("Good rc from subscribe", (rc = MQTTClient_subscribe(c, test_topic, subsqos)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

	multiThread_sendAndReceive(c, 0, test_topic);
	multiThread_sendAndReceive(c, 1, test_topic);
	multiThread_sendAndReceive(c, 2, test_topic);

	MyLog(LOGA_DEBUG, "Stopping");

	if (!(assert("Unsubscribe successful", (rc = MQTTClient_unsubscribe(c, test_topic)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;
	if (!(assert("Disconnect successful", (rc = MQTTClient_disconnect(c, 0)) == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

exit:
	MQTTClient_destroy(&c);
	MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
			(failures == 0) ? "passed" : "failed", testname, tests, failures);

	return failures;
}
Example #14
0
int mqtt_sub(MQTTClient *context, char *topic, int qos) {
	int rc = 0;
	rc = MQTTClient_subscribe(*context, topic, qos);
	return rc;
}
Example #15
0
int test2(struct Options options)
{
	char* testname = "test2";
	int subsqos = 2;
	MQTTClient c;
	MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
	int rc = 0;
	char* test_topic = "C client test2";
	char* topics[2] = {"test_topic", "nosubscribe"};
	int qoss[2] = {2, 2};

	fprintf(xml, "<testcase classname=\"test1\" name=\"bad return code from subscribe\"");
	MyLog(LOGA_INFO, "Starting test 2 - bad return code from subscribe");
	global_start_time = start_clock();
	failures = 0;

	MQTTClient_create(&c, options.connection, "multi_threaded_sample", MQTTCLIENT_PERSISTENCE_DEFAULT, NULL);

	opts.keepAliveInterval = 20;
	opts.cleansession = 1;
	opts.MQTTVersion = 4;
	if (options.haconnections != NULL)
	{
		opts.serverURIs = options.haconnections;
		opts.serverURIcount = options.hacount;
	}

	rc = MQTTClient_setCallbacks(c, NULL, NULL, test2_messageArrived, test2_deliveryComplete);
	assert("Good rc from setCallbacks", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);

	MyLog(LOGA_DEBUG, "Connecting");
	rc = MQTTClient_connect(c, &opts);
	assert("Good rc from connect", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
	if (rc != MQTTCLIENT_SUCCESS)
		goto exit;

	assert("Correct serverURI returned", strcmp(opts.returned.serverURI, options.connection) == 0, "serverURI was %s",
		opts.returned.serverURI);
	assert("Correct MQTTVersion returned", opts.returned.MQTTVersion == 4, "MQTTVersion was %d",
		opts.returned.MQTTVersion);
	assert("Correct sessionPresent returned", opts.returned.sessionPresent == 0, "sessionPresent was %d",
		opts.returned.sessionPresent);

	rc = MQTTClient_subscribe(c, test_topic, subsqos);
	assert("Good rc from subscribe", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);

	rc = MQTTClient_subscribe(c, "nosubscribe", 2);
	assert("0x80 from subscribe", rc == 0x80, "rc was %d", rc);

	rc = MQTTClient_subscribeMany(c, 2, topics, qoss);
	assert("Good rc from subscribe", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
	assert("Correct returned qos from subscribe", qoss[0] == 2, "qos 0 was %d", qoss[0]);
	assert("Correct returned qos from subscribe", qoss[1] == 0x80, "qos 0 was %d", qoss[0]);

	rc = MQTTClient_unsubscribe(c, test_topic);
	assert("Unsubscribe successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);
	rc = MQTTClient_disconnect(c, 0);
	assert("Disconnect successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc);

	MQTTClient_destroy(&c);

exit:
	MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
			(failures == 0) ? "passed" : "failed", testname, tests, failures);
	write_test_result();
	return failures;
}
Example #16
0
int main(int argc, char** argv)
{
	MQTTClient client;
	MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
	char topic[128];
	int rc = 0;
	char url[100];

	create_push_topic(topic, "message");

	printf("topic is %s\n", topic);

  if (strchr(topic, '#') || strchr(topic, '+'))
		opts.showtopics = 1;
  if (opts.showtopics)
		printf("topic is %s\n", topic);

	sprintf(url, "%s:%s", opts.host, opts.port);

	rc = MQTTClient_create(&client, url, opts.clientid, MQTTCLIENT_PERSISTENCE_NONE, NULL);

	signal(SIGINT, cfinish);
	signal(SIGTERM, cfinish);

	conn_opts.keepAliveInterval = 10;
	conn_opts.reliable = 0;
	conn_opts.cleansession = 0;
	conn_opts.username = opts.token;
	conn_opts.password = opts.appid;
	
	myconnect(&client, &conn_opts);
	
	rc = MQTTClient_subscribe(client, topic, opts.qos);

	while (!toStop)
	{
		char* topicName = NULL;
		int topicLen;
		MQTTClient_message* message = NULL;
		
		rc = MQTTClient_receive(client, &topicName, &topicLen, &message, 1000);
		if (message)
		{
			if (opts.showtopics)
				printf("%s\t", topicName);
      if (opts.nodelimiter)
				printf("%.*s", message->payloadlen, (char*)message->payload);
			else
				printf("%.*s%s", message->payloadlen, (char*)message->payload, opts.delimiter);
			fflush(stdout);
			MQTTClient_freeMessage(&message);
			MQTTClient_free(topicName);
		}
		if (rc != 0)
			myconnect(&client, &conn_opts);
	}
	
	printf("Stopping\n");

	MQTTClient_disconnect(client, 0);

 	MQTTClient_destroy(&client);

	return 0;
}
Example #17
0
int mqtt_init(char *hostname, int port, char *certfile, char *nodeKeyS, char *nodeSecret)
{   
	int rc;
	char hostaddress[50];
	bool use_ssl = false;

	if (port == 8883 || (certfile != NULL && strlen(certfile) > 0))
		use_ssl = true;

    Yodiwo_Plegma_NodeKey_t nodeKey;
    if (nodeKeyS == NULL || nodeSecret == NULL) {
    	return -1;
    }
    NodeKey_FromString(&nodeKey, nodeKeyS);
    sprintf(mqtt_topic_sub, "/api/out/" YODIWO_API_VERSION_STR "/%s/#", nodeKeyS);
    sprintf(mqtt_topic_pub, "/api/in/" YODIWO_API_VERSION_STR "/%s/%s/", nodeKey.UserKey.UserID, nodeKeyS);
    printf("topic to subscribe: %s\n", mqtt_topic_sub);

    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    MQTTClient_SSLOptions ssl_opts = MQTTClient_SSLOptions_initializer;
    MQTTClient_deliveryToken token;

    sprintf(hostaddress,
    		use_ssl ? "ssl://%s:%d" : "%s:%d",
			hostname, port);

    rc = MQTTClient_create(&client, hostaddress, nodeKeyS, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    if (rc != MQTTCLIENT_SUCCESS) {
    	return -1;
    }

    if (use_ssl) {
    	ssl_opts.enableServerCertAuth = (certfile != NULL && strlen(certfile) > 0);
        ssl_opts.trustStore = certfile;
        conn_opts.ssl = &ssl_opts;
    }
//    conn_opts.connectTimeout = 50000;
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    conn_opts.MQTTVersion = 4;
    conn_opts.username = nodeKeyS;
    conn_opts.password = nodeSecret;

    MQTTClient_setCallbacks(client, NULL, on_mqtt_disconnected, on_mqtt_message, NULL);

    printf("connecting to MQTT broker: %s:%d\n", hostname, port);
    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        return -1;
    }
    printf("MQTT connected\n") ;
    if ((rc = MQTTClient_subscribe(client, mqtt_topic_sub, 2)) != MQTTCLIENT_SUCCESS) {
        printf("rc from MQTT subscribe is %d\n", rc);
        return rc;
    }
    printf("Subscribed\n");


    return 0;
}
Example #18
0
void MQTT::connect()
{
	try
	{
		if(_started || _client) return;
		_started = true;
		_connectionOptions = new MQTTClient_connectOptions(MQTTClient_connectOptions_initializer);
		if(!_settings.username().empty())
		{
			((MQTTClient_connectOptions*)_connectionOptions)->username = _settings.username().c_str();
			((MQTTClient_connectOptions*)_connectionOptions)->password = _settings.password().c_str();
		}
		if(_settings.enableSSL())
		{
			_out.printInfo("Info: Enabling SSL for MQTT.");
#ifndef OPENSSL
			_out.printError("Error: MQTT library is compiled without OpenSSL support. Can't enable SSL. Aborting.");
			disconnect();
			return;
#endif
			if(_settings.caFile().empty())
			{
				_out.printError("Error: SSL is enabled but \"caFile\" is not set.");
				disconnect();
				return;
			}
			if(!BaseLib::Io::fileExists(_settings.caFile()))
			{
				_out.printError("Error: CA certificate file does not exist or can't be opened.");
				disconnect();
				return;
			}
			if(_settings.certPath().empty())
			{
				_out.printError("Error: SSL is enabled but \"certPath\" is not set.");
				disconnect();
				return;
			}
			if(!BaseLib::Io::fileExists(_settings.certPath()))
			{
				_out.printError("Error: Client certificate file does not exist or can't be opened.");
				disconnect();
				return;
			}
			if(_settings.keyPath().empty())
			{
				_out.printError("Error: SSL is enabled but \"keyPath\" is not set.");
				disconnect();
				return;
			}
			if(!BaseLib::Io::fileExists(_settings.keyPath()))
			{
				_out.printError("Error: Client key file does not exist or can't be opened.");
				disconnect();
				return;
			}

			_sslOptions = new MQTTClient_SSLOptions({ {'M', 'Q', 'T', 'S'}, 0, _settings.caFile().c_str(), _settings.certPath().c_str(), _settings.keyPath().c_str(), nullptr, nullptr, _settings.verifyCertificate() });
			((MQTTClient_connectOptions*)_connectionOptions)->ssl = (MQTTClient_SSLOptions*)_sslOptions;
		}
		MQTTClient_create(&_client, std::string((_settings.enableSSL() ? "ssl://" : "tcp://") + _settings.brokerHostname() + ":" + _settings.brokerPort()).c_str(), _settings.clientName().c_str(), MQTTCLIENT_PERSISTENCE_NONE, NULL);
		((MQTTClient_connectOptions*)_connectionOptions)->keepAliveInterval = 10;
		((MQTTClient_connectOptions*)_connectionOptions)->cleansession = 1;
		MQTTClient_setCallbacks(_client, NULL, NULL, MQTTMessageArrived, NULL);
		int32_t result = MQTTClient_connect(_client, (MQTTClient_connectOptions*)_connectionOptions);
		if (result != MQTTCLIENT_SUCCESS)
		{
			disconnect();
			std::string reason;
			//see http://www.eclipse.org/paho/files/mqttdoc/Cclient/_m_q_t_t_client_8h.html#aaa8ae61cd65c9dc0846df10122d7bd4e
			if(result == 1) reason = "Connection refused: Unacceptable protocol version";
			else if(result == 2) reason = "Connection refused: Identifier rejected";
			else if(result == 3) reason = "Connection refused: Server unavailable";
			else if(result == 4) reason = "Connection refused: Bad user name or password";
			else if(result == 5) reason = "Connection refused: Not authorized";
			else reason = "Unknown reason. Check broker log for more details. A few common reasons: The broker is not running, the broker is not reachable (wrong IP address, wrong port, firewall, ...), the broker requires SSL and SSL is not enabled in Homegear's mqtt.conf.";
			_out.printError("Error: Failed to connect to message broker: " + reason);
			return;
		}
		_out.printInfo("Info: Successfully connected to message broker.");
		MQTTClient_subscribe(_client, std::string("homegear/" + _settings.homegearId() + "/rpc/#").c_str(), 1);
	}
	catch(const std::exception& ex)
	{
		_out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what());
	}
	catch(BaseLib::Exception& ex)
	{
		_out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__, ex.what());
	}
	catch(...)
	{
		_out.printEx(__FILE__, __LINE__, __PRETTY_FUNCTION__);
	}
}
Example #19
0
int test2a_s(struct Options options)
{
	char* testname = "test2a_s";
	char* test_topic = "C client test2a_s";
	int subsqos = 2;
	MQTTClient c;
	MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
	MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
	MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
	int rc = 0;

	failures = 0;
	MyLog(LOGA_INFO, "Starting test 2a_s - Mutual SSL authentication - single threaded client using receive");
	fprintf(xml, "<testcase classname=\"test3\" name=\"test 2a_s\"");
	global_start_time = start_clock();
	
	rc = MQTTClient_create(&c, options.server_auth_connection, "test2a_s", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore);
	if (!(assert("good rc from create", rc == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
		goto exit;

	opts.keepAliveInterval = 20;
	opts.cleansession = 1;
	opts.username = "******";
	opts.password = "******";
	if (options.haconnections != NULL)
	{
		opts.serverURIs = options.haconnections;
		opts.serverURIcount = options.hacount;
	}

	opts.ssl = &sslopts;
	if (options.server_key_file) 
		opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/
	opts.ssl->keyStore = options.client_key_file;  /*file of certificate for client to present to server*/
	if (options.client_key_pass) 
		opts.ssl->privateKeyPassword = options.client_key_pass;
	if (options.client_private_key_file) 
		opts.ssl->privateKey = options.client_private_key_file;

	MyLog(LOGA_DEBUG, "Connecting");

	rc = MQTTClient_connect(c, &opts);
	if (!(assert("Good rc from connect", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

	rc = MQTTClient_subscribe(c, test_topic, subsqos);
	if (!(assert("Good rc from subscribe", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

	singleThread_sendAndReceive(c, 0, test_topic);
	singleThread_sendAndReceive(c, 1, test_topic);
	singleThread_sendAndReceive(c, 2, test_topic);

	MyLog(LOGA_DEBUG, "Stopping\n");

	rc = MQTTClient_unsubscribe(c, test_topic);
	if (!(assert("Unsubscribe successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;
	rc = MQTTClient_disconnect(c, 0);
	if (!(assert("Disconnect successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

	/* Just to make sure we can connect again */
	rc = MQTTClient_connect(c, &opts);
	if (!(assert("Connect successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;
	rc = MQTTClient_disconnect(c, 0);
	if (!(assert("Disconnect successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

exit:
	MQTTClient_destroy(&c);
	MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
			(failures == 0) ? "passed" : "failed", testname, tests, failures);
	write_test_result();
	return failures;
}
Example #20
0
File: mqtt.c Project: tok101/tok101
int mqtt_subscribe_topic(MQTTClient client, const char* topic,int qos)
{
	
    return MQTTClient_subscribe(client, topic, qos);
	
}
Example #21
0
static bool checkAndTryToConnect(PMQTTTAPI_HANDLE_DATA mqttApiState)
{
	bool result;

	if (mqttApiState != NULL)
	{
		if (!mqttApiState->connected)
		{
			/* Codes_SRS_MQTTAPI_04_062: [MQTTAPI_create shall generate SAS Token with an expiring time of 1 hour.] */
			size_t secondsSinceEpoch = (size_t)(difftime(get_time(NULL), EPOCH_TIME_T_VALUE) + 0);
			size_t possibleNewExpiry = secondsSinceEpoch + mqttApiState->sasTokenLifetime;
			STRING_HANDLE zeroLengthString;

			if ((zeroLengthString = STRING_new()) == NULL)
			{
				LogError("Could not generate zeroLenghtString for skn. \r\n");
				result = false;
			}
			else
			{
				STRING_HANDLE newSASToken = SASToken_Create(mqttApiState->device_key, mqttApiState->sasTokenSr, zeroLengthString, possibleNewExpiry);

				if (newSASToken == NULL)
				{
					LogError("Could not generate a SAS Token\r\n");
					result = false;
				}
				else
				{
					/* Codes_SRS_MQTTAPI_04_024: [MQTTAPI_Create shall call underlying library connection functions to establish connection with the server.]  */
					if (!connectToMQTTServer(mqttApiState->client, STRING_c_str(mqttApiState->device_id), STRING_c_str(newSASToken)))
					{
						/* Tests_SRS_MQTTAPI_04_025: [If connection fails MQTTAPI_Create shall return NULL. */
						result = false;
					}
					else
					{
						mqttApiState->connected = true;
						mqttApiState->lastExpiryUsed = possibleNewExpiry;
						result = true;
					}
					STRING_delete(newSASToken);
				}
				STRING_delete(zeroLengthString);
			}
		}
		else
		{
			//Here is the point that we need to check if we need to disconnect, generate a new SAS Token and Connect Again. 
			size_t secondsSinceEpoch;
			int differenceWithLastExpiry;
			secondsSinceEpoch = (size_t)(difftime(get_time(NULL), EPOCH_TIME_T_VALUE) + 0);
			differenceWithLastExpiry = mqttApiState->lastExpiryUsed - secondsSinceEpoch;

			/* Codes_SRS_MQTTAPI_04_063: [DoWork shall check the SAS Token Expiration time for the current connection. If the token is near to expire and there is no pending item, it shall disconnect, generate a new SAS Token with 1 hour expiration and connect again.] */
			if ((differenceWithLastExpiry <= 0)	|| 
				(((size_t)differenceWithLastExpiry) < mqttApiState->sasRefreshLine && DList_IsListEmpty(&(mqttApiState->messagesSent))
				)
				) // Within refresh minutes (or past if negative) of the expiration
			{
				/* First Disconnect */
				/* Codes_SRS_MQTTAPI_04_064: [If the token is expired we shall disconnect, signal that all pending message are failed due to Token Expired.] */
				if (MQTTClient_disconnect(mqttApiState->client, 0) != MQTTCLIENT_SUCCESS)
				{
					LogError("Token is Expired or about to be expired and Disconnect Failed. \r\n");
				}
				else
				{
					size_t possibleNewExpiry = secondsSinceEpoch + mqttApiState->sasTokenLifetime;
					STRING_HANDLE zeroLengthString;

					if ((zeroLengthString = STRING_new()) == NULL)
					{
						LogError("Could not generate zeroLenghtString for skn. \r\n");
						result = false;
					}
					else
					{
						STRING_HANDLE newSASToken = SASToken_Create(mqttApiState->device_key, mqttApiState->sasTokenSr, zeroLengthString, possibleNewExpiry);
						mqttApiState->connected = false;

						if (newSASToken == NULL)
						{
							LogError("Could not generate a SAS Token\r\n");
							result = false;
						}
						else
						{
							/* Codes_SRS_MQTTAPI_04_024: [MQTTAPI_Create shall call underlying library connection functions to establish connection with the server.]  */
							if (!connectToMQTTServer(mqttApiState->client, STRING_c_str(mqttApiState->device_id), STRING_c_str(newSASToken)))
							{
								/* Tests_SRS_MQTTAPI_04_025: [If connection fails MQTTAPI_Create shall return NULL. */
								result = false;
							}
							else
							{
								mqttApiState->connected = true;
								mqttApiState->lastExpiryUsed = possibleNewExpiry;
								if (mqttApiState->subscribed)
								{
									int rc;
									LogInfo("Trying to Subscribe after reconnect.\r\n");

									if ((rc = MQTTClient_subscribe(mqttApiState->client, STRING_c_str(mqttApiState->subscribedTopicHandleData->topicName), SUBSCRIBEQOS)) != MQTTCLIENT_SUCCESS)
									{
										LogError("Could not subscribe again. Won't be able to receive messages. Error Code: %d.\r\n", rc);
									}
									else
									{
										LogInfo("Subscribed succesfully after reconnect..\r\n");
									}
								}
								result = true;
							}
							STRING_delete(newSASToken);
						}
						STRING_delete(zeroLengthString);
					}
				}
			}


			result = true;
		}
	}
	else
	{
		LogError("Invalid Arg. Handle is NULL. \r\n");
		result = false;
	}

	return result;
}
Example #22
0
int test5a(struct Options options)
{
	char* testname = "test5a";
	char* test_topic = "C client SSL test5a";
	int subsqos = 2;
	MQTTClient c;
	MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
	MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
	MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
	int rc = 0;

	failures = 0;
	MyLog(LOGA_INFO, "Starting SSL test 5a - Anonymous ciphers - server authentication disabled");
	fprintf(xml, "<testcase classname=\"test3\" name=\"test 5a\"");
	global_start_time = start_clock();
	
	rc = MQTTClient_create(&c, options.anon_connection, "test5a", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore);
	if (!(assert("good rc from create",	rc == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
		goto exit;

	opts.keepAliveInterval = 20;
	opts.cleansession = 1;
	opts.username = "******";
	opts.password = "******";
	if (options.haconnections != NULL)
	{
		opts.serverURIs = options.haconnections;
		opts.serverURIcount = options.hacount;
	}

	opts.ssl = &sslopts;
	opts.ssl->enabledCipherSuites = "aNULL";
	opts.ssl->enableServerCertAuth = 0;

	MyLog(LOGA_DEBUG, "Connecting");

	rc = MQTTClient_connect(c, &opts);
	if (!(assert("Good rc from connect", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;
	rc = MQTTClient_subscribe(c, test_topic, subsqos);
	if (!(assert("Good rc from subscribe", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

	singleThread_sendAndReceive(c, 0, test_topic);
	singleThread_sendAndReceive(c, 1, test_topic);
	singleThread_sendAndReceive(c, 2, test_topic);

	MyLog(LOGA_DEBUG, "Stopping\n");

	rc = MQTTClient_unsubscribe(c, test_topic);
	if (!(assert("Unsubscribe successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;
	rc = MQTTClient_disconnect(c, 0);
	if (!(assert("Disconnect successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

	/* Just to make sure we can connect again */

	rc = MQTTClient_connect(c, &opts);
	if (!(assert("Connect successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;
	rc = MQTTClient_disconnect(c, 0);
	if (!(assert("Disconnect successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

exit:
	MQTTClient_destroy(&c);
	MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
			(failures == 0) ? "passed" : "failed", testname, tests, failures);
	write_test_result();
	return failures;
}
Example #23
0
void MQTTSubscriber::subscribeTopic(const std::string& topic, int qos, MQTTClient_messageArrived* mA, MQTTClient_connectionLost* cL, void* context) {
	MQTTClient_setCallbacks(client , context, cL, mA, NULL);
	MQTTClient_connect(client, &conn_options);
	MQTTClient_subscribe(client, topic.c_str(), qos);
}
Example #24
0
int test3a_m(struct Options options)
{
	char* testname = "test3a_m";
	char* test_topic = "C client test3a_m";
	int subsqos = 2;
	MQTTClient c;
	MQTTClient_connectOptions opts = MQTTClient_connectOptions_initializer;
	MQTTClient_willOptions wopts = MQTTClient_willOptions_initializer;
	MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
	int rc = 0;

	failures = 0;
	MyLog(LOGA_INFO, "Starting test 3a_m - Server authentication - multi-threaded client using callbacks");
	fprintf(xml, "<testcase classname=\"test3\" name=\"test 3a_m\"");
	global_start_time = start_clock();

	rc = MQTTClient_create(&c, options.server_auth_connection, "test3a_m", MQTTCLIENT_PERSISTENCE_DEFAULT, persistenceStore);
	if (!(assert("good rc from create", rc == MQTTCLIENT_SUCCESS, "rc was %d\n", rc)))
		goto exit;

	opts.keepAliveInterval = 20;
	opts.cleansession = 1;
	opts.username = "******";
	opts.password = "******";
	if (options.haconnections != NULL)
	{
		opts.serverURIs = options.haconnections;
		opts.serverURIcount = options.hacount;
	}

	opts.ssl = &sslopts;
	if (options.server_key_file != NULL) 
		opts.ssl->trustStore = options.server_key_file; /*file of certificates trusted by client*/

	rc = MQTTClient_setCallbacks(c, NULL, NULL, multiThread_messageArrived,	multiThread_deliveryComplete);
	if (!(assert("Good rc from setCallbacks", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

	MyLog(LOGA_DEBUG, "Connecting");

	rc = MQTTClient_connect(c, &opts);
	if (!(assert("Good rc from connect", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

	rc = MQTTClient_subscribe(c, test_topic, subsqos);
	if (!(assert("Good rc from subscribe", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

	multiThread_sendAndReceive(c, 0, test_topic);
	multiThread_sendAndReceive(c, 1, test_topic);
	multiThread_sendAndReceive(c, 2, test_topic);

	MyLog(LOGA_DEBUG, "Stopping\n");

	rc = MQTTClient_unsubscribe(c, test_topic);
	if (!(assert("Unsubscribe successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;
	rc = MQTTClient_disconnect(c, 0);
	if (!(assert("Disconnect successful", rc == MQTTCLIENT_SUCCESS, "rc was %d", rc)))
		goto exit;

exit:
	MQTTClient_destroy(&c);
	MyLog(LOGA_INFO, "%s: test %s. %d tests run, %d failures.",
			(failures == 0) ? "passed" : "failed", testname, tests, failures);
	write_test_result();
	return failures;
}
int main(int argc, char* argv[])
{
    //Getting input from the file for subscribing
    char ADDRESS[50];
    char CLIENTID[23];
    char TOPIC[80];
    char PORT[5];
    FILE* fp = fopen("input_sub.config","r");
    fscanf(fp,"%s",ADDRESS);
    fscanf(fp,"%s",CLIENTID);
    fscanf(fp,"%s",TOPIC);
    fscanf(fp,"%s",PORT);
    sprintf(ADDRESS,"%s:%s",ADDRESS,PORT);
    fclose(fp);
    //WiringPi setup
    wiringPiSetupGpio ();
    pinMode (LED_1, OUTPUT);
    pinMode (LED_2, OUTPUT);
    pinMode (LED_3, OUTPUT);
    //pinMode (SWITCH_1, INPUT);
    //pinMode (SWITCH_2, INPUT);
    //pinMode (SWITCH_3, INPUT);
    //Pull up input pins
    pullUpDnControl (SWITCH_1, PUD_UP);
    pullUpDnControl (SWITCH_2, PUD_UP);
    pullUpDnControl (SWITCH_3, PUD_UP);
    //Set Interrupts
    wiringPiISR(SWITCH_1,INT_EDGE_BOTH,&interruptFunc_1);
    wiringPiISR(SWITCH_2,INT_EDGE_BOTH,&interruptFunc_2);
    wiringPiISR(SWITCH_3,INT_EDGE_BOTH,&interruptFunc_3);
    //Pull down the non ground pins
    pullUpDnControl (19, PUD_DOWN);
    pullUpDnControl (26, PUD_DOWN);
    //Lights Initialization
    digitalWrite(LED_1,HIGH);
    digitalWrite(LED_2,LOW);
    digitalWrite(LED_3,LOW);
    delay(100);
    digitalWrite(LED_1,LOW);
    digitalWrite(LED_2,HIGH);
    digitalWrite(LED_3,LOW);
    delay(100);
    digitalWrite(LED_1,LOW);
    digitalWrite(LED_2,LOW);
    digitalWrite(LED_3,HIGH);
    delay(100);
    digitalWrite(LED_1, LOW);
    digitalWrite(LED_2, LOW);
    digitalWrite(LED_3, LOW);

    //MQTT Setup for subscribing
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    int rc;
    int ch;

    MQTTClient_create(&client, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_USER, NULL);
    conn_opts.keepAliveInterval = 100;
    conn_opts.cleansession = 0;

    MQTTClient_setCallbacks(client, NULL, connlost, msgarrvd, delivered);

    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        exit(-1);
    }
    printf("Subscribing to topic %s\nfor client %s using QoS %d\n\n"
           "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
    MQTTClient_subscribe(client, TOPIC, QOS);

    //Start the new thread
    if(piThreadCreate(mqttStream) != 0)
    {
	printf("ERROR in creating MQTT streaming thread");
    }

    //Main loop
    int previousBoxStatus_1,previousBoxStatus_2,previousBoxStatus_3;

    previousBoxStatus_1 = boxStatus_1;
    previousBoxStatus_2 = boxStatus_2;
    previousBoxStatus_3 = boxStatus_3;

    do 
    {
    	//if the previous mode is not the status now publish else do nothing
	if(previousBoxStatus_1 != boxStatus_1){
		delay(debounceDelay);			//Time delay after an interrupt for the signal to be stable
		publishBoxStatus(10,boxStatus_1);
		previousBoxStatus_1 = boxStatus_1;	
	}
	if(previousBoxStatus_2 != boxStatus_2){
                delay(debounceDelay);                     //Time delay after an interrupt for the signal to be stable
                publishBoxStatus(20,boxStatus_2);
                previousBoxStatus_2 = boxStatus_2;
        }
	if(previousBoxStatus_3 != boxStatus_3){
                delay(debounceDelay);                     //Time delay after an interrupt for the signal to be stable
                publishBoxStatus(30,boxStatus_3);
                previousBoxStatus_3 = boxStatus_3;
        }
       // ch = getchar();
    } while(ch!='Q' && ch != 'q');

    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;
}