Example #1
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();
}
void closeApp(GtkWidget *window, gpointer data)
{
    printf("Destroy\n");
    mqtt_disconnect(&broker);
	close_socket(&broker);
    gtk_main_quit();
}
Example #3
0
int main (int argc, char** argv)
{   
    puts("MQTT PUB Test Code");
    if(argc > 1) {
	parse_options(argc, argv);
    }

//  mqtt_broker_handle_t *broker = mqtt_connect("default_pub","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);
    }
 
    char msg[128];
 
    for(int i = 1; i <= count; ++i) {
        sprintf(msg, "Message number %d", i);
        if(mqtt_publish(broker, topic, msg, QoS1) == -1) {
            printf("publish failed\n");
        }
        else {
            printf("Sent %d messages\n", i);
        }
        sleep(1);
    }
    mqtt_disconnect(broker);
}
Example #4
0
void term(int sig)
{
	printf("Goodbye!\n");
	// >>>>> DISCONNECT
	mqtt_disconnect(&broker);
	close_socket(&broker);

	exit(0);
}
Example #5
0
int main(int argc, char *argv[]){
	if (mqtt_init("device2") != 0) {
		error("init error!\n");
		goto main_error;
	}
	/**
	 * @brief construct CONNECT message
	 */
	if (mqtt_connect(argv[1]) != 0) {
		error("connection error!\n");
		goto main_error;
	}
	/**
	 * @brief construct PUBLICH message
	 */
	if (mqtt_send_subscribe("device1/led_red") != 0) {
		error("publish error!\n");
		goto main_error;
	}

	/* get data */
	while (1)
	{
		/* transport_getdata() has a built-in 1 second timeout,
		your mileage will vary */
		if (mqtt_read() == PUBLISH)
		{
			unsigned char dup;
			int qos;
			unsigned char retained;
			unsigned short msgid;
			int payloadlen_in;
			unsigned char* payload_in;
			int rc;
			MQTTString receivedTopic;

			rc = mqtt_read_publish(&dup, &qos, &retained, &msgid, &receivedTopic,
					&payload_in, &payloadlen_in);
			printf("message arrived %.*s\n", payloadlen_in, payload_in);
			/* send ping message to keep connect */
			mqtt_pingreq();
		}
	}

	/**
	 * @brief construct DISCONNECT message
	 */
	if (mqtt_disconnect() != 0) {
		error("disconnect error!\n");
		goto main_error;
	}
	

	return EXIT_SUCCESS;
main_error:
	return EXIT_FAILURE;
}
void mqtt_update_server(const IPAddress &new_mqtt_server, int new_mqtt_port)
{
  if (cache.set_mqtt_server(new_mqtt_server) || cache.set_mqtt_port(new_mqtt_port))
  {
    cache.save(); // If we are here, something changed and we want to save
    mqtt.setServer(cache.get_mqtt_server(), cache.get_mqtt_port());
    debug.log("MQTT server updated to ", new_mqtt_server, ':', new_mqtt_port);
    next_reconnect = 0;
    mqtt_disconnect();
  }
}
bool KMKMqttClient::disconnect()
{
	int res=mqtt_disconnect(&broker);

	if (getConnectionState() != eTCS_Ready)
	{
		close();
		debugf("KMKMQTT closed connection");
	}

	return res>0;
}
Example #8
0
void itc_mqtt_publish_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_publish(g_mqtt_client_handle, ITC_MQTT_TOPIC, g_mqtt_msg, sizeof(g_mqtt_msg), 0, 0);
	TC_ASSERT_EQ_CLEANUP("mqtt_publish", res, 0,
		mqtt_disconnect(g_mqtt_client_handle); mqtt_deinit_client(g_mqtt_client_handle));
	ITC_MQTT_WAIT_SIGNAL;

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

	res = mqtt_deinit_client(g_mqtt_client_handle);
	TC_ASSERT_EQ("mqtt_deinit_client", res, 0);
	TC_SUCCESS_RESULT();
}
Example #9
0
static void mqtt_ev_cb(struct ev_loop *loop, ev_io *w, int revents)
{
    ev_io_helper_t *watcher = (ev_io_helper_t *)w;
    mqtt_context_t *mqttctx = (mqtt_context_t *)watcher->userdata;

    if (EV_READ & revents)
    {
        if (MOSQ_ERR_SUCCESS != mosquitto_loop_read(mqttctx->mosq
#if LIBMOSQUITTO_VERSION_NUMBER > 1000000
                , 1
#endif
                                                   ))
        {
            LOG_ERROR("read fail");
            mqtt_disconnect(mqttctx);
        }
    }

    if (EV_WRITE & revents)
    {
        if (MOSQ_ERR_SUCCESS != mosquitto_loop_write(mqttctx->mosq
#if LIBMOSQUITTO_VERSION_NUMBER > 1000000
                , 1
#endif
                                                    ))
        {
            LOG_ERROR("write fail");
            mqtt_disconnect(mqttctx);
        }

#if LIBMOSQUITTO_VERSION_NUMBER > 1000000
        if (!mosquitto_want_write(mqttctx->mosq))
#endif
            ev_io_stop(g_srvctx.loop, &mqttctx->write_watcher.io);
    }
}
Example #10
0
/**@brief Function for handling button events.
 *
 * @param[in]   pin_no         The pin number of the button pressed.
 * @param[in]   button_action  The action performed on button.
 */
