Ejemplo n.º 1
0
int main(int argc, char *argv[])
{
	int i;
	char *host = "localhost";
	int port = 1883;
	int keepalive = 60;
	bool clean_session = false;  // Note this, set it to false if you want to get offline message
	struct mosquitto *mosq = NULL;

	mosquitto_lib_init();

	// Note this, this first argv is id, it must be set if clean_session is false
	mosq = mosquitto_new("1", clean_session, NULL);

	if(!mosq){
		fprintf(stderr, "Error: Out of memory.\n");
		return 1;
	}
	mosquitto_log_callback_set(mosq, my_log_callback);
	mosquitto_connect_callback_set(mosq, my_connect_callback);
	mosquitto_message_callback_set(mosq, my_message_callback);
	mosquitto_subscribe_callback_set(mosq, my_subscribe_callback);

	if(mosquitto_connect(mosq, host, port, keepalive)){
		fprintf(stderr, "Unable to connect.\n");
		return 1;
	}

	while(!mosquitto_loop(mosq, -1, 1)){
	}
	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup();
	return 0;
}
Ejemplo n.º 2
0
void
mloop(dispatch_data *dd) {
	char id[30];

	char *host = "130.102.128.123";
	int port = 1883;
	int keepalive = 60;
	bool clean_session = true;
	struct mosquitto *mosq = NULL;
	
	local_dd = dd;
	
	mosq = mosquitto_new(id, NULL);
	if(!mosq){
		fprintf(stderr, "Error: Out of memory.\n");
		return;
	}
	mosq_instance=mosq;
	mosquitto_connect_callback_set(mosq, my_connect_callback);
	mosquitto_message_callback_set(mosq, my_message_callback);
	mosquitto_subscribe_callback_set(mosq, my_subscribe_callback);
	
	if(mosquitto_connect(mosq, host, port, keepalive, clean_session)){
		fprintf(stderr, "Unable to connect.\n");
		return;
	}
	
	while(mosquitto_loop(mosq, -1) != -1){
	}
	mosquitto_destroy(mosq);
	return;
}
Ejemplo n.º 3
0
/* Register the callbacks that the mosquitto connection will use. */
static bool set_callbacks(struct mosquitto *m) {
	mosquitto_connect_callback_set(m, on_connect);
	mosquitto_publish_callback_set(m, on_publish);
	mosquitto_subscribe_callback_set(m, on_subscribe);
	mosquitto_message_callback_set(m, on_message);
	return true;
}
Ejemplo n.º 4
0
Archivo: main.c Proyecto: quedah/techgi
int main(int argc, char *argv[])
{
    int port, client_id, buffer_size;
    int rc;
    struct mosquitto *mosq;

    void* buffer;

    char line[1024];
    const char *name;

    //prepare arguments
    if(argc < 3) {
        printf("usage: %s host port [id]\n", argv[0]);
        return 0;
    }

    port = atoi(argv[2]);
    client_id = -1;
    if(argc > 3) {
        client_id = atoi(argv[3]);
    }

    pthread_mutex_init(&mutex, NULL);

    name = init(client_id);

    //start mosquitto stuff
    mosquitto_lib_init();

    mosq = mosquitto_new(name, true, NULL);
    mosquitto_connect_callback_set(mosq, on_connect);
    mosquitto_subscribe_callback_set(mosq, on_subscribe);
    mosquitto_message_callback_set(mosq, on_message);

    rc = mosquitto_connect_async(mosq, argv[1], port, 60);
    mosquitto_loop_start(mosq);

    while(1) {
        fgets(line, 1024, stdin);

        pthread_mutex_lock(&mutex);
        buffer = message_entered(line, &buffer_size);
        pthread_mutex_unlock(&mutex);

        int sent_mid = -1;
        mosquitto_publish(mosq, &sent_mid, topic_name, buffer_size, buffer, 0, false);

        message_sent(buffer, buffer_size);
    }

    mosquitto_disconnect(mosq);
    mosquitto_loop_stop(mosq, false);

    mosquitto_lib_cleanup();

    cleanup();

    return 0;
}
Ejemplo n.º 5
0
/* {{{ Mosquitto\Client::onSubscribe() */
PHP_METHOD(Mosquitto_Client, onSubscribe)
{
	mosquitto_client_object *object;
	zend_fcall_info subscribe_callback = empty_fcall_info;
	zend_fcall_info_cache subscribe_callback_cache = empty_fcall_info_cache;

	PHP_MOSQUITTO_ERROR_HANDLING();
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "f!",
				&subscribe_callback, &subscribe_callback_cache)  == FAILURE) {

		PHP_MOSQUITTO_RESTORE_ERRORS();
		return;
	}
	PHP_MOSQUITTO_RESTORE_ERRORS();

	object = (mosquitto_client_object *) mosquitto_client_object_get(getThis() TSRMLS_CC);

	if (!ZEND_FCI_INITIALIZED(subscribe_callback)) {
		zend_throw_exception(mosquitto_ce_exception, "Need a valid callback", 0 TSRMLS_CC);
	}

	object->subscribe_callback = subscribe_callback;
	object->subscribe_callback_cache = subscribe_callback_cache;
	Z_ADDREF_P(subscribe_callback.function_name);

	if (subscribe_callback.object_ptr != NULL) {
		Z_ADDREF_P(subscribe_callback.object_ptr);
	}

	mosquitto_subscribe_callback_set(object->client, php_mosquitto_subscribe_callback);
}
Ejemplo n.º 6
0
mosquittopp::mosquittopp(const char *id)
{
	mosq = mosquitto_new(id, this);
	mosquitto_connect_callback_set(mosq, on_connect_wrapper);
	mosquitto_disconnect_callback_set(mosq, on_disconnect_wrapper);
	mosquitto_publish_callback_set(mosq, on_publish_wrapper);
	mosquitto_message_callback_set(mosq, on_message_wrapper);
	mosquitto_subscribe_callback_set(mosq, on_subscribe_wrapper);
	mosquitto_unsubscribe_callback_set(mosq, on_unsubscribe_wrapper);
}
Ejemplo n.º 7
0
mosquittopp::mosquittopp(const char *id, bool clean_session)
{
	m_mosq = mosquitto_new(id, clean_session, this);
	mosquitto_connect_callback_set(m_mosq, on_connect_wrapper);
	mosquitto_disconnect_callback_set(m_mosq, on_disconnect_wrapper);
	mosquitto_publish_callback_set(m_mosq, on_publish_wrapper);
	mosquitto_message_callback_set(m_mosq, on_message_wrapper);
	mosquitto_subscribe_callback_set(m_mosq, on_subscribe_wrapper);
	mosquitto_unsubscribe_callback_set(m_mosq, on_unsubscribe_wrapper);
	mosquitto_log_callback_set(m_mosq, on_log_wrapper);
}
Ejemplo n.º 8
0
static
int
mosq_callback_set(lua_State *L)
{
	mosq_t *ctx = mosq_get(L, 1);

	enum callback_types callback_type = luaL_checkinteger(L, 2);

	if (!lua_isfunction(L, 3)) {
		return luaL_argerror(L, 3, "expecting a function");
	}

	int ref = luaL_ref(L, LUA_REGISTRYINDEX);

	switch (callback_type) {
	case CONNECT:
		ctx->connect_ref = ref;
		mosquitto_connect_callback_set(ctx->mosq, mosq_connect_f);
		break;

	case DISCONNECT:
		ctx->disconnect_ref = ref;
		mosquitto_disconnect_callback_set(ctx->mosq, mosq_disconnect_f);
		break;

	case PUBLISH:
		ctx->publish_ref = ref;
		mosquitto_publish_callback_set(ctx->mosq, mosq_publish_f);
		break;

	case MESSAGE:
		ctx->message_ref = ref;
		mosquitto_message_callback_set(ctx->mosq, mosq_message_f);
		break;

	case SUBSCRIBE:
		ctx->subscribe_ref = ref;
		mosquitto_subscribe_callback_set(ctx->mosq, mosq_subscribe_f);
		break;

	case UNSUBSCRIBE:
		ctx->unsubscribe_ref = ref;
		mosquitto_unsubscribe_callback_set(ctx->mosq, mosq_unsubscribe_f);
		break;

	default:
		luaL_unref(L, LUA_REGISTRYINDEX, ref);
		luaL_argerror(L, 2, "unknown mosquitto callback type");
		break;
	}

	return make_mosq_status_result(L, MOSQ_ERR_SUCCESS);
}
Ejemplo n.º 9
0
    bool connect() {
        struct mosquitto *m = mosquitto_new(options.clientId, true, this);
        this->connection = m;

        mosquitto_connect_callback_set(m, on_connect);
        mosquitto_publish_callback_set(m, on_publish);
        mosquitto_subscribe_callback_set(m, on_subscribe);
        mosquitto_message_callback_set(m, on_message);

        const int res = mosquitto_connect(m, options.brokerHostname, options.brokerPort,
                                          options.keepaliveSeconds);
        return res == MOSQ_ERR_SUCCESS;
    }
