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 4, 2023. It is now read-only.

Simple Async HTTP Request library, supporting GET, POST, PUT, PATCH, DELETE and HEAD, on top of AsyncTCP_RP2040W library for RASPBERRY_PI_PICO_W with CYW43439 WiFi. This library, which relies on AsyncTCP_RP2040W, is part of a series of advanced Async libraries, such as AsyncTCP_RP2040W, AsyncUDP_RP2040W, AsyncWebSockets_RP2040W, AsyncWebServer_R…

License

NotificationsYou must be signed in to change notification settings

khoih-prog/AsyncHTTPRequest_RP2040W

Repository files navigation

arduino-library-badgeGitHub releasecontributions welcomeGitHub issues

Donate to my libraries using BuyMeACoffee



Table of Contents



Why do we need this AsyncAsyncHTTPRequest_RP2040W library

Features

  1. Asynchronous HTTP Request library forRASPBERRY_PI_PICO_W using CYW43439 WiFi
  2. Providing a subset of HTTP.
  3. Relying onKhoi Hoang's AsyncTCP_RP2040W
  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 theAsyncTCP_RP2040W library tofacilitate REST communication from a Client to a Server. The paradigm is similar to the XMLHttpRequest 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 new xbuf class. It handles both character and binary data. Class xbuf uses a chain of small (64 byte) segments that are allocated and added to the tail as data is added and deallocated from the head as data is read, achieving the same result as a dynamic circular buffer limited only by the size of heap. The xbuf implements indexOf and readUntil 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 handled transparently.

This library is based on, modified from:

  1. Bob Lemaire's asyncHTTPrequest Library

Currently Supported Boards

  1. RASPBERRY_PI_PICO_W with CYW43439 WiFi usingarduino-pico core v2.4.0+



Prerequisites

  1. Arduino IDE 1.8.19+ for Arduino.GitHub release
  2. Earle Philhower's arduino-pico core v2.7.1+ forRASPBERRY_PI_PICO_W with CYW43439 WiFi, etc.GitHub release
  3. AsyncTCP_RP2040W library v1.1.0+ for RASPBERRY_PI_PICO_W with CYW43439 WiFi. To install. checkarduino-library-badge


Installation

Use Arduino Library Manager

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

Manual Install

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

VS Code & PlatformIO

  1. InstallVS Code
  2. InstallPlatformIO
  3. InstallAsyncHTTPRequest_RP2040W library by usingLibrary Manager. Search forAsyncHTTPRequest_RP2040W 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


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_RP2040W.hpp"//https://github.com/khoih-prog/AsyncHTTPRequest_RP2040W

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_RP2040W.h"//https://github.com/khoih-prog/AsyncHTTPRequest_RP2040W

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. AsyncHTTPRequest
  2. AsyncCustomHeader
  3. AsyncDweetGet
  4. AsyncDweetPost
  5. AsyncSimpleGET
  6. AsyncWebClientRepeating
  7. multiFileProject

Please take a look at other examples, as well.

