@FlashDok

ESP8266 можно ли запустить web-server на ap/client ip сразу?

Разбираюсь с ESP8266 (пока код для общего познания, код не имеет особого смысла кроме как изучение).
Сейчас МК настроен в режиме AP и Client, запускаю web-server и он запускается на AP IP, т.е web доступен только если подключится к ESP8266 как к AP, также МК подключена в локальную wifi-сеть и там уже web сервер не доступен.
Собственно вопрос как определяется на каком IP запускается сервер и можно ли самому указать ip?

Код
#include <ESP8266WiFi.h>
#include <WiFiClient.h>
#include <ESP8266WebServer.h>
#include <EEPROM.h>

const char* apSSID = "ESP8266_AP";
const char* apPassword = "password";
const int maxAttempts = 5;
const int eepromOffset = 0;

ESP8266WebServer server(80);
int ledPin = 2;
bool ledState = false;
bool connectedToWiFi = false;

String getHTMLHeader() {
  String header = "<!DOCTYPE html><html><head><style>";
  header += "body { font-family: Arial, Helvetica, sans-serif; margin: 20px; }";
  header += "h1 { color: #333; }";
  header += "label { display: block; margin-top: 10px; }";
  header += "input[type=text], input[type=password] { width: 100%; padding: 8px; }";
  header += "button { padding: 8px 16px; background-color: #4CAF50; color: white; border: none; cursor: pointer; }";
  header += ".container { margin-top: 20px; }";
  header += ".container:after { content: ''; display: table; clear: both; }";
  header += ".left { width: 50%; float: left; }";
  header += ".right { width: 50%; float: right; }";
  header += "</style></head><body>";
  return header;
}

void handleRoot() {
  String output = getHTMLHeader();

  if (!connectedToWiFi) {
    output += "<h1>Wi-Fi Configuration</h1>";
    output += "<div class=\"container\">";
    output += "<div class=\"left\">";
    output += "<form action=\"/config\" method=\"POST\">";
    output += "<label for=\"ssid\">SSID:</label>";
    output += "<input type=\"text\" id=\"ssid\" name=\"ssid\"><br>";
    output += "<label for=\"password\">Password:</label>";
    output += "<input type=\"password\" id=\"password\" name=\"password\"><br>";
    output += "<button type=\"submit\">Save</button>";
    output += "</form>";
    output += "</div>";
  } else {
    output += "<h1>ESP8266 LED Control</h1>";
    output += "<div class=\"container\">";
    output += "<div class=\"left\">";
    output += "<p>LED Pin - State: " + String(ledState) + "</p>";
    output += "<form action=\"/toggle\" method=\"POST\">";
    output += "<button type=\"submit\">Toggle LED</button>";
    output += "</form>";
    output += "</div>";
  }
  
  output += "</div></body></html>";
  server.send(200, "text/html", output);
}

void handleConfig() {
  String ssid = server.arg("ssid");
  String password = server.arg("password");

  EEPROM.begin(512);
  for (int i = 0; i < ssid.length(); i++) {
    EEPROM.put(eepromOffset + i, ssid[i]);
  }
  EEPROM.put(eepromOffset + ssid.length(), '\0');
  for (int i = 0; i < password.length(); i++) {
    EEPROM.put(eepromOffset + ssid.length() + 1 + i, password[i]);
  }
  EEPROM.put(eepromOffset + ssid.length() + 1 + password.length(), '\0');
  EEPROM.commit();
  EEPROM.end();

  WiFi.begin(ssid.c_str(), password.c_str());
  int attempts = 0;
  String message;
  while (WiFi.status() != WL_CONNECTED && attempts < maxAttempts) {
    delay(1000);
    attempts++;
    message = "Connection attempt " + String(attempts) + " of " + String(maxAttempts);
    Serial.println(message);
  }
  
  if (WiFi.status() == WL_CONNECTED) {
    connectedToWiFi = true;
    message = "Connected to Wi-Fi";
    Serial.println(message);
  } else {
    message = "Failed to connect to Wi-Fi";
    Serial.println(message);
  }

  server.send(200, "text/html", getHTMLHeader() + "<h1>" + message + "</h1></body></html>");
}

void handleToggle() {
  ledState = !ledState;
  digitalWrite(ledPin, ledState);
  handleRoot();
}

void setup() {
  Serial.begin(9600);

  EEPROM.begin(512);
  String storedSSID = "";
  char ch;
  int i;
  for (i = 0; i < 32; ++i) {
    EEPROM.get(eepromOffset + i, ch);
    if (ch == '\0') break;
    storedSSID += ch;
  }
  String storedPassword = "";
  for (int j = i + 1; j < 64; ++j) {
    EEPROM.get(eepromOffset + j, ch);
    if (ch == '\0') break;
    storedPassword += ch;
  }
  EEPROM.end();

  if (storedSSID != "" && storedPassword != "") {
    WiFi.begin(storedSSID.c_str(), storedPassword.c_str());
    int attempts = 0;
    String message;
    while (WiFi.status() != WL_CONNECTED && attempts < maxAttempts) {
      delay(3000);
      attempts++;
      message = "Connection attempt " + String(attempts) + " of " + String(maxAttempts);
      Serial.println(message);
    }
    
    if (WiFi.status() == WL_CONNECTED) {
      connectedToWiFi = true;
      message = "Connected to Wi-Fi";
      Serial.println(message);
      Serial.println(WiFi.localIP());
    } 
  }
  WiFi.mode(WIFI_AP);
  WiFi.softAP(apSSID, apPassword);
  Serial.println("Started AP mode");
  Serial.print("AP IP address: ");
  Serial.println(WiFi.softAPIP());

  pinMode(ledPin, OUTPUT);
  digitalWrite(ledPin, LOW);

  server.on("/", handleRoot);
  server.on("/config", handleConfig);
  server.on("/toggle", handleToggle);
  server.begin();
}

void loop() {
  server.handleClient();
}
  • Вопрос задан
  • 98 просмотров
Пригласить эксперта
Ответы на вопрос 2
@kalapanga
Как я понимаю, хотя одновременная работа сразу в двух режимах (STA + AP) действительно возможна, но кроме того, что "This provides the possibility of building e.g. mesh networks." эта функция более никак не документирована и производителем особо не поддерживается. Поэтому однозначно сказать, нормальное у Вашего устройства поведение или нет, нельзя. Нигде не описано, а как должно быть.
Если вдруг что не так, надеюсь, меня поправят.
Ответ написан
Комментировать
gashopper
@gashopper
За Ваши деньги - хоть луноход.
IPAddress local_ip(192,168,1,1); // IP-адрес сервера, к которому надо подключаться (вводить в браузере)
IPAddress gateway(192,168,1,1);
IPAddress subnet(255,255,255,0);

ввести перед
ESP8266WebServer server(80);
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы