Skip to content

Commit

Permalink
optimize the configuration
Browse files Browse the repository at this point in the history
  • Loading branch information
georgezhao2010 committed Sep 20, 2023
1 parent dc12eed commit a0f35cf
Show file tree
Hide file tree
Showing 9 changed files with 68 additions and 91 deletions.
83 changes: 41 additions & 42 deletions custom_components/midea_ac_lan/config_flow.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,9 @@
import voluptuous as vol
import os
try:
from homeassistant.helpers.json import save_json
except ImportError:
from homeassistant.util.json import save_json
import logging
from .const import (
DOMAIN,
Expand Down Expand Up @@ -25,17 +31,16 @@
CONF_CUSTOMIZE,
CONF_PASSWORD,
)
import homeassistant.helpers.config_validation as cv
from homeassistant.helpers.aiohttp_client import async_create_clientsession
from .midea.core.discover import discover
from .midea.core.cloud import get_midea_cloud
from .midea.core.device import MiedaDevice
from .midea_devices import MIDEA_DEVICES
import voluptuous as vol
import homeassistant.helpers.config_validation as cv

_LOGGER = logging.getLogger(__name__)

ADD_WAY = {"auto": "Auto", "by_ip": "By IP", "manual": "Manual", "list": "Just list appliances"}
ADD_WAY = {"discovery": "Discovery automatically", "manually": "Configure manually", "list": "List all appliances only"}
PROTOCOLS = {1: "V1", 2: "V2", 3: "V3"}
STORAGE_PATH = f".storage/{DOMAIN}"

Expand All @@ -61,6 +66,12 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
for item in unsorted:
supports[item[0]] = item[1]

def _save_device_token(self, device_id, protocol, token, key):
os.makedirs(self.hass.config.path(STORAGE_PATH), exist_ok=True)
record_file = self.hass.config.path(f"{STORAGE_PATH}/{device_id}.json")
json_data = {"protocol": f"v{protocol}", "token": token, "key": key}
save_json(record_file, json_data)

def _get_configured_account(self):
for entry in self._async_current_entries():
if entry.data.get(CONF_TYPE) == CONF_ACCOUNT:
Expand All @@ -79,19 +90,17 @@ def _already_configured(self, device_id, ip_address):

async def async_step_user(self, user_input=None, error=None):
if user_input is not None:
if user_input["action"] == "auto":
return await self.async_step_discover()
elif user_input["action"] == "manual":
if user_input["action"] == "discovery":
return await self.async_step_discovery()
elif user_input["action"] == "manually":
self.found_device = {}
return await self.async_step_manual()
elif user_input["action"] == "by_ip":
return await self.async_step_byip()
return await self.async_step_manually()
else:
return await self.async_step_list()
return self.async_show_form(
step_id="user",
data_schema=vol.Schema({
vol.Required("action", default="auto"): vol.In(ADD_WAY)
vol.Required("action", default="discovery"): vol.In(ADD_WAY)
}),
errors={"base": error} if error else None
)
Expand Down Expand Up @@ -130,26 +139,6 @@ async def async_step_login(self, user_input=None, error=None):
errors={"base": error} if error else None
)

async def async_step_discover(self, user_input=None, error=None):
self._account, self._password, self._server = self._get_configured_account()
if self._account is None:
return await self.async_step_login()
if user_input is not None:
self.devices = discover(self.supports.keys())
self.available_device = {}
for device_id, device in self.devices.items():
if not self._already_configured(device_id, device.get(CONF_IP_ADDRESS)):
self.available_device[device_id] = \
f"{device_id} ({self.supports.get(device.get(CONF_TYPE))})"
if len(self.available_device) > 0:
return await self.async_step_auto()
else:
return await self.async_step_user(error="no_devices")
return self.async_show_form(
step_id="discover",
errors={"base": error} if error else None
)

