bubble level: protect against sensor init failure

In case of sensor manager initialization failure,
the bubble level factory returns null, the poll thread loop is not started
and API methods return errors.
also check for sensor manager service availability before attempting to
create a sensor manager instance.

The audio HAL does not attempt to create the bubble level at creation time to
avoid possible conflicts with system server starting but only when needed.

Bug 7398856.

Change-Id: If6b69d7343c0bbbb574a6484fbd3d50117d4d89d
diff --git a/audio/audio_hw.c b/audio/audio_hw.c
index 4f75f7d..daaaf26 100644
--- a/audio/audio_hw.c
+++ b/audio/audio_hw.c
@@ -583,6 +583,17 @@
     pthread_mutex_unlock(&adev->lock);
 }
 
+/* must be called with hw device mutex locked */
+bool get_bubblelevel(struct audio_device *adev)
+{
+    if (!adev->bubble_level) {
+        adev->bubble_level = bubble_level_create();
+        if (adev->bubble_level)
+            adev->bubble_level->set_callback(adev->bubble_level, bubblelevel_callback, adev);
+    }
+    return (adev->bubble_level != NULL);
+}
+
 static void force_non_hdmi_out_standby(struct audio_device *adev)
 {
     enum output_type type;
@@ -650,7 +661,8 @@
         set_hdmi_channels(adev, out->config.channels);
 
     /* anticipate level measurement in case we start capture later */
-    adev->bubble_level->poll_once(adev->bubble_level);
+    if (get_bubblelevel(adev))
+        adev->bubble_level->poll_once(adev->bubble_level);
 
     return 0;
 }
@@ -684,8 +696,10 @@
     in->ramp_step = (uint16_t)(USHRT_MAX / in->ramp_frames);
     in->ramp_vol = 0;;
 
-    adev->bubble_level->set_poll_interval(adev->bubble_level, BL_POLL_INTERVAL_MIN_SEC);
-    adev->bubble_level->start_polling(adev->bubble_level);
+    if (get_bubblelevel(adev)) {
+        adev->bubble_level->set_poll_interval(adev->bubble_level, BL_POLL_INTERVAL_MIN_SEC);
+        adev->bubble_level->start_polling(adev->bubble_level);
+    }
 
     return 0;
 }
@@ -1204,7 +1218,8 @@
         select_devices(in->dev);
         in->standby = true;
 
-        in->dev->bubble_level->stop_polling(in->dev->bubble_level);
+        if (get_bubblelevel(in->dev))
+            in->dev->bubble_level->stop_polling(in->dev->bubble_level);
     }
 
     eS305_SetActiveIoHandle(ES305_IO_HANDLE_NONE);
@@ -1686,7 +1701,8 @@
     if (adev->hdmi_drv_fd >= 0)
         close(adev->hdmi_drv_fd);
 
-    bubble_level_release(adev->bubble_level);
+    if (adev->bubble_level)
+        bubble_level_release(adev->bubble_level);
 
     free(device);
     return 0;
@@ -1736,9 +1752,6 @@
     adev->hdmi_drv_fd = -1;
     *device = &adev->hw_device.common;
 
-    adev->bubble_level = bubble_level_create();
-    adev->bubble_level->set_callback(adev->bubble_level, bubblelevel_callback, adev);
-
     return 0;
 }