R/swob.R

Defines functions eccc_swob_rt

Documented in eccc_swob_rt

#' eccc_swob_rt
#'
#' @description Get real-time surface weather observations (SWOB)
#' @param station_number MSC climate station identifier, see
#' \code{eccc_clim_stns}
#' @param start_date Minimum date for values. Data goes back to a maximum of 30
#' days
#' @param end_date Maximum date for values. Data goes back to a maximum of 30
#' days
#' @param query (Optional) List of queryables. This allows for more complicated
#' queries. See \code{eccc_queryables("swob-realtime")}
#' @return \code{tibble} with SWOB data. Note that this table contains a large
#' number of columns (>300).
#' @export
#' @examples
#' eccc_swob_rt(
#'   station_number = "1192948",
#'   start_date = Sys.Date() - 2,
#'   end_date = Sys.Date()
#' )
eccc_swob_rt <- function(station_number, start_date, end_date, query) {
  query_path <- "collections/swob-realtime/items"

  check_missing <- c(
    missing(station_number),
    missing(query)
  )

  if (all(check_missing)) {
    stop("Must provide either ``station_number`` or ``query``")
  }

  if (start_date > end_date) {
    stop("`start_date` must be <= `end_date`")
  }

  # Init empty query list
  if (missing(query)) {
    query <- list()
  }

  # Add station number
  if (!missing(station_number)) {
    query[["clim_id-value"]] <- paste(station_number, collapse = "/")
  }

  # Add dates
  start_date <- format(as.Date(start_date), "%Y-%m-%d")
  end_date <- format(as.Date(end_date), "%Y-%m-%d")

  query[["datetime"]] <- paste(c(start_date, end_date), collapse = "/")

  req <- eccc_request(path = query_path, query = query)

  if (!length(req$content$features)) {
    stop("No data available for selected stations/dates.")
  }

  parsed_req <- eccc_paginate(req)

  dplyr::select(parsed_req, -type)
}
rywhale/ecccgeometR documentation built on Dec. 22, 2021, 8:19 p.m.