Ejemplo n.º 10
0
int mosquittopp::reinitialise(const char *id, bool clean_session)
{
	int rc;
	rc = mosquitto_reinitialise(m_mosq, id, clean_session, this);
	if(rc == MOSQ_ERR_SUCCESS){
		mosquitto_connect_callback_set(m_mosq, on_connect_wrapper);
		mosquitto_disconnect_callback_set(m_mosq, on_disconnect_wrapper);
		mosquitto_publish_callback_set(m_mosq, on_publish_wrapper);
		mosquitto_message_callback_set(m_mosq, on_message_wrapper);
		mosquitto_subscribe_callback_set(m_mosq, on_subscribe_wrapper);
		mosquitto_unsubscribe_callback_set(m_mosq, on_unsubscribe_wrapper);
		mosquitto_log_callback_set(m_mosq, on_log_wrapper);
	}
	return rc;
}
Ejemplo n.º 11
0
Archivo: mqtt.c Proyecto: dsmrd/dsmrd
int mqtt_open(mqtt_t inst, dispatch_t d, const char* name, const char* host, int port, int keepalive) {
    int rval = -1;
    int fd;

    inst->mosq = mosquitto_new(name, true, inst);
    if (inst->mosq == NULL) {
        error("Cannot create mqtt");
    } else {
        inst->dispatch = d;

        mosquitto_log_callback_set(inst->mosq, on_log);
        mosquitto_connect_callback_set(inst->mosq, on_connect);
        mosquitto_disconnect_callback_set(inst->mosq, on_disconnect);
        mosquitto_publish_callback_set(inst->mosq, on_publish);
        mosquitto_message_callback_set(inst->mosq, on_message);
        mosquitto_subscribe_callback_set(inst->mosq, on_subscribe);
        mosquitto_unsubscribe_callback_set(inst->mosq, on_unsubscribe);

        inst->timer = dispatch_create_timer(d, 2000000, mqtt_misc, inst);
        if (inst->timer == NULL) {
            error("Cannot create timer");
        }

        rval = mosquitto_connect(inst->mosq, host, port, keepalive);
        if (rval != MOSQ_ERR_SUCCESS) {
            error("Cannot connect mqtt");
        } else {
            fd = mosquitto_socket(inst->mosq);

            rval = dispatch_register(d, fd, mqtt_read, mqtt_write, NULL, mqtt_close, inst);
            if (rval != 0) {
                error("Cannot register mqtt");
            }
        }
    }

    return rval;
}
Ejemplo n.º 12
0
int main(int argc, char *argv[])
{

//    int fd;
//    fd=OpenToSerial(argv[1]);
//    usleep(50000);
//    WriteToSerial(fd, argv[2]);
//    usleep(600000);
//    ReadFromSerial(fd);
//    close(fd);

	int i;
	char *host = "localhost";
	int port = 1883;
	int keepalive = 60;
	bool clean_session = true;
	//struct mosquitto *mosq = NULL;
	struct mosquitto *output1 = NULL;
	struct mosquitto *output2 = NULL;
	struct mosquitto *output3 = NULL;
	struct mosquitto *output4 = NULL;
	struct mosquitto *output5 = NULL;

	/*Init*/
	mosquitto_lib_init();

	output1 = mosquitto_new(NULL, clean_session, NULL);
		if(!output1){
			fprintf(stderr, "Error: Out of memory1.\n");
			return 1;
		}

	output2 = mosquitto_new(NULL, clean_session, NULL);
		if(!output2){
			fprintf(stderr, "Error: Out of memory2.\n");
			return 1;
		}

	output3 = mosquitto_new(NULL, clean_session, NULL);
		if(!output2){
			fprintf(stderr, "Error: Out of memory3.\n");
			return 1;
		}

    output4 = mosquitto_new(NULL, clean_session, NULL);
		if(!output3){
			fprintf(stderr, "Error: Out of memory4.\n");
			return 1;
		}

	 output5 = mosquitto_new(NULL, clean_session, NULL);
		if(!output3){
			fprintf(stderr, "Error: Out of memory5.\n");
			return 1;
		}

	//mosquitto_log_callback_set(output1, my_log_callback); //Does not need this one for now
	mosquitto_connect_callback_set(output1, output1_connect_callback);
	mosquitto_message_callback_set(output1, output1_message_callback);
	mosquitto_subscribe_callback_set(output1, output1_subscribe_callback);

	mosquitto_connect_callback_set(output2, output2_connect_callback);
	mosquitto_message_callback_set(output2, output2_message_callback);
	mosquitto_subscribe_callback_set(output2, output2_subscribe_callback);

	mosquitto_connect_callback_set(output3, output3_connect_callback);
	mosquitto_message_callback_set(output3, output3_message_callback);
	mosquitto_subscribe_callback_set(output3, output3_subscribe_callback);

	mosquitto_connect_callback_set(output4, output4_connect_callback);
	mosquitto_message_callback_set(output4, output4_message_callback);
	mosquitto_subscribe_callback_set(output4, output4_subscribe_callback);

	mosquitto_connect_callback_set(output5, output5_connect_callback);
	mosquitto_message_callback_set(output5, output5_message_callback);
	mosquitto_subscribe_callback_set(output5, output5_subscribe_callback);


	if(mosquitto_connect(output1, host, port, keepalive)){
		fprintf(stderr, "Unable to connect.\n");
		return 1;
	}

	if(mosquitto_connect(output2, host, port, keepalive)){
		fprintf(stderr, "Unable to connect.\n");
		return 1;
	}

	if(mosquitto_connect(output3, host, port, keepalive)){
		fprintf(stderr, "Unable to connect.\n");
		return 1;
	}

	if(mosquitto_connect(output4, host, port, keepalive)){
		fprintf(stderr, "Unable to connect.\n");
		return 1;
	}

	if(mosquitto_connect(output5, host, port, keepalive)){
		fprintf(stderr, "Unable to connect.\n");
		return 1;
	}

	while(1)
	{
		mosquitto_loop(output1, -1, 1);
		mosquitto_loop(output2, -1, 1);
		mosquitto_loop(output3, -1, 1);
		mosquitto_loop(output4, -1, 1);
		mosquitto_loop(output5, -1, 1);
		usleep(50000);		//sleep for 50ms to catch the breath
	}

//	mosquitto_loop_forever(mosq, -1, 1);


	mosquitto_destroy(output1);
	mosquitto_destroy(output2);
	mosquitto_destroy(output3);
	mosquitto_destroy(output4);
	mosquitto_destroy(output5);

	mosquitto_lib_cleanup();
	return 0;
}
Ejemplo n.º 13
0
//int subscribeFromMaster(char* _host, int _port, char* _topic)
void subscribeFromMaster(struct client_config *s_cfg)
{
	struct mosq_config cfg;
	struct mosquitto *mosq = NULL;
	char *temp[] = {"mosquitto_sub","-h","163.180.117.97","-t","test","-p","10011",};
	int rc;
	
	rc = client_config_load(&cfg, CLIENT_SUB, 7, temp);
	if(rc){
		client_config_cleanup(&cfg);
		if(rc == 2){
			/* --help */
			print_usage();
		}else{
			fprintf(stderr, "\nUse 'mosquitto_sub --help' to see usage.\n");
		}
		return ;
	}
	cfg.port = s_cfg->port;

	cfg.host = (char*)malloc(strlen(s_cfg->host));
	strcpy(cfg.host, s_cfg->host);

	cfg.topic = (char*)malloc(strlen(s_cfg->topic));
	strcpy(cfg.topic, s_cfg->topic);

	cfg.topic_count = 1;


	printf("===================================================\n");
	printf("---------------------------------------------------\n");
	printf("	SUBSCRIBE FROM CLIENT!\n");
	printf("#HOST	: %s\n", cfg.host);
	printf("PORT 	: %d\n", cfg.port);
	printf("TOPIC	: %s\n", cfg.topic);
	printf("---------------------------------------------------\n");
	printf("===================================================\n");
	//mosquitto_lib_init();
	if(client_id_generate(&cfg, "mosqsub")){
		return ;
	}

	mosq = mosquitto_new("monitor", cfg.clean_session, &cfg);
	if(!mosq){
		switch(errno){
			case ENOMEM:
				if(!cfg.quiet) fprintf(stderr, "Error: Out of memory.\n");
				break;
			case EINVAL:
				if(!cfg.quiet) fprintf(stderr, "Error: Invalid id and/or clean_session.\n");
				break;
		}
		mosquitto_lib_cleanup();
		return ;
	}
	if(client_opts_set(mosq, &cfg)){
		return ;
	}
	if(cfg.debug){
		mosquitto_log_callback_set(mosq, my_log_callback);
		mosquitto_subscribe_callback_set(mosq, my_subscribe_callback);
	}
	mosquitto_connect_callback_set(mosq, my_connect_callback);
	mosquitto_message_callback_set(mosq, my_message_callback);

	rc = client_connect(mosq, &cfg);
	if(rc) return ;

	masterMosq = mosq;
	rc = mosquitto_loop_forever(mosq, -1, 1);

	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup();

	if(cfg.msg_count>0 && rc == MOSQ_ERR_NO_CONN){
		rc = 0;
	}
	if(rc){
		fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc));
	}
	return ;
}
Ejemplo n.º 14
0
void MQTT_setup() {
	printf("[MQTT] setup\n");
	char *id = NULL;
	char *id_prefix = NULL;
	int i;
	char *host = "192.168.1.127";
	int port = 1883;
	int keepalive = 60;
	bool clean_session = true;
	bool debug = false;
	int rc, rc2;
	char hostname[21];
	char err[1024];
	
	uint8_t *will_payload = NULL;
	long will_payloadlen = 0;
	int will_qos = 0;
	bool will_retain = false;
	char *will_topic = NULL;
    printf("[MQTT] Initialization MQTT at %s:%i\n", host, port);
	
	if(clean_session == false && (id_prefix || !id)){
		fprintf(stderr, "[MQTT] Error: You must provide a client id if you are using the -c option.\n");
		return 1;
	}
	if(id_prefix){
		id = malloc(strlen(id_prefix)+10);
		if(!id){
			fprintf(stderr, "[MQTT] Error: Out of memory.\n");
			return 1;
		}
		snprintf(id, strlen(id_prefix)+10, "%s%d", id_prefix, getpid());
	}else if(!id){
		id = malloc(30);
		if(!id){
			fprintf(stderr, "[MQTT] Error: Out of memory.\n");
			return 1;
		}
		memset(hostname, 0, 21);
		gethostname(hostname, 20);
		snprintf(id, 23, "mosq_sub_%d_%s", getpid(), hostname);
	}

	if(will_payload && !will_topic){
		fprintf(stderr, "[MQTT] Error: Will payload given, but no will topic given.\n");
		return 1;
	}
	if(will_retain && !will_topic){
		fprintf(stderr, "[MQTT] Error: Will retain given, but no will topic given.\n");
		return 1;
	}
	if(MQTT_password && !MQTT_username){
		fprintf(stderr, "[MQTT] Warning: Not using password since username not set.\n");
	}
	mosquitto_lib_init();
	MQTT_mosq = mosquitto_new(id, NULL);
	if(!MQTT_mosq){
		fprintf(stderr, "[MQTT] Error: Out of memory.\n");
		return 1;
	}
	if(will_topic && mosquitto_will_set(MQTT_mosq, true, will_topic, will_payloadlen, will_payload, will_qos, will_retain)){
		fprintf(stderr, "[MQTT] Error: Problem setting will.\n");
		return 1;
	}
	if(MQTT_username && mosquitto_username_pw_set(MQTT_mosq, MQTT_username, MQTT_password)){
		fprintf(stderr, "[MQTT] Error: Problem setting username and password.\n");
		return 1;
	}
	mosquitto_connect_callback_set(MQTT_mosq, MQTT_connect_callback);
	mosquitto_message_callback_set(MQTT_mosq, MQTT_message_callback);
	
	mosquitto_subscribe_callback_set(MQTT_mosq, MQTT_subscribe_callback);

	rc = mosquitto_connect(MQTT_mosq, host, port, keepalive, clean_session);
	if(rc){
		if(rc == MOSQ_ERR_ERRNO){
			strerror_r(errno, err, 1024);
			fprintf(stderr, "[MQTT] Error: %s\n", err);
		}else{
			fprintf(stderr, "[MQTT] Unable to connect (%d).\n", rc);
		}
		//return rc;
	}

}
Ejemplo n.º 15
0
int run_subscriber(int argc, char* const argv[])
//int main(int argc, char* const argv[])
{
  mosquitto_lib_init();
#if 0
  {
    int major, minor, revision;
    mosquitto_lib_version(&major, &minor, &revision);
    std::cout << "Mosquitto library version - " << major << "." << minor << "." << revision << std::endl;
  }
#endif
  std::cout << "Rx Measurement test program" << std::endl;


  std::string hostname("localhost");
  std::list<std::string> topics;
  int qos = 0; // Cheap.
  int port = 1883;
  bool use_json = false;
  int num_threads = 1;

  enum {
    HELP_OPTION = '?',
    HOST_OPTION = 'h',
    TOPIC_OPTION = 't',
    QOS_OPTION = 'q',
    PORT_OPTION = 'p',
    JSON_MSG_OPTION = 'j',
    BINARY_MSG_OPTION = 'B',
    PARALLEL_OPTION = 'P',
  };
  struct option options[] = {
    {"help", 0, nullptr, HELP_OPTION},
    {"mqtt-host", 1, nullptr, HOST_OPTION},
    {"topic", 1, nullptr, TOPIC_OPTION},
    {"qos", 1, nullptr, QOS_OPTION},
    {"mqtt-port", 1, nullptr, PORT_OPTION},
    {"json", 0, nullptr, JSON_MSG_OPTION},
    {"binary", 0, nullptr, BINARY_MSG_OPTION},
    {"parallel", 1, nullptr, PARALLEL_OPTION},
    {0}
  };

  bool more_options = true;
  while (more_options) {
    int status = getopt_long(argc, argv, "h:t:q:p:j", options, nullptr);

    switch (status) {
    case HOST_OPTION:
      hostname = optarg;
      break;

    case TOPIC_OPTION:
      topics.push_back(optarg);
      break;

    case HELP_OPTION:
      exit(EXIT_FAILURE);
      break;

    case QOS_OPTION:
      qos = atoi(optarg);
      break;

    case PORT_OPTION:
      port = atoi(optarg);
      break;

    case JSON_MSG_OPTION:
      use_json = true;
      break;

    case BINARY_MSG_OPTION:
      use_json = false;
      break;

    case PARALLEL_OPTION:
      num_threads = atoi(optarg);
      break;

    default:
      more_options = false;
      break;
    }
  }

  std::cout << "Connect to host " << hostname << " on port " << port << std::endl;
  for (auto& topic : topics) {
    std::cout << "Subscribe under topic " << topic << std::endl;
  }
  std::cout << "Subscribe with quality of service of " << qos << std::endl;

  {
    std::list<struct mosquitto*> mosq_list;
    
    ReceiveStats data_obj;
    get_timestamp(data_obj.base_nsec);
    data_obj.last_report_nsec = data_obj.base_nsec;

    for (int i = 0; i < num_threads; i++) {
      struct mosquitto *mosq = mosquitto_new(nullptr, /*clean_session=*/true, &data_obj);
      int code = mosquitto_connect(mosq, hostname.c_str(), port, /*keepalive=*/-1);
      if (code != MOSQ_ERR_SUCCESS) {
	switch (code) {
	case MOSQ_ERR_INVAL:
	  std::cerr << "Mosquitto connect failure - invalid input parameters" << std::endl;
	  break;
	case MOSQ_ERR_ERRNO:
	  std::cerr << "Mosquitto connect failure - " << strerror(errno) << std::endl;
	  break;
	default:
	  std::cerr << "Mosquitto connect failure - unknown error" << std::endl;
	  break;
	}
	exit(EXIT_FAILURE);
      }
      mosq_list.push_back(mosq);
    }

#if DISABLE_NAGLE
    for (auto mosq : mosq_list) {
      int sock = mosquitto_socket(mosq);
      if (sock >= 0) {
	int flag = 1;
	int result = setsockopt(sock,
				IPPROTO_TCP,
				TCP_NODELAY,
				(char *) &flag,
				sizeof(flag));
	if (result < 0) {
	  std::cerr << "Unable to disable Nagle algorithm on Misquitto socket, " << strerror(errno) << std::endl;
	}
	else {
	  std::cout << "Disabled Nagle algorithm on Misquitto socket" << std::endl;
	}
      }
      else {
	  std::cerr << "Unable to disable Nagle algorithm on Misquitto, no socket" << std::endl;
      }
    }
#endif

    for (auto mosq : mosq_list) {
      if (use_json) {
	mosquitto_message_callback_set(mosq, &message_callback_json);
      }
      else {
	mosquitto_message_callback_set(mosq, &message_callback_binary);
      }
      mosquitto_subscribe_callback_set(mosq, &subscribe_callback);
    }

    for (auto mosq : mosq_list) {
      int code = mosquitto_loop_start(mosq);
      if (code != MOSQ_ERR_SUCCESS) {
	switch (code) {
	case MOSQ_ERR_INVAL:
	  std::cerr << "Mosquitto loop start failure - invalid input parameters" << std::endl;
	  break;
	case MOSQ_ERR_NOT_SUPPORTED:
	  std::cerr << "Mosquitto loop start failure - not supported" << std::endl;
	  break;
	default:
	  std::cerr << "Mosquitto loop start failure - unknown error" << std::endl;
	  break;
	}
	exit(EXIT_FAILURE);
      }
    }

    for (auto& topic : topics) {
      int mid;
      struct mosquitto* mosq = mosq_list.front();

      // Transfer to back of list.
      mosq_list.pop_front();
      mosq_list.push_back(mosq);
      
      int code = mosquitto_subscribe(mosq, &mid, topic.c_str(), qos);
      if (code != MOSQ_ERR_SUCCESS) {
	switch (code) {
	case MOSQ_ERR_INVAL:
	  std::cerr << "Mosquitto subscribe failure - invalid input parameters" << std::endl;
	  break;
	case MOSQ_ERR_NOMEM:
	  std::cerr << "Mosquitto subscribe failure - out of memory" << std::endl;
	  break;
	case MOSQ_ERR_NO_CONN:
	  std::cerr << "Mosquitto subscribe failure - no connection" << std::endl;
	  break;
	default:
	  std::cerr << "Mosquitto subscribe failure - unknown error" << std::endl;
	  break;
	}
	exit(EXIT_FAILURE);
      }
      std::cout << "Subscribing to topic " << topic << " with mid " << mid << std::endl;
    }

    for (auto mosq : mosq_list) {
      //      mosquitto_disconnect(mosq);
      mosquitto_loop_stop(mosq, false);
      mosquitto_destroy(mosq);
    }
  }

  mosquitto_lib_cleanup();
}
Ejemplo n.º 16
0
void /*PORT_NAME*/_setup() {
	char *id = NULL;
	char *id_prefix = NULL;
	int i;
	char *host = "/*HOST_ADDRESS*/";
	int port = /*PORT_NUMBER*/;
	int keepalive = 60;
	bool clean_session = true;
	bool debug = false;
	int rc, rc2;
	char hostname[21];
	char err[1024];
	
	uint8_t *will_payload = NULL;
	long will_payloadlen = 0;
	int will_qos = 0;
	bool will_retain = false;
	char *will_topic = NULL;

        /*MULTI_TOPIC_INIT*/

        /*TRACE_LEVEL_1*/printf("[/*PORT_NAME*/] Initialization MQTT at %s:%i\n", host, port);
	
	if(clean_session == false && (id_prefix || !id)){
		/*TRACE_LEVEL_1*/fprintf(stderr, "[/*PORT_NAME*/] Error: You must provide a client id if you are using the -c option.\n");
		return 1;
	}
	if(id_prefix){
		id = malloc(strlen(id_prefix)+10);
		if(!id){
			/*TRACE_LEVEL_1*/fprintf(stderr, "[/*PORT_NAME*/] Error: Out of memory.\n");
			return 1;
		}
		snprintf(id, strlen(id_prefix)+10, "%s%d", id_prefix, getpid());
	}else if(!id){
		id = malloc(30);
		if(!id){
			/*TRACE_LEVEL_1*/fprintf(stderr, "[/*PORT_NAME*/] Error: Out of memory.\n");
			return 1;
		}
		memset(hostname, 0, 21);
		gethostname(hostname, 20);
		snprintf(id, 23, "mosq_sub_%d_%s", getpid(), hostname);
	}

	if(will_payload && !will_topic){
		/*TRACE_LEVEL_1*/fprintf(stderr, "[/*PORT_NAME*/] Error: Will payload given, but no will topic given.\n");
		return 1;
	}
	if(will_retain && !will_topic){
		/*TRACE_LEVEL_1*/fprintf(stderr, "[/*PORT_NAME*/] Error: Will retain given, but no will topic given.\n");
		return 1;
	}
	if(/*PORT_NAME*/_password && !/*PORT_NAME*/_username){
		/*TRACE_LEVEL_1*/fprintf(stderr, "[/*PORT_NAME*/] Warning: Not using password since username not set.\n");
	}
	mosquitto_lib_init();
	/*PORT_NAME*/_mosq = mosquitto_new(id, NULL);
	if(!/*PORT_NAME*/_mosq){
		/*TRACE_LEVEL_1*/fprintf(stderr, "[/*PORT_NAME*/] Error: Out of memory.\n");
		return 1;
	}
	if(will_topic && mosquitto_will_set(/*PORT_NAME*/_mosq, true, will_topic, will_payloadlen, will_payload, will_qos, will_retain)){
		/*TRACE_LEVEL_1*/fprintf(stderr, "[/*PORT_NAME*/] Error: Problem setting will.\n");
		return 1;
	}
	if(/*PORT_NAME*/_username && mosquitto_username_pw_set(/*PORT_NAME*/_mosq, /*PORT_NAME*/_username, /*PORT_NAME*/_password)){
		/*TRACE_LEVEL_1*/fprintf(stderr, "[/*PORT_NAME*/] Error: Problem setting username and password.\n");
		return 1;
	}
	mosquitto_connect_callback_set(/*PORT_NAME*/_mosq, /*PORT_NAME*/_connect_callback);
	mosquitto_message_callback_set(/*PORT_NAME*/_mosq, /*PORT_NAME*/_message_callback);
	
	/*TRACE_LEVEL_1*/mosquitto_subscribe_callback_set(/*PORT_NAME*/_mosq, /*PORT_NAME*/_subscribe_callback);

	rc = mosquitto_connect(/*PORT_NAME*/_mosq, host, port, keepalive, clean_session);
	if(rc){
		/*TRACE_LEVEL_1*/if(rc == MOSQ_ERR_ERRNO){
			/*TRACE_LEVEL_1*/strerror_r(errno, err, 1024);
			/*TRACE_LEVEL_1*/fprintf(stderr, "[/*PORT_NAME*/] Error: %s\n", err);
		/*TRACE_LEVEL_1*/}else{
			/*TRACE_LEVEL_1*/fprintf(stderr, "[/*PORT_NAME*/] Unable to connect (%d).\n", rc);
		/*TRACE_LEVEL_1*/}
		//return rc;
	}

}
Ejemplo n.º 17
0
Archivo: test.c Proyecto: weikent/C
int main(int argc, char *argv[])
{
  //	int i;
  //	char *host = "85.119.83.194";
  //  char *host = "37.187.106.16";
  char *host = "test.mosquitto.org";
	int port = 8883;
	int keepalive = 60;
	bool clean_session = true;


	mosquitto_lib_init();
	mosq = mosquitto_new("isocketssssss", clean_session, NULL);
	if(!mosq){
		fprintf(stderr, "Error: Out of memory.\n");
		return 1;
	}

  mosquitto_tls_set(mosq, "mosquitto.org.crt", NULL, NULL, NULL, NULL);
	mosquitto_log_callback_set(mosq, my_log_callback);
	mosquitto_connect_callback_set(mosq, my_connect_callback);
	mosquitto_message_callback_set(mosq, my_message_callback);
	mosquitto_subscribe_callback_set(mosq, my_subscribe_callback);
  mosquitto_disconnect_callback_set(mosq, my_disconnect_callback);

	if(mosquitto_connect(mosq, host, port, keepalive)){
		fprintf(stderr, "Unable to connect.\n");
		return 1;
	}






  int temp;
  pthread_t pt_startech_write;
  if ((temp = pthread_create(&pt_startech_write, NULL, startech_write, NULL)) != 0) {
    printf("create thread for startech_write failed !");
  }
  else{
    printf("create thread for startech_write successed !");
  }

  mosquitto_loop_forever(mosq, -1, 1);

  /* pthread_t pt_startech_read; */
  /* if ((temp = pthread_create(&pt_startech_read, NULL, startech_read, NULL)) != 0) { */
  /*   debug_msg("create thread for startech_read failed !"); */
  /* } */
  /* else{ */
  /*   debug_msg("create thread for strtech_read successed !"); */
  /* } */


  while(1){
    sleep(1);
  }

	return 0;
}
Ejemplo n.º 18
0
int main(int argc, char *argv[])
{
	struct mosq_config cfg;
	int rc;
#ifndef WIN32
		struct sigaction sigact;
#endif
	
	memset(&cfg, 0, sizeof(struct mosq_config));

	rc = client_config_load(&cfg, CLIENT_SUB, argc, argv);
	if(rc){
		client_config_cleanup(&cfg);
		if(rc == 2){
			/* --help */
			print_usage();
		}else{
			fprintf(stderr, "\nUse 'mosquitto_sub --help' to see usage.\n");
		}
		return 1;
	}

	if(cfg.no_retain && cfg.retained_only){
		fprintf(stderr, "\nError: Combining '-R' and '--retained-only' makes no sense.\n");
		return 1;
	}

	mosquitto_lib_init();

	if(client_id_generate(&cfg, "mosqsub")){
		return 1;
	}

	mosq = mosquitto_new(cfg.id, cfg.clean_session, &cfg);
	cfg.idtext = cfg.id;
	if(!mosq){
		switch(errno){
			case ENOMEM:
				if(!cfg.quiet) fprintf(stderr, "Error: Out of memory.\n");
				break;
			case EINVAL:
				if(!cfg.quiet) fprintf(stderr, "Error: Invalid id and/or clean_session.\n");
				break;
		}
		mosquitto_lib_cleanup();
		return 1;
	}
	if(client_opts_set(mosq, &cfg)){
		return 1;
	}
	if(cfg.debug){
		mosquitto_log_callback_set(mosq, my_log_callback);
		mosquitto_subscribe_callback_set(mosq, my_subscribe_callback);
	}
	mosquitto_connect_with_flags_callback_set(mosq, my_connect_callback);

	if(cfg.isfmask) {
		mosquitto_message_callback_set(mosq, my_message_file_callback);
	} else {
		mosquitto_message_callback_set(mosq, my_message_callback);
	}

	rc = client_connect(mosq, &cfg);
	if(rc) return rc;

#ifndef WIN32
	sigact.sa_handler = my_signal_handler;
	sigemptyset(&sigact.sa_mask);
	sigact.sa_flags = 0;

	if(sigaction(SIGALRM, &sigact, NULL) == -1){
		perror("sigaction");
		return 1;
	}

	if(cfg.timeout){
		alarm(cfg.timeout);
	}
#endif

	rc = mosquitto_loop_forever(mosq, -1, 1);

	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup();

	if(cfg.msg_count>0 && rc == MOSQ_ERR_NO_CONN){
		rc = 0;
	}
	if(rc){
		fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc));
	}
	return rc;
}
Ejemplo n.º 19
0
int main(int argc, char *argv[])
{
	char *id = NULL;
	char *id_prefix = NULL;
	int i;
	char *host = "localhost";
	int port = 1883;
	int keepalive = 60;
	bool clean_session = true;
	bool debug = false;
	struct mosquitto *mosq = NULL;
	int rc;
	char hostname[256];
	char err[1024];
	struct userdata ud;
	int len;
	
	char *will_payload = NULL;
	long will_payloadlen = 0;
	int will_qos = 0;
	bool will_retain = false;
	char *will_topic = NULL;

	char *cafile = NULL;
	char *capath = NULL;
	char *certfile = NULL;
	char *keyfile = NULL;

	char *psk = NULL;
	char *psk_identity = NULL;

	memset(&ud, 0, sizeof(struct userdata));

	for(i=1; i<argc; i++){
		if(!strcmp(argv[i], "-p") || !strcmp(argv[i], "--port")){
			if(i==argc-1){
				fprintf(stderr, "Error: -p argument given but no port specified.\n\n");
				print_usage();
				return 1;
			}else{
				port = atoi(argv[i+1]);
				if(port<1 || port>65535){
					fprintf(stderr, "Error: Invalid port given: %d\n", port);
					print_usage();
					return 1;
				}
			}
			i++;
		}else if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--disable-clean-session")){
			clean_session = false;
		}else if(!strcmp(argv[i], "--cafile")){
			if(i==argc-1){
				fprintf(stderr, "Error: --cafile argument given but no file specified.\n\n");
				print_usage();
				return 1;
			}else{
				cafile = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "--capath")){
			if(i==argc-1){
				fprintf(stderr, "Error: --capath argument given but no directory specified.\n\n");
				print_usage();
				return 1;
			}else{
				capath = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "--cert")){
			if(i==argc-1){
				fprintf(stderr, "Error: --cert argument given but no file specified.\n\n");
				print_usage();
				return 1;
			}else{
				certfile = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--debug")){
			debug = true;
		}else if(!strcmp(argv[i], "--help")){
			print_usage();
			return 0;
		}else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--host")){
			if(i==argc-1){
				fprintf(stderr, "Error: -h argument given but no host specified.\n\n");
				print_usage();
				return 1;
			}else{
				host = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "-i") || !strcmp(argv[i], "--id")){
			if(id_prefix){
				fprintf(stderr, "Error: -i and -I argument cannot be used together.\n\n");
				print_usage();
				return 1;
			}
			if(i==argc-1){
				fprintf(stderr, "Error: -i argument given but no id specified.\n\n");
				print_usage();
				return 1;
			}else{
				id = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "-I") || !strcmp(argv[i], "--id-prefix")){
			if(id){
				fprintf(stderr, "Error: -i and -I argument cannot be used together.\n\n");
				print_usage();
				return 1;
			}
			if(i==argc-1){
				fprintf(stderr, "Error: -I argument given but no id prefix specified.\n\n");
				print_usage();
				return 1;
			}else{
				id_prefix = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "-k") || !strcmp(argv[i], "--keepalive")){
			if(i==argc-1){
				fprintf(stderr, "Error: -k argument given but no keepalive specified.\n\n");
				print_usage();
				return 1;
			}else{
				keepalive = atoi(argv[i+1]);
				if(keepalive>65535){
					fprintf(stderr, "Error: Invalid keepalive given: %d\n", keepalive);
					print_usage();
					return 1;
				}
			}
			i++;
		}else if(!strcmp(argv[i], "--key")){
			if(i==argc-1){
				fprintf(stderr, "Error: --key argument given but no file specified.\n\n");
				print_usage();
				return 1;
			}else{
				keyfile = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "--psk")){
			if(i==argc-1){
				fprintf(stderr, "Error: --psk argument given but no key specified.\n\n");
				print_usage();
				return 1;
			}else{
				psk = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "--psk-identity")){
			if(i==argc-1){
				fprintf(stderr, "Error: --psk-identity argument given but no identity specified.\n\n");
				print_usage();
				return 1;
			}else{
				psk_identity = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "-q") || !strcmp(argv[i], "--qos")){
			if(i==argc-1){
				fprintf(stderr, "Error: -q argument given but no QoS specified.\n\n");
				print_usage();
				return 1;
			}else{
				ud.topic_qos = atoi(argv[i+1]);
				if(ud.topic_qos<0 || ud.topic_qos>2){
					fprintf(stderr, "Error: Invalid QoS given: %d\n", ud.topic_qos);
					print_usage();
					return 1;
				}
			}
			i++;
		}else if(!strcmp(argv[i], "--quiet")){
			ud.quiet = true;
		}else if(!strcmp(argv[i], "-t") || !strcmp(argv[i], "--topic")){
			if(i==argc-1){
				fprintf(stderr, "Error: -t argument given but no topic specified.\n\n");
				print_usage();
				return 1;
			}else{
				ud.topic_count++;
				ud.topics = realloc(ud.topics, ud.topic_count*sizeof(char *));
				ud.topics[ud.topic_count-1] = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "-u") || !strcmp(argv[i], "--username")){
			if(i==argc-1){
				fprintf(stderr, "Error: -u argument given but no username specified.\n\n");
				print_usage();
				return 1;
			}else{
				ud.username = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")){
			ud.verbose = 1;
		}else if(!strcmp(argv[i], "-P") || !strcmp(argv[i], "--pw")){
			if(i==argc-1){
				fprintf(stderr, "Error: -P argument given but no password specified.\n\n");
				print_usage();
				return 1;
			}else{
				ud.password = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "--will-payload")){
			if(i==argc-1){
				fprintf(stderr, "Error: --will-payload argument given but no will payload specified.\n\n");
				print_usage();
				return 1;
			}else{
				will_payload = argv[i+1];
				will_payloadlen = strlen(will_payload);
			}
			i++;
		}else if(!strcmp(argv[i], "--will-qos")){
			if(i==argc-1){
				fprintf(stderr, "Error: --will-qos argument given but no will QoS specified.\n\n");
				print_usage();
				return 1;
			}else{
				will_qos = atoi(argv[i+1]);
				if(will_qos < 0 || will_qos > 2){
					fprintf(stderr, "Error: Invalid will QoS %d.\n\n", will_qos);
					return 1;
				}
			}
			i++;
		}else if(!strcmp(argv[i], "--will-retain")){
			will_retain = true;
		}else if(!strcmp(argv[i], "--will-topic")){
			if(i==argc-1){
				fprintf(stderr, "Error: --will-topic argument given but no will topic specified.\n\n");
				print_usage();
				return 1;
			}else{
				will_topic = argv[i+1];
			}
			i++;
		}else{
			fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]);
			print_usage();
			return 1;
		}
	}

	if(clean_session == false && (id_prefix || !id)){
		if(!ud.quiet) fprintf(stderr, "Error: You must provide a client id if you are using the -c option.\n");
		return 1;
	}

	if(ud.topic_count == 0){
		fprintf(stderr, "Error: You must specify a topic to subscribe to.\n");
		print_usage();
		return 1;
	}
	if(will_payload && !will_topic){
		fprintf(stderr, "Error: Will payload given, but no will topic given.\n");
		print_usage();
		return 1;
	}
	if(will_retain && !will_topic){
		fprintf(stderr, "Error: Will retain given, but no will topic given.\n");
		print_usage();
		return 1;
	}
	if(ud.password && !ud.username){
		if(!ud.quiet) fprintf(stderr, "Warning: Not using password since username not set.\n");
	}
	if((certfile && !keyfile) || (keyfile && !certfile)){
		fprintf(stderr, "Error: Both certfile and keyfile must be provided if one of them is.\n");
		print_usage();
		return 1;
	}
	if((cafile || capath) && psk){
		if(!ud.quiet) fprintf(stderr, "Error: Only one of --psk or --cafile/--capath may be used at once.\n");
		return 1;
	}
	if(psk && !psk_identity){
		if(!ud.quiet) fprintf(stderr, "Error: --psk-identity required if --psk used.\n");
		return 1;
	}

	mosquitto_lib_init();

	if(id_prefix){
		id = malloc(strlen(id_prefix)+10);
		if(!id){
			if(!ud.quiet) fprintf(stderr, "Error: Out of memory.\n");
			mosquitto_lib_cleanup();
			return 1;
		}
		snprintf(id, strlen(id_prefix)+10, "%s%d", id_prefix, getpid());
	}else if(!id){
		hostname[0] = '\0';
		gethostname(hostname, 256);
		hostname[255] = '\0';
		len = strlen("mosqsub/-") + 6 + strlen(hostname);
		id = malloc(len);
		if(!id){
			if(!ud.quiet) fprintf(stderr, "Error: Out of memory.\n");
			mosquitto_lib_cleanup();
			return 1;
		}
		snprintf(id, len, "mosqsub/%d-%s", getpid(), hostname);
		if(strlen(id) > MOSQ_MQTT_ID_MAX_LENGTH){
			/* Enforce maximum client id length of 23 characters */
			id[MOSQ_MQTT_ID_MAX_LENGTH] = '\0';
		}
	}

	mosq = mosquitto_new(id, clean_session, &ud);
	if(!mosq){
		switch(errno){
			case ENOMEM:
				if(!ud.quiet) fprintf(stderr, "Error: Out of memory.\n");
				break;
			case EINVAL:
				if(!ud.quiet) fprintf(stderr, "Error: Invalid id and/or clean_session.\n");
				break;
		}
		mosquitto_lib_cleanup();
		return 1;
	}
	if(debug){
		mosquitto_log_callback_set(mosq, my_log_callback);
	}
	if(will_topic && mosquitto_will_set(mosq, will_topic, will_payloadlen, will_payload, will_qos, will_retain)){
		if(!ud.quiet) fprintf(stderr, "Error: Problem setting will.\n");
		mosquitto_lib_cleanup();
		return 1;
	}
	if(ud.username && mosquitto_username_pw_set(mosq, ud.username, ud.password)){
		if(!ud.quiet) fprintf(stderr, "Error: Problem setting username and password.\n");
		mosquitto_lib_cleanup();
		return 1;
	}
	if((cafile || capath) && mosquitto_tls_set(mosq, cafile, capath, certfile, keyfile, NULL)){
		if(!ud.quiet) fprintf(stderr, "Error: Problem setting TLS options.\n");
		mosquitto_lib_cleanup();
		return 1;
	}
	if(psk && mosquitto_tls_psk_set(mosq, psk, psk_identity, NULL)){
		if(!ud.quiet) fprintf(stderr, "Error: Problem setting TLS-PSK options.\n");
		mosquitto_lib_cleanup();
		return 1;
	}
	mosquitto_connect_callback_set(mosq, my_connect_callback);
	mosquitto_message_callback_set(mosq, my_message_callback);
	if(debug){
		mosquitto_subscribe_callback_set(mosq, my_subscribe_callback);
	}

	rc = mosquitto_connect(mosq, host, port, keepalive);
	if(rc){
		if(!ud.quiet){
			if(rc == MOSQ_ERR_ERRNO){
#ifndef WIN32
				strerror_r(errno, err, 1024);
#else
				FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, errno, 0, (LPTSTR)&err, 1024, NULL);
#endif
				fprintf(stderr, "Error: %s\n", err);
			}else{
				fprintf(stderr, "Unable to connect (%d).\n", rc);
			}
		}
		return rc;
		mosquitto_lib_cleanup();
	}

	rc = mosquitto_loop_forever(mosq, -1, 1);

	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup();

	if(rc){
		if(rc == MOSQ_ERR_ERRNO){
			fprintf(stderr, "Error: %s\n", strerror(errno));
		}else{
			fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc));
		}
	}
	return rc;
}
Ejemplo n.º 20
0
int main(int argc, char *argv[]) {
    int pid, opt, ret, running, keepalive;
    int baudrate;
    bool clean_session;
    struct mosquitto *mosq = NULL;
    char uart[MAX_BUFFER];
    char broker[MAX_BUFFER];

    clean_session = true;
    running = 1;
    clean_session = true;
    background = 0;
    keepalive = 5;
    baudrate = 9600;

    memset(topic, 0, sizeof(topic));
    memset(broker, 0, sizeof(broker));
    memcpy(broker, mqtt_broker_host, strlen(mqtt_broker_host));

    while ((opt = getopt(argc, argv, "b:d:s:t:fh?")) != -1) {
	switch (opt) {
	case 'd':
	    strncpy(uart, optarg, sizeof(uart) - 1);
	    break;
	case 's':
	    baudrate = atoi(optarg);
	    break;
	case 'b':
	    strncpy(broker, optarg, sizeof(broker) - 1);
	    break;
	case 't':
	    strncpy(topic, optarg, sizeof(topic) - 1);
	    break;
	case 'f':
	    background = 1;
	    break;
	case 'h':
	case '?':
	    print_usage(basename(argv[0]));
	    exit(EXIT_SUCCESS);
	    break;
	default:
	    fprintf(stderr, "Unknown option %c\n", opt);
	    print_usage(basename(argv[0]));
	    exit(EXIT_FAILURE);
	}
    }

    mosquitto_lib_init();
    mosq = mosquitto_new(NULL, clean_session, NULL);
    if (!mosq) {
	fprintf(stderr, "Error: Out of memory.\n");
	return (EXIT_FAILURE);
    }

    /* daemonize the process if requested */
    if (background) {
	/* fork off the parent process */
	pid = fork();
	if (pid < 0) {
	    exit(EXIT_FAILURE);
	}
	/* if we got a good PID, then we can exit the parent process */
	if (pid > 0) {
	    printf("Going into background ...\n");
	    exit(EXIT_SUCCESS);
	}
    }

    snprintf(topic_in, MAX_BUFFER - 3, "%s/in", topic);

    pfd[1].fd = openDevice(uart, serial_speed(baudrate));
    if (pfd[1].fd <= 0)
	exit(EXIT_FAILURE);

    printf("open serial device fd : %d\n", pfd[1].fd);

    mosquitto_connect_callback_set(mosq, mqtt_cb_connect);
    mosquitto_message_callback_set(mosq, mqtt_cb_msg);
    mosquitto_subscribe_callback_set(mosq, mqtt_cb_subscribe);
    mosquitto_disconnect_callback_set(mosq, mqtt_cb_disconnect);
    if (!background)
	mosquitto_log_callback_set(mosq, mqtt_cb_log);

    // we try until we succeed, or we killed
    while (running) {
	if (mosquitto_connect(mosq, broker, mqtt_broker_port, keepalive)) {
	    printf("Unable to connect, host: %s, port: %d\n", broker, mqtt_broker_port);
	    sleep(2);
	    continue;
	}
	break;
    }
    // pfd[0] is for the mosquitto socket, pfd[1] is for UART, or any
    // other file descriptor we need to handle
    // pfd[1].fd = 0;
    pfd[1].events = POLLIN;	//these 2 won't change, so enough to set it once
    const int nfds = sizeof(pfd) / sizeof(struct pollfd);

    while (running) {
	// this might change (when reconnecting for example)
	// so better check it always
	int mosq_fd = mosquitto_socket(mosq);
	pfd[0].fd = mosq_fd;
	pfd[0].events = POLLIN;
	// we check whether libmosquitto wants to write, and if yes, we
	// also register the POLLOUT event for poll, so it will return
	// when it's possible to write to the socket.
	if (mosquitto_want_write(mosq)) {
	    printf("Set POLLOUT\n");
	    pfd[0].events |= POLLOUT;
	}
	// we set the poll()-s timeout here to the half
	// of libmosquitto's keepalive value, to stay on the safe side
	if (poll(pfd, nfds, keepalive / 2 * 1000) < 0) {
	    printf("Poll() failed with <%s>, exiting", strerror(errno));
	    return EXIT_FAILURE;
	}
	// first checking the mosquitto socket
	// if we supposed to write:
	if (pfd[0].revents & POLLOUT) {
	    mosquitto_loop_write(mosq, 1);
	}
	// or read:
	if (pfd[0].revents & POLLIN) {
	    ret = mosquitto_loop_read(mosq, 1);
	    if (ret == MOSQ_ERR_CONN_LOST) {
		printf("reconnect...\n");
		mosquitto_reconnect(mosq);
	    }
	}
	// we call the misc() funtion in both cases
	mosquitto_loop_misc(mosq);
	// checking if there is data on the UART, if yes, reading it
	// and publish
	if (pfd[1].revents & POLLIN) {
	    char input[64];
	    memset(input, 0, sizeof(input));
	    ret = read(pfd[1].fd, input, 64);
	    if (ret < 0) {
		fprintf(stderr, "%s: read_error\n", __func__);
		exit(EXIT_FAILURE);
	    }
	    printf("%s: %s", uart, input);
	    mosquitto_publish(mosq, NULL, topic_in, strlen(input), input, 0, false);
	}
    }

    mosquitto_destroy(mosq);
    mosquitto_lib_cleanup();

    printf("bye\n");

    return EXIT_SUCCESS;
}
Ejemplo n.º 21
0
static int ctx_callback_set(lua_State *L)
{
	ctx_t *ctx = ctx_check(L, 1);
	int callback_type;

	if (lua_isstring(L, 2)) {
		callback_type = callback_type_from_string(lua_tostring(L, 2));
	} else {
		callback_type = luaL_checkinteger(L, 2);
	}

	if (!lua_isfunction(L, 3)) {
		return luaL_argerror(L, 3, "expecting a callback function");
	}

	/* pop the function from the stack and store it in the registry */
	int ref = luaL_ref(L, LUA_REGISTRYINDEX);

	switch (callback_type) {
		case CONNECT:
			ctx->on_connect = ref;
			mosquitto_connect_callback_set(ctx->mosq, ctx_on_connect);
			break;

		case DISCONNECT:
			ctx->on_disconnect = ref;
			mosquitto_disconnect_callback_set(ctx->mosq, ctx_on_disconnect);
			break;

		case PUBLISH:
			ctx->on_publish = ref;
			mosquitto_publish_callback_set(ctx->mosq, ctx_on_publish);
			break;

		case MESSAGE:
			/* store the reference into the context, to be retrieved by ctx_on_message */
			ctx->on_message = ref;
			/* register C callback in mosquitto */
			mosquitto_message_callback_set(ctx->mosq, ctx_on_message);
			break;

		case SUBSCRIBE:
			ctx->on_subscribe = ref;
			mosquitto_subscribe_callback_set(ctx->mosq, ctx_on_subscribe);
			break;

		case UNSUBSCRIBE:
			ctx->on_unsubscribe = ref;
			mosquitto_unsubscribe_callback_set(ctx->mosq, ctx_on_unsubscribe);
			break;

		case LOG:
			ctx->on_log = ref;
			mosquitto_log_callback_set(ctx->mosq, ctx_on_log);
			break;

		default:
			luaL_unref(L, LUA_REGISTRYINDEX, ref);
			luaL_argerror(L, 2, "not a proper callback type");
			break;
	}

	return mosq__pstatus(L, MOSQ_ERR_SUCCESS);
}
Ejemplo n.º 22
0
/*
 * ##########################
 * Main Function
 * ##########################
 */
