Unit 7 - TCP Programming Techniques
Unit 7 - TCP Programming Techniques
References:
1. https://www.electronics-notes.com/articles/connectivity/wifi-ieee-802-11/what-is-wifi.php
2. https://medium.com/swlh/understanding-socket-connections-in-computer-networking-bac304812b5c
3. https://www.cloudflare.com/learning/ddos/glossary/user-datagram-protocol-udp/
4. https://www.cloudflare.com/learning/ddos/glossary/tcp-ip/
2
READ: https://www.electronics-notes.com/articles/connectivity/wifi-ieee-802-11/what-is-wifi.php
WiFi
• One of the major forms of communication – especially in homes with
broadband connections
• The standard for Wi-Fi is IEEE 802.11
• 802.11n or 802.11ac are variants within the overall series – allows to keep pace
with requirements for more data and higher speeds
• Uses the 2.4 and 5 GHz ISM (Industrial, Scientific and Medical bands) – do not
require a licence
• Core component is the Access Point (AP) – essentially the base station that
communicates with the WiFi enabled devices
• APs can then route data onto a local area network (LAN) via Ethernet and
typically links onto the Internet.
• Most broadband routers have an AP built in
3
ESP8266/ESP-01 Serial WiFi Transceiver Module
• By default, our NUCLEO board does not have WiFi connectivity.
• The ESP8266 is a highly integrated chip designed for the needs of a new
connected world.
• It offers a complete and self-contained Wi-Fi networking solution, supports IEEE
802.11 b/g/n, and has a built-in antenna. Can be used in two ways:
1. Operate as a stand-alone unit which host the application program
2. Operate as an additional module to be connected to a microcontroller
board – uses UART for communication between the module and
microcontroller. The application program is written for the
microcontroller and uses special API’s (functions) to communicate using
the ESP8266.
• In this module we will use option 2.
• There are different modules using the ESP8266 chipset, but the ESP-01 is the
most common and cheapest version:
ESP-01 Modules 4
The pinouts and connection of the ESP-01 is as follows (top view):
ESP-01 Module
2 Microcontroller connection
1 Pin # Description
1 RX TX Pin to transmit to ESP-01
2 VCC +3V
3 GPIO 0 Not connected
4 RESET Output pin to Reset ESP-01
5 GPIO 2 Not connected
6 CH_PD +3V
7 GND GND
7 8 8 TX RX Pin to receive from ESP-01
We have allowed to plug the ESP-01 module directly into the SwLed Shield to
minimize any wiring.
+ + =
5
READ: https://medium.com/swlh/understanding-socket-connections-in-computer-networking-bac304812b5c
7
READ: https://www.cloudflare.com/learning/ddos/glossary/tcp-ip/
• For both UDP and TCP the ESP8266 chip takes care of all the overheads and
processing – we simply write and read message to the ESP-01 module and it
will take care of the transmission.
• For support reasons, we will only cover TCP connections in ECSV311
8
Mbed Network APIs
• All the functions to connect to a network via WiFi, Ethernet, Cellular etc., and to
create UDP and TCP sockets are built into Mbed OS 6.
• The documentation to these can be found at:
https://os.mbed.com/docs/mbed-os/v6.10/apis/index.html
9
• From Mbed OS 6, the ESP8266 driver is part of the Mbed development
environment.
• The API information shown on the previous slide is for noting and future
reference when you start working on more complicated projects.
10
Create a WiFi Connection (Interface) – F446RE
• In this case I plugged my ESP-01 module directly into the SwLed Shield, and
added two jumper wires:
+ +
=
1 RX PC11 (Purple wire)
2 VCC +3V
3 GPIO 0 Not connected
4 RESET PA5
5 GPIO 2 Not connected
6 CH_PD +3V
7 GND GND
8 TX PC10 (Green wire)
11
Create a WiFi Connection (Interface) – F411RE
• In this case I plugged my ESP-01 module directly into the SwLed Shield, and
added two jumper wires:
+ +
=
1 RX PA12 (Purple wire)
2 VCC +3V
3 GPIO 0 Not connected
4 RESET PA5
5 GPIO 2 Not connected
6 CH_PD +3V
7 GND GND
8 TX PA11 (Green wire)
12
Steps to follow:
1. Include the ESP8266Interface.h library
13
3. Connect WiFi
14
3. Get IP address for NUCLEO
Example 1:
Create a Mbed program, that uses the ESP-01 WiFi module, to connect to an
Access Point. The AP info:
ID: Tenda_EDF640
Password: 0123456789
Once the connection is made, the IP address given by the AP to the NUCLEO board
must be displayed. If no connection was established, the program must stop.
15
Solution:
#include "mbed.h"
#include "ESP8266Interface.h"
int main() {
int ret; //general integer variable to use for return values from TCP functions
SocketAddress localAddress; //class object for local (client) socket address (IP address AND Port)
while (1) {
//do nothing
}
}
Result:
16
Create a TCP Socket (Client)
• At this stage, Mbed OS 6 only supports Client mode for TCP – Server should be
supported in future.
• In this section we will assume the WiFi connection code has already been done
(object “wifi” in Example 1)
• Keep in mind that TCP is a reliable connection and delivery is guaranteed.
Steps to follow:
1. Create the TCPSocket object
17
2. Create the TCP Client socket
18
4. Connect to the TCP Server
Format:
bool set_ip_address(addr)
Parameters:
addr Null-terminated representation of the IP address (string)
Returns:
True if address is a valid representation of an IP address, otherwise False and SocketAddress is
set to null
Format:
set_port(port)
Parameters:
port 16-bit port number (int)
Returns:
Nothing
19
How to determine the Server’s IP Address:
You will need the Server’s IP address to know where to send the UDP message
from the NUCLEO board.
• If the server is another device, you will generally be able to set that device’s IP
address – this will not be covered in this chapter
20
• If the server is a local PC on the network, you can follow these instructions to
determine the IP address for that PC:
1. Click Start , type “cmd”, and click on Command Prompt
2. Type “ipconfig” in the Command Prompt window and press Enter.
3. The window should now look similar to this:
Example 2:
Create a Mbed program that creates a TCP socket to be used for communication.
21
Solution:
#include "mbed.h"
#include "ESP8266Interface.h"
ESP8266Interface wifi(PA_11, PA_12, false, NC, NC, PA_5, NC); //create ESP8266Interface object
SocketAddress localAddress; //class object for local NUCLEO (client) socket address (IP address AND Port)
TCPSocket client; //object for the TCP Client (NUCLEO) socket
SocketAddress remoteAddress; //class object for remote (server) socket address
while (1) {
//do nothing
}
}
22
Send a TCP Message
• In this section we will assume the WiFi connection code has already been done
(object “wifi” in Example 1) and that the TCP socket has already been created
(object “client” in Example 2).
Steps to follow:
1. Send TCP message
Example 3:
Create a Mbed program that sends the value of a counter variable every second as
an TCP message to a local PC. 23
Solution:
#include "mbed.h"
#include "ESP8266Interface.h"
ESP8266Interface wifi(PA_11, PA_12, false, NC, NC, PA_5, NC); //create ESP8266Interface object
SocketAddress localAddress; //class object for local NUCLEO (client) socket address (IP address AND Port)
TCPSocket client; //object for the TCP Client (NUCLEO) socket
SocketAddress remoteAddress; //class object for remote (server) socket address
25
How to test the results for Example 3 with YAT
1. Open YAT
2. Click File → New Terminal
3. Select TCP/IP Server for Port Type, and 3000 (or the port number you used in
Mbed) as the Local TCP port
4. Under Local Interface, you must select the option that includes you IP address
at the end:
26
Results:
If you now run the code for Example 3 on the NUCLEO board, you should see the
following in YAT:
These messages in purple are the TCP messages that you are sending from the
NUCLEO board via the ESP-01 WiFi module.
The output from the Mbed Studio Serial Monitor (for the printf statements) would
be similar to this (you could also use Termite for this if you prefer to do so):
27
Receive a TCP Message
• In this section we will assume the WiFi connection code has already been done
(object “wifi” in Example 1) and that the TCP socket has already been created
(object “client” in Example 2).
Steps to follow:
1. Receive TCP message
28
Example 4:
Create a Mbed program that connects to a TCP server and constantly monitors if a
TCP message is received from the server. If a message is received, the IP address
and port number of the server must be displayed in the Serial Monitor (or Termite)
along with the message.
Solution:
#include "mbed.h"
#include "ESP8266Interface.h"
ESP8266Interface wifi(PA_11, PA_12, false, NC, NC, PA_5, NC); //create ESP8266Interface object
SocketAddress localAddress; //class object for local NUCLEO (client) socket address (IP address AND Port)
TCPSocket client; //object for the TCP Client (NUCLEO) socket
SocketAddress remoteAddress; //class object for remote (server) socket address
SocketAddress incomingAddress; //class object to store the socket address (IP address AND Port) for the received message
29
// ===== Connect to server =====
remoteAddress.set_ip_address("192.168.0.110"); //set IP adress of remote (server) adress socket object
remoteAddress.set_port(3000); //set port of remote (server) adress socket object
client.connect(remoteAddress); //make TCP socket connection with server
while (1) {
//read data from server if available and store in msg (msg string size = 40)
//incomingAddress contains sender's IP address and Port from which sent
ret = client.recvfrom(&incomingAddress, msg, 40);
if(ret == 0) { //ret = 0 means client is disconnected from server
printf("Disconnected from Server. Reset TCP Server and NUCLEO board\n");
ThisThread::sleep_for(1s); //wait for 1 second
}
if(ret > 0) { //message received; ret = string length
msg[ret] = '\0'; //add NULL to terminate the RAW data string
printf("Received from %s (%d): %s\n", incomingAddress.get_ip_address(), incomingAddress.get_port(), msg);
}
}
}
Results:
If you use YAT to send a few messages, you should get the following results:
30
The result on the Mbed Serial Monitor would be:
Notice that for every TCP message that was received, it seems that a blank
message also arrives. This is because YAT automatically sends the <CR><LF>
characters after each message. This can be disabled as follows:
1. Click Terminal → Settings
2. Click Text Settings
3. Change EOL sequence to None
31
Creating a TCP Server Application in Visual Basic
Instead of using a terminal program (such as YAT) to communicate with the
NUCLEO board using TCP, we can create an Visual Basic application with a neat GUI
to control and monitor peripherals on the NUCLEO board.
Steps to follow:
1. Create a Visual Basic program and immediately save it.
2. Copy the “WinSock.vb” file (under resources on Moodle site) to the VB project
folder
32
3. In the Solution Explorer, right-click on the project, select Add → Existing Item
33
5. In the Form Load event, add a Timer object to check for incoming TCP
messages, set the TCP port to use for communication, and start the TCP server.
6. Create the ConnectionRequest event code that will accept TCP connections
from other devices.
34
8. Program the Timer Tick event which checks for new incoming TCP messages
35
Creating a TCP Server Application in Node-RED
We can also create a Node-RED GUI (dashboard) to control and monitor
peripherals on the NUCLEO board. The GUI will be set up as a TCP server.
Required nodes:
1. Tcp in
Provides a choice of TCP inputs. Can either connect to a remote TCP port, or
accept incoming connections.
36
2. Tcp out
Provides a choice of TCP outputs. Can either:
• connect to a remote TCP port
• accept incoming connections
• reply to messages received from a TCP In node
Only the msg.payload is sent.
This setup will:
• Send the string (payload) from
a previous node to all
connected TCP sockets.
• If the TCP socket is not created
yet by the tcp in node, this
node will be ignored.
• We can use the msg._session
property to only send the
string to a specific TCP socket
(if multiple TCP sockets were
created)
37
Creating a TCP Server Application in B4A
38
Example 5: TCP Summary – Peer-to-peer
The purpose of the example is to summarize the TCP programming principles.
Create a Mbed system (using a NUCLEO board) whereby a user can control the
output of a LED and monitor the value of an analog input from a PC (or Mobile
phone).
The communications link between the NUCLEO board and the PC is WiFi and a TCP
socket should be used.
Make use of peer-to-peer mode communication between the two devices,
meaning that any of the two nodes (NUCLEO or PC) can initiate a command at any
time. The protocol to be used is as follows:
Command Parameter Direction Description
LED ON or OFF PC → NUCLEO Turn LED on or off
POT 0.0 to 1.0 NUCLEO → PC Report the analog input
(potentiometer) value
The analog value must be reported on by the NUCLEO board every 1 second.
First test the system using YAT, and then develop a Visual Basic application and a
Node-RED flow for the PC (or a B4A application for the Mobile phone). 39
Solution:
#include "mbed.h"
#include "ESP8266Interface.h"
ESP8266Interface wifi(PA_11, PA_12, false, NC, NC, PA_5, NC); //create ESP8266Interface object
SocketAddress localAddress; //class object for local NUCLEO (client) socket address (IP address AND Port)
TCPSocket client; //object for the TCP Client (NUCLEO) socket
SocketAddress remoteAddress; //class object for remote (server) socket address
SocketAddress incomingAddress; //class object to store the socket address (IP address AND Port) for the received message
40
while (1) {
//send pot value to TCP server every 500 ms - will delay receiving of messages
ThisThread::sleep_for(1s); //wait for 1 second
sprintf(tmp, "POT %.3f", pot.read()); //print pot value to a string tmp
client.sendto(remoteAddress, tmp, strlen(tmp)); //send tmp string to TCP server
//read data from server if available and store in msg (msg string size = 40)
//incomingAddress contains sender's IP address and Port from which sent
ret = client.recvfrom(&incomingAddress, msg, 40);
if(ret == 0) { //ret = 0 means client is disconnected from server
printf("Disconnected from Server. Reset TCP Server and NUCLEO board\n");
ThisThread::sleep_for(1s); //wait for 1 second
}
if(ret > 0) { //message received; ret = string length
msg[ret-2] = '\0'; //add NULL to terminate the RAW data string - if CR LF ARE used
//msg[ret] = '\0'; //add NULL to terminate the RAW data string - if CR LF are NOT used
printf("Received from %s (%d): %s\n", incomingAddress.get_ip_address(), incomingAddress.get_port(), msg);
41
Testing with a YAT TCP Server:
42
Visual Basic Application solution:
43
44
Node-RED solution: 5
1 3
5
8
9 7
4. Text output
Displays the PARAMETER value (from the POT x.xxx instruction from the client)
46
5. Slider
Displays the PARAMETER value (from the POT x.xxx instruction from the client)
as a graphical object
6. Switch
Sends the LED ON or LED OFF message to the client (NUCLEO board)
7. Text output
Displays the TCP connection status.
47
8. Countdown
Install the node-red-contrib-countdown package. We use this countdown timer
to check if we are still receiving messages from the TCP client. If no messages
are received within 3 seconds, we assume the TCP socket is closed.
To do this, the countdown node counts down from 3 seconds to 0. When the
count gets to 0, the output payload message becomes “Not connected - reset
NUCLEO”. When the count is >0 the output payload message becomes
“Connected”. Each time a new TCP message is received, the countdown node
resets to 3 seconds.
9. Inject
Injects the default message
“Not connected - reset NUCLEO” at startup
48
B4A Application solution:
49