ReuseConnection

はじめに

HTTPコネクションを再利用します。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
/**
 * reuseConnection.ino
 *
 *  Created on: 22.11.2015
 *
 */


#include <Arduino.h>

#include <WiFi.h>
#include <WiFiMulti.h>

#include <HTTPClient.h>

#define USE_SERIAL Serial

WiFiMulti wifiMulti;

HTTPClient http;
 

WiFiMulti型の変数wifiMultiを定義しています。WiFiMultiクラスは、複数のアクセスポイントを管理するためのクラスです。

HTTPClientクラスは、HTTPクライアントを実現するためのクラスです。

setup()

22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
void setup() {

    USE_SERIAL.begin(115200);

    USE_SERIAL.println();
    USE_SERIAL.println();
    USE_SERIAL.println();

    for(uint8_t t = 4; t > 0; t--) {
        USE_SERIAL.printf("[SETUP] WAIT %d...\n", t);
        USE_SERIAL.flush();
        delay(1000);
    }

    wifiMulti.addAP("SSID", "PASSWORD");

    // allow reuse (if server supports it)
    http.setReuse(true);
}
 

USE_SERIALは、Serialと定義されているので、前半はコンソールへの文字列の出力です。

wifiMullti.addAP()は、WiFiアクセスポイントの登録です。SSIDとPASSWORDは、各自の環境に合わせて変更する必要があります。

http.setReuse(true)を実行することで、HTTPコネクションを再利用するよう指示します。

loop()

42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
void loop() {
    // wait for WiFi connection
    if((wifiMulti.run() == WL_CONNECTED)) {

        http.begin("http://192.168.1.12/test.html");
        //http.begin("192.168.1.12", 80, "/test.html");

        int httpCode = http.GET();
        if(httpCode > 0) {
            USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);

            // file found at server
            if(httpCode == HTTP_CODE_OK) {
                http.writeToStream(&USE_SERIAL);
            }
        } else {
            USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
        }

        http.end();
    }

    delay(1000);
}

wifiMulti.run()は、wifiMullti.addAP()で登録したアクセスポイントに接続するメソッドです。接続に成功するとWL_CONNECTEDが返ってきます。

http.begin()は、アクセスしたいURLを登録します。

http.GET()は、http.begin()で登録したURLを、GETリクエストを使って取得します。サーバに接続できないなど、エラーの場合は、負の値が返ってきます。HTTP接続が成功した場合は、HTTPのステータスコードが返ってきます。

http.writeToStream()は、http.GET()で取得したデータをストリーム(今回はSerial)に書き出します。

http.end()は、TCPのコネクションを切断します。しかし、http.setReuse()を使い、コネクションの再利用の指示をしているので、コネクションの再利用が可能であれば切断しません。

http.GET()の呼び出しに失敗した場合は、http.errorToString()を呼び出して、エラーコードをエラーコードに対応した文字列に変換してから、表示します。

バージョン

Hardware:ESP-WROOM-32
Software:Arduino core for the ESP32 2.0.4

最終更新日

September 4, 2022

inserted by FC2 system