68 lines
1.9 KiB
C++
68 lines
1.9 KiB
C++
#pragma once
|
|
|
|
#include <Arduino.h>
|
|
#include <LittleFS.h>
|
|
#include <functional> // For std::function
|
|
|
|
class RfidDB {
|
|
public:
|
|
// The default constructor uses "/rfid.db"
|
|
RfidDB(const String& filename = "/rfid.db");
|
|
~RfidDB();
|
|
|
|
/**
|
|
* @brief Initializes the filesystem and the database file.
|
|
* Must be called once in setup().
|
|
* @return true on success, otherwise false.
|
|
*/
|
|
bool begin();
|
|
|
|
/**
|
|
* @brief Returns the number of stored IDs.
|
|
*/
|
|
uint32_t count();
|
|
|
|
/**
|
|
* @brief Checks if an ID exists in the database.
|
|
* @param id The ID to check.
|
|
* @return true if the ID exists, otherwise false.
|
|
*/
|
|
bool contains(uint32_t id);
|
|
|
|
/**
|
|
* @brief Adds a new ID. The ID is only added if it does not already exist.
|
|
* @param id The ID to add.
|
|
* @return true if the ID was successfully added, otherwise false.
|
|
*/
|
|
bool add(uint32_t id);
|
|
|
|
/**
|
|
* @brief Removes an ID from the database.
|
|
* @param id The ID to remove.
|
|
* @return true if the ID was found and removed, otherwise false.
|
|
*/
|
|
bool remove(uint32_t id);
|
|
|
|
/**
|
|
* @brief Iterates over all stored IDs and calls a callback function for each.
|
|
* @param callback The function to be called for each ID (e.g., a lambda: `[](uint32_t id){ Serial.println(id); }`).
|
|
*/
|
|
void iterate(std::function<void(uint32_t)> callback);
|
|
|
|
private:
|
|
String filename_;
|
|
String tmpFilename_;
|
|
bool initialized_ = false;
|
|
|
|
static constexpr size_t ENTRY_SIZE = sizeof(uint32_t);
|
|
|
|
// Helper methods
|
|
bool readEntryAt(File &f, uint32_t index, uint32_t &out);
|
|
bool writeEntryAt(File &f, uint32_t index, uint32_t value);
|
|
bool binarySearch(File &f, uint32_t &outIndex, uint32_t key, bool &found);
|
|
uint32_t byteSwap(uint32_t x) const;
|
|
uint32_t fileEntryCount(File &f);
|
|
};
|
|
|
|
// Global instance, kept as requested
|
|
extern RfidDB rfidDB; |