async def async_step_list(self, user_input=None, error=None):
all_devices = discover()
if len(all_devices) > 0:
Expand All @@ -167,12 +156,16 @@ async def async_step_list(self, user_input=None, error=None):
errors={"base": error} if error else None
)

async def async_step_byip(self, user_input=None, error=None):
async def async_step_discovery(self, user_input=None, error=None):
self._account, self._password, self._server = self._get_configured_account()
if self._account is None:
return await self.async_step_login()
if user_input is not None:
self.devices = discover(self.supports.keys(), ip_address=user_input[CONF_IP_ADDRESS])
if user_input[CONF_IP_ADDRESS].lower() == "auto":
ip_address = None
else:
ip_address = user_input[CONF_IP_ADDRESS]
self.devices = discover(self.supports.keys(), ip_address=ip_address)
self.available_device = {}
for device_id, device in self.devices.items():
if not self._already_configured(device_id, device.get(CONF_IP_ADDRESS)):
Expand All @@ -181,11 +174,11 @@ async def async_step_byip(self, user_input=None, error=None):
if len(self.available_device) > 0:
return await self.async_step_auto()
else:
return await self.async_step_byip(error="no_devices")
return await self.async_step_discovery(error="no_devices")
return self.async_show_form(
step_id="byip",
step_id="discovery",
data_schema=vol.Schema({
vol.Required(CONF_IP_ADDRESS): str
vol.Required(CONF_IP_ADDRESS, default="auto"): str
}),
errors={"base": error} if error else None
)
Expand Down Expand Up @@ -227,7 +220,7 @@ async def async_step_auto(self, user_input=None, error=None):
CONF_KEY: key["key"],
}
dm.close_socket()
return await self.async_step_manual()
return await self.async_step_manually()
return await self.async_step_auto(error="connect_error")
return await self.async_step_auto(error="login_failed")
else:
Expand All @@ -239,7 +232,7 @@ async def async_step_auto(self, user_input=None, error=None):
CONF_PORT: device.get(CONF_PORT),
CONF_MODEL: device.get(CONF_MODEL),
}
return await self.async_step_manual()
return await self.async_step_manually()
return self.async_show_form(
step_id="auto",
data_schema=vol.Schema({
Expand All @@ -249,7 +242,7 @@ async def async_step_auto(self, user_input=None, error=None):
errors={"base": error} if error else None
)

async def async_step_manual(self, user_input=None, error=None):
async def async_step_manually(self, user_input=None, error=None):
if user_input is not None:
self.found_device = {
CONF_DEVICE_ID: user_input[CONF_DEVICE_ID],
Expand All @@ -265,9 +258,9 @@ async def async_step_manual(self, user_input=None, error=None):
bytearray.fromhex(user_input[CONF_TOKEN])
bytearray.fromhex(user_input[CONF_KEY])
except ValueError:
return await self.async_step_manual(error="invalid_token")
return await self.async_step_manually(error="invalid_token")
if user_input[CONF_PROTOCOL] == 3 and (len(user_input[CONF_TOKEN]) == 0 or len(user_input[CONF_KEY]) == 0):
return await self.async_step_manual(error="invalid_token")
return await self.async_step_manually(error="invalid_token")
dm = MiedaDevice(
name="",
device_id=user_input[CONF_DEVICE_ID],
Expand All @@ -282,6 +275,12 @@ async def async_step_manual(self, user_input=None, error=None):
)
if dm.connect(refresh_status=False):
dm.close_socket()
self._save_device_token(
user_input[CONF_DEVICE_ID],
user_input[CONF_PROTOCOL],
user_input[CONF_TOKEN],
user_input[CONF_KEY]
)
return self.async_create_entry(
title=f"{user_input[CONF_NAME]}",
data={
Expand All @@ -296,9 +295,9 @@ async def async_step_manual(self, user_input=None, error=None):
CONF_KEY: user_input[CONF_KEY],
})
else:
return await self.async_step_manual(error="config_incorrect")
return await self.async_step_manually(error="config_incorrect")
return self.async_show_form(
step_id="manual",
step_id="manually",
data_schema=vol.Schema({
vol.Required(
CONF_NAME,
Expand Down
2 changes: 1 addition & 1 deletion custom_components/midea_ac_lan/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@
"iot_class": "local_push",
"issue_tracker": "https://github.com/georgezhao2010/midea_ac_lan/issues",
"requirements": [],
"version": "v0.3.19"
"version": "v0.3.21"
}
12 changes: 4 additions & 8 deletions custom_components/midea_ac_lan/translations/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"data": {
"way": "Adding appliances"
},
"description": "Choose 'Auto' or 'Manual' to add a new appliance",
"description": "Choose the way to add a appliance",
"title": "Add new appliance"
},
"login": {
Expand All @@ -24,12 +24,8 @@
"description": "Login and storage your Midea account only for getting the appliance info.\nYou can remove this configuration after all appliance configured.",
"title": "Login"
},
"discover": {
"description": "Discover new Midea devices?",
"title": "New appliance discover"
},
"byip": {
"description": "Input IP address for device",
"discovery": {
"description": "IP address for device, enter \"auto\" to discover automatically",
"title": "By IP",
"data": {
"ip_address": "IP address"
Expand All @@ -46,7 +42,7 @@
"description": "Choose a appliance to add",
"title": "New appliance found"
},
"manual": {
"manually": {
"data": {
"name": "Name (e.g. Living room AC)",
"device_id": "Appliance code",
Expand Down
12 changes: 4 additions & 8 deletions custom_components/midea_ac_lan/translations/fr.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"data": {
"way": "Ajout d'appareil"
},
"description": "Choisissez 'Auto' ou 'Manuel' pour ajouter un nouvel appareil",
"description": "Choisissez comment ajouter des appareils",
"title": "Ajouter un nouvel appareil"
},
"login": {
Expand All @@ -24,12 +24,8 @@
"description": "Login and storage your Midea account only for getting the appliance info.\nYou can remove this configuration after all appliance configured.",
"title": "Login"
},
"discover": {
"description": "Découvrir de nouveaux appareils Midea ?",
"title": "Découverte d'un nouvel appareil"
},
"byip": {
"description": "Saisissez l'adresse IP de l'appareil",
"discovery": {
"description": "Saisissez l'adresse IP de l'appareil, entrez \"auto\" pour découvrir automatiquement.",
"title": "Par IP",
"data": {
"ip_address": "Adresse IP"
Expand All @@ -46,7 +42,7 @@
"description": "Choisissez un appareil à ajouter",
"title": "Nouvel appareil trouvé"
},
"manual": {
"manually": {
"data": {
"name": "Nom (ex: Clim Salon)",
"device_id": "Code appareil",
Expand Down
12 changes: 4 additions & 8 deletions custom_components/midea_ac_lan/translations/hu.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"data": {
"way": "Eszközök hozzáadása"
},
"description": "Válassza az 'Auto' vagy 'Manual' opciót új eszköz hozzáadásához",
"description": "Válassza ki az eszközök hozzáadásának módját",
"title": "Új eszköz hozzáadása"
},
"login": {
Expand All @@ -24,12 +24,8 @@
"description": "Login and storage your Midea account only for getting the appliance info.\nYou can remove this configuration after all appliance configured.",
"title": "Login"
},
"discover": {
"description": "Új Midea eszközöket keres?",
"title": "Új eszköz keresése"
},
"byip": {
"description": "Adja meg az eszköz IP címét",
"discovery": {
"description": "Adja meg az eszköz IP címét, Írja be az \"auto\" kifejezést az automatikus kereséshez",
"title": "IP alapján",
"data": {
"ip_address": "IP cím"
Expand All @@ -46,7 +42,7 @@
"description": "Válassza ki a hozzáadandó eszközt",
"title": "Új eszköz található"
},
"manual": {
"manually": {
"data": {
"name": "Név (pl. Nappali légkondicionáló)",
"device_id": "Eszköz kód",
Expand Down
12 changes: 4 additions & 8 deletions custom_components/midea_ac_lan/translations/ru.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"data": {
"way": "Добавление устройства"
},
"description": "Чтобы добавить новое устройство, выберите 'Авто' или 'Вручную'",
"description": "Выберите способ добавления устройств",
"title": "Добавить новое устройство"
},
"login": {
Expand All @@ -24,12 +24,8 @@
"description": "Login and storage your Midea account only for getting the appliance info.\nYou can remove this configuration after all appliance configured.",
"title": "Login"
},
"discover": {
"description": "Выполнять поиск новых устройств Midea?",
"title": "Поиск новых устройств"
},
"byip": {
"description": "Введите IP-адрес устройства",
"discovery": {
"description": "Введите IP-адрес устройства, введите \"auto\", чтобы автоматически обнаружить",
"title": "По IP",
"data": {
"ip_address": "IP-адрес"
Expand All @@ -46,7 +42,7 @@
"description": "Выберите устройство для добавления",
"title": "Найдено новое устройство"
},
"manual": {
"manually": {
"data": {
"name": "Название (например, Кондиционер в гостиной)",
"device_id": "Идентификатор устройства",
Expand Down
12 changes: 4 additions & 8 deletions custom_components/midea_ac_lan/translations/sk.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
"data": {
"way": "Pridávanie spotrebičov"
},
"description": "Ak chcete pridať nový spotrebič, vyberte možnosť „Automaticky“ alebo „Manuálne“.",
"description": "Vyberte spôsob pridávania zariadení",
"title": "Pridať nový spotrebič"
},
"login": {
Expand All @@ -24,12 +24,8 @@
"description": "Login and storage your Midea account only for getting the appliance info.\nYou can remove this configuration after all appliance configured.",
"title": "Login"
},
"discover": {
"description": "Objaviť nové zariadenia Midea?",
"title": "Objavte nové zariadenie"
},
"byip": {
"description": "Zadajte IP adresu pre zariadenie",
"discovery": {
"description": "Zadajte IP adresu pre zariadenie, zadajte \"auto\" pre automatické vyhľadávanie",
"title": "Podľa IP",
"data": {
"ip_address": "IP adresa"
Expand All @@ -46,7 +42,7 @@
"description": "Vyberte zariadenie, ktoré chcete pridať",
"title": "Našiel sa nový spotrebič"
},
"manual": {
"manually": {
"data": {
"name": "Názov (napr. AC obývačka)",
"device_id": "Kód spotrebiča",
Expand Down
10 changes: 3 additions & 7 deletions custom_components/midea_ac_lan/translations/zh-Hans.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,8 @@
"description": "登录并保存你的美的账户,仅用于获取添加设备时设备信息\n添加设备完成后,你可以删除该配置",
"title": "登录"
},
"discover": {
"description": "要查找并添加新的美的设备吗?",
"title": "查找设备"
},
"byip": {
"description": "输入设备的IP地址",
"discovery": {
"description": "输入设备的IP地址, 输入\"auto\"自动搜索设备",
"title": "指定IP",
"data": {
"ip_address": "IP地址"
Expand All @@ -46,7 +42,7 @@
"description": "选择设备并添加",
"title": "发现新设备"
},
"manual": {
"manually": {
"data": {
"name": "名称(如客厅空调)",
"device_id": "设备编号",
Expand Down
4 changes: 3 additions & 1 deletion hacs.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
{
"name": "Midea AC LAN",
"render_readme": true,
"homeassistant": 2022.5
"homeassistant": 2022.5,
"zip_release": true,
"filename": "mieda_ac_lan.zip"

This comment has been minimized.

Copy link
@Kissycat

Kissycat Aug 31, 2024

不是,合着这玩意儿没对过呗,midea拼成mieda了啊喂,这一年得有多少人下载404呀 @georgezhao2010

}

0 comments on commit a0f35cf

Please sign in to comment.