StreamHttpClient

はじめに

Streamを用いたHTTPクライアントです。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
/**
 * StreamHTTPClient.ino
 *
 *  Created on: 24.05.2015
 *
 */

#include <Arduino.h>

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

#include <HTTPClient.h>

#define USE_SERIAL Serial

WiFiMulti wifiMulti;
 

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

setup()

19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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");

}
 

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

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

loop()

37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
void loop() {
    // wait for WiFi connection
    if((wifiMulti.run() == WL_CONNECTED)) {

        HTTPClient http;

        USE_SERIAL.print("[HTTP] begin...\n");

        // configure server and url
        http.begin("http://192.168.1.12/test.html");
        //http.begin("192.168.1.12", 80, "/test.html");

        USE_SERIAL.print("[HTTP] GET...\n");
        // start connection and send HTTP header
        int httpCode = http.GET();
        if(httpCode > 0) {
            // HTTP header has been send and Server response header has been handled
            USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode);

            // file found at server
            if(httpCode == HTTP_CODE_OK) {

                // get length of document (is -1 when Server sends no Content-Length header)
                int len = http.getSize();

                // create buffer for read
                uint8_t buff[128] = { 0 };

                // get tcp stream
                WiFiClient * stream = http.getStreamPtr();

                // read all data from server
                while(http.connected() && (len > 0 || len == -1)) {
                    // get available data size
                    size_t size = stream->available();

                    if(size) {
                        // read up to 128 byte
                        int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size));

                        // write it to Serial
                        USE_SERIAL.write(buff, c);

                        if(len > 0) {
                            len -= c;
                        }
                    }
                    delay(1);
                }

                USE_SERIAL.println();
                USE_SERIAL.print("[HTTP] connection closed or file end.\n");

            }
        } else {
            USE_SERIAL.printf("[HTTP] GET... failed, error: %s\n", http.errorToString(httpCode).c_str());
        }

        http.end();
    }

    delay(10000);
}

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

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

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

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

http.getSize()は、HTTPレスポンスボディの長さ(content-length)を返します。

http.getStreamPtr()は、HTTPコネクションのデータストリームへのポインタを返します。このポインタから、順次データを取得することができます。この関数の戻り値は、WiFiClientへのポインタ型です。

69行目のwhile文では、未読み込みの文字がなくなるまで(lenが正の間)、データの読み出しを繰り返します。

http.connected()は、HTTPコネクションが確立されていればtrueを返し、切断されていればfalseを返します。

stream->available()は、Serialを利用するときのavailable()と同じで、読み取り可能なデータのバイト数を返します。データがある時は、stream->readBytes()を利用し、データを読み取ります。

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

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

BasicHttpClientで利用した、http.getSting()は、取得したHTTPレスポンスのボディをすべてString型として返却するため、メモリをより多く消費する可能性が高いです。こちらは、順次読み込んでいくので、メモリを節約できる可能性があります。ただし、データをためておく必要がある時は、結局、レスポンスのボディ分だけメモリが必要となります。

バージョン

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

最終更新日

September 4, 2022

inserted by FC2 system