ClearCore Library
Loading...
Searching...
No Matches
EthernetTcpServerHelloWorld_automatic.cpp

Return to SDK Examples for Microchip Studio

1/*
2 * Title: EthernetTCPServer_autoClientManagement
3 *
4 * Objective:
5 * This example demonstrates how to configure a ClearCore as a TCP server to
6 * send and receive TCP datagrams (packets).
7 *
8 * Description:
9 * This example configures a ClearCore device to act as a TCP server.
10 * This server can receive connections from another device acting as a TCP
11 * client to exchange data over ethernet TCP.
12 * This simple example accepts connection requests from clients, receives and
13 * prints incoming data from connected devices, and sends a simple "Hello
14 * client" response.
15 * A partner project, EthernetTcpClientHelloWorld, is available to configure
16 * another ClearCore as a client.
17 *
18 * Setup:
19 * 1. Set the usingDhcp boolean as appropriate. If not using DHCP, specify static
20 * IP and network information.
21 * 2. Ensure the server and client are set up to communicate on the same network.
22 * If both devices are directly connected (as opposed to connected through a switch) an ethernet crossover cable may be required.
23 * 3. It may be helpful to use a terminal application such as PuTTY to view serial output from each device. https://www.putty.org/
24 *
25 * Links:
26 * ** ClearCore Documentation: https://teknic-inc.github.io/ClearCore-library/
27 * ** ClearCore Manual: https://www.teknic.com/files/downloads/clearcore_user_manual.pdf
28 *
29 * Copyright (c) 2022 Teknic Inc. This work is free to use, copy and distribute under the terms of
30 * the standard MIT permissive software license which can be found at https://opensource.org/licenses/MIT
31 */
32
33#include "ClearCore.h"
34#include "EthernetTcpServer.h"
35
36// The port number on the server over which packets will be sent/received
37#define PORT_NUM 8888
38
39// The maximum number of characters to receive from an incoming packet
40#define MAX_PACKET_LENGTH 100
41// Buffer for holding received packets
42unsigned char packetReceived[MAX_PACKET_LENGTH];
43
44// Set usingDhcp to false to use user defined network settings
45bool usingDhcp = true;
46
47int main(void) {
48 // Set up serial communication between ClearCore and PC serial terminal
49 ConnectorUsb.Mode(Connector::USB_CDC);
50 ConnectorUsb.Speed(9600);
51 ConnectorUsb.PortOpen();
52 uint32_t timeout = 5000;
53 uint32_t startTime = Milliseconds();
54 while (!ConnectorUsb && Milliseconds() - startTime < timeout) {
55 continue;
56 }
57
58 // Set connector IO0 as a digital output
59 // When IO0 state is true, a LED will light on the
60 // ClearCore indicating a successful connection to a client
61 ConnectorIO0.Mode(Connector::OUTPUT_DIGITAL);
62
63 // Make sure the physical link is active before continuing
64 while (!EthernetMgr.PhyLinkActive()) {
65 ConnectorUsb.SendLine("The Ethernet cable is unplugged...");
66 Delay_ms(1000);
67 }
68
69 // To configure with an IP address assigned via DHCP
70 EthernetMgr.Setup();
71 if (usingDhcp) {
72 // Use DHCP to configure the local IP address
73
74 bool dhcpSuccess = EthernetMgr.DhcpBegin();
75 if (dhcpSuccess) {
76 ConnectorUsb.Send("DHCP successfully assigned an IP address: ");
77 ConnectorUsb.SendLine(EthernetMgr.LocalIp().StringValue());
78 }
79 else {
80 ConnectorUsb.SendLine("DHCP configuration was unsuccessful!");
81 while (true) {
82 // TCP will not work without a configured IP address
83 continue;
84 }
85 }
86 } else {
87 // Configure with a manually assigned IP address
88
89 // Set ClearCore's IP address
90 IpAddress ip = IpAddress(192, 168, 0, 109);
91 EthernetMgr.LocalIp(ip);
92 ConnectorUsb.Send("Assigned manual IP address: ");
93 ConnectorUsb.SendLine(EthernetMgr.LocalIp().StringValue());
94
95 // Optionally set additional network addresses if needed
96
97 //IpAddress gateway = IpAddress(192, 168, 1, 1);
98 //IpAddress netmask = IpAddress(255, 255, 255, 0);
99 //EthernetMgr.GatewayIp(gateway);
100 //EthernetMgr.NetmaskIp(netmask);
101 }
102
103
104 // Initialize the ClearCore as a server that will listen for
105 // incoming client connections on specified port (8888 by default)
106 EthernetTcpServer server = EthernetTcpServer(PORT_NUM);
107
108 // Initialize a client object
109 // This object will hold a connected client's information
110 // allowing the server to interact with the client
111 EthernetTcpClient client;
112
113 // Start listening for TCP connections
114 server.Begin();
115
116 ConnectorUsb.SendLine("Server now listening for client connections...");
117
118 // Connect to clients, and send/receive packets
119 while(true){
120 // Obtain a reference to a connected client with incoming data available
121 // This function will only return a valid reference if the connected device
122 // has data available to read
123 client = server.Available();
124
125 // Check if the server has returned a connected client with incoming data available
126 if (client.Connected() || client.BytesAvailable() > 0) {
127 // Flash on LED if a client has sent a message
128 ConnectorIO0.State(true);
129
130 // Delay to allow user to see the LED
131 // This example will flash the LED each time a message from a client is received
132 Delay_ms(100);
133
134 // Read packet from the client
135 ConnectorUsb.Send("Read the following from the client: ");
136 while (client.BytesAvailable() > 0) {
137 // Send the data received from the client over a serial port
138 client.Read(packetReceived, MAX_PACKET_LENGTH);
139 ConnectorUsb.Send((char *)packetReceived);
140
141 // Clear the message buffer for the next iteration of the loop
142 for(int i=0; i<MAX_PACKET_LENGTH; i++){
143 packetReceived[i]= NULL;
144 }
145 }
146 ConnectorUsb.SendLine();
147
148 // Send response message to client
149 if (client.Send("Hello client ")>0){
150 ConnectorUsb.SendLine("Sent 'Hello Client' response");
151 }
152 else{
153 ConnectorUsb.SendLine("Unable to send reply");
154 }
155 } else{
156 // Turn off LED if a message has not been received
157 ConnectorIO0.State(false);
158 if(client.ConnectionState()->state == CLOSING){
159 client.Close();
160 }
161
162 // Make sure the physical link is active before continuing
163 while (!EthernetMgr.PhyLinkActive()) {
164 ConnectorUsb.SendLine("The Ethernet cable is unplugged...");
165 Delay_ms(1000);
166 }
167 }
168 // Broadcast message to all clients
169 //server.Send("Hello all clients ");
170
171 // Perform any necessary periodic ethernet updates
172 // Must be called regularly when actively using ethernet
173 EthernetMgr.Refresh();
174 }
175
176}
void Delay_ms(uint32_t ms)
Blocks operations for ms milliseconds.
Definition SysTiming.h:287
uint32_t Milliseconds(void)
Number of milliseconds since the ClearCore was initialized.
int16_t State() override
Get connector's last sampled digital value.
virtual ConnectorModes Mode() override
Get the connector's operational mode.
Definition DigitalInOutAnalogOut.h:70
volatile const bool & PhyLinkActive()
Check the link status from the PHY.
Definition EthernetManager.h:136
IpAddress LocalIp()
Get the local IP address.
void Refresh()
Perform any necessary periodic Ethernet and LwIP updates.
bool DhcpBegin()
Set up DHCP connection to retrieve local IP.
void Setup()
Setup LwIP with the local network interface.
bool SendLine()
Send carriage return and newline characters.
Definition ISerial.h:162
virtual bool Speed(uint32_t bitsPerSecond)=0
Change the baud rate for the port.
bool Send(const char *buffer, size_t bufferSize)
Send the array of characters out the port.
Definition ISerial.h:173
char * StringValue()
Returns a string representation of the IP Address.
Definition IpAddress.h:96
void PortOpen() override
virtual ConnectorModes Mode() override
Get the connector's operational mode.
Definition SerialUsb.h:210