#ifndef __PUBLIC_H
#define	__PUBLIC_H

#include "bsp.h"

#define	LORA_LOWPOWER			//LORA低功耗设备，采用主动上报方式

#define	SENSOR_DATA_LEN_MAX										50
#define	SENSOR_NUM_MAX												16
#define	COMMUNIT_NUM_MAX											32

#define	REGISTER_INTERVAL_MAX									(2 * 60)
#define	COMMUNIT_READ_SENSOR_INTERVAL_MAX			(1 * 60)

#define	LORA_ERR_RESET_DLY_MAX								(10 * 60)				//LORA接收超时复位延时，单位秒
#define	CAT1_ERR_RESET_DLY_MAX								(60 * 60)				//CAT1接收超时复位延时，单位秒

typedef struct GateWay_t GateWayPara_t, *GateWayPara;

typedef void (*SendData)(uint8_t *sData, uint16_t sLen);
typedef int (*DataRevCallBack)(GateWayPara GateWay, uint8_t *rData, uint16_t rLen);
typedef int (*DataRevResCallBack)(GateWayPara GateWay, uint8_t *rData, uint16_t rLen, SendData Response);
typedef int (*SendDataOrg)(uint8_t *sData);

typedef enum {
	DEBUG_CH_DBG,
	DEBUG_CH_RS485_1,
	DEBUG_CH_RS485_2,
}DebugChannel_m;

typedef enum {
	DEV_TYPE_BROADCAST,
	DEV_TYPE_INC_COMMUNIT = 0x8001,
	DEV_TYPE_EXT_COMMUNIT,
	DEV_TYPE_ICE_SENSOR,
	DEV_TYPE_CRACK_SENSOR,
	DEV_TYPE_PRESSURE_SENSOR,
	DEV_TYPE_RAIN_SENSOR,
}DevType_m;

typedef enum {
	CATONE_COMM,
	ETH_COMM,
}CommType_m;

typedef enum {
	LORA_COMM,
	RS485CH1_COMM,
	RS485CH2_COMM
}SensorComm_m;

typedef enum {
	COMM_UNIT_CMD_REG,
	COMM_UNIT_CMD_CAIL,
	COMM_UNIT_CMD_READ,
	COMM_UNIT_CMD_SET_SENSOR_COLL_TIME = 5,
	COMM_UNIT_CMD_TIME_SYNC,
	COMM_UNIT_CMD_CONT_LASER = 8,//激光独有指令
	COMM_UNIT_CMD_GET_SIGNAL,		//0x09 查询Lora信号质量
	COMM_UNIT_CMD_END,
}CommUnitCmd_m;

typedef enum {
	NET_COMM_CMD_REG,
	NET_COMM_CMD_CAIL,
	NET_COMM_CMD_UPDATE,
	NET_COMM_CMD_READ_GW_INFO,
	//NET_COMM_CMD_READ_UNIT_INFO,
	NET_COMM_CMD_GW_PARA_CONFIG,
	NET_COMM_CMD_HIS_DATA,
	NET_COMM_CMD_ADD_UNIT,
	NET_COMM_CMD_LP_DEV_CONFIG,
	NET_COMM_CMD_ALARM,
	NET_COMM_CMD_CONT_LASER,//激光独有指令
	NET_COMM_CMD_END,
}NetCommCmd_m;

typedef enum {
	SENSOR_TYPE_NULL,								//0x0000 空设备
	FORCE_6D,										//0x0001 六维应力
	OSMOTIC_PRESSURE,								//0x0002 渗透压
	ELASTIC_WAVEGUIDE,							//0x0003 弹性波导
	DIELECTRIC_MASS,								//0x0004 介电质普
	VIBRATE_SENSOR,								//0x0005 微振动传感器
	CONT_DEFOR_3D,									//0x0006 三维连续变形
	COMM_UNIT,										//0x0007 通讯单元
	FORCE_3D,										//0x0008 三维应力
	LASER_TRACING,									//0x0009 激光示踪
	WATER_LEVEL,									//0x000A 水位计
	_0x000B,											//0x000B 保留
	_0x000C,											//0x000C 保留	
	MULTI_PARAMETER_FUSION,						//0x000D 多参数融合
	CRACK_DETECTION,								//0x000E 裂缝仪
	_0x000F,											//0x000F 保留
	ATTITUDE_MONITOR,								//0x0010 姿态检测
	LASER_DISPLACE,								//0x0011 激光位移
	REBAR_STRESS,									//0x0012 钢筋应力
	ANCHOR_ROD_STRESS,							//0x0013 锚杆轴力
	SURFACE_STRESS,								//0x0014 表面应力
	PRESSURE,										//0x0015 压力
	MICROWAVE_DISPLACE,							//0x0016 微波位移 
	DISPLACEMENT = 0x0020,						//0x0020 位移监测传感器
}SensorType_m;

typedef struct {//主设备固定包头
	uint8_t BatLevel;								//电池电量
	int8_t RSSI;									//信号强度
	int8_t Nsr;										//信噪比
}__attribute__ ((packed))MasterDev_T,*MasterDevDp;

