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