Initial code commit
[oweals/u-boot_mod.git] / u-boot / net / sntp.c
1 /*
2  * SNTP support driver
3  *
4  * Masami Komiya <mkomiya@sonare.it> 2005
5  *
6  */
7 #include <common.h>
8 #include <command.h>
9 #include <net.h>
10 #include <rtc.h>
11 #include "sntp.h"
12
13 #if ((CONFIG_COMMANDS & CFG_CMD_NET) && (CONFIG_COMMANDS & CFG_CMD_SNTP))
14
15 //#define       DEBUG
16
17 #define SNTP_TIMEOUT    10
18
19 static int SntpOurPort;
20
21 static void SntpSend(void){
22         struct sntp_pkt_t pkt;
23         int pktlen = SNTP_PACKET_LEN;
24         int sport;
25
26 #ifdef DEBUG
27         printf("%s\n", __FUNCTION__);
28 #endif
29
30         memset(&pkt, 0, sizeof(pkt));
31
32         pkt.li = NTP_LI_NOLEAP;
33         pkt.vn = NTP_VERSION;
34         pkt.mode = NTP_MODE_CLIENT;
35
36         memcpy((char *)NetTxPacket + NetEthHdrSize() + IP_HDR_SIZE, (char *)&pkt, pktlen);
37
38         SntpOurPort = 10000 + (get_timer(0) % 4096);
39         sport = NTP_SERVICE_PORT;
40
41         puts("Sending SNTP request...\n");
42
43         NetSendUDPPacket(NetServerEther, NetNtpServerIP, sport, SntpOurPort, pktlen);
44 }
45
46 static void SntpTimeout(void){
47         puts("## Error: timeout\n");
48         NetState = NETLOOP_FAIL;
49
50         return;
51 }
52
53 static void SntpHandler(uchar *pkt, unsigned dest, unsigned src, unsigned len){
54         struct sntp_pkt_t *rpktp = (struct sntp_pkt_t *)pkt;
55         struct rtc_time tm;
56         ulong seconds;
57
58 #ifdef DEBUG
59         printf("%s\n", __FUNCTION__);
60 #endif
61
62         if(dest != SntpOurPort){
63                 return;
64         }
65
66         /*
67          * As the RTC's used in U-Boot supports second resolution only
68          * we simply ignore the sub-second field.
69          */
70         memcpy(&seconds, &rpktp->transmit_timestamp, sizeof(ulong));
71
72         to_tm(ntohl(seconds) - 2208988800UL + NetTimeOffset, &tm);
73
74 #if (CONFIG_COMMANDS & CFG_CMD_DATE)
75         // TODO: find out how to use RTC on
76         //rtc_set(&tm);
77 #endif
78         printf("Got SNTP response: %4d-%02d-%02d %2d:%02d:%02d\n\n", tm.tm_year, tm.tm_mon, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
79         NetState = NETLOOP_SUCCESS;
80 }
81
82 void SntpStart(void){
83 #ifdef DEBUG
84         printf("%s\n", __FUNCTION__);
85 #endif
86
87         NetSetTimeout(SNTP_TIMEOUT * CFG_HZ, SntpTimeout);
88         NetSetHandler(SntpHandler);
89
90         memset(NetServerEther, 0, 6);
91
92         SntpSend();
93 }
94
95 #endif /* CONFIG_COMMANDS & CFG_CMD_SNTP */