]> the.earth.li Git - esp8266-clock.git/blob - clock.c
Update for SDK 2.2.1 with system compiler
[esp8266-clock.git] / clock.c
1 /*
2  * Copyright 2017 Jonathan McDowell <noodles@earth.li>
3  *
4  * This program is free software: you can redistribute it and/or modify
5  * it under the terms of the GNU General Public License as published by
6  * the Free Software Foundation, either version 3 of the License, or
7  * (at your option) any later version.
8  *
9  * This program is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12  * GNU General Public License for more details.
13  *
14  * You should have received a copy of the GNU General Public License
15  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
16  *
17  * NTP code based on https://github.com/raburton/esp8266/tree/master/ntp
18  * Those portions MIT licensed:
19  *
20  * Copyright (c) 2015 Richard A Burton (richardaburton@gmail.com)
21  *
22  * Permission is hereby granted, free of charge, to any person obtaining a copy
23  * of this software and associated documentation files (the "Software"), to deal
24  * in the Software without restriction, including without limitation the rights
25  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
26  * copies of the Software, and to permit persons to whom the Software is
27  * furnished to do so, subject to the following conditions:
28  *
29  * The above copyright notice and this permission notice shall be included in
30  * all copies or substantial portions of the Software.
31  *
32  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
33  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
34  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
35  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
36  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
37  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
38  * THE SOFTWARE.
39  */
40 #include <stdint.h>
41
42 #include <user_interface.h>
43 #include <espconn.h>
44 #include <mem.h>
45 #include <osapi.h>
46
47 #include "clock.h"
48
49 #define NTP_SERVER     "uk.pool.ntp.org"
50 #define NTP_TIMEOUT_MS 5000
51
52 static uint32_t sys_last_ticks;
53 static uint32_t sys_delta;
54 static os_timer_t ntp_timeout;
55
56 static ip_addr_t ntp_server_ip;
57
58 typedef struct {
59         uint8 options;
60         uint8 stratum;
61         uint8 poll;
62         uint8 precision;
63         uint32 root_delay;
64         uint32 root_disp;
65         uint32 ref_id;
66         uint8 ref_time[8];
67         uint8 orig_time[8];
68         uint8 recv_time[8];
69         uint8 trans_time[8];
70 } ntp_t;
71
72 void ICACHE_FLASH_ATTR set_time(uint32_t now)
73 {
74         sys_last_ticks = system_get_time();
75         sys_delta = now - (sys_last_ticks / 1000000);
76 }
77
78 uint32_t ICACHE_FLASH_ATTR get_time(void)
79 {
80         uint32_t sys_ticks;
81
82         sys_ticks = system_get_time();
83         if (sys_ticks < sys_last_ticks) {
84                 sys_delta += (1ULL << 32ULL) / 1000000;
85         }
86         sys_last_ticks = sys_ticks;
87
88         return sys_ticks / 1000000 + sys_delta;
89 }
90
91 bool ICACHE_FLASH_ATTR is_leap(uint32_t year)
92 {
93         return year % 4 == 0 && (year % 100 != 0 || year % 400 == 0);
94 }
95
96 void ICACHE_FLASH_ATTR breakdown_time(uint32_t time, struct tm *result)
97 {
98         uint32_t era, doe, yoe, mp;
99
100         /* Do the time component */
101         result->tm_sec = time % 60;
102         time /= 60;
103         result->tm_min = time % 60;
104         time /= 60;
105         result->tm_hour = time % 24;
106         time /= 24;
107
108         /* Now time is the number of days since 1970-01-01 (a Thursday) */
109         result->tm_wday = (time + 4) % 7;
110
111         /* Below from http://howardhinnant.github.io/date_algorithms.html */
112         time += 719468;
113         era = time / 146097;
114         doe = time - era * 146097;
115         yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
116
117         result->tm_year = yoe + era * 400;
118         result->tm_yday = doe - (365 * yoe + yoe / 4 - yoe / 100);
119         mp = (5 * result->tm_yday + 2) / 153;
120         result->tm_mday = result->tm_yday - (153 * mp + 2) / 5 + 1;
121         result->tm_mon = mp + (mp < 10 ? 2 : -10);
122         if (result->tm_mon <=2)
123                 result->tm_year++;
124
125         /* result->tm_yday is March 1st indexed at this point; fix up */
126         result->tm_yday += 28 + 31;
127         if (is_leap(result->tm_year))
128                 result->tm_yday++;
129 }
130
131 static void ICACHE_FLASH_ATTR ntp_udp_timeout(void *arg)
132 {
133         struct espconn *pCon = (struct espconn *) arg;
134
135         os_timer_disarm(&ntp_timeout);
136         os_printf("NTP timeout.\n");
137
138         // clean up connection
139         if (pCon) {
140                 espconn_delete(pCon);
141                 os_free(pCon->proto.udp);
142                 os_free(pCon);
143                 pCon = 0;
144         }
145 }
146
147 static void ICACHE_FLASH_ATTR ntp_udp_recv(void *arg, char *pdata,
148         unsigned short len)
149 {
150         struct espconn *pCon = (struct espconn *) arg;
151         uint32_t timestamp;
152         ntp_t *ntp;
153         struct tm dt;
154
155         os_printf("Got NTP response.\n");
156
157         os_timer_disarm(&ntp_timeout);
158
159         // Extract NTP time
160         ntp = (ntp_t *) pdata;
161         timestamp = ntp->trans_time[0] << 24 | ntp->trans_time[1] << 16 |
162                 ntp->trans_time[2] << 8 | ntp->trans_time[3];
163         // Convert to Unix time ms
164         timestamp -= 2208988800ULL;
165
166         // Store the time
167         set_time(timestamp);
168
169         // Print it out
170         breakdown_time(timestamp, &dt);
171         os_printf("%04d-%02d-%02d %02d:%02d:%02d (%u)\r\n",
172                 dt.tm_year, dt.tm_mon + 1, dt.tm_mday,
173                 dt.tm_hour, dt.tm_min, dt.tm_sec, timestamp);
174
175         // clean up connection
176         if (pCon) {
177                 espconn_delete(pCon);
178                 os_free(pCon->proto.udp);
179                 os_free(pCon);
180                 pCon = NULL;
181         }
182 }
183
184 void ICACHE_FLASH_ATTR ntp_got_dns(const char *name, ip_addr_t *ip, void *arg)
185 {
186         ntp_t ntp;
187         struct espconn *pCon = (struct espconn *) arg;
188
189         if (ip == NULL) {
190                 os_printf("NTP DNS request failed.\n");
191                 os_free(pCon);
192                 return;
193         }
194
195         os_printf("Sending NTP request.\n");
196
197         // Set up the UDP "connection"
198         pCon->type = ESPCONN_UDP;
199         pCon->state = ESPCONN_NONE;
200         pCon->proto.udp = (esp_udp *) os_zalloc(sizeof(esp_udp));
201         pCon->proto.udp->local_port = espconn_port();
202         pCon->proto.udp->remote_port = 123;
203         os_memcpy(pCon->proto.udp->remote_ip, &ip->addr, 4);
204
205         // Create a really simple NTP request packet
206         os_memset(&ntp, 0, sizeof(ntp_t));
207         ntp.options = 0b00100011; // leap = 0, version = 4, mode = 3 (client)
208
209         // Set timeout timer
210         os_timer_disarm(&ntp_timeout);
211         os_timer_setfn(&ntp_timeout, (os_timer_func_t*) ntp_udp_timeout, pCon);
212         os_timer_arm(&ntp_timeout, NTP_TIMEOUT_MS, 0);
213
214         // Send the NTP request
215         espconn_create(pCon);
216         espconn_regist_recvcb(pCon, ntp_udp_recv);
217         espconn_sent(pCon, (uint8_t *) &ntp, sizeof(ntp_t));
218 }
219
220 void ICACHE_FLASH_ATTR ntp_get_time(void)
221 {
222         struct espconn *pCon = NULL;
223
224         os_printf("Sending DNS request for NTP server.\n");
225         pCon = (struct espconn *) os_zalloc(sizeof(struct espconn));
226         espconn_gethostbyname(pCon, NTP_SERVER, &ntp_server_ip, ntp_got_dns);
227 }
228
229 void ICACHE_FLASH_ATTR rtc_init(void)
230 {
231         sys_last_ticks = system_get_time();
232 }