secure.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // Copyright 2022 QMK
  2. // SPDX-License-Identifier: GPL-2.0-or-later
  3. #include "secure.h"
  4. #include "timer.h"
  5. #ifndef SECURE_UNLOCK_TIMEOUT
  6. # define SECURE_UNLOCK_TIMEOUT 5000
  7. #endif
  8. #ifndef SECURE_IDLE_TIMEOUT
  9. # define SECURE_IDLE_TIMEOUT 60000
  10. #endif
  11. #ifndef SECURE_UNLOCK_SEQUENCE
  12. # define SECURE_UNLOCK_SEQUENCE \
  13. { \
  14. { 0, 0 } \
  15. }
  16. #endif
  17. static secure_status_t secure_status = SECURE_LOCKED;
  18. static uint32_t unlock_time = 0;
  19. static uint32_t idle_time = 0;
  20. secure_status_t secure_get_status(void) {
  21. return secure_status;
  22. }
  23. void secure_lock(void) {
  24. secure_status = SECURE_LOCKED;
  25. }
  26. void secure_unlock(void) {
  27. secure_status = SECURE_UNLOCKED;
  28. idle_time = timer_read32();
  29. }
  30. void secure_request_unlock(void) {
  31. if (secure_status == SECURE_LOCKED) {
  32. secure_status = SECURE_PENDING;
  33. unlock_time = timer_read32();
  34. }
  35. }
  36. void secure_activity_event(void) {
  37. if (secure_status == SECURE_UNLOCKED) {
  38. idle_time = timer_read32();
  39. }
  40. }
  41. void secure_keypress_event(uint8_t row, uint8_t col) {
  42. static const uint8_t sequence[][2] = SECURE_UNLOCK_SEQUENCE;
  43. static const uint8_t sequence_len = sizeof(sequence) / sizeof(sequence[0]);
  44. static uint8_t offset = 0;
  45. if ((sequence[offset][0] == row) && (sequence[offset][1] == col)) {
  46. offset++;
  47. if (offset == sequence_len) {
  48. offset = 0;
  49. secure_unlock();
  50. }
  51. } else {
  52. offset = 0;
  53. secure_lock();
  54. }
  55. }
  56. void secure_task(void) {
  57. #if SECURE_UNLOCK_TIMEOUT != 0
  58. // handle unlock timeout
  59. if (secure_status == SECURE_PENDING) {
  60. if (timer_elapsed32(unlock_time) >= SECURE_UNLOCK_TIMEOUT) {
  61. secure_lock();
  62. }
  63. }
  64. #endif
  65. #if SECURE_IDLE_TIMEOUT != 0
  66. // handle idle timeout
  67. if (secure_status == SECURE_UNLOCKED) {
  68. if (timer_elapsed32(idle_time) >= SECURE_IDLE_TIMEOUT) {
  69. secure_lock();
  70. }
  71. }
  72. #endif
  73. }