#!/bin/sh
#
# args: leafID [concID]
#
# Extract occupancy, light and relative humidity for the given node.
#
# Expected input format is one JSON array record per line with elements
# ISO-format timestamp, concentrator ID, raw leaf ASCII7 printable object
# eg:
#
# [ "2014-12-19T15:39:50Z", "", {"@":"0a45","+":5,"L":163,"B|mV":3315,"v|%":0,"tT|C":7} ]
# [ "2014-12-19T15:40:18Z", "", {"@":"819c","T|C16":156,"L":206,"B|cV":256} ]
# [ "2014-12-19T15:41:20Z", "", {"@":"2d1a","+":3,"v|%":0,"tT|C":7,"O":1,"vac|h":6} ]
#
# and output consisting of space-separated columns of:
# ISOtimestamp occ(%) amblight(%) RH%
#
# 2014-12-29T17:43:41Z 9 - -
# 2014-12-29T17:47:41Z - 12.5625 -
# 2014-12-29T17:55:41Z 0 - -
# 2014-12-29T17:55:41Z - - 12
#
# Example use processing an archive:
# xzmore < data/OpenTRV/pubarchive/partial/201412.json.xz | OpenTRV/scripts/valveAndTemps 3015

leafID=$1
concID=$2

# TODO: extract multiple columns in one go for speed to for better pipelining...

# Script to extract one column.
COLEXTSCRIPT=OpenTRV/scripts/filterJSON

# TEMPORARY FILES, CLEANED UP AT EXIT.
# Temporary crudely-filtered copy of input stream...
TMPIN=/tmp/$leafID.$$.1.tmp
# Clean up all temp files on exit
trap "rm -f $TMPIN" EXIT

# Take filtered copy of stdin to save a little processing effort later...
egrep "$1" > $TMPIN

# Project columns one at a time and sort them back together.
# FIXME: horribly inefficient!
(
$COLEXTSCRIPT "O" $leafID $concID <$TMPIN | awk '{print $1,($3-1)*50,"-","-"}'
$COLEXTSCRIPT "L" $leafID $concID <$TMPIN | awk '{print $1,"-",$3/2.55,"-"}'
$COLEXTSCRIPT "H|%" $leafID $concID <$TMPIN | awk '{print $1,"-","-",$3}'
) | sort

exit 0
