W5100S——MQTT connects to Baidu Tiangong cloud platform

his article explains how to connect W5100S to Baidu Tiangong Cloud Platform via MQTT.
ORIGINAL POST
By NA
components
Hardware Components
w5100s
X 1
stm32f1x
X 1
details

ucc_april1.png

Prepare

  • Software environment: Windows
  • Hardware environment: STM32F103 + W5500
  • Development tools: Keil uVision5
  • Debugging Tool: Serial Debugging Wizard
  • Connected platform: Baidu Yuntiangong ( https://cloud.baidu.com/

2. Introduction to MQTT

MQTT official website address: ( http://mqtt.org/

2.1 Characteristics of the MQTT protocol

MQTT is a client-server based message publish/subscribe transmission protocol. The MQTT protocol is lightweight, simple, open, and easy to implement. These characteristics make it applicable to a wide range. In many cases, including restricted environments such as machine-to-machine (M2M) communication and the Internet of Things (IoT). It has been widely used in satellite sensors to communicate with sensors, occasionally marking medical devices, smart homes, and some miniaturized devices.

The current version of the MQTT protocol is MQTT v3.1.1 released in 2014. In addition to the standard version, there is a simplified version of MQTT-SN. This protocol is primarily for embedded devices. These devices typically work on hundreds of TCP/IP networks, such as: ZigBee.

The MQTT protocol runs on TCP/IP or other network protocols and provides lossless and orderly bidirectional connections. Its features include:

  • The publish/subscribe message pattern used, which provides one-to-many message distribution to decouple applications.
  • Message transmission mechanism that protects the content of the payload.
  • There are three types of Quality of Service (QoS) for transmitting messages:
  • At most once, message loss or duplication can occur at this level, and message distribution depends on the underlying TCP/IP network. That is: <= 1
  • At most once, this level ensures that messages arrive, but messages may be duplicates. That is: >= 1
  • Only once, make sure that the message arrives only once. That is: = 1. This level can be used in some more demanding billing systems.

Minimize data transmission and protocol exchange (protocol header is only 2 bytes) to reduce network traffic

Notification mechanism

2.2 MQTT Protocol principle and implementation

Need to implement the MQTT protocol: client and server

There are three types of identities in the MQTT protocol: publisher, broker (server), and subscriber (subscribe). Among them, the publisher and subscriber of a message are both clients, the message broker is a server, and the publisher of a message can also be a subscriber.

Messages transmitted by MQTT are divided into two parts: subject and message payload.

The topic can be understood as the type of message. After a subscriber subscribes, they will receive the message content (payload) of the topic.

The payload, which can be understood as the content of the message, refers to the content that the subscriber specifically wants to use

2.3 Baidu Yuntiang MQTT connection steps

2.3.1. Enter the management console(Please login in advance);

23. 2. Select the “IoT Access IoT Hub” section

23. 3. Create a project

(The routine is used with data type equipment. For detailed information on data type and equipment type differences, please go to Baidu Yuntiangong for inquiries)

23. 4. After submitting the project, enter the project creation sub-user

Name: the username in the MQTT connection message

Identity: determine the way of access, you can use a key connection.

Strategy: Link permissions and corresponding themes.

Key: Keep it safe. This is the password for the connection. (Forgetting can be reset in the identity list)


After the project has been created successfully, register: name, identity, key. You can modify the corresponding string through the routine to connect the device you created.


3. Routine experimental phenomenon

First, we must look at the experimental phenomenon after the programming process.

Note: The test of receiving messages and posting messages to the topics after the W5100S subscribes to the topic is the establishment of the second device B in Baidu Cloud. Device B broadcasts a message and receives a topic message from the W5100S. This is to check if the W5100S can receive the subject message or send it.

3.1 The serial port prints the message “Connection successful” or “Specific reason for connection failure”.

3.2 Subscribe to topics

3.3. Receive topic messages

3.4. Post a topic message

4. Example code

Because the code involves the unpacking part of MQTT, the detailed explanation is too detailed.

Therefore, this discussion only discusses function functions and code frameworks, and does not disassemble function implementation too much.

4.1. The general framework flow of the main function

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include “stm32f10x.h”
  4. #include “bsp_usart1.h”
  5. #include “bsp_fsmc.h”
  6. #include “bsp_spi.h”
  7. #include “w5100s.h”
  8. #include “W5100s_conf.h”
  9. #include “wizchip_conf.h”
  10. #include “w5100s_conf.h”
  11. #include “utility.h”
  12. #include “tcp_demo.h”
  13. #include “MqttKit.h”
  14. int main(void)
  15. {
  16. systick_init (72); // Inicializa el temporizador de tic
  17. USART1_Config (); // Inicializar USART1: 115200 @ 8-N-1
  18. reset_break_gpio_init (); // Restablecer e interrumpir la inicialización del pin
  19. #if (_WIZCHIP_IO_MODE_ == _WIZCHIP_IO_MODE_SPI_)
  20. spi_gpio_init (); // inicialización del pin SPI
  21. spiinitailize (); // inicialización de configuración SPI
  22. reg_wizchip_spi_cbfunc (spi_read_byte, spi_send_byte); // asignación de funciones de datos de lectura y escritura SPI
  23. reg_wizchip_cs_cbfunc (cs_low, cs_high); // asignación de función de control de selección de chip SPI
  24. #elif (_WIZCHIP_IO_MODE_ == _WIZCHIP_IO_MODE_BUS_INDIR_)
  25. FSMC_gpio_init (); // Inicialización de pin FSMC c
  26. FSMCInitialize (); // Inicialización de configuración de FSMC
  27. #endif
  28. printf (” r n Tecnología Wei Shi – agente oficial de WIZnet W5100S. Soporte técnico completo, gran ventaja de precio! r n r n”);
  29. reset_w5100s (); // Restablecimiento de hardware W5100S
  30. PHY_check (); // programa de verificación de cable de red
  31. set_w5100s_mac (); // Establecer dirección W5100SMAC
  32. set_w5100s_netinfo (); // Establecer parámetros de red W5100S
  33. wizchip_init (txsize, rxsize); // Inicializa el tamaño del búfer de envío y recepción de 4 sockets
  34. printf (” r n La configuración del parámetro de red W5100S está completa, utilice la dirección W5100SIP ‘PING’ de la computadora para verificar si la red es fluida”);
  35. while (1) / * función para ejecución de bucle * /
  36. {
  37. do_tcp_client (); // prueba de bucle invertido de datos del cliente TCP
  38. delay_ms(100);
  39. if (Usuario1 == 0) // Suscribirse
  40. {
  41. while(User1 == 0);
  42. MQTT_STATE = MQTT_PKT_SUBSCRIBE;
  43. }
  44. // if (KEY_5 == 0) // cancelar suscripción
  45. // {
  46. // MQTT_STATE = MQTT_PKT_UNSUBSCRIBE;
  47. // }
  48. si no (Usuario0 == 0) // Publicar
  49. {
  50. while(User0 == 0);
  51. MQTT_STATE =MQTT_PKT_PUBLISH;
  52. }
  53. }
  54. }

The main part of the function, the general framework of the code is still very clear.

The main function is the initialization part before using the microcontroller and the W5100S.

Inside main is the basic TCP client program and key discovery. The different keys change the different states of MQTT_STATE.

Let’s explore the do_tcp_client() function in detail.

4.2.do_tcp_client() function

  1. uint8 buff [2048]; / * define un caché de 2 KB * /
  2. uint8 BD_TG_server_ip [4] = {163,177,150,12}; // dirección IP del servidor BD_TG
  3. uint16 BD_TG_server_port = 1883; // número de puerto del servidor BD_TG
  4. int MQTT_STATE = MQTT_PKT_CONNECT; // conectar
  5. const char * topics [] = {“test”}; // topic
  6. uint8 BD_TG_ping_pak [2] = {0xC0,0x00}; // Mensaje de latido
  7. unsigned char * data_ptr = NULL; // el puntero se refiere a nulo
  8. /**
  9. * @ breve función de demostración de bucle invertido del cliente TCP.
  10. * @ param Ninguno
  11. * @ return Ninguno
  12. */
  13. void do_tcp_client(void)
  14. {
  15. uint16 len=0;
  16. switch (getSn_SR (SOCK_TCPC)) / * Obtener el estado del socket * /
  17. {
  18. caso SOCK_CLOSED: / * el socket está cerrado * /
  19. socket(SOCK_TCPC,Sn_MR_TCP,local_port++,Sn_MR_ND);
  20. break;
  21. case SOCK_INIT: / * el socket está en estado de inicialización * /
  22. connect (SOCK_TCPC, BD_TG_server_ip, BD_TG_server_port); / * servidor de conexión de socket * /
  23. break;
  24. case SOCK_ESTABLISHED: / * el socket está en estado de establecimiento de conexión * /
  25. if(getSn_IR(SOCK_TCPC) & Sn_IR_CON)
  26. {
  27. setSn_IR (SOCK_TCPC, Sn_IR_CON); / * Borrar el bit de bandera de interrupción de recepción * /
  28. }
  29. len = getSn_RX_RSR (SOCK_TCPC); / * Definir len como la longitud de los datos recibidos * /
  30. if(len>0)
  31. {
  32. recv (SOCK_TCPC, buff, len); / * Recibir datos del servidor * /
  33. data_ptr = buff;
  34. if(data_ptr != NULL)
  35. BD_TG_RevPro(data_ptr);
  36. if(publish_buf[0] == 0x31)
  37. {
  38. LED_ALL_ON;
  39. }
  40. else if(publish_buf[0] == 0x32)
  41. {
  42. LED_ALL_OFF;
  43. }
  44. }
  45. switch(MQTT_STATE)
  46. {
  47. / * El protocolo MQTT está conectado a la plataforma de agente BD_TG * /
  48. case MQTT_PKT_CONNECT:
  49. BD_TG_DevLink();
  50. MQTT_STATE = MQTT_PKT_PINGREQ;
  51. break;
  52. / * Suscribirse a temas * /
  53. case MQTT_PKT_SUBSCRIBE:
  54. BD_TG_Subscribe(topics,1);
  55. MQTT_STATE = MQTT_PKT_PINGREQ;
  56. break;
  57. / * Mensaje de liberación de nivel Qos2 * /
  58. case MQTT_PKT_PUBLISH:
  59. BD_TG_Publish (* temas, “Prueba de publicación MQTT”); // Publicar un mensaje
  60. delay_ms (300); // Espera la respuesta de la plataforma
  61. / * Recibir PubRec enviado por la plataforma y responder a la respuesta de PubRel * /
  62. len=getSn_RX_RSR(SOCK_TCPC);
  63. recv(SOCK_TCPC,buff,len);
  64. data_ptr = buff;
  65. if(data_ptr != NULL)
  66. BD_TG_RevPro(data_ptr);
  67. delay_ms (100); // La respuesta de PubRel espera la respuesta de la plataforma
  68. len=getSn_RX_RSR(SOCK_TCPC);
  69. recv(SOCK_TCPC,buff,len);
  70. data_ptr = buff;
  71. if(data_ptr != NULL)
  72. BD_TG_RevPro(data_ptr);
  73. MQTT_STATE = MQTT_PKT_PINGREQ;
  74. / * Enviar una respuesta Ping una vez cada 120 segundos para mantener una conexión larga * /
  75. break;
  76. case MQTT_PKT_UNSUBSCRIBE:
  77. MQTT_UnSubscribe(topics,1);
  78. MQTT_STATE = MQTT_PKT_PINGREQ;
  79. break;
  80. case MQTT_PKT_PINGREQ:
  81. if(BD_TG_ping_time > 120)
  82. {
  83. send(SOCK_TCPC,BD_TG_ping_pak,2);
  84. BD_TG_ping_time = 0;
  85. }
  86. break;
  87. }
  88. break;
  89. case SOCK_CLOSE_WAIT: / * el socket está esperando para cerrarse * /
  90. close(SOCK_TCPC);
  91. break;
  92. }
  93. }

It is primarily a state machine write format. Basic TCP establishes a connection ( State SOCK_ESTABLISHED ), Depending on the state of the MQTT_STATE variable, it is considered that there are different cases, such as sending an MQTT connect message, MQTT subscribe message, MQTT message release, subscribe MQTT cancel message and an MQTT heartbeat message.

At first, it will first enter MQTT_PKT_CONNECT by default and send a connection packet. To connect to Baidu Cloud, the following parameters must be changed:

  1. #define PROID “7321ph4 / w5500” // Nombre completo del dispositivo
  2. #define AUTH_INFO “23h0wtzkmmti982q” // clave API
  3. #define DEVID “qwe” // identidad

The above information will be established by the customer when Baidu Cloud builds the device. We just need to copy the settings and replace the old strings.

And we The MQTT function is implemented, then the corresponding parameter characters of the following functions are replaced Alright

  1. const char * topics [] = {“test”}; // topic
  2. BD_TG_Subscribe (temas, 1); // Tema de suscripción, cantidad 1
  3. BD_TG_Publish (* temas, “Prueba de publicación MQTT”); // Temas publicados, mensajes publicados
  4. MQTT_UnSubscribe (temas, 1); // Temas no suscritos, cantidad 1

For basic subscription and MQTT publication, modify the above parameters to complete.

For other functions, you need to modify the corresponding parameters according to the function description in the package.


The above code is www.w5100s.com Within the 17.MQTT_BDTG routine, this routine has been tested and can be connected to the Baidu Tiangong Cloud platform normally to achieve MQTT subscription, publication and other related functions.

ucc_april1.png

Prepare

  • Software environment: Windows
  • Hardware environment: STM32F103 + W5500
  • Development tools: Keil uVision5
  • Debugging Tool: Serial Debugging Wizard
  • Connected platform: Baidu Yuntiangong ( https://cloud.baidu.com/

2. Introduction to MQTT

MQTT official website address: ( http://mqtt.org/

2.1 Characteristics of the MQTT protocol

MQTT is a client-server based message publish/subscribe transmission protocol. The MQTT protocol is lightweight, simple, open, and easy to implement. These characteristics make it applicable to a wide range. In many cases, including restricted environments such as machine-to-machine (M2M) communication and the Internet of Things (IoT). It has been widely used in satellite sensors to communicate with sensors, occasionally marking medical devices, smart homes, and some miniaturized devices.

The current version of the MQTT protocol is MQTT v3.1.1 released in 2014. In addition to the standard version, there is a simplified version of MQTT-SN. This protocol is primarily for embedded devices. These devices typically work on hundreds of TCP/IP networks, such as: ZigBee.

The MQTT protocol runs on TCP/IP or other network protocols and provides lossless and orderly bidirectional connections. Its features include:

  • The publish/subscribe message pattern used, which provides one-to-many message distribution to decouple applications.
  • Message transmission mechanism that protects the content of the payload.
  • There are three types of Quality of Service (QoS) for transmitting messages:
  • At most once, message loss or duplication can occur at this level, and message distribution depends on the underlying TCP/IP network. That is: <= 1
  • At most once, this level ensures that messages arrive, but messages may be duplicates. That is: >= 1
  • Only once, make sure that the message arrives only once. That is: = 1. This level can be used in some more demanding billing systems.

Minimize data transmission and protocol exchange (protocol header is only 2 bytes) to reduce network traffic

Notification mechanism

2.2 MQTT Protocol principle and implementation

Need to implement the MQTT protocol: client and server

There are three types of identities in the MQTT protocol: publisher, broker (server), and subscriber (subscribe). Among them, the publisher and subscriber of a message are both clients, the message broker is a server, and the publisher of a message can also be a subscriber.

Messages transmitted by MQTT are divided into two parts: subject and message payload.

The topic can be understood as the type of message. After a subscriber subscribes, they will receive the message content (payload) of the topic.

The payload, which can be understood as the content of the message, refers to the content that the subscriber specifically wants to use

2.3 Baidu Yuntiang MQTT connection steps

2.3.1. Enter the management console(Please login in advance);

23. 2. Select the “IoT Access IoT Hub” section

23. 3. Create a project

(The routine is used with data type equipment. For detailed information on data type and equipment type differences, please go to Baidu Yuntiangong for inquiries)

23. 4. After submitting the project, enter the project creation sub-user

Name: the username in the MQTT connection message

Identity: determine the way of access, you can use a key connection.

Strategy: Link permissions and corresponding themes.

Key: Keep it safe. This is the password for the connection. (Forgetting can be reset in the identity list)


After the project has been created successfully, register: name, identity, key. You can modify the corresponding string through the routine to connect the device you created.


3. Routine experimental phenomenon

First, we must look at the experimental phenomenon after the programming process.

Note: The test of receiving messages and posting messages to the topics after the W5100S subscribes to the topic is the establishment of the second device B in Baidu Cloud. Device B broadcasts a message and receives a topic message from the W5100S. This is to check if the W5100S can receive the subject message or send it.

3.1 The serial port prints the message “Connection successful” or “Specific reason for connection failure”.

3.2 Subscribe to topics

3.3. Receive topic messages

3.4. Post a topic message

4. Example code

Because the code involves the unpacking part of MQTT, the detailed explanation is too detailed.

Therefore, this discussion only discusses function functions and code frameworks, and does not disassemble function implementation too much.

4.1. The general framework flow of the main function

  1. #include <stdio.h>
  2. #include <string.h>
  3. #include “stm32f10x.h”
  4. #include “bsp_usart1.h”
  5. #include “bsp_fsmc.h”
  6. #include “bsp_spi.h”
  7. #include “w5100s.h”
  8. #include “W5100s_conf.h”
  9. #include “wizchip_conf.h”
  10. #include “w5100s_conf.h”
  11. #include “utility.h”
  12. #include “tcp_demo.h”
  13. #include “MqttKit.h”
  14. int main(void)
  15. {
  16. systick_init (72); // Inicializa el temporizador de tic
  17. USART1_Config (); // Inicializar USART1: 115200 @ 8-N-1
  18. reset_break_gpio_init (); // Restablecer e interrumpir la inicialización del pin
  19. #if (_WIZCHIP_IO_MODE_ == _WIZCHIP_IO_MODE_SPI_)
  20. spi_gpio_init (); // inicialización del pin SPI
  21. spiinitailize (); // inicialización de configuración SPI
  22. reg_wizchip_spi_cbfunc (spi_read_byte, spi_send_byte); // asignación de funciones de datos de lectura y escritura SPI
  23. reg_wizchip_cs_cbfunc (cs_low, cs_high); // asignación de función de control de selección de chip SPI
  24. #elif (_WIZCHIP_IO_MODE_ == _WIZCHIP_IO_MODE_BUS_INDIR_)
  25. FSMC_gpio_init (); // Inicialización de pin FSMC c
  26. FSMCInitialize (); // Inicialización de configuración de FSMC
  27. #endif
  28. printf (” r n Tecnología Wei Shi – agente oficial de WIZnet W5100S. Soporte técnico completo, gran ventaja de precio! r n r n”);
  29. reset_w5100s (); // Restablecimiento de hardware W5100S
  30. PHY_check (); // programa de verificación de cable de red
  31. set_w5100s_mac (); // Establecer dirección W5100SMAC
  32. set_w5100s_netinfo (); // Establecer parámetros de red W5100S
  33. wizchip_init (txsize, rxsize); // Inicializa el tamaño del búfer de envío y recepción de 4 sockets
  34. printf (” r n La configuración del parámetro de red W5100S está completa, utilice la dirección W5100SIP ‘PING’ de la computadora para verificar si la red es fluida”);
  35. while (1) / * función para ejecución de bucle * /
  36. {
  37. do_tcp_client (); // prueba de bucle invertido de datos del cliente TCP
  38. delay_ms(100);
  39. if (Usuario1 == 0) // Suscribirse
  40. {
  41. while(User1 == 0);
  42. MQTT_STATE = MQTT_PKT_SUBSCRIBE;
  43. }
  44. // if (KEY_5 == 0) // cancelar suscripción
  45. // {
  46. // MQTT_STATE = MQTT_PKT_UNSUBSCRIBE;
  47. // }
  48. si no (Usuario0 == 0) // Publicar
  49. {
  50. while(User0 == 0);
  51. MQTT_STATE =MQTT_PKT_PUBLISH;
  52. }
  53. }
  54. }

The main part of the function, the general framework of the code is still very clear.

The main function is the initialization part before using the microcontroller and the W5100S.

Inside main is the basic TCP client program and key discovery. The different keys change the different states of MQTT_STATE.

Let’s explore the do_tcp_client() function in detail.

4.2.do_tcp_client() function

  1. uint8 buff [2048]; / * define un caché de 2 KB * /
  2. uint8 BD_TG_server_ip [4] = {163,177,150,12}; // dirección IP del servidor BD_TG
  3. uint16 BD_TG_server_port = 1883; // número de puerto del servidor BD_TG
  4. int MQTT_STATE = MQTT_PKT_CONNECT; // conectar
  5. const char * topics [] = {“test”}; // topic
  6. uint8 BD_TG_ping_pak [2] = {0xC0,0x00}; // Mensaje de latido
  7. unsigned char * data_ptr = NULL; // el puntero se refiere a nulo
  8. /**
  9. * @ breve función de demostración de bucle invertido del cliente TCP.
  10. * @ param Ninguno
  11. * @ return Ninguno
  12. */
  13. void do_tcp_client(void)
  14. {
  15. uint16 len=0;
  16. switch (getSn_SR (SOCK_TCPC)) / * Obtener el estado del socket * /
  17. {
  18. caso SOCK_CLOSED: / * el socket está cerrado * /
  19. socket(SOCK_TCPC,Sn_MR_TCP,local_port++,Sn_MR_ND);
  20. break;
  21. case SOCK_INIT: / * el socket está en estado de inicialización * /
  22. connect (SOCK_TCPC, BD_TG_server_ip, BD_TG_server_port); / * servidor de conexión de socket * /
  23. break;
  24. case SOCK_ESTABLISHED: / * el socket está en estado de establecimiento de conexión * /
  25. if(getSn_IR(SOCK_TCPC) & Sn_IR_CON)
  26. {
  27. setSn_IR (SOCK_TCPC, Sn_IR_CON); / * Borrar el bit de bandera de interrupción de recepción * /
  28. }
  29. len = getSn_RX_RSR (SOCK_TCPC); / * Definir len como la longitud de los datos recibidos * /
  30. if(len>0)
  31. {
  32. recv (SOCK_TCPC, buff, len); / * Recibir datos del servidor * /
  33. data_ptr = buff;
  34. if(data_ptr != NULL)
  35. BD_TG_RevPro(data_ptr);
  36. if(publish_buf[0] == 0x31)
  37. {
  38. LED_ALL_ON;
  39. }
  40. else if(publish_buf[0] == 0x32)
  41. {
  42. LED_ALL_OFF;
  43. }
  44. }
  45. switch(MQTT_STATE)
  46. {
  47. / * El protocolo MQTT está conectado a la plataforma de agente BD_TG * /
  48. case MQTT_PKT_CONNECT:
  49. BD_TG_DevLink();
  50. MQTT_STATE = MQTT_PKT_PINGREQ;
  51. break;
  52. / * Suscribirse a temas * /
  53. case MQTT_PKT_SUBSCRIBE:
  54. BD_TG_Subscribe(topics,1);
  55. MQTT_STATE = MQTT_PKT_PINGREQ;
  56. break;
  57. / * Mensaje de liberación de nivel Qos2 * /
  58. case MQTT_PKT_PUBLISH:
  59. BD_TG_Publish (* temas, “Prueba de publicación MQTT”); // Publicar un mensaje
  60. delay_ms (300); // Espera la respuesta de la plataforma
  61. / * Recibir PubRec enviado por la plataforma y responder a la respuesta de PubRel * /
  62. len=getSn_RX_RSR(SOCK_TCPC);
  63. recv(SOCK_TCPC,buff,len);
  64. data_ptr = buff;
  65. if(data_ptr != NULL)
  66. BD_TG_RevPro(data_ptr);
  67. delay_ms (100); // La respuesta de PubRel espera la respuesta de la plataforma
  68. len=getSn_RX_RSR(SOCK_TCPC);
  69. recv(SOCK_TCPC,buff,len);
  70. data_ptr = buff;
  71. if(data_ptr != NULL)
  72. BD_TG_RevPro(data_ptr);
  73. MQTT_STATE = MQTT_PKT_PINGREQ;
  74. / * Enviar una respuesta Ping una vez cada 120 segundos para mantener una conexión larga * /
  75. break;
  76. case MQTT_PKT_UNSUBSCRIBE:
  77. MQTT_UnSubscribe(topics,1);
  78. MQTT_STATE = MQTT_PKT_PINGREQ;
  79. break;
  80. case MQTT_PKT_PINGREQ:
  81. if(BD_TG_ping_time > 120)
  82. {
  83. send(SOCK_TCPC,BD_TG_ping_pak,2);
  84. BD_TG_ping_time = 0;
  85. }
  86. break;
  87. }
  88. break;
  89. case SOCK_CLOSE_WAIT: / * el socket está esperando para cerrarse * /
  90. close(SOCK_TCPC);
  91. break;
  92. }
  93. }

It is primarily a state machine write format. Basic TCP establishes a connection ( State SOCK_ESTABLISHED ), Depending on the state of the MQTT_STATE variable, it is considered that there are different cases, such as sending an MQTT connect message, MQTT subscribe message, MQTT message release, subscribe MQTT cancel message and an MQTT heartbeat message.

At first, it will first enter MQTT_PKT_CONNECT by default and send a connection packet. To connect to Baidu Cloud, the following parameters must be changed:

  1. #define PROID “7321ph4 / w5500” // Nombre completo del dispositivo
  2. #define AUTH_INFO “23h0wtzkmmti982q” // clave API
  3. #define DEVID “qwe” // identidad

The above information will be established by the customer when Baidu Cloud builds the device. We just need to copy the settings and replace the old strings.

And we The MQTT function is implemented, then the corresponding parameter characters of the following functions are replaced Alright

  1. const char * topics [] = {“test”}; // topic
  2. BD_TG_Subscribe (temas, 1); // Tema de suscripción, cantidad 1
  3. BD_TG_Publish (* temas, “Prueba de publicación MQTT”); // Temas publicados, mensajes publicados
  4. MQTT_UnSubscribe (temas, 1); // Temas no suscritos, cantidad 1

For basic subscription and MQTT publication, modify the above parameters to complete.

For other functions, you need to modify the corresponding parameters according to the function description in the package.


The above code is www.w5100s.com Within the 17.MQTT_BDTG routine, this routine has been tested and can be connected to the Baidu Tiangong Cloud platform normally to achieve MQTT subscription, publication and other related functions.

documents
Code
Project code

COMMENTS

Please Login to comment
  Subscribe  
Notify of
POSTED BY
TAGS
Reusable S/W