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.

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