Hi there,
I want to manage certain devices that have an address and a value. I would like to dynamically add and remove devices from my data structure. I believe that using a linked list would be the best choice for this task. It's essential that I use the nRF5 SDK for development purposes, as switching to nRF Connect is not feasible due to ongoing development efforts.
Initially, I considered using the Sorted List library from the nRF5 SDK, but despite a thorough search, I couldn't find any relevant examples in the SDK examples folder or on the web, and I also found that the online documentation was quite sparse and there seemed to be some bugs, link2. Nevertheless, I created a simple example that seems to work reasonably well.
Example:
typedef struct {
uint32_t data;
uint8_t address[8];
nrf_sortlist_item_t item;
} item_t;
bool compare_function(nrf_sortlist_item_t * p_item0, nrf_sortlist_item_t * p_item1)
{
item_t * _p_item0 = CONTAINER_OF(p_item0, item_t, item);
item_t * _p_item1 = CONTAINER_OF(p_item1, item_t, item);
return (_p_item0->address > _p_item1->address) ? true : false;
}
NRF_SORTLIST_DEF(example_list, compare_function);
int main(void) {
uint32_t err_code;
// Initialize Logs, Power & Timer.
log_init();
timers_init();
power_management_init();
item_t item0, item1, item2, item3;
item0.data = 100;
int64_t address = 1;
memcpy(item0.address, &(address), sizeof(address));
item1.data = 110;
address++;
memcpy(item1.address, &(address), sizeof(address));
item2.data = 120;
address++;
memcpy(item2.address, &(address), sizeof(address));
nrf_sortlist_add(&example_list, &item0.item);
nrf_sortlist_add(&example_list, &item1.item);
nrf_sortlist_add(&example_list, &item2.item);
item3.data = 115;
address++;
memcpy(item3.address, &(address), sizeof(address));
nrf_sortlist_add(&example_list, &item3.item);
NRF_LOG_INFO("Test 1: iteration throught");
nrf_sortlist_item_t const * pp_curr = nrf_sortlist_peek(&example_list);
item_t * p_item;
while(pp_curr != NULL)
{
p_item = CONTAINER_OF(pp_curr, item_t, item);
NRF_LOG_INFO("p_item:data: %d, address:%d",p_item->data, p_item->address[0]);
pp_curr = nrf_sortlist_next(pp_curr);
}
NRF_LOG_INFO("Test 2: iteration throught a removed element.");
nrf_sortlist_remove(&example_list, &item2.item);
pp_curr = nrf_sortlist_peek(&example_list);
while(pp_curr != NULL)
{
p_item = CONTAINER_OF(pp_curr, item_t, item);
NRF_LOG_INFO("p_item:data: %d, address:%d",p_item->data, p_item->address[0]);
pp_curr = nrf_sortlist_next(pp_curr);
}
NRF_LOG_INFO("Finished");
for (;;) {
app_sched_execute();
idle_state_handle();
}
}
In this implementation I would also need to deal with memory allocations. Is there an example of how should I allocate heap memory?
Also, I'm curious if there are any additional examples or resources related to sorted linked lists that I may have missed.
Would Nordic recommend that I use a different library or approach?
Thanks for the help!!!