library(ggplot2)

toUtime <- function(df, crellin=T, tsep=T) {
  strf <- "%Y-%m-%dT%H:%M:%S"
  if(!tsep)
    strf <- "%Y-%m-%d %H:%M:%S"
  amount <- 0  
  for(i in c(1:nrow(df))) {
    amount <- as.numeric(as.POSIXct(df$time[i], strf, tz="UTC"))
    if(crellin)
      amount <- amount + 3600 #BST update
    df$utime[i] <- amount
  }
  return(df)
}

#Xively
trl.lr <- read.csv('./trl_xively_living_room.csv', head=F)
colnames(trl.lr) <- c("var","time","value")

#Pi
trl.pi.lr <- read.delim('./trl_living_room_pi.txt')

#change to unix time
levels(trl.lr$time) <- sapply(levels(trl.lr$time), function(x) substring(x,1,nchar(x)-1))
trl.lr$utime <- 0
trl.pi.lr$utime <- 0

trl.lr <- toUtime(trl.lr)
trl.pi.lr <- toUtime(trl.pi.lr, F, F)

#trl.lr$utime <- sapply(trl.lr$time, function(x) as.numeric(as.POSIXct(x, "%Y-%m-%dT%H:%M:%S", tz="UTC")))
trl.lr.temp <- trl.lr[trl.lr$var == "3_Temperature",]

df <- data.frame(sensor=2, time=trl.lr.temp$utime, value=as.numeric(trl.lr.temp$value))
df <- rbind(df, data.frame(sensor=trl.pi.lr$sensor, time=trl.pi.lr$utime, value=as.numeric(trl.pi.lr$temperature)))

#try subtracting 1.25 from 3 -- TEST REMOVE
#df$value[df$sensor == 3] = df$value[df$sensor==3] - 1.25
#df$value[df$sensor == 1] = df$value[df$sensor==1] - 2.25

df$sensor <- as.factor(df$sensor)
levels(df$sensor) <- c("DSB1820", "Crellin", "DHT22")

#human readable time
df$time <- as.POSIXct(df$time, origin="1970-01-01")

#kill extreme values
df <- df[df$value > 15,]

cairo_pdf(filename='./trl_lr_plot.pdf', height=6, width=12)
p <- ggplot(df, aes(x=time,y=value, group=sensor, colour=sensor))
print(
p + geom_line() + xlab("Time (epoch)") + ylab("Temperature (C)") + ggtitle("TRL MSS Living Room")
)
dev.off()
