Ejemplo n.º 1
0
static int ctx_loop_start(lua_State *L)
{
	ctx_t *ctx = ctx_check(L, 1);

	int rc = mosquitto_loop_start(ctx->mosq);
	return mosq__pstatus(L, rc);
}
Ejemplo n.º 2
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.º 3
0
void QMosquitto::start() {
    if(this->mosq == NULL) return;
    if(running) throw "Already running";
    int rc = mosquitto_loop_start(this->mosq);
    if(rc != MOSQ_ERR_SUCCESS) throw "Error starting loop";
    running = true;
}
Ejemplo n.º 4
0
int emit_init()
{
    char *host, *buf = strdup(config.emit_option), *bp;
    int port, rc;
    

    if ((bp = strchr(buf, '/')) == NULL) {
    	fprintf(stderr, "MQTT emitter option is bad (no slash)\n");
	return (1);
    }
    *bp = 0;
    port = atoi(bp+1);
    host = buf;

    mosquitto_lib_init();

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

    rc = mosquitto_connect(config.mosq, host, port, 60);
    if (rc) {
        if (rc == MOSQ_ERR_ERRNO) {
	    char err[1024];

            strerror_r(errno, err, 1024);
            fprintf(stderr, "Error connecting to %s:%d: %s\n", host, port, err);
        } else {
            fprintf(stderr, "Unable to connect (%d).\n", rc);
        }
        mosquitto_lib_cleanup();
        return rc;
    }

    mosquitto_loop_start(config.mosq);

    olog("[*] Connected to MQTT at %s:%d with nsid=%s (topic=%s)\n\n",
    	host, port, config.nsid, config.emit_topic);

    free(buf);
    return (0);
}
Ejemplo n.º 5
0
int mosquittopp::loop_start()
{
	return mosquitto_loop_start(m_mosq);
}
Ejemplo n.º 6
0
int main(int, char**)
{
	SDL_Window *window = 0;
	SDL_Renderer *renderer = 0;
	int code = 0;
	struct mosquitto* mosq;
	bool run = true;
	unsigned int t0 = 0, t1 = 0;
	
	mosquitto_lib_init();

	if((mosq = mosquitto_new(0, true, 0)) == 0)
	{
		std::cout << "Failed to initialize mosquitto." << std::endl;
		code = 1;
		goto end;
	}

	mosquitto_connect_callback_set(mosq, connect_callback);
	mosquitto_message_callback_set(mosq, message_callback);

	//Init SDL
	if (SDL_Init(SDL_INIT_VIDEO) != 0){
		std::cout << "SDL_Init Error: " << SDL_GetError() << std::endl;
		code = 1;
		goto end;
	} 

	//Create a window and renderer attached to it.
	window = SDL_CreateWindow("SDL Skeleton", 100, 100, 800, 600, SDL_WINDOW_SHOWN | SDL_WINDOW_OPENGL);
	renderer = SDL_CreateRenderer(window, 0, SDL_RENDERER_PRESENTVSYNC);


	if(!window || !renderer)
	{
		std::cout << "SDL_CreateWindow or SDL_CreateRenderer Error: " << SDL_GetError() << std::endl;
		code = 1;
		goto end;
	}

	SDL_SetRenderDrawBlendMode(renderer, SDL_BLENDMODE_BLEND);

	//Attempt mosquitto connection to local host.
	mosquitto_connect_async(mosq, "amee.interaktionsbyran.se", 1883, 60);

	//Start the mosquitto network thread.
	if(mosquitto_loop_start(mosq) != MOSQ_ERR_SUCCESS) {
		std::cout << "Failed mosquitto init " << mosq << std::endl;
		code = 1;
		goto end;
	}

	//Block untill the user closes the window
	SDL_Event e;

	while (run) 
	{
		t1 = SDL_GetTicks();
		float delta_time = (float)(t1 - t0)/1000.f;

		while( SDL_PollEvent( &e ) != 0)
		{
			if( e.type == SDL_QUIT )
			{
				run = false;
				break;
			}
		}

		//Clear buffer.
		SDL_SetRenderDrawColor(renderer, 0xff, 0xff, 0xff, 0xff);
		SDL_RenderClear(renderer);

		draw(renderer, delta_time);

		SDL_RenderPresent(renderer);

		t0 = t1;
	}


end:
	SDL_Quit();

	//Cleanup mqtt
	mosquitto_loop_stop(mosq, true);
	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup();

	return code;
}
Ejemplo n.º 7
0
/**
 * Main!
 */