int main(int argc, char *argv[])
{
	/* program setup variable */
	struct mosquitto *mosq = NULL;
	struct mqtt_userdata *ud = NULL;
	bool clean_session = true;
	bool debug = false;
	char buf[MQTT_BUFSIZE];
	char err[MQTT_ERR_BUFSIZE];
	/* client id */
	char id[MQTT_ID_LEN];
	char id_prefix[MQTT_ID_LEN];
	char hostname[MQTT_HOSTNAME_BUFSIZE];
	/* broker variable */
	char host[MQTT_IP_LEN] = "127.0.0.1";
	int port = 1883;
	int keepalive = 3600;
	/* will information */
	char *will_topic = NULL;
	long will_payloadlen = 0;
	char *will_payload = NULL;
	int will_qos = 0;
	bool will_retain = false;
	/* temp variable */
	int i;
	int rc;

	/* initialized program and user data structure */
	ud = malloc(sizeof(struct mqtt_userdata));
	memset(ud, 0, sizeof(struct mqtt_userdata));
	memset(id, '\0', sizeof(id));
	memset(id_prefix, '\0', sizeof(id_prefix));
	ud->topic_qos = 2;

	/* get option */
	for(i=1; i<argc; i++){
		if(!strcmp(argv[i], "-p") || !strcmp(argv[i], "--port")){
			if(i==argc-1){
				fprintf(stderr, "Error: -p argument given but no port specified.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				port = atoi(argv[i+1]);
				if(port<1 || port>65535){
					fprintf(stderr, "Error: Invalid port given: %d\n", port);
					mqtt_print_usage();
					return 1;
				}
			}
			i++;
		}else if(!strcmp(argv[i], "-c") || !strcmp(argv[i], "--disable-clean-session")){
			clean_session = false;
		}else if(!strcmp(argv[i], "-d") || !strcmp(argv[i], "--debug")){
			debug = true;
		}else if(!strcmp(argv[i], "--help")){
			mqtt_print_usage();
			return 0;
		}else if(!strcmp(argv[i], "-h") || !strcmp(argv[i], "--host")){
			if(i==argc-1){
				fprintf(stderr, "Error: -h argument given but no host specified.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				if (strlen(argv[i+1]) >= MQTT_IP_LEN) {
					fprintf(stderr, "Error: max length of ip is %d.\n\n", MQTT_IP_LEN);
					mqtt_print_usage();
				} else {
					memset(host, '\0', sizeof(host));
					strcpy(host, argv[i+1]);
				}
			}
			i++;
		}else if(!strcmp(argv[i], "-i") || !strcmp(argv[i], "--id")){
			if(strlen(id_prefix) != 0){
				fprintf(stderr, "Error: -i and -I argument cannot be used together.\n\n");
				mqtt_print_usage();
				return 1;
			}
			if(i==argc-1){
				fprintf(stderr, "Error: -i argument given but no id specified.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				if (strlen(argv[i+1]) >= MOSQ_MQTT_ID_MAX_LENGTH) {
					fprintf(stderr, "Error: max length of client id is %d.\n\n", MOSQ_MQTT_ID_MAX_LENGTH);
					mqtt_print_usage();
				} else {
					strcpy(id, argv[i+1]);
				}
			}
			i++;
		}else if(!strcmp(argv[i], "-I") || !strcmp(argv[i], "--id-prefix")){
			if(strlen(id) != 0){
				fprintf(stderr, "Error: -i and -I argument cannot be used together.\n\n");
				mqtt_print_usage();
				return 1;
			}
			if(i==argc-1){
				fprintf(stderr, "Error: -I argument given but no id prefix specified.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				if (strlen(argv[i+1]) >= MOSQ_MQTT_ID_MAX_LENGTH) {
					fprintf(stderr, "Error: max length of client id is %d.\n\n", MOSQ_MQTT_ID_MAX_LENGTH);
					mqtt_print_usage();
				} else {
					strcpy(id_prefix, argv[i+1]);
				}
			}
			i++;
		}else if(!strcmp(argv[i], "-k") || !strcmp(argv[i], "--keepalive")){
			if(i==argc-1){
				fprintf(stderr, "Error: -k argument given but no keepalive specified.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				keepalive = atoi(argv[i+1]);
				if(keepalive>65535){
					fprintf(stderr, "Error: Invalid keepalive given: %d\n", keepalive);
					mqtt_print_usage();
					return 1;
				}
			}
			i++;
		}else if(!strcmp(argv[i], "-q") || !strcmp(argv[i], "--qos")){
			if(i==argc-1){
				fprintf(stderr, "Error: -q argument given but no QoS specified.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				ud->topic_qos = atoi(argv[i+1]);
				if(ud->topic_qos<0 || ud->topic_qos>2){
					fprintf(stderr, "Error: Invalid QoS given: %d\n", ud->topic_qos);
					mqtt_print_usage();
					return 1;
				}
			}
			i++;
		}else if(!strcmp(argv[i], "--quiet")){
			ud->quiet = true;
		}else if(!strcmp(argv[i], "-R")){
			ud->no_retain = true;
		}else if(!strcmp(argv[i], "-t") || !strcmp(argv[i], "--topic")){
			if(i==argc-1){
				fprintf(stderr, "Error: -t argument given but no topic specified.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				ud->topic_count++;
				ud->topics = realloc(ud->topics, ud->topic_count*sizeof(char *));
				ud->topics[ud->topic_count-1] = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "-u") || !strcmp(argv[i], "--username")){
			if(i==argc-1){
				fprintf(stderr, "Error: -u argument given but no username specified.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				ud->username = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "-v") || !strcmp(argv[i], "--verbose")){
			ud->verbose = 1;
		}else if(!strcmp(argv[i], "-P") || !strcmp(argv[i], "--pw")){
			if(i==argc-1){
				fprintf(stderr, "Error: -P argument given but no password specified.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				ud->password = argv[i+1];
			}
			i++;
		}else if(!strcmp(argv[i], "--will-payload")){
			if(i==argc-1){
				fprintf(stderr, "Error: --will-payload argument given but no will payload specified.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				will_payload = argv[i+1];
				will_payloadlen = strlen(will_payload);
			}
			i++;
		}else if(!strcmp(argv[i], "--will-qos")){
			if(i==argc-1){
				fprintf(stderr, "Error: --will-qos argument given but no will QoS specified.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				will_qos = atoi(argv[i+1]);
				if(will_qos < 0 || will_qos > 2){
					fprintf(stderr, "Error: Invalid will QoS %d.\n\n", will_qos);
					return 1;
				}
			}
			i++;
		}else if(!strcmp(argv[i], "--will-retain")){
			will_retain = true;
		}else if(!strcmp(argv[i], "--will-topic")){
			if(i==argc-1){
				fprintf(stderr, "Error: --will-topic argument given but no will topic specified.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				will_topic = argv[i+1];
			}
			i++;
		}else{
			fprintf(stderr, "Error: Unknown option '%s'.\n",argv[i]);
			mqtt_print_usage();
			return 1;
		}
	}

	/* verify necessary variable */
	if(clean_session == false && ((strlen(id_prefix) != 0) || (strlen(id) == 0))){
		if(!ud->quiet) fprintf(stderr, "Error: You must provide a client id if you are using the -c option.\n");
		return 1;
	}
	if(ud->topic_count == 0){
		fprintf(stderr, "Error: You must specify a topic to subscribe to.\n");
		mqtt_print_usage();
		return 1;
	}
	if(will_payload && !will_topic){
		fprintf(stderr, "Error: Will payload given, but no will topic given.\n");
		mqtt_print_usage();
		return 1;
	}
	if(will_retain && !will_topic){
		fprintf(stderr, "Error: Will retain given, but no will topic given.\n");
		mqtt_print_usage();
		return 1;
	}
	if(ud->password && !ud->username){
		if(!ud->quiet) fprintf(stderr, "Warning: Not using password since username not set.\n");
	}

	/* setup signal handler */
	signal(SIGINT, mqtt_signal_handler);
	signal(SIGTERM, mqtt_signal_handler);

	/* init mosquitto library */
	mosquitto_lib_init();

	/* setup client id */
	if(strlen(id_prefix) != 0){
		snprintf(id, sizeof(id), "%s%d", id_prefix, getpid());
	}else if(strlen(id) == 0){
		memset(hostname, '\0', sizeof(hostname));
		gethostname(hostname, sizeof(hostname));
		snprintf(id, sizeof(id), "mosqsub/%d-%s", getpid(), hostname);
	}
	if(strlen(id) > MOSQ_MQTT_ID_MAX_LENGTH){
		/* Enforce maximum client id length of 23 characters */
		id[MOSQ_MQTT_ID_MAX_LENGTH] = '\0';
	}

	/* start mosquitto */
	mosq = mosquitto_new(id, clean_session, ud);
	if(!mosq){
		if(!ud->quiet) fprintf(stderr, "Error: %s\n", strerror(errno));
		mosquitto_lib_cleanup();
		return 1;
	}

	/* setup mosquitto */
	if(debug){
		mosquitto_log_callback_set(mosq, mqtt_log_callback);
	}
	if(will_topic && mosquitto_will_set(mosq, will_topic, will_payloadlen, will_payload, will_qos, will_retain)){
		if(!ud->quiet) fprintf(stderr, "Error: Problem setting will.\n");
		mosquitto_lib_cleanup();
		return 1;
	}
	if(ud->username && mosquitto_username_pw_set(mosq, ud->username, ud->password)){
		if(!ud->quiet) fprintf(stderr, "Error: Problem setting username and password.\n");
		mosquitto_lib_cleanup();
		return 1;
	}
	mosquitto_connect_callback_set(mosq, mqtt_connect_callback);
	mosquitto_message_callback_set(mosq, mqtt_message_callback);
	if(debug){
		mosquitto_subscribe_callback_set(mosq, mqtt_subscribe_callback);
	}

	/* connect mosquitto */
	rc = mosquitto_connect(mosq, host, port, keepalive);
	if(rc){
		if(!ud->quiet){
			if(rc == MOSQ_ERR_ERRNO){
#ifndef WIN32
				strerror_r(errno, err, sizeof(err));
#else
				FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM, NULL, errno, 0, (LPTSTR)&err, sizeof(err), NULL);
#endif
				fprintf(stderr, "Error: %s\n", err);
			}else{
				fprintf(stderr, "Unable to connect (%d: %s).\n", rc, mosquitto_strerror(rc));
			}
		}
		mosquitto_lib_cleanup();
		return rc;
	}

	mosquitto_loop_start(mosq);

	/*
	 * loop mosquitto,
	 * it use select() to call back the callback-function which defined before.
	 */
	do{
		if (fgets(buf, sizeof(buf), stdin)) {
			buf[strlen(buf)-1] = '\0';
			rc = mosquitto_publish(mosq, &ud->mid_sent, "simon", strlen(buf), buf, 0, 0);
			if (rc) {
				if (!ud->quiet) fprintf(stderr, "Error: Publish returned %d, disconnecting.\n", rc);
				mosquitto_disconnect(mosq);
			}
		}
	} while (rc == MOSQ_ERR_SUCCESS);

	mosquitto_loop_stop(mosq, false);

	/* free mosquitto */
	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup();
	mqtt_userdata_free(ud);

	return 0;
}