void mqtt_send(struct mosquitto* mosq,
               const char* mqtt_payload,
               const char* mqtt_topic)
{
    // send MQTT message if there is payload
    if (mqtt_payload[0] && mosq) {
      int ret;
      int mid;
      ret = mosquitto_publish(
                        mosq,
                        &mid,
                        mqtt_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);
    }
}
/*
 * ##########################
 * Callback Functions
 * ##########################
 */
void mqtt_connect_callback(struct mosquitto *mosq, void *obj, int result)
{
	int rc = MOSQ_ERR_SUCCESS;
	struct mqtt_userdata *ud = NULL;

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

	if(!result){
		switch(ud->mode){
			case MQTT_MSGMODE_CMD:
			case MQTT_MSGMODE_FILE:
			case MQTT_MSGMODE_STDIN_FILE:
				rc = mosquitto_publish(mosq, &ud->mid_sent, ud->topic, ud->msglen, ud->message, ud->qos, ud->retain);
				break;
			case MQTT_MSGMODE_NULL:
				rc = mosquitto_publish(mosq, &ud->mid_sent, ud->topic, 0, NULL, ud->qos, ud->retain);
				break;
			case MQTT_MSGMODE_STDIN_LINE:
				ud->status = MQTT_STATUS_CONNACK_RECVD;
				break;
		}
		if(rc){
			if(!ud->quiet){
				switch(rc){
					case MOSQ_ERR_INVAL:
						fprintf(stderr, "Error: Invalid input. Does your topic contain '+' or '#'?\n");
						break;
					case MOSQ_ERR_NOMEM:
						fprintf(stderr, "Error: Out of memory when trying to publish message.\n");
						break;
					case MOSQ_ERR_NO_CONN:
						fprintf(stderr, "Error: Client not connected when trying to publish.\n");
						break;
					case MOSQ_ERR_PROTOCOL:
						fprintf(stderr, "Error: Protocol error when communicating with broker.\n");
						break;
					case MOSQ_ERR_PAYLOAD_SIZE:
						fprintf(stderr, "Error: Message payload is too large.\n");
						break;
				}
			}
			mosquitto_disconnect(mosq);
		}
	}else{
		if(result && !ud->quiet){
			fprintf(stderr, "%s\n", mosquitto_connack_string(result));
		}
	}
}
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;
}
Exemple #4
0
int send_insecure_message(time_t tt) {
    char msg[128];
    sprintf(msg, "Insecure Message with sequence: %ld", tt);
    mosquitto_publish(mosq, NULL, "demo/insecure", strlen(msg), (unsigned char*)msg, 0, false);
    DLOG("pub unsigned: %s\n", msg);
    return 0;
}
Exemple #5
0
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;
}
Exemple #6
0
// fork a thread to change the rawdata of input sensor
void thread_to_post(void *arg) {
  char topic[BUFFER_SIZE];
  char json[BUFFER_SIZE];
  int i = 0;
  int r = 0;

  struct mosquitto *mosq = (struct mosquitto *) arg;

  // specify rawdata topic
  snprintf(topic, BUFFER_SIZE, "/v1/device/%s/rawdata", DEVICE_ID);
  
  while (g_thread_running) {
    // prepare the JSON data to change the rawdata
    snprintf(json, BUFFER_SIZE, "[{\"id\":\"%s\",\"value\":[\"%d\"]}]", INPUT_SENSOR_ID, i++);

    // publish the rawdata via MQTT
    r = mosquitto_publish(mosq, NULL, topic, strlen(json), json, 0, false);
    if (r == MOSQ_ERR_SUCCESS) {
      printf("Save: %s\n", json);

    } else {
      printf("Failed to publish the rawdata [%d]\n", r); // MOSQ_ERR_INVAL, MOSQ_ERR_NOMEM, MOSQ_ERR_NO_CONN, MOSQ_ERR_PROTOCOL, MOSQ_ERR_PAYLOAD_SIZE
    }
    
    sleep(5);
  }
  
  pthread_detach(g_thread_to_post);
}
Exemple #7
0
void pub(char *prefix ,char *zone, char *topic, char *str, int retain)
{
	char *fulltopic;
	int rc;
	int qos = 2;
	int mid;

	fulltopic = malloc(strlen(prefix) + 
		((zone) ? strlen(zone) : 0) +
		strlen(topic) + 12);
	if (fulltopic == NULL) {
		fprintf(stderr, "ENOMEM\n");
		return;
	}

	if (zone) {
		sprintf(fulltopic, "%s/%s/%s", prefix, zone, topic);
	} else {
		sprintf(fulltopic, "%s/%s", prefix, topic);
	}
	// printf("%s %s\n", fulltopic, str); fflush(stdout);
	rc = mosquitto_publish(m, &mid, fulltopic, strlen(str), str, qos, retain);
	if (rc != MOSQ_ERR_SUCCESS) {
		fprintf(stderr, "Cannot publish: %s\n", mosquitto_strerror(rc));
		fatal();
	}
	// printf("PUB mid %d\n", mid);

	free(fulltopic);
}
Exemple #8
0
/**
 * Demonstrate sending a signed (HMAC) and then encrypted message to MQTT
 * @param tt just something that varies between messages, so we can see it when decrypted
 * @return
 */
