/***************************************************************************
 * Copyright (C) 2026 Eclipse ThreadX contributors
 *
 * This program and the accompanying materials are made available under the
 * terms of the MIT License which is available at
 * https://opensource.org/licenses/MIT.
 *
 * AI Disclosure: This file was largely AI-generated by Copilot (Sonnet 4.6).
 * The AI-generated portions may be considered public domain (CC0-1.0)
 * and not subject to the project's licence. The human contributor has
 * reviewed and verified that the code is correct.
 *
 * SPDX-License-Identifier: MIT and CC0-1.0
 **************************************************************************/

#include <stdint.h>

#include "i2c_master.h"
#include "properties.h"
#include "temp_sensor.h"

#define ADT7420_I2C_ID       1U
#define ADT7420_ADDR7        0x4BU
#define ADT7420_TEMP_REG     0x00U
#define ADT7420_I2C_FREQ_HZ  200000U

void temp_sensor_init(void)
{
    (void)i2c_master_init(ADT7420_I2C_ID, ADT7420_I2C_FREQ_HZ, ARCHI_FPGA_FREQUENCY);
}

int16_t temp_read_celsius_x10(void)
{
    uint8_t buf[2];
    int16_t raw;
    int16_t value;

    if (i2c_master_read_reg(ADT7420_I2C_ID, ADT7420_ADDR7, ADT7420_TEMP_REG, &buf[0], 2U) != 0)
    {
        return INT16_MIN;
    }

    raw = (int16_t)(((uint16_t)buf[0] << 8U) | (uint16_t)buf[1]);
    value = (int16_t)(raw >> 3);
    return (int16_t)(((int32_t)value * 5) / 8);
}
