public
Last active

Pachube R Functions

  • Download Gist
Pachube.R
R
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
library(rjson)
library(RCurl)
 
Pachube.query <- function(feed='504')
{
json<-getURL(
paste('http://api.pachube.com/v2/feeds/',feed,sep=''),
netrc='optional')
data<-fromJSON(json)
if (data$private == "true" || !is.null(data$error)) stop(data)
return (sapply(data$datastreams,"[[",i="id"))
}
 
Pachube.fetch <- function(feed='504',datastream='0',hours=6)
{
max_range=c(0,6,12,24,5*24,14*24,31*24,90*24,180*24,365*24,365*24)
max_value=c(0,30,60,300,900,3600,10800,21600,43200,84600)
interval=max_value[max(which(max_range<hours))]
start=format(Sys.time()-hours*3600+60,"%Y-%m-%dT%H:%M:%OSZ",tz="UTC")
pages=ceiling(hours*3600/max(1,interval)/1000)
res=matrix(nrow=0,ncol=2)
for (p in 1:pages) {
json<-getURL(paste(
'http://api.pachube.com/v2/feeds/',feed,
'/datastreams/',datastream,
'?start=',start,
'&page=',p,
'&per_page=1000',
'&interval=',interval,
sep=''),netrc='optional')
data<-fromJSON(json)
if (!is.null(data$error)) stop(data)
if (length(data$datapoints)==0) break
m<-matrix(unlist(data$datapoints),ncol=2,byrow=T)
res<-rbind(res,m)
}
return (data.frame(
ts=strptime(res[,2],"%Y-%m-%dT%H:%M:%OS",tz="UTC"),
val=as.numeric(res[,1])))
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.