Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Feb 1, 2023. It is now read-only.

Simple Async HTTP Request library, supporting GET, POST, PUT, PATCH, DELETE and HEAD, on top of Teensy41_AsyncTCP for Teensy 4.1 using QNEthernet. This library is one of the current or future Async libraries to support Teensy 4.1 using QNEthernet, such as AsyncHTTPRequest_Generic, AsyncHTTPSRequest_Generic, AsyncMQTT_Generic, Teensy41_AsyncWebSe…

License

NotificationsYou must be signed in to change notification settings

khoih-prog/AsyncHTTPRequest_Teensy41

Repository files navigation

arduino-library-badgeGitHub releasecontributions welcomeGitHub issues

Donate to my libraries using BuyMeACoffee



Table of Contents



Why do we need this AsyncAsyncHTTPRequest_Teensy41 library

Features

  1. Asynchronous HTTP Request library forTeensy 4.1 using built-in QNEthernet
  2. Providing a subset of HTTP.
  3. Relying onTeensy41_AsyncTCP library
  4. Methods similar in format and usage to XmlHTTPrequest in Javascript.

Supports

  1. GET, POST, PUT, PATCH, DELETE and HEAD
  2. Request and response headers
  3. Chunked response
  4. Single String response for short (<~5K) responses (heap permitting).
  5. Optional onData callback.
  6. Optional onReadyStatechange callback.

Principles of operation

This library adds a simple HTTP layer on top of theTeensy41_AsyncTCP library tofacilitate REST communication from a Client to a Server. The paradigm is similar to theXMLHttpRequest in Javascript, employing the notion of a ready-state progression through the transaction request.

Synchronization can be accomplished using callbacks on ready-state change, a callback on data receipt, or simply polling for ready-state change. Data retrieval can be incremental as received, or bulk retrieved when the transaction completes provided there is enough heap to buffer the entire response.

The underlying buffering uses a newxbuf class. It handles both character and binary data. Classxbuf uses a chain of small (64 byte) segments that are allocated and added to the tail as data is added and de-allocated from the head as data is read, achieving the same result as a dynamic circular buffer, limited only by the size of heap. Thexbuf implementsindexOf andreadUntil functions.

For short transactions, buffer space should not be an issue. In fact, it can be more economical than other methods that use larger fixed length buffers. Data is acked when retrieved by the caller, so there is some limited flow control to limit heap usage for larger transfers.

Request and response headers are handled in the typical fashion.

Chunked responses are recognized and handledtransparently.

This library is based on, modified from:

  1. Bob Lemaire's asyncHTTPrequest Library

Currently Supported Boards

  1. Teensy 4.1 using QNEthernet Library


Prerequisites

  1. Arduino IDE 1.8.19+ for Arduino.GitHub release
  2. Teensy core v1.57+ for Teensy 4.1.GitHub release
  3. QNEthernet Library version v0.17.0+ for Teensy 4.1 built-in Ethernet.
  4. Teensy41_AsyncTCP library v1.1.0+ to useTeensy 4.1 using QNEthernet Library. To install, checkarduino-library-badge


Installation

Use Arduino Library Manager

The best and easiest way is to useArduino Library Manager. Search forAsyncHTTPRequest_Teensy41, then select / install the latest version. You can also use this linkarduino-library-badge for more detailed instructions.

Manual Install

  1. Navigate toAsyncHTTPRequest_Teensy41 page.
  2. Download the latest releaseAsyncHTTPRequest_Teensy41-main.zip.
  3. Extract the zip file toAsyncHTTPRequest_Teensy41-main directory
  4. Copy the wholeAsyncHTTPRequest_Teensy41-main folder to Arduino libraries' directory such as~/Arduino/libraries/.

