コード例 #1
0
ファイル: mqtt_bridge.c プロジェクト: darcyg/mqtt_bridge
void on_mqtt_connect(struct mosquitto *mosq, void *obj, int result)
{
	struct device *dev;
	int rc;

	if (!result) {
		connected = true;
		if(config.debug) printf("MQTT Connected.\n");

		rc = mosquitto_subscribe(mosq, NULL, bridge.bridge_dev->config_topic, config.mqtt_qos);
		if (rc) {
			fprintf(stderr, "MQTT - Subscribe ERROR: %s\n", mosquitto_strerror(rc));
			run = 0;
			return;
		}
		if (config.debug > 1) printf("Subscribe topic: %s\n", bridge.bridge_dev->config_topic);

		for (dev = bridge.dev_list; dev != NULL; dev = dev->next) {
			rc = mosquitto_subscribe(mosq, NULL, dev->config_topic, config.mqtt_qos);
			if (rc) {
				fprintf(stderr, "MQTT - Subscribe ERROR: %s\n", mosquitto_strerror(rc));
				run = 0;
				return;
			}
			if (config.debug > 1) printf("Subscribe topic: %s\n", bridge.bridge_dev->config_topic);
		}

		send_alive(mosq);
	} else {
		fprintf(stderr, "MQTT - Failed to connect: %s\n", mosquitto_connack_string(result));
    }
}
コード例 #2
0
void MQTT_connect_callback(void *obj, int result)
{
	printf("[MQTT] connected callback\n");
	struct mosquitto *mosq = obj;

	int i;
	if(!result){
		mosquitto_subscribe(MQTT_mosq, NULL, MQTT_topic, MQTT_topic_qos);
	}else{
		switch(result){
			case 1:
				fprintf(stderr, "[MQTT] Connection Refused: unacceptable protocol version\n");
				break;
			case 2:
				fprintf(stderr, "[MQTT] Connection Refused: identifier rejected\n");
				break;
			case 3:
				fprintf(stderr, "[MQTT] Connection Refused: broker unavailable\n");
				break;
			case 4:
				fprintf(stderr, "[MQTT] Connection Refused: bad user name or password\n");
				break;
			case 5:
				fprintf(stderr, "[MQTT] Connection Refused: not authorised\n");
				break;
			default:
				fprintf(stderr, "[MQTT] Connection Refused: unknown reason\n");
				break;
		}
	}
}
コード例 #3
0
ファイル: Connector.c プロジェクト: cortoproject/mqtt
static void mqtt_onConnect(
    struct mosquitto *client,
    void *data,
    int rc)
{
    /* Subscribe to topic when connected to the broker */
    mqtt_Connector this = data;
    if (rc != 0) {
        corto_error("mqtt: unable to connect to %s", this->host);
    } else {
        corto_id topic;
        strcpy(topic, this->topic);

        corto_ok("mqtt: connected to %s", this->host);

        /* Subscribe to subtree of mountpoint */
        if (*topic && strcmp(topic, "/")) {
            strcat(topic, "/#");
        } else {
            strcpy(topic, "#");
        }

        corto_trace("mqtt: subscribing to %s", topic);
        if (mosquitto_subscribe(client, 0, topic, 1)) {
            corto_error("mqtt: failed to subscribe for topic");
        }
        corto_ok("mqtt: subscribed to %s", topic);
    }
}
コード例 #4
0
ファイル: main.c プロジェクト: quedah/techgi
void on_connect(struct mosquitto *mosq, void *userdata, int result)
{
    if(!result) {
        // subscribe to chat topic on successful connect.
        mosquitto_subscribe(mosq, NULL, topic_name, 2);
    } else {
        printf("Connect failed\n");
    }
}
コード例 #5
0
ファイル: mqtt.c プロジェクト: backeliten/mqttrf
void output5_connect_callback(struct mosquitto *mosq, void *userdata, int result)
{
	int i;		//Didnt work to use subscribe on two channels, we got a nasty race condition, so that messages was not arrived.
	if(!result){
		/* Subscribe to broker information topics on successful connect. */
		mosquitto_subscribe(mosq, NULL, "command/output5", 2);
	}else{
		fprintf(stderr, "Connect failed\n");
	}
}
コード例 #6
0
void my_connect_callback(struct mosquitto *mosq, void *userdata, int result)
{
	int i;
	if(!result){
		/* Subscribe to broker information topics on successful connect. */
		mosquitto_subscribe(mosq, NULL, "demo", 2);
	}else{
		fprintf(stderr, "Connect failed\n");
	}
}
コード例 #7
0
void my_connect_callback(void *obj, int result)
{
	struct mosquitto *mosq = obj;
	
	if(!result){
		mosquitto_subscribe(mosq, (uint16_t *) 0, "/beacon2", 0);
	}else{
		fprintf(stderr, "Connect failed\n");
	}
}
コード例 #8
0
ファイル: mqtt_s_serial.c プロジェクト: GBert/misc
void mqtt_cb_connect(struct mosquitto *mosq, void *userdata, int result) {
    /* TODO: length */
    char subscribe[MAX_BUFFER];

    snprintf(subscribe, MAX_BUFFER - 4, "%s/out", topic);
    if (!result) {
	mosquitto_subscribe(mosq, NULL, subscribe, 2);
    } else {
	fprintf(stderr, "MQTT subscribe failed\n");
    }
}
コード例 #9
0
bool MosquittoHandler::subscribe(const char* subTopic)
{
    uint16_t mid = 1;

    int errorNum = mosquitto_subscribe(m_mosquittoStruct, &mid, subTopic, 0);

    if(errorNum != MOSQ_ERR_SUCCESS) {
        m_lastErrorString = errorByNum(errorNum);
        return false;
    }
    return true;
}
コード例 #10
0
ファイル: serial.c プロジェクト: dgomes/MELGA
void connect_callback(struct mosquitto *mosq, void *userdata, int level) {
	global_data_t *g = userdata;

	//Subscribe command
	char sub[255];
	snprintf(sub, 255, "%s/cmd", g->client_id);
	int r = mosquitto_subscribe(mosq, NULL, sub, 2);
	INFO("Subscribe %s = %d\n", sub, r);
	if(r != MOSQ_ERR_SUCCESS) {
		ERR("Could not subscribe to %s", sub);
	}
}
コード例 #11
0
ファイル: mqtt.hpp プロジェクト: rraallvv/microflo
 void subscribePorts() {
     for (std::vector<Port>::iterator it = options.info.inports.begin() ; it != options.info.inports.end(); ++it) {
         const Port &port = *it;
         const char *pattern = port.topic.c_str();
         mosquitto_subscribe(this->connection, NULL, pattern, 0);
         LOG("subscribed inport to MQTT topic: %s\n", pattern);
     }
     for (std::vector<Port>::iterator it = options.info.outports.begin() ; it != options.info.outports.end(); ++it) {
         const Port &port = *it;
         network->subscribeToPort(port.node, port.port, true);
         LOG("setup outport to MQTT topic: %s\n", port.topic.c_str());
     }
 }
