Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

107 lines
2.3 KiB

  1. /*
  2. RTMEM MODULE
  3. Copyright (C) 2019 by Maxim Prokhorov <prokhorov dot max at outlook dot com>
  4. */
  5. #include "rtcmem.h"
  6. volatile RtcmemData* Rtcmem = reinterpret_cast<volatile RtcmemData*>(RTCMEM_ADDR);
  7. bool _rtcmem_status = false;
  8. void _rtcmemErase() {
  9. auto ptr = reinterpret_cast<volatile uint32_t*>(RTCMEM_ADDR);
  10. const auto end = ptr + RTCMEM_BLOCKS;
  11. DEBUG_MSG_P(PSTR("[RTCMEM] Erasing start=%p end=%p\n"), ptr, end);
  12. do {
  13. *ptr = 0;
  14. } while (++ptr != end);
  15. }
  16. void _rtcmemInit() {
  17. _rtcmemErase();
  18. Rtcmem->magic = RTCMEM_MAGIC;
  19. }
  20. // Treat memory as dirty on cold boot, hardware wdt reset and rst pin
  21. bool _rtcmemStatus() {
  22. bool readable;
  23. switch (systemResetReason()) {
  24. case REASON_EXT_SYS_RST:
  25. case REASON_WDT_RST:
  26. case REASON_DEFAULT_RST:
  27. readable = false;
  28. break;
  29. default:
  30. readable = true;
  31. }
  32. readable = readable and (RTCMEM_MAGIC == Rtcmem->magic);
  33. return readable;
  34. }
  35. #if TERMINAL_SUPPORT
  36. void _rtcmemInitCommands() {
  37. terminalRegisterCommand(F("RTCMEM.REINIT"), [](Embedis* e) {
  38. _rtcmemInit();
  39. });
  40. #if DEBUG_SUPPORT
  41. terminalRegisterCommand(F("RTCMEM.DUMP"), [](Embedis* e) {
  42. DEBUG_MSG_P(PSTR("[RTCMEM] boot_status=%u status=%u blocks_used=%u\n"),
  43. _rtcmem_status, _rtcmemStatus(), RtcmemSize);
  44. String line;
  45. line.reserve(96);
  46. char buffer[16] = {0};
  47. auto addr = reinterpret_cast<volatile uint32_t*>(RTCMEM_ADDR);
  48. uint8_t block = 1;
  49. uint8_t offset = 0;
  50. uint8_t start = 0;
  51. do {
  52. offset = block - 1;
  53. snprintf(buffer, sizeof(buffer), "%08x ", *(addr + offset));
  54. line += buffer;
  55. if ((block % 8) == 0) {
  56. DEBUG_MSG_P(PSTR("%02u %p: %s\n"), start, addr+start, line.c_str());
  57. start = block;
  58. line = "";
  59. }
  60. ++block;
  61. } while (block<(RTCMEM_BLOCKS+1));
  62. });
  63. #endif
  64. }
  65. #endif
  66. bool rtcmemStatus() {
  67. return _rtcmem_status;
  68. }
  69. void rtcmemSetup() {
  70. _rtcmem_status = _rtcmemStatus();
  71. if (!_rtcmem_status) {
  72. _rtcmemInit();
  73. }
  74. #if TERMINAL_SUPPORT
  75. _rtcmemInitCommands();
  76. #endif
  77. }