1#!/bin/sh -e
2#
3#    wifi_quality: display wifi signal quality
4#
5#    Copyright (C) 2008 Canonical Ltd.
6#    Copyright (C) 2011-2014 Dustin Kirkland
7#
8#    Authors: Dustin Kirkland <kirkland@byobu.org>
9#
10#    This program is free software: you can redistribute it and/or modify
11#    it under the terms of the GNU General Public License as published by
12#    the Free Software Foundation, version 3 of the License.
13#
14#    This program is distributed in the hope that it will be useful,
15#    but WITHOUT ANY WARRANTY; without even the implied warranty of
16#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17#    GNU General Public License for more details.
18#
19#    You should have received a copy of the GNU General Public License
20#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
21
22___get_dev_list() {
23	if [ -n "$MONITORED_NETWORK" ]; then
24		echo "$MONITORED_NETWORK"
25	else
26		iw dev | grep Interface | cut -f2 -d\
27	fi
28}
29
30__wifi_quality_detail() {
31	if eval $BYOBU_TEST iw >/dev/null 2>&1; then
32		local dev
33		for dev in $(___get_dev_list); do
34			iw dev "$dev" info
35			iw dev "$dev" link
36			echo
37		done
38	elif eval $BYOBU_TEST iwconfig >/dev/null 2>&1; then
39		iwconfig 2>/dev/null
40	fi
41}
42
43__wifi_quality() {
44	local out bitrate quality
45	if eval $BYOBU_TEST iwconfig >/dev/null 2>&1; then
46		# iwconfig is expected to output lines like:
47		#    Bit Rate=54 Mb/s   Tx-Power=15 dBm
48		#    Link Quality=60/70  Signal level=-50 dBm
49		# the awk below tokenizes the output and prints shell evalable results
50		out=`iwconfig $MONITORED_NETWORK 2>/dev/null |
51			awk '$0 ~ /[ ]*Link Quality./ {
52			    sub(/.*=/,"",$2); split($2,a,"/");
53			    printf "quality=%.0f\n", 100*a[1]/a[2] };
54			    $0 ~ /[ ]*Bit Rate/ { sub(/.*[:=]/,"",$2); printf("bitrate=%s\n", $2); }
55			    '`
56		eval "$out"
57	elif eval $BYOBU_TEST iw >/dev/null 2>&1; then
58		local dev
59		for dev in $(___get_dev_list); do
60			# iw is expected to output lines like:
61			#     signal: -50 dBm
62			#     rx bitrate: 216.0 MBit/s MCS 13 40MHz
63			# signal to quality: https://superuser.com/a/1360447
64			out=`iw dev "$dev" link 2>/dev/null |
65				awk '$0 ~ /^\s*signal:/ { a = 100 * ($2 + 110) / 70;
66				    printf "quality=%.0f\n", (a > 100) ? 100 : ((a < 0) ? 0 : a); }
67				    $0 ~ /^\s*rx bitrate:/ { printf "bitrate=%s\n", $3; }
68				    '`
69			eval "$out"
70			[ -z "$bitrate" ] || [ -z "$quality" ] || break
71		done
72	fi
73	[ -n "$bitrate" ] || bitrate=0
74	[ -n "$quality" ] || quality=0
75	if [ "$bitrate" -gt 0 ] && [ "$quality" -gt 0 ]; then
76		printf "${ICON_WIFI}"; color b C k; printf "%s" "$bitrate"; color -; color C k; printf "%s" "$ICON_MBPS"; color -; color b C k; printf "%s" "$quality"; color -; color C k; printf "%s" "$PCT"; color --
77	else
78		rm -f "$BYOBU_RUN_DIR/status.$BYOBU_BACKEND/wifi_quality"*
79	fi
80}
81
82# vi: syntax=sh ts=4 noexpandtab
83