示例#1
0
bool MqttClient::subscribe(String topic)
{
	uint16_t msgId = 0;
	debugf("subscription '%s' registered", topic.c_str());
	int res = mqtt_subscribe(&broker, topic.c_str(), &msgId);
	return res > 0;
}
static int webapi_raw(uint32_t connid, uint32_t method, int argc, char **argv, const char *body, const char *reqpath, const char *uri_str, const char *auth)
{
    ebb_connection_info *conninfo;
    int mid;
    char *topic = NULL;

    if (NULL == (topic = strdup(reqpath)))
    {
        LOG_ERROR("out of mem");
        return 1;
    }

    if (NULL == (conninfo = httpd_get_conninfo(connid)))
    {
        LOG_ERROR("bad connid");
        free(topic);
        return 1;
    }

    if (method != EBB_GET)
    {
        conninfo->http_status = 405;    // method not allowed
        free(topic);
        return 1;
    }

    conninfo->rawmode = true;
    strcpy(conninfo->mimetype, "text/html");

    if (sublist_insert(topic))
    {
        if (mqtt_subscribe(&g_srvctx.mqttctx, topic, 2, &mid) != 0)
        {
            conninfo->http_status = 503;
            free(topic);
            return 1;
        }
        else
        {
            LOG_INFO("midconn_insert mid=%d conn=%d", mid, connid);
            conninfo->managed_str = topic;
            midconn_insert(mid, connid);
            conninfo->have_mid = true;
            conninfo->mid = mid;
            return 0;
        }
    }
    else
    {
        stream_t *stream;
        // we're already subscribed, so no need to send mqtt subscribe req
        stream = webapi_subscribe_response(conninfo, topic);
        // for everything in msgcache, if matches topic, inject into conn
        // FIXME, should walk topic tree
        msgcache_foreach(inject_retained, stream);
        free(topic);
        return 0;
    }
    return 1;
}
示例#3
0
int main (int argc, char** argv)
{
    puts("MQTT SUB Test Code");

    if(argc > 1) {
	parse_options(argc, argv);
    }

//  mqtt_broker_handle_t *broker = mqtt_connect("default_sub","127.0.0.1", 1883);
    mqtt_broker_handle_t *broker = mqtt_connect(client_name, ip_addr, port);

    if(broker == 0) {
        puts("Failed to connect");
        exit(1);
    }
  
    int result = mqtt_subscribe(broker, topic, QoS0);
    
    if(result != 1) {
        puts("failed to Subscribe");
        exit(1);
    }

    while(1)
    {
        mqtt_display_message(broker, &putchar);
    }
    return 0;
}
static int webapi_subscribe(uint32_t connid, uint32_t method, int argc, char **argv, const char *body, const char *reqpath, const char *uri_str, const char *auth)
{
    ebb_connection_info *conninfo;
    int mid;
    char *topic = NULL;

    if (NULL == (conninfo = httpd_get_conninfo(connid)))
    {
        LOG_ERROR("bad connid");
        return 1;
    }

    if (method != EBB_PUT && method != EBB_POST)
    {
        conninfo->http_status = 405;    // method not allowed
        return 1;
    }

    if (0 != json_fetch_key(body, &topic))
    {
        LOG_INFO("malformed sub %s", body);
        conninfo->http_status = 400;
        return 1;
    }

LOG_INFO("webapi_subscribe %s", topic);
accesslog_write("%s subscribe %s", conninfo->ipaddr, topic);
    if (sublist_insert(topic))
    {
        if (mqtt_subscribe(&g_srvctx.mqttctx, topic, 2, &mid) != 0)
        {
            conninfo->http_status = 503;
            free(topic);
            return 1;
        }
        else
        {
            LOG_INFO("midconn_insert mid=%d conn=%d", mid, connid);
            conninfo->managed_str = topic;
            midconn_insert(mid, connid);
            conninfo->have_mid = true;
            conninfo->mid = mid;
            return 0;
        }
    }
    else
    {
        stream_t *stream;
        // we're already subscribed, so no need to send mqtt subscribe req
        stream = webapi_subscribe_response(conninfo, topic);
        // for everything in msgcache, if matches topic, inject into conn
        // FIXME, should walk topic tree
        msgcache_foreach(inject_retained, stream);

        free(topic);
        return 0;
    }

    return 1;
}
示例#5
0
void itc_mqtt_subscribe_unsubscribe_p(void)
{
	int res;
	g_mqtt_client_handle = mqtt_init_client(&g_mqtt_client_config);
	TC_ASSERT_NEQ("mqtt_init_client", g_mqtt_client_handle, NULL);
	res = mqtt_connect(g_mqtt_client_handle, CONFIG_ITC_MQTT_BROKER_ADDR, CONFIG_ITC_MQTT_BROKER_PORT, 0);
	TC_ASSERT_EQ_CLEANUP("mqtt_connect", res, 0, mqtt_deinit_client(g_mqtt_client_handle));
	ITC_MQTT_WAIT_SIGNAL;

	res = mqtt_subscribe(g_mqtt_client_handle, ITC_MQTT_TOPIC, 0);
	TC_ASSERT_EQ_CLEANUP("mqtt_subscribe", res, 0,
		mqtt_disconnect(g_mqtt_client_handle); mqtt_deinit_client(g_mqtt_client_handle));

	res = mqtt_unsubscribe(g_mqtt_client_handle, ITC_MQTT_TOPIC);
	TC_ASSERT_EQ_CLEANUP("mqtt_unsubscribe", res, 0,
		mqtt_disconnect(g_mqtt_client_handle); mqtt_deinit_client(g_mqtt_client_handle));

	res = mqtt_disconnect(g_mqtt_client_handle);
	TC_ASSERT_EQ("mqtt_disconnect", res, 0);
	ITC_MQTT_WAIT_SIGNAL;

	res = mqtt_deinit_client(g_mqtt_client_handle);
	TC_ASSERT_EQ("mqtt_deinit_client", res, 0);
	TC_SUCCESS_RESULT();
}
示例#6
0
/**
 * \brief Callback to get the MQTT status update.
 *
 * \param[in] conn_id instance id of connection which is being used.
 * \param[in] type type of MQTT notification. Possible types are:
 *  - [MQTT_CALLBACK_SOCK_CONNECTED](@ref MQTT_CALLBACK_SOCK_CONNECTED)
 *  - [MQTT_CALLBACK_CONNECTED](@ref MQTT_CALLBACK_CONNECTED)
 *  - [MQTT_CALLBACK_PUBLISHED](@ref MQTT_CALLBACK_PUBLISHED)
 *  - [MQTT_CALLBACK_SUBSCRIBED](@ref MQTT_CALLBACK_SUBSCRIBED)
 *  - [MQTT_CALLBACK_UNSUBSCRIBED](@ref MQTT_CALLBACK_UNSUBSCRIBED)
 *  - [MQTT_CALLBACK_DISCONNECTED](@ref MQTT_CALLBACK_DISCONNECTED)
 *  - [MQTT_CALLBACK_RECV_PUBLISH](@ref MQTT_CALLBACK_RECV_PUBLISH)
 * \param[in] data A structure contains notification informations. @ref mqtt_data
 */