int main(int argc, char **argv) {
  struct sigaction sigact;
  char buf[BUF_SIZE];
  int qos, retain, len;
  struct timeval recv_time, now;
  char topic[CONF_MAX_LENGTH_MQTT_TOPIC];
  int i, ret;
  struct mqtt_player_status_msg status;

  if( config_init() ) {
    CRIT("Faild to initialize config.");
  }
  
  parse_args(argc, argv);

  if( !strlen(config.log_file) ) {
    fprintf(stderr, "ERROR: You have to provide a logfile.\n");
    print_usage(*argv);
    exit(1);
  }

  config.fd = fopen(config.log_file, "r");
  if( NULL == config.fd ) {
    CRIT("Could not open log file.");
  }

  memset(&sigact, 0, sizeof(struct sigaction));
  sigact.sa_handler = sig_handler;
  if( sigaction(SIGINT, &sigact, NULL) ) {
    CRIT("Could not initialize signal handler.");
  }
  
  mosquitto_lib_init();

  config.mosq = mosquitto_new(config.mqtt_client_id, config.mqtt_clean_session, NULL);
  if( NULL == config.mosq ) {
    CRIT("Could not create a mosquitto object.");
  }

  if( mosquitto_connect(config.mosq, config.mqtt_broker, config.mqtt_port, config.mqtt_keepalive) ) {
    CRIT("Could not connect MQTT broker.");
  }

  mosquitto_loop_start(config.mosq);

  do {

    if( gettimeofday(&config.start, NULL) ) {
      CRIT("Could not get time().");
    }

    if( 0 != fseek(config.fd, SEEK_SET, 0) ) {
      CRIT("lseek faild.");
    }

    // read file config
    while(1) {
      if( fscanf(config.fd, "cnf time: %ld.%ld\n", &config.record_start_time.tv_sec, &config.record_start_time.tv_usec) ) {
        if( config.verbose ) {
          printf("record time: %3ld", config.record_start_time.tv_sec);
          printf(".%06ld\n", config.record_start_time.tv_usec);
	}
      } else {
        break;
      }
    }

    if( config.verbose ) {
      printf("-- start playing --\n");
    }

    status.status = MQTT_PLAYER_BEGIN_PLAY;
    status.sec = hton64(config.record_start_time.tv_sec);
    status.usec = hton64(config.record_start_time.tv_usec);
    // post status
    mosquitto_publish(config.mosq, NULL, config.mqtt_topic, sizeof(struct mqtt_player_status_msg), &status, 2, 0);

    // read data
    while(1) {
      if( feof(config.fd) ) {
        break;
      }
  
      ret = fscanf(config.fd, "msg %ld.%ld %d %d %d %s\n", &recv_time.tv_sec, &recv_time.tv_usec, &qos, &retain, &len, topic);
      if( 0 == ret ) {
        break;
      }
  
      if( config.verbose ) {
        printf("time: %3ld", recv_time.tv_sec);
        printf(".%06ld ", recv_time.tv_usec);
        printf("qos: %d ", qos);
        printf("retain: %d ", retain);
        printf("len: %d ", len);
        printf("topic: %s\n", topic);
      }
  
      if( 0 > qos && 2 < qos ) {
        CRIT("Format error in '%s'.", config.log_file);
      }
  
      if( 0 > retain && 1 < retain ) {
        CRIT("Format error in '%s'.", config.log_file);
      }
  
      if( 0 < len ) {
        ret == fscanf(config.fd, "%02hhx", &buf[0]);
        if( 0 == ret ) {
          break;
        }
      }
  
      for( i = 1; i < len; i++ ) {
        ret == fscanf(config.fd, " %02hhx", &buf[i]);
        if( 0 == ret ) {
          break;
        }
      }
      ret == fscanf(config.fd, "\n");
      if( 0 == ret ) {
        break;
      }
  
      if( !config.ignore_timing ) {
        timeradd(&recv_time, &config.start, &recv_time);
  
        if( gettimeofday(&now, NULL) ) {
          CRIT("Could not get time.");
        }
  
        if( timercmp(&now, &recv_time, <) ) {
          timersub(&recv_time, &now, &recv_time);
          usleep(recv_time.tv_sec * 1000000 + recv_time.tv_usec);
        }
      }
  
      mosquitto_publish(config.mosq, NULL, topic, len, buf, qos, retain);
    }
    
  }while( config.repeat && feof(config.fd) );

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

  mosquitto_destroy(config.mosq);

  mosquitto_lib_cleanup();

  fclose(config.fd);

  return 0;
}
Ejemplo n.º 8
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;
	char buf[1024];
	bool debug = false;
	struct mosquitto *mosq = NULL;
	int rc;
	int rc2;
	char hostname[256];
	char err[1024];
	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;

	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], "--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], "-f") || !strcmp(argv[i], "--file")){
			if(mode != MSGMODE_NONE){
				fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n");
				print_usage();
				return 1;
			}else if(i==argc-1){
				fprintf(stderr, "Error: -f argument given but no file specified.\n\n");
				print_usage();
				return 1;
			}else{
				if(load_file(argv[i+1])) return 1;
			}
			i++;
		}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], "--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], "-l") || !strcmp(argv[i], "--stdin-line")){
			if(mode != MSGMODE_NONE){
				fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n");
				print_usage();
				return 1;
			}else{
				mode = MSGMODE_STDIN_LINE;
			}
		}else if(!strcmp(argv[i], "-m") || !strcmp(argv[i], "--message")){
			if(mode != MSGMODE_NONE){
				fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n");
				print_usage();
				return 1;
			}else if(i==argc-1){
				fprintf(stderr, "Error: -m argument given but no message specified.\n\n");
				print_usage();
				return 1;
			}else{
				message = argv[i+1];
				msglen = strlen(message);
				mode = MSGMODE_CMD;
			}
			i++;
		}else if(!strcmp(argv[i], "-n") || !strcmp(argv[i], "--null-message")){
			if(mode != MSGMODE_NONE){
				fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n");
				print_usage();
				return 1;
			}else{
				mode = MSGMODE_NULL;
			}
		}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{
				qos = atoi(argv[i+1]);
				if(qos<0 || qos>2){
					fprintf(stderr, "Error: Invalid QoS given: %d\n", qos);
					print_usage();
					return 1;
				}
			}
			i++;
		}else if(!strcmp(argv[i], "--quiet")){
			quiet = true;
		}else if(!strcmp(argv[i], "-r") || !strcmp(argv[i], "--retain")){
			retain = 1;
		}else if(!strcmp(argv[i], "-s") || !strcmp(argv[i], "--stdin-file")){
			if(mode != MSGMODE_NONE){
				fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n");
				print_usage();
				return 1;
			}else{
				if(load_stdin()) return 1;
			}
		}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{
				topic = 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{
				username = argv[i+1];
			}
			i++;
		}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{
				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(!topic || mode == MSGMODE_NONE){
		fprintf(stderr, "Error: Both topic and message must be supplied.\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(password && !username){
		if(!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(!quiet) fprintf(stderr, "Error: Only one of --psk or --cafile/--capath may be used at once.\n");
		return 1;
	}
	if(psk && !psk_identity){
		if(!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(!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("mosqpub/-") + 6 + strlen(hostname);
		id = malloc(len);
		if(!id){
			if(!quiet) fprintf(stderr, "Error: Out of memory.\n");
			mosquitto_lib_cleanup();
			return 1;
		}
		snprintf(id, len, "mosqpub/%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, true, NULL);
	if(!mosq){
		switch(errno){
			case ENOMEM:
				if(!quiet) fprintf(stderr, "Error: Out of memory.\n");
				break;
			case EINVAL:
				if(!quiet) fprintf(stderr, "Error: Invalid id.\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(!quiet) fprintf(stderr, "Error: Problem setting will.\n");
		mosquitto_lib_cleanup();
		return 1;
	}
	if(username && mosquitto_username_pw_set(mosq, username, password)){
		if(!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(!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(!quiet) fprintf(stderr, "Error: Problem setting TLS-PSK options.\n");
		mosquitto_lib_cleanup();
		return 1;
	}
	mosquitto_connect_callback_set(mosq, my_connect_callback);
	mosquitto_disconnect_callback_set(mosq, my_disconnect_callback);
	mosquitto_publish_callback_set(mosq, my_publish_callback);

	rc = mosquitto_connect(mosq, host, port, keepalive);
	if(rc){
		if(!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);
			}
		}
		mosquitto_lib_cleanup();
		return rc;
	}

	if(mode == MSGMODE_STDIN_LINE){
		mosquitto_loop_start(mosq);
	}

	do{
		if(mode == MSGMODE_STDIN_LINE){
			if(status == STATUS_CONNACK_RECVD){
				if(fgets(buf, 1024, stdin)){
					buf[strlen(buf)-1] = '\0';
					rc2 = mosquitto_publish(mosq, &mid_sent, topic, strlen(buf), buf, qos, retain);
					if(rc2){
						if(!quiet) fprintf(stderr, "Error: Publish returned %d, disconnecting.\n", rc2);
						mosquitto_disconnect(mosq);
					}
				}else if(feof(stdin)){
					last_mid = mid_sent;
					status = STATUS_WAITING;
				}
			}else if(status == STATUS_WAITING){
#ifdef WIN32
				Sleep(1000);
#else
				usleep(1000000);
#endif
			}
			rc = MOSQ_ERR_SUCCESS;
		}else{
			rc = mosquitto_loop(mosq, -1, 1);
		}
	}while(rc == MOSQ_ERR_SUCCESS && connected);

	if(mode == MSGMODE_STDIN_LINE){
		mosquitto_loop_stop(mosq, false);
	}

	if(message && mode == MSGMODE_FILE){
		free(message);
	}
	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.º 9
0
int main(int argc, char *argv[])
{
	struct mosq_config cfg;
	char buf[1024];
	struct mosquitto *mosq = NULL;
	int rc;
	int rc2;

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

	topic = cfg.topic;
	message = cfg.message;
	msglen = cfg.msglen;
	qos = cfg.qos;
	retain = cfg.retain;
	mode = cfg.pub_mode;
	username = cfg.username;
	password = cfg.password;
	quiet = cfg.quiet;

	if(cfg.pub_mode == MSGMODE_STDIN_FILE){
		if(load_stdin()){
			fprintf(stderr, "Error loading input from stdin.\n");
			return 1;
		}
	}else if(cfg.file_input){
		if(load_file(cfg.file_input)){
			fprintf(stderr, "Error loading input file \"%s\".\n", cfg.file_input);
			return 1;
		}
	}

	if(!topic || mode == MSGMODE_NONE){
		fprintf(stderr, "Error: Both topic and message must be supplied.\n");
		print_usage();
		return 1;
	}


	mosquitto_lib_init();

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

	mosq = mosquitto_new(cfg.id, true, NULL);
	if(!mosq){
		switch(errno){
			case ENOMEM:
				if(!quiet) fprintf(stderr, "Error: Out of memory.\n");
				break;
			case EINVAL:
				if(!quiet) fprintf(stderr, "Error: Invalid id.\n");
				break;
		}
		mosquitto_lib_cleanup();
		return 1;
	}
	if(cfg.debug){
		mosquitto_log_callback_set(mosq, my_log_callback);
	}
	mosquitto_connect_callback_set(mosq, my_connect_callback);
	mosquitto_disconnect_callback_set(mosq, my_disconnect_callback);
	mosquitto_publish_callback_set(mosq, my_publish_callback);

	if(client_opts_set(mosq, &cfg)){
		return 1;
	}
	rc = client_connect(mosq, &cfg);
	if(rc) return rc;

	if(mode == MSGMODE_STDIN_LINE){
		mosquitto_loop_start(mosq);
	}

	do{
		if(mode == MSGMODE_STDIN_LINE){
			if(status == STATUS_CONNACK_RECVD){
				if(fgets(buf, 1024, stdin)){
					buf[strlen(buf)-1] = '\0';
					rc2 = mosquitto_publish(mosq, &mid_sent, topic, strlen(buf), buf, qos, retain);
					if(rc2){
						if(!quiet) fprintf(stderr, "Error: Publish returned %d, disconnecting.\n", rc2);
						mosquitto_disconnect(mosq);
					}
				}else if(feof(stdin)){
					last_mid = mid_sent;
					status = STATUS_WAITING;
				}
			}else if(status == STATUS_WAITING){
				if(last_mid_sent == last_mid && disconnect_sent == false){
					mosquitto_disconnect(mosq);
					disconnect_sent = true;
				}
#ifdef WIN32
				Sleep(100);
#else
				usleep(100000);
#endif
			}
			rc = MOSQ_ERR_SUCCESS;
		}else{
			rc = mosquitto_loop(mosq, -1, 1);
		}
	}while(rc == MOSQ_ERR_SUCCESS && connected);

	if(mode == MSGMODE_STDIN_LINE){
		mosquitto_loop_stop(mosq, false);
	}

	if(message && mode == MSGMODE_FILE){
		free(message);
	}
	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup();

	if(rc){
		fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc));
	}
	return rc;
}
Ejemplo n.º 10
0
int main(int argc, char **argv)
{
	int opt, rc = 0;

	while ((opt = getopt(argc, argv, "hv")) != -1) {
		switch (opt) {
		case 'v':
			conf.verbosity++;
			break;
		case 'h':
		default:
			return usage(argv[0]);
		}	
	}

	conf.flx_ufd.fd = open(FLX_DEV, O_RDWR);
	if (conf.flx_ufd.fd < 0) {
		perror(FLX_DEV);
		rc = 1;
		goto finish;
	}
	if (!configure_tty(conf.flx_ufd.fd)) {
		fprintf(stderr, "%s: Failed to configure tty params\n", FLX_DEV);
		rc = 2;
		goto finish;
	}

	if (!config_init()) {
		rc = 3;
		goto oom;
	}
	if (!config_load_all()) {
		rc = 4;
		goto finish;
	}

	conf.ubus_ctx = ubus_connect(NULL);
	if (!conf.ubus_ctx) {
		fprintf(stderr, "Failed to connect to ubus\n");
		rc = 5;
		goto finish;
	}

#ifdef WITH_YKW
	conf.ykw = ykw_new(YKW_DEFAULT_THETA);
	if (conf.ykw == NULL) {
		rc = 6;
		goto oom;
	}
#endif

	mosquitto_lib_init();
	snprintf(conf.mqtt.id, MQTT_ID_LEN, MQTT_ID_TPL, getpid());
	conf.mosq = mosquitto_new(conf.mqtt.id, conf.mqtt.clean_session, &conf);
	if (!conf.mosq) {
		switch (errno) {
		case ENOMEM:
			rc = 7;
			goto oom;
		case EINVAL:
			fprintf(stderr, "mosq_new: Invalid id and/or clean_session.\n");
			rc = 8;
			goto finish;
		}
	}
	rc = mosquitto_loop_start(conf.mosq);
	switch (rc) {
	case MOSQ_ERR_INVAL:
		fprintf(stderr, "mosq_loop_start: Invalid input parameters.\n");
		goto finish;
	case MOSQ_ERR_NOT_SUPPORTED:
		fprintf(stderr, "mosq_loop_start: No threading support.\n");
		goto finish;
	};
	rc = mosquitto_connect_async(conf.mosq, conf.mqtt.host, conf.mqtt.port,
	                  conf.mqtt.keepalive);
	switch (rc) {
	case MOSQ_ERR_INVAL:
		fprintf(stderr, "mosq_connect_async: Invalid input parameters.\n");
		goto finish;
	case MOSQ_ERR_ERRNO:
		perror("mosq_connect_async");
		goto finish;
	}

	uloop_init();
	uloop_fd_add(&conf.flx_ufd, ULOOP_READ);
	uloop_timeout_set(&conf.timeout, CONFIG_ULOOP_TIMEOUT);
	ubus_add_uloop(conf.ubus_ctx);
	ubus_register_event_handler(conf.ubus_ctx, &conf.ubus_ev_sighup,
	                            CONFIG_UBUS_EV_SIGHUP);
	ubus_register_event_handler(conf.ubus_ctx, &conf.ubus_ev_shift_calc,
	                            CONFIG_UBUS_EV_SHIFT_CALC);
	uloop_run();
	uloop_done();
	goto finish;

oom:
	fprintf(stderr, "error: Out of memory.\n");
finish:
	mosquitto_disconnect(conf.mosq);
	mosquitto_loop_stop(conf.mosq, false);
	mosquitto_destroy(conf.mosq);
	mosquitto_lib_cleanup();
	ykw_free(conf.ykw);
	if (conf.ubus_ctx != NULL) {
		ubus_free(conf.ubus_ctx);
	}
	close(conf.flx_ufd.fd);
	uci_free_context(conf.uci_ctx);
	return rc;
}
Ejemplo n.º 11
0
int pub_shared_loop(struct mosquitto *mosq)
{
	int read_len;
	int pos;
	int rc, rc2;
	char *buf2;
	int buf_len_actual;
	int mode;
	int loop_delay = 1000;

	if(cfg.repeat_count > 1 && (cfg.repeat_delay.tv_sec == 0 || cfg.repeat_delay.tv_usec != 0)){
		loop_delay = cfg.repeat_delay.tv_usec / 2000;
	}

	mode = cfg.pub_mode;

	if(mode == MSGMODE_STDIN_LINE){
		mosquitto_loop_start(mosq);
	}

	do{
		if(mode == MSGMODE_STDIN_LINE){
			if(status == STATUS_CONNACK_RECVD){
				pos = 0;
				read_len = line_buf_len;
				while(connected && fgets(&line_buf[pos], read_len, stdin)){
					buf_len_actual = strlen(line_buf);
					if(line_buf[buf_len_actual-1] == '\n'){
						line_buf[buf_len_actual-1] = '\0';
						rc2 = my_publish(mosq, &mid_sent, cfg.topic, buf_len_actual-1, line_buf, cfg.qos, cfg.retain);
						if(rc2){
							if(!cfg.quiet) fprintf(stderr, "Error: Publish returned %d, disconnecting.\n", rc2);
							mosquitto_disconnect_v5(mosq, MQTT_RC_DISCONNECT_WITH_WILL_MSG, cfg.disconnect_props);
						}
						break;
					}else{
						line_buf_len += 1024;
						pos += 1023;
						read_len = 1024;
						buf2 = realloc(line_buf, line_buf_len);
						if(!buf2){
							fprintf(stderr, "Error: Out of memory.\n");
							return MOSQ_ERR_NOMEM;
						}
						line_buf = buf2;
					}
				}
				if(feof(stdin)){
					if(mid_sent == -1){
						/* Empty file */
						mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props);
						disconnect_sent = true;
						status = STATUS_DISCONNECTING;
					}else{
						last_mid = mid_sent;
						status = STATUS_WAITING;
					}
				}
			}else if(status == STATUS_WAITING){
				if(last_mid_sent == last_mid && disconnect_sent == false){
					mosquitto_disconnect_v5(mosq, 0, cfg.disconnect_props);
					disconnect_sent = true;
				}
#ifdef WIN32
				Sleep(100);
#else
				struct timespec ts;
				ts.tv_sec = 0;
				ts.tv_nsec = 100000000;
				nanosleep(&ts, NULL);
#endif
			}
			rc = MOSQ_ERR_SUCCESS;
		}else{
			rc = mosquitto_loop(mosq, loop_delay, 1);
			if(ready_for_repeat && check_repeat_time()){
				rc = 0;
				switch(cfg.pub_mode){
					case MSGMODE_CMD:
					case MSGMODE_FILE:
					case MSGMODE_STDIN_FILE:
						rc = my_publish(mosq, &mid_sent, cfg.topic, cfg.msglen, cfg.message, cfg.qos, cfg.retain);
						break;
					case MSGMODE_NULL:
						rc = my_publish(mosq, &mid_sent, cfg.topic, 0, NULL, cfg.qos, cfg.retain);
						break;
					case MSGMODE_STDIN_LINE:
						break;
				}
				if(rc){
					fprintf(stderr, "Error sending repeat publish: %s", mosquitto_strerror(rc));
				}
			}
		}
	}while(rc == MOSQ_ERR_SUCCESS && connected);

	if(mode == MSGMODE_STDIN_LINE){
		mosquitto_loop_stop(mosq, false);
	}
	return 0;
}
Ejemplo n.º 12
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.º 13
0
int main(int argc, char **argv)
{
	struct tm gmt_init, local_init;
	char ch, *progname = *argv, *nodename, *topic, *prefix = DEFAULT_PREFIX;;
	int usage = 0, interval = 10, rc;
	struct utsname uts;
	char clientid[30];
	char *host = "localhost", *ca_file;
	int port = 1883, keepalive = 60;
	int do_tls = FALSE, tls_insecure = FALSE;
	int do_psk = FALSE;
	char *psk_key = NULL, *psk_identity = NULL;
	struct udata udata;

	udata.mid = 17;

	while ((ch = getopt(argc, argv, "i:t:h:p:C:LUK:I:")) != EOF) {
		switch (ch) {
			case 'C':
				ca_file = optarg;
				do_tls = TRUE;
				break;
			case 'h':
				host = optarg;
				break;
			case 'i':
				interval = atoi(optarg);
				interval = (interval < 1) ? 1 : interval;
				break;
			case 's':
				tls_insecure = TRUE;
				break;
			case 'p':
				port = atoi(optarg);
				break;
			case 't':
				prefix = optarg;
				break;
			case 'L':
				do_local = !do_local;
				break;
			case 'U':
				do_utc = !do_utc;
				break;
			case 'I':
				psk_identity = optarg;
				do_psk = TRUE;
				break;
			case 'K':
				psk_key = optarg;
				do_psk = TRUE;
				break;
			default:
				usage = 1;
				break;
		}
	}

	if (do_tls && do_psk)
		usage = 1;
	if (do_psk && (psk_key == NULL || psk_identity == NULL))
		usage = 1;

	if (usage) {
		fprintf(stderr, "Usage: %s [-h host] [-i interval] [-p port] [-t prefix] [-C CA-cert] [-L] [-U] [-K psk-key] [-I psk-identity] [-s]\n", progname);
		exit(1);
	}

	/* Find nodename; chop at first '.' */

	if (uname(&uts) == 0) {
		char *p;
		nodename = strdup(uts.nodename);

		if ((p = strchr(nodename, '.')) != NULL)
			*p = 0;
	} else {
		nodename = strdup("unknown");
	}

	mosquitto_lib_init();

	sprintf(clientid, "mqtt-tics-%d", getpid());
	m = mosquitto_new(clientid, TRUE, (void *)&udata);
	if (!m) {
		fprintf(stderr, "Out of memory.\n");
		exit(1);
	}

	if (do_psk) {
		rc = mosquitto_tls_psk_set(m, psk_key, psk_identity,NULL);
		if (rc != MOSQ_ERR_SUCCESS) {
			fprintf(stderr, "Cannot set TLS PSK: %s\n",
				mosquitto_strerror(rc));
			exit(3);
		}
	} else if (do_tls) {
		rc = mosquitto_tls_set(m, ca_file, NULL, NULL, NULL, NULL);
		if (rc != MOSQ_ERR_SUCCESS) {
			fprintf(stderr, "Cannot set TLS PSK: %s\n",
				mosquitto_strerror(rc));
			exit(3);
		}

		/* FIXME */
		// mosquitto_tls_opts_set(m, SSL_VERIFY_PEER, "tlsv1", NULL);
		
		if (tls_insecure) {
#if LIBMOSQUITTO_VERSION_NUMBER >= 1002000
			/* mosquitto_tls_insecure_set() requires libmosquitto 1.2. */
			mosquitto_tls_insecure_set(m, TRUE);
#endif
		}
	}

	mosquitto_publish_callback_set(m, cb_pub);
	mosquitto_disconnect_callback_set(m, cb_disconnect);
	if ((rc = mosquitto_connect(m, host, port, keepalive)) != MOSQ_ERR_SUCCESS) {
		fprintf(stderr, "Unable to connect to %s:%d: %s\n", host, port,
			mosquitto_strerror(rc));
		perror("");
		exit(2);
	}

	signal(SIGINT, catcher);

	mosquitto_loop_start(m);

	if ((topic = malloc(strlen(prefix) + (3 * strlen(nodename)) + 12)) == NULL) {
		fprintf(stderr, "ENOMEM\n");
		goto abort;
	}
	sprintf(topic, prefix, nodename, nodename, nodename);

	memset(&gmt_init, 0, sizeof(struct tm));
	memset(&local_init, 0, sizeof(struct tm));

	time(&start_tics);

	while (1) {
		pubtime(topic, &gmt_init, &local_init);
		sleep(interval);
	}

	free(topic);

   abort:
	free(nodename);

	mosquitto_disconnect(m);
	mosquitto_loop_stop(m, false);
	mosquitto_lib_cleanup();

	return 0;
}
Ejemplo n.º 14
0
/*
 * ##########################
 * Main Function
 * ##########################
 */
int main(int argc, char *argv[])
{
	/* program setup variable */
	struct mosquitto *mosq = NULL;
	struct mqtt_userdata *ud = NULL;
	unsigned int max_inflight = 20;
	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 = 60;
	/* 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;
	int rc2;

	/* initialized program and user data structure */
	ud = malloc(sizeof(struct mqtt_userdata));
	memset(ud, 0, sizeof(struct mqtt_userdata));
	ud->last_mid = -1;
	ud->connected = true;
	memset(id, '\0', sizeof(id));
	memset(id_prefix, '\0', sizeof(id_prefix));
	ud->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], "-d") || !strcmp(argv[i], "--debug")){
			debug = true;
		}else if(!strcmp(argv[i], "-f") || !strcmp(argv[i], "--file")){
			if(ud->mode != MQTT_MSGMODE_NONE){
				fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n");
				mqtt_print_usage();
				return 1;
			}else if(i==argc-1){
				fprintf(stderr, "Error: -f argument given but no file specified.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				if(mqtt_load_file(argv[i+1], ud)) return 1;
			}
			i++;
		}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], "-l") || !strcmp(argv[i], "--stdin-line")){
			if(ud->mode != MQTT_MSGMODE_NONE){
				fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				ud->mode = MQTT_MSGMODE_STDIN_LINE;
			}
		}else if(!strcmp(argv[i], "-m") || !strcmp(argv[i], "--message")){
			if(ud->mode != MQTT_MSGMODE_NONE){
				fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n");
				mqtt_print_usage();
				return 1;
			}else if(i==argc-1){
				fprintf(stderr, "Error: -m argument given but no message specified.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				ud->message = argv[i+1];
				ud->msglen = strlen(ud->message);
				ud->mode = MQTT_MSGMODE_CMD;
			}
			i++;
		}else if(!strcmp(argv[i], "-M")){
			if(i==argc-1){
				fprintf(stderr, "Error: -M argument given but max_inflight not specified.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				max_inflight = atoi(argv[i+1]);
			}
			i++;
		}else if(!strcmp(argv[i], "-n") || !strcmp(argv[i], "--null-message")){
			if(ud->mode != MQTT_MSGMODE_NONE){
				fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				ud->mode = MQTT_MSGMODE_NULL;
			}
		}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->qos = atoi(argv[i+1]);
				if(ud->qos<0 || ud->qos>2){
					fprintf(stderr, "Error: Invalid QoS given: %d\n", ud->qos);
					mqtt_print_usage();
					return 1;
				}
			}
			i++;
		}else if(!strcmp(argv[i], "--quiet")){
			ud->quiet = true;
		}else if(!strcmp(argv[i], "-r") || !strcmp(argv[i], "--retain")){
			ud->retain = 1;
		}else if(!strcmp(argv[i], "-s") || !strcmp(argv[i], "--stdin-file")){
			if(ud->mode != MQTT_MSGMODE_NONE){
				fprintf(stderr, "Error: Only one type of message can be sent at once.\n\n");
				mqtt_print_usage();
				return 1;
			}else{
				if(mqtt_load_stdin(ud)) return 1;
			}
		}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 = 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], "-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(!ud->topic || ud->mode == MQTT_MSGMODE_NONE){
		fprintf(stderr, "Error: Both topic and message must be supplied.\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");
	}

	/* 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), "mosqub/%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, true, 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_max_inflight_messages_set(mosq, max_inflight);
	mosquitto_connect_callback_set(mosq, mqtt_connect_callback);
	mosquitto_disconnect_callback_set(mosq, mqtt_disconnect_callback);
	mosquitto_publish_callback_set(mosq, mqtt_publish_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;
	}

	/* publish mosquitto mqtt message BASED ON DIFFERENT message mode */
	if(ud->mode == MQTT_MSGMODE_STDIN_LINE){
		mosquitto_loop_start(mosq);
	}

	do{
		if(ud->mode == MQTT_MSGMODE_STDIN_LINE){
			if(ud->status == MQTT_STATUS_CONNACK_RECVD){
				if(fgets(buf, sizeof(buf), stdin)){
					buf[strlen(buf)-1] = '\0';
					rc2 = mosquitto_publish(mosq, &ud->mid_sent, ud->topic, strlen(buf), buf, ud->qos, ud->retain);
					if(rc2){
						if(!ud->quiet) fprintf(stderr, "Error: Publish returned %d, disconnecting.\n", rc2);
						mosquitto_disconnect(mosq);
					}
				}else if(feof(stdin)){
					ud->last_mid = ud->mid_sent;
					ud->status = MQTT_STATUS_WAITING;
				}
			}else if(ud->status == MQTT_STATUS_WAITING){
#ifdef WIN32
				Sleep(1000);
#else
				usleep(1000000);
#endif
			}
			rc = MOSQ_ERR_SUCCESS;
		}else{
			rc = mosquitto_loop(mosq, -1, 1);
		}
	}while(rc == MOSQ_ERR_SUCCESS && ud->connected);

	if(ud->mode == MQTT_MSGMODE_STDIN_LINE){
		mosquitto_loop_stop(mosq, false);
	}

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

	return rc;
}
Ejemplo n.º 15
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;
}