通过WiFi将数据从ESP32发送到服务器

问题描述 投票:0回答:1

我在这里并不陌生,但这是我的第一个问题。我进行了很多搜索,但坦率地说,我不明白这应该如何工作。我定期将数据(温度)获取到我的ESP32,并将其设置为WiFi客户端时,连接到路由器并以某种方式将此数据存储在我的笔记本电脑上(或其他地方,例如本地/网站,不知道这是可能/更好)。连接应该如何工作?我已经安装了XAMPP并运行Apache和MySQL服务器,并尝试使用ESP32库通过Arduino的一些草图连接到我的笔记本电脑]

    // Use WiFiClient class to create TCP connections
WiFiClient client;
const int httpPort = 80;
const char* host = "192.168.1.109";     //The local IP of my Laptop
if (!client.connect(host, httpPort)) {
    Serial.println("connection failed");
    return;
}

但是它没有连接。有人可以告诉我这种联系应该如何形成吗?还是这个问题太含糊?我真的只是想知道这种情况下的“应该如何一起工作”。预先谢谢你。

wifi esp32 local-network
1个回答
0
投票

好,所以经过大量研究和尝试,我设法解决了。现在,我可以使用XAMP将来自ESP32的HTTP请求(如GET或POST)发送到便携式计算机上运行的本地服务器,并获得响应。我还可以通过手机(也位于同一WiFi网络中)连接到本地IP。

对于要连接到本地网络中PC上托管的服务器中某个位置的其他任何人,这些步骤都是:

  • [使用诸如XAMPP(我有Windows 10,因此WAMP也可以使用)之类的应用程序在PC,笔记本电脑上创建本地服务器,下载,安装,打开并启动Apache。
  • 确保防火墙允许您的请求通过(对我来说,它默认是打开的,但是我在其他地方看到防火墙是个问题)
  • 转到您的网络设置,选择您的设备(ESP32,电话等)所连接的网络,并将其配置文件更改为“专用”,这意味着您信任该网络,从而使您的PC可以被发现并能够接受请求。 (这确实很简单,但是花了我几个小时才能找到)

现在,要从手机连接到PC,请打开浏览器,然后将PC的本地IP(即从路由器作为本地网络名称提供给PC的IP)输入浏览器,然后就是这样,您已连接。如果您安装并运行了XAMP,则从同一台PC或其他本地设备连接到本地IP时,它将转发到192.168.x.x / dashboard。如果要创建新的工作区和文件,请浏览安装位置的XAMP文件夹,并在“ / htdocs”子文件夹中进行测试。

用于Arduino中的ESP32通信(基本步骤,不是完整代码):

#include <WiFi.h>
#include <HTTPClient.h>

String host = "http://192.168.x.x/testfolder/";
String file_to_access = "test_post.php";
String URL = host + file_to_access;

void setup(){
 WiFi.begin(ssid, password); //Connect to WiFi

 HTTPClient http;

 bool http_begin = http.begin(URL);
 String message_name = "message_sent";
 String message_value = "This is the value of a message sent by the ESP32 to local server 
 via HTTP POST request";
 String payload_request = message_name + "=" + message_value;  //Combine the name and value
 http.addHeader("Content-Type", "application/x-www-form-urlencoded");
 int httpResponseCode = http.sendRequest("POST", payload_request);
 String payload_response = http.getString();
}

在test_post.php(位于“ C:\ xampp \ htdocs \ testfolder \”文件中)中,我使用了一个简单的脚本来回显通过POST请求接收到的消息,因此它只能从POST请求中“读取”。从浏览器连接到它会给您“抱歉,接受...”消息。

<?php
$message_received = "";
    if ($_SERVER["REQUEST_METHOD"] == "POST"){
        $message_received = $_POST["message_sent"];
        echo "Welcome ESP32, the message you sent me is: " . $message_received;
    }
    else {
        echo "Sorry, accepting only POST requests...";
    }
?>

最后,使用串行打印,输出为:

Response Code: 200
Payload: Welcome ESP32, the message you sent me is: This is the value of a message sent by the ESP32 to local server via HTTP POST request

希望有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.