VS Code & PlatformIO

  1. InstallVS Code
  2. InstallPlatformIO
  3. InstallAsyncHTTPRequest_Teensy41 library by usingLibrary Manager. Search for AsyncHTTPRequest_Teensy41 inPlatform.io Author's Libraries
  4. Use includedplatformio.ini file from examples to ensure that all dependent libraries will installed automatically. Please visit documentation for the other options and examples atProject Configuration File


Packages' Patches

1. For Teensy boards

To be able to compile and run on Teensy boards, you have to copy the files inPackages_Patches for Teensy directory into Teensy hardware directory (./arduino-1.8.19/hardware/teensy/avr/boards.txt).

Supposing the Arduino version is 1.8.19. These files must be copied into the directory:

  • ./arduino-1.8.19/hardware/teensy/avr/boards.txt
  • ./arduino-1.8.19/hardware/teensy/avr/cores/teensy/Stream.h
  • ./arduino-1.8.19/hardware/teensy/avr/cores/teensy3/Stream.h
  • ./arduino-1.8.19/hardware/teensy/avr/cores/teensy4/Stream.h

Whenever a new version is installed, remember to copy this file into the new version directory. For example, new version is x.yy.zzThese files must be copied into the directory:

  • ./arduino-x.yy.zz/hardware/teensy/avr/boards.txt
  • ./arduino-x.yy.zz/hardware/teensy/avr/cores/teensy/Stream.h
  • ./arduino-x.yy.zz/hardware/teensy/avr/cores/teensy3/Stream.h
  • ./arduino-x.yy.zz/hardware/teensy/avr/cores/teensy4/Stream.h


HOWTO FixMultiple Definitions Linker Error

The current library implementation, usingxyz-Impl.h instead of standardxyz.cpp, possibly creates certainMultiple Definitions Linker error in certain use cases.

You can include this.hpp file

// Can be included as many times as necessary, without `Multiple Definitions` Linker Error#include"AsyncHTTPRequest_Teensy41.hpp"//https://github.com/khoih-prog/AsyncHTTPRequest_Teensy41

in many files. But be sure to use the following.h filein just 1.h,.cpp or.ino file, which mustnot be included in any other file, to avoidMultiple Definitions Linker Error

// To be included only in main(), .ino with setup() to avoid `Multiple Definitions` Linker Error#include"AsyncHTTPRequest_Teensy41.h"//https://github.com/khoih-prog/AsyncHTTPRequest_Teensy41

Check the newmultiFileProject example for aHOWTO demo.

Have a look at the discussion inDifferent behaviour using the src_cpp or src_h lib #80



Examples

  1. AsyncCustomHeader
  2. AsyncDweetGet
  3. AsyncDweetPost
  4. AsyncHTTPRequest
  5. AsyncSimpleGET
  6. multiFileProject

