• Уважаемые посетители сайта esp8266.ru!
    Мы отказались от размещения рекламы на страницах форума для большего комфорта пользователей.
    Вы можете оказать посильную поддержку администрации форума. Данные средства пойдут на оплату услуг облачных провайдеров для сайта esp8266.ru
  • Система автоматизации с открытым исходным кодом на базе esp8266/esp32 микроконтроллеров и приложения IoT Manager. Наша группа в Telegram

Нужна помощь WebServer

TAHKICT

New member
Написал сервер для мигания светодиодом.

Код:
#include <ESP8266WiFi.h>           
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

const String nodeId = "4";
const char* ssid = "*";
const char* password = "*";
const String serverURL = "http://192.168.1.129:8181";
const String aliveRequestURL = "/core-rest-api/for-nodes/alive-request-from-node";

ESP8266WebServer server(80);   //Web server object. Will be listening in port 80 (default for HTTP)

void setup() {
  pinMode(1,OUTPUT);
  pinMode(2,OUTPUT);
 
  Serial.begin(115200);
  WiFi.begin(ssid, password); //Connect to the WiFi network

  while (WiFi.status() != WL_CONNECTED) { //Wait for connection
    delay(500);
    Serial.println("Waiting to connect…");
  }

  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());  //Print the local IP to access the server

  sendAliveRequestToServer();
 
  server.on("/command-from-server", handleRequestFromServer); //Associate the handler function to the path
  server.begin();                                    //Start the server
  Serial.println("Server listening");  
}

void loop() {
  server.handleClient();    //Handling of incoming requests
}

void handleRequestFromServer() {
  String message = "";

  if (server.arg("switch")== ""){     //Parameter not found
    message = "Switch argument not found.";
  } else {     //Parameter found
    if(powerSocketSwitch(server.arg("switch")) == true){
      message = "Switched successfully.";
    } else {
      message = "Switched unsuccessfully. Command is not correct.";
    }   
  }

  server.send(200, "text/plain", message);    //Returns the HTTP response
}

boolean powerSocketSwitch(String command){
  if(command == "checked"){
    Serial.println("command checked");
    digitalWrite(1, HIGH);
    digitalWrite(2, HIGH);
    return true;
  } else if(command == "unchecked"){
    Serial.println("command unchecked");
    digitalWrite(1, LOW);
    digitalWrite(2, LOW);
    return true;
  }
  return false;
}

void sendAliveRequestToServer() {
  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
   
    Serial.println("send Alive Request To Server: " + serverURL + aliveRequestURL + "?id=" + nodeId);
    HTTPClient http;  //Declare an object of class HTTPClient
    http.begin(serverURL + aliveRequestURL + "?id=" + nodeId);  //Specify request destination
    int httpCode = http.GET();                                  //Send the request
    if (httpCode > 0) { //Check the returning code
      String payload = http.getString();   //Get the request response payload
      Serial.println(payload);                     //Print the response payload
    }
    http.end();   //Close connection
  }
}
Возвращает ответ про то что все отработало нормально, но по факту светодиод не загорается.

P.S. Скетч, в котором я не разворачиваю сервер и просто мигаю диодом работает нормально.

Подскажите пожалуйста, что не так?
 

TAHKICT

New member
Причину чего лед не мигал нашел. Оказалось был конфликт с Serial.begin.
Рабочий скетч:
Код:
#include <ESP8266WiFi.h>          
#include <ESP8266WebServer.h>
#include <ESP8266HTTPClient.h>

const String nodeId = "4";
const char* ssid = "*";
const char* password = "*";
const String serverURL = "http://192.168.1.129:8181";
const String aliveRequestURL = "/core-rest-api/for-nodes/alive-request-from-node";

ESP8266WebServer server(80);   //Web server object. Will be listening in port 80 (default for HTTP)

void setup() {
  pinMode(1,OUTPUT);
 
  WiFi.begin(ssid, password); //Connect to the WiFi network

  while (WiFi.status() != WL_CONNECTED) { //Wait for connection
    delay(500);
  }

  sendAliveRequestToServer();
 
  server.on("/command-from-server", handleRequestFromServer); //Associate the handler function to the path
  server.begin();                                    //Start the server
}

void loop() {
  server.handleClient();    //Handling of incoming requests
}

void handleRequestFromServer() {
  String message = "";

  if (server.arg("switch")== ""){     //Parameter not found
    message = "Switch argument not found.";
  } else {     //Parameter found
    if(powerSocketSwitch(server.arg("switch")) == true){
      message = "Switched successfully.";
    } else {
      message = "Switched unsuccessfully. Command is not correct.";
    }  
  }

  server.send(200, "text/plain", message);    //Returns the HTTP response
}

boolean powerSocketSwitch(String command){
  if(command == "unchecked"){
    digitalWrite(1, HIGH);
    return true;
  } else if(command == "checked"){
    digitalWrite(1, LOW);
    return true;
  }
  return false;
}

void sendAliveRequestToServer() {
  if (WiFi.status() == WL_CONNECTED) { //Check WiFi connection status
  
    HTTPClient http;  //Declare an object of class HTTPClient
    http.begin(serverURL + aliveRequestURL + "?id=" + nodeId);  //Specify request destination
    int httpCode = http.GET();                                  //Send the request
    if (httpCode > 0) { //Check the returning code
      String payload = http.getString();   //Get the request response payload
    }
    http.end();   //Close connection
  }
}
Хочу обратить на участок кода, который работает ровно наоборот, чем я задумывал
Код:
boolean powerSocketSwitch(String command){
  if(command == "unchecked"){
    digitalWrite(1, HIGH);
    return true;
  } else if(command == "checked"){
    digitalWrite(1, LOW);
    return true;
  }
  return false;
}
Команда "checked" у меня приходит когда диод должен включиться, а получалось наоборот. Поэтому я поменял местами. Но хотелось бы узнать почему так. Кто-нибудь в курсе?
 

tretyakov_sa

Moderator
Команда форума
Команда "checked" у меня приходит когда диод должен включиться, а получалось наоборот. Поэтому я поменял местами. Но хотелось бы узнать почему так. Кто-нибудь в курсе?
Если вы о встроенном диоде то он загорается когда на выходи LOW и гаснет когда на выходе HIGH.
 
Сверху Снизу