Repository navigation
Expand file tree
/
Copy pathTimeSync.cpp
More file actions
168 lines (147 loc) · 6.24 KB
/
Copy pathTimeSync.cpp
File metadata and controls
168 lines (147 loc) · 6.24 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#include "TimeSync.h"
#include <WiFi.h>
#include <esp_sntp.h>
#include <stdlib.h> // setenv(時差の設定)
#include <time.h>
#include "BleScanner.h"
#include "Config.h"
#include "RtcClock.h"
#include "SettingsStore.h"
#include "WebConfigServer.h"
namespace {
// 同期処理の進み具合。update()が呼ばれるたびに、この状態を1つずつ進めます。
// Idle ... 何もしていない(次の同期時刻を待っている)
// Connecting ... Wi-Fiへの接続待ち
// WaitingForNtp ... NTPサーバからの応答待ち
enum class State { Idle, Connecting, WaitingForNtp };
State g_state = State::Idle;
uint32_t g_stateEnteredMillis = 0;
uint32_t g_nextAttemptMillis = 0;
bool g_hasSyncedOnce = false;
time_t g_lastSyncEpoch = 0;
void finish(bool success) {
WiFi.disconnect(true);
WiFi.mode(WIFI_OFF);
#if NTP_PAUSE_BLE_DURING_SYNC
BleScanner::resume();
#endif
g_state = State::Idle;
uint32_t intervalMs =
success ? (uint32_t(NTP_SYNC_INTERVAL_HOURS_DEFAULT) * 3600UL * 1000UL) : NTP_RETRY_INTERVAL_MS;
g_nextAttemptMillis = millis() + intervalMs;
Serial.printf("[NTP] %s -- next attempt in %lus\n", success ? "synced" : "FAILED",
(unsigned long)(intervalMs / 1000));
}
void startAttempt() {
#if NTP_PAUSE_BLE_DURING_SYNC
BleScanner::pause();
#endif
WiFi.mode(WIFI_STA);
String ssid = SettingsStore::wifiSsid();
String pass = SettingsStore::wifiPassword();
Serial.printf("[NTP] connecting to \"%s\" (password length %u)\n", ssid.c_str(),
unsigned(pass.length()));
if (pass.length() > 0) WiFi.begin(ssid.c_str(), pass.c_str());
else WiFi.begin(ssid.c_str());
g_state = State::Connecting;
g_stateEnteredMillis = millis();
}
} // namespace
namespace TimeSync {
void applyTimezone() {
setenv("TZ", LOCAL_TZ_STRING, 1);
tzset();
}
void begin() {
// 時差を先に設定します。
//
// 時差はNTPへの問い合わせ(configTzTime)でも設定されますが、それは最初の
// 同期が済むまで有効になりません。時計ICから日時を復元する場合はそれより
// 早く必要になるので、ここで設定しておきます。設定しないと、表示が9時間
// ずれた世界標準時のままになります。
applyTimezone();
g_state = State::Idle;
g_nextAttemptMillis = millis() + NTP_FIRST_SYNC_DELAY_MS;
}
void update() {
uint32_t now = millis();
switch (g_state) {
case State::Idle:
{
// 同期を始められない理由があるなら、その理由を1度だけ記録して戻ります。
//
// 黙って戻ってしまうと、「時刻が更新されない」ときに、試して失敗して
// いるのか、そもそも試していないのかが分かりません。
//
// Web設定の動作中に見送るのは、無線の役割を3つ(アクセスポイント +
// 子機 + BLE)同時にC6へ負わせないためです。数分ずれても実害は無く、
// Web設定を閉じれば同期されます。
const char *blocked = nullptr;
if (WebConfigServer::isActive()) blocked = "Web設定 is running";
else if (!SettingsStore::hasWifiCredentials()) blocked = "no Wi-Fi credentials stored";
if (blocked) {
static const char *s_lastReported = nullptr;
if (s_lastReported != blocked) {
s_lastReported = blocked;
Serial.printf("[NTP] not syncing: %s\n", blocked);
}
return;
}
if (now < g_nextAttemptMillis) return;
startAttempt();
}
break;
case State::Connecting:
if (WiFi.status() == WL_CONNECTED) {
Serial.printf("[NTP] Wi-Fi up in %lums, IP=%s -- querying %s (fallbacks: %s, %s)\n",
(unsigned long)(now - g_stateEnteredMillis),
WiFi.localIP().toString().c_str(), NTP_SERVER, NTP_SERVER2, NTP_SERVER3);
// 前回の試行の結果が残っていると、それを今回の成功と誤認するので
// 消してから要求します。
sntp_set_sync_status(SNTP_SYNC_STATUS_RESET);
configTzTime(LOCAL_TZ_STRING, NTP_SERVER, NTP_SERVER2, NTP_SERVER3);
g_state = State::WaitingForNtp;
g_stateEnteredMillis = now;
} else if (now - g_stateEnteredMillis > NTP_WIFI_CONNECT_TIMEOUT_MS) {
Serial.printf("[NTP] Wi-Fi did not connect within %lums (status %d)\n",
(unsigned long)NTP_WIFI_CONNECT_TIMEOUT_MS, int(WiFi.status()));
finish(false);
}
break;
case State::WaitingForNtp: {
time_t nowEpoch = time(nullptr);
// 成功したかどうかは、SNTPに直接尋ねます。
//
// 「時計がそれらしい値になったか」で判断してはいけません。電源投入時の
// 時計は0ではなく、実機では2045年を指していました。そのため、応答が
// 届く前から「もっともらしい日時」に見えてしまいます。
if (sntp_get_sync_status() == SNTP_SYNC_STATUS_COMPLETED) {
g_hasSyncedOnce = true;
g_lastSyncEpoch = nowEpoch;
struct tm tmNow;
localtime_r(&nowEpoch, &tmNow);
char buf[32];
strftime(buf, sizeof(buf), "%Y/%m/%d %H:%M:%S", &tmNow);
Serial.printf("[NTP] clock set to %s (took %lums)\n", buf,
(unsigned long)(now - g_stateEnteredMillis));
// 正しい時刻が手に入ったので、本体の時計ICにも書き写します。
// 次に電源を入れたとき、同期を待たずにこの時刻から始められます。
RtcClock::writeFromSystemClock();
finish(true);
} else if (now - g_stateEnteredMillis > NTP_SYNC_TIMEOUT_MS) {
Serial.printf("[NTP] no SNTP reply within %lums (clock still at epoch %ld)\n",
(unsigned long)NTP_SYNC_TIMEOUT_MS, long(nowEpoch));
finish(false);
}
break;
}
}
}
bool isClockPlausible() {
time_t now = time(nullptr);
return now >= CLOCK_PLAUSIBLE_EPOCH && (long long)now < CLOCK_IMPLAUSIBLE_EPOCH;
}
bool hasSyncedOnce() { return g_hasSyncedOnce; }
time_t lastSyncEpoch() { return g_lastSyncEpoch; }
bool isBusy() { return g_state != State::Idle; }
} // namespace TimeSync