static void button_event_handler(uint8_t pin_no, uint8_t button_action)
{
#ifdef COMMISSIONING_ENABLED
    if ((button_action == APP_BUTTON_PUSH) && (pin_no == ERASE_BUTTON_PIN_NO))
    {
        APPL_LOG("[APPL]: Erasing all commissioning settings from persistent storage... \r\n");
        commissioning_settings_clear();
        return;
    }
#endif // COMMISSIONING_ENABLED

    uint32_t err_code;

    // Check if interface has been established.
    if(m_interface_state == false)
    {
        return;
    }

    if (button_action == APP_BUTTON_PUSH)
    {
        switch (pin_no)
        {
            case BSP_BUTTON_0:
            {
                if (m_connection_state == false)
                {
                    err_code = app_timer_start(m_mqtt_conn_timer_id, APP_XIVELY_CONNECT_DELAY, NULL);
                    APP_ERROR_CHECK(err_code);
                }
                break;
            }
            case BSP_BUTTON_1:
            {
                if (m_connection_state == true)
                {
                    err_code = mqtt_disconnect(&m_app_mqtt_id);
                    APP_ERROR_CHECK(err_code);
                }
                break;
            }
            default:
                break;
        }
    }
}
Example #11
0
void itc_mqtt_connect_n_reconnect(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);

	// MQTT Connect
	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;

	// MQTT re-Connect
	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));
	if (g_mqtt_client_handle != NULL) {
		TC_ASSERT_EQ_CLEANUP("mqtt_connect", g_mqtt_client_handle->state, MQTT_CLIENT_STATE_CONNECTED,
			mqtt_disconnect(g_mqtt_client_handle); mqtt_deinit_client(g_mqtt_client_handle));
	}
Example #12
0
void itc_mqtt_connect_disconnect_n(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);

	// MQTT Connect
	res = mqtt_connect(g_mqtt_client_handle, NULL, CONFIG_ITC_MQTT_BROKER_PORT, 0);
	TC_ASSERT_EQ("mqtt_connect", res, -1);

	//MQTT Disconnect
	res = mqtt_disconnect(g_mqtt_client_handle);
	TC_ASSERT_EQ_CLEANUP("mqtt_disconnect", res, 0, mqtt_deinit_client(g_mqtt_client_handle));

	res = mqtt_deinit_client(g_mqtt_client_handle);
	TC_ASSERT_EQ("mqtt_deinit_client", res, 0);
	TC_SUCCESS_RESULT();
}
Example #13
0
static void button_event_handler(uint8_t pin_no, uint8_t button_action)
{
    if (button_action == APP_BUTTON_PUSH)
    {
        switch (pin_no)
        {
            case BSP_BUTTON_0:
            {
                if (m_connection_state == false)
                {
                    mqtt_connect_t param;

                    param.broker_addr    = m_broker_addr;
                    param.broker_port    = APP_MQTT_BROKER_PORT;
                    param.evt_cb         = app_mqtt_evt_handler;
                    param.device_id      = m_device_id;
                    param.p_password     = NULL;
                    param.p_user_name    = NULL;

                    UNUSED_VARIABLE(mqtt_connect(&m_app_mqtt_id, &param));
                }
                break;
            }
            case BSP_BUTTON_1:
            {
                if (m_connection_state == true)
                {
                    app_mqtt_publish(!m_led_state);
                }
                break;
            }
            case BSP_BUTTON_2:
            {
                if (m_connection_state == true)
                {
                    UNUSED_VARIABLE(mqtt_disconnect(&m_app_mqtt_id));
                }
                break;
            }
            default:
                break;
        }
    }
}
Example #14
0
/*---------------------------------------------------------------------------*/
static void
new_net_config(void)
{
    /*
     * We got a new configuration over the net.
     *
     * Disconnect from the current broker and stop the periodic timer.
     *
     * When the source of the new configuration is done, we will get notified
     * via an event.
     */
    if(state == MQTT_CLIENT_STATE_NEWCONFIG) {
        return;
    }

    state = MQTT_CLIENT_STATE_NEWCONFIG;

    etimer_stop(&publish_periodic_timer);
    mqtt_disconnect(&conn);
}
Example #15
0
void itc_mqtt_connect_disconnect_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);

	// MQTT Connect
	res = mqtt_connect(g_mqtt_client_handle, CONFIG_ITC_MQTT_BROKER_ADDR, CONFIG_ITC_MQTT_BROKER_PORT, 0);
	TC_ASSERT_EQ("mqtt_connect", res, 0);
	ITC_MQTT_WAIT_SIGNAL;

	//MQTT Disconnect
	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();
}
Example #16
0
static void mqtt_timeout_cb(struct ev_loop *loop, struct ev_io *w, int revents)
{
    ev_timer_helper_t *watcher = (ev_timer_helper_t *)w;
    mqtt_context_t *mqttctx = (mqtt_context_t *)watcher->userdata;

    if (EV_TIMEOUT & revents)
    {
        if (mqttctx->connected)
        {
            if (MOSQ_ERR_SUCCESS != mosquitto_loop_misc(mqttctx->mosq))
            {
                LOG_ERROR("mosquitto_loop_misc fail");
                mqtt_disconnect(mqttctx);
            }

#if LIBMOSQUITTO_VERSION_NUMBER > 1000000
            if (mosquitto_want_write(mqttctx->mosq))
#endif
                ev_io_start(g_srvctx.loop, &mqttctx->write_watcher.io);
        }
    }
}
Example #17
0
/**@brief Function for handling button events.
 *
 * @param[in]   pin_no         The pin number of the button pressed.
 * @param[in]   button_action  The action performed on button.
 */