int send_signed_message(time_t tt, char *shared_key) {

    // Make message...
    char data[200];
    sprintf(data, "Signed Message with sequence: %ld", tt);

    DLOG("pub SIGNED: %s\n", data);
    unsigned char* hmac;
    unsigned int result_len;

    // printf "%s" "message to be signed..." | openssl sha1 -hmac "karl_hmac_key"
    hmac = HMAC(EVP_sha1(), shared_key, strlen(shared_key), (unsigned char*)data, strlen(data), NULL, &result_len);
    if (hmac == NULL) {
        fatal("Couldn't sign the message: %s\n", ERR_error_string(ERR_get_error(), NULL));
    }

    // Add signature to message
    char topic[60];
    char *tmp = &topic[0];
    tmp += sprintf(topic, "demo/signed/");
    int i;
    for (i = 0; i < result_len; i++) {
        sprintf(tmp + (i*2), "%02x", hmac[i]);
    }
    i = mosquitto_publish(mosq, NULL, topic, strlen(data), (unsigned char*)data, 0, false);
    if (i != MOSQ_ERR_SUCCESS) {
        fatal("Failed to publish message: %d\n", i);
    }
    return 0;
}
Exemple #9
0
 void publish(std::string topic, std::string payload) {
     const int res = mosquitto_publish(this->connection, NULL,
                                       topic.c_str(), payload.size(), payload.c_str(), 0, false);
     if (res != MOSQ_ERR_SUCCESS) {
         //die("publish\n");
     }
 }
