* Copyright (c) 2025 Huawei Technologies Co., Ltd.
* openUBMC is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
* http://license.coscl.org.cn/MulanPSL2
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
*/
#include "fans_rs485_object.h"
#include <chrono>
#include <cstdlib>
#include <ctime>
#include <fcntl.h>
#include <grp.h>
#include <iomanip>
#include <mc/app/service.h>
#include <mc/app/task/task_mgmt.h>
#include <mc/filesystem.h>
#include <mc/log.h>
#include <mc/time.h>
#include <pwd.h>
#include <sstream>
#include <string>
#include <sys/stat.h>
#include <termios.h>
#include <unistd.h>
#include <unistd.h>
#include "fan_rs485_object.h"
#include "internal/bus/bus_uart/uart.h"
#include "internal/manager.h"
namespace dev {
static constexpr uint32_t FAN_RESET_RECOVER_MS = 5000;
std::mutex FansRS485::s_uart_comm_mutex;
FansRS485::FansRS485() = default;
FansRS485::~FansRS485()
{
stop();
}
bool FansRS485::start()
{
elog("FansRS485: start() BEGIN");
std::vector<mc::object_ptr> fan_objects;
auto children = get_children();
elog("FansRS485: start() - searching children, total_children_count=${count}", ("count", children.size()));
for (auto& child : children) {
if (!child) {
continue;
}
std::string object_name = std::string(child->get_name());
size_t pos = object_name.find_first_of("_");
std::string prefix = (pos != std::string::npos) ? object_name.substr(0, pos) : object_name;
if (prefix == "Fan") {
fan_objects.push_back(child);
elog("FansRS485: start() - found FanRS485 child: ${name}", ("name", object_name));
}
}
elog("FansRS485: start() Step1: found ${count} FanRS485 children", ("count", fan_objects.size()));
m_fan_objects.clear();
for (auto& fan_object : fan_objects) {
if (fan_object == nullptr) {
continue;
}
m_fan_objects.push_back(fan_object);
}
elog("FansRS485: start() Step2: stored ${count} fan objects in m_fan_objects", ("count", m_fan_objects.size()));
elog("FansRS485: start() Step4: obtaining uart_bus from device_manager, bus_name='${name}'",
("name", m_uart_bus_name));
if (m_uart_bus_name.empty()) {
elog("FansRS485: start() FAILED at Step4: uart_bus_name not set in init()");
return false;
}
if (m_fan_objects.empty()) {
elog("FansRS485: start() FAILED at Step4: no fan objects available");
return false;
}
auto first_fan = dynamic_cast<FanRS485*>(m_fan_objects[0].get());
if (!first_fan) {
elog("FansRS485: start() FAILED at Step4: first fan object is null");
return false;
}
elog("FansRS485: start() Step4: first_fan found, name=${name}, uart_bus_ptr=${ptr}, protocol_ptr=${proto}",
("name", first_fan->get_object_name())("ptr", static_cast<void*>(first_fan->get_uart_bus()))(
"proto", static_cast<void*>(first_fan->get_protocol())));
auto& manager = dev::device_manager::get_instance();
auto bus_variant = manager.find_object(m_uart_bus_name, dev::object_type::bus);
if (!std::holds_alternative<std::shared_ptr<bus_base>>(bus_variant)) {
elog("FansRS485: start() FAILED at Step4: uart_bus '${name}' not found in device_manager",
("name", m_uart_bus_name));
return false;
}
auto bus_ptr = std::get<std::shared_ptr<bus_base>>(bus_variant);
if (!bus_ptr) {
elog("FansRS485: start() FAILED at Step4: uart_bus '${name}' found but ptr is null", ("name", m_uart_bus_name));
return false;
}
m_uart_bus = std::dynamic_pointer_cast<bus_uart>(bus_ptr);
if (!m_uart_bus) {
elog("FansRS485: start() FAILED at Step4: bus '${name}' is not bus_uart type, actual type='${type}'",
("name", m_uart_bus_name)("type", bus_ptr->get_class_name()));
return false;
}
elog("FansRS485: start() Step4: uart_bus obtained successfully, ptr=${ptr}, bus_name='${name}'",
("ptr", static_cast<void*>(m_uart_bus.get()))("name", m_uart_bus_name));
elog("FansRS485: start() Step5: creating FanRS485CommService");
m_comm_service = std::make_shared<FanRS485CommService>();
elog("FansRS485: start() Step5: FanRS485CommService created, ptr=${ptr}",
("ptr", static_cast<void*>(m_comm_service.get())));
elog(
"FansRS485: start() Step6: calling m_comm_service->init(uart_bus=${bus}) (protocol will be passed per-command)",
("bus", static_cast<void*>(m_uart_bus.get())));
if (!m_comm_service->init(m_uart_bus.get())) {
elog("FansRS485: start() FAILED at Step6: m_comm_service->init() returned false");
return false;
}
elog("FansRS485: start() Step6: m_comm_service->init() OK");
elog("FansRS485: start() Step7: calling m_comm_service->start()");
if (!m_comm_service->start()) {
elog("FansRS485: start() FAILED at Step7: m_comm_service->start() returned false");
return false;
}
elog("FansRS485: start() Step7: CommService started SUCCESSFULLY");
elog("FansRS485: start() Step8: starting and activating ${count} fan objects", ("count", m_fan_objects.size()));
int activated_count = 0;
int failed_count = 0;
for (auto& fan_object_ptr : m_fan_objects) {
if (fan_object_ptr == nullptr) {
continue;
}
auto* fan_object = dynamic_cast<FanRS485*>(fan_object_ptr.get());
if (fan_object == nullptr) {
continue;
}
if (!fan_object->start()) {
elog("FansRS485: start() Step8 PhaseA: fan ${name} start() FAILED",
("name", fan_object->get_object_name()));
failed_count++;
continue;
}
elog("FansRS485: start() Step8 PhaseA: fan ${name} start() SUCCESS", ("name", fan_object->get_object_name()));
fan_object->set_comm_service(m_comm_service);
ilog("FansRS485: start() Step8 PhaseA: set_comm_service done for ${name}",
("name", fan_object->get_object_name()));
}
{
const int reset_retry_max = 3;
for (auto& fan_object_ptr : m_fan_objects) {
if (fan_object_ptr == nullptr) {
continue;
}
auto* fan_object = dynamic_cast<FanRS485*>(fan_object_ptr.get());
if (fan_object == nullptr) {
continue;
}
if (!fan_object->is_basic_initialized()) {
continue;
}
auto* fan_protocol = fan_object->get_protocol();
uint8_t fan_addr = fan_object->get_slave_addr();
bool reset_ok = false;
for (int reset_try = 1; reset_try <= reset_retry_max; ++reset_try) {
ilog("FansRS485: start() Step8.5: resetting fan ${name} (addr=${addr}) attempt ${try}/${max}",
("name", fan_object->get_object_name())("addr", static_cast<int>(fan_addr))("try", reset_try)(
"max", reset_retry_max));
reset_ok = m_comm_service->reset_fan(fan_addr, fan_protocol);
if (reset_ok) {
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(200));
}
if (reset_ok) {
ilog("FansRS485: start() Step8.5: fan ${name} (addr=${addr}) RESET SUCCESS, queue cleared",
("name", fan_object->get_object_name())("addr", static_cast<int>(fan_addr)));
} else {
elog("FansRS485: start() Step8.5: fan ${name} (addr=${addr}) RESET FAILED after ${max} attempts, "
"continuing",
("name", fan_object->get_object_name())("addr", static_cast<int>(fan_addr))("max",
reset_retry_max));
}
}
ilog("FansRS485: start() Step8.5: all fans reset issued, waiting ${ms}ms for fans to recover communication",
("ms", FAN_RESET_RECOVER_MS));
std::this_thread::sleep_for(std::chrono::milliseconds(FAN_RESET_RECOVER_MS));
}
for (auto& fan_object_ptr : m_fan_objects) {
if (fan_object_ptr == nullptr) {
continue;
}
auto* fan_object = dynamic_cast<FanRS485*>(fan_object_ptr.get());
if (fan_object == nullptr) {
continue;
}
if (!fan_object->is_basic_initialized()) {
continue;
}
if (fan_object->activate()) {
elog("FansRS485: start() Step8 PhaseC: fan ${name} ACTIVATED SUCCESS",
("name", fan_object->get_object_name()));
activated_count++;
std::this_thread::sleep_for(std::chrono::milliseconds(200));
ilog("FansRS485: start() Step8 PhaseC: delay 200ms after ${name} to avoid RS485 bus conflict",
("name", fan_object->get_object_name()));
} else {
elog("FansRS485: start() Step8 PhaseC: fan ${name} ACTIVATED FAILED",
("name", fan_object->get_object_name()));
failed_count++;
}
}
elog("FansRS485: start() Step8: activation completed, success=${success}, failed=${fail}",
("success", activated_count)("fail", failed_count));
m_fans.init();
m_fans_oem.init();
elog("FansRS485: start() Step9: Fans interfaces initialized");
m_thread_pool = std::make_shared<mc::runtime::thread_pool>(1);
m_thread_pool->start();
elog("FansRS485: start() Step10: thread_pool started");
m_fans.set_pwm_callback([this](const std::vector<double>& pwm_list) {
return this->SetPWM(pwm_list);
});
m_fans.set_dump_fan_logs_callback([this](const std::vector<uint32_t>& fan_id_list, const std::string& tar_path,
const std::string& caller_username) {
return this->DumpFanLogs(fan_id_list, tar_path, caller_username);
});
m_fans.start();
m_fans_oem.start();
elog("FansRS485: start() Step11: Fans interfaces started");
elog("FansRS485: start() COMPLETED, total_fans=${count}, activated=${act}, failed=${fail}",
("count", m_fan_objects.size())("act", activated_count)("fail", failed_count));
return true;
}
FanRS485* FansRS485::get_first_fan_with_uart_bus()
{
for (auto& fan_obj_ptr : m_fan_objects) {
auto fan = dynamic_cast<FanRS485*>(fan_obj_ptr.get());
if (fan && fan->get_uart_bus()) {
return fan;
}
}
return nullptr;
}
bool FansRS485::stop()
{
if (m_stopped) {
return true;
}
m_stopped = true;
if (m_comm_service) {
m_comm_service->stop();
}
if (m_thread_pool) {
m_thread_pool.reset();
}
m_fans.stop();
m_fans_oem.stop();
for (auto& fan_object_ptr : m_fan_objects) {
if (fan_object_ptr == nullptr) {
continue;
}
auto fan_object = dynamic_cast<FanRS485*>(fan_object_ptr.get());
if (fan_object == nullptr) {
continue;
}
fan_object->deactivate();
if (fan_object->stop()) {
ilog("FansRS485: Stopped FanRS485 child object ${name}", ("name", fan_object->get_object_name()));
} else {
elog("FansRS485: Failed to stop FanRS485 child object ${name}", ("name", fan_object->get_object_name()));
}
}
m_fan_objects.clear();
ilog("FansRS485 stopped");
return true;
}
bool FansRS485::init(mc::mutable_dict& csr_object, const mc::dict& connector)
{
elog("FansRS485: init() BEGIN");
try {
FansRS485::from_variant(csr_object, *this);
elog("FansRS485: init() - from_variant completed");
elog("FansRS485: init() - parsing Buses from connector");
if (connector.contains("Buses")) {
try {
auto buses = connector["Buses"].as<std::vector<std::string>>();
if (!buses.empty()) {
m_uart_bus_name = buses[0];
elog("FansRS485: init() - UART bus name set to '${name}'", ("name", m_uart_bus_name));
} else {
elog("FansRS485: init() FAILED - Buses array is empty");
return false;
}
} catch (const std::exception& e) {
elog("FansRS485: init() FAILED - Error parsing Buses: ${err}", ("err", e.what()));
return false;
}
} else {
elog("FansRS485: init() FAILED - Buses field not found in connector");
return false;
}
elog("FansRS485: init() COMPLETED, uart_bus_name='${name}'", ("name", m_uart_bus_name));
} catch (const std::exception& e) {
elog("FansRS485 init failed, exception: ${exception}", ("exception", e.what()));
return false;
}
return true;
}
void FansRS485::from_variant(const mc::dict& d, dev::FansRS485& obj)
{
mc::from_variant(d, obj);
}
void FansRS485::add_fan_objects(mc::object_ptr fan_object_ptr)
{
if (fan_object_ptr != nullptr) {
m_fan_objects.push_back(fan_object_ptr);
}
}
uint8_t FansRS485::get_fan_count()
{
return m_fan_objects.size();
}
uint8_t FansRS485::SetPWM(const std::vector<double>& pwm_list)
{
dlog("FansRS485::SetPWM BEGIN - pwm_list_size=${size}, fan_count=${fan_count}, pwm_values=[${values}]",
("size", pwm_list.size())("fan_count", get_fan_count())("values", pwm_list));
if (pwm_list.empty() || pwm_list.size() != get_fan_count()) {
wlog("FansRS485 SetPWM: wrong pwm number, expected ${expected}, got ${actual}",
("expected", get_fan_count())("actual", pwm_list.size()));
return 1;
}
const auto& fan_objects = get_fan_objects();
dlog("FansRS485::SetPWM - fan_objects_count=${count}, starting PWM setting loop", ("count", fan_objects.size()));
uint8_t failed_count = 0;
for (size_t index = 0; index < fan_objects.size() && index < pwm_list.size(); ++index) {
dlog("FansRS485::SetPWM - loop[${index}]: processing fan, pwm_value=${pwm}",
("index", index)("pwm", pwm_list[index]));
auto fan_obj = dynamic_cast<FanRS485*>(fan_objects[index].get());
if (fan_obj == nullptr) {
elog("FansRS485::SetPWM - loop[${index}]: dynamic_cast FAILED, fan_object is not FanRS485",
("index", index));
failed_count++;
continue;
}
dlog("FansRS485::SetPWM - loop[${index}]: fan_id=${fan_id}, calling set_pwm_duty_cycle with pwm=${pwm}",
("index", index)("fan_id", fan_obj->m_fan.FanId.get_value())("pwm", pwm_list[index]));
if (!fan_obj->set_pwm_duty_cycle(pwm_list[index])) {
elog("FansRS485::SetPWM - loop[${index}]: fan_id=${fan_id} set_pwm_duty_cycle FAILED "
"(not confirmed by slave), ExpectedPWM NOT updated",
("index", index)("fan_id", fan_obj->m_fan.FanId.get_value()));
failed_count++;
continue;
}
dlog("FansRS485::SetPWM - loop[${index}]: ExpectedPWM set to ${pwm} for fan_id=${fan_id}",
("index", index)("pwm", pwm_list[index])("fan_id", fan_obj->m_fan.FanId.get_value()));
fan_obj->m_fan_metrics.ExpectedPWM.set_value(pwm_list[index]);
}
dlog("FansRS485::SetPWM COMPLETE - processed ${processed} fans, failed=${failed}, pwm_list_size=${size}",
("processed", fan_objects.size())("failed", failed_count)("size", pwm_list.size()));
if (failed_count > 0) {
elog("FansRS485 SetPWM: ${failed}/${total} fans failed to confirm PWM",
("failed", failed_count)("total", pwm_list.size()));
return 1;
}
ilog("FansRS485 SetPWM: successfully set PWM for ${count} fans", ("count", pwm_list.size()));
return 0;
}
uint32_t FansRS485::DumpFanLogs(const std::vector<uint32_t>& fan_id_list, const std::string& tar_path,
const std::string& caller_username)
{
if (fan_id_list.empty()) {
elog("FansRS485 DumpFanLogs: fan_id_list is empty");
return 0;
}
if (tar_path.empty() || tar_path.substr(0, 5) != "/tmp/") {
elog("FansRS485 DumpFanLogs: invalid tar_path ${path}", ("path", tar_path));
return 0;
}
auto* svc = static_cast<mc::app::service*>(get_service());
if (svc == nullptr) {
elog("FansRS485 DumpFanLogs: service is null, cannot create task");
return 0;
}
auto [create_result, err_msg, task_id] =
svc->task_mgmt().create_task("DumpFanLogs", mc::string(this->get_object_path()), 30, []() {
elog("FansRS485: DumpFanLogs task TIMEOUT");
}, {{"Description", mc::string("收集风扇日志")}, {"Stage", mc::string("收集中")}});
if (create_result != mc::app::task::CreateResult::Success) {
elog("FansRS485 DumpFanLogs: create_task failed: ${msg}", ("msg", err_msg));
return 0;
}
ilog("FansRS485 DumpFanLogs: task ${id} created, collecting ${n} fans' logs async, caller=${caller}",
("id", task_id)("n", fan_id_list.size())("caller", caller_username.empty() ? "unknown" : caller_username));
auto fan_ids = fan_id_list;
auto tar = tar_path;
auto caller = caller_username;
m_thread_pool->get_executor().post([this, svc, fan_ids, tar, task_id, caller]() {
uint32_t success_count = 0;
const uint32_t total_count = static_cast<uint32_t>(fan_ids.size());
auto now = std::chrono::system_clock::now();
auto now_time = std::chrono::system_clock::to_time_t(now);
std::stringstream ss;
ss << "/var/log/fan_logs_" << std::put_time(std::localtime(&now_time), "%Y%m%d_%H%M%S");
std::string temp_dir = ss.str();
mc::filesystem::create_directories(temp_dir);
for (size_t i = 0; i < fan_ids.size(); ++i) {
uint32_t fan_id = fan_ids[i];
FanRS485* target_fan = nullptr;
for (auto& fan_obj_ptr : m_fan_objects) {
auto fan_obj = dynamic_cast<FanRS485*>(fan_obj_ptr.get());
if (fan_obj && fan_obj->m_fan.FanId.get_value() == fan_id) {
target_fan = fan_obj;
break;
}
}
if (!target_fan) {
wlog("FansRS485 DumpFanLogs: fan ${id} not found", ("id", fan_id));
continue;
}
std::string fan_log_path = temp_dir + "/fan_" + std::to_string(fan_id) + ".log";
if (target_fan->dump_log_info(fan_log_path)) {
chmod(fan_log_path.c_str(), S_IRUSR | S_IWUSR | S_IRGRP);
success_count++;
ilog("FansRS485 DumpFanLogs: fan ${id} log collected successfully", ("id", fan_id));
} else {
elog("FansRS485 DumpFanLogs: fan ${id} log collection failed", ("id", fan_id));
}
mc::dict progress_data;
progress_data["Progress"] = static_cast<int64_t>((i + 1) * 100 / total_count);
svc->task_mgmt().update_task(task_id, progress_data);
}
std::string tar_cmd = "cd " + temp_dir + " && tar -czf " + tar + " *.log";
int ret = system(tar_cmd.c_str());
std::string chown_user = caller.empty() ? "secbox" : caller;
struct passwd* pw = getpwnam(chown_user.c_str());
struct group* gr = getgrnam(chown_user.c_str());
if (pw && gr) {
if (chown(tar.c_str(), pw->pw_uid, gr->gr_gid) != 0) {
elog("FansRS485 DumpFanLogs: chown to ${user} failed for ${path}", ("user", chown_user)("path", tar));
} else {
ilog("FansRS485 DumpFanLogs: tar file chown to ${user} (uid=${uid}, gid=${gid})",
("user", chown_user)("uid", pw->pw_uid)("gid", gr->gr_gid));
}
} else {
wlog("FansRS485 DumpFanLogs: user ${user} not found, chown skipped", ("user", chown_user));
}
chmod(tar.c_str(), S_IRUSR | S_IWUSR | S_IRGRP);
mc::filesystem::remove_all(temp_dir);
mc::dict data;
data["Progress"] = static_cast<int64_t>(100);
if (ret == 0 && success_count > 0) {
data["State"] = mc::string("Completed");
ilog("FansRS485 DumpFanLogs: task ${tid} COMPLETED, success=${ok}/${total}, path=${path}",
("tid", task_id)("ok", success_count)("total", total_count)("path", tar));
} else {
data["State"] = mc::string("Exception");
data["Status"] = mc::string("Error");
elog("FansRS485 DumpFanLogs: task ${tid} EXCEPTION, ret=${ret}, success=${ok}/${total}",
("tid", task_id)("ret", ret)("ok", success_count)("total", total_count));
}
svc->task_mgmt().update_task(task_id, data);
});
return task_id;
}
}
MC_REFLECT(dev::FansRS485, ((m_fans, "bmc.dev.Fans"))((m_fans_oem, "bmc.dev.Fans.Oem")))