/*
 * Copyright (c) 2026 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.
 */

/*
 * adc_chip.cpp — Zephyr-only 伪 Chip:LS1020 片上温感(ADC1 ch13)实现
 *
 * 见 adc_chip.h 头注释与 docs/design/sensor-mgmt-adaptation.md §4 Phase 1.4。
 * ADC 读法照抄板上验证过的 LS1020 仓 samples/adc/adc_single_channel:
 * channel_id=13(专用温感通道)、ADC_REF_INTERNAL、acquisition_time=15CYCLES、
 * adc_channel_setup 一次 + adc_read 轮询。adc_ls.c 驱动不消费 sequence.channels
 * (按 DT nbr_of_conversion 顺序回填 buffer),与样例一致不显式设置。
 */

#include "adc_chip.h"

#include <mc/log.h>

#include <zephyr/devicetree.h>
#include <zephyr/drivers/adc.h>

#include <cstring>

#include "securec.h"

namespace {

constexpr uint8_t kAdcChannelId = 13; /* ch13 专用片上温感(板上验证 ~2064) */
/* ADC_SAMPLETIME_15CYCLES (hal ls_hal_adcv2.h)。不引 hal 头,避免 include 路径耦合 */
constexpr uint16_t kAdcAcquisitionTime = 0x3;
constexpr uint32_t kSamplePeriodMs     = 500;
constexpr uint32_t kSampleLogInterval  = 20; /* 每 20 次采样 ilog 一次观测 */

} // namespace

namespace dev {

std::vector<uint8_t> Interface_AdcChip::BlockIORead(uint32_t offset, uint32_t length)
{
    const uint16_t code = cached_code();
    dlog("AdcChip BlockIORead: offset=${offset} length=${length} code=${code}",
         ("offset", offset)("length", length)("code", code));

    std::vector<uint8_t> out(length, 0); /* >2 字节部分补零 */
    if (length >= 1) {
        out[0] = static_cast<uint8_t>(code & 0xFF);
    }
    if (length >= 2) {
        out[1] = static_cast<uint8_t>((code >> 8) & 0xFF);
    }
    return out;
}

void Interface_AdcChip::BlockIOWrite(uint32_t offset, const std::vector<uint8_t>& buffer)
{
    /* 片上温感只读;保持 no-op(不抛异常,避免误配置打断扫描链路) */
    (void)offset;
    (void)buffer;
}

bool AdcChip::init(mc::mutable_dict& csr_object, const mc::dict& connector)
{
    (void)csr_object; /* SR 里 AdcChip_1 仅说明性字段,不强制解析 */
    (void)connector;

    const struct device* adc = DEVICE_DT_GET(DT_NODELABEL(adc1));
    if (!device_is_ready(adc)) {
        ilog("AdcChip init: ADC device not ready, cached code stays 0");
    } else {
        struct adc_channel_cfg channel_cfg = {};
        channel_cfg.channel_id             = kAdcChannelId;
        channel_cfg.reference              = ADC_REF_INTERNAL;
        channel_cfg.acquisition_time       = kAdcAcquisitionTime;
        int rc                             = adc_channel_setup(adc, &channel_cfg);
        if (rc != 0) {
            ilog("AdcChip init: adc_channel_setup failed rc=${rc}, cached code stays 0", ("rc", rc));
        } else {
            m_adc = adc;
        }
    }

    /* 周期采样 timer——用法照 i_scanner.cpp 的 m_scanner_timer */
    m_sample_timer = mc::make_shared<mc::timer>(this);
    m_sample_timer->timeout.connect([this]() {
        sample_once();
    });
    m_sample_timer->set_single_shot(false);
    m_sample_timer->start(mc::milliseconds(kSamplePeriodMs));

    ilog("AdcChip init done: adc=${state}, period=${period}ms",
         ("state", m_adc != nullptr ? "ready" : "unavailable")("period", kSamplePeriodMs));
    return true;
}

bool AdcChip::start()
{
    return true; /* 采样 timer 已在 init 中启动 */
}

bool AdcChip::stop()
{
    if (m_sample_timer) {
        m_sample_timer->stop();
        m_sample_timer.reset();
    }
    return true;
}

void AdcChip::sample_once()
{
    if (m_adc == nullptr) {
        return; /* 设备不可用:缓存维持 0,init 时已告警,不再刷屏 */
    }

    uint16_t            buf[4] = {0};
    struct adc_sequence sequence;
    memset_s(&sequence, sizeof(sequence), 0, sizeof(sequence));
    sequence.buffer      = buf;
    sequence.buffer_size = sizeof(buf);

    int rc = adc_read(m_adc, &sequence);
    if (rc != 0) {
        ilog("AdcChip sample: adc_read failed rc=${rc}", ("rc", rc));
        return;
    }

    m_interface_adc_chip.set_cached_code(buf[0]);

    if (++m_sample_count % kSampleLogInterval == 0) {
        ilog("AdcChip sample #${count}: code=${code}", ("count", m_sample_count)("code", buf[0]));
    }
}

} // namespace dev

MC_REFLECT(dev::Interface_AdcChip)
MC_REFLECT(dev::AdcChip, ((m_interface_adc_chip, "bmc.dev.Chip")))