Fix whitespace
[khatus.git] / bin / khatus_controller
1 #! /usr/bin/awk -f
2
3 /^OK/ { debug("OK line", $0) }
4
5 /^ERROR/ {
6 debug("ERROR line", $0)
7 shift()
8 msg_head = $1
9 shift()
10 msg_body = $0
11 alert_trigger_hi(msg_head, "KhatusSensorError", msg_body)
12 }
13
14 /^OK in:ENERGY battery/\
15 {
16 debug("ENERGY battery", $0)
17 sub("%$", "", $5)
18 db["energy_state_prev"] = db["energy_state_curr"]
19 db["energy_state_curr"] = $4
20 db["energy_percentage"] = ensure_numeric($5)
21 alert_check_energy_battery()
22 }
23
24 /^OK in:ENERGY line_power/\
25 {
26 debug("ENERGY line_power", $0)
27 db["energy_line_power_prev"] = db["energy_line_power_curr"]
28 db["energy_line_power_curr"] = $4
29 alert_check_energy_line_power()
30 }
31
32 /^OK in:MEMORY/\
33 {
34 shift()
35 shift()
36 db["memory_total"] = $1
37 db["memory_used"] = $2
38 }
39
40 /^OK in:FAN +status:/\
41 {
42 shift()
43 shift()
44 db["fan_status"] = $2
45 }
46
47 /^OK in:FAN +speed:/\
48 {
49 shift()
50 shift()
51 db["fan_speed"] = $2
52 }
53
54 /^OK in:FAN +level:/\
55 {
56 shift()
57 shift()
58 db["fan_level"] = $2
59 }
60
61 /^OK in:TEMPERATURE/\
62 {
63 shift()
64 shift()
65 db["temperature"] = $1
66 }
67
68 /^OK in:LOAD_AVG/\
69 {
70 shift()
71 shift()
72 set_load_avg()
73 }
74
75 /^OK in:DISK_IO/\
76 {
77 shift()
78 shift()
79 set_disk_io()
80 }
81
82 /^OK in:DISK_SPACE/\
83 {
84 shift()
85 shift()
86 db["disk_space_used"] = $0
87 }
88
89 /^OK in:NET_ADDR_IO/\
90 {
91 shift()
92 shift()
93 set_net_addr_io()
94 }
95
96 /^OK in:NET_WIFI_STATUS/\
97 {
98 shift()
99 shift()
100 set_net_wifi_status()
101 }
102
103 /^OK in:BLUETOOTH_POWER/\
104 {
105 shift()
106 shift()
107 db["bluetooth_power"] = $0
108 }
109
110 /^OK in:SCREEN_BRIGHTNESS/\
111 {
112 shift()
113 shift()
114 set_screen_brightness()
115 }
116
117 /^OK in:VOLUME/\
118 {
119 shift()
120 set_volume()
121 }
122
123 /^OK in:MPD_SONG OK +MPD/ { delete db_mpd_song; next }
124 /^OK in:MPD_SONG OK$/ { set_mpd_playing() ; next }
125 /^OK in:MPD_SONG / { set_mpd_song() ; next }
126
127 /^OK in:MPD_STATE /\
128 {
129 shift()
130 shift()
131 db["mpd_status_state"] = $1
132 db["mpd_status_time"] = $2
133 db["mpd_status_percent"] = $3
134 }
135
136 /^OK in:WEATHER temperature/\
137 {
138 shift()
139 shift()
140 shift()
141 db["weather_temperature"] = $0
142 }
143
144 /^OK in:WEATHER phenomenon/\
145 {
146 shift()
147 shift()
148 shift()
149 alert_trigger_low("weather_phenomenon", "WeatherPhenomenon", $0)
150 }
151
152 /^OK in:DATE_TIME/\
153 {
154 shift()
155 shift()
156 db["datetime"] = $0
157 output_msg_status_bar(make_status_bar())
158 }
159
160 function set_volume( mute, left, right) {
161 # 0 RUNNING no 75% 75%
162 #msg_head = $1
163 #sink = $2
164 #state = $3
165 mute = $4
166 left = $5
167 right = $6
168
169 if (mute == "no") {
170 db["volume"] = sprintf("%s %s", left, right)
171 } else if (mute == "yes") {
172 db["volume"] = "X"
173 } else {
174 error("set_volume", "Unexpected value for 'mute' field: " mute)
175 }
176 }
177
178 function set_mpd_song( key, val) {
179 shift()
180 key = $2
181 shift()
182 shift()
183 val = $0
184 db_mpd_song[key] = val
185 debug("set_mpd_song", "", db_mpd_song)
186 }
187
188 function set_mpd_playing( \
189 currently_playing, name, title, file, last, parts\
190 ) {
191 debug("set_mpd_playing", "", db_mpd_song)
192 name = db_mpd_song["Name:"]
193 title = db_mpd_song["Title:"]
194 file = db_mpd_song["file:"]
195
196 if (name) {
197 currently_playing = name
198 } else if (title) {
199 currently_playing = title
200 } else if (file) {
201 last = split(file, parts, "/")
202 currently_playing = parts[last]
203 } else {
204 currently_playing = ""
205 }
206 db["mpd_playing_prev"] = db["mpd_playing_curr"]
207 db["mpd_playing_curr"] = currently_playing
208
209 alert_check_mpd()
210 }
211
212 function alert_check_mpd( curr, prev, name, body) {
213 prev = db["mpd_playing_prev"]
214 curr = db["mpd_playing_curr"]
215 if (curr && curr != prev) {
216 name = db_mpd_song["Name:"]
217 if (name) {
218 body = name
219 } else {
220 body = \
221 db_mpd_song["Artist:"] \
222 " - " db_mpd_song["Album:"] \
223 " - " db_mpd_song["Title:"]
224 }
225 alert_trigger_low("alert_check_mpd", "MpdNowPlaying", body)
226 }
227 }
228
229 # TODO: Generalize alert spec lang
230 # - trigger threshold
231 # - above/bellow/equal to threshold value
232 # - priority
233 # - snooze time (if already alerted, when to re-alert?)
234 # - text: subject/body
235 function alert_check_energy_battery( \
236 from, dbg, state_curr, state_prev, remaining, subj, body\
237 ) {
238 from = "alert_check_energy_battery"
239
240 state_curr = db["energy_state_curr"]
241 state_prev = db["energy_state_prev"]
242 remaining = db["energy_percentage"]
243
244 dbg["state_curr"] = state_curr
245 dbg["remaining"] = remaining
246 debug(from, "", dbg)
247
248 if (state_curr == "discharging") {
249 if (remaining < 5) {
250 subj = "Energy_CRITICALLY_Low"
251 body = sprintf("%d%% CHARGE NOW!!! GO GO GO!!!", remaining)
252 alert_trigger_hi(from, subj, body)
253 } else if (remaining < 10) {
254 subj = "Energy_Very_Low"
255 body = sprintf("%d%% Plug it in ASAP.", remaining)
256 alert_trigger_hi(from, subj, body)
257 } else if (remaining < 15) {
258 subj = "Energy_Low"
259 body = sprintf("%d%% Get the charger.", remaining)
260 alert_trigger_hi(from, subj, body)
261 } else if (remaining < 20) {
262 subj = "Energy_Low"
263 body = sprintf("%d%% Get the charger.", remaining)
264 alert_trigger_med(from, subj, body)
265 } else if (remaining < 50) {
266 if (!state__alerts__energy__notified_bellow_half) {
267 state__alerts__energy__notified_bellow_half = 1
268 subj = "Energy_Bellow_Half"
269 body = sprintf("%d%% Where is the charger?", remaining)
270 alert_trigger_med(from, subj, body)
271 }
272 }
273 } else {
274 # TODO: Reconsider the competing global-state organizing-conventions
275 state__alerts__energy__notified_bellow_half = 0
276 }
277 }
278
279 function alert_check_energy_line_power( \
280 from, dbg, line_power_curr, line_power_prev, subj, body \
281 ) {
282 from = "alert_check_energy_line_power"
283
284 dbg["energy_line_power_prev"] = db["energy_line_power_prev"]
285 dbg["energy_line_power_curr"] = db["energy_line_power_curr"]
286 debug(from, "", dbg)
287
288 line_power_curr = db["energy_line_power_curr"]
289 line_power_prev = db["energy_line_power_prev"]
290
291 if (line_power_curr == "no" && line_power_prev != "no") {
292 alert_trigger_low(from, "PowerUnplugged", "")
293 }
294 }
295
296 function alert_trigger_low(from, subject, body) {
297 alert_trigger("low", from, subject, body)
298 }
299
300 function alert_trigger_med(from, subject, body) {
301 alert_trigger("med", from, subject, body)
302 }
303
304 function alert_trigger_hi(from, subject, body) {
305 alert_trigger("hi", from, subject, body)
306 }
307
308 function alert_trigger(priority, from, subject, body, msg) {
309 # priority : "low" | "med" | "hi"
310 # subject : no spaces
311 # body : anything
312 msg = sprintf("khatus_%s %s %s %s", from, priority, subject, body)
313 output_msg_alert(msg)
314 }
315
316 function output_msg_alert(msg) {
317 # TODO: Should alerts go into a dedicated channel?
318 output_msg("ALERT", msg, "/dev/stdout")
319 }
320
321 function output_msg_status_bar(msg) {
322 output_msg("STATUS_BAR", msg, "/dev/stdout")
323 }
324
325 function output_msg(type, content, channel) {
326 print(type, content) > channel
327 }
328
329 function set_load_avg( sched) {
330 split($4, sched, "/")
331 db["load_avg_1min"] = $1
332 db["load_avg_5min"] = $2
333 db["load_avg_15min"] = $3
334 db["kern_sched_queue_runnable"] = sched[1]
335 db["kern_sched_queue_total"] = sched[2]
336 db["kern_sched_latest_pid"] = $5
337 }
338
339 function set_disk_io( curr_w, curr_r, prev_w, prev_r) {
340 curr_w = $1
341 curr_r = $2
342 prev_w = db["disk_io_curr_w"]
343 prev_r = db["disk_io_curr_r"]
344 db["disk_io_curr_w"] = curr_w
345 db["disk_io_curr_r"] = curr_r
346 db["disk_io_diff_w"] = curr_w - prev_w
347 db["disk_io_diff_r"] = curr_r - prev_r
348 }
349
350 function set_net_wifi_status( interface) {
351 interface = $1
352 shift()
353 db["net_wifi_status", interface] = $0
354 }
355
356 function set_net_addr_io( \
357 interface, address, io_curr_w, io_curr_r, io_prev_w, io_prev_r\
358 ) {
359 interface = $1
360 address = $2
361 io_curr_w = $3
362 io_curr_r = $4
363 if (interface) {
364 if (address && io_curr_w && io_curr_r) {
365 # recalculate
366 io_prev_w = net_io_curr_w[interface]
367 io_prev_r = net_io_curr_r[interface]
368
369 net_addr[interface] = address
370 net_io_curr_w[interface] = io_curr_w
371 net_io_curr_r[interface] = io_curr_r
372 net_io_diff_w[interface] = io_curr_w - io_prev_w
373 net_io_diff_r[interface] = io_curr_r - io_prev_r
374 } else {
375 # clear
376 net_addr[interface] = ""
377 net_io_curr_w[interface] = 0
378 net_io_curr_r[interface] = 0
379 net_io_diff_w[interface] = 0
380 net_io_diff_r[interface] = 0
381 }
382 }
383 }
384
385 function set_screen_brightness( max, cur) {
386 max = $1
387 cur = $2
388 db["screen_brightness"] = (cur / max) * 100
389 }
390
391 # TODO: Revise overuse of shift() where it is not really needed
392 function shift() {
393 sub("^" $1 " +", "")
394 }
395
396 function make_status_bar( position, bar, sep, i, j) {
397 position[++i] = make_status_energy()
398 position[++i] = make_status_mem()
399 position[++i] = make_status_cpu()
400 position[++i] = make_status_disk()
401 position[++i] = make_status_net()
402 position[++i] = sprintf("B=%s", db["bluetooth_power"])
403 position[++i] = sprintf("*%d%%", db["screen_brightness"])
404 position[++i] = sprintf("(%s)", db["volume"])
405 position[++i] = make_status_mpd()
406 position[++i] = db["weather_temperature"]
407 position[++i] = db["datetime"]
408 bar = ""
409 sep = ""
410 for (j = 1; j <= i; j++) {
411 bar = bar sep position[j]
412 sep = " "
413 }
414 return bar
415 }
416
417 function make_status_energy( state, direction_of_change) {
418 state = db["energy_state_curr"]
419 if (state == "discharging") {
420 direction_of_change = "<"
421 } else if (state == "charging") {
422 direction_of_change = ">"
423 } else {
424 direction_of_change = "="
425 };
426 return sprintf("E%s%d%%", direction_of_change, db["energy_percentage"])
427 }
428
429 function make_status_mem( total, used, percent, status) {
430 total = db["memory_total"]
431 used = db["memory_used"]
432 # To avoid division by zero when data is missing
433 if (total && used) {
434 percent = round((used / total) * 100)
435 status = sprintf("%d%%", percent)
436 } else {
437 status = "__"
438 }
439 return sprintf("M=%s", status)
440 }
441
442 function make_status_cpu( load, temp, fan) {
443 load = db["load_avg_1min"]
444 temp = db["temperature"] / 1000
445 fan = db["fan_speed"]
446 return sprintf("C=[%4.2f %d°C %4drpm]", load, temp, fan)
447 }
448
449 function make_status_disk( bytes_per_sector, bytes_per_mb, w, r) {
450 bytes_per_sector = 512
451 bytes_per_mb = 1024 * 1024
452 w = (db["disk_io_diff_w"] * bytes_per_sector) / bytes_per_mb
453 r = (db["disk_io_diff_r"] * bytes_per_sector) / bytes_per_mb
454 return \
455 sprintf("D=[%s %0.3f▲ %0.3f▼]", db["disk_space_used"], w, r)
456 }
457
458 function make_status_net( \
459 out,
460 number_of_interfaces_to_show,
461 n,
462 array_of_prefixes_of_interfaces_to_show,
463 prefix,
464 interface,
465 label,
466 count_printed,
467 sep,
468 io_stat,
469 dw, dr,
470 bytes_per_unit\
471 ) {
472 out = ""
473 number_of_interfaces_to_show = \
474 split(\
475 opt_prefixes_of_net_interfaces_to_show,\
476 array_of_prefixes_of_interfaces_to_show,\
477 ","\
478 )
479 for (n = 1; n <= number_of_interfaces_to_show; n++) {
480 prefix = array_of_prefixes_of_interfaces_to_show[n]
481 for (interface in net_addr) {
482 if (interface ~ ("^" prefix)) {
483 label = substr(interface, 1, 1)
484 if (net_addr[interface]) {
485 bytes_per_mb = 1024 * 1024 # TODO: option
486 dw = net_io_diff_w[interface] / bytes_per_mb
487 dr = net_io_diff_r[interface] / bytes_per_mb
488 io_stat = sprintf("%0.3f▲ %0.3f▼", dw, dr)
489 } else {
490 io_stat = "--"
491 }
492 if (interface ~ "^w") {
493 label = label ":" db["net_wifi_status", interface]
494 }
495 if (++count_printed > 1) {
496 sep = " "
497 } else {
498 sep = ""
499 }
500 out = out sep label ":" io_stat
501 }
502 }
503 }
504 return sprintf("N[%s]", out)
505 }
506
507 function make_status_mpd( state, status) {
508 state = db["mpd_status_state"]
509
510 if (state == "play") {
511 status = make_status_mpd_state_known("▶")
512 } else if (state == "pause") {
513 status = make_status_mpd_state_known("❚❚")
514 } else if (state == "stop") {
515 status = make_status_mpd_state_known("⬛")
516 } else {
517 status = make_status_mpd_state_unknown("--")
518 }
519
520 return sprintf("[%s]", status)
521 }
522
523 function make_status_mpd_state_known(symbol) {
524 return sprintf(\
525 "%s %s %s %s",
526 symbol,
527 db["mpd_status_time"],
528 db["mpd_status_percent"],
529 substr(db["mpd_playing_curr"], 1, opt_mpd_song_max_chars)\
530 )
531 }
532
533 function make_status_mpd_state_unknown(symbol) {
534 return sprintf("%s", symbol)
535 }
536
537 function round(n) {
538 return int(n + 0.5)
539 }
540
541 function debug(location, msg, values, sep, vals, key, payload) {
542 if (opt_debug) {
543 sep = ""
544 vals = ""
545 for (key in values) {
546 vals = sprintf("%s%s%s: %s", vals, sep, key, values[key])
547 sep = ", "
548 }
549 payload = \
550 sprintf("LOCATION[%s] MSG[%s] DATA[%s]", location, msg, vals)
551 output_msg("DEBUG", payload, "/dev/stderr")
552 }
553 }
554
555 function error(location, msg) {
556 # TODO: Reconsider classifying internal errors as alerts
557 # Maybe better to keep the error class distinct and provide a
558 # an optional transformation from error to alert
559 alert_trigger_hi(location, "KhatusControllerError", msg)
560 }
561
562 function ensure_numeric(n) {
563 return n + 0
564 }
565 #-------------------------------
566 # Why do we need ensure_numeric?
567 #-------------------------------
568 # awk appears to be guessing the type of an inputted scalar based on usage, so
569 # if we read-in a number, but did not use it in any numeric operations, but did
570 # use as a string (even in just a format string!) - it will be treated as a
571 # string and can lead to REALLY SURPRISING behavior in conditional statements,
572 # where smaller number may compare as greater than the bigger ones, such as.
573 #
574 # Demo:
575 #
576 # $ awk 'BEGIN {x = "75"; y = "100"; sprintf("x: %d, y: %d\n", x, y); if (x > y) {print "75 > 100"} else if (x < y) {print "75 < 100"}}'
577 # 75 < 100
578 # $ awk 'BEGIN {x = "75"; y = "100"; sprintf("x: %s, y: %d\n", x, y); if (x > y) {print "75 > 100"} else if (x < y) {print "75 < 100"}}'
579 # 75 > 100
580
581 # However, once used as a number, seems to stay that way even after being
582 # used as string:
583 #
584 # $ awk 'BEGIN {x = "75"; y = "100"; x + y; sprintf("x: %s, y: %d\n", x, y); if (x > y) {print "75 > 100"} else if (x < y) {print "75 < 100"}}'
585 # 75 < 100
586 #
587 # $ awk 'BEGIN {x = "75"; y = "100"; x + y; sprintf("x: %s, y: %d\n", x, y); z = x y; if (x > y) {print "75 > 100"} else if (x < y) {print "75 < 100"}}'
588 # 75 < 100
589 #
590 # $ awk 'BEGIN {x = "75"; y = "100"; x + y; z = x y; if (x > y) {print "75 > 100"} else if (x < y) {print "75 < 100"}}'
591 # 75 < 100
592 # $ awk 'BEGIN {x = "75"; y = "100"; z = x y; if (x > y) {print "75 > 100"} else if (x < y) {print "75 < 100"}}'
593 # 75 > 100
This page took 0.114761 seconds and 4 git commands to generate.