04/28(火)ジャンボタニシ・ESP32 httpsテスト

近所の田んぼへジャンボタニシ観察、ヨット、床屋

ESP32側 https 証明書送信テスト(これ昨日)

PlatformIO イベント部(C++)

ESP32
void func_T5_GPIO12() {

    Serial.println("[T5] HTTPS POST with Cert");
    unsigned long start = millis();

    if (connectWiFi()) {
        WiFiClientSecure client;
        
        // ファイルから証明書を読み込む
        File f = LittleFS.open("/LetsEncrypt_ISRGX1.cert", "r");
        if (f) {
            String cert = f.readString();
            f.close();
            client.setCACert(cert.c_str());
        } else {
            Serial.println("Cert file not found, using insecure mode.");
            client.setInsecure();
        }

        HTTPClient https;
        if (https.begin(client, "https://test.lin.jp")) {
            https.addHeader("Content-Type", "text/plain");
            int code = https.POST("{\"host\":\"esp32\",\"key\":\"temp\",\"value\":25}");
            
            Serial.printf("HTTPS Code: %d\n", code);
            Serial.println(https.getString());
            https.end();
        }

    }

サーバー側

flask (python)

import os

from markupsafe import escape
from flask import Flask, request ,Response

app = Flask(__name__, static_folder="static", static_url_path="/")
from werkzeug.middleware.proxy_fix import ProxyFix
app.wsgi_app = ProxyFix( app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 )

@app.route("/", methods=["POST"])
@app.route("/<path:subpath>", methods=["POST"])
def receive(subpath="upload"):
    content_type = request.content_type or ""

    # multipart/form-data の場合
    if "multipart/form-data" in content_type:
        print("=== multipart/form-data ===")

        # file upload
        for field_name in request.files:
            files = request.files.getlist(field_name)

            for i, file in enumerate(files):
                filename = f"{field_name}_{i}.bin"
                file.save(filename)
                print(f"Saved {filename}")

        # 通常フォームデータ
        for field_name in request.form:
            values = request.form.getlist(field_name)

            for i, value in enumerate(values):
                filename = f"{field_name}_{i}.txt"
                with open(filename, "w", encoding="utf-8") as f:
                    f.write(value)

                print(f"Saved {filename}")

    else:
        body = request.get_data()

        print("=== REQUEST ===")
        print("Path:", request.path)
        print("Headers:\n", request.headers)
        print("Body:\n", body.decode(errors="ignore"))

    #//return "OK\n", 200
    return Response(
        "OK",
        status=200,
        headers={
            "Content-Length": "2",
            "Connection": "close"
        }
    )

if __name__ == "__main__":
    print("Listening on http://0.0.0.0:5000")
    app.run(host="0.0.0.0", port=5000)