R/sensor-catalog.R

Defines functions wl_sensors

Documented in wl_sensors

#' Get a catalog of all types of sensors
#'
#' Returns a catalog of all available sensor types.
#'
#' @param api_key,api_secret WeatherLink API (V2) key/secret. Generate & retrieve them from
#'        [your account page](https://www.weatherlink.com/account). Automagically retrieved from
#'        `WEATHERLINK_API_KEY` and `WEATHERLINK_API_SECRET` environment variables.
#' @return data frame with a `generated_at` attribute
#' @references [API Endpoint](https://weatherlink.github.io/v2-api/api-reference);
#'   [Data structure types](https://weatherlink.github.io/v2-api/data-structure-types)
#' @export
wl_sensors <- function(api_key = Sys.getenv("WEATHERLINK_API_KEY"),
                       api_secret = Sys.getenv("WEATHERLINK_API_SECRET")) {

  list(
    `api-key` = api_key,
    `t` = as.character(as.integer(Sys.time()))
  ) -> params

  digest::hmac(
    key = api_secret,
    object = paste(names(params), as.character(params), sep = "", collapse = ""),
    algo = "sha256"
  ) -> params[["api-signature"]]

  httr::GET(
    url = "https://api.weatherlink.com/v2/sensor-catalog",
    query = params,
    .WEATHERLINK_UA
  ) -> res

  httr::stop_for_status(res)

  res <- httr::content(res, as = "text", encoding = "UTF-8")

  out <- jsonlite::fromJSON(res)

  attr(out$sensor_types, "generated_at") <- anytime::anytime(out$generated_at)

  invisible(out$sensor_types)

}
hrbrmstr/weatherlink documentation built on Jan. 20, 2021, 10:34 p.m.