WiFiClient

はじめに

HTTP GETを利用して、data.sparkfun.com serviceからデータを取得します。

プログラム

定義等

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
/*
 *  This sketch sends data via HTTP GET requests to data.sparkfun.com service.
 *
 *  You need to get streamId and privateKey at data.sparkfun.com and paste them
 *  below. Or just customize this script to talk to other HTTP servers.
 *
 */

#include <WiFi.h>

const char* ssid     = "your-ssid";
const char* password = "your-password";

const char* host = "data.sparkfun.com";
const char* streamId   = "....................";
const char* privateKey = "....................";
 

ssidとpasswordは、自分の環境に合わせて設定してください。

hostは接続先のホスト、streamIdとprivateKeyは、data.sparkfun.comにアクセスする際に必要なIDとキー情報のようです。

setup()

18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
void setup()
{
    Serial.begin(115200);
    delay(10);

    // We start by connecting to a WiFi network

    Serial.println();
    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(ssid);

    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(500);
        Serial.print(".");
    }

    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}
 

WiFi.begin()により、ssidで指定したアクセスポイントに接続します。この際のパスフレーズは、passwordです。WiFiは、WiFi.cppで定義されている事前に変数です。

WiFi.status()は、現在の接続状態を返却します。アクセスポイントに接続しているときは、WL_CONNECTEDが返ってきます。

WiFi.localIP()は、現在割り当てられているIPアドレスを返却します。

loop()

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
int value = 0;

void loop()
{
    delay(5000);
    ++value;

    Serial.print("connecting to ");
    Serial.println(host);

    // Use WiFiClient class to create TCP connections
    WiFiClient client;
    const int httpPort = 80;
    if (!client.connect(host, httpPort)) {
        Serial.println("connection failed");
        return;
    }

    // We now create a URI for the request
    String url = "/input/";
    url += streamId;
    url += "?private_key=";
    url += privateKey;
    url += "&value=";
    url += value;

    Serial.print("Requesting URL: ");
    Serial.println(url);

    // This will send the request to the server
    client.print(String("GET ") + url + " HTTP/1.1\r\n" +
                 "Host: " + host + "\r\n" +
                 "Connection: close\r\n\r\n");
    unsigned long timeout = millis();
    while (client.available() == 0) {
        if (millis() - timeout > 5000) {
            Serial.println(">>> Client Timeout !");
            client.stop();
            return;
        }
    }

    // Read all the lines of the reply from server and print them to Serial
    while(client.available()) {
        String line = client.readStringUntil('\r');
        Serial.print(line);
    }

    Serial.println();
    Serial.println("closing connection");
}

54行目で、WiFiClient型の変数 client を定義しています。この後は、この変数を利用して操作します。

client.connect()を利用して、指定したホストの、指定したポートに接続します。connect()は成功したときに1を返します。

client.print()で、HTTPリクエストを書き込みます。WiFiClientは、Printクラスを継承しているので、Serialと同じように、print()などを利用することができます。

client.available()は、読み込み可能なバイト数を返却します。77行目のwhile文では、利用可能なバイト数が0の時間(この場合は最初のデータが利用可能になるまでの時間)が5秒続くと、タイムアウトし、client.stop()を呼び出して、WiFi接続を停止します。

いったんデータが届くと、client.available()が0より大きい間、データをclient.readStringUntil()で読み続けます。WiFiClientは、Streamクラスも継承しているので、readStringUntil()が利用できます。

この例では、HTTPレスポンスのボディ長は考慮していないので、実際にすべてのデータが読めたかどうかは判断していません。content-lengthを使用した例は、HTTPClientクラスを利用したStreamHttpClientにあります。

バージョン

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

最終更新日

September 4, 2022

inserted by FC2 system