Exemple #1
0
int mqPub(void)
{
	int i;
	char *host = "5.44.237.19";
	int port = 1883;
	int keepalive = 60;
	bool clean_session = true;
	struct mosquitto *mosq = NULL;

	mosquitto_lib_init();
	mosq = mosquitto_new(NULL, 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_publish_callback_set(mosq, my_publish_callback);

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

	mosquitto_loop_forever(mosq, -1, 1);

	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup();
	return 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;
}
/* {{{ Mosquitto\Client::onLog() */
PHP_METHOD(Mosquitto_Client, onLog)
{
	mosquitto_client_object *object;
	zend_fcall_info log_callback = empty_fcall_info;
	zend_fcall_info_cache log_callback_cache = empty_fcall_info_cache;

	PHP_MOSQUITTO_ERROR_HANDLING();
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "f!",
				&log_callback, &log_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(log_callback)) {
		zend_throw_exception(mosquitto_ce_exception, "Need a valid callback", 0 TSRMLS_CC);
	}

	object->log_callback = log_callback;
	object->log_callback_cache = log_callback_cache;
	Z_ADDREF_P(log_callback.function_name);

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

	mosquitto_log_callback_set(object->client, php_mosquitto_log_callback);
}
Exemple #4
0
int main(int argc, char *argv[])
{
	int i;
	char *host = "5.44.237.19";
	int port = 1883;
	int keepalive = 60;
	bool clean_session = true;
	struct mosquitto *mosq = NULL;

	sprintf(mqMsg,"%s",argv[1]);
	printf("And the word is >> %s <<\n", mqMsg);

	mosquitto_lib_init();
	mosq = mosquitto_new(NULL, 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_publish_callback_set(mosq, my_publish_callback);

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

	mosquitto_loop_forever(mosq, -1, 1);

	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup();
	return 0;
}
Exemple #5
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);
}
bool mosq_setup(struct _squash *st)
{
	mosquitto_lib_init();

	DLOG("mosquitto -> (re)connecting\n");
	st->mosq = mosquitto_new(NULL, true, st);
	mosquitto_log_callback_set(st->mosq, mosq_logger);
	mosquitto_message_callback_set(st->mosq, st->msg_handler);
	int rc = mosquitto_connect(st->mosq, st->mq_host, 1883, 60);
	if (MOSQ_ERR_SUCCESS != rc) {
		WLOG("Failed to connect: %s\n", strerror(errno));
		rc = -1;
		goto unwind;
	}

	int mosq_fd = mosquitto_socket(st->mosq);
	if (evutil_make_socket_nonblocking(mosq_fd)) {
		WLOG("Failed to make non-blocking: fd = %d, possibly ok\n", mosq_fd);
	}
	st->mosq_readidle = event_new(st->base, mosq_fd, EV_READ|EV_PERSIST, mosq_ev_io, st);
	if (st->mosq_readidle == NULL) {
		WLOG("Failed to create mosquitto read/idle watcher\n");
		rc = -1;
		goto unwind_readidle;
	}
	st->mosq_write = event_new(st->base, mosq_fd, EV_WRITE, mosq_ev_io, st);
	if (st->mosq_write == NULL) {
		WLOG("Failed to create mosquitto write watcher\n");
		rc = -1;
		goto unwind_write;
	}
	if (mosquitto_want_write(st->mosq)) {
		event_add(st->mosq_write, NULL);
	}

	struct timeval mosq_idle_loop_time = { 0, 100 * 1000 };
	if (event_add(st->mosq_readidle, &mosq_idle_loop_time) < 0) {
		WLOG("Failed to activate mosquitto watcher\n");
		rc = -1;
		goto unwind_write;
	}
	goto out;

unwind_write:
	event_free(st->mosq_write);
unwind_readidle:
	event_free(st->mosq_readidle);
unwind:
	mosquitto_destroy(st->mosq);
	mosquitto_lib_cleanup();

out:
	return rc == 0;
}
Exemple #7
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;
}
Exemple #8
0
int main(int argc, char *argv[])
{
	char *host = "5.44.237.19";
	int port = 1883;
	int keepalive = 60;
	bool clean_session = true;
	struct mosquitto *mosq = NULL;

	/* argv[1] is the filename, argv[2] is the number of MAC addresses */
	/* and argv[3] is the timestamp in secs since the epoch            */

	if(argc==4) {
		macFile=argv[1];
		messagesToSend=atoi(argv[2]);
		if(messagesToSend==0) {
			return 1;
		}
		timeNow=argv[3];
	} else {
		printf("USAGE: thingithonmq macFileName numRecords timeStamp\n       Where timeStamp is in seconds, like date +\%s\n");
		return 1;
	}
		
	/* Start up Mosquitto                                              */

	mosquitto_lib_init();
	mosq = mosquitto_new(NULL, 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_publish_callback_set(mosq, my_publish_callback);

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

	mosquitto_loop_forever(mosq, -1, 1);

	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup();
	return 0;
}
Exemple #9
0
static
int
mosq_log_callback_set(lua_State *L)
{
	mosq_t *ctx = mosq_get(L, 1);

	int log_level_mask = luaL_optinteger(L, 2, MOSQ_LOG_ERR);

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

	ctx->log_level_mask = log_level_mask;
	ctx->log_ref = luaL_ref(L, LUA_REGISTRYINDEX);

	mosquitto_log_callback_set(ctx->mosq, mosq_log_f);

	return make_mosq_status_result(L, MOSQ_ERR_SUCCESS);
}
Exemple #10
0
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;
}
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;
}
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;
}
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;
}
Exemple #14
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 ;
}
Exemple #15
0
int main(int argc, char *argv[])
{
        int port = 1883;
        int reconnect_delay = 1;
        char *host = "localhost";
        char subscription[128];
        int rawcallback;
        struct context *ctx = malloc(sizeof(struct context)+sizeof(default_relay_rules));
        ctx->debug = 0;
        ctx->failures = 0;
        ctx->relay_rules=default_relay_rules; // TODO read relay rules from a configuration file
        ctx->num_relay_rules=sizeof(default_relay_rules)/sizeof(*default_relay_rules);
        int opt;
        ctx->sub_prefix = "telldus";
        ctx->pub_prefix = "";
        struct relay_rule *relay_rules = ctx->relay_rules;

        snprintf(subscription,sizeof(subscription)-1,"%s/#",ctx->sub_prefix);

        while ((opt = getopt(argc, argv, "vS:d:h:p:P:")) != -1) {
                switch (opt) {
                case 'v':
                        ctx->debug++;
                        break;
                case 'h':
                        host=strdup(optarg);
                        break;
                case 'S':
                        ctx->sub_prefix=strdup(optarg);
                        snprintf(subscription,sizeof(subscription)-1,"%s/#",ctx->sub_prefix);
                        break;
                case 'P':
                        ctx->pub_prefix=strdup(optarg);
                        break;
                case 'p':
                        port=atoi(optarg);
                        break;
                case 'd':
                        reconnect_delay=atoi(optarg);
                        break;
                default: /* '?' */
                        fprintf(stderr, "Usage: %s [-v] "
                                "[-h <host>] "
                                "[-p <port>]\n\t"
                                "[-S <subscription topic prefix>] "
                                "[-P <publishing topic prefix>]\n\t"
                                "[-d <reconnect after n seconds> ]\n\n"
                                "\t%s connects to MQTT broker at %s:%d.\n\n"
                                "\tIt subscribes messages for topic '%s'.\n"
                                "\tWhen a 'turnon', 'turnoff' or 'bell' message is received at %s/<device>/method it will trigger\n"
                                "\tthe corresponding operation on a Telldus device with the same name.\n",
                                argv[0],
                                argv[0], host, port,
                                subscription,
                                ctx->sub_prefix);

                        fprintf(stderr,
                                "\n\tIt listens for raw events from Telldus.\n");
                        int f;
                        for(f=0; f<ctx->num_relay_rules; f++) {
                                fprintf(stderr, "\tWhen it receives a raw event where ");
                                int i = 0;
                                const char *separator="";
                                while(ctx->relay_rules[f].filters[i].key &&
                                      relay_rules[f].filters[i].value) {
                                        fprintf(stderr, "%sfield '%s' value is '%s'",
                                                separator,
                                                relay_rules[f].filters[i].key,
                                                relay_rules[f].filters[i].value);
                                        i++;
                                        separator = relay_rules[f].filters[i+1].key ? ", " : " and ";
                                }
                                separator="";
                                fprintf(stderr, "\n\t\tit publishes ");
                                int j = 0;
                                while(relay_rules[f].mqtt_template[j].topicformat &&
                                      relay_rules[f].mqtt_template[j].messageformat) {
                                        fprintf(stderr, "%sa message '%s' on topic '%s%s'",
                                                separator,
                                                relay_rules[f].mqtt_template[j].messageformat,
                                                ctx->pub_prefix,
                                                relay_rules[f].mqtt_template[j].topicformat);
                                        j++;
                                        separator = relay_rules[f].mqtt_template[j+1].topicformat ? ", \n\t\t" : " and \n\t\t";
                                }
                                fprintf(stderr, "\n");
                        }


                        exit(EXIT_FAILURE);
                }
        }

        tdInit();

        // TODO: move after mqtt connection has been established when unregistering and re-registering works ok
        rawcallback = tdRegisterRawDeviceEvent(raw_event,ctx);

        do {
                ctx->failures = 0; // TODO: synchronization for telldus threading

                char hostname[21];
                char id[30];

                memset(hostname, 0, sizeof(hostname));
                gethostname(hostname, sizeof(hostname)-1);
                snprintf(id, sizeof(id)-1, "mosq_pub_%d_%s", getpid(), hostname);

                mosquitto_lib_init();
                ctx->mosq = mosquitto_new(id, true, ctx);
                if(!ctx->mosq) {
                        fprintf(stderr, "Error: Out of memory.\n");
                        return 1;
                }

                if(ctx->debug > 0) {
                        mosquitto_log_callback_set(ctx->mosq,
                                                   my_log_callback);
                }

                int rc;
                rc = mosquitto_connect(ctx->mosq, host, port, 30);
                if(rc) {
                        if(ctx->debug > 0) {
                                fprintf(stderr, "failed to connect %s:%d\n", host, port);
                        }
                        goto clean;
                }
                mosquitto_message_callback_set(ctx->mosq, my_message_callback);

                rc = mosquitto_subscribe(ctx->mosq, NULL, subscription, 0);
                if(rc) {
                        if(ctx->debug > 0) {
                                fprintf(stderr, "failed to subscribe %s\n", subscription);
                        }
                        goto clean;
                }


                do {
                        rc = mosquitto_loop(ctx->mosq, 60, 1);
                } while(rc == MOSQ_ERR_SUCCESS && !ctx->failures);

clean:

                mosquitto_destroy(ctx->mosq);
                mosquitto_lib_cleanup();
        } while(reconnect_delay >= 0 && ( sleep(reconnect_delay), true));

        tdUnregisterCallback(rawcallback);
        tdClose();
        return 0;
}
Exemple #16
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;
}
Exemple #17
0
int main(int argc, char *argv[])
{
	struct mosquitto *mosq = NULL;
	int rc;

	mosquitto_lib_init();

	if(pub_shared_init()) return 1;

	memset(&cfg, 0, sizeof(struct mosq_config));
	rc = client_config_load(&cfg, CLIENT_PUB, argc, argv);
	if(rc){
		if(rc == 2){
			/* --help */
			print_usage();
		}else{
			fprintf(stderr, "\nUse 'mosquitto_pub --help' to see usage.\n");
		}
		goto cleanup;
	}

#ifndef WITH_THREADING
	if(cfg.pub_mode == MSGMODE_STDIN_LINE){
		fprintf(stderr, "Error: '-l' mode not available, threading support has not been compiled in.\n");
		goto cleanup;
	}
#endif

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

	if(!cfg.topic || cfg.pub_mode == MSGMODE_NONE){
		fprintf(stderr, "Error: Both topic and message must be supplied.\n");
		print_usage();
		goto cleanup;
	}


	if(client_id_generate(&cfg)){
		goto cleanup;
	}

	mosq = mosquitto_new(cfg.id, true, NULL);
	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.\n");
				break;
		}
		goto cleanup;
	}
	if(cfg.debug){
		mosquitto_log_callback_set(mosq, my_log_callback);
	}
	mosquitto_connect_v5_callback_set(mosq, my_connect_callback);
	mosquitto_disconnect_v5_callback_set(mosq, my_disconnect_callback);
	mosquitto_publish_v5_callback_set(mosq, my_publish_callback);

	if(client_opts_set(mosq, &cfg)){
		goto cleanup;
	}

	rc = client_connect(mosq, &cfg);
	if(rc){
		goto cleanup;
	}

	rc = pub_shared_loop(mosq);

	if(cfg.message && cfg.pub_mode == MSGMODE_FILE){
		free(cfg.message);
	}
	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup();
	client_config_cleanup(&cfg);
	pub_shared_cleanup();

	if(rc){
		fprintf(stderr, "Error: %s\n", mosquitto_strerror(rc));
	}
	return rc;

