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.

494 lines
14 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
6 years ago
  1. /*
  2. BUTTON MODULE
  3. Copyright (C) 2016-2019 by Xose Pérez <xose dot perez at gmail dot com>
  4. */
  5. #if BUTTON_SUPPORT
  6. #include <bitset>
  7. #include <memory>
  8. #include <vector>
  9. #include "system.h"
  10. #include "relay.h"
  11. #include "light.h"
  12. #include "button.h"
  13. #include "button_config.h"
  14. #include "libs/DebounceEvent.h"
  15. // -----------------------------------------------------------------------------
  16. button_event_delays_t::button_event_delays_t() :
  17. debounce(BUTTON_DEBOUNCE_DELAY),
  18. dblclick(BUTTON_DBLCLICK_DELAY),
  19. lngclick(BUTTON_LNGCLICK_DELAY),
  20. lnglngclick(BUTTON_LNGLNGCLICK_DELAY)
  21. {}
  22. button_event_delays_t::button_event_delays_t(unsigned long debounce, unsigned long dblclick, unsigned long lngclick, unsigned long lnglngclick) :
  23. debounce(debounce),
  24. dblclick(dblclick),
  25. lngclick(lngclick),
  26. lnglngclick(lnglngclick)
  27. {}
  28. button_t::button_t(std::shared_ptr<DebounceEvent::PinBase> pin, int mode, unsigned long actions, unsigned char relayID, button_event_delays_t delays) :
  29. event_handler(new DebounceEvent::DebounceEvent(pin, mode, delays.debounce, delays.dblclick)),
  30. event_delays(delays),
  31. actions(actions),
  32. relayID(relayID)
  33. {}
  34. bool button_t::state() {
  35. return event_handler->pressed();
  36. }
  37. std::vector<button_t> _buttons;
  38. // -----------------------------------------------------------------------------
  39. constexpr const uint8_t _buttonMapReleased(uint8_t count, uint8_t length, unsigned long lngclick_delay, unsigned long lnglngclick_delay) {
  40. return (
  41. (1 == count) ? (
  42. (length > lnglngclick_delay) ? BUTTON_EVENT_LNGLNGCLICK :
  43. (length > lngclick_delay) ? BUTTON_EVENT_LNGCLICK : BUTTON_EVENT_CLICK
  44. ) :
  45. (2 == count) ? BUTTON_EVENT_DBLCLICK :
  46. (3 == count) ? BUTTON_EVENT_TRIPLECLICK :
  47. BUTTON_EVENT_NONE
  48. );
  49. }
  50. const uint8_t _buttonMapEvent(button_t& button, DebounceEvent::Types::event_t event) {
  51. using namespace DebounceEvent;
  52. switch (event) {
  53. case Types::EventPressed:
  54. return BUTTON_EVENT_PRESSED;
  55. case Types::EventChanged:
  56. return BUTTON_EVENT_CLICK;
  57. case Types::EventReleased: {
  58. return _buttonMapReleased(
  59. button.event_handler->getEventCount(),
  60. button.event_handler->getEventLength(),
  61. button.event_delays.lngclick,
  62. button.event_delays.lnglngclick
  63. );
  64. }
  65. case Types::EventNone:
  66. default:
  67. return BUTTON_EVENT_NONE;
  68. }
  69. }
  70. unsigned char buttonCount() {
  71. return _buttons.size();
  72. }
  73. #if MQTT_SUPPORT
  74. std::bitset<BUTTONS_MAX> _buttons_mqtt_send_all(
  75. (1 == BUTTON_MQTT_SEND_ALL_EVENTS) ? 0xFFFFFFFFUL : 0UL
  76. );
  77. std::bitset<BUTTONS_MAX> _buttons_mqtt_retain(
  78. (1 == BUTTON_MQTT_RETAIN) ? 0xFFFFFFFFUL : 0UL
  79. );
  80. void buttonMQTT(unsigned char id, uint8_t event) {
  81. char payload[4] = {0};
  82. itoa(event, payload, 10);
  83. // mqttSend(topic, id, payload, force, retail)
  84. mqttSend(MQTT_TOPIC_BUTTON, id, payload, false, _buttons_mqtt_retain[id]);
  85. }
  86. #endif
  87. #if WEB_SUPPORT
  88. void _buttonWebSocketOnVisible(JsonObject& root) {
  89. if (buttonCount() > 0) {
  90. root["btnVisible"] = 1;
  91. }
  92. }
  93. // XXX: unused! pending webui changes
  94. void _buttonWebSocketOnConnected(JsonObject& root) {
  95. #if 0
  96. if (buttonCount() < 1) return;
  97. JsonObject& module = root.createNestedObject("btn");
  98. // TODO: hardware can sometimes use a different event source
  99. // e.g. Sonoff Dual does not need `Pin`, `Mode` or any of `Del`
  100. // TODO: schema names are uppercase to easily match settings?
  101. // TODO: schema name->type map to generate WebUI elements?
  102. JsonArray& schema = module.createNestedArray("_schema");
  103. schema.add("Pin"); // GPIO id?
  104. schema.add("Mode");
  105. schema.add("Relay");
  106. schema.add("DebDel");
  107. schema.add("DblDel");
  108. schema.add("LngDel");
  109. schema.add("LngLngDel");
  110. #if MQTT_SUPPORT
  111. schema.add("MqttSnd");
  112. schema.add("MqttRetain");
  113. #endif
  114. JsonArray& buttons = module.createNestedArray("list");
  115. for (unsigned char i=0; i<buttonCount(); i++) {
  116. JsonArray& button = buttons.createNestedArray();
  117. button.add(_buttons[i].event_handler.pin.pin);
  118. button.add(_buttons[i].event_handler.pin.mode);
  119. button.add(_buttons[i].relayID);
  120. button.add(_buttons[i].event_delays.debounce);
  121. button.add(_buttons[i].event_delays.dblclick);
  122. button.add(_buttons[i].event_delays.lngclick);
  123. button.add(_buttons[i].event_delays.lnglngclick);
  124. // TODO: send bitmask as number?
  125. #if MQTT_SUPPORT
  126. button.add(_buttons_mqtt_send_all[i] ? 1 : 0);
  127. button.add(_buttons_mqtt_retain[i] ? 1 : 0);
  128. #endif
  129. }
  130. #endif
  131. }
  132. bool _buttonWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  133. return (strncmp(key, "btn", 3) == 0);
  134. }
  135. #endif
  136. bool buttonState(unsigned char id) {
  137. if (id >= _buttons.size()) return false;
  138. return _buttons[id].state();
  139. }
  140. unsigned char buttonAction(unsigned char id, unsigned char event) {
  141. if (id >= _buttons.size()) return BUTTON_MODE_NONE;
  142. return _buttonDecodeEventAction(_buttons[id].actions, event);
  143. }
  144. void buttonEvent(unsigned char id, unsigned char event) {
  145. DEBUG_MSG_P(PSTR("[BUTTON] Button #%u event %u\n"), id, event);
  146. if (event == 0) return;
  147. auto& button = _buttons[id];
  148. unsigned char action = _buttonDecodeEventAction(button.actions, event);
  149. #if MQTT_SUPPORT
  150. if (action != BUTTON_MODE_NONE || _buttons_mqtt_send_all[id]) {
  151. buttonMQTT(id, event);
  152. }
  153. #endif
  154. if (BUTTON_MODE_TOGGLE == action) {
  155. relayToggle(button.relayID);
  156. }
  157. if (BUTTON_MODE_ON == action) {
  158. relayStatus(button.relayID, true);
  159. }
  160. if (BUTTON_MODE_OFF == action) {
  161. relayStatus(button.relayID, false);
  162. }
  163. if (BUTTON_MODE_AP == action) {
  164. if (wifiState() & WIFI_STATE_AP) {
  165. wifiStartSTA();
  166. } else {
  167. wifiStartAP();
  168. }
  169. }
  170. if (BUTTON_MODE_RESET == action) {
  171. deferredReset(100, CUSTOM_RESET_HARDWARE);
  172. }
  173. if (BUTTON_MODE_FACTORY == action) {
  174. DEBUG_MSG_P(PSTR("\n\nFACTORY RESET\n\n"));
  175. resetSettings();
  176. deferredReset(100, CUSTOM_RESET_FACTORY);
  177. }
  178. #if defined(JUSTWIFI_ENABLE_WPS)
  179. if (BUTTON_MODE_WPS == action) {
  180. wifiStartWPS();
  181. }
  182. #endif // defined(JUSTWIFI_ENABLE_WPS)
  183. #if defined(JUSTWIFI_ENABLE_SMARTCONFIG)
  184. if (BUTTON_MODE_SMART_CONFIG == action) {
  185. wifiStartSmartConfig();
  186. }
  187. #endif // defined(JUSTWIFI_ENABLE_SMARTCONFIG)
  188. #if LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  189. if (BUTTON_MODE_DIM_UP == action) {
  190. lightBrightnessStep(1);
  191. lightUpdate(true, true);
  192. }
  193. if (BUTTON_MODE_DIM_DOWN == action) {
  194. lightBrightnessStep(-1);
  195. lightUpdate(true, true);
  196. }
  197. #endif // LIGHT_PROVIDER != LIGHT_PROVIDER_NONE
  198. }
  199. struct DummyPin : virtual public DebounceEvent::PinBase {
  200. DummyPin(unsigned char pin) : DebounceEvent::PinBase(pin) {}
  201. void digitalWrite(int8_t val) {}
  202. void pinMode(int8_t mode) {}
  203. int digitalRead() { return 0; }
  204. };
  205. void buttonSetup() {
  206. // Backwards compatibility
  207. moveSetting("btnDelay", "btnDblDel");
  208. // Special hardware cases
  209. #if (BUTTON_EVENTS_SOURCE == BUTTON_EVENTS_SOURCE_ITEAD_SONOFF_DUAL) || \
  210. (BUTTON_EVENTS_SOURCE == BUTTON_EVENTS_SOURCE_FOXEL_LIGHTFOX_DUAL)
  211. size_t buttons = 0;
  212. #if BUTTON1_RELAY != RELAY_NONE
  213. ++buttons;
  214. #endif
  215. #if BUTTON2_RELAY != RELAY_NONE
  216. ++buttons;
  217. #endif
  218. #if BUTTON3_RELAY != RELAY_NONE
  219. ++buttons;
  220. #endif
  221. #if BUTTON4_RELAY != RELAY_NONE
  222. ++buttons;
  223. #endif
  224. _buttons.reserve(buttons);
  225. // Ignore default button modes
  226. const auto actions = _buttonConstructActions(
  227. BUTTON_MODE_NONE, BUTTON_MODE_TOGGLE, BUTTON_MODE_NONE,
  228. BUTTON_MODE_NONE, BUTTON_MODE_NONE, BUTTON_MODE_NONE
  229. );
  230. const auto delays = button_event_delays_t();
  231. for (unsigned char id = 0; id < buttons; ++id) {
  232. _buttons.emplace_back(
  233. nullptr, BUTTON_PUSHBUTTON,
  234. actions, getSetting({"btnRelay", id}, _buttonRelay(id)),
  235. delays
  236. );
  237. }
  238. // Generic GPIO input handlers
  239. #elif BUTTON_EVENTS_SOURCE == BUTTON_EVENTS_SOURCE_GENERIC
  240. size_t buttons = 0;
  241. // TODO: no real point of doing this when running with dynamic settings
  242. // if there is limit like RELAYS_MAX - use that
  243. // if not, try to allocate some reasonable amount
  244. #if BUTTON1_PIN != GPIO_NONE
  245. ++buttons;
  246. #endif
  247. #if BUTTON2_PIN != GPIO_NONE
  248. ++buttons;
  249. #endif
  250. #if BUTTON3_PIN != GPIO_NONE
  251. ++buttons;
  252. #endif
  253. #if BUTTON4_PIN != GPIO_NONE
  254. ++buttons;
  255. #endif
  256. #if BUTTON5_PIN != GPIO_NONE
  257. ++buttons;
  258. #endif
  259. #if BUTTON6_PIN != GPIO_NONE
  260. ++buttons;
  261. #endif
  262. #if BUTTON7_PIN != GPIO_NONE
  263. ++buttons;
  264. #endif
  265. #if BUTTON8_PIN != GPIO_NONE
  266. ++buttons;
  267. #endif
  268. _buttons.reserve(buttons);
  269. for (unsigned char index = 0; index < buttons; ++index) {
  270. const auto pin = getSetting({"btnGPIO", index}, _buttonPin(index));
  271. if (!gpioValid(pin)) {
  272. break;
  273. }
  274. button_event_delays_t delays {
  275. getSetting({"btnDebDel", index}, _buttonDebounceDelay(index)),
  276. getSetting({"btnDblCDel", index}, _buttonDoubleClickDelay(index)),
  277. getSetting({"btnLngCDel", index}, _buttonLongClickDelay(index)),
  278. getSetting({"btnLngLngCDel", index}, _buttonLongLongClickDelay(index))
  279. };
  280. // TODO: allow to change DebounceEvent::DigitalPin to something else based on config
  281. _buttons.emplace_back(
  282. std::make_shared<DebounceEvent::DigitalPin>(pin),
  283. getSetting({"btnMode", index}, _buttonMode(index)),
  284. getSetting({"btnActions", index}, _buttonConstructActions(index)),
  285. getSetting({"btnRelay", index}, _buttonRelay(index)),
  286. delays
  287. );
  288. }
  289. #endif
  290. DEBUG_MSG_P(PSTR("[BUTTON] Number of buttons: %u\n"), _buttons.size());
  291. #if MQTT_SUPPORT
  292. for (unsigned char index = 0; index < _buttons.size(); ++index) {
  293. _buttons_mqtt_send_all[index] = getSetting({"btnMqttSendAll", index}, _buttonMqttSendAllEvents(index));
  294. _buttons_mqtt_retain[index] = getSetting({"btnMqttRetain", index}, _buttonMqttRetain(index));
  295. }
  296. #endif
  297. // Websocket Callbacks
  298. #if WEB_SUPPORT
  299. wsRegister()
  300. .onConnected(_buttonWebSocketOnVisible)
  301. .onVisible(_buttonWebSocketOnVisible)
  302. .onKeyCheck(_buttonWebSocketOnKeyCheck);
  303. #endif
  304. // Register system callbacks
  305. espurnaRegisterLoop(buttonLoop);
  306. }
  307. // Sonoff Dual does not do real GPIO readings and we
  308. // depend on the external MCU to send us relay / button events
  309. // TODO: move this to a separate 'hardware' setup file?
  310. #if BUTTON_EVENTS_SOURCE == BUTTON_EVENTS_SOURCE_ITEAD_SONOFF_DUAL
  311. void _buttonLoopSonoffDual() {
  312. if (Serial.available() < 4) {
  313. return;
  314. }
  315. unsigned char bytes[4] = {0};
  316. Serial.readBytes(bytes, 4);
  317. if ((bytes[0] != 0xA0) || (bytes[1] != 0x04) && (bytes[3] != 0xA1)) {
  318. return;
  319. }
  320. const unsigned char value = bytes[2];
  321. // RELAYs and BUTTONs are synchonized in the SIL F330
  322. // The on-board BUTTON2 should toggle RELAY0 value
  323. // Since we are not passing back RELAY2 value
  324. // (in the relayStatus method) it will only be present
  325. // here if it has actually been pressed
  326. if ((value & 4) == 4) {
  327. buttonEvent(2, BUTTON_EVENT_CLICK);
  328. return;
  329. }
  330. // Otherwise check if any of the other two BUTTONs
  331. // (in the header) has been pressed, but we should
  332. // ensure that we only toggle one of them to avoid
  333. // the synchronization going mad
  334. // This loop is generic for any PSB-04 module
  335. for (unsigned int i=0; i<relayCount(); i++) {
  336. bool status = (value & (1 << i)) > 0;
  337. // Check if the status for that relay has changed
  338. if (relayStatus(i) != status) {
  339. buttonEvent(i, BUTTON_EVENT_CLICK);
  340. break;
  341. }
  342. }
  343. }
  344. #endif // BUTTON_EVENTS_SOURCE_ITEAD_SONOFF_DUAL == 1
  345. // Lightfox uses the same protocol as Dual, but has slightly different actions
  346. // TODO: same as above, move from here someplace else
  347. #if BUTTON_EVENTS_SOURCE == BUTTON_EVENTS_SOURCE_FOXEL_LIGHTFOX_DUAL
  348. void _buttonLoopFoxelLightfox() {
  349. if (Serial.available() < 4) {
  350. return;
  351. }
  352. unsigned char bytes[4] = {0};
  353. Serial.readBytes(bytes, 4);
  354. if ((bytes[0] != 0xA0) || (bytes[1] != 0x04) && (bytes[3] != 0xA1)) {
  355. return;
  356. }
  357. const unsigned char value = bytes[2];
  358. DEBUG_MSG_P(PSTR("[BUTTON] [LIGHTFOX] Received buttons mask: %u\n"), value);
  359. for (unsigned int i=0; i<_buttons.size(); i++) {
  360. bool clicked = (value & (1 << i)) > 0;
  361. if (clicked) {
  362. buttonEvent(i, BUTTON_EVENT_CLICK);
  363. }
  364. }
  365. }
  366. #endif // BUTTON_EVENTS_SOURCE_FOXEL_LIGHTFOX_DUAL == 1
  367. void _buttonLoopGeneric() {
  368. for (size_t id = 0; id < _buttons.size(); ++id) {
  369. auto& button = _buttons[id];
  370. auto event = button.event_handler->loop();
  371. if (event != DebounceEvent::Types::EventNone) {
  372. buttonEvent(id, _buttonMapEvent(button, event));
  373. }
  374. }
  375. }
  376. void buttonLoop() {
  377. #if BUTTON_EVENTS_SOURCE == BUTTON_EVENTS_SOURCE_GENERIC
  378. _buttonLoopGeneric();
  379. #elif BUTTON_EVENTS_SOURCE == BUTTON_EVENTS_SOURCE_ITEAD_SONOFF_DUAL
  380. _buttonLoopSonoffDual();
  381. #elif BUTTON_EVENTS_SOURCE == BUTTON_EVENTS_SOURCE_FOXEL_LIGHTFOX_DUAL
  382. _buttonLoopFoxelLightfox();
  383. #else
  384. #warning "Unknown value for BUTTON_EVENTS_SOURCE"
  385. #endif
  386. }
  387. #endif // BUTTON_SUPPORT