Fork of the espurna firmware for `mhsw` switches
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

506 lines
13 KiB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
6 years ago
Terminal: change command-line parser (#2247) Change the underlying command line handling: - switch to a custom parser, inspired by redis / sds - update terminalRegisterCommand signature, pass only bare minimum - clean-up `help` & `commands`. update settings `set`, `get` and `del` - allow our custom test suite to run command-line tests - clean-up Stream IO to allow us to print large things into debug stream (for example, `eeprom.dump`) - send parsing errors to the debug log As a proof of concept, introduce `TERMINAL_MQTT_SUPPORT` and `TERMINAL_WEB_API_SUPPORT` - MQTT subscribes to the `<root>/cmd/set` and sends response to the `<root>/cmd`. We can't output too much, as we don't have any large-send API. - Web API listens to the `/api/cmd?apikey=...&line=...` (or PUT, params inside the body). This one is intended as a possible replacement of the `API_SUPPORT`. Internals introduce a 'task' around the AsyncWebServerRequest object that will simulate what WiFiClient does and push data into it continuously, switching between CONT and SYS. Both are experimental. We only accept a single command and not every command is updated to use Print `ctx.output` object. We are also somewhat limited by the Print / Stream overall, perhaps I am overestimating the usefulness of Arduino compatibility to such an extent :) Web API handler can also sometimes show only part of the result, whenever the command tries to yield() by itself waiting for something. Perhaps we would need to create a custom request handler for that specific use-case.
4 years ago
8 years ago
  1. /*
  2. NTP MODULE
  3. Based on esp8266 / esp32 configTime and C date and time functions:
  4. - https://github.com/esp8266/Arduino/blob/master/libraries/esp8266/examples/NTP-TZ-DST/NTP-TZ-DST.ino
  5. - https://www.nongnu.org/lwip/2_1_x/group__sntp.html
  6. - man 3 ctime
  7. Copyright (C) 2019 by Maxim Prokhorov <prokhorov dot max at outlook dot com>
  8. */
  9. #include "ntp.h"
  10. #if NTP_SUPPORT && !NTP_LEGACY_SUPPORT
  11. #include <Arduino.h>
  12. #include <coredecls.h>
  13. #include <Ticker.h>
  14. #include <lwip/apps/sntp.h>
  15. #include <TZ.h>
  16. #include <forward_list>
  17. static_assert(
  18. (SNTP_SERVER_DNS == 1),
  19. "lwip must be configured with SNTP_SERVER_DNS"
  20. );
  21. #include "config/buildtime.h"
  22. #include "ntp_timelib.h"
  23. #include "ws.h"
  24. // Arduino/esp8266 lwip2 custom functions that can be redefined
  25. // Must return time in milliseconds, legacy settings are in seconds.
  26. String _ntp_server;
  27. uint32_t _ntp_startup_delay = (NTP_START_DELAY * 1000);
  28. uint32_t _ntp_update_delay = (NTP_UPDATE_INTERVAL * 1000);
  29. uint32_t sntp_startup_delay_MS_rfc_not_less_than_60000() {
  30. return _ntp_startup_delay;
  31. }
  32. uint32_t sntp_update_delay_MS_rfc_not_less_than_15000() {
  33. return _ntp_update_delay;
  34. }
  35. // We also must shim TimeLib functions until everything else is ported.
  36. // We can't sometimes avoid TimeLib as dependancy though, which would be really bad
  37. static bool _ntp_synced = false;
  38. static time_t _ntp_last = 0;
  39. static time_t _ntp_ts = 0;
  40. static tm _ntp_tm_local;
  41. static tm _ntp_tm_utc;
  42. void _ntpTmCache(time_t ts) {
  43. if (_ntp_ts != ts) {
  44. _ntp_ts = ts;
  45. localtime_r(&_ntp_ts, &_ntp_tm_local);
  46. gmtime_r(&_ntp_ts, &_ntp_tm_utc);
  47. }
  48. }
  49. int hour(time_t ts) {
  50. _ntpTmCache(ts);
  51. return _ntp_tm_local.tm_hour;
  52. }
  53. int minute(time_t ts) {
  54. _ntpTmCache(ts);
  55. return _ntp_tm_local.tm_min;
  56. }
  57. int second(time_t ts) {
  58. _ntpTmCache(ts);
  59. return _ntp_tm_local.tm_sec;
  60. }
  61. int day(time_t ts) {
  62. _ntpTmCache(ts);
  63. return _ntp_tm_local.tm_mday;
  64. }
  65. // `tm.tm_wday` range is 0..6, TimeLib is 1..7
  66. int weekday(time_t ts) {
  67. _ntpTmCache(ts);
  68. return _ntp_tm_local.tm_wday + 1;
  69. }
  70. // `tm.tm_mon` range is 0..11, TimeLib range is 1..12
  71. int month(time_t ts) {
  72. _ntpTmCache(ts);
  73. return _ntp_tm_local.tm_mon + 1;
  74. }
  75. int year(time_t ts) {
  76. _ntpTmCache(ts);
  77. return _ntp_tm_local.tm_year + 1900;
  78. }
  79. int utc_hour(time_t ts) {
  80. _ntpTmCache(ts);
  81. return _ntp_tm_utc.tm_hour;
  82. }
  83. int utc_minute(time_t ts) {
  84. _ntpTmCache(ts);
  85. return _ntp_tm_utc.tm_min;
  86. }
  87. int utc_second(time_t ts) {
  88. _ntpTmCache(ts);
  89. return _ntp_tm_utc.tm_sec;
  90. }
  91. int utc_day(time_t ts) {
  92. _ntpTmCache(ts);
  93. return _ntp_tm_utc.tm_mday;
  94. }
  95. int utc_weekday(time_t ts) {
  96. _ntpTmCache(ts);
  97. return _ntp_tm_utc.tm_wday + 1;
  98. }
  99. int utc_month(time_t ts) {
  100. _ntpTmCache(ts);
  101. return _ntp_tm_utc.tm_mon + 1;
  102. }
  103. int utc_year(time_t ts) {
  104. _ntpTmCache(ts);
  105. return _ntp_tm_utc.tm_year + 1900;
  106. }
  107. time_t now() {
  108. return time(nullptr);
  109. }
  110. // -----------------------------------------------------------------------------
  111. #if WEB_SUPPORT
  112. bool _ntpWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  113. return (strncmp(key, "ntp", 3) == 0);
  114. }
  115. void _ntpWebSocketOnVisible(JsonObject& root) {
  116. root["ntpVisible"] = 1;
  117. }
  118. void _ntpWebSocketOnData(JsonObject& root) {
  119. root["ntpStatus"] = ntpSynced();
  120. }
  121. void _ntpWebSocketOnConnected(JsonObject& root) {
  122. root["ntpServer"] = getSetting("ntpServer", F(NTP_SERVER));
  123. root["ntpTZ"] = getSetting("ntpTZ", NTP_TIMEZONE);
  124. }
  125. #endif
  126. String _ntpGetServer() {
  127. String server;
  128. server = sntp_getservername(0);
  129. if (!server.length()) {
  130. auto ip = IPAddress(sntp_getserver(0));
  131. if (ip) {
  132. server = ip.toString();
  133. }
  134. }
  135. return server;
  136. }
  137. NtpInfo ntpInfo() {
  138. NtpInfo result;
  139. auto ts = now();
  140. result.now = ts;
  141. tm sync_tm;
  142. gmtime_r(&_ntp_last, &sync_tm);
  143. result.sync = ntpDateTime(&sync_tm);
  144. tm utc_tm;
  145. gmtime_r(&ts, &utc_tm);
  146. result.utc = ntpDateTime(&utc_tm);
  147. const char* cfg_tz = getenv("TZ");
  148. if ((cfg_tz != nullptr) && (strcmp(cfg_tz, "UTC0") != 0)) {
  149. tm local_tm;
  150. localtime_r(&ts, &local_tm);
  151. result.local = ntpDateTime(&local_tm);
  152. result.tz = cfg_tz;
  153. }
  154. return result;
  155. }
  156. void _ntpReport() {
  157. if (!ntpSynced()) {
  158. DEBUG_MSG_P(PSTR("[NTP] Not synced\n"));
  159. return;
  160. }
  161. auto info = ntpInfo();
  162. DEBUG_MSG_P(PSTR("[NTP] Server : %s\n"), _ntp_server.c_str());
  163. DEBUG_MSG_P(PSTR("[NTP] Sync Time : %s (UTC)\n"), info.sync.c_str());
  164. DEBUG_MSG_P(PSTR("[NTP] UTC Time : %s\n"), info.utc.c_str());
  165. if (info.tz.length()) {
  166. DEBUG_MSG_P(PSTR("[NTP] Local Time : %s (%s)\n"), info.local.c_str(), info.tz.c_str());
  167. }
  168. }
  169. void _ntpConfigure() {
  170. // Ignore or accept the DHCP SNTP option
  171. // When enabled, it is possible that lwip will replace the NTP server pointer from under us
  172. sntp_servermode_dhcp(getSetting("ntpDhcp", 1 == NTP_DHCP_SERVER));
  173. // Note: TZ_... provided by the Core are already wrapped with PSTR(...)
  174. // but, String() already handles every char pointer as a flash-string
  175. auto cfg_tz = getSetting("ntpTZ", NTP_TIMEZONE);
  176. const char* active_tz = getenv("TZ");
  177. bool changed = cfg_tz != active_tz;
  178. if (changed) {
  179. if (cfg_tz.length()) {
  180. setenv("TZ", cfg_tz.c_str(), 1);
  181. } else {
  182. unsetenv("TZ");
  183. }
  184. tzset();
  185. }
  186. const auto cfg_server = getSetting("ntpServer", F(NTP_SERVER));
  187. const auto active_server = _ntpGetServer();
  188. changed = (cfg_server != active_server) || changed;
  189. // We skip configTime() API since we already set the TZ just above
  190. // (and most of the time we expect NTP server to proxy to multiple servers instead of defining more than one here)
  191. if (changed) {
  192. sntp_stop();
  193. _ntp_server = cfg_server;
  194. sntp_setservername(0, _ntp_server.c_str());
  195. sntp_init();
  196. DEBUG_MSG_P(PSTR("[NTP] Server: %s, TZ: %s\n"), cfg_server.c_str(),
  197. cfg_tz.length() ? cfg_tz.c_str() : "UTC0");
  198. }
  199. }
  200. // -----------------------------------------------------------------------------
  201. bool ntpSynced() {
  202. return _ntp_synced;
  203. }
  204. String ntpDateTime(tm* timestruct) {
  205. char buffer[32];
  206. snprintf_P(buffer, sizeof(buffer),
  207. PSTR("%04d-%02d-%02d %02d:%02d:%02d"),
  208. timestruct->tm_year + 1900,
  209. timestruct->tm_mon + 1,
  210. timestruct->tm_mday,
  211. timestruct->tm_hour,
  212. timestruct->tm_min,
  213. timestruct->tm_sec
  214. );
  215. return String(buffer);
  216. }
  217. String ntpDateTime(time_t ts) {
  218. tm timestruct;
  219. localtime_r(&ts, &timestruct);
  220. return ntpDateTime(&timestruct);
  221. }
  222. String ntpDateTime() {
  223. if (ntpSynced()) {
  224. return ntpDateTime(now());
  225. }
  226. return String();
  227. }
  228. // -----------------------------------------------------------------------------
  229. using NtpTickCallbacks = std::forward_list<NtpTickCallback>;
  230. NtpTickCallbacks _ntp_tick_callbacks;
  231. static Ticker _ntp_tick;
  232. void _ntpTickSchedule(int offset);
  233. void _ntpTickCallback() {
  234. if (!ntpSynced()) {
  235. _ntpTickSchedule(60);
  236. return;
  237. }
  238. const auto ts = now();
  239. tm local_tm;
  240. localtime_r(&ts, &local_tm);
  241. int now_hour = local_tm.tm_hour;
  242. int now_minute = local_tm.tm_min;
  243. static int last_hour = -1;
  244. static int last_minute = -1;
  245. // notify subscribers about each tick interval (note that both can happen simultaneously)
  246. if (last_hour != now_hour) {
  247. last_hour = now_hour;
  248. for (auto& callback : _ntp_tick_callbacks) {
  249. callback(NtpTick::EveryHour);
  250. }
  251. }
  252. if (last_minute != now_minute) {
  253. last_minute = now_minute;
  254. for (auto& callback : _ntp_tick_callbacks) {
  255. callback(NtpTick::EveryMinute);
  256. }
  257. }
  258. // try to autocorrect each invocation
  259. _ntpTickSchedule(60 - local_tm.tm_sec);
  260. }
  261. // XXX: NONOS SDK docs for some reason mention 100 micros as minimum time. Schedule next second in case this is 0
  262. void _ntpTickSchedule(int offset) {
  263. static bool scheduled { false };
  264. if (!scheduled) {
  265. scheduled = true;
  266. _ntp_tick.once_scheduled(offset ? offset : 1, []() {
  267. scheduled = false;
  268. _ntpTickCallback();
  269. });
  270. }
  271. }
  272. void _ntpSetTimeOfDayCallback() {
  273. _ntp_synced = true;
  274. _ntp_last = time(nullptr);
  275. static bool once = true;
  276. if (once) {
  277. schedule_function(_ntpTickCallback);
  278. once = false;
  279. }
  280. #if WEB_SUPPORT
  281. wsPost(_ntpWebSocketOnData);
  282. #endif
  283. schedule_function(_ntpReport);
  284. }
  285. void _ntpSetTimestamp(time_t ts) {
  286. timeval tv { ts, 0 };
  287. timezone tz { 0, 0 };
  288. settimeofday(&tv, &tz);
  289. }
  290. // -----------------------------------------------------------------------------
  291. void _ntpConvertLegacyOffsets() {
  292. bool save { true };
  293. bool found { false };
  294. bool europe { true };
  295. bool dst { true };
  296. int offset { 60 };
  297. settings::kv_store.foreach([&](settings::kvs_type::KeyValueResult&& kv) {
  298. const auto key = kv.key.read();
  299. if (key == F("ntpTZ")) {
  300. save = false;
  301. } else if (key == F("ntpOffset")) {
  302. offset = settings::internal::convert<int>(kv.value.read());
  303. found = true;
  304. } else if (key == F("ntpDST")) {
  305. dst = settings::internal::convert<bool>(kv.value.read());
  306. found = true;
  307. } else if (key == F("ntpRegion")) {
  308. europe = (0 == settings::internal::convert<int>(kv.value.read()));
  309. found = true;
  310. }
  311. });
  312. if (save && found) {
  313. // XXX: only expect offsets in hours
  314. String custom { europe ? F("CET") : F("CST") };
  315. custom.reserve(32);
  316. if (offset > 0) {
  317. custom += '-';
  318. }
  319. custom += abs(offset) / 60;
  320. if (dst) {
  321. custom += europe ? F("CEST") : F("EDT");
  322. if (europe) {
  323. custom += F(",M3.5.0,M10.5.0/3");
  324. } else {
  325. custom += F(",M3.2.0,M11.1.0");
  326. }
  327. }
  328. setSetting("ntpTZ", custom);
  329. }
  330. delSetting("ntpOffset");
  331. delSetting("ntpDST");
  332. delSetting("ntpRegion");
  333. }
  334. void ntpOnTick(NtpTickCallback callback) {
  335. _ntp_tick_callbacks.push_front(callback);
  336. }
  337. void ntpSetup() {
  338. // Randomized in time to avoid clogging the server with simultaneous requests from multiple devices
  339. // (for example, when multiple devices start up at the same time)
  340. const uint32_t startup_delay = getSetting("ntpStartDelay", NTP_START_DELAY);
  341. const uint32_t update_delay = getSetting("ntpUpdateIntvl", NTP_UPDATE_INTERVAL);
  342. _ntp_startup_delay = secureRandom(startup_delay, startup_delay * 2);
  343. _ntp_update_delay = secureRandom(update_delay, update_delay * 2);
  344. DEBUG_MSG_P(PSTR("[NTP] Startup delay: %u (s), Update delay: %u (s)\n"),
  345. _ntp_startup_delay, _ntp_update_delay);
  346. _ntp_startup_delay = _ntp_startup_delay * 1000;
  347. _ntp_update_delay = _ntp_update_delay * 1000;
  348. // start up with some reasonable timestamp already available
  349. _ntpSetTimestamp(__UNIX_TIMESTAMP__);
  350. // will be called every time after ntp syncs AND loop() finishes
  351. settimeofday_cb(_ntpSetTimeOfDayCallback);
  352. // generic configuration, always handled
  353. espurnaRegisterReload(_ntpConfigure);
  354. _ntpConvertLegacyOffsets();
  355. _ntpConfigure();
  356. // make sure our logic does know about the actual server
  357. // in case dhcp sends out ntp settings
  358. static WiFiEventHandler on_sta = WiFi.onStationModeGotIP([](WiFiEventStationModeGotIP) {
  359. if (!sntp_enabled()) {
  360. return;
  361. }
  362. auto server = _ntpGetServer();
  363. if (!server.length()) {
  364. DEBUG_MSG_P(PSTR("[NTP] Updating `ntpDhcp` to ignore the DHCP values\n"));
  365. setSetting("ntpDhcp", "0");
  366. sntp_servermode_dhcp(0);
  367. schedule_function(_ntpConfigure);
  368. return;
  369. }
  370. if (!_ntp_server.length() || (server != _ntp_server)) {
  371. DEBUG_MSG_P(PSTR("[NTP] Updating `ntpServer` setting from DHCP: %s\n"), server.c_str());
  372. _ntp_server = server;
  373. setSetting("ntpServer", server);
  374. }
  375. });
  376. // optional functionality
  377. #if WEB_SUPPORT
  378. wsRegister()
  379. .onVisible(_ntpWebSocketOnVisible)
  380. .onConnected(_ntpWebSocketOnConnected)
  381. .onData(_ntpWebSocketOnData)
  382. .onKeyCheck(_ntpWebSocketOnKeyCheck);
  383. #endif
  384. #if TERMINAL_SUPPORT
  385. terminalRegisterCommand(F("NTP"), [](const terminal::CommandContext&) {
  386. _ntpReport();
  387. terminalOK();
  388. });
  389. terminalRegisterCommand(F("NTP.SETTIME"), [](const terminal::CommandContext& ctx) {
  390. if (ctx.argc != 2) return;
  391. _ntp_synced = true;
  392. _ntpSetTimestamp(ctx.argv[1].toInt());
  393. terminalOK();
  394. });
  395. // TODO:
  396. // terminalRegisterCommand(F("NTP.SYNC"), [](const terminal::CommandContext&) { ... }
  397. //
  398. #endif
  399. }
  400. #endif // NTP_SUPPORT && !NTP_LEGACY_SUPPORT