1
0
mirror of https://github.com/esp8266/Arduino.git synced 2025-06-06 05:21:22 +03:00

Fix code formatting

This commit is contained in:
Ivan Grokhotkov 2016-04-05 02:04:42 +03:00
parent bbc5e9ba01
commit bf7f33d918
4 changed files with 361 additions and 312 deletions

View File

@ -30,7 +30,8 @@
#include "ESP8266HTTPClient.h" #include "ESP8266HTTPClient.h"
class TransportTraits { class TransportTraits
{
public: public:
virtual std::unique_ptr<WiFiClient> create() virtual std::unique_ptr<WiFiClient> create()
{ {
@ -43,7 +44,8 @@ public:
} }
}; };
class TLSTraits : public TransportTraits { class TLSTraits : public TransportTraits
{
public: public:
TLSTraits(const String& fingerprint) : TLSTraits(const String& fingerprint) :
_fingerprint(fingerprint) _fingerprint(fingerprint)
@ -86,7 +88,8 @@ HTTPClient::~HTTPClient()
} }
bool HTTPClient::begin(String url, String httpsFingerprint) { bool HTTPClient::begin(String url, String httpsFingerprint)
{
if (httpsFingerprint.length() == 0) { if (httpsFingerprint.length() == 0) {
return false; return false;
} }
@ -183,8 +186,7 @@ bool HTTPClient::begin(String host, uint16_t port, String uri, bool https, Strin
{ {
if (https) { if (https) {
return begin(host, port, uri, httpsFingerprint); return begin(host, port, uri, httpsFingerprint);
} } else {
else {
return begin(host, port, uri); return begin(host, port, uri);
} }
} }
@ -208,7 +210,8 @@ bool HTTPClient::begin(String host, uint16_t port, String uri, String httpsFinge
* end * end
* called after the payload is handled * called after the payload is handled
*/ */
void HTTPClient::end(void) { void HTTPClient::end(void)
{
if(connected()) { if(connected()) {
if(_tcp->available() > 0) { if(_tcp->available() > 0) {
DEBUG_HTTPCLIENT("[HTTP-Client][end] still data in buffer (%d), clean up.\n", _tcp->available()); DEBUG_HTTPCLIENT("[HTTP-Client][end] still data in buffer (%d), clean up.\n", _tcp->available());
@ -231,7 +234,8 @@ void HTTPClient::end(void) {
* connected * connected
* @return connected status * @return connected status
*/ */
bool HTTPClient::connected() { bool HTTPClient::connected()
{
if(_tcp) { if(_tcp) {
return (_tcp->connected() || (_tcp->available() > 0)); return (_tcp->connected() || (_tcp->available() > 0));
} }
@ -243,7 +247,8 @@ bool HTTPClient::connected() {
* keep-alive * keep-alive
* @param reuse bool * @param reuse bool
*/ */
void HTTPClient::setReuse(bool reuse) { void HTTPClient::setReuse(bool reuse)
{
_reuse = reuse; _reuse = reuse;
} }
@ -251,7 +256,8 @@ void HTTPClient::setReuse(bool reuse) {
* set User Agent * set User Agent
* @param userAgent const char * * @param userAgent const char *
*/ */
void HTTPClient::setUserAgent(const char * userAgent) { void HTTPClient::setUserAgent(const char * userAgent)
{
_userAgent = userAgent; _userAgent = userAgent;
} }
@ -260,7 +266,8 @@ void HTTPClient::setUserAgent(const char * userAgent) {
* @param user const char * * @param user const char *
* @param password const char * * @param password const char *
*/ */
void HTTPClient::setAuthorization(const char * user, const char * password) { void HTTPClient::setAuthorization(const char * user, const char * password)
{
if(user && password) { if(user && password) {
String auth = user; String auth = user;
auth += ":"; auth += ":";
@ -273,7 +280,8 @@ void HTTPClient::setAuthorization(const char * user, const char * password) {
* set the Authorizatio for the http request * set the Authorizatio for the http request
* @param auth const char * base64 * @param auth const char * base64
*/ */
void HTTPClient::setAuthorization(const char * auth) { void HTTPClient::setAuthorization(const char * auth)
{
if(auth) { if(auth) {
_base64Authorization = auth; _base64Authorization = auth;
} }
@ -283,7 +291,8 @@ void HTTPClient::setAuthorization(const char * auth) {
* set the timeout for the TCP connection * set the timeout for the TCP connection
* @param timeout unsigned int * @param timeout unsigned int
*/ */
void HTTPClient::setTimeout(uint16_t timeout) { void HTTPClient::setTimeout(uint16_t timeout)
{
_tcpTimeout = timeout; _tcpTimeout = timeout;
if(connected()) { if(connected()) {
_tcp->setTimeout(timeout); _tcp->setTimeout(timeout);
@ -294,7 +303,8 @@ void HTTPClient::setTimeout(uint16_t timeout) {
* use HTTP1.0 * use HTTP1.0
* @param timeout * @param timeout
*/ */
void HTTPClient::useHTTP10(bool useHTTP10) { void HTTPClient::useHTTP10(bool useHTTP10)
{
_useHTTP10 = useHTTP10; _useHTTP10 = useHTTP10;
} }
@ -302,7 +312,8 @@ void HTTPClient::useHTTP10(bool useHTTP10) {
* send a GET request * send a GET request
* @return http code * @return http code
*/ */
int HTTPClient::GET() { int HTTPClient::GET()
{
return sendRequest("GET"); return sendRequest("GET");
} }
@ -312,11 +323,13 @@ int HTTPClient::GET() {
* @param size size_t * @param size size_t
* @return http code * @return http code
*/ */
int HTTPClient::POST(uint8_t * payload, size_t size) { int HTTPClient::POST(uint8_t * payload, size_t size)
{
return sendRequest("POST", payload, size); return sendRequest("POST", payload, size);
} }
int HTTPClient::POST(String payload) { int HTTPClient::POST(String payload)
{
return POST((uint8_t *) payload.c_str(), payload.length()); return POST((uint8_t *) payload.c_str(), payload.length());
} }
@ -326,7 +339,8 @@ int HTTPClient::POST(String payload) {
* @param payload String data for the message body * @param payload String data for the message body
* @return * @return
*/ */
int HTTPClient::sendRequest(const char * type, String payload) { int HTTPClient::sendRequest(const char * type, String payload)
{
return sendRequest(type, (uint8_t *) payload.c_str(), payload.length()); return sendRequest(type, (uint8_t *) payload.c_str(), payload.length());
} }
@ -337,7 +351,8 @@ int HTTPClient::sendRequest(const char * type, String payload) {
* @param size size_t size for the message body if 0 not send * @param size size_t size for the message body if 0 not send
* @return -1 if no info or > 0 when Content-Length is set by server * @return -1 if no info or > 0 when Content-Length is set by server
*/ */
int HTTPClient::sendRequest(const char * type, uint8_t * payload, size_t size) { int HTTPClient::sendRequest(const char * type, uint8_t * payload, size_t size)
{
// connect to server // connect to server
if(!connect()) { if(!connect()) {
return returnError(HTTPC_ERROR_CONNECTION_REFUSED); return returnError(HTTPC_ERROR_CONNECTION_REFUSED);
@ -370,7 +385,8 @@ int HTTPClient::sendRequest(const char * type, uint8_t * payload, size_t size) {
* @param size size_t size for the message body if 0 not Content-Length is send * @param size size_t size for the message body if 0 not Content-Length is send
* @return -1 if no info or > 0 when Content-Length is set by server * @return -1 if no info or > 0 when Content-Length is set by server
*/ */
int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) { int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size)
{
if(!stream) { if(!stream) {
return returnError(HTTPC_ERROR_NO_STREAM); return returnError(HTTPC_ERROR_NO_STREAM);
@ -485,7 +501,8 @@ int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) {
free(buff); free(buff);
if(size && (int) size != bytesWritten) { if(size && (int) size != bytesWritten) {
DEBUG_HTTPCLIENT("[HTTP-Client][sendRequest] Stream payload bytesWritten %d and size %d mismatch!.\n", bytesWritten, size); DEBUG_HTTPCLIENT("[HTTP-Client][sendRequest] ERROR SEND PAYLOAD FAILED!"); DEBUG_HTTPCLIENT("[HTTP-Client][sendRequest] Stream payload bytesWritten %d and size %d mismatch!.\n", bytesWritten, size);
DEBUG_HTTPCLIENT("[HTTP-Client][sendRequest] ERROR SEND PAYLOAD FAILED!");
return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED); return returnError(HTTPC_ERROR_SEND_PAYLOAD_FAILED);
} else { } else {
DEBUG_HTTPCLIENT("[HTTP-Client][sendRequest] Stream payload written: %d\n", bytesWritten); DEBUG_HTTPCLIENT("[HTTP-Client][sendRequest] Stream payload written: %d\n", bytesWritten);
@ -504,7 +521,8 @@ int HTTPClient::sendRequest(const char * type, Stream * stream, size_t size) {
* size of message body / payload * size of message body / payload
* @return -1 if no info or > 0 when Content-Length is set by server * @return -1 if no info or > 0 when Content-Length is set by server
*/ */
int HTTPClient::getSize(void) { int HTTPClient::getSize(void)
{
return _size; return _size;
} }
@ -512,7 +530,8 @@ int HTTPClient::getSize(void) {
* returns the stream of the tcp connection * returns the stream of the tcp connection
* @return WiFiClient * @return WiFiClient
*/ */
WiFiClient& HTTPClient::getStream(void) { WiFiClient& HTTPClient::getStream(void)
{
if(connected()) { if(connected()) {
return *_tcp; return *_tcp;
} }
@ -526,7 +545,8 @@ WiFiClient& HTTPClient::getStream(void) {
* returns the stream of the tcp connection * returns the stream of the tcp connection
* @return WiFiClient * * @return WiFiClient *
*/ */
WiFiClient* HTTPClient::getStreamPtr(void) { WiFiClient* HTTPClient::getStreamPtr(void)
{
if(connected()) { if(connected()) {
return _tcp.get(); return _tcp.get();
} }
@ -540,7 +560,8 @@ WiFiClient* HTTPClient::getStreamPtr(void) {
* @param stream Stream * * @param stream Stream *
* @return bytes written ( negative values are error codes ) * @return bytes written ( negative values are error codes )
*/ */
int HTTPClient::writeToStream(Stream * stream) { int HTTPClient::writeToStream(Stream * stream)
{
if(!stream) { if(!stream) {
return returnError(HTTPC_ERROR_NO_STREAM); return returnError(HTTPC_ERROR_NO_STREAM);
@ -616,7 +637,8 @@ int HTTPClient::writeToStream(Stream * stream) {
* return all payload as String (may need lot of ram or trigger out of memory!) * return all payload as String (may need lot of ram or trigger out of memory!)
* @return String * @return String
*/ */
String HTTPClient::getString(void) { String HTTPClient::getString(void)
{
StreamString sstring; StreamString sstring;
if(_size) { if(_size) {
@ -636,32 +658,33 @@ String HTTPClient::getString(void) {
* @param error int * @param error int
* @return String * @return String
*/ */
String HTTPClient::errorToString(int error) { String HTTPClient::errorToString(int error)
{
switch(error) { switch(error) {
case HTTPC_ERROR_CONNECTION_REFUSED: case HTTPC_ERROR_CONNECTION_REFUSED:
return String("connection refused"); return String("connection refused");
case HTTPC_ERROR_SEND_HEADER_FAILED: case HTTPC_ERROR_SEND_HEADER_FAILED:
return String("send header failed"); return String("send header failed");
case HTTPC_ERROR_SEND_PAYLOAD_FAILED: case HTTPC_ERROR_SEND_PAYLOAD_FAILED:
return String("send payload failed"); return String("send payload failed");
case HTTPC_ERROR_NOT_CONNECTED: case HTTPC_ERROR_NOT_CONNECTED:
return String("not connected"); return String("not connected");
case HTTPC_ERROR_CONNECTION_LOST: case HTTPC_ERROR_CONNECTION_LOST:
return String("connection lost"); return String("connection lost");
case HTTPC_ERROR_NO_STREAM: case HTTPC_ERROR_NO_STREAM:
return String("no stream"); return String("no stream");
case HTTPC_ERROR_NO_HTTP_SERVER: case HTTPC_ERROR_NO_HTTP_SERVER:
return String("no HTTP server"); return String("no HTTP server");
case HTTPC_ERROR_TOO_LESS_RAM: case HTTPC_ERROR_TOO_LESS_RAM:
return String("too less ram"); return String("too less ram");
case HTTPC_ERROR_ENCODING: case HTTPC_ERROR_ENCODING:
return String("Transfer-Encoding not supported"); return String("Transfer-Encoding not supported");
case HTTPC_ERROR_STREAM_WRITE: case HTTPC_ERROR_STREAM_WRITE:
return String("Stream write error"); return String("Stream write error");
case HTTPC_ERROR_READ_TIMEOUT: case HTTPC_ERROR_READ_TIMEOUT:
return String("read Timeout"); return String("read Timeout");
default: default:
return String(); return String();
} }
} }
@ -671,7 +694,8 @@ String HTTPClient::errorToString(int error) {
* @param value * @param value
* @param first * @param first
*/ */
void HTTPClient::addHeader(const String& name, const String& value, bool first) { void HTTPClient::addHeader(const String& name, const String& value, bool first)
{
// not allow set of Header handled by code // not allow set of Header handled by code
if(!name.equalsIgnoreCase("Connection") && !name.equalsIgnoreCase("User-Agent") && !name.equalsIgnoreCase("Host") && !(_base64Authorization.length() && name.equalsIgnoreCase("Authorization"))) { if(!name.equalsIgnoreCase("Connection") && !name.equalsIgnoreCase("User-Agent") && !name.equalsIgnoreCase("Host") && !(_base64Authorization.length() && name.equalsIgnoreCase("Authorization"))) {
@ -689,44 +713,55 @@ void HTTPClient::addHeader(const String& name, const String& value, bool first)
} }
void HTTPClient::collectHeaders(const char* headerKeys[], const size_t headerKeysCount) { void HTTPClient::collectHeaders(const char* headerKeys[], const size_t headerKeysCount)
{
_headerKeysCount = headerKeysCount; _headerKeysCount = headerKeysCount;
if(_currentHeaders) if(_currentHeaders) {
delete[] _currentHeaders; delete[] _currentHeaders;
}
_currentHeaders = new RequestArgument[_headerKeysCount]; _currentHeaders = new RequestArgument[_headerKeysCount];
for(size_t i = 0; i < _headerKeysCount; i++) { for(size_t i = 0; i < _headerKeysCount; i++) {
_currentHeaders[i].key = headerKeys[i]; _currentHeaders[i].key = headerKeys[i];
} }
} }
String HTTPClient::header(const char* name) { String HTTPClient::header(const char* name)
{
for(size_t i = 0; i < _headerKeysCount; ++i) { for(size_t i = 0; i < _headerKeysCount; ++i) {
if(_currentHeaders[i].key == name) if(_currentHeaders[i].key == name) {
return _currentHeaders[i].value; return _currentHeaders[i].value;
}
} }
return String(); return String();
} }
String HTTPClient::header(size_t i) { String HTTPClient::header(size_t i)
if(i < _headerKeysCount) {
if(i < _headerKeysCount) {
return _currentHeaders[i].value; return _currentHeaders[i].value;
}
return String(); return String();
} }
String HTTPClient::headerName(size_t i) { String HTTPClient::headerName(size_t i)
if(i < _headerKeysCount) {
if(i < _headerKeysCount) {
return _currentHeaders[i].key; return _currentHeaders[i].key;
}
return String(); return String();
} }
int HTTPClient::headers() { int HTTPClient::headers()
{
return _headerKeysCount; return _headerKeysCount;
} }
bool HTTPClient::hasHeader(const char* name) { bool HTTPClient::hasHeader(const char* name)
{
for(size_t i = 0; i < _headerKeysCount; ++i) { for(size_t i = 0; i < _headerKeysCount; ++i) {
if((_currentHeaders[i].key == name) && (_currentHeaders[i].value.length() > 0)) if((_currentHeaders[i].key == name) && (_currentHeaders[i].value.length() > 0)) {
return true; return true;
}
} }
return false; return false;
} }
@ -735,7 +770,8 @@ bool HTTPClient::hasHeader(const char* name) {
* init TCP connection and handle ssl verify if needed * init TCP connection and handle ssl verify if needed
* @return true if connection is ok * @return true if connection is ok
*/ */
bool HTTPClient::connect(void) { bool HTTPClient::connect(void)
{
if(connected()) { if(connected()) {
DEBUG_HTTPCLIENT("[HTTP-Client] connect. already connected, try reuse!\n"); DEBUG_HTTPCLIENT("[HTTP-Client] connect. already connected, try reuse!\n");
@ -779,7 +815,8 @@ bool HTTPClient::connect(void) {
* @param type (GET, POST, ...) * @param type (GET, POST, ...)
* @return status * @return status
*/ */
bool HTTPClient::sendHeader(const char * type) { bool HTTPClient::sendHeader(const char * type)
{
if(!connected()) { if(!connected()) {
return false; return false;
} }
@ -793,9 +830,9 @@ bool HTTPClient::sendHeader(const char * type) {
} }
header += "\r\n" header += "\r\n"
"Host: " + _host + "\r\n" "Host: " + _host + "\r\n"
"User-Agent: " + _userAgent + "\r\n" "User-Agent: " + _userAgent + "\r\n"
"Connection: "; "Connection: ";
if(_reuse) { if(_reuse) {
header += "keep-alive"; header += "keep-alive";
@ -821,7 +858,8 @@ bool HTTPClient::sendHeader(const char * type) {
* reads the response from the server * reads the response from the server
* @return int http code * @return int http code
*/ */
int HTTPClient::handleHeaderResponse() { int HTTPClient::handleHeaderResponse()
{
if(!connected()) { if(!connected()) {
return HTTPC_ERROR_NOT_CONNECTED; return HTTPC_ERROR_NOT_CONNECTED;
@ -912,7 +950,8 @@ int HTTPClient::handleHeaderResponse() {
* @param size int * @param size int
* @return < 0 = error >= 0 = size written * @return < 0 = error >= 0 = size written
*/ */
int HTTPClient::writeToStreamDataBlock(Stream * stream, int size) { int HTTPClient::writeToStreamDataBlock(Stream * stream, int size)
{
int buff_size = HTTP_TCP_BUFFER_SIZE; int buff_size = HTTP_TCP_BUFFER_SIZE;
int len = size; int len = size;
int bytesWritten = 0; int bytesWritten = 0;
@ -1022,7 +1061,8 @@ int HTTPClient::writeToStreamDataBlock(Stream * stream, int size) {
* @param error * @param error
* @return error * @return error
*/ */
int HTTPClient::returnError(int error) { int HTTPClient::returnError(int error)
{
if(error < 0) { if(error < 0) {
DEBUG_HTTPCLIENT("[HTTP-Client][returnError] error(%d): %s\n", error, errorToString(error).c_str()); DEBUG_HTTPCLIENT("[HTTP-Client][returnError] error(%d): %s\n", error, errorToString(error).c_str());
if(connected()) { if(connected()) {

View File

@ -127,96 +127,97 @@ typedef enum {
class TransportTraits; class TransportTraits;
typedef std::unique_ptr<TransportTraits> TransportTraitsPtr; typedef std::unique_ptr<TransportTraits> TransportTraitsPtr;
class HTTPClient { class HTTPClient
public: {
HTTPClient(); public:
~HTTPClient(); HTTPClient();
~HTTPClient();
bool begin(String url); bool begin(String url);
bool begin(String url, String httpsFingerprint); bool begin(String url, String httpsFingerprint);
bool begin(String host, uint16_t port, String uri = "/"); bool begin(String host, uint16_t port, String uri = "/");
bool begin(String host, uint16_t port, String uri, String httpsFingerprint); bool begin(String host, uint16_t port, String uri, String httpsFingerprint);
// deprecated, use the overload above instead // deprecated, use the overload above instead
bool begin(String host, uint16_t port, String uri, bool https, String httpsFingerprint) __attribute__ ((deprecated)); bool begin(String host, uint16_t port, String uri, bool https, String httpsFingerprint) __attribute__ ((deprecated));
void end(void); void end(void);
bool connected(void); bool connected(void);
void setReuse(bool reuse); /// keep-alive void setReuse(bool reuse); /// keep-alive
void setUserAgent(const char * userAgent); void setUserAgent(const char * userAgent);
void setAuthorization(const char * user, const char * password); void setAuthorization(const char * user, const char * password);
void setAuthorization(const char * auth); void setAuthorization(const char * auth);
void setTimeout(uint16_t timeout); void setTimeout(uint16_t timeout);
void useHTTP10(bool usehttp10 = true); void useHTTP10(bool usehttp10 = true);
/// request handling /// request handling
int GET(); int GET();
int POST(uint8_t * payload, size_t size); int POST(uint8_t * payload, size_t size);
int POST(String payload); int POST(String payload);
int sendRequest(const char * type, String payload); int sendRequest(const char * type, String payload);
int sendRequest(const char * type, uint8_t * payload = NULL, size_t size = 0); int sendRequest(const char * type, uint8_t * payload = NULL, size_t size = 0);
int sendRequest(const char * type, Stream * stream, size_t size = 0); int sendRequest(const char * type, Stream * stream, size_t size = 0);
void addHeader(const String& name, const String& value, bool first = false); void addHeader(const String& name, const String& value, bool first = false);
/// Response handling /// Response handling
void collectHeaders(const char* headerKeys[], const size_t headerKeysCount); void collectHeaders(const char* headerKeys[], const size_t headerKeysCount);
String header(const char* name); // get request header value by name String header(const char* name); // get request header value by name
String header(size_t i); // get request header value by number String header(size_t i); // get request header value by number
String headerName(size_t i); // get request header name by number String headerName(size_t i); // get request header name by number
int headers(); // get header count int headers(); // get header count
bool hasHeader(const char* name); // check if header exists bool hasHeader(const char* name); // check if header exists
int getSize(void); int getSize(void);
WiFiClient& getStream(void); WiFiClient& getStream(void);
WiFiClient* getStreamPtr(void); WiFiClient* getStreamPtr(void);
int writeToStream(Stream* stream); int writeToStream(Stream* stream);
String getString(void); String getString(void);
static String errorToString(int error); static String errorToString(int error);
protected: protected:
struct RequestArgument { struct RequestArgument {
String key; String key;
String value; String value;
}; };
void clear(); void clear();
int returnError(int error); int returnError(int error);
bool connect(void); bool connect(void);
bool sendHeader(const char * type); bool sendHeader(const char * type);
int handleHeaderResponse(); int handleHeaderResponse();
int writeToStreamDataBlock(Stream * stream, int len); int writeToStreamDataBlock(Stream * stream, int len);
TransportTraitsPtr _transportTraits; TransportTraitsPtr _transportTraits;
std::unique_ptr<WiFiClient> _tcp; std::unique_ptr<WiFiClient> _tcp;
/// request handling /// request handling
String _host; String _host;
uint16_t _port = 0; uint16_t _port = 0;
bool _reuse = false; bool _reuse = false;
uint16_t _tcpTimeout = HTTPCLIENT_DEFAULT_TCP_TIMEOUT; uint16_t _tcpTimeout = HTTPCLIENT_DEFAULT_TCP_TIMEOUT;
bool _useHTTP10 = false; bool _useHTTP10 = false;
String _uri; String _uri;
String _protocol; String _protocol;
String _headers; String _headers;
String _userAgent = "ESP8266HTTPClient"; String _userAgent = "ESP8266HTTPClient";
String _base64Authorization; String _base64Authorization;
/// Response handling /// Response handling
RequestArgument* _currentHeaders = nullptr; RequestArgument* _currentHeaders = nullptr;
size_t _headerKeysCount = 0; size_t _headerKeysCount = 0;
int _returnCode = 0; int _returnCode = 0;
int _size = -1; int _size = -1;
bool _canReuse = false; bool _canReuse = false;
transferEncoding_t _transferEncoding = HTTPC_TE_IDENTITY; transferEncoding_t _transferEncoding = HTTPC_TE_IDENTITY;
}; };

View File

@ -29,70 +29,70 @@
extern "C" uint32_t _SPIFFS_start; extern "C" uint32_t _SPIFFS_start;
extern "C" uint32_t _SPIFFS_end; extern "C" uint32_t _SPIFFS_end;
ESP8266HTTPUpdate::ESP8266HTTPUpdate(void) { ESP8266HTTPUpdate::ESP8266HTTPUpdate(void)
{
} }
ESP8266HTTPUpdate::~ESP8266HTTPUpdate(void) { ESP8266HTTPUpdate::~ESP8266HTTPUpdate(void)
{
} }
t_httpUpdate_return ESP8266HTTPUpdate::update(const String& url, const String& currentVersion, HTTPUpdateResult ESP8266HTTPUpdate::update(const String& url, const String& currentVersion,
const String& httpsFingerprint, bool reboot) const String& httpsFingerprint, bool reboot)
{ {
rebootOnUpdate(reboot); rebootOnUpdate(reboot);
return update(url, currentVersion, httpsFingerprint); return update(url, currentVersion, httpsFingerprint);
} }
t_httpUpdate_return ESP8266HTTPUpdate::update(const String& url, const String& currentVersion) HTTPUpdateResult ESP8266HTTPUpdate::update(const String& url, const String& currentVersion)
{ {
HTTPClient http; HTTPClient http;
http.begin(url); http.begin(url);
return handleUpdate(http, currentVersion, false); return handleUpdate(http, currentVersion, false);
} }
t_httpUpdate_return ESP8266HTTPUpdate::update(const String& url, const String& currentVersion, HTTPUpdateResult ESP8266HTTPUpdate::update(const String& url, const String& currentVersion,
const String& httpsFingerprint) const String& httpsFingerprint)
{ {
HTTPClient http; HTTPClient http;
http.begin(url, httpsFingerprint); http.begin(url, httpsFingerprint);
return handleUpdate(http, currentVersion, false); return handleUpdate(http, currentVersion, false);
} }
HTTPUpdateResult ESP8266HTTPUpdate::updateSpiffs(const String& url, const String& currentVersion, const String& httpsFingerprint)
t_httpUpdate_return ESP8266HTTPUpdate::updateSpiffs(const String& url, const String& currentVersion, const String& httpsFingerprint)
{ {
HTTPClient http; HTTPClient http;
http.begin(url, httpsFingerprint); http.begin(url, httpsFingerprint);
return handleUpdate(http, currentVersion, true); return handleUpdate(http, currentVersion, true);
} }
t_httpUpdate_return ESP8266HTTPUpdate::updateSpiffs(const String& url, const String& currentVersion) HTTPUpdateResult ESP8266HTTPUpdate::updateSpiffs(const String& url, const String& currentVersion)
{ {
HTTPClient http; HTTPClient http;
http.begin(url); http.begin(url);
return handleUpdate(http, currentVersion, true); return handleUpdate(http, currentVersion, true);
} }
t_httpUpdate_return ESP8266HTTPUpdate::update(const String& host, uint16_t port, const String& uri, const String& currentVersion, HTTPUpdateResult ESP8266HTTPUpdate::update(const String& host, uint16_t port, const String& uri, const String& currentVersion,
bool https, const String& httpsFingerprint, bool reboot) bool https, const String& httpsFingerprint, bool reboot)
{ {
rebootOnUpdate(reboot); rebootOnUpdate(reboot);
if (httpsFingerprint.length() == 0) { if (httpsFingerprint.length() == 0) {
return update(host, port, uri, currentVersion); return update(host, port, uri, currentVersion);
} } else {
else {
return update(host, port, uri, currentVersion, httpsFingerprint); return update(host, port, uri, currentVersion, httpsFingerprint);
} }
} }
t_httpUpdate_return ESP8266HTTPUpdate::update(const String& host, uint16_t port, const String& uri, HTTPUpdateResult ESP8266HTTPUpdate::update(const String& host, uint16_t port, const String& uri,
const String& currentVersion) const String& currentVersion)
{ {
HTTPClient http; HTTPClient http;
http.begin(host, port, uri); http.begin(host, port, uri);
return handleUpdate(http, currentVersion, false); return handleUpdate(http, currentVersion, false);
} }
t_httpUpdate_return ESP8266HTTPUpdate::update(const String& host, uint16_t port, const String& url, HTTPUpdateResult ESP8266HTTPUpdate::update(const String& host, uint16_t port, const String& url,
const String& currentVersion, const String& httpsFingerprint) const String& currentVersion, const String& httpsFingerprint)
{ {
HTTPClient http; HTTPClient http;
http.begin(host, port, url, httpsFingerprint); http.begin(host, port, url, httpsFingerprint);
@ -104,15 +104,17 @@ t_httpUpdate_return ESP8266HTTPUpdate::update(const String& host, uint16_t port,
* return error code as int * return error code as int
* @return int error code * @return int error code
*/ */
int ESP8266HTTPUpdate::getLastError(void){ int ESP8266HTTPUpdate::getLastError(void)
return _lastError; {
return _lastError;
} }
/** /**
* return error code as String * return error code as String
* @return String error * @return String error
*/ */
String ESP8266HTTPUpdate::getLastErrorString(void) { String ESP8266HTTPUpdate::getLastErrorString(void)
{
if(_lastError == 0) { if(_lastError == 0) {
return String(); // no error return String(); // no error
@ -132,22 +134,22 @@ String ESP8266HTTPUpdate::getLastErrorString(void) {
} }
switch(_lastError) { switch(_lastError) {
case HTTP_UE_TOO_LESS_SPACE: case HTTP_UE_TOO_LESS_SPACE:
return String("To less space"); return String("To less space");
case HTTP_UE_SERVER_NOT_REPORT_SIZE: case HTTP_UE_SERVER_NOT_REPORT_SIZE:
return String("Server not Report Size"); return String("Server not Report Size");
case HTTP_UE_SERVER_FILE_NOT_FOUND: case HTTP_UE_SERVER_FILE_NOT_FOUND:
return String("File not Found (404)"); return String("File not Found (404)");
case HTTP_UE_SERVER_FORBIDDEN: case HTTP_UE_SERVER_FORBIDDEN:
return String("Forbidden (403)"); return String("Forbidden (403)");
case HTTP_UE_SERVER_WRONG_HTTP_CODE: case HTTP_UE_SERVER_WRONG_HTTP_CODE:
return String("Wrong HTTP code"); return String("Wrong HTTP code");
case HTTP_UE_SERVER_FAULTY_MD5: case HTTP_UE_SERVER_FAULTY_MD5:
return String("Faulty MD5"); return String("Faulty MD5");
case HTTP_UE_BIN_VERIFY_HEADER_FAILED: case HTTP_UE_BIN_VERIFY_HEADER_FAILED:
return String("Verify bin header failed"); return String("Verify bin header failed");
case HTTP_UE_BIN_FOR_WRONG_FLASH: case HTTP_UE_BIN_FOR_WRONG_FLASH:
return String("bin for wrong flash size"); return String("bin for wrong flash size");
} }
return String(); return String();
@ -158,11 +160,12 @@ String ESP8266HTTPUpdate::getLastErrorString(void) {
* *
* @param http HTTPClient * * @param http HTTPClient *
* @param currentVersion const char * * @param currentVersion const char *
* @return t_httpUpdate_return * @return HTTPUpdateResult
*/ */
t_httpUpdate_return ESP8266HTTPUpdate::handleUpdate(HTTPClient& http, const String& currentVersion, bool spiffs) { HTTPUpdateResult ESP8266HTTPUpdate::handleUpdate(HTTPClient& http, const String& currentVersion, bool spiffs)
{
t_httpUpdate_return ret = HTTP_UPDATE_FAILED; HTTPUpdateResult ret = HTTP_UPDATE_FAILED;
// use HTTP/1.0 for update since the update handler not support any transfer Encoding // use HTTP/1.0 for update since the update handler not support any transfer Encoding
http.useHTTP10(true); http.useHTTP10(true);
@ -221,111 +224,111 @@ t_httpUpdate_return ESP8266HTTPUpdate::handleUpdate(HTTPClient& http, const Stri
} }
switch(code) { switch(code) {
case HTTP_CODE_OK: ///< OK (Start Update) case HTTP_CODE_OK: ///< OK (Start Update)
if(len > 0) { if(len > 0) {
bool startUpdate = true; bool startUpdate = true;
if(spiffs) { if(spiffs) {
size_t spiffsSize = ((size_t) &_SPIFFS_end - (size_t) &_SPIFFS_start); size_t spiffsSize = ((size_t) &_SPIFFS_end - (size_t) &_SPIFFS_start);
if(len > (int) spiffsSize) { if(len > (int) spiffsSize) {
DEBUG_HTTP_UPDATE("[httpUpdate] spiffsSize to low (%d) needed: %d\n", spiffsSize, len); DEBUG_HTTP_UPDATE("[httpUpdate] spiffsSize to low (%d) needed: %d\n", spiffsSize, len);
startUpdate = false; startUpdate = false;
}
} else {
if(len > (int) ESP.getFreeSketchSpace()) {
DEBUG_HTTP_UPDATE("[httpUpdate] FreeSketchSpace to low (%d) needed: %d\n", ESP.getFreeSketchSpace(), len);
startUpdate = false;
}
}
if(!startUpdate) {
_lastError = HTTP_UE_TOO_LESS_SPACE;
ret = HTTP_UPDATE_FAILED;
} else {
WiFiClient * tcp = http.getStreamPtr();
WiFiUDP::stopAll();
WiFiClient::stopAllExcept(tcp);
delay(100);
int command;
if(spiffs) {
command = U_SPIFFS;
DEBUG_HTTP_UPDATE("[httpUpdate] runUpdate spiffs...\n");
} else {
command = U_FLASH;
DEBUG_HTTP_UPDATE("[httpUpdate] runUpdate flash...\n");
}
if(!spiffs) {
uint8_t buf[4];
if(tcp->peekBytes(&buf[0], 4) != 4) {
DEBUG_HTTP_UPDATE("[httpUpdate] peekBytes magic header failed\n");
_lastError = HTTP_UE_BIN_VERIFY_HEADER_FAILED;
http.end();
return HTTP_UPDATE_FAILED;
}
// check for valid first magic byte
if(buf[0] != 0xE9) {
DEBUG_HTTP_UPDATE("[httpUpdate] magic header not starts with 0xE9\n");
_lastError = HTTP_UE_BIN_VERIFY_HEADER_FAILED;
http.end();
return HTTP_UPDATE_FAILED;
}
uint32_t bin_flash_size = ESP.magicFlashChipSize((buf[3] & 0xf0) >> 4);
// check if new bin fits to SPI flash
if(bin_flash_size > ESP.getFlashChipRealSize()) {
DEBUG_HTTP_UPDATE("[httpUpdate] magic header, new bin not fits SPI Flash\n");
_lastError = HTTP_UE_BIN_FOR_WRONG_FLASH;
http.end();
return HTTP_UPDATE_FAILED;
}
}
if(runUpdate(*tcp, len, http.header("x-MD5"), command)) {
ret = HTTP_UPDATE_OK;
DEBUG_HTTP_UPDATE("[httpUpdate] Update ok\n");
http.end();
if(_rebootOnUpdate) {
ESP.restart();
}
} else {
ret = HTTP_UPDATE_FAILED;
DEBUG_HTTP_UPDATE("[httpUpdate] Update failed\n");
}
} }
} else { } else {
_lastError = HTTP_UE_SERVER_NOT_REPORT_SIZE; if(len > (int) ESP.getFreeSketchSpace()) {
ret = HTTP_UPDATE_FAILED; DEBUG_HTTP_UPDATE("[httpUpdate] FreeSketchSpace to low (%d) needed: %d\n", ESP.getFreeSketchSpace(), len);
DEBUG_HTTP_UPDATE("[httpUpdate] Content-Length is 0 or not set by Server?!\n"); startUpdate = false;
}
} }
break;
case HTTP_CODE_NOT_MODIFIED: if(!startUpdate) {
///< Not Modified (No updates) _lastError = HTTP_UE_TOO_LESS_SPACE;
ret = HTTP_UPDATE_NO_UPDATES; ret = HTTP_UPDATE_FAILED;
break; } else {
case HTTP_CODE_NOT_FOUND:
_lastError = HTTP_UE_SERVER_FILE_NOT_FOUND; WiFiClient * tcp = http.getStreamPtr();
WiFiUDP::stopAll();
WiFiClient::stopAllExcept(tcp);
delay(100);
int command;
if(spiffs) {
command = U_SPIFFS;
DEBUG_HTTP_UPDATE("[httpUpdate] runUpdate spiffs...\n");
} else {
command = U_FLASH;
DEBUG_HTTP_UPDATE("[httpUpdate] runUpdate flash...\n");
}
if(!spiffs) {
uint8_t buf[4];
if(tcp->peekBytes(&buf[0], 4) != 4) {
DEBUG_HTTP_UPDATE("[httpUpdate] peekBytes magic header failed\n");
_lastError = HTTP_UE_BIN_VERIFY_HEADER_FAILED;
http.end();
return HTTP_UPDATE_FAILED;
}
// check for valid first magic byte
if(buf[0] != 0xE9) {
DEBUG_HTTP_UPDATE("[httpUpdate] magic header not starts with 0xE9\n");
_lastError = HTTP_UE_BIN_VERIFY_HEADER_FAILED;
http.end();
return HTTP_UPDATE_FAILED;
}
uint32_t bin_flash_size = ESP.magicFlashChipSize((buf[3] & 0xf0) >> 4);
// check if new bin fits to SPI flash
if(bin_flash_size > ESP.getFlashChipRealSize()) {
DEBUG_HTTP_UPDATE("[httpUpdate] magic header, new bin not fits SPI Flash\n");
_lastError = HTTP_UE_BIN_FOR_WRONG_FLASH;
http.end();
return HTTP_UPDATE_FAILED;
}
}
if(runUpdate(*tcp, len, http.header("x-MD5"), command)) {
ret = HTTP_UPDATE_OK;
DEBUG_HTTP_UPDATE("[httpUpdate] Update ok\n");
http.end();
if(_rebootOnUpdate) {
ESP.restart();
}
} else {
ret = HTTP_UPDATE_FAILED;
DEBUG_HTTP_UPDATE("[httpUpdate] Update failed\n");
}
}
} else {
_lastError = HTTP_UE_SERVER_NOT_REPORT_SIZE;
ret = HTTP_UPDATE_FAILED; ret = HTTP_UPDATE_FAILED;
break; DEBUG_HTTP_UPDATE("[httpUpdate] Content-Length is 0 or not set by Server?!\n");
case HTTP_CODE_FORBIDDEN: }
_lastError = HTTP_UE_SERVER_FORBIDDEN; break;
ret = HTTP_UPDATE_FAILED; case HTTP_CODE_NOT_MODIFIED:
break; ///< Not Modified (No updates)
default: ret = HTTP_UPDATE_NO_UPDATES;
_lastError = HTTP_UE_SERVER_WRONG_HTTP_CODE; break;
ret = HTTP_UPDATE_FAILED; case HTTP_CODE_NOT_FOUND:
DEBUG_HTTP_UPDATE("[httpUpdate] HTTP Code is (%d)\n", code); _lastError = HTTP_UE_SERVER_FILE_NOT_FOUND;
//http.writeToStream(&Serial1); ret = HTTP_UPDATE_FAILED;
break; break;
case HTTP_CODE_FORBIDDEN:
_lastError = HTTP_UE_SERVER_FORBIDDEN;
ret = HTTP_UPDATE_FAILED;
break;
default:
_lastError = HTTP_UE_SERVER_WRONG_HTTP_CODE;
ret = HTTP_UPDATE_FAILED;
DEBUG_HTTP_UPDATE("[httpUpdate] HTTP Code is (%d)\n", code);
//http.writeToStream(&Serial1);
break;
} }
http.end(); http.end();
@ -339,7 +342,8 @@ t_httpUpdate_return ESP8266HTTPUpdate::handleUpdate(HTTPClient& http, const Stri
* @param md5 String * @param md5 String
* @return true if Update ok * @return true if Update ok
*/ */
bool ESP8266HTTPUpdate::runUpdate(Stream& in, uint32_t size, String md5, int command) { bool ESP8266HTTPUpdate::runUpdate(Stream& in, uint32_t size, String md5, int command)
{
StreamString error; StreamString error;

View File

@ -60,45 +60,49 @@ enum HTTPUpdateResult {
typedef HTTPUpdateResult t_httpUpdate_return; // backward compatibility typedef HTTPUpdateResult t_httpUpdate_return; // backward compatibility
class ESP8266HTTPUpdate { class ESP8266HTTPUpdate
public: {
ESP8266HTTPUpdate(void); public:
~ESP8266HTTPUpdate(void); ESP8266HTTPUpdate(void);
~ESP8266HTTPUpdate(void);
void rebootOnUpdate(bool reboot) { _rebootOnUpdate = reboot; } void rebootOnUpdate(bool reboot)
{
_rebootOnUpdate = reboot;
}
// This function is deprecated, use rebootOnUpdate and the next one instead // This function is deprecated, use rebootOnUpdate and the next one instead
t_httpUpdate_return update(const String& url, const String& currentVersion, t_httpUpdate_return update(const String& url, const String& currentVersion,
const String& httpsFingerprint, bool reboot) __attribute__((deprecated)); const String& httpsFingerprint, bool reboot) __attribute__((deprecated));
t_httpUpdate_return update(const String& url, const String& currentVersion = ""); t_httpUpdate_return update(const String& url, const String& currentVersion = "");
t_httpUpdate_return update(const String& url, const String& currentVersion, t_httpUpdate_return update(const String& url, const String& currentVersion,
const String& httpsFingerprint); const String& httpsFingerprint);
// This function is deprecated, use one of the overloads below along with rebootOnUpdate // This function is deprecated, use one of the overloads below along with rebootOnUpdate
t_httpUpdate_return update(const String& host, uint16_t port, const String& uri, const String& currentVersion, t_httpUpdate_return update(const String& host, uint16_t port, const String& uri, const String& currentVersion,
bool https, const String& httpsFingerprint, bool reboot) __attribute__((deprecated)); bool https, const String& httpsFingerprint, bool reboot) __attribute__((deprecated));
t_httpUpdate_return update(const String& host, uint16_t port, const String& uri = "/", t_httpUpdate_return update(const String& host, uint16_t port, const String& uri = "/",
const String& currentVersion = ""); const String& currentVersion = "");
t_httpUpdate_return update(const String& host, uint16_t port, const String& url, t_httpUpdate_return update(const String& host, uint16_t port, const String& url,
const String& currentVersion, const String& httpsFingerprint); const String& currentVersion, const String& httpsFingerprint);
// This function is deprecated, use rebootOnUpdate and the next one instead // This function is deprecated, use rebootOnUpdate and the next one instead
t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion, t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion,
const String& httpsFingerprint, bool reboot) __attribute__((deprecated)); const String& httpsFingerprint, bool reboot) __attribute__((deprecated));
t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion = ""); t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion = "");
t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion, const String& httpsFingerprint); t_httpUpdate_return updateSpiffs(const String& url, const String& currentVersion, const String& httpsFingerprint);
int getLastError(void); int getLastError(void);
String getLastErrorString(void); String getLastErrorString(void);
protected: protected:
t_httpUpdate_return handleUpdate(HTTPClient& http, const String& currentVersion, bool spiffs = false); t_httpUpdate_return handleUpdate(HTTPClient& http, const String& currentVersion, bool spiffs = false);
bool runUpdate(Stream& in, uint32_t size, String md5, int command = U_FLASH); bool runUpdate(Stream& in, uint32_t size, String md5, int command = U_FLASH);
int _lastError; int _lastError;
bool _rebootOnUpdate = true; bool _rebootOnUpdate = true;
}; };
extern ESP8266HTTPUpdate ESPhttpUpdate; extern ESP8266HTTPUpdate ESPhttpUpdate;