---
title: "Introduction to cumulocityr"
output:
  html_document:
    theme: cerulean
    highlight: textmate
    fig_width: 6
    fig_height: 4
    toc: true
    toc_depth: 2
vignette: >
  %\VignetteIndexEntry{Introduction to cumulocityr}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, echo = FALSE}
NOT_CRAN <- identical(Sys.getenv("NOT_CRAN"), "TRUE")
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  eval = NOT_CRAN
)
```



```{r load-package}
library(cumulocityr)
library(knitr)
```

### Introduction

This vignette introduces the main functions with a few examples.

### Authentication

Credentials and base url for cumulocity are stored in a user's private `.Renviron` file.

The credentials are defined as follows:

```
CUMULOCITY_base_url = "[tenant url]"
CUMULOCITY_usr = "[username]"
CUMULOCITY_pwd = "[password]"
CUMULOCITY_device_id = "[an example device id]"
```

The tenant url should be of the form "https://tenant_name.cumulocity.com". `CUMULOCITY_device_id` is provided for convenience, but is not required by any of the main functions.

The file `.Renviron` can be edited with `usethis::edit_r_environ()`.



### Get devices

Get devices for the tenant and display a few columns. If no arguments are passed, `get_devices()` returns all devices.

```{r}
devices <- get_devices()
print(devices[,c("type", "name", "id")])
```


### Get measurements

Get measurements for device "Temperature #1" and plot the result. Datetimes are returned as character strings; we first convert to `POSIXct` before plotting.
```{r}
meas <- get_measurements(device_id = 53700,
                         num_rows = 100,
                         date_from = "2019-09-30T19:59:00Z")
kable(head(meas[c("time", "type", "c8y_Temperature.T.value")]))

time_parsed <- as.POSIXct(meas$time, format = "%Y-%m-%dT%H:%M:%OSZ", tz = "Z")

plot(time_parsed, meas$c8y_Temperature.T.value, type = "l",
     xlab = "Time", ylab = "Temperature (deg C)")

```


### Get events

Similarly, we can get events for the same device:
```{r}
events <- get_events(device_id = 53700,
                     num_rows = 6,
                     date_from = "2019-09-30T19:59:00Z")

kable(events[c("type", "time", "c8y_Position.lng", "c8y_Position.alt")])
```

### Unparsed data

By default, the content is parsed, but it is possible to return a list of JSON objects.
```{r}
meas_03 <- get_measurements(device_id = 53700,
                            num_rows = 2,
                            date_from = "2019-09-30T19:59:00Z",
                            parse_json = FALSE)

print(meas_03)
```