コード例 #12
0
ファイル: main.cpp プロジェクト: technocreatives/sdl-base
void connect_callback(struct mosquitto *mosq, void *userdata, int result)
{
	if(!result)
	{
		std::cout << "Connected to broker." << std::endl;
		//Subscribe to broker information topics on successful connect.
		mosquitto_subscribe(mosq, NULL, "$SYS/#", 2);
	}
	else
	{
		std::cout << "Failed to connect to broker :(" << std::endl;
	}
}
コード例 #13
0
ファイル: main_quarterback.c プロジェクト: laurion/RoboSoccer
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;
}
コード例 #14
0
ファイル: test.c プロジェクト: weikent/C
void my_connect_callback(struct mosquitto *mosq, void *userdata, int result)
{
  //	int i;
	if(!result){
		/* Subscribe to broker information topics on successful connect. */
    //		mosquitto_subscribe(mosq, NULL, "$SYS/#", 2);
    int rc = mosquitto_subscribe(mosq, NULL, "isocketsTest/Server/#", 0);
    printf("subscribe rc = %d\n", rc);

    printf("connect successful\n");
	}else{
		fprintf(stderr, "Connect failed\n");
	}
}
コード例 #15
0
static int ctx_subscribe(lua_State *L)
{
	ctx_t *ctx = ctx_check(L, 1);
	int mid;
	const char *sub = luaL_checkstring(L, 2);
	int qos = luaL_optinteger(L, 3, 0);

	int rc = mosquitto_subscribe(ctx->mosq, &mid, sub, qos);

	if (rc != MOSQ_ERR_SUCCESS) {
		return mosq__pstatus(L, rc);
	} else {
		lua_pushinteger(L, mid);
		return 1;
	}
}
コード例 #16
0
ファイル: driver.c プロジェクト: neuroidss/mqtt
static
int
mosq_subscribe(lua_State *L)
{
	mosq_t *ctx = mosq_get(L, 1);
	int mid;
	const char *sub = luaL_checkstring(L, 2);
	int qos = luaL_optinteger(L, 3, 0);

	int rc = mosquitto_subscribe(ctx->mosq, &mid, sub, qos);

	if (rc != MOSQ_ERR_SUCCESS) {
		return make_mosq_status_result(L, rc);
	}

	return make_int_result(L, true, mid);
}
コード例 #17
0
ファイル: sub_client.c プロジェクト: SSSang2/mosquittoMaster
void my_connect_callback(struct mosquitto *mosq, void *obj, int result)
{
	int i;
	struct mosq_config *cfg;

	assert(obj);
	cfg = (struct mosq_config *)obj;

	if(!result){
		for(i=0; i<cfg->topic_count; i++){
			mosquitto_subscribe(mosq, NULL, cfg->topics[i], cfg->qos);
		}
	}else{
		if(result && !cfg->quiet){
			fprintf(stderr, "%s\n", mosquitto_connack_string(result));
		}
	}
}
コード例 #18
0
void my_connect_callback(struct mosquitto *mosq, void *obj, int result)
{
	int i;
	struct userdata *ud;

	assert(obj);
	ud = (struct userdata *)obj;

	if(!result){
		for(i=0; i<ud->topic_count; i++){
			mosquitto_subscribe(mosq, NULL, ud->topics[i], ud->topic_qos);
		}
	}else{
		if(result && !ud->quiet){
			fprintf(stderr, "%s\n", mosquitto_connack_string(result));
		}
	}
}
コード例 #19
0
ファイル: move.c プロジェクト: rafyyy/FotbalRobotic
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;
}
コード例 #20
0
void on_mqtt_connect(struct mosquitto *mosq, void *obj, int result)
{
	int rc;

	if (!result) {
		connected = true;
		if(config.debug != 0) printf("MQTT Connected.\n");

		rc = mosquitto_subscribe(mosq, NULL, bridge.config_topic, config.mqtt_qos);
		if (rc) {
			fprintf(stderr, "MQTT - Subscribe ERROR: %s\n", mosquitto_strerror(rc));
			run = 0;
			return;
		}
		snprintf(gbuf, GBUF_SIZE, "%d,%d", PROTO_ST_ALIVE, bridge.modules_len);
		mqtt_publish(mosq, bridge.status_topic, gbuf);
		return;
	} else {
		fprintf(stderr, "MQTT - Failed to connect: %s\n", mosquitto_connack_string(result));
    }
}
コード例 #21
0
/* {{{ Mosquitto\Client::subscribe() */
PHP_METHOD(Mosquitto_Client, subscribe)
{
	mosquitto_client_object *object;
	char *sub;
	int sub_len, retval, mid;
	long qos;

	PHP_MOSQUITTO_ERROR_HANDLING();
	if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "sl",
				&sub, &sub_len, &qos) == FAILURE) {
		PHP_MOSQUITTO_RESTORE_ERRORS();
		return;
	}
	PHP_MOSQUITTO_RESTORE_ERRORS();

	object = (mosquitto_client_object *) mosquitto_client_object_get(getThis() TSRMLS_CC);
	retval = mosquitto_subscribe(object->client, &mid, sub, qos);

	php_mosquitto_handle_errno(retval, errno TSRMLS_CC);

	RETURN_LONG(mid);
}
コード例 #22
0
ファイル: client.c プロジェクト: YunYenWang/IoT
// connection is ready
void mqtt_callback_connect(struct mosquitto *mosq, void *obj, int result) {
  char topic[BUFFER_SIZE];
  int r = 0;

  printf("MQTT is connected.\n");

  snprintf(topic, BUFFER_SIZE, "/v1/device/%s/sensor/%s/rawdata", DEVICE_ID, OUTPUT_SENSOR_ID);
  
  // subscribe the INPUT sensor
  r = mosquitto_subscribe(mosq, NULL, topic, 0);  
  if (r == 0) {    
    printf("%s is subscribed.\n", topic);

  } else {    
    printf("Failed to subscribe the topic - %s\n", topic);
  }

  // fork a thread to change rawdata of the OUTPUT sensor
  if (pthread_create(&g_thread_to_post, NULL, (void *) thread_to_post, mosq)) {
    printf("Failed to create a thread to change the rawdata.\n");    
  }
}
コード例 #23
0
ファイル: mysql_log.c プロジェクト: PierreF/mosquitto
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;
}
コード例 #24
0
ファイル: td-mqtt.c プロジェクト: peahonen/td-mqtt
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;
}
コード例 #25
0
ファイル: auth_mqtt.c プロジェクト: itgb/ap_apps
void connect_callback(struct mosquitto *mosq, void *obj, int result)
{
	printf("connect_callback obj=%p, result=%d\n", obj, result);
	mosquitto_subscribe(mosq, NULL, "a/local/auth", 0);//client
	mosquitto_subscribe(mosq, NULL, "a/vlan/group/center", 0);//center
}
コード例 #26
0
ファイル: Gateway.c プロジェクト: pecmosg/HomeAuto
int main(int argc, char* argv[]) {
	if (argc != 1) uso();

#ifdef DAEMON
	//Adapted from http://www.netzmafia.de/skripten/unix/linux-daemon-howto.html
	pid_t pid, sid;

	openlog("Gatewayd", LOG_PID, LOG_USER);

	pid = fork();
	if (pid < 0) {
		LOG_E("fork failed");
		exit(EXIT_FAILURE);
	}
	/* If we got a good PID, then
		 we can exit the parent process. */
	if (pid > 0) {
		LOG("Child spawned, pid %d\n", pid);
		exit(EXIT_SUCCESS);
	}

	/* Change the file mode mask */
	umask(0);

	/* Create a new SID for the child process */
	sid = setsid();
	if (sid < 0) {
		LOG_E("setsid failed");
		exit(EXIT_FAILURE);
	}
        
	/* Change the current working directory */
	if ((chdir("/")) < 0) {
	  LOG_E("chdir failed");
	  exit(EXIT_FAILURE);
	}
        
	/* Close out the standard file descriptors */
	close(STDIN_FILENO);
	close(STDOUT_FILENO);
	close(STDERR_FILENO);
#endif //DAEMON

	// Mosquitto ----------------------
	struct mosquitto *m = mosquitto_new(MQTT_CLIENT_ID, true, null);
	if (m == NULL) { die("init() failure\n"); }

	if (!set_callbacks(m)) { die("set_callbacks() failure\n"); }
	if (!connect(m)) { die("connect() failure\n"); }

	//RFM69 ---------------------------
	theConfig.networkId = 101;
	theConfig.nodeId = 12;
	theConfig.frequency = RF69_868MHZ;
	theConfig.keyLength = 16;
	memcpy(theConfig.key, "pecmosg110028225", 16);
	theConfig.isRFM69HW = true;
	theConfig.promiscuousMode = true;
	theConfig.messageWatchdogDelay = 1800000; // 1800 seconds (30 minutes) between two messages 

	rfm69 = new RFM69();
	rfm69->initialize(theConfig.frequency,theConfig.nodeId,theConfig.networkId);
	initRfm(rfm69);

	// Mosquitto subscription ---------
	char subsciptionMask[128];
	sprintf(subsciptionMask, "%s/%03d/#", MQTT_ROOT, theConfig.networkId);
	LOG("Subscribe to Mosquitto topic: %s\n", subsciptionMask);
	mosquitto_subscribe(m, NULL, subsciptionMask, 0);
	
	LOG("setup complete\n");
	return run_loop(m);
}  // end of setup
コード例 #27
0
ファイル: qmosquitto.cpp プロジェクト: grisu48/meteo
void QMosquitto::subscribe(const QString &topic) {
    std::string s_topic = topic.toStdString();
    int rc = mosquitto_subscribe(this->mosq, NULL, s_topic.c_str(), 0);
    if(rc != MOSQ_ERR_SUCCESS)
        throw "Subscribe failed";
}
コード例 #28
0
int run_subscriber(int argc, char* const argv[])
//int main(int argc, char* const argv[])
{
  mosquitto_lib_init();
#if 0
  {
    int major, minor, revision;
    mosquitto_lib_version(&major, &minor, &revision);
    std::cout << "Mosquitto library version - " << major << "." << minor << "." << revision << std::endl;
  }
#endif
  std::cout << "Rx Measurement test program" << std::endl;


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

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

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

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

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

    case HELP_OPTION:
      exit(EXIT_FAILURE);
      break;

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

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

    case JSON_MSG_OPTION:
      use_json = true;
      break;

    case BINARY_MSG_OPTION:
      use_json = false;
      break;

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

    default:
      more_options = false;
      break;
    }
  }

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

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

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

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

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

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

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

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

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

  mosquitto_lib_cleanup();
}
コード例 #29
0
ファイル: mosquittopp.cpp プロジェクト: PierreF/mosquitto
int mosquittopp::subscribe(int *mid, const char *sub, int qos)
{
	return mosquitto_subscribe(m_mosq, mid, sub, qos);
}
コード例 #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;
}