Git Product home page Git Product logo

khoih-prog / asynchttprequest_rp2040w Goto Github PK

View Code? Open in Web Editor NEW
7.0 2.0 1.0 270 KB

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_RP2040W, AsyncHTTPRequest_RP2040W, AsyncHTTPSRequest_RP2040W, etc.

License: GNU General Public License v3.0

C 74.20% C++ 25.48% Shell 0.32%
async async-http-client async-tcp async-tcp-client cyw43439 http-client raspberry-pi-pico-w rp2040 rp2040w wifi

asynchttprequest_rp2040w's Introduction

AsyncHTTPRequest_RP2040W Library

arduino-library-badge GitHub release contributions welcome GitHub issues

Donate to my libraries using BuyMeACoffee



Table of Contents



Why do we need this Async AsyncHTTPRequest_RP2040W library

Features

  1. Asynchronous HTTP Request library for RASPBERRY_PI_PICO_W using CYW43439 WiFi
  2. Providing a subset of HTTP.
  3. Relying on Khoi 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 the AsyncTCP_RP2040W library to facilitate 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 using arduino-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+ for RASPBERRY_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. check arduino-library-badge


Installation

Use Arduino Library Manager

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

Manual Install

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

VS Code & PlatformIO

  1. Install VS Code
  2. Install PlatformIO
  3. Install AsyncHTTPRequest_RP2040W library by using Library Manager. Search for AsyncHTTPRequest_RP2040W in Platform.io Author's Libraries
  4. Use included platformio.ini file from examples to ensure that all dependent libraries will installed automatically. Please visit documentation for the other options and examples at Project Configuration File


HOWTO Fix Multiple Definitions Linker Error

The current library implementation, using xyz-Impl.h instead of standard xyz.cpp, possibly creates certain Multiple 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 file in just 1 .h, .cpp or .ino file, which must not be included in any other file, to avoid Multiple 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 new multiFileProject example for a HOWTO demo.

Have a look at the discussion in Different 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"
#define ASYNC_HTTP_REQUEST_RP2040W_VERSION_MIN_TARGET "AsyncHTTPRequest_RP2040W v1.2.2"
#define ASYNC_HTTP_REQUEST_RP2040W_VERSION_MIN 1002002
// Uncomment for certain HTTP site to optimize
//#define NOT_SEND_HEADER_AFTER_CONNECTED true
// Level from 0-4
#define ASYNC_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;
void sendRequest()
{
static bool 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");
}
}
void requestCB(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("**************************************"));
}
}
}
void printWifiStatus()
{
// 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);
}
void setup()
{
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);
}
void sendRequestRepeat()
{
static unsigned long sendRequest_timeout = 0;
#define SEND_REQUEST_INTERVAL 60000L
// 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;
}
}
void loop()
{
sendRequestRepeat();
}


2. File defines.h

#ifndef defines_h
#define defines_h
#if !( defined(ARDUINO_RASPBERRY_PI_PICO_W) )
#error For RASPBERRY_PI_PICO_W only
#endif
char ssid[] = "your_ssid"; // your network SSID (name)
char pass[] = "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_W
AsyncTCP_RP2040W v1.1.0
AsyncHTTPRequest_RP2040W v1.3.0
Connecting to SSID: HueNet1
SSID: HueNet1
Local IP Address: 192.168.2.77
Request sent

**************************************
abbreviation: EST
client_ip: aaa.bbb.ccc.ddd
datetime: 2023-01-31T23:54:16.675525-05:00
day_of_week: 2
day_of_year: 31
dst: false
dst_from: 
dst_offset: 0
dst_until: 
raw_offset: -18000
timezone: America/Toronto
unixtime: 1675227256
utc_datetime: 2023-02-01T04:54:16.675525+00:00
utc_offset: -05:00
week_number: 5
**************************************

2. AsyncDweetPost running on RASPBERRY_PI_PICO_W using CYW43439 WiFi

Start AsyncDweetPOST on RASPBERRY_PI_PICO_W with RP2040W CYW43439 WiFi
AsyncTCP_RP2040W v1.1.0
AsyncHTTPRequest_RP2040W v1.3.0
Connecting to SSID: HueNet1
SSID: HueNet1
Local IP Address: 192.168.2.180

Making new 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":88
Value string: 88
Actual value: 88

3. AsyncWebClientRepeating running on RASPBERRY_PI_PICO_W using CYW43439 WiFi

Start AsyncWebClientRepeating on RASPBERRY_PI_PICO_W
AsyncTCP_RP2040W v1.1.0
AsyncHTTPRequest_RP2040W v1.3.0
Connecting to SSID: HueNet1
SSID: HueNet1
Local 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

#define ASYNC_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 the arduino-pico core

Sometimes, the library will only work if you update the arduino-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. Fix multiple-definitions linker error and weird bug related to src_cpp.
  5. Optimize library code by using reference-passing instead of value-passing
  6. Fix long timeout if using IPAddress
  7. Not try to reconnect to the same host:port after connected
  8. Fix bug of wrong reqStates
  9. Default to reconnect to the same host:port after connected for new HTTP sites.
  10. Use allman astyle and add utils
  11. Fix bug of _parseURL(). Check Bug with _parseURL() #21
  12. Improve README.md so that links can be used in other sites, such as PIO


Contributions and Thanks

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

  1. Bob Lemaire's asyncHTTPrequest Library to use the better asynchronous features of AsyncTCP_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 under GPLv3

Copyright

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

Copyright (C) 2022- Khoi Hoang

asynchttprequest_rp2040w's People

Contributors

khoih-prog avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

Forkers

vtt-info

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.