Time.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321
  1. /*
  2. time.c - low level time and date functions
  3. Copyright (c) Michael Margolis 2009-2014
  4. This library is free software; you can redistribute it and/or
  5. modify it under the terms of the GNU Lesser General Public
  6. License as published by the Free Software Foundation; either
  7. version 2.1 of the License, or (at your option) any later version.
  8. This library is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. Lesser General Public License for more details.
  12. You should have received a copy of the GNU Lesser General Public
  13. License along with this library; if not, write to the Free Software
  14. Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  15. 1.0 6 Jan 2010 - initial release
  16. 1.1 12 Feb 2010 - fixed leap year calculation error
  17. 1.2 1 Nov 2010 - fixed setTime bug (thanks to Korman for this)
  18. 1.3 24 Mar 2012 - many edits by Paul Stoffregen: fixed timeStatus() to update
  19. status, updated examples for Arduino 1.0, fixed ARM
  20. compatibility issues, added TimeArduinoDue and TimeTeensy3
  21. examples, add error checking and messages to RTC examples,
  22. add examples to DS1307RTC library.
  23. 1.4 5 Sep 2014 - compatibility with Arduino 1.5.7
  24. */
  25. #if ARDUINO >= 100
  26. #include <Arduino.h>
  27. #else
  28. #include <WProgram.h>
  29. #endif
  30. #include "TimeLib.h"
  31. static tmElements_t tm; // a cache of time elements
  32. static time_t cacheTime; // the time the cache was updated
  33. static uint32_t syncInterval = 300; // time sync will be attempted after this many seconds
  34. void refreshCache(time_t t) {
  35. if (t != cacheTime) {
  36. breakTime(t, tm);
  37. cacheTime = t;
  38. }
  39. }
  40. int hour() { // the hour now
  41. return hour(now());
  42. }
  43. int hour(time_t t) { // the hour for the given time
  44. refreshCache(t);
  45. return tm.Hour;
  46. }
  47. int hourFormat12() { // the hour now in 12 hour format
  48. return hourFormat12(now());
  49. }
  50. int hourFormat12(time_t t) { // the hour for the given time in 12 hour format
  51. refreshCache(t);
  52. if( tm.Hour == 0 )
  53. return 12; // 12 midnight
  54. else if( tm.Hour > 12)
  55. return tm.Hour - 12 ;
  56. else
  57. return tm.Hour ;
  58. }
  59. uint8_t isAM() { // returns true if time now is AM
  60. return !isPM(now());
  61. }
  62. uint8_t isAM(time_t t) { // returns true if given time is AM
  63. return !isPM(t);
  64. }
  65. uint8_t isPM() { // returns true if PM
  66. return isPM(now());
  67. }
  68. uint8_t isPM(time_t t) { // returns true if PM
  69. return (hour(t) >= 12);
  70. }
  71. int minute() {
  72. return minute(now());
  73. }
  74. int minute(time_t t) { // the minute for the given time
  75. refreshCache(t);
  76. return tm.Minute;
  77. }
  78. int second() {
  79. return second(now());
  80. }
  81. int second(time_t t) { // the second for the given time
  82. refreshCache(t);
  83. return tm.Second;
  84. }
  85. int day(){
  86. return(day(now()));
  87. }
  88. int day(time_t t) { // the day for the given time (0-6)
  89. refreshCache(t);
  90. return tm.Day;
  91. }
  92. int weekday() { // Sunday is day 1
  93. return weekday(now());
  94. }
  95. int weekday(time_t t) {
  96. refreshCache(t);
  97. return tm.Wday;
  98. }
  99. int month(){
  100. return month(now());
  101. }
  102. int month(time_t t) { // the month for the given time
  103. refreshCache(t);
  104. return tm.Month;
  105. }
  106. int year() { // as in Processing, the full four digit year: (2009, 2010 etc)
  107. return year(now());
  108. }
  109. int year(time_t t) { // the year for the given time
  110. refreshCache(t);
  111. return tmYearToCalendar(tm.Year);
  112. }
  113. /*============================================================================*/
  114. /* functions to convert to and from system time */
  115. /* These are for interfacing with time serivces and are not normally needed in a sketch */
  116. // leap year calulator expects year argument as years offset from 1970
  117. #define LEAP_YEAR(Y) ( ((1970+(Y))>0) && !((1970+(Y))%4) && ( ((1970+(Y))%100) || !((1970+(Y))%400) ) )
  118. static const uint8_t monthDays[]={31,28,31,30,31,30,31,31,30,31,30,31}; // API starts months from 1, this array starts from 0
  119. void breakTime(time_t timeInput, tmElements_t &tm){
  120. // break the given time_t into time components
  121. // this is a more compact version of the C library localtime function
  122. // note that year is offset from 1970 !!!
  123. uint8_t year;
  124. uint8_t month, monthLength;
  125. uint32_t time;
  126. unsigned long days;
  127. time = (uint32_t)timeInput;
  128. tm.Second = time % 60;
  129. time /= 60; // now it is minutes
  130. tm.Minute = time % 60;
  131. time /= 60; // now it is hours
  132. tm.Hour = time % 24;
  133. time /= 24; // now it is days
  134. tm.Wday = ((time + 4) % 7) + 1; // Sunday is day 1
  135. year = 0;
  136. days = 0;
  137. while((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= time) {
  138. year++;
  139. }
  140. tm.Year = year; // year is offset from 1970
  141. days -= LEAP_YEAR(year) ? 366 : 365;
  142. time -= days; // now it is days in this year, starting at 0
  143. days=0;
  144. month=0;
  145. monthLength=0;
  146. for (month=0; month<12; month++) {
  147. if (month==1) { // february
  148. if (LEAP_YEAR(year)) {
  149. monthLength=29;
  150. } else {
  151. monthLength=28;
  152. }
  153. } else {
  154. monthLength = monthDays[month];
  155. }
  156. if (time >= monthLength) {
  157. time -= monthLength;
  158. } else {
  159. break;
  160. }
  161. }
  162. tm.Month = month + 1; // jan is month 1
  163. tm.Day = time + 1; // day of month
  164. }
  165. time_t makeTime(const tmElements_t &tm){
  166. // assemble time elements into time_t
  167. // note year argument is offset from 1970 (see macros in time.h to convert to other formats)
  168. // previous version used full four digit year (or digits since 2000),i.e. 2009 was 2009 or 9
  169. int i;
  170. uint32_t seconds;
  171. // seconds from 1970 till 1 jan 00:00:00 of the given year
  172. seconds= tm.Year*(SECS_PER_DAY * 365);
  173. for (i = 0; i < tm.Year; i++) {
  174. if (LEAP_YEAR(i)) {
  175. seconds += SECS_PER_DAY; // add extra days for leap years
  176. }
  177. }
  178. // add days for this year, months start from 1
  179. for (i = 1; i < tm.Month; i++) {
  180. if ( (i == 2) && LEAP_YEAR(tm.Year)) {
  181. seconds += SECS_PER_DAY * 29;
  182. } else {
  183. seconds += SECS_PER_DAY * monthDays[i-1]; //monthDay array starts from 0
  184. }
  185. }
  186. seconds+= (tm.Day-1) * SECS_PER_DAY;
  187. seconds+= tm.Hour * SECS_PER_HOUR;
  188. seconds+= tm.Minute * SECS_PER_MIN;
  189. seconds+= tm.Second;
  190. return (time_t)seconds;
  191. }
  192. /*=====================================================*/
  193. /* Low level system time functions */
  194. static uint32_t sysTime = 0;
  195. static uint32_t prevMillis = 0;
  196. static uint32_t nextSyncTime = 0;
  197. static timeStatus_t Status = timeNotSet;
  198. getExternalTime getTimePtr; // pointer to external sync function
  199. //setExternalTime setTimePtr; // not used in this version
  200. #ifdef TIME_DRIFT_INFO // define this to get drift data
  201. time_t sysUnsyncedTime = 0; // the time sysTime unadjusted by sync
  202. #endif
  203. time_t now() {
  204. // calculate number of seconds passed since last call to now()
  205. while (millis() - prevMillis >= 1000) {
  206. // millis() and prevMillis are both unsigned ints thus the subtraction will always be the absolute value of the difference
  207. sysTime++;
  208. prevMillis += 1000;
  209. #ifdef TIME_DRIFT_INFO
  210. sysUnsyncedTime++; // this can be compared to the synced time to measure long term drift
  211. #endif
  212. }
  213. if (nextSyncTime <= sysTime) {
  214. if (getTimePtr != 0) {
  215. time_t t = getTimePtr();
  216. if (t != 0) {
  217. setTime(t);
  218. } else {
  219. nextSyncTime = sysTime + syncInterval;
  220. Status = (Status == timeNotSet) ? timeNotSet : timeNeedsSync;
  221. }
  222. }
  223. }
  224. return (time_t)sysTime;
  225. }
  226. void setTime(time_t t) {
  227. #ifdef TIME_DRIFT_INFO
  228. if(sysUnsyncedTime == 0)
  229. sysUnsyncedTime = t; // store the time of the first call to set a valid Time
  230. #endif
  231. sysTime = (uint32_t)t;
  232. nextSyncTime = (uint32_t)t + syncInterval;
  233. Status = timeSet;
  234. prevMillis = millis(); // restart counting from now (thanks to Korman for this fix)
  235. }
  236. void setTime(int hr,int min,int sec,int dy, int mnth, int yr){
  237. // year can be given as full four digit year or two digts (2010 or 10 for 2010);
  238. //it is converted to years since 1970
  239. if( yr > 99)
  240. yr = yr - 1970;
  241. else
  242. yr += 30;
  243. tm.Year = yr;
  244. tm.Month = mnth;
  245. tm.Day = dy;
  246. tm.Hour = hr;
  247. tm.Minute = min;
  248. tm.Second = sec;
  249. setTime(makeTime(tm));
  250. }
  251. void adjustTime(long adjustment) {
  252. sysTime += adjustment;
  253. }
  254. // indicates if time has been set and recently synchronized
  255. timeStatus_t timeStatus() {
  256. now(); // required to actually update the status
  257. return Status;
  258. }
  259. void setSyncProvider( getExternalTime getTimeFunction){
  260. getTimePtr = getTimeFunction;
  261. nextSyncTime = sysTime;
  262. now(); // this will sync the clock
  263. }
  264. void setSyncInterval(time_t interval){ // set the number of seconds between re-sync
  265. syncInterval = (uint32_t)interval;
  266. nextSyncTime = sysTime + syncInterval;
  267. }