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.

1171 lines
32 KiB

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