Skip to content

Instantly share code, notes, and snippets.

@dirkjanfaber
Last active August 29, 2015 14:23
Show Gist options
  • Save dirkjanfaber/b8b88fae32f6b8884c2d to your computer and use it in GitHub Desktop.
Save dirkjanfaber/b8b88fae32f6b8884c2d to your computer and use it in GitHub Desktop.
Light up my hue if there is a traffic jam
#!/bin/bash
# Some environment variables ought to be set
: ${BINGMAP_API_KEY?"You need to set the BINGMAP_API_KEY"}
: ${HUE_BRIDGE?"You need to set the HUE_BRIDGE"}
: ${HUE_KEY?"You need to set the HUE_KEY"}
# preperation for storing the temp file
temp_dir=/tmp/$RANDOM-$$
install -d -m 700 "$temp_dir" || { echo "failed to create temp_dir" >&2; exit 1; }
temp_file=${temp_dir}/traffic4hue.txt
# Fetch traffic information
curl \
--silent \
--request GET \
--output ${temp_file} \
--header "Content-Type: application/json; charset=UTF-8" \
"http://dev.virtualearth.net/REST/v1/Traffic/Incidents/52.96,5.92,53.21,6.57?key=${BINGMAP_API_KEY}&severity=3,4"
# Could fix this by giving the light bulb another colour
[ ! -f ${temp_file} ] && exit 1
# Parse the fetched information and determine the light bulb colour
let JAMS=$(perl -MJSON -MData::Dumper -e '
my $hue=0;
while (<>) {
map {
$hue++ if $_->{'description'} =~ /(A7|Julianaplein)/i;
} @{${from_json($_)->{'resourceSets'}}[0]->{'resources'}};
}
print $hue;
' ${temp_file})
# Echo could be removed if output is not needed, while testing it is handy cron output
echo "Nr of traffic jams: ${JAMS}"
if [[ ${JAMS} -eq 0 ]]
then
exit 0
fi
# We don't expect over 10 jams
if [[ ${JAMS} -gt 10 ]]
then
JAMS=10
fi
let BRI=${JAMS}*25
let SAT=${JAMS}*25
let HUE=0 # red (http://www.developers.meethue.com/documentation/core-concepts)
# Build the JSON data
DATA=$(cat <<__EOT__
{ "on": true, "sat":${SAT}, "bri": ${BRI}, "hue": ${HUE} }
__EOT__
)
if [[ ${HUE} -gt 0 ]]
then
# Traffic JAM, light up the hallway
curl \
--silent \
--request PUT \
--data "${DATA}" \
--header "Content-Type: application/json; charset=UTF-8" \
http://${HUE_BRIDGE}/api/${HUE_KEY}/lights/1/state
fi
# remove the temdir
[ -d ${temp_dir} ] && rm -f ${tempdir}
@dirkjanfaber
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment