server class

This commit is contained in:
DashyFox 2024-10-29 16:37:47 +03:00
parent 94ea050345
commit a102cd3b5f
7 changed files with 183 additions and 23 deletions

121
examples/Server/Server.ino Normal file
View File

@ -0,0 +1,121 @@
#include <SPI.h>
#include <EthernetMaket.h>
// Настройки для W5500
#define W5500_CS_PIN PA2 // Пин для CS
#define SERVER_PORT 1337 // Порт на сервере
byte mac[] = {0xDA, 0x7A, 0xFF, 0x00, 0x00, 0x00}; // MAC-адрес сервера
byte ip[] = {192, 168, 254, 254}; // IP-адрес сервера
uint8_t gateway[] = {192, 168, 0, 1}; // Шлюз
uint8_t subnet[] = {255, 255, 0, 0}; // Маска подсети
EthernetMaketServer server(SERVER_PORT); // Создаем сервер на указанном порту
unsigned long previousMillis = 0; // Время последней отправки
const long interval = 1750; // Интервал отправки данных (1.75 секунды)
uint32_t packetCounter = 0;
uint32_t ttt;
void serverHandler(EthernetClient client)
{
//!
delay(10); // Ожидание окончания принятых данных, переделать в завершение по пакету финализации
byte buf[512];
int len = client.read(buf, sizeof(buf));
// Обработка каждого 4-байтового пакета
for (int i = 0; i < len; i += 4)
{
int packetLen = min(4, len - i); // Определяем длину текущего пакета
processReceivedData(buf + i, packetLen);
for (uint8_t j = 0; j < 3; j++)
{
sendResponse(client, *(uint32_t *)(buf + i));
}
packetCounter++;
}
//!-----------------
Serial.println("DONE");
client.stop();
Serial.println();
Serial.println();
}
void setup()
{
Serial.begin(115200);
// Инициализация SPI и Ethernet
SPI.begin();
pinMode(W5500_CS_PIN, OUTPUT);
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(W5500_CS_PIN, HIGH);
// Инициализация Ethernet
Ethernet.setCsPin(W5500_CS_PIN); // Установка пина CS для W5500
Ethernet.init();
Ethernet.begin(mac, ip, subnet, gateway, gateway);
// Запуск сервера
server.begin();
server.setServerHandler(serverHandler);
Serial.print("Server is running at ");
Serial.println(Ethernet.localIP());
}
void loop()
{
server.tick();
uint32_t currentMillis = millis();
if (currentMillis - ttt > 75)
{
digitalToggle(PC13);
ttt = currentMillis; // Обновляем время
}
}
// Обработка полученных данных
void processReceivedData(byte *data, int len)
{
Serial.print("Received data: ");
for (int i = 0; i < len; i++)
{
Serial.print(data[i], HEX);
Serial.print(" ");
}
Serial.println();
}
// Отправка ответа клиенту
volatile void sendResponse(EthernetClient &client, uint32_t packetCount)
{
byte response[16];
// Заполняем массив данных
for (int i = 0; i < 15; i++)
{
response[i] = (i + packetCount) % 256; // Пример данных
}
// Вычисление контрольной суммы
uint8_t checksum = 0;
for (int i = 0; i < 15; i++)
{
checksum += response[i];
}
response[15] = checksum; // Установка контрольной суммы
// Отправка данных клиенту
client.write(response, sizeof(response));
Serial.print("Send response: ");
for (int i = 0; i < 16; i++)
{
Serial.print(response[i], HEX);
Serial.print(" ");
}
Serial.println();
}

View File

@ -1,24 +1,8 @@
#ifndef __ETHERNETMAKET_H__ #ifndef __ETHERNETMAKET_H__
#define __ETHERNETMAKET_H__ #define __ETHERNETMAKET_H__
#include "Ethernet3.h" #include "EthernetOverride/Server.h"
enum ConnectionStatusSimple{
CONNECT_FAIL = 0,
CONNECT_SUCCESS = 1,
CONNECT_CONNECTING = 2,
CONNECT_START = 3,
CONNECT_IDLE = 4,
CONNECT_CONNECTED = 5,
CONNECT_STOP_START = 6,
CONNECT_STOP_WAITING = 7,
};
#include "EthernetOverride/TCP.h" #include "EthernetOverride/TCP.h"
#include "EthernetOverride/UDP.h"
#endif // __ETHERNETMAKET_H__ #endif // __ETHERNETMAKET_H__

