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.

495 lines
12 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. static_assert(
  15. (SNTP_SERVER_DNS == 1),
  16. "lwip must be configured with SNTP_SERVER_DNS"
  17. );
  18. #include "config/buildtime.h"
  19. #include "debug.h"
  20. #include "broker.h"
  21. #include "ws.h"
  22. BrokerBind(NtpBroker);
  23. // Arduino/esp8266 lwip2 custom functions that can be redefined
  24. // Must return time in milliseconds, legacy settings are in seconds.
  25. String _ntp_server;
  26. uint32_t _ntp_startup_delay = (NTP_START_DELAY * 1000);
  27. uint32_t _ntp_update_delay = (NTP_UPDATE_INTERVAL * 1000);
  28. uint32_t sntp_startup_delay_MS_rfc_not_less_than_60000() {
  29. return _ntp_startup_delay;
  30. }
  31. uint32_t sntp_update_delay_MS_rfc_not_less_than_15000() {
  32. return _ntp_update_delay;
  33. }
  34. // We also must shim TimeLib functions until everything else is ported.
  35. // We can't sometimes avoid TimeLib as dependancy though, which would be really bad
  36. static Ticker _ntp_broker_timer;
  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. const 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. setenv("TZ", cfg_tz.c_str(), 1);
  180. tzset();
  181. }
  182. const auto cfg_server = getSetting("ntpServer", F(NTP_SERVER));
  183. const auto active_server = _ntpGetServer();
  184. changed = (cfg_server != active_server) || changed;
  185. // We skip configTime() API since we already set the TZ just above
  186. // (and most of the time we expect NTP server to proxy to multiple servers instead of defining more than one here)
  187. if (changed) {
  188. sntp_stop();
  189. _ntp_server = cfg_server;
  190. sntp_setservername(0, _ntp_server.c_str());
  191. sntp_init();
  192. DEBUG_MSG_P(PSTR("[NTP] Server: %s, TZ: %s\n"), cfg_server.c_str(), cfg_tz.length() ? cfg_tz.c_str() : "UTC0");
  193. }
  194. }
  195. // -----------------------------------------------------------------------------
  196. bool ntpSynced() {
  197. return _ntp_synced;
  198. }
  199. String ntpDateTime(tm* timestruct) {
  200. char buffer[20];
  201. snprintf_P(buffer, sizeof(buffer),
  202. PSTR("%04d-%02d-%02d %02d:%02d:%02d"),
  203. timestruct->tm_year + 1900,
  204. timestruct->tm_mon + 1,
  205. timestruct->tm_mday,
  206. timestruct->tm_hour,
  207. timestruct->tm_min,
  208. timestruct->tm_sec
  209. );
  210. return String(buffer);
  211. }
  212. String ntpDateTime(time_t ts) {
  213. tm timestruct;
  214. localtime_r(&ts, &timestruct);
  215. return ntpDateTime(&timestruct);
  216. }
  217. String ntpDateTime() {
  218. if (ntpSynced()) {
  219. return ntpDateTime(now());
  220. }
  221. return String();
  222. }
  223. // -----------------------------------------------------------------------------
  224. #if BROKER_SUPPORT
  225. void _ntpBrokerSchedule(int offset);
  226. void _ntpBrokerCallback() {
  227. if (!ntpSynced()) {
  228. _ntpBrokerSchedule(60);
  229. return;
  230. }
  231. const auto ts = now();
  232. // current time and formatter string is in local TZ
  233. tm local_tm;
  234. localtime_r(&ts, &local_tm);
  235. int now_hour = local_tm.tm_hour;
  236. int now_minute = local_tm.tm_min;
  237. static int last_hour = -1;
  238. static int last_minute = -1;
  239. String datetime;
  240. if ((last_minute != now_minute) || (last_hour != now_hour)) {
  241. datetime = ntpDateTime(&local_tm);
  242. }
  243. // notify subscribers about each tick interval (note that both can happen simultaneously)
  244. if (last_hour != now_hour) {
  245. last_hour = now_hour;
  246. NtpBroker::Publish(NtpTick::EveryHour, ts, datetime.c_str());
  247. }
  248. if (last_minute != now_minute) {
  249. last_minute = now_minute;
  250. NtpBroker::Publish(NtpTick::EveryMinute, ts, datetime.c_str());
  251. }
  252. // try to autocorrect each invocation
  253. _ntpBrokerSchedule(60 - local_tm.tm_sec);
  254. }
  255. // XXX: Nonos docs for some reason mention 100 micros as minimum time. Schedule next second in case this is 0
  256. void _ntpBrokerSchedule(int offset) {
  257. _ntp_broker_timer.once_scheduled(offset ?: 1, _ntpBrokerCallback);
  258. }
  259. #endif
  260. void _ntpSetTimeOfDayCallback() {
  261. _ntp_synced = true;
  262. _ntp_last = time(nullptr);
  263. #if BROKER_SUPPORT
  264. static bool once = true;
  265. if (once) {
  266. schedule_function(_ntpBrokerCallback);
  267. once = false;
  268. }
  269. #endif
  270. #if WEB_SUPPORT
  271. wsPost(_ntpWebSocketOnData);
  272. #endif
  273. schedule_function(_ntpReport);
  274. }
  275. void _ntpSetTimestamp(time_t ts) {
  276. timeval tv { ts, 0 };
  277. timezone tz { 0, 0 };
  278. settimeofday(&tv, &tz);
  279. }
  280. // -----------------------------------------------------------------------------
  281. void _ntpConvertLegacyOffsets() {
  282. bool save { true };
  283. bool found { false };
  284. bool europe { true };
  285. bool dst { true };
  286. int offset { 60 };
  287. settings::kv_store.foreach([&](settings::kvs_type::KeyValueResult&& kv) {
  288. const auto key = kv.key.read();
  289. if (key == F("ntpTZ")) {
  290. save = false;
  291. } else if (key == F("ntpOffset")) {
  292. offset = kv.value.read().toInt();
  293. found = true;
  294. } else if (key == F("ntpDST")) {
  295. dst = (1 == kv.value.read().toInt());
  296. found = true;
  297. } else if (key == F("ntpRegion")) {
  298. europe = (0 == kv.value.read().toInt());
  299. found = true;
  300. }
  301. });
  302. if (save && found) {
  303. // XXX: only expect offsets in hours
  304. String custom { europe ? F("CET") : F("CST") };
  305. custom.reserve(32);
  306. if (offset > 0) {
  307. custom += '-';
  308. }
  309. custom += abs(offset) / 60;
  310. if (dst) {
  311. custom += europe ? F("CEST") : F("EDT");
  312. if (europe) {
  313. custom += F(",M3.5.0,M10.5.0/3");
  314. } else {
  315. custom += F(",M3.2.0,M11.1.0");
  316. }
  317. }
  318. setSetting("ntpTZ", custom);
  319. }
  320. delSetting("ntpOffset");
  321. delSetting("ntpDST");
  322. delSetting("ntpRegion");
  323. }
  324. void ntpSetup() {
  325. // Randomized in time to avoid clogging the server with simultaneous requests from multiple devices
  326. // (for example, when multiple devices start up at the same time)
  327. const uint32_t startup_delay = getSetting("ntpStartDelay", NTP_START_DELAY);
  328. const uint32_t update_delay = getSetting("ntpUpdateIntvl", NTP_UPDATE_INTERVAL);
  329. _ntp_startup_delay = secureRandom(startup_delay, startup_delay * 2);
  330. _ntp_update_delay = secureRandom(update_delay, update_delay * 2);
  331. DEBUG_MSG_P(PSTR("[NTP] Startup delay: %us, Update delay: %us\n"),
  332. _ntp_startup_delay, _ntp_update_delay
  333. );
  334. _ntp_startup_delay = _ntp_startup_delay * 1000;
  335. _ntp_update_delay = _ntp_update_delay * 1000;
  336. // start up with some reasonable timestamp already available
  337. _ntpSetTimestamp(__UNIX_TIMESTAMP__);
  338. // will be called every time after ntp syncs AND loop() finishes
  339. settimeofday_cb(_ntpSetTimeOfDayCallback);
  340. // generic configuration, always handled
  341. espurnaRegisterReload(_ntpConfigure);
  342. _ntpConvertLegacyOffsets();
  343. _ntpConfigure();
  344. // make sure our logic does know about the actual server
  345. // in case dhcp sends out ntp settings
  346. static WiFiEventHandler on_sta = WiFi.onStationModeGotIP([](WiFiEventStationModeGotIP) {
  347. if (!sntp_enabled()) {
  348. return;
  349. }
  350. auto server = _ntpGetServer();
  351. if (!server.length()) {
  352. DEBUG_MSG_P(PSTR("[NTP] Updating `ntpDhcp` to ignore the DHCP values\n"));
  353. setSetting("ntpDhcp", "0");
  354. sntp_servermode_dhcp(0);
  355. schedule_function(_ntpConfigure);
  356. return;
  357. }
  358. if (!_ntp_server.length() || (server != _ntp_server)) {
  359. DEBUG_MSG_P(PSTR("[NTP] Updating `ntpServer` setting from DHCP: %s\n"), server.c_str());
  360. _ntp_server = server;
  361. setSetting("ntpServer", server);
  362. }
  363. });
  364. // optional functionality
  365. #if WEB_SUPPORT
  366. wsRegister()
  367. .onVisible(_ntpWebSocketOnVisible)
  368. .onConnected(_ntpWebSocketOnConnected)
  369. .onData(_ntpWebSocketOnData)
  370. .onKeyCheck(_ntpWebSocketOnKeyCheck);
  371. #endif
  372. #if TERMINAL_SUPPORT
  373. terminalRegisterCommand(F("NTP"), [](const terminal::CommandContext&) {
  374. _ntpReport();
  375. terminalOK();
  376. });
  377. terminalRegisterCommand(F("NTP.SETTIME"), [](const terminal::CommandContext& ctx) {
  378. if (ctx.argc != 2) return;
  379. _ntp_synced = true;
  380. _ntpSetTimestamp(ctx.argv[1].toInt());
  381. terminalOK();
  382. });
  383. // TODO:
  384. // terminalRegisterCommand(F("NTP.SYNC"), [](const terminal::CommandContext&) { ... }
  385. //
  386. #endif
  387. }
  388. #endif // NTP_SUPPORT && !NTP_LEGACY_SUPPORT