typedef struct {
	int16_t AccX;
	int16_t AccY;
	int16_t AccZ;
	int32_t Strain1;
	int32_t Strain2;
	int32_t Strain3;
	int32_t Strain4;
	int32_t Strain5;
	int32_t Strain6;
}__attribute__((packed))Force6D_T;

typedef struct {
	MasterDev_T MasterDev;
	int16_t PitchAngle;							//俯仰角偏斜	（范围±900）单位0.1°
	int16_t RollAngle;								//横滚角偏斜	（范围±900）单位0.1°
	int16_t YawAngle;								//偏航角偏斜	（范围0~3600）单位0.1°
}__attribute__((packed))LaserTracingType_T;

typedef struct {//0x0020 位移计
  MasterDev_T MasterDev;
	int16_t PitchAngle;							//俯仰角偏斜（范围±900）单位0.1°
	int16_t RollAngle;								//横滚角偏斜（范围±900）单位0.1°
	int16_t YawAngle;								//偏航角偏斜（范围0~3600）单位0.1°
  float Temp;                     //温度
	float Altitude;									//海拔（）单位cm
	int16_t Distance;								//1轴应力值转位移（范围±300,单位0.1mm）
}__attribute__ ((packed))Displacement_T,*DisplacementDp;

typedef struct {
	int Distance;
}__attribute__((packed))LaserDistanceSensorType_t;

typedef struct {
	uint8_t CommDevAddr[6];			//通讯单元地址
	uint16_t CollectInterval;		//采集时间间隔
	uint16_t ReportInterval;		//上报时间间隔
	uint8_t ERInterval;				//紧急上报时间间隔
	uint8_t ERTime;						//紧急上报时长
}__attribute__((packed))SvrDownLPDevConfigPara_t;

typedef struct {
	uint8_t AlarmType;
	uint8_t AlarmState;
	uint8_t AlarmPara;
}__attribute__((packed))GateWayAlarmType_t;

#define	LW_DEV_COLLECT_INTERVAL_MAX					300//默认300秒
#define	LW_DEV_REPORT_INTERVAL_MAX						20//20分钟
#define	LW_DEV_ER_INTERVAL_MAX							2//2分钟
#define	LW_DEV_ER_TIME_MAX								20//20分钟

typedef struct {
	uint16_t CollectInterval;		//采集时间间隔
	uint16_t ReportInterval;		//上报时间间隔
	uint8_t ERInterval;				//紧急上报时间间隔
	uint8_t ERTime;						//紧急上报时长
	uint32_t TimeStamp;				//时间戳
}__attribute__((packed))LPDevConfigPara_t;

typedef struct {
	bool RegFlag;
	bool RevNewDataFlag;
	bool CommStatus;	//通讯状态，1-在线，0-离线
	bool	CailFlag;	//校准标志（低功耗）
	bool	TimeSyncFlag;	//时间同步标志（低功耗）
	bool	ContLaser;	//激光控制标志（低功耗）
	bool	LaserOnOff;	//激光状态（低功耗）
	uint32_t CommErrCnt;
	uint8_t MasterMac[6];
	uint8_t Mac[SENSOR_NUM_MAX][6];//第一位是主设备，后面全是子设备
	uint8_t BatLevel;
	int8_t RSSI;									//信号强度
	int8_t Nsr;										//信噪比
	uint16_t CUType;
	uint8_t SensorN;
	uint16_t SensorType[SENSOR_NUM_MAX];
	//低功耗设备配置信息
	bool ConfigFlag;			//配置标志，为1表示有新配置，应答低功耗设备时需要附带发送
	uint16_t CollectInterval;		//采集时间间隔
	uint16_t ReportInterval;		//上报时间间隔
	uint8_t ERInterval;				//紧急上报时间间隔
	uint8_t ERTime;						//紧急上报时长
}__attribute__((packed))CommUnitPara_t, *CommUnitPara;

typedef struct {
	bool ExclFlag;
	uint8_t ExclMac[6];//需要排除的通讯单元MAC
}__attribute__((packed))ExclCommUnit_t, *ExclCommUnit;

typedef struct {
	uint8_t Data[SENSOR_NUM_MAX][SENSOR_DATA_LEN_MAX];
}__attribute__((packed))CommUnitData_t, *CommUnitData;

typedef struct {
	CommUnitPara_t Para;
}__attribute__((packed))CommUnit_t, *CommUnit;

typedef struct {
	bool Enable;		//串口使能
	bool CommUnitEnable;		//通讯单元使能，开启（使用内部通讯单元功能，直接和传感器通讯），关闭（直接和RS485类型的通讯单元通讯）
	bool QuerySensorFlag;		//查询传感器标志
	bool UpgradeEnable;//升级功能使能
	uint8_t Power;
	uint32_t BaudRate;
	SendData RS485Send;
	CommUnit_t CUPara;
  CommUnitData_t CUData;
}__attribute__((packed))RS485Para_t, *RS485Para;

typedef struct {
	uint8_t Header;
	uint8_t GWMac[6];
	uint8_t DevMac[6];
	uint8_t Cmd;
	//uint16_t DevType;
	uint16_t PayloadLen;
}__attribute__((packed))CommUnitFrameHeader_t, *CommUnitFrameHeader;

