WEB клиент Ethernet.h

А что, если в POST подсунуть “Connection: close”, разрыва не происходит?

RFC не диктует применение данного хидера исключительно с GET.

HTTP/1.1 defines the “close” connection option for the sender to signal that the connection will be closed after completion of the response. For example,

Connection: close

in either the request or the response header fields indicates that the connection SHOULD NOT be considered `persistent’ (section 8.1) after the current request/response is complete. HTTP/1.1 applications that do not support persistent connections MUST include the “close” connection option in every message.

Спойлер

Start
Status = 0
Status = 0
Status = 0
Status = 0
Status = 0
Status = 0
Status = 0
Status = 0
Status = 0
CONNECTION_FAILED
Status = 0
Status = 0
Status = 0
Status = 0
Status = 0

#include <SPI.h>
#include <Ethernet.h>
#include <avr/wdt.h>

#define PORT_NUMBER 80

const uint8_t mac[] = {0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
const uint8_t ip[] = {192, 168, 1, 88};
const uint8_t gateway[] = {192, 168, 1, 1};
const uint8_t subnet[] = {255, 255, 255, 0};
const uint8_t dns[] = {192, 168, 1, 1};
const uint8_t server[] = {192, 168, 1, 42};
EthernetClient client;

void setup() {
  wdt_disable();
  Serial.begin(9600);
  Ethernet.begin(mac, ip, dns, gateway, subnet);
  Serial.println("Start");
  wdt_enable(WDTO_8S);
}

//bool request_post = false;
//uint32_t request_post_tmr;

void http_request_post() {
  if (client.connect(server, PORT_NUMBER)) {
    client.print(F("POST /12.php HTTP/1.1\r\n"));
    client.print(F("User-Agent: ARDUINO\r\n"));
    client.print(F("Host: "));
    for (uint8_t i = 0; i < 4; i++) {
      client.print(server[i]);
      if (i < 3)client.print(".");
    }
    client.print(F("\r\n"));
    client.print(F("Content-Type: application/x-www-form-urlencoded\r\n"));
    client.print(F("Content-Length: 9 \r\n"));
    client.print(F("\r\n"));
    client.print(F("text=1234"));
    client.print(F("\r\n"));
    client.print("Connection: close\r\n\r\n");
    //request_post = true;
   // request_post_tmr = millis();
  } else {
    Serial.println("CONNECTION_FAILED");
    client.stop();
  }
}



void get_response() {
  if (client.available()) {
    char c = client.read();
    Serial.print(c);
    //request_post_tmr = millis();
  }
}


void loop() {
  wdt_reset();
  get_response();

 // if (request_post && millis() - request_post_tmr >= 500) {
   // Serial.println("CLIENT_STOP");
   // request_post = false;
   // client.stop();
  //}


  static uint32_t timer_status;
  if (millis() - timer_status >= 500) {
    timer_status = millis();
    Serial.print("Status = ");
    Serial.print(client.connected());
    Serial.println("");
  }


  static uint32_t timer;
  if (millis() - timer >= 5000) {
    timer = millis();
    http_request_post();
  }

}

Зачем хидер в тело засунули?
Первая строка - метод, далее все хидеры, затем пустая строка и боди.
Сейчас этот хидер бессмысленнен.

void http_request_post() {
  if (client.connect(server, PORT_NUMBER)) {
    client.print(F("POST /12.php HTTP/1.1\r\n"));
    client.print(F("Host: 192.168.1.42\r\n"));
    client.print(F("User-Agent: ARDUINO\r\n"));
    client.print(F("Content-Type: application/x-www-form-urlencoded\r\n"));
    client.print(F("Content-Length: 9 \r\n\r\n"));
    client.print(F("text=1234"));
    client.print(F("\r\n"));
    client.print("Connection: close\r\n\r\n");
    //request_post = true;
    // request_post_tmr = millis();
  } else {
    Serial.println("CONNECTION_FAILED");
    client.stop();
  }
}

Ответ

Start
Status = 0
Status = 0
Status = 0
Status = 0
Status = 0
HTTP/1.1 200 OK
Date: Fri, 30 Dec 2022 15:39:15 GMT
Content-Type: text/html; charset=UTF-8
Content-LengtStatus = 1
h: 17
Connection: keep-alive
Keep-Alive: timeout=120
Server: Apache
X-Content-Type-Options: nosniff

Text_POST= 1234
HTTP/1.1 400 Bad Request
Server: nginx
Date: Fri, 30 Dec 2022 15:39:15 GMT
Content-Type: text/html
Content-Length: 150
Connection: close

<html>
<head><title>400 Bad Request</title></head>
<body>
<center><h1>400 Bad Request</h1></center>
<hr><center>nginx</center>
</body>
</html>
Status = 0
Status = 0
Status = 0

Ох, беда-беда, огорчение

...
    client.print("Connection: close\r\n");
    client.print(F("Content-Type: application/x-www-form-urlencoded\r\n"));
    client.print(F("Content-Length: 9 \r\n\"));
    client.print(F("\r\n"));
    client.print(F("text=1234"));
    client.print(F("\r\n"));
    
1 лайк
void http_request_post() {
  if (client.connect(server, PORT_NUMBER)) {
    client.print(F("POST /12.php HTTP/1.1\r\n"));
    client.print(F("Host: 192.168.1.42\r\n"));
    client.print(F("User-Agent: ARDUINO\r\n"));
    client.print("Connection: close\r\n");
    client.print(F("Content-Type: application/x-www-form-urlencoded\r\n"));
    client.print(F("Content-Length: 9 \r\n\r\n"));
    client.print(F("text=1234"));
    client.print(F("\r\n"));

    //request_post = true;
    // request_post_tmr = millis();
  } else {
    Serial.println("CONNECTION_FAILED");
    client.stop();
  }
}

tart
Status = 0
Status = 0
Status = 0
Status = 0
Status = 0
HTTP/1.1 200 OK
Date: Fri, 30 Dec 2022 16:07:12 GMT
Content-Type: text/html; charset=UTF-8
Content-LengStatus = 1
th: 17
Connection: close
Server: Apache
X-Content-Type-Options: nosniff

Text_POST= 1234
Status = 0
Status = 0
Status = 0
Status = 0
Status = 0
HTTP/1.1 200 OK
Date: Fri, 30 Dec 2022 16:07:15 GMT
Content-Type: text/html; charset=UTF-8
Content-LengtStatus = 1
h: 17
Connection: close
Server: Apache
X-Content-Type-Options: nosniff

Text_POST= 1234
Status = 0
Status = 0
Status = 0

Т.е. работает?

1 лайк

Да. Спасибо.

Здравствуйте. Помогайте)

Спойлер
#include <SPI.h>
#include <Ethernet.h>
#include <avr/wdt.h>
#include <Wiegand.h>

//Отладка
#define DEBUG
#ifdef DEBUG
#define DEBUG
#define SERIAL_BEGIN Serial.begin(19200)
#define DEBUG_PRINT(x) Serial.print(x)
#define DEBUG_PRINTLN(x) Serial.println(x)
#else
#define DEBUG_PRINT(x)
#define DEBUG_PRINTLN(x)
#define SERIAL_BEGIN
#endif
//Отладка

WIEGAND wg;
uint32_t numcard = 0;
#include "W5500.h"

void setup() {
  wdt_disable();
  Ethernet.begin(mac, ip, dns, gateway, subnet);
  delay(1000);
  wg.begin();
  SERIAL_BEGIN;
  DEBUG_PRINTLN("Start");
  wdt_enable(WDTO_8S);
}


void loop() {
  wdt_reset();
  w5500_read();

  if (wg.available()) {
    numcard = wg.getCode();
    Serial.println(numcard);
    if (numcard > 0) http_request_get();
  }
}

W5500.h

//#include "W5500.h"

const uint8_t mac[] = { 0xDE, 0xAD, 0xBE, 0xEF, 0xFE, 0xED };
const uint8_t ip[] = { 192, 168, 0, 105 };
const uint8_t gateway[] = { 192, 168, 0, 1 };
const uint8_t subnet[] = { 255, 255, 255, 0 };
const uint8_t dns[] = { 192, 168, 0, 1 };
const uint8_t server[] = { 192, 168, 0, 25 };
const uint8_t port = 80;

const uint8_t max_buf = 100;
char buffers[max_buf];
uint8_t pos_buf;

EthernetClient client;

void buf_clear() {
  memset(buffers, 0, max_buf);
  pos_buf = 0;
}

void w5500_read() {

  if (client.available()) {
    uint8_t temp = client.read();
    if (temp) {
      buffers[pos_buf] = temp;
      pos_buf++;
      if (pos_buf >= max_buf) {
        buf_clear();
      } else {
        
        if (temp == '\n' && pos_buf > 1 && buffers[pos_buf - 2] == '\r') {
          if (strstr(buffers, "#") != NULL) {
            DEBUG_PRINTLN(buffers);
          }
          buf_clear();
        }
      }
    }
  }
}

void http_request_get() {
  client.stop();
  delay(10);
  if (client.connect(server, port)) {
    DEBUG_PRINTLN("СONNECTED");
    client.print(F("GET /auto.php?numcard="));
    client.print(numcard);
    client.print(F(" HTTP/1.1\r\n"));
    client.print(F("User-Agent: Arduino\r\n"));
    client.print(F("Host: 192.168.0.25\r\n"));
    client.print(F("Connection: close\r\n\r\n"));
  } else {
    DEBUG_PRINTLN("CONNECTION_FAILED");
  }
}

auto.php

<?php
$numcard = preg_replace('/[^0-9]/', '', $_GET['numcard']);
$card_hex = dechex($numcard);
$serial_hex = substr($card_hex, 0, 2);
$number_hex = substr($card_hex, 2, 4);
$card_seria = hexdec($serial_hex);
$card_number = hexdec($number_hex);

echo $card_seria . "---" . $card_number . "#";
?>

Прикладываю к считывателю разные карты, а в мониторе порта получаю следующее:

8637075
СONNECTED
131---51859#HTTP/1.1 200 OK

1103923
СONNECTED
131---51859#HTTP/1.1 200 OK

Считыватель выдаёт верные номера карты, разные, а в ответе на запрос я получаю одну и туже информацию, но если приложить пропуск еще раз, все ок.

1103923
СONNECTED
16---55347#HTTP/1.1 200 OK

1103923
СONNECTED
16---55347#HTTP/1.1 200 OK

1103923
СONNECTED
16---55347#HTTP/1.1 200 OK

8637075
СONNECTED
16---55347#HTTP/1.1 200 OK

8637075
СONNECTED
131---51859#HTTP/1.1 200 OK


13-14-15 строки, приложила другую карту, 17-18-19 строки приложила эту же карту еще раз

помогло ?)))

if (numcard > 0) {
  http_request_get();
  numcard = 0;  // Сброс значения после отправки
}

И так пробовала, хотя считыватель каждый раз обновляет значение, в мониторе порта оно верное.

if (client.connect(server, port)) {
    DEBUG_PRINTLN("СONNECTED");
    client.print(F("GET /auto.php?numcard="));
    client.print(numcard);
    client.print(F("&times="));
    client.print(millis());
    client.print(F(" HTTP/1.1\r\n"));
    client.print(F("User-Agent: Arduino\r\n"));
    client.print(F("Host: 192.168.0.25\r\n"));
    client.print(F("Connection: close\r\n\r\n"));

И вот так делала

8637075 -- 1 карта (значение со считывателя)
СONNECTED
8637075---131---51859#HTTP/1.1 200 OK

8637075 -- 1 карта (значение со считывателя)
СONNECTED
8637075---131---51859#HTTP/1.1 200 OK

8637075 -- 1 карта (значение со считывателя)
СONNECTED
8637075---131---51859#HTTP/1.1 200 OK

1103923 -- 2 карта (значение со считывателя)
СONNECTED
8637075---131---51859#HTTP/1.1 200 OK

1103923 -- 2 карта (значение со считывателя)
СONNECTED
1103923---16---55347#HTTP/1.1 200 OK

Сделала такую проверку

  if (!flag && millis() - tims >= 3000) {
    flag = true;
    tims = millis();
    numcard = 1103923;
    http_request_get();
  }

  if (flag && millis() - tims >= 3000) {
    flag = false;
    tims = millis();
    numcard = 8637075;
    http_request_get();
  }

Что за бред? Почему так?

СONNECTED
card = 8637075
1103923---16---55347#HTTP/1.1 200 OK

СONNECTED
card = 1103923
8637075---131---51859#HTTP/1.1 200 OK

СONNECTED
card = 8637075
1103923---16---55347#HTTP/1.1 200 OK

СONNECTED
card = 1103923
8637075---131---51859#HTTP/1.1 200 OK

СONNECTED
card = 8637075
1103923---16---55347#HTTP/1.1 200 OK

Изменила php

<?php

$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPRQSTUVWXYZ0123456789";
$code = "";
$clen = strlen($chars) - 1;

while (strlen($code) < 9) {
    $code .= $chars[mt_rand(0, $clen)];
}

$numcard = preg_replace('/[^0-9]/', '', $_GET['numcard']);
$card_hex = dechex($numcard);
$serial_hex = substr($card_hex, 0, 2);
$number_hex = substr($card_hex, 2, 4);
$card_seria = hexdec($serial_hex);
$card_number = hexdec($number_hex);

echo $_GET['numcard'] . "---" . $code ."#";
?>

Получаю

СONNECTED
card = 8637075
1103923---EC2L7FIy4#HTTP/1.1 200 OK

СONNECTED
card = 1103923
8637075---R8ppMcbJb#HTTP/1.1 200 OK

СONNECTED
card = 8637075
1103923---JUmX8hT6Y#HTTP/1.1 200 OK

СONNECTED
card = 1103923
8637075---uzrxTdQ1a#HTTP/1.1 200 OK
void loop() {
wdt_reset();
w5500_read();
if (wg.available()) {
uint32_t currentCard = wg.getCode();  // Локальная переменная
if (currentCard != numcard) {         // Только если карта изменилась
numcard = currentCard;
DEBUG_PRINTLN(numcard);
http_request_get(); }
}
}

а что будет если везде насувать delay ?)))

void setup() {
  wdt_disable();
  Ethernet.begin(mac, ip, dns, gateway, subnet);
  delay(1000);
  wg.begin();
delay(100);
  SERIAL_BEGIN;
  DEBUG_PRINTLN("Start");
  wdt_enable(WDTO_8S);
}
 if (numcard > 0) http_request_get();
delay(100);

Наставила, не помогло(

СONNECTED
card = 8637075
8637075---8TpPbXBC4#HTTP/1.1 200 OK

СONNECTED
card = 8637075
8637075---Staa2EejR#HTTP/1.1 200 OK

СONNECTED
card = 1103923
8637075---qJjUoPlY1#HTTP/1.1 200 OK

СONNECTED
card = 1103923
1103923---IXVbpGUmv#HTTP/1.1 200 OK

Изменила код приёма

  if (client.available()) {
    char c = client.read();
    Serial.print( c );
  }

СONNECTED
numbers = 8637075
HTTP/1.1 200 OK
Date: Fri, 25 Jul 2025 11:01:36 GMT
Server: Apache
Content-Length: 8
Connection: close
Content-Type: text/html; charset=UTF-8

8637075#
СONNECTED
numbers = 1103923
HTTP/1.1 200 OK
Date: Fri, 25 Jul 2025 11:01:47 GMT
Server: Apache
Content-Length: 8
Connection: close
Content-Type: text/html; charset=UTF-8

1103923#

Всё стало правильно. В чём косяк?

uint8_t или uint32_t не вмещал данные ?)))
но скорее всего что то с символом \n было связанно, то ли он был толи наоборот не было))) но это не точно, а пальцем в небо

не понимаю код… он точно будет работать ? или он только первый символ проверяет ?)))

не поняла про что это

какой именно?

    char c = client.read();

char c передает символ за символом ? а не 1 символ 1 раз… верно ?)))
и если так, то наверное что то символом конца строки связанно,(\n) передавая по 1 символу, условие срабатывает… пока нет вывода с символом конца строки

а вот если char “C” не передает символ за символом, а передает только 1 символ, будет срабатывать на похожую карту…