/**
* StreamHTTPClient.ino
* HTTPClient+stream->readBytesを使う
*/
#include <ESP8266WiFi.h>
#include <ESP8266HTTPClient.h>
const char* ssid = "アクセスポイントのSSID";
const char* password = "アクセスポイントのパスワード";
WiFiClient client;
HTTPClient http;
void httpPrint(int len, uint8_t *buff) {
char ch[2];
ch[1] = 0;
for(int i=0; i<len; i++) {
ch[0] = buff[i];
if (isAlphaNumeric(ch[0])) {
Serial.printf("%c",ch[0]);
} else if
(strstr("\"!#$%&'()=-<> ;:/,.@[]+*",ch)) {
Serial.printf("%c",ch[0]);
} else if (ch[0] == 0x0a) {
Serial.printf("\n");
} else {
//
Serial.printf("0x%02x",ch[0]);
Serial.printf("*");
}
}
}
void setup() {
Serial.begin(9600);
delay(500);
WiFi.begin(ssid, password);
Serial.println("");
// Wait for connection
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
Serial.print("IP address: ");
Serial.println(WiFi.localIP());
}
void loop() {
int counter=0;
long psize=0;
Serial.print("[HTTP] begin...\n");
http.begin("weather.livedoor.com", 80,
"/forecast/rss/area/230010.xml");
Serial.print("[HTTP] GET...\n");
// start connection and send HTTP header
int httpCode = http.GET();
// httpCode will be negative on error
if(httpCode > 0) {
// HTTP header has been send and Server
response header has been handled
Serial.printf("[HTTP] GET... code:
%d\n", httpCode);
// file found at server
if(httpCode == HTTP_CODE_OK) {
// get lenght 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();
counter++;
if(size) {
//
read up to 128 byte
int
c = stream->readBytes(buff, ((size > sizeof(buff)) ?
sizeof(buff) : size));
psize=psize+c;
//
httpPrint(c,buff);
// delay(1);
if(len > 0) {
len -= c;
}
}
}
Serial.print("[HTTP]
connection closed or file end.\n");
}
} else {
Serial.printf("[HTTP] GET... failed,
error: %s\n", http.errorToString(httpCode).c_str());
}
http.end();
Serial.printf("counter=%d
psize=%d\n\n",counter,psize);
delay(10000);
}
|