Exemple #10
0
/* Loop until it is explicitly halted or the network is lost, then clean up. */
static int run_loop(struct client_info *info) {
    int res = MOSQ_ERR_SUCCESS;
    int i = 0;
    char buf[1024];

    memset(buf, 0, sizeof(buf));
    do {
	res = mosquitto_loop(info->m, -1, 1 /* unused */);
	if (res != MOSQ_ERR_SUCCESS) break;
	sleep(5);
	memset(buf, 0, sizeof(buf));
	sprintf(buf, "test_msg#%d\n", i++);
	res = mosquitto_publish(info->m, &mid_sent, PUBLISH_TOPIC,
		      strlen(buf), buf, PUBLISH_MSG_QOS, 0);
    }while(res == MOSQ_ERR_SUCCESS && connected);

    mosquitto_destroy(info->m);
    (void)mosquitto_lib_cleanup();

    if (res == MOSQ_ERR_SUCCESS) {
        return 0;
    } else {
        return 1;
    }
}
Exemple #11
0
static
int
mosq_publish(lua_State *L)
{
	mosq_t *ctx = mosq_get(L, 1);
	int mid;	/* message id is referenced in the publish callback */
	const char *topic = luaL_checkstring(L, 2);
	size_t payloadlen = 0;
	const void *payload = NULL;

	if (!lua_isnil(L, 3)) {
		payload = lua_tolstring(L, 3, &payloadlen);
	};

	int qos = luaL_optinteger(L, 4, 0);
	bool retain = lua_toboolean(L, 5);

	int rc = mosquitto_publish(ctx->mosq, &mid, topic, payloadlen, payload, qos, retain);

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

	return make_int_result(L, true, mid);
}
Exemple #12
0
int MqttHal_Publish(char *macAddr, int cmdType, char *strName, char *strValue)
{
	int rc = MOSQ_ERR_SUCCESS;
	char topic[128];
	char message[1024];
	int msglen = 0;
	time_t currTime;
	//char seesionID[34];

	//printf("\033[33m %s(%d): cmdType=%d, strName=%s, strValue=%s \033[0m\n", __func__, __LINE__, cmdType, strName, strValue);
	#ifndef WIN32
	srandom(time(NULL));
	#endif
	memset(topic, 0, sizeof(topic));
	memset(message, 0, sizeof(message));
	memset(g_sessionID, 0, sizeof(g_sessionID));
	sprintf(g_sessionID, "99C21CCBBFE40F528C0EDDF9%08X", rand());
	switch(cmdType) {
		case Mote_Cmd_SetSensorValue:
			sprintf(message, SET_SENHUB_V_JSON, strValue, "SenData", strName, g_sessionID);
			break;
		case Mote_Cmd_SetMoteName:
			//sprintf(message, SET_SENHUB_SV_JSON, strValue, "Info", strName, g_sessionID);
			sprintf(message, SET_DEVNAME_JSON, g_sessionID, strValue);
			break;
		case Mote_Cmd_SetMoteReset:
			sprintf(message, SET_SENHUB_BV_JSON, strValue, "Info", strName, g_sessionID);
			break;
		case Mote_Cmd_SetAutoReport:
			sprintf(message, SET_SENHUB_BV_JSON, strValue, "Action", strName, g_sessionID);
			break;
		default:
			printf("%s: not support this cmd=%d!\n", __func__, cmdType);
			return -1;
	}
	
	//printf("\033[33m %s: %s \033[0m\n", __func__, message);
	sprintf(topic, "/cagent/admin/%s/%s", macAddr, WA_SUB_CBK_TOPIC);
	msglen = strlen(message);
	rc = mosquitto_publish(g_mosq, &g_mid_sent, topic, msglen, message, g_mosq_cfg.qos, g_mosq_cfg.retain);
	if(rc == MOSQ_ERR_SUCCESS) {
		time(&currTime);
		g_pubResp = 0;
		while(!g_pubResp) {
			//printf("%s: wait \n", __func__);
			if(isResponseTimeout(currTime)) {
				printf("%s: pub timeout!\n", __func__);
				break;
			}
		}
		//printf("\033[33m %s: got respone(%d) \033[0m\n", __func__, g_pubResp);
	}

	if(g_pubResp != SET_SUCCESS_CODE) {
		return -2;
	}

	return 0;
}
Exemple #13
0
static void raw_event(const char *data, int controllerId, int callbackId, void *context)
{
        struct context *ctx = context;
        struct relay_rule *relay_rules = ctx->relay_rules;
        if(ctx->debug>1)
                printf("raw_event: %s\n", data);

        struct telldus_data d;
        telldus_data_init(&d,data);
        int f = 0;
        for(f=0; f<ctx->num_relay_rules; f++) {
                int i = 0;
                int accepted = 1;
                // ensure all filters match in this relay_rule specification
                while(relay_rules[f].filters[i].key && relay_rules[f].filters[i].value && accepted) {
                        char expected[256];
                        telldus_data_get_value(expected, sizeof(expected)-1,
                                               relay_rules[f].filters[i].key, &d);
                        accepted &= !strcmp(expected, relay_rules[f].filters[i].value);
                        i++;
                }
                int j = 0;
                if(accepted) {
                        // matched, now format and deliver messages on all associated mqtt_templates
                        while(relay_rules[f].mqtt_template[j].topicformat &&
                              relay_rules[f].mqtt_template[j].messageformat &&
                                ! ctx->failures) {
                                char topic[1024];
                                char publish_topic[1024];
                                char message[256];
                                format_message(topic, sizeof(topic)-1,
                                               relay_rules[f].mqtt_template[j].topicformat, &d);
                                format_message(message, sizeof(topic)-1,
                                               relay_rules[f].mqtt_template[j].messageformat, &d);
                                snprintf(publish_topic,sizeof(publish_topic),
                                         "%s%s",ctx->pub_prefix,topic);
                                int rc2;
                                static int mid_sent = 0;
                                rc2 = mosquitto_publish(ctx->mosq,
                                                        &mid_sent,
                                                        publish_topic,
                                                        strlen(message),
                                                        (uint8_t *)message,
                                                        relay_rules[f].mqtt_template[j].qos,
                                                        relay_rules[f].mqtt_template[j].retain);
                                if(rc2) {
                                        fprintf(stderr, "Error: mosquitto_publish() returned %d: %s.\n", rc2, mosquitto_strerror(rc2));
// ignore failures for now, telldus callbacks can appear before MQTT connection is established
//                                        ctx->failures++;
                                }
                                if(ctx->debug>3)
                                        fprintf(stderr, "Done with template %d.\n", j);
                                j++;
                        }
                }
        }
        telldus_data_release(&d);

}
Exemple #14
0
void emit(char *jsonstring)
{
    if (config.emit_verbose)
    	printf("%s\n", jsonstring);

	mosquitto_publish(config.mosq, NULL, config.emit_topic,
		strlen(jsonstring), jsonstring, 0, false);
}
void on_connect(struct mosquitto *mosq, void *obj, int rc)
{
	if(rc){
		exit(1);
	}else{
		mosquitto_publish(mosq, &sent_mid, "psk/test", strlen("message"), "message", 0, false);
	}
}
Exemple #16
0
Fichier : test.c Projet : weikent/C
void *startech_write(void *arg){
  for(;;){
  printf("iiiiiiiiiiiiiiiiiiiiiiiiiiiiii\n" );
  int rc = mosquitto_publish(mosq, NULL, "isocketsTest/device/aaaaaa", 10, "uuuuuuuuuu", 0, false);
  printf("publish rc = %d\n", rc);
  sleep(20);
  }
}
Exemple #17
0
void my_publish(uint16_t id, double x, double y, double z)
{
	char buffer[100];
	
	sprintf(buffer, "ID:%d, XYZ: %f %f %f", id, x, y, z);
	
	mosquitto_publish(mosq_instance, (uint16_t *)0, "/beacon3", sizeof(buffer), (uint8_t *) buffer, 0, FALSE);
}
Exemple #18
0
int main(int argc, char *argv[])
{
	struct mosquitto *mosq;
	int i;
	double dstart, dstop, diff;
	FILE *fptr;
	uint8_t *buf;
	
	buf = malloc(MESSAGE_SIZE*MESSAGE_COUNT);
	if(!buf){
		printf("Error: Out of memory.\n");
		return 1;
	}

	start.tv_sec = 0;
	start.tv_usec = 0;
	stop.tv_sec = 0;
	stop.tv_usec = 0;

	if(create_data()){
		printf("Error: Unable to create random input data.\n");
		return 1;
	}
	fptr = fopen("msgsps_pub.dat", "rb");
	if(!fptr){
		printf("Error: Unable to open random input data.\n");
		return 1;
	}
	fread(buf, sizeof(uint8_t), MESSAGE_SIZE*MESSAGE_COUNT, fptr);
	fclose(fptr);

	mosquitto_lib_init();

	mosq = mosquitto_new("perftest", true, NULL);
	mosquitto_connect_callback_set(mosq, my_connect_callback);
	mosquitto_disconnect_callback_set(mosq, my_disconnect_callback);
	mosquitto_publish_callback_set(mosq, my_publish_callback);

	mosquitto_connect(mosq, "127.0.0.1", 1884, 600);

	i=0;
	while(!mosquitto_loop(mosq, 1, 10) && run){
		if(i<MESSAGE_COUNT){
			mosquitto_publish(mosq, NULL, "perf/test", MESSAGE_SIZE, &buf[i*MESSAGE_SIZE], 0, false);
			i++;
		}
	}
	dstart = (double)start.tv_sec*1.0e6 + (double)start.tv_usec;
	dstop = (double)stop.tv_sec*1.0e6 + (double)stop.tv_usec;
	diff = (dstop-dstart)/1.0e6;

	printf("Start: %g\nStop: %g\nDiff: %g\nMessages/s: %g\n", dstart, dstop, diff, (double)MESSAGE_COUNT/diff);

	mosquitto_destroy(mosq);
	mosquitto_lib_cleanup();

	return 0;
}
Exemple #19
0
void my_connect_callback(struct mosquitto *mosq, void *userdata, int result)
{
	int i;
	if(!result){
		mosquitto_publish(mosq, NULL, "hello/world", strlen(mqMsg), mqMsg, 2, 0);
	}else{
		fprintf(stderr, "Connect failed\n");
	}
}
Exemple #20
0
static void MQTTSendULong(struct mosquitto* _client, int node, int sensor, int var, unsigned long val) {
	char buff_topic[6];
	char buff_message[12];

	sprintf(buff_topic, "%02d%01d%01d", node, sensor, var);
	sprintf(buff_message, "%u", val);
//	LOG("%s %s", buff_topic, buff_message);
	mosquitto_publish(_client, 0, &buff_topic[0], strlen(buff_message), buff_message, 0, false);
	}
Exemple #21
0
void my_connect_callback(struct mosquitto *mosq, void *userdata, int result)
{
	if(!result){
		/* Subscribe to broker information topics on successful connect. */
		mosquitto_publish(mosq, NULL, "hello/world", strlen(mqMsg), mqMsg, 2, 0);
	}else{
		fprintf(stderr, "Connect failed\n");
	}
}
Exemple #22
0
static void MQTTSendFloat(struct mosquitto* _client, int node, int sensor, int var, float val) {
	char buff_topic[6];
	char buff_message[12];

	sprintf(buff_topic, "%02d%01d%01d", node, sensor, var);
	snprintf(buff_message, 12, "%f", val);
//	LOG("%s %s", buff_topic, buff_message);
	mosquitto_publish(_client, 0, buff_topic, strlen(buff_message), buff_message, 0, false);

	}
Exemple #23
0
int mqtt_publish(struct mosquitto *mosq, char *topic, char *payload)
{
	int rc;

	rc = mosquitto_publish(mosq, NULL, topic, strlen(payload), payload, config.mqtt_qos, false);
	if (rc) {
		fprintf(stderr, "Error: MQTT publish returned: %s\n", mosquitto_strerror(rc));
		return 0;
	}
	return 1;
}
Exemple #24
0
int mqtt_publish(mqtt_t inst, char* topic, char* payload) {
    int rval = 0;
    int qos = 0;
    bool retain = false;
    int mid = 0;

    if (inst->connected != 0) {
        rval = mosquitto_publish(inst->mosq, &mid, topic, (int)strlen(payload), payload, qos, retain);
        if (rval != MOSQ_ERR_SUCCESS) {
            error("Cannot publish: %s", mosquitto_strerror(rval));
        }
    }

    return rval;
}
Exemple #25
0
static void shift_pub(void)
{
	int len;
	char topic[CONFIG_STR_MAX];
	char data[CONFIG_STR_MAX];
	struct timeval t;

	if (gettimeofday(&t, NULL) != 0) {
		return;
	}	
	snprintf(topic, CONFIG_STR_MAX, SHIFT_TOPIC, conf.device);
	len = snprintf(data, CONFIG_STR_MAX, SHIFT_DATA_TPL, (int)t.tv_sec,
	               conf.port[0].shift, conf.port[1].shift, conf.port[2].shift);
	mosquitto_publish(conf.mosq, NULL, topic, len, data, conf.mqtt.qos,
	                  conf.mqtt.retain);
}
void MQTT_forwardMessage(uint8_t * msg, int size/*PUBLISH_MULTI_OR_MONO_DECLARATION*/) {
    int n, m, i;
    int length = size;
    unsigned char buf[(length * 3 + 1)];
    unsigned char *p = &buf[0];	
    unsigned char *q = p;
    n = 0;
    for(i = 0; i < length; i++) {
        n += sprintf((unsigned char *)q, "%03i", (unsigned char) msg[i]);
        n--;
        q += 3;
    }
    *q = '\0';
    n++;
    printf("[MQTT] Trying to send:\n%s \n", p);
    
    /*PUBLISH_MULTI_OR_MONO_CORE*/
    mosquitto_publish(MQTT_mosq, &MQTT_mid_sent, MQTT_topic, length * 3 + 1, p, MQTT_qos, MQTT_retain);
}
Exemple #27
0
void /*PORT_NAME*/_forwardMessage(uint8_t * msg, int size/*PUBLISH_MULTI_OR_MONO_DECLARATION*/) {
    int n, m, i;
    int length = size;
    unsigned char buf[(length * 3 + 1)];
    unsigned char *p = &buf[0];	
    unsigned char *q = p;
    n = 0;
    for(i = 0; i < length; i++) {
        n += sprintf((unsigned char *)q, "%03i", (unsigned char) msg[i]);
        n--;
        q += 3;
    }
    *q = '\0';
    n++;
    n++;
    /*TRACE_LEVEL_3*/printf("[/*PORT_NAME*/] publish:\"%s\"\n", p);
    
    /*PUBLISH_MULTI_OR_MONO_CORE*/
    mosquitto_publish(/*PORT_NAME*/_mosq, &/*PORT_NAME*/_mid_sent, /*PORT_NAME*/_topic, (length * 3 + 1), p, /*PORT_NAME*/_qos, /*PORT_NAME*/_retain);
}
bool MosquittoHandler::publish(const char *pubTopic, const char *text)
{
    std::string content(text);
    if (content.size() == 0)
    {
        content = "<NO CONTENT>";
    }
    //std::cout << "Publishing " << content << " to topic " << pubTopic << std::endl;

    uint16_t mid = 1;

    int errorNum = mosquitto_publish(m_mosquittoStruct, &mid, pubTopic, strlen(text), (const uint8_t*)text, 0, 0);

    if(errorNum != MOSQ_ERR_SUCCESS) {
        m_lastErrorString = errorByNum(errorNum);
        return false;
    }
    return true;

}
Exemple #29
0
    virtual void packetSent(const Message &m, const Component *sender, MicroFlo::PortId senderPort) {
        const MicroFlo::NodeId senderId = sender->id();
        //LOG("packet sent %d\n", senderId);

        const Port * port = findPortByEdge(options.info.outports, senderId, senderPort);
        if (port) {
            const char *outTopic = port->topic.c_str();

            const std::string data = encodePacket(m.pkg);
            const int res = mosquitto_publish(this->connection, NULL, outTopic,
                                              data.size(), data.c_str(), 0, false);
            LOG("sending on MQTT topic %s: %s\n", outTopic, data.c_str());

            if (res != MOSQ_ERR_SUCCESS) {
                //die("publish\n");
            }
        } else {
            LOG("no MQTT topic associated\n");
        }
    }
Exemple #30
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;
}