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.

505 lines
20 KiB

  1. /*
  2. KingArt Cover/Shutter/Blind/Curtain support for ESPURNA
  3. Based on xdrv_19_ps16dz.dimmer.ino, PS_16_DZ dimmer support for Tasmota
  4. Copyright (C) 2019 by Albert Weterings
  5. Based on curtain_kingart.ino Albert Weterings
  6. Copyright (C) 2020 - Eric Chauvet
  7. */
  8. #include "curtain_kingart.h"
  9. #if KINGART_CURTAIN_SUPPORT
  10. #include "ntp.h"
  11. #include "mqtt.h"
  12. #include "settings.h"
  13. #include "ws.h"
  14. #ifndef KINGART_CURTAIN_PORT
  15. #define KINGART_CURTAIN_PORT Serial // Hardware serial port by default
  16. #endif
  17. #ifndef KINGART_CURTAIN_BUFFER_SIZE
  18. #define KINGART_CURTAIN_BUFFER_SIZE 100 // Local UART buffer size
  19. #endif
  20. #define KINGART_CURTAIN_TERMINATION '\e' // Termination character after each message
  21. #define KINGART_CURTAIN_BAUDRATE 19200 // Serial speed is fixed for the device
  22. // --> Let see after if we define a curtain generic switch, use these for now
  23. #define CURTAIN_BUTTON_UNKNOWN -1
  24. #define CURTAIN_BUTTON_PAUSE 0
  25. #define CURTAIN_BUTTON_OPEN 1
  26. #define CURTAIN_BUTTON_CLOSE 2
  27. #define CURTAIN_INIT_CLOSE 1
  28. #define CURTAIN_INIT_OPEN 2
  29. #define CURTAIN_INIT_POSITION 3
  30. #define CURTAIN_POSITION_UNKNOWN -1
  31. // <--
  32. #define KINGART_DEBUG_MSG_P(...) do { if (_curtain_debug_flag) { DEBUG_MSG_P(__VA_ARGS__); } } while(0)
  33. char _KACurtainBuffer[KINGART_CURTAIN_BUFFER_SIZE];
  34. bool _KACurtainNewData = false;
  35. // Status vars - for curtain move detection :
  36. int _curtain_position = CURTAIN_POSITION_UNKNOWN;
  37. int _curtain_last_position = CURTAIN_POSITION_UNKNOWN;
  38. int _curtain_button = CURTAIN_BUTTON_UNKNOWN;
  39. int _curtain_last_button = CURTAIN_BUTTON_UNKNOWN;
  40. unsigned long last_uptime = 0;
  41. int _curtain_position_set = CURTAIN_POSITION_UNKNOWN; //Last position asked to be set (not the real position, the real query - updated when the curtain stops moving)
  42. bool _curtain_waiting_ack = false; //Avoid too fast MQTT commands
  43. bool _curtain_ignore_next_position = false; //Avoid a bug (see (*1)
  44. bool _curtain_initial_position_set = false; //Flag to detect if we manage to set the curtain back to its position before power off or reboot
  45. // Calculated behaviour depending on KA switch, MQTT and UI actions
  46. bool _curtain_moving = true;
  47. //Enable more traces, true as a default and stopped when curtain is setup.
  48. bool _curtain_debug_flag = true;
  49. #if WEB_SUPPORT
  50. bool _curtain_report_ws = true; //This will init curtain control and flag the web ui update
  51. #endif // WEB_SUPPORT
  52. //------------------------------------------------------------------------------
  53. void curtainUpdateUI() {
  54. #if WEB_SUPPORT
  55. _curtain_report_ws = true;
  56. #endif // WEB_SUPPORT
  57. }
  58. //------------------------------------------------------------------------------
  59. int setButtonFromSwitchText(String & text) {
  60. if(text == "on")
  61. return CURTAIN_BUTTON_OPEN;
  62. else if(text == "off")
  63. return CURTAIN_BUTTON_CLOSE;
  64. else if(text == "pause")
  65. return CURTAIN_BUTTON_PAUSE;
  66. else
  67. return CURTAIN_BUTTON_UNKNOWN;
  68. }
  69. // -----------------------------------------------------------------------------
  70. // Private
  71. // -----------------------------------------------------------------------------
  72. //------------------------------------------------------------------------------
  73. //This check that wa got latest and new stats from the AT+RESULT message
  74. bool _KAValidStatus() {
  75. return _curtain_button != CURTAIN_BUTTON_UNKNOWN &&
  76. _curtain_last_button != CURTAIN_BUTTON_UNKNOWN &&
  77. _curtain_position != CURTAIN_POSITION_UNKNOWN &&
  78. _curtain_last_position != CURTAIN_POSITION_UNKNOWN;
  79. }
  80. //------------------------------------------------------------------------------
  81. //We consider that the curtain is moving. A timer is set to get the position of the curtain sending AT+START messages in the loop()
  82. void _KASetMoving() {
  83. last_uptime = millis() + 1000; //Let the returned curtain position to be refreshed to know of the curtain is still moving
  84. _curtain_moving = true;
  85. }
  86. //------------------------------------------------------------------------------
  87. //Send a buffer to serial
  88. void _KACurtainSend(const char * tx_buffer) {
  89. KINGART_CURTAIN_PORT.print(tx_buffer);
  90. KINGART_CURTAIN_PORT.print(KINGART_CURTAIN_TERMINATION);
  91. KINGART_CURTAIN_PORT.flush();
  92. KINGART_DEBUG_MSG_P(PSTR("[KA] UART OUT %s\n"), tx_buffer);
  93. }
  94. //------------------------------------------------------------------------------
  95. //Send a formatted message to MCU
  96. void _KACurtainSet(int button, int position = CURTAIN_POSITION_UNKNOWN) {
  97. if(_curtain_waiting_ack) {
  98. KINGART_DEBUG_MSG_P(PSTR("[KA] UART ACK not received : Request ignored!\n"));
  99. return;
  100. }
  101. char tx_buffer[80] = {0};
  102. if(button != CURTAIN_BUTTON_UNKNOWN && position != CURTAIN_POSITION_UNKNOWN) {
  103. snprintf_P(
  104. tx_buffer, sizeof(tx_buffer),
  105. PSTR("AT+UPDATE=\"sequence\":\"%d%03u\",\"switch\":\"%s\",\"setclose\":%d"),
  106. now(), millis() % 1000,
  107. (button == CURTAIN_BUTTON_PAUSE ? "pause" : (button == CURTAIN_BUTTON_OPEN ? "on" : "off")), position
  108. );
  109. } else if(button == CURTAIN_BUTTON_UNKNOWN) {
  110. snprintf_P(
  111. tx_buffer, sizeof(tx_buffer),
  112. PSTR("AT+UPDATE=\"sequence\":\"%d%03u\",\"setclose\":%d"),
  113. now(), millis() % 1000,
  114. position
  115. );
  116. } else {
  117. snprintf_P(
  118. tx_buffer, sizeof(tx_buffer),
  119. PSTR("AT+UPDATE=\"sequence\":\"%d%03u\",\"switch\":\"%s\""),
  120. now(), millis() % 1000,
  121. (button == CURTAIN_BUTTON_PAUSE ? "pause" : (button == CURTAIN_BUTTON_OPEN ? "on" : "off"))
  122. );
  123. }
  124. _KACurtainSend(tx_buffer);
  125. _curtain_waiting_ack = true;
  126. }
  127. //------------------------------------------------------------------------------
  128. //Stop moving will set the real curtain position to the GUI/MQTT
  129. void _KAStopMoving() {
  130. _curtain_moving = false;
  131. if( _curtain_position != CURTAIN_POSITION_UNKNOWN)
  132. _curtain_position_set = _curtain_position;
  133. else if( _curtain_last_position != CURTAIN_POSITION_UNKNOWN)
  134. _curtain_position_set = _curtain_last_position;
  135. if (!_curtain_initial_position_set) { //The curtain stopped moving for the first time, set the position back to
  136. int init_position = getSetting("curtainBoot", 0);
  137. KINGART_DEBUG_MSG_P(PSTR("[KA] curtainBoot : %d, curtainBootPos : %d\n"), init_position, getSetting("curtainBootPos", 100));
  138. if (init_position == CURTAIN_INIT_CLOSE) {
  139. _KACurtainSet(CURTAIN_BUTTON_CLOSE);
  140. } else if (init_position == CURTAIN_INIT_OPEN) {
  141. _KACurtainSet(CURTAIN_BUTTON_OPEN);
  142. } else if (init_position == CURTAIN_INIT_POSITION) {
  143. int pos = getSetting("curtainBootPos", 100); //Set closed if we do not have initial position set.
  144. if (_curtain_position_set != pos) {
  145. _KACurtainSet(CURTAIN_BUTTON_UNKNOWN, pos);
  146. }
  147. }
  148. _curtain_initial_position_set = true;
  149. _curtain_debug_flag = false; //Disable debug - user has could ask for it
  150. } else if(_curtain_position_set != CURTAIN_POSITION_UNKNOWN && _curtain_position_set != getSetting("curtainBootPos", _curtain_position_set)) {
  151. setSetting("curtainBootPos", _curtain_last_position); //Remeber last position in case of power loss
  152. }
  153. }
  154. //------------------------------------------------------------------------------
  155. //Receive a buffer from serial
  156. bool _KACurtainReceiveUART() {
  157. static unsigned char ndx = 0;
  158. while (KINGART_CURTAIN_PORT.available() > 0 && !_KACurtainNewData) {
  159. char rc = KINGART_CURTAIN_PORT.read();
  160. if (rc != KINGART_CURTAIN_TERMINATION) {
  161. _KACurtainBuffer[ndx] = rc;
  162. if (ndx < KINGART_CURTAIN_BUFFER_SIZE - 1) ndx++;
  163. } else {
  164. _KACurtainBuffer[ndx] = '\0';
  165. _KACurtainNewData = true;
  166. ndx = 0;
  167. }
  168. }
  169. if(_KACurtainNewData) {
  170. KINGART_DEBUG_MSG_P(PSTR("[KA] Serial received : %s\n"), _KACurtainBuffer);
  171. _KACurtainNewData = false;
  172. return true;
  173. }
  174. return false;
  175. }
  176. /*
  177. Buttons on the device will move Cover/Shutter/Blind/Curtain up/open or down/close On the end of
  178. every movement the unit reports the last action and posiston over MQTT topic {hostname}/curtain
  179. RAW paylod format looks like:
  180. AT+UPDATE="switch":"on","setclose":13
  181. AT+UPDATE="switch":"off","setclose":38
  182. AT+UPDATE="switch":"pause","setclose":75
  183. The device is listening to MQTT topic {hostname}/curtain/set, to which you can send:
  184. - position value, in range from 0 to 100
  185. - "pause", to stop the movement.
  186. The device will determine the direction all by itself.
  187. # Set the Cover / Shutter / Blind / Curtain run time
  188. The factory default Open and Close run time for the switch is 50 seconds, and it must be set to
  189. an accurate run time for smooth working. Some motors do not have the resistance stop function,
  190. so when the Cover/Shutter/Blind/Curtain track open or close to the maximum length, but the motor keeps on running.
  191. This might cause damage on the motor and the switch, it also wastes a lot of energy. In order
  192. to protect the motor, this switch designed with a time setting function. After setting up the run time,
  193. the switch will automaticly stop when the track reaches its limits. The run time setting is also helpful
  194. for the accurate control when manually controlling the device via the touch panel.
  195. After installing the switch and connecting the switch for the very first time:
  196. - First, it will automatically close the Cover/Shutter/Blind/Curtain to the maximum.
  197. - Press and hold the touch interface pause button for around 4 seconds until the red background
  198. led lights up and starts blinking. Then, press the open touch button so start the opening process.
  199. - When cover is fully open, press the Open or Close button to stop the timer and save the calculated run time.
  200. To configure the device:
  201. - Press up/down for 5 seconds to bring device into AP mode. After pressing up/down again, device will restart in normal mode.
  202. */
  203. //------------------------------------------------------------------------------
  204. void _KACurtainResult() {
  205. // Need to send confirmation to the N76E003AT20 that message is received
  206. // ECH : TODO Check this is the case every time
  207. _KACurtainSend("AT+SEND=ok");
  208. //Init receive stats : The buffer which may contain : "setclose":INT(0-100) or "switch":["on","off","pause"]
  209. const String buffer(_KACurtainBuffer);
  210. _curtain_button = CURTAIN_BUTTON_UNKNOWN;
  211. _curtain_position = CURTAIN_POSITION_UNKNOWN;
  212. if(buffer.indexOf("AT+RESULT") == 0) { //AT+RESULT is an acquitment of our command (MQTT or GUI)
  213. //Set the status on what we kown
  214. if( ( _curtain_last_button == CURTAIN_BUTTON_OPEN && _curtain_last_position == 0 ) ||
  215. ( _curtain_last_button == CURTAIN_BUTTON_CLOSE && _curtain_last_position == 100 ) ||
  216. _curtain_last_button == CURTAIN_BUTTON_PAUSE) { //The curtain is max opened, closed or pause
  217. _KAStopMoving();
  218. } else { //Else it is probably moving
  219. _KASetMoving();
  220. /*
  221. (*1) ATTENTION THERE :
  222. Send immediatly a AT+START - we need to purge the first response.
  223. It will return us the right direction of the switch but the position
  224. we set instead of the real on. We take care of the switch response but
  225. we ignore the position.
  226. */
  227. _KACurtainSend("AT+START");
  228. _curtain_ignore_next_position = true;
  229. }
  230. //Time to update UI
  231. curtainUpdateUI();
  232. _curtain_waiting_ack = false;
  233. return;
  234. } else if(buffer.indexOf("AT+UPDATE") == 0) { //AT+UPDATE is a response from the switch itself or AT+SEND query
  235. // Get switch status from MCU
  236. int switch_idx = buffer.indexOf("switch");
  237. if (switch_idx > 0) {
  238. String switch_text = buffer.substring(switch_idx + strlen("switch") + 3, buffer.length());
  239. int leftovers = switch_text.indexOf('"');
  240. if (leftovers > 0) { //We must find leftover as it is text
  241. switch_text = switch_text.substring(0, leftovers);
  242. _curtain_button = setButtonFromSwitchText(switch_text);
  243. }
  244. }
  245. // Get position from MCU
  246. int setclose_idx = buffer.indexOf("setclose");
  247. if (setclose_idx > 0) {
  248. String position = buffer.substring(setclose_idx + strlen("setclose") + 2, buffer.length());
  249. int leftovers = position.indexOf(',');
  250. if (leftovers > 0) { // Not found if finishing by setclose
  251. position = position.substring(0, leftovers);
  252. }
  253. if(_curtain_ignore_next_position) { // (*1)
  254. _curtain_ignore_next_position = false;
  255. } else {
  256. _curtain_position = position.toInt();
  257. }
  258. }
  259. } else {
  260. KINGART_DEBUG_MSG_P(PSTR("[KA] ERROR : Serial unknown message : %s\n"), _KACurtainBuffer);
  261. }
  262. //Check if curtain is moving or not
  263. if( _curtain_button == CURTAIN_BUTTON_PAUSE ) { //This is returned from MCU and tells us than last status is pause or full opened or closed
  264. _KAStopMoving();
  265. } else if(_curtain_moving ) {
  266. if(_KAValidStatus()) {
  267. if(_curtain_last_button != _curtain_button) //Direction change? Reset the timer to know
  268. _KASetMoving();
  269. else if(_curtain_last_position == _curtain_position) //Same direction, same position - curtain is not moving anymore
  270. _KAStopMoving();
  271. }
  272. } else { //Not paused, not moving, and we received an AT+UPDATE -> This means that we are moving
  273. _KASetMoving();
  274. }
  275. //Update last position and transmit to MQTT (GUI is at the end)
  276. if(_curtain_position != CURTAIN_POSITION_UNKNOWN && _curtain_last_position != _curtain_position) {
  277. _curtain_last_position = _curtain_position;
  278. #if MQTT_SUPPORT
  279. const String pos = String(_curtain_last_position);
  280. mqttSend(MQTT_TOPIC_CURTAIN, pos.c_str());
  281. #endif // MQTT_SUPPORT
  282. }
  283. //Reset last button to make the algorithm work and set last button state
  284. if(!_curtain_moving) {
  285. _curtain_last_button = CURTAIN_BUTTON_UNKNOWN;
  286. } else if (_curtain_button != CURTAIN_BUTTON_UNKNOWN) {
  287. _curtain_last_button = _curtain_button;
  288. }
  289. // Handle configuration button presses
  290. if (buffer.indexOf("enterESPTOUCH") > 0) {
  291. wifiStartAP();
  292. } else if (buffer.indexOf("exitESPTOUCH") > 0) {
  293. deferredReset(100, CustomResetReason::Hardware);
  294. } else { //In any other case, update as it could be a move action
  295. curtainUpdateUI();
  296. }
  297. }
  298. // -----------------------------------------------------------------------------
  299. // MQTT Support
  300. // -----------------------------------------------------------------------------
  301. #if MQTT_SUPPORT
  302. //------------------------------------------------------------------------------
  303. void _curtainMQTTCallback(unsigned int type, const char * topic, char * payload) {
  304. if (type == MQTT_CONNECT_EVENT) {
  305. mqttSubscribe(MQTT_TOPIC_CURTAIN);
  306. } else if (type == MQTT_MESSAGE_EVENT) {
  307. // Match topic
  308. const String t = mqttMagnitude(const_cast<char*>(topic));
  309. if (t.equals(MQTT_TOPIC_CURTAIN)) {
  310. if (strcmp(payload, "pause") == 0) {
  311. _KACurtainSet(CURTAIN_BUTTON_PAUSE);
  312. } else if (strcmp(payload, "on") == 0) {
  313. _KACurtainSet(CURTAIN_BUTTON_OPEN);
  314. } else if (strcmp(payload, "off") == 0) {
  315. _KACurtainSet(CURTAIN_BUTTON_CLOSE);
  316. } else {
  317. _curtain_position_set = String(payload).toInt();
  318. _KACurtainSet(CURTAIN_BUTTON_UNKNOWN, _curtain_position_set);
  319. }
  320. }
  321. }
  322. }
  323. #endif // MQTT_SUPPORT
  324. // -----------------------------------------------------------------------------
  325. // WEB Support
  326. // -----------------------------------------------------------------------------
  327. #if WEB_SUPPORT
  328. //------------------------------------------------------------------------------
  329. void _curtainWebSocketOnConnected(JsonObject& root) {
  330. root["curtainType"] = getSetting("curtainType", "0");
  331. root["curtainBoot"] = getSetting("curtainBoot", "0");
  332. root["curtainConfig"] = 1;
  333. }
  334. //------------------------------------------------------------------------------
  335. bool _curtainWebSocketOnKeyCheck(const char * key, JsonVariant& value) {
  336. if (strncmp(key, "curtain", strlen("curtain")) == 0) return true;
  337. return false;
  338. }
  339. //------------------------------------------------------------------------------
  340. void _curtainWebSocketUpdate(JsonObject& root) {
  341. JsonObject& state = root.createNestedObject("curtainState");
  342. state["get"] = _curtain_last_position;
  343. if(_curtain_position_set == CURTAIN_POSITION_UNKNOWN) {
  344. _curtain_position_set = _curtain_last_position;
  345. }
  346. state["set"] = _curtain_position_set;
  347. state["button"] = _curtain_last_button;
  348. state["moving"] = _curtain_moving;
  349. state["type"] = getSetting("curtainType", "0");
  350. }
  351. //------------------------------------------------------------------------------
  352. void _curtainWebSocketStatus(JsonObject& root) {
  353. _curtainWebSocketUpdate(root);
  354. }
  355. //------------------------------------------------------------------------------
  356. void _curtainWebSocketOnAction(uint32_t client_id, const char * action, JsonObject& data) {
  357. if (strcmp(action, "curtainAction") == 0) {
  358. if (data.containsKey("position")) {
  359. _curtain_position_set = data["position"].as<int>();
  360. _KACurtainSet(CURTAIN_BUTTON_UNKNOWN, _curtain_position_set);
  361. } else if(data.containsKey("button")){
  362. _curtain_last_button = data["button"].as<int>();
  363. _KACurtainSet(_curtain_last_button);
  364. }
  365. }
  366. }
  367. void _curtainWebSocketOnVisible(JsonObject& root) {
  368. root["curtainVisible"] = 1;
  369. }
  370. #endif //WEB_SUPPORT
  371. // -----------------------------------------------------------------------------
  372. // SETUP & LOOP
  373. // -----------------------------------------------------------------------------
  374. //------------------------------------------------------------------------------
  375. void _KACurtainLoop() {
  376. if(_KACurtainReceiveUART()) {
  377. _KACurtainResult();
  378. } else if(_curtain_moving) { //When curtain move and no messages, get position every 600ms with AT+START
  379. unsigned long uptime = millis();
  380. long diff = uptime - last_uptime;
  381. if(diff >= 600) {
  382. _KACurtainSend("AT+START");
  383. last_uptime = uptime;
  384. }
  385. }
  386. #if WEB_SUPPORT
  387. if (_curtain_report_ws) { //Launch a websocket update
  388. wsPost(_curtainWebSocketUpdate);
  389. _curtain_report_ws = false;
  390. }
  391. #endif
  392. }
  393. // -----------------------------------------------------------------------------
  394. // Public
  395. // -----------------------------------------------------------------------------
  396. //------------------------------------------------------------------------------
  397. void kingartCurtainSetup() {
  398. // Init port to receive and send messages
  399. KINGART_CURTAIN_PORT.begin(KINGART_CURTAIN_BAUDRATE);
  400. #if MQTT_SUPPORT
  401. // Register MQTT callback only when supported
  402. mqttRegister(_curtainMQTTCallback);
  403. #endif // MQTT_SUPPORT
  404. #if WEB_SUPPORT
  405. // Websockets
  406. wsRegister()
  407. .onVisible(_curtainWebSocketOnVisible)
  408. .onConnected(_curtainWebSocketOnConnected)
  409. .onKeyCheck(_curtainWebSocketOnKeyCheck)
  410. .onAction(_curtainWebSocketOnAction)
  411. .onData(_curtainWebSocketUpdate);
  412. #endif
  413. // Register loop to poll the UART for new messages
  414. espurnaRegisterLoop(_KACurtainLoop);
  415. }
  416. //------------------------------------------------------------------------------
  417. void curtainSetPosition(unsigned char id, long value) {
  418. if (id > 1) return;
  419. _KACurtainSet(CURTAIN_BUTTON_UNKNOWN, constrain(value, 0, 100));
  420. }
  421. unsigned char curtainCount() {
  422. return 1;
  423. }
  424. #endif // KINGART_CURTAIN_SUPPORT