typedef struct {
	uint8_t Header;
	uint8_t GWMac[6];
	//uint8_t SvrMac[6];
	uint8_t Cmd;
	uint8_t BatLevel;
	uint32_t Timestamp;
	uint8_t PacketNum;
	uint8_t PacketIdx;
	uint16_t PayloadLen;
}__attribute__((packed))NetCommFrameHeader_t, *NetCommFrameHeader;

typedef struct {
	bool OnOff;
	SendData LoraSend;
	uint8_t ucChannel;
	int8_t ucPower;
	uint8_t SignalBw;
	uint8_t SpreadFactor;
	uint8_t ErrorCoding;
	uint8_t RegPreamble;
	uint32_t FreqCent;
}LoraPara_t, *pLoraPara;

typedef struct {
	uint8_t DestAddr[4];								//目的服务器地址
	uint16_t DestPort;									//目的服务器端口
	uint8_t LocalAddr[4];								//本地客户端地址(预留)
	uint16_t LocalPort;									//本地客户端端口(预留)
}LTENetPara_t, *pLTENetPara;

typedef struct {
	uint8_t IpMode;								//IP模式：DHCP/静态
	uint8_t IpAddr[4];								//本地IP地址
	uint16_t IpPort;									//本地端口
	uint8_t WorkMode;						//工作模式
	uint8_t SubnetMask[4];						//子网掩码
	uint8_t Gateway[4];								//网关
	uint8_t DestIp[4];								//目的IP地址
	uint16_t DestPort;								//目的端口
}EthNetPara_t, *pEthNetPara;

typedef struct {
	uint32_t SavFlag;									//存储标志
	CommType_m Comm;									//网关通讯方式
	uint8_t GwMac[6];									//网关mac
	LTENetPara_t LTENet;								//Cat1/4G服务器参数
	EthNetPara_t EthNet;								//以太网网络参数
	uint32_t CommUnitReadInterval;				//通讯单元读取时间间隔,单位S
	CommUnitPara_t CommUnitArray[COMMUNIT_NUM_MAX];			//注册的通讯单元信息
	ExclCommUnit_t ExclCommUnit[COMMUNIT_NUM_MAX];			//排除的通讯单元信息
	RS485Para_t Rs485Ch1;							//RS485通道1配置
	RS485Para_t Rs485Ch2;							//RS485通道2配置
	uint8_t DebugChannel;							//调试通道
	LoraPara_t Lora;									//Lora配置
	bool OutageFlag;									//断电报警标志
	uint16_t crc16;
}__attribute__((packed))GWConfigPara_t, *GWConfigPara;

struct GateWay_t{
	bool TimeSyncFlag;								//时间同步标志
	bool SvrRegFlag;									//服务器注册标志
	uint8_t SvrMac[6];								//服务器mac
	GWConfigPara_t ConfigPara;						//配置参数
	CommUnitData_t CUDataArray[COMMUNIT_NUM_MAX];
	uint8_t Battery;									//电池电量
	uint16_t UploadInterval;						//上传间隔
	uint32_t HistoryNum;								//历史数据数量
	DataRevCallBack SvrRevCallBack;				//接收到服务器回调
	DataRevResCallBack CommUnitRevCallBack;	//通讯单元接收回调
	rt_mq_t NetSendData_MQ;							//网络发送数据队列，第一个字节用于存储消息长度, 第二字节存储命令字，后为数据
	rt_mq_t LoraRev_MQ;								//Lora接收消息队列，第一个字节用于存储消息长度，后为数据
	rt_mutex_t UartRevMutex;
	
	uint8_t BatteryReadDlyCnt;		//读取电压延时，单位秒，防止4G发送拉低电池电压，造成断电误报
};

int Cat1EthRevCallBack(GateWayPara GateWay, uint8_t *rData, uint16_t rLen);
uint16_t CRC_Modbus(uint16_t wBase, __IO uint8_t *para, uint16_t length);
uint8_t AsciiToHex(char *ASCData, uint8_t *HexData, uint8_t sLen);
void HexToAscii(uint8_t *HexData, char *ASCData, uint8_t sLen);
int NetCommOrgData(GateWayPara GateWay, uint8_t *MegData, uint8_t *OutData);
int CommUnitAnalyze(GateWayPara GateWay, uint8_t *rData, uint16_t rLen, SendData Response);
void DebugAnalyze(GateWayPara GateWay, uint8_t *rData, uint16_t rLen);
void CommUnitCmdSend(GateWayPara GateWay, uint8_t *CommUnitMac, CommUnitCmd_m Cmd, uint8_t *Payload, uint16_t PayloadLen, SendData Send);
int CheckCommUnitReg(GateWayPara GateWay, uint8_t *CommUnitMac);
int CheckCommUnitExcl(GateWayPara GateWay, uint8_t *CommUnitMac);
int CommUintOrgData(GateWayPara GateWay, CommUnitPara CUPara, CommUnitData CUData, uint8_t *sData);
void DebugDisplaySensorData(int SensorIdx, uint16_t SensorType, uint8_t *SensorData);
#endif

