 /* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file    yunhorn_sts_sensors.h											   *
  * @author  Yunhorn Technology Limited Application Team					   *
  * @brief   Header for Yunhorn SmarToilets Product sensors application		   *
  ******************************************************************************
  * @attention
  * V2022-0823
  * Copyright (c) 2023 Yunhorn Technology Limited.
  * Copyright (c) 2023 Shenzhen Yunhorn Technology Co., Ltd.
  * All rights reserved.
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */

/* Define to prevent recursive inclusion -------------------------------------*/
#ifndef __YUNHORN_STS_SENSORS_H__
#define __YUNHORN_STS_SENSORS_H__

#ifdef __cplusplus
extern "C" {
#endif
/* Includes ------------------------------------------------------------------*/

/* USER CODE BEGIN Includes */
#include "stdint.h"
#include <stddef.h>
#include "yunhorn_sts_prd_conf.h"
#include "LmHandler.h"

/* USER CODE END Includes */

/* Exported types ------------------------------------------------------------*/
/**
  * Sensor data parameters
  */
	

enum cfg_cmd_order{
	CFG_CMD1=0,		//'Y'
	CFG_CMD2,			//'D' 'Z' 'V' 'O' 'F' 'H' 'M' 'L'
	CFG_CMD3,			// # Z {H, S, C}  M {0,1,2,3,4]
	CFG_CMD4,			// # 
	CFG_CMD5,			// 'S','M','H'
	CFG_CMD6
};
enum p_cmd_order{
	P_CMD=0,			//'P'  //P_MTM_CODE,		// #1
	P_MTM_VER,			// #1
	P_MEMS_NO,			// #2
	//P_MEM_CFG,			// #3
	P_WORK_MODE,			// #4 work mode
	P_NET_COLOR			// #5 cloud net color
};

//"P 0 0 "+"1 2 3 1 2 3 1 2 3 1 2"
// P 
// P 1 SENSOR HEAD 0
// P 1 0  SENSOR HEAD 0, VERSION 0
// P 1 0 1 2  SENSOR HEAD 0, VERSION 0, VALUE 12, 1*10+2


typedef struct
{
  uint8_t WakeUpStatus;
  uint8_t SleepStatus;
} STS_PRESENCE_SENSOR_Event_Status_t;



/* USER CODE BEGIN ET */

/* USER CODE END ET */

/* Exported constants --------------------------------------------------------*/

/* USER CODE BEGIN EC */

/* USER CODE END EC */

/* External variables --------------------------------------------------------*/
/* USER CODE BEGIN EV */

/* USER CODE END EV */

/* Exported macro ------------------------------------------------------------*/
/* USER CODE BEGIN EM */

/* USER CODE END EM */

/* Exported functions prototypes ---------------------------------------------*/
//  0 --- 10  11   12 -- 39    40 41 42 43         44-63
//            LEN  P RSS       FALL_DETECTION      AC_CODE
enum nvm_order {
NVM_MTM1=0,									// 0
NVM_MTM2,									// 1
NVM_VER,									// 2
NVM_HWV,									// 3
NVM_PERIODICITY,							// 4
NVM_UNIT,									// 5
NVM_SAMPLING,								// 6
NVM_S_UNIT,									// 7
NVM_WORK_MODE,								// 8
NVM_SERVICE_MASK,							// 9
NVM_IOC_MASK,								//10
NVM_LEN,									//11, 32=0x20
	NVM_CFG_START=12,						//12, p[0] bytes for configs,
											//13, p[1]
											//14, p[2]
											//15, p[3]
											//16, p[4]
											//17, p[5]
											//18, p[6]
											//19, p[7]
											//20, p[8]
											//21, p[9]
											//22, p[10]
											//23, p[11]
											//24, p[12]
											//25, p[13]
											//26, p[14]
											//27, p[15]
											//28, p[16]
											//29, p[17]
											//30, p[18]
	NVM_CFG_START_END=31,					//31, p[19]
	NVM_RESERVE02,							//32
	NVM_RESERVE03,							//33
	NVM_SENSOR_INSTALL_HEIGHT,				//34
	NVM_ALARM_PARAMETER05,					//35
	NVM_ALARM_MUTE_RESET_TIMER,				//36
	NVM_ALARM_LAMP_BAR_FLASHING_COLOR,		//37
	NVM_OCCUPANCY_OVERTIME_THRESHOLD, 		//38

	NVM_MOTIONLESS_DURATION_THRESHOLD,		//39
	NVM_UNCONSCIOUS_LEVEL_THRESHOLD,			//40

	NVM_FALL_DETECTION_ACC_THRESHOLD,		//41
	NVM_FALL_DETECTION_DEPTH_THRESHOLD,		//42
	NVM_FALL_CONFIRM_THRESHOLD,				//43

	NVM_AC_CODE_START=44					//STORED, NO UPLOAD
											//63,  20 bytes for AC code
};

typedef	struct sts_cfg_nvm {
	uint8_t mtmcode1;
	uint8_t mtmcode2;
	uint8_t version;
	uint8_t hardware_ver;
	uint8_t periodicity;		//count of uplink duty cycle duration high {99}
	uint8_t unit;				// uplink time unit of duty cycle duration, in 'S', 'M','H' seconds, minutes, hours
	uint8_t sampling;			//count of sampling duty cycle duration high {99}
	uint8_t s_unit;				// sampling time unit of duty cycle duration, in 'S', 'M','H' seconds, minutes, hours
	uint8_t work_mode;
	uint8_t sts_service_mask;
	uint8_t sts_ioc_mask;			// I/O Control mask enable all 0xFF, Disable all 0x00 0b0000 0000
	uint8_t length;				// length of following parameters except  AC CODE(20bytes)
	uint8_t p[STS_CFG_PCFG_SIZE];

	uint8_t reserve02;
	uint8_t reserve03;
	uint8_t sensor_install_height_in_10cm;
	uint8_t alarm_parameter05;
	uint8_t alarm_mute_reset_timer_in_10sec;			//60(0x3C) sec alarm_mute_or_reset_expire_timer_in_sec
	uint8_t alarm_lamp_bar_flashing_color;				//Lamp Bar Flashing color define, 0x20, 2==STS_RED, 0 = STS_DARK, 0x23, 2=STS_RED, 3=STS_BLUE
	uint8_t occupancy_overtime_threshold_in_10min;		// 0 - 9： 0：disable, 1-9 occupy over time threshold * 10 min

	uint8_t motionless_duration_threshold_in_min;		// 10(0x0A) min (2 min.) motionless_duration_threshold_in_min
	uint8_t unconscious_or_motionless_level_threshold;	// 0 - 9 motion level *128

	uint8_t fall_detection_acc_threshold;				// 0 - 9: 0:disable: 1-9 accelaration mg/s2
	uint8_t fall_detection_depth_threshold;				// 0 - 9: 0:disable: 1-9 fall down depth * 10 cm
	uint8_t fall_confirm_threshold_in_10sec;			// 0-60(0x3C) Sec, or 3*10(0x03) sec default falldown_confirm_threshold_in_10sec

	uint8_t ac[YUNHORN_STS_AC_CODE_SIZE];				// authorization code, 20 bytes MCU UUID coded
} sts_cfg_nvm_t;

#ifndef TRUE
#define	TRUE 	1
#endif
#ifndef FALSE
#define FALSE 	0
#endif

#define	STS_SERVICE_MASK_L0		(0)		// Service normal , no mask off
#define	STS_SERVICE_MASK_L1		(1)		// service mask level 1, sensing data upload in silence mode, node appearance silence (no LED, No display, no sound, no vibration)
#define	STS_SERVICE_MASK_L2		(2)		// service mask level 2, NO sensing data upload (event or periodicity)
#define	STS_SERVICE_MASK_L3		(3)		// service mask level 3, NO responsing to cloud control command, or config change/responding, EXCEPT STS_SERVICE_MASK_ON_OFF cmd

typedef struct sts_tof_range_data {
	 uint16_t tof_1_distance_mm;
	 uint16_t tof_2_distance_mm;
	 uint16_t tof_3_distance_mm;
} sts_tof_range_data_t;

typedef struct sts_r_sensor_data
{
	uint16_t install_height_mm;		/*Default distance sensor measured distance */
	uint16_t battery_mV;			/*mV, 1000mv-5000mv, regular 3300mV - 3600mV --4200mV */

	uint8_t on_off_event;			/* 1: liquid sensed, 0: no liquid sensed */
	uint8_t liquid_level;			/* for multi-level liquid sensor		*/
	uint8_t measure_tech;     		/* 0: capacity, 1:dTof, 2: ultrasonic  */

	uint16_t distance1_mm; 			/* Additional #1 distance  */	// water tank or cistern water level
	uint16_t distance2_mm;			/* Additional #2 distance  */
	uint16_t distance3_mm;			/* Additional #3 distance  */

	uint8_t battery_Pct;  			/* % of battery two digits, 88% (00-99)%   */

} sts_r_sensor_data_t;

/**
  * @brief  Store/Write/Flash Configuration in RW RAM 	
  */
void OnStoreSTSCFGContextRequest(void);

/**
  * @brief  Read config from flash
  */
void OnRestoreSTSCFGContextRequest(uint8_t *cfg_in_nvm);

void STS_REBOOT_CONFIG_Init(void);

/**
  * @brief  Apply/Process config to board
  */
void OnRestoreSTSCFGContextProcess(void);

/**
  * @brief  Read duty cycle level count from flash
  */
//uint8_t * read_duty_cycle_level_from_flash(uint8_t *flash_code_duty_cycle_level, uint32_t Save_Config_Flash_Addr);

void STS_SENSOR_Power_ON(uint8_t cnt);
void STS_SENSOR_Power_OFF(uint8_t cnt);
void STS_SENSOR_MEMS_Reset(uint8_t cnt);

void STS_PRESENCE_SENSOR_NVM_CFG(void);
void STS_PRESENCE_SENSOR_NVM_CFG_SIMPLE(void);

void STS_SENSOR_NVM_CFG_SIMPLE(void);
void STS_SENSOR_NVM_CFG(void);

void STS_YunhornSTSEventP1_Process(void);
void STS_YunhornSTSEventP2_Process(void);
void STS_YunhornSTSEventP3_Process(void);
void STS_YunhornSTSEventP4_Process(void);
void STS_YunhornSTSEventP5_Process(void);
void STS_YunhornSTSEventP6_Process(void);
void STS_YunhornSTSEventP7_Process(void);
void STS_YunhornSTSEventRFAC_Process(void);
void STS_YunhornAuthenticationCode_Process(void);

void STS_Reed_Hall_Presence_Detection(void);

void STS_SENSOR_Upload_Config_Invalid_Message(void);
void STS_SENSOR_Upload_Message(uint8_t appDataPort, uint8_t appBufferSize, uint8_t *appDataBuffer);
void STS_SENSOR_Upload_AppData_Message(LmHandlerAppData_t stsAppdata);
void STS_SENSOR_MEMS_Get_ID(uint16_t *devID);
void STS_RR_Sensor_Read(sts_tof_range_data_t *sts_rr_sensor_data);
void STS_R4_sensor_read(sts_r_sensor_data_t *sts_r_sensor_data);
void STS_M1_sensor_read(sts_r_sensor_data_t *sts_m_sensor_data);
void OnYunhornSTSHeartBeatPeriodicityChanged(uint32_t periodicity);
void OnYunhornSTSTxPeriodicityChanged(uint32_t periodicity);
void USER_APP_AUTO_RESPONDER_Parse(uint8_t *parse_buffer, uint8_t parse_buffer_size);
void STS_SENSOR_Function_Test_Process(void);
void STS_SENSOR_Distance_Test_Process(void);
void STS_PRESENCE_SENSOR_Function_Test_Process(uint8_t *self_test_result, uint8_t count);
void STS_PRESENCE_SENSOR_Distance_Measure_Process(void);

/* USER CODE BEGIN Private defines */
/* 
    In this example TIM2 input clock (TIM2CLK)  is set to APB1 clock (PCLK1),
    since APB1 prescaler is equal to 1.
      TIM2CLK = PCLK1
      PCLK1 = HCLK
      => TIM2CLK = HCLK = SystemCoreClock
    To get TIM2 counter clock at 10 KHz, the Prescaler is computed as following:
    Prescaler = (TIM2CLK / TIM2 counter clock) - 1
    Prescaler = (SystemCoreClock /10 KHz) - 1

    Note:
     SystemCoreClock variable holds HCLK frequency and is defined in system_stm32wlxx.c file.
     Each time the core clock (HCLK) changes, user had to update SystemCoreClock
     variable value. Otherwise, any configuration based on this variable will be incorrect.
     This variable is updated in three ways:
      1) by calling CMSIS function SystemCoreClockUpdate()
      2) by calling HAL API function HAL_RCC_GetSysClockFreq()
      3) each time HAL_RCC_ClockConfig() is called to configure the system clock frequency
  ----------------------------------------------------------------------- */

/* Compute the prescaler value to have TIMx counter clock equal to 10000 Hz */

//#define PRESCALER_VALUE (uint32_t)(((SystemCoreClock) / (10,000)) - 1)

#define PRESCALER_VALUE (uint32_t)(((SystemCoreClock) / (1000000)) - 1)   
// STS-M7 == 2,000,000 == 0.5us ==> 2 Ghz             
// STS-M7 == 1,000,000 == 1.0us ==> 1 GHZ                **************
// STS-M7 == 0,010,000 ==  10ms ==> 100 hz

  /* Initialize TIMx peripheral as follows:
       + Period = 10000 - 1
       + Prescaler = (SystemCoreClock/10000) - 1
       + ClockDivision = 0
       + Counter direction = Up
  */

#define PERIOD_VALUE (1000 - 1);     //(1/PERIOD_VALUE) ms, for 1024hz it's about 0.976ms
//#define PERIOD_VALUE (1000 - 1);   // 1000 hz, 1ms
//#define PERIOD_VALUE 	(320 - 1);
// STS-M7 == 1,000 * 1.0us == 1000 us ==> 1.0 ms ==> 1000 ms /1.0ms ==>1000 hz sample rate
// STS-M7 == 1,000 * 0.5us == 500 us ==> 0.5 ms ==> 1000 ms /0.5ms ==>2000 hz sample rate

/* USER CODE END Private defines */


//=============================================================================
void DelayMicroSeconds(uint32_t nbrOfUs);
//=============================================================================
// Wait function for small delays.
//-----------------------------------------------------------------------------
// input:  nbrOfUs   wait x times approx. one micro second (fcpu = 8MHz)
// return: -
// remark: smallest delay is approx. 15us due to function call



//#define SYSTEM_CORE_CLOCK 48000000 
#define DBG_TIME
#define DELAY_MS_CLOCK    (SYSTEM_CORE_CLOCK - 18) / 11000
#define DELAY_100US_CLOCK    (SYSTEM_CORE_CLOCK) / 120600
#define DELAY_10US_CLOCK    (SYSTEM_CORE_CLOCK) / 1200000
#define DELAY_1US_CLOCK    (SYSTEM_CORE_CLOCK) / 12000000
#define NOP() __ASM volatile ("nop")

#define I2C_TIMING 0x20303E5D
#define I2C_TIMING_TOF250		0x20303E5D
#define I2C_TIMING_ADXL345_STANDARD_MODE			0x20303E5D  //STANDARD MODE 100Khz *******
#define I2C_TIMING_ADXL345_FAST_MODE			0x2010091A  //FAST MODE 400Khz
#define I2C_TIMING_ADXL345_FAST_PLUS_MODE			0x20000209  //FAST PLUS MODE 1000Khz

void Delay(uint32_t nTime);
void DelayMs(uint32_t mS);
void Delay1Us(uint32_t time);
void Delay10Us(uint32_t time);
void Delay100Us(uint32_t time);

/* USER CODE BEGIN EFP */

/* USER CODE END EFP */

#ifdef __cplusplus
}
#endif

#endif /* __YUNHORN_STS_SENSORS_H__ */