#include"defines.h"
#defineASYNC_HTTP_REQUEST_TEENSY41_VERSION_MIN_TARGET"AsyncHTTPRequest_Teensy41 v1.10.0"
#defineASYNC_HTTP_REQUEST_TEENSY41_VERSION_MIN1010000
// Uncomment for certain HTTP site to optimize
//#define NOT_SEND_HEADER_AFTER_CONNECTED true
// Level from 0-4
#defineASYNC_HTTP_DEBUG_PORT Serial
#define_ASYNC_HTTP_LOGLEVEL_2
// 600s = 10 minutes to not flooding, 60s in testing
#defineHTTP_REQUEST_INTERVAL_MS10000//600000
// Seconds for timeout, default is 3s
#defineDEFAULT_RX_TIMEOUT10
// To be included only in main(), .ino with setup() to avoid `Multiple Definitions` Linker Error
#include<AsyncHTTPRequest_Teensy41.h>// https://github.com/khoih-prog/AsyncHTTPRequest_Teensy41
#include<Ticker.h>// https://github.com/sstaub/Ticker
AsyncHTTPRequest request;
voidsendRequest();
// Repeat forever, millis() resolution
TickersendHTTPRequest(sendRequest, HTTP_REQUEST_INTERVAL_MS,0, MILLIS);
voidsendRequest()
{
staticbool requestOpenResult;
if (request.readyState() == readyStateUnsent || request.readyState() == readyStateDone)
{
//requestOpenResult = request.open("GET", "http://worldtimeapi.org/api/timezone/Europe/London.txt");
requestOpenResult = request.open("GET","http://worldtimeapi.org/api/timezone/America/Toronto.txt");
if (requestOpenResult)
{
// Only send() if open() returns true, or crash
request.send();
}
else
{
Serial.println("Can't send bad request");
}
}
else
{
Serial.println("Can't send request");
}
}
voidrequestCB(void *optParm, AsyncHTTPRequest *request,int readyState)
{
(void) optParm;
if (readyState == readyStateDone)
{
AHTTP_LOGDEBUG(F("\n**************************************"));
AHTTP_LOGDEBUG1(F("Response Code ="), request->responseHTTPString());
if (request->responseHTTPcode() ==200)
{
Serial.println(F("\n**************************************"));
Serial.println(request->responseText());
Serial.println(F("**************************************"));
}
}
}
voidsetup()
{
Serial.begin(115200);
while (!Serial &&millis() <5000);
Serial.print("\nStart AsyncHTTPRequest on");
Serial.println(BOARD_NAME);
Serial.println(ASYNC_HTTP_REQUEST_TEENSY41_VERSION);
#if defined(ASYNC_HTTP_REQUEST_TEENSY41_VERSION_MIN)
if (ASYNC_HTTP_REQUEST_TEENSY41_VERSION_INT < ASYNC_HTTP_REQUEST_TEENSY41_VERSION_MIN)
{
Serial.print("Warning. Must use this example on Version equal or later than :");
Serial.println(ASYNC_HTTP_REQUEST_TEENSY41_VERSION_MIN_TARGET);
}
#endif
delay(500);
#if USING_DHCP
// Start the Ethernet connection, using DHCP
Serial.print("Initialize Ethernet using DHCP =>");
Ethernet.begin();
#else
// Start the Ethernet connection, using static IP
Serial.print("Initialize Ethernet using static IP =>");
Ethernet.begin(myIP, myNetmask, myGW);
Ethernet.setDNSServerIP(mydnsServer);
#endif
if (!Ethernet.waitForLocalIP(5000))
{
Serial.println(F("Failed to configure Ethernet"));
if (!Ethernet.linkStatus())
{
Serial.println(F("Ethernet cable is not connected."));
}
// Stay here forever
while (true)
{
delay(1);
}
}
else
{
Serial.print(F("Connected! IP address:"));
Serial.println(Ethernet.localIP());
}
#if USING_DHCP
delay(1000);
#else
delay(2000);
#endif
request.setDebug(false);
request.onReadyStateChange(requestCB);
sendHTTPRequest.start();//start the ticker.
// Send first request now
//delay(60);
sendRequest();
}
voidloop()
{
sendHTTPRequest.update();
}


2. Filedefines.h

#ifndef defines_h
#definedefines_h
#if !( defined(CORE_TEENSY) && defined(__IMXRT1062__) && defined(ARDUINO_TEENSY41) )
#error Only Teensy 4.1 supported
#endif
// Debug Level from 0 to 4
#define_TEENSY41_ASYNC_TCP_LOGLEVEL_1
#define_AWS_TEENSY41_LOGLEVEL_1
#defineSHIELD_TYPE"Teensy4.1 QNEthernet"
#if (_AWS_TEENSY41_LOGLEVEL_ > 3)
#warning Using QNEthernet lib for Teensy 4.1. Must also use Teensy Packages Patch or error
#endif
#defineUSING_DHCPtrue
//#define USING_DHCP false
#if !USING_DHCP
// Set the static IP address to use if the DHCP fails to assign
IPAddressmyIP(192,168,2,222);
IPAddressmyNetmask(255,255,255,0);
IPAddressmyGW(192,168,2,1);
//IPAddress mydnsServer(192, 168, 2, 1);
IPAddressmydnsServer(8,8,8,8);
#endif
#include"QNEthernet.h"// https://github.com/ssilverman/QNEthernet
usingnamespaceqindesign::network;
//#include <AsyncHTTPRequest_Teensy41.h>
#endif//defines_h



