The following code examples show the typical usage of Flash Data Storage in an application.
Initialization, like every other operation in FDS which involves writing or erasing flash memory, is an asynchronous operation whose completion is reported to the application through a callback. Therefore, before initializing FDS, you must register a callback handler to handle FDS events.
The following example code shows the signature of the event handler and how to register it with FDS:
After the event handler has been registered, initialize FDS:
The operation will return an event notification upon success.
In the Peer Manager, fds_init is part of the initialization function pm_init.
The following example code shows how to write a record:
The command is queued up, and the success or failure is indicated through event callbacks. Upon success, the fds_write function returns a descriptor for the record, which can be used to further manipulate the record.
Instead of writing a record right away, it is possible to reserve memory beforehand and use the resulting reservation token to either write the record at a later moment using the functions fds_reserve, and fds_write_reserved. To cancel a reservation, use fds_reserve_cancel.
Because the uniqueness of record keys is not enforced, looking up a record by a given set of keys can result in multiple matches. To handle multiple matches, the fds_find, fds_find_by_type and fds_find_by_instance functions accept a fds_find_token_t structure as parameter, which is used to keep information about the progress of the operation. Once a descriptor for a matching record is returned by the first invocation of any of these functions, subsequent calls using the same token will resume searching from the last record matched. Therefore, it is possible to enumerate records. The following example code shows how to use the find functionality to retrieve a record and read its contents.
Keep in mind that closing a record using fds_close will not invalidate the record descriptor neither the fds_record_t structure. In fact, the record descriptor can still be used to manipulate the record, e.g. opening it again or deleting it. However, the data pointed by the fds_record_t structure is not guaranteed to remain unmodified if the record has been closed.
To delete a record, you must . This can either be returned by fds_write or it can be obtained using fds_find, fds_find_by_type and fds_find_by_instance as shown above. The following example code shows clear an item for which you have a descriptor for:
The operation is queued up, and the success or failure is indicated through event callbacks.
Keep in mind that using fds_clear will not free the flash memory used by the record. To reclaim flash space used by records deleted using fds_clear, use fds_gc.