Repository: Hypfer/esp8266-midea-dehumidifier Branch: master Commit: 317e2295dde7 Files: 8 Total size: 39.1 KB Directory structure: gitextract_o0uhkbxp/ ├── LICENSE ├── README.md └── src/ └── esp8266-midea-dehumidifier/ ├── checksums.ino ├── configFileHandling.ino ├── esp8266-midea-dehumidifier.ino ├── serialCommunication.ino ├── types.h └── wifi.h ================================================ FILE CONTENTS ================================================ ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================
esp8266-midea-dehumidifier

Free your dehumidifier from the cloud

This repo contains software to build a replacement wifi adapter for your wifi-enabled midea dehumidifier which enables cloud-free operation utilizing MQTT. Home Assistant Autodiscovery for all features is supported since Home Assistant 2021.08. Furthermore, the WifiManager library is used for on-the-fly configuration. Also, ArduinoOTA is used, so that firmware updates are possible even with a reassembled device. If you're looking for the exact opposite of this, check out [esp8266-deerma-humidifier](https://github.com/Hypfer/esp8266-deerma-humidifier/). Or maybe even use both simultaneously and see who wins? This should work with all wifi-enabled Midea-made dehumidifiers. They are sold under different brands including: * Comfee * Inventor Quoting from [node-mideahvac](https://github.com/reneklootwijk/node-mideahvac): The WiFi interface [on these machines] is provided by a dongle, called WiFi SmartKey, either connected to an USB type-A connector or a JST-HX type of connector. This dongle wraps the UART protocol used to communicate with the unit with a layer for authentication and encryption for communication with a mobile app via the Midea cloud or directly via a local LAN connection. However, it turned out the dongle is just connected to a serial interface (TTL level) of the unit. This means an alternative is to hook up directly to this serial interface and bypass the cloud, authentication and encryption stuff, [which is exactly what this project does]. ## Compatibility list This list contains all tested and known-working dehumidifiers: * Midea MAD22S1WWT * Comfee MDDF-16DEN7-WF * Comfee MDDF-20DEN7-WF * Inventor Eva II PRO WI-FI * Inventor EVA ION PRO WiFi 20L * Midea Cube 20 ([#22](https://github.com/Hypfer/esp8266-midea-dehumidifier/issues/22)) * Midea Cube 35 ([#29](https://github.com/Hypfer/esp8266-midea-dehumidifier/issues/29)) * Midea Cube 50 ([#27](https://github.com/Hypfer/esp8266-midea-dehumidifier/issues/27)) Additionally, there are models that technically also work but have some issues: * Comfee MDDF-20DEN7 - lacks Wi-Fi Button and USB port. The guide below doesn't fully apply! ([#24](https://github.com/Hypfer/esp8266-midea-dehumidifier/pull/24)) ## Health and Safety Please note that some of the supported dehumidifiers such as the Comfee MDDF-20DEN7-WF use R290 as its coolant which - [while having a much lower global warming potential than other coolants](https://en.wikipedia.org/wiki/Refrigerant#Environmental_issues) - is also **Propane**. Yes, _the_ **Propane**. Therefore, when disassembling, please be extra careful so that you don't damage anything since a leak may result in you blowing yourself up and/or burning your house down. ## Building the Adapter ![adapter](./img/adapter.jpg) This is how the finished replacement adapter I'm using looks like. To build one of these, you will need: * ESP8266 ESP-01 Module * ESP-01 Serial Adapter Board with 3.3v to 5v Level Shifters * USB A to Terminal Plug Adapter * Some Dupont Cables * Something to flash the ESP-01 Just source those from the supplier of your choice and compare product listings with this finished adapter photo. For flashing the ESP-01, there are some nice and self-contained USB to ESP-01 Adapters. However, they cannot flash the module without soldering an extra button to it. You might want to get one of those as well and then follow [this instructable](https://www.instructables.com/id/USB-to-ESP-01-Board-Adapter-Modification/). The firmware can be built and flashed using the Arduino IDE. For this, you will need to add ESP8266 support to it by [using the Boards Manager](https://github.com/esp8266/Arduino#installing-with-boards-manager). Furthermore, you will also need to install the following libraries using the Library Manager: * ArduinoOTA 1.0.3 * ArduinoJSON 6.10.1 * PubSubClient 2.8.0 * WiFiManager 0.15.0 ## Using the Adapter Current supported features are: * On/Off * Mode * Fan Speed * Humidity Setpoint Also, the WiFi indicator on the unit continues to work like it's the real wifi adapter. ### Configuring Wifi Since this project is using the WifiManager library, the ESP8266 will open up a WiFi Access Point for its initial configuration or if it is unable to connect to the previously configured WiFi. The library pretends that said WiFi AP requires a captive portal which triggers a notification on recent android phones. Simply connect to the AP with your phone, tap the "Login required"-notification and you should be able to configure everything. If for any reason you require to reconfigure everything, you can simply push and the WiFi button of your Dehumidifier for three seconds. This also deletes the config and opens up the initial configuration Access Point again. ### Controlling the Appliance Since we're using the Home Assistant Autodiscovery feature, everything should just work™. If you're using something else other than Home Assistant, you can of course also control it by manually sending JSONs to the command mqtt topic of the unit: ``` esp8266-midea-dehumidifier/DEHUMIDIFIER-FFFFFF/command { "state": "on", "humiditySetpoint": 55, "fanSpeed": "medium", "mode": "setpoint" } ``` You can omit parameters that you don't want to change. The current status of the unit will be published like this: ``` esp8266-midea-dehumidifier/DEHUMIDIFIER-FFFFFF/state { "state": "on", "humiditySetpoint": 55, "humidityCurrent": 41, "errorCode": 0, "fanSpeed": "medium", "mode": "setpoint" } ``` ## Misc As you can see, on the Comfee MDDF-20DEN7-WF, the replacement adapter actually fits inside the mounting point of the regular WiFi adapter. ![comfee adapter](./img/comfee_adapter_mounted.jpg) ## References and sources The knowledge to create the logic to monitor and control the Midea-'like' AC units was gathered by reverse engineering Android applications from various vendors, analyzing the UART protocol between an Artel unit and an SK103 SmartKey, documents found on the Internet, primarily in Chinese and the work from: * Mac Zhou: * NeoAcheron: * Rene Klootwijk: ================================================ FILE: src/esp8266-midea-dehumidifier/checksums.ino ================================================ static const byte crc_table[] = { 0x00,0x5e,0xbc,0xE2,0x61,0x3F,0xDD,0x83, 0xC2,0x9C,0x7E,0x20,0xA3,0xFD,0x1F,0x41, 0x9D,0xC3,0x21,0x7F,0xFC,0xA2,0x40,0x1E, 0x5F,0x01,0xE3,0xBD,0x3E,0x60,0x82,0xDC, 0x23,0x7D,0x9F,0xC1,0x42,0x1C,0xFE,0xA0, 0xE1,0xBF,0x5D,0x03,0x80,0xDE,0x3C,0x62, 0xBE,0xE0,0x02,0x5C,0xDF,0x81,0x63,0x3D, 0x7C,0x22,0xC0,0x9E,0x1D,0x43,0xA1,0xFF, 0x46,0x18,0xFA,0xA4,0x27,0x79,0x9B,0xC5, 0x84,0xDA,0x38,0x66,0xE5,0xBB,0x59,0x07, 0xDB,0x85,0x67,0x39,0xBA,0xE4,0x06,0x58, 0x19,0x47,0xA5,0xFB,0x78,0x26,0xC4,0x9A, 0x65,0x3B,0xD9,0x87,0x04,0x5A,0xB8,0xE6, 0xA7,0xF9,0x1B,0x45,0xC6,0x98,0x7A,0x24, 0xF8,0xA6,0x44,0x1A,0x99,0xC7,0x25,0x7B, 0x3A,0x64,0x86,0xD8,0x5B,0x05,0xE7,0xB9, 0x8C,0xD2,0x30,0x6E,0xED,0xB3,0x51,0x0F, 0x4E,0x10,0xF2,0xAC,0x2F,0x71,0x93,0xCD, 0x11,0x4F,0xAD,0xF3,0x70,0x2E,0xCC,0x92, 0xD3,0x8D,0x6F,0x31,0xB2,0xEC,0x0E,0x50, 0xAF,0xF1,0x13,0x4D,0xCE,0x90,0x72,0x2C, 0x6D,0x33,0xD1,0x8F,0x0C,0x52,0xB0,0xEE, 0x32,0x6C,0x8E,0xD0,0x53,0x0D,0xEF,0xB1, 0xF0,0xAE,0x4C,0x12,0x91,0xCF,0x2D,0x73, 0xCA,0x94,0x76,0x28,0xAB,0xF5,0x17,0x49, 0x08,0x56,0xB4,0xEA,0x69,0x37,0xD5,0x8B, 0x57,0x09,0xEB,0xB5,0x36,0x68,0x8A,0xD4, 0x95,0xCB,0x29,0x77,0xF4,0xAA,0x48,0x16, 0xE9,0xB7,0x55,0x0B,0x88,0xD6,0x34,0x6A, 0x2B,0x75,0x97,0xC9,0x4A,0x14,0xF6,0xA8, 0x74,0x2A,0xC8,0x96,0x15,0x4B,0xA9,0xF7, 0xB6,0xE8,0x0A,0x54,0xD7,0x89,0x6B,0x35 }; byte crc8(byte *addr, byte len){ byte crc = 0; while(len--){ crc = crc_table[*addr++ ^ crc]; } return crc; } byte checksum(byte *addr, byte len) { byte sum = 0; *addr++; while(len--) { sum = sum + *addr++; } return 256 - sum; } ================================================ FILE: src/esp8266-midea-dehumidifier/configFileHandling.ino ================================================ void saveConfig() { DynamicJsonDocument json(512); json["mqtt_server"] = mqtt_server; json["username"] = username; json["password"] = password; File configFile = SPIFFS.open("/config.json", "w"); if (!configFile) { return; } serializeJson(json, configFile); configFile.close(); } void loadConfig() { if (SPIFFS.begin()) { if (SPIFFS.exists("/config.json")) { File configFile = SPIFFS.open("/config.json", "r"); if (configFile) { const size_t size = configFile.size(); std::unique_ptr buf(new char[size]); configFile.readBytes(buf.get(), size); DynamicJsonDocument json(512); if (DeserializationError::Ok == deserializeJson(json, buf.get())) { strcpy(mqtt_server, json["mqtt_server"]); strcpy(username, json["username"]); strcpy(password, json["password"]); } } } } } ================================================ FILE: src/esp8266-midea-dehumidifier/esp8266-midea-dehumidifier.ino ================================================ #include "types.h" #include "wifi.h" #include #include #include #include #include #include //#include #include #include dehumidifierState_t state; byte serialRxBuf[255]; byte serialTxBuf[255]; uint8_t mqttRetryCounter = 0; WiFiManager wifiManager; WiFiClient wifiClient; PubSubClient mqttClient; WiFiManagerParameter custom_mqtt_server("server", "mqtt server", mqtt_server, sizeof(mqtt_server)); WiFiManagerParameter custom_mqtt_user("user", "MQTT username", username, sizeof(username)); WiFiManagerParameter custom_mqtt_pass("pass", "MQTT password", password, sizeof(password)); unsigned long lastMqttConnectionAttempt = millis(); const long mqttConnectionInterval = 60000; unsigned long statusPollPreviousMillis = millis(); const long statusPollInterval = 30000; char identifier[24]; #define FIRMWARE_PREFIX "esp8266-midea-dehumidifier" #define AVAILABILITY_ONLINE "online" #define AVAILABILITY_OFFLINE "offline" char MQTT_TOPIC_AVAILABILITY[128]; char MQTT_TOPIC_STATE[128]; char MQTT_TOPIC_COMMAND[128]; char MQTT_TOPIC_AUTOCONF_WIFI_SENSOR[128]; char MQTT_TOPIC_AUTOCONF_HUMIDITY_SENSOR[128]; char MQTT_TOPIC_AUTOCONF_FAN[128]; char MQTT_TOPIC_AUTOCONF_HUMIDIFIER[128]; bool shouldSaveConfig = false; void saveConfigCallback () { shouldSaveConfig = true; } void setup() { Serial.begin(9600); //Initializing with defaults until we have a status update state.powerOn = false; state.fanSpeed = low; state.mode = setpoint; state.humiditySetpoint = 55; state.currentHumidity = 45; state.errorCode = 0; delay(3000); updateAndSendNetworkStatus(false); snprintf(identifier, sizeof(identifier), "DEHUMIDIFIER-%X", ESP.getChipId()); snprintf(MQTT_TOPIC_AVAILABILITY, 127, "%s/%s/status", FIRMWARE_PREFIX, identifier); snprintf(MQTT_TOPIC_STATE, 127, "%s/%s/state", FIRMWARE_PREFIX, identifier); snprintf(MQTT_TOPIC_COMMAND, 127, "%s/%s/command", FIRMWARE_PREFIX, identifier); snprintf(MQTT_TOPIC_AUTOCONF_HUMIDITY_SENSOR, 127, "homeassistant/sensor/%s/%s_humidity/config", FIRMWARE_PREFIX, identifier); snprintf(MQTT_TOPIC_AUTOCONF_WIFI_SENSOR, 127, "homeassistant/sensor/%s/%s_wifi/config", FIRMWARE_PREFIX, identifier); snprintf(MQTT_TOPIC_AUTOCONF_FAN, 127, "homeassistant/select/%s/%s_fan/config", FIRMWARE_PREFIX, identifier); snprintf(MQTT_TOPIC_AUTOCONF_HUMIDIFIER, 127, "homeassistant/humidifier/%s/%s_dehumidifier/config", FIRMWARE_PREFIX, identifier); WiFi.hostname(identifier); loadConfig(); setupWifi(); setupOTA(); mqttClient.setServer(mqtt_server, 1883); mqttClient.setKeepAlive(10); mqttClient.setBufferSize(2048); mqttClient.setCallback(mqttCallback); mqttReconnect(); } void setupOTA() { ArduinoOTA.onStart([]() { //Serial.println("Start"); }); ArduinoOTA.onEnd([]() { //Serial.println("\nEnd"); }); ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { //Serial.printf("Progress: %u%%\r", (progress / (total / 100))); }); ArduinoOTA.onError([](ota_error_t error) { /* Serial.printf("Error[%u]: ", error); if (error == OTA_AUTH_ERROR) Serial.println("Auth Failed"); else if (error == OTA_BEGIN_ERROR) Serial.println("Begin Failed"); else if (error == OTA_CONNECT_ERROR) Serial.println("Connect Failed"); else if (error == OTA_RECEIVE_ERROR) Serial.println("Receive Failed"); else if (error == OTA_END_ERROR) Serial.println("End Failed"); */ }); ArduinoOTA.setHostname(identifier); //This is less of a security measure and more a accidential flash prevention ArduinoOTA.setPassword(identifier); ArduinoOTA.begin(); } void loop() { ArduinoOTA.handle(); handleUart(); mqttClient.loop(); if (statusPollInterval <= (millis() - statusPollPreviousMillis)) { statusPollPreviousMillis = millis(); getStatus(); } if (!mqttClient.connected() && (mqttConnectionInterval <= (millis() - lastMqttConnectionAttempt)) ) { lastMqttConnectionAttempt = millis(); mqttReconnect(); } } void setupWifi() { wifiManager.setDebugOutput(false); wifiManager.setSaveConfigCallback(saveConfigCallback); wifiManager.addParameter(&custom_mqtt_server); wifiManager.addParameter(&custom_mqtt_user); wifiManager.addParameter(&custom_mqtt_pass); WiFi.hostname(identifier); wifiManager.autoConnect(identifier); mqttClient.setClient(wifiClient); strcpy(mqtt_server, custom_mqtt_server.getValue()); strcpy(username, custom_mqtt_user.getValue()); strcpy(password, custom_mqtt_pass.getValue()); if (shouldSaveConfig) { saveConfig(); } else { //For some reason, the read values get overwritten in this function //To combat this, we just reload the config //This is most likely a logic error which could be fixed otherwise loadConfig(); } } void resetWifiSettingsAndReboot() { wifiManager.resetSettings(); updateAndSendNetworkStatus(false); delay(3000); ESP.restart(); } void mqttReconnect() { for (int attempt = 0; attempt < 3; ++attempt) { if (mqttClient.connect(identifier, username, password, MQTT_TOPIC_AVAILABILITY, 1, true, AVAILABILITY_OFFLINE)) { mqttClient.publish(MQTT_TOPIC_AVAILABILITY, AVAILABILITY_ONLINE, true); updateAndSendNetworkStatus(true); getStatus(); publishAutoConfig(); //Make sure to subscribe after polling the status so that we never execute commands with the default data mqttClient.subscribe(MQTT_TOPIC_COMMAND); break; } else { delay(5000); } } } boolean isMqttConnected() { return mqttClient.connected(); } void publishState() { DynamicJsonDocument wifiJson(192); DynamicJsonDocument stateJson(604); char payload[256]; wifiJson["ssid"] = WiFi.SSID(); wifiJson["ip"] = WiFi.localIP().toString(); wifiJson["rssi"] = WiFi.RSSI(); stateJson["state"] = state.powerOn ? "on" : "off"; stateJson["humiditySetpoint"] = state.humiditySetpoint; stateJson["humidityCurrent"] = state.currentHumidity; stateJson["errorCode"] = state.errorCode; switch (state.fanSpeed) { case low: stateJson["fanSpeed"] = "low"; break; case medium: stateJson["fanSpeed"] = "medium"; break; case high: stateJson["fanSpeed"] = "high"; break; } switch (state.mode) { case setpoint: stateJson["mode"] = "setpoint"; break; case continuous: stateJson["mode"] = "continuous"; break; case smart: stateJson["mode"] = "smart"; break; case clothesDrying: stateJson["mode"] = "clothesDrying"; break; } stateJson["wifi"] = wifiJson.as(); serializeJson(stateJson, payload); mqttClient.publish(MQTT_TOPIC_STATE, payload, true); } void mqttCallback(char* topic, byte* payload, unsigned int length) { if (strcmp(topic, MQTT_TOPIC_COMMAND) == 0) { DynamicJsonDocument commandJson(256); char payloadText[length + 1]; snprintf(payloadText, length + 1, "%s", payload); DeserializationError err = deserializeJson(commandJson, payloadText); if (!err) { handleStateUpdateRequest( commandJson["state"].as(), commandJson["mode"].as(), commandJson["fanSpeed"].as(), commandJson["humiditySetpoint"].as() ); getStatus(); } } } void publishAutoConfig() { char mqttPayload[2048]; DynamicJsonDocument device(256); DynamicJsonDocument autoconfPayload(1024); StaticJsonDocument<64> identifiersDoc; JsonArray identifiers = identifiersDoc.to(); identifiers.add(identifier); device["identifiers"] = identifiers; device["manufacturer"] = "Midea Group Co., Ltd."; device["model"] = "Generic Dehumidifier"; device["name"] = identifier; device["sw_version"] = "2023.08.0"; autoconfPayload["device"] = device.as(); autoconfPayload["availability_topic"] = MQTT_TOPIC_AVAILABILITY; autoconfPayload["state_topic"] = MQTT_TOPIC_STATE; autoconfPayload["name"] = "WiFi"; autoconfPayload["value_template"] = "{{value_json.wifi.rssi}}"; autoconfPayload["unique_id"] = identifier + String("_wifi"); autoconfPayload["unit_of_measurement"] = "dBm"; autoconfPayload["json_attributes_topic"] = MQTT_TOPIC_STATE; autoconfPayload["json_attributes_template"] = "{\"ssid\": \"{{value_json.wifi.ssid}}\", \"ip\": \"{{value_json.wifi.ip}}\"}"; autoconfPayload["icon"] = "mdi:wifi"; serializeJson(autoconfPayload, mqttPayload); mqttClient.publish(MQTT_TOPIC_AUTOCONF_WIFI_SENSOR, mqttPayload, true); autoconfPayload.clear(); autoconfPayload["device"] = device.as(); autoconfPayload["availability_topic"] = MQTT_TOPIC_AVAILABILITY; autoconfPayload["state_topic"] = MQTT_TOPIC_STATE; autoconfPayload["name"] = "Humidity"; autoconfPayload["device_class"] = "humidity"; autoconfPayload["unit_of_measurement"] = "%"; autoconfPayload["value_template"] = "{{value_json.humidityCurrent}}"; autoconfPayload["unique_id"] = identifier + String("_humidity"); serializeJson(autoconfPayload, mqttPayload); mqttClient.publish(MQTT_TOPIC_AUTOCONF_HUMIDITY_SENSOR, mqttPayload, true); autoconfPayload.clear(); StaticJsonDocument<64> optionsDoc; JsonArray speedOptions = optionsDoc.to(); speedOptions.add("low"); speedOptions.add("medium"); speedOptions.add("high"); autoconfPayload["device"] = device.as(); autoconfPayload["availability_topic"] = MQTT_TOPIC_AVAILABILITY; autoconfPayload["name"] = "Fan"; autoconfPayload["unique_id"] = identifier + String("_fan"); autoconfPayload["icon"] = "mdi:fan"; autoconfPayload["state_topic"] = MQTT_TOPIC_STATE; autoconfPayload["command_topic"] = MQTT_TOPIC_COMMAND; autoconfPayload["options"] = speedOptions; autoconfPayload["state_topic"] = MQTT_TOPIC_STATE; autoconfPayload["command_topic"] = MQTT_TOPIC_COMMAND; autoconfPayload["value_template"] = "{{value_json.fanSpeed}}"; autoconfPayload["command_template"] = "{\"fanSpeed\": \"{{value}}\"}"; serializeJson(autoconfPayload, mqttPayload); mqttClient.publish(MQTT_TOPIC_AUTOCONF_FAN, mqttPayload, true); autoconfPayload.clear(); autoconfPayload["device"] = device.as(); autoconfPayload["availability_topic"] = MQTT_TOPIC_AVAILABILITY; autoconfPayload["name"] = "Dehumidifier"; autoconfPayload["unique_id"] = identifier + String("_dehumidifier"); autoconfPayload["device_class"] = "dehumidifier"; autoconfPayload["max_humidity"] = 85; autoconfPayload["min_humidity"] = 35; autoconfPayload["state_topic"] = MQTT_TOPIC_STATE; autoconfPayload["state_value_template"] = "{\"state\": \"{{value_json.state}}\"}"; autoconfPayload["payload_on"] = "{\"state\": \"on\"}"; autoconfPayload["payload_off"] = "{\"state\": \"off\"}"; autoconfPayload["command_topic"] = MQTT_TOPIC_COMMAND; autoconfPayload["state_value_template"] = "{\"state\": \"{{value_json.state}}\"}"; autoconfPayload["payload_on"] = "{\"state\": \"on\"}"; autoconfPayload["payload_off"] = "{\"state\": \"off\"}"; StaticJsonDocument<64> modesDoc; JsonArray modes = modesDoc.to(); autoconfPayload["target_humidity_state_topic"] = MQTT_TOPIC_STATE; autoconfPayload["target_humidity_command_topic"] = MQTT_TOPIC_COMMAND; autoconfPayload["target_humidity_state_template"] = "{{value_json.humiditySetpoint | int}}"; autoconfPayload["target_humidity_command_template"] = "{\"humiditySetpoint\": {{value | int}}}"; modes.add("setpoint"); modes.add("continuous"); modes.add("smart"); modes.add("clothesDrying"); autoconfPayload["modes"] = modes; autoconfPayload["mode_state_topic"] = MQTT_TOPIC_STATE; autoconfPayload["mode_command_topic"] = MQTT_TOPIC_COMMAND; autoconfPayload["mode_state_template"] = "{{value_json.mode}}"; autoconfPayload["mode_command_template"] = "{\"mode\": \"{{value}}\"}"; serializeJson(autoconfPayload, mqttPayload); mqttClient.publish(MQTT_TOPIC_AUTOCONF_HUMIDIFIER, mqttPayload, true); autoconfPayload.clear(); } ================================================ FILE: src/esp8266-midea-dehumidifier/serialCommunication.ino ================================================ byte networkStatus[20]; byte currentHeader[10]; byte getStatusCommand[21] = { 0x41, 0x81, 0x00, 0xff, 0x03, 0xff, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03 }; byte setStatusCommand[25]; void parseState() { state.powerOn = serialRxBuf[11] & 0x01 > 0; state.mode = (dehumMode_t)(serialRxBuf[12] & 0x0f); state.fanSpeed = (fanSpeed_t)(serialRxBuf[13] & 0x7f); state.humiditySetpoint = serialRxBuf[17] >= 100 ? 99 : serialRxBuf[17]; state.currentHumidity = serialRxBuf[26]; state.errorCode = serialRxBuf[31]; clearRxBuf(); } void clearRxBuf() { //Clear everything for the next message memset(serialRxBuf, 0, sizeof(serialRxBuf)); } void clearTxBuf() { //Clear everything for the next message memset(serialTxBuf, 0, sizeof(serialTxBuf)); } void handleUart() { if (Serial.available()) { Serial.readBytesUntil('\n', serialRxBuf, 250); if (serialRxBuf[10] == 0xc8) { parseState(); publishState(); } else if (serialRxBuf[10] == 0x63) { updateAndSendNetworkStatus(isMqttConnected()); } else if ( //Yes, this is ugly :( serialRxBuf[10] == 0x0 && serialRxBuf[50] == 0xaa && serialRxBuf[51] == 0x1e && serialRxBuf[52] == 0xa1 && //Appliance Type serialRxBuf[58] == 0x03 && serialRxBuf[59] == 0x64 && serialRxBuf[61] == 0x01 && serialRxBuf[65] == 0x01 ) { resetWifiSettingsAndReboot(); } else { //Serial.print("Received msg with invalid type: "); //Serial.println(serialRxBuf[10]); } } } void writeHeader(byte msgType, byte agreementVersion, byte packetLength) { currentHeader[0] = 0xAA; //Sync Header currentHeader[1] = 10 + packetLength + 1; currentHeader[2] = 0xA1; //ApplianceType currentHeader[3] = 0x00; //Frame sync check (not used) currentHeader[4] = 0x00; //Reserved currentHeader[5] = 0x00; //Reserved currentHeader[6] = 0x00; //MsgId currentHeader[7] = 0x00; //ProtocolVersion currentHeader[8] = agreementVersion; currentHeader[9] = msgType; } void handleStateUpdateRequest(String requestedState, String mode, String fanSpeed, byte humiditySetpoint) { dehumidifierState_t newState; newState.powerOn = state.powerOn; newState.mode = state.mode; newState.fanSpeed = state.fanSpeed; newState.humiditySetpoint = state.humiditySetpoint; if (requestedState == "on") { newState.powerOn = true; } else if (requestedState == "off") { newState.powerOn = false; } if (mode == "setpoint") { newState.mode = (dehumMode_t)setpoint; } else if (mode == "continuous") { newState.mode = (dehumMode_t)continuous; } else if (mode == "smart") { newState.mode = (dehumMode_t)smart; } else if (mode == "clothesDrying") { newState.mode = (dehumMode_t)clothesDrying; } if (fanSpeed == "low") { newState.fanSpeed = (fanSpeed_t)low; } else if (fanSpeed == "medium") { newState.fanSpeed = (fanSpeed_t)medium; } else if (fanSpeed == "high") { newState.fanSpeed = (fanSpeed_t)high; } if (humiditySetpoint && humiditySetpoint >= 35 && humiditySetpoint <= 85) { newState.humiditySetpoint = humiditySetpoint; } if ( //Only send if we have updates newState.powerOn != state.powerOn || newState.mode != state.mode || newState.fanSpeed != state.fanSpeed || newState.humiditySetpoint != state.humiditySetpoint ) { updateSetStatus( newState.powerOn, newState.mode, newState.fanSpeed, newState.humiditySetpoint ); sendSetStatus(); //Write back so that we don't swallow commands if there are many coming right after each other //This may cause unexpected results if the connection to the unit doesn't work state.powerOn = newState.powerOn; state.mode = newState.mode; state.fanSpeed = newState.fanSpeed; state.humiditySetpoint = newState.humiditySetpoint; delay(30); } } void sendSetStatus() { sendMessage(0x02, 0x03, 25, setStatusCommand); } void updateSetStatus(boolean powerOn, dehumMode_t dehumMode, fanSpeed_t fanSpeed, byte humiditySetpoint) { memset(setStatusCommand, 0, sizeof(setStatusCommand)); setStatusCommand[0] = 0x48; //Magic setStatusCommand[1] = powerOn ? 0x01 : 0x00; setStatusCommand[2] = (byte)(dehumMode & 0x0f); setStatusCommand[3] = (byte)fanSpeed; setStatusCommand[7] = humiditySetpoint; } void updateAndSendNetworkStatus(boolean isConnected) { updateNetworkStatus(isConnected); sendMessage(0x0D, 0x03, 20, networkStatus); } void getStatus() { sendMessage(0x03, 0x03, 21, getStatusCommand); } void updateNetworkStatus(boolean isConnected) { memset(networkStatus, 0, sizeof(networkStatus)); // Byte 0: Module type: // - 0x00 RF module // - 0x01 WiFi module networkStatus[0] = 0x01; // Byte 1: WiFi module working mode: // - 0x01 Client mode // - 0x02 Configuration mode // - 0x03 AP mode networkStatus[1] = 0x01; // Byte 2: WiFi signal strength // - 0x00 No signal // - 0x01 Weak // - 0x02 Low // - 0x03 Medium // - 0x04 Strong // - 0xFF WiFi is not supported networkStatus[2] = 0x04; // Byte 3-6: IPv4 address of client in reverse order networkStatus[3] = 1; networkStatus[4] = 0; networkStatus[5] = 0; networkStatus[6] = 127; // Byte 7: RF Signal strength // - 0x00, no signal // - 0x01, weak // - 0x02, low // - 0x03, medium // - 0x04, strong // - 0xFF, RF is not supported networkStatus[7] = 0xff; // Byte 8: Router status // - 0x00, wireless router is connected // - 0x01, wireless router not connected // - 0x02, connecting to a wireless router // - 0x03, password verification error // - 0x04, no wireless router found // - 0x05, IP cannot be obtained // - 0x06, wireless unstable // - 0xFF, WI-FI failure networkStatus[8] = isConnected ? 0x00 : 0x01; // Byte 9: Cloud service connection status: // - 0x00, connected to the cloud service center // - 0x01, not connected to the cloud service center // - 0x02, unstable internet connection // - 0x03, domain name resolution error // - 0x04, cloud service connection refused // - 0x05, cloud service maintenance // - 0xFF, cloud service failure networkStatus[9] = isConnected ? 0x00 : 0x01; // Byte 10: Direct LAN connection status // - 0x00: No connection/connection has been disconnected // - 0x01: connected/connected with mobile terminal networkStatus[10] = 0x00; // Byte 11 Number of TCP connections between the module and the mobile terminal networkStatus[11] = 0x00; // Byte 12 - 19 Reserved } void sendMessage(byte msgType, byte agreementVersion, byte payloadLength, byte *payload) { clearTxBuf(); writeHeader(msgType, agreementVersion, payloadLength); memcpy(serialTxBuf, currentHeader, 10); memcpy(serialTxBuf + 10, payload, payloadLength); serialTxBuf[10 + payloadLength] = crc8(serialTxBuf + 10, payloadLength); serialTxBuf[10 + payloadLength + 1] = checksum(serialTxBuf, 10 + payloadLength + 1); Serial.write(serialTxBuf, 10 + payloadLength + 2); } ================================================ FILE: src/esp8266-midea-dehumidifier/types.h ================================================ enum fanSpeed_t { low = 40, medium = 60, high = 80 }; enum dehumMode_t { setpoint = 1, continuous = 2, smart = 3, clothesDrying = 4 }; struct dehumidifierState_t { boolean powerOn; dehumMode_t mode; fanSpeed_t fanSpeed; byte humiditySetpoint; byte currentHumidity; byte errorCode; }; ================================================ FILE: src/esp8266-midea-dehumidifier/wifi.h ================================================ char mqtt_server[80] = "example.tld"; char username[24] = ""; char password[24] = "";