From 9d9410087703348704f2f9d339b7616e8da2f55d Mon Sep 17 00:00:00 2001 From: NanamiAdmin Date: Fri, 15 Aug 2025 12:43:14 +0800 Subject: [PATCH] modified: src/main.cpp --- src/main.cpp | 46 ++++++++++++++++++++++++++++++++++------------ 1 file changed, 34 insertions(+), 12 deletions(-) diff --git a/src/main.cpp b/src/main.cpp index 39d7935..26f1817 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -133,9 +133,42 @@ void setup() { } } +void executeCommand(String user_command, WiFiClient* client, int Mode) { // Mode 0: Serial, Mode 1: TCP + if (user_command == "temp.read") { + float temperature = dht22.readTemperature(); + if (Mode == 0){ + Serial.printf("Temperature: %.2f °C\n", temperature); + } + if (Mode == 1 && client && *client) { + client->println(temperature); + } + user_command = ""; // Clear command after processing + } + if (user_command == "hum.read") { + float humidity = dht22.readHumidity(); + if (Mode == 0){ + Serial.printf("Humidity: %.2f %%\n", humidity); + } + if (Mode == 1 && client && *client) { + client->println(humidity); + } + user_command = ""; // Clear command after processing + } +} + void loop() { String user_command; WiFiClient client; // Declare client at the start + + // Serial command handling + if (Serial.available()) { + String user_command = Serial.readStringUntil('\n'); // Read serial command + user_command.trim(); // Remove whitespace + Serial.printf("Received command: %s\n", user_command.c_str()); // Print received command + executeCommand(user_command, nullptr, 0); // Pass nullptr for Serial mode + } + + // TCP command handling if(server.hasClient()) { // Check if there is a client connected Serial.println("A new client connected to web server."); server.setNoDelay(true); @@ -151,21 +184,10 @@ void loop() { currentLine.trim(); // Remove whitespace user_command = currentLine; Serial.printf("Received command: %s\n", user_command.c_str()); + executeCommand(user_command, &client, 1); // Pass pointer for TCP mode } } } } } - if (user_command == "temp.read") { - float temperature = dht22.readTemperature(); - client.println(temperature); - Serial.printf("Temperature: %.2f °C\n", temperature); - user_command = ""; // Clear command after processing - } - if (user_command == "hum.read") { - float humidity = dht22.readHumidity(); - client.println(humidity); - Serial.printf("Humidity: %.2f %%\n", humidity); - user_command = ""; // Clear command after processing - } } \ No newline at end of file