Exemplo n.º 1
0
void log_mqtt(std::string payload) {
  if (!getenv("MQTT_SERVER")) {
    return;
  }

  init_mqtt();

  int rc;

  if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
  {
    std::cout << "Failed to connect to MQTT server, return code:" << rc << std::endl;
    return;
  }

  std::stringstream json;
  json << "{\"d\": " << payload << " }";
  std::string jsonStr = json.str();

  pubmsg.payload = &jsonStr;
  pubmsg.payloadlen = json.str().length();
  pubmsg.qos = QOS;
  pubmsg.retained = 0;
  MQTTClient_publishMessage(client, getenv("MQTT_TOPIC"), &pubmsg, &token);
  std::cout << "Publishing to MQTT server on" << getenv("MQTT_TOPIC") << std::endl;
  std::cout << json.str() << std::endl;
  rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
  std::cout << "MQTT message delivered" << std::endl;
  MQTTClient_disconnect(client, 10000);
}
Exemplo n.º 2
0
int main(int argc, char* argv[])
{
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    MQTTClient_deliveryToken token;
    int rc;

    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);	
    }
    pubmsg.payload = PAYLOAD;
    pubmsg.payloadlen = strlen(PAYLOAD);
    pubmsg.qos = QOS;
    pubmsg.retained = 0;
    deliveredtoken = 0;
    MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
    printf("Waiting for publication of %s\n"
            "on topic %s for client with ClientID: %s\n",
            PAYLOAD, TOPIC, CLIENTID);
    while(deliveredtoken != token);
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;
}
Exemplo n.º 3
0
int main(int argc, char* 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(EXIT_FAILURE);
    }
    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;
}
Exemplo n.º 4
0
void MQTT::disconnect()
{
	try
	{
		_started = false;
		if(_client)
		{
			MQTTClient_disconnect(_client, 10000);
			MQTTClient_destroy(&_client);
			_client = nullptr;
		}
		if(_connectionOptions)
		{
			delete((MQTTClient_connectOptions*)_connectionOptions);
			_connectionOptions = nullptr;
		}
		if(_sslOptions)
		{
			delete((MQTTClient_SSLOptions*)_sslOptions);
			_sslOptions = nullptr;
		}
	}
	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__);
	}
}
Exemplo n.º 5
0
int main(int argc, char* argv[])
{
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    MQTTClient_deliveryToken token;
    int rc;

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

    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        exit(-1);
    }
    pubmsg.payload = PAYLOAD;
    pubmsg.payloadlen = strlen(PAYLOAD);
    pubmsg.qos = QOS;
    pubmsg.retained = 0;
    MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
    printf("Waiting for up to %d seconds for publication of %s\n"
            "on topic %s for client with ClientID: %s\n",
            (int)(TIMEOUT/1000), PAYLOAD, TOPIC, CLIENTID);
    rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
    printf("Message with delivery token %d delivered\n", token);
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;
}
int main()
{
	// check that we are running on Galileo or Edison
	mraa::Platform platform = mraa::getPlatformType();
	if ((platform != mraa::INTEL_GALILEO_GEN1) &&
			(platform != mraa::INTEL_GALILEO_GEN2) &&
			(platform != mraa::INTEL_EDISON_FAB_C)) {
		std::cerr << "Unsupported platform, exiting" << std::endl;
		return mraa::ERROR_INVALID_PLATFORM;
	}

	// create the MQTT client
	int rc = 0;
	rc = MQTTClient_create(&client, const_cast<char *>(host),
			const_cast<char *>(clientID), MQTTCLIENT_PERSISTENCE_NONE, NULL);
	if (rc != MQTTCLIENT_SUCCESS) {
		std::cerr << "Failed to create MQTT client, exiting" << std::endl;
		exit(rc);
	}

	// setup call backs before connecting the client to the server
	MQTTClient_setCallbacks(client, NULL,
			&connection_lost, NULL, &delivery_complete);

	MQTTClient_connectOptions data = MQTTClient_connectOptions_initializer;
	data.username = const_cast<char *>(username);
	data.password = const_cast<char *>(password);
	// connect the client to the server
	rc = MQTTClient_connect(client, &data);
	if (rc != MQTTCLIENT_SUCCESS) {
		std::cerr << "Failed to connect MQTT client, exiting" << std::endl;
		exit(rc);
	}

	// led connected to D3 (digital out)
	upm::GroveLed* led = new upm::GroveLed(3);

	// temperature sensor connected to A0 (analog in)
	upm::GroveTemp* temp_sensor = new upm::GroveTemp(0);

	// simple error checking
	if ((led == NULL) || (temp_sensor == NULL)) {
		std::cerr << "Can't create all objects, exiting" << std::endl;
		return mraa::ERROR_UNSPECIFIED;
	}

	// loop forever updating the temperature values every second
	for (;;) {
		temperature_update(temp_sensor, led);
		sleep(1);
	}

	printf("Stopping\n");

	int timeout = 100;
	MQTTClient_disconnect(client, timeout);
	MQTTClient_destroy(&client);
	return mraa::SUCCESS;
}
Exemplo n.º 7
0
Arquivo: mqtt.c Projeto: tok101/tok101
int mqtt_client_disconnect(MQTTClient* pClient)
{
	if (!*pClient)
		return 0;
    MQTTClient_disconnect(*pClient, 10000);
    MQTTClient_destroy(pClient);
	return 0;
}
Exemplo n.º 8
0
void *sync_func(void *arg)
{
	int fd_cl, t_seek=0, synced_events, synced_count=0, total_count=0;
	char buf[MSG_LEN], events_buf[32];
	int ret=0;

	while(1) {
		ret = check_data_status();
		if((ret > 0) &&  client_connect()) {

		//	printf("data_status : %d\n", check_data_status());
			
			pthread_mutex_lock(&mtx);
			fd_cl = open(CLIENT_FILENAME, O_SYNC | O_RDONLY, 0666);	
			do {
				total_count = current_events(1);
				synced_count = current_events(2);
				printf("++ total_events: %d || synced_events: %d\n", total_count, synced_count);
				ret = lseek(fd_cl, 0, SEEK_SET);
				printf("VDEBUG__ 11 Seek position = %d || return %d\n", 0, ret);
				ret = lseek(fd_cl, (MSG_LEN*synced_count), SEEK_SET);
				printf("VDEBUG__ 22 Seek position = %d || return %d\n", (MSG_LEN*synced_count), ret);
				ret = read(fd_cl, buf, MSG_LEN);
				printf("VDEBUG__ sync_func() read %d bytes\n", ret);

				printf("VDEBUG__ Buffer to publish: %s\n", buf);

				if(!publish(MSG_LEN, buf)) {				/* Considering publish will return 0 when sucess */
					/* Saving number of events to disk */
					synced_events = open("SYNCED_EVENTS", O_CREAT | O_TRUNC | O_SYNC | O_WRONLY, 0666);
					ret = lseek(synced_events, 0, SEEK_SET);
					printf("VDEBUG__ lseeked synced count file to %d\n", ret);
					sprintf(events_buf, "%d", ++synced_count);
here:				ret = write(synced_events, events_buf, strlen(events_buf));
					close(synced_events);
					if (ret==-1) {
						printf("VDEBUG__ writing synced count failed !\n");
						printf("Retrying..\n");
						sleep(1);
						goto here;
					}
					printf("VDEBUG__ written synced count %d\n", synced_count);
				}
			} while (synced_count < total_count);
			close(fd_cl);

			MQTTClient_disconnect(client, 10000);
			pthread_mutex_unlock(&mtx);
		}
		else {
			sleep(10);
		}
	}
	pthread_exit(NULL);	
}
// [START iot_mqtt_publish]
int Publish(char* payload, int payload_size) {
  int rc = -1;
  MQTTClient client = {0};
  MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
  MQTTClient_message pubmsg = MQTTClient_message_initializer;
  MQTTClient_deliveryToken token = {0};

  MQTTClient_create(&client, opts.address, opts.clientid,
      MQTTCLIENT_PERSISTENCE_NONE, NULL);
  conn_opts.keepAliveInterval = 20;
  conn_opts.cleansession = 1;
  conn_opts.username = kUsername;
  conn_opts.password = CreateJwt(opts.ecpath, opts.projectid);
  MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;

  sslopts.trustStore = opts.rootpath;
  sslopts.privateKey = opts.ecpath;
  conn_opts.ssl = &sslopts;

  unsigned long retry_interval_ms = kInitialConnectIntervalMillis;
  unsigned long total_retry_time_ms = 0;
  while ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) {
    if (rc == 3) {  // connection refused: server unavailable
      usleep(retry_interval_ms / 1000);
      total_retry_time_ms += retry_interval_ms;
      if (total_retry_time_ms >= kMaxConnectRetryTimeElapsedMillis) {
        printf("Failed to connect, maximum retry time exceeded.");
        exit(EXIT_FAILURE);
      }
      retry_interval_ms *= kIntervalMultiplier;
      if (retry_interval_ms > kMaxConnectIntervalMillis) {
        retry_interval_ms = kMaxConnectIntervalMillis;
      }
    } else {
      printf("Failed to connect, return code %d\n", rc);
      exit(EXIT_FAILURE);
    }
  }

  pubmsg.payload = payload;
  pubmsg.payloadlen = payload_size;
  pubmsg.qos = kQos;
  pubmsg.retained = 0;
  MQTTClient_publishMessage(client, opts.topic, &pubmsg, &token);
  printf("Waiting for up to %lu seconds for publication of %s\n"
          "on topic %s for client with ClientID: %s\n",
          (kTimeout/1000), opts.payload, opts.topic, opts.clientid);
  rc = MQTTClient_waitForCompletion(client, token, kTimeout);
  printf("Message with delivery token %d delivered\n", token);
  MQTTClient_disconnect(client, 10000);
  MQTTClient_destroy(&client);

  return rc;
}
Exemplo n.º 10
0
static PyObject* mqttv3_disconnect(PyObject* self, PyObject *args)
{
	MQTTClient c;
	int timeout = 0;
	int rc;

	if (!PyArg_ParseTuple(args, "k|i", &c, &timeout))
		return NULL;
	Py_BEGIN_ALLOW_THREADS rc = MQTTClient_disconnect(c, timeout);
	Py_END_ALLOW_THREADS
	return Py_BuildValue("i", rc);
}
Exemplo n.º 11
0
/**
 * @name Disconnect and destroy the MQTT client
 * @brief Used to close the connections for cleanup activities.
 * @return boolean, which specifies whether the connection is disconnected or not
 */
