Skip to content

W5100S??MQTT connects to Baidu Tiangong cloud platform

W5100S??MQTT connects to Baidu Tiangong cloud platform

teju

Published March 02, 2022

57 UCC

16 VAR

Components

Hardware components

x 1


Project description

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); 2.3 Baidu Yuntiang MQTT connection steps 23.?2. Select the "IoT Access IoT Hub" section 2.3 Baidu Yuntiang MQTT connection steps 23.?3. Create a project 2.3 Baidu Yuntiang MQTT connection steps 2.3 Baidu Yuntiang MQTT connection steps (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 2.3 Baidu Yuntiang MQTT connection steps 2.3 Baidu Yuntiang MQTT connection steps Name: the username in the MQTT connection message 2.3 Baidu Yuntiang MQTT connection steps Identity: determine the way of access, you can use a key connection. 2.3 Baidu Yuntiang MQTT connection steps Strategy: Link permissions and corresponding themes. 2.3 Baidu Yuntiang MQTT connection steps 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". Note: The test of receiving messages and posting messages to the topics after the W5100S subscribes to the topic is the estab 3.2 Subscribe to topics Note: The test of receiving messages and posting messages to the topics after the W5100S subscribes to the topic is the estab 3.3.?Receive topic messages Note: The test of receiving messages and posting messages to the topics after the W5100S subscribes to the topic is the estab 3.4.?Post a topic message Note: The test of receiving messages and posting messages to the topics after the W5100S subscribes to the topic is the estab

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 inicializacion del pin
  19. #if (_WIZCHIP_IO_MODE_ == _WIZCHIP_IO_MODE_SPI_)
  20. spi_gpio_init (); // inicializacion del pin SPI
  21. spiinitailize (); // inicializacion de configuracion SPI
  22. reg_wizchip_spi_cbfunc (spi_read_byte, spi_send_byte); // asignacion de funciones de datos de lectura y escritura SPI
  23. reg_wizchip_cs_cbfunc (cs_low, cs_high); // asignacion de funcion de control de seleccion de chip SPI
  24. #elif (_WIZCHIP_IO_MODE_ == _WIZCHIP_IO_MODE_BUS_INDIR_)
  25. FSMC_gpio_init (); // Inicializacion de pin FSMC c
  26. FSMCInitialize (); // Inicializacion de configuracion de FSMC
  27. #endif
  28. printf (" r n Tecnologia Wei Shi - agente oficial de WIZnet W5100S. Soporte tecnico completo, gran ventaja de precio! r n r n");
  29. reset_w5100s (); // Restablecimiento de hardware W5100S
  30. PHY_check (); // programa de verificacion de cable de red
  31. set_w5100s_mac (); // Establecer direccion W5100SMAC
  32. set_w5100s_netinfo (); // Establecer parametros de red W5100S
  33. wizchip_init (txsize, rxsize); // Inicializa el tamano del bufer de envio y recepcion de 4 sockets
  34. printf (" r n La configuracion del parametro de red W5100S esta completa, utilice la direccion W5100SIP 'PING' de la computadora para verificar si la red es fluida");
  35. while (1) / * funcion para ejecucion 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 suscripcion
  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 cache de 2 KB * /
  2. uint8 BD_TG_server_ip [4] = {163,177,150,12}; // direccion IP del servidor BD_TG
  3. uint16 BD_TG_server_port = 1883; // numero 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 funcion de demostracion 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 esta cerrado * /
  19. socket(SOCK_TCPC,Sn_MR_TCP,local_port++,Sn_MR_ND);
  20. break;
  21. case SOCK_INIT: / * el socket esta en estado de inicializacion * /
  22. connect (SOCK_TCPC, BD_TG_server_ip, BD_TG_server_port); / * servidor de conexion de socket * /
  23. break;
  24. case SOCK_ESTABLISHED: / * el socket esta en estado de establecimiento de conexion * /
  25. if(getSn_IR(SOCK_TCPC) & Sn_IR_CON)
  26. {
  27. setSn_IR (SOCK_TCPC, Sn_IR_CON); / * Borrar el bit de bandera de interrupcion de recepcion * /
  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 esta 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 liberacion de nivel Qos2 * /
  58. case MQTT_PKT_PUBLISH:
  59. BD_TG_Publish (* temas, "Prueba de publicacion 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 conexion 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 esta 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 suscripcion, cantidad 1
  3. BD_TG_Publish (* temas, "Prueba de publicacion 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

Comments

Comments