Refactor msg reading function
[khatus.git] / bin / khatus_loop
1 #! /bin/bash
2
3 MSG_TAG_SEP=': '
4
5 fetch_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
26 fetch_datetime() {
27 date +'%a %b %d %H:%M:%S'
28 }
29
30 read_and_react() {
31 pipe="$1"
32 tail -f "$pipe" \
33 | stdbuf -o L awk \
34 '
35 /^in:WEATHER:/\
36 {
37 db["weather_temperature"] = read_msg()
38 }
39
40 /^in:DATE_TIME:/\
41 {
42 db["datetime"] = read_msg()
43 }
44
45 /^out:BAR:/\
46 {
47 print make_bar()
48 }
49
50 function read_msg() {
51 sub("^" $1 " +", "")
52 return $0
53 }
54
55 function make_bar( position, bar, i) {
56 position[++i] = db["weather_temperature"]
57 position[++i] = db["datetime"]
58 bar = ""
59 sep = ""
60 for (j = 1; j <= i; j++) {
61 bar = bar sep position[j]
62 sep = " "
63 }
64 return bar
65 }
66 '
67 }
68
69 trigger_bar() {
70 echo ''
71 }
72
73 spawn() {
74 cmd="$1"
75 pipe="$2"
76 tag="$3"
77 interval="$4"
78 while true; do
79 echo "${tag}${MSG_TAG_SEP}$($cmd)" > "$pipe"
80 sleep "$interval"
81 done &
82 }
83
84 main() {
85 dir_bin="$1"
86 dir_data="$2"
87 pipe="$dir_data/pipe"
88
89 WEATHER_STATION_ID='KJFK'
90
91 rm -f "$pipe"
92 mkfifo "$pipe"
93
94 spawn fetch_datetime "$pipe" 'in:DATE_TIME' 1
95 spawn fetch_weather "$pipe" 'in:WEATHER' $(( 30 * 60 ))
96 spawn trigger_bar "$pipe" 'out:BAR' 1
97 read_and_react "$pipe"
98 }
99
100 main $@
This page took 0.070099 seconds and 4 git commands to generate.