static void mqtt_callback(struct mqtt_module *module_inst, int type, union mqtt_data *data)
{
	switch (type) {
	case MQTT_CALLBACK_SOCK_CONNECTED:
	{
		/*
		 * If connecting to broker server is complete successfully, Start sending CONNECT message of MQTT.
		 * Or else retry to connect to broker server.
		 */
		if (data->sock_connected.result >= 0) {
			mqtt_connect_broker(module_inst, 1, NULL, NULL, mqtt_user, NULL, NULL, 0, 0, 0);
		} else {
			printf("Connect fail to server(%s)! retry it automatically.\r\n", main_mqtt_broker);
			mqtt_connect(module_inst, main_mqtt_broker); /* Retry that. */
		}
	}
	break;

	case MQTT_CALLBACK_CONNECTED:
		if (data->connected.result == MQTT_CONN_RESULT_ACCEPT) {
			/* Subscribe chat topic. */
			mqtt_subscribe(module_inst, MAIN_CHAT_TOPIC "#", 0);
			/* Enable USART receiving callback. */
			usart_enable_callback(&cdc_uart_module, USART_CALLBACK_BUFFER_RECEIVED);
			printf("Preparation of the chat has been completed.\r\n");
		} else {
			/* Cannot connect for some reason. */
			printf("MQTT broker decline your access! error code %d\r\n", data->connected.result);
		}

		break;

	case MQTT_CALLBACK_RECV_PUBLISH:
		/* You received publish message which you had subscribed. */
		if (data->recv_publish.topic != NULL && data->recv_publish.msg != NULL) {
			if (!strncmp(data->recv_publish.topic, MAIN_CHAT_TOPIC, strlen(MAIN_CHAT_TOPIC))) {
				/* Print user name and message */
				for (int i = strlen(MAIN_CHAT_TOPIC); i < data->recv_publish.topic_size; i++) {
					printf("%c", data->recv_publish.topic[i]);
				}
				printf(" >> ");
				for (int i = 0; i < data->recv_publish.msg_size; i++) {
					printf("%c", data->recv_publish.msg[i]);
				}
				printf("\r\n");
			}
		}

		break;

	case MQTT_CALLBACK_DISCONNECTED:
		/* Stop timer and USART callback. */
		printf("MQTT disconnected\r\n");
		usart_disable_callback(&cdc_uart_module, USART_CALLBACK_BUFFER_RECEIVED);
		break;
	}
}
示例#7
0
/*******************************************************
 *
 * 返回成功订阅Topic的个数
 *
 ********************************************************/
int32 Mqtt_SubLoginTopic( mqtt_broker_handle_t *LoginBroker,pgcontext pgc,int16 mqttstatus )
{
    char Sub_TopicBuf[100];
    char Topic[100];

    memset(Sub_TopicBuf,0,100);
    memset(Topic,0,100);
    
    switch(mqttstatus)
    {
    case MQTT_STATUS_REQ_LOGINTOPIC1:
        init_subTopic(LoginBroker,pgc,Sub_TopicBuf,1);
        if(mqtt_subscribe( LoginBroker,Sub_TopicBuf,&(pgc->rtinfo.waninfo.mqttMsgsubid) )==1)
        {   
            sprintf(Topic,"LOGIN sub topic1 is:%s",Sub_TopicBuf);
            GAgent_Printf(GAGENT_INFO,Topic);
            GAgent_Printf(GAGENT_INFO,"MQTT_STATUS_LOGINTOPIC1");
        }
        break;            
    case MQTT_STATUS_REQ_LOGINTOPIC2:
        init_subTopic(LoginBroker,pgc,Sub_TopicBuf,2);
        if(mqtt_subscribe( LoginBroker,Sub_TopicBuf,&(pgc->rtinfo.waninfo.mqttMsgsubid) )==1)
        {    
            sprintf(Topic,"LOGIN T2 sub topic is:%s",Sub_TopicBuf);                                
            GAgent_Printf(GAGENT_INFO,Topic);
            GAgent_Printf(GAGENT_INFO,"MQTT_STATUS_LOGINTOPIC2");
        }
        break;
    case MQTT_STATUS_REQ_LOGINTOPIC3:
        init_subTopic(LoginBroker,pgc,Sub_TopicBuf,3);
        if(mqtt_subscribe( LoginBroker,Sub_TopicBuf,&(pgc->rtinfo.waninfo.mqttMsgsubid) )==1)
        {
            sprintf(Topic,"LOGIN T3 sub topic is:%s",Sub_TopicBuf);
            GAgent_Printf(GAGENT_INFO,Topic);
            GAgent_Printf(GAGENT_INFO,"MQTT_STATUS_LOGINTOPIC3");
        }
        break;
    default:
        break;
    }

    return 0;
}
示例#8
0
/*---------------------------------------------------------------------------*/
static void
subscribe(void)
{
    /* Publish MQTT topic in IBM quickstart format */
    mqtt_status_t status;

    status = mqtt_subscribe(&conn, NULL, sub_topic, MQTT_QOS_LEVEL_0);

    DBG("APP - Subscribing!\n");
    if(status == MQTT_STATUS_OUT_QUEUE_FULL) {
        DBG("APP - Tried to subscribe but command queue was full!\n");
    }
}
示例#9
0
/****************************************************************************
 * Static Functions
 ****************************************************************************/
static void my_connect_callback(void *client, int result)
{
	mqtt_client_t *mqtt_client = (mqtt_client_t *)client;
	mqtt_msg_t *mqtt_msg = NULL;

	if (mqtt_client == NULL || mqtt_client->config == NULL) {
		fprintf(stderr, "Error: >>> connect callback: %s is NULL.\n", mqtt_client == NULL ? "mqtt_client" : "mqtt_client->config");
		return;
	}

	if (result == MQTT_CONN_ACCEPTED) {

		MQTT_SUB_DEBUG_PRINT(mqtt_client, ">>> connect callback: client_id=%s, connect success!\n", mqtt_client->config->client_id);

		if (mqtt_client->config->user_data) {
			mqtt_msg = (mqtt_msg_t *)mqtt_client->config->user_data;
			if (mqtt_subscribe(mqtt_client, mqtt_msg->topic, mqtt_msg->qos) != 0) {
				fprintf(stderr, "Error: mqtt_subscribe() failed.\n");
			}
		} else {
			fprintf(stderr, "Error: mqtt_client is NULL.\n");
		}
	} else {
		char reason_str[40];
		switch (result) {
		case MQTT_CONN_REFUSED_UNACCEPTABLE_PROTOCOL_VER:
			snprintf(reason_str, sizeof(reason_str), "unacceptable protocol version");
			break;
		case MQTT_CONN_REFUSED_ID_REJECTED:
			snprintf(reason_str, sizeof(reason_str), "identifier rejected");
			break;
		case MQTT_CONN_REFUSED_BAD_USER_NAME_OR_PASSWORD:
			snprintf(reason_str, sizeof(reason_str), "bad user name or password");
			break;
		case MQTT_CONN_REFUSED_NOT_AUTHORIZED:
			snprintf(reason_str, sizeof(reason_str), "not authorized");
			break;
		default:
			snprintf(reason_str, sizeof(reason_str), "unknown");
			break;
		}

		MQTT_SUB_DEBUG_PRINT(mqtt_client, ">>> connect callback: client_id=%s, connect failed (reason: %s)\n", mqtt_client->config->client_id, reason_str);
	}
}
示例#10
0
/*
 * Subscribe the topic: IOT_MQTT_Subscribe(pclient, TOPIC_DATA, IOTX_MQTT_QOS1, _demo_message_arrive, NULL);
 * Publish the topic: IOT_MQTT_Publish(pclient, TOPIC_DATA, &topic_msg);
 */
static void mqtt_work(void *parms)
{

    int rc = -1;

    if (is_subscribed == 0) {
        /* Subscribe the specific topic */
        rc = mqtt_subscribe(TOPIC_GET, mqtt_sub_callback, NULL);
        if (rc < 0) {
            // IOT_MQTT_Destroy(&pclient);
            LOG("IOT_MQTT_Subscribe() failed, rc = %d", rc);
        }
        is_subscribed = 1;
        aos_schedule_call(ota_init, NULL);
    }
#ifndef MQTT_PRESS_TEST
    else {
        /* Generate topic message */
        int msg_len = snprintf(msg_pub, sizeof(msg_pub), "{\"attr_name\":\"temperature\", \"attr_value\":\"%d\"}", cnt);
        if (msg_len < 0) {
            LOG("Error occur! Exit program");
        }
        rc = mqtt_publish(TOPIC_UPDATE, IOTX_MQTT_QOS1, msg_pub, msg_len);
        if (rc < 0) {
            LOG("error occur when publish");
        }

        LOG("packet-id=%u, publish topic msg=%s", (uint32_t)rc, msg_pub);
    }
    cnt++;
    if (cnt < 200) {
        aos_post_delayed_action(3000, mqtt_work, NULL);
    } else {
        aos_cancel_delayed_action(3000, mqtt_work, NULL);
        mqtt_unsubscribe(TOPIC_GET);
        aos_msleep(200);
        mqtt_deinit_instance();
        is_subscribed = 0;
        cnt = 0;
    }
#endif
}
示例#11
0
/* USER CODE BEGIN 0 */
static void mqtt_connection_cb(mqtt_client_t *client, void *arg, mqtt_connection_status_t status)
{
  err_t err;
  if(status == MQTT_CONNECT_ACCEPTED) {
    printf("mqtt_connection_cb: Successfully connected\n");

    /* Setup callback for incoming publish requests */
    mqtt_set_inpub_callback(client, mqtt_incoming_publish_cb, mqtt_incoming_data_cb, arg);

    /* Subscribe to a topic named "subtopic" with QoS level 1, call mqtt_sub_request_cb with result */
    err = mqtt_subscribe(client, "subtopic", 1, mqtt_sub_request_cb, arg);

    if(err != ERR_OK) {
      printf("mqtt_subscribe return: %d\n", err);
    }
  } else {
    printf("mqtt_connection_cb: Disconnected, reason: %d\n", status);

}
}
/*                            Functions                        */
void  lcfu___MQTT_SUBSCRIBE(LC_TD_Function_MQTT_SUBSCRIBE* LC_this, LcCgChar LC_VD_TOPIC[65], struct _lcoplck_epdb_1_impl* pEPDB)
{
  /* mqtt_rc mqtt_subscribe(const char* topic); */
	LC_this->LC_VD_ENO = mqtt_subscribe(LC_VD_TOPIC) == MQTT_RC_OK ? LC_EL_true : LC_EL_false;
}
示例#13
0
/**
 * Main routine
 *
 */