#include"defines.h"
#defineASYNC_HTTP_REQUEST_RP2040W_VERSION_MIN_TARGET"AsyncHTTPRequest_RP2040W v1.2.2"
#defineASYNC_HTTP_REQUEST_RP2040W_VERSION_MIN1002002
// 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_1
// To be included only in main(), .ino with setup() to avoid `Multiple Definitions` Linker Error
#include<AsyncHTTPRequest_RP2040W.h>// https://github.com/khoih-prog/AsyncHTTPRequest_RP2040W
AsyncHTTPRequest request;
int status = WL_IDLE_STATUS;
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");
//requestOpenResult = request.open("GET", "http://213.188.196.246/api/timezone/America/Toronto.txt");
if (requestOpenResult)
{
Serial.println("Request sent");
// 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_LOGWARN(F("\n**************************************"));
AHTTP_LOGWARN1(F("Response Code ="), request->responseHTTPString());
if (request->responseHTTPcode() ==200)
{
Serial.println(F("\n**************************************"));
Serial.println(request->responseText());
Serial.println(F("**************************************"));
}
}
}
voidprintWifiStatus()
{
// print the SSID of the network you're attached to:
Serial.print("SSID:");
Serial.println(WiFi.SSID());
// print your board's IP address:
IPAddress ip = WiFi.localIP();
Serial.print("Local IP Address:");
Serial.println(ip);
}
voidsetup()
{
Serial.begin(115200);
while (!Serial &&millis() <5000);
Serial.print("\nStart AsyncHTTPRequest on");
Serial.println(BOARD_NAME);
Serial.println(ASYNCTCP_RP2040W_VERSION);
Serial.println(ASYNC_HTTP_REQUEST_RP2040W_VERSION);
#if defined(ASYNC_HTTP_REQUEST_RP2040W_VERSION_MIN)
if (ASYNC_HTTP_REQUEST_RP2040W_VERSION_INT < ASYNC_HTTP_REQUEST_RP2040W_VERSION_MIN)
{
Serial.print("Warning. Must use this example on Version equal or later than :");
Serial.println(ASYNC_HTTP_REQUEST_RP2040W_VERSION_MIN_TARGET);
}
#endif
///////////////////////////////////
// check for the WiFi module:
if (WiFi.status() == WL_NO_MODULE)
{
Serial.println("Communication with WiFi module failed!");
// don't continue
while (true);
}
Serial.print(F("Connecting to SSID:"));
Serial.println(ssid);
status = WiFi.begin(ssid, pass);
delay(1000);
// attempt to connect to WiFi network
while ( status != WL_CONNECTED)
{
delay(500);
// Connect to WPA/WPA2 network
status = WiFi.status();
}
printWifiStatus();
///////////////////////////////////
request.setDebug(false);
request.onReadyStateChange(requestCB);
}
voidsendRequestRepeat()
{
staticunsignedlong sendRequest_timeout =0;
#defineSEND_REQUEST_INTERVAL60000L
// sendRequest every SEND_REQUEST_INTERVAL (60) seconds: we don't need to sendRequest frequently
if ((millis() > sendRequest_timeout) || (sendRequest_timeout ==0))
{
sendRequest();
sendRequest_timeout =millis() + SEND_REQUEST_INTERVAL;
}
}
voidloop()
{
sendRequestRepeat();
}


2. Filedefines.h

#ifndefdefines_h
#definedefines_h
#if !( defined(ARDUINO_RASPBERRY_PI_PICO_W) )
#error For RASPBERRY_PI_PICO_W only
#endif
charssid[]="your_ssid";// your network SSID (name)
charpass[]="12345678";// your network password (use for WPA, or use as key for WEP), length must be 8+
#endif//defines_h



Debug Terminal Output Samples

1.AsyncHTTPRequest running on RASPBERRY_PI_PICO_W using CYW43439 WiFi

Start AsyncHTTPRequest on RASPBERRY_PI_PICO_WAsyncTCP_RP2040W v1.1.0AsyncHTTPRequest_RP2040W v1.3.0Connecting to SSID: HueNet1SSID: HueNet1Local IP Address:192.168.2.77Request sent**************************************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**************************************

2.AsyncDweetPost running on RASPBERRY_PI_PICO_W using CYW43439 WiFi

Start AsyncDweetPOST on RASPBERRY_PI_PICO_W with RP2040W CYW43439 WiFiAsyncTCP_RP2040W v1.1.0AsyncHTTPRequest_RP2040W v1.3.0Connecting to SSID: HueNet1SSID: HueNet1Local IP Address:192.168.2.180Makingnew POST request**************************************{"this":"succeeded","by":"dweeting","the":"dweet","with":{"thing":"pinA0-Read","created":"2022-08-14T00:17:43.768Z","content":{"sensorValue":88},"transaction":"34ca3083-054b-42ef-bcb0-91f7150dc680"}}**************************************"sensorValue":88Value string:88Actual value:88

3.AsyncWebClientRepeating running on RASPBERRY_PI_PICO_W using CYW43439 WiFi

