Nest thermostat data access using R

UPDATE 12/03/13: Since Nest Labs’ move to an official API, the code below no longer works. Still, a good example of a webservice connection…

Gets “energy_latest” (10 days of usage) data from Nest Labs:

getNestData <- function(username,password) {
    
    library(RCurl)
    library(rjson)
    
    loginURL <- c("https://home.nest.com/user/login?")
    loginParams <- c("username" = username, "password" = password)
    loginResponse <- fromJSON(postForm(loginURL,.params=loginParams))
    #return(loginResponse)
    
    loginResponseObjects <- list("urls","access_token","userid","expires_in","user")
    
    #note: the following function returns "urls" for the name of the transport_url, since getting 
    #only the first element in each response object (in this case, think of urls as "url secure")
    sapply(loginResponseObjects,function(x) {
        respObj <- unlist(loginResponse[[x]][[1]],use.names=F)
        assign(x,respObj,envir=parent.frame(3))
        })
    
    #url to get system status
    statusURL <- paste(urls,'/v2/mobile/',user,sep="")
    
    #authorization token string
    authToken <- paste("Basic",access_token)
    
    #timestamp in milliseconds -- to pass with data request
    options(digits=13)
    msTimestamp <- as.integer(Sys.time()) * 1000
    
    #RCurl info for User-Agent
    sessInfo <- sessionInfo()
    RCurlVersion <- sessInfo$otherPkgs$RCurl$Version
    userAgent <- paste("RCurl",RCurlVersion)
    
    #status request is just a call to the transport url
    statusHeaders <- c("Host" = urls, "Authorization" = authToken, "X-nl-user-id" = userid, "User-Agent" = userAgent, "Accept-Language" = "en-us")
    status <- fromJSON(getURL(statusURL,httpheader = statusHeaders)) #, verbose = T
    #return(status)
    
    #body for energy_latest 
    deviceID <- as.character(status[['device']][[1]]['serial_number'])
    elKey <- paste("energy_latest",deviceID,sep=".")
    elPostfield <- toJSON(list("keys"=list(list("key" = elKey))))
    
    energyURL <- paste(urls,'/v2/subscribe',sep="")
    
    #headers for energy call
    energyHeaders <- c(statusHeaders,c("X-nl-client-timestamp" = msTimestamp, "X-nl-protocol-version" = "1", "Content-Type" = "application/json")) #
    
    #get the energy data  
    energy <- fromJSON(postForm(energyURL,.opts = list(httpheader = energyHeaders, postfields = elPostfield), style='post')) #, verbose = TRUE
    
    return(energy)
    
}
Advertisements
This entry was posted in data access, R and tagged . Bookmark the permalink.