cleanup:
	mosquitto_lib_cleanup();
	client_config_cleanup(&cfg);
	pub_shared_cleanup();
	return 1;
}
Exemple #18
0
Fichier : test.c Projet : 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;
}
/*
 * ##########################
 * 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;
}
Exemple #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;
}
/*
 * ##########################
 * 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;
}
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);
}
Exemple #23
0
int main( int argc, char* argv[] ) {
	setbuf(stdout, NULL);
	INFO("%s v1.0\n", argv[0]);
	config_t cfg;
	global_data_t state;
	struct mosquitto *mosq = NULL;

	config_init(&cfg);
	loadDefaults(&cfg);
    loadSerialDefaults(&cfg);

	if(parseArgs(argc, argv, &cfg)) {
		exit(1);
	}
	if(parseSerialArgs(argc, argv, &cfg)) {
        exit(1);
    }

	//config_write(&cfg, stderr);

	port_t serial;
	loadSerial(&cfg, &serial);

	if(serial.name == NULL) {
		ERR("Could not load serial configuration\n");
		exit(2);
	}

	if(!strlen(serial.name)) {
		ERR("You must specify the serial port\n");
		exit(2);
	}

	DBG("Setting up serial port...");
	state.arduino_fd = setupSerial(serial.name, serial.speed);
	if(state.arduino_fd < 0) {
		ERR("Failed to setup serial port %s @ %d\n", serial.name, serial.speed);
		exit(2);
	}
	INFO("listening for event on %s\n", serial.name);

	mosquitto_lib_init();
	mqttserver_t mqtt;
	loadMQTT(&cfg, &mqtt);

	char hostname[BUF_MAX];
	gethostname(hostname, BUF_MAX);
	asprintf(&state.client_id, "%s.%s", hostname, (char *) strlaststr(serial.name, "/"));
	mosq = mosquitto_new(state.client_id, true, &state.arduino_fd); //use port name as client id
	if(!mosq) {
		ERR("Couldn't create a new mosquitto client instance\n");
		exit(3);
	}

	//TODO setup callbacks
	mosquitto_log_callback_set(mosq, log_callback);
	mosquitto_disconnect_callback_set(mosq, disconnect_callback);
	mosquitto_connect_callback_set(mosq, connect_callback);
	mosquitto_message_callback_set(mosq, message_callback);

	INFO("Connecting to %s:%d ... ", mqtt.servername, mqtt.port);
	if(mosquitto_connect(mosq, mqtt.servername, mqtt.port, mqtt.keepalive)){
		ERR("\nUnable to connect to %s:%d.\n", mqtt.servername, mqtt.port);
		exit(3);
	}
	INFO("done\n");

	int mosq_fd = mosquitto_socket(mosq);

	fd_set active_fd_set, read_fd_set;
	/* Initialize the set of active sockets. */
	FD_ZERO (&active_fd_set);
	FD_SET (state.arduino_fd, &active_fd_set);
	FD_SET (mosq_fd, &active_fd_set);

	char buf[BUF_MAX];
	bzero(buf,BUF_MAX);

	int retries = 0;

	//TODO setup syscall to stop process
	while(1) {
		/* Block until input arrives on one or more active sockets. */
		read_fd_set = active_fd_set;
		if (select (FD_SETSIZE, &read_fd_set, NULL, NULL, NULL) < 0) {
			ERR("Error in select\n");
			sleep(BACKOFF);
			int r = mosquitto_reconnect(mosq);
			retries++;
			if(r != MOSQ_ERR_SUCCESS) {
				ERR("Could not reconnect to broker: %s\n", strerror(r));
				if(retries > MAX_RETRIES) {
					/* Cleanup */
					mosquitto_destroy(mosq);
					mosquitto_lib_cleanup();
					exit (EXIT_FAILURE);
				}
			} else {
				retries = 0;
				continue;
			}
		}

		/* Service all the sockets with input pending. */
		int i;
		for (i = 0; i < FD_SETSIZE; ++i)
			if (FD_ISSET (i, &read_fd_set)) {
				if(i == state.arduino_fd) {
					if(!readSerial(state.arduino_fd, buf, BUF_MAX, serial.timeout)) {
						arduinoEvent(buf, &cfg, mosq);
						bzero(buf,BUF_MAX);
					}
				} else if(i == mosq_fd) {
					mosquitto_loop_read(mosq, 1);
					mosquitto_loop_write(mosq, 1);
					mosquitto_loop_misc(mosq);
				}
			}
	};

	return EXIT_SUCCESS;
}