1 /* USER CODE BEGIN Header */
2 /**
3   ******************************************************************************
4   * @file    adv_buff_alloc_tiny.c
5   * @author  AMS - RF Application team
6   * @brief   Module providing a simplified scheme for buffer allocation for
7   *          legacy advertising.
8   ******************************************************************************
9   * @attention
10   *
11   * Copyright (c) 2024 STMicroelectronics.
12   * All rights reserved.
13   *
14   * This software is licensed under terms that can be found in the LICENSE file
15   * in the root directory of this software component.
16   * If no LICENSE file comes with this software, it is provided AS-IS.
17   *
18   ******************************************************************************
19   */
20 /* USER CODE END Header */
21 #include <stdint.h>
22 #include <stdlib.h>
23 #include "adv_buff_alloc_tiny.h"
24 
25 uint8_t buffer[NUM_BUFFERS][31];
26 
27 /* Variable used to keep which buffer is used and which one is not in use by the link layer. */
28 uint8_t used_buffers_msk;
29 
30 #define BUFFER_IN_USE(i)        (used_buffers_msk & (1<<i))
31 #define SET_BUFFER_IN_USE(i)    (used_buffers_msk |= (1<<i))
32 #define CLEAR_BUFFER_IN_USE(i)  (used_buffers_msk &= ~(1<<i))
33 
34 /**
35 * @brief  Initialize the module for buffer allocation.
36 * @retval None
37 */
adv_tiny_buff_init(void)38 void adv_tiny_buff_init(void)
39 {
40   used_buffers_msk = 0;
41 }
42 
43 /**
44 * @brief  Mark a buffer as free.
45 * @param  buff Pointer to the buffer
46 * @retval None
47 */
adv_tiny_buff_free(void * p)48 void adv_tiny_buff_free(void * p)
49 {
50   for(int i = 0; i < NUM_BUFFERS; i++)
51   {
52     if(p == buffer[i])
53     {
54       CLEAR_BUFFER_IN_USE(i);
55       return;
56     }
57   }
58 }
59 
60 /**
61 * @brief  Allocate a buffer of 31 bytes for legacy advertising or scan response data.
62 * @retval It returns the pointer to the buffer.
63 */
adv_tiny_buff_alloc(void)64 void * adv_tiny_buff_alloc(void)
65 {
66   uint8_t i;
67 
68   for(i = 0; i < NUM_BUFFERS && BUFFER_IN_USE(i) ; i++);
69 
70   if(i == NUM_BUFFERS)
71   {
72     // No free buffer found.
73     return NULL;
74   }
75 
76   SET_BUFFER_IN_USE(i);
77 
78   return buffer[i];
79 }
80