From d84bb7ac4b3bf8085fc41a7c5e979cd1990936b9 Mon Sep 17 00:00:00 2001 From: Camden Dixie O'Brien Date: Wed, 17 May 2023 16:04:10 +0100 Subject: [PATCH] Add support for getting day of the week to time module --- components/time/time_manager.c | 47 ++++++++++++++++++++++++++++++++-- components/time/time_manager.h | 20 +++++++++++++++ 2 files changed, 65 insertions(+), 2 deletions(-) diff --git a/components/time/time_manager.c b/components/time/time_manager.c index b6738f8..c257942 100644 --- a/components/time/time_manager.c +++ b/components/time/time_manager.c @@ -118,6 +118,11 @@ static int date_command_func(int argc, char **argv) printf("%04u-%02u-%02u\n", date.year, date.month, date.day); return 0; } else if (argc == 2) { + if (strcmp(argv[1], "week-day") == 0) { + const WeekDay day = get_week_day(); + printf("%s\n", week_day_name(day)); + return 0; + } Date date; const int result = sscanf( argv[1], "%04u-%02u-%02u", &date.year, &date.month, &date.day); @@ -190,8 +195,8 @@ void time_manager_init(void) "time", "Get, set or store the time", "time [HH:MM] OR time store", time_command_func); console_register( - "date", "Get or set the date", "date [yyyy-mm-dd]", - date_command_func); + "date", "Get or set the date, or get the day of the week", + "date [yyyy-mm-dd] OR date week-day", date_command_func); console_register( "sntp", "Manage SNTP", "sntp ", sntp_command_func); @@ -274,3 +279,41 @@ void set_date(Date date) tv.tv_sec = mktime(&timeinfo); settimeofday(&tv, NULL); } + +WeekDay get_week_day(void) +{ + struct timeval tv; + gettimeofday(&tv, NULL); + struct tm timeinfo; + (void)localtime_r(&tv.tv_sec, &timeinfo); + if (timeinfo.tm_wday == 0) + return WEEK_DAY_SUNDAY; + else + return (WeekDay)(timeinfo.tm_wday - 1); +} + +const char *week_day_name(WeekDay day) +{ + switch (day) { + case WEEK_DAY_MONDAY: + return "Monday"; + case WEEK_DAY_TUESDAY: + return "Tuesday"; + case WEEK_DAY_WEDNESDAY: + return "Wednesday"; + case WEEK_DAY_THURSDAY: + return "Thursday"; + case WEEK_DAY_FRIDAY: + return "Friday"; + case WEEK_DAY_SATURDAY: + return "Saturday"; + case WEEK_DAY_SUNDAY: + return "Sunday"; + + default: + ESP_LOGE( + TAG, "Invalid day of the week passed to %s(): %u", __func__, + (unsigned)day); + return "INVALID"; + } +} diff --git a/components/time/time_manager.h b/components/time/time_manager.h index 123f60c..305b544 100644 --- a/components/time/time_manager.h +++ b/components/time/time_manager.h @@ -17,6 +17,16 @@ typedef struct { unsigned day; } Date; +typedef enum { + WEEK_DAY_MONDAY, + WEEK_DAY_TUESDAY, + WEEK_DAY_WEDNESDAY, + WEEK_DAY_THURSDAY, + WEEK_DAY_FRIDAY, + WEEK_DAY_SATURDAY, + WEEK_DAY_SUNDAY, +} WeekDay; + /** * Initialize the time module. */ @@ -42,4 +52,14 @@ Date get_date(void); */ void set_date(Date date); +/** + * Get which day of the week it is. + */ +WeekDay get_week_day(void); + +/** + * Get the name of a day of the week. + */ +const char *week_day_name(WeekDay day); + #endif