|
| 1 | +/** |
| 2 | + * StreamHttpClient.ino |
| 3 | + * |
| 4 | + * Created on: 24.05.2015 |
| 5 | + * |
| 6 | + */ |
| 7 | + |
| 8 | +#include <Arduino.h> |
| 9 | + |
| 10 | +#include <ESP8266WiFi.h> |
| 11 | +#include <ESP8266WiFiMulti.h> |
| 12 | + |
| 13 | +#include <ESP8266httpClient.h> |
| 14 | + |
| 15 | +#define USE_SERIAL Serial |
| 16 | + |
| 17 | +ESP8266WiFiMulti WiFiMulti; |
| 18 | + |
| 19 | +void setup() { |
| 20 | + |
| 21 | + USE_SERIAL.begin(115200); |
| 22 | + // USE_SERIAL.setDebugOutput(true); |
| 23 | + |
| 24 | + USE_SERIAL.println(); |
| 25 | + USE_SERIAL.println(); |
| 26 | + USE_SERIAL.println(); |
| 27 | + |
| 28 | + for(uint8_t t = 4; t > 0; t--) { |
| 29 | + USE_SERIAL.printf("[SETUP] WAIT %d...\n", t); |
| 30 | + USE_SERIAL.flush(); |
| 31 | + delay(1000); |
| 32 | + } |
| 33 | + |
| 34 | + WiFiMulti.addAP("SSID", "PASSWORD"); |
| 35 | + |
| 36 | +} |
| 37 | + |
| 38 | +void loop() { |
| 39 | + // wait for WiFi connection |
| 40 | + if((WiFiMulti.run() == WL_CONNECTED)) { |
| 41 | + |
| 42 | + httpClient http; |
| 43 | + |
| 44 | + USE_SERIAL.print("[HTTP] begin...\n"); |
| 45 | + // configure traged server and url |
| 46 | + http.begin("192.168.1.12", 80, "/test.html"); |
| 47 | + |
| 48 | + USE_SERIAL.print("[HTTP] GET...\n"); |
| 49 | + // start connection and send HTTP header |
| 50 | + int httpCode = http.GET(); |
| 51 | + if(httpCode) { |
| 52 | + // HTTP header has been send and Server response header has been handled |
| 53 | + |
| 54 | + USE_SERIAL.printf("[HTTP] GET... code: %d\n", httpCode); |
| 55 | + |
| 56 | + // file found at server |
| 57 | + if(httpCode == 200) { |
| 58 | + |
| 59 | + // get lenght of document (is -1 when Server sends no Content-Length header) |
| 60 | + int len = http.getSize(); |
| 61 | + |
| 62 | + // create buffer for read |
| 63 | + uint8_t buff[128] = { 0 }; |
| 64 | + |
| 65 | + // get tcp stream |
| 66 | + WiFiClient * stream = http.getStreamPtr(); |
| 67 | + |
| 68 | + // read all data from server |
| 69 | + while(http.connected() && (len > 0 || len == -1)) { |
| 70 | + // get available data size |
| 71 | + size_t size = stream->available(); |
| 72 | + |
| 73 | + if(size) { |
| 74 | + // read up to 128 byte |
| 75 | + int c = stream->readBytes(buff, ((size > sizeof(buff)) ? sizeof(buff) : size)); |
| 76 | + |
| 77 | + // write it to Serial |
| 78 | + USE_SERIAL.write(buff, c); |
| 79 | + |
| 80 | + if(len > 0) { |
| 81 | + len -= c; |
| 82 | + } |
| 83 | + } |
| 84 | + delay(1); |
| 85 | + } |
| 86 | + |
| 87 | + USE_SERIAL.println(); |
| 88 | + USE_SERIAL.print("[HTTP] connection closed or file end.\n"); |
| 89 | + |
| 90 | + } |
| 91 | + } else { |
| 92 | + USE_SERIAL.print("[HTTP] GET... failed, no connection or no HTTP server\n"); |
| 93 | + } |
| 94 | + } |
| 95 | + |
| 96 | + delay(10000); |
| 97 | +} |
| 98 | + |
0 commit comments