Add support for getting day of the week to time module

This commit is contained in:
Camden Dixie O'Brien 2023-05-17 16:04:10 +01:00
parent 8904f9ab8e
commit d84bb7ac4b
2 changed files with 65 additions and 2 deletions

View File

@ -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 <status|restart|stop>",
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";
}
}

View File

@ -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