1 // Copyright 2021 Google LLC 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 #include "host_manager.hpp" 16 17 #include <phosphor-logging/log.hpp> 18 #include <sdbusplus/bus.hpp> 19 #include <sdbusplus/message.hpp> 20 21 #include <format> 22 #include <functional> 23 #include <variant> 24 25 using phosphor::logging::level; 26 using phosphor::logging::log; 27 28 HostManager::HostManager() : 29 postcodes_(), bus_(sdbusplus::bus::new_default()), 30 signal_(bus_, HostManager::GetMatch().c_str(), 31 [this](auto& m) -> void { this->DbusHandleSignal(m); }), 32 post_poller_enabled_(true) 33 { 34 // Spin off thread to listen on bus_ 35 auto post_poller_thread = std::mem_fn(&HostManager::PostPollerThread); 36 post_poller_ = std::make_unique<std::thread>(post_poller_thread, this); 37 } 38 39 int HostManager::DbusHandleSignal(sdbusplus::message_t& msg) 40 { 41 log<level::INFO>("Property Changed!"); 42 std::string msgSensor, busName{POSTCODE_BUSNAME}; 43 std::map<std::string, 44 std::variant<std::tuple<uint64_t, std::vector<uint8_t>>>> 45 msgData; 46 msg.read(msgSensor, msgData); 47 48 if (msgSensor == busName) 49 { 50 auto valPropMap = msgData.find("Value"); 51 if (valPropMap != msgData.end()) 52 { 53 uint64_t rawValue = 54 std::get<uint64_t>(std::get<0>(valPropMap->second)); 55 56 PushPostcode(rawValue); 57 } 58 } 59 60 return 0; 61 } 62 63 void HostManager::PushPostcode(uint64_t postcode) 64 { 65 // Get lock 66 std::lock_guard<std::mutex> lock(postcodes_lock_); 67 // Add postcode to queue 68 postcodes_.push_back(postcode); 69 } 70 71 std::vector<uint64_t> HostManager::DrainPostcodes() 72 { 73 // Get lock 74 std::lock_guard<std::mutex> lock(postcodes_lock_); 75 76 auto count = postcodes_.size(); 77 if (count > 0) 78 { 79 std::string msg = std::format("Draining Postcodes. Count: {}.", count); 80 log<level::ERR>(msg.c_str()); 81 } 82 83 // Drain the queue into a list 84 // TODO: maximum # postcodes? 85 std::vector<uint64_t> result(postcodes_); 86 postcodes_.clear(); 87 88 return result; 89 } 90 91 std::string HostManager::GetMatch() 92 { 93 std::string obj{POSTCODE_OBJECTPATH}; 94 return std::string("type='signal'," 95 "interface='org.freedesktop.DBus.Properties'," 96 "member='PropertiesChanged'," 97 "path='" + 98 obj + "'"); 99 } 100 101 void HostManager::PostPollerThread() 102 { 103 while (post_poller_enabled_) 104 { 105 bus_.process_discard(); 106 bus_.wait(); 107 } 108 } 109