more function

This commit is contained in:
Simon 2024-08-16 15:15:01 +02:00
parent b7b81e2ef2
commit bda91ce189
3 changed files with 76 additions and 8 deletions

23
R/getIdFromCoords.R Normal file
View file

@ -0,0 +1,23 @@
getIdFromCoords <- function(coords,stations=NULL,N=1){
# Ensure coords is a numeric vector of length 2 (latitude and longitude)
if (!is.numeric(coords) || length(coords) != 2) {
stop("coords must be a numeric vector of length 2 (latitude, longitude)")
}
# Load stations data if not provided
if (is.null(stations)) {
stations <- getStations()
# Further check to ensure stations is a data.frame and has required columns
if (!is.data.frame(stations) || !all(c("Latitude", "Longitude", "Id_station") %in% names(stations))) {
stop("stations must be a data frame with at least 'Latitude', 'Longitude', and 'Id_station' columns")
}
}
if(is.null(stations))stations=getStations()
# Calculate Euclidean distances and find the closest station
station.alldist <- dist(rbind(coords, cbind(stations$Latitude, stations$Longitude)))
closestIndexes <- order(as.matrix(station.alldist)[1, -1])
# Return the ID of the closest station
return(stations[closestIndexes[1:N],])
}

View file

@ -1,4 +1,4 @@
getStationData <- function(start_date, end_date, station_id,headers = headers,dpclim = "public/DPClim/v1/") { getStationData <- function(start_date, end_date, station_id,headers = headers,dpclim = "public/DPClim/v1/",timesleep=5,base="https://public-api.meteofrance.fr") {
start_date <- as.Date(start_date) start_date <- as.Date(start_date)
end_date <- as.Date(end_date) end_date <- as.Date(end_date)
url <- modify_url(base,path = paste0(dpclim,"commande-station/infrahoraire-6m")) url <- modify_url(base,path = paste0(dpclim,"commande-station/infrahoraire-6m"))
@ -13,24 +13,22 @@ getStationData <- function(start_date, end_date, station_id,headers = headers,dp
# Add headers # Add headers
# Make the GET request # Make the GET request
response <- GET(url_with_params, headers) response <- request_api(url_with_params, headers,code=202)
if(response$status_code == 202){ if(response$status_code == 202){
url <- modify_url(base,path = paste0(dpclim,"commande/fichier")) url <- modify_url(base,path = paste0(dpclim,"commande/fichier"))
parameters <- list("id-cmde" = content(response)[[1]][[1]] ) parameters <- list("id-cmde" = content(response)[[1]][[1]] )
# Create the complete URL with parameters
url_with_params <- modify_url(url, query = parameters) url_with_params <- modify_url(url, query = parameters)
response <- GET(url_with_params, headers) response <- request_api(url_with_params, headers,code=c(204,201))
while(response$status_code == 204){ while(response$status_code == 204){
response <- GET(url_with_params, headers)
print("file not finished yet, wait 5s") print("file not finished yet, wait 5s")
Sys.sleep(5) Sys.sleep(60)
response <- request_api(url_with_params, headers,code=c(204,201))
} }
if(response$status_code == 201){ if(response$status_code == 201){
return(read.csv(text=content(response,as="text")[[1]],sep=";",header=T,dec = ",")) return(read.csv(text=content(response,as="text")[[1]],sep=";",header=T,dec = ","))
} }
} }
print(sprintf("Failed to retrieve data from the API. Status code: %s", response$status_code)) print("Failed to retrieve data from the API. Why? not sure..")
return(NULL) return(NULL)
} }

47
R/request.R Normal file
View file

@ -0,0 +1,47 @@
#' Perform a GET request with retries
#'
#' This function attempts to perform a GET request to the specified URL with the provided headers
#' and checks for a specific HTTP status code. It retries the request if the desired status code is not received,
#' or if the request results in an error.
#'
#' @param url_with_params The full URL to which the GET request is made, including any necessary query parameters.
#' @param headers A list of headers to include in the GET request.
#' @param code The desired HTTP status code for a successful request.
#'
#' @return NULL if the request does not succeed within the retry limit or if the desired status code is not achieved.
#' Otherwise, returns the response from the successful GET request.
#' @examples
#' \dontrun{
#' url <- "http://example.com/api"
#' headers <- list(Authorization = "Bearer TOKEN", Accept = "application/json")
#' code <- 200 # Looking for a '200 OK' response
#' response <- requests(url, headers, code)
#' if (is.null(response)) {
#' print("Request failed or did not return the expected status code.")
#' } else {
#' print("Request succeeded.")
#' }
#' }
#' @export
#' @import httr
request_api <- function(url_with_params,headers,code,retry_limit=5,timesleep=20){
retry_count <- 0
success <- FALSE
while(retry_count < retry_limit && !success) {
response <- tryCatch(GET(url_with_params, headers),error=function(e){print(e);NULL})
print(response)
if(!is.null(response) && (response$status_code %in% code)) {
success <- TRUE
} else {
print(url_with_params)
print(paste0("retry #",retry_count,"/",retry_limit))
retry_count <- retry_count + 1
Sys.sleep(timesleep)
}
}
if(!success) return(NULL)
else return(response)
}