#' @title Gestión alumbrados (exterior, parking) y ventiladores + actualizacióna atributos en base a horarios plataforma
#'
#' @description Gestión alumbrados (exterior, parking) y ventiladores + actualizacióna atributos en base a horarios definidos en la plataforma.
#'
#' @param campo
#'
#' @return json
#'
#' @examples gestion_on_off_horarios_alumbrados_ventiladores("exterior")
#'
#' @import httr
#' jsonlite
#' rjson
#' RCurl
#' dplyr
#' lubridate
#' timeDate
#'
#' @export
gestion_on_off_horarios_alumbrados_ventiladores <- function(campo){
campo <- as.character(campo) # Selectro del campo (exterior, parking o ventiladores)
# ==============================================================================
# PETICIÓN TOKEN THB
# ==============================================================================
cuerpo <- '{"username":"kepa@techfriendly.es","password":"kepa_tech"}'
post <- httr::POST(url = "http://116.202.100.157:8080/api/auth/login",
add_headers("Content-Type"="application/json","Accept"="application/json"),
body = cuerpo,
encode = "json",verbose()
)
resultado_peticion_token <- httr::content(post)
auth_thb <- paste("Bearer",resultado_peticion_token$token)
auth_chirpstack <- "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhcGlfa2V5X2lkIjoiOTU2OWFkODctZGQzMC00NWM3LWJiY2EtNjhiMDFhNGE5ODY2IiwiYXVkIjoiYXMiLCJpc3MiOiJhcyIsIm5iZiI6MTYxMDQzNzg1Mywic3ViIjoiYXBpX2tleSJ9.gEnEi84JHBkqZMxKiJLe8wRE-ZaNKTXmOXj4sqoGD9g"
# ==============================================================================
# LECTURA ATRIBUTOS HORARIO
# ==============================================================================
id_dispositivo <- "3202bd70-418c-11ec-b26c-5339f6f4e88b" # Disposiitvo "Horarios". Contiene los horarios como atributos del servidor.
# Petición atributos
claves_atributos <- URLencode(c("Horario alumbrado exterior OFF,Horario alumbrado exterior ON,Horario alumbrado parking OFF,Horario alumbrado parking ON,Horario ventiladores ON,Horario ventiladores OFF"))
url <- paste("http://116.202.100.157:8080/api/plugins/telemetry/DEVICE/",id_dispositivo,"/values/attributes?keys=",claves_atributos,sep = "")
atributos <- httr::GET(url = url, add_headers("Content-Type"="application/json","Accept"="application/json","X-Authorization"=auth_thb))
atributos <- jsonlite::fromJSON(rawToChar(atributos$content))
# ==============================================================================
# LÓGICA ON/OFF
# ==============================================================================
tiempo_actual <- Sys.time()
second(tiempo_actual) <- 0
# Horarios OFF/ON en base al campo
horarios <- switch (campo,
"exterior" = c(atributos$value[grep("Horario alumbrado exterior OFF",atributos$key)], atributos$value[grep("Horario alumbrado exterior ON",atributos$key)]),
"parking" = c(atributos$value[grep("Horario alumbrado parking OFF",atributos$key)], atributos$value[grep("Horario alumbrado parking ON",atributos$key)]),
"ventiladores" = c(atributos$value[grep("Horario ventiladores OFF",atributos$key)], atributos$value[grep("Horario ventiladores ON",atributos$key)])
)
tiempo_off <- Sys.time()
hour(tiempo_off) <- as.numeric(gsub("[:].*","",horarios[1]))
minute(tiempo_off) <- as.numeric(gsub(".*[:]","",horarios[1]))
second(tiempo_off) <- 0
tiempo_on <- Sys.time()
hour(tiempo_on) <- as.numeric(gsub("[:].*","",horarios[2]))
minute(tiempo_on) <- as.numeric(gsub(".*[:]","",horarios[2]))
second(tiempo_on) <- 0
dev_eui_alumbrado_exterior <- "70b3d54996e1a124"
dev_eui_parking <- c("70b3d54996e1a124", "70b3d5499ed16ab2")
dev_eui_ventiladores <- c("70b3d54990ad715c","70b3d54993efda3d","70b3d54996e1a124")
if(tiempo_actual >= tiempo_on && tiempo_actual < (tiempo_on + 60*15)){ # Encender
accion <- 1
}else if(tiempo_actual >= tiempo_off && tiempo_actual < (tiempo_off + 60*15)){ # Apagar
accion <- 0
}
# ==============================================================================
# EJECUCIÓN ON/OFF
# ==============================================================================
# Ejecucción encendido o apagado
switch (campo,
"exterior" = {
id_dispositivos <- "14661340-819b-11eb-b605-01af9c6dd825"
#atributos_actualizacion <- c("Alumbrado OFF/ON 1", "Alumbrado OFF/ON 2", "Alumbrado OFF/ON 3", "Alumbrado OFF/ON 4") # Rampas 1, Rampas 2, Proyectores 1, Proyectores 2
atributos_actualizacion <- c("Alumbrado OFF/ON 1", "Alumbrado OFF/ON 2") # Rampas 1, Rampas 2
dev_eui <- dev_eui_alumbrado_exterior
url_downlink_chirp <- paste("http://94.130.25.30:8080/api/devices/",dev_eui,"/queue",sep = "")
if(accion == 1){
#comandos <- c("MTAx", "MjAx", "MzAx", "NDAx")
comandos <- c("MTAx", "MjAx")
}else{
#comandos <- c("MTAw", "MjAw", "MzAw", "NDAw")
comandos <- c("MTAw", "MjAw")
}
for(i in 1:length(comandos)){
post <- httr::POST(url = url_downlink_chirp,
add_headers("Content-Type"="application/json","Accept"="application/json","Grpc-Metadata-Authorization"=auth_chirpstack),
body = list(deviceQueueItem=list(confirmed= TRUE,data=comandos[i],devEUI=dev_eui,fPort= 2)),
encode = "json",verbose()
)
Sys.sleep(3)
}
},
"parking" = {
id_dispositivos <- c("14661340-819b-11eb-b605-01af9c6dd825", "6a360ae0-819c-11eb-b605-01af9c6dd825")
#atributos_actualizacion <- c("Alumbrado OFF/ON 1", "Alumbrado OFF/ON 2", "Alumbrado OFF/ON 5", "Alumbrado OFF/ON 6") # Parking 2, Parking 4, Parking 1, Parking 3
atributos_actualizacion <- c("Alumbrado OFF/ON 1", "Alumbrado OFF/ON 6") # Parking 2, Parking 3
dev_eui <- dev_eui_parking
for(j in 1:length(dev_eui)){
url_downlink_chirp <- paste("http://94.130.25.30:8080/api/devices/",dev_eui[j],"/queue",sep = "")
if(accion == 1){
#comandos <- c("NTAx", "NjAx", "MTAx", "MjAx")
comandos <- c("NTAx", "MjAx")
}else{
#comandos <- c("NTAw", "NjAw", "MTAw", "MjAw")
comandos <- c("NTAw", "MjAw")
}
for(i in 1:((length(comandos)-length(dev_eui)))){
if(j > 1){
i <- i+j
}
post <- httr::POST(url = url_downlink_chirp,
add_headers("Content-Type"="application/json","Accept"="application/json","Grpc-Metadata-Authorization"=auth_chirpstack),
body = list(deviceQueueItem=list(confirmed= TRUE,data=comandos[i],devEUI=dev_eui[j],fPort= 2)),
encode = "json",verbose()
)
Sys.sleep(3)
}
}
},
"ventiladores" = {
id_dispositivos <- c("622988c0-7681-11eb-b605-01af9c6dd825", "1bd63020-7682-11eb-b605-01af9c6dd825", "14661340-819b-11eb-b605-01af9c6dd825")
atributos_actualizacion <- c("Alumbrado OFF/ON 1", "Alumbrado OFF/ON 2", "Alumbrado OFF/ON 3", "Alumbrado OFF/ON 4", "Alumbrado OFF/ON 5", "Alumbrado OFF/ON 6")
dev_eui <- dev_eui_ventiladores
dev_eui_df <- c(rep(dev_eui[1],3), rep(dev_eui[2],6), rep(dev_eui[3],2))
comandos_on_df <- c("NzAx","ODAx","OTAx","NzAx","ODAx","OTAx","MTAwMQ==","MjAwMQ==","MzAwMQ==","NzAx","ODAx")
comandos_off_df <- c("NzAw","ODAw","OTAw","NzAw","ODAw","OTAw","MTAwMA==","MjAwMA==","MzAwMA==","NzAw","ODAw")
df <- data.frame(dev_eui_df,comandos_off_df,comandos_on_df,stringsAsFactors = FALSE)
for(j in 1:length(dev_eui)){
url_downlink_chirp <- paste("http://94.130.25.30:8080/api/devices/",dev_eui[j],"/queue",sep = "")
if(accion == 1){
comandos <- df$comandos_on_df[df$dev_eui_df == dev_eui[j]]
}else{
comandos <- df$comandos_off_df[df$dev_eui_df == dev_eui[j]]
}
for(i in 1:length(comandos)){
post <- httr::POST(url = url_downlink_chirp,
add_headers("Content-Type"="application/json","Accept"="application/json","Grpc-Metadata-Authorization"=auth_chirpstack),
body = list(deviceQueueItem=list(confirmed= TRUE,data=comandos[i],devEUI=dev_eui[j],fPort= 2)),
encode = "json",verbose()
)
Sys.sleep(3)
}
}
}
)
# ==============================================================================
# ACTUALIZACIÓN ATRIBUTOS
# ==============================================================================
for(i in 1:length(id_dispositivos)){
# GET token del dispositivo
url <- paste("http://116.202.100.157:8080/api/device/",id_dispositivos[i],"/credentials",sep = "")
get_token <- httr::GET(url = url, add_headers("Content-Type"="application/json","Accept"="application/json","X-Authorization"=auth_thb))
token <- jsonlite::fromJSON(rawToChar(get_token$content))
token <- token$credentialsId
url <- paste("http://116.202.100.157:8080/api/v1/",token,"/attributes",sep = "")
if(accion == 1){
valor <- TRUE
}else{
valor <- FALSE
}
switch (campo,
"exterior" = {
# 1) json exterior
json_envio_plataforma <- paste('{"Alumbrado OFF/ON 1":', valor,
',"Alumbrado OFF/ON 2":', valor,
'}',sep = "")
},
"parking" = {
# 2) json parking
if(i == 1){
json_envio_plataforma <- paste('{"Alumbrado OFF/ON 6":', valor,
'}',sep = "")
}else{
json_envio_plataforma <- paste('{"Alumbrado OFF/ON 1":', valor,
'}',sep = "")
}
},
"ventiladores" = {
# 2) json ventiladores
if(i == 1){
json_envio_plataforma <- paste('{"Ventilador OFF/ON 1":', valor,
',"Ventilador OFF/ON 2":', valor,
',"Ventilador OFF/ON 3":', valor,
'}',sep = "")
}else if(i == 2){
json_envio_plataforma <- paste('{"Ventilador OFF/ON 1":', valor,
',"Ventilador OFF/ON 2":', valor,
',"Ventilador OFF/ON 3":', valor,
',"Ventilador OFF/ON 4":', valor,
'"Ventilador OFF/ON 5":', valor,
',"Ventilador OFF/ON 6":', valor,
'}',sep = "")
}else{
json_envio_plataforma <- paste('{"Ventilador OFF/ON 1":', valor,
',"Ventilador OFF/ON 2":', valor,
'}',sep = "")
}
}
)
post <- httr::POST(url = url,
add_headers("Content-Type"="application/json","Accept"="application/json","X-Authorization"=auth_thb),
body = json_envio_plataforma,
verify= FALSE,
encode = "json",verbose()
)
}
return(1)
}
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.