1 //
2 // Copyright (C) 2020 The Android Open Source Project
3 //
4 // Licensed under the Apache License, Version 2.0 (the "License");
5 // you may not use this file except in compliance with the License.
6 // You may obtain a copy of the License at
7 //
8 //      http://www.apache.org/licenses/LICENSE-2.0
9 //
10 // Unless required by applicable law or agreed to in writing, software
11 // distributed under the License is distributed on an "AS IS" BASIS,
12 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 // See the License for the specific language governing permissions and
14 // limitations under the License.
15 
16 #include "host/frontend/gcastv2/signaling_server/device_registry.h"
17 
18 #include <android-base/logging.h>
19 
20 #include "host/frontend/gcastv2/signaling_server/device_handler.h"
21 
22 namespace cuttlefish {
23 
RegisterDevice(const std::string & device_id,std::weak_ptr<DeviceHandler> device_handler)24 bool DeviceRegistry::RegisterDevice(
25     const std::string& device_id,
26     std::weak_ptr<DeviceHandler> device_handler) {
27   if (devices_.count(device_id) > 0) {
28     LOG(ERROR) << "Device '" << device_id << "' is already registered";
29     return false;
30   }
31 
32   devices_.try_emplace(device_id, device_handler);
33   LOG(INFO) << "Registered device: '" << device_id << "'";
34   return true;
35 }
36 
UnRegisterDevice(const std::string & device_id)37 void DeviceRegistry::UnRegisterDevice(const std::string& device_id) {
38   auto record = devices_.find(device_id);
39   if (record == devices_.end()) {
40     LOG(WARNING) << "Requested to unregister an unkwnown device: '" << device_id
41                  << "'";
42     return;
43   }
44   devices_.erase(record);
45   LOG(INFO) << "Unregistered device: '" << device_id << "'";
46 }
47 
GetDevice(const std::string & device_id)48 std::shared_ptr<DeviceHandler> DeviceRegistry::GetDevice(
49     const std::string& device_id) {
50   if (devices_.count(device_id) == 0) {
51     LOG(INFO) << "Requested device (" << device_id << ") is not registered";
52     return nullptr;
53   }
54   auto device_handler = devices_[device_id].lock();
55   if (!device_handler) {
56     LOG(WARNING) << "Destroyed device handler detected for device '"
57                  << device_id << "'";
58     UnRegisterDevice(device_id);
59   }
60   return device_handler;
61 }
62 
ListDeviceIds() const63 std::vector<std::string> DeviceRegistry::ListDeviceIds() const {
64   std::vector<std::string> ret;
65   for (const auto& entry: devices_) {
66     ret.push_back(entry.first);
67   }
68   return ret;
69 }
70 
71 }  // namespace cuttlefish
72