/**
 * @file    self_ptl.h
 * @brief   自协议层公共头 — 配置数据结构、帧类型、双协议常量
 */

#ifndef _SELF_PTL_H_
#define _SELF_PTL_H_

#include "myBase.h"
#include "mySystem.h"
#include "myDatacenter.h"
#include <string>
#include <vector>

#ifdef __cplusplus
extern "C" {
#endif

#define MODULE_SELF_PTL "self_ptl"

/* IEC-104 帧常量 */
#define IEC_START_1 0x68
#define IEC_START_2 0x10
#define IEC_TAIL    0x16

/* 环形缓冲大小 */
#define SELF_PTL_BUF_SIZE  2048
#define SELF_PTL_TEMP_SIZE 256
#define IEC_APCI_MIN_LEN   4
#define IEC_FRAME_OVERHEAD 2

/* 信号端口起始地址 */
#define YX_START_PORT 0x01    /**< 遥信起始位置 */
#define YC_START_PORT 0x4001  /**< 遥测起始位置 */
#define DD_START_PORT 0x6401  /**< 电度起始位置 */

/* IEC-104 帧类型 */
enum
{
	ERR_FRAME = 0,
	I_FRAME,
	S_FRAME,
	U_FRAME,
};

#ifdef __cplusplus
}
#endif

/* =========================== C++ 部分 =========================== */

#ifdef __cplusplus

/* APCI帧结构 */
#pragma pack(1)
typedef struct
{
	uint8_t start;
	uint8_t len;
	uint8_t ctrl1;
	uint8_t ctrl2;
	uint8_t ctrl3;
	uint8_t ctrl4;
	uint8_t data[0];
}stru_iec104_apci;
#pragma pack()

/* ASDU帧结构 */
#pragma pack(1)
typedef struct
{
	uint8_t  ti;
	uint8_t  vsq;
	uint16_t cot;
	uint16_t asdu_addr;
	uint8_t  inf[3];
	uint8_t  data[0];
}stru_iec104_asdu;
#pragma pack()

/* XML 配置解析结构体 */
typedef struct
{
	std::string saddr;
	std::string desc;
	int         inf;
}stru_self_ptl_cfg_base;

typedef struct
{
	stru_self_ptl_cfg_base base;
	int                    type;
	std::string            unit;
	std::string            min;
	std::string            max;
	std::string            step;
	std::vector<std::string> val;
	std::vector<std::string> default_value;
}stru_self_ptl_cfg_param;

/* 文件目录条目 (dir_pop_out 回调使用) */
typedef struct
{
	char     name[256];
	uint8_t  len;
	uint32_t attr;
	uint32_t size;
}stru_dir_info;

typedef struct
{
	bool init;
	std::vector<stru_self_ptl_cfg_base>  st_vec;
	std::vector<stru_self_ptl_cfg_base>  mx_vec;
	std::vector<stru_self_ptl_cfg_base>  co_vec;
	std::vector<stru_self_ptl_cfg_base>  dd_vec;
	std::vector<stru_self_ptl_cfg_param> ao_vec;
	std::vector<stru_self_ptl_cfg_param> param_vec;
	uint8_t ao_md5[16];
}stru_self_ptl_cfg;

/* 运行时数据绑定 */
typedef struct
{
	stru_self_ptl_cfg_base *p_base;
	void                   *p_data;
	dc_ctrl_t       *p_ctrl;
}stru_self_ptl_cfg_base_data;

typedef struct
{
	stru_self_ptl_cfg_param *p_param;
	dc_ctrl_t        *p_ctrl;
	std::vector<void *>      vec_p_data;
}stru_self_ptl_cfg_param_data;

typedef struct
{
	std::vector<stru_self_ptl_cfg_base_data>  st_vec;
	std::vector<stru_self_ptl_cfg_base_data>  mx_vec;
	std::vector<stru_self_ptl_cfg_base_data>  co_vec;
	std::vector<stru_self_ptl_cfg_base_data>  dd_vec;

	std::vector<stru_self_ptl_cfg_param_data> ao_vec;
	std::vector<stru_self_ptl_cfg_param_data> param_vec;
}stru_self_ptl_cfg_data;

#endif /* __cplusplus */

#endif /* _SELF_PTL_H_ */
