soft_rtc.c 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. /*
  2. * Copyright (c) 2006-2018, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2018-01-30 armink the first version
  9. */
  10. #include <time.h>
  11. #include <string.h>
  12. #include <rtthread.h>
  13. #include <drivers/rtc.h>
  14. #ifdef RT_USING_SOFT_RTC
  15. /* 2018-01-30 14:44:50 = RTC_TIME_INIT(2018, 1, 30, 14, 44, 50) */
  16. #define RTC_TIME_INIT(year, month, day, hour, minute, second) \
  17. {.tm_year = year - 1900, .tm_mon = month - 1, .tm_mday = day, .tm_hour = hour, .tm_min = minute, .tm_sec = second}
  18. #ifndef SOFT_RTC_TIME_DEFAULT
  19. #define SOFT_RTC_TIME_DEFAULT RTC_TIME_INIT(2018, 1, 1, 0, 0 ,0)
  20. #endif
  21. static struct rt_device soft_rtc_dev;
  22. static rt_tick_t init_tick;
  23. static time_t init_time;
  24. static rt_err_t soft_rtc_control(rt_device_t dev, int cmd, void *args)
  25. {
  26. time_t *time;
  27. struct tm time_temp;
  28. RT_ASSERT(dev != RT_NULL);
  29. memset(&time_temp, 0, sizeof(struct tm));
  30. switch (cmd)
  31. {
  32. case RT_DEVICE_CTRL_RTC_GET_TIME:
  33. time = (time_t *) args;
  34. *time = init_time + (rt_tick_get() - init_tick) / RT_TICK_PER_SECOND;
  35. break;
  36. case RT_DEVICE_CTRL_RTC_SET_TIME:
  37. {
  38. time = (time_t *) args;
  39. init_time = *time - (rt_tick_get() - init_tick) / RT_TICK_PER_SECOND;
  40. break;
  41. }
  42. }
  43. return RT_EOK;
  44. }
  45. #ifdef RT_USING_DEVICE_OPS
  46. const static struct rt_device_ops soft_rtc_ops =
  47. {
  48. RT_NULL,
  49. RT_NULL,
  50. RT_NULL,
  51. RT_NULL,
  52. RT_NULL,
  53. soft_rtc_control
  54. };
  55. #endif
  56. int rt_soft_rtc_init(void)
  57. {
  58. static rt_bool_t init_ok = RT_FALSE;
  59. struct tm time_new = SOFT_RTC_TIME_DEFAULT;
  60. if (init_ok)
  61. {
  62. return 0;
  63. }
  64. /* make sure only one 'rtc' device */
  65. RT_ASSERT(!rt_device_find("rtc"));
  66. init_tick = rt_tick_get();
  67. init_time = mktime(&time_new);
  68. soft_rtc_dev.type = RT_Device_Class_RTC;
  69. /* register rtc device */
  70. #ifdef RT_USING_DEVICE_OPS
  71. soft_rtc_dev.ops = &soft_rtc_ops;
  72. #else
  73. soft_rtc_dev.init = RT_NULL;
  74. soft_rtc_dev.open = RT_NULL;
  75. soft_rtc_dev.close = RT_NULL;
  76. soft_rtc_dev.read = RT_NULL;
  77. soft_rtc_dev.write = RT_NULL;
  78. soft_rtc_dev.control = soft_rtc_control;
  79. #endif
  80. /* no private */
  81. soft_rtc_dev.user_data = RT_NULL;
  82. rt_device_register(&soft_rtc_dev, "rtc", RT_DEVICE_FLAG_RDWR);
  83. init_ok = RT_TRUE;
  84. return 0;
  85. }
  86. INIT_DEVICE_EXPORT(rt_soft_rtc_init);
  87. #endif /* RT_USING_SOFT_RTC */