From 3565cd1da64d6d0d273476e6bd94a83cd65d4b0e Mon Sep 17 00:00:00 2001
From: Siraaj Khandkar <siraaj@khandkar.net>
Date: Thu, 14 Feb 2019 16:07:59 -0500
Subject: [PATCH] Add bluetooth sensor

---
 x4/bin/khatus_x4_sensor_bluetooth | 23 +++++++++++++++++++++++
 x4/sanity_check                   |  7 +++++--
 2 files changed, 28 insertions(+), 2 deletions(-)
 create mode 100755 x4/bin/khatus_x4_sensor_bluetooth

diff --git a/x4/bin/khatus_x4_sensor_bluetooth b/x4/bin/khatus_x4_sensor_bluetooth
new file mode 100755
index 0000000..96d28a8
--- /dev/null
+++ b/x4/bin/khatus_x4_sensor_bluetooth
@@ -0,0 +1,23 @@
+#! /bin/sh
+
+set -e
+
+. "$(dirname $(realpath $0))/khatus_x4_lib_common_sensor.sh"
+
+count_powered_controllers() {
+    bluetoothctl -- show | grep -c 'Powered: yes'
+}
+
+count_connected_devices() {
+    bluetoothctl -- paired-devices \
+    | awk '{print $2}' \
+    | xargs -I % bluetoothctl -- info % \
+    | grep -c 'Connected: yes'
+}
+
+sensor() {
+    printf "count_powered_controllers %d\n" $(count_powered_controllers)
+    printf "count_connected_devices %d\n" $(count_connected_devices)
+}
+
+run
diff --git a/x4/sanity_check b/x4/sanity_check
index 7ed1ca0..af68cf6 100755
--- a/x4/sanity_check
+++ b/x4/sanity_check
@@ -12,11 +12,12 @@ sensors_kill_all() {
         kill -9 $(cat $pid_file) || true
         rm $pid_file
     done
-    pkill khatus_x4
+    pkill khatus_x4_sensor || true
 }
 
 sensors_fork_all() {
     ./bin/khatus_x4_sensor_datetime &
+    ./bin/khatus_x4_sensor_bluetooth&
     ./bin/khatus_x4_sensor_mpd      &
     ./bin/khatus_x4_sensor_energy   &
 }
@@ -35,9 +36,11 @@ sensors_read_all() {
     do
         battery_state="$(sensor_read_one ${dir}/khatus_x4_sensor_energy/out/battery_state)"
         battery_percentage="$(sensor_read_one ${dir}/khatus_x4_sensor_energy/out/battery_percentage)"
+        bluetooth_controllers="$(sensor_read_one ${dir}/khatus_x4_sensor_bluetooth/out/count_powered_controllers)"
+        bluetooth_devices="$(sensor_read_one ${dir}/khatus_x4_sensor_bluetooth/out/count_connected_devices)"
         datetime="$(sensor_read_one ${dir}/khatus_x4_sensor_datetime/out/datetime)"
         mpd="$(sensor_read_one ${dir}/khatus_x4_sensor_mpd/out/status)"
-        echo "E[${battery_state} ${battery_percentage}] [${mpd}] ${datetime}"
+        echo "E[${battery_state} ${battery_percentage}] [${mpd}] [$bluetooth_controllers $bluetooth_devices] ${datetime}"
         sleep 1
     done
 }
-- 
2.20.1