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

	mosquitto_lib_init();

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

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

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

	while(!mosquitto_loop(mosq, -1, 1)){
	}
	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup();
	return 0;
}
Example #2
0
/* Register the callbacks that the mosquitto connection will use. */
static bool set_callbacks(struct mosquitto *m) {
	mosquitto_connect_callback_set(m, on_connect);
	mosquitto_publish_callback_set(m, on_publish);
	mosquitto_subscribe_callback_set(m, on_subscribe);
	mosquitto_message_callback_set(m, on_message);
	return true;
}
Example #3
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;
}
Example #4
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;
}
Example #5
0
void
mloop(dispatch_data *dd) {
	char id[30];

	char *host = "130.102.128.123";
	int port = 1883;
	int keepalive = 60;
	bool clean_session = true;
	struct mosquitto *mosq = NULL;
	
	local_dd = dd;
	
	mosq = mosquitto_new(id, NULL);
	if(!mosq){
		fprintf(stderr, "Error: Out of memory.\n");
		return;
	}
	mosq_instance=mosq;
	mosquitto_connect_callback_set(mosq, my_connect_callback);
	mosquitto_message_callback_set(mosq, my_message_callback);
	mosquitto_subscribe_callback_set(mosq, my_subscribe_callback);
	
	if(mosquitto_connect(mosq, host, port, keepalive, clean_session)){
		fprintf(stderr, "Unable to connect.\n");
		return;
	}
	
	while(mosquitto_loop(mosq, -1) != -1){
	}
	mosquitto_destroy(mosq);
	return;
}
bool MosquittoHandler::init(std::string id)
{
    int minor, major, revision;
    mosquitto_lib_version(&major, &minor, &revision);

    if(numOfInstances == 0) {
        mosquitto_lib_init();
    }
    m_libInit = true;
    numOfInstances++;

    void* obj = (void*) this;

    m_mosquittoStruct = mosquitto_new(id.c_str(), obj);
    if(!m_mosquittoStruct) {
        m_lastErrorString = "Cannot create new Mosquitto instance";
        return false;
    }

    mosquitto_log_init(m_mosquittoStruct, MOSQ_LOG_ERR || MOSQ_LOG_WARNING, MOSQ_LOG_STDOUT);
    mosquitto_connect_callback_set(m_mosquittoStruct, MosquittoHandler::onConnectWrapper);
    mosquitto_disconnect_callback_set(m_mosquittoStruct, MosquittoHandler::onDisconnectWrapper);
    mosquitto_message_callback_set(m_mosquittoStruct, MosquittoHandler::onMessageWrapper);

    return true;
}
Example #7
0
File: main.c Project: 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;
}
Example #8
0
/* {{{ Mosquitto\Client::onMessage() */
PHP_METHOD(Mosquitto_Client, onMessage)
{
	mosquitto_client_object *object;
	zend_fcall_info message_callback = empty_fcall_info;
	zend_fcall_info_cache message_callback_cache = empty_fcall_info_cache;

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

	object->message_callback = message_callback;
	object->message_callback_cache = message_callback_cache;
	Z_ADDREF_P(message_callback.function_name);

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

	mosquitto_message_callback_set(object->client, php_mosquitto_message_callback);
}
Example #9
0
QMosquitto::QMosquitto(QObject *parent) : QObject(parent)
{
    mosquitto_lib_init();
    this->mosq = mosquitto_new(NULL, true, this);
    if(this->mosq == NULL) throw "Error creating mosquitto object";

    // Register message callback
    mosquitto_message_callback_set(this->mosq, on_message);
}
mosquittopp::mosquittopp(const char *id)
{
	mosq = mosquitto_new(id, this);
	mosquitto_connect_callback_set(mosq, on_connect_wrapper);
	mosquitto_disconnect_callback_set(mosq, on_disconnect_wrapper);
	mosquitto_publish_callback_set(mosq, on_publish_wrapper);
	mosquitto_message_callback_set(mosq, on_message_wrapper);
	mosquitto_subscribe_callback_set(mosq, on_subscribe_wrapper);
	mosquitto_unsubscribe_callback_set(mosq, on_unsubscribe_wrapper);
}
Example #11
0
int MqttHal_Init()
{
	int rc = 0;
	//struct mosq_config mosq_cfg;
	senhub_info_t *pshinfo;
	g_SensorHubList = NULL;
	
	//ADV_INFO("%s: \n", __func__);
	rc = mqtt_client_config_load(&g_mosq_cfg, CLIENT_SUB, 1, NULL);
	if(rc){
		mqtt_client_config_cleanup(&g_mosq_cfg);
		return 1;
	}

	mosquitto_lib_init();

	if(mqtt_client_id_generate(&g_mosq_cfg, "advmqttcli")){
		return 1;
	}

	g_mosq = mosquitto_new(g_mosq_cfg.id, g_mosq_cfg.clean_session, &g_mosq_cfg);
	if(!g_mosq){
		switch(errno){
			case ENOMEM:
				if(!g_mosq_cfg.quiet) fprintf(stderr, "Error: Out of memory.\n");
				break;
			case EINVAL:
				if(!g_mosq_cfg.quiet) fprintf(stderr, "Error: Invalid id and/or clean_session.\n");
				break;
		}
		mosquitto_lib_cleanup();
		return 1;
	}
	if(mqtt_client_opts_set(g_mosq, &g_mosq_cfg)){
		return 1;
	}

	mosquitto_connect_callback_set(g_mosq, MqttHal_Connect_Callback);
	mosquitto_message_callback_set(g_mosq, MqttHal_Message_Callback);

    mosquitto_disconnect_callback_set(g_mosq, MqttHal_Disconnect_Callback);
    mosquitto_publish_callback_set(g_mosq, MqttHal_Publish_Callback);

	// Create senhub root
	pshinfo = malloc(sizeof(senhub_info_t));
	memset(pshinfo, 0, sizeof(senhub_info_t));
	sprintf(pshinfo->macAddress, "0000%s" , g_GWInfMAC);
	pshinfo->jsonNode = NULL;
	pshinfo->id = senhub_list_newId(g_SensorHubList);
	//printf("%s: list add id=%d\n", __func__, pshinfo->id);
	g_SensorHubList = SENHUB_LIST_ADD(g_SensorHubList, pshinfo);

	return rc;
}
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;
}
Example #13
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);
}
Example #14
0
static
int
mosq_callback_set(lua_State *L)
{
	mosq_t *ctx = mosq_get(L, 1);

	enum callback_types callback_type = luaL_checkinteger(L, 2);

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

	int ref = luaL_ref(L, LUA_REGISTRYINDEX);

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

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

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

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

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

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

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

	return make_mosq_status_result(L, MOSQ_ERR_SUCCESS);
}
Example #15
0
    bool connect() {
        struct mosquitto *m = mosquitto_new(options.clientId, true, this);
        this->connection = m;

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

        const int res = mosquitto_connect(m, options.brokerHostname, options.brokerPort,
                                          options.keepaliveSeconds);
        return res == MOSQ_ERR_SUCCESS;
    }
