4.3.1 Execution

main.c – Initialize the Wi-Fi module and test the TCP client.

  1. Code summary:
    • Configure the network parameters in main.h.
      /** Wi-Fi Settings */
      #define MAIN_WLAN_SSID                    "DEMO_AP" /**< Destination SSID */
      #define MAIN_WLAN_AUTH                    M2M_WIFI_SEC_WPA_PSK /**< Security manner */
      #define MAIN_WLAN_PSK                     "12345678" /**< Password for Destination SSID */
      #define MAIN_WIFI_M2M_PRODUCT_NAME        "NMCTemp"
      #define MAIN_WIFI_M2M_SERVER_IP           0xc0a80164 //0xFFFFFFFF /* 255.255.255.255 */
      #define MAIN_WIFI_M2M_SERVER_PORT         (6666)
      #define MAIN_WIFI_M2M_REPORT_INTERVAL     (1000)
    • Initialize the socket module and register the socket callback function.
      /* Initialize socket address structure. */
      addr.sin_family = AF_INET;
      addr.sin_port = _htons(MAIN_WIFI_M2M_SERVER_PORT);
      addr.sin_addr.s_addr = _htonl(MAIN_WIFI_M2M_SERVER_IP);
      /* Initialize socket module */
      socketInit();
      registerSocketCallback(socket_cb, NULL);
      Note: The Server IP address in this example is 0xc0a80164, which translates to 192.168.1.100.
    • Connect to the AP.
      /* Connect to router. */
      m2m_wifi_connect((char *)MAIN_WLAN_SSID, sizeof(MAIN_WLAN_SSID),
              MAIN_WLAN_AUTH, (char *)MAIN_WLAN_PSK, M2M_WIFI_CH_ALL);
    • After the device is connected to the AP, create a TCP client socket and connect to the server in the main loop.
      /* Open client socket. */
      if (tcp_client_socket < 0) {
          if ((tcp_client_socket = socket(AF_INET, SOCK_STREAM, 0)) < 0) {
          printf("main: failed to create TCP client socket error!\r\n");
          continue;
      }
      /* Connect server */
      ret = connect(tcp_client_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in));
    • Requests to connect, send and recv can be executed sequentially in the socket_cb() function. Also, while using the send operation, the maximum data that can be transmitted using socket API send() is 1400 bytes.
      static void socket_cb(SOCKET sock, uint8_t u8Msg, void *pvMsg)
      {
      ...
      case SOCKET_MSG_CONNECT:
      	{
      		if (pstrConnect && pstrConnect->s8Error >= 0)
      			send(tcp_client_socket, &msg_wifi_product, ...);
      	}
      	...
      	case SOCKET_MSG_SEND:
      	{
      		recv(tcp_client_socket, gau8SocketTestBuffer, ...);
      	}
      	...
      	case SOCKET_MSG_RECV:
      	{
      		tstrSocketRecvMsg *pstrRecv = (tstrSocketRecvMsg *)pvMsg;
      		if (pstrRecv && pstrRecv->s16BufferSize > 0) {
      			printf("socket_cb: recv success!\r\n");
      			printf("TCP Client Test Complete!\r\n");
      		}
      	}
      
  2. Build the program and download it into the board.
  3. Start the application.