[Bluetooth] Add bluetooth power off listener for GATTServer
[platform/core/api/webapi-plugins.git] / src / bluetooth / bluetooth_gatt_server.cc
index d1a4bd6..fe33139 100644 (file)
@@ -34,18 +34,27 @@ BluetoothGATTServer::BluetoothGATTServer(BluetoothInstance& instance,
       service_{service},
       initialized_{false},
       running_{false},
-      handle_{nullptr} {
+      handle_{nullptr},
+      power_state_change_callback_id_{-1} {
   ScopeLogger();
-  /*
-   * TODO: register a callback, that deinitializes a server, unregisters its
-   * services, destroys handle_ and sets running_ to false
-   * when Bluetooth is turned off.
-   */
+
+  power_state_change_callback_id_ =
+      instance_.GetBluetoothAdapter().AddPowerStateListener([this](const int state) {
+        ScopeLogger("BluetoothGATTServer PowerStateListenerCallback: %d", state);
+        if ((false == state) && (true == running_)) {
+          UnregisterAllServicesImpl();
+          DestroyAllGATTObjects();
+          Deinitialize();
+          PowerStateChangeCb(false);
+          SetRunningState(false);
+        }
+      });
 }
 
 BluetoothGATTServer::~BluetoothGATTServer() {
   ScopeLogger();
 
+  instance_.GetBluetoothAdapter().RemovePowerStateListener(power_state_change_callback_id_);
   UnregisterAllServicesImpl();
   DestroyAllGATTObjects();
   Deinitialize();
@@ -403,6 +412,18 @@ bool BluetoothGATTServer::DestroyDescriptor(int total, int index, bt_gatt_h hand
   return true;
 }
 
+void BluetoothGATTServer::PowerStateChangeCb(bool state) {
+  ScopeLogger();
+  picojson::value result{picojson::object{}};
+  auto& obj = result.get<picojson::object>();
+
+  obj.insert(
+      std::make_pair("listenerId", "BluetoothGattServerBluetoothAdapterStateChangeListener"));
+  obj.insert(std::make_pair("state", picojson::value(state)));
+
+  Instance::PostMessage(&instance_, result.serialize().c_str());
+}
+
 void BluetoothGATTServer::SetRunningState(bool state) {
   ScopeLogger();
   if (state != running_) {