static void button_event_handler(uint8_t pin_no, uint8_t button_action)
{
    uint32_t err_code;

    // Check if interface has been established.
    if(m_interface_state == false)
    {
        return;
    }

    if (button_action == APP_BUTTON_PUSH)
    {
        switch (pin_no)
        {
            case BSP_BUTTON_0:
            {
                if (m_connection_state == false)
                {
                    err_code = app_timer_start(m_mqtt_conn_timer_id, APP_XIVELY_CONNECT_DELAY, NULL);
                    APP_ERROR_CHECK(err_code);
                }
                break;
            }
            case BSP_BUTTON_1:
            {
                if (m_connection_state == true)
                {
                    err_code = mqtt_disconnect(&m_app_mqtt_id);
                    APP_ERROR_CHECK(err_code);
                }
                break;
            }
            default:
                break;
        }
    }
}
Example #18
0
/**
 * \brief Callback to get the Wi-Fi status update.
 *
 * \param[in] msg_type type of Wi-Fi notification. Possible types are:
 *  - [M2M_WIFI_RESP_CURRENT_RSSI](@ref M2M_WIFI_RESP_CURRENT_RSSI)
 *  - [M2M_WIFI_RESP_CON_STATE_CHANGED](@ref M2M_WIFI_RESP_CON_STATE_CHANGED)
 *  - [M2M_WIFI_RESP_CONNTION_STATE](@ref M2M_WIFI_RESP_CONNTION_STATE)
 *  - [M2M_WIFI_RESP_SCAN_DONE](@ref M2M_WIFI_RESP_SCAN_DONE)
 *  - [M2M_WIFI_RESP_SCAN_RESULT](@ref M2M_WIFI_RESP_SCAN_RESULT)
 *  - [M2M_WIFI_REQ_WPS](@ref M2M_WIFI_REQ_WPS)
 *  - [M2M_WIFI_RESP_IP_CONFIGURED](@ref M2M_WIFI_RESP_IP_CONFIGURED)
 *  - [M2M_WIFI_RESP_IP_CONFLICT](@ref M2M_WIFI_RESP_IP_CONFLICT)
 *  - [M2M_WIFI_RESP_P2P](@ref M2M_WIFI_RESP_P2P)
 *  - [M2M_WIFI_RESP_AP](@ref M2M_WIFI_RESP_AP)
 *  - [M2M_WIFI_RESP_CLIENT_INFO](@ref M2M_WIFI_RESP_CLIENT_INFO)
 * \param[in] pvMsg A pointer to a buffer containing the notification parameters
 * (if any). It should be casted to the correct data type corresponding to the
 * notification type. Existing types are:
 *  - tstrM2mWifiStateChanged
 *  - tstrM2MWPSInfo
 *  - tstrM2MP2pResp
 *  - tstrM2MAPResp
 *  - tstrM2mScanDone
 *  - tstrM2mWifiscanResult
 */