Example #16
0
// establish the MQTT connection
int mqtt_loop(char *host, int port, char *username, char *password) {
  struct mosquitto *mosq;
  int r = 0;
  
  mosquitto_lib_init();
  
  if ((mosq = mosquitto_new(NULL, true, NULL)) == NULL) {    
    r = -1;
    
    printf("Failed to build the MQTT object.\n" );
    
    goto  FUNCTION_END;
  }
  
  // declare the callback functions  
  mosquitto_connect_callback_set(mosq, mqtt_callback_connect);  
  mosquitto_message_callback_set(mosq, mqtt_callback_message);  
  mosquitto_disconnect_callback_set(mosq, mqtt_callback_disconnect);
  
  // authentication  
  r = mosquitto_username_pw_set(mosq, username, password);
  
  if (r) {    
    r = -2;
    
    printf("Failed to setup the MQTT authentication - %d.\n", r);
    
    goto  FUNCTION_END;
  }
  
  // connect and wait  
  if (mosquitto_connect(mosq, host, port, 60) == MOSQ_ERR_SUCCESS) {    
    r = 0;
    
    mosquitto_loop_forever(mosq, -1, 1);

  } else {    
    r = -3;
    
    printf("Failed to connect to MQTT broker.\n");
  }
  
  mosquitto_destroy(mosq);
  
FUNCTION_END:
  
  mosquitto_lib_cleanup();
  
  return r;
}
Example #17
0
int main(int argc, char *argv[])
{
char clientid[24]="FcBitu'";
int rc = 0;
//int nr = 0;

struct mosquitto *mosq;
int mid;

signal(SIGINT, handle_signal);
signal(SIGTERM, handle_signal);

mosquitto_lib_init();
mosq = mosquitto_new(clientid, true, NULL);

if(mosq){
mosquitto_connect_callback_set(mosq, connect_callback);
mosquitto_message_callback_set(mosq, message_callback);
rc = mosquitto_connect(mosq, mqtt_host, mqtt_port, 60);
mosquitto_subscribe(mosq, NULL, "coords", 0);

while(run){
rc = mosquitto_loop(mosq, 1, 1);
if(run && rc){
        sleep(2);
        printf ("\n run: %d   rc: %d  \n", run,rc);
        mosquitto_reconnect(mosq);
        }
printf("robot: timestamp: %d     X: %d        Y: %d    unghi: %d\n ",coordrob[4] .timestamp,coordrob[4] .x,coordrob[4] .y,coordrob[4] .angle);
printf("0: timestamp: %d     X: %d        Y: %d    unghi: %d\n ",coordrob[0] .timestamp,coordrob[0] .x,coordrob[0] .y,coordrob[0] .angle);

quarterback_oriented();
mosquitto_publish(mosq, &mid, idfundas, sizeof(struct control), &ctr[fundas], 0, false);
mosquitto_publish(mosq, &mid, idminge, sizeof(struct control), &ctr[0], 0, false);
//mosquitto_publish(mosq, &mid, idportar, sizeof(struct control), &ctr[ceva_portar], 0, false);

//usleep(1000);
/*if (nr >= 255) nr = 0;
ctr.right = nr; ctr.left = nr;
nr = nr + 1;
printf ("comenzi robot: ctr.right: %d  ctr.left: %d timestamp: %d\n", ctr.right,ctr.left,coordrob[0].timestamp);
fflush(stdout);*/
}
mosquitto_destroy(mosq);
}

mosquitto_lib_cleanup();

return rc;
}
Example #18
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;
}
Example #19
0
int auth_mqtt_init(void)
{
	mosquitto_lib_init();
	auth_mqtt_mosq = mosquitto_new("auth_client_XXXXXXXXXXXX", true, NULL);
	if (!auth_mqtt_mosq) {
		mosquitto_lib_cleanup();
		return -1;
	}
	mosquitto_username_pw_set(auth_mqtt_mosq, "#qmsw2..5#", "@oawifi15%");
	mosquitto_connect_callback_set(auth_mqtt_mosq, connect_callback);
	mosquitto_message_callback_set(auth_mqtt_mosq, message_callback);
	mosquitto_connect(auth_mqtt_mosq, "127.0.0.1", 1883, 60);

	return 0;
}
Example #20
0
int main(int argc, char *argv[])
{
    char clientid[24]="Move Test";
    struct mosquitto *mosq;
    int rc = 0;
    int mid;

    signal(SIGINT, handle_signal);
    signal(SIGTERM, handle_signal);

    mosquitto_lib_init();


    mosq = mosquitto_new(clientid, true, NULL);
    if(mosq) {
        mosquitto_connect_callback_set(mosq, connect_callback);
        mosquitto_message_callback_set(mosq, message_callback);

        rc = mosquitto_connect(mosq, mqtt_host, mqtt_port, 60);

        mosquitto_subscribe(mosq, NULL, "#", 0);

        ctr.left=100;
        ctr.right=100;
        ctr.time=0;
        mosquitto_publish(mosq, &mid, "in15", sizeof(ctr), &ctr, 2, false);

        while(run) {
            rc = mosquitto_loop(mosq, -1, 1);
            if(run && rc) {
                sleep(20);
                mosquitto_reconnect(mosq);
            }
        }
        mosquitto_destroy(mosq);
    }

    mosquitto_lib_cleanup();

    return rc;
}
Example #21
0
File: mqtt.c Project: dsmrd/dsmrd
int mqtt_open(mqtt_t inst, dispatch_t d, const char* name, const char* host, int port, int keepalive) {
    int rval = -1;
    int fd;

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

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

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

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

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

    return rval;
}
int main(int argc, char *argv[])
{
	int rc;
	struct mosquitto *mosq;

	int port = atoi(argv[1]);

	mosquitto_lib_init();

	mosq = mosquitto_new("publish-qos2-test", true, &run);
	mosquitto_int_option(mosq, MOSQ_OPT_PROTOCOL_VERSION, MQTT_PROTOCOL_V5);
	mosquitto_connect_callback_set(mosq, on_connect);
	mosquitto_disconnect_callback_set(mosq, on_disconnect);
	mosquitto_message_callback_set(mosq, on_message);

	rc = mosquitto_connect(mosq, "localhost", port, 60);

	while(run == -1){
		mosquitto_loop(mosq, 100, 1);
	}

	mosquitto_lib_cleanup();
	return run;
}
Example #23
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 ;
}
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();
}
Example #25
0
void /*PORT_NAME*/_setup() {
	char *id = NULL;
	char *id_prefix = NULL;
	int i;
	char *host = "/*HOST_ADDRESS*/";
	int port = /*PORT_NUMBER*/;
	int keepalive = 60;
	bool clean_session = true;
	bool debug = false;
	int rc, rc2;
	char hostname[21];
	char err[1024];
	
	uint8_t *will_payload = NULL;
	long will_payloadlen = 0;
	int will_qos = 0;
	bool will_retain = false;
	char *will_topic = NULL;

        /*MULTI_TOPIC_INIT*/

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

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

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

}
Example #26
0
File: test.c Project: 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;
}
Example #27
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;
}
Example #28
0
int main(int argc, char *argv[])
{
	MYSQL *connection;
	my_bool reconnect = true;
	char clientid[24];
	struct mosquitto *mosq;
	int rc = 0;

	signal(SIGINT, handle_signal);
	signal(SIGTERM, handle_signal);

	mysql_library_init(0, NULL, NULL);
	mosquitto_lib_init();

	connection = mysql_init(NULL);

	if(connection){
		mysql_options(connection, MYSQL_OPT_RECONNECT, &reconnect);

		connection = mysql_real_connect(connection, db_host, db_username, db_password, db_database, db_port, NULL, 0);

		if(connection){
			stmt = mysql_stmt_init(connection);

			mysql_stmt_prepare(stmt, db_query, strlen(db_query));

			memset(clientid, 0, 24);
			snprintf(clientid, 23, "mysql_log_%d", getpid());
			mosq = mosquitto_new(clientid, true, connection);
			if(mosq){
				mosquitto_connect_callback_set(mosq, connect_callback);
				mosquitto_message_callback_set(mosq, message_callback);


			    rc = mosquitto_connect(mosq, mqtt_host, mqtt_port, 60);

				mosquitto_subscribe(mosq, NULL, "#", 0);

				while(run){
					rc = mosquitto_loop(mosq, -1, 1);
					if(run && rc){
						sleep(20);
						mosquitto_reconnect(mosq);
					}
				}
				mosquitto_destroy(mosq);
			}
			mysql_stmt_close(stmt);

			mysql_close(connection);
		}else{
			fprintf(stderr, "Error: Unable to connect to database.\n");
			printf("%s\n", mysql_error(connection));
			rc = 1;
		}
	}else{
		fprintf(stderr, "Error: Unable to start mysql.\n");
		rc = 1;
	}

	mysql_library_end();
	mosquitto_lib_cleanup();

	return rc;
}
Example #29
0
static int ctx_callback_set(lua_State *L)
{
	ctx_t *ctx = ctx_check(L, 1);
	int callback_type;

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

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

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

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

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

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

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

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

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

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

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

	return mosq__pstatus(L, MOSQ_ERR_SUCCESS);
}
Example #30
0
int main(int argc, char *argv[]) {
  // initialize the system logging
  openlog("ampel", LOG_CONS | LOG_PID, LOG_USER);
  syslog(LOG_INFO, "Starting Ampel controller.");

  // initialize I2C
  I2C_init();
  
  // initialize MQTT
  mosquitto_lib_init();
  
  void *mqtt_obj;
  struct mosquitto *mosq;
  mosq = mosquitto_new("ampel", true, mqtt_obj);
  if (((int)mosq == ENOMEM) || ((int)mosq == EINVAL)) {
        syslog(LOG_ERR, "MQTT error %d (%s)!", 
                        (int)mosq,
                        mosquitto_strerror((int)mosq));
    mosq = NULL;
  }
  
  if (mosq) {
    int ret;
    
    ret = mosquitto_connect(mosq, MQTT_HOST, MQTT_PORT, 30);
    if (ret == MOSQ_ERR_SUCCESS)
      syslog(LOG_INFO, "MQTT connection to %s established.", MQTT_HOST);
    else {
        syslog(LOG_ERR, "MQTT error %d (%s)!", 
                        ret,
                        mosquitto_strerror(ret));
        //TODO cleanup
        return -1;
    }      
  }
  
  // subscribe to door topic
  if (mosq) {
    mosquitto_message_callback_set(mosq, mqtt_message_callback);
    mosquitto_subscribe(mosq, NULL, MQTT_DOOR_TOPIC, 0);
  }

  struct ampel_state_t before = {
    .red = false,
    .green = false,
    .blink = false
  };

  int countdown;
  
  char mqtt_payload[MQTT_MSG_MAXLEN];
  
  char run=1;
  int i=0;
  while(run) {
    struct ampel_state_t color = before;

    // check space status
    bool is_open = get_space_status(SPACEAPI_PATH);
    
    // manage the countdown
    if (!is_open && door_is_locked) {
      if (countdown) --countdown;
    } else {
      countdown = 30;
    }
    
    // set ampel according to space status
    color.red = !is_open && countdown;
    color.green = is_open;
    color.blink = door_is_locked;

    printf("****** %u\n", i++);
    printf("Ampel State:\n");
    char* on = color.blink ? "Blink" : "On";
    printf("Red:\t\t%s\n", color.red ? on : "Off");
    printf("Green:\t\t%s\n", color.green ? on : "Off");
    printf("Door:\t\t%s\n", door_is_closed ? 
                            (door_is_locked ? "Locked" : "Closed")
                            : "Open");
    printf("Countdown:\t%d s\n", countdown);
    printf("\n");
    
    // set the LEDs
    ampel_set_color(color);

    // emit MQTT messages
    mqtt_payload[0] = 0;

    // render MQTT-message based on ampel state
    if ((before.red != color.red) ||
        (before.green != color.green) ||
        (before.blink != color.blink)) {
        
      strcpy(mqtt_payload, MQTT_MSG_AMPEL);
        
      char b = color.blink ? 'b' : '1';  
      mqtt_payload[13] = color.red   ? b : '0';
      mqtt_payload[14] = color.green ? b : '0';      
    }

    before = color;      
    
    // send MQTT message if there is payload
    if (mqtt_payload[0] && mosq) {
      int ret;
      int mid;
      ret = mosquitto_publish(
                        mosq, 
                        &mid,
                        MQTT_AMPEL_TOPIC,
                        strlen(mqtt_payload), mqtt_payload,
                        2, /* qos */
                        true /* retain */
                       );
      if (ret != MOSQ_ERR_SUCCESS)
        syslog(LOG_ERR, "MQTT error on message \"%s\": %d (%s)", 
                        mqtt_payload, 
                        ret,
                        mosquitto_strerror(ret));
      else
        syslog(LOG_INFO, "MQTT message \"%s\" sent with id %d.", 
                         mqtt_payload, mid);
    }
    
    // call the mosquitto loop to process messages
    if (mosq) {
      int ret;
      ret = mosquitto_loop(mosq, 100, 1);
      // if failed, try to reconnect
      if (ret) {
        syslog(LOG_ERR, "MQTT reconnect.");
        mosquitto_reconnect(mosq);
      }
    }
    
    if (sleep(1)) 
      break;
  }

  // clean-up MQTT
  if (mosq) {
    mosquitto_disconnect(mosq);
    mosquitto_destroy(mosq);
  }
  mosquitto_lib_cleanup();

  syslog(LOG_INFO, "Doorstate observer finished.");
  closelog();
    
  return 0;
}