Debug Terminal Output Samples

1.AsyncHTTPRequest on TEENSY 4.1

Start AsyncHTTPRequest on TEENSY4.1AsyncHTTPRequest_Teensy41 v1.10.0Initialize Ethernetusing DHCP => Connected! IP address:192.168.2.107**************************************abbreviation: ESTclient_ip: aaa.bbb.ccc.ddddatetime:2023-01-31T23:54:16.675525-05:00day_of_week:2day_of_year:31dst:falsedst_from: dst_offset:0dst_until: raw_offset: -18000timezone: America/Torontounixtime:1675227256utc_datetime:2023-02-01T04:54:16.675525+00:00utc_offset: -05:00week_number:5****************************************************************************abbreviation: ESTclient_ip: aaa.bbb.ccc.ddddatetime:2023-01-31T23:55:16.675337-05:00day_of_week:2day_of_year:31dst:falsedst_from: dst_offset:0dst_until: raw_offset: -18000timezone: America/Torontounixtime:1675227316utc_datetime:2023-02-01T04:55:16.675337+00:00utc_offset: -05:00week_number:5**************************************

2.AsyncCustomHeader on TEENSY 4.1

Start AsyncCustomHeader on TEENSY4.1AsyncHTTPRequest_Teensy41 v1.10.0Initialize Ethernetusing DHCP => Connected! IP address:192.168.2.107Sending GET Request to http://worldtimeapi.org/api/timezone/America/Toronto.txt**************************************abbreviation: ESTclient_ip: aaa.bbb.ccc.ddddatetime:2023-01-31T23:56:16.674942-05:00day_of_week:2day_of_year:31dst:falsedst_from: dst_offset:0dst_until: raw_offset: -18000timezone: America/Torontounixtime:1675227376utc_datetime:2023-02-01T04:56:16.674942+00:00utc_offset: -05:00week_number:5**************************************Sending GET Request to http://worldtimeapi.org/api/timezone/America/Toronto.txt**************************************abbreviation: ESTclient_ip: aaa.bbb.ccc.ddddatetime:2023-01-31T23:57:16.675848-05:00day_of_week:2day_of_year:31dst:falsedst_from: dst_offset:0dst_until: raw_offset: -18000timezone: America/Torontounixtime:1675227436utc_datetime:2023-02-01T04:57:16.675848+00:00utc_offset: -05:00week_number:5**************************************

3.AsyncDweetGET on TEENSY 4.1

Start AsyncDweetGET on TEENSY4.1AsyncHTTPRequest_Teensy41 v1.10.0Initialize Ethernetusing DHCP => Connected! IP address:192.168.2.107**************************************{"this":"succeeded","by":"dweeting","the":"dweet","with":{"thing":"currentSecond","created":"2022-03-18T19:51:49.407Z","content":{"second":66},"transaction":"4dcdcae9-ace0-4767-86d0-6b830fd3fc05"}}**************************************"second":66Value string:66Actual value:66

4.AsyncDweetPOST on TEENSY 4.1

Start AsyncDweetPOST on TEENSY4.1AsyncHTTPRequest_Teensy41 v1.10.0Initialize Ethernetusing DHCP => Connected! IP address:192.168.2.107Makingnew POST request**************************************{"this":"succeeded","by":"dweeting","the":"dweet","with":{"thing":"pinA0-Read","created":"2022-03-18T19:57:17.768Z","content":{"sensorValue":1007},"transaction":"76940001-4d31-4995-a712-189d9d874cb1"}}**************************************"sensorValue":1007Value string:1007Actual value:1007

