Esempio n. 1
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;
}
Esempio 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;

    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;
}
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);
}
Esempio n. 4
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;
}
Esempio n. 5
0
static bool connectToMQTTServer(MQTTClient client, const char* username, const char* password)
{
	bool result;
	MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
	MQTTClient_SSLOptions sslopts = MQTTClient_SSLOptions_initializer;
	int rc;
	conn_opts.keepAliveInterval = 20;
	conn_opts.cleansession = 1;
	conn_opts.MQTTVersion = 4;
	conn_opts.username = username;
	conn_opts.password = password;

	conn_opts.ssl = &sslopts;
	sslopts.enableServerCertAuth = 0;

	/* Codes_SRS_MQTTAPI_04_024: [MQTTAPI_Create shall call underlying library connection functions to establish connection with the server.]  */
	if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
	{
		LogError("Failed to connect, MQTTClient_connect returned: %d\r\n", rc);
		result = false;
	}
	else
	{
		result = true;
	}

	return result;
}
Esempio n. 6
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();
   }
}
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;
}
Esempio n. 8
0
void myconnect(MQTTClient* client, MQTTClient_connectOptions* opts)
{
	printf("Connecting\n");
	if (MQTTClient_connect(*client, opts) != 0)
	{
		printf("Failed to connect\n");
		exit(-1);	
	}
}
Esempio n. 9
0
void myconnect(MQTTClient* client, MQTTClient_connectOptions* opts)
{
	int rc = 0;
	if ((rc = MQTTClient_connect(*client, opts)) != 0)
	{
		printf("Failed to connect, return code %d\n", rc);
		exit(-1);	
	}
}
// [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;
}
Esempio n. 11
0
/*********************************************************************

Test2c: Mutual SSL Authentication - Client does not have Server cert

*********************************************************************/
int test2c(struct Options options)
{
	char* testname = "test2c";
	char* test_topic = "C client test2c";
	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 2c - connection to SSL MQTT server, server auth enabled but unknown cert");
	fprintf(xml, "<testcase classname=\"test3\" name=\"test 2c\"");
	global_start_time = start_clock();
	
	rc = MQTTClient_create(&c, options.mutual_auth_connection, "test2c", 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;
	//opts.ssl->enabledCipherSuites = "DEFAULT";
	//opts.ssl->enabledServerCertAuth = 0;

	MyLog(LOGA_DEBUG, "Connecting");

	rc = MQTTClient_connect(c, &opts);
	if (!(assert("Good rc from connect", rc == MQTTCLIENT_FAILURE, "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;
}
Esempio n. 12
0
/**
 * @name Create and initialize the MQTT client
 * @brief initializes the plugin.
 * @param[in] servQuery is the service query being queried for
 * @return boolean, which specifies whether the connection is successfully established or not
 *
 * Establishes the connection with an MQTT broker.
 */
int init(void *servQuery) {
    ServiceQuery *serviceQuery = (ServiceQuery *) servQuery;
    int rc = 0;
    char uri[256];

    if (isPresentPropertyInCommParams(serviceQuery, "ssl") == true && \
        strcasecmp(getValueInCommParams(serviceQuery, "ssl"), "true") == 0) {
        sprintf(uri, "ssl://%s:%d", serviceQuery->address, serviceQuery->port);

        conn_opts.ssl = &sslopts;

        if (isPresentPropertyInCommParams(serviceQuery, "keyStore")) {
            conn_opts.ssl->keyStore = getValueInCommParams(serviceQuery, "keyStore");
        }
        if (isPresentPropertyInCommParams(serviceQuery, "privateKey")) {
            conn_opts.ssl->privateKey = getValueInCommParams(serviceQuery, "privateKey");
        }
        if (isPresentPropertyInCommParams(serviceQuery, "trustStore")) {
            conn_opts.ssl->trustStore = getValueInCommParams(serviceQuery, "trustStore");
        }

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

    // Default settings:
    char clientID[256];
    sprintf(clientID, "%s_%d", CLIENTID, getpid());

    MQTTClient_create(&client, uri, clientID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    MQTTClient_setCallbacks(client, serviceQuery, connectionLost, messageArrived, NULL);

    conn_opts.cleansession = 0;
    conn_opts.keepAliveInterval = 20;
    conn_opts.retryInterval = 0;

    if (isPresentPropertyInCommParams(serviceQuery, "username") == true && \
        isPresentPropertyInCommParams(serviceQuery, "password") == true) {
        conn_opts.username = getValueInCommParams(serviceQuery, "username");
        conn_opts.password = getValueInCommParams(serviceQuery, "password");
    }

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

    return rc;
}
Esempio n. 13
0
MQTTClient *mqtt_create(char *clientid, MQTTClient_messageArrived *arrived) {
	int rc = 0;
	MQTTClient *context = (MQTTClient*)malloc(sizeof(MQTTClient));
	MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;

	MQTTClient_create(context, MQTT_ADDRESS, clientid, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    conn_opts.keepAliveInterval = 0;
    conn_opts.cleansession = 1;
	if(arrived) MQTTClient_setCallbacks(*context, NULL, NULL, arrived, NULL);
	MQTTClient_connect(*context, &conn_opts);
	return context;
}
Esempio n. 14
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);
   }
}
Esempio n. 15
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;
}
Esempio n. 16
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);
}
Esempio n. 17
0
// 通信の開始を試みる
DWORD __stdcall CConMQTT::vTryConnect(LPVOID lpArg)
{
	// 局所変数宣言
	MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;    // 接続オプション

	conn_opts.keepAliveInterval = 20;   // キープアライブ [sec]
	conn_opts.cleansession = 1;         // ?

	if (MQTTClient_connect(*reinterpret_cast<MQTTClient*>(lpArg), &conn_opts) != MQTTCLIENT_SUCCESS)
	{
		return -1;
	}

	return 0;
}
Esempio n. 18
0
void connectionLost(void *context, char *cause) {
    ServiceQuery *serviceQuery = (ServiceQuery *)context;
    int rc;

    printf("Connection lost due to :%s\n", cause);
    printf("Reconnecting...\n");

    conn_opts.cleansession = 1;
    conn_opts.keepAliveInterval = 20;
    conn_opts.retryInterval = 1000;

    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS) {
        printf("Failed to start connect, return code %d\n", rc);
        exit(1);
    }
}
Esempio n. 19
0
// 通信の開始を試みる
DWORD __stdcall CConMQTT::startConnect(LPVOID lpArg)
{
	MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;

	conn_opts.keepAliveInterval = 20;
	conn_opts.cleansession = 1;

	if (MQTTClient_connect(*reinterpret_cast<MQTTClient*>(lpArg), &conn_opts) != MQTTCLIENT_SUCCESS)
	{
		printf("Failed to connect\n");
		return -1;
		//exit(-1);
	}

	return 0;
}
Esempio n. 20
0
/*********************************************************************

Test1: SSL connection to non SSL MQTT server

*********************************************************************/
int test1(struct Options options)
{
	char* testname = "test1";
	char* test_topic = "C client SSL test1";
	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 1 - connection to nonSSL MQTT server");
	fprintf(xml, "<testcase classname=\"test3\" name=\"SSL connect fail to nonSSL MQTT server\"");
	global_start_time = start_clock();
	
	rc = MQTTClient_create(&c, options.connection, "test1",	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*/

	MyLog(LOGA_DEBUG, "Connecting");

	rc = MQTTClient_connect(c, &opts);
	if (!(assert("Connect should fail", rc == MQTTCLIENT_FAILURE, "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;
}
Esempio n. 21
0
/*********************************************************************

Test3b: Server Authentication - Client does not have server cert

*********************************************************************/
int test3b(struct Options options)
{
	char* testname = "test3b";
	char* test_topic = "C client test3b";
	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 3b - connection to SSL MQTT server with clientauth=opt but client does not have server cert");
	
	if (!(assert("good rc from create", (rc = MQTTClient_create(&c, options.connection, "test3b", 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 = 0;

	MyLog(LOGA_DEBUG, "Connecting");

	if (!(assert("Good rc from connect", (rc = MQTTClient_connect(c, &opts)) == MQTTCLIENT_FAILURE, "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;
}
Esempio n. 22
0
//--------------------------------------------------------------------------------------------------
le_result_t mqtt_Connect
(
    mqtt_SessionRef_t sessionRef   ///< [IN] Session to connect
)
{
    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 connectResult = MQTTClient_connect(s->client, &s->connectOptions);
    le_result_t result;
    switch (connectResult)
    {
        case SOCKET_ERROR:
            LE_WARN("Socket error");
            result = LE_FAULT;
            break;

        case MQTTCLIENT_NULL_PARAMETER:
        case MQTTCLIENT_BAD_STRUCTURE:
        case MQTTCLIENT_BAD_UTF8_STRING:
            result = LE_BAD_PARAMETER;
            break;

        case MQTTCLIENT_SUCCESS:
            result = LE_OK;
            break;

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

    return result;
}
Esempio n. 23
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;
}
Esempio n. 24
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;
}
Esempio n. 25
0
File: mqtt.c Progetto: tok101/tok101
int mqtt_client_connect(MQTTClient* pClient, const char* address, const char* clientid , MQTTClient_connectionLost* connlost,
														MQTTClient_messageArrived* msgarrvd, MQTTClient_deliveryComplete* delivered)
{
	MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
	int rc;
//	  int ch;

	MQTTClient_create(pClient, address, clientid,
		MQTTCLIENT_PERSISTENCE_NONE, NULL);
	conn_opts.keepAliveInterval = 20;
	conn_opts.cleansession = 1;

	MQTTClient_setCallbacks(*pClient, NULL, connlost, msgarrvd, delivered);

	if ((rc = MQTTClient_connect(*pClient, &conn_opts)) != MQTTCLIENT_SUCCESS)
	{
		LOG_E("Failed to connect, return code %d\n", rc);
		MQTTClient_destroy(pClient);
		return -1;		 
	}
	return rc;
}
Esempio n. 26
0
// -------------------------------------------------------------------
// INITIALISATION DE LA CONNEXION AU BROCKER MQTT
// -------------------------------------------------------------------
int mqtt_init(const char *IPaddress, const char *clientID, MQTTClient_messageArrived* msgarr){
		int rc;

		MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
		//MQTTClient_message pubmsg = MQTTClient_message_initializer;

		// Configuration des param�tres de connexion
		MQTTClient_create(&client, IPaddress, clientID, MQTTCLIENT_PERSISTENCE_NONE, NULL);

		conn_opts.keepAliveInterval = 20;
		conn_opts.cleansession = 1;
		// Fin de config connexion

		// Configuration de la fonction callback de souscription
		MQTTClient_setCallbacks(client, NULL, connlost, msgarr, delivered);

		// Tentative de connexion au broker mqtt
		if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
		{
			return(rc);
		}else return 0;
	}
Esempio n. 27
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;
}
Esempio n. 28
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;
}
Esempio n. 29
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;
}
Esempio n. 30
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;
}