Make an async HTTP request

Hi!

I have a photon board and I am trying to send a http request every time a button is pressed. The problem is the http request seems to block the main loop and can’t detect the next button press until after the request is made. Is there anyway to make the request async so it doesn’t block the loop. The button can be pressed rather rapidly and I want to catch each press.

I am also not 100% that is it blocking, it may be that is just can only send request so fast. If that is the case it there a way to improve the speed the requests can be sent at. I am just making a call to a local server on the same wifi network.

Here is the code for reference

#include <HttpClient.h>
#include <stdio.h>
#include <cstdio>
#include <stdlib.h>

int button = D0;

long startTime = micros();
bool buttonPressed = false;

HttpClient http;
http_header_t headers[] = {
    { "Accept" , "*/*"},
    { NULL, NULL }
};
http_request_t request;
http_response_t response;

void setup() {
	pinMode(button, INPUT_PULLDOWN);
	startTime = micros();
        request.hostname = "192.168.0.212";
        request.port = 3000;
}

void loop() {
    int buttonVal = digitalRead(button);
    
    if (buttonVal == HIGH) {
        if (!buttonPressed) {
            float duration = micros() - startTime;
            char path[128];
            snprintf(path,128,"/lights/switch/up?time=%f",duration);
            request.path = path;
            http.get(request, response, headers);
            startTime = micros();
        }
        buttonPressed = true;
    } else {
        if (buttonPressed) {
            float duration = micros() - startTime;
            char path[128];
            snprintf(path,128,"/lights/switch/down?time=%f",duration);
            request.path = path;
            http.get(request, response, headers);
            startTime = micros();
        }
        buttonPressed = false;
    }
}
1 Like