Start AsyncWebClientRepeating on RASPBERRY_PI_PICO_WAsyncTCP_RP2040W v1.1.0AsyncHTTPRequest_RP2040W v1.3.0Connecting to SSID: HueNet1SSID: HueNet1Local IP Address:192.168.2.180**************************************           `:;;;,`                      .:;;:.                   .;;;;;;;;;;;`                :;;;;;;;;;;:     TM       `;;;;;;;;;;;;;;;`            :;;;;;;;;;;;;;;;           :;;;;;;;;;;;;;;;;;;         `;;;;;;;;;;;;;;;;;;         ;;;;;;;;;;;;;;;;;;;;;       .;;;;;;;;;;;;;;;;;;;;       ;;;;;;;;:`   `;;;;;;;;;     ,;;;;;;;;.`   .;;;;;;;;     .;;;;;;,         :;;;;;;;   .;;;;;;;          ;;;;;;;    ;;;;;;             ;;;;;;;  ;;;;;;,            ;;;;;;.  ,;;;;;               ;;;;;;.;;;;;;`              ;;;;;;  ;;;;;.                ;;;;;;;;;;;`      ```       ;;;;;` ;;;;;                  ;;;;;;;;;,       ;;;       .;;;;;`;;;;:                  `;;;;;;;;        ;;;        ;;;;;,;;;;`    `,,,,,,,,      ;;;;;;;      .,,;;;,,,     ;;;;;:;;;;`    .;;;;;;;;       ;;;;;,      :;;;;;;;;     ;;;;;:;;;;`    .;;;;;;;;      `;;;;;;      :;;;;;;;;     ;;;;;.;;;;.                   ;;;;;;;.        ;;;        ;;;;; ;;;;;                  ;;;;;;;;;        ;;;        ;;;;; ;;;;;                 .;;;;;;;;;;       ;;;       ;;;;;, ;;;;;;               `;;;;;;;;;;;;                ;;;;;  `;;;;;,             .;;;;;; ;;;;;;;              ;;;;;;   ;;;;;;:           :;;;;;;.  ;;;;;;;            ;;;;;;     ;;;;;;;`       .;;;;;;;,    ;;;;;;;;        ;;;;;;;:      ;;;;;;;;;:,:;;;;;;;;;:      ;;;;;;;;;;:,;;;;;;;;;;       `;;;;;;;;;;;;;;;;;;;.        ;;;;;;;;;;;;;;;;;;;;          ;;;;;;;;;;;;;;;;;           :;;;;;;;;;;;;;;;;:            ,;;;;;;;;;;;;;,              ;;;;;;;;;;;;;;                .;;;;;;;;;`                  ,;;;;;;;;:                                                                                                                                                                                                                                                 ;;;   ;;;;;`  ;;;;:  .;;  ;; ,;;;;;, ;;. `;,  ;;;;       ;;;   ;;:;;;  ;;;;;; .;;  ;; ,;;;;;: ;;; `;, ;;;:;;     ,;:;   ;;  ;;  ;;  ;; .;;  ;;   ,;,   ;;;,`;, ;;  ;;     ;; ;:  ;;  ;;  ;;  ;; .;;  ;;   ,;,   ;;;;`;, ;;  ;;.    ;: ;;  ;;;;;:  ;;  ;; .;;  ;;   ,;,   ;;`;;;, ;;  ;;`   ,;;;;;  ;;`;;   ;;  ;; .;;  ;;   ,;,   ;; ;;;, ;;  ;;    ;;  ,;, ;; .;;  ;;;;;:  ;;;;;: ,;;;;;: ;;  ;;, ;;;;;;    ;;   ;; ;;  ;;` ;;;;.   `;;;:  ,;;;;;, ;;  ;;,  ;;;;   **************************************


Debug

Debug is enabled by default on Serial.

You can also change the debugging level from 0 to 4

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

Troubleshooting

If you get compilation errors, more often than not, you may need to install a newer version of thearduino-pico core

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


Issues

Submit issues to:AsyncHTTPRequest_RP2040W issues


TO DO

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

DONE

  1. Add support to RASPBERRY_PI_PICO_W using CYW43439 WiFi
  2. Add debugging features.
  3. Add PUT, PATCH, DELETE and HEAD besides GET and POST.
  4. Fixmultiple-definitions linker error and weird bug related tosrc_cpp.
  5. Optimize library code by usingreference-passing instead ofvalue-passing
  6. Fix long timeout if usingIPAddress
  7. Not try to reconnect to the samehost:port after connected
  8. Fix bug of wrongreqStates
  9. Default to reconnect to the samehost:port after connected for new HTTP sites.
  10. Useallman astyle and addutils
  11. Fix bug of_parseURL(). CheckBug with _parseURL() #21
  12. 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 ofAsyncTCP_RP2040W.
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 AsyncTCP_RP2040W library for RASPBERRY_PI_PICO_W with CYW43439 WiFi. This library, which relies on AsyncTCP_RP2040W, is part of a series of advanced Async libraries, such as AsyncTCP_RP2040W, AsyncUDP_RP2040W, AsyncWebSockets_RP2040W, AsyncWebServer_R…

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp