I am trying to do periodic HTTP request with a time stamp of 1-2 seconds. The program runs on my Raspberry Pi Zero W. Program runs very good and fairly deterministic for the first couple of minutes, and then something happens and I don't get any response for some time, and then, after some time, it unblocks and runs ok until next blockage.
I tried to eliminate curl_easy_cleanup function execution after every http_request because I have red in documentation that curl handles shall not be cleaned very frequently, and it behaves better in reality, for some time..(it blocks again). I have also tried to call curl_easy_cleanup function in handler after every http response, but it produces seg fault.
I expect of my program to be deterministic, in a way to perform HTTP requests on every n seconds.
(This is my first Stack Overflow post, I hope that I managed to explain my question in a good way :) Here is my code:
#include <stdio.h>
#include <curl/curl.h>
#include <string.h>
#include <pigpio.h>
#define PTR_OFFSET 49
#define SIZEOF_MSG 5
#define DELAY_TIME 100
#define GPIO_PIN 25
char niz[20];
char opcija0[] = "00000";
char opcija1[] = "00001";
size_t write_callback(void *contents, size_t size, size_t nmemb, void *userp){
memcpy(niz, (char *)contents + PTR_OFFSET, SIZEOF_MSG);
size_t total_size = size*nmemb;
if (!memcmp(niz, opcija0, SIZEOF_MSG))
{
gpioWrite(GPIO_PIN, 0);
printf("GPIO OFF\n");
}
if (!memcmp(niz, opcija1, SIZEOF_MSG))
{
gpioWrite(GPIO_PIN, 1);
printf("GPIO ON\n");
}
printf("Niz je: %s\n", niz);
return total_size;
}
int main(){
CURL *curl;
CURLcode res;
if (gpioInitialise() < 0)
{
fprintf(stderr, "pigpio initialisation failed\n");
return 1;
}
gpioSetMode(GPIO_PIN, PI_OUTPUT);
while(1)
{
curl = curl_easy_init();
if (curl) {
const char *url = "https://3704-109-245-204-66.ngrok-free.app/Filip/?y=1"; //Replace with wanted URL
//Set the URL
curl_easy_setopt(curl, CURLOPT_URL, url);
//Set the write callback function to print the response
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback);
//Perform the request
res = curl_easy_perform(curl);
//Check for errors
if (res != CURLE_OK) {
fprintf(stderr, "curl_easy_perform() failed: %s\n", curl_easy_strerror(res));
} else {
printf("\nRequest succesful.\n");
}
//Cleanup and free resources
//curl_easy_cleanup(curl);
} else {
fprintf(stderr, "Failed to initialize libcurl.\n");
}
time_sleep(2);
}
return 0;
}