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.

736 lines
20 KiB

7 years ago
7 years ago
7 years ago
7 years ago
  1. /*
  2. RELAY MODULE
  3. Copyright (C) 2016-2017 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #include <EEPROM.h>
  6. #include <Ticker.h>
  7. #include <ArduinoJson.h>
  8. #include <vector>
  9. #include <functional>
  10. typedef struct {
  11. // Configuration variables
  12. unsigned char pin; // GPIO pin for the relay
  13. unsigned char type; // RELAY_TYPE_NORMAL, RELAY_TYPE_INVERSE or RELAY_TYPE_LATCHED
  14. unsigned char reset_pin; // GPIO to reset the relay if RELAY_TYPE_LATCHED
  15. unsigned long pulse; // RELAY_PULSE_NONE, RELAY_PULSE_OFF or RELAY_PULSE_ON
  16. unsigned long pulse_ms; // Pulse length in millis
  17. unsigned long delay_on; // Delay to turn relay ON
  18. unsigned long delay_off; // Delay to turn relay OFF
  19. // Status variables
  20. bool current_status; // Holds the current (physical) status of the relay
  21. bool target_status; // Holds the target status
  22. unsigned int fw_start; // Flood window start time
  23. unsigned char fw_count; // Number of changes within the current flood window
  24. unsigned int change_time; // Scheduled time to change
  25. bool report; // Whether to report to own topic
  26. bool group_report; // Whether to report to group topic
  27. // Helping objects
  28. Ticker pulseTicker; // Holds the pulse back timer
  29. } relay_t;
  30. std::vector<relay_t> _relays;
  31. bool _relayRecursive = false;
  32. Ticker _relaySaveTicker;
  33. // -----------------------------------------------------------------------------
  34. // RELAY PROVIDERS
  35. // -----------------------------------------------------------------------------
  36. void _relayProviderStatus(unsigned char id, bool status) {
  37. // Check relay ID
  38. if (id >= _relays.size()) return;
  39. // Store new current status
  40. _relays[id].current_status = status;
  41. #if RELAY_PROVIDER == RELAY_PROVIDER_RFBRIDGE
  42. rfbStatus(id, status);
  43. #endif
  44. #if RELAY_PROVIDER == RELAY_PROVIDER_DUAL
  45. // Calculate mask
  46. unsigned char mask=0;
  47. for (unsigned char i=0; i<_relays.size(); i++) {
  48. if (_relays[i].current_status) mask = mask + (1 << i);
  49. }
  50. // Send it to F330
  51. Serial.flush();
  52. Serial.write(0xA0);
  53. Serial.write(0x04);
  54. Serial.write(mask);
  55. Serial.write(0xA1);
  56. Serial.flush();
  57. #endif
  58. #if RELAY_PROVIDER == RELAY_PROVIDER_LIGHT
  59. lightState(status);
  60. lightUpdate(true, true);
  61. #endif
  62. #if RELAY_PROVIDER == RELAY_PROVIDER_RELAY
  63. if (_relays[id].type == RELAY_TYPE_NORMAL) {
  64. digitalWrite(_relays[id].pin, status);
  65. } else if (_relays[id].type == RELAY_TYPE_INVERSE) {
  66. digitalWrite(_relays[id].pin, !status);
  67. } else if (_relays[id].type == RELAY_TYPE_LATCHED) {
  68. digitalWrite(_relays[id].pin, LOW);
  69. digitalWrite(_relays[id].reset_pin, LOW);
  70. if (status) {
  71. digitalWrite(_relays[id].pin, HIGH);
  72. } else {
  73. digitalWrite(_relays[id].reset_pin, HIGH);
  74. }
  75. delay(RELAY_LATCHING_PULSE);
  76. digitalWrite(_relays[id].pin, LOW);
  77. digitalWrite(_relays[id].reset_pin, LOW);
  78. }
  79. #endif
  80. }
  81. // -----------------------------------------------------------------------------
  82. // RELAY
  83. // -----------------------------------------------------------------------------
  84. void relayPulse(unsigned char id) {
  85. byte mode = _relays[id].pulse;
  86. if (mode == RELAY_PULSE_NONE) return;
  87. unsigned long ms = _relays[id].pulse_ms;
  88. if (ms == 0) return;
  89. bool status = relayStatus(id);
  90. bool pulseStatus = (mode == RELAY_PULSE_ON);
  91. if (pulseStatus == status) {
  92. _relays[id].pulseTicker.detach();
  93. } else {
  94. _relays[id].pulseTicker.once_ms(ms, relayToggle, id);
  95. }
  96. }
  97. bool relayStatus(unsigned char id, bool status, bool report, bool group_report) {
  98. if (id >= _relays.size()) return false;
  99. bool changed = false;
  100. if (_relays[id].current_status == status) {
  101. if (_relays[id].target_status != status) {
  102. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled change cancelled\n"), id);
  103. _relays[id].target_status = status;
  104. _relays[id].report = false;
  105. _relays[id].group_report = false;
  106. changed = true;
  107. }
  108. } else {
  109. unsigned int current_time = millis();
  110. unsigned int fw_end = _relays[id].fw_start + 1000 * RELAY_FLOOD_WINDOW;
  111. unsigned long delay = status ? _relays[id].delay_on : _relays[id].delay_off;
  112. _relays[id].fw_count++;
  113. _relays[id].change_time = current_time + delay;
  114. // If current_time is off-limits the floodWindow...
  115. if (current_time < _relays[id].fw_start || fw_end <= current_time) {
  116. // We reset the floodWindow
  117. _relays[id].fw_start = current_time;
  118. _relays[id].fw_count = 1;
  119. // If current_time is in the floodWindow and there have been too many requests...
  120. } else if (_relays[id].fw_count >= RELAY_FLOOD_CHANGES) {
  121. // We schedule the changes to the end of the floodWindow
  122. // unless it's already delayed beyond that point
  123. if (fw_end - delay > current_time) {
  124. _relays[id].change_time = fw_end;
  125. }
  126. }
  127. _relays[id].target_status = status;
  128. if (report) _relays[id].report = true;
  129. if (group_report) _relays[id].group_report = true;
  130. relaySync(id);
  131. DEBUG_MSG_P(PSTR("[RELAY] #%d scheduled %s in %u ms\n"),
  132. id, status ? "ON" : "OFF",
  133. (_relays[id].change_time - current_time));
  134. changed = true;
  135. }
  136. return changed;
  137. }
  138. bool relayStatus(unsigned char id, bool status) {
  139. return relayStatus(id, status, true, true);
  140. }
  141. bool relayStatus(unsigned char id) {
  142. // Check relay ID
  143. if (id >= _relays.size()) return false;
  144. // Get status from storage
  145. return _relays[id].current_status;
  146. }
  147. void relaySync(unsigned char id) {
  148. // No sync if none or only one relay
  149. if (_relays.size() < 2) return;
  150. // Do not go on if we are comming from a previous sync
  151. if (_relayRecursive) return;
  152. // Flag sync mode
  153. _relayRecursive = true;
  154. byte relaySync = getSetting("relaySync", RELAY_SYNC).toInt();
  155. bool status = _relays[id].target_status;
  156. // If RELAY_SYNC_SAME all relays should have the same state
  157. if (relaySync == RELAY_SYNC_SAME) {
  158. for (unsigned short i=0; i<_relays.size(); i++) {
  159. if (i != id) relayStatus(i, status);
  160. }
  161. // If NONE_OR_ONE or ONE and setting ON we should set OFF all the others
  162. } else if (status) {
  163. if (relaySync != RELAY_SYNC_ANY) {
  164. for (unsigned short i=0; i<_relays.size(); i++) {
  165. if (i != id) relayStatus(i, false);
  166. }
  167. }
  168. // If ONLY_ONE and setting OFF we should set ON the other one
  169. } else {
  170. if (relaySync == RELAY_SYNC_ONE) {
  171. unsigned char i = (id + 1) % _relays.size();
  172. relayStatus(i, true);
  173. }
  174. }
  175. // Unflag sync mode
  176. _relayRecursive = false;
  177. }
  178. void relaySave() {
  179. unsigned char bit = 1;
  180. unsigned char mask = 0;
  181. for (unsigned int i=0; i < _relays.size(); i++) {
  182. if (relayStatus(i)) mask += bit;
  183. bit += bit;
  184. }
  185. EEPROM.write(EEPROM_RELAY_STATUS, mask);
  186. DEBUG_MSG_P(PSTR("[RELAY] Saving mask: %d\n"), mask);
  187. EEPROM.commit();
  188. }
  189. void relayToggle(unsigned char id, bool report, bool group_report) {
  190. if (id >= _relays.size()) return;
  191. relayStatus(id, !relayStatus(id), report, group_report);
  192. }
  193. void relayToggle(unsigned char id) {
  194. relayToggle(id, true, true);
  195. }
  196. unsigned char relayCount() {
  197. return _relays.size();
  198. }
  199. unsigned char relayParsePayload(const char * payload) {
  200. // Payload could be "OFF", "ON", "TOGGLE"
  201. // or its number equivalents: 0, 1 or 2
  202. // trim payload
  203. char * p = ltrim((char *)payload);
  204. // to lower
  205. for (unsigned char i=0; i<strlen(p); i++) {
  206. p[i] = tolower(p[i]);
  207. }
  208. unsigned int value;
  209. if (strcmp(p, "off") == 0) {
  210. value = 0;
  211. } else if (strcmp(p, "on") == 0) {
  212. value = 1;
  213. } else if (strcmp(p, "toggle") == 0) {
  214. value = 2;
  215. } else if (strcmp(p, "query") == 0) {
  216. value = 3;
  217. } else {
  218. value = p[0] - '0';
  219. }
  220. if (0 <= value && value <=3) return value;
  221. return 0xFF;
  222. }
  223. // BACKWARDS COMPATIBILITY
  224. void _relayBackwards() {
  225. byte relayMode = getSetting("relayMode", RELAY_BOOT_MODE).toInt();
  226. byte relayPulseMode = getSetting("relayPulseMode", RELAY_PULSE_MODE).toInt();
  227. float relayPulseTime = getSetting("relayPulseTime", RELAY_PULSE_TIME).toFloat();
  228. if (relayPulseMode == RELAY_PULSE_NONE) relayPulseTime = 0;
  229. for (unsigned int i=0; i<_relays.size(); i++) {
  230. if (!hasSetting("relayBoot", i)) setSetting("relayBoot", i, relayMode);
  231. if (!hasSetting("relayPulse", i)) setSetting("relayPulse", i, relayPulseMode);
  232. if (!hasSetting("relayTime", i)) setSetting("relayTime", i, relayPulseTime);
  233. }
  234. delSetting("relayMode");
  235. delSetting("relayPulseMode");
  236. delSetting("relayPulseTime");
  237. }
  238. void _relayBoot() {
  239. _relayRecursive = true;
  240. unsigned char bit = 1;
  241. bool trigger_save = false;
  242. // Get last statuses from EEPROM
  243. unsigned char mask = EEPROM.read(EEPROM_RELAY_STATUS);
  244. DEBUG_MSG_P(PSTR("[RELAY] Retrieving mask: %d\n"), mask);
  245. // Walk the relays
  246. for (unsigned int i=0; i<_relays.size(); i++) {
  247. _relays[i].current_status = false;
  248. _relays[i].target_status = false;
  249. unsigned char boot_mode = getSetting("relayBoot", i, RELAY_BOOT_MODE).toInt();
  250. switch (boot_mode) {
  251. case RELAY_BOOT_OFF:
  252. relayStatus(i, false);
  253. break;
  254. case RELAY_BOOT_ON:
  255. relayStatus(i, true);
  256. break;
  257. case RELAY_BOOT_SAME:
  258. relayStatus(i, (mask & bit) == bit);
  259. break;
  260. case RELAY_BOOT_TOOGLE:
  261. relayStatus(i, (mask & bit) != bit);
  262. mask ^= bit;
  263. trigger_save = true;
  264. break;
  265. }
  266. bit <<= 1;
  267. }
  268. // Save if there is any relay in the RELAY_BOOT_TOOGLE mode
  269. if (trigger_save) {
  270. EEPROM.write(EEPROM_RELAY_STATUS, mask);
  271. EEPROM.commit();
  272. }
  273. _relayRecursive = false;
  274. }
  275. //------------------------------------------------------------------------------
  276. // WEBSOCKETS
  277. //------------------------------------------------------------------------------
  278. #if WEB_SUPPORT
  279. void _relayWebSocketUpdate(JsonObject& root) {
  280. JsonArray& relay = root.createNestedArray("relayStatus");
  281. for (unsigned char i=0; i<relayCount(); i++) {
  282. relay.add(_relays[i].target_status);
  283. }
  284. }
  285. void _relayWebSocketOnStart(JsonObject& root) {
  286. if (relayCount() == 0) return;
  287. // Statuses
  288. _relayWebSocketUpdate(root);
  289. // Configuration
  290. JsonArray& config = root.createNestedArray("relayConfig");
  291. for (unsigned char i=0; i<relayCount(); i++) {
  292. JsonObject& line = config.createNestedObject();
  293. line["gpio"] = _relays[i].pin;
  294. line["type"] = _relays[i].type;
  295. line["reset"] = _relays[i].reset_pin;
  296. line["boot"] = getSetting("relayBoot", i, RELAY_BOOT_MODE).toInt();
  297. line["pulse"] = _relays[i].pulse;
  298. line["pulse_ms"] = _relays[i].pulse_ms / 1000.0;
  299. #if MQTT_SUPPORT
  300. line["group"] = getSetting("mqttGroup", i, "");
  301. line["group_inv"] = getSetting("mqttGroupInv", i, 0).toInt() == 1;
  302. #endif
  303. }
  304. if (relayCount() > 1) {
  305. root["multirelayVisible"] = 1;
  306. root["relaySync"] = getSetting("relaySync", RELAY_SYNC);
  307. }
  308. root["relayVisible"] = 1;
  309. }
  310. void _relayWebSocketOnAction(const char * action, JsonObject& data) {
  311. if (strcmp(action, "relay") != 0) return;
  312. if (data.containsKey("status")) {
  313. unsigned char value = relayParsePayload(data["status"]);
  314. if (value == 3) {
  315. wsSend(_relayWebSocketUpdate);
  316. } else if (value < 3) {
  317. unsigned int relayID = 0;
  318. if (data.containsKey("id")) {
  319. String value = data["id"];
  320. relayID = value.toInt();
  321. }
  322. // Action to perform
  323. if (value == 0) {
  324. relayStatus(relayID, false);
  325. } else if (value == 1) {
  326. relayStatus(relayID, true);
  327. } else if (value == 2) {
  328. relayToggle(relayID);
  329. }
  330. }
  331. }
  332. }
  333. void _relayConfigure() {
  334. for (unsigned int i=0; i<_relays.size(); i++) {
  335. pinMode(_relays[i].pin, OUTPUT);
  336. if (_relays[i].type == RELAY_TYPE_LATCHED) pinMode(_relays[i].reset_pin, OUTPUT);
  337. _relays[i].pulse = getSetting("relayPulse", i, RELAY_PULSE_MODE).toInt();
  338. _relays[i].pulse_ms = 1000 * getSetting("relayTime", i, RELAY_PULSE_MODE).toFloat();
  339. }
  340. }
  341. void relaySetupWS() {
  342. wsOnSendRegister(_relayWebSocketOnStart);
  343. wsOnActionRegister(_relayWebSocketOnAction);
  344. wsOnAfterParseRegister(_relayConfigure);
  345. }
  346. #endif // WEB_SUPPORT
  347. //------------------------------------------------------------------------------
  348. // REST API
  349. //------------------------------------------------------------------------------
  350. #if WEB_SUPPORT
  351. void relaySetupAPI() {
  352. // API entry points (protected with apikey)
  353. for (unsigned int relayID=0; relayID<relayCount(); relayID++) {
  354. char url[15];
  355. snprintf_P(url, sizeof(url), PSTR("%s/%d"), MQTT_TOPIC_RELAY, relayID);
  356. char key[10];
  357. snprintf_P(key, sizeof(key), PSTR("%s%d"), MQTT_TOPIC_RELAY, relayID);
  358. apiRegister(url, key,
  359. [relayID](char * buffer, size_t len) {
  360. snprintf_P(buffer, len, PSTR("%d"), relayStatus(relayID) ? 1 : 0);
  361. },
  362. [relayID](const char * payload) {
  363. unsigned char value = relayParsePayload(payload);
  364. if (value == 0xFF) {
  365. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  366. return;
  367. }
  368. if (value == 0) {
  369. relayStatus(relayID, false);
  370. } else if (value == 1) {
  371. relayStatus(relayID, true);
  372. } else if (value == 2) {
  373. relayToggle(relayID);
  374. }
  375. }
  376. );
  377. }
  378. }
  379. #endif // WEB_SUPPORT
  380. //------------------------------------------------------------------------------
  381. // MQTT
  382. //------------------------------------------------------------------------------
  383. #if MQTT_SUPPORT
  384. void relayMQTT(unsigned char id) {
  385. if (id >= _relays.size()) return;
  386. // Send state topic
  387. if (_relays[id].report) {
  388. _relays[id].report = false;
  389. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? "1" : "0");
  390. }
  391. // Check group topic
  392. if (_relays[id].group_report) {
  393. _relays[id].group_report = false;
  394. String t = getSetting("mqttGroup", id, "");
  395. if (t.length() > 0) {
  396. bool status = relayStatus(id);
  397. if (getSetting("mqttGroupInv", id, 0).toInt() == 1) status = !status;
  398. mqttSendRaw(t.c_str(), status ? "1" : "0");
  399. }
  400. }
  401. }
  402. void relayMQTT() {
  403. for (unsigned int id=0; id < _relays.size(); id++) {
  404. mqttSend(MQTT_TOPIC_RELAY, id, _relays[id].current_status ? "1" : "0");
  405. }
  406. }
  407. void relayMQTTCallback(unsigned int type, const char * topic, const char * payload) {
  408. if (type == MQTT_CONNECT_EVENT) {
  409. // Send status on connect
  410. #if not HEARTBEAT_REPORT_RELAY
  411. relayMQTT();
  412. #endif
  413. // Subscribe to own /set topic
  414. char buffer[strlen(MQTT_TOPIC_RELAY) + 3];
  415. snprintf_P(buffer, sizeof(buffer), PSTR("%s/+"), MQTT_TOPIC_RELAY);
  416. mqttSubscribe(buffer);
  417. // Subscribe to group topics
  418. for (unsigned int i=0; i < _relays.size(); i++) {
  419. String t = getSetting("mqttGroup", i, "");
  420. if (t.length() > 0) mqttSubscribeRaw(t.c_str());
  421. }
  422. }
  423. if (type == MQTT_MESSAGE_EVENT) {
  424. // Get relay
  425. unsigned int relayID;
  426. bool is_group_topic = false;
  427. // Get value
  428. unsigned char value = relayParsePayload(payload);
  429. if (value == 0xFF) {
  430. DEBUG_MSG_P(PSTR("[RELAY] Wrong payload (%s)\n"), payload);
  431. return;
  432. }
  433. // Check group topics
  434. for (unsigned int i=0; i < _relays.size(); i++) {
  435. String t = getSetting("mqttGroup", i, "");
  436. if (t.equals(topic)) {
  437. if (getSetting("mqttGroupInv", i, 0).toInt() == 1) {
  438. if (value < 2) value = 1 - value;
  439. }
  440. DEBUG_MSG_P(PSTR("[RELAY] Matched group topic for relayID %d\n"), i);
  441. is_group_topic = true;
  442. relayID = i;
  443. break;
  444. }
  445. }
  446. // Not group topic, look for own topic
  447. if (!is_group_topic) {
  448. // Match topic
  449. String t = mqttSubtopic((char *) topic);
  450. if (!t.startsWith(MQTT_TOPIC_RELAY)) return;
  451. // Get relay ID
  452. relayID = t.substring(strlen(MQTT_TOPIC_RELAY)+1).toInt();
  453. if (relayID >= relayCount()) {
  454. DEBUG_MSG_P(PSTR("[RELAY] Wrong relayID (%d)\n"), relayID);
  455. return;
  456. }
  457. }
  458. // Action to perform
  459. if (value == 0) {
  460. relayStatus(relayID, false, mqttForward(), !is_group_topic);
  461. } else if (value == 1) {
  462. relayStatus(relayID, true, mqttForward(), !is_group_topic);
  463. } else if (value == 2) {
  464. relayToggle(relayID, true, true);
  465. }
  466. }
  467. }
  468. void relaySetupMQTT() {
  469. mqttRegister(relayMQTTCallback);
  470. }
  471. #endif
  472. //------------------------------------------------------------------------------
  473. // InfluxDB
  474. //------------------------------------------------------------------------------
  475. #if INFLUXDB_SUPPORT
  476. void relayInfluxDB(unsigned char id) {
  477. if (id >= _relays.size()) return;
  478. char buffer[20];
  479. snprintf_P(buffer, sizeof(buffer), PSTR("%s,id=%d"), MQTT_TOPIC_RELAY, id);
  480. idbSend(buffer, relayStatus(id) ? "1" : "0");
  481. }
  482. #endif
  483. //------------------------------------------------------------------------------
  484. // Setup
  485. //------------------------------------------------------------------------------
  486. void relaySetup() {
  487. // Dummy relays for AI Light, Magic Home LED Controller, H801,
  488. // Sonoff Dual and Sonoff RF Bridge
  489. #ifdef DUMMY_RELAY_COUNT
  490. for (unsigned char i=0; i < DUMMY_RELAY_COUNT; i++) {
  491. _relays.push_back((relay_t) {0, RELAY_TYPE_NORMAL});
  492. }
  493. #else
  494. #ifdef RELAY1_PIN
  495. _relays.push_back((relay_t) { RELAY1_PIN, RELAY1_TYPE, RELAY1_RESET_PIN, RELAY1_DELAY_ON, RELAY1_DELAY_OFF });
  496. #endif
  497. #ifdef RELAY2_PIN
  498. _relays.push_back((relay_t) { RELAY2_PIN, RELAY2_TYPE, RELAY2_RESET_PIN, RELAY2_DELAY_ON, RELAY2_DELAY_OFF });
  499. #endif
  500. #ifdef RELAY3_PIN
  501. _relays.push_back((relay_t) { RELAY3_PIN, RELAY3_TYPE, RELAY3_RESET_PIN, RELAY3_DELAY_ON, RELAY3_DELAY_OFF });
  502. #endif
  503. #ifdef RELAY4_PIN
  504. _relays.push_back((relay_t) { RELAY4_PIN, RELAY4_TYPE, RELAY4_RESET_PIN, RELAY4_DELAY_ON, RELAY4_DELAY_OFF });
  505. #endif
  506. #endif
  507. _relayBackwards();
  508. _relayConfigure();
  509. _relayBoot();
  510. relayLoop();
  511. #if WEB_SUPPORT
  512. relaySetupAPI();
  513. relaySetupWS();
  514. #endif
  515. #if MQTT_SUPPORT
  516. relaySetupMQTT();
  517. #endif
  518. DEBUG_MSG_P(PSTR("[RELAY] Number of relays: %d\n"), _relays.size());
  519. }
  520. void relayLoop(void) {
  521. unsigned char id;
  522. for (id = 0; id < _relays.size(); id++) {
  523. unsigned int current_time = millis();
  524. bool status = _relays[id].target_status;
  525. if ((_relays[id].current_status != status)
  526. && (current_time >= _relays[id].change_time)) {
  527. DEBUG_MSG_P(PSTR("[RELAY] #%d set to %s\n"), id, status ? "ON" : "OFF");
  528. // Call the provider to perform the action
  529. _relayProviderStatus(id, status);
  530. // Send MQTT
  531. #if MQTT_SUPPORT
  532. relayMQTT(id);
  533. #endif
  534. if (!_relayRecursive) {
  535. relayPulse(id);
  536. _relaySaveTicker.once_ms(RELAY_SAVE_DELAY, relaySave);
  537. #if WEB_SUPPORT
  538. wsSend(_relayWebSocketUpdate);
  539. #endif
  540. }
  541. #if DOMOTICZ_SUPPORT
  542. domoticzSendRelay(id);
  543. #endif
  544. #if INFLUXDB_SUPPORT
  545. relayInfluxDB(id);
  546. #endif
  547. _relays[id].report = false;
  548. _relays[id].group_report = false;
  549. }
  550. }
  551. }