static void wifi_callback(uint8 msg_type, void *msg_data)
{
	tstrM2mWifiStateChanged *msg_wifi_state;
	uint8 *msg_ip_addr;

	switch (msg_type) {
	case M2M_WIFI_RESP_CON_STATE_CHANGED:
		msg_wifi_state = (tstrM2mWifiStateChanged *)msg_data;
		if (msg_wifi_state->u8CurrState == M2M_WIFI_CONNECTED) {
			/* If Wi-Fi is connected. */
			printf("Wi-Fi connected\r\n");
			m2m_wifi_request_dhcp_client();
		} else if (msg_wifi_state->u8CurrState == M2M_WIFI_DISCONNECTED) {
			/* If Wi-Fi is disconnected. */
			printf("Wi-Fi disconnected\r\n");
			m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID),
					MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL);
			/* Disconnect from MQTT broker. */
			/* Force close the MQTT connection, because cannot send a disconnect message to the broker when network is broken. */
			mqtt_disconnect(&mqtt_inst, 1);
		}

		break;

	case M2M_WIFI_REQ_DHCP_CONF:
		msg_ip_addr = (uint8 *)msg_data;
		printf("Wi-Fi IP is %u.%u.%u.%u\r\n",
				msg_ip_addr[0], msg_ip_addr[1], msg_ip_addr[2], msg_ip_addr[3]);
		/* Try to connect to MQTT broker when Wi-Fi was connected. */
		mqtt_connect(&mqtt_inst, main_mqtt_broker);
		break;

	default:
		break;
	}
}
Example #19
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;
}
Example #20
0
PROCESS_THREAD(mqtt_socket_process, ev, data)
{
	PROCESS_BEGIN();
	
    SOCKETMSG msg;
	static struct etimer mqtt_socket_timer;
	int recv;


	mqtt_tcp_socket_init();
	app_mqtt_init(&g_stMQTTBroker);
	mqtt_tcp_connect(MQTT_SERVER_ADDR, MQTT_SERVER_PORT);

	while(1) 
	{
		PROCESS_WAIT_EVENT();

		if(ev == resolv_event_found)
		{
			char *p_hostname = (char *)data;

			if(strcmp(p_hostname, MQTT_SERVER_ADDR))
				continue;
			
			uip_ipaddr_t addr;
			uip_ipaddr_t *p_addr = &addr;
			uip_ip4addr_t remote_ip_addr;
			resolv_lookup(p_hostname, &p_addr);
			uip_ipaddr_copy(&remote_ip_addr, p_addr);

			char ip_str[20]= {0}; 
			sprintf(ip_str,"%d.%d.%d.%d", remote_ip_addr.u8[0], remote_ip_addr.u8[1], remote_ip_addr.u8[2], remote_ip_addr.u8[3]);
		
			mqtt_tcp_connect(ip_str, MQTT_SERVER_PORT);	
		}
		else if(ev == PROCESS_EVENT_EXIT)
		{
			mqtt_disconnect(&g_stMQTTBroker);
			tcpclose(g_mqtt_socket_para.fd);
			break;
		}
		else if(ev == PROCESS_EVENT_MSG)
		{
            msg = *(SOCKETMSG *)data;

			if(msg.status == SOCKET_CONNECTED) 
			{
				printf("MQTT tcp socket(%d) connected\n", msg.socket);
				g_mqtt_socket_para.connect_status = SOCKET_CONNECTED;
				tcp_set_send_buffer_size(g_mqtt_socket_para.fd, MQTT_SOCKET_SEND_BUF_SIZE);

				mqtt_login_server(&g_stMQTTBroker);
			}
			else if(msg.status == SOCKET_CLOSED)
			{
				if(g_mqtt_socket_para.connect_status == SOCKET_CREATE)
					printf("Socked(%d) create fail and retry...\n", msg.socket);
				else
					printf("MQTT tcp socket(%d) closed\n", msg.socket);		

				g_mqtt_socket_para.fd = -1;
				g_mqtt_socket_para.connect_status = SOCKET_CLOSED;
				etimer_set(&mqtt_socket_timer, 3*CLOCK_SECOND);
				PROCESS_WAIT_EVENT_UNTIL(etimer_expired(&mqtt_socket_timer));
				
				mqtt_tcp_connect(MQTT_SERVER_ADDR, MQTT_SERVER_PORT);				
			}
			else if(msg.status == SOCKET_SENDACK)
			{
			
			}
			else if(msg.status == SOCKET_NEWDATA)
			{
				g_mqtt_socket_para.connect_status = SOCKET_NEWDATA;

				recv = tcprecv(g_mqtt_socket_para.fd, g_mqtt_socket_para.recv_buf, MQTT_SOCKET_RECV_BUF_SIZE);
				if(recv<=0)
				{
					printf("tcprecv error! ret:%d\n", recv);
					continue;
				}
				
				app_parse_mqttmsg(g_mqtt_socket_para.recv_buf);	
			}
		
		}
		

	}
	
	PROCESS_END();
}
Example #21
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();
}
/*---------------------------------------------------------------------------*/
static
PT_THREAD(connect_pt(struct pt *pt, struct mqtt_connection *conn))
{
  PT_BEGIN(pt);

  DBG("MQTT - Sending CONNECT message...\n");

  /* Set up FHDR */
  conn->out_packet.fhdr = MQTT_FHDR_MSG_TYPE_CONNECT;
  conn->out_packet.remaining_length = 0;
  conn->out_packet.remaining_length += MQTT_CONNECT_VHDR_FLAGS_SIZE;
  conn->out_packet.remaining_length += MQTT_STRING_LENGTH(&conn->client_id);
  conn->out_packet.remaining_length += MQTT_STRING_LENGTH(&conn->credentials.username);
  conn->out_packet.remaining_length += MQTT_STRING_LENGTH(&conn->credentials.password);
  conn->out_packet.remaining_length += MQTT_STRING_LENGTH(&conn->will.topic);
  conn->out_packet.remaining_length += MQTT_STRING_LENGTH(&conn->will.message);
  encode_remaining_length(conn->out_packet.remaining_length_enc,
                          &conn->out_packet.remaining_length_enc_bytes,
                          conn->out_packet.remaining_length);
  if(conn->out_packet.remaining_length_enc_bytes > 4) {
    call_event(conn, MQTT_EVENT_PROTOCOL_ERROR, NULL);
    PRINTF("MQTT - Error, remaining length > 4 bytes\n");
    PT_EXIT(pt);
  }

  /* Write Fixed Header */
  PT_MQTT_WRITE_BYTE(conn, conn->out_packet.fhdr);
  PT_MQTT_WRITE_BYTES(conn,
                      conn->out_packet.remaining_length_enc,
                      conn->out_packet.remaining_length_enc_bytes);
  PT_MQTT_WRITE_BYTE(conn, 0);
  PT_MQTT_WRITE_BYTE(conn, 6);
  PT_MQTT_WRITE_BYTES(conn, (uint8_t *)MQTT_PROTOCOL_NAME, 6);
  PT_MQTT_WRITE_BYTE(conn, MQTT_PROTOCOL_VERSION);
  PT_MQTT_WRITE_BYTE(conn, conn->connect_vhdr_flags);
  PT_MQTT_WRITE_BYTE(conn, (conn->keep_alive >> 8));
  PT_MQTT_WRITE_BYTE(conn, (conn->keep_alive & 0x00FF));
  PT_MQTT_WRITE_BYTE(conn, conn->client_id.length << 8);
  PT_MQTT_WRITE_BYTE(conn, conn->client_id.length & 0x00FF);
  PT_MQTT_WRITE_BYTES(conn, (uint8_t *)conn->client_id.string,
                      conn->client_id.length);
  if(conn->connect_vhdr_flags & MQTT_VHDR_WILL_FLAG) {
    PT_MQTT_WRITE_BYTE(conn, conn->will.topic.length << 8);
    PT_MQTT_WRITE_BYTE(conn, conn->will.topic.length & 0x00FF);
    PT_MQTT_WRITE_BYTES(conn, (uint8_t *)conn->will.topic.string,
                        conn->will.topic.length);
    PT_MQTT_WRITE_BYTE(conn, conn->will.message.length << 8);
    PT_MQTT_WRITE_BYTE(conn, conn->will.message.length & 0x00FF);
    PT_MQTT_WRITE_BYTES(conn, (uint8_t *)conn->will.message.string,
                        conn->will.message.length);
    DBG("MQTT - Setting will topic to '%s' %u bytes and message to '%s' %u bytes\n",
        conn->will.topic.string,
        conn->will.topic.length,
        conn->will.message.string,
        conn->will.message.length);
  }
  if(conn->connect_vhdr_flags & MQTT_VHDR_USERNAME_FLAG) {
    PT_MQTT_WRITE_BYTE(conn, conn->credentials.username.length << 8);
    PT_MQTT_WRITE_BYTE(conn, conn->credentials.username.length & 0x00FF);
    PT_MQTT_WRITE_BYTES(conn,
                        (uint8_t *)conn->credentials.username.string,
                        conn->credentials.username.length);
  }
  if(conn->connect_vhdr_flags & MQTT_VHDR_PASSWORD_FLAG) {
    PT_MQTT_WRITE_BYTE(conn, conn->credentials.password.length << 8);
    PT_MQTT_WRITE_BYTE(conn, conn->credentials.password.length & 0x00FF);
    PT_MQTT_WRITE_BYTES(conn,
                        (uint8_t *)conn->credentials.password.string,
                        conn->credentials.password.length);
  }

  /* Send out buffer */
  send_out_buffer(conn);
  conn->state = MQTT_CONN_STATE_CONNECTING_TO_BROKER;

  timer_set(&conn->t, RESPONSE_WAIT_TIMEOUT);

  /* Wait for CONNACK */
  reset_packet(&conn->in_packet);
  PT_WAIT_UNTIL(pt, conn->out_packet.qos_state == MQTT_QOS_STATE_GOT_ACK ||
                timer_expired(&conn->t));
  if(timer_expired(&conn->t)) {
    DBG("Timeout waiting for CONNACK\n");
    /* We stick to the letter of the spec here: Tear the connection down */
    mqtt_disconnect(conn);
  }
  reset_packet(&conn->in_packet);

  DBG("MQTT - Done sending CONNECT\n");

#if DEBUG_MQTT == 1
  DBG("MQTT - CONNECT message sent: \n");
  uint16_t i;
  for(i = 0; i < (conn->out_buffer_ptr - conn->out_buffer); i++) {
    DBG("%02X ", conn->out_buffer[i]);
  }
  DBG("\n");
#endif

  PT_END(pt);
}
int server_connect(int doConnect)
{
    int16_t packet_length;
    char host[30];  // temp space for hostname string

    serverConnected = 0;

    if (doConnect)
    {
        sprintf(host, THINGFABRIC_BROKER_HOSTNAME);
        char *hostname = host;
        hostname_to_ip(hostname , broker_ip);

        if ((broker_ip == NULL) || (broker_ip[0] == 0))
        {
            return 0;
        }

        printf("\n%s resolved to %s\n" , hostname , broker_ip);

        sleep(5);

        // now connect using user/password, publish sensor values on
        // appropriate topic (<domain>/<device type>/<device id>
        char clientIDStr[100];
        sprintf(clientIDStr, "%s/%s", THINGFABRIC_DEVICE_TYPE, THINGFABRIC_DEVICE_ID);
        mqtt_init(&broker, clientIDStr);
        mqtt_init_auth(&broker, THINGFABRIC_USERNAME, THINGFABRIC_PASSWORD);
        init_socket(&broker, broker_ip, THINGFABRIC_BROKER_PORT);

        serverConnected = 1;

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

        if(MQTTParseMessageType(packet_buffer) != MQTT_MSG_CONNACK)
        {
            fprintf(stderr, "CONNACK expected!\n");
            serverConnected = 0;
        }

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

        if (serverConnected)
        {
            sprintf(pubTopic, "%s/%s/%s", THINGFABRIC_DOMAIN, THINGFABRIC_DEVICE_TYPE, THINGFABRIC_DEVICE_ID);
            printf("%s\n", pubTopic);

            // configure the ping timer
            signal(SIGALRM, alive);
            alarm(keepalive);
        }
        else
        {
            fprintf(stderr, "Error connecting to MQTT server\n");
        }
    }
    else
    {
        printf("Disconnecting from server\n");
        mqtt_disconnect(&broker);
        close_socket(&broker);
        serverConnected = 0;
    }

    return serverConnected;
}
Example #24
0
	TC_ASSERT_NEQ("mqtt_init_client", g_mqtt_client_handle, NULL);

	// MQTT Connect
	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;

	// MQTT re-Connect
	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));
	if (g_mqtt_client_handle != NULL) {
		TC_ASSERT_EQ_CLEANUP("mqtt_connect", g_mqtt_client_handle->state, MQTT_CLIENT_STATE_CONNECTED,
			mqtt_disconnect(g_mqtt_client_handle); mqtt_deinit_client(g_mqtt_client_handle));
	}
	//MQTT Disconnect
	res = mqtt_disconnect(g_mqtt_client_handle);
	TC_ASSERT_EQ_CLEANUP("mqtt_disconnect", res, 0, mqtt_deinit_client(g_mqtt_client_handle));
	ITC_MQTT_WAIT_SIGNAL;

	res = mqtt_deinit_client(g_mqtt_client_handle);
	TC_ASSERT_EQ("mqtt_deinit_client", res, 0);
	TC_SUCCESS_RESULT();
}