int main()
{
	int packet_length;
	uint16_t msg_id, msg_id_rcv;

	mqtt_init(&broker, "client-id");
	//mqtt_init_auth(&broker, "quijote", "rocinante");
	init_socket(&broker, "107.22.188.194", 1883, keepalive);

	// >>>>> CONNECT
	mqtt_connect(&broker);
	// <<<<< CONNACK
	packet_length = read_packet(1);
	if(packet_length < 0)
	{
		fprintf(stderr, "Error(%d) on read packet!\n", packet_length);
		return -1;
	}

	if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_CONNACK)
	{
		fprintf(stderr, "CONNACK expected!\n");
		return -2;
	}

	if(packet_buffer[3] != 0x00)
	{
		fprintf(stderr, "CONNACK failed!\n");
		return -2;
	}

	// Signals after connect MQTT
	signal(SIGALRM, alive);
	alarm(keepalive);
	signal(SIGINT, term);

	// >>>>> SUBSCRIBE
	mqtt_subscribe(&broker, "public/test/topic", &msg_id);
	// <<<<< SUBACK
	packet_length = read_packet(1);
	if(packet_length < 0)
	{
		fprintf(stderr, "Error(%d) on read packet!\n", packet_length);
		return -1;
	}

	if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_SUBACK)
	{
		fprintf(stderr, "SUBACK expected!\n");
		return -2;
	}

	msg_id_rcv = mqtt_parse_msg_id(packet_buffer);
	if(msg_id != msg_id_rcv)
	{
		fprintf(stderr, "%d message id was expected, but %d message id was found!\n", msg_id, msg_id_rcv);
		return -3;
	}

	while(1)
	{
		// <<<<<
		packet_length = read_packet(0);
		if(packet_length == -1)
		{
			fprintf(stderr, "Error(%d) on read packet!\n", packet_length);
			return -1;
		}
		else if(packet_length > 0)
		{
			printf("Packet Header: 0x%x...\n", packet_buffer[0]);
			if(MQTTParseMessageType(packet_buffer) == MQTT_MSG_PUBLISH)
			{
				uint8_t topic[255], msg[1000];
				uint16_t len;
				len = mqtt_parse_pub_topic(packet_buffer, topic);
				topic[len] = '\0'; // for printf
				len = mqtt_parse_publish_msg(packet_buffer, msg);
				msg[len] = '\0'; // for printf
				printf("%s %s\n", topic, msg);
			}
		}

	}
	return 0;
}
void *listener_thread(void *threadId)
{
    int packet_length;
	uint16_t msg_id, msg_id_rcv;
	int error = 0;

	printf("Starting listener thread...\n");

    // >>>>> SUBSCRIBE
	mqtt_subscribe(&broker, "yefsec0rk7uhatp/HighTemp", &msg_id);
	// <<<<< SUBACK
	packet_length = read_packet(1);
	if(packet_length < 0)
	{
		fprintf(stderr, "Error(%d) on read packet!\n", packet_length);
		error = 1;
	}

	//printf("%s", packet_buffer);

	if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_SUBACK)
	{
		fprintf(stderr, "SUBACK expected!\n");
		error = 1;
	}

	//printf("%s", packet_buffer);

	msg_id_rcv = mqtt_parse_msg_id(packet_buffer);
	if(msg_id != msg_id_rcv)
	{
		fprintf(stderr, "%d message id was expected, but %d message id was found!\n", msg_id, msg_id_rcv);
		error = 1;
	}

	//printf("%s", packet_buffer);

	if (error)
    {
        printf("error setting up listener socket\n");
    }

	while(1)
	{
	    printf("Waiting for message...\n");

		packet_length = read_packet(0);
		if(packet_length == -1)
		{
			fprintf(stderr, "Error(%d) on read packet!\n", packet_length);
			break;
		}
		else if(packet_length > 0)
		{
			printf("Packet Header: 0x%x...\n", packet_buffer[0]);
			if(MQTTParseMessageType(packet_buffer) == MQTT_MSG_PUBLISH)
			{
				uint8_t topic[255], msg[1000];
				uint16_t len;

				led("g1", 1);

				len = mqtt_parse_pub_topic(packet_buffer, topic);
				topic[len] = '\0'; // for printf
				len = mqtt_parse_publish_msg(packet_buffer, msg);
				msg[len] = '\0'; // for printf
				printf("%s %s\n", topic, msg);

				sleep(1);

				led("g1", 0);
			}
			else if (MQTTParseMessageType(packet_buffer) == MQTT_MSG_PINGRESP)
            {
                printf("Ping response received\n");
            }
		}

	}

	pthread_exit(NULL);
}
static void *mqtt_sub_thread(void *param)
{
    MQTTPacket_connectData condata = MQTTPacket_connectData_initializer;
    int pktype, rc, len;
    int failcnt = 0;
    unsigned char wbuf[64];
    unsigned char rbuf[64];

    DEBUG("sub thread start\n");

    _csub.wbuf = wbuf;
    _csub.wbuflen = sizeof(wbuf);
    _csub.rbuf = rbuf;
    _csub.rbuflen = sizeof(rbuf);
    _csub.getfn = sub_read;

    if ((_csub.sockfd = mqtt_netconnect(HOSTNAME, HOSTPORT)) < 0)
    {
        DEBUG("sub netconnect fail\n");

        return 0;
    }

    DEBUG("sub connect to: %s %d\n", HOSTNAME, HOSTPORT);

    condata.clientID.cstring = "mqttsub";
    condata.keepAliveInterval = KEEPALIVE_INTERVAL;
    condata.cleansession = 1;
    condata.username.cstring = USERNAME;
    condata.password.cstring = PASSWORD;

    rc = mqtt_connect(&_csub, &condata);
    if (rc < 0)
        goto exit;

    DEBUG("sub connect ok\n");

    rc = mqtt_subscribe(&_csub, TOPIC, 0);
    if (rc < 0)
        goto exit;

    DEBUG("sub topic: %s\n", TOPIC);

    mqtt_ping_start(&_csub.sockfd);

    while (1)
    {
        pktype = MQTTPacket_read(_csub.rbuf, _csub.rbuflen, sub_read);

        switch (pktype)
        {
        case CONNACK:
        case PUBACK:
        case SUBACK:
            break;
        case PUBLISH:
        {
            MQTTString topic;
            mqtt_msg_t msg;

            if (MQTTDeserialize_publish(&msg.dup, &msg.qos, &msg.retained, &msg.id, &topic,
                                                         &msg.payload, &msg.payloadlen, _csub.rbuf, _csub.rbuflen) != 1)
                goto exit;

            msgprocess(&topic, &msg);

            if (msg.qos != 0)
            {
                if (msg.qos == 1)
                    len = MQTTSerialize_ack(_csub.wbuf, _csub.wbuflen, PUBACK, 0, msg.id);
                else if (msg.qos == 2)
                    len = MQTTSerialize_ack(_csub.wbuf, _csub.wbuflen, PUBREC, 0, msg.id);

                if (len <= 0)
                    rc = -1;
                else
                    rc = mqtt_write(_csub.sockfd, _csub.wbuf, len);

                if (rc == -1)
                    goto exit;
            }
        }
        break;
        case PUBCOMP:
            break;
        case PINGRESP:
            failcnt = 0;
            break;
        case -1:
            if (++failcnt > KEEPALIVE_INTERVAL)
            {
                /*  */
                goto exit;
            }
            break;
        }
    }
    /*  */
    mqtt_disconnect(&_csub);

exit:
    mqtt_netdisconnect(&_csub.sockfd);
    DEBUG("sub thread exit\n");

    return 0;
}
示例#16
0
void mqttSub(uint8_t qos)
{
	mqtt_subscribe(&myClient, "matt/pizza", qos);
}
示例#17
0
void app_parse_mqttmsg(uint8_t *packet_buffer)
{
	uint8_t msg_type = 0;
	uint16_t msg_id_rcv = 0;
	char topic_name[56]={0};
	char msg[128]={0};
			
	msg_type = MQTTParseMessageType(packet_buffer);
	//printf("-----> parse:0x%02X\n", msg_type);
	switch(msg_type)
	{
		case MQTT_MSG_CONNACK:
			if(packet_buffer[3] == 0)
			{
				printf("Mqtt login server success\n");

				/* subscribe  */
				init_topic(&g_sub_topic, sub_topic_name, sizeof(sub_topic_name));
				mqtt_subscribe(&g_stMQTTBroker, g_sub_topic->name, &(g_sub_topic->msg_id));

				/* publish msg with Qos 0 */
				//step1:>>>publish               
				init_topic(&g_pub_topic1, pub_topic_name1, sizeof(pub_topic_name1));
				mqtt_publish(&g_stMQTTBroker, g_pub_topic1->name, pub_msg1, 0);

				printf("APP publish msg[%s] with Qos 0\n", pub_msg1);
				deinit_topic(&g_pub_topic1);
				
				/* publish msg with Qos 1 */
				//step1:>>>publish
				//step2:<<<puback
				init_topic(&g_pub_topic2, pub_topic_name2, sizeof(pub_topic_name2));
				mqtt_publish_with_qos(&g_stMQTTBroker, g_pub_topic2->name, pub_msg2, 0, 1, &(g_pub_topic2->msg_id));

			}
			else
				printf("Mqtt login server fail!\n");
			break;

		case MQTT_MSG_SUBACK:
			msg_id_rcv = mqtt_parse_msg_id(packet_buffer);
			if(g_sub_topic && msg_id_rcv == g_sub_topic->msg_id)
				printf("Subcribe topic[%s] success\n", g_sub_topic->name);
			break;

		case MQTT_MSG_PUBLISH:
			mqtt_parse_pub_topic(packet_buffer, topic_name);	
			mqtt_parse_publish_msg(packet_buffer, msg);
			printf("****** Topic[%s] recv msg: *****\n%s\n",topic_name, msg);

			/* unsubscribe */
			if(!strcmp(g_sub_topic->name, topic_name))
				mqtt_unsubscribe(&g_stMQTTBroker, g_sub_topic->name, &(g_sub_topic->msg_id));
			
			break;

		case MQTT_MSG_UNSUBACK:
			msg_id_rcv = mqtt_parse_msg_id(packet_buffer);
			if(g_sub_topic && msg_id_rcv == g_sub_topic->msg_id)
			{
				printf("Unsubcribe topic[%s] success\n", g_sub_topic->name);
				deinit_topic(&g_sub_topic);
			}
			break;	

		case MQTT_MSG_PUBACK://Qos1
			msg_id_rcv = mqtt_parse_msg_id(packet_buffer);
			if(g_pub_topic2 && msg_id_rcv == g_pub_topic2->msg_id)
			{
				printf("APP publish msg[%s] with Qos 1\n", pub_msg2);
				deinit_topic(&g_pub_topic2);

				/* publish msg with Qos 2 */
				//step1:>>>publish
				//step2:<<<pubrec
				//step3:>>>pubrel
				//step4:<<<pubcomp
				init_topic(&g_pub_topic3, pub_topic_name3, sizeof(pub_topic_name3));
				mqtt_publish_with_qos(&g_stMQTTBroker, g_pub_topic3->name, pub_msg3, 1, 2, &(g_pub_topic3->msg_id));
			}
			break;

		case MQTT_MSG_PUBREC://Qos2
			msg_id_rcv = mqtt_parse_msg_id(packet_buffer);
			if(g_pub_topic3 && msg_id_rcv == g_pub_topic3->msg_id)
				mqtt_pubrel(&g_stMQTTBroker, g_pub_topic3->msg_id);
			break;

		case MQTT_MSG_PUBCOMP://Qos2
			msg_id_rcv = mqtt_parse_msg_id(packet_buffer);
			if(g_pub_topic3 && msg_id_rcv == g_pub_topic3->msg_id)
			{
				printf("APP publish msg[%s] with Qos 2\n", pub_msg3);
				deinit_topic(&g_pub_topic3);
			}	
			break;

		default:
			printf("Unknow mqtt msg type\n");
			break;
	}
		
}
static void mqtt_callback(struct mqtt_module *module_inst, int type, union mqtt_data *data)
{
	printf("MQTT CALLBACK ENTER"DEBUG_EOL);
	switch (type) {
	case MQTT_CALLBACK_SOCK_CONNECTED:
	{
		printf("MQTT SOCK CONNECTED"DEBUG_EOL);
		/*
		 * If connecting to broker server is complete successfully, Start sending CONNECT message of MQTT.
		 * Or else retry to connect to broker server.
		 */
		if (data->sock_connected.result >= 0) {
			printf("mqtt connect broker"DEBUG_EOL);
		    printf("socket %i", data->sock_connected.result);		
			int response = mqtt_connect_broker(module_inst, 1, NULL, NULL, gau0TheThingsIOHttpSubsURL, NULL, NULL, 0, 0, 0);
			// int response = mqtt_connect_broker(module_inst, 1, "1", "test", NULL, NULL, NULL, 0, 0, 0);
			printf("response %s %i"DEBUG_EOL,gau0TheThingsIOHttpSubsURL, response);
		} else {
			printf("Connect fail to server(%s)! retry it automatically.\r\n", main_mqtt_broker);
			mqtt_connect(module_inst, main_mqtt_broker); /* Retry that. */
		}
	}
	break;

	case MQTT_CALLBACK_CONNECTED:
		if (data->connected.result == MQTT_CONN_RESULT_ACCEPT) {
			/* Subscribe chat topic. */
			/* the subscribe topic in the subscribe endpoint */
			printf("subscribe topic %s"DEBUG_EOL, gau0TheThingsIOHttpSubsURL);
			mqtt_subscribe(module_inst, gau0TheThingsIOHttpSubsURL, 0);
			/* Enable USART receiving callback. */
			
			// TODO we have mqtt connection
			//usart_enable_callback(&cdc_uart_module, USART_CALLBACK_BUFFER_RECEIVED);
			printf("Preparation of the chat has been completed.\r\n");
		} else {
			/* Cannot connect for some reason. */
			printf("MQTT broker decline your access! error code %d\r\n", data->connected.result);
		}

		break;

	case MQTT_CALLBACK_RECV_PUBLISH:
	
		printf("--- start receiving MQTT subscribe data ---"DEBUG_EOL);
		/* You received publish message which you had subscribed. */
		if (data->recv_publish.topic != NULL && data->recv_publish.msg != NULL) {
				char message[data->recv_publish.msg_size];
				for (int i = 0; i < data->recv_publish.msg_size; i++) {
				//	printf("%c", data->recv_publish.msg[i]);
					message[i] = data->recv_publish.msg[i];
				}
				
				//message[data->recv_publish.msg_size +] = '\0';
				if (subscribe_cb)
				{
					subscribe_cb(&message);
				}
				
		printf(DEBUG_EOL);				
		printf("--- end receiving MQTT subscribe data ---"DEBUG_EOL);
			/* printf("%c", data->recv_publish.topic[i]);
				printf("\r\n");
			if (!strncmp(data->recv_publish.topic, MAIN_CHAT_TOPIC, strlen(MAIN_CHAT_TOPIC))) {
				///* Print user name and message
				for (int i = strlen(MAIN_CHAT_TOPIC); i < data->recv_publish.topic_size; i++) {
					printf("%c", data->recv_publish.topic[i]);
				}
				printf(" >> ");
				for (int i = 0; i < data->recv_publish.msg_size; i++) {
					printf("%c", data->recv_publish.msg[i]);
				}
				
			} */
		}

		break;

	case MQTT_CALLBACK_DISCONNECTED:
		/* Stop timer and USART callback. */		
		//DBG_LOG("\r\nMQTT disconnected :");
		//DBG_LOG_DEV("length of the data is %d",len);
		if (gboolAlwaysMQTTConnected)
		{	
			mqtt_connect(module_inst, main_mqtt_broker);
		}
		
		// TODO we don't have mqtt connection
		//usart_disable_callback(&cdc_uart_module, USART_CALLBACK_BUFFER_RECEIVED);
		break;
	}
}
示例#19
0
/* Implementation of the client process */
PROCESS_THREAD(rako_bridge_process, ev, data)
{
  static uint8_t in_buffer[64];
  static uint8_t out_buffer[64];
  static char topic[64];
  static uip_ip6addr_t* address;
  static mqtt_connect_info_t connect_info = 
  {
    .client_id = "contiki",
    .username = NULL,
    .password = NULL,
    .will_topic = NULL,
    .will_message = NULL,
    .keepalive = 60,
    .will_qos = 0,
    .will_retain = 0,
    .clean_session = 1,
  };

  PROCESS_BEGIN();
    
  PRINTF("Myha started\n");

  if(ev == PROCESS_EVENT_INIT)
  {
    address = myha_get_mqtt_address();

    rako_init();

    mqtt_init(in_buffer, sizeof(in_buffer), out_buffer, sizeof(out_buffer));
    mqtt_connect(address, UIP_HTONS(1883), 1, &connect_info);
  }

  for(;;)
  {
    PROCESS_WAIT_EVENT();

    if(ev == PROCESS_EVENT_EXIT)
    {
      mqtt_disconnect();
    }
    else if(ev == mqtt_event)
    {
      if(mqtt_event_is_connected(data))
      {
        PRINTF("Myha: MQTT connected\n");

        sprintf_P(topic, PSTR("%s/name"), myha_get_node_id());
        mqtt_publish(topic, "Rako Bridge", 0, 0);
        PROCESS_WAIT_EVENT_UNTIL(ev == mqtt_event);

        sprintf_P(topic, PSTR("%s/+/set/+"), myha_get_node_id());

        PRINTF("Myha: subscribing: %s...\n", topic);
        mqtt_subscribe(topic);
        PROCESS_WAIT_EVENT_UNTIL(ev == mqtt_event);
        PRINTF("    done.\n");
      }
      else if(mqtt_event_is_disconnected(data))
      {
        PRINTF("Myha: MQTT disconnected\n");
      }
      else if(mqtt_event_is_publish(data))
      {
        int house, room, channel;
        char* name;
        const char* topic = mqtt_event_get_topic(data);
        const char* message = mqtt_event_get_data(data);

        PRINTF("Myha: got publish: %s = %s\n", topic, message);
        if(split_set_topic(topic, &house, &room, &channel, &name) == 0)
        {
          if(strcmp_P(name, PSTR("set/level")) == 0)
          {
            int level = atoi(message);
            rako_send_level(house, room, channel, level);

            PRINTF("Myha: sending level: %u\n", level);
            PROCESS_WAIT_EVENT_UNTIL(ev == rako_sent_event);
            PRINTF("Myha: done\n");
          }
          else if(strcmp_P(name, PSTR("set/scene")) == 0)
          {
            int scene = atoi(message);
            if(scene == 0)
              rako_send_off(house, room, channel);
            else
              rako_send_scene(house, room, channel, scene);

            PRINTF("Myha: sending rako scene command, house: %u, room: %u, channel: %u\n", house, room, channel);
            PROCESS_WAIT_EVENT_UNTIL(ev == rako_sent_event);
            PRINTF("Myha: done\n");
          }
          else
            PRINTF("Myha: not level: %s\n", name);
        }
        else
          PRINTF("Myha: split failed\n");
      }
    }
    else if(ev == rako_cmd_event)
    {
      rako_cmd_t* cmd = (rako_cmd_t*)data;
      
      if(cmd->command == RAKO_CMD_SCENE_SET)
      {
        char message[4];
        get_device_topic(topic, cmd->house, cmd->room, 0, "scene");
        sprintf(message, "%u", cmd->data);
        mqtt_publish(topic, message, 0, 0);
      }
      else if(cmd->command == RAKO_CMD_OFF)
      {
        get_device_topic(topic, cmd->house, cmd->room, 0, "scene");
        mqtt_publish(topic, "0", 0, 0);
      }
    }
    else if(ev == rako_recv_event)
    {
      rako_msg_t* msg = (rako_msg_t*)data;
      PRINTF("RAKO: received: raw: %08lx, house: %u, room: %u\n", msg->raw, msg->command.house, msg->command.room);
    }
    else if(ev == rako_sent_event)
    {
      PRINTF("RAKO: sent\n");
    }
  }

  PROCESS_END();
}
示例#20
0
/**
 * Main routine
 *
 */
