BSD socket API is A set of standard function calls to include internet communication capabilities in a product
Other sockets API exists but the BSD socket is generally regarded as the standard.
The sockets API makes use of 2 mechanisms to deliver data to the application level: ports & sockets.
All TCP/IP stacks have 65,535 ports for both TCP & UDP
A port is not a physical interface. Once an application has created a socket and bound it to a port, data destined for that port will be delivered to the application.
A TCP/IP or UDP/IP packet is transmitted to a host, it eventually goes to the correct port then the socket conveys the packet’s data to the application
Now Let’s go though some common socket calls
Now we will go through this example https://github.com/espressif/esp-idf/tree/master/examples/protocols/sockets/tcp_client
This example makes esp32 a tcp client. At the host computer, a script will run as a TCP server.
ESP32 has a lwIP stack, this stack has the socket API.
The API can be found in this file
esp-idf/components/lwip/lwip/src/include/lwip/sockets.h
To create a socket instance we have to use the following function of sockets.h
The type argument can be from the following values
domain & protocol initialized as
The socket() creates a socket and returns the socket number
Now we are going to understand another basic structure related to socket programming which is sockaddr_in
We have to create this structure type variable and use it to assign the server’s IP address to which we want to connect
Then this variable is used at the socket connection method
This above function will connect to the server
Similarly, other function such as send() and recv() of the API is used for communication
The example code connects to wifi using example_connect() function, this is a blocking function and the block waits until a connection is established. the default event loop must be created before as wifi connection code is event based
The code creates a freeRtos task that tries to connect to the server in an infinite loop and if connected then it communicates with the server in another infinite loop
Running the Server Script
So the server is running on our host whose IP is 192.168.11.96
Now we need to assign this IP address to CONFIG_EXAMPLE_IPV4_ADDR macro
This can be done by idf.py menuconfig , in the same way, we assigned wifi SSID and Password values using the menuconfig
After assigning the server’s IP address and Port , program esp32 .
After getting connected to wifi , esp32 will connect to the server [host machine] and the server and client will communicate with each other
Here on the left side ESP32 log is printed and on the right side the python server’s log
---------------------------------------------------------------------------------------------------------------------------------------------
Reference
http://wiki.treck.com/Introduction_to_BSD_Sockets
0 comments:
Post a Comment