Microchip® Advanced Software Framework

 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Groups Pages
Functions

         The function performs the necessary initializations for the socket library through the following steps:

Functions

NMI_API sint8 accept (SOCKET sock, struct sockaddr *addr, uint8 *addrlen)
 
NMI_API sint8 bind (SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen)
 
NMI_API sint8 close (SOCKET sock)
 Synchronous close function, releases all the socket assigned resources. More...
 
NMI_API sint8 connect (SOCKET sock, struct sockaddr *pstrAddr, uint8 u8AddrLen)
 
sint8 get_alpn_index (SOCKET sock)
 
sint8 get_error_detail (SOCKET sock, tstrSockErr *pstrErr)
 
NMI_API sint8 gethostbyname (uint8 *pcHostName)
 
NMI_API sint8 getsockopt (SOCKET sock, uint8 u8Level, uint8 u8OptName, const void *pvOptValue, uint8 *pu8OptLen)
 Get socket options retrieves. This Function isn't implemented yet but this is the form that will be released later. More...
 
NMI_API uint8 IsSocketReady (void)
 
NMI_API sint8 listen (SOCKET sock, uint8 backlog)
 
NMI_API sint8 m2m_ping_req (uint32 u32DstIP, uint8 u8TTL, tpfPingCb fpPingCb)
 The function request to send ping request to the given IP Address. More...
 
NMI_API uint32 nmi_inet_addr (char *pcIpAddr)
 
NMI_API sint16 recv (SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec)
 
NMI_API sint16 recvfrom (SOCKET sock, void *pvRecvBuf, uint16 u16BufLen, uint32 u32Timeoutmsec)
 
NMI_API void registerSocketCallback (tpfAppSocketCb socket_cb, tpfAppResolveCb resolve_cb)
 
sint8 secure (SOCKET sock)
 
NMI_API sint16 send (SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 u16Flags)
 
NMI_API sint16 sendto (SOCKET sock, void *pvSendBuffer, uint16 u16SendLength, uint16 flags, struct sockaddr *pstrDestAddr, uint8 u8AddrLen)
 Asynchronous sending function, used to send data on a UDP socket. Called by the application code when there is data required to be sent on a UDP socket. More...
 
sint8 set_alpn_list (SOCKET sock, const char *pcProtocolList)
 
NMI_API sint8 setsockopt (SOCKET socket, uint8 u8Level, uint8 option_name, const void *option_value, uint16 u16OptionLen)
 
NMI_API SOCKET socket (uint16 u16Domain, uint8 u8Type, uint8 u8Config)
 
NMI_API void socketDeinit (void)
 Socket Layer De-initialization. More...
 
NMI_API void socketInit (void)
 

NMI_API sint8 accept ( SOCKET  sock,
struct sockaddr addr,
uint8 addrlen 
)
The function has no current implementation. An empty declaration is used to prevent errors when legacy application code is used.
As it has no effect, it can be safely removed from any application using it.
Parameters
[in]sockSocket ID, must hold a non negative value. A negative value will return a socket error SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
[in]addrNot used in the current implementation.
[in]addrlenNot used in the current implementation.
Returns
The function returns ZERO for successful operations and a negative value otherwise. The possible error values are:

References MAX_SOCKET, SOCK_ERR_INVALID_ARG, and SOCK_ERR_NO_ERROR.

Referenced by prov_socket_cb().

NMI_API sint8 bind ( SOCKET  sock,
struct sockaddr pstrAddr,
uint8  u8AddrLen 
)
Asynchronous bind function associates the provided address and local port to the socket.
The function can be used with both TCP and UDP sockets. It is mandatory to call the @ref bind function before starting any UDP or TCP server operation.
Upon socket bind completion, the application will receive a @ref SOCKET_MSG_BIND message in the socket callback.
Parameters
[in]sockSocket ID, must hold a non negative value. A negative value will return a socket error SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
[in]pstrAddrPointer to socket address structure "sockaddr_in" sockaddr_in
[in]u8AddrLenSize of the given socket address structure in bytes.
Precondition
The socket function must be called to allocate a socket before passing the socket ID to the bind function.
See Also
socket
connect
listen
accept
recv
recvfrom
send
sendto
Returns
The function returns ZERO for successful operations and a negative value otherwise. The possible error values are:

Example

This example demonstrates the call of the bind socket operation after a successful socket operation.

