Multiplex stateless writers to one stateful reader
[khatus.git] / bin / khatus_loop
CommitLineData
438d0d5f
SK
1#! /bin/bash
2
3MSG_TAG_SEP=': '
4
5fetch_weather() {
6 metar -d "$WEATHER_STATION_ID" 2>&1 \
7 | awk '
8 /METAR pattern not found in NOAA data/ {
9 failures++
10 }
11
12 /^Temperature/ {
13 celsius = $3;
14 fahrenheit = (celsius * (9 / 5)) + 32;
15 temperature = fahrenheit
16 }
17
18 END {
19 if (failures > 0) {
20 temperature = "--"
21 }
22 print temperature "°F"
23 }'
24}
25
26fetch_datetime() {
27 date +'%a %b %d %H:%M:%S'
28}
29
30read_and_react() {
31 pipe="$1"
32 tail -f "$pipe" \
33 | stdbuf -o L awk \
34 '
35 /^in:WEATHER:/\
36 {
37 chop_off_msg_tag()
38 db["weather_temperature"] = $0
39 }
40
41 /^in:DATE_TIME:/\
42 {
43 chop_off_msg_tag()
44 db["datetime"] = $0
45 }
46
47 /^out:BAR:/\
48 {
49 chop_off_msg_tag()
50 print make_bar()
51 }
52
53 function chop_off_msg_tag() {
54 sub("^" $1 " +", "")
55 }
56
57 function make_bar( position, bar, i) {
58 position[++i] = db["weather_temperature"]
59 position[++i] = db["datetime"]
60 bar = ""
61 sep = ""
62 for (j = 1; j <= i; j++) {
63 bar = bar sep position[j]
64 sep = " "
65 }
66 return bar
67 }
68 '
69}
70
71trigger_bar() {
72 echo ''
73}
74
75spawn() {
76 cmd="$1"
77 pipe="$2"
78 tag="$3"
79 interval="$4"
80 while true; do
81 echo "${tag}${MSG_TAG_SEP}$($cmd)" > "$pipe"
82 sleep "$interval"
83 done &
84}
85
86main() {
87 dir_bin="$1"
88 dir_data="$2"
89 pipe="$dir_data/pipe"
90
91 WEATHER_STATION_ID='KJFK'
92
93 rm -f "$pipe"
94 mkfifo "$pipe"
95
96 spawn fetch_datetime "$pipe" 'in:DATE_TIME' 1
97 spawn fetch_weather "$pipe" 'in:WEATHER' $(( 30 * 60 ))
98 spawn trigger_bar "$pipe" 'out:BAR' 1
99 read_and_react "$pipe"
100}
101
102main $@
This page took 0.026267 seconds and 4 git commands to generate.