1 /* Real Time Clock Driver Test
2  *	by: Benjamin Gaignard (benjamin.gaignard@linaro.org)
3  *
4  * To build
5  *	gcc rtctest_setdate.c -o rtctest_setdate
6  *
7  *   This program is free software: you can redistribute it and/or modify
8  *   it under the terms of the GNU General Public License as published by
9  *   the Free Software Foundation, either version 2 of the License, or
10  *   (at your option) any later version.
11  *
12  *   This program is distributed in the hope that it will be useful,
13  *   but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *   GNU General Public License for more details.
16  */
17 
18 #include <stdio.h>
19 #include <linux/rtc.h>
20 #include <sys/ioctl.h>
21 #include <sys/time.h>
22 #include <sys/types.h>
23 #include <fcntl.h>
24 #include <unistd.h>
25 #include <stdlib.h>
26 #include <errno.h>
27 
28 static const char default_time[] = "00:00:00";
29 
30 int main(int argc, char **argv)
31 {
32 	int fd, retval;
33 	struct rtc_time new, current;
34 	const char *rtc, *date;
35 	const char *time = default_time;
36 
37 	switch (argc) {
38 	case 4:
39 		time = argv[3];
40 		/* FALLTHROUGH */
41 	case 3:
42 		date = argv[2];
43 		rtc = argv[1];
44 		break;
45 	default:
46 		fprintf(stderr, "usage: rtctest_setdate <rtcdev> <DD-MM-YYYY> [HH:MM:SS]\n");
47 		return 1;
48 	}
49 
50 	fd = open(rtc, O_RDONLY);
51 	if (fd == -1) {
52 		perror(rtc);
53 		exit(errno);
54 	}
55 
56 	sscanf(date, "%d-%d-%d", &new.tm_mday, &new.tm_mon, &new.tm_year);
57 	new.tm_mon -= 1;
58 	new.tm_year -= 1900;
59 	sscanf(time, "%d:%d:%d", &new.tm_hour, &new.tm_min, &new.tm_sec);
60 
61 	fprintf(stderr, "Test will set RTC date/time to %d-%d-%d, %02d:%02d:%02d.\n",
62 		new.tm_mday, new.tm_mon + 1, new.tm_year + 1900,
63 		new.tm_hour, new.tm_min, new.tm_sec);
64 
65 	/* Write the new date in RTC */
66 	retval = ioctl(fd, RTC_SET_TIME, &new);
67 	if (retval == -1) {
68 		perror("RTC_SET_TIME ioctl");
69 		close(fd);
70 		exit(errno);
71 	}
72 
73 	/* Read back */
74 	retval = ioctl(fd, RTC_RD_TIME, &current);
75 	if (retval == -1) {
76 		perror("RTC_RD_TIME ioctl");
77 		exit(errno);
78 	}
79 
80 	fprintf(stderr, "\n\nCurrent RTC date/time is %d-%d-%d, %02d:%02d:%02d.\n",
81 		current.tm_mday, current.tm_mon + 1, current.tm_year + 1900,
82 		current.tm_hour, current.tm_min, current.tm_sec);
83 
84 	close(fd);
85 	return 0;
86 }
87