static int mqtt_sub(void)
{
	int packet_length,socket_id;
	uint16_t msg_id, msg_id_rcv;
        mqtt_broker_handle_t broker;
        
        packet_buffer.len=BUFSIZE;
        broker.socket_info = (void *)&socket_id;
        

	mqtt_init(&broker, "MQTT_SUB");
	//mqtt_init_auth(&broker, "quijote", "rocinante");
	socket_id = init_socket(&broker);

	// >>>>> CONNECT
	mqtt_connect(&broker);
	// <<<<< CONNACK
        
       // unsigned long pubTaskHandle= getTaskHandle(SUB_TASKID);
       // vTaskPrioritySet( (xTaskHandle)&pubTaskHandle, PUB_TASK_PRIORITY);                   //to degrade sub_task priority to let it as the same of pub_task

      
        
	packet_length = read_packet(1,socket_id,(Tranmit_t *)&packet_buffer);
	if(packet_length < 0)
	{
		UART_PRINT("Error(%d) on read packet!\n\r");
		return -1;
	}

	if(MQTTParseMessageType(packet_buffer.buffer) != MQTT_MSG_CONNACK)
	{
		UART_PRINT("CONNACK expected!\n\r");
		return -2;
	}

	if(packet_buffer.buffer[3] != 0x00)
	{
		UART_PRINT("CONNACK failed!\n\r");
		return -2;
	}
        
        
        
        UART_PRINT("Connected to broker!\n\r");
        
        
        
                if(OSI_OK != osi_TaskCreate( taskPub,
    				(const signed char*)"taskPub",
    				2048, NULL, PUB_TASK_PRIORITY, (OsiTaskHandle)&pubTaskHandle ))
      UART_PRINT("taskPub failed\n\r");

	// Signals after connect MQTT
	//signal(SIGALRM, alive);
	//alarm(keepalive);
	//signal(SIGINT, term);

	// >>>>> SUBSCRIBE
	mqtt_subscribe(&broker, "helloword", &msg_id);
	// <<<<< SUBACK
	packet_length = read_packet(1,socket_id,(Tranmit_t *)&packet_buffer);
	if(packet_length < 0)
	{
		UART_PRINT("Error(%d) on read packet!\n\r");
		return -1;
	}

	if(MQTTParseMessageType(packet_buffer.buffer) != MQTT_MSG_SUBACK)
	{
		UART_PRINT("SUBACK expected!\n\r");
		return -2;
	}

	msg_id_rcv = mqtt_parse_msg_id(packet_buffer.buffer);
	if(msg_id != msg_id_rcv)
	{
		UART_PRINT("%d message id was expected, but %d message id was found!\n\r");
		return -3;
	}

	while(1)
	{
		// <<<<<
		packet_length = read_packet(0,socket_id,(Tranmit_t *)&packet_buffer);
		if(packet_length == -1)
		{
			UART_PRINT("Error(%d) on read packet!\n\r");
			return -1;
		}
		else if(packet_length > 0)
		{
			UART_PRINT("Packet Header: 0x%x...\n\r");
			if(MQTTParseMessageType(packet_buffer.buffer) == MQTT_MSG_PUBLISH)
			{
				uint8_t topic[TOPIC_LEN_MAX], msg[MSG_LEN_MAX];
				uint16_t len;
				len = mqtt_parse_pub_topic(packet_buffer.buffer, topic);
				topic[len] = '\0'; // for printf
				len = mqtt_parse_publish_msg(packet_buffer.buffer, msg);
				msg[len] = '\0'; // for printf
				//UART_PRINT("%s %s\n\r", topic, msg);
                                UART_PRINT(topic);
                                UART_PRINT("\n\r");
                                UART_PRINT(msg);
                                UART_PRINT("\n\r");
			}
		}

	}
	return 0;
}
示例#21
0
static int check_option_on_client_running(void)
{
	int result = CHECK_OPTION_RESULT_CHECKED_ERROR;

	if (!g_mqtt_client_handle) {
		if (g_stop || g_sub_topic || g_unsub_topic) {
			printf("Error: MQTT client is not running.\n");
			goto done;
		}

		result = CHECK_OPTION_RESULT_NOTHING_TODO;
		goto done;
	}

	if (g_mqtt_client_handle && !(g_stop || g_sub_topic || g_unsub_topic)) {
		printf("Error: MQTT client is running. You have to stop the mqtt subscriber with --stop\n");
		printf("      in order to start new mqtt subscriber.\n");
		goto done;
	}

	if (g_stop) {
		int disconnect_try_count = 20;

		MQTT_SUB_DEBUG_PRINT(g_mqtt_client_handle, "disconnect from a MQTT broker before stopping MQTT client.\n");
		while ((mqtt_disconnect(g_mqtt_client_handle) != 0) && disconnect_try_count) {
			disconnect_try_count--;
			usleep(500 * 1000);
		}
		if (disconnect_try_count == 0) {
			fprintf(stderr, "Error: mqtt_disconnect() failed.\n");
			goto done;
		}

		MQTT_SUB_DEBUG_PRINT(g_mqtt_client_handle, "deinitialize MQTT client context.\n");
		if (mqtt_deinit_client(g_mqtt_client_handle) != 0) {
			fprintf(stderr, "Error: mqtt_deinit_client() failed.\n");
			goto done;
		}

		g_mqtt_client_handle = NULL;
		clean_client_config();
	} else {
		if (g_sub_topic) {
			MQTT_SUB_DEBUG_PRINT(g_mqtt_client_handle, "subscribe the specified topic.\n");
			if (mqtt_subscribe(g_mqtt_client_handle, g_sub_topic, g_qos) != 0) {
				fprintf(stderr, "Error: mqtt_subscribe() failed.\n");
				goto done;
			}
		}

		if (g_unsub_topic) {
			MQTT_SUB_DEBUG_PRINT(g_mqtt_client_handle, "unsubscribe the specified topic.\n");
			if (mqtt_unsubscribe(g_mqtt_client_handle, g_unsub_topic) != 0) {
				fprintf(stderr, "Error: mqtt_unsubscribe() failed.\n");
				goto done;
			}
		}
	}

	/* result is success */
	result = CHECK_OPTION_RESULT_CHECKED_OK;

done:
	return result;
}
static void handle_mqtt_input(char* data)
{
    mqtt_event_data_t event_data;

    printf("New data received data [%d] [%d]\n", data[0], data[1]);

    switch(data[1])
    {
    case MQTT_MSG_CONNACK:
    {
        PRINTF("CONNACK received %d\n", data[2]);
        switch(data[2])
        {
        case 0:
            mqtt.state = MQTT_STATE_CONNECTED;
            mqtt.keepalive_error = 0;
            printf("start keepalive timer\n");

            printf("stop connection timer\n");
            //etimer_stop(&connection_timer);
            event_data.type = MQTT_EVENT_TYPE_CONNECTED;
            printf("post connect event\n");
            process_post_synch(mqtt.calling_process, mqtt_event, &event_data);

            memset(topic_name, 0, sizeof(topic_name));
            memcpy(topic_name, "temp/", 5);
            onewire_id_str_get(topic_name + 5);
            printf("Topic name : %s\n", topic_name);
            mqtt_subscribe(topic_name);

            break;
        case 1:
            printf("CONNACK:\t Rejected: congestion\n");
            break;
        case 2:
            printf("CONNACK:\t Rejected: invalid topic ID\n");
            break;
        case 3:
            printf("CONNACK:\t Rejected: not supported\n");
            break;
        }
        break;
    }
    case MQTT_MSG_PINGREQ:
    {
        PRINTF("PINGREQ received\n");
        /* Send ping response */
        mqtt_msg_ping_send(&mqtt, MQTT_MSG_PINGRESP);
        uip_udp_packet_send(mqtt.udp_connection, mqtt.data, mqtt.len);
        /* Reset the ping timer as the conenction is alive */


        break;
    }
    case MQTT_MSG_PINGRESP:
    {
        PRINTF("PINGRESP received\n");
        /* We get an answer to pingreq, reset keepalive error counter */
        mqtt.keepalive_error = 0;
        break;
    }
    case MQTT_MSG_SUBACK:
    {
        PRINTF("SUBACK received\n");
        if (mqtt.pending_msg == MQTT_MSG_SUBSCRIBE)
        {
            mqtt.topics[mqtt.nb_topics].id = data[3] << 8 | data[4];
            printf("Topic %s subscribed with id :%d\n", mqtt.topics[mqtt.nb_topics].name, mqtt.topics[mqtt.nb_topics].id);
            mqtt.nb_topics++;
        }
        else
        {
            printf("Error : we get suback without subscribe\n");
        }
        break;
    }
    case MQTT_MSG_PUBLISH:
    {
        int i;
        uint16_t id = data[3] << 8 | data[4];
        uint8_t len = data[0] - 7;

        printf("MQTT_MSG_PUBLISH %d\n", id);
        if (mqtt.state != MQTT_STATE_CONNECTED)
            return;

        for (i = 0; i < mqtt.nb_topics; i++)
        {
            if (mqtt.topics[i].id == id)
            {

                event_data.type  = MQTT_EVENT_TYPE_PUBLISH;
                event_data.topic = mqtt.topics[i].name;
                event_data.data  = data + 7;
                mqtt.data[0] = 7;
                mqtt.data[1] = MQTT_MSG_PUBACK;
                mqtt.data[2] = data[2];
                mqtt.data[3] = data[3];
                mqtt.data[4] = data[4];
                mqtt.data[5] = data[5];
                mqtt.data[6] = 0;
                mqtt.len = 7;
                uip_udp_packet_send(mqtt.udp_connection, mqtt.data, mqtt.len);
                process_post_synch(mqtt.calling_process, mqtt_event, &event_data);
                break;
            }
        }

        break;
    }
    default:
        PRINTF("UNNOWN MESSAGE %d\n", data[1]);
    }

}