/*** 
 * @Author: mbw
 * @Date: 2024-11-30 16:46:31
 * @LastEditors: mbw && 1600520629@qq.com
 * @LastEditTime: 2025-02-21 15:32:14
 * @FilePath: \ble_bjq_ch303rct6_ml307\bsp\inc\bsp_mq.h
 * @Description: 
 * @
 * @Copyright (c) 2024 by ${git_name_email}, All Rights Reserved. 
 */
/*
 * @Author       : stark1898y 1658608470@qq.com
 * @Date         : 2023-08-02 11:49:34
 * @LastEditors  : stark1898y 1658608470@qq.com
 * @LastEditTime : 2024-06-19 09:42:35
 * @FilePath     : \wuxi_alarm_ch32v303rct6_rtt\bsp\inc\bsp_mq.h
 * @Description  :
 *
 * Copyright (c) 2023 by yzy, All Rights Reserved.
 */
#ifndef __BSP_MQ_H__
#define __BSP_MQ_H__

#include "board.h"

// MQ采样间隔
#define MQ_SAMPLING_INTERVAL_MS              (100U)

#define SENSOR_SAMPLING_TIMS (10U)

// MQ采样时间窗口
#define MQ_SAMPLING_S               (uint8_t)(3U)

// 5s 50个点 采样次数
#define MQ_SAMPLING_TIMS            (uint16_t)((1000 / MQ_SAMPLING_INTERVAL_MS) * MQ_SAMPLING_S)

// MQ_SAMPLING_TIMS
#define MQ_THRESHOLD_NORMAL_TIMS    (uint16_t)((MQ_SAMPLING_TIMS / MQ_SAMPLING_S) * (MQ_SAMPLING_S * 0.7))
#define MQ_THRESHOLD_ALARM_TIMS     (uint16_t)((MQ_SAMPLING_TIMS / MQ_SAMPLING_S) * (MQ_SAMPLING_S * 0.7))
#define MQ_THRESHOLD_FAULT_TIMS     (uint16_t)((MQ_SAMPLING_TIMS / MQ_SAMPLING_S) * (MQ_SAMPLING_S * 0.7))

// MQ传感器实际电压要放大
#define MQ_VOLTAGE_RATIO            (1.74F)

// adc voltage 1000x
#define MQ_VOLTAGE_HIGH_LIMIT       (4095U)
#define MQ_VOLTAGE_LOW_LIMIT        (100U)

#define MQ_VOLTAGE_ALARM_DEFAULT    (uint16_t)(2500U)
// 甲烷 5   VOL% = 50,000 ppm = 100 LEL;  1 LEL = 500 ppm
// 丙烷 2.2 VOL% = 22,000 ppm = 100 %LEL; 1 LEL = 220 ppm; 8 LEL = 1760 ppm; 10 LEL = 2200 ppm;

#define MQ_END_OF_LIFE_TIMS_DAYS        (uint16_t)(365 * 5 + 30 * 3)

#define GAS_SNESOR_THREAD_STACK_SIZE    (1024)
#define GAS_SENSOR_THREAD_PRIORITY      9
#define GAS_SENSOR_THREAD_TIMESLICE     5

#define MQ_EVENT_NORMAL_FLAG            (1 << 0)
#define MQ_EVENT_ALARM_FLAG             (1 << 1)
#define MQ_EVENT_END_OF_LIFE_FLAG       (1 << 2)
#define MQ_EVENT_OPEN_CIRCUIT_FLAG      (1 << 3)
#define MQ_EVENT_SHORT_CIRCUIT_FLAG     (1 << 4)
#define MQ_EVENT_CALIBRATION_FLAG       (1 << 5)
#define MQ_EVENT_FAULT_FLAG             (1 << 6)

#define MQ_EVENT_TO_BE_CALIB_FLAG       (1 << 7)

extern struct rt_event mq_event;

typedef struct __attribute__((packed))
{
    uint32_t expiration_seconds;    // 传感器到期时间，s
    uint16_t alarm_value;           // 报警器阈值

    uint8_t status_buffer[MQ_SAMPLING_TIMS];    //  采样缓存数组

    uint8_t detection_flag; // 实时检测的标志

    uint8_t end_of_life;    // 寿命到期
    uint8_t last_life;      // 上次状态
    uint8_t to_be_calib;    // 待标定
}TsSensor_t;
extern TsSensor_t Sensor_device;

typedef enum
{
    kSensorNormal = 0,
    kSensorAlarm  = 1,
    kSensorFault,
    kSensorEndOfLife,
    kSensorAbnormal,
} TeH308Status;


int BSP_MQ_Init(void);
uint16_t Get_Gas_VoltageInt1000x(void);
uint16_t Get_Gas_VoltageAdcInt1000x(void);
uint8_t IS_EndOfLife(void);


#endif // !__BSP_MQ_H__
