4.2.1 Execution

main.c - Initialize the Wi-Fi module and test with the UDP 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           0xFFFFFFFF /* 255.255.255.255 */
      #define MAIN_WIFI_M2M_SERVER_PORT         (6666)
      #define MAIN_WIFI_M2M_REPORT_INTERVAL     (1000)
    • Initialize the socket module and create the UDP server socket.
      /* 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);
    • 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 an RX socket and bind it in the main loop.
      
      if (rx_socket < 0) {
          if ((rx_socket = socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
              printf("main : failed to create RX UDP Client socket error!\r\n");
              continue;
          }
          /* Socket bind */
          bind(rx_socket, (struct sockaddr *)&addr, sizeof(struct sockaddr_in));
      }
    • In the socket_cb() function, prepare a buffer to receive data.
      static void socket_cb(SOCKET sock, uint8_t u8Msg, void *pvMsg)
      {
          if (u8Msg == SOCKET_MSG_BIND) {
      	recvfrom(sock, gau8SocketTestBuffer, MAIN_WIFI_M2M_BUFFER_SIZE, 0);
    • You can receive data in the socket_cb() function with the SOCKET_MSG_RECVFROM message when a client device sends data. (Use “UDP Client” example.)
      static void socket_cb(SOCKET sock, uint8_t u8Msg, void *pvMsg)
      {
          ...
          } else if (u8Msg == SOCKET_MSG_RECVFROM) {
          tstrSocketRecvMsg *pstrRx = (tstrSocketRecvMsg *)pvMsg;
          if (pstrRx->pu8Buffer && pstrRx->s16BufferSize) {
              printf("socket_cb: received app message.(%u)\r\n", packetCnt);
      	/* Prepare next buffer reception. */
      	recvfrom(sock, gau8SocketTestBuffer, MAIN_WIFI_M2M_BUFFER_SIZE, 0);
  2. Build the program and download it into the board.
  3. Start the application.