5.AsyncSimpleGET on TEENSY 4.1

Start AsyncSimpleGET on TEENSY4.1AsyncHTTPRequest_Teensy41 v1.10.0Initialize Ethernetusing DHCP => Connected! IP address:192.168.2.107**************************************abbreviation: ESTclient_ip: aaa.bbb.ccc.ddddatetime:2023-01-31T23:58:16.676610-05:00day_of_week:2day_of_year:31dst:falsedst_from: dst_offset:0dst_until: raw_offset: -18000timezone: America/Torontounixtime:1675227496utc_datetime:2023-02-01T04:58:16.676610+00:00utc_offset: -05:00week_number:5****************************************************************************abbreviation: ESTclient_ip: aaa.bbb.ccc.ddddatetime:2023-01-31T23:59:16.675139-05:00day_of_week:2day_of_year:31dst:falsedst_from: dst_offset:0dst_until: raw_offset: -18000timezone: America/Torontounixtime:1675227556utc_datetime:2023-02-01T04:59:16.675139+00:00utc_offset: -05:00week_number:5**************************************


Debug

Debug is enabled by default on Serial.

You can also change the debugging level from 0 to 4

#defineASYNC_HTTP_DEBUG_PORT           Serial// Use from 0 to 4. Higher number, more debugging messages and memory usage.#define_ASYNC_HTTP_LOGLEVEL_1

Troubleshooting

If you get compilation errors, more often than not, you may need to install a newer version of theESP32 / ESP8266 / STM32 core for Arduino.

Sometimes, the library will only work if you update theTeensy core to the latest version because I am using newly added functions.


Issues

Submit issues to:AsyncHTTPRequest_Teensy41 issues


TO DO

  1. Fix bug. Add enhancement
  2. Add many more examples.

DONE

  1. Initial porting and coding forTeensy 4.1 using built-in QNEthernet
  2. Add debugging features.
  3. Add PUT, PATCH, DELETE and HEAD besides GET and POST.
  4. Optimize library code by usingreference-passing instead ofvalue-passing
  5. Fix long timeout if usingIPAddress
  6. Display only successful responseText in examples
  7. Improve debug messages by adding functions to display error messages instead ofcryptic error number
  8. Not try to reconnect to the samehost:port after connected
  9. Fix bug of wrongreqStates
  10. Default to reconnect to the samehost:port after connected for new HTTP sites.
  11. Useallman astyle and addutils
  12. Fix_parseURL() bug. CheckBug with _parseURL() #21
  13. ImproveREADME.md so that links can be used in other sites, such asPIO


Contributions and Thanks

This library is based on, modified, bug-fixed and improved from:

  1. Bob Lemaire'sasyncHTTPrequest Library to use the betterasynchronous features of these following Async TCP Libraries : (ESPAsyncTCP,AsyncTCP, andTeensy41_AsyncTCP )
boblemaire
⭐️ Bob Lemaire


Contributing

If you want to contribute to this project:

  • Report bugs and errors
  • Ask for enhancements
  • Create issues and pull requests
  • Tell other people about this library

License and credits

  • The library is licensed underGPLv3

Copyright

Copyright (C) <2018> <Bob Lemaire, IoTaWatt, Inc.>

Copyright (C) <2022-> Khoi Hoang

About

Simple Async HTTP Request library, supporting GET, POST, PUT, PATCH, DELETE and HEAD, on top of Teensy41_AsyncTCP for Teensy 4.1 using QNEthernet. This library is one of the current or future Async libraries to support Teensy 4.1 using QNEthernet, such as AsyncHTTPRequest_Generic, AsyncHTTPSRequest_Generic, AsyncMQTT_Generic, Teensy41_AsyncWebSe…

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors2

  •  
  •  

[8]ページ先頭

©2009-2025 Movatter.jp