/**
 * @testcase             itc_mqtt_disconnect_n_redisconnect
 * @brief                already disconnected from server
 * @scenario             already disconnected from server
 * @apicovered           mqtt_init_client, mqtt_connect, mqtt_disconnect, mqtt_deinit_client
 * @precondition         mqtt_disconnect
 * @postcondition        mqtt_deinit_client
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;
}
Example #26
0
/*---------------------------------------------------------------------------*/
static void
state_machine(void)
{
    switch(state) {
    case MQTT_CLIENT_STATE_INIT:
        /* If we have just been configured register MQTT connection */
        mqtt_register(&conn, &mqtt_client_process, client_id, mqtt_event,
                      MQTT_CLIENT_MAX_SEGMENT_SIZE);

        /*
         * Authentication: provide user name and password
         */
        if(strlen(conf->auth_token) > 0) {
            mqtt_set_username_password(&conn, "use-token-auth",
                                       conf->auth_token);
        }

        /* _register() will set auto_reconnect. We don't want that. */
        conn.auto_reconnect = 0;
        connect_attempt = 1;

        /*
         * Wipe out the default route so we'll republish it every time we switch to
         * a new broker
         */
        memset(&def_route, 0, sizeof(def_route));

        state = MQTT_CLIENT_STATE_REGISTERED;
        DBG("Init\n");
    /* Continue */
    case MQTT_CLIENT_STATE_REGISTERED:
        if(uip_ds6_get_global(ADDR_PREFERRED) != NULL) {
            /* Registered and with a public IP. Connect */
            DBG("Registered. Connect attempt %u\n", connect_attempt);
            ping_parent();
            connect_to_broker();
        }
        etimer_set(&publish_periodic_timer, CC26XX_WEB_DEMO_NET_CONNECT_PERIODIC);
        return;
        break;
    case MQTT_CLIENT_STATE_CONNECTING:
        leds_on(CC26XX_WEB_DEMO_STATUS_LED);
        ctimer_set(&ct, CONNECTING_LED_DURATION, publish_led_off, NULL);
        /* Not connected yet. Wait */
        DBG("Connecting (%u)\n", connect_attempt);
        break;
    case MQTT_CLIENT_STATE_CONNECTED:
    /* Don't subscribe unless we are a registered device
    if(strncasecmp(conf->org_id, QUICKSTART, strlen(conf->org_id)) == 0) {
      DBG("Using 'quickstart': Skipping subscribe\n");
      state = MQTT_CLIENT_STATE_PUBLISHING;
    }*/
    /* Continue */
    case MQTT_CLIENT_STATE_PUBLISHING:
        /* If the timer expired, the connection is stable. */
        if(timer_expired(&connection_life)) {
            /*
             * Intentionally using 0 here instead of 1: We want RECONNECT_ATTEMPTS
             * attempts if we disconnect after a successful connect
             */
            connect_attempt = 0;
        }

        if(mqtt_ready(&conn) && conn.out_buffer_sent) {
            /* Connected. Publish */
            if(state == MQTT_CLIENT_STATE_CONNECTED) {
                subscribe();
                state = MQTT_CLIENT_STATE_PUBLISHING;
            } else {
                leds_on(CC26XX_WEB_DEMO_STATUS_LED);
                ctimer_set(&ct, PUBLISH_LED_ON_DURATION, publish_led_off, NULL);
                publish();
            }
            etimer_set(&publish_periodic_timer, conf->pub_interval);

            DBG("Publishing\n");
            /* Return here so we don't end up rescheduling the timer */
            return;
        } else {
            /*
             * Our publish timer fired, but some MQTT packet is already in flight
             * (either not sent at all, or sent but not fully ACKd).
             *
             * This can mean that we have lost connectivity to our broker or that
             * simply there is some network delay. In both cases, we refuse to
             * trigger a new message and we wait for TCP to either ACK the entire
             * packet after retries, or to timeout and notify us.
             */
            DBG("Publishing... (MQTT state=%d, q=%u)\n", conn.state,
                conn.out_queue_full);
        }
        break;
    case MQTT_CLIENT_STATE_DISCONNECTED:
        DBG("Disconnected\n");
        if(connect_attempt < RECONNECT_ATTEMPTS ||
                RECONNECT_ATTEMPTS == RETRY_FOREVER) {
            /* Disconnect and backoff */
            clock_time_t interval;
            mqtt_disconnect(&conn);
            connect_attempt++;

            interval = connect_attempt < 3 ? RECONNECT_INTERVAL << connect_attempt :
                       RECONNECT_INTERVAL << 3;

            DBG("Disconnected. Attempt %u in %lu ticks\n", connect_attempt, interval);

            etimer_set(&publish_periodic_timer, interval);

            state = MQTT_CLIENT_STATE_REGISTERED;
            return;
        } else {
            /* Max reconnect attempts reached. Enter error state */
            state = MQTT_CLIENT_STATE_ERROR;
            DBG("Aborting connection after %u attempts\n", connect_attempt - 1);
        }
        break;
    case MQTT_CLIENT_STATE_NEWCONFIG:
        /* Only update config after we have disconnected */
        if(conn.state == MQTT_CONN_STATE_NOT_CONNECTED) {
            update_config();
            DBG("New config\n");

            /* update_config() scheduled next pass. Return */
            return;
        }
        break;
    case MQTT_CLIENT_STATE_CONFIG_ERROR:
        /* Idle away. The only way out is a new config */
        printf("Bad configuration.\n");
        return;
    case MQTT_CLIENT_STATE_ERROR:
    default:
        leds_on(CC26XX_WEB_DEMO_STATUS_LED);
        /*
         * 'default' should never happen.
         *
         * If we enter here it's because of some error. Stop timers. The only thing
         * that can bring us out is a new config event
         */
        printf("Default case: State=0x%02x\n", state);
        return;
    }

    /* If we didn't return so far, reschedule ourselves */
    etimer_set(&publish_periodic_timer, STATE_MACHINE_PERIODIC);
}
Example #27
0
int main(int argc, char* argv[])
{
	int packet_length;
	uint16_t msg_id, msg_id_rcv;
	mqtt_broker_handle_t broker;

	mqtt_init(&broker, "avengalvon");
	mqtt_init_auth(&broker, "cid", "campeador");
	init_socket(&broker, "127.0.0.1", 1883);

	// >>>>> 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;
	}

	// >>>>> PUBLISH QoS 0
	printf("Publish: QoS 0\n");
	mqtt_publish(&broker, "hello/emqtt", "Example: QoS 0", 0);

	// >>>>> PUBLISH QoS 1
	printf("Publish: QoS 1\n");
	mqtt_publish_with_qos(&broker, "hello/emqtt", "Example: QoS 1", 0, 1, &msg_id);
	// <<<<< PUBACK
	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_PUBACK)
	{
		fprintf(stderr, "PUBACK 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;
	}

	// >>>>> PUBLISH QoS 2
	printf("Publish: QoS 2\n");
	mqtt_publish_with_qos(&broker, "hello/emqtt", "Example: QoS 2", 1, 2, &msg_id); // Retain
	// <<<<< PUBREC
	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_PUBREC)
	{
		fprintf(stderr, "PUBREC 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;
	}

	// >>>>> PUBREL
	mqtt_pubrel(&broker, msg_id);
	// <<<<< PUBCOMP
	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_PUBCOMP)
	{
		fprintf(stderr, "PUBCOMP 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;
	}

	// >>>>> DISCONNECT
	mqtt_disconnect(&broker);
	close_socket(&broker);
	return 0;
}
Example #28
0
int main(int argc, char* argv[])
{
	int packet_length;
	uint16_t msg_id, msg_id_rcv;
	mqtt_broker_handle_t broker;

   mqtt_init(&broker, "sancho");
   mqtt_init_auth(&broker, "quijote", "rocinante");
   init_socket(&broker, "192.168.10.40", 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;
	}


	// >>>>> PUBLISH QoS 0
	printf("Publish: QoS 0\n");
	mqtt_publish(&broker, "public/myexample/example", "Test libemqtt message.", 0);
	// >>>>> PUBLISH QoS 1
	printf("Publish: QoS 1\n");
	mqtt_publish_with_qos(&broker, "hello/emqtt", "Example: QoS 1", 0, 1, &msg_id);
	// <<<<< PUBACK
	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_PUBACK)
	{
		fprintf(stderr, "PUBACK expected!\n");
		return -2;
	}

	MQTTParseMessageId(packet_buffer, msg_id_rcv);
	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;
	}

	// >>>>> PUBLISH QoS 2
	printf("Publish: QoS 2\n");
	mqtt_publish_with_qos(&broker, "hello/emqtt", "Example: QoS 2", 1, 2, &msg_id); // Retain
	// <<<<< PUBREC
	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_PUBREC)
	{
		fprintf(stderr, "PUBREC expected!\n");
		return -2;
	}

	MQTTParseMessageId(packet_buffer, msg_id_rcv);
	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;
	}

	// >>>>> PUBREL
	mqtt_pubrel(&broker, msg_id);
	// <<<<< PUBCOMP
	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_PUBCOMP)
	{
		fprintf(stderr, "PUBCOMP expected!\n");
		return -2;
	}

	MQTTParseMessageId(packet_buffer, msg_id_rcv);
	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;
	}

	// >>>>> DISCONNECT
	mqtt_disconnect(&broker);
	close_socket(&broker);
	return 0;
}