Skip to content

Commit

Permalink
Re-connect to git
Browse files Browse the repository at this point in the history
  • Loading branch information
judge2005 committed Oct 10, 2023
0 parents commit 98e1375
Show file tree
Hide file tree
Showing 4 changed files with 291 additions and 0 deletions.
205 changes: 205 additions & 0 deletions ESPAsyncHTTPClient.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
#include <ESPAsyncHTTPClient.h>

#define DEBUG(...) {}

String& ByteString::copy(const void *data, unsigned int length) {
if (!reserve(length)) {
invalidate();
return *this;
}
#if defined (ESP32) || defined (NEW_WSTRING)
setLen(length);
memcpy(wbuffer(), data, length);
wbuffer()[length] = 0;
#else
len = length;
memcpy(buffer, data, length);
buffer[length] = 0;
#endif
return *this;
}

void AsyncHTTPClient::initialize(String url) {
// check for : (http: or https:
int index = url.indexOf(':');
if (index < 0) {
initialized = false; // This is not a URL
}

protocol = url.substring(0, index);
DEBUG(protocol);
port = 80; //Default
if (index == 5) {
port = 443;
}

url.remove(0, (index + 3)); // remove http:// or https://

index = url.indexOf('/');
String hostPart = url.substring(0, index);
DEBUG(hostPart);
url.remove(0, index); // remove hostPart part

// get Authorization
index = hostPart.indexOf('@');

if (index >= 0) {
// auth info
String auth = hostPart.substring(0, index);
hostPart.remove(0, index + 1); // remove auth part including @
base64Authorization = base64::encode(auth);
}

// get port
index = hostPart.indexOf(':');
if (index >= 0) {
host = hostPart.substring(0, index); // hostname
host.remove(0, (index + 1)); // remove hostname + :
DEBUG(host);
port = host.toInt(); // get port
DEBUG(port);
} else {
host = hostPart;
DEBUG(host);
}
uri = url;
#if ASYNC_TCP_SSL_ENABLED
initialized = protocol == "http" || protocol == "https";
#else
initialized = protocol == "http";
#endif

DEBUG(initialized);
request = "GET " + uri + " HTTP/1.1\r\nHost: " + host + "\r\n\r\n";

DEBUG(request);
initialized = true;
}

String AsyncHTTPClient::getBody() {
if (statusCode == 200) {
// This is not a good check for chunked transfer encoding - it should ignore case and spaces
int chunkedIndex = response.indexOf("Transfer-Encoding: chunked");
int bodyStart = response.indexOf("\r\n\r\n") + 4;
if (bodyStart <= 3) {
return "";
}
if (chunkedIndex != -1) {
String body;
const char *buf = response.c_str();
int chunkSize = strtol(buf + bodyStart, 0, 16);
while (chunkSize) {
// Move past chunk size
bodyStart = response.indexOf("\r\n", bodyStart) + 2;
body += response.substring(bodyStart, bodyStart + chunkSize);

// Move past chunk
bodyStart = response.indexOf("\r\n", bodyStart + chunkSize) + 2;
chunkSize = strtol(buf + bodyStart, 0, 16);
}

return body;
} else {
return response.substring(bodyStart);
}
} else {
return "";
}
}

void AsyncHTTPClient::clientError(void *arg, AsyncClient *client,
err_t error) {
DEBUG("Connect Error");
AsyncHTTPClient *self = (AsyncHTTPClient*) arg;
self->onFail("Connection error");
self->aClient = NULL;
delete client;
}

void AsyncHTTPClient::clientDisconnect(void *arg, AsyncClient *client) {
DEBUG("Disconnected");
AsyncHTTPClient *self = (AsyncHTTPClient*) arg;
self->aClient = NULL;
delete client;
}

void AsyncHTTPClient::clientData(void *arg, AsyncClient *client, void *data, size_t len) {
DEBUG("Got response");

AsyncHTTPClient *self = (AsyncHTTPClient*) arg;
self->response = ByteString(data, len);
String status = self->response.substring(9, 12);
self->statusCode = atoi(status.c_str());
DEBUG(status.c_str());

if (self->statusCode == 200) {
self->onSuccess();
} else {
self->onFail("Failed with code " + status);
}
}

void AsyncHTTPClient::clientConnect(void *arg, AsyncClient *client) {
DEBUG("Connected");

AsyncHTTPClient *self = (AsyncHTTPClient*) arg;

self->response.copy("", 0);
self->statusCode = -1;

// Clear oneError handler
self->aClient->onError(NULL, NULL);

// Set disconnect handler
client->onDisconnect(clientDisconnect, self);

client->onData(clientData, self);

//send the request
client->write(self->request.c_str());
}

void AsyncHTTPClient::makeRequest(void (*success)(), void (*fail)(String msg)) {
onFail = fail;

if (!initialized) {
fail("Not initialized");
return;
}

if (aClient) { //client already exists
fail("Call taking forever");
return;
}

aClient = new AsyncClient();
if (!aClient) { //could not allocate client
fail("Out of memory");
return;
}

onSuccess = success;

aClient->onError(clientError, this);

aClient->onConnect(clientConnect, this);
bool connected = false;
#if ASYNC_TCP_SSL_ENABLED
if (protocol == "https") {
DEBUG("Creating secure connection");
connected = aClient->connect(host.c_str(), port, true);
} else {
connected = aClient->connect(host.c_str(), port, false);
}
#else
connected = aClient->connect(host.c_str(), port);
#endif
if (!connected) {
DEBUG("Connect Fail");
fail("Connection failed");
AsyncClient * client = aClient;
aClient = NULL;
delete client;
}
}

61 changes: 61 additions & 0 deletions ESPAsyncHTTPClient.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
#ifndef ASYNCHTTPCLIENT_H_
#define ASYNCHTTPCLIENT_H_
#include "Arduino.h"
#ifdef ESP8266
#include "ESPAsyncTCP.h"
#else
#include "AsyncTCP.h"
#endif
#include <base64.h>

#ifndef DEBUG
#define DEBUG(...) {}
#endif


class ByteString: public String {
public:
ByteString(void *data, size_t len) :
String() {
copy(data, len);
}

ByteString() :
String() {
}

String& copy(const void *data, unsigned int length);
};

/**
* Asynchronous HTTP Client
*/
struct AsyncHTTPClient {
AsyncClient *aClient = NULL;

bool initialized = false;
String protocol;
String base64Authorization;
String host;
int port;
String uri;
String request;

ByteString response;
int statusCode;
void (*onSuccess)();
void (*onFail)(String);

void initialize(String url);
int getStatusCode() { return statusCode; }

String getBody();

static void clientError(void *arg, AsyncClient *client, err_t error);
static void clientDisconnect(void *arg, AsyncClient *client);
static void clientData(void *arg, AsyncClient *client, void *data, size_t len);
static void clientConnect(void *arg, AsyncClient *client);
void makeRequest(void (*success)(), void (*fail)(String msg));
};

#endif ASYNCHTTPCLIENT_H_
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2017 Paul Andrews

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# ESPAsyncHttpClient
A very basic asynchronous HTTP client for the ESP8266 that uses ESPAsyncTCP. it was written for a very specific need, so it is not a truly general class.

This code is provided as-is. I am more than happy for anyone to take it and use it, or turn it into an actual general library.

0 comments on commit 98e1375

Please sign in to comment.