struct sockaddr_in addr;
SOCKET udpServerSocket =-1;
int ret = -1;
if(udpServerSocket == -1)
{
if(udpServerSocket >= 0)
{
addr.sin_family = AF_INET;
addr.sin_port = _htons(UDP_SERVER_PORT);
addr.sin_addr.s_addr = 0;
ret = bind(udpServerSocket,(struct sockaddr*)&addr,sizeof(addr));
if(ret == 0)
printf("Bind success!\n");
else
{
printf("Bind Failed. Error code = %d\n",ret);
close(udpServerSocket);
}
else
{
printf("UDP Server Socket Creation Failed\n");
return;
}
}

References m2m_memcpy(), MAX_SOCKET, NULL, tstrBindCmd::sock, SOCK_ERR_INVALID, SOCK_ERR_INVALID_ARG, SOCK_ERR_NO_ERROR, SOCKET_CMD_BIND, SOCKET_REQUEST, tstrBindCmd::strAddr, tstrSockAddr::u16Family, tstrSockAddr::u16Port, tstrSocket::u16SessionID, tstrBindCmd::u16SessionID, and tstrSockAddr::u32IPAddr.

Referenced by wifi_ap_provision().

NMI_API sint8 close ( SOCKET  sock)

Synchronous close function, releases all the socket assigned resources.

Parameters
[in]sockSocket ID, must hold a non negative value. A negative value will return a socket error SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
Precondition
Sockets must be initialized through the call of the socketInit function. close is called only for valid socket identifiers created through the socket function.
Warning
If close is called while there are still pending messages (sent or received ) they will be discarded.
See Also
socketInit, socket
Returns
The function returned SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise.

References M2M_INFO, m2m_memset(), MAX_SOCKET, NULL, tstrCloseCmd::sock, SOCK_ERR_INVALID, SOCK_ERR_INVALID_ARG, SOCK_ERR_NO_ERROR, SOCKET_CMD_CLOSE, SOCKET_CMD_SSL_CLOSE, SOCKET_REQUEST, SSL_FLAGS_ACTIVE, tstrCloseCmd::u16SessionID, and tstrSocket::u16SessionID.

Referenced by wifi_ap_provision().

NMI_API sint8 connect ( SOCKET  sock,
struct sockaddr pstrAddr,
uint8  u8AddrLen 
)
Establishes a TCP connection with a remote server.
The asynchronous connect function must be called after receiving a valid socket ID from the @ref socket function.
The application socket callback function is notified of the result of the connection attempt through the event @ref SOCKET_MSG_CONNECT,
along with a structure @ref tstrSocketConnectMsg.
If socket connection fails, the application should call @ref close().
A successful connect means the TCP session is active. The application is then required to make a call to the @ref recv function
to receive any packets transmitted by the remote server, unless the application is interrupted by a notification of socket connection
termination.
Parameters
[in]sockSocket ID, must hold a non negative value. A negative value will return a socket error SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
[in]pstrAddrAddress of the remote server.
[in]u8AddrLenSize of the given socket address structure in bytes. Not currently used, implemented for BSD compatibility only.
Precondition
The socket function must be called to allocate a TCP socket before passing the socket ID to the bind function. If the socket is not bound, you do NOT have to call bind before the "connect" function.
See Also
socket recv send close
Returns
The function returns ZERO for successful operations and a negative value otherwise. The possible error values are:

Example

The example demonstrates a TCP application, showing how the asynchronous call to the connect function is made through the main function and how the callback function handles the SOCKET_MSG_CONNECT event.

Main Function

struct sockaddr_in Serv_Addr;
SOCKET TcpClientSocket =-1;
int ret = -1
Serv_Addr.sin_family = AF_INET;
Serv_Addr.sin_port = _htons(1234);
Serv_Addr.sin_addr.s_addr = inet_addr(SERVER);
printf("Connected to server via socket %u\n",TcpClientSocket);
do
{
ret = connect(TcpClientSocket,(sockaddr_in*)&Serv_Addr,sizeof(Serv_Addr));
if(ret != 0)
{
printf("Connection Error\n");
}
else
{
printf("Connection successful.\n");
break;
}
}while(1)

Socket Callback

if(u8Msg == SOCKET_MSG_CONNECT)
{
if(pstrConnect->s8Error == 0)
{
uint8 acBuffer[GROWL_MSG_SIZE];
uint16 u16MsgSize;
printf("Connect success!\n");
u16MsgSize = FormatMsg(u8ClientID, acBuffer);
send(sock, acBuffer, u16MsgSize, 0);
recv(pstrNotification->Socket, (void*)au8Msg,GROWL_DESCRIPTION_MAX_LENGTH, GROWL_RX_TIMEOUT);
u8Retry = GROWL_CONNECT_RETRY;
}
else
{
M2M_DBG("Connection Failed, Error: %d\n",pstrConnect->s8Error");
close(pstrNotification->Socket);
}
}

References m2m_memcpy(), MAX_SOCKET, NULL, tstrConnectCmd::sock, SOCK_ERR_INVALID, SOCK_ERR_INVALID_ARG, SOCK_ERR_NO_ERROR, SOCKET_CMD_CONNECT, SOCKET_CMD_SSL_CONNECT, SOCKET_REQUEST, SSL_FLAGS_ACTIVE, tstrConnectCmd::strAddr, tstrSocket::u16SessionID, tstrConnectCmd::u16SessionID, tstrSocket::u8SSLFlags, and tstrConnectCmd::u8SslFlags.

sint8 get_alpn_index ( SOCKET  sock)

This function gets the index of the protocol negotiated via ALPN. It should be called when a SSL socket connection succeeds, in order to determine which application-layer protocol must be used.

Parameters
[in]sockSocket ID obtained by a call to socket. This is the SSL socket to which the ALPN applies.
Returns
The function returns:
  • >0: 1-based index of negotiated protocol with respect to the list previously provided to set_alpn_list.
  • 0: No negotiation occurred (eg TLS peer did not support ALPN).
  • <0: Invalid parameters (socket is not in use, or not an SSL socket).
See Also
Example

References SOCK_ERR_INVALID_ARG, SSL_FLAGS_ACTIVE, TCP_SOCK_MAX, and tstrSocket::u8AlpnStatus.

sint8 get_error_detail ( SOCKET  sock,
tstrSockErr pstrErr 
)

This function gets detail about a socket failure. The application can call this when notified of a socket failure via SOCKET_MSG_CONNECT or SOCKET_MSG_RECV. If used, it must be called before close.

Parameters
[in]sockSocket ID obtained by a call to socket.
[out]pstrErrPointer to structure to be populated with the details of the socket failure.
Returns
The function returns SOCK_ERR_NO_ERROR if the request is successful. In this case pstrErr has been populated. The function returns a negative value if the request is not successful. In this case pstrErr has not been populated.

References tstrSockErr::enuErrSource, NULL, SOCK_ERR_INVALID_ARG, SOCK_ERR_NO_ERROR, TCP_SOCK_MAX, tstrSocket::u8ErrCode, tstrSockErr::u8ErrCode, and tstrSocket::u8ErrSource.

NMI_API sint8 gethostbyname ( uint8 pcHostName)
         Asynchronous DNS resolving function. This function uses DNS to resolve a domain name to the corresponding IP address.
         A call to this function will cause a DNS request to be sent and the response will be delivered to the DNS callback
         function registered using registerSocketCallback.
Parameters
[in]pcHostNameNULL terminated string containing the domain name for the remote host. Its size must not exceed HOSTNAME_MAX_SIZE.
See Also
registerSocketCallback
Warning
Successful completion of a call to gethostbyname() does not guarantee success of the DNS request, a negative return value indicates only locally-detected errors
Returns

References HOSTNAME_MAX_SIZE, M2M_REQ_DATA_PKT, m2m_strlen(), NULL, SOCK_ERR_INVALID, SOCK_ERR_INVALID_ARG, SOCK_ERR_NO_ERROR, SOCKET_CMD_DNS_RESOLVE, and SOCKET_REQUEST.

NMI_API sint8 getsockopt ( SOCKET  sock,
uint8  u8Level,
uint8  u8OptName,
const void *  pvOptValue,
uint8 pu8OptLen 
)

Get socket options retrieves. This Function isn't implemented yet but this is the form that will be released later.

Parameters
[in]sockSocket Identifier.
[in]u8LevelThe protocol level of the option.
[in]u8OptNameThe u8OptName argument specifies a single option to get.
[out]pvOptValueThe pvOptValue argument contains pointer to a buffer containing the option value.
[out]pu8OptLenOption value buffer length.
Returns
The function shall return ZERO for successful operation and a negative value otherwise.

References SOCK_ERR_INVALID_ARG.

NMI_API uint8 IsSocketReady ( void  )
See Also
socketInit socketDeinit
Returns
If the socket has been initialized and is ready. Should return 1 after socketInit and 0 after socketDeinit

References gbSocketInit.

NMI_API sint8 listen ( SOCKET  sock,
uint8  backlog 
)
After successfully binding a socket to an IP address and port on the system, start listening passively for incoming connections.
   The socket must be bound on a local port or the listen operation fails.
   Upon the call to the asynchronous listen function, response is received through the event @ref SOCKET_MSG_LISTEN
in the socket callback.

A successful listen means the TCP server operation is active. If a connection is accepted, then the application socket callback function is
notified with the new connected socket through the event @ref SOCKET_MSG_ACCEPT. Hence there is no need to call the @ref accept function
after calling @ref listen.

After a connection is accepted, the user is then required to call @ref recv to receive any packets transmitted by the remote host or to receive notification of socket connection
termination.
Parameters
[in]sockSocket ID, must hold a non negative value. A negative value will return a socket error SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
[in]backlogNot used by the current implementation.
Precondition
The bind function must be called to assign the port number and IP address to the socket before the listen operation.
See Also
bind
accept
recv
recvfrom
send
sendto
Returns
The function returns ZERO for successful operations and a negative value otherwise. The possible error values are:

Example

This example demonstrates the call of the listen socket operation after a successful socket operation.

static void TCP_Socketcallback(SOCKET sock, uint8 u8Msg, void * pvMsg)
{
int ret =-1;
switch(u8Msg)
{
{
tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg;
if(pstrBind != NULL)
{
if(pstrBind->status == 0)
{
ret = listen(sock, 0);
if(ret <0)
printf("Listen failure! Error = %d\n",ret);
}
else
{
M2M_ERR("bind Failure!\n");
close(sock);
}
}
}
break;
{
if(pstrListen != NULL)
{
if(pstrListen->status == 0)
{
ret = accept(sock,NULL,0);
}
else
{
M2M_ERR("listen Failure!\n");
close(sock);
}
}
}
break;
{
if(pstrAccept->sock >= 0)
{
TcpNotificationSocket = pstrAccept->sock;
recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT);
}
else
{
M2M_ERR("accept failure\n");
}
}
break;
default:
break;
}
}

References MAX_SOCKET, NULL, tstrListenCmd::sock, SOCK_ERR_INVALID, SOCK_ERR_INVALID_ARG, SOCK_ERR_NO_ERROR, SOCKET_CMD_LISTEN, SOCKET_REQUEST, tstrSocket::u16SessionID, tstrListenCmd::u16SessionID, and tstrListenCmd::u8BackLog.

Referenced by prov_socket_cb().

NMI_API sint8 m2m_ping_req ( uint32  u32DstIP,
uint8  u8TTL,
tpfPingCb  fpPingCb 
)

The function request to send ping request to the given IP Address.

Parameters
[in]u32DstIPTarget Destination IP Address for the ping request. It must be represented in Network byte order. The function nmi_inet_addr could be used to translate the dotted decimal notation IP to its Network bytes order integer representative.
[in]u8TTLIP TTL value for the ping request. If set to ZERO, the default value SHALL be used.
[in]fpPingCbCallback will be called to deliver the ping statistics.
Warning
This API should only be used to request one ping at a time; calling this API invalidates callbacks for previous ping requests.
See Also
nmi_inet_addr
Returns
The function returns M2M_SUCCESS for successful operations and a negative value otherwise.

References gfpPingCb, gu32PingId, M2M_ERR_INVALID_ARG, NULL, SOCKET_CMD_PING, SOCKET_REQUEST, tstrPingCmd::u16PingCount, tstrPingCmd::u32CmdPrivate, tstrPingCmd::u32DestIPAddr, and tstrPingCmd::u8TTL.

NMI_API uint32 nmi_inet_addr ( char *  pcIpAddr)
         Synchronous function which returns a BSD socket compliant Internet Protocol (IPv4) socket address.
         This IPv4 address in the input string parameter could either be specified as a hostname, or as a numeric string
         representation like n.n.n.n known as the IPv4 dotted-decimal format (i.e. "192.168.10.1").
         This function is used whenever an ip address needs to be set in the proper format
         (i.e. for the @ref tstrM2MIPConfig structure).
Parameters
[in]pcIpAddrA null terminated string containing the IP address in IPv4 dotted-decimal address.
Returns
Unsigned 32-bit integer representing the IP address in Network byte order (eg. "192.168.10.1" will be expressed as 0x010AA8C0).

References m2m_memcpy().

NMI_API sint16 recv ( SOCKET  sock,
void *  pvRecvBuf,
uint16  u16BufLen,
uint32  u32Timeoutmsec 
)
An asynchronous receive function, used to retrieve data from a TCP stream.
Before calling the recv function, a successful socket connection status must have been received through any of the two socket events
[SOCKET_MSG_CONNECT] or [SOCKET_MSG_ACCEPT], from the socket callback. Hence, indicating that the socket is already connected to a remote
host.
The application receives the required data in response to this asynchronous call through the reception of the event @ref SOCKET_MSG_RECV in the
socket callback.

Receiving the SOCKET_MSG_RECV message in the callback with zero or negative buffer length indicates the following:
- @ref SOCK_ERR_NO_ERROR        : Socket connection closed. The application should now call @ref close().
- @ref SOCK_ERR_CONN_ABORTED    : Socket connection aborted. The application should now call @ref close().
- @ref SOCK_ERR_TIMEOUT         : Socket receive timed out. The socket connection remains open.
Parameters
[in]sockSocket ID, must hold a non negative value. A negative value will return a socket error SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
[in]pvRecvBufPointer to a buffer that will hold the received data. The buffer is used in the recv callback to deliver the received data to the caller. The buffer must be resident in memory (heap or global buffer).
[in]u16BufLenThe buffer size in bytes.
[in]u32TimeoutmsecTimeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout will be set to infinite (the recv function waits forever). If the timeout period is elapsed with no data received, the socket will get a timeout error.
Precondition
  • The socket function must be called to allocate a TCP socket before passing the socket ID to the recv function.
  • The socket in a connected state is expected to receive data through the socket interface.
See Also
socket
connect
bind
listen
recvfrom
close
Returns
The function returns ZERO for successful operations and a negative value otherwise. The possible error values are:

Example

The example demonstrates a code snippet for the calling of the recv function in the socket callback upon notification of the accept or connect events, and the parsing of the received data when the SOCKET_MSG_RECV event is received.

switch(u8Msg)
{
{
if(pstrAccept->sock >= 0)
{
recv(pstrAccept->sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT);
}
else
{
M2M_ERR("accept\n");
}
}
break;
{
if(pstrRx->s16BufferSize > 0)
{
recv(sock,gau8RxBuffer,sizeof(gau8RxBuffer),TEST_RECV_TIMEOUT);
}
else
{
printf("Socket recv Error: %d\n",pstrRx->s16BufferSize);
close(sock);
}
}
break;
default:
break;
}

References tstrSocket::bIsRecvPending, MAX_SOCKET, NM_BSP_B_L_32, NULL, tstrSocket::pu8UserBuffer, tstrRecvCmd::sock, SOCK_ERR_BUFFER_FULL, SOCK_ERR_INVALID_ARG, SOCK_ERR_NO_ERROR, SOCKET_CMD_RECV, SOCKET_CMD_SSL_RECV, SOCKET_REQUEST, SSL_FLAGS_ACTIVE, SSL_FLAGS_DELAY, tstrRecvCmd::u16BufLen, tstrSocket::u16SessionID, tstrRecvCmd::u16SessionID, tstrSocket::u16UserBufferSize, tstrRecvCmd::u32Timeoutmsec, and tstrSocket::u8SSLFlags.

Referenced by prov_socket_cb().

NMI_API sint16 recvfrom ( SOCKET  sock,
void *  pvRecvBuf,
uint16  u16BufLen,
uint32  u32Timeoutmsec 
)
Receives data from a UDP Socket.

The asynchronous recvfrom function is used to retrieve data from a UDP socket. The socket must already be bound to
a local port before a call to the recvfrom function is made (i.e message @ref SOCKET_MSG_BIND is received
with successful status in the socket callback).

Upon calling the recvfrom function with a successful return code, the application is expected to receive a notification
in the socket callback whenever a message is received through the @ref SOCKET_MSG_RECVFROM event.

Receiving the SOCKET_MSG_RECVFROM message in the callback with zero, indicates that the socket is closed.
Whereby a negative buffer length indicates one of the socket error codes such as socket timeout error @ref SOCK_ERR_TIMEOUT

The recvfrom callback can also be used to show the IP address of the remote host that sent the frame by
using the "strRemoteAddr" element in the @ref tstrSocketRecvMsg structure. (refer to the code example)
Parameters
[in]sockSocket ID, must hold a non negative value. A negative value will return a socket error SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
[in]pvRecvBufPointer to a buffer that will hold the received data. The buffer shall be used in the recv callback to deliver the received data to the caller. The buffer must be resident in memory (heap or global buffer).
[in]u16BufLenThe buffer size in bytes.
[in]u32TimeoutSecondsTimeout for the recv function in milli-seconds. If the value is set to ZERO, the timeout will be set to infinite (the recv function waits forever).
Precondition
  • The socket function must be called to allocate a TCP socket before passing the socket ID to the recv function.
  • The socket corresponding to the socket ID must be successfully bound to a local port through the call to a bind function.
See Also
socket bind close
Returns
The function returns ZERO for successful operations and a negative value otherwise. The possible error values are:

Example

The example demonstrates a code snippet for the calling of the recvfrom function in the socket callback upon notification of a successful bind event, and the parsing of the received data when the SOCKET_MSG_RECVFROM event is received.

switch(u8Msg)
{
{
tstrSocketBindMsg *pstrBind = (tstrSocketBindMsg*)pvMsg;
if(pstrBind != NULL)
{
if(pstrBind->status == 0)
{
recvfrom(sock, gau8SocketTestBuffer, TEST_BUFFER_SIZE, 0);
}
else
{
M2M_ERR("bind\n");
}
}
}
break;
{
if(pstrRx->s16BufferSize > 0)
{
//get the remote host address and port number
uint16 u16port = pstrRx->strRemoteAddr.sin_port;
uint32 strRemoteHostAddr = pstrRx->strRemoteAddr.sin_addr.s_addr;
printf("Received frame with size = %d.\tHost address=%x, Port number = %d\n\n",pstrRx->s16BufferSize,strRemoteHostAddr, u16port);
ret = recvfrom(sock,gau8SocketTestBuffer,sizeof(gau8SocketTestBuffer),TEST_RECV_TIMEOUT);
}
else
{
printf("Socket recv Error: %d\n",pstrRx->s16BufferSize);
ret = close(sock);
}
}
break;
default:
break;
}

References tstrSocket::bIsRecvPending, MAX_SOCKET, NM_BSP_B_L_32, NULL, tstrSocket::pu8UserBuffer, tstrRecvCmd::sock, SOCK_ERR_BUFFER_FULL, SOCK_ERR_INVALID_ARG, SOCK_ERR_NO_ERROR, SOCKET_CMD_RECVFROM, SOCKET_REQUEST, tstrRecvCmd::u16BufLen, tstrSocket::u16SessionID, tstrRecvCmd::u16SessionID, tstrSocket::u16UserBufferSize, and tstrRecvCmd::u32Timeoutmsec.

NMI_API void registerSocketCallback ( tpfAppSocketCb  pfAppSocketCb,
tpfAppResolveCb  pfAppResolveCb 
)
Register two callback functions one for asynchronous socket events and the other one for DNS callback registering function.
The registered callback functions are used to retrieve information in response to the asynchronous socket functions called.
Parameters
[in]socket_cbAssignment of callback function to the global callback tpfAppSocketCb gpfAppSocketCb. Delivers socket messages to the host application. In response to the asynchronous function calls, such as bind listen accept connect
[in]resolve_cbAssignment of callback function to the global callback tpfAppResolveCb gpfAppResolveCb. Used for DNS resolving functionality. The DNS resolving technique is determined by the application registering the callback. NULL is assigned when DNS resolution is not required.
Returns
void
Remarks
If any of the socket functionality is not to be used, NULL is passed in as a parameter. It must be invoked after socketInit and before other socket layer operations.

Example

This example demonstrates the use of the registerSocketCallback to register a socket callback function with DNS resolution CB set to null for a simple UDP server example.

tstrNetworkId strNetworkId;
tstrAuthPsk strAuthPsk;
int8_t ret;
struct sockaddr_in addr;
// Initialize the board
//Initialize the UART console.
// Initialize the BSP.
// 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 Wi-Fi parameters structure.
memset((uint8_t *)&param, 0, sizeof(tstrWifiInitParam));
// Initialize Wi-Fi driver with data and status callbacks.
ret = m2m_wifi_init(&param);
if (M2M_SUCCESS != ret) {
printf("main: m2m_wifi_init call error!(%d)\r\n", ret);
while (1) {
}
}
// Initialize socket module
// Connect to router.
strNetworkId.pu8Bssid = NULL;
strNetworkId.pu8Ssid = MAIN_WLAN_SSID;
strNetworkId.u8SsidLen = sizeof(MAIN_WLAN_SSID);
strNetworkId.u8Channel = M2M_WIFI_CH_ALL;
strAuthPsk.pu8Psk = NULL;
strAuthPsk.pu8Passphrase = MAIN_WLAN_PSK;
strAuthPsk.u8PassphraseLen = (uint8)strlen((char*)MAIN_WLAN_PSK);
m2m_wifi_connect_psk(WIFI_CRED_SAVE_ENCRYPTED, &strNetworkId, &strAuthPsk);

References gpfAppResolveCb, and gpfAppSocketCb.

Referenced by wifi_ap_provision().

sint8 secure ( SOCKET  sock)
Converts an (insecure) TCP connection with a remote server into a secure TLS-over-TCP connection.
It may be called after both of the following:\n
- a TCP socket has been created by the @ref socket function, with u8Config parameter set to
@ref SOCKET_CONFIG_SSL_DELAY.\n
- a successful connection has been made on the socket via the @ref connect function.
This is an asynchronous API; the application socket callback function is notified of the result
of the attempt to make the connection secure through the event @ref SOCKET_MSG_SECURE, along
with a structure @ref tstrSocketConnectMsg.
If the attempt to make the connection secure fails, the application should call @ref close().
Parameters
[in]sockSocket ID, corresponding to a connected TCP socket.
Precondition
socket and connect must be called to connect a TCP socket before passing the socket ID to this function. Value SOCKET_CONFIG_SSL_DELAY must have been set in the u8Config parameter that was passed to socket.
See Also
socket connect
Returns
The function returns SOCK_ERR_NO_ERROR for successful operations and a negative error value otherwise. The possible error values are:

References MAX_SOCKET, NULL, tstrConnectCmd::sock, SOCK_ERR_INVALID, SOCK_ERR_INVALID_ARG, SOCK_ERR_NO_ERROR, SOCKET_CMD_SECURE, SOCKET_REQUEST, SSL_FLAGS_ACTIVE, SSL_FLAGS_DELAY, tstrSocket::u16SessionID, tstrConnectCmd::u16SessionID, tstrSocket::u8SSLFlags, and tstrConnectCmd::u8SslFlags.

NMI_API sint16 send ( SOCKET  sock,
void *  pvSendBuffer,
uint16  u16SendLength,
uint16  flags 
)
Asynchronous sending function, used to send data on a TCP/UDP socket.

Called by the application code when there is outgoing data available required to be sent on a specific socket handler.
The only difference between this function and the similar @ref sendto function, is the type of socket the data is sent on and the parameters passed in.
@ref send function is most commonly called for sockets in a connected state.
After the data is sent, the socket callback function registered using registerSocketCallback(), is expected to receive an event of type
@ref SOCKET_MSG_SEND holding information containing the number of data bytes sent.
Parameters
[in]sockSocket ID, must hold a non negative value. A negative value will return a socket error SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
[in]pvSendBufferPointer to a buffer holding data to be transmitted.
[in]u16SendLengthThe buffer size in bytes.
[in]u16FlagsNot used in the current implementation.
Precondition
Sockets must be initialized using socketInit.
For TCP Socket:
Must use a successfully connected Socket (so that the intended recipient address is known ahead of sending the data). Hence this function is expected to be called after a successful socket connect operation(in client case or accept in the the server case).
For UDP Socket:
UDP sockets most commonly use sendto function, where the destination address is defined. However, in-order to send outgoing data using the send function, at least one successful call must be made to the sendto function before consecutive calls to the send function, to ensure that the destination address is saved in the firmware.
See Also
socketInit recv sendto socket connect accept sendto
Warning
u16SendLength must not exceed SOCKET_BUFFER_MAX_LENGTH.
Use a valid socket identifier through the prior call to the socket function. Must use a valid buffer pointer. Successful completion of a call to send() does not guarantee delivery of the message, A negative return value indicates only locally-detected errors
Returns
The function shall return SOCK_ERR_NO_ERROR for successful operation and a negative value otherwise.

References M2M_REQ_DATA_PKT, MAX_SOCKET, NM_BSP_B_L_16, NULL, tstrSendCmd::sock, SOCK_ERR_BUFFER_FULL, SOCK_ERR_INVALID_ARG, SOCK_ERR_NO_ERROR, SOCKET_BUFFER_MAX_LENGTH, SOCKET_CMD_SEND, SOCKET_CMD_SSL_SEND, SOCKET_REQUEST, SSL_FLAGS_ACTIVE, SSL_FLAGS_DELAY, TCP_SOCK_MAX, TCP_TX_PACKET_OFFSET, tstrSocket::u16DataOffset, tstrSendCmd::u16DataSize, tstrSocket::u16SessionID, tstrSendCmd::u16SessionID, and UDP_TX_PACKET_OFFSET.

Referenced by html_handler().

NMI_API sint16 sendto ( SOCKET  sock,
void *  pvSendBuffer,
uint16  u16SendLength,
uint16  flags,
struct sockaddr pstrDestAddr,
uint8  u8AddrLen 
)

Asynchronous sending function, used to send data on a UDP socket. Called by the application code when there is data required to be sent on a UDP socket.

The application code is expected to receive data from a successfully bound socket node. The only difference between this function and the similar send function, is the type of socket the data is received on. This function works only with UDP sockets. After the data is sent, the socket callback function registered using registerSocketCallback(), is expected to receive an event of type SOCKET_MSG_SENDTO.

Parameters
[in]sockSocket ID, must hold a non negative value. A negative value will return a socket error SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
[in]pvSendBufferPointer to a buffer holding data to be transmitted. A NULL value will return a socket error SOCK_ERR_INVALID_ARG. Indicating that an invalid argument is passed in.
[in]u16SendLengthThe buffer size in bytes. It must not exceed SOCKET_BUFFER_MAX_LENGTH.
[in]flagsNot used in the current implementation
[in]pstrDestAddrThe destination address.
[in]u8AddrLenDestination address length in bytes. Not used in the current implementation, only included for BSD compatibility.
Precondition
Sockets must be initialized using socketInit.
See Also
socketInit recvfrom sendto socket connect accept send
Warning
u16SendLength must not exceed SOCKET_BUFFER_MAX_LENGTH.
Use a valid socket (returned from socket). A valid buffer pointer must be used (not NULL).
Successful completion of a call to sendto does not guarantee delivery of the message, A negative return value indicates only locally-detected errors.
Returns
The function returns SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise.

References IP_PACKET_OFFSET, M2M_HIF_HDR_OFFSET, M2M_HIF_MAX_PACKET_SIZE, m2m_memset(), M2M_REQ_DATA_PKT, MAX_SOCKET, NM_BSP_B_L_16, NULL, RAW_SOCK_ID, in_addr::s_addr, sockaddr_in::sin_addr, sockaddr_in::sin_family, sockaddr_in::sin_port, tstrSendCmd::sock, SOCK_ERR_BUFFER_FULL, SOCK_ERR_INVALID_ARG, SOCK_ERR_NO_ERROR, SOCKET_BUFFER_MAX_LENGTH, SOCKET_CMD_SENDTO, SOCKET_REQUEST, tstrSendCmd::strAddr, tstrSendCmd::u16DataSize, tstrSockAddr::u16Family, tstrSockAddr::u16Port, tstrSocket::u16SessionID, tstrSendCmd::u16SessionID, tstrSockAddr::u32IPAddr, and UDP_TX_PACKET_OFFSET.

sint8 set_alpn_list ( SOCKET  sock,
const char *  pcProtocolList 
)

This function sets the protocol list used for application-layer protocol negotiation (ALPN). If used, it must be called after creating a SSL socket (using socket) and before connecting/binding (using connect or bind) or securing (using secure).

Parameters
[in]sockSocket ID obtained by a call to socket. This is the SSL socket to which the ALPN list applies.
[in]pcProtocolListPointer to the list of protocols available in the application.
The entries in the list must:
  • be separated with ' ' (space).
  • not contain ' ' (space) or '\0' (NUL).
  • be non-zero length.
The list itself must:
  • be terminated with '\0' (NUL).
  • be no longer than ALPN_LIST_MAX_APP_LENGTH, including separators (spaces) and terminator (NUL).
  • contain at least one entry.
Returns
The function returns M2M_SUCCESS for successful operations and a negative value otherwise.

Example

The example demonstrates an application using set_alpn_list and get_alpn_index to negotiate secure HTTP/2 (with fallback option of HTTP/1.1).

Main Function

* if (TcpClientSocket >= 0)
* {
* struct sockaddr_in Serv_Addr = {
* .sin_port = _htons(1234),
* .sin_addr.s_addr = inet_addr(SERVER)
* };
* set_alpn_list(TcpClientSocket, "h2 http/1.1");
* connect(TcpClientSocket, &Serv_Addr, sizeof(Serv_Addr));
* }
*

Socket Callback

* if(u8Msg == SOCKET_MSG_CONNECT)
* {
* tstrSocketConnectMsg *pstrConnect = (tstrSocketConnectMsg*)pvMsg;
* if(pstrConnect->s8Error == 0)
* {
* uint8 alpn_index = get_alpn_index(pstrConnect->sock);
* switch (alpn_index)
* {
* case 1:
* printf("Negotiated HTTP/2\n");
* break;
* case 2:
* printf("Negotiated HTTP/1.1\n");
* break;
* case 0:
* printf("Protocol negotiation did not occur\n");
* break;
* }
* }
* }
*

References ALPN_LIST_MAX_APP_LENGTH, ALPN_LIST_MAX_SIZE, m2m_memcpy(), m2m_strlen(), NULL, setsockopt(), SO_SSL_ALPN, SOCK_ERR_INVALID_ARG, SOL_SSL_SOCKET, and TCP_SOCK_MAX.

NMI_API sint8 setsockopt ( SOCKET  sock,
uint8  u8Level,
uint8  option_name,
const void *  option_value,
uint16  u16OptionLen 
)
The setsockopt() function shall set the option specified by the option_name
argument, at the protocol level specified by the level argument, to the value
pointed to by the option_value argument for the socket specified by the socket argument.
Parameters
[in]socketSocket handler.
[in]u8LevelProtocol level.
Supported protocol levels are SOL_SOCKET, SOL_SSL_SOCKET and SOL_RAW.
[in]option_nameOption to be set.
For protocol level SOL_SOCKET, the supported option names are:
SO_SET_UDP_SEND_CALLBACK
SO_TCP_KEEPALIVE
SO_TCP_KEEPIDLE
SO_TCP_KEEPINTVL
SO_TCP_KEEPCNT
For protocol level SOL_SSL_SOCKET, the supported option names are:
SO_SSL_BYPASS_X509_VERIF
SO_SSL_SNI
SO_SSL_ENABLE_SESSION_CACHING
SO_SSL_ENABLE_CERTNAME_VALIDATION
SO_SSL_ALPN
For protocol level SOL_RAW, the supported option names are:
SO_ICMP_FILTER
[in]option_valuePointer to user provided value.
[in]u16OptionLenLength of the option value in bytes. Refer to each option documentation for the required length.
Returns
The function shall return SOCK_ERR_NO_ERROR for successful operation and a negative value (indicating the error) otherwise.

References MAX_SOCKET, NULL, rawSetSockOpt(), tstrSetSocketOptCmd::sock, SOCK_ERR_INVALID, SOCK_ERR_INVALID_ARG, SOCK_ERR_NO_ERROR, SOCKET_CMD_SET_SOCKET_OPTION, SOCKET_REQUEST, SOL_RAW, SOL_SOCKET, SOL_SSL_SOCKET, sslSetSockOpt(), tstrSocket::u16SessionID, tstrSetSocketOptCmd::u16SessionID, tstrSetSocketOptCmd::u32OptionValue, and tstrSetSocketOptCmd::u8Option.

Referenced by set_alpn_list().

NMI_API SOCKET socket ( uint16  u16Domain,
uint8  u8Type,
uint8  u8Config 
)
Synchronous socket allocation function based on the specified socket type. Created sockets are non-blocking and their possible types are either TCP or a UDP sockets.
The maximum allowed number of TCP sockets is @ref TCP_SOCK_MAX sockets while the maximum number of UDP sockets that can be created simultaneously is @ref UDP_SOCK_MAX sockets.
Parameters
[in]u16DomainSocket family. The only allowed value is AF_INET (IPv4.0) for TCP/UDP sockets.
[in]u8TypeSocket type. Allowed values are:
[in]u8ConfigUsed to specify the socket configuration. The interpretation of this parameter depends on the setting of u8Type.
Precondition
The socketInit function must be called once at the beginning of the application to initialize the socket handler. before any call to the socket function can be made.
See Also
connect secure bind listen accept recv recvfrom send sendto close setsockopt getsockopt
Returns
On successful socket creation, a non-blocking socket type is created and a socket ID is returned In case of failure the function returns a negative value, identifying one of the socket error codes defined. For example: SOCK_ERR_INVALID for invalid argument or SOCK_ERR_MAX_TCP_SOCK if the number of TCP allocated sockets exceeds the number of available sockets.
Remarks
The socket function must be called before any other related socket functions "e.g. send, recv, close ..etc"

Example

This example demonstrates the use of the socket function to allocate the socket, returning the socket handler to be used for other socket operations. Socket creation is dependent on the socket type.

UDP example

SOCKET UdpServerSocket = -1;

TCP example

References AF_INET, tstrSocket::bIsUsed, gu16SessionID, M2M_INFO, m2m_memset(), RAW_SOCK_ID, SOCK_DGRAM, SOCK_RAW, SOCK_STREAM, SOCKET_CMD_SSL_CREATE, SOCKET_CONFIG_IPPROTO_RAW, SOCKET_CONFIG_SSL_DELAY, SOCKET_CONFIG_SSL_OFF, SOCKET_REQUEST, SSL_FLAGS_ACTIVE, SSL_FLAGS_DELAY, tstrSSLSocketCreateCmd::sslSock, TCP_SOCK_MAX, tstrSocket::u16SessionID, tstrSocket::u8SSLFlags, and UDP_SOCK_MAX.

Referenced by wifi_ap_provision().

NMI_API void socketDeinit ( void  )

Socket Layer De-initialization.

The function performs the necessary cleanup for the socket library static data It must be invoked only after all desired socket operations have been performed on any active sockets.

References gbSocketInit, gpfAppResolveCb, gpfAppSocketCb, hif_register_cb(), m2m_memset(), M2M_REQ_GROUP_IP, MAX_SOCKET, and NULL.

Referenced by wifi_ap_provision().

NMI_API void socketInit ( void  )
The function performs the necessary initialization for the socket library through the following steps:
- A check made by the global variable gbSocketInit, ensuring that initialization for sockets is performed only once,
 in-order to prevent resetting the socket instances already created in the global socket array (gastrSockets).
- Zero initializations to the global socket array (gastrSockets), which holds the list of TCP sockets.
- Registers the socket (Host Interface)hif callback function through the call to the hif_register_cb function.
   This facilitates handling all of the socket related functions received through interrupts from the firmware.
Returns
void
Remarks
This initialization function must be invoked before any socket operation is performed. No error codes from this initialization function since the socket array is statically allocated based on the maximum number of sockets MAX_SOCKET which is tuned to the systems capability.

Example

This example demonstrates the use of the socketInit for socket initialization for an mqtt chat application.

tstrNetworkId strNetworkId;
tstrAuthPsk strAuthPsk;
int8_t ret;
char topic[strlen(MAIN_CHAT_TOPIC) + MAIN_CHAT_USER_NAME_SIZE + 1];
//Initialize the board.
//Initialize the UART console.
// Initialize the BSP.
----------
// Initialize socket interface.
registerSocketCallback(socket_event_handler, socket_resolve_handler);
// Connect to router.
strNetworkId.pu8Bssid = NULL;
strNetworkId.pu8Ssid = MAIN_WLAN_SSID;
strNetworkId.u8SsidLen = sizeof(MAIN_WLAN_SSID);
strNetworkId.u8Channel = M2M_WIFI_CH_ALL;
strAuthPsk.pu8Psk = NULL;
strAuthPsk.pu8Passphrase = MAIN_WLAN_PSK;
strAuthPsk.u8PassphraseLen = (uint8)strlen((char*)MAIN_WLAN_PSK);
m2m_wifi_connect_psk(WIFI_CRED_SAVE_ENCRYPTED, &strNetworkId, &strAuthPsk);

References gbSocketInit, gu16SessionID, hif_register_cb(), m2m_ip_cb(), m2m_memset(), M2M_REQ_GROUP_IP, and MAX_SOCKET.

Referenced by wifi_ap_provision().