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 <variant> 23 24 using phosphor::logging::level; 25 using phosphor::logging::log; 26 27 HostManager::HostManager() : 28 postcodes_(), bus_(sdbusplus::bus::new_default()), 29 signal_(bus_, HostManager::GetMatch().c_str(), 30 [this](auto& m) -> void { this->DbusHandleSignal(m); }), 31 post_poller_enabled_(true) 32 { 33 // Spin off thread to listen on bus_ 34 auto post_poller_thread = std::mem_fn(&HostManager::PostPollerThread); 35 post_poller_ = std::make_unique<std::thread>(post_poller_thread, this); 36 } 37 38 int HostManager::DbusHandleSignal(sdbusplus::message_t& msg) 39 { 40 log<level::INFO>("Property Changed!"); 41 std::string msgSensor, busName{POSTCODE_BUSNAME}; 42 std::map<std::string, 43 std::variant<std::tuple<uint64_t, std::vector<uint8_t>>>> 44 msgData; 45 msg.read(msgSensor, msgData); 46 47 if (msgSensor == busName) 48 { 49 auto valPropMap = msgData.find("Value"); 50 if (valPropMap != msgData.end()) 51 { 52 uint64_t rawValue = 53 std::get<uint64_t>(std::get<0>(valPropMap->second)); 54 55 PushPostcode(rawValue); 56 } 57 } 58 59 return 0; 60 } 61 62 void HostManager::PushPostcode(uint64_t postcode) 63 { 64 // Get lock 65 std::lock_guard<std::mutex> lock(postcodes_lock_); 66 // Add postcode to queue 67 postcodes_.push_back(postcode); 68 } 69 70 std::vector<uint64_t> HostManager::DrainPostcodes() 71 { 72 // Get lock 73 std::lock_guard<std::mutex> lock(postcodes_lock_); 74 75 auto count = postcodes_.size(); 76 if (count > 0) 77 { 78 std::string msg = std::format("Draining Postcodes. Count: {}.", count); 79 log<level::ERR>(msg.c_str()); 80 } 81 82 // Drain the queue into a list 83 // TODO: maximum # postcodes? 84 std::vector<uint64_t> result(postcodes_); 85 postcodes_.clear(); 86 87 return result; 88 } 89 90 std::string HostManager::GetMatch() 91 { 92 std::string obj{POSTCODE_OBJECTPATH}; 93 return std::string("type='signal'," 94 "interface='org.freedesktop.DBus.Properties'," 95 "member='PropertiesChanged'," 96 "path='" + 97 obj + "'"); 98 } 99 100 void HostManager::PostPollerThread() 101 { 102 while (post_poller_enabled_) 103 { 104 bus_.process_discard(); 105 bus_.wait(); 106 } 107 } 108