Программный модуль для датчика RSО-31S. v.0.19
ПО является неотъемлемой частью датчика RSО-31S, отдельно потребителю не поставляется и эксплуатируется только в составе устройства.
/**
* @file application.c
* @brief application.c реализует функционал устройства RSO-31S
* @internal
* Revision: ver 0.19
* Compiler: armcc
*
*/
/********* HEADER FILE INCLUDES *************************************************/
#include "debug_info.h"
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include "nrf.h"
#include "nrf_delay.h"
#include "nrf_gpio.h"
#include "nordic_common.h"
#include "app_error.h"
#include "nrf_soc.h"
#include "app_timer.h"
#include "app_util.h"
#include "app_util_platform.h"
#include "custom_board.h"
#include "r4s_lib.h"
#include "r4s_slave.h"
#include "r4s_slave_external.h"
#include "r4s_master.h"
#include "r4s_master_external.h"
#include "com_slave.h"
#include "com_master.h"
#include "master_control_table.h"
#include "timers_config.h"
#include "control.h"
#include "indication.h"
#include "temperature.h"
#include "temperature_service.h"
#include "event_base.h"
#include "application.h"
#include "application_api.h"
#include "custom_board.h"
#include "com_slave_extention.h"
#include "cr2032.h"
#include "com_slave_extention.h"
#include "adv_data.h"
#include "adv_data_config.h"
#include "evcal.h"
#include "calendar.h"
#include "log_service.h"
#include "cycle_buf.h"
#include "sfloat.h"
#include "battery_service.h"
#include "com_slave.h"
/********* DEFINES **************************************************************/
#define BAT_CHARGE_LIMIT 5
#define ALERT_RESET_TIMEOUT_MS (60 * 1000)
#define REED_MASK_Pos (0)
#define REMOVAL_SENSOR_MASK_Pos (1)
#define BUTTON_MASK_Pos (2)
/********* MACROS ***************************************************************/
/********* TYPES ***************************************************************/
#pragma pack(push, 1)
typedef union {
struct {
uint16_t reed_flag;
uint16_t sensors_state;
ls_sensor_removing_data_t removing;
uint16_t unused;
} val;
uint64_t data_raw;
} reed_state_data_t;
#pragma pack(pop)
/********* VARIABLES *****************************************************/
static app_state_t app_state = APP_START; /* состояние state machine*/
static bool app_test_init_success = false;
static bool app_timerout_flag = false; /* флаг timeout-a */
static bool AppPairingFl = false; /* флаг pairing*/
static bool AppUnPairingFl = false; /* флаг unpairing sound */
static reed_state_t app_reed_state = REED_STATE_OPENED;
static bool app_sw_timerout_flag = false; /* флаг timeout-a */
static bool app_alert_timerout_flag = false;
static btn_data_t btn_data;
static reed_data_t reed_data;
static sw_data_t sw_data;
static temp_trigger_t app_temp_trigger[TEMPERATURE_TRIGGER_MAX_COUNT];
static uint8_t temp_triggers_count = 0;
static float app_temp = 0;
static bool app_need_update = false;
static volatile uint8_t reed_close_count = 0;
static alert_level_t alert_level = ALERT_IDLE;
static bool alert_disabled = false;
APP_TIMER_DEF(app_timer_id);
APP_TIMER_DEF(app_sw_timer_id);
APP_TIMER_DEF(alert_timer_id);
static uint8_t app_battery_charge = 100;
static cm_dev_support_ac_t m_required_ac = {
.ac = {
AC_EXTENTION_START_CMD,
AC_EXTENTION_STOP_CMD
}
};
/********* FUNCTION PROTOTYPES **************************************************/
__STATIC_INLINE uint32_t api_temp_test_proccess(void); // функция проверки температурного датчика
__STATIC_INLINE uint32_t api_battery_test_proccess(void); // функция проверки батареи
#ifndef DEBUG_MCT
//static void application_store_state_log(uint16_t sensors_state_mask);
static void application_store_reed_log(void);
__STATIC_INLINE void application_functionality_violation_log(void);
__STATIC_INLINE void api_reset_params_at_unpairing(void);
#endif
static void api_set_alert_state(alert_level_t lvl);
static void api_master_evt_handler(com_master_evt_t * p_evt);
static void api_internal_action_process(mct_link_t *link);
/********* FUNCTIONS IMPLEMENTATION *********************************************/
__STATIC_INLINE bool api_state_check(app_state_t state)
{
return app_state == state;
}
__STATIC_INLINE void set_default() {
uint32_t err_code;
// Проверка дефолтных конфигов (не удаляемых)
mct_transaction_t * tran = NULL;
mct_searchp_context_t default_conf_search;
mct_link_t link;
static const exten_req_set_alert_t alert_on = {
.alert_level = ALERT_HIGH,
};
static const exten_req_set_alert_t alert_off = {
.alert_level = ALERT_IDLE,
};
memset(&default_conf_search, 0x00, sizeof(default_conf_search));
default_conf_search.params.filter.perm_mask = (1 << MCT_PERM_READ_MASK_pos) | (1 << MCT_PERM_UPDATE_MASK_pos);
default_conf_search.params.values.perm = MCT_PERM(MCT_PERM_ONLY_MASTER, MCT_PERM_ONLY_MASTER);
// При инициализации есть гарантия того, что ни одной транзакции открытой нет
err_code = mct_open_transaction(&tran, TRAN_READ_WRITE, TRAN_MASTER_PERM);
APP_ERROR_CHECK(err_code);
// Событие дефолтное найдено
if (mct_find_link(tran, &default_conf_search, &link) == NRF_SUCCESS){
err_code = mct_rollback(&tran);
APP_ERROR_CHECK(err_code);
} else {
memset(&link, 0x00, sizeof(link));
link.event = EVT_BINARY_SENSOR(REMOVAL_SENSOR_EVENT_CODE, REMOVAL_SENSOR_MASK_Pos, BIN_SENSOR_STATE_DETECTED);
// link.tok_id = 0;
link.ac = AC_EXTENTION_ALERT_NOTIFY;
memcpy(link.data, (uint8_t *)&alert_on, MCT_DATA_SIZE);
link.enable = 1;
link.perm = MCT_PERM(MCT_PERM_ONLY_MASTER, MCT_PERM_ONLY_MASTER);
err_code = mct_set_link(tran, &link);
APP_ERROR_CHECK(err_code);
memset(&link, 0x00, sizeof(link));
link.event = EVT_REED(REED_MASK_Pos, REED_EVENT_OPEN);
// link.tok_id = 0;
link.ac = AC_EXTENTION_ALERT_NOTIFY;
memcpy(link.data, (uint8_t *)&alert_on, MCT_DATA_SIZE);
link.enable = 1;
link.perm = MCT_PERM(MCT_PERM_ONLY_MASTER, MCT_PERM_ONLY_MASTER);
err_code = mct_set_link(tran, &link);
APP_ERROR_CHECK(err_code);
memset(&link, 0x00, sizeof(link));
link.event = EVT_REED(REED_MASK_Pos, REED_EVENT_CLOSE);
// link.tok_id = 0;
link.ac = AC_EXTENTION_ALERT_NOTIFY;
memcpy(link.data, (uint8_t *)&alert_off, MCT_DATA_SIZE);
link.enable = 1;
link.perm = MCT_PERM(MCT_PERM_ONLY_MASTER, MCT_PERM_ONLY_MASTER);
err_code = mct_set_link(tran, &link);
APP_ERROR_CHECK(err_code);
err_code = mct_commit(&tran);
APP_ERROR_CHECK(err_code);
}
}
/**@brief Функция инициализирует сенсорную кнопку
*
* @param none
*
* @return none
*/
static void app_cap_button_init(void) {
nrf_gpio_cfg_output(BUTTON_ENABLE);
}
/**@brief Функция активирует сенсорную кнопку
*
* @param none
*
* @return none
*/
static void app_cap_button_enable(void) {
nrf_gpio_pin_set(BUTTON_ENABLE);
}
/**@brief Функция деактивирует сенсорную кнопку
*
* @param none
*
* @return none
*/
static void app_cap_button_disable(void) {
nrf_gpio_pin_clear(BUTTON_ENABLE);
}
static void alert_timer_handler( void * p_context) {
app_alert_timerout_flag = true;
}
/**@brief Обработчик таймера sw.
*
* @param none
*
* @return none
*/
static void app_sw_timer_handler( void* p_context )
{
app_sw_timerout_flag = true;
}
/**@brief Обработчик таймера таймаута.
*
* @param none
*
* @return none
*/
static void app_timeout_timer_handler( void* p_context )
{
//APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_YELLOW"[APPL]: app_timeout_timer_handler\r\n"RTT_CTRL_RESET);
app_timerout_flag = true;
}
/**@brief Обработчик таймера измерения заряда.
*
* @param none
*
* @return none
*/
static void app_temp_data_handler(float *p_temp)
{
uint32_t err_code;
app_temp = *p_temp;
err_code = cr2032_read_charge_val((int16_t)app_temp, &app_battery_charge );
APP_ERROR_CHECK(err_code);
if(app_battery_charge <= BAT_CHARGE_LIMIT)
{
api_state_change(APP_BAT_LOW);
}
com_slave_send_state();
}
#ifndef DEBUG_MCT
/**
* @brief Функция вызывается при срабатывании часов (1 сек)
*
* @param none
* @return none
*
*/
static void calendar_timer_handle(void){
uint32_t err_code;
err_code = evcal_one_sec_handler();
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
}
/**
* @brief Функция вызывается при срабатывании событий из календаря
*
* @param none
* @return none
*
*/
static void evcal_calendar_task(evcal_info_packet_t const*p_data){
if(p_data == NULL) return;
uint8_t action_code = p_data->array[1];
switch(action_code)
{
case AC_EXTENTION_START_CMD:
{
exten_req_start_t *p_in_exp_pckt = (exten_req_start_t *) &p_data->array[2];
if((p_in_exp_pckt->mask & 0x1) != 0){
alert_disabled = false;
}
break;
}
case AC_EXTENTION_STOP_CMD:
{
exten_req_stop_t *p_in_exp_pckt = (exten_req_stop_t *) &p_data->array[2];
if((p_in_exp_pckt->mask & 0x1) != 0){
alert_disabled = true;
api_reset_alert_state();
}
break;
}
}
return;
}
#endif
void application_init(void)
{
uint32_t err_code;
err_code = app_timer_create ( &app_timer_id, APP_TIMER_MODE_SINGLE_SHOT, app_timeout_timer_handler );
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
err_code = app_timer_create ( &app_sw_timer_id, APP_TIMER_MODE_SINGLE_SHOT, app_sw_timer_handler );
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
err_code = app_timer_create ( &alert_timer_id, APP_TIMER_MODE_SINGLE_SHOT, alert_timer_handler );
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
#ifndef DEBUG_MCT
err_code = calendar_set_one_sec_callback(calendar_timer_handle); //установка callback часов
APP_ERROR_CHECK(err_code);
err_code = evcal_set_callback(evcal_calendar_task); //установка callback при срабатывании расписания
APP_ERROR_CHECK(err_code);
#endif
err_code = temperature_service_init(&app_temp, app_temp_data_handler);
APP_ERROR_CHECK(err_code);
app_need_update = true;
app_cap_button_init();
// Настройка com_master
com_master_set_required_ac(&m_required_ac);
com_master_set_event_handler(api_master_evt_handler);
com_master_set_internal_action_handler(api_internal_action_process);
set_default();
}
/********************************************************************************
*
********************************************************************************/
/**@brief Функция выполняет работу при выходе из соответствующего состояния
*
* @param none
*
* @return none
*/
__STATIC_INLINE void application_init_prew_state( app_state_t app_new_state )
{
static app_state_t app_prew_state = APP_START;
if( app_prew_state == app_new_state )return;
switch( app_prew_state )
{
case APP_START:
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_YELLOW"[APPL]: APP_IDLE>>\r\n"RTT_CTRL_RESET);
break;
}
case APP_WAIT_TEST:
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_YELLOW"[APPL]: APP_WAIT_TEST>>\r\n"RTT_CTRL_RESET);
app_cap_button_enable();
break;
}
case APP_TEST:
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_YELLOW"[APPL]: APP_TEST>>\r\n"RTT_CTRL_RESET);
break;
}
case APP_ACTIVE:
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_YELLOW"[APPL]: APP_ACTIVE>>\r\n"RTT_CTRL_RESET);
break;
}
case APP_PASSIVE:
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_YELLOW"[APPL]: APP_PASSIVE>>\r\n"RTT_CTRL_RESET);
break;
}
case APP_PAIRING:
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_YELLOW"[APPL]: APP_PAIRING>>\r\n"RTT_CTRL_RESET);
ind_state_change(IND_PAIRING_STOP);
com_master_pairing_stop();
com_slave_pairing_stop();
APP_ERROR_CHECK( app_timer_stop(app_timer_id));
break;
}
case APP_SLAVE_FW_UPDATE:
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_YELLOW"[APPL]: APP_SLAVE_FW_UPDATE>>\r\n"RTT_CTRL_RESET);
APP_ERROR_CHECK( app_timer_stop(app_timer_id));
ind_state_change(IND_FIRMWARE_UPDATE_STOP);
break;
}
default:
{
break;
}
}
app_prew_state = app_new_state;
return;
}
/**@brief Функция выполняет работу при входе в новое состояние
*
* @param none
*
* @return none
*/
__STATIC_INLINE void application_init_new_state( app_state_t app_new_state )
{
uint32_t err_code;
static app_state_t app_prew_state = APP_START;
if( app_prew_state == app_new_state )return;
switch( app_new_state )
{
case APP_START:
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_YELLOW"[APPL]: >>APP_IDLE\r\n"RTT_CTRL_RESET);
break;
}
case APP_WAIT_TEST:
{
app_timerout_flag = false;
err_code = app_timer_start(app_timer_id, APP_TIMER_TICKS(APP_WAIT_TEST_START_TIMEOUT_MS, APP_TIMER_PRESCALER), NULL );
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
break;
}
case APP_TEST:
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_YELLOW"[APPL]: >>APP_TEST\r\n"RTT_CTRL_RESET);
err_code = app_timer_stop(app_timer_id);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
err_code = api_temp_test_proccess();
if(err_code != NRF_SUCCESS)
{
ind_state_change(IND_TEST_FAILED);
break;
}
err_code = api_battery_test_proccess();
if(err_code != NRF_SUCCESS)
{
ind_state_change(IND_TEST_FAILED);
break;
}
ind_state_change(IND_TEST_START);
app_timerout_flag = false;
err_code = app_timer_start(app_timer_id, APP_TIMER_TICKS(APP_TEST_START_TIMEOUT_MS, APP_TIMER_PRESCALER), NULL );
#ifdef DEBUG
APP_ERROR_CHECK( err_code );
#endif
app_test_init_success = true;
break;
}
case APP_ACTIVE:
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_YELLOW"[APPL]: >>APP_ACTIVE\r\n"RTT_CTRL_RESET);
err_code = app_timer_stop(app_timer_id);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
app_timerout_flag = false;
com_slave_send_state(); //отправить нотификацию на телефон о состоянии датчика
ind_state_change(IND_ACTIVE);
#ifndef DEBUG_MCT
// if (!AppPairingFl) {
// application_store_state_log(0x1);
// }
#endif
AppPairingFl = false;
break;
}
case APP_PASSIVE:
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_YELLOW"[APPL]: >>APP_PASSIVE\r\n"RTT_CTRL_RESET);
err_code = app_timer_stop(app_timer_id);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
app_timerout_flag = false;
com_slave_send_state(); //отправить нотификацию на телефон о состоянии датчика
ind_state_change(IND_PASSIVE);
#ifndef DEBUG_MCT
// if (!AppPairingFl) {
// application_store_state_log(0x0);
// }
#endif
AppPairingFl = false;
break;
}
case APP_PAIRING:
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_YELLOW"[APPL]: >>APP_PAIRING\r\n"RTT_CTRL_RESET);
err_code = app_timer_stop(app_timer_id);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
app_timerout_flag = false;
err_code = app_timer_start(app_timer_id,APP_TIMER_TICKS(APP_PAIRING_TIMEOUT_MS, APP_TIMER_PRESCALER), NULL );
#ifdef DEBUG
APP_ERROR_CHECK( err_code );
#endif
com_slave_pairing_start();
com_master_pairing_start();
ind_state_change(IND_PAIRING_START);
break;
}
case APP_SLAVE_FW_UPDATE:
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_YELLOW"[APPL]: >>APP_SLAVE_FW_UPDATE\r\n"RTT_CTRL_RESET);
err_code = app_timer_stop(app_timer_id);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
app_timerout_flag = false;
err_code = app_timer_start(app_timer_id,APP_TIMER_TICKS(APP_FW_UPDATE_TIMEOUT_MS, APP_TIMER_PRESCALER), NULL );
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
ind_state_change(IND_FIRMWARE_UPDATE_START);
break;
}
case APP_BAT_LOW:
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_YELLOW"[APPL]: >>APP_BAT_LOW\r\n"RTT_CTRL_RESET);
ind_state_change(IND_BATTERY_LOW_START);
break;
}
default:
{
break;
}
}
app_prew_state = app_new_state;
return;
}
/********************************************************************************
*
********************************************************************************/
void application_process()
{
uint32_t err_code;
err_code = button_read( BUTTON_ID, &btn_data );
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
err_code = reed_read( REED_ID, &reed_data);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
err_code = sw_read( SW_ID, &sw_data);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
if(app_state != APP_TEST)
{
// Датчик откреплен
if(sw_data.event_open == SW_EVENT_CAPTURED)
{
err_code = app_timer_stop(app_sw_timer_id);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
if(app_sw_timerout_flag)
{
#ifndef DEBUG_MCT
application_functionality_violation_log();
#endif
com_master_prior_proccess(EVT_BINARY_SENSOR(REMOVAL_SENSOR_EVENT_CODE, REMOVAL_SENSOR_MASK_Pos, BIN_SENSOR_STATE_DETECTED));
}
}
// Датчик закреплен
if(sw_data.event_close == SW_EVENT_CAPTURED)
{
err_code = app_timer_stop(app_sw_timer_id);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
app_sw_timerout_flag = false;
err_code = app_timer_start(app_sw_timer_id, APP_TIMER_TICKS(APP_SWITCH_TIMEOUT_MS, APP_TIMER_PRESCALER), NULL );
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
}
}
switch(app_state)
{
case APP_START:
{
api_state_change(APP_WAIT_TEST);
break;
}
case APP_WAIT_TEST:
{
if (app_timerout_flag) {
ind_state_change(IND_START);
api_state_change(APP_ACTIVE);
break;
}
if (reed_data.event_close == SW_EVENT_CAPTURED) {
if(++reed_close_count == 3) {
reed_close_count = 0;
api_state_change(APP_TEST);
}
}
break;
}
case APP_TEST:
{
if(app_test_init_success)
{
if(app_timerout_flag)//прошло 60 секунд
{
ind_state_change(IND_TEST_TIMEOUT);
api_state_change(APP_ACTIVE);
break;
}
if(sw_data.event_close == SW_EVENT_CAPTURED)
{
err_code = app_timer_stop(app_timer_id);
APP_ERROR_CHECK( err_code );
app_timerout_flag = false;
err_code = app_timer_start(app_timer_id,APP_TIMER_TICKS(APP_TEST_START_TIMEOUT_MS, APP_TIMER_PRESCALER), NULL );
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
ind_state_change(IND_TEST_SWITCH);
break;
}
if(btn_data.event_press == BTN_EVENT_CAPTURED)
{
err_code = app_timer_stop(app_timer_id);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
app_timerout_flag = false;
err_code = app_timer_start(app_timer_id,APP_TIMER_TICKS(APP_TEST_START_TIMEOUT_MS, APP_TIMER_PRESCALER), NULL );
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
ind_state_change(IND_TEST_BUTTON);
break;
}
if(reed_data.event_open == REED_EVENT_CAPTURED)
{
err_code = app_timer_stop(app_timer_id);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
app_timerout_flag = false;
err_code = app_timer_start(app_timer_id,APP_TIMER_TICKS(APP_TEST_START_TIMEOUT_MS, APP_TIMER_PRESCALER), NULL );
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
ind_state_change(IND_TEST_REED);
break;
}
if(reed_data.event_close == REED_EVENT_CAPTURED)
{
err_code = app_timer_stop(app_timer_id);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
app_timerout_flag = false;
err_code = app_timer_start(app_timer_id,APP_TIMER_TICKS(APP_TEST_START_TIMEOUT_MS, APP_TIMER_PRESCALER), NULL );
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
ind_state_change(IND_TEST_REED);
break;
}
}
break;
}
case APP_PAIRING:
{
if( app_timerout_flag == true )
{
ind_state_change(IND_PAIRING_ERROR);
api_state_change(APP_ACTIVE);
}
break;
}
case APP_SLAVE_FW_UPDATE:
{
if( app_timerout_flag == true ) //таймаут обновления прошивки
{
api_state_change(APP_ACTIVE);
}
break;
}
case APP_PASSIVE:
case APP_ACTIVE:
{
if(api_state_check(APP_ACTIVE))
{
/******** TEMP **********/
api_update_triggers();
/******** REED **********/
if(reed_data.event_close==REED_EVENT_CAPTURED)
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_RED"[APPL]: REED SW CLOSED\r\n"RTT_CTRL_RESET);
com_master_prior_proccess(EVT_REED(REED_MASK_Pos, REED_EVENT_CLOSE)); // выполнение команд на ИУ согласно конфигуратору
com_slave_send_state(); //отправить нотификацию на телефон о состоянии датчика
#ifndef DEBUG_MCT
application_store_reed_log();
#endif
}
if(reed_data.event_open==REED_EVENT_CAPTURED)
{
APP_PRINTF(0,RTT_CTRL_RESET"[APPL]: REED SW OPEN\r\n"RTT_CTRL_RESET);
com_master_prior_proccess(EVT_REED(REED_MASK_Pos, REED_EVENT_OPEN)); // выполнение команд на ИУ согласно конфигуратору
com_slave_send_state(); //отправить нотификацию на телефон о состоянии датчика
#ifndef DEBUG_MCT
application_store_reed_log();
#endif
}
}
/******** BUTTON **********/
if(btn_data.event_press==BTN_EVENT_CAPTURED)
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_RED"[APPL]: BUTTON PRESSED\r\n"RTT_CTRL_RESET);
}
if (btn_data.pressed_time_ms >= APP_PAIRING_STATE_ENTER_TIME_MS
&& btn_data.pressed_time_ms < APP_UNPAIRING_STATE_ENTER_TIME_MS)
{
if(AppPairingFl==false)
{
APP_PRINTF(0,RTT_CTRL_RESET"[APPL]: BUTTON PRESSED FOR 5s\r\n"RTT_CTRL_RESET);
AppPairingFl=true;
ind_state_change(IND_PAIRING_INIT); // индикация пейрига
}
}
if (btn_data.pressed_time_ms >= APP_UNPAIRING_STATE_ENTER_TIME_MS)
{
if(AppUnPairingFl==false)
{
APP_PRINTF(0,RTT_CTRL_RESET"[APPL]: BUTTON PRESSED FOR 10s\r\n"RTT_CTRL_RESET);
AppPairingFl=false;
AppUnPairingFl=true;
ind_state_change(IND_UNPAIRING_INIT); // индикация анпейринга
}
}
if(btn_data.event_release==BTN_EVENT_CAPTURED)
{
APP_PRINTF(0,RTT_CTRL_RESET"[APPL]: BUTTON RELEASED\r\n"RTT_CTRL_RESET);
if(AppPairingFl==true)
{
api_state_change(APP_PAIRING); // переход в стейт пейринга
}
else
{
if(AppUnPairingFl==true)
{
AppUnPairingFl=false;
com_slave_unpair_proccess(); // анпейринг на слейве
com_master_unpairing(); // анпейринг на мастере
#ifndef DEBUG_MCT
api_reset_params_at_unpairing();
#endif
ind_state_change(IND_UNPAIRING_SUCCESS);
app_need_update = true;
} else if(api_state_check(APP_ACTIVE)) {
com_master_proccess(EVT_BTN_PRESSED(BUTTON_MASK_Pos, BTN_CLICK_SINGLE));
}
}
}
break;
}
case APP_BAT_LOW:
{
break;
}
default:
{
APP_PRINTF(0,RTT_CTRL_TEXT_BRIGHT_YELLOW"[APPL]: default\r\n"RTT_CTRL_RESET);
api_state_change(APP_ACTIVE);
break;
}
}
if(app_need_update) api_param_update();
if (app_alert_timerout_flag) {
app_alert_timerout_flag = false;
api_reset_alert_state();
}
// Если все в расписании выключено или удалено, то включаем триггеры
err_code = evcal_add_transaction(EVCAL_TRANSACTION_READ);
if (err_code == NRF_SUCCESS) {
uint8_t count = 0;
evcal_task_t task;
bool is_any_enabled = false;
evcal_get_task_number(&count);
for (uint8_t i = 0; i < count; i++) {
evcal_get_task_data(i, &task);
if (task.enable) {
is_any_enabled = true;
}
}
if (!is_any_enabled) {
alert_disabled = false;
}
evcal_dec_transaction(EVCAL_COMMIT_TRANSACTION);
}
}
/********************************************************************************
*
********************************************************************************/
/********************************************************************************
*
********************************************************************************/
/**
* описание в application_api.h
*/
/***************************COMMON************************************/
void api_slave_set_connection_flag(void) {
if(app_state == APP_PAIRING)
{
uint32_t err_code;
err_code = app_timer_stop(app_timer_id);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
}
}
void api_slave_clear_connection_flag(void) {
if( app_state == APP_PAIRING ) {
ind_state_change(IND_PAIRING_ERROR);
api_state_change(APP_ACTIVE);
}
//выйти из режимов управления камерой или перепрошивки если в них находимся
if(app_state == APP_SLAVE_FW_UPDATE)
{
api_state_change(APP_ACTIVE);
}
}
void api_state_change(app_state_t new_state)
{
app_state = new_state;
application_init_prew_state( app_state );
application_init_new_state( app_state );
}
uint8_t api_get_state(void)
{
switch(app_state)
{
case APP_PASSIVE:
{
return APP_API_PASSIVE_STATE;
}
case APP_SLAVE_FW_UPDATE:
{
return APP_API_FW_UPDATE_STATE;
}
case APP_ACTIVE:
{
return APP_API_STAND_BY_STATE;
}
case APP_BAT_LOW:
{
return APP_API_ERROR_STATE;
}
case APP_PAIRING:
return APP_API_PAIRING_STATE;
default:
{
return APP_API_ERROR_STATE;
}
}
}
void api_update_triggers(void) {
temp_event_check(app_temp_trigger, temp_triggers_count);
for(uint8_t i=0; i<temp_triggers_count;i++) {
temp_trigger_t * p_this_trigger = &app_temp_trigger[i];
if(p_this_trigger->temp_state == TRIGGER_CAPTURED)
{
com_master_proccess(p_this_trigger->com_event);
p_this_trigger->temp_state = TRIGGER_PROCESSED;
}
}
}
void api_reset_alert_state() {
api_set_alert_state(ALERT_IDLE);
}
static void api_set_alert_state(alert_level_t lvl) {
if (alert_disabled) {
alert_level = ALERT_IDLE;
} else {
alert_level = lvl;
}
if (alert_level == ALERT_IDLE) {
app_advertising_set_alert_state(false);
} else {
app_advertising_set_alert_state(true);
}
}
void api_get_alert_state(uint8_t *p_lvl) {
*p_lvl = alert_level;
}
static void api_internal_action_process(mct_link_t *link) {
switch(link->ac){
case AC_EXTENTION_ALERT_NOTIFY:{
exten_req_set_alert_t *p_alert = (exten_req_set_alert_t *) link->data;
// Сброс флага только в течение 2-х минут
if (p_alert->alert_level == ALERT_IDLE) {
uint32_t err_code = app_timer_stop(alert_timer_id);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
err_code = app_timer_start(alert_timer_id, APP_TIMER_TICKS(ALERT_RESET_TIMEOUT_MS, APP_TIMER_PRESCALER), NULL);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
} else {
uint32_t err_code = app_timer_stop(alert_timer_id);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
api_set_alert_state(p_alert->alert_level);
}
break;
}
default: // неизвестный action code
break;
}
}
void api_param_update(void)
{
uint32_t err_code;
temp_triggers_count = 0;
err_code = temp_param_update(app_temp_trigger, &temp_triggers_count);
if(err_code != NRF_ERROR_BUSY)
{
app_need_update = false;
}
}
uint8_t api_get_battery_charge(void)
{
return app_battery_charge;
}
/**
* описание в application_api.h
*/
uint16_t api_get_temp(void)
{
return FloatToSFloat16(app_temp);
}
////////////////////////////////////////////////////////////////
/**
* описание в application_api.h
*/
uint8_t api_set_calendar_data(void *timestamp, void *shift)
{
calendar_utc_t m_time_stamp = 0;
calendar_shift_utc_t m_shift = 0;
m_time_stamp = uint32_decode(timestamp); //преобразуем данные массива в uint32_t
m_shift = uint32_decode(shift); //преобразуем данные массива в uint32_t
uint32_t err_code = calendar_set_time(m_time_stamp, m_shift);
switch (err_code)
{
case NRF_SUCCESS:
return ERSP_SUCCESS;
case NRF_ERROR_INVALID_DATA:
return ERSP_ERROR_INVALID_DATA;
case DRIVER_MODULE_NOT_INITIALZED:
return ERSP_ERROR_INTERNAL;
}
return ERSP_ERROR_UNKNOWN;
}
/**
* описание в application_api.h
*/
void api_get_calendar_data(void *timestamp, void *shift)
{
calendar_utc_t m_time_stamp = 0;
calendar_shift_utc_t m_shift = 0;
//получаем данные о текущем UTC и времени сдвига
uint32_t err_code = calendar_get_utc_time(&m_time_stamp, &m_shift);
APP_ERROR_CHECK(err_code);
memcpy(timestamp, &m_time_stamp, sizeof(calendar_utc_t));
memcpy(shift, &m_shift, sizeof(calendar_shift_utc_t));
}
/**
* @brief Возвращает состояние датчика.
*
*/
uint8_t api_reed_state_get(void)
{
if(api_state_check(APP_ACTIVE))
{
app_reed_state = reed_data.state;
}
return app_reed_state;
}
__STATIC_INLINE uint32_t api_temp_test_proccess(void)
{
if(app_temp >= 10 && app_temp <= 60)
{
return NRF_SUCCESS;
}
return NRF_ERROR_INVALID_STATE;
}
__STATIC_INLINE uint32_t api_battery_test_proccess(void)
{
uint32_t err_code;
err_code = cr2032_read_charge_val((int16_t)app_temp, &app_battery_charge );
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
if(app_battery_charge > 0)
{
return NRF_SUCCESS;
}
return NRF_ERROR_NOT_FOUND;
}
#ifndef DEBUG_MCT
__STATIC_INLINE void api_reset_params_at_unpairing( void )
{
//события календаря (до этого уже должны быть очищены все транзакции)
if (evcal_add_transaction(EVCAL_TRANSACTION_WRITE) == NRF_SUCCESS) {
evcal_erase_all_tasks();
evcal_dec_transaction(EVCAL_COMMIT_TRANSACTION);
}
alert_disabled = false;
}
/*
static void application_store_state_log(uint16_t sensors_state_mask) {
calendar_utc_t utc = 0;
calendar_shift_utc_t shift = 0;
//получаем данные о текущем UTC и времени сдвига
APP_ERROR_CHECK(calendar_get_utc_time(&utc, &shift));
if (utc == 0) {// Время не установлено или не верное, не логировать
return;
}
// Упаковка данных
reed_state_data_t pack =
{
.val = {
.sensors_state = sensors_state_mask,
},
};
cb_data_t record = {
.id = LS_ID_COMPLEX_SENSORS_MODE,
.utc = utc,
.data = pack.data_raw,
};
APP_ERROR_CHECK(cb_put(&record));
}
*/
static void application_store_reed_log(void) {
cb_data_t record;
calendar_utc_t utc = 0;
calendar_shift_utc_t shift = 0;
//получаем данные о текущем UTC и времени сдвига
APP_ERROR_CHECK(calendar_get_utc_time(&utc, &shift));
if (utc == 0) {// Время не установлено или не верное, не логировать
return;
}
// Упаковка данных
reed_state_data_t pack =
{
.val = {
.reed_flag = api_reed_state_get(),
},
};
record.id = LS_ID_COMPLEX_REED;
record.utc = utc;
record.data = pack.data_raw;
APP_ERROR_CHECK(cb_put(&record));
}
__STATIC_INLINE void application_functionality_violation_log(void) {
cb_data_t record;
calendar_utc_t utc = 0;
calendar_shift_utc_t shift = 0;
//получаем данные о текущем UTC и времени сдвига
APP_ERROR_CHECK(calendar_get_utc_time(&utc, &shift));
if (utc == 0) {// Время не установлено или не верное, не логировать
return;
}
// Упаковка данных
reed_state_data_t pack =
{
.val = {
.removing.fields = {
// Тип нарушения - снятие датчика
.reserved_must_be_zero = 0,
},
},
};
record.id = LS_ID_SENSOR_REMOVING;
record.utc = utc;
record.data = pack.data_raw;
APP_ERROR_CHECK(cb_put(&record));
}
#endif
/********************************************************************************/
/***************************PERIPHERAL************************************/
uint8_t api_get_error(void)
{
switch(app_state)
{
case APP_BAT_LOW:
return APP_API_BATTERY_LOW_ERROR;
default:
return APP_API_NO_ERROR;
}
}
uint8_t api_enter_fw_update_state(void)
{
if((app_state == APP_ACTIVE)
|| (app_state == APP_PASSIVE)
||( app_state == APP_SLAVE_FW_UPDATE))
{
api_state_change(APP_SLAVE_FW_UPDATE);
return 1;
}
return 0;
}
void api_fw_update_proc(void)
{
if( app_state == APP_SLAVE_FW_UPDATE )
{
uint32_t err_code;
err_code = app_timer_stop(app_timer_id);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
err_code = app_timer_start(app_timer_id,APP_TIMER_TICKS(APP_FW_UPDATE_TIMEOUT_MS, APP_TIMER_PRESCALER), NULL );
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
}
}
uint8_t api_go_to_stand_by(void)
{
if(( app_state != APP_ACTIVE)
&& ( app_state != APP_PAIRING )
&& ( app_state != APP_SLAVE_FW_UPDATE ))
{
return 0;
}
if( ( app_state == APP_PAIRING )
|| ( app_state == APP_SLAVE_FW_UPDATE ))
{
api_state_change(APP_ACTIVE);
}
return 1;
}
void r4s_slave_pairing_success( void )
{
if( app_state == APP_PAIRING ) {
ind_state_change(IND_PAIRING_SUCCESS);
api_state_change(APP_ACTIVE);
}
}
/********************************************************************************/
/***************************CENTRAL************************************/
/********************************************************************************/
__STATIC_INLINE void set_default_config(uint8_t tok_id, cm_dev_support_ac_t * required_ac) {
mct_transaction_t * tran = NULL;
mct_link_t link;
mct_searchp_context_t search;
memset(&search, 0, sizeof(mct_searchp_context_t));
uint32_t err_code;
APP_PRINTF(0, RTT_CTRL_TEXT_BRIGHT_GREEN"[APPL]: api_master_pairing_complete\r\n"RTT_CTRL_RESET);
if (required_ac->is_support[0] && required_ac->is_support[1]){
// Тип транзакции READ_WRITE не рекомендуется использовать, если не будет гарантированной записи
// иначе пока транзакция не будет закрыта остальные транзакции не возможны
err_code = mct_open_transaction(&tran, TRAN_READ_WRITE, TRAN_COMMON_PERM);
if (err_code != NRF_ERROR_BUSY){
APP_ERROR_CHECK(err_code);
memset(&link, 0, sizeof(mct_link_t));
link.tok_id = tok_id;
link.event = EVT_REED(REED_MASK_Pos, REED_EVENT_OPEN);
link.ac = AC_EXTENTION_START_CMD;
link.data[0]=0xFF;
link.data[1]=0xFF;
link.enable = 0x01;
link.uuid = 0;
err_code = mct_set_link(tran, &link);
if (err_code != NRF_ERROR_NO_MEM)
APP_ERROR_CHECK(err_code);
memset(&link, 0, sizeof(mct_link_t));
link.tok_id = tok_id;
link.event = EVT_REED(REED_MASK_Pos, REED_EVENT_CLOSE);
link.ac = AC_EXTENTION_STOP_CMD;
link.data[0]=0xFF;
link.data[1]=0xFF;
link.enable = 0x01;
link.uuid = 0;
err_code = mct_set_link(tran, &link);
if (err_code != NRF_ERROR_NO_MEM)
APP_ERROR_CHECK(err_code);
err_code = mct_commit(&tran);
#ifdef DEBUG
APP_ERROR_CHECK(err_code);
#endif
}
}
}
static void api_master_evt_handler(com_master_evt_t * p_evt) {
switch (p_evt->id) {
case COM_MASTER_PAIRING_SUCCESS:{
ind_state_change(IND_PAIRING_SUCCESS);
api_state_change(APP_ACTIVE);
break;
}
case COM_MASTER_PAIRING_ERROR: {
ind_state_change(IND_PAIRING_ERROR);
api_state_change(APP_ACTIVE);
break;
}
case COM_MASTER_DEFAULT_CONFIG_REQUIRED:{
set_default_config(
p_evt->param.default_config_required.tok_id,
p_evt->param.default_config_required.p_required_ac
);
break;
}
}
}
/*****************************************************************************************************/