[
  {
    "path": "LICENSE",
    "content": "                                 Apache License\n                           Version 2.0, January 2004\n                        http://www.apache.org/licenses/\n\n   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION\n\n   1. Definitions.\n\n      \"License\" shall mean the terms and conditions for use, reproduction,\n      and distribution as defined by Sections 1 through 9 of this document.\n\n      \"Licensor\" shall mean the copyright owner or entity authorized by\n      the copyright owner that is granting the License.\n\n      \"Legal Entity\" shall mean the union of the acting entity and all\n      other entities that control, are controlled by, or are under common\n      control with that entity. For the purposes of this definition,\n      \"control\" means (i) the power, direct or indirect, to cause the\n      direction or management of such entity, whether by contract or\n      otherwise, or (ii) ownership of fifty percent (50%) or more of the\n      outstanding shares, or (iii) beneficial ownership of such entity.\n\n      \"You\" (or \"Your\") shall mean an individual or Legal Entity\n      exercising permissions granted by this License.\n\n      \"Source\" form shall mean the preferred form for making modifications,\n      including but not limited to software source code, documentation\n      source, and configuration files.\n\n      \"Object\" form shall mean any form resulting from mechanical\n      transformation or translation of a Source form, including but\n      not limited to compiled object code, generated documentation,\n      and conversions to other media types.\n\n      \"Work\" shall mean the work of authorship, whether in Source or\n      Object form, made available under the License, as indicated by a\n      copyright notice that is included in or attached to the work\n      (an example is provided in the Appendix below).\n\n      \"Derivative Works\" shall mean any work, whether in Source or Object\n      form, that is based on (or derived from) the Work and for which the\n      editorial revisions, annotations, elaborations, or other modifications\n      represent, as a whole, an original work of authorship. For the purposes\n      of this License, Derivative Works shall not include works that remain\n      separable from, or merely link (or bind by name) to the interfaces of,\n      the Work and Derivative Works thereof.\n\n      \"Contribution\" shall mean any work of authorship, including\n      the original version of the Work and any modifications or additions\n      to that Work or Derivative Works thereof, that is intentionally\n      submitted to Licensor for inclusion in the Work by the copyright owner\n      or by an individual or Legal Entity authorized to submit on behalf of\n      the copyright owner. For the purposes of this definition, \"submitted\"\n      means any form of electronic, verbal, or written communication sent\n      to the Licensor or its representatives, including but not limited to\n      communication on electronic mailing lists, source code control systems,\n      and issue tracking systems that are managed by, or on behalf of, the\n      Licensor for the purpose of discussing and improving the Work, but\n      excluding communication that is conspicuously marked or otherwise\n      designated in writing by the copyright owner as \"Not a Contribution.\"\n\n      \"Contributor\" shall mean Licensor and any individual or Legal Entity\n      on behalf of whom a Contribution has been received by Licensor and\n      subsequently incorporated within the Work.\n\n   2. Grant of Copyright License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      copyright license to reproduce, prepare Derivative Works of,\n      publicly display, publicly perform, sublicense, and distribute the\n      Work and such Derivative Works in Source or Object form.\n\n   3. Grant of Patent License. Subject to the terms and conditions of\n      this License, each Contributor hereby grants to You a perpetual,\n      worldwide, non-exclusive, no-charge, royalty-free, irrevocable\n      (except as stated in this section) patent license to make, have made,\n      use, offer to sell, sell, import, and otherwise transfer the Work,\n      where such license applies only to those patent claims licensable\n      by such Contributor that are necessarily infringed by their\n      Contribution(s) alone or by combination of their Contribution(s)\n      with the Work to which such Contribution(s) was submitted. If You\n      institute patent litigation against any entity (including a\n      cross-claim or counterclaim in a lawsuit) alleging that the Work\n      or a Contribution incorporated within the Work constitutes direct\n      or contributory patent infringement, then any patent licenses\n      granted to You under this License for that Work shall terminate\n      as of the date such litigation is filed.\n\n   4. Redistribution. You may reproduce and distribute copies of the\n      Work or Derivative Works thereof in any medium, with or without\n      modifications, and in Source or Object form, provided that You\n      meet the following conditions:\n\n      (a) You must give any other recipients of the Work or\n          Derivative Works a copy of this License; and\n\n      (b) You must cause any modified files to carry prominent notices\n          stating that You changed the files; and\n\n      (c) You must retain, in the Source form of any Derivative Works\n          that You distribute, all copyright, patent, trademark, and\n          attribution notices from the Source form of the Work,\n          excluding those notices that do not pertain to any part of\n          the Derivative Works; and\n\n      (d) If the Work includes a \"NOTICE\" text file as part of its\n          distribution, then any Derivative Works that You distribute must\n          include a readable copy of the attribution notices contained\n          within such NOTICE file, excluding those notices that do not\n          pertain to any part of the Derivative Works, in at least one\n          of the following places: within a NOTICE text file distributed\n          as part of the Derivative Works; within the Source form or\n          documentation, if provided along with the Derivative Works; or,\n          within a display generated by the Derivative Works, if and\n          wherever such third-party notices normally appear. The contents\n          of the NOTICE file are for informational purposes only and\n          do not modify the License. You may add Your own attribution\n          notices within Derivative Works that You distribute, alongside\n          or as an addendum to the NOTICE text from the Work, provided\n          that such additional attribution notices cannot be construed\n          as modifying the License.\n\n      You may add Your own copyright statement to Your modifications and\n      may provide additional or different license terms and conditions\n      for use, reproduction, or distribution of Your modifications, or\n      for any such Derivative Works as a whole, provided Your use,\n      reproduction, and distribution of the Work otherwise complies with\n      the conditions stated in this License.\n\n   5. Submission of Contributions. Unless You explicitly state otherwise,\n      any Contribution intentionally submitted for inclusion in the Work\n      by You to the Licensor shall be under the terms and conditions of\n      this License, without any additional terms or conditions.\n      Notwithstanding the above, nothing herein shall supersede or modify\n      the terms of any separate license agreement you may have executed\n      with Licensor regarding such Contributions.\n\n   6. Trademarks. This License does not grant permission to use the trade\n      names, trademarks, service marks, or product names of the Licensor,\n      except as required for reasonable and customary use in describing the\n      origin of the Work and reproducing the content of the NOTICE file.\n\n   7. Disclaimer of Warranty. Unless required by applicable law or\n      agreed to in writing, Licensor provides the Work (and each\n      Contributor provides its Contributions) on an \"AS IS\" BASIS,\n      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or\n      implied, including, without limitation, any warranties or conditions\n      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A\n      PARTICULAR PURPOSE. You are solely responsible for determining the\n      appropriateness of using or redistributing the Work and assume any\n      risks associated with Your exercise of permissions under this License.\n\n   8. Limitation of Liability. In no event and under no legal theory,\n      whether in tort (including negligence), contract, or otherwise,\n      unless required by applicable law (such as deliberate and grossly\n      negligent acts) or agreed to in writing, shall any Contributor be\n      liable to You for damages, including any direct, indirect, special,\n      incidental, or consequential damages of any character arising as a\n      result of this License or out of the use or inability to use the\n      Work (including but not limited to damages for loss of goodwill,\n      work stoppage, computer failure or malfunction, or any and all\n      other commercial damages or losses), even if such Contributor\n      has been advised of the possibility of such damages.\n\n   9. Accepting Warranty or Additional Liability. While redistributing\n      the Work or Derivative Works thereof, You may choose to offer,\n      and charge a fee for, acceptance of support, warranty, indemnity,\n      or other liability obligations and/or rights consistent with this\n      License. However, in accepting such obligations, You may act only\n      on Your own behalf and on Your sole responsibility, not on behalf\n      of any other Contributor, and only if You agree to indemnify,\n      defend, and hold each Contributor harmless for any liability\n      incurred by, or claims asserted against, such Contributor by reason\n      of your accepting any such warranty or additional liability.\n\n   END OF TERMS AND CONDITIONS\n\n   APPENDIX: How to apply the Apache License to your work.\n\n      To apply the Apache License to your work, attach the following\n      boilerplate notice, with the fields enclosed by brackets \"[]\"\n      replaced with your own identifying information. (Don't include\n      the brackets!)  The text should be enclosed in the appropriate\n      comment syntax for the file format. We also recommend that a\n      file or class name and description of purpose be included on the\n      same \"printed page\" as the copyright notice for easier\n      identification within third-party archives.\n\n   Copyright [yyyy] [name of copyright owner]\n\n   Licensed under the Apache License, Version 2.0 (the \"License\");\n   you may not use this file except in compliance with the License.\n   You may obtain a copy of the License at\n\n       http://www.apache.org/licenses/LICENSE-2.0\n\n   Unless required by applicable law or agreed to in writing, software\n   distributed under the License is distributed on an \"AS IS\" BASIS,\n   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n   See the License for the specific language governing permissions and\n   limitations under the License.\n"
  },
  {
    "path": "README.md",
    "content": "<div align=\"center\">\n    <img src=\"https://github.com/Hypfer/esp8266-midea-dehumidifier/blob/master/img/logo.svg\" width=\"800\" alt=\"esp8266-midea-dehumidifier\">\n    <p align=\"center\"><h2>Free your dehumidifier from the cloud</h2></p>\n</div>\n\nThis repo contains software to build a replacement wifi adapter for your wifi-enabled midea dehumidifier\nwhich enables cloud-free operation utilizing MQTT.\n\nHome Assistant Autodiscovery for all features is supported since Home Assistant 2021.08.\nFurthermore, the WifiManager library is used for on-the-fly configuration.\nAlso, ArduinoOTA is used, so that firmware updates are possible even with a reassembled device.\n\n\nIf you're looking for the exact opposite of this, check out [esp8266-deerma-humidifier](https://github.com/Hypfer/esp8266-deerma-humidifier/).\nOr maybe even use both simultaneously and see who wins?\n\n\nThis should work with all wifi-enabled Midea-made dehumidifiers. They are sold under different brands including:\n* Comfee\n* Inventor\n\nQuoting from [node-mideahvac](https://github.com/reneklootwijk/node-mideahvac):\n\nThe WiFi interface [on these machines] is provided by a dongle, called WiFi SmartKey, either connected to an USB type-A\nconnector or a JST-HX type of connector. This dongle wraps the UART protocol used to communicate with the unit with a\nlayer for authentication and encryption for communication with a mobile app via the Midea cloud or directly via a local LAN connection.\n\nHowever, it turned out the dongle is just connected to a serial interface (TTL level) of the unit.\nThis means an alternative is to hook up directly to this serial interface and bypass the cloud, authentication and encryption stuff,\n[which is exactly what this project does].\n\n## Compatibility list\nThis list contains all tested and known-working dehumidifiers:\n\n* Midea MAD22S1WWT\n* Comfee MDDF-16DEN7-WF\n* Comfee MDDF-20DEN7-WF\n* Inventor Eva II PRO WI-FI\n* Inventor EVA ION PRO WiFi 20L\n* Midea Cube 20 ([#22](https://github.com/Hypfer/esp8266-midea-dehumidifier/issues/22))\n* Midea Cube 35 ([#29](https://github.com/Hypfer/esp8266-midea-dehumidifier/issues/29))\n* Midea Cube 50 ([#27](https://github.com/Hypfer/esp8266-midea-dehumidifier/issues/27))\n\nAdditionally, there are models that technically also work but have some issues:\n\n* 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))\n\n## Health and Safety\nPlease 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) -\nis also **Propane**.\n\nYes, _the_ **Propane**.\n\nTherefore, when disassembling, please be extra careful so that you don't damage anything since a leak may result in\nyou blowing yourself up and/or burning your house down.\n\n## Building the Adapter\n![adapter](./img/adapter.jpg)\nThis is how the finished replacement adapter I'm using looks like.\n\nTo build one of these, you will need:\n\n* ESP8266 ESP-01 Module\n* ESP-01 Serial Adapter Board with 3.3v to 5v Level Shifters\n* USB A to Terminal Plug Adapter\n* Some Dupont Cables\n* Something to flash the ESP-01\n\nJust source those from the supplier of your choice and compare product listings with this finished adapter photo.\n\nFor flashing the ESP-01, there are some nice and self-contained USB to ESP-01 Adapters.\n\nHowever, they cannot flash the module without soldering an extra button to it.\nYou 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/).\n\nThe firmware can be built and flashed using the Arduino IDE.\n\nFor this, you will need to add ESP8266 support to it by [using the Boards Manager](https://github.com/esp8266/Arduino#installing-with-boards-manager).\n\nFurthermore, you will also need to install the following libraries using the Library Manager:\n\n* ArduinoOTA 1.0.3\n* ArduinoJSON 6.10.1\n* PubSubClient 2.8.0\n* WiFiManager 0.15.0\n\n## Using the Adapter\nCurrent supported features are:\n\n* On/Off\n* Mode\n* Fan Speed\n* Humidity Setpoint\n\nAlso, the WiFi indicator on the unit continues to work like it's the real wifi adapter.\n\n### Configuring Wifi\nSince this project is using the WifiManager library, the ESP8266 will open up a WiFi Access Point for its initial configuration\nor if it is unable to connect to the previously configured WiFi.\n\nThe library pretends that said WiFi AP requires a captive portal which triggers a notification on recent android phones.\nSimply connect to the AP with your phone, tap the \"Login required\"-notification and you should be able to configure everything.\n\nIf for any reason you require to reconfigure everything, you can simply push and the WiFi button of your Dehumidifier for three seconds.\nThis also deletes the config and opens up the initial configuration Access Point again.\n\n### Controlling the Appliance\nSince we're using the Home Assistant Autodiscovery feature, everything should just work™.\n\nIf you're using something else other than Home Assistant, you can of course also control it by manually sending\nJSONs to the command mqtt topic of the unit:\n```\nesp8266-midea-dehumidifier/DEHUMIDIFIER-FFFFFF/command\n\n{\n\t\"state\": \"on\",\n\t\"humiditySetpoint\": 55,\n\t\"fanSpeed\": \"medium\",\n\t\"mode\": \"setpoint\"\n}\n```\nYou can omit parameters that you don't want to change.\n\nThe current status of the unit will be published like this:\n```\nesp8266-midea-dehumidifier/DEHUMIDIFIER-FFFFFF/state\n\n{\n\t\"state\": \"on\",\n\t\"humiditySetpoint\": 55,\n\t\"humidityCurrent\": 41,\n\t\"errorCode\": 0,\n\t\"fanSpeed\": \"medium\",\n\t\"mode\": \"setpoint\"\n}\n```\n\n## Misc\nAs you can see, on the Comfee MDDF-20DEN7-WF, the replacement adapter actually fits inside the mounting point of the regular WiFi adapter.\n![comfee adapter](./img/comfee_adapter_mounted.jpg)\n\n## References and sources\n\nThe 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:\n\n* Mac Zhou: <https://github.com/mac-zhou/midea-msmart>\n* NeoAcheron: <https://github.com/NeoAcheron/midea-ac-py>\n* Rene Klootwijk: <https://github.com/reneklootwijk/node-mideahvac>\n"
  },
  {
    "path": "src/esp8266-midea-dehumidifier/checksums.ino",
    "content": "static const byte crc_table[] = {  \n    0x00,0x5e,0xbc,0xE2,0x61,0x3F,0xDD,0x83,\n    0xC2,0x9C,0x7E,0x20,0xA3,0xFD,0x1F,0x41,\n    0x9D,0xC3,0x21,0x7F,0xFC,0xA2,0x40,0x1E,\n    0x5F,0x01,0xE3,0xBD,0x3E,0x60,0x82,0xDC,\n    0x23,0x7D,0x9F,0xC1,0x42,0x1C,0xFE,0xA0,\n    0xE1,0xBF,0x5D,0x03,0x80,0xDE,0x3C,0x62,\n    0xBE,0xE0,0x02,0x5C,0xDF,0x81,0x63,0x3D,\n    0x7C,0x22,0xC0,0x9E,0x1D,0x43,0xA1,0xFF,\n    0x46,0x18,0xFA,0xA4,0x27,0x79,0x9B,0xC5,\n    0x84,0xDA,0x38,0x66,0xE5,0xBB,0x59,0x07,\n    0xDB,0x85,0x67,0x39,0xBA,0xE4,0x06,0x58,\n    0x19,0x47,0xA5,0xFB,0x78,0x26,0xC4,0x9A,\n    0x65,0x3B,0xD9,0x87,0x04,0x5A,0xB8,0xE6,\n    0xA7,0xF9,0x1B,0x45,0xC6,0x98,0x7A,0x24,\n    0xF8,0xA6,0x44,0x1A,0x99,0xC7,0x25,0x7B,\n    0x3A,0x64,0x86,0xD8,0x5B,0x05,0xE7,0xB9,\n    0x8C,0xD2,0x30,0x6E,0xED,0xB3,0x51,0x0F,\n    0x4E,0x10,0xF2,0xAC,0x2F,0x71,0x93,0xCD,\n    0x11,0x4F,0xAD,0xF3,0x70,0x2E,0xCC,0x92,\n    0xD3,0x8D,0x6F,0x31,0xB2,0xEC,0x0E,0x50,\n    0xAF,0xF1,0x13,0x4D,0xCE,0x90,0x72,0x2C,\n    0x6D,0x33,0xD1,0x8F,0x0C,0x52,0xB0,0xEE,\n    0x32,0x6C,0x8E,0xD0,0x53,0x0D,0xEF,0xB1,\n    0xF0,0xAE,0x4C,0x12,0x91,0xCF,0x2D,0x73,\n    0xCA,0x94,0x76,0x28,0xAB,0xF5,0x17,0x49,\n    0x08,0x56,0xB4,0xEA,0x69,0x37,0xD5,0x8B,\n    0x57,0x09,0xEB,0xB5,0x36,0x68,0x8A,0xD4,\n    0x95,0xCB,0x29,0x77,0xF4,0xAA,0x48,0x16,\n    0xE9,0xB7,0x55,0x0B,0x88,0xD6,0x34,0x6A,\n    0x2B,0x75,0x97,0xC9,0x4A,0x14,0xF6,0xA8,\n    0x74,0x2A,0xC8,0x96,0x15,0x4B,0xA9,0xF7,\n    0xB6,0xE8,0x0A,0x54,0xD7,0x89,0x6B,0x35\n};\n\nbyte crc8(byte *addr, byte len){\n  byte crc = 0;\n  while(len--){\n     crc = crc_table[*addr++ ^ crc]; \n  }\n return crc;\n}\n\nbyte checksum(byte *addr, byte len) {\n  byte sum = 0;\n  *addr++;\n\n  while(len--) {\n    sum = sum + *addr++;\n  }\n\n  return 256 - sum;\n}\n"
  },
  {
    "path": "src/esp8266-midea-dehumidifier/configFileHandling.ino",
    "content": "void saveConfig() {\n  DynamicJsonDocument json(512);\n  json[\"mqtt_server\"] = mqtt_server;\n  json[\"username\"] = username;\n  json[\"password\"] = password;\n\n  File configFile = SPIFFS.open(\"/config.json\", \"w\");\n  if (!configFile) {\n    return;\n  }\n\n  serializeJson(json, configFile);\n  configFile.close();\n}\n\nvoid loadConfig() {\n  if (SPIFFS.begin()) {\n\n    if (SPIFFS.exists(\"/config.json\")) {\n      File configFile = SPIFFS.open(\"/config.json\", \"r\");\n\n      if (configFile) {\n        const size_t size = configFile.size();\n        std::unique_ptr<char[]> buf(new char[size]);\n\n        configFile.readBytes(buf.get(), size);\n        DynamicJsonDocument json(512);\n\n        if (DeserializationError::Ok == deserializeJson(json, buf.get())) {\n          strcpy(mqtt_server, json[\"mqtt_server\"]);\n          strcpy(username, json[\"username\"]);\n          strcpy(password, json[\"password\"]);\n        }\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "src/esp8266-midea-dehumidifier/esp8266-midea-dehumidifier.ino",
    "content": "#include \"types.h\"\n#include \"wifi.h\"\n\n#include <ESP8266WiFi.h>\n#include <DNSServer.h>\n#include <ESP8266WebServer.h>\n#include <ArduinoJson.h>\n#include <WiFiManager.h>\n#include <PubSubClient.h>\n//#include <SoftwareSerial.h>\n#include <ArduinoOTA.h>\n#include <FS.h>\n\ndehumidifierState_t state;\n\nbyte serialRxBuf[255];\nbyte serialTxBuf[255];\nuint8_t mqttRetryCounter = 0;\n\n\nWiFiManager wifiManager;\nWiFiClient wifiClient;\nPubSubClient mqttClient;\n\nWiFiManagerParameter custom_mqtt_server(\"server\", \"mqtt server\", mqtt_server, sizeof(mqtt_server));\nWiFiManagerParameter custom_mqtt_user(\"user\", \"MQTT username\", username, sizeof(username));\nWiFiManagerParameter custom_mqtt_pass(\"pass\", \"MQTT password\", password, sizeof(password));\n\nunsigned long lastMqttConnectionAttempt = millis();\nconst long mqttConnectionInterval = 60000;\n\nunsigned long statusPollPreviousMillis = millis();\nconst long statusPollInterval = 30000;\n\nchar identifier[24];\n#define FIRMWARE_PREFIX \"esp8266-midea-dehumidifier\"\n#define AVAILABILITY_ONLINE \"online\"\n#define AVAILABILITY_OFFLINE \"offline\"\nchar MQTT_TOPIC_AVAILABILITY[128];\nchar MQTT_TOPIC_STATE[128];\nchar MQTT_TOPIC_COMMAND[128];\n\nchar MQTT_TOPIC_AUTOCONF_WIFI_SENSOR[128];\nchar MQTT_TOPIC_AUTOCONF_HUMIDITY_SENSOR[128];\n\n\nchar MQTT_TOPIC_AUTOCONF_FAN[128];\nchar MQTT_TOPIC_AUTOCONF_HUMIDIFIER[128];\n\n\n\n\nbool shouldSaveConfig = false;\n\nvoid saveConfigCallback () {\n  shouldSaveConfig = true;\n}\n\nvoid setup() {\n  Serial.begin(9600);\n\n  //Initializing with defaults until we have a status update\n  state.powerOn = false;\n  state.fanSpeed = low;\n  state.mode = setpoint;\n  state.humiditySetpoint = 55;\n  state.currentHumidity = 45;\n  state.errorCode = 0;\n\n  delay(3000);\n  updateAndSendNetworkStatus(false);\n\n\n  snprintf(identifier, sizeof(identifier), \"DEHUMIDIFIER-%X\", ESP.getChipId());\n  snprintf(MQTT_TOPIC_AVAILABILITY, 127, \"%s/%s/status\", FIRMWARE_PREFIX, identifier);\n  snprintf(MQTT_TOPIC_STATE, 127, \"%s/%s/state\", FIRMWARE_PREFIX, identifier);\n  snprintf(MQTT_TOPIC_COMMAND, 127, \"%s/%s/command\", FIRMWARE_PREFIX, identifier);\n\n  snprintf(MQTT_TOPIC_AUTOCONF_HUMIDITY_SENSOR, 127, \"homeassistant/sensor/%s/%s_humidity/config\", FIRMWARE_PREFIX, identifier);\n  snprintf(MQTT_TOPIC_AUTOCONF_WIFI_SENSOR, 127, \"homeassistant/sensor/%s/%s_wifi/config\", FIRMWARE_PREFIX, identifier);\n\n  snprintf(MQTT_TOPIC_AUTOCONF_FAN, 127, \"homeassistant/select/%s/%s_fan/config\", FIRMWARE_PREFIX, identifier);\n  snprintf(MQTT_TOPIC_AUTOCONF_HUMIDIFIER, 127, \"homeassistant/humidifier/%s/%s_dehumidifier/config\", FIRMWARE_PREFIX, identifier);\n\n\n  WiFi.hostname(identifier);\n\n  loadConfig();\n\n  setupWifi();\n  setupOTA();\n  mqttClient.setServer(mqtt_server, 1883);\n  mqttClient.setKeepAlive(10);\n  mqttClient.setBufferSize(2048);\n  mqttClient.setCallback(mqttCallback);\n\n  mqttReconnect();\n}\n\nvoid setupOTA() {\n\n  ArduinoOTA.onStart([]() {\n    //Serial.println(\"Start\");\n  });\n  ArduinoOTA.onEnd([]() {\n    //Serial.println(\"\\nEnd\");\n  });\n  ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) {\n    //Serial.printf(\"Progress: %u%%\\r\", (progress / (total / 100)));\n  });\n  ArduinoOTA.onError([](ota_error_t error) {\n    /*\n      Serial.printf(\"Error[%u]: \", error);\n      if (error == OTA_AUTH_ERROR) Serial.println(\"Auth Failed\");\n      else if (error == OTA_BEGIN_ERROR) Serial.println(\"Begin Failed\");\n      else if (error == OTA_CONNECT_ERROR) Serial.println(\"Connect Failed\");\n      else if (error == OTA_RECEIVE_ERROR) Serial.println(\"Receive Failed\");\n      else if (error == OTA_END_ERROR) Serial.println(\"End Failed\");\n    */\n  });\n\n  ArduinoOTA.setHostname(identifier);\n\n  //This is less of a security measure and more a accidential flash prevention\n  ArduinoOTA.setPassword(identifier);\n  ArduinoOTA.begin();\n}\n\n\nvoid loop() {\n  ArduinoOTA.handle();\n  handleUart();\n  mqttClient.loop();\n\n  if (statusPollInterval <= (millis() - statusPollPreviousMillis)) {\n    statusPollPreviousMillis = millis();\n    getStatus();\n  }\n\n  if (!mqttClient.connected() && (mqttConnectionInterval <= (millis() - lastMqttConnectionAttempt)) )  {\n    lastMqttConnectionAttempt = millis();\n    mqttReconnect();\n  }\n}\n\nvoid setupWifi() {\n  wifiManager.setDebugOutput(false);\n  wifiManager.setSaveConfigCallback(saveConfigCallback);\n\n  wifiManager.addParameter(&custom_mqtt_server);\n  wifiManager.addParameter(&custom_mqtt_user);\n  wifiManager.addParameter(&custom_mqtt_pass);\n\n  WiFi.hostname(identifier);\n  wifiManager.autoConnect(identifier);\n  mqttClient.setClient(wifiClient);\n\n  strcpy(mqtt_server, custom_mqtt_server.getValue());\n  strcpy(username, custom_mqtt_user.getValue());\n  strcpy(password, custom_mqtt_pass.getValue());\n\n  if (shouldSaveConfig) {\n    saveConfig();\n  } else {\n    //For some reason, the read values get overwritten in this function\n    //To combat this, we just reload the config\n    //This is most likely a logic error which could be fixed otherwise\n    loadConfig();\n  }\n}\n\nvoid resetWifiSettingsAndReboot() {\n  wifiManager.resetSettings();\n  updateAndSendNetworkStatus(false);\n  delay(3000);\n  ESP.restart();\n}\n\nvoid mqttReconnect()\n{\n  for (int attempt = 0; attempt < 3; ++attempt) {\n    if (mqttClient.connect(identifier, username, password, MQTT_TOPIC_AVAILABILITY, 1, true, AVAILABILITY_OFFLINE)) {\n      mqttClient.publish(MQTT_TOPIC_AVAILABILITY, AVAILABILITY_ONLINE, true);\n      updateAndSendNetworkStatus(true);\n      getStatus();\n      publishAutoConfig();\n\n      //Make sure to subscribe after polling the status so that we never execute commands with the default data\n      mqttClient.subscribe(MQTT_TOPIC_COMMAND);\n      break;\n    } else {\n      delay(5000);\n    }\n  }\n}\n\nboolean isMqttConnected() {\n  return mqttClient.connected();\n}\n\nvoid publishState() {\n  DynamicJsonDocument wifiJson(192);\n  DynamicJsonDocument stateJson(604);\n  char payload[256];\n\n  wifiJson[\"ssid\"] = WiFi.SSID();\n  wifiJson[\"ip\"] = WiFi.localIP().toString();\n  wifiJson[\"rssi\"] = WiFi.RSSI();\n\n  stateJson[\"state\"] = state.powerOn ? \"on\" : \"off\";\n  stateJson[\"humiditySetpoint\"] = state.humiditySetpoint;\n  stateJson[\"humidityCurrent\"] = state.currentHumidity;\n  stateJson[\"errorCode\"] = state.errorCode;\n\n  switch (state.fanSpeed) {\n    case low:\n      stateJson[\"fanSpeed\"] = \"low\";\n      break;\n    case medium:\n      stateJson[\"fanSpeed\"] = \"medium\";\n      break;\n    case high:\n      stateJson[\"fanSpeed\"] = \"high\";\n      break;\n  }\n\n  switch (state.mode) {\n    case setpoint:\n      stateJson[\"mode\"] = \"setpoint\";\n      break;\n    case continuous:\n      stateJson[\"mode\"] = \"continuous\";\n      break;\n    case smart:\n      stateJson[\"mode\"] = \"smart\";\n      break;\n    case clothesDrying:\n      stateJson[\"mode\"] = \"clothesDrying\";\n      break;\n  }\n\n  stateJson[\"wifi\"] = wifiJson.as<JsonObject>();\n\n  serializeJson(stateJson, payload);\n  mqttClient.publish(MQTT_TOPIC_STATE, payload, true);\n}\n\nvoid mqttCallback(char* topic, byte* payload, unsigned int length) {\n  if (strcmp(topic, MQTT_TOPIC_COMMAND) == 0) {\n    DynamicJsonDocument commandJson(256);\n    char payloadText[length + 1];\n\n    snprintf(payloadText, length + 1, \"%s\", payload);\n\n    DeserializationError err = deserializeJson(commandJson, payloadText);\n\n    if (!err) {\n      handleStateUpdateRequest(\n        commandJson[\"state\"].as<String>(),\n        commandJson[\"mode\"].as<String>(),\n        commandJson[\"fanSpeed\"].as<String>(),\n        commandJson[\"humiditySetpoint\"].as<byte>()\n      );\n\n      getStatus();\n    }\n  }\n}\n\nvoid publishAutoConfig() {\n  char mqttPayload[2048];\n  DynamicJsonDocument device(256);\n  DynamicJsonDocument autoconfPayload(1024);\n  StaticJsonDocument<64> identifiersDoc;\n  JsonArray identifiers = identifiersDoc.to<JsonArray>();\n\n  identifiers.add(identifier);\n\n  device[\"identifiers\"] = identifiers;\n  device[\"manufacturer\"] = \"Midea Group Co., Ltd.\";\n  device[\"model\"] = \"Generic Dehumidifier\";\n  device[\"name\"] = identifier;\n  device[\"sw_version\"] = \"2023.08.0\";\n\n\n  autoconfPayload[\"device\"] = device.as<JsonObject>();\n  autoconfPayload[\"availability_topic\"] = MQTT_TOPIC_AVAILABILITY;\n  autoconfPayload[\"state_topic\"] = MQTT_TOPIC_STATE;\n  autoconfPayload[\"name\"] = \"WiFi\";\n  autoconfPayload[\"value_template\"] = \"{{value_json.wifi.rssi}}\";\n  autoconfPayload[\"unique_id\"] = identifier + String(\"_wifi\");\n  autoconfPayload[\"unit_of_measurement\"] = \"dBm\";\n  autoconfPayload[\"json_attributes_topic\"] = MQTT_TOPIC_STATE;\n  autoconfPayload[\"json_attributes_template\"] = \"{\\\"ssid\\\": \\\"{{value_json.wifi.ssid}}\\\", \\\"ip\\\": \\\"{{value_json.wifi.ip}}\\\"}\";\n  autoconfPayload[\"icon\"] = \"mdi:wifi\";\n\n  serializeJson(autoconfPayload, mqttPayload);\n  mqttClient.publish(MQTT_TOPIC_AUTOCONF_WIFI_SENSOR, mqttPayload, true);\n\n  autoconfPayload.clear();\n\n\n  autoconfPayload[\"device\"] = device.as<JsonObject>();\n  autoconfPayload[\"availability_topic\"] = MQTT_TOPIC_AVAILABILITY;\n  autoconfPayload[\"state_topic\"] = MQTT_TOPIC_STATE;\n  autoconfPayload[\"name\"] = \"Humidity\";\n  autoconfPayload[\"device_class\"] = \"humidity\";\n  autoconfPayload[\"unit_of_measurement\"] = \"%\";\n  autoconfPayload[\"value_template\"] = \"{{value_json.humidityCurrent}}\";\n  autoconfPayload[\"unique_id\"] = identifier + String(\"_humidity\");\n\n  serializeJson(autoconfPayload, mqttPayload);\n  mqttClient.publish(MQTT_TOPIC_AUTOCONF_HUMIDITY_SENSOR, mqttPayload, true);\n\n  autoconfPayload.clear();\n\n\n  StaticJsonDocument<64> optionsDoc;\n  JsonArray speedOptions = optionsDoc.to<JsonArray>();\n\n  speedOptions.add(\"low\");\n  speedOptions.add(\"medium\");\n  speedOptions.add(\"high\");\n\n  autoconfPayload[\"device\"] = device.as<JsonObject>();\n  autoconfPayload[\"availability_topic\"] = MQTT_TOPIC_AVAILABILITY;\n  autoconfPayload[\"name\"] = \"Fan\";\n  autoconfPayload[\"unique_id\"] = identifier + String(\"_fan\");\n  autoconfPayload[\"icon\"] = \"mdi:fan\";\n\n  autoconfPayload[\"state_topic\"] = MQTT_TOPIC_STATE;\n  autoconfPayload[\"command_topic\"] = MQTT_TOPIC_COMMAND;\n\n  autoconfPayload[\"options\"] = speedOptions;\n  autoconfPayload[\"state_topic\"] = MQTT_TOPIC_STATE;\n  autoconfPayload[\"command_topic\"] = MQTT_TOPIC_COMMAND;\n  autoconfPayload[\"value_template\"] = \"{{value_json.fanSpeed}}\";\n  autoconfPayload[\"command_template\"] = \"{\\\"fanSpeed\\\": \\\"{{value}}\\\"}\";\n\n  serializeJson(autoconfPayload, mqttPayload);\n  mqttClient.publish(MQTT_TOPIC_AUTOCONF_FAN, mqttPayload, true);\n\n  autoconfPayload.clear();\n\n\n  autoconfPayload[\"device\"] = device.as<JsonObject>();\n  autoconfPayload[\"availability_topic\"] = MQTT_TOPIC_AVAILABILITY;\n  autoconfPayload[\"name\"] = \"Dehumidifier\";\n  autoconfPayload[\"unique_id\"] = identifier + String(\"_dehumidifier\");\n  autoconfPayload[\"device_class\"] = \"dehumidifier\";\n\n  autoconfPayload[\"max_humidity\"] = 85;\n  autoconfPayload[\"min_humidity\"] = 35;\n\n  autoconfPayload[\"state_topic\"] = MQTT_TOPIC_STATE;\n  autoconfPayload[\"state_value_template\"] = \"{\\\"state\\\": \\\"{{value_json.state}}\\\"}\";\n  autoconfPayload[\"payload_on\"] = \"{\\\"state\\\": \\\"on\\\"}\";\n  autoconfPayload[\"payload_off\"] = \"{\\\"state\\\": \\\"off\\\"}\";\n  autoconfPayload[\"command_topic\"] = MQTT_TOPIC_COMMAND;\n  autoconfPayload[\"state_value_template\"] = \"{\\\"state\\\": \\\"{{value_json.state}}\\\"}\";\n  autoconfPayload[\"payload_on\"] = \"{\\\"state\\\": \\\"on\\\"}\";\n  autoconfPayload[\"payload_off\"] = \"{\\\"state\\\": \\\"off\\\"}\";\n\n  StaticJsonDocument<64> modesDoc;\n  JsonArray modes = modesDoc.to<JsonArray>();\n\n  autoconfPayload[\"target_humidity_state_topic\"] = MQTT_TOPIC_STATE;\n  autoconfPayload[\"target_humidity_command_topic\"] = MQTT_TOPIC_COMMAND;\n  autoconfPayload[\"target_humidity_state_template\"] = \"{{value_json.humiditySetpoint | int}}\";\n  autoconfPayload[\"target_humidity_command_template\"] = \"{\\\"humiditySetpoint\\\": {{value | int}}}\";\n\n  modes.add(\"setpoint\");\n  modes.add(\"continuous\");\n  modes.add(\"smart\");\n  modes.add(\"clothesDrying\");\n\n  autoconfPayload[\"modes\"] = modes;\n  autoconfPayload[\"mode_state_topic\"] = MQTT_TOPIC_STATE;\n  autoconfPayload[\"mode_command_topic\"] = MQTT_TOPIC_COMMAND;\n  autoconfPayload[\"mode_state_template\"] = \"{{value_json.mode}}\";\n  autoconfPayload[\"mode_command_template\"] = \"{\\\"mode\\\": \\\"{{value}}\\\"}\";\n\n  serializeJson(autoconfPayload, mqttPayload);\n  mqttClient.publish(MQTT_TOPIC_AUTOCONF_HUMIDIFIER, mqttPayload, true);\n\n  autoconfPayload.clear();\n}\n"
  },
  {
    "path": "src/esp8266-midea-dehumidifier/serialCommunication.ino",
    "content": "byte networkStatus[20];\nbyte currentHeader[10];\nbyte getStatusCommand[21] = {\n  0x41, 0x81, 0x00, 0xff, 0x03, 0xff,\n  0x00, 0x02, 0x00, 0x00, 0x00, 0x00,\n  0x00, 0x00, 0x00, 0x00, 0x00, 0x00,\n  0x00, 0x00, 0x03\n};\nbyte setStatusCommand[25];\n\nvoid parseState() {\n  state.powerOn = serialRxBuf[11] & 0x01 > 0;\n  state.mode = (dehumMode_t)(serialRxBuf[12] & 0x0f);\n  state.fanSpeed = (fanSpeed_t)(serialRxBuf[13] & 0x7f);\n\n  state.humiditySetpoint = serialRxBuf[17] >= 100 ? 99 : serialRxBuf[17];\n  state.currentHumidity = serialRxBuf[26];\n  state.errorCode = serialRxBuf[31];\n\n  clearRxBuf();\n}\n\nvoid clearRxBuf() {\n  //Clear everything for the next message\n  memset(serialRxBuf, 0, sizeof(serialRxBuf));\n}\nvoid clearTxBuf() {\n  //Clear everything for the next message\n  memset(serialTxBuf, 0, sizeof(serialTxBuf));\n}\n\nvoid handleUart() {\n  if (Serial.available()) {\n    Serial.readBytesUntil('\\n', serialRxBuf, 250);\n    if (serialRxBuf[10] == 0xc8) {\n      parseState();\n      publishState();\n    } else if (serialRxBuf[10] == 0x63) {\n      updateAndSendNetworkStatus(isMqttConnected());\n    } else if ( //Yes, this is ugly :(\n      serialRxBuf[10] == 0x0 &&\n      serialRxBuf[50] == 0xaa &&\n      serialRxBuf[51] == 0x1e &&\n      serialRxBuf[52] == 0xa1 && //Appliance Type\n      serialRxBuf[58] == 0x03 &&\n      serialRxBuf[59] == 0x64 &&\n      serialRxBuf[61] == 0x01 &&\n      serialRxBuf[65] == 0x01\n    ) {\n      resetWifiSettingsAndReboot();\n    } else {\n      //Serial.print(\"Received msg with invalid type: \");\n      //Serial.println(serialRxBuf[10]);\n    }\n  }\n}\n\nvoid writeHeader(byte msgType, byte agreementVersion, byte packetLength) {\n  currentHeader[0] = 0xAA; //Sync Header\n  currentHeader[1] = 10 + packetLength + 1;\n  currentHeader[2] = 0xA1; //ApplianceType\n  currentHeader[3] = 0x00; //Frame sync check (not used)\n  currentHeader[4] = 0x00; //Reserved\n  currentHeader[5] = 0x00; //Reserved\n  currentHeader[6] = 0x00; //MsgId\n  currentHeader[7] = 0x00; //ProtocolVersion\n  currentHeader[8] = agreementVersion;\n  currentHeader[9] = msgType;\n}\n\nvoid handleStateUpdateRequest(String requestedState, String mode, String fanSpeed, byte humiditySetpoint) {\n  dehumidifierState_t newState;\n\n  newState.powerOn = state.powerOn;\n  newState.mode = state.mode;\n  newState.fanSpeed = state.fanSpeed;\n  newState.humiditySetpoint = state.humiditySetpoint;\n\n  if (requestedState == \"on\") {\n    newState.powerOn = true;\n  } else if (requestedState == \"off\") {\n    newState.powerOn = false;\n  }\n\n  if (mode == \"setpoint\") {\n    newState.mode = (dehumMode_t)setpoint;\n  } else if (mode == \"continuous\") {\n    newState.mode = (dehumMode_t)continuous;\n  } else if (mode == \"smart\") {\n    newState.mode = (dehumMode_t)smart;\n  } else if (mode == \"clothesDrying\") {\n    newState.mode = (dehumMode_t)clothesDrying;\n  }\n\n  if (fanSpeed == \"low\") {\n    newState.fanSpeed = (fanSpeed_t)low;\n  } else if (fanSpeed == \"medium\") {\n    newState.fanSpeed = (fanSpeed_t)medium;\n  } else if (fanSpeed == \"high\") {\n    newState.fanSpeed = (fanSpeed_t)high;\n  }\n\n  if (humiditySetpoint && humiditySetpoint >= 35 && humiditySetpoint <= 85) {\n    newState.humiditySetpoint = humiditySetpoint;\n  }\n\n  if ( //Only send if we have updates\n    newState.powerOn != state.powerOn ||\n    newState.mode != state.mode ||\n    newState.fanSpeed != state.fanSpeed ||\n    newState.humiditySetpoint != state.humiditySetpoint\n  ) {\n    updateSetStatus(\n      newState.powerOn,\n      newState.mode,\n      newState.fanSpeed,\n      newState.humiditySetpoint\n    );\n    sendSetStatus();\n\n    //Write back so that we don't swallow commands if there are many coming right after each other\n    //This may cause unexpected results if the connection to the unit doesn't work\n    state.powerOn = newState.powerOn;\n    state.mode = newState.mode;\n    state.fanSpeed = newState.fanSpeed;\n    state.humiditySetpoint = newState.humiditySetpoint;\n    delay(30);\n  }\n}\n\nvoid sendSetStatus() {\n  sendMessage(0x02, 0x03, 25, setStatusCommand);\n}\n\nvoid updateSetStatus(boolean powerOn, dehumMode_t dehumMode, fanSpeed_t fanSpeed, byte humiditySetpoint) {\n  memset(setStatusCommand, 0, sizeof(setStatusCommand));\n\n  setStatusCommand[0] = 0x48; //Magic\n  setStatusCommand[1] = powerOn ? 0x01 : 0x00;\n  setStatusCommand[2] = (byte)(dehumMode & 0x0f);\n  setStatusCommand[3] = (byte)fanSpeed;\n  setStatusCommand[7] = humiditySetpoint;\n}\n\nvoid updateAndSendNetworkStatus(boolean isConnected) {\n  updateNetworkStatus(isConnected);\n  sendMessage(0x0D, 0x03, 20, networkStatus);\n}\n\nvoid getStatus() {\n  sendMessage(0x03, 0x03, 21, getStatusCommand);\n}\n\nvoid updateNetworkStatus(boolean isConnected) {\n  memset(networkStatus, 0, sizeof(networkStatus));\n\n  // Byte 0: Module type:\n  // - 0x00 RF module\n  // - 0x01 WiFi module\n  networkStatus[0] = 0x01;\n\n  // Byte 1: WiFi module working mode:\n  // - 0x01 Client mode\n  // - 0x02 Configuration mode\n  // - 0x03 AP mode\n  networkStatus[1] = 0x01;\n\n  // Byte 2: WiFi signal strength\n  // - 0x00 No signal\n  // - 0x01 Weak\n  // - 0x02 Low\n  // - 0x03 Medium\n  // - 0x04 Strong\n  // - 0xFF WiFi is not supported\n  networkStatus[2] = 0x04;\n\n  // Byte 3-6: IPv4 address of client in reverse order\n  networkStatus[3] = 1;\n  networkStatus[4] = 0;\n  networkStatus[5] = 0;\n  networkStatus[6] = 127;\n\n  // Byte 7: RF Signal strength\n  // - 0x00, no signal\n  // - 0x01, weak\n  // - 0x02, low\n  // - 0x03, medium\n  // - 0x04, strong\n  // - 0xFF, RF is not supported\n  networkStatus[7] = 0xff;\n\n  // Byte 8: Router status\n  // - 0x00, wireless router is connected\n  // - 0x01, wireless router not connected\n  // - 0x02, connecting to a wireless router\n  // - 0x03, password verification error\n  // - 0x04, no wireless router found\n  // - 0x05, IP cannot be obtained\n  // - 0x06, wireless unstable\n  // - 0xFF, WI-FI failure\n  networkStatus[8] = isConnected ? 0x00 : 0x01;\n\n  // Byte 9: Cloud service connection status:\n  // - 0x00, connected to the cloud service center\n  // - 0x01, not connected to the cloud service center\n  // - 0x02, unstable internet connection\n  // - 0x03, domain name resolution error\n  // - 0x04, cloud service connection refused\n  // - 0x05, cloud service maintenance\n  // - 0xFF, cloud service failure\n  networkStatus[9] = isConnected ? 0x00 : 0x01;\n\n  // Byte 10: Direct LAN connection status\n  // - 0x00: No connection/connection has been disconnected\n  // - 0x01: connected/connected with mobile terminal\n  networkStatus[10] = 0x00;\n\n  // Byte 11 Number of TCP connections between the module and the mobile terminal\n  networkStatus[11] = 0x00;\n\n  // Byte 12 - 19 Reserved\n}\n\nvoid sendMessage(byte msgType, byte agreementVersion, byte payloadLength, byte *payload) {\n  clearTxBuf();\n\n  writeHeader(msgType, agreementVersion, payloadLength);\n  memcpy(serialTxBuf, currentHeader, 10);\n  memcpy(serialTxBuf + 10, payload, payloadLength);\n  serialTxBuf[10 + payloadLength] = crc8(serialTxBuf + 10, payloadLength);\n  serialTxBuf[10 + payloadLength + 1] = checksum(serialTxBuf, 10 + payloadLength + 1);\n\n  Serial.write(serialTxBuf, 10 + payloadLength + 2);\n}\n"
  },
  {
    "path": "src/esp8266-midea-dehumidifier/types.h",
    "content": "enum fanSpeed_t {\n  low = 40,\n  medium = 60,\n  high = 80\n};\n\nenum dehumMode_t {\n  setpoint = 1,\n  continuous = 2,\n  smart = 3,\n  clothesDrying = 4\n};\n\nstruct dehumidifierState_t { \n  boolean powerOn;\n  dehumMode_t mode;\n  fanSpeed_t fanSpeed;\n  byte humiditySetpoint;\n  byte currentHumidity;\n  byte errorCode;\n};\n"
  },
  {
    "path": "src/esp8266-midea-dehumidifier/wifi.h",
    "content": "char mqtt_server[80] = \"example.tld\";\n\nchar username[24] = \"\";\nchar password[24] = \"\";\n"
  }
]