mirror of
https://github.com/deunix-educ/voice-assistant.git
synced 2026-11-26 20:19:43 +01:00
F2 : enregistrer, lister et supprimer les empreintes du capteur R503
- Firmware : FingerprintEnrollment (deux poses du même doigt, doublon refusé, poses de doigts différents refusées, délais), FingerprintPort (interface testable), commandes du capteur (image, extraction, recherche, fusion, écriture, suppression, table d'index), commandes MQTT fp_enroll / fp_delete / fp_list / fp_cancel. - Délai de 3 s pour les commandes qui calculent (300 ms étaient trop courts) ; tout code inattendu du capteur est journalisé. - Serveur : section fingerprint.users (emplacement -> nom), FingerprintBook. - Outils : tools/finger.py, make finger-list | finger-enroll | finger-delete. - 53 tests nouveaux (automate compilé avec g++, outil avec une carte simulée). Vérifié sur la carte : enregistrement, liste, refus d'un doigt déjà connu et de deux doigts différents. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -53,6 +53,13 @@ void CommandHandler::handle(const uint8_t* payload, size_t length) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (strncmp(command, "fp_", 3) == 0) {
|
||||
if (_onFingerprint != nullptr) {
|
||||
_onFingerprint(command, doc["id"] | -1, doc["all"] | false);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (strcmp(command, "device") == 0) {
|
||||
handleDevice(doc["device"] | "", doc["action"] | "");
|
||||
return;
|
||||
|
||||
@@ -23,6 +23,11 @@
|
||||
* {"cmd":"capture","active":true} (étape 13) le serveur a entendu le mot de
|
||||
* réveil et écoute la commande : LED allumée
|
||||
*
|
||||
* {"cmd":"fp_enroll","id":3} (branche fingerprint, F2) enregistre un doigt
|
||||
* {"cmd":"fp_delete","id":3} ou {"cmd":"fp_delete","all":true} supprime une empreinte ou toutes
|
||||
* {"cmd":"fp_list"} / {"cmd":"fp_cancel"} liste les empreintes / abandonne l'enregistrement
|
||||
* -> les réponses sont des événements « fp_… » (voir main.cpp)
|
||||
*
|
||||
* Le traitement reste court : il est appelé depuis le rappel MQTT, dans loop().
|
||||
*/
|
||||
class CommandHandler {
|
||||
@@ -30,9 +35,15 @@ public:
|
||||
/// Rappel pour un mode activé ou désactivé par le serveur.
|
||||
using ModeCallback = void (*)(bool enabled);
|
||||
|
||||
/// Rappel des commandes d'empreinte : nom de la commande, id (-1 si absent), « all » vrai ou faux.
|
||||
using FingerprintCallback = void (*)(const char* command, int id, bool all);
|
||||
|
||||
CommandHandler(PlaybackStream& playback, MqttLink& mqtt, DemoDevices& devices,
|
||||
ModeCallback onListen, ModeCallback onCapture);
|
||||
|
||||
/// Branche les commandes d'empreinte (branche fingerprint) ; sans cela, elles sont ignorées.
|
||||
void setFingerprintCallback(FingerprintCallback callback) { _onFingerprint = callback; }
|
||||
|
||||
/// Traite un message du topic control.
|
||||
void handle(const uint8_t* payload, size_t length);
|
||||
|
||||
@@ -42,6 +53,7 @@ private:
|
||||
DemoDevices& _devices;
|
||||
ModeCallback _onListen;
|
||||
ModeCallback _onCapture;
|
||||
FingerprintCallback _onFingerprint = nullptr;
|
||||
|
||||
/// Commande domotique : exécution puis confirmation sur voice/<id>/event.
|
||||
void handleDevice(const char* device, const char* action);
|
||||
|
||||
@@ -0,0 +1,223 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include <functional>
|
||||
|
||||
#include "FingerprintPort.h"
|
||||
|
||||
/**
|
||||
* @file FingerprintEnrollment.h
|
||||
* @brief Enregistrement d'une empreinte : deux poses du même doigt, sans attente bloquante.
|
||||
*
|
||||
* Déroulement (chaque attente est limitée par @p timeoutMs) :
|
||||
*
|
||||
* attend un doigt → capture, extrait (tampon 1), vérifie qu'il n'est pas déjà connu
|
||||
* → attend le retrait → attend un doigt → capture, extrait (tampon 2)
|
||||
* → fusionne les deux (elles doivent être du même doigt) → écrit à l'emplacement demandé.
|
||||
*
|
||||
* update() est appelé à chaque tour de loop() : il ne dialogue avec le capteur que
|
||||
* lorsque le signal de touche annonce un doigt, au plus une fois toutes les pollMs.
|
||||
* Header seul, sans Arduino : testé sur le PC (server/tests/test_fingerprint_enrollment.py).
|
||||
*/
|
||||
class FingerprintEnrollment {
|
||||
public:
|
||||
/// Étape annoncée à l'écouteur.
|
||||
enum class Step : uint8_t {
|
||||
Start, ///< enregistrement lancé : poser le doigt
|
||||
Retry, ///< capture inutilisable (reason) : retirer le doigt et recommencer
|
||||
RemoveFinger, ///< première pose réussie : retirer le doigt
|
||||
PlaceAgain, ///< doigt retiré : reposer le MÊME doigt
|
||||
Done, ///< empreinte enregistrée
|
||||
Failed, ///< abandon (reason) ; pour already_enrolled, l'id est celui du doigt déjà connu
|
||||
};
|
||||
|
||||
/// Reçoit chaque étape : (étape, id, motif ou nullptr).
|
||||
using Listener = std::function<void(Step, uint16_t, const char*)>;
|
||||
|
||||
static constexpr uint8_t MAX_RETRIES = 5; ///< captures inutilisables tolérées avant d'abandonner
|
||||
|
||||
FingerprintEnrollment(FingerprintPort& port, Listener listener, uint32_t timeoutMs, uint32_t pollMs = 60,
|
||||
uint32_t releaseMs = 300)
|
||||
: _port(port), _listener(std::move(listener)), _timeoutMs(timeoutMs), _pollMs(pollMs),
|
||||
_releaseMs(releaseMs) {}
|
||||
|
||||
/// true pendant un enregistrement.
|
||||
bool busy() const { return _state != State::Idle; }
|
||||
|
||||
/**
|
||||
* @brief Lance l'enregistrement à l'emplacement @p id.
|
||||
* @return false si un enregistrement est déjà en cours.
|
||||
*/
|
||||
bool begin(uint16_t id, uint32_t now) {
|
||||
if (busy()) {
|
||||
return false;
|
||||
}
|
||||
_id = id;
|
||||
_retries = 0;
|
||||
enter(State::First, now);
|
||||
_listener(Step::Start, _id, nullptr);
|
||||
return true;
|
||||
}
|
||||
|
||||
/// Abandonne l'enregistrement en cours (sans effet au repos).
|
||||
void cancel() {
|
||||
if (busy()) {
|
||||
fail("cancelled", _id, false);
|
||||
}
|
||||
}
|
||||
|
||||
/// À appeler à chaque tour de loop() avec millis().
|
||||
void update(uint32_t now) {
|
||||
if (!busy()) {
|
||||
return;
|
||||
}
|
||||
if (now - _phaseStart > _timeoutMs) {
|
||||
fail("timeout", _id);
|
||||
return;
|
||||
}
|
||||
if (_state == State::Release) {
|
||||
watchRelease(now);
|
||||
return;
|
||||
}
|
||||
if (now - _lastPoll < _pollMs) {
|
||||
return;
|
||||
}
|
||||
_lastPoll = now;
|
||||
if (!_port.touched()) {
|
||||
return;
|
||||
}
|
||||
const auto image = _port.getImage();
|
||||
if (image == FingerprintPort::NO_FINGER) {
|
||||
return; // le signal de touche précède la lecture : on réessaie au prochain tour
|
||||
}
|
||||
if (image != FingerprintPort::OK) {
|
||||
fail("sensor", _id);
|
||||
return;
|
||||
}
|
||||
if (_state == State::First) {
|
||||
firstPose(now);
|
||||
} else {
|
||||
secondPose(now);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
enum class State : uint8_t { Idle, First, Release, Second };
|
||||
|
||||
FingerprintPort& _port;
|
||||
Listener _listener;
|
||||
uint32_t _timeoutMs;
|
||||
uint32_t _pollMs;
|
||||
uint32_t _releaseMs;
|
||||
State _state = State::Idle;
|
||||
State _afterRelease = State::First;
|
||||
uint16_t _id = 0;
|
||||
uint8_t _retries = 0;
|
||||
uint32_t _phaseStart = 0;
|
||||
uint32_t _lastPoll = 0;
|
||||
uint32_t _releasedSince = 0;
|
||||
bool _releasing = false;
|
||||
|
||||
// Entre dans une attente : l'anneau dit ce que le capteur attend.
|
||||
void enter(State state, uint32_t now) {
|
||||
_state = state;
|
||||
_phaseStart = now;
|
||||
_lastPoll = now;
|
||||
if (state == State::First || state == State::Second) {
|
||||
_port.setAura(FingerprintPort::Aura::Breathing, FingerprintPort::Color::Blue, 0x60, 0);
|
||||
} else if (state == State::Release) {
|
||||
_releasing = false;
|
||||
_port.setAura(FingerprintPort::Aura::Off, FingerprintPort::Color::Blue, 0, 0);
|
||||
}
|
||||
}
|
||||
|
||||
void firstPose(uint32_t now) {
|
||||
const auto extracted = _port.extract(1);
|
||||
if (extracted != FingerprintPort::OK) {
|
||||
retry(extracted, now);
|
||||
return;
|
||||
}
|
||||
uint16_t found = 0;
|
||||
uint16_t score = 0;
|
||||
const auto searched = _port.search(1, found, score);
|
||||
if (searched == FingerprintPort::OK) {
|
||||
fail("already_enrolled", found);
|
||||
return;
|
||||
}
|
||||
if (searched != FingerprintPort::NO_MATCH_IN_LIBRARY) {
|
||||
fail("sensor", _id);
|
||||
return;
|
||||
}
|
||||
_port.setAura(FingerprintPort::Aura::On, FingerprintPort::Color::Purple, 0, 0);
|
||||
_listener(Step::RemoveFinger, _id, nullptr);
|
||||
_afterRelease = State::Second;
|
||||
enter(State::Release, now);
|
||||
}
|
||||
|
||||
void secondPose(uint32_t now) {
|
||||
const auto extracted = _port.extract(2);
|
||||
if (extracted != FingerprintPort::OK) {
|
||||
retry(extracted, now);
|
||||
return;
|
||||
}
|
||||
const auto merged = _port.createModel();
|
||||
if (merged != FingerprintPort::OK) {
|
||||
fail(merged == FingerprintPort::MODEL_MISMATCH ? "mismatch" : "sensor", _id);
|
||||
return;
|
||||
}
|
||||
const auto stored = _port.store(1, _id);
|
||||
if (stored != FingerprintPort::OK) {
|
||||
fail(stored == FingerprintPort::BAD_LOCATION ? "bad_id"
|
||||
: stored == FingerprintPort::FLASH_ERROR ? "storage" : "sensor", _id);
|
||||
return;
|
||||
}
|
||||
_state = State::Idle;
|
||||
_port.setAura(FingerprintPort::Aura::Flashing, FingerprintPort::Color::Blue, 0x20, 3);
|
||||
_listener(Step::Done, _id, nullptr);
|
||||
}
|
||||
|
||||
// Capture inutilisable : on le dit, on attend le retrait du doigt, puis on recommence la même pose.
|
||||
void retry(FingerprintPort::Code code, uint32_t now) {
|
||||
if (code != FingerprintPort::IMAGE_MESSY && code != FingerprintPort::FEATURES_TOO_FEW) {
|
||||
fail("sensor", _id);
|
||||
return;
|
||||
}
|
||||
const char* reason = code == FingerprintPort::IMAGE_MESSY ? "messy" : "few_features";
|
||||
if (++_retries > MAX_RETRIES) {
|
||||
fail(reason, _id);
|
||||
return;
|
||||
}
|
||||
_listener(Step::Retry, _id, reason);
|
||||
_afterRelease = _state;
|
||||
enter(State::Release, now);
|
||||
}
|
||||
|
||||
void watchRelease(uint32_t now) {
|
||||
if (_port.touched()) {
|
||||
_releasing = false;
|
||||
return;
|
||||
}
|
||||
if (!_releasing) {
|
||||
_releasing = true;
|
||||
_releasedSince = now;
|
||||
return;
|
||||
}
|
||||
if (now - _releasedSince < _releaseMs) {
|
||||
return;
|
||||
}
|
||||
const bool second = _afterRelease == State::Second;
|
||||
enter(_afterRelease, now);
|
||||
if (second) {
|
||||
_listener(Step::PlaceAgain, _id, nullptr); // aussi après une capture ratée de la 2e pose
|
||||
}
|
||||
}
|
||||
|
||||
void fail(const char* reason, uint16_t id, bool flash = true) {
|
||||
_state = State::Idle;
|
||||
_port.setAura(flash ? FingerprintPort::Aura::Flashing : FingerprintPort::Aura::Off,
|
||||
FingerprintPort::Color::Red, 0x20, 3);
|
||||
_listener(Step::Failed, id, reason);
|
||||
}
|
||||
};
|
||||
@@ -75,6 +75,37 @@ inline size_t build(uint32_t address, uint8_t pid, const uint8_t* payload, size_
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Emplacements occupés d'après une page de la table d'index du capteur.
|
||||
*
|
||||
* Un bit par emplacement, 8 par octet, le bit de poids faible d'abord : l'octet 0 couvre les
|
||||
* emplacements 0 à 7, et ainsi de suite.
|
||||
*
|
||||
* @param bitmap Octets de la page.
|
||||
* @param bytes Nombre d'octets de la page (32).
|
||||
* @param first Emplacement du premier bit de la page.
|
||||
* @param limit Capacité de la bibliothèque : les bits au-delà sont ignorés.
|
||||
* @param ids Reçoit les emplacements occupés.
|
||||
* @param maxIds Taille de @p ids.
|
||||
* @return Nombre d'emplacements occupés (même si @p ids est plein : le compte reste juste).
|
||||
*/
|
||||
inline size_t idsFromIndexTable(const uint8_t* bitmap, size_t bytes, uint16_t first, uint16_t limit,
|
||||
uint16_t* ids, size_t maxIds) {
|
||||
size_t found = 0;
|
||||
for (size_t byte = 0; byte < bytes; ++byte) {
|
||||
for (int bit = 0; bit < 8; ++bit) {
|
||||
const uint16_t id = static_cast<uint16_t>(first + byte * 8 + bit);
|
||||
if (id < limit && (bitmap[byte] & (1u << bit)) != 0) {
|
||||
if (found < maxIds) {
|
||||
ids[found] = id;
|
||||
}
|
||||
++found;
|
||||
}
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Décodeur octet par octet d'un paquet reçu. Pas d'allocation, pas d'attente.
|
||||
*
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
/**
|
||||
* @file FingerprintPort.h
|
||||
* @brief Ce que l'enregistrement d'une empreinte attend du capteur.
|
||||
*
|
||||
* Une interface plutôt que la classe du capteur : le déroulement de l'enregistrement
|
||||
* (FingerprintEnrollment.h) se teste alors sur le PC avec un faux capteur, sans carte.
|
||||
* Pas de dépendance à Arduino.
|
||||
*/
|
||||
class FingerprintPort {
|
||||
public:
|
||||
/// Code de retour : ceux du capteur (0x00 = succès), plus trois erreurs locales.
|
||||
using Code = uint8_t;
|
||||
static constexpr Code OK = 0x00;
|
||||
static constexpr Code NO_FINGER = 0x02;
|
||||
static constexpr Code IMAGE_MESSY = 0x06; ///< image trop brouillée
|
||||
static constexpr Code FEATURES_TOO_FEW = 0x07; ///< pas assez de points caractéristiques
|
||||
static constexpr Code NO_MATCH = 0x08;
|
||||
static constexpr Code NO_MATCH_IN_LIBRARY = 0x09; ///< empreinte inconnue du capteur
|
||||
static constexpr Code MODEL_MISMATCH = 0x0A; ///< les deux poses ne sont pas le même doigt
|
||||
static constexpr Code BAD_LOCATION = 0x0B; ///< emplacement hors de la bibliothèque
|
||||
static constexpr Code WRONG_PASSWORD = 0x13;
|
||||
static constexpr Code FLASH_ERROR = 0x18; ///< écriture en mémoire du capteur impossible
|
||||
static constexpr Code BAD_CHECKSUM = 0xE3; ///< réponse altérée
|
||||
static constexpr Code BAD_REPLY = 0xE5; ///< réponse inattendue ou d'une autre adresse
|
||||
static constexpr Code TIMEOUT = 0xE9; ///< pas de réponse : câblage, débit ou alimentation
|
||||
|
||||
/// Effet de l'anneau lumineux.
|
||||
enum class Aura : uint8_t { Breathing = 1, Flashing = 2, On = 3, Off = 4, FadeIn = 5, FadeOut = 6 };
|
||||
|
||||
/// Couleur de l'anneau (le R503 simple n'a que ces trois-là).
|
||||
enum class Color : uint8_t { Red = 1, Blue = 2, Purple = 3 };
|
||||
|
||||
virtual ~FingerprintPort() = default;
|
||||
|
||||
/// true tant qu'un doigt couvre le capteur (signal de touche, sans dialogue série).
|
||||
virtual bool touched() const = 0;
|
||||
|
||||
/// Capture l'image du doigt posé dans le capteur (NO_FINGER si rien).
|
||||
virtual Code getImage() = 0;
|
||||
|
||||
/// Extrait les caractéristiques de l'image dans le tampon 1 ou 2.
|
||||
virtual Code extract(uint8_t buffer) = 0;
|
||||
|
||||
/// Cherche le contenu d'un tampon dans les empreintes enregistrées : emplacement et score.
|
||||
virtual Code search(uint8_t buffer, uint16_t& id, uint16_t& score) = 0;
|
||||
|
||||
/// Fusionne les tampons 1 et 2 en un modèle.
|
||||
virtual Code createModel() = 0;
|
||||
|
||||
/// Écrit le modèle du tampon à l'emplacement @p id.
|
||||
virtual Code store(uint8_t buffer, uint16_t id) = 0;
|
||||
|
||||
/// Pilote l'anneau lumineux. @p speed : 0 à 255 ; @p times : 0 = sans fin.
|
||||
virtual Code setAura(Aura effect, Color color, uint8_t speed, uint8_t times) = 0;
|
||||
};
|
||||
@@ -4,6 +4,14 @@
|
||||
|
||||
namespace {
|
||||
// Codes d'instruction du capteur (fiche R503).
|
||||
constexpr uint8_t CMD_GET_IMAGE = 0x01;
|
||||
constexpr uint8_t CMD_EXTRACT = 0x02;
|
||||
constexpr uint8_t CMD_SEARCH = 0x04;
|
||||
constexpr uint8_t CMD_CREATE_MODEL = 0x05;
|
||||
constexpr uint8_t CMD_STORE = 0x06;
|
||||
constexpr uint8_t CMD_DELETE = 0x0C;
|
||||
constexpr uint8_t CMD_EMPTY = 0x0D;
|
||||
constexpr uint8_t CMD_INDEX_TABLE = 0x1F;
|
||||
constexpr uint8_t CMD_VERIFY_PASSWORD = 0x13;
|
||||
constexpr uint8_t CMD_READ_PARAMETERS = 0x0F;
|
||||
constexpr uint8_t CMD_TEMPLATE_COUNT = 0x1D;
|
||||
@@ -44,6 +52,7 @@ FingerprintSensor::Code FingerprintSensor::readParameters(Parameters& parameters
|
||||
}
|
||||
const uint8_t* data = _parser.payload() + 1;
|
||||
parameters.libraryCapacity = word(data + 4);
|
||||
_capacity = parameters.libraryCapacity;
|
||||
parameters.securityLevel = word(data + 6);
|
||||
parameters.address = (static_cast<uint32_t>(word(data + 8)) << 16) | word(data + 10);
|
||||
parameters.packetBytes = static_cast<uint16_t>(32u << (word(data + 12) & 0x3));
|
||||
@@ -66,18 +75,88 @@ FingerprintSensor::Code FingerprintSensor::setAura(Aura effect, Color color, uin
|
||||
return exchange(command, sizeof(command));
|
||||
}
|
||||
|
||||
FingerprintSensor::Code FingerprintSensor::listTemplates(uint16_t* ids, size_t maxIds, size_t& found) {
|
||||
found = 0;
|
||||
// La table d'index tient en pages de 256 emplacements (32 octets, un bit chacun).
|
||||
for (uint16_t page = 0; page * 256u < _capacity; ++page) {
|
||||
const uint8_t command[] = {CMD_INDEX_TABLE, static_cast<uint8_t>(page)};
|
||||
const Code code = exchange(command, sizeof(command));
|
||||
if (code != OK || _parser.length() < 33) {
|
||||
return code == OK ? BAD_REPLY : code;
|
||||
}
|
||||
found += FingerprintPacket::idsFromIndexTable(_parser.payload() + 1, 32, static_cast<uint16_t>(page * 256u),
|
||||
_capacity, ids + found, found < maxIds ? maxIds - found : 0);
|
||||
}
|
||||
return OK;
|
||||
}
|
||||
|
||||
FingerprintSensor::Code FingerprintSensor::remove(uint16_t id) {
|
||||
const uint8_t command[] = {CMD_DELETE, static_cast<uint8_t>(id >> 8), static_cast<uint8_t>(id), 0x00, 0x01};
|
||||
return exchange(command, sizeof(command), FP_SLOW_REPLY_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
FingerprintSensor::Code FingerprintSensor::removeAll() {
|
||||
const uint8_t command[] = {CMD_EMPTY};
|
||||
return exchange(command, sizeof(command), FP_SLOW_REPLY_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
bool FingerprintSensor::touched() const {
|
||||
return (digitalRead(_touchPin) == HIGH) != FP_TOUCH_ACTIVE_LOW;
|
||||
}
|
||||
|
||||
FingerprintSensor::Code FingerprintSensor::getImage() {
|
||||
const uint8_t command[] = {CMD_GET_IMAGE};
|
||||
return exchange(command, sizeof(command), FP_SLOW_REPLY_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
FingerprintSensor::Code FingerprintSensor::extract(uint8_t buffer) {
|
||||
const uint8_t command[] = {CMD_EXTRACT, buffer};
|
||||
return exchange(command, sizeof(command), FP_SLOW_REPLY_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
FingerprintSensor::Code FingerprintSensor::search(uint8_t buffer, uint16_t& id, uint16_t& score) {
|
||||
const uint8_t command[] = {CMD_SEARCH, buffer, 0x00, 0x00, static_cast<uint8_t>(_capacity >> 8),
|
||||
static_cast<uint8_t>(_capacity)};
|
||||
const Code code = exchange(command, sizeof(command), FP_SLOW_REPLY_TIMEOUT_MS);
|
||||
if (code != OK) {
|
||||
return code;
|
||||
}
|
||||
if (_parser.length() < 5) {
|
||||
return BAD_REPLY;
|
||||
}
|
||||
id = word(_parser.payload() + 1);
|
||||
score = word(_parser.payload() + 3);
|
||||
return OK;
|
||||
}
|
||||
|
||||
FingerprintSensor::Code FingerprintSensor::createModel() {
|
||||
const uint8_t command[] = {CMD_CREATE_MODEL};
|
||||
return exchange(command, sizeof(command), FP_SLOW_REPLY_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
FingerprintSensor::Code FingerprintSensor::store(uint8_t buffer, uint16_t id) {
|
||||
const uint8_t command[] = {CMD_STORE, buffer, static_cast<uint8_t>(id >> 8), static_cast<uint8_t>(id)};
|
||||
return exchange(command, sizeof(command), FP_SLOW_REPLY_TIMEOUT_MS);
|
||||
}
|
||||
|
||||
const char* FingerprintSensor::describe(Code code) {
|
||||
switch (code) {
|
||||
case OK:
|
||||
return "ok";
|
||||
case NO_FINGER:
|
||||
return "pas de doigt";
|
||||
case IMAGE_MESSY:
|
||||
return "image brouillee";
|
||||
case FEATURES_TOO_FEW:
|
||||
return "pas assez de details sur le doigt";
|
||||
case NO_MATCH_IN_LIBRARY:
|
||||
return "empreinte inconnue";
|
||||
case MODEL_MISMATCH:
|
||||
return "les deux poses ne sont pas le meme doigt";
|
||||
case BAD_LOCATION:
|
||||
return "emplacement hors de la bibliotheque";
|
||||
case FLASH_ERROR:
|
||||
return "ecriture impossible dans le capteur";
|
||||
case WRONG_PASSWORD:
|
||||
return "mot de passe refuse";
|
||||
case BAD_CHECKSUM:
|
||||
@@ -91,7 +170,7 @@ const char* FingerprintSensor::describe(Code code) {
|
||||
}
|
||||
}
|
||||
|
||||
FingerprintSensor::Code FingerprintSensor::exchange(const uint8_t* command, size_t length) {
|
||||
FingerprintSensor::Code FingerprintSensor::exchange(const uint8_t* command, size_t length, uint32_t timeoutMs) {
|
||||
uint8_t packet[FingerprintPacket::MAX_PACKET];
|
||||
const size_t size = FingerprintPacket::build(_address, FingerprintPacket::Command, command, length, packet,
|
||||
sizeof(packet));
|
||||
@@ -105,21 +184,32 @@ FingerprintSensor::Code FingerprintSensor::exchange(const uint8_t* command, size
|
||||
|
||||
_parser = FingerprintPacket::Parser(_address);
|
||||
const uint32_t began = millis();
|
||||
while ((millis() - began) < FP_REPLY_TIMEOUT_MS) {
|
||||
while (_serial.available() > 0) {
|
||||
Code code = TIMEOUT;
|
||||
while ((millis() - began) < timeoutMs) {
|
||||
bool finished = false;
|
||||
while (_serial.available() > 0 && !finished) {
|
||||
const auto status = _parser.feed(static_cast<uint8_t>(_serial.read()));
|
||||
if (status == FingerprintPacket::Parser::Status::Incomplete) {
|
||||
continue;
|
||||
}
|
||||
finished = true;
|
||||
if (status == FingerprintPacket::Parser::Status::Done) {
|
||||
if (_parser.pid() != FingerprintPacket::Ack || _parser.length() < 1) {
|
||||
return BAD_REPLY;
|
||||
}
|
||||
return _parser.payload()[0];
|
||||
code = (_parser.pid() != FingerprintPacket::Ack || _parser.length() < 1) ? BAD_REPLY
|
||||
: _parser.payload()[0];
|
||||
} else {
|
||||
code = status == FingerprintPacket::Parser::Status::BadChecksum ? BAD_CHECKSUM : BAD_REPLY;
|
||||
}
|
||||
return status == FingerprintPacket::Parser::Status::BadChecksum ? BAD_CHECKSUM : BAD_REPLY;
|
||||
}
|
||||
if (finished) {
|
||||
break;
|
||||
}
|
||||
delay(1);
|
||||
}
|
||||
return TIMEOUT;
|
||||
// Les codes attendus en fonctionnement normal restent muets ; tout le reste est dit, avec la commande
|
||||
// et le temps passé : c'est ce qui permet de comprendre un échec sans rien deviner.
|
||||
if (code != OK && code != NO_FINGER && code != NO_MATCH_IN_LIBRARY) {
|
||||
Serial.printf("# empreinte : commande 0x%02X -> code 0x%02X (%s) apres %lu ms\n", command[0], code,
|
||||
describe(code), static_cast<unsigned long>(millis() - began));
|
||||
}
|
||||
return code;
|
||||
}
|
||||
|
||||
@@ -3,6 +3,8 @@
|
||||
#include <Arduino.h>
|
||||
|
||||
#include "FingerprintPacket.h"
|
||||
#include "FingerprintPort.h"
|
||||
#include "config.h"
|
||||
|
||||
/**
|
||||
* @brief Dialogue avec un capteur d'empreinte Grow R503, par liaison série.
|
||||
@@ -13,18 +15,8 @@
|
||||
* Les méthodes d'échange attendent la réponse (FP_REPLY_TIMEOUT_MS au plus) : à
|
||||
* n'appeler que depuis loop() ou setup(), jamais depuis une tâche audio.
|
||||
*/
|
||||
class FingerprintSensor {
|
||||
class FingerprintSensor : public FingerprintPort {
|
||||
public:
|
||||
/// Code de retour : ceux du capteur (0x00 = succès), plus trois erreurs locales.
|
||||
using Code = uint8_t;
|
||||
static constexpr Code OK = 0x00;
|
||||
static constexpr Code NO_FINGER = 0x02;
|
||||
static constexpr Code NO_MATCH_IN_LIBRARY = 0x09;
|
||||
static constexpr Code WRONG_PASSWORD = 0x13;
|
||||
static constexpr Code BAD_CHECKSUM = 0xE3; ///< réponse altérée
|
||||
static constexpr Code BAD_REPLY = 0xE5; ///< réponse inattendue ou d'une autre adresse
|
||||
static constexpr Code TIMEOUT = 0xE9; ///< pas de réponse : câblage, débit ou alimentation
|
||||
|
||||
/// Réglages lus dans le capteur.
|
||||
struct Parameters {
|
||||
uint16_t libraryCapacity = 0; ///< empreintes que le capteur peut garder
|
||||
@@ -34,11 +26,8 @@ public:
|
||||
uint32_t baud = 0;
|
||||
};
|
||||
|
||||
/// Effet de l'anneau lumineux.
|
||||
enum class Aura : uint8_t { Breathing = 1, Flashing = 2, On = 3, Off = 4, FadeIn = 5, FadeOut = 6 };
|
||||
|
||||
/// Couleur de l'anneau (le R503 simple n'a que ces trois-là).
|
||||
enum class Color : uint8_t { Red = 1, Blue = 2, Purple = 3 };
|
||||
/// Capacité des R503 ; remplacée par la valeur lue dans le capteur par readParameters().
|
||||
static constexpr uint16_t DEFAULT_CAPACITY = 200;
|
||||
|
||||
FingerprintSensor(HardwareSerial& serial, int rxPin, int txPin, int touchPin);
|
||||
|
||||
@@ -51,6 +40,9 @@ public:
|
||||
/// true si begin() a réussi : sinon, les autres méthodes ne tentent rien.
|
||||
bool present() const { return _present; }
|
||||
|
||||
/// Empreintes que le capteur peut garder.
|
||||
uint16_t capacity() const { return _capacity; }
|
||||
|
||||
/// Poignée de main (0x40) : le capteur répond OK s'il est prêt.
|
||||
Code handShake();
|
||||
|
||||
@@ -60,12 +52,28 @@ public:
|
||||
/// Nombre d'empreintes enregistrées.
|
||||
Code templateCount(uint16_t& count);
|
||||
|
||||
/// Pilote l'anneau lumineux. @p speed : 0 à 255 ; @p times : 0 = sans fin.
|
||||
Code setAura(Aura effect, Color color, uint8_t speed, uint8_t times);
|
||||
/**
|
||||
* @brief Emplacements occupés (table d'index du capteur).
|
||||
* @param ids Reçoit les emplacements, dans l'ordre croissant.
|
||||
* @param maxIds Taille de @p ids.
|
||||
* @param found Nombre d'emplacements occupés.
|
||||
*/
|
||||
Code listTemplates(uint16_t* ids, size_t maxIds, size_t& found);
|
||||
|
||||
/// true tant qu'un doigt couvre le capteur (signal de touche, sans dialogue série ;
|
||||
/// polarité : FP_TOUCH_ACTIVE_LOW dans config.h).
|
||||
bool touched() const;
|
||||
/// Efface l'empreinte de l'emplacement @p id.
|
||||
Code remove(uint16_t id);
|
||||
|
||||
/// Efface toutes les empreintes.
|
||||
Code removeAll();
|
||||
|
||||
// --- FingerprintPort
|
||||
bool touched() const override;
|
||||
Code getImage() override;
|
||||
Code extract(uint8_t buffer) override;
|
||||
Code search(uint8_t buffer, uint16_t& id, uint16_t& score) override;
|
||||
Code createModel() override;
|
||||
Code store(uint8_t buffer, uint16_t id) override;
|
||||
Code setAura(Aura effect, Color color, uint8_t speed, uint8_t times) override;
|
||||
|
||||
/// Texte français d'un code de retour, pour le journal.
|
||||
static const char* describe(Code code);
|
||||
@@ -76,9 +84,10 @@ private:
|
||||
int _txPin;
|
||||
int _touchPin;
|
||||
uint32_t _address = FingerprintPacket::DEFAULT_ADDRESS;
|
||||
uint16_t _capacity = DEFAULT_CAPACITY;
|
||||
bool _present = false;
|
||||
FingerprintPacket::Parser _parser;
|
||||
|
||||
// Envoie une commande et rend le code de retour ; le contenu de la réponse reste dans _parser.
|
||||
Code exchange(const uint8_t* command, size_t length);
|
||||
Code exchange(const uint8_t* command, size_t length, uint32_t timeoutMs = FP_REPLY_TIMEOUT_MS);
|
||||
};
|
||||
|
||||
+113
-1
@@ -25,6 +25,7 @@
|
||||
#include "AudioOutput.h"
|
||||
#include "CommandHandler.h"
|
||||
#include "DemoDevices.h"
|
||||
#include "FingerprintEnrollment.h"
|
||||
#include "FingerprintSensor.h"
|
||||
#include "MicCapture.h"
|
||||
#include "MicSelfTest.h"
|
||||
@@ -67,6 +68,8 @@ AudioFifo captureFifo; ///< micro -> tâche de capture -> loop() -> réseau
|
||||
PushButton button(PIN_BUTTON_PTT, BUTTON_DEBOUNCE_MS);
|
||||
FingerprintSensor fingerprint(Serial2, PIN_FP_RX, PIN_FP_TX, PIN_FP_TOUCH); ///< capteur R503 (branche fingerprint)
|
||||
bool fingerprintWasTouched = false;
|
||||
void onEnrollmentStep(FingerprintEnrollment::Step step, uint16_t id, const char* reason);
|
||||
FingerprintEnrollment enrollment(fingerprint, onEnrollmentStep, FP_ENROLL_TIMEOUT_MS);
|
||||
StatusLed led(PIN_STATUS_LED);
|
||||
DemoDevices devices(PIN_DEMO_LIGHT);
|
||||
SerialFramer framer(Serial);
|
||||
@@ -107,6 +110,7 @@ PlaybackStream playback(speaker, playbackFifo);
|
||||
void onListen(bool enabled);
|
||||
void onCapture(bool active);
|
||||
CommandHandler commands(playback, mqtt, devices, onListen, onCapture);
|
||||
void onFingerprintCommand(const char* command, int id, bool all);
|
||||
|
||||
// Pile et contrôle de la tâche de capture, alloués statiquement.
|
||||
StaticTask_t captureTaskControl;
|
||||
@@ -503,11 +507,118 @@ void probeFingerprint() {
|
||||
Serial.println("# empreinte : posez un doigt : l'anneau doit passer au violet et le journal l'indiquer");
|
||||
}
|
||||
|
||||
/**
|
||||
* @brief Étape F2 : une étape de l'enregistrement, journalisée et publiée sur voice/<id>/event.
|
||||
*
|
||||
* {"event":"fp_enroll","step":"start|retry|remove_finger|place_again|done|failed","id":3,"reason":"messy"}
|
||||
* Pour « failed/already_enrolled », « id » est l'emplacement du doigt déjà connu.
|
||||
*/
|
||||
void onEnrollmentStep(FingerprintEnrollment::Step step, uint16_t id, const char* reason) {
|
||||
using Step = FingerprintEnrollment::Step;
|
||||
const char* name = "start";
|
||||
switch (step) {
|
||||
case Step::Start: name = "start"; break;
|
||||
case Step::Retry: name = "retry"; break;
|
||||
case Step::RemoveFinger: name = "remove_finger"; break;
|
||||
case Step::PlaceAgain: name = "place_again"; break;
|
||||
case Step::Done: name = "done"; break;
|
||||
case Step::Failed: name = "failed"; break;
|
||||
}
|
||||
Serial.printf("# empreinte : enregistrement %s, emplacement %u%s%s\n", name, id, reason != nullptr ? ", " : "",
|
||||
reason != nullptr ? reason : "");
|
||||
char payload[128];
|
||||
if (reason != nullptr) {
|
||||
snprintf(payload, sizeof(payload), "{\"event\":\"fp_enroll\",\"step\":\"%s\",\"id\":%u,\"reason\":\"%s\"}",
|
||||
name, id, reason);
|
||||
} else {
|
||||
snprintf(payload, sizeof(payload), "{\"event\":\"fp_enroll\",\"step\":\"%s\",\"id\":%u}", name, id);
|
||||
}
|
||||
mqtt.publish("event", payload, false);
|
||||
}
|
||||
|
||||
/// Publie l'échec d'une commande d'empreinte refusée avant même de toucher au capteur.
|
||||
void publishEnrollmentRefused(int id, const char* reason) {
|
||||
char payload[128];
|
||||
snprintf(payload, sizeof(payload), "{\"event\":\"fp_enroll\",\"step\":\"failed\",\"id\":%d,\"reason\":\"%s\"}", id,
|
||||
reason);
|
||||
mqtt.publish("event", payload, false);
|
||||
}
|
||||
|
||||
/// Étape F2 : liste des emplacements occupés, publiée sur voice/<id>/event.
|
||||
void publishFingerprintList() {
|
||||
uint16_t ids[FingerprintSensor::DEFAULT_CAPACITY];
|
||||
size_t found = 0;
|
||||
uint16_t count = 0;
|
||||
const auto listed = fingerprint.listTemplates(ids, sizeof(ids) / sizeof(ids[0]), found);
|
||||
const auto counted = fingerprint.templateCount(count);
|
||||
char payload[1280]; // 200 emplacements de 3 chiffres + virgule au pire : ~800 octets
|
||||
int used = snprintf(payload, sizeof(payload), "{\"event\":\"fp_list\",\"ok\":%s,\"capacity\":%u,\"count\":%u,\"ids\":[",
|
||||
listed == FingerprintSensor::OK ? "true" : "false", fingerprint.capacity(),
|
||||
counted == FingerprintSensor::OK ? count : 0);
|
||||
for (size_t i = 0; listed == FingerprintSensor::OK && i < found && i < sizeof(ids) / sizeof(ids[0]) &&
|
||||
used < static_cast<int>(sizeof(payload)) - 8;
|
||||
++i) {
|
||||
used += snprintf(payload + used, sizeof(payload) - used, "%s%u", i == 0 ? "" : ",", ids[i]);
|
||||
}
|
||||
snprintf(payload + used, sizeof(payload) - used, "]}");
|
||||
Serial.printf("# empreinte : liste : %u emplacement(s) occupe(s), le capteur en compte %u (%s)\n",
|
||||
static_cast<unsigned>(found), count, FingerprintSensor::describe(listed));
|
||||
mqtt.publish("event", payload, false);
|
||||
}
|
||||
|
||||
/// Étape F2 : suppression d'une empreinte (ou de toutes), confirmée sur voice/<id>/event.
|
||||
void deleteFingerprint(int id, bool all) {
|
||||
const auto code = all ? fingerprint.removeAll() : fingerprint.remove(static_cast<uint16_t>(id));
|
||||
char payload[128];
|
||||
if (all) {
|
||||
snprintf(payload, sizeof(payload), "{\"event\":\"fp_delete\",\"all\":true,\"ok\":%s}",
|
||||
code == FingerprintSensor::OK ? "true" : "false");
|
||||
} else {
|
||||
snprintf(payload, sizeof(payload), "{\"event\":\"fp_delete\",\"id\":%d,\"ok\":%s}", id,
|
||||
code == FingerprintSensor::OK ? "true" : "false");
|
||||
}
|
||||
Serial.printf("# empreinte : suppression %s : %s\n", all ? "de toutes" : "d'une", FingerprintSensor::describe(code));
|
||||
mqtt.publish("event", payload, false);
|
||||
}
|
||||
|
||||
/// Commandes fp_* du serveur (CommandHandler) : enregistrer, supprimer, lister, annuler.
|
||||
void onFingerprintCommand(const char* command, int id, bool all) {
|
||||
if (!fingerprint.present()) {
|
||||
Serial.println("# empreinte : commande ignoree, capteur absent");
|
||||
if (strcmp(command, "fp_enroll") == 0) {
|
||||
publishEnrollmentRefused(id, "sensor");
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (strcmp(command, "fp_list") == 0) {
|
||||
publishFingerprintList();
|
||||
} else if (strcmp(command, "fp_cancel") == 0) {
|
||||
enrollment.cancel();
|
||||
} else if (strcmp(command, "fp_delete") == 0) {
|
||||
if (enrollment.busy()) {
|
||||
Serial.println("# empreinte : suppression refusee pendant un enregistrement");
|
||||
} else if (all || (id >= 0 && id < fingerprint.capacity())) {
|
||||
deleteFingerprint(id, all);
|
||||
}
|
||||
} else if (strcmp(command, "fp_enroll") == 0) {
|
||||
if (id < 0 || id >= fingerprint.capacity()) {
|
||||
publishEnrollmentRefused(id, "bad_id");
|
||||
} else if (!enrollment.begin(static_cast<uint16_t>(id), millis())) {
|
||||
publishEnrollmentRefused(id, "busy");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Étape F1 : le signal de touche allume l'anneau et s'affiche dans le moniteur.
|
||||
void updateFingerprint() {
|
||||
if (!fingerprint.present()) {
|
||||
return;
|
||||
}
|
||||
if (enrollment.busy()) {
|
||||
enrollment.update(millis());
|
||||
fingerprintWasTouched = fingerprint.touched(); // l'anneau est piloté par l'enregistrement
|
||||
return;
|
||||
}
|
||||
const bool touched = fingerprint.touched();
|
||||
if (touched == fingerprintWasTouched) {
|
||||
return;
|
||||
@@ -588,8 +699,9 @@ void setup() {
|
||||
}
|
||||
}
|
||||
|
||||
// --- Capteur d'empreinte (branche fingerprint, étape F1).
|
||||
// --- Capteur d'empreinte (branche fingerprint, étapes F1 et F2).
|
||||
probeFingerprint();
|
||||
commands.setFingerprintCallback(onFingerprintCommand);
|
||||
|
||||
// --- Entrée : auto-test du micro.
|
||||
micReady = selfTest.run();
|
||||
|
||||
Reference in New Issue
Block a user