/*
 * @Author: mypx
 * @Date: 2025-08-01 16:41:56
 * @LastEditTime: 2025-09-25 16:52:54
 * @LastEditors: mypx mypx_coder@163.com
 * @Description: 
 */
#ifndef __MB_COMMAND_H__
#define __MB_COMMAND_H__
#include "mb_regs_def.h"
#include "nanomodbus.h"
#include "pm_common.h"
#include "pm_params.h"
#include <stdint.h>
// RT-Thread API
#include <rtthread.h>

typedef enum
{
    SYS_CTRL_INIT_CODE            = 0x0001, // 设备初始化
    SYS_CTRL_START_MEAS_CODE      = 0x0002, // 开始测量
    SYS_CTRL_STOP_MEAS_CODE       = 0x0003, // 停止测量
    SYS_CTRL_CLEAR_DATA_CODE      = 0x0004, // 数据清零
    SYS_CTRL_START_TEMP_CTRL_CODE = 0x0005, // 开始控温
    SYS_CTRL_STOP_TEMP_CTRL_CODE  = 0x0006, // 停止控温
} SysCtrlCode;

typedef int (*system_ctrl_handler_t)(SysCtrlCode code);
typedef void (*meas_mode_handler_t)(uint8_t mode);
typedef void (*target_temp_handler_t)(float temp);
typedef void (*tube_length_handler_t)(uint16_t length);
typedef void (*meas_precision_handler_t)(uint8_t precision);
typedef void (*auto_measure_count_handler_t)(uint8_t count);

typedef struct
{
    system_ctrl_handler_t system_ctrl_handler;
    meas_mode_handler_t   meas_mode_handler;
    target_temp_handler_t target_temp_handler;
    tube_length_handler_t tube_length_handler;
    meas_precision_handler_t meas_precision_handler;
    auto_measure_count_handler_t auto_measure_count_handler;
} mb_cmd_handler_t;

#define IR_BUF_SIZE  128
#define REG_BUF_SIZE 128

typedef struct
{
    uint16_t          regs[REG_BUF_SIZE];      // 保持寄存器（可读写）
    uint16_t          input_regs[IR_BUF_SIZE]; // 输入寄存器（只读）
    mb_cmd_handler_t *handler;
    /* 保护 input_regs 的互斥锁 */
    rt_mutex_t        input_lock;
} mb_command_t;

// 初始化命令处理模块
void mb_command_init(mb_command_t *handler);

// 返回当前命令实例（用于访问 input_regs/regs）
mb_command_t *get_command_instance(void);

// 处理保持寄存器写入（3xxxx）
nmbs_error mb_handle_write_holding_registers(uint16_t address, uint16_t quantity, const uint16_t *registers);

// 处理输入寄存器读取（4xxxx）-0x04
nmbs_error mb_handle_read_input_registers(uint16_t address, uint16_t quantity, uint16_t *registers_out);

// 输入寄存器同步接口声明
void mb_sync_running_status_reg(PmRunningState state);
void mb_sync_exception_reg(uint32_t exception, bool set);
void mb_sync_realtime_temp(float temperature);
void mb_sync_realtime_rotation(float rotation);
void mb_sync_result(uint8_t mode, float value, float temp);
void mb_sync_meas_done_flag(bool done);

#endif
