初始版本

This commit is contained in:
xiaozhengsheng 2025-08-19 09:49:41 +08:00
parent 10f1ddf1c1
commit 6df0f7d96e
2974 changed files with 1712873 additions and 54 deletions

83
.gitignore vendored
View File

@ -1,54 +1,33 @@
# ---> C
# Prerequisites
*.d
# This is comment, and ignored by git.
# Object files
*.o
*.ko
*.obj
*.elf
# Linker output
*.ilk
*.map
*.exp
# Precompiled Headers
*.gch
*.pch
# Libraries
*.lib
*.a
*.la
*.lo
# Shared objects (inc. Windows DLLs)
*.dll
*.so
*.so.*
*.dylib
# Executables
*.orig
*.exe
*.out
*.app
*.i*86
*.x86_64
*.hex
# Debug files
*.dSYM/
*.su
*.idb
*.pdb
# Kernel Module Compile Results
*.mod*
*.cmd
.tmp_versions/
modules.order
Module.symvers
Mkfile.old
dkms.conf
*.o
*.bak
*.ddk
*.edk
*.lst
*.lnp
*.mpf
*.mpj
*.obj
*.omf
*.opt
*.plg
*.rpt
*.tmp
*.__i
*.crf
*.o
*.d
*.axf
*.tra
*.dep
*.iex
*.htm
*.sct
*.map
JLinkLog.txt
*.bkp
*.dtmp
~*

12
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,12 @@
{
"files.associations": {
"nrf_drv_ppi.h": "c",
"drv_saadc.h": "c",
"bsp_btn_ble.h": "c",
"nrf_delay.h": "c",
"timer.h": "c",
"drv_uart.h": "c",
"nrf_drv_saadc.h": "c"
},
"cmake.sourceDirectory": "F:/work/HL-PDJ-1_PelvicFloor/external/mbedtls"
}

144
DSP_LIB/IIR.c Normal file
View File

@ -0,0 +1,144 @@
#include "IIR.h"
#include "arm_math.h"
#include "arm_const_structs.h"
//Log需要引用的头文件
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#define bp_numStages 1 /* 2阶IIR滤波的个数 */
#define bs_numStages 2 /* 2阶IIR滤波的个数 */
#define BLOCK_SIZE 1 /* 调用一次arm_biquad_cascade_df1_f32处理的采样点个数 */
uint32_t blockSize = BLOCK_SIZE;
static float32_t IIRStateF32_bp[4*bp_numStages]; /* 带通滤波器状态缓存 */
static float32_t IIRStateF32_bs[4*bs_numStages]; /* 带阻滤波器状态缓存 */
arm_biquad_casd_df1_inst_f32 S_BS;
arm_biquad_casd_df1_inst_f32 S_BP;
float32_t bpScaleValue;
float32_t bsScaleValue;
/* Elliptic带通滤波器系数20Hz 500Hz*/
const float32_t IIRCoeffs32BP[5*bp_numStages] = {
1.0f, 0, -1.0f, 0.638776097661321373699649939226219430566f, 0.339488565819422882796629892254713922739f
};
/* 巴特沃斯带阻滤波器系数48Hz 52Hz*/
const float32_t IIRCoeffs32BS[5*bs_numStages] = {
1.0f, -1.975854434025588135526163569011259824038f, 1.0f, 1.937393708057424390744927222840487957001f, -0.966392678521233783328625577269122004509f,
1.0f, -1.975854434025588135526163569011259824038f, 1.0f, 1.952884644070242314839447317353915423155f, -0.972373462682551759073135144717525690794f
};
void arm_iir_f32_bs(void)
{
/* 初始化 */
arm_biquad_cascade_df1_init_f32(&S_BS, bs_numStages, (float32_t *)&IIRCoeffs32BS[0], (float32_t *)&IIRStateF32_bs[0]);
/*放缩系数 */
bsScaleValue = 0.984570131944842996674083224206697195768f*0.984570131944842996674083224206697195768f;
}
void bs_bp(float32_t *bpinputF32_IN,float32_t *bsoutputF32_IN)
{
float32_t bpoutputF32_IN __attribute__((aligned(4)));
arm_biquad_cascade_df1_f32(&S_BP, bpinputF32_IN, &bpoutputF32_IN, blockSize);
bpoutputF32_IN = (bpoutputF32_IN)*bpScaleValue;
arm_biquad_cascade_df1_f32(&S_BS, &bpoutputF32_IN, bsoutputF32_IN, blockSize);
*bsoutputF32_IN = (*bsoutputF32_IN)*bsScaleValue;
}
/*
*********************************************************************************************************
* : arm_iir_f32_bp
* : arm_iir_f32_hp实现带通滤波器
*
* :
*********************************************************************************************************
*/
void arm_iir_f32_bp(void)
{
/* 初始化 */
arm_biquad_cascade_df1_init_f32(&S_BP, bp_numStages, (float32_t *)&IIRCoeffs32BP[0], (float32_t *)&IIRStateF32_bp[0]);
/*放缩系数 */
bpScaleValue = 0.66974428290971144139831494612735696137f;
}
#define TEST_LENGTH_SAMPLES 400 /* 采样点数 */
//static float32_t testInput_f32_50Hz_200Hz[TEST_LENGTH_SAMPLES]; /* 采样点 */
//static float32_t testOutput_f32_50Hz_200Hz[TEST_LENGTH_SAMPLES];
float math_caculate_signal(uint16_t sampleHz)
{
static uint16_t i = 0;
float singalOutput;
/* 50Hz正弦波 + 200Hz正弦波 */
singalOutput = arm_sin_f32(2 * 3.1415926f * 50 * i / sampleHz) +
arm_sin_f32(2 * 3.1415926f * 200 * i / sampleHz);
/* 归零逻辑当i达到一个完整周期的采样点数时 */
if (++i >= (sampleHz / 50)) {
i = 0;
}
return singalOutput;
}
void FilterInit()
{
arm_iir_f32_bs(); // 带阻滤波器
arm_iir_f32_bp(); // 带通滤波器
////test code
// CreateData();
//
// for (int i = 0; i < TEST_LENGTH_SAMPLES; i++)
// {
// arm_biquad_cascade_df1_f32(&S_BS, &testInput_f32_50Hz_200Hz[i], &testOutput_f32_50Hz_200Hz[i], 1);
// }
/*
NRF_LOG_INFO("raw\r\n");
char stf[10];
for (int i = 0; i < TEST_LENGTH_SAMPLES; i++)
{
sprintf(stf,"%0.3f", testInput_f32_50Hz_200Hz[i]);
NRF_LOG_INFO("%s",stf);
if (NRF_LOG_PROCESS() == false) //处理挂起的log
{
}
}
NRF_LOG_INFO("proccess\r\n");
NRF_LOG_PROCESS();
arm_biquad_cascade_df1_f32(&S_BS, testInput_f32_50Hz_200Hz, testOutput_f32_50Hz_200Hz, TEST_LENGTH_SAMPLES);
for (int i = 0; i < TEST_LENGTH_SAMPLES; i++)
{
sprintf(stf,"%0.3f", testOutput_f32_50Hz_200Hz[i]);
NRF_LOG_INFO("%s",stf);
if (NRF_LOG_PROCESS() == false) //处理挂起的log
{
}
}
while(1)
{
NRF_LOG_PROCESS();
}
*/
//处理挂起的log
//////end
}

20
DSP_LIB/IIR.h Normal file
View File

@ -0,0 +1,20 @@
#ifndef _IIR_H_
#define _IIR_H_
#include <stdbool.h>
#include <stdint.h>
#include "nrf.h"
#include "string.h"
#include "arm_math.h"
void FilterInit(void);
void arm_iir_f32_bs(void);
void arm_iir_f32_bp(void);
void bs_bp(float32_t *bpinputF32_IN,float32_t *bsoutputF32_IN);
float math_caculate_signal(uint16_t sampleHz);
#endif

View File

@ -0,0 +1,136 @@
/* ----------------------------------------------------------------------
* Copyright (C) 2010-2014 ARM Limited. All rights reserved.
*
* $Date: 19. March 2015
* $Revision: V.1.4.5
*
* Project: CMSIS DSP Library
* Title: arm_common_tables.h
*
* Description: This file has extern declaration for common tables like Bitreverse, reciprocal etc which are used across different functions
*
* Target Processor: Cortex-M4/Cortex-M3
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* - Neither the name of ARM LIMITED nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* -------------------------------------------------------------------- */
#ifndef _ARM_COMMON_TABLES_H
#define _ARM_COMMON_TABLES_H
#include "arm_math.h"
extern const uint16_t armBitRevTable[1024];
extern const q15_t armRecipTableQ15[64];
extern const q31_t armRecipTableQ31[64];
//extern const q31_t realCoefAQ31[1024];
//extern const q31_t realCoefBQ31[1024];
extern const float32_t twiddleCoef_16[32];
extern const float32_t twiddleCoef_32[64];
extern const float32_t twiddleCoef_64[128];
extern const float32_t twiddleCoef_128[256];
extern const float32_t twiddleCoef_256[512];
extern const float32_t twiddleCoef_512[1024];
extern const float32_t twiddleCoef_1024[2048];
extern const float32_t twiddleCoef_2048[4096];
extern const float32_t twiddleCoef_4096[8192];
#define twiddleCoef twiddleCoef_4096
extern const q31_t twiddleCoef_16_q31[24];
extern const q31_t twiddleCoef_32_q31[48];
extern const q31_t twiddleCoef_64_q31[96];
extern const q31_t twiddleCoef_128_q31[192];
extern const q31_t twiddleCoef_256_q31[384];
extern const q31_t twiddleCoef_512_q31[768];
extern const q31_t twiddleCoef_1024_q31[1536];
extern const q31_t twiddleCoef_2048_q31[3072];
extern const q31_t twiddleCoef_4096_q31[6144];
extern const q15_t twiddleCoef_16_q15[24];
extern const q15_t twiddleCoef_32_q15[48];
extern const q15_t twiddleCoef_64_q15[96];
extern const q15_t twiddleCoef_128_q15[192];
extern const q15_t twiddleCoef_256_q15[384];
extern const q15_t twiddleCoef_512_q15[768];
extern const q15_t twiddleCoef_1024_q15[1536];
extern const q15_t twiddleCoef_2048_q15[3072];
extern const q15_t twiddleCoef_4096_q15[6144];
extern const float32_t twiddleCoef_rfft_32[32];
extern const float32_t twiddleCoef_rfft_64[64];
extern const float32_t twiddleCoef_rfft_128[128];
extern const float32_t twiddleCoef_rfft_256[256];
extern const float32_t twiddleCoef_rfft_512[512];
extern const float32_t twiddleCoef_rfft_1024[1024];
extern const float32_t twiddleCoef_rfft_2048[2048];
extern const float32_t twiddleCoef_rfft_4096[4096];
/* floating-point bit reversal tables */
#define ARMBITREVINDEXTABLE__16_TABLE_LENGTH ((uint16_t)20 )
#define ARMBITREVINDEXTABLE__32_TABLE_LENGTH ((uint16_t)48 )
#define ARMBITREVINDEXTABLE__64_TABLE_LENGTH ((uint16_t)56 )
#define ARMBITREVINDEXTABLE_128_TABLE_LENGTH ((uint16_t)208 )
#define ARMBITREVINDEXTABLE_256_TABLE_LENGTH ((uint16_t)440 )
#define ARMBITREVINDEXTABLE_512_TABLE_LENGTH ((uint16_t)448 )
#define ARMBITREVINDEXTABLE1024_TABLE_LENGTH ((uint16_t)1800)
#define ARMBITREVINDEXTABLE2048_TABLE_LENGTH ((uint16_t)3808)
#define ARMBITREVINDEXTABLE4096_TABLE_LENGTH ((uint16_t)4032)
extern const uint16_t armBitRevIndexTable16[ARMBITREVINDEXTABLE__16_TABLE_LENGTH];
extern const uint16_t armBitRevIndexTable32[ARMBITREVINDEXTABLE__32_TABLE_LENGTH];
extern const uint16_t armBitRevIndexTable64[ARMBITREVINDEXTABLE__64_TABLE_LENGTH];
extern const uint16_t armBitRevIndexTable128[ARMBITREVINDEXTABLE_128_TABLE_LENGTH];
extern const uint16_t armBitRevIndexTable256[ARMBITREVINDEXTABLE_256_TABLE_LENGTH];
extern const uint16_t armBitRevIndexTable512[ARMBITREVINDEXTABLE_512_TABLE_LENGTH];
extern const uint16_t armBitRevIndexTable1024[ARMBITREVINDEXTABLE1024_TABLE_LENGTH];
extern const uint16_t armBitRevIndexTable2048[ARMBITREVINDEXTABLE2048_TABLE_LENGTH];
extern const uint16_t armBitRevIndexTable4096[ARMBITREVINDEXTABLE4096_TABLE_LENGTH];
/* fixed-point bit reversal tables */
#define ARMBITREVINDEXTABLE_FIXED___16_TABLE_LENGTH ((uint16_t)12 )
#define ARMBITREVINDEXTABLE_FIXED___32_TABLE_LENGTH ((uint16_t)24 )
#define ARMBITREVINDEXTABLE_FIXED___64_TABLE_LENGTH ((uint16_t)56 )
#define ARMBITREVINDEXTABLE_FIXED__128_TABLE_LENGTH ((uint16_t)112 )
#define ARMBITREVINDEXTABLE_FIXED__256_TABLE_LENGTH ((uint16_t)240 )
#define ARMBITREVINDEXTABLE_FIXED__512_TABLE_LENGTH ((uint16_t)480 )
#define ARMBITREVINDEXTABLE_FIXED_1024_TABLE_LENGTH ((uint16_t)992 )
#define ARMBITREVINDEXTABLE_FIXED_2048_TABLE_LENGTH ((uint16_t)1984)
#define ARMBITREVINDEXTABLE_FIXED_4096_TABLE_LENGTH ((uint16_t)4032)
extern const uint16_t armBitRevIndexTable_fixed_16[ARMBITREVINDEXTABLE_FIXED___16_TABLE_LENGTH];
extern const uint16_t armBitRevIndexTable_fixed_32[ARMBITREVINDEXTABLE_FIXED___32_TABLE_LENGTH];
extern const uint16_t armBitRevIndexTable_fixed_64[ARMBITREVINDEXTABLE_FIXED___64_TABLE_LENGTH];
extern const uint16_t armBitRevIndexTable_fixed_128[ARMBITREVINDEXTABLE_FIXED__128_TABLE_LENGTH];
extern const uint16_t armBitRevIndexTable_fixed_256[ARMBITREVINDEXTABLE_FIXED__256_TABLE_LENGTH];
extern const uint16_t armBitRevIndexTable_fixed_512[ARMBITREVINDEXTABLE_FIXED__512_TABLE_LENGTH];
extern const uint16_t armBitRevIndexTable_fixed_1024[ARMBITREVINDEXTABLE_FIXED_1024_TABLE_LENGTH];
extern const uint16_t armBitRevIndexTable_fixed_2048[ARMBITREVINDEXTABLE_FIXED_2048_TABLE_LENGTH];
extern const uint16_t armBitRevIndexTable_fixed_4096[ARMBITREVINDEXTABLE_FIXED_4096_TABLE_LENGTH];
/* Tables for Fast Math Sine and Cosine */
extern const float32_t sinTable_f32[FAST_MATH_TABLE_SIZE + 1];
extern const q31_t sinTable_q31[FAST_MATH_TABLE_SIZE + 1];
extern const q15_t sinTable_q15[FAST_MATH_TABLE_SIZE + 1];
#endif /* ARM_COMMON_TABLES_H */

View File

@ -0,0 +1,79 @@
/* ----------------------------------------------------------------------
* Copyright (C) 2010-2014 ARM Limited. All rights reserved.
*
* $Date: 19. March 2015
* $Revision: V.1.4.5
*
* Project: CMSIS DSP Library
* Title: arm_const_structs.h
*
* Description: This file has constant structs that are initialized for
* user convenience. For example, some can be given as
* arguments to the arm_cfft_f32() function.
*
* Target Processor: Cortex-M4/Cortex-M3
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* - Neither the name of ARM LIMITED nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* -------------------------------------------------------------------- */
#ifndef _ARM_CONST_STRUCTS_H
#define _ARM_CONST_STRUCTS_H
#include "arm_math.h"
#include "arm_common_tables.h"
extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len16;
extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len32;
extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len64;
extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len128;
extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len256;
extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len512;
extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len1024;
extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len2048;
extern const arm_cfft_instance_f32 arm_cfft_sR_f32_len4096;
extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len16;
extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len32;
extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len64;
extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len128;
extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len256;
extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len512;
extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len1024;
extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len2048;
extern const arm_cfft_instance_q31 arm_cfft_sR_q31_len4096;
extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len16;
extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len32;
extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len64;
extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len128;
extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len256;
extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len512;
extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len1024;
extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len2048;
extern const arm_cfft_instance_q15 arm_cfft_sR_q15_len4096;
#endif

7556
DSP_LIB/Include/arm_math.h Normal file

File diff suppressed because it is too large Load Diff

740
DSP_LIB/Include/core_cm0.h Normal file
View File

@ -0,0 +1,740 @@
/**************************************************************************//**
* @file core_cm0.h
* @brief CMSIS Cortex-M0 Core Peripheral Access Layer Header File
* @version V4.10
* @date 18. March 2015
*
* @note
*
******************************************************************************/
/* Copyright (c) 2009 - 2015 ARM LIMITED
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of ARM nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
*
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
#if defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#endif
#ifndef __CORE_CM0_H_GENERIC
#define __CORE_CM0_H_GENERIC
#ifdef __cplusplus
extern "C" {
#endif
/** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions
CMSIS violates the following MISRA-C:2004 rules:
\li Required Rule 8.5, object/function definition in header file.<br>
Function definitions in header files are used to allow 'inlining'.
\li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
Unions are used for effective representation of core registers.
\li Advisory Rule 19.7, Function-like macro defined.<br>
Function-like macros are used to allow more efficient code.
*/
/*******************************************************************************
* CMSIS definitions
******************************************************************************/
/** \ingroup Cortex_M0
@{
*/
/* CMSIS CM0 definitions */
#define __CM0_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */
#define __CM0_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */
#define __CM0_CMSIS_VERSION ((__CM0_CMSIS_VERSION_MAIN << 16) | \
__CM0_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */
#define __CORTEX_M (0x00) /*!< Cortex-M Core */
#if defined ( __CC_ARM )
#define __ASM __asm /*!< asm keyword for ARM Compiler */
#define __INLINE __inline /*!< inline keyword for ARM Compiler */
#define __STATIC_INLINE static __inline
#elif defined ( __GNUC__ )
#define __ASM __asm /*!< asm keyword for GNU Compiler */
#define __INLINE inline /*!< inline keyword for GNU Compiler */
#define __STATIC_INLINE static inline
#elif defined ( __ICCARM__ )
#define __ASM __asm /*!< asm keyword for IAR Compiler */
#define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */
#define __STATIC_INLINE static inline
#elif defined ( __TMS470__ )
#define __ASM __asm /*!< asm keyword for TI CCS Compiler */
#define __STATIC_INLINE static inline
#elif defined ( __TASKING__ )
#define __ASM __asm /*!< asm keyword for TASKING Compiler */
#define __INLINE inline /*!< inline keyword for TASKING Compiler */
#define __STATIC_INLINE static inline
#elif defined ( __CSMC__ )
#define __packed
#define __ASM _asm /*!< asm keyword for COSMIC Compiler */
#define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */
#define __STATIC_INLINE static inline
#endif
/** __FPU_USED indicates whether an FPU is used or not.
This core does not support an FPU at all
*/
#define __FPU_USED 0
#if defined ( __CC_ARM )
#if defined __TARGET_FPU_VFP
#warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __GNUC__ )
#if defined (__VFP_FP__) && !defined(__SOFTFP__)
#warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __ICCARM__ )
#if defined __ARMVFP__
#warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __TMS470__ )
#if defined __TI__VFP_SUPPORT____
#warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __TASKING__ )
#if defined __FPU_VFP__
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __CSMC__ ) /* Cosmic */
#if ( __CSMC__ & 0x400) // FPU present for parser
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#endif
#include <stdint.h> /* standard types definitions */
#include <core_cmInstr.h> /* Core Instruction Access */
#include <core_cmFunc.h> /* Core Function Access */
#ifdef __cplusplus
}
#endif
#endif /* __CORE_CM0_H_GENERIC */
#ifndef __CMSIS_GENERIC
#ifndef __CORE_CM0_H_DEPENDANT
#define __CORE_CM0_H_DEPENDANT
#ifdef __cplusplus
extern "C" {
#endif
/* check device defines and use defaults */
#if defined __CHECK_DEVICE_DEFINES
#ifndef __CM0_REV
#define __CM0_REV 0x0000
#warning "__CM0_REV not defined in device header file; using default!"
#endif
#ifndef __NVIC_PRIO_BITS
#define __NVIC_PRIO_BITS 2
#warning "__NVIC_PRIO_BITS not defined in device header file; using default!"
#endif
#ifndef __Vendor_SysTickConfig
#define __Vendor_SysTickConfig 0
#warning "__Vendor_SysTickConfig not defined in device header file; using default!"
#endif
#endif
/* IO definitions (access restrictions to peripheral registers) */
/**
\defgroup CMSIS_glob_defs CMSIS Global Defines
<strong>IO Type Qualifiers</strong> are used
\li to specify the access to peripheral variables.
\li for automatic generation of peripheral register debug information.
*/
#ifdef __cplusplus
#define __I volatile /*!< Defines 'read only' permissions */
#else
#define __I volatile const /*!< Defines 'read only' permissions */
#endif
#define __O volatile /*!< Defines 'write only' permissions */
#define __IO volatile /*!< Defines 'read / write' permissions */
/*@} end of group Cortex_M0 */
/*******************************************************************************
* Register Abstraction
Core Register contain:
- Core Register
- Core NVIC Register
- Core SCB Register
- Core SysTick Register
******************************************************************************/
/** \defgroup CMSIS_core_register Defines and Type Definitions
\brief Type definitions and defines for Cortex-M processor based devices.
*/
/** \ingroup CMSIS_core_register
\defgroup CMSIS_CORE Status and Control Registers
\brief Core Register type definitions.
@{
*/
/** \brief Union type to access the Application Program Status Register (APSR).
*/
typedef union
{
struct
{
uint32_t _reserved0:28; /*!< bit: 0..27 Reserved */
uint32_t V:1; /*!< bit: 28 Overflow condition code flag */
uint32_t C:1; /*!< bit: 29 Carry condition code flag */
uint32_t Z:1; /*!< bit: 30 Zero condition code flag */
uint32_t N:1; /*!< bit: 31 Negative condition code flag */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} APSR_Type;
/* APSR Register Definitions */
#define APSR_N_Pos 31 /*!< APSR: N Position */
#define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */
#define APSR_Z_Pos 30 /*!< APSR: Z Position */
#define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */
#define APSR_C_Pos 29 /*!< APSR: C Position */
#define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */
#define APSR_V_Pos 28 /*!< APSR: V Position */
#define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */
/** \brief Union type to access the Interrupt Program Status Register (IPSR).
*/
typedef union
{
struct
{
uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */
uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} IPSR_Type;
/* IPSR Register Definitions */
#define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */
#define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */
/** \brief Union type to access the Special-Purpose Program Status Registers (xPSR).
*/
typedef union
{
struct
{
uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */
uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */
uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */
uint32_t _reserved1:3; /*!< bit: 25..27 Reserved */
uint32_t V:1; /*!< bit: 28 Overflow condition code flag */
uint32_t C:1; /*!< bit: 29 Carry condition code flag */
uint32_t Z:1; /*!< bit: 30 Zero condition code flag */
uint32_t N:1; /*!< bit: 31 Negative condition code flag */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} xPSR_Type;
/* xPSR Register Definitions */
#define xPSR_N_Pos 31 /*!< xPSR: N Position */
#define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */
#define xPSR_Z_Pos 30 /*!< xPSR: Z Position */
#define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */
#define xPSR_C_Pos 29 /*!< xPSR: C Position */
#define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */
#define xPSR_V_Pos 28 /*!< xPSR: V Position */
#define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */
#define xPSR_T_Pos 24 /*!< xPSR: T Position */
#define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */
#define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */
#define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */
/** \brief Union type to access the Control Registers (CONTROL).
*/
typedef union
{
struct
{
uint32_t _reserved0:1; /*!< bit: 0 Reserved */
uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */
uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} CONTROL_Type;
/* CONTROL Register Definitions */
#define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */
#define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */
/*@} end of group CMSIS_CORE */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC)
\brief Type definitions for the NVIC Registers
@{
*/
/** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC).
*/
typedef struct
{
__IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */
uint32_t RESERVED0[31];
__IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */
uint32_t RSERVED1[31];
__IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */
uint32_t RESERVED2[31];
__IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */
uint32_t RESERVED3[31];
uint32_t RESERVED4[64];
__IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */
} NVIC_Type;
/*@} end of group CMSIS_NVIC */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_SCB System Control Block (SCB)
\brief Type definitions for the System Control Block Registers
@{
*/
/** \brief Structure type to access the System Control Block (SCB).
*/
typedef struct
{
__I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */
__IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */
uint32_t RESERVED0;
__IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */
__IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */
__IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */
uint32_t RESERVED1;
__IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */
__IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */
} SCB_Type;
/* SCB CPUID Register Definitions */
#define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */
#define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */
#define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */
#define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */
#define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */
#define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */
#define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */
#define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */
#define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */
#define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */
/* SCB Interrupt Control State Register Definitions */
#define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */
#define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */
#define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */
#define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */
#define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */
#define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */
#define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */
#define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */
#define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */
#define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */
#define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */
#define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */
#define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */
#define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */
#define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */
#define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */
#define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */
#define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */
/* SCB Application Interrupt and Reset Control Register Definitions */
#define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */
#define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */
#define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */
#define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */
#define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */
#define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */
#define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */
#define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */
#define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */
#define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */
/* SCB System Control Register Definitions */
#define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */
#define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */
#define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */
#define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */
#define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */
#define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */
/* SCB Configuration Control Register Definitions */
#define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */
#define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */
#define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */
#define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */
/* SCB System Handler Control and State Register Definitions */
#define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */
#define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */
/*@} end of group CMSIS_SCB */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_SysTick System Tick Timer (SysTick)
\brief Type definitions for the System Timer Registers.
@{
*/
/** \brief Structure type to access the System Timer (SysTick).
*/
typedef struct
{
__IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */
__IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */
__IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */
__I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */
} SysTick_Type;
/* SysTick Control / Status Register Definitions */
#define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */
#define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */
#define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */
#define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */
#define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */
#define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */
#define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */
#define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */
/* SysTick Reload Register Definitions */
#define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */
#define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */
/* SysTick Current Register Definitions */
#define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */
#define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */
/* SysTick Calibration Register Definitions */
#define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */
#define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */
#define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */
#define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */
#define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */
#define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */
/*@} end of group CMSIS_SysTick */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug)
\brief Cortex-M0 Core Debug Registers (DCB registers, SHCSR, and DFSR)
are only accessible over DAP and not via processor. Therefore
they are not covered by the Cortex-M0 header file.
@{
*/
/*@} end of group CMSIS_CoreDebug */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_core_base Core Definitions
\brief Definitions for base addresses, unions, and structures.
@{
*/
/* Memory mapping of Cortex-M0 Hardware */
#define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */
#define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */
#define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */
#define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */
#define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */
#define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */
#define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */
/*@} */
/*******************************************************************************
* Hardware Abstraction Layer
Core Function Interface contains:
- Core NVIC Functions
- Core SysTick Functions
- Core Register Access Functions
******************************************************************************/
/** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference
*/
/* ########################## NVIC functions #################################### */
/** \ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_NVICFunctions NVIC Functions
\brief Functions that manage interrupts and exceptions via the NVIC.
@{
*/
/* Interrupt Priorities are WORD accessible only under ARMv6M */
/* The following MACROS handle generation of the register offset and byte masks */
#define _BIT_SHIFT(IRQn) ( ((((uint32_t)(int32_t)(IRQn)) ) & 0x03UL) * 8UL)
#define _SHP_IDX(IRQn) ( (((((uint32_t)(int32_t)(IRQn)) & 0x0FUL)-8UL) >> 2UL) )
#define _IP_IDX(IRQn) ( (((uint32_t)(int32_t)(IRQn)) >> 2UL) )
/** \brief Enable External Interrupt
The function enables a device-specific interrupt in the NVIC interrupt controller.
\param [in] IRQn External interrupt number. Value cannot be negative.
*/
__STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
{
NVIC->ISER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
/** \brief Disable External Interrupt
The function disables a device-specific interrupt in the NVIC interrupt controller.
\param [in] IRQn External interrupt number. Value cannot be negative.
*/
__STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn)
{
NVIC->ICER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
/** \brief Get Pending Interrupt
The function reads the pending register in the NVIC and returns the pending bit
for the specified interrupt.
\param [in] IRQn Interrupt number.
\return 0 Interrupt status is not pending.
\return 1 Interrupt status is pending.
*/
__STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn)
{
return((uint32_t)(((NVIC->ISPR[0] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL));
}
/** \brief Set Pending Interrupt
The function sets the pending bit of an external interrupt.
\param [in] IRQn Interrupt number. Value cannot be negative.
*/
__STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn)
{
NVIC->ISPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
/** \brief Clear Pending Interrupt
The function clears the pending bit of an external interrupt.
\param [in] IRQn External interrupt number. Value cannot be negative.
*/
__STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn)
{
NVIC->ICPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
/** \brief Set Interrupt Priority
The function sets the priority of an interrupt.
\note The priority cannot be set for every core interrupt.
\param [in] IRQn Interrupt number.
\param [in] priority Priority to set.
*/
__STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)
{
if((int32_t)(IRQn) < 0) {
SCB->SHP[_SHP_IDX(IRQn)] = ((uint32_t)(SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) |
(((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn)));
}
else {
NVIC->IP[_IP_IDX(IRQn)] = ((uint32_t)(NVIC->IP[_IP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) |
(((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn)));
}
}
/** \brief Get Interrupt Priority
The function reads the priority of an interrupt. The interrupt
number can be positive to specify an external (device specific)
interrupt, or negative to specify an internal (core) interrupt.
\param [in] IRQn Interrupt number.
\return Interrupt Priority. Value is aligned automatically to the implemented
priority bits of the microcontroller.
*/
__STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn)
{
if((int32_t)(IRQn) < 0) {
return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS)));
}
else {
return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS)));
}
}
/** \brief System Reset
The function initiates a system reset request to reset the MCU.
*/
__STATIC_INLINE void NVIC_SystemReset(void)
{
__DSB(); /* Ensure all outstanding memory accesses included
buffered write are completed before reset */
SCB->AIRCR = ((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) |
SCB_AIRCR_SYSRESETREQ_Msk);
__DSB(); /* Ensure completion of memory access */
while(1) { __NOP(); } /* wait until reset */
}
/*@} end of CMSIS_Core_NVICFunctions */
/* ################################## SysTick function ############################################ */
/** \ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_SysTickFunctions SysTick Functions
\brief Functions that configure the System.
@{
*/
#if (__Vendor_SysTickConfig == 0)
/** \brief System Tick Configuration
The function initializes the System Timer and its interrupt, and starts the System Tick Timer.
Counter is in free running mode to generate periodic interrupts.
\param [in] ticks Number of ticks between two interrupts.
\return 0 Function succeeded.
\return 1 Function failed.
\note When the variable <b>__Vendor_SysTickConfig</b> is set to 1, then the
function <b>SysTick_Config</b> is not included. In this case, the file <b><i>device</i>.h</b>
must contain a vendor-specific implementation of this function.
*/
__STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks)
{
if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) { return (1UL); } /* Reload value impossible */
SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */
NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */
SysTick->VAL = 0UL; /* Load the SysTick Counter Value */
SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
SysTick_CTRL_TICKINT_Msk |
SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */
return (0UL); /* Function successful */
}
#endif
/*@} end of CMSIS_Core_SysTickFunctions */
#ifdef __cplusplus
}
#endif
#endif /* __CORE_CM0_H_DEPENDANT */
#endif /* __CMSIS_GENERIC */

View File

@ -0,0 +1,854 @@
/**************************************************************************//**
* @file core_cm0plus.h
* @brief CMSIS Cortex-M0+ Core Peripheral Access Layer Header File
* @version V4.10
* @date 18. March 2015
*
* @note
*
******************************************************************************/
/* Copyright (c) 2009 - 2015 ARM LIMITED
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of ARM nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
*
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
#if defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#endif
#ifndef __CORE_CM0PLUS_H_GENERIC
#define __CORE_CM0PLUS_H_GENERIC
#ifdef __cplusplus
extern "C" {
#endif
/** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions
CMSIS violates the following MISRA-C:2004 rules:
\li Required Rule 8.5, object/function definition in header file.<br>
Function definitions in header files are used to allow 'inlining'.
\li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
Unions are used for effective representation of core registers.
\li Advisory Rule 19.7, Function-like macro defined.<br>
Function-like macros are used to allow more efficient code.
*/
/*******************************************************************************
* CMSIS definitions
******************************************************************************/
/** \ingroup Cortex-M0+
@{
*/
/* CMSIS CM0P definitions */
#define __CM0PLUS_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */
#define __CM0PLUS_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */
#define __CM0PLUS_CMSIS_VERSION ((__CM0PLUS_CMSIS_VERSION_MAIN << 16) | \
__CM0PLUS_CMSIS_VERSION_SUB) /*!< CMSIS HAL version number */
#define __CORTEX_M (0x00) /*!< Cortex-M Core */
#if defined ( __CC_ARM )
#define __ASM __asm /*!< asm keyword for ARM Compiler */
#define __INLINE __inline /*!< inline keyword for ARM Compiler */
#define __STATIC_INLINE static __inline
#elif defined ( __GNUC__ )
#define __ASM __asm /*!< asm keyword for GNU Compiler */
#define __INLINE inline /*!< inline keyword for GNU Compiler */
#define __STATIC_INLINE static inline
#elif defined ( __ICCARM__ )
#define __ASM __asm /*!< asm keyword for IAR Compiler */
#define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */
#define __STATIC_INLINE static inline
#elif defined ( __TMS470__ )
#define __ASM __asm /*!< asm keyword for TI CCS Compiler */
#define __STATIC_INLINE static inline
#elif defined ( __TASKING__ )
#define __ASM __asm /*!< asm keyword for TASKING Compiler */
#define __INLINE inline /*!< inline keyword for TASKING Compiler */
#define __STATIC_INLINE static inline
#elif defined ( __CSMC__ )
#define __packed
#define __ASM _asm /*!< asm keyword for COSMIC Compiler */
#define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */
#define __STATIC_INLINE static inline
#endif
/** __FPU_USED indicates whether an FPU is used or not.
This core does not support an FPU at all
*/
#define __FPU_USED 0
#if defined ( __CC_ARM )
#if defined __TARGET_FPU_VFP
#warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __GNUC__ )
#if defined (__VFP_FP__) && !defined(__SOFTFP__)
#warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __ICCARM__ )
#if defined __ARMVFP__
#warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __TMS470__ )
#if defined __TI__VFP_SUPPORT____
#warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __TASKING__ )
#if defined __FPU_VFP__
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __CSMC__ ) /* Cosmic */
#if ( __CSMC__ & 0x400) // FPU present for parser
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#endif
#include <stdint.h> /* standard types definitions */
#include <core_cmInstr.h> /* Core Instruction Access */
#include <core_cmFunc.h> /* Core Function Access */
#ifdef __cplusplus
}
#endif
#endif /* __CORE_CM0PLUS_H_GENERIC */
#ifndef __CMSIS_GENERIC
#ifndef __CORE_CM0PLUS_H_DEPENDANT
#define __CORE_CM0PLUS_H_DEPENDANT
#ifdef __cplusplus
extern "C" {
#endif
/* check device defines and use defaults */
#if defined __CHECK_DEVICE_DEFINES
#ifndef __CM0PLUS_REV
#define __CM0PLUS_REV 0x0000
#warning "__CM0PLUS_REV not defined in device header file; using default!"
#endif
#ifndef __MPU_PRESENT
#define __MPU_PRESENT 0
#warning "__MPU_PRESENT not defined in device header file; using default!"
#endif
#ifndef __VTOR_PRESENT
#define __VTOR_PRESENT 0
#warning "__VTOR_PRESENT not defined in device header file; using default!"
#endif
#ifndef __NVIC_PRIO_BITS
#define __NVIC_PRIO_BITS 2
#warning "__NVIC_PRIO_BITS not defined in device header file; using default!"
#endif
#ifndef __Vendor_SysTickConfig
#define __Vendor_SysTickConfig 0
#warning "__Vendor_SysTickConfig not defined in device header file; using default!"
#endif
#endif
/* IO definitions (access restrictions to peripheral registers) */
/**
\defgroup CMSIS_glob_defs CMSIS Global Defines
<strong>IO Type Qualifiers</strong> are used
\li to specify the access to peripheral variables.
\li for automatic generation of peripheral register debug information.
*/
#ifdef __cplusplus
#define __I volatile /*!< Defines 'read only' permissions */
#else
#define __I volatile const /*!< Defines 'read only' permissions */
#endif
#define __O volatile /*!< Defines 'write only' permissions */
#define __IO volatile /*!< Defines 'read / write' permissions */
/*@} end of group Cortex-M0+ */
/*******************************************************************************
* Register Abstraction
Core Register contain:
- Core Register
- Core NVIC Register
- Core SCB Register
- Core SysTick Register
- Core MPU Register
******************************************************************************/
/** \defgroup CMSIS_core_register Defines and Type Definitions
\brief Type definitions and defines for Cortex-M processor based devices.
*/
/** \ingroup CMSIS_core_register
\defgroup CMSIS_CORE Status and Control Registers
\brief Core Register type definitions.
@{
*/
/** \brief Union type to access the Application Program Status Register (APSR).
*/
typedef union
{
struct
{
uint32_t _reserved0:28; /*!< bit: 0..27 Reserved */
uint32_t V:1; /*!< bit: 28 Overflow condition code flag */
uint32_t C:1; /*!< bit: 29 Carry condition code flag */
uint32_t Z:1; /*!< bit: 30 Zero condition code flag */
uint32_t N:1; /*!< bit: 31 Negative condition code flag */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} APSR_Type;
/* APSR Register Definitions */
#define APSR_N_Pos 31 /*!< APSR: N Position */
#define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */
#define APSR_Z_Pos 30 /*!< APSR: Z Position */
#define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */
#define APSR_C_Pos 29 /*!< APSR: C Position */
#define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */
#define APSR_V_Pos 28 /*!< APSR: V Position */
#define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */
/** \brief Union type to access the Interrupt Program Status Register (IPSR).
*/
typedef union
{
struct
{
uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */
uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} IPSR_Type;
/* IPSR Register Definitions */
#define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */
#define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */
/** \brief Union type to access the Special-Purpose Program Status Registers (xPSR).
*/
typedef union
{
struct
{
uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */
uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */
uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */
uint32_t _reserved1:3; /*!< bit: 25..27 Reserved */
uint32_t V:1; /*!< bit: 28 Overflow condition code flag */
uint32_t C:1; /*!< bit: 29 Carry condition code flag */
uint32_t Z:1; /*!< bit: 30 Zero condition code flag */
uint32_t N:1; /*!< bit: 31 Negative condition code flag */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} xPSR_Type;
/* xPSR Register Definitions */
#define xPSR_N_Pos 31 /*!< xPSR: N Position */
#define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */
#define xPSR_Z_Pos 30 /*!< xPSR: Z Position */
#define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */
#define xPSR_C_Pos 29 /*!< xPSR: C Position */
#define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */
#define xPSR_V_Pos 28 /*!< xPSR: V Position */
#define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */
#define xPSR_T_Pos 24 /*!< xPSR: T Position */
#define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */
#define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */
#define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */
/** \brief Union type to access the Control Registers (CONTROL).
*/
typedef union
{
struct
{
uint32_t nPRIV:1; /*!< bit: 0 Execution privilege in Thread mode */
uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */
uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} CONTROL_Type;
/* CONTROL Register Definitions */
#define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */
#define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */
#define CONTROL_nPRIV_Pos 0 /*!< CONTROL: nPRIV Position */
#define CONTROL_nPRIV_Msk (1UL /*<< CONTROL_nPRIV_Pos*/) /*!< CONTROL: nPRIV Mask */
/*@} end of group CMSIS_CORE */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC)
\brief Type definitions for the NVIC Registers
@{
*/
/** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC).
*/
typedef struct
{
__IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */
uint32_t RESERVED0[31];
__IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */
uint32_t RSERVED1[31];
__IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */
uint32_t RESERVED2[31];
__IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */
uint32_t RESERVED3[31];
uint32_t RESERVED4[64];
__IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */
} NVIC_Type;
/*@} end of group CMSIS_NVIC */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_SCB System Control Block (SCB)
\brief Type definitions for the System Control Block Registers
@{
*/
/** \brief Structure type to access the System Control Block (SCB).
*/
typedef struct
{
__I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */
__IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */
#if (__VTOR_PRESENT == 1)
__IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */
#else
uint32_t RESERVED0;
#endif
__IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */
__IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */
__IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */
uint32_t RESERVED1;
__IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */
__IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */
} SCB_Type;
/* SCB CPUID Register Definitions */
#define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */
#define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */
#define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */
#define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */
#define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */
#define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */
#define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */
#define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */
#define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */
#define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */
/* SCB Interrupt Control State Register Definitions */
#define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */
#define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */
#define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */
#define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */
#define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */
#define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */
#define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */
#define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */
#define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */
#define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */
#define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */
#define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */
#define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */
#define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */
#define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */
#define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */
#define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */
#define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */
#if (__VTOR_PRESENT == 1)
/* SCB Interrupt Control State Register Definitions */
#define SCB_VTOR_TBLOFF_Pos 8 /*!< SCB VTOR: TBLOFF Position */
#define SCB_VTOR_TBLOFF_Msk (0xFFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */
#endif
/* SCB Application Interrupt and Reset Control Register Definitions */
#define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */
#define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */
#define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */
#define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */
#define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */
#define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */
#define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */
#define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */
#define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */
#define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */
/* SCB System Control Register Definitions */
#define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */
#define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */
#define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */
#define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */
#define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */
#define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */
/* SCB Configuration Control Register Definitions */
#define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */
#define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */
#define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */
#define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */
/* SCB System Handler Control and State Register Definitions */
#define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */
#define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */
/*@} end of group CMSIS_SCB */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_SysTick System Tick Timer (SysTick)
\brief Type definitions for the System Timer Registers.
@{
*/
/** \brief Structure type to access the System Timer (SysTick).
*/
typedef struct
{
__IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */
__IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */
__IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */
__I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */
} SysTick_Type;
/* SysTick Control / Status Register Definitions */
#define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */
#define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */
#define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */
#define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */
#define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */
#define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */
#define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */
#define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */
/* SysTick Reload Register Definitions */
#define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */
#define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */
/* SysTick Current Register Definitions */
#define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */
#define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */
/* SysTick Calibration Register Definitions */
#define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */
#define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */
#define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */
#define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */
#define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */
#define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */
/*@} end of group CMSIS_SysTick */
#if (__MPU_PRESENT == 1)
/** \ingroup CMSIS_core_register
\defgroup CMSIS_MPU Memory Protection Unit (MPU)
\brief Type definitions for the Memory Protection Unit (MPU)
@{
*/
/** \brief Structure type to access the Memory Protection Unit (MPU).
*/
typedef struct
{
__I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */
__IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */
__IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */
__IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */
__IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */
} MPU_Type;
/* MPU Type Register */
#define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */
#define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */
#define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */
#define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */
#define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */
#define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */
/* MPU Control Register */
#define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */
#define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */
#define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */
#define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */
#define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */
#define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */
/* MPU Region Number Register */
#define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */
#define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */
/* MPU Region Base Address Register */
#define MPU_RBAR_ADDR_Pos 8 /*!< MPU RBAR: ADDR Position */
#define MPU_RBAR_ADDR_Msk (0xFFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */
#define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */
#define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */
#define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */
#define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */
/* MPU Region Attribute and Size Register */
#define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */
#define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */
#define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */
#define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */
#define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */
#define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */
#define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */
#define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */
#define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */
#define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */
#define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */
#define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */
#define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */
#define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */
#define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */
#define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */
#define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */
#define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */
#define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */
#define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */
/*@} end of group CMSIS_MPU */
#endif
/** \ingroup CMSIS_core_register
\defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug)
\brief Cortex-M0+ Core Debug Registers (DCB registers, SHCSR, and DFSR)
are only accessible over DAP and not via processor. Therefore
they are not covered by the Cortex-M0 header file.
@{
*/
/*@} end of group CMSIS_CoreDebug */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_core_base Core Definitions
\brief Definitions for base addresses, unions, and structures.
@{
*/
/* Memory mapping of Cortex-M0+ Hardware */
#define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */
#define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */
#define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */
#define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */
#define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */
#define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */
#define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */
#if (__MPU_PRESENT == 1)
#define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */
#define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */
#endif
/*@} */
/*******************************************************************************
* Hardware Abstraction Layer
Core Function Interface contains:
- Core NVIC Functions
- Core SysTick Functions
- Core Register Access Functions
******************************************************************************/
/** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference
*/
/* ########################## NVIC functions #################################### */
/** \ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_NVICFunctions NVIC Functions
\brief Functions that manage interrupts and exceptions via the NVIC.
@{
*/
/* Interrupt Priorities are WORD accessible only under ARMv6M */
/* The following MACROS handle generation of the register offset and byte masks */
#define _BIT_SHIFT(IRQn) ( ((((uint32_t)(int32_t)(IRQn)) ) & 0x03UL) * 8UL)
#define _SHP_IDX(IRQn) ( (((((uint32_t)(int32_t)(IRQn)) & 0x0FUL)-8UL) >> 2UL) )
#define _IP_IDX(IRQn) ( (((uint32_t)(int32_t)(IRQn)) >> 2UL) )
/** \brief Enable External Interrupt
The function enables a device-specific interrupt in the NVIC interrupt controller.
\param [in] IRQn External interrupt number. Value cannot be negative.
*/
__STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
{
NVIC->ISER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
/** \brief Disable External Interrupt
The function disables a device-specific interrupt in the NVIC interrupt controller.
\param [in] IRQn External interrupt number. Value cannot be negative.
*/
__STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn)
{
NVIC->ICER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
/** \brief Get Pending Interrupt
The function reads the pending register in the NVIC and returns the pending bit
for the specified interrupt.
\param [in] IRQn Interrupt number.
\return 0 Interrupt status is not pending.
\return 1 Interrupt status is pending.
*/
__STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn)
{
return((uint32_t)(((NVIC->ISPR[0] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL));
}
/** \brief Set Pending Interrupt
The function sets the pending bit of an external interrupt.
\param [in] IRQn Interrupt number. Value cannot be negative.
*/
__STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn)
{
NVIC->ISPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
/** \brief Clear Pending Interrupt
The function clears the pending bit of an external interrupt.
\param [in] IRQn External interrupt number. Value cannot be negative.
*/
__STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn)
{
NVIC->ICPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
/** \brief Set Interrupt Priority
The function sets the priority of an interrupt.
\note The priority cannot be set for every core interrupt.
\param [in] IRQn Interrupt number.
\param [in] priority Priority to set.
*/
__STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)
{
if((int32_t)(IRQn) < 0) {
SCB->SHP[_SHP_IDX(IRQn)] = ((uint32_t)(SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) |
(((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn)));
}
else {
NVIC->IP[_IP_IDX(IRQn)] = ((uint32_t)(NVIC->IP[_IP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) |
(((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn)));
}
}
/** \brief Get Interrupt Priority
The function reads the priority of an interrupt. The interrupt
number can be positive to specify an external (device specific)
interrupt, or negative to specify an internal (core) interrupt.
\param [in] IRQn Interrupt number.
\return Interrupt Priority. Value is aligned automatically to the implemented
priority bits of the microcontroller.
*/
__STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn)
{
if((int32_t)(IRQn) < 0) {
return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS)));
}
else {
return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS)));
}
}
/** \brief System Reset
The function initiates a system reset request to reset the MCU.
*/
__STATIC_INLINE void NVIC_SystemReset(void)
{
__DSB(); /* Ensure all outstanding memory accesses included
buffered write are completed before reset */
SCB->AIRCR = ((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) |
SCB_AIRCR_SYSRESETREQ_Msk);
__DSB(); /* Ensure completion of memory access */
while(1) { __NOP(); } /* wait until reset */
}
/*@} end of CMSIS_Core_NVICFunctions */
/* ################################## SysTick function ############################################ */
/** \ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_SysTickFunctions SysTick Functions
\brief Functions that configure the System.
@{
*/
#if (__Vendor_SysTickConfig == 0)
/** \brief System Tick Configuration
The function initializes the System Timer and its interrupt, and starts the System Tick Timer.
Counter is in free running mode to generate periodic interrupts.
\param [in] ticks Number of ticks between two interrupts.
\return 0 Function succeeded.
\return 1 Function failed.
\note When the variable <b>__Vendor_SysTickConfig</b> is set to 1, then the
function <b>SysTick_Config</b> is not included. In this case, the file <b><i>device</i>.h</b>
must contain a vendor-specific implementation of this function.
*/
__STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks)
{
if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) {return (1UL);} /* Reload value impossible */
SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */
NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */
SysTick->VAL = 0UL; /* Load the SysTick Counter Value */
SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
SysTick_CTRL_TICKINT_Msk |
SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */
return (0UL); /* Function successful */
}
#endif
/*@} end of CMSIS_Core_SysTickFunctions */
#ifdef __cplusplus
}
#endif
#endif /* __CORE_CM0PLUS_H_DEPENDANT */
#endif /* __CMSIS_GENERIC */

1693
DSP_LIB/Include/core_cm3.h Normal file

File diff suppressed because it is too large Load Diff

1858
DSP_LIB/Include/core_cm4.h Normal file

File diff suppressed because it is too large Load Diff

2397
DSP_LIB/Include/core_cm7.h Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,664 @@
/**************************************************************************//**
* @file core_cmFunc.h
* @brief CMSIS Cortex-M Core Function Access Header File
* @version V4.10
* @date 18. March 2015
*
* @note
*
******************************************************************************/
/* Copyright (c) 2009 - 2015 ARM LIMITED
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of ARM nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
*
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
#ifndef __CORE_CMFUNC_H
#define __CORE_CMFUNC_H
/* ########################### Core Function Access ########################### */
/** \ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_RegAccFunctions CMSIS Core Register Access Functions
@{
*/
#if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/
/* ARM armcc specific functions */
#if (__ARMCC_VERSION < 400677)
#error "Please use ARM Compiler Toolchain V4.0.677 or later!"
#endif
/* intrinsic void __enable_irq(); */
/* intrinsic void __disable_irq(); */
/** \brief Get Control Register
This function returns the content of the Control Register.
\return Control Register value
*/
__STATIC_INLINE uint32_t __get_CONTROL(void)
{
register uint32_t __regControl __ASM("control");
return(__regControl);
}
/** \brief Set Control Register
This function writes the given value to the Control Register.
\param [in] control Control Register value to set
*/
__STATIC_INLINE void __set_CONTROL(uint32_t control)
{
register uint32_t __regControl __ASM("control");
__regControl = control;
}
/** \brief Get IPSR Register
This function returns the content of the IPSR Register.
\return IPSR Register value
*/
__STATIC_INLINE uint32_t __get_IPSR(void)
{
register uint32_t __regIPSR __ASM("ipsr");
return(__regIPSR);
}
/** \brief Get APSR Register
This function returns the content of the APSR Register.
\return APSR Register value
*/
__STATIC_INLINE uint32_t __get_APSR(void)
{
register uint32_t __regAPSR __ASM("apsr");
return(__regAPSR);
}
/** \brief Get xPSR Register
This function returns the content of the xPSR Register.
\return xPSR Register value
*/
__STATIC_INLINE uint32_t __get_xPSR(void)
{
register uint32_t __regXPSR __ASM("xpsr");
return(__regXPSR);
}
/** \brief Get Process Stack Pointer
This function returns the current value of the Process Stack Pointer (PSP).
\return PSP Register value
*/
__STATIC_INLINE uint32_t __get_PSP(void)
{
register uint32_t __regProcessStackPointer __ASM("psp");
return(__regProcessStackPointer);
}
/** \brief Set Process Stack Pointer
This function assigns the given value to the Process Stack Pointer (PSP).
\param [in] topOfProcStack Process Stack Pointer value to set
*/
__STATIC_INLINE void __set_PSP(uint32_t topOfProcStack)
{
register uint32_t __regProcessStackPointer __ASM("psp");
__regProcessStackPointer = topOfProcStack;
}
/** \brief Get Main Stack Pointer
This function returns the current value of the Main Stack Pointer (MSP).
\return MSP Register value
*/
__STATIC_INLINE uint32_t __get_MSP(void)
{
register uint32_t __regMainStackPointer __ASM("msp");
return(__regMainStackPointer);
}
/** \brief Set Main Stack Pointer
This function assigns the given value to the Main Stack Pointer (MSP).
\param [in] topOfMainStack Main Stack Pointer value to set
*/
__STATIC_INLINE void __set_MSP(uint32_t topOfMainStack)
{
register uint32_t __regMainStackPointer __ASM("msp");
__regMainStackPointer = topOfMainStack;
}
/** \brief Get Priority Mask
This function returns the current state of the priority mask bit from the Priority Mask Register.
\return Priority Mask value
*/
__STATIC_INLINE uint32_t __get_PRIMASK(void)
{
register uint32_t __regPriMask __ASM("primask");
return(__regPriMask);
}
/** \brief Set Priority Mask
This function assigns the given value to the Priority Mask Register.
\param [in] priMask Priority Mask
*/
__STATIC_INLINE void __set_PRIMASK(uint32_t priMask)
{
register uint32_t __regPriMask __ASM("primask");
__regPriMask = (priMask);
}
#if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300)
/** \brief Enable FIQ
This function enables FIQ interrupts by clearing the F-bit in the CPSR.
Can only be executed in Privileged modes.
*/
#define __enable_fault_irq __enable_fiq
/** \brief Disable FIQ
This function disables FIQ interrupts by setting the F-bit in the CPSR.
Can only be executed in Privileged modes.
*/
#define __disable_fault_irq __disable_fiq
/** \brief Get Base Priority
This function returns the current value of the Base Priority register.
\return Base Priority register value
*/
__STATIC_INLINE uint32_t __get_BASEPRI(void)
{
register uint32_t __regBasePri __ASM("basepri");
return(__regBasePri);
}
/** \brief Set Base Priority
This function assigns the given value to the Base Priority register.
\param [in] basePri Base Priority value to set
*/
__STATIC_INLINE void __set_BASEPRI(uint32_t basePri)
{
register uint32_t __regBasePri __ASM("basepri");
__regBasePri = (basePri & 0xff);
}
/** \brief Set Base Priority with condition
This function assigns the given value to the Base Priority register only if BASEPRI masking is disabled,
or the new value increases the BASEPRI priority level.
\param [in] basePri Base Priority value to set
*/
__STATIC_INLINE void __set_BASEPRI_MAX(uint32_t basePri)
{
register uint32_t __regBasePriMax __ASM("basepri_max");
__regBasePriMax = (basePri & 0xff);
}
/** \brief Get Fault Mask
This function returns the current value of the Fault Mask register.
\return Fault Mask register value
*/
__STATIC_INLINE uint32_t __get_FAULTMASK(void)
{
register uint32_t __regFaultMask __ASM("faultmask");
return(__regFaultMask);
}
/** \brief Set Fault Mask
This function assigns the given value to the Fault Mask register.
\param [in] faultMask Fault Mask value to set
*/
__STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask)
{
register uint32_t __regFaultMask __ASM("faultmask");
__regFaultMask = (faultMask & (uint32_t)1);
}
#endif /* (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) */
#if (__CORTEX_M == 0x04) || (__CORTEX_M == 0x07)
/** \brief Get FPSCR
This function returns the current value of the Floating Point Status/Control register.
\return Floating Point Status/Control register value
*/
__STATIC_INLINE uint32_t __get_FPSCR(void)
{
#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
register uint32_t __regfpscr __ASM("fpscr");
return(__regfpscr);
#else
return(0);
#endif
}
/** \brief Set FPSCR
This function assigns the given value to the Floating Point Status/Control register.
\param [in] fpscr Floating Point Status/Control value to set
*/
__STATIC_INLINE void __set_FPSCR(uint32_t fpscr)
{
#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
register uint32_t __regfpscr __ASM("fpscr");
__regfpscr = (fpscr);
#endif
}
#endif /* (__CORTEX_M == 0x04) || (__CORTEX_M == 0x07) */
#elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/
/* GNU gcc specific functions */
/** \brief Enable IRQ Interrupts
This function enables IRQ interrupts by clearing the I-bit in the CPSR.
Can only be executed in Privileged modes.
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_irq(void)
{
__ASM volatile ("cpsie i" : : : "memory");
}
/** \brief Disable IRQ Interrupts
This function disables IRQ interrupts by setting the I-bit in the CPSR.
Can only be executed in Privileged modes.
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_irq(void)
{
__ASM volatile ("cpsid i" : : : "memory");
}
/** \brief Get Control Register
This function returns the content of the Control Register.
\return Control Register value
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_CONTROL(void)
{
uint32_t result;
__ASM volatile ("MRS %0, control" : "=r" (result) );
return(result);
}
/** \brief Set Control Register
This function writes the given value to the Control Register.
\param [in] control Control Register value to set
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_CONTROL(uint32_t control)
{
__ASM volatile ("MSR control, %0" : : "r" (control) : "memory");
}
/** \brief Get IPSR Register
This function returns the content of the IPSR Register.
\return IPSR Register value
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_IPSR(void)
{
uint32_t result;
__ASM volatile ("MRS %0, ipsr" : "=r" (result) );
return(result);
}
/** \brief Get APSR Register
This function returns the content of the APSR Register.
\return APSR Register value
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_APSR(void)
{
uint32_t result;
__ASM volatile ("MRS %0, apsr" : "=r" (result) );
return(result);
}
/** \brief Get xPSR Register
This function returns the content of the xPSR Register.
\return xPSR Register value
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_xPSR(void)
{
uint32_t result;
__ASM volatile ("MRS %0, xpsr" : "=r" (result) );
return(result);
}
/** \brief Get Process Stack Pointer
This function returns the current value of the Process Stack Pointer (PSP).
\return PSP Register value
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PSP(void)
{
register uint32_t result;
__ASM volatile ("MRS %0, psp\n" : "=r" (result) );
return(result);
}
/** \brief Set Process Stack Pointer
This function assigns the given value to the Process Stack Pointer (PSP).
\param [in] topOfProcStack Process Stack Pointer value to set
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PSP(uint32_t topOfProcStack)
{
__ASM volatile ("MSR psp, %0\n" : : "r" (topOfProcStack) : "sp");
}
/** \brief Get Main Stack Pointer
This function returns the current value of the Main Stack Pointer (MSP).
\return MSP Register value
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_MSP(void)
{
register uint32_t result;
__ASM volatile ("MRS %0, msp\n" : "=r" (result) );
return(result);
}
/** \brief Set Main Stack Pointer
This function assigns the given value to the Main Stack Pointer (MSP).
\param [in] topOfMainStack Main Stack Pointer value to set
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_MSP(uint32_t topOfMainStack)
{
__ASM volatile ("MSR msp, %0\n" : : "r" (topOfMainStack) : "sp");
}
/** \brief Get Priority Mask
This function returns the current state of the priority mask bit from the Priority Mask Register.
\return Priority Mask value
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_PRIMASK(void)
{
uint32_t result;
__ASM volatile ("MRS %0, primask" : "=r" (result) );
return(result);
}
/** \brief Set Priority Mask
This function assigns the given value to the Priority Mask Register.
\param [in] priMask Priority Mask
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_PRIMASK(uint32_t priMask)
{
__ASM volatile ("MSR primask, %0" : : "r" (priMask) : "memory");
}
#if (__CORTEX_M >= 0x03)
/** \brief Enable FIQ
This function enables FIQ interrupts by clearing the F-bit in the CPSR.
Can only be executed in Privileged modes.
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE void __enable_fault_irq(void)
{
__ASM volatile ("cpsie f" : : : "memory");
}
/** \brief Disable FIQ
This function disables FIQ interrupts by setting the F-bit in the CPSR.
Can only be executed in Privileged modes.
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE void __disable_fault_irq(void)
{
__ASM volatile ("cpsid f" : : : "memory");
}
/** \brief Get Base Priority
This function returns the current value of the Base Priority register.
\return Base Priority register value
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_BASEPRI(void)
{
uint32_t result;
__ASM volatile ("MRS %0, basepri" : "=r" (result) );
return(result);
}
/** \brief Set Base Priority
This function assigns the given value to the Base Priority register.
\param [in] basePri Base Priority value to set
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_BASEPRI(uint32_t value)
{
__ASM volatile ("MSR basepri, %0" : : "r" (value) : "memory");
}
/** \brief Set Base Priority with condition
This function assigns the given value to the Base Priority register only if BASEPRI masking is disabled,
or the new value increases the BASEPRI priority level.
\param [in] basePri Base Priority value to set
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_BASEPRI_MAX(uint32_t value)
{
__ASM volatile ("MSR basepri_max, %0" : : "r" (value) : "memory");
}
/** \brief Get Fault Mask
This function returns the current value of the Fault Mask register.
\return Fault Mask register value
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FAULTMASK(void)
{
uint32_t result;
__ASM volatile ("MRS %0, faultmask" : "=r" (result) );
return(result);
}
/** \brief Set Fault Mask
This function assigns the given value to the Fault Mask register.
\param [in] faultMask Fault Mask value to set
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FAULTMASK(uint32_t faultMask)
{
__ASM volatile ("MSR faultmask, %0" : : "r" (faultMask) : "memory");
}
#endif /* (__CORTEX_M >= 0x03) */
#if (__CORTEX_M == 0x04) || (__CORTEX_M == 0x07)
/** \brief Get FPSCR
This function returns the current value of the Floating Point Status/Control register.
\return Floating Point Status/Control register value
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __get_FPSCR(void)
{
#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
uint32_t result;
/* Empty asm statement works as a scheduling barrier */
__ASM volatile ("");
__ASM volatile ("VMRS %0, fpscr" : "=r" (result) );
__ASM volatile ("");
return(result);
#else
return(0);
#endif
}
/** \brief Set FPSCR
This function assigns the given value to the Floating Point Status/Control register.
\param [in] fpscr Floating Point Status/Control value to set
*/
__attribute__( ( always_inline ) ) __STATIC_INLINE void __set_FPSCR(uint32_t fpscr)
{
#if (__FPU_PRESENT == 1) && (__FPU_USED == 1)
/* Empty asm statement works as a scheduling barrier */
__ASM volatile ("");
__ASM volatile ("VMSR fpscr, %0" : : "r" (fpscr) : "vfpcc");
__ASM volatile ("");
#endif
}
#endif /* (__CORTEX_M == 0x04) || (__CORTEX_M == 0x07) */
#elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/
/* IAR iccarm specific functions */
#include <cmsis_iar.h>
#elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/
/* TI CCS specific functions */
#include <cmsis_ccs.h>
#elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/
/* TASKING carm specific functions */
/*
* The CMSIS functions have been implemented as intrinsics in the compiler.
* Please use "carm -?i" to get an up to date list of all intrinsics,
* Including the CMSIS ones.
*/
#elif defined ( __CSMC__ ) /*------------------ COSMIC Compiler -------------------*/
/* Cosmic specific functions */
#include <cmsis_csm.h>
#endif
/*@} end of CMSIS_Core_RegAccFunctions */
#endif /* __CORE_CMFUNC_H */

View File

@ -0,0 +1,916 @@
/**************************************************************************//**
* @file core_cmInstr.h
* @brief CMSIS Cortex-M Core Instruction Access Header File
* @version V4.10
* @date 18. March 2015
*
* @note
*
******************************************************************************/
/* Copyright (c) 2009 - 2014 ARM LIMITED
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of ARM nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
*
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
#ifndef __CORE_CMINSTR_H
#define __CORE_CMINSTR_H
/* ########################## Core Instruction Access ######################### */
/** \defgroup CMSIS_Core_InstructionInterface CMSIS Core Instruction Interface
Access to dedicated instructions
@{
*/
#if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/
/* ARM armcc specific functions */
#if (__ARMCC_VERSION < 400677)
#error "Please use ARM Compiler Toolchain V4.0.677 or later!"
#endif
/** \brief No Operation
No Operation does nothing. This instruction can be used for code alignment purposes.
*/
#define __NOP __nop
/** \brief Wait For Interrupt
Wait For Interrupt is a hint instruction that suspends execution
until one of a number of events occurs.
*/
#define __WFI __wfi
/** \brief Wait For Event
Wait For Event is a hint instruction that permits the processor to enter
a low-power state until one of a number of events occurs.
*/
#define __WFE __wfe
/** \brief Send Event
Send Event is a hint instruction. It causes an event to be signaled to the CPU.
*/
#define __SEV __sev
/** \brief Instruction Synchronization Barrier
Instruction Synchronization Barrier flushes the pipeline in the processor,
so that all instructions following the ISB are fetched from cache or
memory, after the instruction has been completed.
*/
#define __ISB() do {\
__schedule_barrier();\
__isb(0xF);\
__schedule_barrier();\
} while (0)
/** \brief Data Synchronization Barrier
This function acts as a special kind of Data Memory Barrier.
It completes when all explicit memory accesses before this instruction complete.
*/
#define __DSB() do {\
__schedule_barrier();\
__dsb(0xF);\
__schedule_barrier();\
} while (0)
/** \brief Data Memory Barrier
This function ensures the apparent order of the explicit memory operations before
and after the instruction, without ensuring their completion.
*/
#define __DMB() do {\
__schedule_barrier();\
__dmb(0xF);\
__schedule_barrier();\
} while (0)
/** \brief Reverse byte order (32 bit)
This function reverses the byte order in integer value.
\param [in] value Value to reverse
\return Reversed value
*/
#define __REV __rev
/** \brief Reverse byte order (16 bit)
This function reverses the byte order in two unsigned short values.
\param [in] value Value to reverse
\return Reversed value
*/
#ifndef __NO_EMBEDDED_ASM
__attribute__((section(".rev16_text"))) __STATIC_INLINE __ASM uint32_t __REV16(uint32_t value)
{
rev16 r0, r0
bx lr
}
#endif
/** \brief Reverse byte order in signed short value
This function reverses the byte order in a signed short value with sign extension to integer.
\param [in] value Value to reverse
\return Reversed value
*/
#ifndef __NO_EMBEDDED_ASM
__attribute__((section(".revsh_text"))) __STATIC_INLINE __ASM int32_t __REVSH(int32_t value)
{
revsh r0, r0
bx lr
}
#endif
/** \brief Rotate Right in unsigned value (32 bit)
This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits.
\param [in] value Value to rotate
\param [in] value Number of Bits to rotate
\return Rotated value
*/
#define __ROR __ror
/** \brief Breakpoint
This function causes the processor to enter Debug state.
Debug tools can use this to investigate system state when the instruction at a particular address is reached.
\param [in] value is ignored by the processor.
If required, a debugger can use it to store additional information about the breakpoint.
*/
#define __BKPT(value) __breakpoint(value)
/** \brief Reverse bit order of value
This function reverses the bit order of the given value.
\param [in] value Value to reverse
\return Reversed value
*/
#if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300)
#define __RBIT __rbit
#else
__attribute__((always_inline)) __STATIC_INLINE uint32_t __RBIT(uint32_t value)
{
uint32_t result;
int32_t s = 4 /*sizeof(v)*/ * 8 - 1; // extra shift needed at end
result = value; // r will be reversed bits of v; first get LSB of v
for (value >>= 1; value; value >>= 1)
{
result <<= 1;
result |= value & 1;
s--;
}
result <<= s; // shift when v's highest bits are zero
return(result);
}
#endif
/** \brief Count leading zeros
This function counts the number of leading zeros of a data value.
\param [in] value Value to count the leading zeros
\return number of leading zeros in value
*/
#define __CLZ __clz
#if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300)
/** \brief LDR Exclusive (8 bit)
This function executes a exclusive LDR instruction for 8 bit value.
\param [in] ptr Pointer to data
\return value of type uint8_t at (*ptr)
*/
#define __LDREXB(ptr) ((uint8_t ) __ldrex(ptr))
/** \brief LDR Exclusive (16 bit)
This function executes a exclusive LDR instruction for 16 bit values.
\param [in] ptr Pointer to data
\return value of type uint16_t at (*ptr)
*/
#define __LDREXH(ptr) ((uint16_t) __ldrex(ptr))
/** \brief LDR Exclusive (32 bit)
This function executes a exclusive LDR instruction for 32 bit values.
\param [in] ptr Pointer to data
\return value of type uint32_t at (*ptr)
*/
#define __LDREXW(ptr) ((uint32_t ) __ldrex(ptr))
/** \brief STR Exclusive (8 bit)
This function executes a exclusive STR instruction for 8 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
\return 0 Function succeeded
\return 1 Function failed
*/
#define __STREXB(value, ptr) __strex(value, ptr)
/** \brief STR Exclusive (16 bit)
This function executes a exclusive STR instruction for 16 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
\return 0 Function succeeded
\return 1 Function failed
*/
#define __STREXH(value, ptr) __strex(value, ptr)
/** \brief STR Exclusive (32 bit)
This function executes a exclusive STR instruction for 32 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
\return 0 Function succeeded
\return 1 Function failed
*/
#define __STREXW(value, ptr) __strex(value, ptr)
/** \brief Remove the exclusive lock
This function removes the exclusive lock which is created by LDREX.
*/
#define __CLREX __clrex
/** \brief Signed Saturate
This function saturates a signed value.
\param [in] value Value to be saturated
\param [in] sat Bit position to saturate to (1..32)
\return Saturated value
*/
#define __SSAT __ssat
/** \brief Unsigned Saturate
This function saturates an unsigned value.
\param [in] value Value to be saturated
\param [in] sat Bit position to saturate to (0..31)
\return Saturated value
*/
#define __USAT __usat
/** \brief Rotate Right with Extend (32 bit)
This function moves each bit of a bitstring right by one bit.
The carry input is shifted in at the left end of the bitstring.
\param [in] value Value to rotate
\return Rotated value
*/
#ifndef __NO_EMBEDDED_ASM
__attribute__((section(".rrx_text"))) __STATIC_INLINE __ASM uint32_t __RRX(uint32_t value)
{
rrx r0, r0
bx lr
}
#endif
/** \brief LDRT Unprivileged (8 bit)
This function executes a Unprivileged LDRT instruction for 8 bit value.
\param [in] ptr Pointer to data
\return value of type uint8_t at (*ptr)
*/
#define __LDRBT(ptr) ((uint8_t ) __ldrt(ptr))
/** \brief LDRT Unprivileged (16 bit)
This function executes a Unprivileged LDRT instruction for 16 bit values.
\param [in] ptr Pointer to data
\return value of type uint16_t at (*ptr)
*/
#define __LDRHT(ptr) ((uint16_t) __ldrt(ptr))
/** \brief LDRT Unprivileged (32 bit)
This function executes a Unprivileged LDRT instruction for 32 bit values.
\param [in] ptr Pointer to data
\return value of type uint32_t at (*ptr)
*/
#define __LDRT(ptr) ((uint32_t ) __ldrt(ptr))
/** \brief STRT Unprivileged (8 bit)
This function executes a Unprivileged STRT instruction for 8 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
*/
#define __STRBT(value, ptr) __strt(value, ptr)
/** \brief STRT Unprivileged (16 bit)
This function executes a Unprivileged STRT instruction for 16 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
*/
#define __STRHT(value, ptr) __strt(value, ptr)
/** \brief STRT Unprivileged (32 bit)
This function executes a Unprivileged STRT instruction for 32 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
*/
#define __STRT(value, ptr) __strt(value, ptr)
#endif /* (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) */
#elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/
/* GNU gcc specific functions */
/* Define macros for porting to both thumb1 and thumb2.
* For thumb1, use low register (r0-r7), specified by constrant "l"
* Otherwise, use general registers, specified by constrant "r" */
#if defined (__thumb__) && !defined (__thumb2__)
#define __CMSIS_GCC_OUT_REG(r) "=l" (r)
#define __CMSIS_GCC_USE_REG(r) "l" (r)
#else
#define __CMSIS_GCC_OUT_REG(r) "=r" (r)
#define __CMSIS_GCC_USE_REG(r) "r" (r)
#endif
/** \brief No Operation
No Operation does nothing. This instruction can be used for code alignment purposes.
*/
__attribute__((always_inline)) __STATIC_INLINE void __NOP(void)
{
__ASM volatile ("nop");
}
/** \brief Wait For Interrupt
Wait For Interrupt is a hint instruction that suspends execution
until one of a number of events occurs.
*/
__attribute__((always_inline)) __STATIC_INLINE void __WFI(void)
{
__ASM volatile ("wfi");
}
/** \brief Wait For Event
Wait For Event is a hint instruction that permits the processor to enter
a low-power state until one of a number of events occurs.
*/
__attribute__((always_inline)) __STATIC_INLINE void __WFE(void)
{
__ASM volatile ("wfe");
}
/** \brief Send Event
Send Event is a hint instruction. It causes an event to be signaled to the CPU.
*/
__attribute__((always_inline)) __STATIC_INLINE void __SEV(void)
{
__ASM volatile ("sev");
}
/** \brief Instruction Synchronization Barrier
Instruction Synchronization Barrier flushes the pipeline in the processor,
so that all instructions following the ISB are fetched from cache or
memory, after the instruction has been completed.
*/
__attribute__((always_inline)) __STATIC_INLINE void __ISB(void)
{
__ASM volatile ("isb 0xF":::"memory");
}
/** \brief Data Synchronization Barrier
This function acts as a special kind of Data Memory Barrier.
It completes when all explicit memory accesses before this instruction complete.
*/
__attribute__((always_inline)) __STATIC_INLINE void __DSB(void)
{
__ASM volatile ("dsb 0xF":::"memory");
}
/** \brief Data Memory Barrier
This function ensures the apparent order of the explicit memory operations before
and after the instruction, without ensuring their completion.
*/
__attribute__((always_inline)) __STATIC_INLINE void __DMB(void)
{
__ASM volatile ("dmb 0xF":::"memory");
}
/** \brief Reverse byte order (32 bit)
This function reverses the byte order in integer value.
\param [in] value Value to reverse
\return Reversed value
*/
__attribute__((always_inline)) __STATIC_INLINE uint32_t __REV(uint32_t value)
{
#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 5)
return __builtin_bswap32(value);
#else
uint32_t result;
__ASM volatile ("rev %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) );
return(result);
#endif
}
/** \brief Reverse byte order (16 bit)
This function reverses the byte order in two unsigned short values.
\param [in] value Value to reverse
\return Reversed value
*/
__attribute__((always_inline)) __STATIC_INLINE uint32_t __REV16(uint32_t value)
{
uint32_t result;
__ASM volatile ("rev16 %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) );
return(result);
}
/** \brief Reverse byte order in signed short value
This function reverses the byte order in a signed short value with sign extension to integer.
\param [in] value Value to reverse
\return Reversed value
*/
__attribute__((always_inline)) __STATIC_INLINE int32_t __REVSH(int32_t value)
{
#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
return (short)__builtin_bswap16(value);
#else
uint32_t result;
__ASM volatile ("revsh %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) );
return(result);
#endif
}
/** \brief Rotate Right in unsigned value (32 bit)
This function Rotate Right (immediate) provides the value of the contents of a register rotated by a variable number of bits.
\param [in] value Value to rotate
\param [in] value Number of Bits to rotate
\return Rotated value
*/
__attribute__((always_inline)) __STATIC_INLINE uint32_t __ROR(uint32_t op1, uint32_t op2)
{
return (op1 >> op2) | (op1 << (32 - op2));
}
/** \brief Breakpoint
This function causes the processor to enter Debug state.
Debug tools can use this to investigate system state when the instruction at a particular address is reached.
\param [in] value is ignored by the processor.
If required, a debugger can use it to store additional information about the breakpoint.
*/
#define __BKPT(value) __ASM volatile ("bkpt "#value)
/** \brief Reverse bit order of value
This function reverses the bit order of the given value.
\param [in] value Value to reverse
\return Reversed value
*/
__attribute__((always_inline)) __STATIC_INLINE uint32_t __RBIT(uint32_t value)
{
uint32_t result;
#if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300)
__ASM volatile ("rbit %0, %1" : "=r" (result) : "r" (value) );
#else
int32_t s = 4 /*sizeof(v)*/ * 8 - 1; // extra shift needed at end
result = value; // r will be reversed bits of v; first get LSB of v
for (value >>= 1; value; value >>= 1)
{
result <<= 1;
result |= value & 1;
s--;
}
result <<= s; // shift when v's highest bits are zero
#endif
return(result);
}
/** \brief Count leading zeros
This function counts the number of leading zeros of a data value.
\param [in] value Value to count the leading zeros
\return number of leading zeros in value
*/
#define __CLZ __builtin_clz
#if (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300)
/** \brief LDR Exclusive (8 bit)
This function executes a exclusive LDR instruction for 8 bit value.
\param [in] ptr Pointer to data
\return value of type uint8_t at (*ptr)
*/
__attribute__((always_inline)) __STATIC_INLINE uint8_t __LDREXB(volatile uint8_t *addr)
{
uint32_t result;
#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
__ASM volatile ("ldrexb %0, %1" : "=r" (result) : "Q" (*addr) );
#else
/* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not
accepted by assembler. So has to use following less efficient pattern.
*/
__ASM volatile ("ldrexb %0, [%1]" : "=r" (result) : "r" (addr) : "memory" );
#endif
return ((uint8_t) result); /* Add explicit type cast here */
}
/** \brief LDR Exclusive (16 bit)
This function executes a exclusive LDR instruction for 16 bit values.
\param [in] ptr Pointer to data
\return value of type uint16_t at (*ptr)
*/
__attribute__((always_inline)) __STATIC_INLINE uint16_t __LDREXH(volatile uint16_t *addr)
{
uint32_t result;
#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
__ASM volatile ("ldrexh %0, %1" : "=r" (result) : "Q" (*addr) );
#else
/* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not
accepted by assembler. So has to use following less efficient pattern.
*/
__ASM volatile ("ldrexh %0, [%1]" : "=r" (result) : "r" (addr) : "memory" );
#endif
return ((uint16_t) result); /* Add explicit type cast here */
}
/** \brief LDR Exclusive (32 bit)
This function executes a exclusive LDR instruction for 32 bit values.
\param [in] ptr Pointer to data
\return value of type uint32_t at (*ptr)
*/
__attribute__((always_inline)) __STATIC_INLINE uint32_t __LDREXW(volatile uint32_t *addr)
{
uint32_t result;
__ASM volatile ("ldrex %0, %1" : "=r" (result) : "Q" (*addr) );
return(result);
}
/** \brief STR Exclusive (8 bit)
This function executes a exclusive STR instruction for 8 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
\return 0 Function succeeded
\return 1 Function failed
*/
__attribute__((always_inline)) __STATIC_INLINE uint32_t __STREXB(uint8_t value, volatile uint8_t *addr)
{
uint32_t result;
__ASM volatile ("strexb %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" ((uint32_t)value) );
return(result);
}
/** \brief STR Exclusive (16 bit)
This function executes a exclusive STR instruction for 16 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
\return 0 Function succeeded
\return 1 Function failed
*/
__attribute__((always_inline)) __STATIC_INLINE uint32_t __STREXH(uint16_t value, volatile uint16_t *addr)
{
uint32_t result;
__ASM volatile ("strexh %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" ((uint32_t)value) );
return(result);
}
/** \brief STR Exclusive (32 bit)
This function executes a exclusive STR instruction for 32 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
\return 0 Function succeeded
\return 1 Function failed
*/
__attribute__((always_inline)) __STATIC_INLINE uint32_t __STREXW(uint32_t value, volatile uint32_t *addr)
{
uint32_t result;
__ASM volatile ("strex %0, %2, %1" : "=&r" (result), "=Q" (*addr) : "r" (value) );
return(result);
}
/** \brief Remove the exclusive lock
This function removes the exclusive lock which is created by LDREX.
*/
__attribute__((always_inline)) __STATIC_INLINE void __CLREX(void)
{
__ASM volatile ("clrex" ::: "memory");
}
/** \brief Signed Saturate
This function saturates a signed value.
\param [in] value Value to be saturated
\param [in] sat Bit position to saturate to (1..32)
\return Saturated value
*/
#define __SSAT(ARG1,ARG2) \
({ \
uint32_t __RES, __ARG1 = (ARG1); \
__ASM ("ssat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \
__RES; \
})
/** \brief Unsigned Saturate
This function saturates an unsigned value.
\param [in] value Value to be saturated
\param [in] sat Bit position to saturate to (0..31)
\return Saturated value
*/
#define __USAT(ARG1,ARG2) \
({ \
uint32_t __RES, __ARG1 = (ARG1); \
__ASM ("usat %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \
__RES; \
})
/** \brief Rotate Right with Extend (32 bit)
This function moves each bit of a bitstring right by one bit.
The carry input is shifted in at the left end of the bitstring.
\param [in] value Value to rotate
\return Rotated value
*/
__attribute__((always_inline)) __STATIC_INLINE uint32_t __RRX(uint32_t value)
{
uint32_t result;
__ASM volatile ("rrx %0, %1" : __CMSIS_GCC_OUT_REG (result) : __CMSIS_GCC_USE_REG (value) );
return(result);
}
/** \brief LDRT Unprivileged (8 bit)
This function executes a Unprivileged LDRT instruction for 8 bit value.
\param [in] ptr Pointer to data
\return value of type uint8_t at (*ptr)
*/
__attribute__((always_inline)) __STATIC_INLINE uint8_t __LDRBT(volatile uint8_t *addr)
{
uint32_t result;
#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
__ASM volatile ("ldrbt %0, %1" : "=r" (result) : "Q" (*addr) );
#else
/* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not
accepted by assembler. So has to use following less efficient pattern.
*/
__ASM volatile ("ldrbt %0, [%1]" : "=r" (result) : "r" (addr) : "memory" );
#endif
return ((uint8_t) result); /* Add explicit type cast here */
}
/** \brief LDRT Unprivileged (16 bit)
This function executes a Unprivileged LDRT instruction for 16 bit values.
\param [in] ptr Pointer to data
\return value of type uint16_t at (*ptr)
*/
__attribute__((always_inline)) __STATIC_INLINE uint16_t __LDRHT(volatile uint16_t *addr)
{
uint32_t result;
#if (__GNUC__ > 4) || (__GNUC__ == 4 && __GNUC_MINOR__ >= 8)
__ASM volatile ("ldrht %0, %1" : "=r" (result) : "Q" (*addr) );
#else
/* Prior to GCC 4.8, "Q" will be expanded to [rx, #0] which is not
accepted by assembler. So has to use following less efficient pattern.
*/
__ASM volatile ("ldrht %0, [%1]" : "=r" (result) : "r" (addr) : "memory" );
#endif
return ((uint16_t) result); /* Add explicit type cast here */
}
/** \brief LDRT Unprivileged (32 bit)
This function executes a Unprivileged LDRT instruction for 32 bit values.
\param [in] ptr Pointer to data
\return value of type uint32_t at (*ptr)
*/
__attribute__((always_inline)) __STATIC_INLINE uint32_t __LDRT(volatile uint32_t *addr)
{
uint32_t result;
__ASM volatile ("ldrt %0, %1" : "=r" (result) : "Q" (*addr) );
return(result);
}
/** \brief STRT Unprivileged (8 bit)
This function executes a Unprivileged STRT instruction for 8 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
*/
__attribute__((always_inline)) __STATIC_INLINE void __STRBT(uint8_t value, volatile uint8_t *addr)
{
__ASM volatile ("strbt %1, %0" : "=Q" (*addr) : "r" ((uint32_t)value) );
}
/** \brief STRT Unprivileged (16 bit)
This function executes a Unprivileged STRT instruction for 16 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
*/
__attribute__((always_inline)) __STATIC_INLINE void __STRHT(uint16_t value, volatile uint16_t *addr)
{
__ASM volatile ("strht %1, %0" : "=Q" (*addr) : "r" ((uint32_t)value) );
}
/** \brief STRT Unprivileged (32 bit)
This function executes a Unprivileged STRT instruction for 32 bit values.
\param [in] value Value to store
\param [in] ptr Pointer to location
*/
__attribute__((always_inline)) __STATIC_INLINE void __STRT(uint32_t value, volatile uint32_t *addr)
{
__ASM volatile ("strt %1, %0" : "=Q" (*addr) : "r" (value) );
}
#endif /* (__CORTEX_M >= 0x03) || (__CORTEX_SC >= 300) */
#elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/
/* IAR iccarm specific functions */
#include <cmsis_iar.h>
#elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/
/* TI CCS specific functions */
#include <cmsis_ccs.h>
#elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/
/* TASKING carm specific functions */
/*
* The CMSIS functions have been implemented as intrinsics in the compiler.
* Please use "carm -?i" to get an up to date list of all intrinsics,
* Including the CMSIS ones.
*/
#elif defined ( __CSMC__ ) /*------------------ COSMIC Compiler -------------------*/
/* Cosmic specific functions */
#include <cmsis_csm.h>
#endif
/*@}*/ /* end of group CMSIS_Core_InstructionInterface */
#endif /* __CORE_CMINSTR_H */

View File

@ -0,0 +1,697 @@
/**************************************************************************//**
* @file core_cmSimd.h
* @brief CMSIS Cortex-M SIMD Header File
* @version V4.10
* @date 18. March 2015
*
* @note
*
******************************************************************************/
/* Copyright (c) 2009 - 2014 ARM LIMITED
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of ARM nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
*
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
#if defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#endif
#ifndef __CORE_CMSIMD_H
#define __CORE_CMSIMD_H
#ifdef __cplusplus
extern "C" {
#endif
/*******************************************************************************
* Hardware Abstraction Layer
******************************************************************************/
/* ################### Compiler specific Intrinsics ########################### */
/** \defgroup CMSIS_SIMD_intrinsics CMSIS SIMD Intrinsics
Access to dedicated SIMD instructions
@{
*/
#if defined ( __CC_ARM ) /*------------------RealView Compiler -----------------*/
/* ARM armcc specific functions */
#define __SADD8 __sadd8
#define __QADD8 __qadd8
#define __SHADD8 __shadd8
#define __UADD8 __uadd8
#define __UQADD8 __uqadd8
#define __UHADD8 __uhadd8
#define __SSUB8 __ssub8
#define __QSUB8 __qsub8
#define __SHSUB8 __shsub8
#define __USUB8 __usub8
#define __UQSUB8 __uqsub8
#define __UHSUB8 __uhsub8
#define __SADD16 __sadd16
#define __QADD16 __qadd16
#define __SHADD16 __shadd16
#define __UADD16 __uadd16
#define __UQADD16 __uqadd16
#define __UHADD16 __uhadd16
#define __SSUB16 __ssub16
#define __QSUB16 __qsub16
#define __SHSUB16 __shsub16
#define __USUB16 __usub16
#define __UQSUB16 __uqsub16
#define __UHSUB16 __uhsub16
#define __SASX __sasx
#define __QASX __qasx
#define __SHASX __shasx
#define __UASX __uasx
#define __UQASX __uqasx
#define __UHASX __uhasx
#define __SSAX __ssax
#define __QSAX __qsax
#define __SHSAX __shsax
#define __USAX __usax
#define __UQSAX __uqsax
#define __UHSAX __uhsax
#define __USAD8 __usad8
#define __USADA8 __usada8
#define __SSAT16 __ssat16
#define __USAT16 __usat16
#define __UXTB16 __uxtb16
#define __UXTAB16 __uxtab16
#define __SXTB16 __sxtb16
#define __SXTAB16 __sxtab16
#define __SMUAD __smuad
#define __SMUADX __smuadx
#define __SMLAD __smlad
#define __SMLADX __smladx
#define __SMLALD __smlald
#define __SMLALDX __smlaldx
#define __SMUSD __smusd
#define __SMUSDX __smusdx
#define __SMLSD __smlsd
#define __SMLSDX __smlsdx
#define __SMLSLD __smlsld
#define __SMLSLDX __smlsldx
#define __SEL __sel
#define __QADD __qadd
#define __QSUB __qsub
#define __PKHBT(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0x0000FFFFUL) | \
((((uint32_t)(ARG2)) << (ARG3)) & 0xFFFF0000UL) )
#define __PKHTB(ARG1,ARG2,ARG3) ( ((((uint32_t)(ARG1)) ) & 0xFFFF0000UL) | \
((((uint32_t)(ARG2)) >> (ARG3)) & 0x0000FFFFUL) )
#define __SMMLA(ARG1,ARG2,ARG3) ( (int32_t)((((int64_t)(ARG1) * (ARG2)) + \
((int64_t)(ARG3) << 32) ) >> 32))
#elif defined ( __GNUC__ ) /*------------------ GNU Compiler ---------------------*/
/* GNU gcc specific functions */
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD8(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("sadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD8(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("qadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD8(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("shadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD8(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("uadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD8(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("uqadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD8(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("uhadd8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB8(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("ssub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB8(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("qsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB8(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("shsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB8(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("usub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB8(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("uqsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB8(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("uhsub8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SADD16(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("sadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD16(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("qadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHADD16(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("shadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UADD16(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("uadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQADD16(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("uqadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHADD16(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("uhadd16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSUB16(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("ssub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB16(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("qsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSUB16(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("shsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USUB16(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("usub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSUB16(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("uqsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSUB16(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("uhsub16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SASX(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("sasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QASX(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("qasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHASX(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("shasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UASX(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("uasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQASX(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("uqasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHASX(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("uhasx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SSAX(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("ssax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSAX(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("qsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SHSAX(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("shsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAX(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("usax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UQSAX(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("uqsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UHSAX(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("uhsax %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USAD8(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("usad8 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __USADA8(uint32_t op1, uint32_t op2, uint32_t op3)
{
uint32_t result;
__ASM volatile ("usada8 %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) );
return(result);
}
#define __SSAT16(ARG1,ARG2) \
({ \
uint32_t __RES, __ARG1 = (ARG1); \
__ASM ("ssat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \
__RES; \
})
#define __USAT16(ARG1,ARG2) \
({ \
uint32_t __RES, __ARG1 = (ARG1); \
__ASM ("usat16 %0, %1, %2" : "=r" (__RES) : "I" (ARG2), "r" (__ARG1) ); \
__RES; \
})
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTB16(uint32_t op1)
{
uint32_t result;
__ASM volatile ("uxtb16 %0, %1" : "=r" (result) : "r" (op1));
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __UXTAB16(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("uxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTB16(uint32_t op1)
{
uint32_t result;
__ASM volatile ("sxtb16 %0, %1" : "=r" (result) : "r" (op1));
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SXTAB16(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("sxtab16 %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUAD (uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("smuad %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUADX (uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("smuadx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLAD (uint32_t op1, uint32_t op2, uint32_t op3)
{
uint32_t result;
__ASM volatile ("smlad %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLADX (uint32_t op1, uint32_t op2, uint32_t op3)
{
uint32_t result;
__ASM volatile ("smladx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLALD (uint32_t op1, uint32_t op2, uint64_t acc)
{
union llreg_u{
uint32_t w32[2];
uint64_t w64;
} llr;
llr.w64 = acc;
#ifndef __ARMEB__ // Little endian
__ASM volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) );
#else // Big endian
__ASM volatile ("smlald %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) );
#endif
return(llr.w64);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLALDX (uint32_t op1, uint32_t op2, uint64_t acc)
{
union llreg_u{
uint32_t w32[2];
uint64_t w64;
} llr;
llr.w64 = acc;
#ifndef __ARMEB__ // Little endian
__ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) );
#else // Big endian
__ASM volatile ("smlaldx %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) );
#endif
return(llr.w64);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSD (uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("smusd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMUSDX (uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("smusdx %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSD (uint32_t op1, uint32_t op2, uint32_t op3)
{
uint32_t result;
__ASM volatile ("smlsd %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMLSDX (uint32_t op1, uint32_t op2, uint32_t op3)
{
uint32_t result;
__ASM volatile ("smlsdx %0, %1, %2, %3" : "=r" (result) : "r" (op1), "r" (op2), "r" (op3) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLSLD (uint32_t op1, uint32_t op2, uint64_t acc)
{
union llreg_u{
uint32_t w32[2];
uint64_t w64;
} llr;
llr.w64 = acc;
#ifndef __ARMEB__ // Little endian
__ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) );
#else // Big endian
__ASM volatile ("smlsld %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) );
#endif
return(llr.w64);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint64_t __SMLSLDX (uint32_t op1, uint32_t op2, uint64_t acc)
{
union llreg_u{
uint32_t w32[2];
uint64_t w64;
} llr;
llr.w64 = acc;
#ifndef __ARMEB__ // Little endian
__ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[0]), "=r" (llr.w32[1]): "r" (op1), "r" (op2) , "0" (llr.w32[0]), "1" (llr.w32[1]) );
#else // Big endian
__ASM volatile ("smlsldx %0, %1, %2, %3" : "=r" (llr.w32[1]), "=r" (llr.w32[0]): "r" (op1), "r" (op2) , "0" (llr.w32[1]), "1" (llr.w32[0]) );
#endif
return(llr.w64);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SEL (uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("sel %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QADD(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("qadd %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __QSUB(uint32_t op1, uint32_t op2)
{
uint32_t result;
__ASM volatile ("qsub %0, %1, %2" : "=r" (result) : "r" (op1), "r" (op2) );
return(result);
}
#define __PKHBT(ARG1,ARG2,ARG3) \
({ \
uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \
__ASM ("pkhbt %0, %1, %2, lsl %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \
__RES; \
})
#define __PKHTB(ARG1,ARG2,ARG3) \
({ \
uint32_t __RES, __ARG1 = (ARG1), __ARG2 = (ARG2); \
if (ARG3 == 0) \
__ASM ("pkhtb %0, %1, %2" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2) ); \
else \
__ASM ("pkhtb %0, %1, %2, asr %3" : "=r" (__RES) : "r" (__ARG1), "r" (__ARG2), "I" (ARG3) ); \
__RES; \
})
__attribute__( ( always_inline ) ) __STATIC_INLINE uint32_t __SMMLA (int32_t op1, int32_t op2, int32_t op3)
{
int32_t result;
__ASM volatile ("smmla %0, %1, %2, %3" : "=r" (result): "r" (op1), "r" (op2), "r" (op3) );
return(result);
}
#elif defined ( __ICCARM__ ) /*------------------ ICC Compiler -------------------*/
/* IAR iccarm specific functions */
#include <cmsis_iar.h>
#elif defined ( __TMS470__ ) /*---------------- TI CCS Compiler ------------------*/
/* TI CCS specific functions */
#include <cmsis_ccs.h>
#elif defined ( __TASKING__ ) /*------------------ TASKING Compiler --------------*/
/* TASKING carm specific functions */
/* not yet supported */
#elif defined ( __CSMC__ ) /*------------------ COSMIC Compiler -------------------*/
/* Cosmic specific functions */
#include <cmsis_csm.h>
#endif
/*@} end of group CMSIS_SIMD_intrinsics */
#ifdef __cplusplus
}
#endif
#endif /* __CORE_CMSIMD_H */

View File

@ -0,0 +1,864 @@
/**************************************************************************//**
* @file core_sc000.h
* @brief CMSIS SC000 Core Peripheral Access Layer Header File
* @version V4.10
* @date 18. March 2015
*
* @note
*
******************************************************************************/
/* Copyright (c) 2009 - 2015 ARM LIMITED
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of ARM nor the names of its contributors may be used
to endorse or promote products derived from this software without
specific prior written permission.
*
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS AND CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
---------------------------------------------------------------------------*/
#if defined ( __ICCARM__ )
#pragma system_include /* treat file as system include file for MISRA check */
#endif
#ifndef __CORE_SC000_H_GENERIC
#define __CORE_SC000_H_GENERIC
#ifdef __cplusplus
extern "C" {
#endif
/** \page CMSIS_MISRA_Exceptions MISRA-C:2004 Compliance Exceptions
CMSIS violates the following MISRA-C:2004 rules:
\li Required Rule 8.5, object/function definition in header file.<br>
Function definitions in header files are used to allow 'inlining'.
\li Required Rule 18.4, declaration of union type or object of union type: '{...}'.<br>
Unions are used for effective representation of core registers.
\li Advisory Rule 19.7, Function-like macro defined.<br>
Function-like macros are used to allow more efficient code.
*/
/*******************************************************************************
* CMSIS definitions
******************************************************************************/
/** \ingroup SC000
@{
*/
/* CMSIS SC000 definitions */
#define __SC000_CMSIS_VERSION_MAIN (0x04) /*!< [31:16] CMSIS HAL main version */
#define __SC000_CMSIS_VERSION_SUB (0x00) /*!< [15:0] CMSIS HAL sub version */
#define __SC000_CMSIS_VERSION ((__SC000_CMSIS_VERSION_MAIN << 16) | \
__SC000_CMSIS_VERSION_SUB ) /*!< CMSIS HAL version number */
#define __CORTEX_SC (000) /*!< Cortex secure core */
#if defined ( __CC_ARM )
#define __ASM __asm /*!< asm keyword for ARM Compiler */
#define __INLINE __inline /*!< inline keyword for ARM Compiler */
#define __STATIC_INLINE static __inline
#elif defined ( __GNUC__ )
#define __ASM __asm /*!< asm keyword for GNU Compiler */
#define __INLINE inline /*!< inline keyword for GNU Compiler */
#define __STATIC_INLINE static inline
#elif defined ( __ICCARM__ )
#define __ASM __asm /*!< asm keyword for IAR Compiler */
#define __INLINE inline /*!< inline keyword for IAR Compiler. Only available in High optimization mode! */
#define __STATIC_INLINE static inline
#elif defined ( __TMS470__ )
#define __ASM __asm /*!< asm keyword for TI CCS Compiler */
#define __STATIC_INLINE static inline
#elif defined ( __TASKING__ )
#define __ASM __asm /*!< asm keyword for TASKING Compiler */
#define __INLINE inline /*!< inline keyword for TASKING Compiler */
#define __STATIC_INLINE static inline
#elif defined ( __CSMC__ )
#define __packed
#define __ASM _asm /*!< asm keyword for COSMIC Compiler */
#define __INLINE inline /*use -pc99 on compile line !< inline keyword for COSMIC Compiler */
#define __STATIC_INLINE static inline
#endif
/** __FPU_USED indicates whether an FPU is used or not.
This core does not support an FPU at all
*/
#define __FPU_USED 0
#if defined ( __CC_ARM )
#if defined __TARGET_FPU_VFP
#warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __GNUC__ )
#if defined (__VFP_FP__) && !defined(__SOFTFP__)
#warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __ICCARM__ )
#if defined __ARMVFP__
#warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __TMS470__ )
#if defined __TI__VFP_SUPPORT____
#warning "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __TASKING__ )
#if defined __FPU_VFP__
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#elif defined ( __CSMC__ ) /* Cosmic */
#if ( __CSMC__ & 0x400) // FPU present for parser
#error "Compiler generates FPU instructions for a device without an FPU (check __FPU_PRESENT)"
#endif
#endif
#include <stdint.h> /* standard types definitions */
#include <core_cmInstr.h> /* Core Instruction Access */
#include <core_cmFunc.h> /* Core Function Access */
#ifdef __cplusplus
}
#endif
#endif /* __CORE_SC000_H_GENERIC */
#ifndef __CMSIS_GENERIC
#ifndef __CORE_SC000_H_DEPENDANT
#define __CORE_SC000_H_DEPENDANT
#ifdef __cplusplus
extern "C" {
#endif
/* check device defines and use defaults */
#if defined __CHECK_DEVICE_DEFINES
#ifndef __SC000_REV
#define __SC000_REV 0x0000
#warning "__SC000_REV not defined in device header file; using default!"
#endif
#ifndef __MPU_PRESENT
#define __MPU_PRESENT 0
#warning "__MPU_PRESENT not defined in device header file; using default!"
#endif
#ifndef __NVIC_PRIO_BITS
#define __NVIC_PRIO_BITS 2
#warning "__NVIC_PRIO_BITS not defined in device header file; using default!"
#endif
#ifndef __Vendor_SysTickConfig
#define __Vendor_SysTickConfig 0
#warning "__Vendor_SysTickConfig not defined in device header file; using default!"
#endif
#endif
/* IO definitions (access restrictions to peripheral registers) */
/**
\defgroup CMSIS_glob_defs CMSIS Global Defines
<strong>IO Type Qualifiers</strong> are used
\li to specify the access to peripheral variables.
\li for automatic generation of peripheral register debug information.
*/
#ifdef __cplusplus
#define __I volatile /*!< Defines 'read only' permissions */
#else
#define __I volatile const /*!< Defines 'read only' permissions */
#endif
#define __O volatile /*!< Defines 'write only' permissions */
#define __IO volatile /*!< Defines 'read / write' permissions */
/*@} end of group SC000 */
/*******************************************************************************
* Register Abstraction
Core Register contain:
- Core Register
- Core NVIC Register
- Core SCB Register
- Core SysTick Register
- Core MPU Register
******************************************************************************/
/** \defgroup CMSIS_core_register Defines and Type Definitions
\brief Type definitions and defines for Cortex-M processor based devices.
*/
/** \ingroup CMSIS_core_register
\defgroup CMSIS_CORE Status and Control Registers
\brief Core Register type definitions.
@{
*/
/** \brief Union type to access the Application Program Status Register (APSR).
*/
typedef union
{
struct
{
uint32_t _reserved0:28; /*!< bit: 0..27 Reserved */
uint32_t V:1; /*!< bit: 28 Overflow condition code flag */
uint32_t C:1; /*!< bit: 29 Carry condition code flag */
uint32_t Z:1; /*!< bit: 30 Zero condition code flag */
uint32_t N:1; /*!< bit: 31 Negative condition code flag */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} APSR_Type;
/* APSR Register Definitions */
#define APSR_N_Pos 31 /*!< APSR: N Position */
#define APSR_N_Msk (1UL << APSR_N_Pos) /*!< APSR: N Mask */
#define APSR_Z_Pos 30 /*!< APSR: Z Position */
#define APSR_Z_Msk (1UL << APSR_Z_Pos) /*!< APSR: Z Mask */
#define APSR_C_Pos 29 /*!< APSR: C Position */
#define APSR_C_Msk (1UL << APSR_C_Pos) /*!< APSR: C Mask */
#define APSR_V_Pos 28 /*!< APSR: V Position */
#define APSR_V_Msk (1UL << APSR_V_Pos) /*!< APSR: V Mask */
/** \brief Union type to access the Interrupt Program Status Register (IPSR).
*/
typedef union
{
struct
{
uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */
uint32_t _reserved0:23; /*!< bit: 9..31 Reserved */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} IPSR_Type;
/* IPSR Register Definitions */
#define IPSR_ISR_Pos 0 /*!< IPSR: ISR Position */
#define IPSR_ISR_Msk (0x1FFUL /*<< IPSR_ISR_Pos*/) /*!< IPSR: ISR Mask */
/** \brief Union type to access the Special-Purpose Program Status Registers (xPSR).
*/
typedef union
{
struct
{
uint32_t ISR:9; /*!< bit: 0.. 8 Exception number */
uint32_t _reserved0:15; /*!< bit: 9..23 Reserved */
uint32_t T:1; /*!< bit: 24 Thumb bit (read 0) */
uint32_t _reserved1:3; /*!< bit: 25..27 Reserved */
uint32_t V:1; /*!< bit: 28 Overflow condition code flag */
uint32_t C:1; /*!< bit: 29 Carry condition code flag */
uint32_t Z:1; /*!< bit: 30 Zero condition code flag */
uint32_t N:1; /*!< bit: 31 Negative condition code flag */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} xPSR_Type;
/* xPSR Register Definitions */
#define xPSR_N_Pos 31 /*!< xPSR: N Position */
#define xPSR_N_Msk (1UL << xPSR_N_Pos) /*!< xPSR: N Mask */
#define xPSR_Z_Pos 30 /*!< xPSR: Z Position */
#define xPSR_Z_Msk (1UL << xPSR_Z_Pos) /*!< xPSR: Z Mask */
#define xPSR_C_Pos 29 /*!< xPSR: C Position */
#define xPSR_C_Msk (1UL << xPSR_C_Pos) /*!< xPSR: C Mask */
#define xPSR_V_Pos 28 /*!< xPSR: V Position */
#define xPSR_V_Msk (1UL << xPSR_V_Pos) /*!< xPSR: V Mask */
#define xPSR_T_Pos 24 /*!< xPSR: T Position */
#define xPSR_T_Msk (1UL << xPSR_T_Pos) /*!< xPSR: T Mask */
#define xPSR_ISR_Pos 0 /*!< xPSR: ISR Position */
#define xPSR_ISR_Msk (0x1FFUL /*<< xPSR_ISR_Pos*/) /*!< xPSR: ISR Mask */
/** \brief Union type to access the Control Registers (CONTROL).
*/
typedef union
{
struct
{
uint32_t _reserved0:1; /*!< bit: 0 Reserved */
uint32_t SPSEL:1; /*!< bit: 1 Stack to be used */
uint32_t _reserved1:30; /*!< bit: 2..31 Reserved */
} b; /*!< Structure used for bit access */
uint32_t w; /*!< Type used for word access */
} CONTROL_Type;
/* CONTROL Register Definitions */
#define CONTROL_SPSEL_Pos 1 /*!< CONTROL: SPSEL Position */
#define CONTROL_SPSEL_Msk (1UL << CONTROL_SPSEL_Pos) /*!< CONTROL: SPSEL Mask */
/*@} end of group CMSIS_CORE */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_NVIC Nested Vectored Interrupt Controller (NVIC)
\brief Type definitions for the NVIC Registers
@{
*/
/** \brief Structure type to access the Nested Vectored Interrupt Controller (NVIC).
*/
typedef struct
{
__IO uint32_t ISER[1]; /*!< Offset: 0x000 (R/W) Interrupt Set Enable Register */
uint32_t RESERVED0[31];
__IO uint32_t ICER[1]; /*!< Offset: 0x080 (R/W) Interrupt Clear Enable Register */
uint32_t RSERVED1[31];
__IO uint32_t ISPR[1]; /*!< Offset: 0x100 (R/W) Interrupt Set Pending Register */
uint32_t RESERVED2[31];
__IO uint32_t ICPR[1]; /*!< Offset: 0x180 (R/W) Interrupt Clear Pending Register */
uint32_t RESERVED3[31];
uint32_t RESERVED4[64];
__IO uint32_t IP[8]; /*!< Offset: 0x300 (R/W) Interrupt Priority Register */
} NVIC_Type;
/*@} end of group CMSIS_NVIC */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_SCB System Control Block (SCB)
\brief Type definitions for the System Control Block Registers
@{
*/
/** \brief Structure type to access the System Control Block (SCB).
*/
typedef struct
{
__I uint32_t CPUID; /*!< Offset: 0x000 (R/ ) CPUID Base Register */
__IO uint32_t ICSR; /*!< Offset: 0x004 (R/W) Interrupt Control and State Register */
__IO uint32_t VTOR; /*!< Offset: 0x008 (R/W) Vector Table Offset Register */
__IO uint32_t AIRCR; /*!< Offset: 0x00C (R/W) Application Interrupt and Reset Control Register */
__IO uint32_t SCR; /*!< Offset: 0x010 (R/W) System Control Register */
__IO uint32_t CCR; /*!< Offset: 0x014 (R/W) Configuration Control Register */
uint32_t RESERVED0[1];
__IO uint32_t SHP[2]; /*!< Offset: 0x01C (R/W) System Handlers Priority Registers. [0] is RESERVED */
__IO uint32_t SHCSR; /*!< Offset: 0x024 (R/W) System Handler Control and State Register */
uint32_t RESERVED1[154];
__IO uint32_t SFCR; /*!< Offset: 0x290 (R/W) Security Features Control Register */
} SCB_Type;
/* SCB CPUID Register Definitions */
#define SCB_CPUID_IMPLEMENTER_Pos 24 /*!< SCB CPUID: IMPLEMENTER Position */
#define SCB_CPUID_IMPLEMENTER_Msk (0xFFUL << SCB_CPUID_IMPLEMENTER_Pos) /*!< SCB CPUID: IMPLEMENTER Mask */
#define SCB_CPUID_VARIANT_Pos 20 /*!< SCB CPUID: VARIANT Position */
#define SCB_CPUID_VARIANT_Msk (0xFUL << SCB_CPUID_VARIANT_Pos) /*!< SCB CPUID: VARIANT Mask */
#define SCB_CPUID_ARCHITECTURE_Pos 16 /*!< SCB CPUID: ARCHITECTURE Position */
#define SCB_CPUID_ARCHITECTURE_Msk (0xFUL << SCB_CPUID_ARCHITECTURE_Pos) /*!< SCB CPUID: ARCHITECTURE Mask */
#define SCB_CPUID_PARTNO_Pos 4 /*!< SCB CPUID: PARTNO Position */
#define SCB_CPUID_PARTNO_Msk (0xFFFUL << SCB_CPUID_PARTNO_Pos) /*!< SCB CPUID: PARTNO Mask */
#define SCB_CPUID_REVISION_Pos 0 /*!< SCB CPUID: REVISION Position */
#define SCB_CPUID_REVISION_Msk (0xFUL /*<< SCB_CPUID_REVISION_Pos*/) /*!< SCB CPUID: REVISION Mask */
/* SCB Interrupt Control State Register Definitions */
#define SCB_ICSR_NMIPENDSET_Pos 31 /*!< SCB ICSR: NMIPENDSET Position */
#define SCB_ICSR_NMIPENDSET_Msk (1UL << SCB_ICSR_NMIPENDSET_Pos) /*!< SCB ICSR: NMIPENDSET Mask */
#define SCB_ICSR_PENDSVSET_Pos 28 /*!< SCB ICSR: PENDSVSET Position */
#define SCB_ICSR_PENDSVSET_Msk (1UL << SCB_ICSR_PENDSVSET_Pos) /*!< SCB ICSR: PENDSVSET Mask */
#define SCB_ICSR_PENDSVCLR_Pos 27 /*!< SCB ICSR: PENDSVCLR Position */
#define SCB_ICSR_PENDSVCLR_Msk (1UL << SCB_ICSR_PENDSVCLR_Pos) /*!< SCB ICSR: PENDSVCLR Mask */
#define SCB_ICSR_PENDSTSET_Pos 26 /*!< SCB ICSR: PENDSTSET Position */
#define SCB_ICSR_PENDSTSET_Msk (1UL << SCB_ICSR_PENDSTSET_Pos) /*!< SCB ICSR: PENDSTSET Mask */
#define SCB_ICSR_PENDSTCLR_Pos 25 /*!< SCB ICSR: PENDSTCLR Position */
#define SCB_ICSR_PENDSTCLR_Msk (1UL << SCB_ICSR_PENDSTCLR_Pos) /*!< SCB ICSR: PENDSTCLR Mask */
#define SCB_ICSR_ISRPREEMPT_Pos 23 /*!< SCB ICSR: ISRPREEMPT Position */
#define SCB_ICSR_ISRPREEMPT_Msk (1UL << SCB_ICSR_ISRPREEMPT_Pos) /*!< SCB ICSR: ISRPREEMPT Mask */
#define SCB_ICSR_ISRPENDING_Pos 22 /*!< SCB ICSR: ISRPENDING Position */
#define SCB_ICSR_ISRPENDING_Msk (1UL << SCB_ICSR_ISRPENDING_Pos) /*!< SCB ICSR: ISRPENDING Mask */
#define SCB_ICSR_VECTPENDING_Pos 12 /*!< SCB ICSR: VECTPENDING Position */
#define SCB_ICSR_VECTPENDING_Msk (0x1FFUL << SCB_ICSR_VECTPENDING_Pos) /*!< SCB ICSR: VECTPENDING Mask */
#define SCB_ICSR_VECTACTIVE_Pos 0 /*!< SCB ICSR: VECTACTIVE Position */
#define SCB_ICSR_VECTACTIVE_Msk (0x1FFUL /*<< SCB_ICSR_VECTACTIVE_Pos*/) /*!< SCB ICSR: VECTACTIVE Mask */
/* SCB Interrupt Control State Register Definitions */
#define SCB_VTOR_TBLOFF_Pos 7 /*!< SCB VTOR: TBLOFF Position */
#define SCB_VTOR_TBLOFF_Msk (0x1FFFFFFUL << SCB_VTOR_TBLOFF_Pos) /*!< SCB VTOR: TBLOFF Mask */
/* SCB Application Interrupt and Reset Control Register Definitions */
#define SCB_AIRCR_VECTKEY_Pos 16 /*!< SCB AIRCR: VECTKEY Position */
#define SCB_AIRCR_VECTKEY_Msk (0xFFFFUL << SCB_AIRCR_VECTKEY_Pos) /*!< SCB AIRCR: VECTKEY Mask */
#define SCB_AIRCR_VECTKEYSTAT_Pos 16 /*!< SCB AIRCR: VECTKEYSTAT Position */
#define SCB_AIRCR_VECTKEYSTAT_Msk (0xFFFFUL << SCB_AIRCR_VECTKEYSTAT_Pos) /*!< SCB AIRCR: VECTKEYSTAT Mask */
#define SCB_AIRCR_ENDIANESS_Pos 15 /*!< SCB AIRCR: ENDIANESS Position */
#define SCB_AIRCR_ENDIANESS_Msk (1UL << SCB_AIRCR_ENDIANESS_Pos) /*!< SCB AIRCR: ENDIANESS Mask */
#define SCB_AIRCR_SYSRESETREQ_Pos 2 /*!< SCB AIRCR: SYSRESETREQ Position */
#define SCB_AIRCR_SYSRESETREQ_Msk (1UL << SCB_AIRCR_SYSRESETREQ_Pos) /*!< SCB AIRCR: SYSRESETREQ Mask */
#define SCB_AIRCR_VECTCLRACTIVE_Pos 1 /*!< SCB AIRCR: VECTCLRACTIVE Position */
#define SCB_AIRCR_VECTCLRACTIVE_Msk (1UL << SCB_AIRCR_VECTCLRACTIVE_Pos) /*!< SCB AIRCR: VECTCLRACTIVE Mask */
/* SCB System Control Register Definitions */
#define SCB_SCR_SEVONPEND_Pos 4 /*!< SCB SCR: SEVONPEND Position */
#define SCB_SCR_SEVONPEND_Msk (1UL << SCB_SCR_SEVONPEND_Pos) /*!< SCB SCR: SEVONPEND Mask */
#define SCB_SCR_SLEEPDEEP_Pos 2 /*!< SCB SCR: SLEEPDEEP Position */
#define SCB_SCR_SLEEPDEEP_Msk (1UL << SCB_SCR_SLEEPDEEP_Pos) /*!< SCB SCR: SLEEPDEEP Mask */
#define SCB_SCR_SLEEPONEXIT_Pos 1 /*!< SCB SCR: SLEEPONEXIT Position */
#define SCB_SCR_SLEEPONEXIT_Msk (1UL << SCB_SCR_SLEEPONEXIT_Pos) /*!< SCB SCR: SLEEPONEXIT Mask */
/* SCB Configuration Control Register Definitions */
#define SCB_CCR_STKALIGN_Pos 9 /*!< SCB CCR: STKALIGN Position */
#define SCB_CCR_STKALIGN_Msk (1UL << SCB_CCR_STKALIGN_Pos) /*!< SCB CCR: STKALIGN Mask */
#define SCB_CCR_UNALIGN_TRP_Pos 3 /*!< SCB CCR: UNALIGN_TRP Position */
#define SCB_CCR_UNALIGN_TRP_Msk (1UL << SCB_CCR_UNALIGN_TRP_Pos) /*!< SCB CCR: UNALIGN_TRP Mask */
/* SCB System Handler Control and State Register Definitions */
#define SCB_SHCSR_SVCALLPENDED_Pos 15 /*!< SCB SHCSR: SVCALLPENDED Position */
#define SCB_SHCSR_SVCALLPENDED_Msk (1UL << SCB_SHCSR_SVCALLPENDED_Pos) /*!< SCB SHCSR: SVCALLPENDED Mask */
/*@} end of group CMSIS_SCB */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_SCnSCB System Controls not in SCB (SCnSCB)
\brief Type definitions for the System Control and ID Register not in the SCB
@{
*/
/** \brief Structure type to access the System Control and ID Register not in the SCB.
*/
typedef struct
{
uint32_t RESERVED0[2];
__IO uint32_t ACTLR; /*!< Offset: 0x008 (R/W) Auxiliary Control Register */
} SCnSCB_Type;
/* Auxiliary Control Register Definitions */
#define SCnSCB_ACTLR_DISMCYCINT_Pos 0 /*!< ACTLR: DISMCYCINT Position */
#define SCnSCB_ACTLR_DISMCYCINT_Msk (1UL /*<< SCnSCB_ACTLR_DISMCYCINT_Pos*/) /*!< ACTLR: DISMCYCINT Mask */
/*@} end of group CMSIS_SCnotSCB */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_SysTick System Tick Timer (SysTick)
\brief Type definitions for the System Timer Registers.
@{
*/
/** \brief Structure type to access the System Timer (SysTick).
*/
typedef struct
{
__IO uint32_t CTRL; /*!< Offset: 0x000 (R/W) SysTick Control and Status Register */
__IO uint32_t LOAD; /*!< Offset: 0x004 (R/W) SysTick Reload Value Register */
__IO uint32_t VAL; /*!< Offset: 0x008 (R/W) SysTick Current Value Register */
__I uint32_t CALIB; /*!< Offset: 0x00C (R/ ) SysTick Calibration Register */
} SysTick_Type;
/* SysTick Control / Status Register Definitions */
#define SysTick_CTRL_COUNTFLAG_Pos 16 /*!< SysTick CTRL: COUNTFLAG Position */
#define SysTick_CTRL_COUNTFLAG_Msk (1UL << SysTick_CTRL_COUNTFLAG_Pos) /*!< SysTick CTRL: COUNTFLAG Mask */
#define SysTick_CTRL_CLKSOURCE_Pos 2 /*!< SysTick CTRL: CLKSOURCE Position */
#define SysTick_CTRL_CLKSOURCE_Msk (1UL << SysTick_CTRL_CLKSOURCE_Pos) /*!< SysTick CTRL: CLKSOURCE Mask */
#define SysTick_CTRL_TICKINT_Pos 1 /*!< SysTick CTRL: TICKINT Position */
#define SysTick_CTRL_TICKINT_Msk (1UL << SysTick_CTRL_TICKINT_Pos) /*!< SysTick CTRL: TICKINT Mask */
#define SysTick_CTRL_ENABLE_Pos 0 /*!< SysTick CTRL: ENABLE Position */
#define SysTick_CTRL_ENABLE_Msk (1UL /*<< SysTick_CTRL_ENABLE_Pos*/) /*!< SysTick CTRL: ENABLE Mask */
/* SysTick Reload Register Definitions */
#define SysTick_LOAD_RELOAD_Pos 0 /*!< SysTick LOAD: RELOAD Position */
#define SysTick_LOAD_RELOAD_Msk (0xFFFFFFUL /*<< SysTick_LOAD_RELOAD_Pos*/) /*!< SysTick LOAD: RELOAD Mask */
/* SysTick Current Register Definitions */
#define SysTick_VAL_CURRENT_Pos 0 /*!< SysTick VAL: CURRENT Position */
#define SysTick_VAL_CURRENT_Msk (0xFFFFFFUL /*<< SysTick_VAL_CURRENT_Pos*/) /*!< SysTick VAL: CURRENT Mask */
/* SysTick Calibration Register Definitions */
#define SysTick_CALIB_NOREF_Pos 31 /*!< SysTick CALIB: NOREF Position */
#define SysTick_CALIB_NOREF_Msk (1UL << SysTick_CALIB_NOREF_Pos) /*!< SysTick CALIB: NOREF Mask */
#define SysTick_CALIB_SKEW_Pos 30 /*!< SysTick CALIB: SKEW Position */
#define SysTick_CALIB_SKEW_Msk (1UL << SysTick_CALIB_SKEW_Pos) /*!< SysTick CALIB: SKEW Mask */
#define SysTick_CALIB_TENMS_Pos 0 /*!< SysTick CALIB: TENMS Position */
#define SysTick_CALIB_TENMS_Msk (0xFFFFFFUL /*<< SysTick_CALIB_TENMS_Pos*/) /*!< SysTick CALIB: TENMS Mask */
/*@} end of group CMSIS_SysTick */
#if (__MPU_PRESENT == 1)
/** \ingroup CMSIS_core_register
\defgroup CMSIS_MPU Memory Protection Unit (MPU)
\brief Type definitions for the Memory Protection Unit (MPU)
@{
*/
/** \brief Structure type to access the Memory Protection Unit (MPU).
*/
typedef struct
{
__I uint32_t TYPE; /*!< Offset: 0x000 (R/ ) MPU Type Register */
__IO uint32_t CTRL; /*!< Offset: 0x004 (R/W) MPU Control Register */
__IO uint32_t RNR; /*!< Offset: 0x008 (R/W) MPU Region RNRber Register */
__IO uint32_t RBAR; /*!< Offset: 0x00C (R/W) MPU Region Base Address Register */
__IO uint32_t RASR; /*!< Offset: 0x010 (R/W) MPU Region Attribute and Size Register */
} MPU_Type;
/* MPU Type Register */
#define MPU_TYPE_IREGION_Pos 16 /*!< MPU TYPE: IREGION Position */
#define MPU_TYPE_IREGION_Msk (0xFFUL << MPU_TYPE_IREGION_Pos) /*!< MPU TYPE: IREGION Mask */
#define MPU_TYPE_DREGION_Pos 8 /*!< MPU TYPE: DREGION Position */
#define MPU_TYPE_DREGION_Msk (0xFFUL << MPU_TYPE_DREGION_Pos) /*!< MPU TYPE: DREGION Mask */
#define MPU_TYPE_SEPARATE_Pos 0 /*!< MPU TYPE: SEPARATE Position */
#define MPU_TYPE_SEPARATE_Msk (1UL /*<< MPU_TYPE_SEPARATE_Pos*/) /*!< MPU TYPE: SEPARATE Mask */
/* MPU Control Register */
#define MPU_CTRL_PRIVDEFENA_Pos 2 /*!< MPU CTRL: PRIVDEFENA Position */
#define MPU_CTRL_PRIVDEFENA_Msk (1UL << MPU_CTRL_PRIVDEFENA_Pos) /*!< MPU CTRL: PRIVDEFENA Mask */
#define MPU_CTRL_HFNMIENA_Pos 1 /*!< MPU CTRL: HFNMIENA Position */
#define MPU_CTRL_HFNMIENA_Msk (1UL << MPU_CTRL_HFNMIENA_Pos) /*!< MPU CTRL: HFNMIENA Mask */
#define MPU_CTRL_ENABLE_Pos 0 /*!< MPU CTRL: ENABLE Position */
#define MPU_CTRL_ENABLE_Msk (1UL /*<< MPU_CTRL_ENABLE_Pos*/) /*!< MPU CTRL: ENABLE Mask */
/* MPU Region Number Register */
#define MPU_RNR_REGION_Pos 0 /*!< MPU RNR: REGION Position */
#define MPU_RNR_REGION_Msk (0xFFUL /*<< MPU_RNR_REGION_Pos*/) /*!< MPU RNR: REGION Mask */
/* MPU Region Base Address Register */
#define MPU_RBAR_ADDR_Pos 8 /*!< MPU RBAR: ADDR Position */
#define MPU_RBAR_ADDR_Msk (0xFFFFFFUL << MPU_RBAR_ADDR_Pos) /*!< MPU RBAR: ADDR Mask */
#define MPU_RBAR_VALID_Pos 4 /*!< MPU RBAR: VALID Position */
#define MPU_RBAR_VALID_Msk (1UL << MPU_RBAR_VALID_Pos) /*!< MPU RBAR: VALID Mask */
#define MPU_RBAR_REGION_Pos 0 /*!< MPU RBAR: REGION Position */
#define MPU_RBAR_REGION_Msk (0xFUL /*<< MPU_RBAR_REGION_Pos*/) /*!< MPU RBAR: REGION Mask */
/* MPU Region Attribute and Size Register */
#define MPU_RASR_ATTRS_Pos 16 /*!< MPU RASR: MPU Region Attribute field Position */
#define MPU_RASR_ATTRS_Msk (0xFFFFUL << MPU_RASR_ATTRS_Pos) /*!< MPU RASR: MPU Region Attribute field Mask */
#define MPU_RASR_XN_Pos 28 /*!< MPU RASR: ATTRS.XN Position */
#define MPU_RASR_XN_Msk (1UL << MPU_RASR_XN_Pos) /*!< MPU RASR: ATTRS.XN Mask */
#define MPU_RASR_AP_Pos 24 /*!< MPU RASR: ATTRS.AP Position */
#define MPU_RASR_AP_Msk (0x7UL << MPU_RASR_AP_Pos) /*!< MPU RASR: ATTRS.AP Mask */
#define MPU_RASR_TEX_Pos 19 /*!< MPU RASR: ATTRS.TEX Position */
#define MPU_RASR_TEX_Msk (0x7UL << MPU_RASR_TEX_Pos) /*!< MPU RASR: ATTRS.TEX Mask */
#define MPU_RASR_S_Pos 18 /*!< MPU RASR: ATTRS.S Position */
#define MPU_RASR_S_Msk (1UL << MPU_RASR_S_Pos) /*!< MPU RASR: ATTRS.S Mask */
#define MPU_RASR_C_Pos 17 /*!< MPU RASR: ATTRS.C Position */
#define MPU_RASR_C_Msk (1UL << MPU_RASR_C_Pos) /*!< MPU RASR: ATTRS.C Mask */
#define MPU_RASR_B_Pos 16 /*!< MPU RASR: ATTRS.B Position */
#define MPU_RASR_B_Msk (1UL << MPU_RASR_B_Pos) /*!< MPU RASR: ATTRS.B Mask */
#define MPU_RASR_SRD_Pos 8 /*!< MPU RASR: Sub-Region Disable Position */
#define MPU_RASR_SRD_Msk (0xFFUL << MPU_RASR_SRD_Pos) /*!< MPU RASR: Sub-Region Disable Mask */
#define MPU_RASR_SIZE_Pos 1 /*!< MPU RASR: Region Size Field Position */
#define MPU_RASR_SIZE_Msk (0x1FUL << MPU_RASR_SIZE_Pos) /*!< MPU RASR: Region Size Field Mask */
#define MPU_RASR_ENABLE_Pos 0 /*!< MPU RASR: Region enable bit Position */
#define MPU_RASR_ENABLE_Msk (1UL /*<< MPU_RASR_ENABLE_Pos*/) /*!< MPU RASR: Region enable bit Disable Mask */
/*@} end of group CMSIS_MPU */
#endif
/** \ingroup CMSIS_core_register
\defgroup CMSIS_CoreDebug Core Debug Registers (CoreDebug)
\brief SC000 Core Debug Registers (DCB registers, SHCSR, and DFSR)
are only accessible over DAP and not via processor. Therefore
they are not covered by the Cortex-M0 header file.
@{
*/
/*@} end of group CMSIS_CoreDebug */
/** \ingroup CMSIS_core_register
\defgroup CMSIS_core_base Core Definitions
\brief Definitions for base addresses, unions, and structures.
@{
*/
/* Memory mapping of SC000 Hardware */
#define SCS_BASE (0xE000E000UL) /*!< System Control Space Base Address */
#define SysTick_BASE (SCS_BASE + 0x0010UL) /*!< SysTick Base Address */
#define NVIC_BASE (SCS_BASE + 0x0100UL) /*!< NVIC Base Address */
#define SCB_BASE (SCS_BASE + 0x0D00UL) /*!< System Control Block Base Address */
#define SCnSCB ((SCnSCB_Type *) SCS_BASE ) /*!< System control Register not in SCB */
#define SCB ((SCB_Type *) SCB_BASE ) /*!< SCB configuration struct */
#define SysTick ((SysTick_Type *) SysTick_BASE ) /*!< SysTick configuration struct */
#define NVIC ((NVIC_Type *) NVIC_BASE ) /*!< NVIC configuration struct */
#if (__MPU_PRESENT == 1)
#define MPU_BASE (SCS_BASE + 0x0D90UL) /*!< Memory Protection Unit */
#define MPU ((MPU_Type *) MPU_BASE ) /*!< Memory Protection Unit */
#endif
/*@} */
/*******************************************************************************
* Hardware Abstraction Layer
Core Function Interface contains:
- Core NVIC Functions
- Core SysTick Functions
- Core Register Access Functions
******************************************************************************/
/** \defgroup CMSIS_Core_FunctionInterface Functions and Instructions Reference
*/
/* ########################## NVIC functions #################################### */
/** \ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_NVICFunctions NVIC Functions
\brief Functions that manage interrupts and exceptions via the NVIC.
@{
*/
/* Interrupt Priorities are WORD accessible only under ARMv6M */
/* The following MACROS handle generation of the register offset and byte masks */
#define _BIT_SHIFT(IRQn) ( ((((uint32_t)(int32_t)(IRQn)) ) & 0x03UL) * 8UL)
#define _SHP_IDX(IRQn) ( (((((uint32_t)(int32_t)(IRQn)) & 0x0FUL)-8UL) >> 2UL) )
#define _IP_IDX(IRQn) ( (((uint32_t)(int32_t)(IRQn)) >> 2UL) )
/** \brief Enable External Interrupt
The function enables a device-specific interrupt in the NVIC interrupt controller.
\param [in] IRQn External interrupt number. Value cannot be negative.
*/
__STATIC_INLINE void NVIC_EnableIRQ(IRQn_Type IRQn)
{
NVIC->ISER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
/** \brief Disable External Interrupt
The function disables a device-specific interrupt in the NVIC interrupt controller.
\param [in] IRQn External interrupt number. Value cannot be negative.
*/
__STATIC_INLINE void NVIC_DisableIRQ(IRQn_Type IRQn)
{
NVIC->ICER[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
/** \brief Get Pending Interrupt
The function reads the pending register in the NVIC and returns the pending bit
for the specified interrupt.
\param [in] IRQn Interrupt number.
\return 0 Interrupt status is not pending.
\return 1 Interrupt status is pending.
*/
__STATIC_INLINE uint32_t NVIC_GetPendingIRQ(IRQn_Type IRQn)
{
return((uint32_t)(((NVIC->ISPR[0] & (1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL))) != 0UL) ? 1UL : 0UL));
}
/** \brief Set Pending Interrupt
The function sets the pending bit of an external interrupt.
\param [in] IRQn Interrupt number. Value cannot be negative.
*/
__STATIC_INLINE void NVIC_SetPendingIRQ(IRQn_Type IRQn)
{
NVIC->ISPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
/** \brief Clear Pending Interrupt
The function clears the pending bit of an external interrupt.
\param [in] IRQn External interrupt number. Value cannot be negative.
*/
__STATIC_INLINE void NVIC_ClearPendingIRQ(IRQn_Type IRQn)
{
NVIC->ICPR[0] = (uint32_t)(1UL << (((uint32_t)(int32_t)IRQn) & 0x1FUL));
}
/** \brief Set Interrupt Priority
The function sets the priority of an interrupt.
\note The priority cannot be set for every core interrupt.
\param [in] IRQn Interrupt number.
\param [in] priority Priority to set.
*/
__STATIC_INLINE void NVIC_SetPriority(IRQn_Type IRQn, uint32_t priority)
{
if((int32_t)(IRQn) < 0) {
SCB->SHP[_SHP_IDX(IRQn)] = ((uint32_t)(SCB->SHP[_SHP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) |
(((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn)));
}
else {
NVIC->IP[_IP_IDX(IRQn)] = ((uint32_t)(NVIC->IP[_IP_IDX(IRQn)] & ~(0xFFUL << _BIT_SHIFT(IRQn))) |
(((priority << (8 - __NVIC_PRIO_BITS)) & (uint32_t)0xFFUL) << _BIT_SHIFT(IRQn)));
}
}
/** \brief Get Interrupt Priority
The function reads the priority of an interrupt. The interrupt
number can be positive to specify an external (device specific)
interrupt, or negative to specify an internal (core) interrupt.
\param [in] IRQn Interrupt number.
\return Interrupt Priority. Value is aligned automatically to the implemented
priority bits of the microcontroller.
*/
__STATIC_INLINE uint32_t NVIC_GetPriority(IRQn_Type IRQn)
{
if((int32_t)(IRQn) < 0) {
return((uint32_t)(((SCB->SHP[_SHP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS)));
}
else {
return((uint32_t)(((NVIC->IP[ _IP_IDX(IRQn)] >> _BIT_SHIFT(IRQn) ) & (uint32_t)0xFFUL) >> (8 - __NVIC_PRIO_BITS)));
}
}
/** \brief System Reset
The function initiates a system reset request to reset the MCU.
*/
__STATIC_INLINE void NVIC_SystemReset(void)
{
__DSB(); /* Ensure all outstanding memory accesses included
buffered write are completed before reset */
SCB->AIRCR = ((0x5FAUL << SCB_AIRCR_VECTKEY_Pos) |
SCB_AIRCR_SYSRESETREQ_Msk);
__DSB(); /* Ensure completion of memory access */
while(1) { __NOP(); } /* wait until reset */
}
/*@} end of CMSIS_Core_NVICFunctions */
/* ################################## SysTick function ############################################ */
/** \ingroup CMSIS_Core_FunctionInterface
\defgroup CMSIS_Core_SysTickFunctions SysTick Functions
\brief Functions that configure the System.
@{
*/
#if (__Vendor_SysTickConfig == 0)
/** \brief System Tick Configuration
The function initializes the System Timer and its interrupt, and starts the System Tick Timer.
Counter is in free running mode to generate periodic interrupts.
\param [in] ticks Number of ticks between two interrupts.
\return 0 Function succeeded.
\return 1 Function failed.
\note When the variable <b>__Vendor_SysTickConfig</b> is set to 1, then the
function <b>SysTick_Config</b> is not included. In this case, the file <b><i>device</i>.h</b>
must contain a vendor-specific implementation of this function.
*/
__STATIC_INLINE uint32_t SysTick_Config(uint32_t ticks)
{
if ((ticks - 1UL) > SysTick_LOAD_RELOAD_Msk) {return (1UL);} /* Reload value impossible */
SysTick->LOAD = (uint32_t)(ticks - 1UL); /* set reload register */
NVIC_SetPriority (SysTick_IRQn, (1UL << __NVIC_PRIO_BITS) - 1UL); /* set Priority for Systick Interrupt */
SysTick->VAL = 0UL; /* Load the SysTick Counter Value */
SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk |
SysTick_CTRL_TICKINT_Msk |
SysTick_CTRL_ENABLE_Msk; /* Enable SysTick IRQ and SysTick Timer */
return (0UL); /* Function successful */
}
#endif
/*@} end of CMSIS_Core_SysTickFunctions */
#ifdef __cplusplus
}
#endif
#endif /* __CORE_SC000_H_DEPENDANT */
#endif /* __CMSIS_GENERIC */

1675
DSP_LIB/Include/core_sc300.h Normal file

File diff suppressed because it is too large Load Diff

Binary file not shown.

View File

@ -1,3 +1,3 @@
# HL-PDJ-1
# HL-WXCK-I
家用盆底肌训练仪程序
无线产后治疗仪软件代码

12
Readme.txt Normal file
View File

@ -0,0 +1,12 @@
V0.0.0.0
建立工程,修改刺激方案,输出双向波
V0.0.0.1
删除触发电刺激、采集相关内容,增加电流按键检测功能
V0.0.0.2
将SAADC的采样位数由14位改为12位精度降低这样可以一次性初始化所有采集通道如果使用14位则一次只能使用一个通道
电极脱落检测电压门限为90mv电流小于7毫安不检测
V0.0.0.3
修改刺激波形使用TIM1定时器通过定时器控制PE3PE4的输出PWM1为高电平
V1.0.0.1
增加电刺激返回的时候定时器清0和GPIOTE初始化解决初始输出电平时高时低问题

108
app/Inc/IoControl.h Normal file
View File

@ -0,0 +1,108 @@
/********************************************************************
Copyright (c) 2021 Xiangyu Medical Co.Ltd. All rights reserved.
FileName : IoControl.h
Author : zhangdawei
Version : V1.0
Date :
Note :
History :
********************************************************************/
#ifndef _IOCONTROL_H__
#define _IOCONTROL_H__
/* Includes ------------------------------------------------------*/
#include "nrf52.h"
#include "nrf_gpio.h"
#include "timer.h"
#include "drv_saadc.h"
#include "drv_uart.h"
#include "nrf_drv_gpiote.h"
//Log需要引用的头文件
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
#include "nrf_delay.h"
/* Public define -------------------------------------------------*/
#define MERGE(Msb,Lsb) ((Msb<<8)|Lsb)
/* 按键检测 */
#define KEY_PWR_SWITICH ( 16 )
/* 电源锁定 */
#define KEY_POWER ( 13 )
/* 指示灯 */
#define LED_YELLOW ( 11 )
#define LED_WHITE ( 12 )
/* DAC 引脚*/
#define PWM_DAC_GPIO ( 26 )
/* 充电芯片引脚定义,低电平是充电中,高电平是充电完成或未充电 */
#define CHG_MANAGER_EN ( 15 ) //充电管理芯片的EN引脚内部200K下拉电阻。 高电平:禁用充电器 低电平Low或悬空Floating启用充电器
#define CHG_MANAGER_PPR ( 23 ) //充电管理芯片的PPR引脚 开漏输出外部上拉3.0V,低电平:输入充电电压正常,高电平:输入充电电压异常
#define CHG_MANAGER_CHG ( 14 ) //充电指示引脚,低电平是充电中,充电结束为高电平
#define STIM_RMS_RELAY_PIN ( 27 ) // 肌电采集继电器控制引脚
#define STIM_RELAY_PIN ( 28 ) //刺激继电器控制引脚
#define SAMPLE_POWER_PIN ( 20 ) //采样电源控制引脚
#define BOOST_DISCHARGE_PIN ( 18 ) //boost升压放电引脚
#define BASE_WAVE_06_PIN ( 6 ) //刺激基础波形控制引脚6
#define BASE_WAVE_07_PIN ( 7 ) //刺激基础波形控制引脚7
#define BASE_WAVE_08_PIN ( 8 ) //刺激基础波形控制引脚8
#define BOOST_VOLTAGE_CONTROL_PIN ( 25 ) //boost电压控制引脚
/* Public typedef ------------------------------------------------*/
//设备开关机状态
typedef enum
{
POWER_OPEN = 0,
POWER_CLOSE
}DeviceStateInfo_e;
// 充电状态
typedef enum
{
Uncharged = 0,
Charging,
ChargeComplete
}ChargingStateInfo_e;
typedef enum
{
Bit_RESET = 0,
Bit_SET
}BitAction;
typedef struct{
nrf_drv_gpiote_pin_t KeyPinNumber;
bool shineng;
}KeyStateInfo_t;
/* Public constants ----------------------------------------------*/
/* Public variables ----------------------------------------------*/
extern DeviceStateInfo_e DeviceState;
extern ChargingStateInfo_e ChargeState;
extern ChargingStateInfo_e ChargeLastState;
/* Public function prototypes ------------------------------------*/
void StartAdv(void);
void StopAdv(void);
void GpioInit(void);
void EXIT_KEY_Init(void);
void open_acquisition_relay(void);
void close_acquisition_relay(void);
void LedControl(void);
void StimStateInfoStructInit(SchemeData_t SchemeDataIn);
void VariableInit(void);
void StimOutCtlOpen(void);
void StimOutCtlClose(void);
void StimReleaseOpen(void);
void StimReleaseClose(void);
void PreStorageSchemeDataInit(void);
void KeyPinHandler(void);
void close_stimulate_relay(void);
void open_stimulate_relay(void);
#endif
/*************************** END OF FILE ***************************/

45
app/Inc/drv_saadc.h Normal file
View File

@ -0,0 +1,45 @@
/********************************************************************
Copyright (c) 2021 Xiangyu Medical Co.Ltd. All rights reserved.
FileName : drv_saadc.h
Author : zhangdawei
Version : V1.0
Date :
Note :
History :
********************************************************************/
/* Includes ------------------------------------------------------*/
#ifndef DRV_SAADC_H__
#define DRV_SAADC_H__
#include "nrf_drv_timer.h"
#include "nrf_drv_saadc.h"
#include "IoControl.h"
/* Public define -------------------------------------------------*/
#define SAADC_BATTERY_CHANNEL 1 // 电池电压检测通道
#define SAADC_ELECTRODE_CHANNEL 2 // 电极片脱落电压
#define SAADC_RMS_SAMPLE_CHANNEL 0 // 肌电采样通道
#define AD_RAW_MAX 50
/* Public typedef ------------------------------------------------*/
typedef struct
{
//float AdRaw[AD_RAW_MAX+50];//原始值数组
float EmgValue;//计算值
unsigned char emgCnt;
}emg_data_t;
/* Public constants ----------------------------------------------*/
/* Public variables ----------------------------------------------*/
extern uint8_t Battery_Percentage;
/* Public function prototypes ------------------------------------*/
void battery_adc_init(void);
void timer1_output_ctrl_init(void);
void rms_saadc_init(void);
void PPIEegAdcInit(void);
void timer3_rms_init(void);
void timer3_rms_stop(void);
void timer3_rms_start(void);
void CalculateBatteryPower(void);
#endif
/*************************** END OF FILE ***************************/

241
app/Inc/drv_uart.h Normal file
View File

@ -0,0 +1,241 @@
/********************************************************************
Copyright (c) 2021 Xiangyu Medical Co.Ltd. All rights reserved.
FileName : drv_uart.h
Author : zhangdawei
Version : V1.0
Date :
Note :
History :
********************************************************************/
/* Includes ------------------------------------------------------*/
#ifndef DRV_UART_H__
#define DRV_UART_H__
#include "sdk_config.h"
#include "ble_nus.h"
#include "ble_link_ctx_manager.h"
/* Public define -------------------------------------------------*/
#define ONE_SECOND ( 1000000 ) /* 1s = 1000000us */
/* 功能码定义 */
#define RUN_ROLL ( 0x81 ) //运行轮询
#define VERSION_INQUIRY ( 0x82 ) //版本查询
#define STIM_PARA_CONTROL ( 0x83 ) //模式、脉宽、频率、斜坡时间设置
#define START_STOP_CONTROL ( 0x84 ) //控制
#define PRE_ADJUST ( 0x85 ) //预调节
#define CURRENT_CONTROL ( 0x86 ) //电流设置
#define EEG_DATA ( 0x87 ) //肌电数据上报
#define TRIG_COLLECT_START_CONTROL ( 0x88 ) //触发采集开始
#define TRIG_STIM_START_CONTROL ( 0x89 ) //触发刺激开始
#define STATUS_INQUIRY ( 0x8A ) //轮询
#define MAC_QUERY ( 0x8B ) //MAC地址查询
#define STATE_UPLOAD ( 0x92 ) //状态上传(电极片状态和适配器状态)
#define SCHEME_QUERY ( 0x91 ) //方案查询
/* 刺激启停控制数据偏移定义 */
#define StartStopOffset ( 4 )
/* 刺激启停控制数据描述 */
#define CH_STOP ( 0x00 )
#define CH_START ( 0x01 )
#define CH_PAUSE ( 0x02 )
#define CH_CONTINUE ( 0x03 )
/* 刺激参数数据偏移定义 */
#define HeadOffset ( 0 )
#define DataLengthOffset ( 1 )
#define FunctionCodeOffset ( 2 )
#define ChannelNumOffset ( 3 )
#define SchemeCategoryOffset ( 4 )
#define SchemeIDMSBOffset ( 5 )
#define SchemeIDLSBOffset ( 6 )
#define FreqMSBOffset ( 7 )
#define FreqLSBOffset ( 8 )
#define WidthMSBOffset ( 9 )
#define WidthLSBOffset ( 10 )
#define RampUpTimeLSBOffset ( 12 )
#define RampUpTimeMSBOffset ( 11 )
#define RampSmoothTimeLSBOffset ( 14 )
#define RampSmoothTimeMSBOffset ( 13 )
#define RampDownTimeLSBOffset ( 16 )
#define RampDownTimeMSBOffset ( 15 )
#define RampBreakTimeLSBOffset ( 18 )
#define RampBreakTimeMSBOffset ( 17 )
/* 状态轮询数据偏移定义 */
#define ElectrodeStatusOffset ( 4 )
#define StimStatusOffset ( 5 )
#define StimCurrentOffset ( 6 )
#define ResetOffset ( 7 )
#define DataCrcOffset ( 8 )
#define TailOffset ( 9 )
/* 运行轮询数据偏移定义 */
#define AdapterStatusOffset ( 5 )
#define BatteryLevelOffset ( 4 )
/* 刺激电流数据偏移定义 */
#define PRE_ADJUST_OFFSET ( 4 )
/* 预调节数据定义 */
#define START_PRE_ADJUST ( 0x01 )
#define STOP_PRE_ADJUST ( 0x00 )
/* 方案存储属性定义 */
#define TEMP_STORAGE ( 1 ) // 临时存储
#define PERMANENT_STORAGE ( 2 ) // 永久存储
#define FDS_DATA_LENGTH ( 20 ) // 存储空间长度
//头尾帧
#define FRAME_HEADER (0xAA)
#define FRAME_TAIL (0x55)
//功能码
// Function Codes (Converted to UPPER_SNAKE_CASE)
#define D_PARAMETER_SET (0x71) // Original: D_ParameterSet
#define D_CHANNEL_CTRL (0x72) // Original: D_ChannelCtrl
#define D_CURRENT_SET (0x73) // Original: D_CurrentSet
#define D_EMG_DATA_REPORT (0x74) // Original: D_EmgDataReport
#define D_DATA_MODE_SWITCH (0x75) // Original: D_DataModeSwitch
#define D_PREINSTALL_CTRL (0x76) // Original: D_PreinstallCtrl
#define D_TRIGGER_MODE_CTRL (0x77) // Original: D_TriggerModeCtrl
#define D_POLL_CMD (0x78) // Original: D_PollCmd
#define D_SLICE_FALL_DETECT_SWITCH (0x79) // Original: D_SliceFallDetectSwitch
#define D_TURN_OFF_CMD (0x7A) // Original: D_TurnOffCmd
#define D_BLE_SCAN_SWITCH (0x7B) // Original: D_BleScanSwitch
#define D_MAC_ADDR_REPORT (0x7C) // Original: D_MacAddrReport
#define D_BLE_CONNECT_CMD (0x7D) // Original: D_BleConnectCmd
/* Public typedef ------------------------------------------------*/
/* 方案信息结构体 */
typedef struct
{
uint8_t StorageMode; //存储模式
uint8_t SchemeIDMSB; //方案ID
uint8_t SchemeIDLSB;
uint8_t FreqMSB; //频率
uint8_t FreqLSB;
uint8_t WidthMSB; //脉宽
uint8_t WidthLSB;
uint8_t RampUpTimeMSB; //波升
uint8_t RampUpTimeLSB;
uint8_t RampSmoothTimeMSB;//保持
uint8_t RampSmoothTimeLSB;
uint8_t RampDownTimeMSB; //波降
uint8_t RampDownTimeLSB;
uint8_t RampBreakTimeMSB; //休息
uint8_t RampBreakTimeLSB;
}SchemeData_t;
#define RMS_USER_DATA_LENGTH 4//110///4 //用户数据长度
#pragma pack(1)
typedef struct
{
uint8_t frameHeader; //帧头
uint8_t frameLength; //帧长度
uint8_t functionCode; //功能码
uint8_t myNumber; //编号
uint8_t channel; //通道号
uint16_t rmsDataBuffer[RMS_USER_DATA_LENGTH]; //数据内容
uint8_t checkSum; //校验和
uint8_t frameTail; //帧尾
} rms_data_t;
typedef struct
{
uint8_t frameHeader; //帧头
uint8_t frameLength; //帧长度
uint8_t functionCode; //功能码
uint8_t channel; //通道号
uint8_t ChargeState; //充电状态
uint8_t BatteryLevelA; //A 电池电量
uint8_t BatteryLevelB; //B 电池电量
uint8_t BatteryLevelC; //C 电池电量
uint8_t reserve[5]; //保留字段
uint8_t checkSum; //校验和
uint8_t frameTail; //帧尾
} reply_run_status_t;
#define MAX_VERSION_LEN 15
typedef struct
{
uint8_t frameHeader; //帧头
uint8_t frameLength; //帧长度
uint8_t functionCode; //功能码
uint8_t channel; //通道号
uint8_t VersionDes[MAX_VERSION_LEN]; //版本描述
uint8_t checkSum; //校验和
uint8_t frameTail; //帧尾
} check_version_t;
#pragma pack()
//设备连接状态
typedef enum
{
DisconnectState = 0,
ConnectState
}ConnectStateInfo_e;
// 电极片状态
typedef enum
{
ElectrodeFalloff,
ElectrodeConnectted
}ElectrodeStatusInfo_e;
// 适配器连接状态
typedef enum
{
AdapterNotConnected = 0,
AdapterConnected
}AdapterStateInfo_e;
//FDS异步操作标志结构体
typedef struct
{
bool scheme_update; //scheme_record记录更新标志
bool read; //读记录标志
bool gc; //碎片收集标志
bool busy; //FDS忙标志
}my_fds_info_t;
//记录scheme的id和内容
typedef struct
{
uint8_t text[FDS_DATA_LENGTH];
}__attribute__((aligned(4)))SchemePara_t;
/* Public constants ----------------------------------------------*/
/* Public variables ----------------------------------------------*/
extern uint16_t m_conn_handle;
extern uint16_t m_ble_nus_max_data_len;
extern uint8_t CurrentFlag;
extern ConnectStateInfo_e DeviceConnectState;
extern ElectrodeStatusInfo_e ElectrodeStatusInfo;
extern my_fds_info_t my_fds_info;
extern SchemePara_t SchemePara;
extern SchemeData_t SchemeData;
extern uint8_t BLE_MAC[BLE_GAP_ADDR_LEN];
extern AdapterStateInfo_e AdapterState;
extern AdapterStateInfo_e LastAdapterState;
extern SchemeData_t PreStorageSchemeData;
extern ElectrodeStatusInfo_e LastElectrodeStatusInfo;
extern uint16_t ccrvaluebuf[70];
extern uint8_t eegflag;
/* Public function prototypes ------------------------------------*/
void service_nus_init(void);
void StartManage(void);
void PauseManage(void);
void RecoverManage(void);
void StopManage(void);
void CloseOutput(void);
void SetStandardCurrent(uint8_t* AnalysisDataBfferIn_t);
void RunRoll(void);
void CheckVersion(void);
void UpdateCurrent(uint8_t CurrentSend);
void JudgeLedMode(void);
void DisconnectControl(void);
void SchemeQuery(uint8_t idMSB,uint8_t idLSB);
void UpdateControlStatus(uint8_t ControlStatus);
void StateUpLoad(AdapterStateInfo_e AdapterStateTemp , ElectrodeStatusInfo_e ElectrodeStatusTemp);
void EegDataSend(void);
void user_ble_or_uart_send(char * txBufferP, uint16_t Length);
void ble_send_rms_data(uint16_t rms_data);
#endif
/*************************** END OF FILE ***************************/

117
app/Inc/timer.h Normal file
View File

@ -0,0 +1,117 @@
/********************************************************************
Copyright (c) 2021 Xiangyu Medical Co.Ltd. All rights reserved.
FileName : timer.h
Author : zhangdawei
Version : V1.0
Date :
Note :
History :
********************************************************************/
#ifndef TIMER_H__
#define TIMER_H__
/* Includes ------------------------------------------------------*/
#include "app_timer.h"
/* Public define -------------------------------------------------*/
#define RAMP_TIM_TIME ( 1000 )
/* 呼吸灯的步长 */
#define M_STEP ( 100 )
/* 频率对应的周期值 */
#define CYCLE_CALUE ( 1000 )
#define SIQU ( 200 )
/* Public typedef ------------------------------------------------*/
/*通道状态*/
typedef enum
{
IdleState = 0, // 空闲态
StimState, // 刺激态
StimAdjState // 刺激调节态
}ChannelState_e;
typedef enum
{
E_RMS_STOP = 0x00,
E_RMS_START = 0x01,
E_RMS_PAUSE = 0x02,
E_RMS_CONTINUE = 0x03,
E_STIM_STOP = 0x04,
E_STIM_START = 0x05,
E_STIM_PAUSE = 0x06,
E_STIM_CONTINUE = 0x07
}E_WORK_STATE;
/* LED状态 */
typedef enum
{
Disconnect_Highbattery = 0, //未连接有电
Disconnect_Lowbattery, // 未连接低电
Connect_Lowbattery, // 连接低电
Connect_Highbattery, // 连接有电
Null
}LedModeInfo_e;
/* 斜坡状态 */
typedef enum
{
RampIdle = 0,
RampUp,
RampDown,
RampSmooth,
RampBreak
}RampState_e;
/* 通道工作状态 */
typedef enum
{
Close,
Open,
Pause,
Continue,
Ready
}ChannelWorkState_e;
/* 刺激参数信息结构体 */
typedef struct
{
uint16_t usRampUpTime; // 上坡时间 单位为ms
uint16_t usRampDownTime; // 下坡时间
uint16_t usSmoothTime; // 平坡时间
uint16_t usBreakTime; // 休息时间
uint16_t usFreqBuf; // 频率
ChannelWorkState_e ChannelWorkState; // 通道当前工作状态
uint32_t usWidth; // 脉冲宽度
uint32_t usCycle; // 脉冲周期
RampState_e Ramp_e; // 斜坡状态
uint8_t ucCurrent; // 标称电流值
uint16_t usCcrValue; // 标称的CCR值
}StimStateInfo_t;
/* Public constants ----------------------------------------------*/
/* Public variables ----------------------------------------------*/
extern StimStateInfo_t ChannelStimStateInfo_t;
extern uint8_t PwmLedInit_Flag;
extern bool LongPressEvent;
extern bool BeepBeepOpenFlag;
/* Public function prototypes ------------------------------------*/
void AppTimersInit(void);
void ApplicationTimersStart(void);
void PwmDACInit(void);
void PwmDACStop(void);
void PwmLedUnInit(void);
void PwmSubtractStop(void);
void GpioteInit(void);
void PPIPwmInit(void);
void SetCurrent(uint16_t CcrIn);
void OutputCurrentCtrl(void);
void BlinkTwice(void);
void pwm0_common_init(void);
void SetPWMValues(uint16_t tempvalue);
void pwm2common_init(void);
void PwmDACPlay(void);
void pwm2_play(void);
void pwm0_play(void);
#endif
/*************************** END OF FILE ***************************/

31
app/Inc/user_config.h Normal file
View File

@ -0,0 +1,31 @@
/********************************************************************
Copyright (c) 2021 Xiangyu Medical Co.Ltd. All rights reserved.
FileName :
Author : xiaozhengsheng
Version : V1.0
Date :
Note :
History :
********************************************************************/
#ifndef _USER_CONFIG_H_
#define _USER_CONFIG_H_
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#define SOFT_VERSION_MAX_LENGTH 50
typedef struct {
uint8_t major; // 主版本号 (V1)
uint8_t minor; // 次版本号 (.0)
uint8_t patch; // 修订号 (.0)
uint8_t build; // 构建号 (.0)
uint8_t testVersion[30];
} version_t;
extern char softWareVersion[SOFT_VERSION_MAX_LENGTH];
void read_config_user_config(void);
#endif
/*************************** END OF FILE ***************************/

201
app/Src/IoControl.c Normal file
View File

@ -0,0 +1,201 @@
/********************************************************************
Copyright (c) 2021 Xiangyu Medical Co.Ltd. All rights reserved.
FileName : IoControl.c
Author : zhangdawei
Version : V1.0
Date :
Note :
History :
********************************************************************/
/* Includes ------------------------------------------------------*/
#include "IoControl.h"
#include "drv_uart.h"
#include "nrf_drv_gpiote.h"
/* Private define ------------------------------------------------*/
/* Private typedef -----------------------------------------------*/
/* Private constants ---------------------------------------------*/
/* Private variables ---------------------------------------------*/
uint8_t LastState = Null; //保存上一次的状态
/* Private function prototypes -----------------------------------*/
/* Public constants ----------------------------------------------*/
/* Public variables ----------------------------------------------*/
DeviceStateInfo_e DeviceState = POWER_CLOSE; //设备开关机状态
ChargingStateInfo_e ChargeState = Uncharged;
ChargingStateInfo_e ChargeLastState = Uncharged;
KeyStateInfo_t KeyStateInfo;
/********************************************************************
* name : void GpioInit(void)
* description : GPIO引脚初始化
* Input : void
* Output : void
* Return :
********************************************************************/
void GpioInit(void)
{
NRF_UICR->NFCPINS = 0;
nrf_gpio_cfg_output(KEY_POWER);
nrf_gpio_cfg_output(LED_YELLOW);
// nrf_gpio_cfg_output(CHARGE_LED);
nrf_gpio_cfg_output(STIM_RMS_RELAY_PIN);
nrf_gpio_cfg_output(STIM_RELAY_PIN);
nrf_gpio_cfg_output(SAMPLE_POWER_PIN);
// nrf_gpio_pin_clear(KEY_POWER);
nrf_gpio_pin_clear(LED_YELLOW);
// nrf_gpio_pin_clear(CHARGE_LED);
nrf_gpio_pin_clear(STIM_RMS_RELAY_PIN);
nrf_gpio_pin_clear(STIM_RELAY_PIN);
nrf_gpio_pin_clear(SAMPLE_POWER_PIN);
/////////
nrf_gpio_cfg_input(CHG_MANAGER_CHG, NRF_GPIO_PIN_NOPULL);//检测充电状态
}
/* 电刺激输出使能脚 */
void StimOutCtlOpen(void)
{
}
void StimOutCtlClose(void)
{
}
/* 能量释放控制 */
void StimReleaseOpen(void)
{
}
void StimReleaseClose(void)
{
}
// OK按键处理函数
void KEY_PWR_SWITICH_Handler(void)
{
}
//GPIOTE事件处理函回调函数事件回调函数里面可以获取pin编号和引脚状态变化
void in_pin_handler(nrf_drv_gpiote_pin_t pin, nrf_gpiote_polarity_t action)
{
if(pin == KEY_PWR_SWITICH)
{
KeyStateInfo.shineng = true;
KeyStateInfo.KeyPinNumber = KEY_PWR_SWITICH;
}
}
void EXIT_KEY_Init(void)
{
ret_code_t err_code;
nrf_gpio_cfg_input(KEY_PWR_SWITICH, NRF_GPIO_PIN_PULLUP);//检测开关机信号
}
/********************************************************************
* name : void open_acquisition_relay(void)
* description :
* Input : void
* Output : void
* Return :
********************************************************************/
void open_acquisition_relay(void)
{
nrf_gpio_pin_set(STIM_RMS_RELAY_PIN); //闭合继电器
nrf_gpio_pin_clear(STIM_RELAY_PIN); //打开刺激继电器
}
/********************************************************************
* name : void close_acquisition_relay(void)
* description :
* Input : void
* Output : void
* Return :
********************************************************************/
void close_acquisition_relay(void)
{
nrf_gpio_pin_clear(STIM_RMS_RELAY_PIN);
nrf_gpio_pin_clear(STIM_RELAY_PIN);
}
/********************************************************************
* name : void open_stimulate_relay(void)
* description :
* Input : void
* Output : void
* Return :
********************************************************************/
void open_stimulate_relay(void)
{
nrf_gpio_pin_clear(STIM_RMS_RELAY_PIN);
nrf_gpio_pin_set(STIM_RELAY_PIN);
}
/********************************************************************
* name : void close_stimulate_relay(void)
* description :
* Input : void
* Output : void
* Return :
********************************************************************/
void close_stimulate_relay(void)
{
nrf_gpio_pin_clear(STIM_RMS_RELAY_PIN);
nrf_gpio_pin_clear(STIM_RELAY_PIN);
}
/********************************************************************
* name : void StimStateInfoStructInit(SchemeData_t SchemeDataIn)
* description :
* Input : void
* Output : void
* Return :
********************************************************************/
void StimStateInfoStructInit(SchemeData_t SchemeDataIn)
{
}
// 设备预存信息初始化ID :101 腹直肌分离
void PreStorageSchemeDataInit(void)
{
}
void KeyPinHandler(void)
{
if(KeyStateInfo.shineng == true)
{
switch(KeyStateInfo.KeyPinNumber)
{
case KEY_PWR_SWITICH:
{
KEY_PWR_SWITICH_Handler();
break;
}
}
KeyStateInfo.shineng = false;
}
}
/********************************************************************
* name : void VariableInit(void)
* description :
* Input : void
* Output : void
* Return :
********************************************************************/
void VariableInit(void)
{
}
/*************************** END OF FILE ***************************/

364
app/Src/drv_saadc.c Normal file
View File

@ -0,0 +1,364 @@
/********************************************************************
Copyright (c) 2021 Xiangyu Medical Co.Ltd. All rights reserved.
FileName : drv_saadc.c
Author : zhangdawei
Version : V1.0
Date :
Note :
History :
********************************************************************/
/* Includes ------------------------------------------------------*/
#include "nrf_drv_ppi.h"
#include "app_timer.h"
#include "bsp_btn_ble.h"
#include "drv_saadc.h"
#include "timer.h"
#include "string.h"
#include "drv_uart.h"
#include "nrf_drv_ppi.h"
#include "IIR.h"
/* Private define ------------------------------------------------*/
/* Private typedef -----------------------------------------------*/
#define SAMPLES_BUFFER_LEN 10
/* Private constants ---------------------------------------------*/
//定义Timer1的驱动程序实例。驱动程序实例的ID对应Timer的ID如NRF_DRV_TIMER_INSTANCE(1)对应Timer1
const nrfx_timer_t TIMER_ADC = NRF_DRV_TIMER_INSTANCE(4);
static nrf_ppi_channel_t m_ppi_channel5;
const nrfx_timer_t TIMER3_RMS = NRFX_TIMER_INSTANCE(3); //读取rms值的定时器3
static nrf_saadc_value_t m_buffer_pool[2][SAMPLES_BUFFER_LEN];
/* Private variables ---------------------------------------------*/
/* Private function prototypes -----------------------------------*/
/* Public constants ----------------------------------------------*/
/* Public variables ----------------------------------------------*/
//电池电压回调函数,堵塞模式,不需要事件,定义空的事件回调函数
void saadc_battery_callback(nrfx_saadc_evt_t const * p_event){}
//刺激反馈电压,堵塞模式,不需要事件,定义空的事件回调函数
void saadc_stimulate_callback(nrfx_saadc_evt_t const * p_event){}
/********************************************************************
* name : void battery_adc_init(void)
* description : ADC初始化,
* Input : void
* Output : void
* Return :
********************************************************************/
void battery_adc_init(void)
{
ret_code_t err_code;
//初始化SAADC注册事件回调函数。空函数即可
err_code = nrf_drv_saadc_init(NULL, saadc_battery_callback);
APP_ERROR_CHECK(err_code);
//配置通道1输入引脚为AIN7电池电压
nrf_saadc_channel_config_t channeltwo_config =
NRFX_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_AIN7);
err_code = nrfx_saadc_channel_init(SAADC_BATTERY_CHANNEL, &channeltwo_config);
APP_ERROR_CHECK(err_code);
// //配置通道2输入引脚为AIN4电极片脱落电压检测
// nrf_saadc_channel_config_t channelthree_config =
// NRFX_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_AIN4);
// //初始化SAADC通道3
// err_code = nrfx_saadc_channel_init(SAADC_ELECTRODE_CHANNEL, &channelthree_config);
// APP_ERROR_CHECK(err_code);
}
// 如需更高精度非线性计算(示例)
float nonlinear_percentage(float voltage) {
// 三元锂电池的典型放电曲线拟合多项式
float p = (voltage - 3.4f) / 0.8f; // 归一化到[0,1]
return 100 * (1.0f - 0.2f*p - 0.8f*p*p);
}
// 锂电池电量计算函数
// 输入:当前电压(单位:伏特)
// 输出电量百分比0~100
int calculate_battery_percentage(float voltage)
{
// 定义电压范围
const float VOLTAGE_MIN = 3.4f; // 0%电量对应电压
const float VOLTAGE_MAX = 4.195f; // 100%电量对应电压
// 边界检查
if (voltage <= VOLTAGE_MIN) {
return 0;
} else if (voltage >= VOLTAGE_MAX) {
return 100;
}
// 线性插值计算百分比(可根据实际放电曲线修改算法)
float percentage = (voltage - VOLTAGE_MIN) / (VOLTAGE_MAX - VOLTAGE_MIN) * 100.0f;
// 四舍五入取整
return (int)(percentage + 0.5f);
}
/********************************************************************
* name : void CalculateBatteryPower(void)
* description : 0-100
* Input : void
* Output : void
* Return : void
********************************************************************/
void CalculateBatteryPower(void)
{
uint16_t Adctemp;
nrf_saadc_value_t Battery_Saadc_Value;
//启动一次ADC采样,存在Battery_Saadc_Value中
nrfx_saadc_sample_convert(SAADC_BATTERY_CHANNEL, &Battery_Saadc_Value);
Adctemp = ((Battery_Saadc_Value * 3600) / 16384);
static float lastBatteryPercentage = 100;
int temp = calculate_battery_percentage(Adctemp * 5.12557);
if(Uncharged == ChargeState) //如果没有处于充电状态,不允许电量上升,只能下降
{
if(temp < lastBatteryPercentage)
Battery_Percentage = temp;
}
else
{
Battery_Percentage = temp;
}
lastBatteryPercentage = Battery_Percentage;
}
short short_to_big_endian(short value)
{
uint8_t buf[2];
short resultShort;
buf[0] = (value >> 8) & 0xFF; // 高字节Big-Endian 第一个字节)
buf[1] = value & 0xFF; // 低字节Big-Endian 第二个字节)
memcpy(&resultShort,buf,2);
return resultShort;
}
/********************************************************************
* name : void rms_saadc_callback(nrfx_saadc_evt_t const * p_event)
* description : SAADC事件回调函数
* Input : nrfx_saadc_evt_t const * p_eventsaadc事件
* Output : void
* Return :
********************************************************************/
void rms_saadc_callback(nrfx_saadc_evt_t const * p_event)
{
static float32_t AdcFilter_g[AD_RAW_MAX] __attribute__((aligned(4)));
float32_t outFilter __attribute__((aligned(4)));
float32_t vol __attribute__((aligned(4)));
static emg_data_t emgData=
{
.emgCnt = 0
};
if(p_event->type == NRF_DRV_SAADC_EVT_DONE)
{
ret_code_t err_code;
err_code = nrf_drv_saadc_buffer_convert(p_event->data.done.p_buffer, SAMPLES_BUFFER_LEN);
APP_ERROR_CHECK(err_code);
}
for(int i = 0; i < SAMPLES_BUFFER_LEN; i++)
{
if(p_event->data.done.p_buffer[i] < 0)
vol = 0;
else
{
vol = (p_event->data.done.p_buffer[i]*3600/16384) - 1545; //
}
bs_bp(&vol, &outFilter); //5.6us
if(emgData.emgCnt < AD_RAW_MAX) //防止溢出
AdcFilter_g[emgData.emgCnt] = outFilter;
emgData.emgCnt++;
if(emgData.emgCnt >= AD_RAW_MAX)
{
emgData.emgCnt=0;
float32_t temp __attribute__((aligned(4)));
arm_rms_f32(AdcFilter_g, AD_RAW_MAX, &temp);//6us
emgData.EmgValue = temp*0.8806 - 3.028;
if(emgData.EmgValue < 0)
emgData.EmgValue = 0;
// if(temp < 0)
// emgData.EmgValue = 0;
// else
// emgData.EmgValue = 0.6722 * temp + 3.7097;
uint16_t outfRms;
outfRms = (short)emgData.EmgValue;
outfRms = short_to_big_endian(outfRms);
ble_send_rms_data(outfRms);
}
//ble_send_rms_data(save_value[i]);
}
}
void timer3_rms_handler(nrf_timer_event_t event_type, void* p_context)
{
}
/********************************************************************
* name : void timer3_rms_init(void)
* description : 1
* Input : void
* Output : void
* Return :
********************************************************************/
void timer3_rms_init(void)
{
uint32_t err_code = NRF_SUCCESS;
uint32_t time_us = 500; //采样频率2kHz
uint32_t time_ticks;
nrfx_timer_config_t timer3_cfg = NRFX_TIMER_DEFAULT_CONFIG;
err_code = nrfx_timer_init(&TIMER3_RMS, &timer3_cfg, timer3_rms_handler);
APP_ERROR_CHECK(err_code);
time_ticks = nrfx_timer_us_to_ticks(&TIMER3_RMS, time_us);
nrfx_timer_extended_compare(
&TIMER3_RMS, NRF_TIMER_CC_CHANNEL0, time_ticks, NRF_TIMER_SHORT_COMPARE0_CLEAR_MASK, true);
}
/********************************************************************
* name : void timer3_rms_start(void)
* description : 1
* Input : void
* Output : void
* Return :
********************************************************************/
void timer3_rms_start(void)
{
nrfx_timer_enable(&TIMER3_RMS);
}
/********************************************************************
* name : void timer3_rms_stop(void)
* description : 1
* Input : void
* Output : void
* Return :
********************************************************************/
void timer3_rms_stop(void)
{
nrfx_timer_disable(&TIMER3_RMS);
}
/********************************************************************
* name : void PPIEegAdcInit(void)
* description : ADCPPI通道初始化
* Input : void
* Output : void
* Return :
********************************************************************/
void PPIEegAdcInit(void)
{
uint32_t err_code = NRF_SUCCESS;
err_code = nrf_drv_ppi_init();
APP_ERROR_CHECK(err_code);
//分配PPI通道PPI通道的分配是由驱动函数完成的分配的通道号保存到my_ppi_channel1中
err_code = nrf_drv_ppi_channel_alloc(&m_ppi_channel5);
APP_ERROR_CHECK(err_code);
//分配PPI通道的EEP和TEP
err_code = nrf_drv_ppi_channel_assign(m_ppi_channel5,
nrf_drv_timer_event_address_get(&TIMER3_RMS, NRF_TIMER_EVENT_COMPARE0),
nrf_drv_saadc_sample_task_get());
APP_ERROR_CHECK(err_code);
//使能PPI通道
err_code = nrf_drv_ppi_channel_enable(m_ppi_channel5);
APP_ERROR_CHECK(err_code);
}
/********************************************************************
* name : void rms_saadc_init(void)
* description : saadc初始化
* Input : void
* Output : void
* Return :
********************************************************************/
void rms_saadc_init(void)
{
ret_code_t err_code;
nrf_drv_saadc_uninit(); //先反初始化
//配置通道0输入引脚为AIN3采集信号
nrf_saadc_channel_config_t channel_config =
NRFX_SAADC_DEFAULT_CHANNEL_CONFIG_SE(NRF_SAADC_INPUT_AIN2);
//初始化SAADC注册事件回调函数。
err_code = nrf_drv_saadc_init(NULL, rms_saadc_callback);
APP_ERROR_CHECK(err_code);
//初始化SAADC通道0
err_code = nrfx_saadc_channel_init(SAADC_RMS_SAMPLE_CHANNEL, &channel_config);
APP_ERROR_CHECK(err_code);
//配置缓存1将缓存1地址赋值给SAADC驱动程序中的控制块m_cb的一级缓存指针
err_code = nrfx_saadc_buffer_convert(m_buffer_pool[0], SAMPLES_BUFFER_LEN);
APP_ERROR_CHECK(err_code);
//配置缓存2将缓存1地址赋值给SAADC驱动程序中的控制块m_cb的二级缓存指针
err_code = nrfx_saadc_buffer_convert(m_buffer_pool[1], SAMPLES_BUFFER_LEN);
APP_ERROR_CHECK(err_code);
}
// 电极脱落检测
void ElectFallOff(void)
{
}
/********************************************************************
* name : void timer4_output_ctrl_handler(nrf_timer_event_t event_type, void* p_context)
* description :
* Input : nrf_timer_event_t event_type
void* p_context
* Output : void
* Return :
********************************************************************/
void timer1_output_ctrl_handler(nrf_timer_event_t event_type, void* p_context)
{
switch(event_type)
{
case NRF_TIMER_EVENT_COMPARE0:
//ElectFallOff();
break;
default:
break;
}
}
/********************************************************************
* name : void timer1_output_ctrl_init(void)
* description :
* Input : void
* Output : void
* Return :
********************************************************************/
void timer1_output_ctrl_init(void)
{
ret_code_t err_code = NRF_SUCCESS;
uint32_t time_us = 50;
uint32_t time_ticks;
nrfx_timer_config_t timer_cfg = NRFX_TIMER_DEFAULT_CONFIG;
err_code = nrfx_timer_init(&TIMER_ADC, &timer_cfg, timer1_output_ctrl_handler);
APP_ERROR_CHECK(err_code);
//定时时间(单位us)转换为ticks
time_ticks = nrfx_timer_us_to_ticks(&TIMER_ADC, time_us);
//设置定时器捕获/比较通道及该通道的比较值,使能通道的比较中断
nrfx_timer_extended_compare(
&TIMER_ADC, NRF_TIMER_CC_CHANNEL0, time_ticks, NRF_TIMER_SHORT_COMPARE0_CLEAR_MASK, true);
nrfx_timer_enable(&TIMER_ADC);
}
/*************************** END OF FILE ***************************/

817
app/Src/drv_uart.c Normal file
View File

@ -0,0 +1,817 @@
/********************************************************************
Copyright (c) 2021 Xiangyu Medical Co.Ltd. All rights reserved.
FileName : drv_uart.c
Author : zhangdawei
Version : V1.0
Date :
Note :
History :
********************************************************************/
/* Includes ------------------------------------------------------*/
#include "drv_uart.h"
#include "pca10040.h"
#include "ble_nus.h"
#include "time.h"
#include "IoControl.h"
#include "nrf_drv_timer.h"
#include "fds.h"
/* Private define ------------------------------------------------*/
BLE_NUS_DEF(m_nus); //定义名称为m_nus的串口透传服务实例
/* Private typedef -----------------------------------------------*/
/* Private constants ---------------------------------------------*/
/* 接收到的方案信息 */
SchemeData_t SchemeData;
SchemeData_t PreStorageSchemeData;// 设备预存信息
uint16_t m_ble_nus_max_data_len = BLE_GATT_ATT_MTU_DEFAULT - 3; /**< Maximum length of data (in bytes) that can be transmitted to the peer by the Nordic UART service module. */
/* Private variables ---------------------------------------------*/
//该变量用于保存连接句柄,初始值设置为无连接
uint16_t m_conn_handle = BLE_CONN_HANDLE_INVALID;
/* 电池电量的原始值 */
nrf_saadc_value_t Battery_Saadc_Value = 10000;
/* 电池电压百分比 */
uint8_t Battery_Percentage = 100;
/* 肌电采集定时器初始化标志 */
uint8_t TimerEegAdcInit_Flag = 0;
/* 控制电流标志 */
uint8_t CurrentFlag = 0;
/* 设备的连接状态 */
ConnectStateInfo_e DeviceConnectState = DisconnectState;
ElectrodeStatusInfo_e ElectrodeStatusInfo = ElectrodeConnectted;
ElectrodeStatusInfo_e LastElectrodeStatusInfo = ElectrodeConnectted;
/* 适配器连接状态 */
AdapterStateInfo_e AdapterState = AdapterNotConnected;
AdapterStateInfo_e LastAdapterState = AdapterNotConnected;
/* MAC地址数组 */
uint8_t BLE_MAC[BLE_GAP_ADDR_LEN];
//定义FDS异步操作标志结构体
my_fds_info_t my_fds_info;
// 初始化参数信息
SchemePara_t SchemePara = {
.text = 0
};
uint16_t ccrvaluebuf[70] = {
23,25,27,29,31,33,35,37,39,41, //1-10
43,45,47,50,52,54,56,58,60,63, //11-20
65,67,69,71,74,76,78,80,82,85, //21-30
87,89,91,93,95,97,99,101,103,105, //31-40
108,111,114,117,120,123,126,129,132,134, //41-50
136,138,140,142,144,146,148,150,152,154, //51-60
155,156,158,160,162,164,167,170,172,174 //61-70
};
#define EEG_DATA_LENGTH ( 50 )
uint8_t aEEGData[EEG_DATA_LENGTH] = {
23,25,27,29,31,33,35,37,39,41,
43,45,47,50,52,54,56,58,60,63,
65,67,69,71,74,76,78,80,82,85,
87,89,91,93,95,97,99,101,103,105,
108,111,114,117,120,123,126,129,132,134
};
uint8_t eegmode = 0;
uint8_t eegflag = 0;
StimStateInfo_t ChannelStimStateInfo_t;
rms_data_t rmsData = {.frameHeader = FRAME_HEADER,
.frameLength = sizeof(rmsData) - 4, //减去帧头、帧长度、校验和、帧尾
.functionCode = D_EMG_DATA_REPORT,
.myNumber = 0x01,
.channel = 0x01,
//.rmsDataBuffer = {0},
.checkSum = 0,
.frameTail = FRAME_TAIL
};
/* Private function prototypes -----------------------------------*/
void StatusInquiry(ElectrodeStatusInfo_e Electrodestatus);
void StartStopCtrl(uint8_t StartStopValue);
void MACQuery(void);
/* Public constants ----------------------------------------------*/
/* Public variables ----------------------------------------------*/
/********************************************************************
* name : void SetFreqWidth(uint8_t* AnalysisDataBffer_t)
* description :
* Input : AnalysisDataBffer_t
* Output : void
* Return : void
********************************************************************/
void SetFreqWidth(uint8_t* AnalysisDataBffer_t)
{
}
/********************************************************************
* name : void SetRampTime(uint8_t* AnalysisDataBfferIn_t)
* description :
* Input : AnalysisDataBffer_t
* Output : void
* Return : void
********************************************************************/
void SetRampTime(uint8_t* AnalysisDataBffer_t)
{
}
/********************************************************************
* name : void SetStimPara(uint8_t* AnalysisDataBfferIn_t)
* description :
* Input : AnalysisDataBffer_t
* Output : void
* Return : void
********************************************************************/
void SetStimPara(uint8_t* AnalysisDataBffer_t)
{
//开启采集模式
if(1 == AnalysisDataBffer_t[4])
{
eegmode = 1;
return;
}
}
/********************************************************************
* name : static void nus_data_handler(ble_nus_evt_t * p_evt)
* description : BLE串口透传事件回调函数
* Input : ble_nus_evt_t * p_evt
* Output : void
* Return : void
********************************************************************/
static void nus_data_handler(ble_nus_evt_t * p_evt)
{
uint8_t FrameLength = 0;//帧长度
uint8_t FunctionCode = 0;//功能码
uint8_t CheckSum = 0;//校验和
uint8_t Sum = 0;//数据和
uint8_t SumCCR = 0;//CCR值
#define RX_BLE_DATA_LEN 100
uint8_t RecieveData[RX_BLE_DATA_LEN] = {0}; //接收数据帧的数组
if(p_evt->type == BLE_NUS_EVT_RX_DATA)
{
uint16_t Length = 0;
Length = p_evt->params.rx_data.length;
if(Length > RX_BLE_DATA_LEN)
{
NRF_LOG_ERROR("RecieveData length error");
return;
}
else
{
memcpy(RecieveData, p_evt->params.rx_data.p_data, Length);
}
/* 解析蓝牙收到的数据 */
if(0xAA == RecieveData[0])
{
FrameLength = RecieveData[1]; //帧长度
if(FrameLength > (RX_BLE_DATA_LEN - 4))
{
NRF_LOG_ERROR("RecieveData length error %d", FrameLength);
return;
}
else if(0x55 != RecieveData[FrameLength + 3]) //查找帧尾
{
NRF_LOG_ERROR("RecieveData end flag error");
return;
}
CheckSum = RecieveData[FrameLength + 2]; //校验和
//if(0x55 == RecieveData[FrameLength + 3]) //查找帧尾
{
/*校验数据包*/
for(uint8_t i = 0; i < FrameLength; i++)
{
Sum += RecieveData[i+2];
}
SumCCR = Sum & 0xff;
if(CheckSum == SumCCR)
{
FunctionCode = RecieveData[2];
/*模式、脉宽、频率、斜坡时间设置*/
if(STIM_PARA_CONTROL == FunctionCode)
{
SetStimPara(RecieveData); //设置参数
ble_nus_data_send(&m_nus, RecieveData, &Length, m_conn_handle);//将收到的数据回复回去
}
/*电流控制 (控制刺激强度)*/
else if(CURRENT_CONTROL == FunctionCode)
{
NRF_LOG_INFO("CURRENT_CONTROL");
// SetStandardCurrent(RecieveData); //设置电流
// CurrentFlag = 1; //设置电流的标志此标志为1时表示可以输出电流
ble_nus_data_send(&m_nus, RecieveData, &Length, m_conn_handle);//将收到的数据回复回去
}
/*刺激启停控制*/
else if(START_STOP_CONTROL == FunctionCode)
{
NRF_LOG_INFO("START_STOP_CONTROL");
// CurrentFlag = 0; //此标志清0此时开启电流的标志由通道模式和通道状态控制
uint8_t StartStopValue = CH_STOP; //初始状态为停止
StartStopValue = RecieveData[StartStopOffset]; //设置启停状态
StartStopCtrl(StartStopValue); //启停控制
ble_nus_data_send(&m_nus, RecieveData, &Length, m_conn_handle);//将收到的数据回复回去
}
/*触发采集开始*/
else if(TRIG_COLLECT_START_CONTROL == FunctionCode)
{
NRF_LOG_INFO("TRIG_COLLECT_START_CONTROL");
ble_nus_data_send(&m_nus, RecieveData, &Length, m_conn_handle);//将收到的数据回复回去
}
/*触发刺激开始*/
else if(TRIG_STIM_START_CONTROL == FunctionCode)
{
NRF_LOG_INFO("TRIG_STIM_START_CONTROL");
ble_nus_data_send(&m_nus, RecieveData, &Length, m_conn_handle);//将收到的数据回复回去
}
/*轮询0x8A*/
else if(STATUS_INQUIRY == FunctionCode)
{
StatusInquiry(ElectrodeStatusInfo);
NRF_LOG_INFO("STATUS_INQUIRY");
}
/* 运行轮询 */
else if(RUN_ROLL == FunctionCode)
{
RunRoll();
NRF_LOG_INFO("RUN_ROLL");
}
/* 版本查询 */
else if(VERSION_INQUIRY == FunctionCode)
{
CheckVersion();
NRF_LOG_INFO("VERSION_INQUIRY");
}
else if(SCHEME_QUERY == FunctionCode)
{
//SchemeQuery();
my_fds_info.read = true;
NRF_LOG_INFO("SCHEME_QUERY");
}
else if(MAC_QUERY == FunctionCode)
{
MACQuery();
}
}
}
}
/***********end***********/
}
}
/********************************************************************
* name : void service_nus_init(void)
* description :
* Input : void
* Output : void
* Return : void
********************************************************************/
void service_nus_init(void)
{
ret_code_t err_code;
ble_nus_init_t nus_init; //定义串口透传初始化结构体
/*------------------以下代码初始化串口透传服务-------------*/
memset(&nus_init, 0, sizeof(nus_init)); //清零串口透传服务初始化结构体
nus_init.data_handler = nus_data_handler; //设置串口透传事件回调函数
err_code = ble_nus_init(&m_nus, &nus_init); //初始化串口透传服务
APP_ERROR_CHECK(err_code);
/*------------------初始化串口透传服务-END-----------------*/
}
/********************************************************************
* name : void StartStopCtrl(uint8_t ucStartStopValueIn)
* description :
* Input : ucStartStopValueIn
ucChannelIn
* Output : void
* Return : void
********************************************************************/
void StartStopCtrl(uint8_t StartStopValue)
{
switch(StartStopValue)
{
case CH_START: StartManage();
break;
case CH_PAUSE: PauseManage();
break;
case CH_CONTINUE: RecoverManage();
break;
case CH_STOP: StopManage();
break;
default: break;
}
}
/********************************************************************
* name : void StartManage(void)
* description :
* Input : void
* Output : void
* Return : void
********************************************************************/
void StartManage(void)
{
if(eegmode == 1)
{
eegflag = 1;
}
}
/********************************************************************
* name : void PauseManage(void)
* description :
* Input : Channel
* Output : void
* Return : void
********************************************************************/
void PauseManage(void)
{
if(eegmode == 1)
{
eegflag = 0;
}
// CHAChannelState_e = IdleState; //设置状态为空闲态空闲状态下pwm_flag置0
// ChannelStimStateInfo_t.ChannelWorkState = Pause;
// PwmDACStop();
// CloseOutput(); //关闭输出
// NRF_LOG_INFO("Pause_Stim");
}
/********************************************************************
* name : void CloseOutput(void)
* description : 00,PWM
* Input : void
* Output : void
* Return : void
********************************************************************/
void CloseOutput(void)
{
if(eegmode == 1)
{
eegmode = 0;
eegflag = 0;
}
//ChannelStimStateInfo_t.ucCurrent = 0;
// ChannelStimStateInfo_t.Ramp_e = RampIdle;//斜坡状态为空闲态
// RampTime = 0; //斜坡时间清0
// SetCurrent(0); //设置输出电流为0
// PwmSubtractStop(); //关闭输出PWM
// PwmDACStop(); //停止充能PWM
//// GpioteInit();
}
/********************************************************************
* name : void RecoverManage(void)
* description :
* Input : void
* Output : void
* Return : void
********************************************************************/
void RecoverManage(void)
{
if(eegmode == 1)
{
eegflag = 1;
}
}
/********************************************************************
* name : void StopManage(void)
* description :
* Input : void
* Output : void
* Return : void
********************************************************************/
void StopManage(void)
{
}
/********************************************************************
* name : void SetStandardCurrent(uint8_t* AnalysisDataBfferIn_t)
* description :
* Input : AnalysisDataBfferIn_t
* Output : void
* Return : void
********************************************************************/
void SetStandardCurrent(uint8_t* AnalysisDataBffer_t)
{
}
/********************************************************************
* name : void StatusInquiry(void)
* description :
* Input : void
* Output : void
* Return : void
********************************************************************/
void StatusInquiry(ElectrodeStatusInfo_e Electrodestatus)
{
uint8_t j = 2;
static uint8_t aTxBuffer[10] = {0};
uint32_t ulCrc = 0;
uint16_t Length = 10;
/* 帧头、帧尾*/
aTxBuffer[HeadOffset] = 0xAA;
aTxBuffer[DataLengthOffset] = 0x06;
aTxBuffer[FunctionCodeOffset] = STATUS_INQUIRY;
aTxBuffer[ChannelNumOffset] = 0x00;
aTxBuffer[ElectrodeStatusOffset] = 0x01;
aTxBuffer[StimStatusOffset] = ChannelStimStateInfo_t.Ramp_e;
aTxBuffer[StimCurrentOffset] = ChannelStimStateInfo_t.ucCurrent;
aTxBuffer[ResetOffset] = 0x00;
aTxBuffer[TailOffset] = 0x55;
/* 校验和 */
for(uint8_t i = 0; i < 6; i++)
{
ulCrc += aTxBuffer[j];
j++;
}
aTxBuffer[DataCrcOffset] = (uint8_t)ulCrc;
ble_nus_data_send(&m_nus, aTxBuffer, &Length, m_conn_handle);
}
/********************************************************************
* name : uint8_t caculate_sum_check(void)
* description :
* Input : typeStructHeader
typeStructLength
* Output : void
* Return :
********************************************************************/
uint8_t caculate_sum_check(uint8_t *typeStructHeader, uint8_t typeStructLength)
{
uint8_t sum = 0;
uint8_t * typeStructCMD = &typeStructHeader[2];
for (uint8_t i = 0; i < typeStructLength; i++)
{
sum += typeStructCMD[i];
}
return sum&0xFF;
}
/// @brief 运行状态回复
reply_run_status_t replyRunStatus = {
.frameHeader = FRAME_HEADER,
.frameLength = sizeof(replyRunStatus) - 4, //减去帧头、帧长度、校验和、帧尾
.functionCode = RUN_ROLL,
.myNumber = 0x01,
.channel = 0x01,
.checkSum = 0,
.frameTail = FRAME_TAIL
};
/********************************************************************
* name : void RunRoll(void)
* description :
* Input : void
* Output : void
* Return : void
********************************************************************/
void RunRoll(void)
{
uint32_t ulCrc = 0;
uint16_t Length = sizeof(replyRunStatus);
replyRunStatus.ChargeState = ChargeState;
replyRunStatus.BatteryLevelA = Battery_Percentage;
replyRunStatus.checkSum = (uint8_t)caculate_sum_check((uint8_t *)&replyRunStatus, replyRunStatus.frameLength);
ble_nus_data_send(&m_nus, &replyRunStatus.frameHeader, &Length, m_conn_handle);
}
/********************************************************************
* name : void CheckVersion(void)
* description :
* Input : void
* Output : void
* Return : void
********************************************************************/
check_version_t checkVersion = {
.frameHeader = FRAME_HEADER,
.frameLength = sizeof(checkVersion) - 4, //减去帧头、帧长度、校验和、帧尾
.functionCode = VERSION_INQUIRY,
.myNumber = 0x01,
.channel = 0x01,
.checkSum = 0,
.frameTail = FRAME_TAIL
}
void CheckVersion(void)
{
uint8_t j = 2;
static uint8_t aTxBuffer[21] = {0};
uint32_t ulCrc = 0;
uint16_t Length = 21;
/* 帧头、帧尾*/
aTxBuffer[HeadOffset] = 0xAA;
aTxBuffer[DataLengthOffset] = 0x11;
aTxBuffer[FunctionCodeOffset] = VERSION_INQUIRY;
aTxBuffer[ChannelNumOffset] = 0x00;
aTxBuffer[20] = 0x55;
/* 协议中规定先发送高字节,后发送低字节 */
aTxBuffer[4] = VersionDes[0];
aTxBuffer[5] = VersionDes[1];
aTxBuffer[6] = VersionDes[2];
aTxBuffer[7] = VersionDes[3];
aTxBuffer[8] = VersionDes[4];
aTxBuffer[9] = VersionDes[5];
aTxBuffer[10] = VersionDes[6];
aTxBuffer[11] = VersionDes[7];
aTxBuffer[12] = 0x00;
aTxBuffer[13] = 0x00;
aTxBuffer[14] = 0x00;
aTxBuffer[15] = 0x00;
aTxBuffer[16] = 0x00;
aTxBuffer[17] = 0x00;
aTxBuffer[18] = 0x00;
/* 校验和 */
for(uint8_t i = 0; i < 17; i++)
{
ulCrc += aTxBuffer[j];
j++;
}
aTxBuffer[19] = (uint8_t)ulCrc;
ble_nus_data_send(&m_nus, aTxBuffer, &Length, m_conn_handle);
}
/********************************************************************
* name : void EegDataSend(void)
* description :
* Input : void
* Output : void
* Return : void
********************************************************************/
void EegDataSend(void)
{
uint8_t j = 2;
static uint8_t aTxBuffer[EEG_DATA_LENGTH+6] = {0};
uint32_t ulCrc = 0;
uint16_t Length = EEG_DATA_LENGTH+6;
ret_code_t err_code;
/* 帧头、帧尾*/
aTxBuffer[HeadOffset] = 0xAA;
aTxBuffer[DataLengthOffset] = 0x34;
aTxBuffer[FunctionCodeOffset] = EEG_DATA;
aTxBuffer[ChannelNumOffset] = 0x00;
aTxBuffer[EEG_DATA_LENGTH+5] = 0x55;
/* 协议中规定先发送高字节,后发送低字节 */
memcpy(&aTxBuffer[4],aEEGData,EEG_DATA_LENGTH);
/* 校验和 */
for(uint8_t i = 0; i < EEG_DATA_LENGTH+2; i++)
{
ulCrc += aTxBuffer[j];
j++;
}
aTxBuffer[EEG_DATA_LENGTH+4] = (uint8_t)ulCrc;
ble_nus_data_send(&m_nus, aTxBuffer, &Length, m_conn_handle);
}
/********************************************************************
* name : void UpdateCurrent(uint8_t CurrentSend)
* description :
* Input : void
* Output : void
* Return : void
********************************************************************/
void UpdateCurrent(uint8_t CurrentSend)
{
uint8_t j = 2;
uint8_t aTxBuffer[8] = {0};
uint32_t ulCrc = 0;
uint16_t Length = 8;
/* 帧头、帧尾*/
aTxBuffer[HeadOffset] = 0xAA;
aTxBuffer[DataLengthOffset] = 0x04;
aTxBuffer[FunctionCodeOffset] = CURRENT_CONTROL;
aTxBuffer[ChannelNumOffset] = 0x00;
aTxBuffer[7] = 0x55;
/* 协议中规定先发送高字节,后发送低字节 */
aTxBuffer[4] = CurrentSend;
aTxBuffer[5] = 0x01; // 01代表蓝牙设备发送
/* 校验和 */
for(uint8_t i = 0; i < 4; i++)
{
ulCrc += aTxBuffer[j];
j++;
}
aTxBuffer[6] = (uint8_t)ulCrc;
ble_nus_data_send(&m_nus, aTxBuffer, &Length, m_conn_handle);
}
void user_ble_or_uart_send(char * txBufferP, uint16_t Length)
{
ble_nus_data_send(&m_nus, txBufferP, &Length, m_conn_handle);
}
/********************************************************************
* name : void ble_send_rms_data(uint16_t rms_data)
* description :
* Input : uint16_t rms_data
* Output : void
* Return :
********************************************************************/
void ble_send_rms_data(uint16_t rms_data)
{
uint32_t TempSum = 0;
static uint8_t sendCnt = 0;
if(sendCnt < RMS_USER_DATA_LENGTH)
{
rmsData.rmsDataBuffer[sendCnt] = rms_data; //将rms_data存入rmsData的rmsDataBuffer数组中
sendCnt++;
if(sendCnt < RMS_USER_DATA_LENGTH)
return ; //如果发送次数小于RMS_USER_DATA_LENGTH则不发送
}
sendCnt = 0; //发送次数达到RMS_USER_DATA_LENGTH后重置发送次数
rmsData.myNumber = 1;
//rmsData.myNumber++;
uint8_t * sumCheckStartP = (uint8_t *)&rmsData.functionCode;
for(uint8_t i = 0; i < rmsData.frameLength; i++)
{
TempSum += sumCheckStartP[i];
}
rmsData.checkSum = TempSum & 0xff;
user_ble_or_uart_send((uint8_t *)&rmsData, sizeof(rmsData)); //145us
}
/********************************************************************
* name : void StateUpLoad(AdapterStateInfo_e AdapterStateTemp , ElectrodeStatusInfo_e ElectrodeStatusTemp)
* description :
* Input : AdapterStateInfo_e AdapterStateTemp , ElectrodeStatusInfo_e ElectrodeStatusTemp
* Output : void
* Return : void
********************************************************************/
void StateUpLoad(AdapterStateInfo_e AdapterStateTemp , ElectrodeStatusInfo_e ElectrodeStatusTemp)
{
uint8_t j = 2;
uint8_t aTxBuffer[8] = {0};
uint32_t ulCrc = 0;
uint16_t Length = 8;
AdapterStateInfo_e AdapterStateIn;
ElectrodeStatusInfo_e ElectrodeStatusIn;
AdapterStateIn = AdapterStateTemp;
ElectrodeStatusIn = ElectrodeStatusTemp;
/* 帧头、帧尾*/
aTxBuffer[HeadOffset] = 0xAA;
aTxBuffer[DataLengthOffset] = 0x04;
aTxBuffer[FunctionCodeOffset] = STATE_UPLOAD;
aTxBuffer[ChannelNumOffset] = 0x00;
aTxBuffer[7] = 0x55;
aTxBuffer[4] = AdapterStateIn; // 适配器连接状态
aTxBuffer[5] = ElectrodeStatusIn; // 电极片状态
if(ElectrodeStatusIn == ElectrodeFalloff)
{
ElectrodeStatusInfo = ElectrodeConnectted;
}
NRF_LOG_INFO("Electrodestatus = %d",ElectrodeStatusIn);
/* 校验和 */
for(uint8_t i = 0; i < 4; i++)
{
ulCrc += aTxBuffer[j];
j++;
}
aTxBuffer[6] = (uint8_t)ulCrc;
ble_nus_data_send(&m_nus, aTxBuffer, &Length, m_conn_handle);
}
/********************************************************************
* name : void UpdateControlStatus(uint8_t ControlStatus)
* description :
* Input : void
* Output : void
* Return : void
********************************************************************/
void UpdateControlStatus(uint8_t ControlStatus)
{
uint8_t j = 2;
uint8_t aTxBuffer[8] = {0};
uint32_t ulCrc = 0;
uint16_t Length = 8;
/* 帧头、帧尾*/
aTxBuffer[HeadOffset] = 0xAA;
aTxBuffer[DataLengthOffset] = 0x04;
aTxBuffer[FunctionCodeOffset] = START_STOP_CONTROL;
aTxBuffer[ChannelNumOffset] = 0x00;
aTxBuffer[7] = 0x55;
/* 协议中规定先发送高字节,后发送低字节 */
aTxBuffer[4] = ControlStatus;
aTxBuffer[5] = 0x01; // 01代表蓝牙设备发送
/* 校验和 */
for(uint8_t i = 0; i < 4; i++)
{
ulCrc += aTxBuffer[j];
j++;
}
aTxBuffer[6] = (uint8_t)ulCrc;
ble_nus_data_send(&m_nus, aTxBuffer, &Length, m_conn_handle);
}
/********************************************************************
* name : void SchemeQuery(uint8_t idMSB,uint8_t idLSB)
* description :
* Input : void
* Output : void
* Return : void
********************************************************************/
void SchemeQuery(uint8_t idMSB,uint8_t idLSB)
{
uint8_t j = 2;
static uint8_t aTxBuffer[8] = {0};
uint32_t ulCrc = 0;
uint16_t Length = 8;
/* 帧头、帧尾*/
aTxBuffer[HeadOffset] = 0xAA;
aTxBuffer[DataLengthOffset] = 0x04;
aTxBuffer[FunctionCodeOffset] = SCHEME_QUERY;
aTxBuffer[ChannelNumOffset] = 0x00;
aTxBuffer[7] = 0x55;
/* 协议中规定先发送高字节,后发送低字节 */
aTxBuffer[4] = idMSB;
aTxBuffer[5] = idLSB;
/* 校验和 */
for(uint8_t i = 0; i < 4; i++)
{
ulCrc += aTxBuffer[j];
j++;
}
aTxBuffer[6] = (uint8_t)ulCrc;
ble_nus_data_send(&m_nus, aTxBuffer, &Length, m_conn_handle);
}
/********************************************************************
* name : void MACQuery(void)
* description : MAC地址查询
* Input : void
* Output : void
* Return : void
********************************************************************/
void MACQuery(void)
{
uint8_t j = 2;
static uint8_t aTxBuffer[12] = {0};
uint32_t ulCrc = 0;
uint16_t Length = 12;
/* 帧头、帧尾*/
aTxBuffer[HeadOffset] = 0xAA;
aTxBuffer[DataLengthOffset] = 0x08;
aTxBuffer[FunctionCodeOffset] = MAC_QUERY;
aTxBuffer[ChannelNumOffset] = 0x00;
aTxBuffer[11] = 0x55;
aTxBuffer[4] = BLE_MAC[5];
aTxBuffer[5] = BLE_MAC[4];
aTxBuffer[6] = BLE_MAC[3];
aTxBuffer[7] = BLE_MAC[2];
aTxBuffer[8] = BLE_MAC[1];
aTxBuffer[9] = BLE_MAC[0];
/* 校验和 */
for(uint8_t i = 0; i < 8; i++)
{
ulCrc += aTxBuffer[j];
j++;
}
aTxBuffer[10] = (uint8_t)ulCrc;
ble_nus_data_send(&m_nus, aTxBuffer, &Length, m_conn_handle);
}
/********************************************************************
* name : void JudgeLedMode(void)
* description :
* Input : void
* Output : void
* Return : void
********************************************************************/
void JudgeLedMode(void)
{
}
void DisconnectControl(void)
{
StopManage();
}
/*************************** END OF FILE ***************************/

482
app/Src/timer.c Normal file
View File

@ -0,0 +1,482 @@
/********************************************************************
Copyright (c) 2021 Xiangyu Medical Co.Ltd. All rights reserved.
FileName : timer.c
Author : zhangdawei
Version : V1.0
Date :
Note :
History :
********************************************************************/
/* Includes ------------------------------------------------------*/
#include "nrf_drv_pwm.h"
#include "drv_uart.h"
#include "IoControl.h"
#include "timer.h"
#include "nrf_delay.h"
#include "nrf_drv_ppi.h"
#include "nrf_drv_gpiote.h"
/* Private define ------------------------------------------------*/
/* 定义APP定时器 */
APP_TIMER_DEF(detect_button_100ms);
#define DETECT_BUTTON APP_TIMER_TICKS(100)
/* Private typedef -----------------------------------------------*/
//定义名称为m_pwm_add的驱动程序实例
static nrfx_pwm_t m_pwm_dac = NRFX_PWM_INSTANCE(1);
static nrfx_pwm_t m_pwm0 = NRFX_PWM_INSTANCE(0);
static nrfx_pwm_t m_pwm2 = NRFX_PWM_INSTANCE(2);
/* Private constants ---------------------------------------------*/
/* Private variables ---------------------------------------------*/
/* 呼吸灯占空比 */
uint16_t m_step = 150;
/* 存放RunLED占空比的数组 */
static nrf_pwm_values_common_t seq3_values[M_STEP*2];
//定义PWM序列该序列必须位于RAM中因此要定义为static类型
static nrf_pwm_values_common_t dac_values[] = {CYCLE_CALUE}; //14
static nrf_pwm_values_wave_form_t seq0_current_values[] =
{
10000 - 600,
10000 - 400,
10000 - 200,
10000 //100Hz
};
static nrf_pwm_values_wave_form_t seq2_current_values[] =
{
800 - 125,
800,
800,
800 //20khz
};
E_WORK_STATE eRmsState = E_RMS_STOP;
/* Private function prototypes -----------------------------------*/
/* Public constants ----------------------------------------------*/
/* Public variables ----------------------------------------------*/
/********************************************************************
* name : void acquisition_start(void)
* description :
* Input : void
* Output : void
* Return :
********************************************************************/
void acquisition_start(void)
{
eRmsState = E_RMS_START;
// rms_saadc_init();
nrf_gpio_pin_set(SAMPLE_POWER_PIN);
open_acquisition_relay();
timer3_rms_start();
}
/********************************************************************
* name : void acquisition_stop(void)
* description :
* Input : void
* Output : void
* Return :
********************************************************************/
void acquisition_stop(void)
{
timer3_rms_stop();
eRmsState = E_RMS_STOP;
nrf_gpio_pin_clear(SAMPLE_POWER_PIN);
close_acquisition_relay();
}
/********************************************************************
* name : void stimulate_start(void)
* description :
* Input : void
* Output : void
* Return :
********************************************************************/
void stimulate_start(void)
{
acquisition_stop(); //先停止肌电采集
// stimulate_stop(); //停止刺激,重新开始刺激
eRmsState = E_STIM_START;
open_stimulate_relay();
pwm0_play();
pwm2_play();
}
/********************************************************************
* name : void stimulate_stop(void)
* description :
* Input : void
* Output : void
* Return :
********************************************************************/
void stimulate_stop(void)
{
eRmsState = E_STIM_STOP;
close_stimulate_relay();
}
/********************************************************************
* name : static void detect_button(void)
* description :
* Input : void
* Output : void
* Return :
********************************************************************/
static void detect_button(void)
{
static uint8_t CountValue=0;
if((Bit_RESET == nrf_gpio_pin_read(KEY_PWR_SWITICH))&&((ChargeState == Uncharged))) //检测按键是否按下
{
CountValue++;
if(CountValue == 10)
{
if(POWER_CLOSE == DeviceState) //开机
{
DeviceState = POWER_OPEN;
nrf_gpio_pin_set(KEY_POWER); //锁定电源键给MCU供电
NRF_LOG_INFO("Open!");
StartAdv();
}
else if(POWER_OPEN == DeviceState) //关机
{
DeviceState = POWER_CLOSE;
acquisition_stop();
NRF_LOG_INFO("Close!");
nrf_gpio_pin_clear(KEY_POWER); //断电
}
}
}
else
{
CountValue = 0;
}
static uint16_t runBlinkCount = 0;
if(runBlinkCount == 0 && DeviceState == POWER_OPEN)
nrf_gpio_pin_set(LED_YELLOW);
else if(runBlinkCount == 1)
nrf_gpio_pin_clear(LED_YELLOW);
if(runBlinkCount++ > 8) //1S闪烁一次
{
runBlinkCount = 0;
}
}
/********************************************************************
* name : static void detect_charging_status(void)
* description :
* Input : void
* Output : void
* Return :
********************************************************************/
static void detect_charging_status(void)
{
static uint8_t CountValue=0;
if((Bit_RESET == nrf_gpio_pin_read(CHG_MANAGER_CHG))) //检测按键是否按下
{
ChargeState = Charging;
}
else
{
ChargeState = Uncharged;
}
}
/********************************************************************
* name : static void Hundredms_handler(void * p_context)
* description : 100ms中断一次
* Input : void *p_context
* Output : void
* Return :
********************************************************************/
static void Hundredms_handler(void * p_context)
{
//防止编译器警告同时清晰地的表明p_context未使用而不是应用程序忽略了。如果应用
//程序需要使用p_context则不需要这行代码
UNUSED_PARAMETER(p_context);
/* 开机按键检测处理 */
detect_button();
/* 电池电量检测 */
CalculateBatteryPower();
/* 充电状态检测 */
detect_charging_status();
static uint16_t delay_open = 0;
if(POWER_OPEN == DeviceState && delay_open != 70 && delay_open++ >60 )
{
//acquisition_start();
stimulate_start();
delay_open = 70;
}
}
/********************************************************************
* name : void AppTimersInit(void)
* description : APP定时器模块APP定时器
* Input : void
* Output : void
* Return :
********************************************************************/
void AppTimersInit(void)
{
ret_code_t err_code = app_timer_init();//初始化APP定时器模块
APP_ERROR_CHECK(err_code);
err_code = app_timer_create(&detect_button_100ms,
APP_TIMER_MODE_REPEATED,
Hundredms_handler);
APP_ERROR_CHECK(err_code);
}
/********************************************************************
* name : void ApplicationTimersStart(void)
* description : APP定时器
* Input : void
* Output : void
* Return :
********************************************************************/
void ApplicationTimersStart(void)
{
ret_code_t err_code;
err_code = app_timer_start(detect_button_100ms, DETECT_BUTTON, NULL);
APP_ERROR_CHECK(err_code);
}
/********************************************************************
* name : void PwmDACInit(void)
* description : DAC的pwm初始化
* Input : void
* Output : void
* Return :
********************************************************************/
void PwmDACInit(void)
{
//定义PWM初始化配置结构体并初始化参数
nrfx_pwm_config_t const config0 =
{
.output_pins =
{
PWM_DAC_GPIO, //通道0映射到P WM_DAC_GPIO空闲状态输出低电平
NRFX_PWM_PIN_NOT_USED , //通道1不使用
NRFX_PWM_PIN_NOT_USED , //通道2不使用
NRFX_PWM_PIN_NOT_USED //通道3不使用
},
.irq_priority = APP_IRQ_PRIORITY_LOWEST,//中断优先级
.base_clock = NRF_PWM_CLK_1MHz, //PWM时钟频率设置为1MHz
.count_mode = NRF_PWM_MODE_UP, //向上计数模式
.top_value = CYCLE_CALUE, //该值为周期值
.load_mode = NRF_PWM_LOAD_COMMON, //通用模式
.step_mode = NRF_PWM_STEP_AUTO //序列中的周期自动推进
};
APP_ERROR_CHECK(nrfx_pwm_init(&m_pwm_dac, &config0, NULL));//初始化PWM
}
/********************************************************************
* name : void PwmDACPlay(void)
* description : PWM
* Input : void
* Output : void
* Return :
********************************************************************/
void PwmDACPlay(void)
{
//定义PWM播放序列播放序列包含了PWM序列的起始地址、大小和序列播放控制描述
nrf_pwm_sequence_t const seq =
{
.values.p_common = dac_values,//指向PWM序列
.length = NRF_PWM_VALUES_LENGTH(dac_values),//PWM序列中包含的周期个数
.repeats = 0, //序列中周期重复次数为0
.end_delay = 0 //序列后不插入延时
};
//启动PWM序列播放flags设置为NRFX_PWM_FLAG_LOOP序列播放完成后自动触发任务重新播放
(void)nrfx_pwm_simple_playback(&m_pwm_dac, &seq, 1, NRFX_PWM_FLAG_LOOP);
}
void SetPWMValues(uint16_t tempvalue)
{
*dac_values = CYCLE_CALUE - tempvalue;
}
/********************************************************************
* name : void PwmDACStop(void)
* description : PWM
* Input : void
* Output : void
* Return :
********************************************************************/
void PwmDACStop(void)
{
nrfx_pwm_stop(&m_pwm_dac,1);
}
/********************************************************************
* name : void pwm0_common_init(void)
* description : PWM初始化
* Input : void
* Output : void
* Return :
********************************************************************/
void pwm0_common_init(void)
{
//定义PWM初始化配置结构体并初始化参数
nrfx_pwm_config_t const config0 =
{
.output_pins =
{
BASE_WAVE_06_PIN,
BASE_WAVE_07_PIN,
BASE_WAVE_08_PIN,
NRFX_PWM_PIN_NOT_USED
},
.irq_priority = APP_IRQ_PRIORITY_LOWEST,//中断优先级
.base_clock = NRF_PWM_CLK_1MHz, //PWM时钟频率设置为16MHz
.count_mode = NRF_PWM_MODE_UP, //向上计数模式
.top_value = 0, //使用波形装载模式时,该值被忽略
.load_mode = NRF_PWM_LOAD_WAVE_FORM, //独立装载模式
.step_mode = NRF_PWM_STEP_AUTO //序列中的周期自动推进
};
//初始化PWM
APP_ERROR_CHECK(nrfx_pwm_init(&m_pwm0, &config0, NULL));
/////////////
//pwm0_play();
}
/********************************************************************
* name : void pwm0_play(void)
* description : PWM开始播放
* Input : void
* Output : void
* Return :
********************************************************************/
void pwm0_play(void)
{
//定义PWM播放序列播放序列包含了PWM序列的起始地址、大小和序列播放控制描述
nrf_pwm_sequence_t const seq0 =
{
.values.p_wave_form = seq0_current_values,//指向PWM序列
.length = NRF_PWM_VALUES_LENGTH(seq0_current_values),//PWM序列中包含的周期个数
.repeats = 0, //序列中周期重复次数为0
.end_delay = 0 //序列后不插入延时
};
//启动PWM序列播放flags设置为NRFX_PWM_FLAG_LOOP序列播放完成后自动触发任务重新播放
//如改为NRFX_PWM_FLAG_STOP则播放结束后PWM停止
(void)nrfx_pwm_simple_playback(&m_pwm0, &seq0, 1,
NRFX_PWM_FLAG_LOOP);
}
void pwm0_stop(void)
{
nrfx_pwm_stop(&m_pwm0, 1);
}
/********************************************************************
* name : void pwm2_common_init(void)
* description : PWM初始化
* Input : void
* Output : void
* Return :
********************************************************************/
void pwm2common_init(void)
{
//定义PWM初始化配置结构体并初始化参数
nrfx_pwm_config_t const config0 =
{
.output_pins =
{
BOOST_VOLTAGE_CONTROL_PIN,
NRFX_PWM_PIN_NOT_USED,
NRFX_PWM_PIN_NOT_USED,
NRFX_PWM_PIN_NOT_USED
},
.irq_priority = APP_IRQ_PRIORITY_LOWEST,//中断优先级
.base_clock = NRF_PWM_CLK_16MHz, //PWM时钟频率设置为16MHz
.count_mode = NRF_PWM_MODE_UP, //向上计数模式
.top_value = 0, //使用波形装载模式时,该值被忽略
.load_mode = NRF_PWM_LOAD_WAVE_FORM, //独立装载模式
.step_mode = NRF_PWM_STEP_AUTO //序列中的周期自动推进
};
//初始化PWM
APP_ERROR_CHECK(nrfx_pwm_init(&m_pwm2, &config0, NULL));
/////////////
//pwm2_play();
}
/********************************************************************
* name : void pwm2_play(void)
* description : PWM开始播放
* Input : void
* Output : void
* Return :
********************************************************************/
void pwm2_play(void)
{
//定义PWM播放序列播放序列包含了PWM序列的起始地址、大小和序列播放控制描述
nrf_pwm_sequence_t const seq2 =
{
.values.p_wave_form = seq2_current_values,//指向PWM序列
.length = NRF_PWM_VALUES_LENGTH(seq2_current_values),//PWM序列中包含的周期个数
.repeats = 0, //序列中周期重复次数为0
.end_delay = 0 //序列后不插入延时
};
//启动PWM序列播放flags设置为NRFX_PWM_FLAG_LOOP序列播放完成后自动触发任务重新播放
//如改为NRFX_PWM_FLAG_STOP则播放结束后PWM停止
(void)nrfx_pwm_simple_playback(&m_pwm2, &seq2, 1,
NRFX_PWM_FLAG_LOOP);
}
void pwm2_stop(void)
{
nrfx_pwm_stop(&m_pwm2, 1);
}
/********************************************************************
* name : void GpioteInit(void)
* description : GPIOTE初始化
* Input : void
* Output : void
* Return :
********************************************************************/
void GpioteInit(void)
{
}
/********************************************************************
* name : void PPIPwmInit(void)
* description : PWM的PPI初始化
* Input : void
* Output : void
* Return :
********************************************************************/
void PPIPwmInit(void)
{
}
/*************************** END OF FILE ***************************/

32
app/Src/user_config.c Normal file
View File

@ -0,0 +1,32 @@
/********************************************************************
Copyright (c) 2025 Xiangyu Medical Co.Ltd. All rights reserved.
FileName : spi.c
Author : xiaozhengsheng
Version : V1.0
Date :
Note :
History :
********************************************************************/
/* Includes ------------------------------------------------------*/
#include "user_config.h"
//Log需要引用的头文件
#include "nrf_log.h"
#include "nrf_log_ctrl.h"
#include "nrf_log_default_backends.h"
version_t softVersion={
.major = 1,
.minor = 0,
.patch = 0, // 修订号 (.0)
.build = 0, // 构建号 (.0)
.testVersion = {"alpha1-1"} //内部测试版本正式发布需要填0alpha内部测试
};
char softWareVersion[SOFT_VERSION_MAX_LENGTH] = {0}; //软件版本号
void read_config_user_config(void)
{
snprintf(softWareVersion, SOFT_VERSION_MAX_LENGTH, "V%d.%d.%d.%d-%s", softVersion.major, softVersion.minor, softVersion.patch, softVersion.build, softVersion.testVersion);
NRF_LOG_INFO("Software Version: %s", softWareVersion);
NRF_LOG_INFO("product model: HL-PDJ-1");
}

883
app/main.c Normal file
View File

@ -0,0 +1,883 @@
/****************************************Copyright (c)************************************************
** []
**--------------File Info-----------------------------------------------------------------------------
** File name : main.c
** Last modified Date:
** Last Version :
** Descriptions : 使SDK版本-SDK_17.0.2
**----------------------------------------------------------------------------------------------------
** Created by :
** Created date :
** Version : 1.0
** Descriptions : 2021.4.6PM_EVT_CONN_SEC_CONFIG_REQ
2021.4.7广3广187.5ms
BLE事件处理函数中添加pm_handler_secure_on_connection函数
2021.4.9GATT初始化中加入nrf_ble_gatt_att_mtu_periph_set()MTU大小
2021.4.12:PWM初始化函数以及在定时器中调用PWM开始播放函数
2021.5.12300msMTU不成功的情况
**---------------------------------------------------------------------------------------------------*/
//引用的C库头文件
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
//APP定时器需要引用的头文件
#include "bsp_btn_ble.h"
//电源管理需要引用的头文件
#include "nrf_pwr_mgmt.h"
//SoftDevice handler configuration需要引用的头文件
#include "nrf_sdh.h"
#include "nrf_sdh_soc.h"
#include "nrf_sdh_ble.h"
//排序写入模块需要引用的头文件
#include "nrf_ble_qwr.h"
//GATT需要引用的头文件
#include "nrf_ble_gatt.h"
//连接参数协商需要引用的头文件
#include "ble_conn_params.h"
//广播需要引用的头文件
#include "ble_advdata.h"
#include "ble_advertising.h"
//串口透传需要引用的头文件
#include "drv_uart.h"
//引用FDS头文件
#include "fds.h"
//配对管理器包含头文件
#include "peer_manager.h"
#include "peer_manager_handler.h"
//WDT头文件
#include "nrfx_wdt.h"
#include "nrf_drv_clock.h"
#include "IoControl.h"
#include "IIR.h"
/***********************************************/
#define DEVICE_NAME "HL-PDJ-A" // 设备名称字符串
#define UARTS_SERVICE_UUID_TYPE BLE_UUID_TYPE_BLE // 串口透传服务UUID类型厂商自定义UUID
#define MIN_CONN_INTERVAL MSEC_TO_UNITS(20, UNIT_1_25_MS) // 最小连接间隔 (0.1 秒)
#define MAX_CONN_INTERVAL MSEC_TO_UNITS(20, UNIT_1_25_MS) // 最大连接间隔 (0.2 秒)
#define SLAVE_LATENCY 0 // 从机延迟
#define CONN_SUP_TIMEOUT MSEC_TO_UNITS(4000, UNIT_10_MS) // 监督超时(4 秒)
#define FIRST_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(5000) // 定义首次调用sd_ble_gap_conn_param_update()函数更新连接参数延迟时间5秒
#define NEXT_CONN_PARAMS_UPDATE_DELAY APP_TIMER_TICKS(30000) // 定义每次调用sd_ble_gap_conn_param_update()函数更新连接参数的间隔时间30秒
#define MAX_CONN_PARAMS_UPDATE_COUNT 3 // 定义放弃连接参数协商前尝试连接参数协商的最大次数3次
#define APP_ADV_INTERVAL 160 // 广播间隔 (100 ms)单位0.625 ms
#define APP_ADV_DURATION 0 // 广播持续时间单位10ms。设置为0表示不超时
#define SEC_PARAM_BOND 1 //是否支持绑定1支持0不支持
#define SEC_PARAM_MITM 0 //是否支持MITM保护1支持0不支持
#define SEC_PARAM_LESC 0 //是否使用安全连接配对LESC1使用LESC0使用传统配对
#define SEC_PARAM_KEYPRESS 0 //是否生成按键通知1生成0不生成
#define SEC_PARAM_IO_CAPABILITIES BLE_GAP_IO_CAPS_NONE //IO能力无输入/输出能力
#define SEC_PARAM_OOB 0 //是否支持OOB1支持0不支持
#define SEC_PARAM_MIN_KEY_SIZE 7 //最小加密密钥大小
#define SEC_PARAM_MAX_KEY_SIZE 16 //最大加密密钥大小
#define APP_BLE_OBSERVER_PRIO 3 //应用程序BLE事件监视者优先级应用程序不能修改该数值
#define APP_BLE_CONN_CFG_TAG 1 //SoftDevice BLE配置标志
//用于stack dump的错误代码可以用于栈回退时确定堆栈位置
#define DEAD_BEEF 0xDEADBEEF
//定义文件ID和该文件包含的记录的KEY
#define DEVICE_FILE (0x1000)//文件ID
#define DEVICE_SCHEME_KEY (0x1001)//记录KEY该记录存放的文件ID=0X1001
ble_gap_addr_t addr_ios;
uint8_array_t address_ios;
// 包含参数信息的记录
fds_record_t const m_SchemePara =
{
.file_id = DEVICE_FILE,
.key = DEVICE_SCHEME_KEY,
.data.p_data = &SchemePara,
//记录的长度必须以4字节为单位
.data.length_words = (sizeof(SchemePara) + 3) / sizeof(uint32_t),
};
//BLE串口透传例程中服务UUID列表
static ble_uuid_t m_adv_uuids[] =
{
{BLE_UUID_NUS_SERVICE,UARTS_SERVICE_UUID_TYPE}
};
//保存申请的喂狗通道
nrfx_wdt_channel_id m_channel_id;
/*必须的观察者函数*/
NRF_BLE_GATT_DEF(m_gatt); //定义名称为m_gatt的GATT模块实例
NRF_BLE_QWR_DEF(m_qwr); //定义一个名称为m_qwr的排队写入实例
BLE_ADVERTISING_DEF(m_advertising); //定义名称为m_advertising的广播模块实例
void WdtFeed(void);
//GATT事件处理函数
void gatt_evt_handler(nrf_ble_gatt_t * p_gatt, nrf_ble_gatt_evt_t const * p_evt)
{
//如果是MTU交换事件
if ((m_conn_handle == p_evt->conn_handle) && (p_evt->evt_id == NRF_BLE_GATT_EVT_ATT_MTU_UPDATED)) //如果主句发起MTU升级请求
{
//设置串口透传服务的有效数据长度MTU-opcode-handle
m_ble_nus_max_data_len = p_evt->params.att_mtu_effective - OPCODE_LENGTH - HANDLE_LENGTH;///247字节
NRF_LOG_INFO("Data len is set to 0x%X(%d)", m_ble_nus_max_data_len, m_ble_nus_max_data_len);
}
NRF_LOG_DEBUG("ATT MTU exchange completed. central 0x%x peripheral 0x%x",
p_gatt->att_mtu_desired_central,
p_gatt->att_mtu_desired_periph);
}
//初始化日志打印模块
static void log_init(void)
{
//初始化log程序模块
ret_code_t err_code = NRF_LOG_INIT(NULL);
APP_ERROR_CHECK(err_code);
//设置log输出终端根据sdk_config.h中的配置设置输出终端为UART或者RTT
NRF_LOG_DEFAULT_BACKENDS_INIT();
}
//GAP Generic Access Profile参数初始化该函数配置需要的GAP参数包括设备名称外观特征、首选连接参数
static void gap_params_init(void)
{
ret_code_t err_code;
//定义连接参数结构体变量
ble_gap_conn_params_t gap_conn_params;
ble_gap_conn_sec_mode_t sec_mode;
//设置GAP的安全模式,即设置设备名称特征的写权限这里设置的是安全模式1等级1即无安全性
BLE_GAP_CONN_SEC_MODE_SET_OPEN(&sec_mode);
//设置GAP设备名称
err_code = sd_ble_gap_device_name_set(&sec_mode,
(const uint8_t *)DEVICE_NAME,
strlen(DEVICE_NAME));
APP_ERROR_CHECK(err_code);
//如果需要设置外观特征,在这里使用如下的代码设置
/* err_code = sd_ble_gap_appearance_set(BLE_APPEARANCE_);
APP_ERROR_CHECK(err_code); */
//设置首选连接参数设置前先清零gap_conn_params
memset(&gap_conn_params, 0, sizeof(gap_conn_params));
gap_conn_params.min_conn_interval = MIN_CONN_INTERVAL;//最小连接间隔
gap_conn_params.max_conn_interval = MAX_CONN_INTERVAL;//最小连接间隔
gap_conn_params.slave_latency = SLAVE_LATENCY; //从机延迟
gap_conn_params.conn_sup_timeout = CONN_SUP_TIMEOUT; //监督超时
//调用协议栈API sd_ble_gap_ppcp_set配置GAP参数
err_code = sd_ble_gap_ppcp_set(&gap_conn_params);
APP_ERROR_CHECK(err_code);
}
//初始化GATT程序模块
static void gatt_init(void)
{
//初始化GATT程序模块
ret_code_t err_code = nrf_ble_gatt_init(&m_gatt, gatt_evt_handler);
//检查函数返回的错误代码
APP_ERROR_CHECK(err_code);
//设置服务端的默认MTU大小
err_code = nrf_ble_gatt_att_mtu_periph_set(&m_gatt, NRF_SDH_BLE_GATT_MAX_MTU_SIZE);
APP_ERROR_CHECK(err_code);
}
//空闲状态处理函数(该函数需要放到主循环里面执行)。如果没有挂起的日志操作,则睡眠直到下一个事件发生后唤醒系统
static void idle_state_handle(void)
{
//处理挂起的log
if (NRF_LOG_PROCESS() == false)
{
//运行电源管理
nrf_pwr_mgmt_run();
}
}
//删除绑定信息
static void delete_bonds(void)
{
ret_code_t err_code;
err_code = pm_peers_delete();
APP_ERROR_CHECK(err_code);
}
//初始化电源管理模块
static void power_management_init(void)
{
ret_code_t err_code;
//初始化电源管理
err_code = nrf_pwr_mgmt_init();
//检查函数返回的错误代码
APP_ERROR_CHECK(err_code);
}
//连接参数协商模块错误处理事件参数nrf_error包含了错误代码通过nrf_error可以分析错误信息
static void conn_params_error_handler(uint32_t nrf_error)
{
//检查错误代码
APP_ERROR_HANDLER(nrf_error);
}
//连接参数协商模块事件处理函数
static void on_conn_params_evt(ble_conn_params_evt_t * p_evt)
{
ret_code_t err_code;
//判断事件类型,根据事件类型执行动作
//连接参数协商失败
if (p_evt->evt_type == BLE_CONN_PARAMS_EVT_FAILED)
{
err_code = sd_ble_gap_disconnect(m_conn_handle, BLE_HCI_CONN_INTERVAL_UNACCEPTABLE);
APP_ERROR_CHECK(err_code);
}
//连接参数协商成功
if (p_evt->evt_type == BLE_CONN_PARAMS_EVT_SUCCEEDED)
{
//功能代码;
}
}
//连接参数协商模块初始化(用于启动和执行连接参数协商规程)
static void conn_params_init(void)
{
ret_code_t err_code;
//定义连接参数协商模块初始化结构体
ble_conn_params_init_t cp_init;
//配置之前先清零
memset(&cp_init, 0, sizeof(cp_init));
//设置为NULL从主机获取连接参数
cp_init.p_conn_params = NULL;
//连接或启动通知到首次发起连接参数更新请求之间的时间设置为5秒
cp_init.first_conn_params_update_delay = FIRST_CONN_PARAMS_UPDATE_DELAY;
//每次调用sd_ble_gap_conn_param_update()函数发起连接参数更新请求的之间的间隔时间设置为30秒
cp_init.next_conn_params_update_delay = NEXT_CONN_PARAMS_UPDATE_DELAY;
//放弃连接参数协商前尝试连接参数协商的最大次数设置为3次
cp_init.max_conn_params_update_count = MAX_CONN_PARAMS_UPDATE_COUNT;
//连接参数更新从连接事件开始计时
cp_init.start_on_notify_cccd_handle = BLE_GATT_HANDLE_INVALID;
//连接参数更新失败不断开连接
cp_init.disconnect_on_fail = false;
//注册连接参数更新事件句柄
cp_init.evt_handler = on_conn_params_evt;
//注册连接参数更新错误事件句柄
cp_init.error_handler = conn_params_error_handler;
//调用库函数(以连接参数更新初始化结构体为输入参数)初始化连接参数协商模块
err_code = ble_conn_params_init(&cp_init);
APP_ERROR_CHECK(err_code);
}
//BLE事件处理函数
static void ble_evt_handler(ble_evt_t const * p_ble_evt, void * p_context)
{
ret_code_t err_code = NRF_SUCCESS;
//连接建立后立即启动安全当接收到连接建立事件BLE_GAP_EVT_CONNECTED时启动安全性
pm_handler_secure_on_connection(p_ble_evt);
//判断BLE事件类型根据事件类型执行相应操作
switch (p_ble_evt->header.evt_id)
{
//断开连接事件
case BLE_GAP_EVT_DISCONNECTED:
//打印提示信息
NRF_LOG_INFO("Disconnected.");
DeviceConnectState = DisconnectState;
DisconnectControl();
break;
//连接事件
case BLE_GAP_EVT_CONNECTED:
NRF_LOG_INFO("Connected.");
DeviceConnectState = ConnectState;
DisconnectControl();
//保存连接句柄
m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle;
//将连接句柄分配给排队写入实例,分配后排队写入实例和该连接关联,这样,当有
//多个连接的时候,通过关联不同的排队写入实例,很方便单独处理各个连接
err_code = nrf_ble_qwr_conn_handle_assign(&m_qwr, m_conn_handle);
APP_ERROR_CHECK(err_code);
break;
//PHY更新事件
case BLE_GAP_EVT_PHY_UPDATE_REQUEST:
{
NRF_LOG_DEBUG("PHY update request.");
ble_gap_phys_t const phys =
{
.rx_phys = BLE_GAP_PHY_AUTO,
.tx_phys = BLE_GAP_PHY_AUTO,
};
//响应PHY更新规程
err_code = sd_ble_gap_phy_update(p_ble_evt->evt.gap_evt.conn_handle, &phys);
APP_ERROR_CHECK(err_code);
} break;
//GATT客户端超时事件
case BLE_GATTC_EVT_TIMEOUT:
NRF_LOG_DEBUG("GATT Client Timeout.");
//断开当前连接
err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gattc_evt.conn_handle,
BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
APP_ERROR_CHECK(err_code);
break;
//GATT服务器超时事件
case BLE_GATTS_EVT_TIMEOUT:
NRF_LOG_DEBUG("GATT Server Timeout.");
//断开当前连接
err_code = sd_ble_gap_disconnect(p_ble_evt->evt.gatts_evt.conn_handle,
BLE_HCI_REMOTE_USER_TERMINATED_CONNECTION);
APP_ERROR_CHECK(err_code);
break;
default:
break;
}
}
//初始化BLE协议栈
static void ble_stack_init(void)
{
ret_code_t err_code;
//请求使能SoftDevice该函数中会根据sdk_config.h文件中低频时钟的设置来配置低频时钟
err_code = nrf_sdh_enable_request();
APP_ERROR_CHECK(err_code);
//定义保存应用程序RAM起始地址的变量
uint32_t ram_start = 0;
//使用sdk_config.h文件的默认参数配置协议栈获取应用程序RAM起始地址保存到变量ram_start
err_code = nrf_sdh_ble_default_cfg_set(APP_BLE_CONN_CFG_TAG, &ram_start);
APP_ERROR_CHECK(err_code);
//使能BLE协议栈
err_code = nrf_sdh_ble_enable(&ram_start);
APP_ERROR_CHECK(err_code);
//注册BLE事件回调函数
NRF_SDH_BLE_OBSERVER(m_ble_observer, APP_BLE_OBSERVER_PRIO, ble_evt_handler, NULL);
}
//广播事件处理函数
static void on_adv_evt(ble_adv_evt_t ble_adv_evt)
{
ret_code_t err_code;
//判断广播事件类型
switch (ble_adv_evt)
{
//快速广播启动事件:快速广播启动后会产生该事件
case BLE_ADV_EVT_FAST:
NRF_LOG_INFO("Fast advertising.");
//设置广播指示灯为正在广播D1指示灯闪烁
// err_code = bsp_indication_set(BSP_INDICATE_ADVERTISING);
// APP_ERROR_CHECK(err_code);
break;
//广播IDLE事件广播超时后会产生该事件
case BLE_ADV_EVT_IDLE:
//断电
NRF_LOG_INFO("BLE_ADV_EVT_IDLE");
nrf_gpio_pin_clear(KEY_POWER);
break;
default:
break;
}
}
//广播初始化
static void advertising_init(void)
{
uint32_t err_code;
//定义广播初始化配置结构体变量
ble_advertising_init_t init;
err_code = sd_ble_gap_addr_get(&addr_ios);
APP_ERROR_CHECK(err_code);
address_ios.size = 6;
address_ios.p_data = addr_ios.addr;
ble_advdata_manuf_data_t test;
test.company_identifier = 0x1122;
test.data = address_ios;
//配置之前先清零
memset(&init, 0, sizeof(init));
//设备名称类型:全名
init.advdata.name_type = BLE_ADVDATA_FULL_NAME;
//是否包含外观:包含
init.advdata.include_appearance = false;
//包含ble设备地址
// init.advdata.include_ble_device_addr = true;
init.advdata.p_manuf_specific_data = &test;
init.srdata.uuids_complete.uuid_cnt = sizeof(m_adv_uuids)/sizeof(m_adv_uuids[0]);
init.srdata.uuids_complete.p_uuids = m_adv_uuids;
//Flag:一般可发现模式不支持BR/EDR
init.advdata.flags = BLE_GAP_ADV_FLAGS_LE_ONLY_GENERAL_DISC_MODE;
//设置广播模式为快速广播
init.config.ble_adv_fast_enabled = true;
//设置广播间隔和广播持续时间
init.config.ble_adv_fast_interval = APP_ADV_INTERVAL;
init.config.ble_adv_fast_timeout = APP_ADV_DURATION;
//广播事件回调函数
init.evt_handler = on_adv_evt;
//初始化广播
err_code = ble_advertising_init(&m_advertising, &init);
APP_ERROR_CHECK(err_code);
//设置广播配置标记。APP_BLE_CONN_CFG_TAG是用于跟踪广播配置的标记这是为未来预留的一个参数在将来的SoftDevice版本中
//可以使用sd_ble_gap_adv_set_configure()配置新的广播配置
//当前SoftDevice版本S132 V7.2.0版本支持的最大广播集数量为1因此APP_BLE_CONN_CFG_TAG只能写1。
ble_advertising_conn_cfg_tag_set(&m_advertising, APP_BLE_CONN_CFG_TAG);
}
//启动广播,该函数所用的模式必须和广播初始化中设置的广播模式一样
static void advertising_start(bool erase_bonds)
{
if(erase_bonds == true)
{
//删除flash中存储的配对信息执行完删除后会产生PM_EVT_PEERS_DELETE_SUCCEEDED事件
//在该事件下会启动广播
delete_bonds();
}
else
{
//使用广播初始化中设置的广播模式启动广播
ret_code_t err_code = ble_advertising_start(&m_advertising, BLE_ADV_MODE_FAST);
//检查函数返回的错误代码
APP_ERROR_CHECK(err_code);
}
}
//排队写入事件处理函数,用于处理排队写入模块的错误
static void nrf_qwr_error_handler(uint32_t nrf_error)
{
//检查错误代码
APP_ERROR_HANDLER(nrf_error);
}
//服务初始化,包含初始化排队写入模块和初始化应用程序使用的服务
static void services_init(void)
{
ret_code_t err_code;
//定义排队写入初始化结构体变量
nrf_ble_qwr_init_t qwr_init = {0};
//排队写入事件处理函数
qwr_init.error_handler = nrf_qwr_error_handler;
//初始化排队写入模块
err_code = nrf_ble_qwr_init(&m_qwr, &qwr_init);
APP_ERROR_CHECK(err_code);
//串口透传服务初始化
service_nus_init();
}
#if 1
//配对管理器事件处理函数
static void pm_evt_handler(pm_evt_t const * p_evt)
{
//1、打印日志 2、连接已绑定设备时启动加密 3、出现错误调用错误处理程序
pm_handler_on_pm_evt(p_evt);
//清理配对设备在flash中的保存的绑定信息当flash存储空间不足时删除
//排列最低的配对设备的信息
pm_handler_flash_clean(p_evt);
switch(p_evt->evt_id)
{
//存储的绑定信息已成功删除
case PM_EVT_PEERS_DELETE_SUCCEEDED:
//若程序启动时执行了删除绑定信息操作,在该事件下启动广播
advertising_start(false);
break;
case PM_EVT_CONN_SEC_CONFIG_REQ:
{
// 拒绝来自已经绑定对等方的配对请求.
pm_conn_sec_config_t conn_sec_config = {.allow_repairing = true};
pm_conn_sec_config_reply(p_evt->conn_handle, &conn_sec_config);
} break;
default:
break;
}
}
#endif
//配对管理器初始化
static void peer_manager_init(void)
{
ble_gap_sec_params_t sec_param;
ret_code_t err_code;
//初始化配对管理器软件库
err_code = pm_init();
APP_ERROR_CHECK(err_code);
//配置安全参数前先清零结构体sec_param
memset(&sec_param, 0, sizeof(ble_gap_sec_params_t));
//初始化安全性参数结构体,
sec_param.bond = SEC_PARAM_BOND; //支持绑定
sec_param.mitm = SEC_PARAM_MITM; //无MITM保护
sec_param.lesc = SEC_PARAM_LESC; //不支持安全连接配对,即使用传统配对
sec_param.keypress = SEC_PARAM_KEYPRESS; //无按键通知
sec_param.io_caps = SEC_PARAM_IO_CAPABILITIES; //无IO能力
sec_param.oob = SEC_PARAM_OOB; //不支持OOB
sec_param.min_key_size = SEC_PARAM_MIN_KEY_SIZE; //最小加密密钥大小7字节
sec_param.max_key_size = SEC_PARAM_MAX_KEY_SIZE; //最大加密密钥大小16字节
//本地密钥分发配置
sec_param.kdist_own.enc = 1; //分发本地LTK
sec_param.kdist_own.id = 1; //分发本地IRK
//对端密钥分发配置
sec_param.kdist_peer.enc = 1; //要求对方分发LTK
sec_param.kdist_peer.id = 1; //要求对方分发IRK
//配置安全参数
err_code = pm_sec_params_set(&sec_param);
APP_ERROR_CHECK(err_code);
//向配对管理器注册事件句柄
err_code = pm_register(pm_evt_handler);
APP_ERROR_CHECK(err_code);
}
//FDS事件处理函数
static void fds_evt_handler(fds_evt_t const * p_evt)
{
//判断事件类型
switch (p_evt->id)
{
case FDS_EVT_INIT://FDS初始化事件
if (p_evt->result == NRF_SUCCESS)//初始化成功
{
my_fds_info.busy = false;
}
break;
case FDS_EVT_WRITE://FDS写记录事件
{
if (p_evt->result == NRF_SUCCESS)//写记录成功
{
my_fds_info.busy = false;
}
} break;
case FDS_EVT_UPDATE://FDS更新记录事件
{
if (p_evt->result == NRF_SUCCESS)//写记录成功
{
my_fds_info.busy = false;
}
} break;
case FDS_EVT_GC://FDS碎片整理事件
{
if (p_evt->result == NRF_SUCCESS)//碎片整理成功
{
my_fds_info.busy = false;
}
} break;
default:
break;
}
}
//等待FDS初始化完成
static void wait_for_fds_ready(void)
{
while (my_fds_info.busy)
{
(void) sd_app_evt_wait();
}
}
// 读取方案并且发送
void read_scheme(void)
{
ret_code_t rc;
//定义并初始化记录描述符结构体变量
fds_record_desc_t desc = {0};
//定义并初始化记录查找令牌结构体变量
fds_find_token_t tok = {0};
uint16_t tempidvalue;
//清零tok从头查找
memset(&tok, 0x00, sizeof(fds_find_token_t));
//在DEVICE_FILE文件中查找记录m_version_record
rc = fds_record_find(DEVICE_FILE, DEVICE_SCHEME_KEY, &desc, &tok);
//查找到记录后,读取记录内容
if(rc == NRF_SUCCESS)
{
fds_flash_record_t temp = {0};
//打开记录读取记录内容
rc = fds_record_open(&desc, &temp);
APP_ERROR_CHECK(rc);
//拷贝记录内容
memcpy(&SchemeData, temp.p_data, sizeof(SchemeData_t));
//读取后,关闭记录
rc = fds_record_close(&desc);
APP_ERROR_CHECK(rc);
// 连接状态下发送方案ID
if(DeviceConnectState == ConnectState)
{
SchemeQuery(SchemeData.SchemeIDMSB,SchemeData.SchemeIDLSB);
}
// 未连接状态下给默认的治疗方案
else
{
StimStateInfoStructInit(SchemeData);
}
}
}
// 存储管理中断处理函数
void FdsHandler(fds_record_desc_t *Desc,fds_find_token_t *Tok)
{
ret_code_t rc;
if(my_fds_info.read == true)//读取记录
{
my_fds_info.read = false;
read_scheme();//读取记录数据,并发送
}
//更新记录m_fw_record
if((my_fds_info.scheme_update == true) && (my_fds_info.busy == false))
{
//清零tok从头查找
memset(Tok, 0x00, sizeof(fds_find_token_t));
//在DEVICE_FILE文件中查找记录m_fw_record
rc = fds_record_find(DEVICE_FILE, DEVICE_SCHEME_KEY, Desc, Tok);
if (rc == NRF_SUCCESS)
{
my_fds_info.busy = true;
my_fds_info.scheme_update = false;
//更新记录m_fw_record
rc = fds_record_update(Desc, &m_SchemePara);
APP_ERROR_CHECK(rc);
wait_for_fds_ready();
NRF_LOG_INFO("fds_record_update");
}
}
}
void wdt_event_handler(void)
{
}
void WdtInit(void)
{
ret_code_t err_code = NRF_SUCCESS;
//定义WDT配置结构体并使用
nrfx_wdt_config_t config = NRFX_WDT_DEAFULT_CONFIG;
//初始化WDT
err_code = nrfx_wdt_init(&config, wdt_event_handler);
//申请喂狗通道,也就是使用哪个
err_code = nrfx_wdt_channel_alloc(&m_channel_id);
APP_ERROR_CHECK(err_code);
//启动WDT
nrfx_wdt_enable();
}
//喂狗函数
void WdtFeed(void)
{
//喂狗
nrfx_wdt_channel_feed(m_channel_id);
}
void clocks_start(void)
{
NRF_CLOCK->EVENTS_HFCLKSTARTED = 0;//清零高频时钟启动事件
NRF_CLOCK->TASKS_HFCLKSTART = 1; //启动高频时钟
//等待高频时钟启动完成
while (NRF_CLOCK->EVENTS_HFCLKSTARTED == 0);
}
//驱动初始化
void DeviceInit(void)
{
/* 初始化控制gpio */
GpioInit();
clocks_start();
EXIT_KEY_Init();
/* 初始化APP定时器 */
AppTimersInit();
timer3_rms_init();
/* DACPWM初始化 */
// PwmDACInit();
/* SAADC初始化 */
battery_adc_init();
rms_saadc_init();
/* 采样的PPI初始化 */
//PPIPwmInit();
PPIEegAdcInit();
/* GPIOTE初始化 */
GpioteInit();
// nrf_gpio_pin_clear(H_CTL1_PWM);
// nrf_gpio_pin_clear(H_CTL2_PWM);
/* 刺激PWM初始化 */
pwm0_common_init();
pwm2common_init();
//timer1_output_ctrl_init();
/* 喂狗初始化 */
WdtInit();
}
//广播中添加MAC地址
void MacSet(void)
{
ble_gap_addr_t addr;
uint32_t err_code = sd_ble_gap_addr_get(&addr);
APP_ERROR_CHECK(err_code);
memcpy(BLE_MAC,addr.addr,BLE_GAP_ADDR_LEN);
err_code = sd_ble_gap_addr_set(&addr);
APP_ERROR_CHECK(err_code);
}
void StartAdv(void)
{
//启动广播
advertising_start(false);
}
// 关闭广播
void StopAdv(void)
{
NRF_LOG_INFO("StopAdv!");
sd_ble_gap_adv_stop(m_advertising.adv_handle);
}
void user_ble_init(void)
{
//初始化协议栈
ble_stack_init();
//变量初始化
VariableInit();
//配置GAP参数
gap_params_init();
//初始化GATT
gatt_init();
//初始化服务
services_init();
//在广播数据中添加MAC地址
MacSet();
//初始化广播
advertising_init();
//连接参数协商初始化
conn_params_init();
//配对管理器初始化
peer_manager_init();
//LOG打印信息
NRF_LOG_INFO("BLE started.");
}
//fds存储管理初始化
void fdsInit(ret_code_t rec,fds_record_desc_t desct,fds_find_token_t token)
{
//注册FDS事件回调函数接收FS事件
(void)fds_register(fds_evt_handler);
my_fds_info.busy = true;
rec = fds_init();//初始化FDS
APP_ERROR_CHECK(rec);//用错误处理模块检查函数返回值
//FDS初始化是异步的因此要等待FDS初始化完成
wait_for_fds_ready();
//清零tok从头查找
memset(&token, 0x00, sizeof(fds_find_token_t));
//在DEVICE_FILE文件中查找记录m_desp_record
rec = fds_record_find(DEVICE_FILE, DEVICE_SCHEME_KEY, &desct, &token);
NRF_LOG_INFO("rec = %d",rec);
//没有查找到m_desp_record记录写入记录
if (rec != NRF_SUCCESS)
{
my_fds_info.busy = true;
StimStateInfoStructInit(PreStorageSchemeData); // 用预存的信息给刺激参数赋值
memcpy(SchemePara.text,&PreStorageSchemeData,sizeof(PreStorageSchemeData));
rec = fds_record_write(&desct, &m_SchemePara);
APP_ERROR_CHECK(rec);
wait_for_fds_ready();
}
else
{
my_fds_info.read = true;
}
}
//主函数
int main(void)
{
ret_code_t rc;
//定义并初始化记录描述符结构体变量
fds_record_desc_t desc = {0};
//定义并初始化记录查找令牌结构体变量
fds_find_token_t tok = {0};
//初始化log程序模块
log_init();
//滤波器初始化
FilterInit();
// 设备预存信息初始化ID :101 腹直肌分离
PreStorageSchemeDataInit();
//fds存储管理初始化
fdsInit(rc,desc,tok);
//器件初始化
DeviceInit();
//初始化电源管理
power_management_init();
user_ble_init();
//启动已经创建的APP定时器
ApplicationTimersStart();
//主循环
while(true)
{
// 存储事件处理函数
FdsHandler(&desc,&tok);
//处理挂起的LOG和运行电源管理
idle_state_handle();
WdtFeed();
if(POWER_CLOSE == DeviceState)
{
continue;
}
KeyPinHandler();// 按键中断处理
//输出电流控制
/* 适配器和电极片脱落状态变化上传 */
if(AdapterState == LastAdapterState)
{
StateUpLoad(AdapterState,ElectrodeStatusInfo);
if(AdapterState == AdapterConnected)
{
LastAdapterState = AdapterNotConnected;
}
else
{
LastAdapterState = AdapterConnected;
}
}
if(ElectrodeStatusInfo == LastElectrodeStatusInfo)
{
StateUpLoad(AdapterState,ElectrodeStatusInfo);
if(ElectrodeStatusInfo == ElectrodeFalloff)
{
LastElectrodeStatusInfo = ElectrodeConnectted;
}
else
{
LastElectrodeStatusInfo = ElectrodeFalloff;
}
}
}
}

View File

@ -0,0 +1,82 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_ATOMIC_H_INCLUDED
#define HAL_ATOMIC_H_INCLUDED
#include <stdint.h>
/** @file
* This file contains declarations of the Atomic section routines and necessary types.
*
* @defgroup hal_atomic HAL Atomic API
* @ingroup hal_15_4
* @{
* @brief Module to declare HAL Atomic API
* @details The Atomic module implements atomic section interface. This is made by disabling the global interrupts,
* which is a hardware dependent feature. The user may call hal_atomic_start() to open an atomic section
* (disable interrupts) and hal_atomic_end() to exit from the section (restore interrupts). The algorithm
* supports nesting sections.
*/
typedef volatile uint32_t atomic_t;
/**@brief Enters atomic section.
*
* @details Disables global interrupts.
*
* @param[in] p_atomic pointer to buffer to store current value of the status register.
*/
void hal_atomic_start(atomic_t * p_atomic);
/**
* @brief Exits atomic section
*
* @details Restores status register
*
* @param[in] p_atomic pointer to buffer to restore current value of the status register from.
*/
void hal_atomic_end(atomic_t * p_atomic);
/** @} */
#endif // HAL_ATOMIC_H_INCLUDED

View File

@ -0,0 +1,59 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_CLOCK_H_INCLUDED
#define HAL_CLOCK_H_INCLUDED
/**
* @defgroup hal_clock HAL Clock API
* @ingroup hal_15_4
* @{
* @brief Module to declare HAL Clock library
*/
/** @brief This function performs initialization and configuration of processor's
* clock module.
*/
void hal_clock_init(void);
/** @} */
#endif /* HAL_CLOCK_H_INCLUDED */

View File

@ -0,0 +1,113 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_DEBUG_INTERFACE_H_INCLUDED
#define HAL_DEBUG_INTERFACE_H_INCLUDED
#if defined(NRF52) || defined(NRF52840_XXAA)
#include "nrf_assert.h"
#endif // NRF52
/**
* @defgroup hal_debug_interface HAL Debug Interface
* @ingroup hal_15_4
* @{
* @brief Module to declare HAL debug interface
*/
#ifdef CONFIG_DEBUG
#include <stdint.h>
#define HAL_DEBUG_INTERFACE_INIT() hal_debug_init()
#define HAL_DEBUG_INTERFACE_PUT(c, n) hal_debug_put(c, n)
#define HAL_DEBUG_INTERFACE_PUTC(c) hal_debug_putc(c)
#define HAL_DEBUG_INTERFACE_PUTS(s) hal_debug_puts(s)
/**
* @brief Debug interface initialization
*/
void hal_debug_init(void);
/**
* @brief Sends string to the debug interface
*
* @details send debug data using debug interface
*
* @param[in] p_data debug string.
* @param[in] len string length.
*/
void hal_debug_put(const void * p_data, uint8_t len);
/**
* @brief Sends char symbol to the debug interface
*
* @details send debug data using debug interface
*
* @param[in] data char symbol.
*/
void hal_debug_putc(const char data);
/**
* @brief Sends a null-terminated string to the debug interface
*
* @details send debug data using debug interface
*
* @param[in] p_data null-terminated string.
*/
void hal_debug_puts(const char * p_data);
#else
/* If debug is disabled, these macros are just a stub.*/
#define HAL_DEBUG_INTERFACE_INIT()
#define HAL_DEBUG_INTERFACE_PUT(c, n)
#define HAL_DEBUG_INTERFACE_PUTC(c)
#define HAL_DEBUG_INTERFACE_PUTS(s)
#endif // CONFIG_DEBUG
/** @} */
#endif // HAL_DEBUG_INTERFACE_H_INCLUDED

View File

@ -0,0 +1,65 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_DELAY_H_INCLUDED
#define HAL_DELAY_H_INCLUDED
#include <stdint.h>
/** @file
* This file contains declaration of the Hardware Delay routine.
*
* @defgroup hal_delay HAL Delay API
* @ingroup hal_15_4
* @{
* @brief Module to declare HAL Delay API
* @details The Delay module implements the only hal_delay() routine to delay the execution for some microseconds.
*/
/**@brief Function for delaying execution for number of microseconds.
*
* @param[in] number_of_us number of microseconds to delay.
*/
void hal_delay(uint32_t number_of_us);
/** @} */
#endif // HAL_DELAY_H_INCLUDED

View File

@ -0,0 +1,54 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_LED_H_INCLUDED
#define HAL_LED_H_INCLUDED
#include <stdint.h>
#define HAL_LED_AMOUNT 4
void hal_led_init(uint32_t led_mask);
void hal_led_on(uint32_t led_mask);
void hal_led_off(uint32_t led_mask);
void hal_led_toggle(uint32_t led_mask);
#endif /* HAL_LED_H_INCLUDED */

View File

@ -0,0 +1,89 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_MUTEX_H_INCLUDED
#define HAL_MUTEX_H_INCLUDED
#include "hal_atomic.h"
/** @file
* This is a simple mutex interface to be used in System Memory Manager
* to make it thread aware.
*
* @defgroup hal_mutex HAL Mutex API
* @ingroup hal_15_4
* @{
* @details NRF52 implementation is void and PC implementation is identical to atomic.
*/
#if defined ( __GNUC__ )
#include <signal.h>
typedef volatile sig_atomic_t mutex_t;
#else
#include <stdint.h>
typedef volatile uint32_t mutex_t;
#endif
/**@brief Configures mutex lock before first usage.
*
* @param[inout] p_mutex pointer to mutex variable.
*/
void hal_mutex_init(mutex_t * p_mutex);
/**@brief Atomically sets mutex. If set is failed, enters spin lock loop.
*
* @param[in] p_mutex pointer to mutex variable.
*/
void hal_mutex_lock(mutex_t * p_mutex);
/**
* @brief Atomically clears mutex. Every other thread, spinning at this lock may
* try to lock it afterwards.
*
* @param[in] p_mutex pointer to mutex variable.
*/
void hal_mutex_unlock(mutex_t * p_mutex);
/** @} */
#endif /* HAL_MUTEX_H_INCLUDED */

View File

@ -0,0 +1,70 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_RNG_H_INCLUDED
#define HAL_RNG_H_INCLUDED
#include <stdint.h>
/** @file
* This file contains declaration of the random number generator routine.
*
* @defgroup hal_rng HAL Random Number Generator API
* @ingroup hal_15_4
* @{
* @brief Module to declare HAL Random Number Generator API
* @details The Random number generator module implements the only hal_rand_get() routine to get an unsigned 8-bits
* random number generated by hardware.
*/
/**@brief Initialize hardware random generator.
*/
extern void hal_rand_init(void);
/**@brief Generates random number using hardware.
*
* @return An unsigned 8-bits random number.
*/
extern uint8_t hal_rand_get(void);
/** @} */
#endif /* HAL_RNG_H_INCLUDED */

View File

@ -0,0 +1,100 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_SLEEP_H_INCLUDED
#define HAL_SLEEP_H_INCLUDED
#include <stdint.h>
/** @file
* This file contains declaration of the HAL sleep interface.
*
* @defgroup hal_sleep HAL Sleep API
* @ingroup hal_15_4
* @{
* @brief Module to declare HAL Sleep API
* @details The Sleep module implements the only hal_sleep() routine to put the hardware to the sleep mode for some
* milliseconds. The user can use convenient macros DAYS_TO_MS(), HOURS_TO_MS(), MINS_TO_MS(), and SEC_TO_MS()
* to convert different time periods into milliseconds. Please note that this module requires a call to
* hal_sleep_init() which is in turn called by sys_init() before using any module routines. This module is
* only used to implement the System Sleep interface. The hal_sleep() routine is not assumed to be used by
* the user explicitly.
*/
/**@brief Converts days to milliseconds */
#define DAYS_TO_MS(d) ((d) * 3600L * 24L * 1000L )
/**@brief Converts hours to milliseconds */
#define HOURS_TO_MS(h) ((h) * 3600L * 1000L )
/**@brief Converts minutes to milliseconds */
#define MINS_TO_MS(m) ((m) * 60L * 1000L )
/**@brief Converts seconds to milliseconds */
#define SEC_TO_MS(s) ((s) * 1000L )
/**@brief Information, provided by the HAL, in order to explain the reason,
* which caused the system to wake up.
*/
typedef enum
{
UNKNOWN_INTERRUPT, /**< HAL can't define a wake up reason */
RTC_CC_INTERRUPT /**< RTC interrupt was the awakening reason */
} hal_wakeup_reason_t;
/**@brief Puts hardware into the sleep mode for some milliseconds.
*
* @param[in] sleep_time_ms Time to sleep in ms
*
* @retval wakeup_reason Specifies reason of awakening
*/
hal_wakeup_reason_t hal_sleep(uint32_t sleep_time_ms);
/**@brief Initialization of the sleep module
*
*/
void hal_sleep_init(void);
/** @} */
#endif /* HAL_SLEEP_H_INCLUDED */

View File

@ -0,0 +1,124 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_TASK_H_INCLUDED
#define HAL_TASK_H_INCLUDED
#include <stdint.h>
#include "hal_atomic.h"
#include "sys_utils.h"
#include "sys_task_scheduler.h"
/**
* @defgroup hal_task HAL Tasks
* @ingroup hal_15_4
* @{
* @brief Module to declare HAL tasks library
*/
/**@brief Identifiers for registered HAL handlers.
*
* @details enumeration with identifiers of registered HAL handlers.
* HAL handlers will be called from the HAL task.
*/
typedef enum
{
HAL_TIMER_TASK_ID,
HAL_UART_TASK_ID,
HAL_TIMER_CRITICAL_MANUAL_TASK,
HAL_TASKS_AMOUNT,
} hal_task_id_t;
/**@brief Prototype of a HAL task handler.
*
* @details Handler which will be called from HAL task.
*/
typedef void (* hal_task_handler_t)(void);
void hal_task_handler(void);
void hal_timer_task_handler(void);
void hal_uart_task_handler(void);
void hal_timer_critical_manual_handler(void);
/**@brief Pending HAL tasks.
*
* @details Variable which includes markers of pending HAL tasks.
*/
extern volatile uint_fast16_t g_hal_tasks;
/**@brief Notify task scheduler to add a HAL task for execution.
*
* @details The function sets a marker for the HAL task for execution.
*
* @param[in] hal_task_id HAL task identifier (see \ref hal_task_id_t enumeration).
*/
static inline void hal_task_post(hal_task_id_t hal_task_id)
{
atomic_t atomic = 0;
hal_atomic_start(&atomic);
g_hal_tasks |= BIT(hal_task_id);
hal_atomic_end(&atomic);
sys_task_post(HAL_TASK_ID);
}
/**@brief Removes a task from pending list in HAL task scheduler.
*
* @details The function removes a marker from the HAL execution list.
*
* @param[in] hal_task_id HAL task identifier (see \ref hal_task_id_t enumeration).
*/
static inline void hal_task_unpost(hal_task_id_t hal_task_id)
{
atomic_t atomic = 0;
hal_atomic_start(&atomic);
g_hal_tasks &= ~BIT(hal_task_id);
hal_atomic_end(&atomic);
}
/** @} */
#endif // HAL_TASK_H_INCLUDED

View File

@ -0,0 +1,80 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_TIMER_H_INCLUDED
#define HAL_TIMER_H_INCLUDED
#include "hal_delay.h"
#include <stdint.h>
/**
* @defgroup hal_timer HAL Timer
* @ingroup hal_15_4
* @{
* @brief Module to declare HAL timer interface
*/
/**@brief Initializes hardware timer.
*/
void hal_timer_init(void);
/**@brief Starts hardware timer.
*
* @param[in] interval timer interval in microseconds for timer start.
*/
void hal_timer_start(uint64_t interval);
/**@brief Stops hardware timer.
*/
void hal_timer_stop(void);
/**@brief Reads microseconds passed since the device start.
*
* @return time in microseconds since the device was launched.
*/
uint64_t hal_time_get(void);
/** @} */
#endif /* HAL_TIMER_H_INCLUDED */

View File

@ -0,0 +1,82 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_TIMER_CRITICAL_H_INCLUDED
#define HAL_TIMER_CRITICAL_H_INCLUDED
#include <stdint.h>
#include <stdbool.h>
/**
* @defgroup hal_timer_critical HAL Hardware Critical Timer
* @ingroup hal_15_4
* @{
* @brief Module to declare HAL hardware critical timer interface
*/
/**@brief Prototype for critical timer handler.
*/
typedef void (* hal_timer_critical_handler_t)(void);
/**@brief Starts hardware critical timer.
*
* @param[in] interval_us timer interval for timer start.
* @param[in] handler critical timer event handler.
*/
void hal_timer_critical_start(uint32_t interval_us, hal_timer_critical_handler_t handler);
/**@brief Stops hardware critical timer.
*/
void hal_timer_critical_stop(void);
/**@brief Check if critical timer is currently used.
*
* @retval timer_state true - timer is running now
* false - timer in stop mode
*/
bool is_critical_timer_started(void);
/** @} */
#endif /* HAL_TIMER_CRITICAL_H_INCLUDED */

View File

@ -0,0 +1,103 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_TRACE_INTERFACE_H_INCLUDED
#define HAL_TRACE_INTERFACE_H_INCLUDED
/**
* @defgroup hal_trace_interface HAL Trace Interface
* @ingroup hal_15_4
* @{
* @brief Module to declare HAL Trace Interface
*/
#ifdef CONFIG_TRACE
#include "hal_uart.h"
#define HAL_TRACE_INTERFACE_REUSE(p_uart_desc) hal_trace_reuse(p_uart_desc)
#define HAL_TRACE_INTERFACE_INIT() hal_trace_init()
#define HAL_TRACE_INTERFACE_PUTS(s) hal_trace_puts(s)
#define HAL_TRACE_INTERFACE_FINALIZE() hal_trace_finalize()
/**
* @brief Trace interface initialization
*/
void hal_trace_init(void);
/**
* @brief Initializes trace interface, using already initialized UART.
*
* @param[in] p_uart_desc UART descriptor, which has been already initialized.
*/
void hal_trace_reuse(hal_uart_descriptor_t * p_uart_desc);
/**
* @brief Sends a null-terminated string to the debug interface
*
* @details send debug data using debug interface
*
* @param[in] p_data null-terminated string.
*/
void hal_trace_puts(const char * p_data);
/**
* @brief Finalizes buffered trace data output to UART,
* before commencing non-buffered assertion output
*/
void hal_trace_finalize(void);
#else
/* If debug is disabled, these macros are just a stub.*/
#define HAL_TRACE_INTERFACE_REUSE(p_uart_desc)
#define HAL_TRACE_INTERFACE_INIT()
#define HAL_TRACE_INTERFACE_PUTS(s)
#define HAL_TRACE_INTERFACE_FINALIZE()
#endif // CONFIG_DEBUG
/** @} */
#endif // HAL_TRACE_INTERFACE_H_INCLUDED

View File

@ -0,0 +1,284 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_UART_H_INCLUDED
#define HAL_UART_H_INCLUDED
#include <stdint.h>
#include <stdlib.h>
#include <limits.h>
/** @file
* This file contains declarations of the routines, types and macros to implement the UART protocol.
*
* @defgroup hal_uart HAL UART protocol
* @ingroup hal_15_4
* @{
* @brief Module to declare HAL UART protocol
* @details The UART module implements the standard UART driver API. This includes open/close via hal_uart_open(),
* hal_uart_close(), read/write via hal_uart_read(), hal_uart_write() routines, and hal_uart_puts() for
* sending a null-terminated string in a non-blocking way. The user also can get some info about the available
* bytes for read/write via hal_uart_read_buffer_size_get() and hal_uart_write_buffer_size_get(). This implies
* that the user may register read/write buffers to use for buffered input/output and handler routines that
* will be called upon read/written characters. Also the most popular settings of the UART driver are supported:
* different baudrates, parity checks, flow control, character size, and stop bits.
*/
/** @brief Maximum size in bytes of input and output buffers. */
#define MAX_QUEUE_LENGTH 0xffffu
/** @brief Maximum size in bytes of data can be stored in hardware unit output buffer. */
#define MAX_TX_CHUNK_SIZE UCHAR_MAX
/** @brief UART baudrate. */
typedef enum
{
HAL_UART_BAUDRATE_38400, /**< 38400 bits per second.*/
HAL_UART_BAUDRATE_115200, /**< 115200 bits per second.*/
HAL_UART_BAUDRATE_230400 /**< 230400 bits per second.*/
} hal_uart_baudrate_t;
/** @brief UART parity check. */
typedef enum
{
HAL_UART_PARITY_NONE, /**< Do not check parity.*/
HAL_UART_PARITY_EVEN /**< Check even parity.*/
} hal_uart_parity_t;
/** @brief UART flow control. */
typedef enum
{
HAL_UART_FLOW_CONTROL_DISABLED, /**< Flow control is disabled.*/
HAL_UART_FLOW_CONTROL_ENABLED, /**< Flow control is enabled.*/
} hal_uart_flow_control_t;
/** @brief UART character size settings. */
typedef enum
{
HAL_UART_FIVE_BITS_CHAR = 5, /**< 5 bits character.*/
HAL_UART_SIX_BITS_CHAR, /**< 6 bits character.*/
HAL_UART_SEVEN_BITS_CHAR, /**< 7 bits character.*/
HAL_UART_EIGHT_BITS_CHAR, /**< 8 bits character.*/
} hal_uart_char_size_t;
/** @brief UART stop bits settings. */
typedef enum
{
HAL_UART_ONE_STOP_BIT, /**< 1 stop bit.*/
HAL_UART_ONEHALF_STOP_BITS, /**< 1.5 stop bits.*/
HAL_UART_TWO_STOP_BITS, /**< 2 stop bits.*/
} hal_uart_stop_bits_t;
/** @brief Represents error source for the UART driver. There might be other values,
* representing clearer elaborating of error statuses, if this module is used
* with Windows or Linux.
*/
typedef enum
{
HAL_UART_ERROR_NONE = 0, /**< Success.*/
HAL_UART_ERROR_TX_OVERFLOW = 252, /**< This error happens when amount of elements in
the transmitter ring buffer exceeds its size.
All the data above limit is not placed into
buffer.*/
HAL_UART_ERROR_RX_OVERFLOW = 253, /**< This error happens when amount of elements in
the receiver ring buffer exceeds its size.
All the unread data is overwritten with new
received data.*/
HAL_UART_ERROR_RX_UNDERFLOW = 254, /**< This error happens when the user-side software
tries to read more elements than it is available
in the receive buffer.
The user-side buffer will be filled with all available
characters and then the error handler is started.*/
HAL_UART_ERROR_HW_ERROR = 255, /**< There is some unrecoverable error in hardware.*/
} hal_uart_error_t;
/**
* @brief User-side handler of UART read and write events.
*
* @param[in] channel event channel number.
* @param[in] char_count number of characters successfully sent before entering
* the callback function.
*/
typedef void (*hal_uart_handler_t)(uint32_t channel, size_t char_count);
/**
* @brief User-side handler for UART error events.
*
* @param[in] channel event channel number.
* @param[in] error_id call reason.
*/
typedef void (*hal_uart_error_handler_t)(uint32_t channel, hal_uart_error_t error_id);
/** @brief HAL UART configuration structure.
*/
typedef struct
{
uint32_t module; /**< UART module number. By now zero
is the only option.*/
uint32_t tx_pin; /**< Number of pin used as TX.*/
uint32_t rx_pin; /**< Number of pin used as RX.*/
uint32_t cts_pin; /**< Number of pin used as CTS.*/
uint32_t rts_pin; /**< Number of pin used as RTS.*/
hal_uart_baudrate_t baudrate; /**< Baudrate selector.*/
hal_uart_parity_t parity; /**< Parity selector.*/
hal_uart_flow_control_t flow_control; /**< Flow control selector.*/
hal_uart_char_size_t char_size; /**< Size of char in bits.*/
hal_uart_stop_bits_t stop_bits; /**< Stop bits number.*/
} hal_uart_config_t;
/**
* @brief This structure defines the UART module operation.
*
* If \a write_buffer_ptr is defined as NULL, then sending data will work
* in blocking way, that is call for \a hal_uart_write will be completed
* only after sending of the last byte passed as input parameter.
*
* If \a read_buffer_ptr is defined as NULL, then driver will drop every
* received byte.
*/
typedef struct
{
hal_uart_config_t uart_config; /**< UART settings struct.*/
hal_uart_handler_t write_handler; /**< Callback function for write operation.*/
void * write_buffer_ptr; /**< User-side buffer for write operation.*/
size_t write_buffer_size; /**< Size of write operation buffer.*/
hal_uart_handler_t read_handler; /**< Callback function for read operation.*/
void * read_buffer_ptr; /**< User-side buffer for read operation.*/
size_t read_buffer_size; /**< Size of read operation buffer.*/
hal_uart_error_handler_t error_handler; /**< Callback function in case of something
goes wrong.*/
} hal_uart_descriptor_t;
/**
* @brief Configures UART interface using input parameter.
*
* @param[in] config pointer to a config struct.
* @param[in] descriptor pointer to a descriptor struct.
*
* @return Return status of operation.
*/
hal_uart_error_t hal_uart_open(const hal_uart_config_t * config,
const hal_uart_descriptor_t * descriptor);
/**
* @brief Sends data in a non-blocking way.
*
* @param[in] descriptor pointer to the UART module operation structure.
* @param[in] data pointer to the user-side buffer of output data.
* @param[in] length number of bytes to transmit.
*
* If descriptor has a non-null \a write_buffer_ptr then this function will use it
* as a temporary buffer and will copy input \a data to it before starting
* transmit. If descriptor has the NULL \a write_buffer_ptr, then the user-side code
* is responsible to retain \a data until \a write_handler is called.
*/
void hal_uart_write(const hal_uart_descriptor_t * descriptor,
const uint8_t * data,
const size_t length);
/**
* @brief Sends a null-terminated C-string in a non-blocking way.
*
* @param[in] descriptor pointer to the UART module operation structure.
* @param[in] s null-terminated string to send.
*/
void hal_uart_puts(const hal_uart_descriptor_t * descriptor, const char * s);
/**
* @brief Receives data in a non-blocking way.
*
* @param[in] descriptor pointer to the UART module operation structure.
* @param[out] data pointer to the user-side buffer used to receive data.
* @param[in] length number of bytes to receive.
*
* If descriptor has a non-null \a read_buffer_ptr, then this function is used to
* copy input characters from it to \a data.
* If \a read_buffer_ptr is NULL, then this function ignores all inputs.
*/
void hal_uart_read(const hal_uart_descriptor_t * descriptor,
uint8_t * data,
const size_t length);
/**
* @brief Returns number of bytes available to read from the income buffer of the
* driver.
*
* @param[in] descriptor pointer to driver structure.
*
* @return Number of bytes available to read.
*/
size_t hal_uart_read_buffer_size_get(const hal_uart_descriptor_t * descriptor);
/**
* @brief Returns number of bytes available to write to the outgoing buffer of the
* driver.
*
* @param[in] descriptor pointer to driver structure.
*
* @return Number of bytes available to write.
*/
size_t hal_uart_write_buffer_size_get(const hal_uart_descriptor_t * descriptor);
/**
* @brief This function deallocates resources previously allocated by hal_uart_open.
*
* @param[in] descriptor pointer to driver structure.
*
* @return Return status of operation.
*/
hal_uart_error_t hal_uart_close(const hal_uart_descriptor_t * descriptor);
#if defined(CONFIG_TRACE) && defined(CONFIG_DEBUG)
/**
* @brief Finalizes remaining trace data output to UART.
*
* @details This debugging feature is needed to finalize buffered trace output
* to UART before commencing non-buffered assertion output.
*/
void hal_uart_trace_finalize(void);
#endif
/** @} */
#endif /* HAL_UART_H_INCLUDED */

View File

@ -0,0 +1,105 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_UART_TASK_SCHEDULER_H_INCLUDED
#define HAL_UART_TASK_SCHEDULER_H_INCLUDED
#include <stdint.h>
#include "hal_atomic.h"
#include "hal_task_scheduler.h"
#include "sys_utils.h"
/**
* @defgroup hal_uart_task_scheduler HAL UART Task Scheduler
* @ingroup hal_15_4
* @{
* @brief Module to declare HAL UART Task Scheduler interface
*/
/**@brief Identifiers for registered UART event handlers.
*
* @details enumeration with identifiers of registered UART event handlers.
* UART handlers will be called from the HAL_UART task. */
typedef enum
{
HAL_UART_RX_TASK_ID,
HAL_UART_TX_TASK_ID,
HAL_UART_ERROR_TASK_ID,
HAL_UART_TASKS_AMOUNT,
} hal_uart_task_id_t;
/**@brief Prototype of a UART task handler.
*
* @details Handler which will be called from HAL_UART task. */
typedef void (* hal_uart_task_handler_t)(uint32_t channel);
void hal_uart_rx_handler(uint32_t channel);
void hal_uart_tx_handler(uint32_t channel);
void hal_uart_error_handler(uint32_t channel);
/**@brief UART channels.
*
* @details Array which includes event id for every channel it happened. */
extern volatile uint16_t g_hal_uart_modules_tasks[CONFIG_HAL_UART_CHANNELS];
/**@brief Notifies HAL task scheduler to add an UART task for execution.
*
* @details The function sets a marker for the UART event task for execution.
* And sets this marker for a channel where event happened.
*
* @param[in] channel event channel.
* @param[in] hal_uart_task_id HAL task identificator. */
static inline void hal_uart_task_post(uint32_t channel,
uint8_t hal_uart_task_id)
{
atomic_t atomic = 0;
hal_atomic_start(&atomic);
g_hal_uart_modules_tasks[channel] |= BIT(hal_uart_task_id);
hal_atomic_end(&atomic);
hal_task_post(HAL_UART_TASK_ID);
}
/** @} */
#endif /* HAL_UART_TASK_SCHEDULER_H_INCLUDED */

View File

@ -0,0 +1,90 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_EXCEPTIONS_H_INCLUDED
#define HAL_EXCEPTIONS_H_INCLUDED
#include <stdint.h>
/**
* @defgroup hal_15_4_nrf52 Chip-specific library interface
* @ingroup hal_15_4
*
* @defgroup hal_nrf52_exceptions HAL exceptions
* @ingroup hal_15_4_nrf52
* @{
*/
/** @brief Size of stack dump in 4-byte words.*/
#define HAL_EXCEPTIONS_DUMP_SIZE 16
/** @brief Defines where to put a '\n' in stack dump.
*
* This value defines power of 2 items in one row.
* E.g. 3 gives 2 ^ 3 = 8 items in a row.*/
#define HAL_EXCEPTIONS_ITEMS_IN_LINE 3
/** @brief This structure holds values of fault status registers.*/
typedef struct
{
uint32_t CFSR; /*!< Configurable Fault Status Register.*/
uint32_t HFSR; /*!< HardFault Status Register.*/
uint32_t DFSR; /*!< Debug Fault Status Register.*/
uint32_t AFSR; /*!< Auxiliary Fault Status Register.*/
} hal_exceptions_status_registers_t;
/** @brief This structure is put into dump monitor port and holds values of said
* registers when exception has happen.*/
typedef struct
{
uint32_t R0; /**< Register R0 (Argument 1 / word result).*/
uint32_t R1; /**< Register R1 (Argument 2 / double-word result).*/
uint32_t R2; /**< Register R2 (Argument 3).*/
uint32_t R3; /**< Register R3 (Argument 4).*/
uint32_t R12; /**< Register R12 (Scratch register (corruptible)).*/
uint32_t LR; /**< Link register (R14).*/
uint32_t PC; /**< Program counter (R15).*/
uint32_t PSR; /**< Combined processor status register.*/
uint32_t* FP; /**< Value of register, which may be used as Frame Pointer.*/
} hal_exceptions_dump_t;
/** @} */
#endif // HAL_EXCEPTIONS_H_INCLUDED

View File

@ -0,0 +1,107 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_NRF52_RTC_H_INCLUDED
#define HAL_NRF52_RTC_H_INCLUDED
#include "nordic_common.h"
#include "nrf_drv_config.h"
#include "nrf_drv_common.h"
#include "nrf_drv_rtc.h"
#include "nrf_rtc.h"
/**
* @defgroup hal_nrf52_rtc HAL RTC
* @ingroup hal_15_4_nrf52
* @{
*/
// RTC counter bitlenght
#define LAGEST_PRESCALER_VALUE 4096
// RTC counter bitlenght
#define RTC_CNT_BITLENGHT 24
// Longest sleep time, ms
#define LONGEST_SLEEP_TIME ((( 1UL << RTC_CNT_BITLENGHT ) \
/(RTC_INPUT_FREQ/LAGEST_PRESCALER_VALUE)) * 1000UL )
// Shortest sleep time, ms
#define SHORTEST_SLEEP_TIME 1
/**@brief Function for initialize low frequency clock
*/
void rtc_lfclk_start(void);
/** @brief Function initialization and configuration of RTC driver instance.
*
* @param[in] sleep_time_ms after this time compare event will be triggered
*/
void rtc_start(uint32_t sleep_time_ms);
/** @brief Stop RTC
*/
void rtc_stop(void);
/** @brief Get RTC counter
*
* @retval uint32_t Contents of RTC counter register.
*/
uint32_t rtc_cnt_get(void);
/** @brief Get time elapsed since cnt_ticks
*
* @param[in] cnt_ticks Number of rtc-ticks
*
* @retval uint32_t Time since cnt_ticks, ms
*/
uint64_t get_rtc_time_since(uint32_t cnt_ticks);
/** @brief Check if rtc compare interrupt was triggered after calling
* rtc_start function
*
* @retval bool true - compare interrupt was triggered
* false - it wasn't
*/
bool is_rtc_comp_irq_triggerd(void);
/** @} */
#endif /* HAL_NRF52_RTC_H_INCLUDED */

View File

@ -0,0 +1,75 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef HAL_NRF52_TIMER_INCLUDED
#define HAL_NRF52_TIMER_INCLUDED
/**
* @defgroup hal_nrf52_timer HAL timer - additional features
* @ingroup hal_15_4_nrf52
* @{
*/
/**@brief Pause hardware timer.
*/
void hal_timer_pause(void);
/**@brief Resume hardware timer.
*/
void hal_timer_resume(void);
/**@brief Set a new system time
*
* @param[in] time_us time to set.
*/
void hal_time_adjust(uint64_t time_us);
/**@brief Uninit hardwware timer
*/
void hal_timer_uninit(void);
/** @} */
#endif /* HAL_NRF52_TIMER_INCLUDED */

View File

@ -0,0 +1,61 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_AUTO_REQUEST_H_INCLUDED
#define MAC_AUTO_REQUEST_H_INCLUDED
/** @file
*
* @defgroup mac_auto_request MAC auto request
* @ingroup mac_15_4
* @{
*/
/**
* @brief This function is called when a new beacon has been sent.
*
* @param[in] p_ind - Pointer to beacon indication structure.
*/
void mac_auto_request_notify_ind(mac_beacon_ind_t * p_ind);
/** @} */
#endif /* MAC_AUTO_REQUEST_H_INCLUDED_ */

View File

@ -0,0 +1,467 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_COMMON_H_INCLUDED
#define MAC_COMMON_H_INCLUDED
#include <stdint.h>
#include "phy_common.h"
#if (CONFIG_SECURE == 1)
#include "mac_security.h"
#endif
/** @file
* Types and declarations common for different MLME transactions listed here.
*
* @defgroup mac_common MAC Common API
* @ingroup mac_15_4
* @{
* @brief Module for declaring MAC Common API.
* @details The Common MAC module contains declarations of commonly used MAC routines and necessary
* macros and types.
*/
/**@brief Maximum interval for acknowledgement frame to arrive in microseconds.
*
* macAckWaitDuration = aUnitBackoffPeriod(only for beacon enabled PAN) +
* aTurnaroundTime +
* phySHRDuration + ceil(6 * phySymbolsPerOctet) =
* 20 + 12 + 10 + 6 * 2 =
* 54 symbols / 62.5 ksymbols/s = 864 us (544 us for beacon disabled PAN)
*/
#if (CONFIG_BEACON_ENABLED == 1)
#define macAckWaitDuration 864
#else
#define macAckWaitDuration 544
#endif
/**@brief The maximum number of octets added by the MAC
* sublayer to the MAC payload of a beacon frame.
*/
#define aMaxBeaconOverhead 75
/**@brief The number of symbols forming the basic time period
* used by the CSMA-CA algorithm.
*/
#define aUnitBackoffPeriod 20UL
/**@brief The number of symbols forming a superframe slot
* when the superframe order is equal to 0.
*/
#define aBaseSlotDuration 60UL
/**@brief The number of slots contained in any superframe. */
#define aNumSuperframeSlots 16UL
/**@brief The number of symbols forming a superframe when
* the superframe order is equal to 0.
*/
#define aBaseSuperframeDuration (aBaseSlotDuration * aNumSuperframeSlots)
/**@brief The maximum size, in octets, of a beacon payload. */
#define aMaxBeaconPayloadLength (aMaxPHYPacketSize - aMaxBeaconOverhead)
/**@brief The maximum number of octets added by the MAC
* sublayer to the PSDU without security.
*/
#define aMaxMPDUUnsecuredOverhead 25
/**@brief The maximum number of octets that can be transmitted in the MAC Payload
* field of an unsecured MAC frame that will be guaranteed not to exceed aMaxPHYPacketSize.
*/
#define aMaxMACSafePayloadSize (aMaxPHYPacketSize - aMaxMPDUUnsecuredOverhead)
/**@brief The minimum number of octets added by the MAC sublayer to the PSDU.*/
#define aMinMPDUOverhead 9
/**@brief The maximum number of octets that can be transmitted in the MAC
* Payload field.
*/
#define aMaxMACPayloadSize (aMaxPHYPacketSize - aMinMPDUOverhead)
/**@brief The maximum size of an MPDU, in octets, that can be followed by a SIFS period. */
#define aMaxSIFSFrameSize 18
/**@brief The minimum number of symbols forming the CAP.
*
* @details This ensures that MAC commands can still be transferred to devices
* when GTSs are being used.
*/
#define aMinCAPLength 440
/**@brief The number of superframes in which a GTS descriptor exists
* in the beacon frame of the PAN coordinator.
*/
#define aGTSDescPersistenceTime 4
/**@brief The number of consecutive lost beacons that will cause the MAC sublayer
* of a receiving device to declare a loss of synchronization.
*/
#define aMaxLostBeacons 4
/**@brief Maximum number of battery life extension periods. */
#define MAC_MIN_BATT_LIFE_EXT_PERIODS 6
/**@brief Minimum number of battery life extension periods. */
#define MAC_MAX_BATT_LIFE_EXT_PERIODS 41
/**@brief Minimum value for macBeaconOrder parameter. */
#define MAC_MIN_BEACON_ORDER 0
/**@brief Maximum value for macBeaconOrder parameter. */
#define MAC_MAX_BEACON_ORDER 15
/**@brief Minimum value for macMaxCSMABackoffs parameter. */
#define MAC_MIN_MAX_CSMA_BACKOFFS 0
/**@brief Maximum value for macMaxCSMABackoffs parameter. */
#define MAC_MAX_MAX_CSMA_BACKOFFS 5
/**@brief Minimum value for macMinBE parameter. */
#define MAC_MIN_MIN_BE 0
/**@brief Minimum value for macMaxBE parameter. */
#define MAC_MIN_MAX_BE 3
/**@brief Maximum value for macMaxBE parameter. */
#define MAC_MAX_MAX_BE 8
/**@brief Minimum value for macSuperframeOrder parameter. */
#define MAC_MIN_SUPERFRAME_ORDER 0
/**@brief Maximum value for macSuperframeOrder parameter. */
#define MAC_MAX_SUPERFRAME_ORDER 15
/**@brief Minimum value for macMaxFrameRetries parameter. */
#define MAC_MIN_MAX_FRAME_RETRIES 0
/**@brief Maximum value for macMaxFrameRetries parameter. */
#define MAC_MAX_MAX_FRAME_RETRIES 7
/**@brief Minimum value for macResponseWaitTime parameter. */
#define MAC_MIN_RESPONSE_WAIT_TIME 2
/**@brief Maximum value for macResponseWaitTime parameter. */
#define MAC_MAX_RESPONSE_WAIT_TIME 64
/**@brief A handy macro for a never initialized short address. */
#define MAC_SHORT_ADDRESS_NOT_SET 0xFFFF
/**@brief A handy macro for a never initialized short address. */
#define MAC_EXTENDED_ADDRESS_NOT_SET 0xFFFFFFFFFFFFFFFFULL
/**@brief A value of MAC beacon order attribute which determines
* a state with no periodic beacons.
*/
#define MAC_NO_BEACONS 15
/**@brief A handy macro for broadcast address. */
#define MAC_BROADCAST_SHORT_ADDRESS 0xFFFF
/**@brief A handy macro for unknown PAN ID. */
#define MAC_BROADCAST_PANID 0xFFFF
/**@brief Short address field value that is used when the device does not
* support short addressing mode.
*/
#define MAC_EXTENDED_ADDRESS_ONLY 0xFFFE
/**@brief Final CAP slot field value in the beacon for non-beacon enabled PAN. */
#define MAC_FINAL_CAP_SLOT_NBPAN 15
/**@brief Total amount of slots available in beacon enabled PAN. */
#define MAC_SLOT_AMOUNT 16
/**@brief This is the value of auto request key index until it has been set. */
#define MAC_SECURITY_KEY_INDEX_NOT_SET 0xFF
/**@brief Length of short MAC address in bytes. */
#define MAC_ADDR_SHORT_LEN 2
/**@brief Length of extended MAC address in bytes. */
#define MAC_ADDR_EXTENDED_LEN 8
/**@brief Length of PAN ID field in bytes. */
#define MAC_PAN_ID_LEN 2
/**@brief MAC footer (FCS) size. */
#define MAC_MFR_SIZE 2
/**@brief Maximum auxiliary header length */
#if (CONFIG_SECURE == 1)
#define MAC_MAX_AUX_HEADER_SIZE 14
#else
#define MAC_MAX_AUX_HEADER_SIZE 0
#endif
/**@brief Maximum MAC header length */
#define MAC_MAX_MHR_SIZE (PHY_MAX_HEADER_SIZE + \
2 /* Frame control */ + \
1 /* Data sequence number */ + \
2 * (sizeof(uint16_t) + (sizeof(uint64_t))) /* Two PAN IDs and extended addresses */ + \
MAC_MAX_AUX_HEADER_SIZE)
/**@brief Maximum MAC header length for beacon frame */
#define MAC_MAX_BCN_MHR_SIZE (PHY_MAX_HEADER_SIZE + \
2 /* Frame control field */ + \
1 /* Beacon sequence number */ + \
sizeof(uint16_t) /* PAN ID */ + \
sizeof(uint64_t) /* Extended address */ + \
MAC_MAX_AUX_HEADER_SIZE)
/**@brief Memory which should be reserved for MAC fields */
#if (CONFIG_SECURE == 1)
#define MAC_MEMORY_RESERVE (MAC_MAX_MHR_SIZE + MAX_MIC_SIZE + MAC_MFR_SIZE)
#else
#define MAC_MEMORY_RESERVE (MAC_MAX_MHR_SIZE + MAC_MFR_SIZE)
#endif
/**@brief Offset of MAC payload in the frame buffer */
#define MAC_MAX_MSDU_OFFSET MAC_MAX_MHR_SIZE
/**@brief Possible MAC frame types. */
typedef enum
{
MAC_BEACON, /**< Frame is a beacon. */
MAC_DATA, /**< Frame is a data frame. */
MAC_ACK, /**< Frame is a MAC ACKnowledgement. */
MAC_COMMAND /**< Frame is a MAC command. */
} mac_frame_type_t;
/**@brief MAC ADDRESS. */
typedef union
{
uint16_t short_address; /**< 16-bit short address. */
uint64_t long_address; /**< 64-bit long address. */
} mac_addr_t;
/**@brief MAC ADDR MODE. */
typedef enum
{
MAC_ADDR_NONE = 0, /**< NO address is used. */
MAC_ADDR_SHORT = 2, /**< Short address is used. */
MAC_ADDR_LONG = 3 /**< Long address is used. */
} mac_addr_mode_t;
typedef enum
{
MAC_FRAME_VERSION_2003, /**< IEEE 802.15.4-2003 compliant. */
MAC_FRAME_VERSION_2006 /**< IEEE 802.15.4-2006 compliant. */
} mac_frame_version_t;
/**
* @brief MAC status
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.17
* excluding:
* MAC_IS_NOT_AVAILABLE
* This status is necessary for synchronous API.
*/
typedef enum
{
MAC_SUCCESS = 0x00, /* 0 */ /**< Operation is successful. */
MAC_COUNTER_ERROR = 0xDB, /* 219 */ /**< The frame counter purportedly applied
by the originator of the received
frame is invalid. */
MAC_IMPROPER_KEY_TYPE = 0xDC, /* 220 */ /**< The key purportedly applied by the
originator of the received frame is
not allowed to be used with that
frame type according to the key usage
policy of the recipient. */
MAC_IMPROPER_SECURITY_LEVEL = 0xDD, /* 221 */ /**< The security level purportedly applied
by the originator of the received
frame does not meet the minimum
security level required/expected by
the recipient for that frame type. */
MAC_UNSUPPORTED_LEGACY = 0xDE, /* 222 */ /**< The received frame was purportedly
secured using security based on IEEE
Std 802.15.4-2003, and such security
is not supported by this standard. */
MAC_UNSUPPORTED_SECURITY = 0xDF, /* 223 */ /**< The security purportedly applied by
the originator of the received frame
is not supported. */
MAC_BEACON_LOSS = 0xE0, /* 224 */ /**< The beacon was lost following a
synchronization request. */
MAC_CHANNEL_ACCESS_FAILURE = 0xE1, /* 225 */ /**< A transmission could not take place
due to activity on the channel, i.e.
the CSMA-CA mechanism has failed. */
MAC_DENIED = 0xE2, /* 226 */ /**< The GTS request has been denied by
the PAN coordinator. */
MAC_DISABLE_TRX_FAILURE = 0xE3, /* 227 */ /**< The attempt to disable the
transceiver has failed. */
MAC_SECURITY_ERROR = 0xE4, /* 228 */ /**< Cryptographic processing of the
received secured frame failed. */
MAC_FRAME_TOO_LONG = 0xE5, /* 229 */ /**< Either a frame resulting from
processing has a length that is
greater than aMaxPHYPacketSize or
a requested transaction is too large
to fit in the CAP or GTS. */
MAC_INVALID_GTS = 0xE6, /* 230 */ /**< The requested GTS transmission failed
because the specified GTS either did
not have a transmit GTS direction or
was not defined. */
MAC_INVALID_HANDLE = 0xE7, /* 231 */ /**< A request to purge an MSDU from the
transaction queue was made using an
MSDU handle that was not found in
the transaction table. */
MAC_INVALID_PARAMETER = 0xE8, /* 232 */ /**< A parameter in the primitive is
either not supported or is out of
the valid range. */
MAC_NO_ACK = 0xE9, /* 233 */ /**< No acknowledgment was received after
macMaxFrameRetries. */
MAC_NO_BEACON = 0xEA, /* 234 */ /**< A scan operation failed to find any
network beacons. */
MAC_NO_DATA = 0xEB, /* 235 */ /**< No response data was available
following a request. */
MAC_NO_SHORT_ADDRESS = 0xEC, /* 236 */ /**< The operation failed because a 16-bit
short address was not allocated. */
MAC_OUT_OF_CAP = 0xED, /* 237 */ /**< A receiver enable request was
unsuccessful because it could not be
completed within the CAP.
@note The enumeration description is
not used in this standard, and it is
included only to meet the backwards
compatibility requirements for
IEEE Std 802.15.4-2003. */
MAC_PAN_ID_CONFLICT = 0xEE, /* 238 */ /**< A PAN identifier conflict has been
detected and communicated to the PAN
coordinator. */
MAC_REALIGNMENT = 0xEF, /* 239 */ /**< A coordinator realignment command has
been received. */
MAC_TRANSACTION_EXPIRED = 0xF0, /* 240 */ /**< The transaction has expired and its
information was discarded. */
MAC_TRANSACTION_OVERFLOW = 0xF1, /* 241 */ /**< There is no capacity to store the
transaction. */
MAC_TX_ACTIVE = 0xF2, /* 242 */ /**< The transceiver was in the transmitter
enabled state when the receiver was
requested to be enabled.
@note The enumeration description is
not used in this standard, and it is
included only to meet the backwards
compatibility requirements for
IEEE Std 802.15.4-2003. */
MAC_UNAVAILABLE_KEY = 0xF3, /* 243 */ /**< The key purportedly used by the
originator of the received frame is
not available or, if available, the
originating device is not known or is
blacklisted with that particular
key. */
MAC_UNSUPPORTED_ATTRIBUTE = 0xF4, /* 244 */ /**< A SET/GET request was issued with the
identifier of a PIB attribute that is
not supported. */
MAC_INVALID_ADDRESS = 0xF5, /* 245 */ /**< A request to send data was
unsuccessful because neither the source
address parameters nor the destination
address parameters were present. */
MAC_ON_TIME_TOO_LONG = 0xF6, /* 246 */ /**< A receiver enable request was
unsuccessful because it specified a
number of symbols that was longer than
the beacon interval. */
MAC_PAST_TIME = 0xF7, /* 247 */ /**< A receiver enable request was
unsuccessful because it could not be
completed within the current superframe
and was not permitted to be deferred
until the next superframe. */
MAC_TRACKING_OFF = 0xF8, /* 248 */ /**< The device was instructed to start
sending beacons based on the timing
of the beacon transmissions of its
coordinator, but the device is not
currently tracking the beacon of its
coordinator. */
MAC_INVALID_INDEX = 0xF9, /* 249 */ /**< An attempt to write to a MAC PIB
attribute that is in a table failed
because the specified table index
was out of range. */
MAC_LIMIT_REACHED = 0xFA, /* 250 */ /**< A scan operation terminated
prematurely because the number of
PAN descriptors stored reached an
implementation specified maximum. */
MAC_READ_ONLY = 0xFB, /* 251 */ /**< A SET/GET request was issued with the
identifier of an attribute that is
read only. */
MAC_SCAN_IN_PROGRESS = 0xFC, /* 252 */ /**< A request to perform a scan operation
failed because the MLME was in the
process of performing a previously
initiated scan operation. */
MAC_SUPERFRAME_OVERLAP = 0xFD, /* 253 */ /**< The device was instructed to start
sending beacons based on the timing
of the beacon transmissions of its
coordinator, but the instructed start
time overlapped the transmission time
of the beacon of its coordinator. */
/* Statuses out from standard. It is used for synchronous API */
MAC_IS_NOT_AVAILABLE = 0xFF /* 255 */ /**< MAC is not available. */
} mac_status_t;
/**
* @brief Payload descriptor.
*
* @details Not covered by the standard.
* Contains information sufficient to allow the next higher layer to clean
* the memory allocated for incoming frames.
*/
typedef struct
{
/**
* Pointer to the set of octets forming the frame payload being indicated by
* the MAC sublayer entity.
*/
uint8_t * p_payload;
/**
* Offset of the payload data relative to the beginning of the frame.
* Equal to the MAC header.
*/
uint8_t payload_offset;
} mac_payload_descriptor_t;
/** @brief Command frame IDs defined by the MAC sublayer that are listed
* in Table 82 of the standard.
*/
typedef enum
{
MAC_CMD_ASSOC_REQ = 0x01, /**< Association request.*/
MAC_CMD_ASSOC_RESP = 0x02, /**< Association response.*/
MAC_CMD_DISASSOC_NTF = 0x03, /**< Disassociation notification.*/
MAC_CMD_DATA_REQ = 0x04, /**< Data request.*/
MAC_CMD_PANID_CONFLICT_NTF = 0x05, /**< PAN ID conflict notification.*/
MAC_CMD_ORPHAN_NTF = 0x06, /**< Orphan notification.*/
MAC_CMD_BEACON_REQ = 0x07, /**< Beacon request.*/
MAC_CMD_COORD_REALIGN = 0x08, /**< Coordinator realignment.*/
MAC_CMD_GTS_REQ = 0x09 /**< GTS request.*/
} mac_command_id_t;
/** @} */
#endif // MAC_COMMON_H_INCLUDED

View File

@ -0,0 +1,333 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_MCPS_DATA_H_INCLUDED
#define MAC_MCPS_DATA_H_INCLUDED
#include <stdint.h>
#include "mac_common.h"
#include "mac_task_scheduler.h"
/** @file
* The MAC Data module declares the MAC Data transmittion routines and necessary types
* according to the MAC specification.
*
* @defgroup mac_data MAC MCPS Data API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC MCPS Data API.
* @details The MAC MCPS Data module declares the MAC Data transmission routines and necessary types according
* to the MAC specification. More specifically, MAC data request mcps_data_req(), and MAC Data
* indication mcps_data_ind() primitives are declared. The confirmation callback typedef is
* declared as mcps_data_conf_cb_t.
*/
/**
* @brief TX options bit fields.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.1.1.
*/
#define TX_ACKNOWLEDGED_BIT (0)
#define TX_GTS_BIT (1)
#define TX_INDIRECT_BIT (2)
/**
* @brief TX options for MAC data transmission.
*
* @details The three bits (b0, b1, b2) indicate the transmission options for this MSDU.
* For b0, 1 = acknowledged transmission, 0 = unacknowledged transmission.
* For b1, 1 = GTS transmission, 0 = CAP transmission for a beacon-enabled PAN.
* For b2, 1 = indirect transmission, 0 = direct transmission.
* For a nonbeacon-enabled PAN, bit b1 should always be set to 0.
*/
typedef struct
{
uint8_t ack : 1;
uint8_t gts : 1;
uint8_t indirect : 1;
uint8_t : 5;
} mac_tx_options_t;
/**
* @brief MCPS-DATA.confirm.
*
* @details The MCPS-DATA.confirm primitive reports the results of a request to transfer
* a data SPDU (MSDU) from a local SSCS entity to a single peer SSCS entity.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.1.2.
*/
typedef struct
{
/** The handle associated with the MSDU being confirmed. */
uint8_t msdu_handle;
/** The status of the last MSDU transmission. */
mac_status_t status;
/**
* Optional. The time, in symbols, at which the data was transmitted (see 7.5.4.1).
*
* The value of this parameter will be considered valid only if the value of the
* status parameter is SUCCESS; if the status parameter is not equal to
* SUCCESS, the value of the Timestamp parameter will not be used for any other
* purpose. The symbol boundary is described by macSyncSymbolOffset (see Table 86 in 7.4.1).
*
* This is a 24-bit value, and the precision of this value will be a minimum of 20 bits,
* with the lowest 4 bits being the least significant.
*/
uint32_t timestamp;
} mcps_data_conf_t;
/**
* @brief MCPS-DATA.request.
*
* @details The MCPS-DATA.request primitive requests the transfer of
* a data SPDU (i.e., MSDU) from a local SSCS entity to a single peer SSCS entity.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.1.1.
*/
typedef struct
{
/** Do not edit this field. */
mac_abstract_req_t service;
/** Confirm to this request. */
mcps_data_conf_t confirm;
/**
* The source addressing mode for this primitive and
* subsequent MPDU. This value can take one of the following values:
* @ref mac_addr_mode_t
* 0x00 = no address (addressing fields omitted, see 7.2.1.1.8).
* 0x01 = reserved.
* 0x02 = 16-bit short address.
* 0x03 = 64-bit extended address.
*/
mac_addr_mode_t src_addr_mode;
/**
* The destination addressing mode for this primitive
* and subsequent MPDU.
* According to 7.1.1.1.1, Table 41.
*/
mac_addr_mode_t dst_addr_mode;
/** The 16-bit PAN identifier of the entity to which the MSDU is being transferred. */
uint16_t dst_pan_id;
/** The individual device address of the entity to which the MSDU is being transferred. */
mac_addr_t dst_addr;
/** The number of octets contained in the MSDU to be transmitted by
* the MAC sublayer entity.
*/
uint8_t msdu_length;
/**
* The pointer to the set of octets forming the MSDU
* to be transmitted by the MAC sublayer entity.
*
* Caller must provide enough space for MAC and PHY header before this pointer.
*/
uint8_t * msdu;
/** The handle associated with the MSDU to be transmitted by the MAC sublayer entity. */
uint8_t msdu_handle;
/**
* The bits (b0, b1, b2) indicate the transmission options for this MSDU.
* For b0, 1 = acknowledged transmission, 0 = unacknowledged transmission.
* For b1, 1 = GTS transmission, 0 = CAP transmission for a beacon-enabled PAN.
* For b2, 1 = indirect transmission, 0 = direct transmission.
* For a nonbeacon-enabled PAN, bit b1 should always be set to 0.
*/
mac_tx_options_t tx_options;
#if (CONFIG_SECURE == 1)
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID node. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mcps_data_req_t;
/**
* @brief Private information passed with MCPS-DATA.indication.
* Not covered by the standard.
*/
typedef struct
{
/** RSSI value, which corresponds to packet that caused this indication. */
int8_t rssi;
/** Value of a pending bit from MHR. */
uint8_t pending_bit;
} mcps_data_ind_private_t;
/**
* @brief MCPS-DATA.indication
*
* @details The MCPS-DATA.indication primitive indicates the transfer of
* a data SPDU (i.e., MSDU) from the MAC sublayer to the local SSCS entity.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.1.3
*/
typedef struct
{
mcps_data_ind_private_t service;
/**
* The source addressing mode for this primitive corresponding to the received MPDU.
* According to 7.1.1.1.1, Table 43.
*/
mac_addr_mode_t src_addr_mode;
/** The 16-bit PAN identifier of the entity from which the MSDU was received. */
uint16_t src_pan_id;
/** The individual device address of the entity from which the MSDU was received. */
mac_addr_t src_addr;
/**
* The destination addressing mode for this primitive corresponding to the received MPDU.
* According to 7.1.1.1.1, Table 43.
*/
mac_addr_mode_t dst_addr_mode;
/** The 16-bit PAN identifier of the entity to which the MSDU is being transferred. */
uint16_t dst_pan_id;
/** The individual device address of the entity to which the MSDU is being transferred. */
mac_addr_t dst_addr;
/** The number of octets contained in the MSDU being indicated by the MAC sublayer entity. */
uint8_t msdu_length;
/**
* The information that is required for the next higher layer to read incoming message and to
* free the memory allocated for this message.
*/
mac_payload_descriptor_t msdu;
/**
* LQI value measured during reception of the MPDU.
* Lower values represent lower LQI (see 6.9.8).
*/
uint8_t mpdu_link_quality;
/** The DSN of the received data frame. */
uint8_t dsn;
/**
* Optional. The time, in symbols, at which the data was received (see 7.5.4.1).
* The symbol boundary is described by macSyncSymbolOffset (see Table 86 in 7.4.1).
*
* This is a 24-bit value, and the precision of this value shall be a minimum of 20 bits,
* with the lowest 4 bits being the least significant.
*/
uint32_t timestamp;
#if (CONFIG_SECURE == 1)
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID node. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mcps_data_ind_t;
/**
* @brief Confirmation function.
*
* @details The MCPS-DATA.confirm primitive is generated by the MAC sublayer
* entity in response to an MCPS-DATA. request primitive. The MCPS-DATA.confirm
* primitive returns a status of either SUCCESS, indicating that the request to
* transmit was successful, or the appropriate error code.
* The status values are fully described in 7.1.1.1.3 and subclauses referenced by 7.1.1.1.3.
*
* @param Pointer to confirmation primitive.
*/
typedef void (* mcps_data_conf_cb_t)(mcps_data_conf_t *);
/**
* @brief MCPS-DATA.request service
*
* @details The MCPS-DATA.request primitive is generated by a local SSCS entity
* when a data SPDU (i.e., MSDU) is to be transferred to a peer SSCS entity.
* After request completion, user callback will be issued with
* valid data stored in structure @ref mcps_data_conf_t.
*
* @param req Pointer to MCPS-DATA request structure.
* @param conf_cb Pointer to confirmation function (user callback).
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.1.2.
*/
void mcps_data_req(mcps_data_req_t * req, mcps_data_conf_cb_t conf_cb);
/**
* @brief MCPS-DATA.indication handler.
*
* @details The MCPS-DATA.indication primitive is generated by the MAC sublayer and
* issued to the SSCS on receipt of a data frame at the local MAC sublayer entity
* that passes the appropriate message filtering operations as described in 7.5.6.2.
*
* @param ind MCPS-DATA.indication structure.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.1.3.
*/
extern void mcps_data_ind(mcps_data_ind_t * ind);
/**
* @brief Free memory allocated for incoming message.
*
* @details The function will be invoked after all manipulations
* with MSDU are completed. That is necessary to return the memory allocated by MAC
* into the heap.
*
* @param p_payload_descriptor - Pointer to MSDU descriptor.
*/
void mac_mem_msdu_free(mac_payload_descriptor_t * p_payload_descriptor);
/** @} */
#endif // MAC_MCPS_DATA_H_INCLUDED

View File

@ -0,0 +1,152 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_MCPS_PURGE_H_INCLUDED
#define MAC_MCPS_PURGE_H_INCLUDED
#if (CONFIG_PURGE_ENABLED == 1)
#include <stdint.h>
#include "mac_common.h"
#include "mac_task_scheduler.h"
/** @file
* The MAC Purge module declares the MAC Purge routines and necessary types
* according to the MAC specification.
*
* @defgroup mac_purge MAC MCPS Purge API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC MCPS Purge API.
* @details The MAC MCPS Purge module declares the MAC Purge routines and necessary types according to
* the MAC specification. More specifically, MAC purge request mcps_purge_req(), and the
* confirmation callback typedef is declared as mcps_purge_conf_cb_t. An additional primitive
* not covered by the standard is declared. This is mpcs_purge() which is a synchronous version
* of mcps_purge_req().
*/
/**
* @brief MCPS-PURGE.confirm.
*
* @details The MCPS-PURGE.confirm primitive allows the MAC sublayer to notify the next higher layer
* of the success of its request to purge an MSDU from the transaction queue.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.1.5.
*/
typedef struct
{
/** The handle of the MSDU to be purged from the transaction queue. */
uint8_t msdu_handle;
/** The status of the request to be purged an MSDU from the transaction queue. */
mac_status_t status;
} mcps_purge_conf_t;
/**
* @brief MCPS-PURGE.request.
*
* @details The MCPS-PURGE.request primitive allows the next higher layer
* to purge an MSDU from the transaction queue.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.1.4.
*/
typedef struct
{
/** Do not edit this field. */
mac_abstract_req_t service;
/** Confirmation to this request. */
mcps_purge_conf_t confirm;
/** The handle of the MSDU to be purged from the transaction queue. */
uint8_t msdu_handle;
} mcps_purge_req_t;
/**
* @brief Confirmation function.
*
* @details The MCPS-PURGE.confirm primitive is generated by the MAC sublayer
* entity in response to an MCPS-PURGE.request primitive. The MCPS-PURGE.confirm
* primitive returns a status of either SUCCESS, indicating that the purge request
* was successful, or INVALID_HANDLE, indicating an error.
* The status values are fully described in 7.1.1.4.3.
*
* @param Pointer to confirmation primitive.
*/
typedef void (* mcps_purge_conf_cb_t)(mcps_purge_conf_t *);
/**
* @brief MCPS-PURGE.request service.
*
* @details The MCPS-PURGE.request primitive is generated by the next higher layer
* whenever an MSDU is to be purged from the transaction queue.
* After request completion, user callback will be issued with
* valid data stored in structure mcps_purge_conf_t.
*
* @param req Pointer to MCPS-PURGE request structure.
* @param conf_cb Pointer to the confirmation function (user callback).
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.1.4.
*/
void mcps_purge_req(mcps_purge_req_t * req, mcps_purge_conf_cb_t conf_cb);
/**
* @brief Performs MCPS-PURGE.request directly (without request - confirm approach).
*
* @details Optional. Not covered by the standard.
*
* The MCPS-PURGE.request primitive is generated by the next higher layer
* whenever an MSDU is to be purged from the transaction queue.
*
* @param req Pointer to MCPS-PURGE request structure.
*
* @return Result of the purge procedure.
*/
mac_status_t mcps_purge(mcps_purge_req_t * req);
/** @} */
#endif // (CONFIG_PURGE_ENABLED == 1)
#endif // MAC_MCPS_PURGE_H_INCLUDED

View File

@ -0,0 +1,336 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_MLME_ASSOCIATE_H_INCLUDED
#define MAC_MLME_ASSOCIATE_H_INCLUDED
#include <stdint.h>
#include "mac_common.h"
#include "mac_task_scheduler.h"
/** @file
* The MAC Association module declares the MAC Association routines and necessary types/macros
* according to the MAC specification.
*
* @defgroup mac_assoc MAC MLME Association API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC MLME Association API.
* @details The MLME Association module declares Association MAC routines and necessary macros/types according
* to the MAC specification. More specifically, MLME Association request aka mlme_associate_req(),
* MLME Association confirm callback typedef aka mlme_associate_conf_cb_t, MLME Association indication
* as mlme_associate_ind(), and MLME Response aka mlme_associate_resp() primitives are declared.
*/
/**
* @brief Capability information field.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.3.1.2.
*/
#define ALTERNATE_PAN_COORDINATOR_BIT (0)
#define DEVICE_TYPE_BIT (1)
#define POWER_SOURCE_BIT (2)
#define RECEIVER_ON_WHEN_IDLE_BIT (3)
#define SECURITY_CAPABILITY_BIT (6)
#define ALLOCATE_ADDRESS_BIT (7)
/**
* @brief Valid values of the Association Status field
*
* In accordance with IEEE Std 802.15.4-2006, section 7.3.2.3
*/
typedef enum
{
MAC_ASSOCIATION_SUCCESSFUL = 0,
MAC_PAN_AT_CAPACITY,
MAC_PAN_ACCESS_DENIED
} mac_association_status_t;
/**
* @brief Capability information field
*
* In accordance with IEEE Std 802.15.4-2006, section 7.3.1.2.
*/
typedef struct
{
uint8_t alternate_pan_coordinator : 1;
uint8_t device_type : 1;
uint8_t power_source : 1;
uint8_t rx_on_when_idle : 1;
uint8_t reserved : 2;
uint8_t security_capability : 1;
uint8_t allocate_address : 1;
} mac_capability_t;
/**@brief The Alternate PAN Coordinator subfield of the Capability Information field. */
typedef enum
{
MAC_CAP_CANNOT_BE_PAN_COORD = 0, /**< Device is not capable of becoming
the PAN coordinator.*/
MAC_CAP_CAN_BE_PAN_COORD /**< Device is capable of becoming
the PAN coordinator.*/
} mac_cap_alt_pan_coord_t;
/**@brief The Device Type subfield of the Capability Information field. */
typedef enum
{
MAC_CAP_RFD_DEVICE = 0, /**< Device is an RFD.*/
MAC_CAP_FFD_DEVICE /**< Device is an FFD.*/
} mac_cap_device_type_t;
/**@brief The Power Source subfield of the Capability Information field. */
typedef enum
{
MAC_CAP_BATTERY_POWERED = 0, /**< Device is not AC-powered.*/
MAC_CAP_MAINS_POWERED /**< Device is receiving power from the
alternating current mains.*/
} mac_cap_power_source_t;
/**@brief The Receiver On When Idle subfield of the Capability Information field. */
typedef enum
{
MAC_CAP_RX_OFF_WHEN_IDLE = 0, /**< Device conserves power during idle.*/
MAC_CAP_RX_ON_WHEN_IDLE /**< Device does not disable its receiver
to conserve power during idle periods.*/
} mac_cap_rx_when_idle_t;
/**@brief The Security Capability subfield of the Capability Information field. */
typedef enum
{
MAC_CAP_CANNOT_SECURE = 0, /**< Device does not support securing.*/
MAC_CAP_CAN_SECURE /**< Device is capable of sending and receiving
cryptographically protected MAC frames.*/
} mac_cap_secure_t;
/**@brief The Allocate Address subfield of the Capability Information field. */
typedef enum
{
MAC_CAP_SHORT_ADDR_NOT_REQ = 0, /**< The coordinator will not allocate a
16-bit short address as a result of
the association procedure.*/
MAC_CAP_SHORT_ADDR_REQ /**< The coordinator will allocate a
16-bit short address as a result of
the association procedure.*/
} mac_cap_allocate_addr_t;
#if (CONFIG_ASSOCIATE_REQ_ENABLED == 1)
/**
* @brief MLME-ASSOCIATE.confirm
*
* The MLME-ASSOCIATE.confirm primitive is generated by the initiating MLME and
* issued to its next higher layer in response to an MLME-ASSOCIATE.request primitive.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.3.4.
*/
typedef struct
{
uint16_t assoc_short_address; /**< Association short 16-bit address. */
mac_status_t status; /**< Status of operation. */
#if (CONFIG_SECURE == 1)
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID mode. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mlme_associate_conf_t;
/**
* @brief MLME-ASSOCIATE.request.
*
* @details Allows a device to request an association with a coordinator.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.3.1.
*/
typedef struct
{
/** Do not edit this field. */
mac_abstract_req_t service;
/** Confirmation to this request. */
mlme_associate_conf_t confirm;
/**
* A total of 27 channels numbered 0 to 26.
* are available per channel page (section 6.1.2.1).
*/
uint8_t logical_channel;
/**
* A total of 32 channel pages are available
* with channel pages 3 to 31 being reserved
* for future use (section 6.1.2.2).
*/
#ifdef CONFIG_SUB_GHZ
uint8_t channel_page; /**< Channel page. */
#endif
mac_addr_mode_t coord_addr_mode; /**< Coordinator address mode. */
uint16_t coord_pan_id; /**< Coordinator PAN ID. */
mac_addr_t coord_address; /**< Coordinator address. */
mac_capability_t capability_information; /**< Capability information. */
#if (CONFIG_SECURE == 1)
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID mode. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mlme_associate_req_t;
#if (CONFIG_ASSOCIATE_IND_ENABLED == 1)
/**
* @brief MLME-ASSOCIATE.indication.
*
* @details The MLME-ASSOCIATE.indication primitive is generated by the MLME of
* the coordinator and issued to its next higher layer to indicate the reception
* of an association request command.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.3.2.
*/
typedef struct
{
uint64_t device_address; /**< 64-bit IEEE address. */
uint8_t capability_information; /**< Capability information. */
#if (CONFIG_SECURE == 1)
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID mode. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mlme_associate_ind_t;
/**
* @brief MLME-ASSOCIATE.response.
*
* @details Generated by the next higher layer of a coordinator and issued
* to its MLME in order to respond to the MLME-ASSOCIATE.indication primitive.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.3.3.
*/
typedef struct
{
uint64_t device_address; /**< 64-bit IEEE address. */
uint16_t assoc_short_address; /**< Association short 16-bit address. */
mac_association_status_t status; /**< Status of operation. */
#if (CONFIG_SECURE == 1)
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID mode. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mlme_associate_resp_t;
#endif // (CONFIG_ASSOCIATE_IND_ENABLED == 1)
/**
* @brief Confirmation function.
*
* @details The MLME-ASSOCIATE.confirm primitive is generated by the
* initiating MLME and issued to its next higher layer in response to
* an MLME-ASSOCIATE.request primitive. If the request was successful,
* the status parameter will indicate a successful association, as
* contained in the Status field of the association response command.
* Otherwise, the status parameter indicates either an error code from
* the received association response command or the appropriate error
* code from Table 50.
* The status values are fully described in 7.1.3.1.3 and subclauses referenced by 7.1.3.1.3.
*
* @param Pointer to confirmation primitive.
*/
typedef void (* mlme_associate_conf_cb_t)(mlme_associate_conf_t *);
/**
* @brief MLME-ASSOCIATE request.
*
* @details Requests an association with a PAN through a coordinator
* After request completion, user callback will be issued with
* valid data stored in structure mlme_set_conf_t.
*
* @param req MLME_ASSOCIATE request structure.
* @param conf_cb Pointer to user callback.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.3.5
*/
void mlme_associate_req(mlme_associate_req_t * req, mlme_associate_conf_cb_t conf_cb);
#if (CONFIG_ASSOCIATE_IND_ENABLED == 1)
/**
* @brief MLME-ASSOCIATE indication handler.
*
* @details Indicates an association with a PAN through a coordinator
* next higher layer of a coordinator receives the MLME-ASSOCIATE.indication
* primitive to determine whether to accept or reject the unassociated device
* using an algorithm outside the scope of standard.
*
* @param ind MLME ASSOCIATE indication structure.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.3.5.
*/
extern void mlme_associate_ind(mlme_associate_ind_t * ind);
/**
* @brief MLME-ASSOCIATE response.
*
* @details Respond to an association with a PAN and issue to its MLME in order to
* respond to the MLME-ASSOCIATE.indication.
* Response structure passed as a parameter to this function must be retained
* in memory until the related MLME-COMM-STATUS.indication is received.
*
* @param resp MLME_ASSOCIATE response structure.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.3.5.
*/
void mlme_associate_resp(mlme_associate_resp_t * resp);
#endif // (CONFIG_ASSOCIATE_IND_ENABLED == 1)
#endif // (CONFIG_ASSOCIATE_REQ_ENABLED == 1)
/** @} */
#endif // MAC_MLME_ASSOCIATE_H_INCLUDED

View File

@ -0,0 +1,175 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_MLME_BEACON_NOTIFY_H_INCLUDED
#define MAC_MLME_BEACON_NOTIFY_H_INCLUDED
#include <stdint.h>
#include <stdbool.h>
#include "mac_common.h"
#include "mac_time.h"
/** @file
* The MAC Beacon notify module declares the MAC beacon notification routine and necessary
* types/macros according to the MAC specification.
*
* @defgroup mac_beacon_notify MAC MLME Beacon Notify API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC MLME Beacon Notify API.
* @details The MAC Beacon Notify module declares Beacon Notify MLME routines and necessary macros/types
* according to the MAC specification. MAC MLME Beacon notify indication is declared as
* mlme_beacon_notify_ind().
*/
/**@brief This constant is defined in 7.2.2.1.7 Address List field
*
* @details The maximum number of addresses pending shall be limited to seven and may comprise
* both short and extended addresses.
*/
#define MAC_PENDING_ADDR_MAX 7
/*@brief The maximum length of GTS fields inside beacon in octets.
*
* @details This definition is used to allocate memory for outgoing beacon.
*/
#define MAC_MAX_GTS_FIELD_LEN 23
/**@brief Superframe specification structure.*/
typedef struct
{
uint16_t beacon_order : 4;
uint16_t superframe_order : 4;
uint16_t final_cap_slot : 4;
uint16_t battery_life_extension : 1;
uint16_t reserved : 1;
uint16_t pan_coordinator : 1;
uint16_t association_permit : 1;
} mac_superframe_spec_t;
/** @brief List of pending addresses
* Short addresses are at the top of the table.
*/
typedef struct
{
mac_addr_t addr_list[MAC_PENDING_ADDR_MAX];
/**< Addresses array. */
uint8_t short_addr_number; /**< Number of short addresses in the array. */
uint8_t ext_addr_number; /**< Number of long addresses in the array. */
} mac_pending_addr_list_t;
/**@brief PAN Descriptor structure.
*
* @details See Table 55-Elements of PANDescriptor.
*/
typedef struct
{
mac_addr_mode_t coord_addr_mode; /**< Coordinator addressing mode. */
uint16_t coord_pan_id; /**< Coordinator PAN ID. */
mac_addr_t coord_address; /**< Coordinator address. */
uint8_t logical_channel; /**< Logical channel. */
#ifdef CONFIG_SUB_GHZ
uint8_t channel_page; /**< Channel page. */
#endif
mac_superframe_spec_t superframe_spec; /**< Superframe specification. */
bool gts_permit; /**< Is GTS permitted? */
uint8_t link_quality; /**< Link quality. */
mac_timestamp_t timestamp; /**< Timestamp. */
#if (CONFIG_SECURE == 1)
uint8_t security_failure; /**< Security failure. */
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID mode. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mac_pan_descriptor_t;
/**@brief Pending Address Specification
*
* @details See Figure 51-Format of the Pending Address Specification field.
*/
typedef struct
{
uint8_t pending_short : 3;
uint8_t : 1;
uint8_t pending_extended : 3;
uint8_t : 1;
} mac_pend_addr_spec_t;
/**@brief MLME-BEACON-NOTIFY.indication parameters
*
* @details See 7.1.5.1 MLME-BEACON-NOTIFY.indication
*/
typedef struct
{
uint8_t bsn; /**< Beacon sequence number. */
mac_pan_descriptor_t pan_descriptor; /**< PAN descriptor. */
mac_pend_addr_spec_t pend_addr_spec; /**< Pending address specification. */
mac_addr_t addr_list[MAC_PENDING_ADDR_MAX];
/**< Addresses array. */
uint8_t sdu_length; /**< SDU length. */
mac_payload_descriptor_t sdu; /**< SDU. */
#if (CONFIG_SECURE == 1)
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID mode. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mlme_beacon_notify_ind_t;
/**@brief User implemented function, which handles MLME-BEACON-NOTIFY.indication.
*
* @details The MLME-BEACON-NOTIFY.indication primitive is used to send parameters contained
* within a beacon frame received by the MAC sublayer to the next higher layer.
* The primitive also sends a measure of the LQI and the time the beacon frame
* was received. See 7.1.5.1 MLME-BEACON-NOTIFY.indication.
*
* @param ind MLME-BEACON-NOTIFY.indication parameters. See @ref mlme_beacon_notify_ind_t.
*/
extern void mlme_beacon_notify_ind(mlme_beacon_notify_ind_t * ind);
/** @} */
#endif // MAC_MLME_BEACON_NOTIFY_H_INCLUDED

View File

@ -0,0 +1,135 @@
// Terms and conditions of usage are described in detail in NORDIC
// SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT.
//
// Licensees are granted free, non-transferable use of the information. NO
// WARRANTY of ANY KIND is provided. This heading must NOT be removed from
// the file.
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_MLME_COMM_STATUS_H_INCLUDED
#define MAC_MLME_COMM_STATUS_H_INCLUDED
#include <stdint.h>
#include "mac_common.h"
/** @file
* The MAC Comm Status module declares the MAC communication status indication routine and
* necessary types/macros according to the MAC specification.
*
* @defgroup mac_comm_status MAC MLME Comm Status API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC MLME Comm Status API.
* @details The MAC Comm Status module declares communication status indication MLME routine and necessary
* macros/types according to the MAC specification. MAC MLME Comm Status indication is declared as
* mlme_comm_status_ind().
*/
/**
* @brief MLME-COMM-STATUS.indication
*
* @details The MLME-COMM-STATUS.indication primitive allows the MLME to indicate a
* communication status.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.12.1
*/
typedef struct
{
/**
* The 16-bit PAN identifier of the device from which the frame was received or to
* which the frame was being sent.
*/
uint16_t pan_id;
/**
* The source addressing mode for this primitive. This value can take one of the
* following values:
* @ref mac_addr_mode_t
* 0x00 = no address (addressing fields omitted).
* 0x01 = reserved.
* 0x02 = 16-bit short address.
* 0x03 = 64-bit extended address.
*/
mac_addr_mode_t src_addr_mode;
/**
* The individual device address of the entity from which the frame causing the error
* originated.
*/
mac_addr_t src_addr;
/**
* The destination addressing mode for this primitive.
* According to 7.1.12.1.1, Table 69.
*/
mac_addr_mode_t dst_addr_mode;
/** The individual device address of the device for which the frame was intended. */
mac_addr_t dst_addr;
/** The communications status. */
mac_status_t status;
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID mode. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
} mlme_comm_status_ind_t;
/**
* @brief MLME-COMM-STATUS.indication handler
*
* @details The MLME-COMM-STATUS.indication primitive is generated by the MLME and issued to its next higher
* layer either following a transmission instigated through a response primitive or on receipt of a frame that
* generates an error in its security processing (see 7.5.8.2.3).
*
* @param ind MLME-COMM-STATUS.indication structure.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.12.1
*/
extern void mlme_comm_status_ind(mlme_comm_status_ind_t * ind);
/** @} */
#endif // MAC_MLME_COMM_STATUS_H_INCLUDED

View File

@ -0,0 +1,199 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_MLME_DISASSOCIATE_H_INCLUDED
#define MAC_MLME_DISASSOCIATE_H_INCLUDED
#if (CONFIG_DISASSOCIATE_ENABLED == 1)
#include <stdint.h>
#include <stdbool.h>
#include "mac_common.h"
#include "mac_task_scheduler.h"
/** @file
* The MAC MLME Disassociate module declares the MAC disassociation routines and
* necessary types/macros according to the MAC specification.
*
* @defgroup mac_diassociate MAC MLME Disassociate API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC MLME Disassociate API.
* @details The MLME Disassociation module declares Disassociation MAC routines and necessary types
* according to the MAC specification. More specifically, MLME Disassociation request aka
* mlme_disassociate_req(), MLME Disassociation confirm callback typedef aka
* mlme_disassociate_conf_cb_t, and MLME Disassociation indication as mlme_disassociate_ind()
* primitives are declared.
*/
/**
* @brief MAC Disassociation Reason field
*
* In accordance with IEEE Std 802.15.4-2006, section 7.3.2.2
*/
typedef enum
{
/** The coordinator wishes the device to leave the PAN. */
MAC_COORD_REASON = 1,
/** The device wishes to leave the PAN. */
MAC_DEV_REASON = 2
} mac_disassociate_reason_t;
/**
* @brief MLME-DISASSOCIATE.confirm
*
* @details On receipt of the MLME-DISASSOCIATE.confirm primitive, the next
* higher layer of the initiating device is notified of the result of the
* disassociation attempt. If the disassociation attempt was successful,
* the status parameter will be set to SUCCESS. Otherwise, the status parameter
* indicates the error.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.4.3
*/
typedef struct
{
mac_status_t status; /**< Status of operation. */
mac_addr_mode_t device_addr_mode; /**< Device addressing mode. */
uint16_t device_pan_id; /**< Device PAN ID. */
mac_addr_t device_address; /**< Device address. */
} mlme_disassociate_conf_t;
/**
* @brief MLME-DISASSOCIATE.request
*
* @details The MLME-DISASSOCIATE.request primitive is generated by the next
* higher layer of an associated device and issued to its MLME to request
* disassociation from the PAN. It is also generated by the next higher layer
* of the coordinator and issued to its MLME to instruct an
* associated device to leave the PAN.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.4.1
*/
typedef struct
{
/** Do not edit this field. */
mac_abstract_req_t service;
/** Confirm to this request. */
mlme_disassociate_conf_t confirm;
mac_addr_mode_t device_addr_mode; /**< Device addressing mode. */
uint16_t device_pan_id; /**< Device PAN ID. */
mac_addr_t device_address; /**< Device address. */
mac_disassociate_reason_t disassociate_reason; /**< Disassociation reason. */
bool tx_indirect; /**< Is TX indirect? */
#if (CONFIG_SECURE == 1)
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID mode. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mlme_disassociate_req_t;
/**
* @brief MLME-DISASSOCIATE.indication
*
* @details Is generated by the MLME and issued to its next higher
* layer on receipt of a disassociation notification command.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.4.2
*/
typedef struct
{
uint64_t device_address; /**< Device address. */
mac_disassociate_reason_t disassociate_reason; /**< Disassociation reason. */
#if (CONFIG_SECURE == 1)
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID mode. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mlme_disassociate_ind_t;
/**
* @brief Customer's function of confirmation
*
* @details The MLME-DISASSOCIATE.confirm primitive is generated by the initiating
* MLME and issued to its next higher layer in response to an MLME-DISASSOCIATE.request
* primitive. This primitive returns a status of either SUCCESS, indicating that the
* disassociation request was successful, or the appropriate error code.
* The status values are fully described in 7.1.4.1.3 and subclauses referenced by 7.1.4.1.3.
*
* @param pointer to confirmation primitive
*/
typedef void (* mlme_disassociate_conf_cb_t)(mlme_disassociate_conf_t *);
/**
* @brief MLME-DISASSOCIATE request
*
* @details Request disassociation with a PAN
* After request completion, user callback will be issued with
* valid data stored in structure @ref mlme_disassociate_conf_t.
*
* @param req MLME_DISASSOCIATE request structure.
* @param conf_cb pointer to user callback.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.4.4
*/
void mlme_disassociate_req(mlme_disassociate_req_t * req, mlme_disassociate_conf_cb_t conf_cb);
/**
* @brief MLME-DISASSOCIATE indication handler
*
* @details Indicates an disassociation with a PAN
*
* @param ind MLME_DISASSOCIATE indication structure.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.4.4
*/
extern void mlme_disassociate_ind(mlme_disassociate_ind_t * ind);
/** @} */
#endif // (CONFIG_DISASSOCIATE_ENABLED == 1)
#endif // MAC_MLME_DISASSOCIATE_H_INCLUDED

View File

@ -0,0 +1,211 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_MLME_GTS_H_INCLUDED
#define MAC_MLME_GTS_H_INCLUDED
#if (CONFIG_GTS_ENABLED == 1)
#include <stdint.h>
#include "mac_common.h"
#include "mac_task_scheduler.h"
/** @file
* The MAC MLME GTS module declares the MAC Guaranteed time slots routines and
* necessary types/macros according to the MAC specification.
*
* @defgroup mac_gts MAC MLME GTS API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC MLME GTS API.
* @details The MAC GTS module declares MAC Guaranteed Time Slots routines and necessary types according to
* the MAC specification. More specifically, MLME GTS request aka mlme_gts_req(), MLME GTS indicaton
* aka mlme_gts_ind(), and MLME GTS confirm callback typedef aka mlme_gts_conf_cb_t primitives are
* declared.
*/
/**@brief GTS directions, from device side. */
typedef enum
{
MAC_GTS_DIR_TXONLY = 0, /**< TX only direction. */
MAC_GTS_DIR_RXONLY = 1 /**< RX only direction. */
} mac_gts_direction_t;
/**@brief GTS characteristics type. */
typedef enum
{
MAC_GTS_DEALLOC = 0, /**< GTS Dealloc. */
MAC_GTS_ALLOC = 1 /**< GTS Alloc. */
} mac_gts_characteristics_type_t;
/**@brief MAC GTS characteristics (not packed)
*
* @details See Section 7.3.9.2
*/
typedef union
{
struct
{
uint8_t gts_length : 4;
uint8_t gts_direction : 1;
uint8_t characterictics_type : 1;
uint8_t : 2;
} bit;
uint8_t all;
} mac_gts_characteristics_t;
/**
* @brief MLME-GTS.confirm
*
* @details The MLME-GTS.confirm primitive reports the results of a
* request to allocate a new GTS or deallocate an existing GTS.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.7.2
*/
typedef struct
{
mac_gts_characteristics_t gts_characteristics; /**< GTS characteristics. */
mac_status_t status; /**< Status of operation. */
} mlme_gts_conf_t;
/**
* @brief MLME-GTS.request
*
* @details The MLME-GTS.request primitive allows a device to send a request
* to the PAN coordinator to allocate a new GTS or to deallocate an existing GTS.
* This primitive is also used by the PAN coordinator to initiate a GTS deallocation.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.7.1
*/
typedef struct
{
/** Do not edit this field. */
mac_abstract_req_t service;
/** Confirm to this request. */
mlme_gts_conf_t confirm;
mac_gts_characteristics_t gts_characteristics; /**< GTS characteristics. */
#if (CONFIG_SECURE == 1)
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID mode. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mlme_gts_req_t;
/**
* @brief MLME-GTS.indication
*
* @details The MLME-GTS.indication primitive indicates that a
* GTS has been allocated or that a previously allocated GTS
* has been deallocated.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.7.3
*/
typedef struct
{
uint16_t device_address; /**< Device address. */
mac_gts_characteristics_t gts_characteristics; /**< GTS characteristics. */
#if (CONFIG_SECURE == 1)
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID mode. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mlme_gts_ind_t;
/**
* @brief MLME-GTS confirm callback
*
* @details The MLME-GTS.confirm primitive is generated by the MLME and
* issued to its next higher layer in response to a previously
* issued MLME-GTS.request primitive.
*
* @param MLME_GTS callback structure.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.7.4
*/
typedef void (* mlme_gts_conf_cb_t)(mlme_gts_conf_t *);
/**
* @brief MLME-GTS request
*
* @details The MLME-GTS.request primitive is generated by the next higher
* layer of a device and issued to its MLME to request the allocation of a
* new GTS or to request the deallocation of an existing GTS. It is also
* generated by the next higher layer of the PAN coordinator and issued to
* its MLME to request the deallocation of an existing GTS.
*
* @param req MLME_GTS request structure.
* @param conf_cb pointer to user callback.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.7.4
*/
void mlme_gts_req(mlme_gts_req_t * req, mlme_gts_conf_cb_t conf_cb);
/**
* @brief MLME-GTS indication handler
*
* @details The MLME-GTS.indication primitive is generated by the MLME of
* the PAN coordinator to its next higher layer whenever a GTS is allocated
* or deallocated following the reception of a GTS request command (see 7.3.9)
* by the MLME. The MLME of the PAN coordinator also generates this primitive when a GTS
* deallocation is initiated by the PAN coordinator itself.
*
* @param ind MLME_GTS indication structure.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.7.4
*/
extern void mlme_gts_ind(mlme_gts_ind_t * ind);
/** @} */
#endif // (CONFIG_GTS_ENABLED == 1)
#endif // MAC_MLME_GTS_H_INCLUDED

View File

@ -0,0 +1,151 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_MLME_ORPHAN_H_INCLUDED
#define MAC_MLME_ORPHAN_H_INCLUDED
#if (CONFIG_ORPHAN_ENABLED == 1)
#include <stdint.h>
#include <stdbool.h>
#include "mac_common.h"
/** @file
* The MAC MLME Orphan module declares the MAC Orphan routines and
* necessary types/macros according to the MAC specification.
*
* @defgroup mac_orphan MAC MLME Orphan API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC MLME Orphan API.
* @details The MAC Orphan module declares routines and necessary types to deal with the Orphan devices
* according to the MAC specification. More specifically, MAC MLME Orphan indication aka
* mlme_orphan_ind(), MAC MLME Orphan response aka mlme_orphan_resp() primitives are declared.
*/
/**
* @brief MLME-ORPHAN.indication
*
* @details The MLME-ORPHAN.indication primitive allows the MLME of a coordinator
* to notify the next higher layer of the presence of an orphaned device.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.8.1
*/
typedef struct
{
/** The address of the orphaned device. */
uint64_t orphan_address;
#if (CONFIG_SECURE == 1)
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID mode. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mlme_orphan_ind_t;
/**
* @brief MLME-ORPHAN.response
*
* @details The MLME-ORPHAN.response primitive allows the next higher layer of a coordinator
* to respond to the MLME-ORPHAN.indication primitive.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.8.2
*/
typedef struct
{
/** Do not edit this field. */
mac_abstract_req_t service;
/** The address of the orphaned device. */
uint64_t orphan_address;
/**
* The 16-bit short address allocated to the orphaned device if it is associated with this
* coordinator. The special short address 0xfffe indicates that no short address was
* allocated, and the device will use its 64-bit extended address in all communications.
* If the device was not associated with this coordinator, this field will contain the
* value 0xffff and be ignored on receipt.
*/
uint16_t short_address;
/** TRUE if the orphaned device is associated with this coordinator or FALSE otherwise. */
bool associated_member;
#if (CONFIG_SECURE == 1)
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID mode. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mlme_orphan_resp_t;
/**
* @brief MLME-ORPHAN.indication handler
*
* @details The MLME-ORPHAN.indication primitive is generated by the MLME of a coordinator
* and issued to its next higher layer on receipt of an orphan notification command (see 7.3.6).
*
* @param ind MLME-ORPHAN.indication structure.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.8.1
*/
extern void mlme_orphan_ind(mlme_orphan_ind_t * ind);
/**
* @brief MLME-ORPHAN.response handler
*
* @details The MLME-ORPHAN.response primitive is generated by the next higher layer and issued to its MLME
* when it reaches a decision about whether the orphaned device indicated in the MLME-ORPHAN.indication
* primitive is associated.
*
* @param resp MLME-ORPHAN.response structure.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.8.2
*/
void mlme_orphan_resp(mlme_orphan_resp_t * resp);
/** @} */
#endif // (CONFIG_ORPHAN_ENABLED == 1)
#endif // MAC_MLME_ORPHAN_H_INCLUDED

View File

@ -0,0 +1,508 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_MLME_PIB_H_INCLUDED
#define MAC_MLME_PIB_H_INCLUDED
#include <stdint.h>
#include "mac_common.h"
#include "phy_plme_pib.h"
#include "mac_task_scheduler.h"
#include "mac_security.h"
#include "sys_debug.h"
/** @file
* The MAC MLME PIB module declares the MAC PHY Information Base routines and
* necessary types/macros according to the MAC specification.
*
* @defgroup mac_pib MAC MLME PIB API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC MLME PIB API.
* @details The MAC PIB module declares routines and necessary types to deal with the PHY Information Base
* functionality related to MAC. More specifically, MLME PIB Get request aka mlme_get_req(), MLME
* PIB Set request aka mlme_set_req(), MLME PIB confirmation callbacks aka mlme_get_conf_cb_t, and
* mlme_set_conf_cb_t primitives are declared. Two additional primitives not covered by the
* standard are declared. These are mlme_get() and mlme_set() which are synchronous versions of
* mlme_get_req() and mlme_set_req() accordingly. There is one helper informational routine
* mlme_pib_attr_size_calc() to count MLME attribute size in bytes. Refer to the
* mac_pib_param_test application for detailed samples of implementation of these primitives.
* This module also defines the MAC Table API. The tables can be used to deal with MAC attributes.
* A special initialization routine mac_table_init() should be called before using of any other MAC
* table API. The mac_table_reset() routine is used to clean up an existing (initialized) table.
* mac_table_idx_get() searches through a MAC table to find the item with requested idx. The
* mac_table_item_set() routine is needed to substitute a table item with a new value. The
* mac_table_item_remove() routine removes the item with the given index from the table and
* frees all resources associated with the item. mac_table_item_front() and mac_table_item_next()
* return the first and next item from the table. The mac_table_size_get() routine returns the
* number of items in the table, while mac_table_is_empty() checks if the table is empty.
*/
/**
* @brief MAC PIB attribute identifiers
*
* In accordance with IEEE Std 802.15.4-2006, section 7.4.2
*/
typedef enum
{
MAC_ACK_WAIT_DURATION = 0x40,
MAC_ASSOCIATION_PERMIT,
MAC_AUTO_REQUEST,
MAC_BATT_LIFE_EXT,
MAC_BATT_LIFE_EXT_PERIODS,
MAC_BEACON_PAYLOAD, /* 0x45 */
MAC_BEACON_PAYLOAD_LENGTH,
MAC_BEACON_ORDER, /**< Specification of how often the
coordinator transmits its
beacon. If BO = 15, the
coordinator will not transmit
a periodic beacon.*/
MAC_BEACON_TX_TIME,
MAC_BSN,
MAC_COORD_EXTENDED_ADDRESS, /* 0x4A */
MAC_COORD_SHORT_ADDRESS,
MAC_DSN,
MAC_GTS_PERMIT,
MAC_MAX_CSMA_BACKOFFS,
MAC_MIN_BE,
MAC_PAN_ID, /**< PAN Identifier.*/
/* 0x50 */
MAC_PROMISCUOUS_MODE,
MAC_RX_ON_WHEN_IDLE,
MAC_SHORT_ADDRESS, /**< MAC Short Address.*/
MAC_SUPERFRAME_ORDER,
MAC_TRANSACTION_PERSISTENCE_TIME, /* 0x55 */
MAC_ASSOCIATED_PAN_COORD,
MAC_MAX_BE,
MAC_MAX_FRAME_TOTAL_WAIT_TIME,
MAC_MAX_FRAME_RETRIES,
MAC_RESPONSE_WAIT_TIME, /* 0x5A */
MAC_SYNC_SYMBOL_OFFSET,
MAC_TIMESTAMP_SUPPORTED,
MAC_SECURITY_ENABLED,
MAC_MIN_LIFS_PERIOD, /* 0x5E No attribute id in Table 86.*/
MAC_MIN_SIFS_PERIOD, /* 0x5F No attribute id in Table 86.*/
MAC_EXTENDED_ADDRESS, /**< MAC Extended Address.*/
/* 0x60 Not covered by standard.*/
MAC_IS_PAN_COORD,
#if (CONFIG_SECURE == 1)
MAC_KEY_TABLE = 0x71,
MAC_KEY_TABLE_ENTRIES,
MAC_DEVICE_TABLE,
MAC_DEVICE_TABLE_ENTRIES,
MAC_SECURITY_LEVEL_TABLE, /* 0x75 */
MAC_SECURITY_LEVEL_TABLE_ENTRIES,
MAC_FRAME_COUNTER,
MAC_AUTO_REQUEST_SECURITY_LEVEL,
MAC_AUTO_REQUEST_KEY_ID_MODE,
MAC_AUTO_REQUEST_KEY_SOURCE, /* 0x7A */
MAC_AUTO_REQUEST_KEY_INDEX,
MAC_DEFAULT_KEY_SOURCE,
MAC_PAN_COORD_EXTENDED_ADDRESS,
MAC_PAN_COORD_SHORT_ADDRESS,
/* Items below do not covered by the standard */
// these three IDs are used to make access to the root of security tables
MAC_KEY_TABLE_POINTER,
MAC_DEVICE_TABLE_POINTER,
MAC_SECURITY_LEVEL_TABLE_POINTER,
// these three IDs are stored inside PIB base and
// used to get table item sizes
MAC_KEY_ID_LOOKUP_LIST,
MAC_KEY_DEVICE_LIST,
MAC_KEY_USAGE_LIST,
#endif
} mlme_pib_attr_id_t;
/**
* @brief United PIB attribute identifiers
*
* To unite access to MAC and PHY PIB by one API
*/
typedef union
{
mlme_pib_attr_id_t mlme_id; /**< PIB is MAC-based. */
plme_pib_attr_id_t plme_id; /**< PIB is PHY-based. */
} pib_id_t;
/**
* @brief MLME-GET.confirm
*
* @details structure for confirming information about a given PIB attribute.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.6.2
*/
typedef struct
{
mac_status_t status; /**< Status of operation. */
pib_id_t pib_attribute; /**< PIB Attribute. */
uint8_t pib_attribute_idx; /**< PIB Attribute index. */
/** value size is calculated with 'mlme_pib_attr_size_calc' */
uint8_t * value; /**< Attribute value. */
} mlme_get_conf_t;
/**
* @brief MLME-GET.request
*
* @details structure for requesting information about a given PIB attribute.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.6.1
*/
typedef struct
{
/** Do not edit this field. */
mac_abstract_req_t service;
/** Confirm to this request. */
mlme_get_conf_t confirm;
pib_id_t pib_attribute; /**< PIB Attribute. */
uint8_t pib_attribute_idx; /**< PIB Attribute index. */
} mlme_get_req_t;
/**
* @brief MLME-SET.confirm
*
* @details structure for reporting the results of an attempt to write a value
* to a PIB attribute.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.13.2
*/
typedef struct
{
mac_status_t status; /**< Status of operation. */
pib_id_t pib_attribute; /**< PIB Attribute. */
uint8_t pib_attribute_idx; /**< PIB Attribute index. */
} mlme_set_conf_t;
/**
* @brief MLME-SET.request
*
* @details structure for setting a PIB attribute.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.13.1
*/
typedef struct
{
/** Do not edit this field. */
mac_abstract_req_t service;
/** Confirm to this request. */
mlme_set_conf_t confirm;
pib_id_t pib_attribute; /**< PIB Attribute. */
uint8_t pib_attribute_idx; /**< PIB Attribute index. */
uint8_t * value; /**< Attribute value. The value size is calculated
with mlme_pib_attr_size_calc. */
} mlme_set_req_t;
/**
* @brief Customer's function of confirmation
*
* @details The MLME-GET.confirm primitive is generated by the MLME and issued
* to its next higher layer in response to an MLME-GET.request primitive.
* This primitive returns a status of either SUCCESS, indicating that the request
* to read a PIB attribute was successful, or an error code of UNSUPPORTED_ATTRIBUTE.
* When an error code of UNSUPPORTED_ATTRIBUTE is returned, the PIBAttribute value
* parameter will be set to length zero. The status values are fully described in 7.1.6.1.3.
*
* @param pointer to confirmation primitive
*/
typedef void (* mlme_get_conf_cb_t)(mlme_get_conf_t *);
/**
* @brief Customer's function of confirmation
*
* @details The MLME-SET.confirm primitive is generated by the MLME and issued to its
* next higher layer in response to an MLME-SET.request primitive. The MLME-SET.confirm
* primitive returns a status of either SUCCESS, indicating that the requested value was
* written to the indicated PIB attribute, or the appropriate error code.
* The status values are fully described in 7.1.13.1.3.
*
* @param pointer to confirmation primitive
*/
typedef void (* mlme_set_conf_cb_t)(mlme_set_conf_t *);
/**
* @brief MLME-GET request
*
* @details Request information about a given PIB attribute.
*
* @param[in] req pointer to request structure.
* @param[in] conf_cb pointer to user callback.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.6.
* See \a mlme_get() for more details.
*/
void mlme_get_req(mlme_get_req_t * req, mlme_get_conf_cb_t conf_cb);
/**
* @brief MLME-SET request
*
* @details Request to set a PIB attribute.
* After request completion, user callback will be issued with
* valid data stored in structure @ref mlme_set_conf_t.
*
* See \a mlme_set() for more details.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.13
*
* @param[in] req MLME_SET request structure.
* @param[in] conf_cb pointer to user callback.
*/
void mlme_set_req(mlme_set_req_t * req, mlme_set_conf_cb_t conf_cb);
/**
* @brief Counts MLME attribute size
*
* @details This is an implementation-specific function not covered by the standard.
*
* @param[in] id attribute id.
* @param[in] idx index inside the table in case the attribute is a table.
*
* @return size of attribute in bytes.
*/
size_t mlme_pib_attr_size_calc(pib_id_t id, uint8_t idx);
/**
* @brief Gets parameters from PIB directly (without request - confirm approach)
*
* @details Optional. Not covered by a standard.
*
* For non-tabled attributes this function will return value to location
* passed to the last argument.
*
* For tabled attributes this function will return pointer to
* a descriptor structure of corresponding table.
*
* @param[in] id attribute id.
* @param[in] idx index inside the table in case the attribute is a table.
* @param[out] mem either pointer to memory where attribute value is returned
* (for all attributes except MAC_KEY_TABLE, MAC_DEVICE_TABLE,
* MAC_SECURITY_LEVEL_TABLE), or pointer to memory where pointer
* to attribute storage place is returned.
*
* @return status of operation
*/
mac_status_t mlme_get(pib_id_t id, uint8_t idx, void * mem);
/**
* @brief Sets parameters to PIB directly (without request - confirm approach)
*
* @details Optional. Not covered by a standard.
*
* This function performs copying or replacement of some attribute value
* into the PIB base memory.
*
* Note, that all security tables are copied into dynamic memory, that
* mlme_set is responsible to allocate. For nested tables copying is done
* in a shallow manner (in Python sense). It means that passed \a mac_key_descr_t
* is copied as-is, without creating copies of internal tables.
* Caller must allocate and prepare all nested tables such as
* #MAC_KEY_DEVICE_LIST, #MAC_KEY_ID_LOOKUP_LIST and #MAC_KEY_USAGE_LIST
* before calling this function.
*
* Passed attribute value will replace the current one, if the item with such
* \a id and \a idx already exists. This function is responsible for
* freeing all items during destruction of existing objects.
*
* @note Nested tables may be expanded and reduced with \a mac_table_item_set()
* and other similar functions.
*
* @param[in] id attribute id.
* @param[in] idx index inside the table in case the attribute is a table.
* @param[out] mem pointer to memory for parameter storing.
*
* @return status of operation
*/
mac_status_t mlme_set(pib_id_t id, uint8_t idx, void * mem);
#if (CONFIG_SECURE == 1)
/**
* @brief Initializes a table. This function MUST be called before accessing
* to a newly allocated table.
*
* @param[out] p_table Pointer to a fresh table.
*/
void mac_table_init(mac_table_t * p_table);
/**
* @brief Resets a table, freeing all its elements.
*
* @param[in] p_table Pointer to the table to reset.
* @param[in] id One of #MAC_KEY_TABLE, #MAC_DEVICE_TABLE, #MAC_SECURITY_LEVEL_TABLE,
* #MAC_KEY_ID_LOOKUP_LIST, #MAC_KEY_DEVICE_LIST, #MAC_KEY_USAGE_LIST to let
* function know about the size of p_item.
*/
void mac_table_reset(mac_table_t * p_table, mlme_pib_attr_id_t id);
/**
* @brief Searches through mac_table_t and finds the item with requested idx.
*
* @param[in] p_table Table to search through.
* @param[in] idx Item idx to match.
*
* @return Pointer to mac_table_item_t with requested idx or NULL if such
* an item cannot be found.
*/
mac_table_item_t * mac_table_idx_get(const mac_table_t * p_table, uint8_t idx);
/**
* @brief Sets new value item for mac_table_t.
*
* @param[out] p_table Pointer to the table to add item to.
* @param[in] p_item Pointer to a new item. This item must include appropriate idx
* (less than the maximum table size).
* @param[in] id One of #MAC_KEY_TABLE, #MAC_DEVICE_TABLE, #MAC_SECURITY_LEVEL_TABLE,
* #MAC_KEY_ID_LOOKUP_LIST, #MAC_KEY_DEVICE_LIST, #MAC_KEY_USAGE_LIST to let
* function know about the size of p_item.
* @param[in] idx Item index inside the selected table.
*
* @details This function performs a "deep copy" of passed table item to conform with
* mlme_set behavior. New copy resides in the heap memory. If an item with requested
* idx has been already set earlier, this function frees the old item and pushes
* a new one instead.
*
* @retval #MAC_INVALID_INDEX if idx exceeds allowed maximum number of items in
* the table.
* @retval #MAC_LIMIT_REACHED if there is no enough dynamic memory to put this item
* into the security table.
* @retval #MAC_SUCCESS if insertion has been performed successfully.
*/
mac_status_t mac_table_item_set(mac_table_t * p_table,
const mac_table_item_t * p_item,
mlme_pib_attr_id_t id,
uint8_t idx);
/**
* @brief Removes an item from a mac_table_t instance and frees all resources,
* associated with this item.
*
* @param[out] p_table Pointer to the table to remove item from.
* @param[in] id One of #MAC_KEY_TABLE, #MAC_DEVICE_TABLE, #MAC_SECURITY_LEVEL_TABLE,
* #MAC_KEY_ID_LOOKUP_LIST, #MAC_KEY_DEVICE_LIST, #MAC_KEY_USAGE_LIST to let
* function perform down-casting correctly.
* @param[in] idx Item index inside of selected table.
*
* @retval #MAC_INVALID_INDEX if passed index is not found in the table or exceeds
* the allowed maximum.
* @retval #MAC_SUCCESS if no errors happen during removing.
*/
mac_status_t mac_table_item_remove(mac_table_t * p_table,
mlme_pib_attr_id_t id,
uint8_t idx);
/**
* @brief Gets first available item from a table.
*
* @details This function might be used along with \a mac_table_item_next to
* search through some table.
*
* @param[in] p_table Pointer to a MAC table.
*
* @return Pointer to the first table item or NULL if the table is empty.
*/
mac_table_item_t * mac_table_item_front(const mac_table_t * p_table);
/**
* @brief Returns the next available item in table.
*
* @details MAC tables are stored unsorted in memory, so there is no guarantee that
* index of the next item is always greater or smaller than the current one.
* Items are not stored in chronological order either.
*
* @param[in] p_table Pointer to a table to select item from.
* @param[in] p_current_item Pointer to the current item.
*
* @return Pointer to the next item in table or NULL, if the item is the last one.
*/
mac_table_item_t * mac_table_item_next(const mac_table_t * p_table,
const mac_table_item_t * p_current_item);
/**
* @brief Gets number of items used inside mac_table_t.
*
* @param[in] p_table Pointer to interested table.
*
* @return 8-bit integer equal to number of items inside the table that have
* been set at least once.
*/
static inline uint8_t mac_table_size_get(const mac_table_t * p_table)
{
ASSERT(p_table != NULL);
return p_table->size;
}
/**
* @brief This function checks if a MAC table is empty.
*
* @param[in] p_table Pointer to a MAC table.
*
* @return true if there are no items inside table, false otherwise.
*/
static inline bool mac_table_is_empty(const mac_table_t * p_table)
{
ASSERT(p_table != NULL);
return sys_queue_is_empty(&p_table->queue);
}
#endif
/** @} */
#endif // MAC_MLME_PIB_H_INCLUDED

View File

@ -0,0 +1,151 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_MLME_POLL_H_INCLUDED
#define MAC_MLME_POLL_H_INCLUDED
#include <stdint.h>
#include "mac_common.h"
#include "mac_task_scheduler.h"
/** @file
* The MAC MLME Poll module declares the MAC Poll primitives and necessary types
* according to the MAC specification.
*
* @defgroup mac_poll MAC MLME Poll API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC MLME Poll API.
* @details The MAC Poll module declares MLME Poll primitives and necessary types according to
* the MAC specification. More specifically, MLME Poll request aka mlme_poll_req(), MLME Poll
* indicaton aka mlme_poll_ind(), and MLME Poll confirm callback typedef aka mlme_poll_conf_cb_t
* primitives are declared.
*/
/**@brief MLME-POLL.confirm
*
* @details The MLME-POLL.confirm primitive reports the results of a request
* to poll the coordinator for data.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.16.2
*/
typedef struct
{
mac_status_t status; /**< Status of operation. */
} mlme_poll_conf_t;
/**@brief MLME-POLL.request
*
* @details The MLME-POLL.request primitive prompts the device
* to request data from the coordinator.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.16.1
*/
typedef struct
{
/** Do not edit this field. */
mac_abstract_req_t service;
/** Confirm to this request. */
mlme_poll_conf_t confirm;
mac_addr_mode_t coord_addr_mode; /**< Coordinator address mode. */
uint16_t coord_pan_id; /**< Coordinator PAN ID. */
mac_addr_t coord_address; /**< Coordinator address. */
#if (CONFIG_SECURE == 1)
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID mode. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mlme_poll_req_t;
/** @brief MLME-Poll.indication
*
* @details The MLME-POLL.indication primitive indicates the reception
* of a Data request command frame by the MAC sub-layer and issued to
* the local SSCS (service specific convergence sublayer).
*/
typedef struct
{
mac_addr_mode_t src_addr_mode; /**< Source address mode. */
mac_addr_t src_address; /**< Source address. */
} mlme_poll_ind_t;
/**@brief Prototype of the user-implemented MLME-POLL.confirm callback function.
*
* @details The MLME-POLL.confirm primitive is generated by the MLME and issued
* to its next higher layer in response to an MLME-POLL.request primitive.
* If the request was successful, the status parameter will be equal to SUCCESS,
* indicating a successful poll for data. Otherwise, the status parameter indicates the
* appropriate error code. The status values are fully described in 7.1.16.1.3 and
* the subclauses referenced by 7.1.16.1.3.
*
* @param pointer to a confirmation primitive.
*/
typedef void (* mlme_poll_conf_cb_t)(mlme_poll_conf_t *);
/**@brief MLME-POLL.request
*
* @details The MLME-POLL.request primitive is generated by the next higher layer and
* issued to its MLME when data are to be requested from a coordinator.
*
* @param[in] req MLME-POLL.request parameters
* @param[in] conf_cb User-implemented callback function, which will be
* called by MLME in order to pass MLME-POLL.confirm to the user.
*/
void mlme_poll_req(mlme_poll_req_t * req, mlme_poll_conf_cb_t conf_cb);
/**@brief MLME-POLL.indication
*
* @details The MLME-Poll.indication primitive notifies the next higher level that
* a request for data has been received.
*
* @param[in] p_ind pointer to a poll indication structure
*/
extern void mlme_poll_ind(mlme_poll_ind_t * p_ind);
/** @} */
#endif // MAC_MLME_POLL_H_INCLUDED

View File

@ -0,0 +1,125 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_MLME_RESET_H_INCLUDED
#define MAC_MLME_RESET_H_INCLUDED
#include <stdint.h>
#include <stdbool.h>
#include "mac_common.h"
#include "mac_task_scheduler.h"
/** @file
* The MAC MLME Reset module declares the MAC Reset primitives and necessary types
* according to the MAC specification.
*
* @defgroup mac_reset MAC MLME Reset API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC MLME Reset API.
* @details The MAC Reset module declares MLME Reset primitives and necessary types according to
* the MAC specification. More specifically, MLME Reset request aka mlme_reset_req(), and MLME
* Reset confirm callback typedef aka mlme_reset_conf_cb_t primitives are declared.
*/
/**@brief MLME-Reset.confirm
*
* @details The MLME-Reset.confirm primitive reports the results of a request
* to reset MAC layer of the device.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.9.2
*/
typedef struct
{
mac_status_t status; /**< Status of operation. */
} mlme_reset_conf_t;
/**@brief MLME-RESET.request
*
* @details The MLME-RESET.request primitive allows the next
* higher layer to request that the MLME performs a reset operation.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.9.1
*/
typedef struct
{
/** Do not edit this field. */
mac_abstract_req_t service;
/** Confirm to this request. */
mlme_reset_conf_t confirm;
bool set_default_pib; /**< Set the default PIB. */
} mlme_reset_req_t;
/**
* @brief MLME-RESET confirm callback
*
* @details The MLME-RESET.confirm primitive is generated by the MLME and
* issued to its next higher layer in response to an MLME-RESET.request primitive and
* following the receipt of the PLME-SET-TRXSTATE.confirm primitive.
*
* @param reset status (@c MAC_SUCCESS only).
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.9.2
*/
typedef void (* mlme_reset_conf_cb_t)(mlme_reset_conf_t *);
/**
* @brief MLME-RESET request
*
* @details The MLME-RESET.request primitive is generated by the next higher layer and
* issued to the MLME to request a reset of the MAC sublayer to its initial conditions.
* The MLME-RESET.request primitive is issued prior to the use of the MLME-START.request
* or the MLME-ASSOCIATE.request primitives.
*
* @param[in] req pointer to MCPS-RESET.request structure.
* @param[in] conf_cb pointer to user callback.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.9.1
*/
void mlme_reset_req(mlme_reset_req_t * req, mlme_reset_conf_cb_t conf_cb);
/** @} */
#endif // MAC_MLME_RESET_H_INCLUDED

View File

@ -0,0 +1,181 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_MLME_RX_ENABLE_H_INCLUDED
#define MAC_MLME_RX_ENABLE_H_INCLUDED
#if (CONFIG_RXE_ENABLED == 1)
#include <stdint.h>
#include <stdbool.h>
#include "mac_common.h"
#include "mac_task_scheduler.h"
/** @file
* The MAC MLME RX-Enable module declares the MAC RX-Enable primitives and necessary types
* according to the MAC specification.
*
* @defgroup mac_rx_enable MAC MLME RX-Enable API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC MLME RX-Enable API.
* @details The MAC RX-Enable module declares MLME RX-Enable primitives and necessary types according to
* the MAC specification. More specifically, MLME RX-Enable request aka mlme_rx_enable_req(),
* and MLME RX-Enable confirm callback typedef aka mlme_rx_enable_conf_cb_t primitives are
* declared. One additional primitive not covered by the standard is declared. This is
* mlme_rx_enable() which is synchronous (i.e. does not require confirmation) version of
* mlme_rx_enable_req().
*/
/**
* @brief MLME-RX-ENABLE.confirm
*
* @details The MLME-RX-ENABLE.confirm primitive reports the results of an attempt
* to enable or disable the receiver.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.10.2
*/
typedef struct
{
mac_status_t status; /**< Status of operation. */
} mlme_rx_enable_conf_t;
/**
* @brief MLME-RX-ENABLE.request
*
* @details The MLME-RX-ENABLE.request primitive allows the next higher layer
* to request that the receiver is either enabled for a finite period of time or disabled.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.10.1
*/
typedef struct
{
/** Do not edit this field. */
mac_abstract_req_t service;
/** Confirm to this request. */
mlme_rx_enable_conf_t confirm;
/**
* @details
* TRUE if the requested operation can be deferred until the next superframe
* if the requested time has already passed.
* FALSE if the requested operation is only to be attempted in the current superframe.
*
* If the issuing device is the PAN coordinator, the term superframe refers to its own
* superframe. Otherwise, the term refers to the superframe of the coordinator through
* which the issuing device is associated.
*
* @note This parameter is ignored for nonbeacon-enabled PANs.
*/
bool defer_permit;
/**
* @details
* The number of symbols measured from the start of the superframe before the receiver is
* to be enabled or disabled.
* This is a 24-bit value, and the precision of this value shall be a minimum of 20 bits,
* with the lowest 4 bits being the least significant.
*
* If the issuing device is the PAN coordinator, the term superframe refers to its own
* superframe. Otherwise, the term refers to the superframe of the coordinator through
* which the issuing device is associated.
*
* @note This parameter is ignored for nonbeacon-enabled PANs.
*/
uint32_t rx_on_time;
/**
* The number of symbols the receiver is to be enabled for.
*
* If this parameter is equal to 0x000000, the receiver is to be disabled.
*/
uint32_t rx_on_duration;
} mlme_rx_enable_req_t;
/**
* @brief Customer's function of confirmation.
*
* @details The MLME-RX-ENABLE.confirm primitive is generated by the MLME and issued to
* its next higher layer in response to an MLME-RX-ENABLE.request primitive.
*
* @param pointer to a confirmation primitive.
*/
typedef void (* mlme_rx_enable_conf_cb_t)(mlme_rx_enable_conf_t *);
/**
* @brief MLME-RX-ENABLE.request service
*
* @details The MLME-RX-ENABLE.request primitive is generated by the next higher layer and
* issued to the MLME to enable the receiver for a fixed duration, at a time relative to the
* start of the current or next superframe on a beacon-enabled PAN or immediately on a
* nonbeacon-enabled PAN. This primitive may also be generated to cancel a previously generated
* request to enable the receiver. After request completion, user callback will be issued with
* valid data stored in structure mlme_rx_enable_conf_t.
*
* @note The receiver is enabled or disabled exactly once per primitive request.
*
* @param[in] req pointer to MLME-RX-ENABLE request structure.
* @param[in] conf_cb - pointer to confirm function (user callback).
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.10.1
*/
void mlme_rx_enable_req(mlme_rx_enable_req_t * req, mlme_rx_enable_conf_cb_t conf_cb);
/**
* @brief Enables permission for receiving.
*
* @details Optional. Not covered by a standard.
*
* @param[in] req pointer to MLME-RX-ENABLE request structure.
*
* @return status of operation.
*/
mac_status_t mlme_rx_enable(mlme_rx_enable_req_t * req);
/** @} */
#endif // (CONFIG_RXE_ENABLED == 1)
#endif // MAC_MLME_RX_ENABLE_H_INCLUDED

View File

@ -0,0 +1,160 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_MLME_SCAN_H_INCLUDED
#define MAC_MLME_SCAN_H_INCLUDED
#include <stdint.h>
#include "mac_common.h"
#include "mac_mlme_beacon_notify.h"
#include "mac_task_scheduler.h"
/** @file
* The MAC MLME Scan module declares the MAC Scan primitives and necessary types
* according to the MAC specification.
*
* @defgroup mac_scan MAC MLME Scan API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC MLME Scan API.
* @details The MAC Scan module declares MLME Scan primitives and necessary types according to
* the MAC specification. More specifically, MLME Scan request aka mlme_scan_req(), and MLME
* Scan confirm callback typedef aka mlme_scan_conf_cb_t primitives are declared.
*/
/**@brief Type of scan. */
typedef enum
{
ED_SCAN = 0, /**< Energy detection scan. */
ACTIVE_SCAN, /**< Active scan. */
PASSIVE_SCAN, /**< Passive scan. */
ORPHAN_SCAN /**< Orphan scan. */
} mac_scan_type_t;
/**
* @brief MLME-SCAN.confirm
*
* @details The MLME-SCAN.confirm reports the result of the channel scan request.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.11.2
*/
typedef struct
{
mac_status_t status; /**< Status of operation. */
mac_scan_type_t scan_type; /**< Scan type. */
#ifdef CONFIG_SUB_GHZ
uint8_t channel_page; /**< Channel page. */
#endif
uint32_t unscanned_channels; /**< Unscanned channels. */
uint8_t result_list_size; /**< Result list size. */
uint8_t * energy_detect_list; /**< Energy detection list. */
mac_pan_descriptor_t * pan_descriptor_list; /**< PAN descriptor list. */
} mlme_scan_conf_t;
/**
* @brief MLME-SCAN.request
*
* @details The MLME-SCAN.request primitive is used to initiate a channel
* scan over a given list of channels.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.11.1
*/
typedef struct
{
/** Do not edit this field. */
mac_abstract_req_t service;
/** Confirm to this request. */
mlme_scan_conf_t confirm;
mac_scan_type_t scan_type; /**< Scan type. */
uint32_t scan_channels; /**< Scan channels. */
uint8_t scan_duration; /**< Scan duration. */
uint8_t pan_descriptors_buf_size; /**< PAN descriptor buffer size. */
mac_pan_descriptor_t * pan_descriptors_buf; /**< PAN descriptor buffer. */
uint8_t energy_detect_buf_size; /**< Energy detection buffer size. */
uint8_t * energy_detect_buf; /**< Energy detection buffer. */
#ifdef CONFIG_SUB_GHZ
uint8_t channel_page; /**< Channel page. */
#endif
#if (CONFIG_SECURE == 1)
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID mode. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mlme_scan_req_t;
/**
* @brief User callback to scan request.
*
* @details The MLME-SCAN.confirm primitive is generated by the MLME and issued to
* its next higher layer when the channel scan initiated with
* the MLME-SCAN.request primitive has completed.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.11.2
*/
typedef void (* mlme_scan_conf_cb_t)(mlme_scan_conf_t *);
/**
* @brief MLME-SCAN request
*
* @details The MLME-SCAN.request primitive is generated by the next higher layer and
* issued to its MLME to initiate a channel scan to search for activity within the POS
* of the device. This primitive can be used to perform an ED scan to determine channel
* usage, an active or passive scan to locate beacon frames containing any PAN identifier,
* or an orphan scan to locate a PAN to which the device is currently associated.
*
* @param[in] req MLME-SCAN request structure.
* @param[in] conf_cb pointer to user callback.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.11.1
*/
void mlme_scan_req(mlme_scan_req_t * req, mlme_scan_conf_cb_t conf_cb);
/** @} */
#endif // MAC_MLME_SCAN_H_INCLUDED

View File

@ -0,0 +1,150 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_MLME_START_H_INCLUDED
#define MAC_MLME_START_H_INCLUDED
#if (CONFIG_START_ENABLED == 1)
#include <stdint.h>
#include "mac_common.h"
#include "sys_utils.h"
#include "mac_task_scheduler.h"
/** @file
* The MAC MLME Start module declares the MAC Start primitives and necessary types
* according to the MAC specification.
*
* @defgroup mac_start MAC MLME Start API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC MLME Start API.
* @details The MAC Start module declares MLME Start primitives and necessary types according to
* the MAC specification. More specifically, MLME Start request aka mlme_start_req(), and MLME
* Start confirm callback typedef aka mlme_start_conf_cb_t primitives are declared.
*/
/**@brief MLME-Start.confirm
*
* @details The MLME-Start.confirm primitive reports the results of a request
* to start the device.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.14.1.2
*/
typedef struct
{
mac_status_t status; /**< Status of operation. */
} mlme_start_conf_t;
/**
* @brief MLME-START.request
*
* @details The MLME-START.request primitive allows the PAN coordinator
* to initiate a new PAN or to start using a new superframe configuration.
* This primitive may also be used by a device already associated with an
* existing PAN to start using a new superframe configuration.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.14.1.1
*/
typedef struct
{
/** Do not edit this field. */
mac_abstract_req_t service;
/** Confirm to this request. */
mlme_start_conf_t confirm;
uint16_t pan_id; /**< PAN ID. */
uint8_t logical_channel; /**< Logical channel. */
#ifdef CONFIG_SUB_GHZ
uint8_t channel_page; /**< Channel page. */
#endif
uint32_t start_time; /**< Start time. */
uint8_t beacon_order; /**< Beacon order. */
uint8_t superframe_order; /**< Superframe order. */
bool pan_coordinator; /**< Is PAN Coordinator? */
bool battery_life_extension; /**< Is battery life long? */
bool coord_realignment; /**< Is coordinator realignment? */
#if (CONFIG_SECURE == 1)
/* The security parameters for the coordinator realignment are declared below. */
uint8_t coord_realign_security_level; /**< Security level. */
uint8_t coord_realign_key_id_mode; /**< Key ID mode. */
uint64_t coord_realign_key_source; /**< Key source. */
uint8_t coord_realign_key_index; /**< Key index. */
/* The security parameters for the beacon are declared below. */
uint8_t beacon_security_level; /**< Security level. */
uint8_t beacon_key_id_mode; /**< Key ID mode. */
uint64_t beacon_key_source; /**< Key source. */
uint8_t beacon_key_index; /**< Key index. */
#endif
} mlme_start_req_t;
/**
* @brief Callback to the next higher layer.
*
* @details After request completion, passed callback
* will be issued with status provided as a parameter.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.14.2.2
*/
typedef void (* mlme_start_conf_cb_t)(mlme_start_conf_t *);
/**
* @brief MLME-START request.
*
* @details Generated by the next higher layer and issued to its MLME to
* request that a device starts using a new superframe configuration.
*
* @param[in] req MLME-START request structure.
* @param[in] conf_cb pointer to user callback.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.14.1.2
*/
void mlme_start_req(mlme_start_req_t * req, mlme_start_conf_cb_t conf_cb);
/** @} */
#endif // (CONFIG_START_ENABLED == 1)
#endif // MAC_MLME_START_H_INCLUDED

View File

@ -0,0 +1,153 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_MLME_SYNC_H_INCLUDED
#define MAC_MLME_SYNC_H_INCLUDED
#if (CONFIG_SYNC_ENABLED == 1)
#include <stdint.h>
#include "mac_common.h"
#include "mac_task_scheduler.h"
/** @file
* The MAC MLME Sync module declares the MAC Sync primitives and necessary types
* according to the MAC specification.
*
* @defgroup mac_sync MAC MLME Sync API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC MLME Sync API.
* @details The MAC Sync module declares MLME Sync and sync loss primitives and necessary types according to
* the MAC specification. More specifically, MLME Sync request aka mlme_sync_req(), and MLME
* Sync Loss indication aka mlme_sync_loss_ind() primitives are declared.
*/
/**@brief Sync Loss reason enumeration. */
typedef enum
{
MAC_SYNC_BEACON_LOST, /**< Beacon lost. */
MAC_SYNC_REALIGNMENT, /**< Realignment. */
MAC_SYNC_PAN_ID_CONFLICT /**< PAN ID Conflict. */
} mlme_sync_loss_reason_t;
/**
* @brief MLME-SYNC-LOSS.indication
*
* @details On receipt of the MLME-SYNC-LOSS.indication primitive, the next
* higher layer is notified of a loss of synchronization.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.15.2
*/
typedef struct
{
mlme_sync_loss_reason_t loss_reason; /**< Loss reason. */
uint16_t pan_id; /**< PAN ID. */
uint8_t logical_channel; /**< Logical channel. */
#ifdef CONFIG_SUB_GHZ
uint8_t channel_page; /**< Channel page. */
#endif
#if (CONFIG_SECURE == 1)
uint8_t security_level; /**< Security level. */
uint8_t key_id_mode; /**< Key ID mode. */
uint64_t key_source; /**< Key source. */
uint8_t key_index; /**< Key index. */
#endif
} mlme_sync_loss_ind_t;
#if (CONFIG_SYNC_REQ_ENABLED == 1)
/**
* @brief MLME-SYNC.request
*
* @details The MLME-SYNC.request primitive is generated by the next higher
* layer of a device on a beacon-enabled PAN and issued to its MLME to
* synchronize with the coordinator.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.15.1
*/
typedef struct
{
/** Do not edit this field. */
mac_abstract_req_t service;
uint8_t logical_channel; /**< Logical channel. */
#ifdef CONFIG_SUB_GHZ
uint8_t channel_page; /**< Channel page. */
#endif
bool track_beacon; /**< Track beacon? */
} mlme_sync_req_t;
/**
* @brief MLME-SYNC-LOSS indication.
*
* @details Generated by the MLME of a device and issued to its next
* higher layer in the event of a loss of synchronization with the
* coordinator. It is also generated by the MLME of the PAN coordinator
* and issued to its next higher layer in the event of a PAN ID conflict.
*
* @param[in] ind MLME-SYNC-LOSS indication structure.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.7.4
*/
extern void mlme_sync_loss_ind(mlme_sync_loss_ind_t * ind);
/**
* @brief MLME-SYNC request.
*
* @details Generated by the next higher layer of a device on a
* beacon-enabled PAN and issued to its MLME to synchronize with
* the coordinator.
*
* @param[in] req MLME_SYNC request structure.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.1.15.1
*/
void mlme_sync_req(mlme_sync_req_t * req);
#endif // (CONFIG_SYNC_REQ_ENABLED == 1)
/** @} */
#endif // (CONFIG_SYNC_ENABLED == 1)
#endif // MAC_MLME_SYNC_H_INCLUDED

View File

@ -0,0 +1,82 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_PANID_CONFLICT_H_INCLUDED
#define MAC_PANID_CONFLICT_H_INCLUDED
#if (CONFIG_PANID_CONFLICT_ENABLED == 1)
#include "mac_common.h"
/** @file
* @defgroup mac_pan_id PAN ID Conflict API
* @ingroup mac_15_4
* @{
* @brief Module for handling PAN ID conflicts.
*/
/**
* @brief A callback function used to notify Pan ID conflict detection algorithm about
* a new beacon frame.
*
* @param p_beacon - pointer to beacon descriptor struct.
*/
void mac_panid_conflict_beacon_notify_ind(const mac_beacon_ind_t * p_beacon);
#if (CONFIG_PANID_CONFLICT_RESOLUTION_ENABLED == 1)
/**@brief Callback function which handles end of Pan ID conflict cmd TX,
* called by FP
* @param[in] status Confirmation status to be raised
*/
void mac_panid_conflict_cb(mac_status_t status);
#endif
/**@brief Indicates whether the pan id conflict was detected
*
* @return Result of pan id conflict detection
*/
bool mac_panid_conflict_detected(void);
/** @} */
#endif
#endif /* MAC_PANID_CONFLICT_H_INCLUDED */

View File

@ -0,0 +1,318 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_SECURITY_H_INCLUDED
#define MAC_SECURITY_H_INCLUDED
#include "sys_queue.h"
#include "sec_aes_ccm.h"
/** @file
* The MAC MLME Security module declares the MAC Security types
* according to the MAC specification.
*
* @defgroup mac_security MAC MLME Security API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC MLME Security API.
* @details The MAC Security module declares types/macros needed to implement and use the MAC security
* engine according to the MAC specification. No routines or callbacks are declared here.
*/
/**
* @brief MAC sublayer security levels.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.6.2.2.1
*/
typedef enum
{
MAC_SEC_OFF = 0, /**< Security is OFF. */
MAC_SEC_MIC32, /**< MIC32 security. */
MAC_SEC_MIC64, /**< MIC64 security. */
MAC_SEC_MIC128, /**< MIC128 security. */
MAC_SEC_ENC, /**< ENC security. */
MAC_SEC_ENC_MIC32, /**< ENC/MIC32 security. */
MAC_SEC_ENC_MIC64, /**< ENC/MIC64 security. */
MAC_SEC_ENC_MIC128 /**< ENC/MIC128 security. */
} mac_security_level_t;
/**
* @brief MAC key identifier mode.
*
* In accordance with IEEE Std 802.15.4-2006, section 7.6.2.2.2
*/
typedef enum
{
MAC_KEY_ID_IMPL = 0, /**< Impl. */
MAC_KEY_ID_ONE_OCTET, /**< One octet. */
MAC_KEY_ID_FOUR_OCTET, /**< 4 octets. */
MAC_KEY_ID_EIGHT_OCTET /**< 8 octets. */
} mac_key_id_mode_t;
/**@brief Size (in bytes) of short security look up item. This size is
* set when lookup size equals to 0.
*/
#define MAC_LOOKUP_DATA_SIZE_SHORT 5
/**@brief Size (in bytes) of long security Key look up item. This size is
* set when lookup size equals to 1.
*/
#define MAC_KEY_LOOKUP_DATA_SIZE_LONG 9
/**@brief Size (in bytes) of long security Data look up item. This size is
* set when lookup size equals to 1.
*/
#define MAC_DATA_LOOKUP_DATA_SIZE_LONG 8
/**@brief Length of \a mac_key_source_t. Equals to extended address length. */
#define MAC_KEY_SOURCE_SIZE 8
/**@brief This bit-mask is used to get UniqueDevice field value of
* \a mac_key_device_descr_t.
*/
#define MAC_KEY_DEVICE_FLAG_UNIQUE 0x01
/**@brief This bit-mask is used to get BlackListed field value of
* \a mac_key_device_descr_t.
*/
#define MAC_KEY_DEVICE_FLAG_BLACKLISTED 0x02
/**@brief Length of key. */
#define MAC_SECURITY_KEY_SIZE 16
/**@brief Length of nonce for aes-ccm algorithm .*/
#define MAC_SECURITY_NONCE_SIZE 13
/**@brief Maximum MIC size .*/
#define MAX_MIC_SIZE 16
/**@brief This type is used to store security key .*/
typedef uint8_t mac_key_t[MAC_SECURITY_KEY_SIZE];
/**@brief This type is used to store security key lookup data .*/
typedef uint8_t mac_key_lookup_data_t[MAC_KEY_LOOKUP_DATA_SIZE_LONG];
/**@brief This type is used to store security data lookup data .*/
typedef uint8_t mac_data_lookup_data_t[MAC_DATA_LOOKUP_DATA_SIZE_LONG];
/**@brief This type is used to store security key source address .*/
typedef uint64_t mac_key_source_t;
/**@brief This type represents key LookupDataSize according to Table 94 .*/
typedef enum
{
KEY_LOOKUP_SIZE_FIVE = 0, /**< Size is 5. */
KEY_LOOKUP_SIZE_NINE = 1 /**< Size is 9. */
} mac_key_lookup_size_t;
/**@brief This type represents real size of key LookupData .*/
typedef enum
{
KEY_LOOKUP_SIZE_FIVE_VAL = 5, /**< Size is 5. */
KEY_LOOKUP_SIZE_NINE_VAL = 9 /**< Size is 9. */
} mac_key_lookup_size_val_t;
/**@brief This type represents data LookupDataSize .*/
typedef enum
{
DATA_LOOKUP_SIZE_FOUR_VAL = 4, /**< Size is 4. */
DATA_LOOKUP_SIZE_EIGHT_VAL = 8 /**< Size is 8. */
} mac_data_lookup_size_val_t;
/**@brief Abstract type to work with growing tables such as some of MAC
* security attributes.
*/
typedef struct
{
sys_queue_t queue; /**< Service field .*/
uint8_t size; /**< Number of currently allocated
items inside the table .*/
} mac_table_t;
/**@brief Due to processing algorithm this field MUST be the first inside a
* table or list.
*/
typedef struct
{
sys_queue_item_t item; /**< Service field .*/
uint8_t idx; /**< Index inside table .*/
} mac_table_item_t;
/**@brief KeyIdLookupDescriptor as described in Table 94 .*/
typedef struct
{
mac_table_item_t table_service; /**< Service field .*/
mac_key_lookup_data_t data; /**< Set of 5 or 9 bytes.
Data used to identify the key .*/
mac_key_lookup_size_t size; /**< A value of LOOKUP_SIZE_FIVE indicates a set
of 5 bytes; a value of LOOKUP_SIZE_NINE
indicates a set of 9 bytes .*/
} mac_key_id_lookup_descr_t;
/**@brief KeyIdLookupLis as described in Table 89 .*/
typedef mac_table_t mac_key_id_lookup_list_t;
/**@brief DeviceDescriptor as described in Table 93 .*/
typedef struct
{
mac_table_item_t table_service; /**< Service field .*/
uint16_t pan_id; /**< The 16-bit PAN identifier of the device in
this DeviceDescriptor .*/
uint16_t short_address; /**< The 16-bit short address of the device in
this DeviceDescriptor. A value of
#MAC_EXTENDED_ADDRESS_ONLY
indicates that this device is using only its
extended address. A value of
#MAC_BROADCAST_SHORT_ADDRESS
indicates that this value is unknown .*/
uint64_t extended_address; /**< The 64-bit IEEE extended address of the
device in this DeviceDescriptor. This
element is also used in unsecuring
operations on incoming frames .*/
uint32_t frame_counter; /**< The incoming frame counter of the device
in this DeviceDescriptor. This value is used
to ensure sequential freshness of frames .*/
bool exempt; /**< Indication of whether the device may
override the minimum security level
settings defined in \a mac_security_level_table_t .*/
} mac_device_descr_t;
/**@brief DeviceTable as described in Table 93 .*/
typedef mac_table_t mac_device_table_t;
/**@brief KeyDeviceDescriptor as described in Table 91 .*/
typedef struct
{
mac_table_item_t table_service; /**< Service field .*/
uint8_t device_handle; /**< Handle to the DeviceDescriptor
corresponding to the device (see
\a mac_device_descr_t).
The value is an index of the device descriptor
instance from device table .*/
uint8_t unique_device : 1; /**< Indication of whether the device indicated
by DeviceDescriptorHandle is uniquely
associated with the KeyDescriptor, i.e., it
is a link key as opposed to a group key .*/
uint8_t blacklisted : 1; /**< Indication of whether the device indicated
by DeviceDescriptorHandle previously
communicated with this key prior to the
exhaustion of the frame counter. If TRUE,
this indicates that the device shall not use
this key further because it exhausted its
use of the frame counter used with this
key .*/
} mac_key_device_descr_t;
/**@brief KeyDeviceList as described in Table 89 .*/
typedef mac_table_t mac_key_device_list_t;
/**@brief KeyUsageDescriptor as described in Table 90 .*/
typedef struct
{
mac_table_item_t table_service; /**< Service field .*/
uint8_t frame_type : 3; /**< See \a mac_frame_type_t .*/
uint8_t cmd_frame_id : 4; /**< See \a mac_command_id_t .*/
} mac_key_usage_descr_t;
/**@brief KeyUsageList as described in Table 89 .*/
typedef mac_table_t mac_key_usage_list_t;
/**@brief KeyDescriptor as described in Table 89 .*/
typedef struct
{
mac_table_item_t table_service; /**< Service field .*/
mac_key_id_lookup_list_t id_lookup_list; /**< A list of KeyIdLookupDescriptor entries
used to identify this KeyDescriptor .*/
mac_key_device_list_t key_device_list; /**< A list of KeyDeviceDescriptor entries
indicating which devices are currently
using this key, including their blacklist
status .*/
mac_key_usage_list_t key_usage_list; /**< A list of KeyUsageDescriptor entries
indicating which frame types this key may
be used with .*/
mac_key_t key; /**< The actual value of the key .*/
} mac_key_descr_t;
/**@brief KeyTable as described in Table 88 .*/
typedef mac_table_t mac_key_table_t;
/**@brief SecurityLevelDescriptor as described in Table 93 .*/
typedef struct
{
mac_table_item_t table_service; /**< Service field. */
uint16_t frame_type : 3; /**< See \a mac_frame_type_t .*/
uint16_t cmd_frame_id : 4; /**< See \a mac_command_id_t .*/
uint16_t security_min : 3; /**< The minimal required/expected security
level for incoming MAC frames with the
indicated frame type and, if present,
command frame type (see
\a mac_security_level_t) .*/
uint16_t override_min : 1; /**< Indication of whether originating devices
for which the Exempt flag is set may
override the minimum security level
indicated by the SecurityMinimum
element. If TRUE, this indicates that for
originating devices with Exempt status,
the incoming security level zero is
acceptable, in addition to the incoming
security levels meeting the minimum
expected security level indicated by the
SecurityMinimum element .*/
} mac_security_level_descr_t;
typedef mac_table_t mac_security_level_table_t;
/** @} */
#endif // MAC_SECURITY_H_INCLUDED

View File

@ -0,0 +1,205 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_TASK_SCHEDULER_H_INCLUDED
#define MAC_TASK_SCHEDULER_H_INCLUDED
#include <stdint.h>
#include "sys_queue.h"
#include "sys_time.h"
/** @file
*
* @defgroup mac_task_scheduler MAC task scheduler
* @ingroup mac_15_4
* @{
* @brief Module for MAC task scheduling.
*/
/**@brief Identifiers for external requests.
*/
typedef enum
{
#if (CONFIG_PURGE_ENABLED == 1)
MAC_PURGE_REQ_ID,
#endif
#if (CONFIG_ASSOCIATE_REQ_ENABLED == 1)
MAC_ASSOCIATE_REQ_ID,
#endif
#if (CONFIG_DISASSOCIATE_ENABLED == 1)
MAC_DISASSOCIATE_REQ_ID,
#endif
MAC_GET_REQ_ID,
#if (CONFIG_GTS_ENABLED == 1)
MAC_GTS_REQ_ID,
#endif
MAC_RESET_REQ_ID,
#if (CONFIG_RXE_ENABLED == 1)
MAC_RX_ENABLE_REQ_ID,
#endif
MAC_SCAN_REQ_ID,
MAC_SET_REQ_ID,
#if (CONFIG_SYNC_REQ_ENABLED == 1)
MAC_SYNC_REQ_ID,
#endif
MAC_POLL_REQ_ID,
#if (CONFIG_START_ENABLED == 1)
MAC_START_REQ_ID,
#endif
MAC_DATA_REQ_ID,
#if (CONFIG_ORPHAN_ENABLED == 1)
MAC_ORPHAN_RESP_ID,
#endif
MAC_REQS_AMOUNT
} mac_req_id_t;
/**@brief Identifiers for internal handlers.
*
* These handlers are used for private MAC task scheduling.
*/
typedef enum
{
#if (CONFIG_FFD_DEVICE == 1) && (CONFIG_BEACON_ENABLED == 1)
MAC_SUPERFRAME_OUT_TASK_ID,
#endif
MAC_CSMA_CA_TASK_ID,
#if (CONFIG_START_ENABLED == 1)
MAC_START_TASK_ID,
#endif
MAC_FP_TX_TASK_ID,
MAC_DATA_DIR_CONF_ID,
#if (CONFIG_INDIRECT_ENGINE_ENABLED == 1)
MAC_INDIR_ENGINE_REQ_ID,
#endif
MAC_FP_RX_TASK_ID,
#if (CONFIG_ORPHAN_ENABLED == 1)
MAC_ORPHAN_IND_ID,
#endif
#if (CONFIG_DISASSOCIATE_ENABLED == 1)
MAC_DISASSOC_IND_ID,
#endif
#if (CONFIG_SYNC_ENABLED == 1)
MAC_SYNC_LOSS_IND_ID,
#endif
MAC_GET_CONF_ID,
MAC_SET_CONF_ID,
MAC_REQ_QUEUE_TASK_ID,
MAC_POLL_TASK_ID,
MAC_SCAN_CONF_ID,
MAC_MEM_ALLOCATOR_TASK_ID,
MAC_TASKS_AMOUNT
} mac_task_id_t;
/**@brief MAC request descriptor.
*/
typedef struct
{
sys_queue_item_t item;
mac_req_id_t id;
void * p_conf_cb; //pointer to confirmation primitive
} mac_abstract_req_t;
/**@brief scheduler memory.
*/
typedef struct
{
sys_queue_t outer_req_queue;
volatile uint32_t pending_tasks;
bool mac_scheduler_busy;
} mac_scheduler_mem_t;
/**@brief MAC task handler prototype.
*
* @details Handler which will be called by the MAC scheduler.
*/
typedef void (* mac_task_handler_t)(void);
/**@brief MAC external requests queue task handler prototype.
*
* @details Handler which will be called by the MAC scheduler inside
* corresponding task handler.
*/
typedef void (* mac_req_handler_t)(mac_abstract_req_t *);
/**@brief Initialize MAC scheduler.
*
* @details Clean up MAC request's queue.
*/
void mac_init(void);
/**@brief MAC task handler.
*
* @details Handler invokes a MAC primitives routine for a request according to
* the requests identification.
*/
void mac_task_handler(void);
/**@brief Scheduler request from some MAC primitive.
*
* @details Place request to MAC scheduler queue for a further handling.
*
* @param[in] p_req Pointer to a request structure.
*/
void mac_request_schedule(mac_abstract_req_t * p_req);
/**@brief Internal function of MAC API.
*
* This function is used to post tasks between MAC primitives.
*
* @param[in] id MAC task ID.
*
*/
void mac_internal_task_post(mac_task_id_t id);
/**@brief Internal function of MAC API.
*
* Notifies mac scheduler that incoming request has been completely
* served and may be safely removed from MAC task queue.
*
* @param[in] p_req Pointer to a request structure.
*/
void mac_close_request(mac_abstract_req_t * p_req);
/** @} */
#endif // MAC_TASK_SCHEDULER_H_INCLUDED

View File

@ -0,0 +1,151 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef MAC_TIME_H_INCLUDED
#define MAC_TIME_H_INCLUDED
#include <stdint.h>
#include "sys_time.h"
#include "hal_timer.h"
#include "hal_timer_critical.h"
#include "sys_debug.h"
/** @file
* The MAC Time module declares some useful macros/types and routines that deal with the MAC
* timer.
*
* @defgroup mac_time MAC Time API
* @ingroup mac_15_4
* @{
* @brief Module to declare MAC Time API.
* @details The MAC Time module declares some useful macros/types and routines that deal with the MAC
* timer. More specifically, some convertion routines such as mac_timestamp_from_systime(),
* mac_time_from_us(), and mac_time_to_us() are declared here.
*/
/**@brief This mask shall always be used after any mathematical operation on
* mac_time_t to avoid overflow.
*/
#define MAC_TIME_MASK 0xFFFFFFULL
/**@brief Type of MAC time in symbols. */
typedef uint32_t mac_time_t;
/**@brief Type is used to save timestamps with microsecond precision. */
typedef uint32_t mac_timestamp_t;
/**@brief Gets timestamp from system time.
*
* @param[in] time_us System time.
*
* @return Time in us but smaller type size.
*/
static inline mac_timestamp_t mac_timestamp_from_systime(sys_time_t time_us)
{
return (mac_timestamp_t)time_us;
}
/**@brief Converts microseconds to symbol time.
*
* @details Symbol time is measured in PHY Symbol Periods (16 us).
*
* @param[in] time_us Time in microseconds.
*
* @return Time in PHY Symbol Periods (16 us).
*/
static inline mac_time_t mac_time_from_us(sys_time_t time_us)
{
return (mac_time_t)((time_us >> 4ull) & MAC_TIME_MASK);
}
/**@brief Converts symbol time to microseconds.
*
* @details Symbol time is measured in PHY Symbol Periods (16 us).
*
* @param[in] time_symbol Time in PHY Symbol Periods (16 us).
*
* @return Time in microseconds.
*/
static inline sys_time_t mac_time_to_us(mac_time_t time_symbol)
{
return time_symbol << 4u;
}
/**@brief Starts the critical MAC timer.
*
* @details The callback function of the critical MAC timer will be called from
* the timer's interrupt routine. Only one critical MAC timer can run
* at the same time.
*
* @warning This is internal MAC functionality, needed for the realtime channel access.
* This function must not be used by other modules.
*
* @param[in] interval_us Interval in microseconds, after which the callback
* function will be called.
* @param[in] callback Callback function to be called after the specified inteval.
*/
static inline void mac_timer_critical_start(sys_time_t interval_us, void (* callback)(void))
{
// Make sure interval_us fits into 32 bits, since hardware critical timer is 32 bit.
ASSERT(interval_us < (1ULL << 32));
hal_timer_critical_start((uint32_t)interval_us, callback);
}
/**@brief Stops the critical MAC timer.
*
* @details After critical MAC timer is stopped with this function, its callback will not be called.
*
* @warning This is internal MAC functionality, needed for the realtime channel access.
* This function must not be used by other modules.
*/
static inline void mac_timer_critical_stop(void)
{
hal_timer_critical_stop();
}
/** @} */
#endif // MAC_TIME_H_INCLUDED

View File

@ -0,0 +1,240 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PHY_COMMON_H_INCLUDED
#define PHY_COMMON_H_INCLUDED
/** @file
* This file contains declarations of commonly used PHY routines and necessary macros/types.
*
* @defgroup phy_common PHY Common API
* @ingroup phy_15_4
* @{
* @brief Module to declare Common PHY API
* @details The Common PHY module contains declarations of commonly used PHY routines and necessary macros/types.
*/
/**@brief The maximum PSDU size (in octets) the PHY shall be able to receive (aMaxPHYPacketSize).
*
* @details See Table 22 - PHY constants.
*/
#define PHY_MAX_PACKET_SIZE 127
/**@brief The maximum PHR size (in octets).
*
* @details See 6.3 PPDU format.
*/
#define PHY_MAX_HEADER_SIZE 1
/**@brief Maximum PPDU size */
#define PHY_MAX_PPDU_SIZE (PHY_MAX_HEADER_SIZE + PHY_MAX_PACKET_SIZE)
/**@brief Position of PHY header related to income PPDU start pointer.*/
#define PHY_HEADER_POS (-1)
/**@brief Size of PHY header in bytes.*/
#define PHY_HEADER_SIZE 1
/**@brief Maximum channel number.*/
#define PHY_MAX_CHANNEL_NUM 0x1Au
/**@brief Minimum channel number.*/
#define PHY_MIN_CHANNEL_NUM 0x0Bu
// for 2400 MHz O-QPSK 1 octet = 2 symbols 1 symbol = 32bits chip
#define aMaxPHYPacketSize PHY_MAX_PACKET_SIZE // in octets
#define aTurnaroundTime 12 // in symbols
#define aTurnaroundTimeUs 192 // in us
// Read only parameters
#define PHY_CURRENT_PAGE 0x0u
#define PHY_CHANNEL_SUPPORTED 0x07FFF800ul
#define PHY_SHR_DURATION 10u
#define PHY_MAX_FRAME_DURATION (PHY_SHR_DURATION + (int)((aMaxPHYPacketSize + 1) * PHY_SYMBOLS_PER_OCTET))
#define PHY_SYMBOLS_PER_OCTET 2u
// CCA values
#define PHY_TRX_CCA_MODE0 0
#define PHY_TRX_CCA_MODE1 1
#define PHY_TRX_CCA_MODE2 2
#define PHY_TRX_CCA_MODE3 3
/** @brief Minimum value that can be used to set radio transmit power. Equals
* to -32 dBm.
*
* This is a combination of digits which includes:
* 2 MSBs represent the tolerance on the transmit power
* 6 LSBs which may be written to, represent a signed integer in twos-complement format,
* corresponding to the nominal transmit power of the device in decibels relative to 1 mW.
* All combinations less than 0xBF are valid.
*/
#define PHY_MIN_TX_POWER 0x20
/** @brief Internal parameter of the PHY layer.
*
* @details Position of the sign bit inside transmit power attribute.*/
#define PHY_TRANSMIT_POWER_SIGN_BIT_POS 5
/** @brief Internal parameter of the PHY layer.
*
* @details This mask hides transmit power from transmit power attribute value,
* but leaves precision bitfield.
*/
#define PHY_TRANSMIT_POWER_MASK 0xC0
/** @brief Internal parameter of the PHY layer.
*
* @details This mask hides precision bitfield from transmit power attribute value,
* leaving transmit power unchanged.
*/
#define PHY_TRANSMIT_POWER_MASK_INV 0x3F
// Possible transmit power
#define DBM_11 ( 11 & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_10 ( 10 & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_9 ( 9 & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_8 ( 8 & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_7 ( 7 & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_6 ( 6 & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_5 ( 5 & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_4 ( 4 & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_3 ( 3 & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_2 ( 2 & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_1 ( 1 & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_0 ( 0 & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_1 (( -1) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_2 (( -2) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_3 (( -3) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_4 (( -4) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_5 (( -5) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_6 (( -6) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_7 (( -7) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_8 (( -8) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_9 (( -9) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_10 ((-10) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_11 ((-11) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_12 ((-12) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_13 ((-13) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_14 ((-14) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_15 ((-15) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_16 ((-16) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_17 ((-17) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_18 ((-18) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_19 ((-19) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_20 ((-20) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_21 ((-21) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_22 ((-22) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_23 ((-23) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_24 ((-24) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_25 ((-25) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_26 ((-26) & PHY_TRANSMIT_POWER_MASK_INV)
#define DBM_MIN_27 ((-27) & PHY_TRANSMIT_POWER_MASK_INV)
/**@brief Common PHY enumerations description used in various PHY primitives.
*
* @details See Table 18-PHY enumerations description for detailed info on the statuses up to PHY_READ_ONLY.
* The statuses with higher numbers are implementation specific and used for synchronous API only.
*/
typedef enum
{
/** The CCA attempt has detected a busy channel. */
PHY_BUSY = 0x00,
/** The transceiver is asked to change its state while receiving. */
PHY_BUSY_RX = 0x01,
/** The transceiver is asked to change its state while transmitting. */
PHY_BUSY_TX = 0x02,
/** The transceiver is to be switched off immediately. */
PHY_FORCE_TRX_OFF = 0x03,
/** The CCA attempt has detected an idle channel. */
PHY_IDLE = 0x04,
/** A SET/GET request was issued with a parameter in the primitive that is
out of the valid range. */
PHY_INVALID_PARAMETER = 0x05,
/** The transceiver is in or is to be configured into the receiver enabled state. */
PHY_RX_ON = 0x06,
/** A SET/GET, an ED operation, or a transceiver state change was successful. */
PHY_SUCCESS = 0x07,
/** The transceiver is in or is to be configured into the transceiver disabled state. */
PHY_TRX_OFF = 0x08,
/** The transceiver is in or is to be configured into the transmitter enabled state. */
PHY_TX_ON = 0x09,
/** A SET/GET request was issued with the identifier of an attribute that is not supported. */
PHY_UNSUPPORTED_ATTRIBUTE = 0x0A,
/** A SET/GET request was issued with the identifier of an attribute that is read-only.*/
PHY_READ_ONLY = 0x0B,
/* Statuses out of the standard. They are used for synchronous API */
/** Transceiver is forced to change it's state to PHY_TX_ON (potential packet drop). */
PHY_FORCE_TX_ON = 0xFC,
/** Data cannot be sent due to failed CCA results.*/
PHY_CHANNEL_ACCESS_FAILURE = 0xFD,
/** Data had been sent but ACK frame hasn't been received.*/
PHY_NO_ACK = 0xFE,
/** PHY is not available for synchronous access */
PHY_IS_NOT_AVAILABLE = 0xFF
} phy_enum_t;
/**@brief PHY status type.*/
typedef phy_enum_t phy_status_t;
/** @} */
#endif // PHY_COMMON_H_INCLUDED

View File

@ -0,0 +1,187 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PHY_PD_DATA_H_INCLUDED
#define PHY_PD_DATA_H_INCLUDED
#include <stdint.h>
#include <stdbool.h>
#include "sys_utils.h"
#include "sys_time.h"
#include "phy_common.h"
#include "mac_time.h"
#include "sys_queue.h"
/** @file
* This file contains declarations of PHY Data transmission routines and necessary types.
*
* @defgroup phy_data PHY Data API
* @ingroup phy_15_4
* @{
* @brief Module to declare PHY Data API
* @details The PHY Data module declares the PHY Data transmission routines and necessary types according to
* the PHY specification. More specifically, PHY data request pd_data_req(), PHY data confirm
* pd_data_conf(), and PHY Data indication pd_data_ind() primitives are declared.
*/
/**@brief PD-DATA.request parameters.
*
* @details See 6.2.1.1 PD-DATA.request.
* See Table 6 - PD-DATA.request parameters.
*/
typedef struct
{
/** The set of octets forming the PSDU to be transmitted by the PHY entity. */
uint8_t * psdu;
/** The number of octets contained in the PSDU to be transmitted by the PHY entity.
Valid range: less or equal to @ref PHY_MAX_PACKET_SIZE. */
uint8_t psdu_length;
} pd_data_req_t;
/**@brief Private information which is passed with PD-DATA.confirm.
* Not covered by standard.
*/
typedef struct
{
/** pending value to store pending bit value if frame was acknowledged. */
bool pending;
} pd_data_conf_private_t;
/**@brief PD-DATA.confirm parameters.
*
* @details See 6.2.1.2 PD-DATA.confirm.
* See Table 7 - PD-DATA.confirm parameters.
*/
typedef struct
{
/** Service field. */
pd_data_conf_private_t service;
/** The result of the request to transmit a packet.
* Valid range: PHY_SUCCESS, PHY_RX_ON, PHY_TRX_OFF, PHY_BUSY_TX.
* See @ref phy_enum_t.
*
* When radio chip successfully transmits data, but cannot receive
* ACK in FAST_ACK mode, the result is PHY_TX_ON.
*/
phy_enum_t status;
} pd_data_conf_t;
/**@brief Private information which is passed with PD-DATA.indication.
* Not covered by standard.
*/
typedef struct
{
/** RSSI value, which corresponds to packet that caused this indication. */
int8_t rssi;
/** Buffer to store incoming frame. */
uint8_t frame_buffer[PHY_MAX_PACKET_SIZE + PHY_MAX_HEADER_SIZE];
/** Timestamp of the moment when PHY header octet reception has been started. */
mac_timestamp_t timestamp;
/** This field allows storing instances of this structure in a queue. */
sys_queue_item_t queue_item;
#ifdef CONFIG_PHY_CERT_CRC_HOOK
bool crc_status;
#endif
} pd_data_ind_private_t;
/**@brief PD-DATA.indication parameters.
*
* @details See 6.2.1.3 PD-DATA.indication.
* See Table 8 - PD-DATA.indication parameters.
*/
typedef struct
{
/** Service field. */
pd_data_ind_private_t service;
/** The set of octets forming the PSDU received by the PHY entity. */
uint8_t * psdu;
/** The number of octets contained in the PSDU received by the PHY entity.
Valid range: less or equal to @ref PHY_MAX_PACKET_SIZE. */
uint8_t psdu_length;
/** Link quality (LQI) value measured during reception of the PPDU (see 6.9.8).
Valid range: 0x00 - 0xFF. */
uint8_t ppdu_link_quality;
} pd_data_ind_t;
/**@brief PD-DATA.request primitive.
*
* @details The PD-DATA.request primitive requests the transfer of an MPDU (i.e., PSDU)
* from the MAC sublayer to the local PHY entity.
* See 6.2.1.1 PD-DATA.request.
*
* @param[in] req Pointer to PD-DATA.request parameters. See @ref pd_data_req_t.
*/
void pd_data_req(pd_data_req_t * req);
/**@brief PD-DATA.confirm primitive.
*
* @details Callback function, implemented by the next higher layer,
* which handles the PD-DATA.confirm primitive.
* See 6.2.1.2 PD-DATA.confirm.
*
* @param[out] conf Pointer to PD-DATA.confirm parameters. See @ref pd_data_conf_t.
*/
void pd_data_conf(pd_data_conf_t * conf);
/**@brief PD-DATA.indication primitive.
*
* @details The PD-DATA.indication primitive indicates the transfer of an MPDU (i.e., PSDU)
* from the PHY to the local MAC sublayer entity.
* See 6.2.1.3 PD-DATA.indication.
* This function must be implemented by the next higher layer.
*
* @param[out] ind Pointer to PD-DATA.indication parameters. See @ref pd_data_ind_t.
* Data are valid until next fully received packet.
*/
void pd_data_ind(pd_data_ind_t * ind);
/** @} */
#endif // PHY_PD_DATA_H_INCLUDED

View File

@ -0,0 +1,106 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PHY_PLME_CCA_H_INCLUDED
#define PHY_PLME_CCA_H_INCLUDED
#include <stdint.h>
#include "phy_common.h"
/** @file
* This file contains declarations of Clear Channel Assessment PHY routines and necessary types.
*
* @defgroup phy_cca PHY CCA API
* @ingroup phy_15_4
* @{
* @brief Module to declare PHY Clear Channel Assessment API
* @details The PHY CCA module declares Clear Channel Assessment PHY routines and necessary types according to
* the PHY specification. More specifically, PHY CCA request plme_cca_req(), PHY CCA confirm
* plme_cca_conf() primitives are declared. An additional primitive not covered by the standard is declared.
* This is plme_cca() which is a synchronous version of plme_cca_req().
*/
/**@brief PLME-CCA.confirm parameters
*
* @details The PLME-CCA.confirm primitive is generated by
* the initiating PLME and issued to its next higher layer
* in response to an PLME-CCA.request primitive.
* In accordance with IEEE Std 802.15.4-2006, section 6.2.2.2.1
*/
typedef struct
{
/** One of PHY_TRX_OFF, PHY_BUSY or PHY_IDLE. */
phy_enum_t status;
} plme_cca_conf_t;
/**@brief PLME-CCA.request
*
* @details Request for clear channel assessment.
* In accordance with IEEE Std 802.15.4-2006, section 6.2.2.1
*/
void plme_cca_req(void);
/**@brief PLME-CCA.confirm callback function, implemented by the next higher layer.
*
* @details The PLME-CCA.confirm primitive is generated by the PLME and issued
* to its next higher layer in response to an PLME-CCA.request primitive.
* In accordance with IEEE Std 802.15.4-2006, section 6.2.2.2
*
* @param[out] conf Pointer to PLME-CCA.confirm parameters
*/
void plme_cca_conf(plme_cca_conf_t * conf);
/**@brief Direct (synchronous) PLME-CCA.request
*
* @details Optional. Not covered by a standard.
*
* @return One of PHY_TRX_OFF, PHY_BUSY or PHY_IDLE,
* or implementation defined error code in case of
* unavailability of access to system resources.
*/
phy_enum_t plme_cca(void);
/** @} */
#endif // PHY_PLME_CCA_H_INCLUDED

View File

@ -0,0 +1,110 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PHY_PLME_ED_H_INCLUDED
#define PHY_PLME_ED_H_INCLUDED
#include <stdint.h>
#include "phy_common.h"
/** @file
* This file contains declarations of Energy Detection PHY routines and necessary types.
*
* @defgroup phy_ed PHY ED API
* @ingroup phy_15_4
* @{
* @brief Module to declare PHY Energy Detection API
* @details The PHY ED module declares Energy Detection PHY routines and necessary types according to
* the PHY specification. More specifically, PHY ED request plme_ed_req(), PHY ED confirm
* plme_ed_conf() primitives are declared.
*/
/**@brief Describes the current state of the ED algorithm. */
typedef enum
{
PHY_PLME_ED_STATE_IDLE, /**< Algorithm is idle. */
PHY_PLME_ED_STATE_BUSY /**< Currently performing ED. */
} phy_plme_ed_state_t;
/**@brief This structure holds static data of this module. */
typedef struct
{
phy_plme_ed_state_t state;
} phy_plme_ed_mem_t;
/**@brief PLME-ED.confirm parameters.
*
* @details The PLME-ED.confirm primitive is generated by the PLME and issued
* to its next higher layer in response to an PLME-ED.request primitive.
*
* In accordance with IEEE Std 802.15.4-2006, section 6.2.2.4.1.
*/
typedef struct
{
/** One of PHY_SUCCESS, PHY_TRX_OFF or PHY_TX_ON. */
phy_enum_t status;
/** Energy level for the current channel, if status is SUCCESS. */
uint8_t energy_level;
} plme_ed_conf_t;
/**@brief PLME-ED.request.
*
* @details Request ED measurement for the current channel.
* In accordance with IEEE Std 802.15.4-2006, section 6.2.2.3.
*/
void plme_ed_req(void);
/**@brief The PLME-ED.confirm callback function, implemented by the next higher layer.
*
* @details The PLME-ED.confirm primitive is generated by the PLME and issued
* to its next higher layer in response to an PLME-ED.request primitive.
* In accordance with IEEE Std 802.15.4-2006, section 6.2.2.4.
*
* @param[out] conf Pointer to PLME-ED.confirm parameters
*/
void plme_ed_conf(plme_ed_conf_t * conf);
/** @} */
#endif // PHY_PLME_ED_H_INCLUDED

View File

@ -0,0 +1,212 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PHY_PLME_PIB_H_INCLUDED
#define PHY_PLME_PIB_H_INCLUDED
#include <stdint.h>
#include <stddef.h>
#include "phy_common.h"
/** @file
* This file contains declarations of PHY Information Base routines and necessary types.
*
* @defgroup phy_pib PHY PIB API
* @ingroup phy_15_4
* @{
* @brief Module to declare PHY Information Base API
* @details The PHY PIB module declares PHY Information Base routines and necessary types according to
* the PHY specification. More specifically, PHY PIB Get request plme_get_req(), PHY PIB Set request
* plme_set_req(), PHY PIB Get confirm plme_get_conf(), and PHY PIB Set confirm plme_set_conf()
* primitives are declared. Two additional primitives not covered by the standard are declared. These are
* plme_get() and plme_set() which are synchronous versions of plme_get_req() and plme_set_req() accordingly.
*/
#define PHY_TX_POWER_TOLERANCE_1DB 0x00
#define PHY_TX_POWER_TOLERANCE_3DB 0x40
#define PHY_TX_POWER_TOLERANCE_6DB 0x80
#define PHY_TX_POWER_TOLERANCE_MASK 0xC0
/**
* @brief PHY PIB attribute identificators.
*
* @details In accordance with IEEE Std 802.15.4-2006, section 6.4.2.
*/
typedef enum
{
PHY_CURRENT_CHANNEL_ID = 0x00, /**< Current channel. */
PHY_CHANNELS_SUPPORTED_ID = 0x01, /**< Supported channels. @note read only. */
PHY_TRANSMIT_POWER_ID = 0x02, /**< Transmit power. */
PHY_CCA_MODE_ID = 0x03, /**< CCA mode. */
PHY_CURRENT_PAGE_ID = 0x04, /**< Current page. */
PHY_MAX_FRAME_DURATION_ID = 0X05, /**< MAX Frame duration. @note read only. */
PHY_SHR_DURATION_ID = 0x06, /**< SHR Duration. @note read only. */
PHY_SYMBOLS_PER_OCTET_ID = 0x07, /**< Symbols per octet. @note read only. */
} plme_pib_attr_id_t;
/**
* @brief PHY PIB attribute type sizes.
*
* @details In accordance with IEEE Std 802.15.4-2006, Table 23.
*/
typedef union
{
uint8_t phy_current_channel; /**< Current channel. */
uint32_t phy_channels_supported; /**< Supported channels. */
int8_t phy_transmit_power; /**< Returns one of the DBM_xxx macro values. */
uint8_t phy_cca_mode; /**< CCA mode. */
uint8_t phy_current_page; /**< Current page. */
uint16_t phy_max_frame_duration; /**< MAX Frame duration. */
uint8_t phy_shr_duration; /**< SHR Duration. */
uint16_t phy_symbols_per_octet; /**< Symbols per octet. */
} phy_pib_item_t;
/**@brief PLME-GET.request parameters.
*
* @details In accordance with IEEE Std 802.15.4-2006, section 6.2.2.5.
*/
typedef struct
{
plme_pib_attr_id_t pib_attribute; /**< PIB attribute. */
} plme_get_req_t;
/**@brief PLME-GET.confirm parameters.
*
* @details In accordance with IEEE Std 802.15.4-2006, section 6.2.2.6.
*/
typedef struct
{
phy_status_t status; /**< Status of operation. */
plme_pib_attr_id_t pib_attribute; /**< PIB attribute. */
phy_pib_item_t pib_attribute_value; /**< Attribute value. */
} plme_get_conf_t;
/**@brief PLME-SET.request parameters.
*
* @details In accordance with IEEE Std 802.15.4-2006, section 6.2.2.9.
*/
typedef struct
{
plme_pib_attr_id_t pib_attribute; /**< PIB attribute. */
phy_pib_item_t pib_attribute_value; /**< Attribute value. */
} plme_set_req_t;
/**@brief PLME-SET.confirm parameters.
*
* @details In accordance with IEEE Std 802.15.4-2006, section 6.2.2.10.
*/
typedef struct
{
phy_status_t status; /**< Status of operation. */
plme_pib_attr_id_t pib_attribute; /**< PIB attribute. */
} plme_set_conf_t;
/**@brief PLME-GET.request.
*
* @details In accordance with IEEE Std 802.15.4-2006, section 6.2.2.5.
*
* @param[in] req Pointer to PLME-GET.request parameters. See @ref plme_get_req_t.
*/
void plme_get_req(plme_get_req_t * req);
/**@brief PLME-GET.confirm callback function, implemented by the next higher layer.
*
* @details The PLME-GET.confirm primitive is generated by the PLME and issued
* to its next higher layer in response to an PLME-GET.request primitive.
* In accordance with IEEE Std 802.15.4-2006, section 6.2.2.6.
*
* @param[out] conf Pointer to PLME-GET.confirm parameters. See @ref plme_get_conf_t.
*/
void plme_get_conf(plme_get_conf_t * conf);
/**@brief PLME-SET.request.
*
* @details In accordance with IEEE Std 802.15.4-2006, section 6.2.2.9.
*
* @param[in] req Pointer to PLME-SET.request parameters. See @ref plme_set_req_t.
*/
void plme_set_req(plme_set_req_t * req);
/**@brief PLME-SET.confirm callback function, implemented by the next higher layer.
*
* @details In accordance with IEEE Std 802.15.4-2006, section 6.2.2.10.
*
* @param[out] conf Pointer to PLME-SET.confirm parameters. See @ref plme_set_conf_t.
*/
void plme_set_conf(plme_set_conf_t * conf);
/**
* @brief Getting parameters from PIB directly (without request - confirm approach)
*
* @details Optional. Not covered by a standard.
*
* @param[in] id attribute id.
* @param[out] mem pointer to memory for parameter storing.
*
* @return status of operation.
*/
phy_status_t plme_get(plme_pib_attr_id_t id, void * mem);
/**
* @brief Setting parameters to PIB directly (without request - confirm approach)
*
* @details Optional. Not covered by a standard.
*
* @param[in] id attribute id.
* @param[out] mem pointer to memory for parameter storing.
*
* @return status of operation.
*/
phy_status_t plme_set(plme_pib_attr_id_t id, void * mem);
/** @} */
#endif // PHY_PLME_PIB_H_INCLUDED

View File

@ -0,0 +1,135 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef PHY_PLME_TRX_H_INCLUDED
#define PHY_PLME_TRX_H_INCLUDED
#include <stdint.h>
#include "phy_common.h"
/** @file
* This file contains declarations of PHY TRX routines and necessary types.
*
* @defgroup phy_trx PHY TRX API
* @ingroup phy_15_4
* @{
* @brief Module to declare PHY Transceiver State API
* @details The PHY TRX module declares Transceiver state change PHY routines and necessary types according to
* the PHY specification. More specifically, PHY set TRX state request plme_set_trx_state_req(),
* PHY TRX state change confirm plme_set_trx_state_conf() primitives are declared. An additional
* primitive not covered by the standard is declared. This is plme_set_trx_state() which is a synchronous
* version of plme_set_trx_state_req().
*/
/**
* @brief PLME-SET_TRX_STATE.request parameters.
*
* @details The PLME-SET_TRX_STATE.request primitive is generated
* by the next higher layer of a device and issued to its PLME to
* set transmitter status.
*
* In accordance with IEEE Std 802.15.4-2006, section 6.2.2.7.1
*/
typedef struct
{
/** One of PHY_RX_ON, PHY_TRX_OFF, PHY_FORCE_TRX_OFF, PHY_TX_ON or PHY_FORCE_TX_ON. */
phy_enum_t state;
} plme_trx_req_t;
/**
* @brief PLME-TRX.confirm parameters.
*
* @details The PLME-TRX.confirm primitive is generated by
* PLME and issued to its next higher layer in response to
* an PLME-SET_TRX_STATE.request primitive.
*
* In accordance with IEEE Std 802.15.4-2006, section 6.2.2.8.1
*/
typedef struct
{
/** Holds result of trx state change request.
*
* @details Equals to PHY_SUCCESS if state changed successfully
* or current PHY state in either case.
*/
phy_enum_t status;
} plme_trx_conf_t;
/**@brief PLME-SET_TRX_STATE request.
*
* @details Request PHY to change internal operating state.
* In accordance with IEEE Std 802.15.4-2006, section 6.2.2.7
*
* @param[in] req Pointer to PLME-SET_TRX_STATE.request parameters.
* See @ref plme_trx_req_t.
*/
void plme_set_trx_state_req(plme_trx_req_t * req);
/**@brief PLME-SET_TRX_STATE.confirm callback function, implemented by the next higher layer.
*
* @details The PLME-SET_TRX_STATE.confirm primitive is generated
* by the PLME and issued to its next higher layer in response to
* an PLME-SET_TRX_STATE.request primitive.
*
* In accordance with IEEE Std 802.15.4-2006, section 6.2.2.8
*
* @param[out] conf Pointer to PLME-TRX.confirm parameters. See @ref plme_trx_conf_t.
*/
void plme_set_trx_state_conf(plme_trx_conf_t * conf);
/**@brief Direct (synchronous) PLME-SET_TRX_STATE access.
*
* @details Optional. Not covered by the standard.
* @param[in] state One of PHY_RX_ON, PHY_TRX_OFF, PHY_FORCE_TRX_OFF or PHY_TX_ON.
*
* @return PHY_SUCCESS if state changed successfully or current PHY state
* in either case.
*/
phy_enum_t plme_set_trx_state(phy_enum_t state);
/** @} */
#endif // PHY_PLME_TRX_H_INCLUDED

View File

@ -0,0 +1,99 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef RAL_API_SPEC_H_INCLUDED
#define RAL_API_SPEC_H_INCLUDED
#include <stdbool.h>
/**
* @defgroup ral_api_spec RAL Special API
* @ingroup ral_api
* @{
*/
/**@brief Specific CCA MODE for FPGA RAL
*/
#define RAL_TRX_CCA_MODE4 4
/**@brief Maximum available value of CCA MODE for FPGA RAL
*/
#define RAL_TRX_CCA_MODE_MAX RAL_TRX_CCA_MODE4
/**@brief Maximum duration of CCA algorithm including a task scheduling
*/
#define RAL_LONGEST_CCA_DURATION_US 500
/**@brief Maximum transmit power in dBm
*/
#define RAL_MAXIMUM_TX_POWER 9
/**@brief Maximum tolerance of transmit power in dBm
*/
#define RAL_TX_POWER_TOLERANCE PHY_TX_POWER_TOLERANCE_6DB
/**@brief Value of RF signal power (in dBm) for RSSI equals zero.
*/
#define RSSI_BASE_VAL 90
/**@brief Values above this shouldn't appear in RSSI register result.*/
#define RSSI_REG_MAX_VAL 20
/**@brief Controls whether radio module will automatically calculate Frame
* Control Sequence field.
*
* @param auto_fcs_enabled if set to true, automatically generated FCS will
* replace the last two bytes of PHY service data unit.
*/
void ral_auto_fcs_set(bool auto_fcs_enabled);
/**@brief Controls whether radio module will enter channel jamming mode.
*
* @param jamming_enabled if set to true, radio will perform jamming on current
* channel and energy. No data transmission can be done
* while jamming is enabled.
*/
void ral_jam_control_set(bool jamming_enabled);
/** @} */
#endif// RAL_API_SPEC_H_INCLUDED

View File

@ -0,0 +1,96 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef RAL_FSM_H_INCLUDED
#define RAL_FSM_H_INCLUDED
#include "sys_fsm.h"
/**
* @defgroup ral_api_fsm RAL FSM API
* @ingroup ral_api
* @{
*/
// list of possible events
typedef enum
{
E_RESET,
E_TRX_END, /**< Radio signals that TX or RX is complete.*/
E_TX_REQ, /**< Initiates upload of a frame into radio memory and
transmission of it into air.*/
E_TRX_OFF,
E_TX_ON,
E_FORCE_TX_ON,
E_RX_ON,
} ral_fsm_events_t;
// states
typedef enum
{
/* State symbol for short FSM debug mode */
/* I */ S_TRX_OFF,
/* J */ S_TX_ON,
/* */ S_BUSY_TX,
/* G */ S_RX_ON,
/* B */ S_BUSY_RX,
} ral_fsm_states_t;
/**@brief Reads current state of RAL state machine.
*
* @return Current state.
*/
ral_fsm_states_t ral_fsm_current_state_get(void);
/**@brief Initializes finite state machine of radio chip.*/
void ral_fsm_init(void);
/**@brief Sends new event to radio FSM. This function is used for
* changing radio state.
*
* @param event - event id for FSM.
* @param p_data - pointer to event specific data (expects pointer to ral_mem_t).
*/
void ral_fsm_event_post(ral_fsm_events_t event, void * p_data);
/** @} */
#endif /* RAL_FSM_H_INCLUDED */

View File

@ -0,0 +1,88 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef RAL_FSM_PRIVATE_H_INCLUDED
#define RAL_FSM_PRIVATE_H_INCLUDED
#include "nrf52840.h"
#include "nrf52840_bitfields.h"
/**
* @defgroup ral_api_fsm_private RAL FSM private API
* @ingroup ral_api
* @{
*/
/** @brief Private RAL function. Sets radio module into TRX_OFF mode if
* it was in RX or TX mode. */
void ral_fsm_a_trx_off(void * p_data);
/** @brief Private RAL function. Sets radio module into TRX_OFF mode if
* it was in BUSY_RX or BUSY_TX mode. */
void ral_fsm_a_force_trx_off(void * p_data);
/** @brief Private RAL function. Switches radio module from TRX_OFF
* to TX_ON mode. */
void ral_fsm_a_tx_on(void * p_data);
/** @brief Private RAL function. Switches radio module from TRX_OFF
* to RX_ON mode. */
void ral_fsm_a_rx_on(void * p_data);
/** @brief Private RAL function. Switches radio module from TX_ON
* to RX_ON mode. */
void ral_fsm_a_tx_to_rx(void * p_data);
/** @brief Private RAL function. Switches radio module from RX_ON
* to TX_ON mode. */
void ral_fsm_a_rx_to_tx(void * p_data);
/** @brief Private RAL function. Switches radio module from TRX_OFF
* to channel jamming mode. */
void ral_jamming_on(void);
/** @brief Private RAL function. Switches radio module from channel jamming
* mode to TRX_OFF state. */
void ral_jamming_off(void);
/** @} */
#endif /* RAL_FSM_PRIVATE_H_INCLUDED */

View File

@ -0,0 +1,65 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef RAL_IRQ_HANDLERS_H_INCLUDED
#define RAL_IRQ_HANDLERS_H_INCLUDED
#define RAL_NRF_BCC_COMPARE_VALUE 32
#define RAL_NRF_BCC_COMPARE_NONE (RAL_NRF_BCC_COMPARE_VALUE + 16)
#define RAL_NRF_BCC_COMPARE_SHORT (RAL_NRF_BCC_COMPARE_VALUE + 32)
#define RAL_NRF_BCC_COMPARE_LONG (RAL_NRF_BCC_COMPARE_VALUE + 80)
/**
* @defgroup ral_api_irq_handlers RAL auxiliary functions
* @ingroup ral_api
* @{
*/
/**@brief RAL IRQ handler symbol importer (dummy function).
*
* @details This function is only used to correctly import
* RADIO_IRQHandler symbol.
*/
void ral_irq_handler_import(void);
/** @} */
#endif// RAL_IRQ_HANDLERS_H_INCLUDED

View File

@ -0,0 +1,69 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef RAL_INIT_H_INCLUDED
#define RAL_INIT_H_INCLUDED
/**
* @defgroup ral_api_init RAL RF initialization API
* @ingroup ral_api
* @{
*/
/**@brief Initializes radio transceiver.
*/
void ral_rf_init(void);
/**@brief Channel number setting.
*
* @param channel_num - channel number
*/
void ral_rf_channel_set(uint8_t channel_num);
/**@brief Channel number getting.
*
* @return channel number
*/
uint8_t ral_rf_channel_get(void);
/** @} */
#endif /* RAL_INIT_H_INCLUDED */

View File

@ -0,0 +1,230 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef RAL_API_H_INCLUDED
#define RAL_API_H_INCLUDED
#include "ral_api_spec.h"
#include "sys_time.h"
#include "phy_common.h"
#include "phy_pd_data.h"
#include "mac_common.h"
#include "mac_mlme_pib.h"
#include "mac_time.h"
#include <stdint.h>
#include <stdbool.h>
/**@file ral_api.h
*
* @defgroup ral_api Radio Abstraction Layer common API
* @ingroup ral_15_4
* @{
*
* @brief Radio abstraction layer common interface.
*
* @details These are requirements for the implementation code:
*
* - no frames must be received between new frame indication and
* a call to ral_data_ind_read.
*/
// various constants to use with MAC/PHY header parsing
#define PHR_POS 0
#define PHR_SIZE 1
#define CRC_SIZE 2
#define MAC_FRAME_CTRL_POS 0
#define MAC_FRAME_CTRL_SIZE 2
#define ACK_REQUEST_MASK 0x20
#define SEQ_NUM_POS (MAC_FRAME_CTRL_POS + MAC_FRAME_CTRL_SIZE)
#define ACK_PD_BIT_MASK 0x0010
#define FRAME_TYPE_MASK 0x0007
#define FRAME_TYPE_BEACON 0x0000
#define FRAME_TYPE_DATA 0x0001
#define FRAME_TYPE_ACK 0x0002
#define FRAME_TYPE_COMMAND 0x0003
#define FRAME_PENDING_MASK 0x0010
/**@brief RAL atomic section */
typedef volatile uint8_t ral_atomic_t;
// private RAL data
typedef struct
{
volatile uint8_t tx_seq_num;
volatile bool ack_needed;
volatile bool waiting_for_ack;
volatile ral_atomic_t ral_atomic;
volatile mac_timestamp_t received_frame_timestamp;
volatile bool spi_transfer;
volatile bool cca_performing;
#if defined(AT86RF231)
volatile int8_t ed_value;
volatile bool unread_frame; /** This flag is used to deny transmission if incoming frame
has not been read from radio buffer.
todo: remove this deny to accelerate data exchange.
*/
volatile bool is_promiscuous_mode; /**< Set to true if promiscuous mode is enabled.*/
#elif (defined(NRF52_SERIES) || defined(NRF52))
// pointer to free memory for rx DMA
volatile uint8_t * p_buffer;
volatile sys_time_t calibr_value;
volatile uint8_t bcc_part;
#endif
} ral_mem_t;
/**@brief Initializes radio abstraction layer.
*/
void ral_init(void);
/**@brief Resets radio abstraction layer.
*/
void ral_reset(void);
/**@brief Performs synchronous ED measurement.
*/
uint8_t ral_ed_perform(void);
/**@brief Sends request to change radio state.
*
* @param state - New radio state. One of...
*
* @return PHY_SUCCESS, if state has been successfully achieved;
* current state, if state cannot be reached.*/
phy_enum_t ral_state_set(const phy_enum_t state);
/**@brief Returns current state of radio.
*/
phy_enum_t ral_state_get(void);
/**@brief Puts radio into sleep mode
*/
void ral_sleep(void);
/**@brief Awakes a radio
*/
void ral_wakeup(void);
/**@brief Performs synchronous cca.
*/
phy_status_t ral_cca_perform(void);
/**@brief Sends PHY frame.
*
* @param[in] pd_data - full data frame to be send.
*
* @details RAL automatically adds header and FCS control bytes
* to \a pd_data. Caller must reserve 1 byte before \a psdu
* pointer and may leave last two bytes of payload (i.e. FCS
* control field) uninitialized.
*
* RF chip or RAL code is responsible to receive an ACK frame.
* After ACK is handled, device should be restored to the TX state.*/
void ral_data_req(pd_data_req_t * pd_data);
/**@brief Reads indication frame from radio.
*
* @retval Pointer on the structure of a PHY data indication
* with received frame.
*/
pd_data_ind_t * ral_data_ind_read(void);
/**@brief Enable data flow from radio hardware after it was disabled
* by ral_data_flow_disable().
*/
void ral_data_flow_enable(void);
/**@brief Disable data flow from radio hardware
*/
void ral_data_flow_disable(void);
/**@brief This function is used to set attribute from MAC or PHY layer
* without checking of its boundaries.
*
* @param id - one of #MAC_SHORT_ADDRESS, #MAC_EXTENDED_ADDRESS, #MAC_PAN_ID
* and some other values.
* @param p_value - pointer to new value.
*/
void ral_attribute_set(uint8_t id, const void * p_value);
/**@brief This function is used to get a copy of attribute value stored inside
* radio module.
*
* @param[in] id - one of #PHY_CURRENT_CHANNEL_ID, #PHY_TRANSMIT_POWER_ID or
* #PHY_CCA_MODE_ID. Other attributes are not supported.
* @param[out] p_attr_value - pointer to value to get.
*/
void ral_attribute_get(uint8_t id, void * p_attr_value);
/**@brief This function is used to define frame start time by it's size
* and the timestamp, when RX IRQ has been received.
*
* @param irq_time - moment when IRQ has been received.
* @param frame_size - size of received frame in bytes.
*
* @retval MAC timestamp when PHY header has been started to receive.
*/
mac_timestamp_t ral_rx_start_time(mac_timestamp_t irq_time, uint8_t frame_size);
/**@brief This function performs RSSI.
*
* @return RSSI sample value.
*/
uint8_t ral_rssi_get(void);
/**@brief This function calculates the adjusted RSSI value using a temperature
* correction factor.
*
* @param[in] rssi - RSSI sample value (as returned by @ref ral_rssi_get).
* @param[in] temp - Temperature value in °C.
*
* @return Temperature-corrected RSSI value.
*/
uint8_t ral_rssi_corrected_get(uint8_t rssi, int8_t temp);
/** @} */
#endif /* RAL_API_H_INCLUDED */

View File

@ -0,0 +1,128 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SEC_AES_CCM_H_INCLUDED
#define SEC_AES_CCM_H_INCLUDED
#include <stdint.h>
/** @file
* This file contains declarations of the AES CCM encryption/decryption routines and necessary types.
* It also contains the declaration of the Security Abstract library initialization routine.
*
* @defgroup sec_aes_ccm Security AES CCM declarations
* @ingroup sec_15_4
* @{
* @brief Module to declare Security AES CCM API
*/
/**
* @brief AES CCM Status enumeration.
*/
typedef enum
{
AES_CCM_OK, /**< AES CCM operation succeeded. */
AES_ENGINE_FAIL, /**< AES engine failed. */
AES_CCM_FAIL, /**< CCM algorithm failed. */
AES_CCM_AUTH_FAIL /**< CCM authentication failed. */
} sec_aes_ccm_status_t;
/**
* @brief AES CCM request.
*
* @details The AES CCM request primitive is issued by the AES user.
* There are two use cases for the request:
* The first one is to encrypt the user text with some given key.
* The second one is to decrypt the cipher text against the key.
* The encrypted or decrypted data is stored in text_data.
*/
typedef struct
{
/** Counted authentication tag. */
uint8_t * mic;
/** Security level identifier. */
uint8_t level;
/** A 128-bit-long string to be used as a key. Each entity must have evidence that access
* to this key is restricted to the entity itself and its intended key sharing group member(s). */
uint8_t * key;
/** A nonce N of 15 - L octets. Within the scope of any encryption key, the nonce value must be unique. */
uint8_t * nonce;
/** An octet string representing plain text data in case of encryption and cipher text data
* in case of decryption. */
uint8_t * text_data;
/** Text data length. */
uint8_t text_data_len;
/** Octet string representing input data to perform authentication. */
uint8_t * auth_data;
/** Auth data length. */
uint8_t auth_data_len;
} sec_aes_ccm_req_t;
/**
* @brief Function for initializing the security abstraction layer.
*/
void sec_init(void);
/**
* @brief AES CCM encryption transformation.
*
* @details Performs synchronous encryption of data.
*
* @param req Encryption request structure.
* @return AES_CCM_OK on success, otherwise an implementation defined error.
*/
sec_aes_ccm_status_t sec_aes_ccm_enc(sec_aes_ccm_req_t * req);
/**
* @brief AES CCM decryption transformation.
*
* @details Performs synchronous decryption of a cipher.
*
* @param req Decryption request structure.
* @return AES_CCM_OK on success, otherwise an implementation defined error.
*/
sec_aes_ccm_status_t sec_aes_ccm_dec(sec_aes_ccm_req_t * req);
/** @} */
#endif /* SEC_AES_CCM_H_INCLUDED */

View File

@ -0,0 +1,75 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SEC_AES_ENTITY_H_INCLUDED
#define SEC_AES_ENTITY_H_INCLUDED
#include <stdint.h>
/** @file
* This file contains declaration of the AES encryption routine.
* It also contains the declaration of the AES entity initialization routine.
*
* @defgroup aes_entity Security AES entity declarations
* @ingroup sec_15_4
* @{
* @brief Module to declare AES entity API.
*/
/**
* @brief Function for initializing the AES ECB module.
*/
void aes_entity_init(void);
/**
* @brief AES encryption.
*
* @details Performs synchronous encryption of text against the key.
* Encrypted data is stored to text memory.
*
* @param key Pointer to a 128-bit key.
* @param text Pointer to a 128-bit plain text data.
*/
void aes_handle(uint8_t * key, uint8_t * text);
/** @} */
#endif /* SEC_AES_ENTITY_H_INCLUDED */

View File

@ -0,0 +1,95 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SYS_CRC_H_INCLUDED
#define SYS_CRC_H_INCLUDED
#include <stdint.h>
#include <stddef.h>
/** @file
* This file contains declarations of the CRC computing routines and necessary macros/types.
*
* @defgroup sys_crc System CRC API
* @ingroup sys_15_4
* @{
* @brief Module to declare System CRC API.
* @details The CRC module implements a set of routines to compute the 16-bit CRC value for octet arrays.
*/
/**
* @brief Defines an initial value for the CRC sum.
*/
#define SYS_CRC_INIT 0
/**
* @brief CRC value type. This module uses 16-bit CRC.
*/
typedef uint16_t sys_crc_t;
/**
* @brief Function for computing CRC value for given data.
*
* @param[in] p_data Pointer to data to compute.
* @param[in] length Length of data.
*
* @return Returns the CRC value for input data.
*/
sys_crc_t sys_crc_calc(const uint8_t * p_data, size_t length);
/**
* @brief Function for updating the CRC value taking into the account the previously counted value.
*
* @details This function is used when input data is represented by several pieces.
* Consequently, a call to this function for each piece will give a correct
* total CRC value.
*
* @param[in] current_crc Previously counted CRC value. Should be SYS_CRC_INIT for the first piece.
* @param[in] p_data Pointer to the current piece of data.
* @param[in] length Length of the current piece of data.
*
* @return Returns the updated CRC value.
*/
sys_crc_t sys_crc_continue(sys_crc_t current_crc, const uint8_t * p_data, size_t length);
/** @} */
#endif /* SYS_CRC_H_INCLUDED */

View File

@ -0,0 +1,180 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SYS_DEBUG_H_INCLUDED
#define SYS_DEBUG_H_INCLUDED
#include "hal_debug_interface.h"
#include "hal_trace_interface.h"
#include <stdbool.h>
#include <stdarg.h>
/* This header file contains macros for debugging. */
#ifndef __FILENAME__
#define __FILENAME__ __FILE__
#endif // __FILENAME__
#ifndef ASSERT
#ifdef CONFIG_DEBUG
#define ASSERT(CONDITION_STATEMENT) \
do \
{ \
bool LOCAL_CONDITION_CHECK = (CONDITION_STATEMENT); \
if (LOCAL_CONDITION_CHECK != true) \
{ \
sys_assert_handler((#CONDITION_STATEMENT), __LINE__, __FILENAME__); \
} \
} while (0)
#else
#define ASSERT(CONDITION_STATEMENT)
#endif // CONFIG_DEBUG
#endif // ASSERT
#ifndef ASSERT_INFO
#ifdef CONFIG_DEBUG
#define ASSERT_INFO(CONDITION_STATEMENT, INFO_FMT, ...) \
do \
{ \
bool LOCAL_CONDITION_CHECK = (CONDITION_STATEMENT); \
if (LOCAL_CONDITION_CHECK != true) \
{ \
sys_assert_info_handler((#CONDITION_STATEMENT), __LINE__, __FILENAME__, \
INFO_FMT, __VA_ARGS__); \
} \
} while (0)
#else
#define ASSERT_INFO(CONDITION_STATEMENT, INFO_FMT, ...)
#endif // CONFIG_DEBUG
#endif // ASSERT_INFO
#ifndef ASSERT_STATIC
#ifdef CONFIG_DEBUG
#define ASSERT_STATIC(e) do { enum {SA = 1/(e)}; } while (0)
#else
#define ASSERT_STATIC(e)
#endif // CONFIG_DEBUG
#endif // ASSERT_STATIC
/**
* @defgroup sys_debug Debugging macros
* @ingroup sys_15_4
* @{
* @brief Functions used for debugging.
*/
/**@brief System assertion fault handler.
*
* @details This macro should be used whenever an assertion fault is detected.
*
* @param[in] CONDITION_STRING Assertion condition string, which occurred to be not true.
*/
#define SYS_ASSERT_HANDLER(CONDITION_STRING) \
do \
{ \
sys_assert_handler(CONDITION_STRING, __LINE__, __FILE__); \
} while (0)
#ifndef TRACE_PUTS
#ifdef CONFIG_TRACE
#define TRACE_PUTS(s) HAL_TRACE_INTERFACE_PUTS(s)
#else
#define TRACE_PUTS(s)
#endif //CONFIG_TRACE
#endif //TRACE_PUTS
#ifndef TRACE
#ifdef CONFIG_TRACE
#define TRACE(INFO_FMT, ...) sys_trace_handler(INFO_FMT, __VA_ARGS__)
#else
#define TRACE(INFO_FMT, ...)
#endif // CONFIG_DEBUG
#endif // TRACE
/**@brief System assertion fault handler function.
*
* @param[in] condition Assertion condition string, which was expected to be true.
*
* @param[in] line Line number.
*
* @param[in] file File name.
*/
extern void sys_assert_handler(
const char * condition, const int line, const char * file);
/**@brief System assertion fault handler function with additional assertion information.
*
* @param[in] condition Assertion condition string, which was expected to be true.
*
* @param[in] line Line number.
*
* @param[in] file File name.
*
* @param[in] info_fmt Format string for additional assert information.
*
* @param[in] ... Arguments list corresponding to the format string.
*/
extern void sys_assert_info_handler(
const char * condition, const int line, const char * file,
const char * info_fmt, ...);
/**@brief System trace output handler function.
*
* @param[in] fmt Format string for trace output.
*
* @param[in] ... Arguments list corresponding to the format string.
*/
extern void sys_trace_handler(const char * fmt, ...);
/** @} */
#endif // SYS_DEBUG_H_INCLUDED

View File

@ -0,0 +1,167 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SYS_EVENTS_H_INCLUDED
#define SYS_EVENTS_H_INCLUDED
#include <stddef.h>
#include "sys_queue.h"
/** @file
* This file contains declarations of the Events API and necessary types. The Events feature is implemented
* using the Queue functionality.
*
* @defgroup sys_events System events API
* @ingroup sys_15_4
* @{
* @brief Module for declaring system events API.
* @details The Events module defines some routines to subscribe/unsubscribe to/from system events. The events pool
* can be extended by adding new events to the sys_event_id_t enumeration. The registered callbacks
* can be called for an array of events. The callbacks can be called implicitly via posting the event by the
* sys_event_post() routine.
*/
/**@brief IDs of globally available events.
*
* @details Event IDs are system extension points that allow the user to implement
* specific processing of predefined set of events, occurring in different modules.
*/
typedef enum
{
SYS_EVENT_FALLING_ASLEEP, /**< Falling asleep event. */
SYS_EVENT_WAKE_UP, /**< Waking up event. */
SYS_EVENT_OUT_OF_MEMORY, /**< Out of memory event. */
SYS_EVENT_MEMORY_FREED, /**< Memory was freed up event. */
/** \note The list of system events can be extended during the implementation phase. */
/* The following event IDs are used only for unit testing */
TST_EVENT_0, /**< Test event #0. */
TST_EVENT_1, /**< Test event #1. */
TST_EVENT_2, /**< Test event #2. */
#if (CONFIG_USE_SYS_TASK_NOTIFIER == 1)
/** This event is posted when there are unhandled events available in
* any of the schedulers.
*/
SYS_EVENT_NEW_TASK,
#endif
SYS_EVENTS_AMOUNT
} sys_event_id_t;
/**@brief Prototype of user-implemented callback for processing an event.
*
* @details This callback is registered for the given event by a *_subscribe routine,
* and is then called by the system events engine, when this event occurs.
*
* @param[in] p_data Pointer to the data, specific for this event.
*/
typedef void (* sys_event_callback_t)(const void * p_data);
/**@brief Event descriptor.
*
* @details This descriptor is used to subscribe/unsubscribe to/from the event.
*/
typedef struct
{
/** Service field. */
sys_queue_item_t queue_item;
/** ID of the event to which this callback is to be subscribed. */
sys_event_id_t event_id;
/** Callback function which is to be called when this event occurs. */
sys_event_callback_t callback;
} sys_event_desc_t;
/**@brief Function for initializing the global events infrastructure.
*/
void sys_events_init(void);
/**@brief Function for subscribing to a system event.
*
* @param[in] p_event_desc Pointer to the event descriptor.
*/
void sys_event_subscribe(sys_event_desc_t * p_event_desc);
/**@brief Function for unsubscribing from a system event event.
*
* @param[in] p_event_desc Pointer to the event descriptor.
*/
void sys_event_unsubscribe(sys_event_desc_t * p_event_desc);
/**@brief Function for subscribing to a group of events.
*
* @param[in] p_desc_array Pointer to the array of event descriptors.
* @param[in] desc_amount Amount of event descriptors in the array.
*/
void sys_events_array_subscribe(sys_event_desc_t * p_desc_array, size_t desc_amount);
/**@brief Function for unsubscribing from the group of events.
*
*
* @param[in] p_desc_array Pointer to the array of event descriptors.
* @param[in] desc_amount Amount of the event descriptors in the array.
*/
void sys_events_array_unsubscribe(sys_event_desc_t * p_desc_array, size_t desc_amount);
/**@brief Function for posting an event.
*
* @details This function is used to notify all the subscribers of the given events via
* their callbacks, when the given event occurs.
*
* @param[in] event_id ID of the event to be posted.
* @param[in] p_data Pointer to be passed to the event handlers' callbacks.
*/
void sys_event_post(sys_event_id_t event_id, const void * p_data);
/** @} */
#endif // SYS_EVENTS_H_INCLUDED

View File

@ -0,0 +1,286 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SYS_FSM_H_INCLUDED
#define SYS_FSM_H_INCLUDED
#include <stdint.h>
#include <stdbool.h>
/** @file
* This file contains declarations of the Finite State Machine (FSM) primitives and necessary types.
*
* @defgroup sys_fsm Finite State Machine API
* @ingroup sys_15_4
* @{
* @brief Module to declare Finite State Machine API
* @details The FSM module implements the Finite State Machine abstraction. The user is intended to implement a transition
* table of states with guards and actions in order to represent some event-driven subject. When a table is
* implemented, call sys_fsm_init() to initialize the FSM. After that, the only routine to
* work with FSM is sys_fsm_event_post().
*/
/**@brief Fixed-size type for FSM state ID.
*/
typedef uint8_t sys_fsm_state_id_t;
/**@brief Fixed-size type for FSM event ID.
*/
typedef uint8_t sys_fsm_event_id_t;
/**@brief Fixed-size type for FSM guard condition ID.
*/
typedef uint8_t sys_fsm_guard_id_t;
/**@brief Fixed-size type for FSM action ID.
*/
typedef uint8_t sys_fsm_action_id_t;
/**@brief FSM transition description (item of FSM transition table).
*
* @details When an event with given event_id occurs, the guard condition with guard_id
* is checked, and if it returns true, the action with action_id is performed,
* and state machine is switched to the state with new_state_id.
*/
typedef struct
{
sys_fsm_event_id_t event_id; /**< FSM event ID. */
sys_fsm_guard_id_t guard_id; /**< FSM guard ID. */
sys_fsm_action_id_t action_id; /**< FSM action ID. */
sys_fsm_state_id_t new_state_id; /**< New state ID. */
#if defined(CONFIG_FSM_DEBUG)
const char * debug_string;
#endif
} sys_fsm_transition_t;
/**@brief FSM transition declaration (item of FSM transition table).
*/
#if defined(CONFIG_FSM_DEBUG)
# define SYS_FSM_TRANSITION(event_id, guard_id, action_id, new_state_id) \
{(event_id), (guard_id), (action_id), (new_state_id), \
"(" #event_id ", " #guard_id ", " #action_id " -> " #new_state_id ")"}
#else
# define SYS_FSM_TRANSITION(event_id, guard_id, action_id, new_state_id) \
{(event_id), (guard_id), (action_id), (new_state_id)}
#endif
/**@brief FSM state declaration.
*
* @details The state is an aggregator item of the FSM transition table, aggregating
* the transitions, declared immediately after this state declaration.
* All transition declaration items, following the state declaration item,
* will be aggregated in this state, until the next state declaration item,
* or the "end of table" item.
*/
#define SYS_FSM_STATE(state_id) \
{(state_id) | SYS_FSM_STATE_FLAG, 0, 0, 0}
/**@brief Empty guard condition ID.
*
* @details Special value of the guard_id field. If it is used in transition declaration,
* guard check will be omitted.
*/
#define SYS_FSM_NO_GUARD 0xFF
/**@brief Empty guard condition ID (useful synonym).
*
* @details Special value of the guard_id field. If it is used in transition declaration,
* guard check will be omitted.
*/
#define SYS_FSM_OTHERWISE 0xFF
/**@brief Empty guard condition ID (useful synonym).
*
* @details Special value of the guard_id field. If it is used in transition declaration,
* guard check will be omitted.
*/
#define SYS_FSM_ALWAYS 0xFF
/**@brief Empty action ID.
*
* @details Special value of the action_id field. If it is used in transition declaration,
* no action will be performed during the transition.
*/
#define SYS_FSM_NO_ACTION 0xFF
/**@brief Same state ID.
*
* @details Special value of the next_state_id field. If it is used in transition
* declaration, the current state will not be changed.
*/
#define SYS_FSM_SAME_STATE 0xFF
/**@brief Any state ID.
*
* @details Special value of the event_id field. If it is used in transition
* declaration table, then the transitions listed in this state will be applied
* in case they have not been listed in the transition table for the
* current FSM state.
* Only one SYS_FSM_STATE(SYS_FSM_ANY_STATE) can be present in the transition table.
*/
#define SYS_FSM_ANY_STATE 0xFF
/**@brief State declaration flag.
*
* @details Special flag of the event_id field. This flag is used to distinguish
* between state declaration and transition declaration.
*/
#define SYS_FSM_STATE_FLAG 0x80
/**@brief Prototype of a user-defined FSM guard condition function.
*
* @details You must implement a single FSM guard condition function which will
* use an ID of the needed guard check as a parameter.
*
* @param[in] guard_id Guard condition ID to be checked.
* @param[in] p_data Additional FSM specific data.
*
* @retval true Transition is allowed, false otherwise.
*/
typedef bool (* sys_fsm_guard_t)(sys_fsm_guard_id_t guard_id, void * p_data);
/**@brief Prototype of a user-defined FSM action function.
*
* @details You must implement a single FSM action function which will
* use an ID of the needed action as a parameter.
*
* @param[in] action_id Action ID to be performed.
* @param[in] p_data Additional FSM specific data.
*/
typedef void (* sys_fsm_action_t)(sys_fsm_action_id_t action_id, void * p_data);
/**@brief Constant FSM descriptor which can reside in read-only memory.
*/
typedef struct
{
#if defined(CONFIG_FSM_DEBUG)
const char * debug_fsm_name;
#endif
/** Pointer to the transition table.
*/
const sys_fsm_transition_t * transition_table;
/** Number of transitions in the transition table.
*/
uint8_t transitions_amount;
/** Initial state ID.
*/
sys_fsm_state_id_t initial_state;
/** Pointer to the guard condition function.
*/
sys_fsm_guard_t guard;
/** Pointer to the action function.
*/
sys_fsm_action_t action;
} sys_fsm_const_descriptor_t;
/**@brief FSM dynamic descriptor, holding the current state of the FSM.
*/
typedef struct
{
/** Pointer to the constant FSM descriptor which can reside in read-only memory.
*/
const sys_fsm_const_descriptor_t * fsm_const_desc;
/** Index of the "any state transitions" block.
*/
uint8_t any_state_transitions_index;
/** Current state ID.
*/
volatile sys_fsm_state_id_t current_state;
/** Recursion protection.
*/
volatile uint8_t recursion_protection;
} sys_fsm_t;
#if defined(CONFIG_FSM_DEBUG)
#define FSM_DEBUG_NAME(name_string) .debug_fsm_name = name_string,
#else
#define FSM_DEBUG_NAME(name_string)
#endif
/**@brief Function for initializing a specific FSM.
*
* @param[in] p_fsm Pointer to FSM descriptor to initialize.
* @param[in] p_fsm_const Pointer to constant FSM descriptor with transition table, etc.
*/
void sys_fsm_init(sys_fsm_t * p_fsm, const sys_fsm_const_descriptor_t * p_fsm_const);
/**@brief Function for posting an event to FSM.
*
* @details This function causes FSM transition from the current state to the new state,
* according to the transition table of this FSM.
* The corresponding guard check and action is performed.
*
* @param[in] p_fsm Pointer to FSM descriptor.
* @param[in] event_id Event ID to post.
* @param[in] p_data Pointer to the FSM-specific data.
*/
void sys_fsm_event_post(sys_fsm_t * p_fsm, sys_fsm_event_id_t event_id, void * p_data);
/** @} */
#endif // SYS_FSM_H_INCLUDED

View File

@ -0,0 +1,69 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SYS_INIT_H_INCLUDED
#define SYS_INIT_H_INCLUDED
#include <stddef.h>
/**
* @defgroup sys_15_4_init Initialization API
* @ingroup sys_15_4
* @{
* @brief API for initizalizing the system abstraction library.
*/
/** @brief Initializes every component of this stack.
*
* This function must be called before using any of the components.
*
* @param[in] p_start Pool start address.
* @param[in] size Size of the pool in bytes.
*
* @details The pool start address must be aligned on the ALIGN_VALUE boundary, which is
* defined in @c sys_utils.h.
* The pool size should be multiple of an ALIGN_VALUE, which is defined in @c sys_utils.h.
*/
void sys_init(void * p_start, size_t size);
/** @} */
#endif /* SYS_INIT_H_INCLUDED */

View File

@ -0,0 +1,248 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SYS_LIST_H_INCLUDED
#define SYS_LIST_H_INCLUDED
/** @file
* This file contains declarations of the doubly linked list primitives and necessary types.
* This implementation is Linux-proven and used in the memory management module.
*
* @defgroup sys_list Doubly linked list API.
* @ingroup sys_15_4
* @{
* @brief Module to declare the doubly linked list API.
*/
/**
* Internal list "head" struct.
*/
struct sys_list_head
{
struct sys_list_head * next;
struct sys_list_head * prev;
};
typedef struct sys_list_head sys_list_head_t;
/**
* @brief Initializes a list by variable name.
* @warning this macro assumes that a list "head" (sys_list_head_t) variable
* with name \a name is already created.
*
* @param[inout] name The "head" struct name.
*/
#define LIST_HEAD_INIT(name) { &(name), &(name) }
/**
* @brief Defines and initializes a new list.
* @details A call to this macro creates a new variable with the given name and
* initializes it as a list "head".
*
* @param[inout] name The "head" struct name.
*/
#define LIST_HEAD(name) sys_list_head_t name = { &(name), &(name) }
/**
* @brief Initializes a list by pointer.
*
* @param[inout] ptr Pointer to a list.
*/
#define INIT_LIST_HEAD(ptr) \
do \
{ \
(ptr)->prev = (ptr); \
(ptr)->next = (ptr); \
} while (0)
/**
* @brief Checks if a list is empty.
*
* @param[in] sys_list_head Pointer to a list.
* @return 0 if not empty, non-zero otherwise.
*/
#define IS_EMPTY(sys_list_head) (sys_list_head)->next == (sys_list_head)
/**
* @brief Adds a new item to the list between \a l_prev and \a l_next elements.
* @warning This routine assumes that \a l_next is next to \a l_prev in the list.
* @note This is an internal helper routine which is not intended to be used by the user.
*
* @param[in] l_prev Pointer to the previous element.
* @param[in] l_next Pointer to the next element.
* @param[in] l_new Pointer to a new element.
*/
static inline void sys_ll_list_add(sys_list_head_t * l_prev,
sys_list_head_t * l_next,
sys_list_head_t * l_new)
{
l_new->prev = l_prev;
l_prev->next = l_new;
l_next->prev = l_new;
l_new->next = l_next;
}
/**
* @brief Deletes an element between \a l_prev and \a l_next elements.
* @warning This macro assumes that \a l_next is next to \a l_prev in the list.
* @note This is an internal helper routine which is not intended to be used by the user.
*
* @param[in] l_prev Pointer to the previous element.
* @param[in] l_next Pointer to the next element.
*/
static inline void sys_ll_list_del(sys_list_head_t * l_next,
sys_list_head_t * l_prev)
{
l_next->prev = l_prev;
l_prev->next = l_next;
}
/**
* @brief Function for adding a new item to the head of the list.
*
* @param[in] new Pointer to a new element.
* @param[in] head Pointer to the list head.
*/
static inline void sys_list_add(sys_list_head_t * new, sys_list_head_t * head)
{
sys_ll_list_add(head, head->next, new);
}
/**
* @brief Function for adding a new item to the tail of the list.
*
* @param[in] new Pointer to a new element.
* @param[in] head Pointer to the list head.
*/
static inline void sys_list_add_tail(sys_list_head_t * new, sys_list_head_t * head)
{
sys_ll_list_add(head->prev, head, new);
}
/**
* @brief Function for deleting an entry from list.
*
* @param[in] entry The element to delete from the list.
*/
static inline void sys_list_del(sys_list_head_t * entry)
{
sys_ll_list_del(entry->next, entry->prev);
}
/**
* @brief Function for deleting an entry from the list and reinitializing it.
*
* @param[in] entry The element to delete from the list.
*/
static inline void sys_list_del_init(sys_list_head_t * entry)
{
sys_ll_list_del(entry->next, entry->prev);
INIT_LIST_HEAD(entry);
}
/**
* @brief Function for testing if a list is empty.
* @param[in] head The list to test.
* @return 0 if not empty, non-zero otherwise.
*/
static inline unsigned int sys_list_empty(sys_list_head_t * head)
{
return IS_EMPTY(head);
}
/**
* @brief Sets a pointer to a variable to the parent structure pointer using a
* pointer to a field in this structure.
*
* @note This is a version of @ref GET_PARENT_BY_FIELD() extended by setting to a variable.
*
* @param[out] ll_ret_var Variable pointer name to return.
* @param[in] ll_ptr Pointer to the structure field.
* @param[in] ll_type Name of the parent structure.
* @param[in] ll_member Name of the structure field.
*/
#define SYS_LIST_ENTRY(ll_ret_var, ll_ptr, ll_type, ll_member) \
do \
{ \
size_t p = (size_t) ll_ptr; \
size_t off = offsetof(ll_type, ll_member); \
ll_ret_var = (ll_type *) (p - off); \
} while (0)
/**
* @brief Iterates through the list.
* @note Use @ref SYS_LIST_FOR_EACH_SAFE() for thread-safe cases.
*
* @param[out] pos Iterator variable.
* @param[in] head Pointer to the list head.
*/
#define SYS_LIST_FOR_EACH(pos, head) \
for (pos = ((head)->next); \
((pos) != (head)); \
pos = (pos)->next)
/**
* @brief Thread-safe version of @ref SYS_LIST_FOR_EACH().
*
* @param[out] ll_pos Iterator variable.
* @param[out] ll_pos_n Temporary iterator variable (next entry).
* @param[in] ll_head Pointer to the list head.
*/
#define SYS_LIST_FOR_EACH_SAFE(ll_pos, ll_pos_n, ll_head) \
for (ll_pos = (ll_head)->next, ll_pos_n = (ll_head)->next->next; \
(ll_pos) != (ll_head); \
ll_pos = ll_pos_n, ll_pos_n = ll_pos->next)
/** @} */
#endif /* SYS_LIST_H_INCLUDED */

View File

@ -0,0 +1,92 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SYS_MEMORY_MANAGER_H_INCLUDED
#define SYS_MEMORY_MANAGER_H_INCLUDED
#include <stddef.h>
#include <stdint.h>
/** @file
* This file contains declarations of the Memory manager API.
*
* @defgroup sys_memory_manager Memory Manager API
* @ingroup sys_15_4
* @{
* @brief Module to declare Memory Manager API.
* @details The Memory Manager module implements the standard API for allocating/freeing memory chunks. The module must
* be initialized by sys_mm_init() before a call to any alloc/free routines. The memory can be allocated by a
* call to sys_mm_alloc() and freed by a call to sys_mm_free(). Minimal chunk of memory to allocate is one byte,
* however the sys_mm_alloc() routine will allocate the number of bytes aligned to the length of the
* machine word (e.g. 4 bytes for 32-bit architectures). The module is implemented using the doubly linked
* lists API.
*/
/**@brief Function for initializing the memory manager.
* @details Initialize the memory manager pool of the 'size' bytes length at 'p_start' address.
*
* @param p_start Pool start address.
* @param size Size of the pool in bytes.
*/
void sys_mm_init(void * p_start, size_t size);
/**@brief Function for allocating memory in the pool.
* @details Search and allocate free memory resources.
*
* @param[in] size Size of the requested memory.
*
* @retval Pointer to allocated memory,
* NULL in case of error.
*/
void * sys_mm_alloc(size_t size);
/**@brief Function for freeing the allocated memory.
*
* @param[in] p_addr Pointer to the memory to free.
*
*/
void sys_mm_free(void * p_addr);
/** @} */
#endif // SYS_MEMORY_MANAGER_H_INCLUDED

View File

@ -0,0 +1,290 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SYS_QUEUE_H_INCLUDED
#define SYS_QUEUE_H_INCLUDED
#include <stdbool.h>
#include <stdint.h>
/** @file
* This file contains declarations of the primitives to work with queues and necessary types.
*
* @defgroup sys_queues Queue API
* @ingroup sys_15_4
* @{
* @brief Module to declare the queue API.
* @details The queue module implements a set of routines to deal with queues. Before
* any calls to its API are issued, a queue must be initialized using sys_queue_init(). The following routines
* return queue items from different parts of an initialized queue without removing it from the queue:
* sys_queue_front(), sys_queue_back(), sys_queue_next(), and sys_queue_at().
* The following routines insert elements to the queue: sys_queue_push_front(),
* sys_queue_push_back(), sys_queue_push_predicated(), sys_queue_push_predicated_force(), and sys_queue_insert().
* The following routines remove elements from the queue: sys_queue_pop_front(), sys_queue_remove(),
* sys_queue_remove_after(). These helper routines get information about a queue: sys_queue_size() and
* sys_queue_is_empty(). The module also supports an iterator macro implemented by SYS_QUEUE_FOR_EACH().
*/
/**@brief Queue item descriptor.
*
* @details In order to store any user data struct in a queue, the user struct should contain
* a field of type 'sys_queue_item_t'. This field may be at any offset.
* The user data item can be cast from the queue item,
* by the \ref GET_PARENT_BY_FIELD() macro from sys_utils.h.
*/
typedef struct sys_queue_item_s
{
struct sys_queue_item_s * next;
} sys_queue_item_t;
/**@brief Queue descriptor.
*/
typedef sys_queue_item_t sys_queue_t;
/**@brief Prototype of a predicate function for pushing an item into the queue.
*
* @details As a user of the queue library, implement the predicate function and pass it
* as a parameter to \ref sys_queue_push_predicated(). You can choose
* whether insertion of a new item should be done before the given existing item of
* the queue, or not.
*
* @param[in] p_before_item Pointer to the existing item before which a new item
* should be inserted.
* @param[in] p_new_item Pointer to the item to be inserted into the queue.
*
* @retval true Insertion is to be done before the given item, false otherwise.
*/
typedef bool (* sys_queue_push_predicate_t)(
sys_queue_item_t * p_before_item,
sys_queue_item_t * p_new_item);
/**@brief Function for initializing the queue before any other usage of the queue.
*
* @details Initialize (reset) the queue to its initial state. The queue becomes empty.
*
* @param[in] p_queue Queue to be initialized.
*/
void sys_queue_init(sys_queue_t * p_queue);
/**@brief Function for getting the front (head) item of the queue without removing it.
*
* @details Return a pointer to the item from the head of the queue but leave it in the queue.
*
* @param[in] p_queue Queue to get the item from.
*
* @retval Pointer to the head item of the queue, or NULL if the queue is empty.
*/
sys_queue_item_t * sys_queue_front(const sys_queue_t * p_queue);
/**@brief Function for getting the back (tail) item of the queue without removing it.
*
* @details Return a pointer to the item from the tail of the queue but leave it in the queue.
*
* @param[in] p_queue Queue to get the item from.
*
* @retval Pointer to the tail item of the queue, or NULL if the queue is empty.
*/
sys_queue_item_t * sys_queue_back(const sys_queue_t * p_queue);
/**@brief Function for getting the item, next to the given item of the queue.
*
* @details Return a pointer to the next item after the given one, or NULL if the
* given item is the last item of the queue.
*
* @param[in] p_queue Pointer to the queue.
* @param[in] p_item Pointer to the item.
*
* @retval Pointer to the next item after the given one, or NULL if the
* given item is the last item of the queue.
*/
sys_queue_item_t * sys_queue_next(const sys_queue_t * p_queue, const sys_queue_item_t * p_item);
/**@brief Function for pushing an item to the front (head) of the queue.
*
* @details This function inserts an item to the head of the queue.
*
* @param[in] p_queue Queue to push the item to.
* @param[in] p_item Item to insert to the front of the queue.
*/
void sys_queue_push_front(sys_queue_t * p_queue, sys_queue_item_t * p_item);
/**@brief Function for pushing an item to the back (tail) of the queue.
*
* @details This function inserts an item to the tail of the queue.
*
* @param[in] p_queue Queue to push the item to.
* @param[in] p_item Item to insert to the tail of the queue.
*/
void sys_queue_push_back(sys_queue_t * p_queue, sys_queue_item_t * p_item);
/**@brief Function for pushing an item to the queue with a predicate.
*
* @details Conditionally push an item to the queue using the given predicate that tries to determine
* the insertion position.
*
* @param[in] p_queue Queue to push the item to.
* @param[in] p_item Item to be pushed.
* @param[in] predicate Predicate to be used to find the insertion position.
*
* @retval true The item was inserted into the queue, false otherwise.
*/
bool sys_queue_push_predicated(
sys_queue_t * p_queue,
sys_queue_item_t * p_item,
sys_queue_push_predicate_t predicate);
/**@brief Function for pushing an item to the queue with a predicate forcing insertion to the tail if the predicate
* fails.
*
* @details Unconditionally push an item to the queue using the given predicate that tries to
* determine the insertion position.
* If predicate returns false, then force the insertion to the tail of the queue.
*
* @param[in] p_queue Queue to push item to.
* @param[in] p_item Item to be pushed.
* @param[in] predicate Predicate to be used to find the insertion position.
*/
void sys_queue_push_predicated_force(
sys_queue_t * p_queue,
sys_queue_item_t * p_item,
sys_queue_push_predicate_t predicate);
/**@brief Function for getting and removing the front (head) item from the queue.
*
* @details Get an item from the head of the queue and remove it from the queue.
*
* @param[in] p_queue Queue to get and remove the head item from.
*
* @retval Pointer to the head item of queue or NULL if the queue is empty.
*/
sys_queue_item_t * sys_queue_pop_front(sys_queue_t * p_queue);
/**@brief Function for removing an item from the queue.
*
* @details The given item will be removed from the queue.
*
* @note The complexity of this function is O(n). Use function \ref sys_queue_remove_after()
* whenever the previous item of the queue is known.
*
* @param[in] p_queue Queue to remove the item from.
* @param[in] p_item Item to remove from the queue.
*/
void sys_queue_remove(sys_queue_t * p_queue, sys_queue_item_t * p_item);
/**@brief Function for removing the item after the given item from the queue.
*
* @details The item next to the given one will be removed from the queue.
*
* @param[in] p_queue Queue to remove the item from.
* @param[in] p_after_item Next to this item will be removed.
*/
void sys_queue_remove_after(sys_queue_t * p_queue, sys_queue_item_t * p_after_item);
/**@brief Function for returning the current size of a queue, i.e. number of elements inside it.
*
* @details This function goes through the whole queue, so it is relatively slow.
*
* @param[in] p_queue Queue to work with.
*
* @retval Number of items currently inserted into the queue.
*/
uint8_t sys_queue_size(const sys_queue_t * p_queue);
/**@brief Function for returning a pointer to the item inside a queue represented by an index.
*
* @details This function searches through the whole queue, so it is relatively slow.
*
* @param[in] p_queue Queue to work with.
* @param[in] index Requested index.
*
* @retval Pointer to the requested item or NULL if the queue size is less
* than \a index.
*/
sys_queue_item_t * sys_queue_at(const sys_queue_t * p_queue, const uint8_t index);
/**@brief Function for inserting an item at the specified position represented by an index in the queue.
* If this position is too big, it is inserted to the tail of the queue.
*
* @details This function searches through the whole queue, so it is relatively slow.
*
* @param[in] p_queue Queue to insert to.
* @param[in] p_item Item to be inserted.
* @param[in] pos Position inside the queue (0 is the front).
*/
void sys_queue_insert(sys_queue_t * p_queue, sys_queue_item_t * p_item, const uint8_t pos);
/**@brief Function for determining if a queue is empty.
*
* @param[in] p_queue Queue to be checked.
*
* @retval True if queue is empty, false otherwise.
*/
bool sys_queue_is_empty(const sys_queue_t * p_queue);
/**@brief Macro for iterating through all items in the queue.
*
* @param[in] p_queue Pointer to the queue (sys_queue_t *).
* @param[in] p_iterator Variable to be used as an iterator (sys_queue_item_t *).
*/
#define SYS_QUEUE_FOR_EACH(p_queue, p_iterator) \
for (sys_queue_item_t * p_iterator = sys_queue_front(p_queue); \
p_iterator != NULL; \
p_iterator = sys_queue_next(p_queue, p_iterator))
/** @} */
#endif // SYS_QUEUE_H_INCLUDED

View File

@ -0,0 +1,202 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SYS_RINGBUFFER_H_INCLUDED
#define SYS_RINGBUFFER_H_INCLUDED
#include <stdint.h>
#include <stdlib.h>
#include <stdbool.h>
/** @file
* This file contains declarations of the Ring buffer routines and necessary types. Please note that
* each ring buffer element should have size of 1 byte.
*
* @defgroup sys_ringbuffer System Ring buffer API
* @ingroup sys_15_4
* @{
* @brief Module for declaring System Ring buffer API.
* @details The Ring Buffer module implements routines to deal with the ring buffer. The following routines are supported:
* sys_ringbuffer_insert(), sys_ringbuffer_remove() to operate with single element. The
* sys_ringbuffer_remove_multiple() can be used to remove (read) several elements at once. The
* sys_ringbuffer_clear(), sys_ringbuffer_init(), and sys_ringbuffer_init_over() functions are used to clean up and
* initialize the ring buffer. Some information about the initialized ring buffer is available via the
* following routines: sys_ringbuffer_size_get() to get the number of used elements, sys_ringbuffer_chunk_get()
* to return the biggest, available to read, continuous chunk of elements, sys_ringbuffer_is_empty() and
* sys_ringbuffer_is_full() to check if the ring buffer is empty/full, and sys_ringbuffer_max_size_get() to get
* the ring buffer capacity. One of the samples for ring buffer usage is the UART implementation.
*/
/** This structure holds all necessary information about a ring buffer. It is intentionally left undocumented
* by Doxygen.
*
* All these fields are private and must NOT be changed by the user.
*/
typedef struct
{
size_t write_index;
size_t read_index;
uint8_t * array;
size_t size;
bool is_full;
} sys_ringbuffer_t;
/** @brief Function for initializing an empty ring buffer over passed memory.
*
* @param[inout] buffer Instance of sys_ringbuffer_t that will be initialized.
* @param[in] memory Start address of the memory region used as a ring buffer.
* @param[in] length Size in bytes of the memory region used as a ring buffer.
*/
void sys_ringbuffer_init(sys_ringbuffer_t * buffer,
const void * memory,
const size_t length);
/** @brief Function for initializing a ring buffer over passed memory and marking all
* pre_init_length elements as inserted.
*
* @details This function may be used to initialize a buffer with some
* pre-initialized data in it. Passed memory region is interpreted by this function
* as an already filled (partly or fully) ring buffer so that \a pre_init_length
* elements are marked as inserted.
*
* @param[inout] buffer Instance of sys_ringbuffer_t that will be initialized.
* @param[in] memory Start address of the memory region used as a ring buffer.
* @param[in] pre_init_length Number of elements (bytes) that had already been in \a memory.
* They would be inserted into the newly-initialized ring buffer in a FIFO manner.
* @param[in] length Size of the memory region used as a ring buffer.
*/
void sys_ringbuffer_init_over(sys_ringbuffer_t * buffer,
const void * memory,
const size_t pre_init_length,
const size_t length);
/** @brief Function for removing an element from a ring buffer and returning it.
*
* @param[inout] buf Instance of @c sys_ringbuffer_t.
*
* @return Value of the removed element.
*
* @warning This buffer has no underflow control except assert.
*/
uint8_t sys_ringbuffer_remove(sys_ringbuffer_t * buf);
/** @brief Function for quickly removing up to chunk_size elements from a ring buffer
* and marking those elements as available in the ring buffer.
*
* @param[inout] buffer Instance of @c sys_ringbuffer_t.
* @param[in] chunk_size Number of elements to release.
*/
void sys_ringbuffer_remove_multiple(sys_ringbuffer_t * buffer,
const size_t chunk_size);
/** @brief Function for inserting a new element into a ring buffer.
*
* @param[inout] buffer Instance of @c sys_ringbuffer_t.
* @param[in] data Element value to insert.
*
* @warning In case of overflow, this buffer will overwrite the oldest
* element and the number of available elements will remain unchanged.
*/
void sys_ringbuffer_insert(sys_ringbuffer_t * buffer, const uint8_t data);
/** @brief Function for clearing an instance of \a sys_ringbuffer_t, making it empty.
*
* @param[inout] buffer Instance of @c sys_ringbuffer_t.
*/
void sys_ringbuffer_clear(sys_ringbuffer_t * buffer);
/** @brief Function for returning the number of used elements in a ring buffer instance.
*
* @param[inout] buf Instance of sys_ringbuffer_t.
*
* @return Number of elements.
*/
size_t sys_ringbuffer_size_get(const sys_ringbuffer_t * buf);
/** @brief Function for returning the biggest, available to read, continuous chunk from a ring buffer array.
*
* @param[inout] buffer Instance of @c sys_ringbuffer_t.
* @param[out] chunk Pointer to a memory chunk removed from the ring buffer.
* @param[out] chunk_size Size of the removed chunk.
*
* @warning The returned chunk is still part of the ring buffer. To make the chunk elements available
* for write, call @c sys_ringbuffer_remove_multiple() after the chunk is processed.
*/
void sys_ringbuffer_chunk_get(sys_ringbuffer_t * buffer,
void ** chunk,
size_t * chunk_size);
/** @brief Function for checking whether a ring buffer is empty.
*
* @param[inout] buf Instance of @c sys_ringbuffer_t.
*
* @return True if the ring buffer is empty.
*/
static inline bool sys_ringbuffer_is_empty(const sys_ringbuffer_t * buf)
{
return ((buf->write_index == buf->read_index) && (!buf->is_full));
}
/** @brief Function for checking whether a ring buffer is full.
*
* @param[inout] buf Instance of @c sys_ringbuffer_t.
*
* @return True if number of items in the buffer equals to (length - 1).
*/
static inline bool sys_ringbuffer_is_full(const sys_ringbuffer_t * buf)
{
return buf->is_full;
}
/** @brief Function for returning number of elements that can be potentially put into the buffer.
*
* @param[inout] buf Instance of @c sys_ringbuffer_t.
*
* @return Number of elements.
*/
static inline size_t sys_ringbuffer_max_size_get(const sys_ringbuffer_t * buf)
{
return buf->size;
}
/** @} */
#endif /* SYS_RINGBUFFER_H_INCLUDED */

View File

@ -0,0 +1,142 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SYS_SLAB_ALLOCATOR_H_INCLUDED
#define SYS_SLAB_ALLOCATOR_H_INCLUDED
#include "phy_pd_data.h"
#ifndef CONFIG_SLAB_FRAME_POOL_SIZE
#define CONFIG_SLAB_FRAME_POOL_SIZE 4
#warning "CONFIG_SLAB_FRAME_POOL_SIZE not set in .config, using default"
#endif
/** @file
* This file contains declarations of the SLAB allocator API.
*
* @defgroup sys_slab_allocator SLAB Allocator API
* @ingroup sys_15_4
* @{
* @brief Module for declaring the SLAB Allocator API
*/
/**@brief The SLAB allocator buffer type (free or busy buffer).
*/
typedef enum
{
SYS_SLAB_FREE_BUFFER, /**< The buffer is free */
SYS_SLAB_BUSY_BUFFER, /**< The buffer is busy */
} sys_slab_buffer_type_t;
/**@brief Initializes the SLAB allocator.
*
* @details Preallocates the frame pool
*/
void sys_sa_init(void);
/**@brief Resets the SLAB allocator.
*
* @details Clear allocated the frame pools
*/
void sys_sa_reset(void);
/**@brief Inserts item into one of the queues of the SLAB allocator.
*
* @details This function is used to put the item into the SLAB allocator
* queue. Type of buffer shall be chosen.
*
* @param[in] type Type of an inserted buffer (free or busy).
* @param[in] p_item Pointer to an inserted buffer.
*/
void sys_sa_buffer_put(sys_slab_buffer_type_t type, pd_data_ind_t * p_item);
/**@brief Gets item from one of the queues of the SLAB allocator.
*
* @details This function is used to get the item from the SLAB allocator
* queues. Type of buffer shall be chosen. The buffer is deleted
* from the SLAB allocator
*
* @param[in] type Type of a gotten buffer (free or busy).
*
* @retval Pointer to a gotten buffer in case of success. NULL otherwise.
*/
pd_data_ind_t * sys_sa_buffer_get(sys_slab_buffer_type_t type);
/**@brief Deletes an allocated item from the heap.
*
* @details This function is used to delete allocated by SLAB allocator buffer
* from the heap. Pointer to a frame memory of an allocated item shall be used.
*
* @param[in] p_frame Pointer to a frame memory of an allocated item.
*/
void sys_sa_buffer_free(uint8_t * p_frame);
/**@brief Returns buffer back to queue of free buffers.
*
* @details This function is used to return allocated buffer back to the queue
* without allocation and deallocation.
*
* @param[in] p_item Pointer to an allocated item.
*/
void sys_sa_buffer_release(pd_data_ind_t * p_item);
/**@brief Allocates memory for the queue of free buffers.
*
* @details This function is used to allocate buffer from heap
* and put them into the queue
*
* @retval True in case of success. False otherwise.
*/
bool sys_sa_memory_allocate(void);
/**@brief Checks if there are any buffers in the SLAB allocator queue or not.
*
* @details Type of checked buffers shall be passed.
*
* @param[in] type Type of an checked buffers (free or busy).
*
* @retval True in case of absence of buffers. False otherwise.
*/
bool sys_sa_is_empty(sys_slab_buffer_type_t type);
/** @} */
#endif /* SYS_SLAB_ALLOCATOR_H_INCLUDED */

View File

@ -0,0 +1,155 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SYS_SLEEP_H_INCLUDED
#define SYS_SLEEP_H_INCLUDED
#include <stdint.h>
#include "sys_events.h"
#include "hal_sleep.h"
/** @file
*
* @defgroup sys_sleep Falling Asleep API
* @ingroup sys_15_4
* @{
* @brief Module for declaring the Falling Asleep API.
* @details Because additional preparation may be required to be done by user modules,
* prior to putting hardware into the sleep mode, a notification and approval mechanism
* is provided to the user.
* Each module that wants to be notified about the "falling asleep" event, has to subscribe
* to the HAL_EVENT_FALLING_ASLEEP event, using sys_sleep_approver_register(), and to
* get the unique approver's ID value.
* In the handler of the HAL_EVENT_FALLING_ASLEEP event, the module is able to perform
* the required preparation before falling asleep, and to approve the falling asleep request,
* using the module unique approver ID, after all preparation to sleep is finished.
* The hardware will fall asleep only after all the registered approvers
* approve the fall asleep request.
*/
/**@brief Approver ID typedef.
*/
typedef uint8_t sys_sleep_approver_id_t;
/* Sanity check for CONFIG_MAX_SLEEP_APPROVERS
*/
#if (!defined(CONFIG_MAX_SLEEP_APPROVERS))
# error "CONFIG_MAX_SLEEP_APPROVERS must be defined in config file"
#elif (CONFIG_MAX_SLEEP_APPROVERS >= 256)
# error "CONFIG_MAX_SLEEP_APPROVERS must be less than 256"
#endif
/**@brief Function for initializing the system sleep module.
*
* @details This function must be called before any usage of the System Sleep module.
*/
void sys_sleep_init(void);
/**@brief Function for registering the approver of the system sleep request.
*
* @details After the sleep approver is registered with this function, the hardware will
* not fall asleep without its approval.
*
* @param[in] p_event_falling_asleep Event descriptor, which will handle
* the SYS_EVENT_FALLING_ASLEEP event.
* @param[in] p_event_wake_up Event descriptor, which will handle
* the SYS_EVENT_WAKE_UP event.
*
* @retval The unique approver ID, reserved for this newly-registered approver.
* This ID will be required to approve system sleep requests by this approver module.
*/
sys_sleep_approver_id_t sys_sleep_approver_register(
sys_event_desc_t * p_event_falling_asleep,
sys_event_desc_t * p_event_wake_up);
/**@brief Function for unregistering the approver of the system sleep request.
*
* @details After the approver is unregistered, its approval will not be
* required to put the system into sleep mode.
*
* @param[in] approver_id The unique approver ID to be unregistered.
* @param[in] p_event_falling_asleep Event descriptor to unsubscribe from
* the SYS_EVENT_FALLING_ASLEEP event.
* @param[in] p_event_wake_up Event descriptor to unsubscribe from
* the SYS_EVENT_WAKE_UP event.
*/
void sys_sleep_approver_unregister(
sys_sleep_approver_id_t approver_id,
sys_event_desc_t * p_event_falling_asleep,
sys_event_desc_t * p_event_wake_up);
/**@brief Function for approving the system sleep request.
*
* @details This function is to be called by the registered approver
* in order to approve putting the system into the sleep mode.
*
* @param[in] approver_id The unique approver ID.
*/
void sys_sleep_approve(sys_sleep_approver_id_t approver_id);
/**@brief Function for requesting the system to safely enter into sleep mode.
*
* @details This function notifies all the registered sleep approvers with the
* HAL_EVENT_FALLING_ASLEEP event, allowing them to perform all the needed preparation
* before the hardware falls asleep. The hardware will enter sleep mode only after
* all registered approvers approve the fall asleep request.
*
* @param[in] sleep_time_ms Defines sleep time in ms.
*/
void sys_sleep_request_ms(uint32_t sleep_time_ms);
/**@brief Function for getting information about the wakeup reason.
*
* @retval hal_wakeup_reason Interrupt source which was the wakeup reason.
*/
hal_wakeup_reason_t sys_sleep_wakeup_reason(void);
/** @} */
#endif // SYS_SLEEP_H_INCLUDED

View File

@ -0,0 +1,121 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SYS_TASK_SCHEDULER_H_INCLUDED
#define SYS_TASK_SCHEDULER_H_INCLUDED
#include <stdint.h>
#include <stdbool.h>
#include "sys_utils.h"
#include "hal_atomic.h"
#include "sys_events.h"
/** @file
* @defgroup sys_task_scheduler Task scheduler
* @ingroup sys_15_4
* @{
* @brief Module for task scheduling.
*/
/**@brief Identificators for registered handlers.
*
* Handlers will be called from the task scheduler.
*/
typedef enum
{
PHY_TASK_ID,
HAL_TASK_ID,
#if (CONFIG_HIGHEST_LAYER_PHY == 0)
MAC_TASK_ID,
#endif
APP_TASK_ID,
SYS_TASK_ID,
SYS_TASKS_AMOUNT
} sys_task_ids_t;
/**@brief Prototype of a task handler.
*
* @details Handler which will be called by the scheduler.
*/
typedef void (* sys_task_handler_t)(void);
/**@brief Pending tasks.
*
* @details Variable which includes markers of pending tasks.
*/
extern volatile uint_fast16_t g_tasks;
/**@brief Notify task scheduler to add a task for execution.
*
* @details The function sets a marker for the task for execution.
* The task handler implements a tree architecture.
* Task handler of each layer includes handlers of the layer's components.
*
* @param[in] task_id Task identificator.
*/
static inline void sys_task_post(sys_task_ids_t task_id)
{
atomic_t atomic = 0;
hal_atomic_start(&atomic);
g_tasks |= BIT(task_id);
#if (CONFIG_USE_SYS_TASK_NOTIFIER == 1)
sys_event_post(SYS_EVENT_NEW_TASK, NULL);
#endif
hal_atomic_end(&atomic);
}
/**@brief Returns true, if there are any event flags awaiting in the system scheduler.
*/
static inline bool sys_tasks_pending(void)
{
return g_tasks != 0;
}
/**@brief Handle tasks in the main function.
*
* @details Handle tasks in the main function.
*/
void sys_task_run(void);
/** @} */
#endif // SYS_TASK_SCHEDULER_H_INCLUDED

View File

@ -0,0 +1,180 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SYS_TIME_H_INCLUDED
#define SYS_TIME_H_INCLUDED
#include <stdint.h>
#include "sys_queue.h"
/** @file
* This file contains declarations of the primitives to work with Time (timers) and necessary types.
*
* @defgroup sys_time Time API
* @ingroup sys_15_4
* @{
* @brief Module for declaring Time API.
* @details The system time module implements some routines to deal with time (timers). The timer can be started by
* sys_timer_start(), stopped by sys_timer_stop(), and adjusted after sleep by sys_timer_adjust(). Some
* information can be acquired by sys_timer_is_started() and sys_time_get(). The correct API for implementing hardware
* delays is sys_time_delay_us(). Note that the module must be initialized by sys_timers_init() which
* is done by sys_init().
*/
/**@brief Unsigned type of system time.
*/
typedef uint64_t sys_time_t;
/**@brief Signed type of system time.
*/
typedef int64_t sys_signed_time_t;
/**@brief Prototype of the user-defined timer callback.
*
* @param p_data Pointer to the data, specific for this callback.
*/
typedef void (* sys_timer_callback_t)(void * p_data);
/**@brief System timer type (one-shot or periodic timer).
*/
typedef enum
{
SYS_TIMER_ONESHOT, /**< The timer is Oneshot */
SYS_TIMER_PERIODIC /**< The timer is Periodic */
} sys_timer_type_t;
/**@brief Timer descriptor.
*/
typedef struct
{
/** Service field. */
sys_queue_item_t item;
/** Service field. */
sys_time_t absolute_time;
/** Relevant time moment, at which this timer is programmed to be triggered,
* measured in microseconds.
*/
sys_time_t interval;
/** Periodic or one-shot timer.
*
* @details If type is set to SYS_TIMER_PERIODIC, the timer will restart automatically
* with the same period.
*/
sys_timer_type_t type;
/** Timer callback function.
*
* @details This function is to be called, when this timer triggers.
*/
sys_timer_callback_t callback;
/** Timer callback parameter.
*
* @details This pointer is to be passed to the timer callback function.
*/
void * p_data;
} sys_timer_t;
/**@brief Function for initializing the timers module.
*/
void sys_timers_init(void);
/**@brief Function for starting the timer.
*
* @details See the description of \ref sys_timer_t fields for the details
* on how to program the timer.
*
* @param[in] p_timer Pointer to a valid timer descriptor, which is filled by the user,
* according to \ref sys_timer_t fields description.
*/
void sys_timer_start(sys_timer_t * p_timer);
/**@brief Function for stopping the timer.
*
* @details This function is used to stop the timer, which was started earlier.
* After this function is called, the timer will not fire.
*
* @param[in] p_timer Pointer to a valid timer descriptor.
*/
void sys_timer_stop(sys_timer_t * p_timer);
/**@brief Function for checking if input timer has been started.
*
* @param[in] p_timer Pointer to a timer.
*
* @retval true p_timer has been started and has not been stopped yet.
* @retval false p_timer has never been started or already timed out.
*/
bool sys_timer_is_started(sys_timer_t * p_timer);
/**@brief Function for getting the current system time.
*
* @retval The current system timer counter value in microseconds.
*/
sys_time_t sys_time_get(void);
/**@brief Function for implementing a delay for short hardware delays.
*
* @warning Interrupts are NOT disabled inside this function.
*
* @param[in] delay_us Number of microseconds to delay.
*/
void sys_time_delay_us(uint32_t delay_us);
/**@brief Function for executing expired timers after sleep.
*/
void sys_timer_adjust(void);
/** @} */
#endif // SYS_TIME_H_INCLUDED

View File

@ -0,0 +1,541 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef SYS_UTILS_H_INCLUDED
#define SYS_UTILS_H_INCLUDED
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#if (defined(__GNUC__) && !defined(__SES_ARM))
#include <strings.h>
#endif
#ifdef __MINGW32__
#define ffs __builtin_ffs
#endif
/** @file
* This file contains definitions of useful macros and types.
*
* @defgroup sys_utils System Utilities API
* @ingroup sys_15_4
* @{
* @brief Module to declare System Utilities API.
* @details The System Utilities module implements multiple useful macros and inlines for the whole stack. Including
* this header you will get access to GET_PARENT_BY_FIELD(), FIELD_SIZE() to work with complex structures,
* ARRAY_SIZE() for arrays, mathematics macros like IMP(), LL_MIN(), LL_MAX(), CEIL(), ROUND(), Bitmap helpers
* and many others. The variable arguments support macros are also defined here. Some SWAP routines are implemented
* by this module as well.
*/
/**@brief Returns the pointer to the data structure
*
* @param[in] struct_type name of the parent structure
* @param[in] field_name name of the structure field
* @param[in] field_pointer pointer to the structure field
*
* @retval Pointer to the parent structure which includes the field.
*/
#define GET_PARENT_BY_FIELD(struct_type, field_name, field_pointer) \
((struct_type*)(void*)(((uint8_t*)field_pointer) - offsetof(struct_type, field_name)))
/**@brief Returns the implication of two given expressions x and y.
* @details The implication means: if X==TRUE then Y==TRUE.
* The formula is: (X imp Y) = ((not X) or Y)
*/
#define IMP(x, y) ( !(x) || (y) )
/**@brief Returns the minimum of two given expressions x and y.
*/
#define LL_MIN(x, y) ( ((x) < (y)) ? (x) : (y) )
/**@brief Returns the maximum of two given expressions x and y.
*/
#define LL_MAX(x, y) ( ((x) > (y)) ? (x) : (y) )
/**@brief Returns the quotient of a divided by b rounded upwards to the nearest
* integer.
*/
#define CEIL(a, b) ((a) ? (((a) - 1U) / (b) + 1U) : 0U)
/**@brief Returns the quotient of a divided by b rounded to the nearest integer
* according to the standard arithmetic rules: if the fractional part of (a/b) is greater
* or equal to 0.5 then the result is rounded upwards; if the fractional part of (a/b) is
* less then 0.5 the result is rounded downwards.
*
* @note Use this formula only for unsigned arguments. The formula is not compatible with
* the signed arguments: when a and b have different signs it gives incorrect result.
*/
#define ROUND(a, b) ( ((a) + ((b) >> 1)) / (b) )
/**@brief Declares a long bitmap named name of size bits. The size is rounded
* upwards to come a multiple of 8.
*/
#define BITMAP_DECLARE(name, size) uint8_t name[CEIL(size, 8)]
/**@brief Clears all bits in given bitmap.
*/
#define BITMAP_RESET(name) memset((name), 0U, sizeof(name))
/**@brief Returns the value of a bit at position bit in the long bitmap named name.
*/
#define BITMAP_ISSET(name, bit) ( 0 != ((name)[(bit) >> 3] & (1 << ((bit) & 0x7))) )
/**@brief Sets the bit at position bit in the long bitmap named name.
*/
#define BITMAP_SET(name, bit) (name)[(bit) >> 3] |= (1 << ((bit) & 0x7))
/**@brief Clears the bit at position bit in the long bitmap named name.
*/
#define BITMAP_CLR(name, bit) (name)[(bit) >> 3] &= ~(1 << ((bit) & 0x7))
/**@brief Assigns the given bitmap with the second bitmap.
*/
#define BITMAP_ASSIGN(nameDst, nameSrc) memcpy((nameDst), (nameSrc), sizeof(nameDst))
/**@brief Compares two bitmaps and returns zero if they are equal.
*/
#define BITMAP_EQUAL(name1, name2) ((sizeof(name1) == sizeof(name2)) && \
(memcmp((name1), (name2), sizeof(name1)) == 0))
/**@brief Checks number. Return true if number is power of two.
*/
#define LL_IS_POWER_OF_TWO(name) ((0 != (name)) && (0 == ((name)&(name - 1))))
/**@brief Return True if mask is fully included into a given set and False otherwise
*/
#define IS_SUBSET_OF(mask, set) ((mask) == ((set) & (mask)))
/**@brief Creates a bit mask with single set bit on the specified position.
*/
#define BIT(pos) (1UL << (pos))
/**@brief Gets the given bit in the given value
*/
#define BIT_GET(val, pos) ((((uint32_t)val) & BIT(pos)) != 0)
/**@brief Sets or clears the given bit in the given value
*/
#define BIT_SET(val, pos, bit) { \
if (bit) \
{ \
val |= BIT(pos); \
} \
else \
{ \
val &= ~BIT(pos); \
} \
}
/**@brief Returns two to the income power.*/
#define POWER2(n) (1ULL << (n))
/**@brief Creates a bit mask of specified length.
*/
#define BIT_MASK(len) (BIT(len) - 1UL)
/**@brief Creates a bit field mask of specified length and start position.
*/
#define BIT_FIELD_MASK(start, len) (BIT_MASK(len) << (start))
/**@brief Creates a bit field mask of specified length, start position and value.
*/
#define BIT_FIELD_VALUE(value, start, len) (((value) & BIT_MASK(len)) << (start))
/**@brief Extracts a bit field value of specified start position and length.
*/
#define GET_BITFIELD_VALUE(bitmask, start, len) (((bitmask) >> (start)) & BIT_MASK(len))
/**@brief Inserts a bit field value with specified start position and length.
*/
#define SET_BITFIELD_VALUE(bitmask, start, len, value) \
(bitmask = (bitmask & ~BIT_FIELD_MASK(start, len)) | BIT_FIELD_VALUE(value, start, len))
/**@brief Extracts a mask from a BITMAP.
* BITMAP MUST be aligned and mask length MUST be one of 2, 4, 8, 16, 32.
*/
#define BITMAP_MASK_GET(bitmap, bit, len) \
GET_BITFIELD_VALUE(((uint32_t*)(bitmap))[(bit) >> 5], (bit) & 0x1F, len)
/**@brief Sets up a mask to a BITMAP.
* BITMAP MUST be aligned and mask length MUST be one of 2, 4, 8, 16, 32.
*/
#define BITMAP_MASK_SET(bitmap, bit, len, value) \
SET_BITFIELD_VALUE(((uint32_t*)(bitmap))[(bit) >> 5], (bit) & 0x1F, len, value)
/**@brief Gets amount of the arguments.
*/
#define VA_NARGS(...) VA_NARGS_EVAL(__VA_ARGS__)
#define VA_NARGS_EVAL(...) VA_NARGS_IMPL(__VA_ARGS__, \
/* 255, 254, */ 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243, 242, 241, 240, \
239, 238, 237, 236, 235, 234, 233, 232, 231, 230, 229, 228, 227, 226, 225, 224, \
223, 222, 221, 220, 219, 218, 217, 216, 215, 214, 213, 212, 211, 210, 209, 208, \
207, 206, 205, 204, 203, 202, 201, 200, 199, 198, 197, 196, 195, 194, 193, 192, \
191, 190, 189, 188, 187, 186, 185, 184, 183, 182, 181, 180, 179, 178, 177, 176, \
175, 174, 173, 172, 171, 170, 169, 168, 167, 166, 165, 164, 163, 162, 161, 160, \
159, 158, 157, 156, 155, 154, 153, 152, 151, 150, 149, 148, 147, 146, 145, 144, \
143, 142, 141, 140, 139, 138, 137, 136, 135, 134, 133, 132, 131, 130, 129, 128, \
127, 126, 125, 124, 123, 122, 121, 120, 119, 118, 117, 116, 115, 114, 113, 112, \
111, 110, 109, 108, 107, 106, 105, 104, 103, 102, 101, 100, 99, 98, 97, 96, \
095, 94, 93, 92, 91, 90, 89, 88, 87, 86, 85, 84, 83, 82, 81, 80, \
079, 78, 77, 76, 75, 74, 73, 72, 71, 70, 69, 68, 67, 66, 65, 64, \
063, 62, 61, 60, 59, 58, 57, 56, 55, 54, 53, 52, 51, 50, 49, 48, \
047, 46, 45, 44, 43, 42, 41, 40, 39, 38, 37, 36, 35, 34, 33, 32, \
031, 30, 29, 28, 27, 26, 25, 24, 23, 22, 21, 20, 19, 18, 17, 16, \
015, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0)
/**@brief Helper macro. Gets amount of the arguments.
*/
#define VA_NARGS_IMPL(_________1, _2, _3, _4, _5, _6, _7, \
_8, _9, _10, _11, _12, _13, _14, _15, \
__16, _17, _18, _19, _20, _21, _22, _23, \
_24, _25, _26, _27, _28, _29, _30, _31, \
__32, _33, _34, _35, _36, _37, _38, _39, \
_40, _41, _42, _43, _44, _45, _46, _47, \
__48, _49, _50, _51, _52, _53, _54, _55, \
_56, _57, _58, _59, _60, _61, _62, _63, \
__64, _65, _66, _67, _68, _69, _70, _71, \
_72, _73, _74, _75, _76, _77, _78, _79, \
__80, _81, _82, _83, _84, _85, _86, _87, \
_88, _89, _90, _91, _92, _93, _94, _95, \
__96, _97, _98, _99, _100, _101, _102, _103, \
_104, _105, _106, _107, _108, _109, _110, _111, \
_112, _113, _114, _115, _116, _117, _118, _119, \
_120, _121, _122, _123, _124, _125, _126, _127, \
_128, _129, _130, _131, _132, _133, _134, _135, \
_136, _137, _138, _139, _140, _141, _142, _143, \
_144, _145, _146, _147, _148, _149, _150, _151, \
_152, _153, _154, _155, _156, _157, _158, _159, \
_160, _161, _162, _163, _164, _165, _166, _167, \
_168, _169, _170, _171, _172, _173, _174, _175, \
_176, _177, _178, _179, _180, _181, _182, _183, \
_184, _185, _186, _187, _188, _189, _190, _191, \
_192, _193, _194, _195, _196, _197, _198, _199, \
_200, _201, _202, _203, _204, _205, _206, _207, \
_208, _209, _210, _211, _212, _213, _214, _215, \
_216, _217, _218, _219, _220, _221, _222, _223, \
_224, _225, _226, _227, _228, _229, _230, _231, \
_232, _233, _234, _235, _236, _237, _238, _239, \
_240, _241, _242, _243, _244, _245, _246, _247, \
_248, _249, _250, _251, _252, _253, /* _254, _255, */\
N, ...) N
/**@brief Gets amount of the arguments. Execute by compiler.
*/
#define VA_NARGS_COMPILE_TIME(...) ((uint8_t)(sizeof((uint8_t[]){ __VA_ARGS__ })/sizeof(uint8_t)))
/**@brief Swaps values.
*/
#define SWAP_XOR(a, b) \
do \
{ \
(((b) ^= (a) ^= (b), (a) ^= (b))); \
} while(0);
/**@brief Compare two number and take care of overflow threshold limit.
*/
#define COMPARE_WITH_THRESHOLD(a, b, threshold) \
(((LL_MAX((a), (b)) - LL_MIN((a), (b))) < (threshold)) ? ((a) >= (b) ? 1 : 0) : ((a) > (b) ? 0 : 1))
#define ROUND_MASK(a) ((a) - 1)
#define ROUND_UP(x, a) (((x) + ROUND_MASK(a)) & ~ROUND_MASK(a))
#define ROUND_DOWN(x, a) ((x) & ~ROUND_MASK(a))
/**@brief Dereferences input pointer \a y as a type \a x.
*
* @param[in] x type name.
* @param[in] y pointer name.
*/
#define DEREF_VOID_PTR_AS(x, y) (*(x *)y)
/**@brief Extends some bit value to the left extending 2's complement value
* to 8-bit length.
*
* @param[out] result variable, where result is store to.
* @param[in] x input value.
* @param[in] sign_pos an integer in range 2..6 specifying bit position of sign bit.
*/
#define SIGN_EXTENSION(result, x, sign_pos) \
do \
{ \
result = x & (1 << sign_pos) ? \
x | (~((1 << (sign_pos + 1)) - 1)) : \
x & ((1 << (sign_pos + 1)) - 1); \
} while (0)
/**@brief Clears some most significant bits of integer value reducing it precision.
* Name and interface of the macro emphasizes complementary action to #SIGN_EXTENSION.
*
* @param[out] result variable, where result is store to.
* @param[in] x input value.
* @param[in] sign_pos an integer in range 2..6 specifying bit position of sign bit.
*/
#define SIGN_COMPRESSION(result, x, sign_pos) \
do \
{ \
result = x & ((1 << (sign_pos + 1)) - 1); \
} while (0)
/************************* PROTOTYPES **************************************************/
/**@brief Swaps values of two bytes.
*
*/
static inline void SWAP8(uint8_t * const x, uint8_t * const y)
{
uint8_t _x = *x;
*x = *y;
*y = _x;
}
/**@brief Swaps values of two double words (DWORD).
*
*/
static inline void SWAP32(uint32_t * const x, uint32_t * const y)
{
uint32_t _x = *x;
*x = *y;
*y = _x;
}
/**@brief Swaps values of two arrays.
*
* @param[inout] x array pointer
* @param[inout] y array pointer
* @param[in] length amount of bytes to swap
*/
static inline void SWAP_ARRAYS(void * x, void * y, uint32_t length)
{
uint8_t *_x = (uint8_t *)(void *)x;
uint8_t *_y = (uint8_t *)(void *)y;
if (0x0 == ((((size_t)_x) | ((size_t)_y)) & 0x3))
{
size_t len4 = length / sizeof(uint32_t);
for (size_t i = 0; i < len4; i++)
{
SWAP32((uint32_t*)_x, (uint32_t*)_y);
_x += sizeof(uint32_t);
_y += sizeof(uint32_t);
}
length &= 0x3;
}
for (size_t i = 0; i < length; i++)
{
SWAP8(_x, _y);
_x++;
_y++;
}
}
/**@brief Find the first bit of the bitmap with the given value
* (one or zero, as specified).
*
* @param[in] p_bitmap Pointer to bitmap.
* @param[in] bitmap_size Number of bits in the bitmap.
* @param[in] bit_value The bit value to find (one or zero).
*
* @retval Bit position of the bit with specified value, or bitmap_size if no such bit
* was found.
*/
static inline size_t bitmap_find_bit(uint8_t * p_bitmap, size_t bitmap_size, uint8_t bit_value)
{
#if (defined(__GNUC__) && !defined(__SES_ARM))
if (bitmap_size <= 32)
{
uint32_t bitmap;
memcpy(&bitmap, p_bitmap, sizeof(uint32_t));
if (!bit_value)
{
bitmap ^= 0xFFFFFFFF;
}
size_t result = ffs(bitmap);
if (result == 0 || result > bitmap_size)
{
return bitmap_size;
}
// built-in ffs implementation gives ffs(1) = 1, not 0
return result - 1;
}
else
#endif
{
for (size_t i = 0; i < bitmap_size; i++)
{
if (BITMAP_ISSET(p_bitmap, i) == bit_value)
{
return i;
}
}
return bitmap_size;
}
}
/**@brief Reverse the elements of array
*
* @param[in] ptr Pointer to array.
* @param[in] len Length of array.
*/
static inline void array_reverse(uint8_t * ptr, size_t len)
{
for (size_t i = 0; i < len/2; i++)
{
SWAP_XOR(ptr[i], ptr[len - 1 - i]);
}
}
/**@brief Returns least significant byte of word.
*/
#define LSB_WORD(x) ((uint8_t)(x & 0xFF))
/**@brief Returns least significant byte of halfword.
*/
#define LSB_HWORD(x) LSB_WORD(x)
/**@brief Returns most significant byte of halfword.
*/
#define MSB_HWORD(x) ((uint8_t)(x >> 8))
#define ALIGN_VALUE (sizeof(size_t))
/**@brief Compiler-independent definitions.
*/
#if defined ( __CC_ARM )
#ifndef __WEAK
#define __WEAK __weak
#endif
#ifndef PACK
#define PACK __attribute__ ((packed))
#endif
#ifndef BEGIN_PACK
#define BEGIN_PACK
#endif
#ifndef END_PACK
#define END_PACK
#endif
#ifndef __ALIGN
#define __ALIGN(n) __align(n)
#endif
#elif defined ( __ICCARM__ )
#ifndef __WEAK
#define __WEAK __weak
#endif
#ifndef PACK
#define PACK
#endif
#ifndef BEGIN_PACK
#define BEGIN_PACK _Pragma("pack(push, 1)")
#endif
#ifndef END_PACK
#define END_PACK _Pragma("pack(pop)")
#endif
#ifndef __ALIGN
#define __ALIGN(n)
#endif
#elif defined ( __GNUC__ )
#ifndef __WEAK
#define __WEAK __attribute__((weak))
#endif
#ifndef PACK
#define PACK __attribute__ ((packed))
#endif
#ifndef BEGIN_PACK
#define BEGIN_PACK _Pragma("pack(push,1)")
#endif
#ifndef END_PACK
#define END_PACK _Pragma("pack(pop)")
#endif
#ifndef __ALIGN
#define __ALIGN(n) __attribute__((aligned(n)))
#endif
#elif defined ( __TASKING__ )
#ifndef __WEAK
#define __WEAK __attribute__((weak))
#endif
#ifndef PACK
#define PACK __attribute__ ((packed))
#endif
#ifndef BEGIN_PACK
#define BEGIN_PACK
#endif
#ifndef END_PACK
#define END_PACK
#endif
#ifndef __ALIGN
#define __ALIGN(n) __align(n)
#endif
#endif
/** @} */
#endif /* SYS_UTILS_H_INCLUDED */

View File

@ -0,0 +1,110 @@
/**
* Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
*
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form, except as embedded into a Nordic
* Semiconductor ASA integrated circuit in a product or a software update for
* such product, must reproduce the above copyright notice, this list of
* conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
*
* 3. Neither the name of Nordic Semiconductor ASA nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* 4. This software, with or without modification, must only be used with a
* Nordic Semiconductor ASA integrated circuit.
*
* 5. Any software provided in binary form under this license must not be reverse
* engineered, decompiled, modified and/or disassembled.
*
*
* THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
* OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
* GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef STACK_802_15_4_CONFIG_H__
#define STACK_802_15_4_CONFIG_H__
#define CONFIG_DEBUG 1
#define CONFIG_MM_DEBUG 1
#define CONFIG_TEST_CHANNEL 15
#define CONFIG_TEST_CHANNEL_MASK (1 << CONFIG_TEST_CHANNEL)
#define CONFIG_BEACON_ENABLED 1
#define CONFIG_FFD_DEVICE 1
#define CONFIG_RXE_ENABLED 1
#define CONFIG_GTS_ENABLED 1
#define CONFIG_SYNC_REQ_ENABLED 1
#define CONFIG_ASSOCIATE_IND_ENABLED 1
#define CONFIG_ORPHAN_ENABLED 1
#define CONFIG_START_ENABLED 1
#define CONFIG_ED_SCAN_ENABLED 1
#define CONFIG_ACTIVE_SCAN_ENABLED 1
#define CONFIG_PURGE_ENABLED 1
#define CONFIG_PANID_CONFLICT_RESOLUTION_ENABLED 1
#define CONFIG_ASSOCIATION_REQ_CMD_RX_ENABLED 1
#define CONFIG_ASSOCIATION_REQ_CMD_TX_ENABLED 1
#define CONFIG_ASSOCIATION_RESP_CMD_RX_ENABLED 1
#define CONFIG_ASSOCIATION_RESP_CMD_TX_ENABLED 1
#define CONFIG_DISASSOCIATION_NTF_CMD_RX_ENABLED 1
#define CONFIG_DISASSOCIATION_NTF_CMD_TX_ENABLED 1
#define CONFIG_DATA_REQ_CMD_RX_ENABLED 1
#define CONFIG_DATA_REQ_CMD_TX_ENABLED 1
#define CONFIG_PAN_CONFLICT_NTF_CMD_RX_ENABLED 1
#define CONFIG_PAN_CONFLICT_NTF_CMD_TX_ENABLED 1
#define CONFIG_ORPHAN_NTF_CMD_RX_ENABLED 1
#define CONFIG_ORPHAN_NTF_CMD_TX_ENABLED 1
#define CONFIG_BEACON_REQ_CMD_RX_ENABLED 1
#define CONFIG_BEACON_REQ_CMD_TX_ENABLED 1
#define CONFIG_COORD_REALIGN_CMD_RX_ENABLED 1
#define CONFIG_COORD_REALIGN_CMD_TX_ENABLED 1
#define CONFIG_GTS_REQ_CMD_RX_ENABLED 1
#define CONFIG_GTS_REQ_CMD_TX_ENABLED 1
#define CONFIG_INDIRECT_ENGINE_ENABLED 1
#define CONFIG_ASSOCIATE_REQ_ENABLED 1
#define CONFIG_DISASSOCIATE_ENABLED 1
#define CONFIG_PANID_CONFLICT_ENABLED 1
#define CONFIG_SYNC_ENABLED 1
#define CONFIG_NONE_ADDR_SUPPORT_ENABLED 1
#define CONFIG_PASSIVE_ORPHAN_SCAN_ENABLED 1
#define CONFIG_PROMISCUOUS_MODE_ENABLED 1
#define CONFIG_USE_SYS_TASK_NOTIFIER 1
#define CONFIG_POOL_SIZE 0x2000
#define CONFIG_SLAB_FRAME_POOL_SIZE 4
#define CONFIG_MEMORY_POLLING_INTERVAL_MS 10
#define CONFIG_MAX_SLEEP_APPROVERS 32
#define CONFIG_HAL_UART_CHANNELS 1
#define CONFIG_MAC_KEY_TABLE_SIZE 8
#define CONFIG_MAC_DEVICE_TABLE_SIZE 8
#define CONFIG_MAC_SECURITY_LEVEL_TABLE_SIZE 8
#define CONFIG_MAC_KEY_ID_LOOKUP_LIST_SIZE 8
#define CONFIG_MAC_KEY_DEVICE_LIST_SIZE 8
#define CONFIG_MAC_KEY_USAGE_LIST_SIZE 8
#define CONFIG_IEEE_ADDRESS 0x0123456789ABCDEFULL
#define CONFIG_BEACON_RX_TIME 5000
#define CONFIG_TEST_SUBTREE_MAC 1
#define CONFIG_TEST_SUBTREE_TST 1
#define CONFIG_COAP_TICK_INTERVAL_US 500000
#define CONFIG_COAP_MM_SMALL_BLOCK_COUNT 32
#define CONFIG_COAP_MM_MEDIUM_BLOCK_COUNT 32
#define CONFIG_COAP_MM_LARGE_BLOCK_COUNT 32
#define CONFIG_COAP_MESSAGE_QUEUE_SIZE 32
#endif // STACK_802_15_4_CONFIG_H__

Binary file not shown.

View File

@ -0,0 +1,38 @@
Copyright (c) 2016 - 2020 Nordic Semiconductor ASA and Luxoft Global Operations Gmbh.
All Rights Reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form, except as embedded into a Nordic
Semiconductor ASA integrated circuit in a product or a software update for
such product, must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other
materials provided with the distribution.
3. Neither the name of Nordic Semiconductor ASA nor the names of its
contributors may be used to endorse or promote products derived from this
software without specific prior written permission.
4. This software, with or without modification, must only be used with a
Nordic Semiconductor ASA integrated circuit.
5. Any software provided in binary form under this license must not be reverse
engineered, decompiled, modified and/or disassembled.
THIS SOFTWARE IS PROVIDED BY NORDIC SEMICONDUCTOR ASA "AS IS" AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL NORDIC SEMICONDUCTOR ASA OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Some files were not shown because too many files have changed in this diff Show More