int done() {
    int rc = 0;

    if ((rc = MQTTClient_disconnect(client, 10000)) != MQTTCLIENT_SUCCESS) {
        printf("Failed to start disconnect, return code %d\n", rc);
        exit(-1);
    }

    MQTTClient_destroy(&client);

    return rc;
}
Exemplo n.º 12
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;
}
Exemplo n.º 13
0
void log_mqtt(std::string payload) {
  if (!getenv("MQTT_SERVER")) {
    return;
  }

  MQTTClient client;
  MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
  MQTTClient_message pubmsg = MQTTClient_message_initializer;
  MQTTClient_deliveryToken token;
  int rc;

  MQTTClient_create(&client, getenv("MQTT_SERVER"), getenv("MQTT_CLIENTID"),
     MQTTCLIENT_PERSISTENCE_NONE, NULL);
  conn_opts.keepAliveInterval = 20;
  conn_opts.cleansession = 1;
  conn_opts.username = getenv("MQTT_USERNAME");
  conn_opts.password = getenv("MQTT_PASSWORD");

  MQTTClient_SSLOptions sslOptions = MQTTClient_SSLOptions_initializer;
  if (getenv("MQTT_CERT") && getenv("MQTT_KEY") && getenv("MQTT_CA")) {
    sslOptions.keyStore = getenv("MQTT_CERT");
    sslOptions.privateKey = getenv("MQTT_KEY");
    sslOptions.trustStore = getenv("MQTT_CA");
  } else {
    sslOptions.enableServerCertAuth = false;
  };
  conn_opts.ssl = &sslOptions;

  if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
  {
    std::cout << "Failed to connect to MQTT server, return code:" << rc << std::endl;
    return;
  }

  std::stringstream json;
  json << "{\"d\": " << payload << " }";
  std::string jsonStr = json.str();

  pubmsg.payload = &jsonStr;
  pubmsg.payloadlen = json.str().length();
  pubmsg.qos = QOS;
  pubmsg.retained = 0;
  MQTTClient_publishMessage(client, getenv("MQTT_TOPIC"), &pubmsg, &token);
  std::cout << "Publishing to MQTT server on" << getenv("MQTT_TOPIC") << std::endl;
  std::cout << json.str() << std::endl;
  rc = MQTTClient_waitForCompletion(client, token, TIMEOUT);
  std::cout << "MQTT message delivered" << std::endl;
  MQTTClient_disconnect(client, 10000);
  MQTTClient_destroy(&client);
}
Exemplo n.º 14
0
bool CConMQTT::bDisconnect(void)
{
	// 局所変数宣言
	int iRet;

	// 通信を切断する
	iRet = MQTTClient_disconnect(m_Client, TIMEOUT);
	if (MQTTCLIENT_SUCCESS != iRet) {
		return false;
	}

	MQTTClient_destroy(&m_Client);

	m_bConected = false;

	return true;
}
Exemplo n.º 15
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;
}
Exemplo n.º 16
0
//--------------------------------------------------------------------------------------------------
le_result_t mqtt_Disconnect
(
    mqtt_SessionRef_t sessionRef   ///< [IN] Session to disconnect
)
{
    mqtt_Session* s = le_ref_Lookup(SessionRefMap, sessionRef);
    if (s == NULL)
    {
        LE_KILL_CLIENT("Session doesn't exist");
        return LE_FAULT;
    }
    if (s->clientSession != mqtt_GetClientSessionRef())
    {
        LE_KILL_CLIENT("Session doesn't belong to this client");
        return LE_FAULT;
    }

    const int waitBeforeDisconnectMs = 0;
    const int disconnectResult = MQTTClient_disconnect(s->client, waitBeforeDisconnectMs);
    le_result_t result;
    switch (disconnectResult)
    {
        case MQTTCLIENT_SUCCESS:
            result = LE_OK;
            break;

        case MQTTCLIENT_FAILURE:
            result = LE_FAULT;
            break;

        case MQTTCLIENT_DISCONNECTED:
            result = LE_FAULT;
            LE_WARN("Already disconnected");
            break;

        default:
            LE_WARN("Paho disconnect returned (%d)", disconnectResult);
            result = LE_FAULT;
            break;
    }

    return result;
}
Exemplo n.º 17
0
int main(int argc, char* argv[])
{
    if(argc < 4) {
        std::cout << "usage: " << argv[0] << " server_url user password" << std::endl;
        return -1;
    }

    std::cout << argv[0] << " " << argv[1] << " " << argv[2] << " " << argv[3] << std::endl;


    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    MQTTClient_deliveryToken token;
    int rc;
    MQTTClient_create(&client, argv[1], CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    conn_opts.username = argv[2];
    conn_opts.password = argv[3];
    conn_opts.connectTimeout = 200;


    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);
    }
    pubmsg.payload = const_cast<char*>(PAYLOAD);
    pubmsg.payloadlen = strlen(PAYLOAD);
    pubmsg.qos = QOS;
    pubmsg.retained = 0;
    deliveredtoken = 0;
    MQTTClient_publishMessage(client, TOPIC, &pubmsg, &token);
    printf("Waiting for publication of %s\n"
           "on topic %s for client with ClientID: %s\n",
           PAYLOAD, TOPIC, CLIENTID);
    while(deliveredtoken != token);
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;
}
Exemplo n.º 18
0
void *algoidTask (void * arg){
	printf ("# Demarrage tache ALGOID Protocol: OK\n");
	 													// duty cycle is 50% for ePWM0A , 25% for ePWM0B;
// BOUCLE PRINCIPALE
	    while(!EndOfApp)
	    {
	    // Envoie le prochaine message en attente dans la pile
	    	SendQueueingTXmsg(algoidMsgTXStack);
	    	usleep(100000);
	    }
 // FIN BOUCLE PRINCIPAL

	    MQTTClient_disconnect(client, 10000);
	    MQTTClient_destroy(&client);

	    return 0;
  usleep(5000);

  printf( "# ARRET tache ALGOID\n");

  usleep(10000);
  pthread_exit (0);
}
Exemplo n.º 19
0
int main(int argc, char** argv)
{
	MQTTClient client;
	MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
	MQTTClient_SSLOptions ssl_opts = MQTTClient_SSLOptions_initializer;
	char* topic = NULL;
	char* buffer = NULL;
	int rc = 0;
	char url[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);
	
	topic = argv[1];
	printf("Using topic %s\n", topic);

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

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

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

	conn_opts.keepAliveInterval = 10;
	conn_opts.reliable = 0;
	conn_opts.cleansession = 1;
	conn_opts.username = opts.username;
	conn_opts.password = opts.password;
	ssl_opts.enableServerCertAuth = 0;
	conn_opts.ssl = &ssl_opts;
	
	myconnect(&client, &conn_opts);

	buffer = malloc(opts.maxdatalen);
	
	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, opts.qos, opts.retained, NULL);
		if (rc != 0)
		{
			myconnect(&client, &conn_opts);
			rc = MQTTClient_publish(client, topic, data_len, buffer, opts.qos, opts.retained, NULL);
		}
		if (opts.qos > 0)
			MQTTClient_yield();
	}
	
	printf("Stopping\n");
	
	free(buffer);

	MQTTClient_disconnect(client, 0);

 	MQTTClient_destroy(&client);

	return 0;
}
Exemplo n.º 20
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;
}
Exemplo n.º 21
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;
}
Exemplo n.º 22
0
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;
}
Exemplo n.º 23
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;
}
Exemplo n.º 24
0
// 通信の終了
bool CConMQTT::bDisconnect(void)
{
	MQTTClient_disconnect(m_client, TIMEOUT);
	MQTTClient_destroy(&m_client);
	return true;
}
Exemplo n.º 25
0
void MQTTAPI_Destroy(MQTTAPI_HANDLE instance)
{
	PMQTTTAPI_HANDLE_DATA mqttHandleData = instance;

	/* Codes_SRS_MQTTAPI_04_021: [If parameter instance is NULL then MQTTAPI_Destroy shall take no action.] */
	if (mqttHandleData != NULL)
	{
		/* Codes_SRS_MQTTAPI_04_022: [MQTTAPI_Destroy shall free all resources used by MQTTAPI_HANDLE.]  */
		STRING_delete(mqttHandleData->device_id);
		STRING_delete(mqttHandleData->device_key);
		STRING_delete(mqttHandleData->sasTokenSr);
		/* Codes_SRS_MQTTAPI_04_049: [If the instance is connected, MQTTAPI_Destroy shall disconnect the instance] */
		if (mqttHandleData->subscribed)
		{
			MQTTAPI_Unsubscribe(mqttHandleData->subscribedTopicHandleData);
		}

		if (mqttHandleData->connected)
		{
			MQTTClient_disconnect(mqttHandleData->client, 0);
		}

		/* Codes_SRS_MQTTAPI_04_053: [If there are messages to be sent MQTTAPI_Destroy shall signalize the user that the message couldn’t be sent by reason of MQTTAPI_CONFIRMATION_BECAUSE_DESTROY]  */
		{
			PDLIST_ENTRY received;
			while ((received = DList_RemoveHeadList(&(mqttHandleData->messagesReceived))) != &(mqttHandleData->messagesReceived))
			{
				MQTTAPI_MESSAGE_RECEIVED_LIST* temp = containingRecord(received, MQTTAPI_MESSAGE_RECEIVED_LIST, entry);
				if (mqttHandleData->maCallBack != NULL)
				{
					if (!mqttHandleData->maCallBack(mqttHandleData->maCallbackContext, temp->messageReceived))
					{
						LogError("Client could not handle message, dropping it.");
					}
				}

				free(temp->messageReceived->payload);
				free(temp->messageReceived);
				free(temp);
			}
		}

		{
			PDLIST_ENTRY messageToSend;
			while ((messageToSend = DList_RemoveHeadList(&(mqttHandleData->messagesToSend))) != &(mqttHandleData->messagesToSend))
			{
				MQTTAPI_MESSAGE_SEND_LIST* temp = containingRecord(messageToSend, MQTTAPI_MESSAGE_SEND_LIST, entry);

				if (mqttHandleData->dcCallback != NULL)
				{
					mqttHandleData->dcCallback(temp->context, MQTTAPI_CONFIRMATION_BECAUSE_DESTROY);
					MQTTClient_freeMessage(&(temp->messageToSend));
					free(temp->messageToSend);
					STRING_delete(temp->topicName);
					free(temp);
				}
			}
		}

		{
			PDLIST_ENTRY currentListEntry;
			while ((currentListEntry = DList_RemoveHeadList(&(mqttHandleData->messagesSent))) != &(mqttHandleData->messagesSent))
			{
				MQTTAPI_MESSAGE_SEND_LIST* temp = containingRecord(currentListEntry, MQTTAPI_MESSAGE_SEND_LIST, entry);

				if (mqttHandleData->dcCallback != NULL)
				{
					mqttHandleData->dcCallback(temp->context, MQTTAPI_CONFIRMATION_BECAUSE_DESTROY);
					MQTTClient_freeMessage(&(temp->messageToSend));
					free(temp->messageToSend);
					STRING_delete(temp->topicName);
					free(temp);
				}
			}
		}

		MQTTClient_destroy(mqttHandleData->client);
		Lock_Deinit(mqttHandleData->LockHandle);
		free(mqttHandleData);
	}
}
Exemplo n.º 26
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;
}
Exemplo n.º 27
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;
}
Exemplo n.º 28
0
void MQTTSubscriber::disconnect() {
	MQTTClient_disconnect(client, 1000L);
	MQTTClient_destroy(&client);
}
Exemplo n.º 29
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;
}
Exemplo n.º 30
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;
}