mirror of
https://github.com/Show-maket/EthernetMaket.git
synced 2025-05-04 15:20:18 +00:00
185 lines
5.9 KiB
C++
185 lines
5.9 KiB
C++
#include "EthernetMaket.h" // Предполагается, что этот файл подключает Ethernet3.h
|
||
|
||
// Настройки для W5500
|
||
#define W5500_CS_PIN PA2 // Пин для CS
|
||
#define SOCKET_NUMBER 0 // Используем сокет 0
|
||
#define SERVER_PORT 1337 // Порт на сервере
|
||
#define CLIENT_PORT 1337 // Порт клиента
|
||
|
||
#define ServerMac {0xDA, 0x7A, 0xFF, 0x00, 0x00, 0x00}
|
||
#define ServerIP {192, 168, 254, 254}
|
||
|
||
#define IniMac {0xDA, 0x7A, 0xF0, 0x00, 0x00, 0x00}
|
||
#define IniIP {192, 168, 254, 253}
|
||
|
||
uint8_t gateway[] = {192, 168, 0, 1}; // Шлюз
|
||
uint8_t subnet[] = {255, 255, 0, 0}; // Маска подсети
|
||
|
||
uint8_t mac[] = IniMac; // MAC-адрес
|
||
uint8_t localIP[] = IniIP; // Локальный IP-адрес
|
||
|
||
uint8_t serverMac[] = ServerMac; // MAC-адрес сервера
|
||
uint8_t serverIP[] = ServerIP; // IP-адрес сервера
|
||
|
||
uint8_t buf[512]; // Буфер для передачи данных
|
||
|
||
unsigned long previousMillis = 0; // Для хранения времени последней отправки
|
||
const long interval = 3750; // Интервал отправки данных (1.75 секунды)
|
||
uint32_t ttt;
|
||
|
||
EthernetServer server(SERVER_PORT);
|
||
EthernetMaketClient client;
|
||
|
||
// EthernetMaketClient c;
|
||
|
||
uint32_t packetCounter = 0;
|
||
|
||
unsigned long lastActivityTime = 0; // Время последней активности
|
||
const long timeout = 300; // Таймаут неактивности в миллисекундах
|
||
|
||
bool wasConnected = false;
|
||
bool dataReady = false;
|
||
|
||
void setup()
|
||
{
|
||
Serial.begin(115200);
|
||
pinMode(LED_BUILTIN, OUTPUT);
|
||
Ethernet.setCsPin(W5500_CS_PIN);
|
||
Ethernet.init();
|
||
|
||
// Настройка Ethernet с указанием статических параметров
|
||
Ethernet.begin(mac, localIP, gateway, gateway, subnet);
|
||
|
||
// Ethernet.setRtTimeOut(1000 * 10);
|
||
// Ethernet.setRtCount(3);
|
||
|
||
// client.setNoDelayedACK(true); // Не ждать ответа от сервера
|
||
}
|
||
|
||
void loop()
|
||
{
|
||
uint32_t currentMillis = millis();
|
||
if (currentMillis - ttt > 75)
|
||
{
|
||
digitalToggle(PC13);
|
||
ttt = currentMillis; // Обновляем время
|
||
}
|
||
|
||
if (currentMillis - previousMillis >= interval)
|
||
{
|
||
previousMillis = currentMillis;
|
||
|
||
Serial.println("\n\nConnecting...");
|
||
|
||
client.stop(); // Завершаем предыдущее соединение
|
||
dataReady = true;
|
||
|
||
}
|
||
|
||
// Подключаемся к серверу
|
||
ConnectionStatusSimple connectStatus;
|
||
bool isNonBlocking = true; // Флаг для определения режима подключения
|
||
|
||
if (isNonBlocking)
|
||
{
|
||
connectStatus = client.connectNonBlock(serverIP, SERVER_PORT);
|
||
}
|
||
else
|
||
{
|
||
connectStatus = (ConnectionStatusSimple)client.connect(serverIP, SERVER_PORT);
|
||
}
|
||
|
||
if (connectStatus == CONNECT_SUCCESS)
|
||
{
|
||
Serial.print("Connection established in ");
|
||
Serial.println(isNonBlocking ? "non-blocking mode" : "blocking mode");
|
||
//! Соединение установлено
|
||
lastActivityTime = millis(); // Обновляем время последней активности
|
||
for (size_t i = 0; i < 3; i++)
|
||
{
|
||
client.write((uint8_t *)&packetCounter, sizeof(packetCounter));
|
||
|
||
// Печать отправленного пакета
|
||
Serial.print("Sending packet: ");
|
||
for (size_t j = 0; j < sizeof(packetCounter); j++)
|
||
{
|
||
Serial.print(((uint8_t *)&packetCounter)[j], HEX);
|
||
Serial.print(" ");
|
||
}
|
||
Serial.println();
|
||
packetCounter++;
|
||
lastActivityTime = millis(); // Обновляем время последней активности
|
||
}
|
||
dataReady = false;
|
||
connectStatus = CONNECT_IDLE;
|
||
}
|
||
else
|
||
{
|
||
Serial.print("Failed to connect to server in ");
|
||
Serial.println(isNonBlocking ? "non-blocking mode" : "blocking mode");
|
||
connectStatus = CONNECT_IDLE;
|
||
client.stop();
|
||
}
|
||
|
||
// Проверка наличия доступных данных от сервера
|
||
if (client.available() > 0)
|
||
{
|
||
byte response[16];
|
||
int len = client.read(response, sizeof(response));
|
||
|
||
if (len == 16)
|
||
{
|
||
// Проверка контрольной суммы
|
||
uint8_t checksum = 0;
|
||
for (int i = 0; i < 15; i++)
|
||
{
|
||
checksum += response[i];
|
||
}
|
||
|
||
Serial.print("RX: ");
|
||
for (int i = 0; i < 16; i++)
|
||
{
|
||
Serial.print(response[i], HEX);
|
||
Serial.print(" ");
|
||
}
|
||
|
||
if (response[15] == checksum)
|
||
{
|
||
Serial.println("Checksum is OK");
|
||
}
|
||
else
|
||
{
|
||
Serial.println("Checksum is ERROR");
|
||
}
|
||
lastActivityTime = millis(); // Обновляем время последней активности
|
||
}
|
||
else
|
||
{
|
||
Serial.println("Received an incomplete response");
|
||
}
|
||
}
|
||
|
||
// Обновление состояния подключения
|
||
if (!wasConnected && client.connected())
|
||
{
|
||
wasConnected = true;
|
||
}
|
||
|
||
if (wasConnected && !client.connected())
|
||
{
|
||
wasConnected = false;
|
||
client.stop();
|
||
Serial.println("Client disconnected");
|
||
}
|
||
|
||
// Закрытие соединения по таймеру неактивности
|
||
if (client.connected() && (millis() - lastActivityTime > timeout))
|
||
{
|
||
wasConnected = false;
|
||
Serial.println("Connection closed due to inactivity");
|
||
client.stop();
|
||
}
|
||
}
|
||
|
||
|