View File

@ -61,4 +61,39 @@ void EthernetMaketServer::begin(int sock)
listen(sock); listen(sock);
EthernetClass::_server_port[sock] = _port; EthernetClass::_server_port[sock] = _port;
} }
}
void EthernetMaketServer::begin()
{
EthernetServer::begin();
}
void EthernetMaketServer::tick()
{
for (int sock = 0; sock < MAX_SOCK_NUM; sock++)
{
EthernetMaketClient sclient = available(sock);
if (sclient.connected() && sclient.available() > 0)
{
serverHandler(sclient);
}
// // Закрытие соединения по таймеру неактивности
// if (sclient.connected() && (millis() - lastActivityTime > timeout))
// {
// Serial.println("Connection closed due to inactivity");
// sclient.stop();
// }
// if (!wasConnected && sclient.connected())
// {
// wasConnected[sock] = true;
// }
// if (wasConnected && !sclient.connected())
// {
// wasConnected[sock] = false;
// sclient.stop();
// Serial.println("Client disconnected");
// }
}
} }

View File

@ -1,16 +1,17 @@
#ifndef __MAKET_SERVER_H__ #ifndef __MAKET_SERVER_H__
#define __MAKET_SERVER_H__ #define __MAKET_SERVER_H__
#include "Ethernet3.h" #include "../util/config.h"
#include "TCP.h" #include "TCP.h"
#include <functional> #include <functional>
class EthernetMaketClient;
class EthernetMaketServer : EthernetServer class EthernetMaketServer : EthernetServer
{ {
private: private:
EthernetClient available(); EthernetClient available();
void accept(int sock); void accept(int sock);
std::function<void(EthernetMaketClient)> serverHandler = [](EthernetMaketClient sclient){}; std::function<void(EthernetMaketClient)> serverHandler = [](EthernetMaketClient sclient) {};
bool wasConnected[MAX_SOCK_NUM];
public: public:
using EthernetServer::EthernetServer; using EthernetServer::EthernetServer;
@ -18,7 +19,9 @@ public:
void setServerHandler(std::function<void(EthernetMaketClient)> handler); void setServerHandler(std::function<void(EthernetMaketClient)> handler);
void resetServerHandler(); void resetServerHandler();
void begin() override;
void begin(int sock); void begin(int sock);
void tick();
}; };
#endif // __MAKET_SERVER_H__ #endif // __MAKET_SERVER_H__

View File

@ -1,7 +1,7 @@
#ifndef __MAKET_TCP_H__ #ifndef __MAKET_TCP_H__
#define __MAKET_TCP_H__ #define __MAKET_TCP_H__
#include "../EthernetMaket.h" #include "../util/config.h"
class EthernetMaketClient : public EthernetClient class EthernetMaketClient : public EthernetClient
{ {

View File

@ -1,7 +1,7 @@
#ifndef __MAKET_UDP_H__ #ifndef __MAKET_UDP_H__
#define __MAKET_UDP_H__ #define __MAKET_UDP_H__
#include "../EthernetMaket.h" #include "../util/config.h"
class EthernetMaketUDP : EthernetUDP class EthernetMaketUDP : EthernetUDP
{ {
private: private:

17
src/util/config.h Normal file
View File

@ -0,0 +1,17 @@
#ifndef __ETHERNET_MAKET_CONFIG_H__
#define __ETHERNET_MAKET_CONFIG_H__
#include "Ethernet3.h"
enum ConnectionStatusSimple{
CONNECT_FAIL = 0,
CONNECT_SUCCESS = 1,
CONNECT_CONNECTING = 2,
CONNECT_START = 3,
CONNECT_IDLE = 4,
CONNECT_CONNECTED = 5,
CONNECT_STOP_START = 6,
CONNECT_STOP_WAITING = 7,
};
#endif // __ETHERNET_MAKET_CONFIG_H__