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.

1197 lines
33 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
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
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
  1. /*
  2. RF BRIDGE MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include "rfbridge.h"
  6. #if RFB_SUPPORT
  7. #include "api.h"
  8. #include "relay.h"
  9. #include "terminal.h"
  10. #include "mqtt.h"
  11. #include "ws.h"
  12. #include "utils.h"
  13. BrokerBind(RfbridgeBroker);
  14. #include <algorithm>
  15. #include <cstring>
  16. #include <list>
  17. #include <memory>
  18. // -----------------------------------------------------------------------------
  19. // GLOBALS TO THE MODULE
  20. // -----------------------------------------------------------------------------
  21. unsigned char _rfb_repeat = RFB_SEND_TIMES;
  22. #if RFB_PROVIDER == RFB_PROVIDER_RCSWITCH
  23. #include <RCSwitch.h>
  24. RCSwitch * _rfb_modem;
  25. bool _rfb_receive { false };
  26. bool _rfb_transmit { false };
  27. #else
  28. constexpr bool _rfb_receive { true };
  29. constexpr bool _rfb_transmit { true };
  30. #endif
  31. // -----------------------------------------------------------------------------
  32. // MATCH RECEIVED CODE WITH THE SPECIFIC RELAY ID
  33. // -----------------------------------------------------------------------------
  34. #if RELAY_SUPPORT
  35. struct RfbRelayMatch {
  36. RfbRelayMatch() = default;
  37. RfbRelayMatch(unsigned char id_, PayloadStatus status_) :
  38. id(id_),
  39. status(status_),
  40. _found(true)
  41. {}
  42. bool ok() {
  43. return _found;
  44. }
  45. void reset(unsigned char id_, PayloadStatus status_) {
  46. id = id_;
  47. status = status_;
  48. _found = true;
  49. }
  50. unsigned char id { 0u };
  51. PayloadStatus status { PayloadStatus::Unknown };
  52. private:
  53. bool _found { false };
  54. };
  55. struct RfbLearn {
  56. unsigned long ts;
  57. unsigned char id;
  58. bool status;
  59. };
  60. static std::unique_ptr<RfbLearn> _rfb_learn;
  61. #endif // RELAY_SUPPORT
  62. // -----------------------------------------------------------------------------
  63. // EFM8BB1 PROTOCOL PARSING
  64. // -----------------------------------------------------------------------------
  65. constexpr uint8_t RfbDefaultProtocol { 0u };
  66. constexpr uint8_t CodeStart { 0xAAu };
  67. constexpr uint8_t CodeEnd { 0x55u };
  68. constexpr uint8_t CodeAck { 0xA0u };
  69. // both stock and https://github.com/Portisch/RF-Bridge-EFM8BB1/
  70. // sending:
  71. constexpr uint8_t CodeLearn { 0xA1u };
  72. // receiving:
  73. constexpr uint8_t CodeLearnTimeout { 0xA2u };
  74. constexpr uint8_t CodeLearnOk { 0xA3u };
  75. constexpr uint8_t CodeRecvBasic = { 0xA4u };
  76. constexpr uint8_t CodeSendBasic = { 0xA5u };
  77. // only https://github.com/Portisch/RF-Bridge-EFM8BB1/
  78. constexpr uint8_t CodeRecvProto { 0xA6u };
  79. constexpr uint8_t CodeRecvBucket { 0xB1u };
  80. struct RfbParser {
  81. using callback_type = void(uint8_t, const std::vector<uint8_t>&);
  82. using state_type = void(RfbParser::*)(uint8_t);
  83. // AA XX ... 55
  84. // ^~~~~ ~~ - protocol head + tail
  85. // ^~ - message code
  86. // ^~~ - actual payload is always 9 bytes
  87. static constexpr size_t PayloadSizeBasic { 9ul };
  88. static constexpr size_t MessageSizeBasic { PayloadSizeBasic + 3ul };
  89. static constexpr size_t MessageSizeMax { 112ul };
  90. RfbParser() = delete;
  91. RfbParser(const RfbParser&) = delete;
  92. explicit RfbParser(callback_type* callback) :
  93. _callback(callback)
  94. {}
  95. RfbParser(RfbParser&&) = default;
  96. void stop(uint8_t c) {
  97. }
  98. void start(uint8_t c) {
  99. switch (c) {
  100. case CodeStart:
  101. _state = &RfbParser::read_code;
  102. break;
  103. default:
  104. _state = &RfbParser::stop;
  105. break;
  106. }
  107. }
  108. void read_code(uint8_t c) {
  109. _payload_code = c;
  110. switch (c) {
  111. // Generic ACK signal. We *expect* this after our requests
  112. case CodeAck:
  113. // *Expect* any code within a certain window.
  114. // Only matters to us, does not really do anything but help us to signal that the next code needs to be recorded
  115. case CodeLearnTimeout:
  116. _state = &RfbParser::read_end;
  117. break;
  118. // both stock and https://github.com/Portisch/RF-Bridge-EFM8BB1/
  119. // receive 9 bytes, where first 3 2-byte tuples are timings
  120. // and the last 3 bytes are the actual payload
  121. case CodeLearnOk:
  122. case CodeRecvBasic:
  123. _payload_length = PayloadSizeBasic;
  124. _state = &RfbParser::read_until_length;
  125. break;
  126. // specific to the https://github.com/Portisch/RF-Bridge-EFM8BB1/
  127. // receive N bytes, where the 1st byte is the protocol ID and the next N-1 bytes are the payload
  128. case CodeRecvProto:
  129. _state = &RfbParser::read_length;
  130. break;
  131. // unlike CodeRecvProto, we don't have any length byte here :/ for some reason, it is there only when sending
  132. // just bail out when we find CodeEnd
  133. // (TODO: is number of buckets somehow convertible to the 'expected' size?)
  134. case CodeRecvBucket:
  135. _state = &RfbParser::read_length;
  136. break;
  137. default:
  138. _state = &RfbParser::stop;
  139. break;
  140. }
  141. }
  142. void read_end(uint8_t c) {
  143. if (CodeEnd == c) {
  144. _callback(_payload_code, _payload);
  145. }
  146. _state = &RfbParser::stop;
  147. }
  148. void read_until_end(uint8_t c) {
  149. if (CodeEnd == c) {
  150. read_end(c);
  151. return;
  152. }
  153. _payload.push_back(c);
  154. }
  155. void read_until_length(uint8_t c) {
  156. _payload.push_back(c);
  157. if ((_payload_offset + _payload_length) == _payload.size()) {
  158. switch (_payload_code) {
  159. case CodeLearnOk:
  160. case CodeRecvBasic:
  161. case CodeRecvProto:
  162. _state = &RfbParser::read_end;
  163. break;
  164. case CodeRecvBucket:
  165. _state = &RfbParser::read_until_end;
  166. break;
  167. default:
  168. _state = &RfbParser::stop;
  169. break;
  170. }
  171. _payload_length = 0u;
  172. }
  173. }
  174. void read_length(uint8_t c) {
  175. switch (_payload_code) {
  176. case CodeRecvProto:
  177. _payload_length = c;
  178. break;
  179. case CodeRecvBucket:
  180. _payload_length = c * 2;
  181. break;
  182. default:
  183. _state = &RfbParser::stop;
  184. return;
  185. }
  186. _payload.push_back(c);
  187. _payload_offset = _payload.size();
  188. _state = &RfbParser::read_until_length;
  189. }
  190. bool loop(uint8_t c) {
  191. (this->*_state)(c);
  192. return (_state != &RfbParser::stop);
  193. }
  194. void reset() {
  195. _payload.clear();
  196. _payload_code = 0u;
  197. _state = &RfbParser::start;
  198. }
  199. void reserve(size_t size) {
  200. _payload.reserve(size);
  201. }
  202. private:
  203. callback_type* _callback { nullptr };
  204. state_type _state { &RfbParser::start };
  205. std::vector<uint8_t> _payload;
  206. size_t _payload_length { 0ul };
  207. size_t _payload_offset { 0ul };
  208. uint8_t _payload_code { 0ul };
  209. };
  210. // -----------------------------------------------------------------------------
  211. // MESSAGE SENDER
  212. //
  213. // Depends on the selected provider. While we do serialize RCSwitch results,
  214. // we don't want to pass around such byte-array everywhere since we already
  215. // know all of the required data members and can prepare a basic POD struct
  216. // -----------------------------------------------------------------------------
  217. #if RFB_PROVIDER == RFB_PROVIDER_EFM8BB1
  218. struct RfbMessage {
  219. RfbMessage(const RfbMessage&) = default;
  220. RfbMessage(RfbMessage&&) = default;
  221. explicit RfbMessage(uint8_t (&data)[RfbParser::PayloadSizeBasic], unsigned char repeats_) :
  222. repeats(repeats_)
  223. {
  224. std::copy(data, data + sizeof(data), code);
  225. }
  226. uint8_t code[RfbParser::PayloadSizeBasic] { 0u };
  227. uint8_t repeats { 1u };
  228. };
  229. #elif RFB_PROVIDER == RFB_PROVIDER_RCSWITCH
  230. struct RfbMessage {
  231. using code_type = decltype(std::declval<RCSwitch>().getReceivedValue());
  232. static constexpr size_t BufferSize = sizeof(code_type) + 5;
  233. uint8_t protocol;
  234. uint16_t timing;
  235. uint8_t bits;
  236. code_type code;
  237. uint8_t repeats;
  238. };
  239. #endif // RFB_PROVIDER == RFB_PROVIDER_EFM8BB1
  240. static std::list<RfbMessage> _rfb_message_queue;
  241. void _rfbLearnImpl();
  242. void _rfbReceiveImpl();
  243. void _rfbSendImpl(const RfbMessage& message);
  244. // -----------------------------------------------------------------------------
  245. // WEBUI INTEGRATION
  246. // -----------------------------------------------------------------------------
  247. #if WEB_SUPPORT
  248. void _rfbWebSocketSendCodeArray(JsonObject& root, unsigned char start, unsigned char size) {
  249. JsonObject& rfb = root.createNestedObject("rfb");
  250. rfb["size"] = size;
  251. rfb["start"] = start;
  252. JsonArray& on = rfb.createNestedArray("on");
  253. JsonArray& off = rfb.createNestedArray("off");
  254. for (uint8_t id=start; id<start+size; id++) {
  255. on.add(rfbRetrieve(id, true));
  256. off.add(rfbRetrieve(id, false));
  257. }
  258. }
  259. void _rfbWebSocketOnVisible(JsonObject& root) {
  260. root["rfbVisible"] = 1;
  261. }
  262. void _rfbWebSocketOnConnected(JsonObject& root) {
  263. root["rfbRepeat"] = getSetting("rfbRepeat", RFB_SEND_TIMES);
  264. root["rfbCount"] = relayCount();
  265. #if RFB_PROVIDER == RFB_PROVIDER_RCSWITCH
  266. root["rfbdirectVisible"] = 1;
  267. root["rfbRX"] = getSetting("rfbRX", RFB_RX_PIN);
  268. root["rfbTX"] = getSetting("rfbTX", RFB_TX_PIN);
  269. #endif
  270. }
  271. void _rfbWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  272. if (strcmp(action, "rfblearn") == 0) rfbLearn(data["id"], data["status"]);
  273. if (strcmp(action, "rfbforget") == 0) rfbForget(data["id"], data["status"]);
  274. if (strcmp(action, "rfbsend") == 0) rfbStore(data["id"], data["status"], data["data"].as<const char*>());
  275. }
  276. bool _rfbWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  277. return (strncmp(key, "rfb", 3) == 0);
  278. }
  279. void _rfbWebSocketOnData(JsonObject& root) {
  280. _rfbWebSocketSendCodeArray(root, 0, relayCount());
  281. }
  282. #endif // WEB_SUPPORT
  283. // -----------------------------------------------------------------------------
  284. // RELAY <-> CODE MATCHING
  285. // -----------------------------------------------------------------------------
  286. #if RFB_PROVIDER == RFB_PROVIDER_EFM8BB1
  287. // we only care about last 6 chars (3 bytes in hex),
  288. // since in 'default' mode rfbridge only handles a single protocol
  289. bool _rfbCompare(const char* lhs, const char* rhs, size_t length) {
  290. return (0 == std::memcmp((lhs + length - 6), (rhs + length - 6), 6));
  291. }
  292. #elif RFB_PROVIDER == RFB_PROVIDER_RCSWITCH
  293. // protocol is [2:3), actual payload is [10:), as bit length may vary
  294. // although, we don't care if it does, since we expect length of both args to be the same
  295. bool _rfbCompare(const char* lhs, const char* rhs, size_t length) {
  296. return (0 == std::memcmp((lhs + 2), (rhs + 2), 2))
  297. && (0 == std::memcmp((lhs + 10), (rhs + 10), length - 10));
  298. }
  299. #endif // RFB_PROVIDER == RFB_PROVIDER_EFM8BB1
  300. #if RELAY_SUPPORT
  301. static bool _rfb_status_lock = false;
  302. // try to find the 'code' saves as either rfbON# or rfbOFF#
  303. //
  304. // **always** expect full length code as input to simplify comparison
  305. // previous implementation tried to help MQTT / API requests to match based on the saved code,
  306. // thus requiring us to 'return' value from settings as the real code, replacing input
  307. RfbRelayMatch _rfbMatch(const char* code) {
  308. if (!relayCount()) {
  309. return {};
  310. }
  311. const auto len = strlen(code);
  312. // we gather all available options, as the kv store might be defined in any order
  313. // scan kvs only once, since we want both ON and OFF options and don't want to depend on the relayCount()
  314. RfbRelayMatch matched;
  315. using namespace settings;
  316. kv_store.foreach([code, len, &matched](kvs_type::KeyValueResult&& kv) {
  317. const auto key = kv.key.read();
  318. PayloadStatus status = key.startsWith(F("rfbON"))
  319. ? PayloadStatus::On : key.startsWith(F("rfbOFF"))
  320. ? PayloadStatus::Off : PayloadStatus::Unknown;
  321. if (PayloadStatus::Unknown == status) {
  322. return;
  323. }
  324. const auto value = kv.value.read();
  325. if (len != value.length()) {
  326. return;
  327. }
  328. if (!_rfbCompare(code, value.c_str(), len)) {
  329. return;
  330. }
  331. // note: strlen is constexpr here
  332. const char* id_ptr = key.c_str() + (
  333. (PayloadStatus::On == status) ? strlen("rfbON") : strlen("rfbOFF"));
  334. if (*id_ptr == '\0') {
  335. return;
  336. }
  337. char *endptr = nullptr;
  338. const auto id = strtoul(id_ptr, &endptr, 10);
  339. if (endptr == id_ptr || endptr[0] != '\0' || id > std::numeric_limits<uint8_t>::max() || id >= relayCount()) {
  340. return;
  341. }
  342. // when we see the same id twice, we match the opposite statuses
  343. if (matched.ok() && (id == matched.id)) {
  344. matched.status = PayloadStatus::Toggle;
  345. return;
  346. }
  347. matched.reset(matched.ok()
  348. ? std::min(static_cast<uint8_t>(id), matched.id)
  349. : static_cast<uint8_t>(id),
  350. status
  351. );
  352. });
  353. return matched;
  354. }
  355. void _rfbLearnFromString(std::unique_ptr<RfbLearn>& learn, const char* buffer) {
  356. if (!learn) return;
  357. DEBUG_MSG_P(PSTR("[RF] Learned %s for relay ID %u after %u ms\n"), buffer, learn->id, millis() - learn->ts);
  358. rfbStore(learn->id, learn->status, buffer);
  359. // Websocket update needs to happen right here, since the only time
  360. // we send these in bulk is at the very start of the connection
  361. #if WEB_SUPPORT
  362. auto id = learn->id;
  363. wsPost([id](JsonObject& root) {
  364. _rfbWebSocketSendCodeArray(root, id, 1);
  365. });
  366. #endif
  367. learn.reset(nullptr);
  368. }
  369. bool _rfbRelayHandler(const char* buffer, bool locked = false) {
  370. _rfb_status_lock = locked;
  371. bool result { false };
  372. auto match = _rfbMatch(buffer);
  373. if (match.ok()) {
  374. DEBUG_MSG_P(PSTR("[RF] Matched with the relay ID %u\n"), match.id);
  375. switch (match.status) {
  376. case PayloadStatus::On:
  377. case PayloadStatus::Off:
  378. relayStatus(match.id, (PayloadStatus::On == match.status));
  379. result = true;
  380. break;
  381. case PayloadStatus::Toggle:
  382. relayToggle(match.id);
  383. result = true;
  384. case PayloadStatus::Unknown:
  385. break;
  386. }
  387. }
  388. _rfb_status_lock = false;
  389. return result;
  390. }
  391. #endif // RELAY_SUPPORT
  392. // -----------------------------------------------------------------------------
  393. // RF handler implementations
  394. // -----------------------------------------------------------------------------
  395. #if RFB_PROVIDER == RFB_PROVIDER_EFM8BB1
  396. void _rfbEnqueue(uint8_t (&code)[RfbParser::PayloadSizeBasic], unsigned char repeats = 1u) {
  397. if (!_rfb_transmit) return;
  398. _rfb_message_queue.push_back(RfbMessage(code, repeats));
  399. }
  400. bool _rfbEnqueue(const char* code, unsigned char repeats = 1u) {
  401. uint8_t buffer[RfbParser::PayloadSizeBasic] { 0u };
  402. if (hexDecode(code, strlen(code), buffer, sizeof(buffer))) {
  403. _rfbEnqueue(buffer, repeats);
  404. return true;
  405. }
  406. DEBUG_MSG_P(PSTR("[RF] Cannot decode the message\n"));
  407. return false;
  408. }
  409. void _rfbSendRaw(const uint8_t* message, unsigned char size) {
  410. Serial.write(message, size);
  411. }
  412. void _rfbAckImpl() {
  413. static uint8_t message[3] {
  414. CodeStart, CodeAck, CodeEnd
  415. };
  416. DEBUG_MSG_P(PSTR("[RF] Sending ACK\n"));
  417. Serial.write(message, sizeof(message));
  418. Serial.flush();
  419. }
  420. void _rfbLearnImpl() {
  421. static uint8_t message[3] {
  422. CodeStart, CodeLearn, CodeEnd
  423. };
  424. DEBUG_MSG_P(PSTR("[RF] Sending LEARN\n"));
  425. Serial.write(message, sizeof(message));
  426. Serial.flush();
  427. }
  428. void _rfbSendImpl(const RfbMessage& message) {
  429. Serial.write(CodeStart);
  430. Serial.write(CodeSendBasic);
  431. _rfbSendRaw(message.code, sizeof(message.code));
  432. Serial.write(CodeEnd);
  433. Serial.flush();
  434. }
  435. void _rfbParse(uint8_t code, const std::vector<uint8_t>& payload) {
  436. switch (code) {
  437. case CodeAck:
  438. DEBUG_MSG_P(PSTR("[RF] Received ACK\n"));
  439. break;
  440. case CodeLearnTimeout:
  441. _rfbAckImpl();
  442. #if RELAY_SUPPORT
  443. DEBUG_MSG_P(PSTR("[RF] Learn timeout after %u ms\n"), millis() - _rfb_learn->ts);
  444. _rfb_learn.reset(nullptr);
  445. #endif
  446. break;
  447. case CodeLearnOk:
  448. case CodeRecvBasic: {
  449. _rfbAckImpl();
  450. if (payload.size() != RfbParser::PayloadSizeBasic) {
  451. break;
  452. }
  453. char buffer[(RfbParser::PayloadSizeBasic * 2) + 1] = {0};
  454. if (hexEncode(payload.data(), payload.size(), buffer, sizeof(buffer))) {
  455. DEBUG_MSG_P(PSTR("[RF] Received code: %s\n"), buffer);
  456. #if RELAY_SUPPORT
  457. if (CodeLearnOk == code) {
  458. _rfbLearnFromString(_rfb_learn, buffer);
  459. } else {
  460. _rfbRelayHandler(buffer);
  461. }
  462. #endif
  463. #if MQTT_SUPPORT
  464. mqttSend(MQTT_TOPIC_RFIN, buffer, false, false);
  465. #endif
  466. #if BROKER_SUPPORT
  467. RfbridgeBroker::Publish(RfbDefaultProtocol, buffer + 6);
  468. #endif
  469. }
  470. break;
  471. }
  472. case CodeRecvProto:
  473. case CodeRecvBucket: {
  474. _rfbAckImpl();
  475. char buffer[(RfbParser::MessageSizeMax * 2) + 1] = {0};
  476. if (hexEncode(payload.data(), payload.size(), buffer, sizeof(buffer))) {
  477. DEBUG_MSG_P(PSTR("[RF] Received %s code: %s\n"),
  478. (CodeRecvProto == code) ? "advanced" : "bucket", buffer
  479. );
  480. #if MQTT_SUPPORT
  481. mqttSend(MQTT_TOPIC_RFIN, buffer, false, false);
  482. #endif
  483. #if BROKER_SUPPORT
  484. // ref. https://github.com/Portisch/RF-Bridge-EFM8BB1/wiki/0xA6#example-of-a-received-decoded-protocol
  485. RfbridgeBroker::Publish(payload[0], buffer + 2);
  486. #endif
  487. } else {
  488. DEBUG_MSG_P(PSTR("[RF] Received 0x%02X (%u bytes)\n"), code, payload.size());
  489. }
  490. break;
  491. }
  492. }
  493. }
  494. static RfbParser _rfb_parser(_rfbParse);
  495. void _rfbReceiveImpl() {
  496. while (Serial.available()) {
  497. auto c = Serial.read();
  498. if (c < 0) {
  499. continue;
  500. }
  501. // narrowing is justified, as `c` can only contain byte-sized value
  502. if (!_rfb_parser.loop(static_cast<uint8_t>(c))) {
  503. _rfb_parser.reset();
  504. }
  505. }
  506. }
  507. // note that we don't care about queue here, just dump raw message as-is
  508. void _rfbSendRawFromPayload(const char * raw) {
  509. auto rawlen = strlen(raw);
  510. if (rawlen > (RfbParser::MessageSizeMax * 2)) return;
  511. if ((rawlen < 6) || (rawlen & 1)) return;
  512. DEBUG_MSG_P(PSTR("[RF] Sending RAW MESSAGE \"%s\"\n"), raw);
  513. size_t bytes = 0;
  514. uint8_t message[RfbParser::MessageSizeMax] { 0u };
  515. if ((bytes = hexDecode(raw, rawlen, message, sizeof(message)))) {
  516. if (message[0] != CodeStart) return;
  517. if (message[bytes - 1] != CodeEnd) return;
  518. _rfbSendRaw(message, bytes);
  519. }
  520. }
  521. #elif RFB_PROVIDER == RFB_PROVIDER_RCSWITCH
  522. namespace {
  523. size_t _rfb_bits_for_bytes(size_t bits) {
  524. decltype(bits) bytes = 0;
  525. decltype(bits) need = 0;
  526. while (need < bits) {
  527. need += 8u;
  528. bytes += 1u;
  529. }
  530. return bytes;
  531. }
  532. // TODO: RCSwitch code type: long unsigned int != uint32_t, thus the specialization
  533. static_assert(sizeof(uint32_t) == sizeof(long unsigned int), "");
  534. template <typename T>
  535. T _rfb_bswap(T value);
  536. template <>
  537. [[gnu::unused]] uint32_t _rfb_bswap(uint32_t value) {
  538. return __builtin_bswap32(value);
  539. }
  540. template <>
  541. [[gnu::unused]] long unsigned int _rfb_bswap(long unsigned int value) {
  542. return __builtin_bswap32(value);
  543. }
  544. template <>
  545. [[gnu::unused]] uint64_t _rfb_bswap(uint64_t value) {
  546. return __builtin_bswap64(value);
  547. }
  548. }
  549. void _rfbEnqueue(uint8_t protocol, uint16_t timing, uint8_t bits, RfbMessage::code_type code, unsigned char repeats = 1u) {
  550. if (!_rfb_transmit) return;
  551. _rfb_message_queue.push_back(RfbMessage{protocol, timing, bits, code, repeats});
  552. }
  553. void _rfbEnqueue(const char* code, unsigned char repeats = 1u) {
  554. uint8_t buffer[RfbMessage::BufferSize] { 0u };
  555. if (hexDecode(code, strlen(code), buffer, sizeof(buffer))) {
  556. RfbMessage::code_type code;
  557. std::memcpy(&code, &buffer[5], _rfb_bits_for_bytes(buffer[4]));
  558. code = _rfb_bswap(code);
  559. _rfbEnqueue(buffer[1], (buffer[3] << 8) | buffer[2], buffer[4], code, repeats);
  560. } else {
  561. DEBUG_MSG_P(PSTR("[RF] Cannot decode the message\n"));
  562. }
  563. }
  564. void _rfbLearnImpl() {
  565. DEBUG_MSG_P(PSTR("[RF] Entering LEARN mode\n"));
  566. }
  567. void _rfbSendImpl(const RfbMessage& message) {
  568. if (!_rfb_transmit) return;
  569. // TODO: note that this seems to be setting global setting
  570. // if code for some reason forgets this, we end up with the previous value
  571. _rfb_modem->setProtocol(message.protocol);
  572. if (message.timing) {
  573. _rfb_modem->setPulseLength(message.timing);
  574. }
  575. _rfb_modem->send(message.code, message.bits);
  576. _rfb_modem->resetAvailable();
  577. }
  578. // Try to mimic the basic RF message format. although, we might have different size of the code itself
  579. // Skip leading zeroes and only keep the useful data
  580. //
  581. // TODO: 'timing' value shooould be relatively small,
  582. // since it's original intent was to be used with 16bit ints
  583. // TODO: both 'protocol' and 'bitlength' fit in a byte, despite being declared as 'unsigned int'
  584. size_t _rfbModemPack(uint8_t (&out)[RfbMessage::BufferSize], RfbMessage::code_type code, unsigned int protocol, unsigned int timing, unsigned int bits) {
  585. static_assert((sizeof(decltype(code)) == 4) || (sizeof(decltype(code)) == 8), "");
  586. size_t index = 0;
  587. out[index++] = 0xC0;
  588. out[index++] = static_cast<uint8_t>(protocol);
  589. out[index++] = static_cast<uint8_t>(timing >> 8);
  590. out[index++] = static_cast<uint8_t>(timing);
  591. out[index++] = static_cast<uint8_t>(bits);
  592. auto bytes = _rfb_bits_for_bytes(bits);
  593. if (bytes > (sizeof(out) - index)) {
  594. return 0;
  595. }
  596. // manually overload each bswap, since we can't use ternary here
  597. // (and `if constexpr (...)` is only available starting from Arduino Core 3.x.x)
  598. decltype(code) swapped = _rfb_bswap(code);
  599. uint8_t raw[sizeof(swapped)];
  600. std::memcpy(raw, &swapped, sizeof(raw));
  601. while (bytes) {
  602. out[index++] = raw[sizeof(raw) - (bytes--)];
  603. }
  604. return index;
  605. }
  606. void _rfbLearnFromReceived(std::unique_ptr<RfbLearn>& learn, const char* buffer) {
  607. if (millis() - learn->ts > RFB_LEARN_TIMEOUT) {
  608. DEBUG_MSG_P(PSTR("[RF] Learn timeout after %u ms\n"), millis() - learn->ts);
  609. learn.reset(nullptr);
  610. return;
  611. }
  612. _rfbLearnFromString(learn, buffer);
  613. }
  614. void _rfbReceiveImpl() {
  615. if (!_rfb_receive) return;
  616. if (!_rfb_modem->available()) return;
  617. static unsigned long last = 0;
  618. if (millis() - last < RFB_RECEIVE_DELAY) return;
  619. last = millis();
  620. auto rf_code = _rfb_modem->getReceivedValue();
  621. if (!rf_code) return;
  622. uint8_t message[RfbMessage::BufferSize];
  623. auto real_msgsize = _rfbModemPack(
  624. message,
  625. rf_code,
  626. _rfb_modem->getReceivedProtocol(),
  627. _rfb_modem->getReceivedDelay(),
  628. _rfb_modem->getReceivedBitlength()
  629. );
  630. char buffer[(sizeof(message) * 2) + 1] = {0};
  631. if (hexEncode(message, real_msgsize, buffer, sizeof(buffer))) {
  632. DEBUG_MSG_P(PSTR("[RF] Received code: %s\n"), buffer);
  633. #if RELAY_SUPPORT
  634. if (_rfb_learn) {
  635. _rfbLearnFromReceived(_rfb_learn, buffer);
  636. } else {
  637. _rfbRelayHandler(buffer);
  638. }
  639. #endif
  640. #if MQTT_SUPPORT
  641. mqttSend(MQTT_TOPIC_RFIN, buffer, false, false);
  642. #endif
  643. #if BROKER_SUPPORT
  644. RfbridgeBroker::Publish(message[1], buffer + 10);
  645. #endif
  646. }
  647. _rfb_modem->resetAvailable();
  648. }
  649. #endif // RFB_PROVIDER == ...
  650. void _rfbSendQueued() {
  651. if (!_rfb_transmit) return;
  652. if (_rfb_message_queue.empty()) return;
  653. static unsigned long last = 0;
  654. if (millis() - last < RFB_SEND_DELAY) return;
  655. last = millis();
  656. auto message = _rfb_message_queue.front();
  657. _rfb_message_queue.pop_front();
  658. _rfbSendImpl(message);
  659. // Sometimes we really want to repeat the message, not only to rely on built-in transfer repeat
  660. if (message.repeats > 1) {
  661. message.repeats -= 1;
  662. _rfb_message_queue.push_back(std::move(message));
  663. }
  664. yield();
  665. }
  666. // Check if the payload looks like a HEX code (plus comma, specifying the 'repeats' arg for the queue)
  667. void _rfbSendFromPayload(const char * payload) {
  668. size_t repeats { 1ul };
  669. size_t len { strlen(payload) };
  670. const char* sep { strchr(payload, ',') };
  671. if (sep && (*(sep + 1) != '\0')) {
  672. char *endptr = nullptr;
  673. repeats = strtoul(sep, &endptr, 10);
  674. if (endptr == payload || endptr[0] != '\0') {
  675. return;
  676. }
  677. len -= strlen(sep);
  678. }
  679. if (!len || (len & 1)) {
  680. return;
  681. }
  682. // We postpone the actual sending until the loop, as we may've been called from MQTT or HTTP API
  683. // RFB_PROVIDER implementation should select the appropriate de-serialization function
  684. _rfbEnqueue(payload, repeats);
  685. }
  686. void _rfbLearnStartFromPayload(const char* payload) {
  687. // The payload must be the `relayID,mode` (where mode is either 0 or 1)
  688. const char* sep = strchr(payload, ',');
  689. if (nullptr == sep) {
  690. return;
  691. }
  692. // ref. RelaysMax, we only have up to 2 digits
  693. char relay[3] {0, 0, 0};
  694. if ((sep - payload) > 2) {
  695. return;
  696. }
  697. std::copy(payload, sep, relay);
  698. char *endptr = nullptr;
  699. const auto id = strtoul(relay, &endptr, 10);
  700. if (endptr == &relay[0] || endptr[0] != '\0') {
  701. return;
  702. }
  703. if (id >= relayCount()) {
  704. DEBUG_MSG_P(PSTR("[RF] Invalid relay ID (%u)\n"), id);
  705. return;
  706. }
  707. ++sep;
  708. if ((*sep == '0') || (*sep == '1')) {
  709. rfbLearn(id, (*sep != '0'));
  710. }
  711. }
  712. #if MQTT_SUPPORT
  713. void _rfbMqttCallback(unsigned int type, const char * topic, char * payload) {
  714. if (type == MQTT_CONNECT_EVENT) {
  715. char buffer[strlen(MQTT_TOPIC_RFLEARN) + 3];
  716. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_RFLEARN);
  717. mqttSubscribe(buffer);
  718. if (_rfb_transmit) {
  719. mqttSubscribe(MQTT_TOPIC_RFOUT);
  720. }
  721. #if RFB_PROVIDER == RFB_PROVIDER_EFM8BB1
  722. mqttSubscribe(MQTT_TOPIC_RFRAW);
  723. #endif
  724. }
  725. if (type == MQTT_MESSAGE_EVENT) {
  726. String t = mqttMagnitude((char *) topic);
  727. if (t.startsWith(MQTT_TOPIC_RFLEARN)) {
  728. _rfbLearnStartFromPayload(payload);
  729. return;
  730. }
  731. if (t.equals(MQTT_TOPIC_RFOUT)) {
  732. #if RELAY_SUPPORT
  733. // we *sometimes* want to check the code against available rfbON / rfbOFF
  734. // e.g. in case we want to control some external device and have an external remote.
  735. // - when remote press happens, relays stay in sync when we receive the code via the processing loop
  736. // - when we send the code here, we never register it as *sent*,, thus relays need to be made in sync manually
  737. if (!_rfbRelayHandler(payload, /* locked = */ true)) {
  738. #endif
  739. _rfbSendFromPayload(payload);
  740. #if RELAY_SUPPORT
  741. }
  742. #endif
  743. return;
  744. }
  745. #if RFB_PROVIDER == RFB_PROVIDER_EFM8BB1
  746. if (t.equals(MQTT_TOPIC_RFRAW)) {
  747. // in case this is RAW message, we should not match anything and just send it as-is to the serial
  748. _rfbSendRawFromPayload(payload);
  749. return;
  750. }
  751. #endif
  752. }
  753. }
  754. #endif // MQTT_SUPPORT
  755. #if API_SUPPORT
  756. void _rfbApiSetup() {
  757. apiReserve(3u);
  758. apiRegister({
  759. MQTT_TOPIC_RFOUT, Api::Type::Basic, ApiUnusedArg,
  760. apiOk, // just a stub, nothing to return
  761. [](const Api&, ApiBuffer& buffer) {
  762. _rfbSendFromPayload(buffer.data);
  763. }
  764. });
  765. apiRegister({
  766. MQTT_TOPIC_RFLEARN, Api::Type::Basic, ApiUnusedArg,
  767. [](const Api&, ApiBuffer& buffer) {
  768. if (_rfb_learn) {
  769. snprintf_P(buffer.data, buffer.size, PSTR("learning id:%u,status:%c"),
  770. _rfb_learn->id, _rfb_learn->status ? 't' : 'f'
  771. );
  772. } else {
  773. snprintf_P(buffer.data, buffer.size, PSTR("waiting"));
  774. }
  775. },
  776. [](const Api&, ApiBuffer& buffer) {
  777. _rfbLearnStartFromPayload(buffer.data);
  778. }
  779. });
  780. #if RFB_PROVIDER == RFB_PROVIDER_EFM8BB1
  781. apiRegister({
  782. MQTT_TOPIC_RFRAW, Api::Type::Basic, ApiUnusedArg,
  783. apiOk, // just a stub, nothing to return
  784. [](const Api&, ApiBuffer& buffer) {
  785. _rfbSendRawFromPayload(buffer.data);
  786. }
  787. });
  788. #endif
  789. }
  790. #endif // API_SUPPORT
  791. #if TERMINAL_SUPPORT
  792. void _rfbInitCommands() {
  793. terminalRegisterCommand(F("RFB.LEARN"), [](const terminal::CommandContext& ctx) {
  794. if (ctx.argc != 3) {
  795. terminalError(ctx, F("RFB.LEARN <ID> <STATUS>"));
  796. return;
  797. }
  798. int id = ctx.argv[1].toInt();
  799. if (id >= relayCount()) {
  800. terminalError(ctx, F("Invalid relay ID"));
  801. return;
  802. }
  803. rfbLearn(id, (ctx.argv[2].toInt()) == 1);
  804. terminalOK(ctx);
  805. });
  806. terminalRegisterCommand(F("RFB.FORGET"), [](const terminal::CommandContext& ctx) {
  807. if (ctx.argc < 2) {
  808. terminalError(ctx, F("RFB.FORGET <ID> [<STATUS>]"));
  809. return;
  810. }
  811. int id = ctx.argv[1].toInt();
  812. if (id >= relayCount()) {
  813. terminalError(ctx, F("Invalid relay ID"));
  814. return;
  815. }
  816. if (ctx.argc == 3) {
  817. rfbForget(id, (ctx.argv[2].toInt()) == 1);
  818. } else {
  819. rfbForget(id, true);
  820. rfbForget(id, false);
  821. }
  822. terminalOK(ctx);
  823. });
  824. #if RFB_PROVIDER == RFB_PROVIDER_EFM8BB1
  825. terminalRegisterCommand(F("RFB.WRITE"), [](const terminal::CommandContext& ctx) {
  826. if (ctx.argc != 2) {
  827. terminalError(ctx, F("RFB.WRITE <PAYLOAD>"));
  828. return;
  829. }
  830. _rfbSendRawFromPayload(ctx.argv[1].c_str());
  831. terminalOK(ctx);
  832. });
  833. #endif
  834. }
  835. #endif // TERMINAL_SUPPORT
  836. // -----------------------------------------------------------------------------
  837. // PUBLIC
  838. // -----------------------------------------------------------------------------
  839. void rfbStore(unsigned char id, bool status, const char * code) {
  840. settings_key_t key { status ? F("rfbON") : F("rfbOFF"), id };
  841. setSetting(key, code);
  842. DEBUG_MSG_P(PSTR("[RF] Saved %s => \"%s\"\n"), key.toString().c_str(), code);
  843. }
  844. String rfbRetrieve(unsigned char id, bool status) {
  845. return getSetting({ status ? F("rfbON") : F("rfbOFF"), id });
  846. }
  847. void rfbStatus(unsigned char id, bool status) {
  848. // ref. receiver loop, we need to protect ourselves from re-sending the code we received to turn this relay ID on / off
  849. if (_rfb_status_lock) {
  850. return;
  851. }
  852. String value = rfbRetrieve(id, status);
  853. if (value.length() && !(value.length() & 1)) {
  854. _rfbSendFromPayload(value.c_str());
  855. }
  856. }
  857. void rfbLearn(unsigned char id, bool status) {
  858. _rfb_learn.reset(new RfbLearn { millis(), id, status });
  859. _rfbLearnImpl();
  860. }
  861. void rfbForget(unsigned char id, bool status) {
  862. delSetting({status ? F("rfbON") : F("rfbOFF"), id});
  863. // Websocket update needs to happen right here, since the only time
  864. // we send these in bulk is at the very start of the connection
  865. #if WEB_SUPPORT
  866. wsPost([id](JsonObject& root) {
  867. _rfbWebSocketSendCodeArray(root, id, 1);
  868. });
  869. #endif
  870. }
  871. // -----------------------------------------------------------------------------
  872. // SETUP & LOOP
  873. // -----------------------------------------------------------------------------
  874. void rfbSetup() {
  875. #if RFB_PROVIDER == RFB_PROVIDER_EFM8BB1
  876. _rfb_parser.reserve(RfbParser::MessageSizeBasic);
  877. #elif RFB_PROVIDER == RFB_PROVIDER_RCSWITCH
  878. {
  879. auto rx = getSetting("rfbRX", RFB_RX_PIN);
  880. auto tx = getSetting("rfbTX", RFB_TX_PIN);
  881. // TODO: tag gpioGetLock with a NAME string, skip log here
  882. _rfb_receive = gpioValid(rx);
  883. _rfb_transmit = gpioValid(tx);
  884. if (!_rfb_transmit && !_rfb_receive) {
  885. DEBUG_MSG_P(PSTR("[RF] Neither RX or TX are set\n"));
  886. return;
  887. }
  888. _rfb_modem = new RCSwitch();
  889. if (_rfb_receive) {
  890. _rfb_modem->enableReceive(rx);
  891. DEBUG_MSG_P(PSTR("[RF] RF receiver on GPIO %u\n"), rx);
  892. }
  893. if (_rfb_transmit) {
  894. auto transmit = getSetting("rfbTransmit", RFB_TRANSMIT_TIMES);
  895. _rfb_modem->enableTransmit(tx);
  896. _rfb_modem->setRepeatTransmit(transmit);
  897. DEBUG_MSG_P(PSTR("[RF] RF transmitter on GPIO %u\n"), tx);
  898. }
  899. }
  900. #endif
  901. #if MQTT_SUPPORT
  902. mqttRegister(_rfbMqttCallback);
  903. #endif
  904. #if API_SUPPORT
  905. _rfbApiSetup();
  906. #endif
  907. #if WEB_SUPPORT
  908. wsRegister()
  909. .onVisible(_rfbWebSocketOnVisible)
  910. .onConnected(_rfbWebSocketOnConnected)
  911. .onData(_rfbWebSocketOnData)
  912. .onAction(_rfbWebSocketOnAction)
  913. .onKeyCheck(_rfbWebSocketOnKeyCheck);
  914. #endif
  915. #if TERMINAL_SUPPORT
  916. _rfbInitCommands();
  917. #endif
  918. _rfb_repeat = getSetting("rfbRepeat", RFB_SEND_TIMES);
  919. // Note: as rfbridge protocol is simplistic enough, we rely on Serial queue to deliver timely updates
  920. // learn / command acks / etc. are not queued, only RF messages are
  921. espurnaRegisterLoop([]() {
  922. _rfbReceiveImpl();
  923. _rfbSendQueued();
  924. });
  925. }
  926. #endif // RFB_SUPPORT