Skip to content

Commit 5c16dea

Browse files
authored
Merge pull request #412 from krahabb/dev_5_0
Release Moonlight.0.3
2 parents 8a65f61 + c0fdefb commit 5c16dea

File tree

14 files changed

+135
-159
lines changed

14 files changed

+135
-159
lines changed

.devcontainer/devcontainer.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
"python.analysis.autoSearchPaths": false,
1717
"python.formatting.provider": "black",
1818
"python.formatting.blackPath": "/usr/local/py-utils/bin/black",
19+
"python.experiments.optOutFrom": ["pythonTestAdapter"],
1920
"editor.formatOnPaste": false,
2021
"editor.formatOnSave": true,
2122
"editor.formatOnType": true,

.vscode/settings.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,6 @@
1616
"tests"
1717
],
1818
"[python]": {
19-
"editor.defaultFormatter": "ms-python.vscode-pylance"
19+
"editor.defaultFormatter": "ms-python.black-formatter"
2020
}
2121
}

custom_components/meross_lan/__init__.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -338,10 +338,6 @@ def get(hass: HomeAssistant) -> MerossApi:
338338
Loggable.hass = hass
339339

340340
async def _async_unload_merossapi(_event) -> None:
341-
for device in MerossApi.active_devices():
342-
await device.async_shutdown()
343-
for profile in MerossApi.active_profiles():
344-
await profile.async_shutdown()
345341
await api.async_terminate()
346342
Loggable.api = None # type: ignore
347343
Loggable.hass = None # type: ignore
@@ -446,10 +442,10 @@ async def _async_device_request(device: MerossDevice):
446442
await MerossHttpClient(
447443
host,
448444
key or self.key,
449-
async_get_clientsession(self.hass),
445+
None,
450446
self, # type: ignore (self almost duck-compatible with logging.Logger)
451447
self.VERBOSE,
452-
).async_request_message(request)
448+
).async_request_raw(request.json())
453449
or {}
454450
)
455451
except Exception as exception:
@@ -498,7 +494,12 @@ def attach_mqtt(self, device: MerossDevice):
498494
async def async_terminate(self):
499495
"""complete shutdown when HA exits. See self.async_shutdown for differences"""
500496
self.hass.services.async_remove(mlc.DOMAIN, mlc.SERVICE_REQUEST)
497+
for device in MerossApi.active_devices():
498+
await device.async_shutdown()
499+
for profile in MerossApi.active_profiles():
500+
await profile.async_shutdown()
501501
await super().async_shutdown()
502+
await MerossHttpClient.async_shutdown_session()
502503
self._mqtt_connection = None
503504

504505
def build_device(self, device_id: str, config_entry: ConfigEntry) -> MerossDevice:
@@ -648,7 +649,7 @@ async def async_setup_entry(hass: HomeAssistant, config_entry: ConfigEntry):
648649
await api.entry_update_listener(hass, config_entry)
649650
await api.async_setup_entry(hass, config_entry)
650651
return True
651-
652+
652653
case _:
653654
raise ConfigEntryError(
654655
f"Unknown configuration type (entry_id:{config_entry.entry_id} title:'{config_entry.title}')"

custom_components/meross_lan/config_flow.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@
1414
from homeassistant.const import CONF_ERROR
1515
from homeassistant.data_entry_flow import FlowHandler, callback
1616
from homeassistant.helpers import config_validation as cv, device_registry as dr
17-
from homeassistant.helpers.aiohttp_client import async_get_clientsession
1817
from homeassistant.helpers.selector import selector
1918
import voluptuous as vol
2019

@@ -441,7 +440,7 @@ async def _async_http_discovery(
441440
self._httpclient = _httpclient = MerossHttpClient(
442441
host,
443442
key,
444-
async_get_clientsession(self.hass),
443+
None,
445444
api, # type: ignore (api almost duck-compatible with logging.Logger)
446445
api.VERBOSE,
447446
)

custom_components/meross_lan/manifest.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,5 @@
1818
"/appliance/+/publish"
1919
],
2020
"requirements": [],
21-
"version": "5.0.2"
21+
"version": "5.0.3"
2222
}

custom_components/meross_lan/meross_device.py

Lines changed: 33 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,9 @@
1111
import weakref
1212
from zoneinfo import ZoneInfo
1313

14-
from aiohttp import ServerDisconnectedError
14+
import aiohttp
1515
from homeassistant.core import callback
1616
from homeassistant.helpers import device_registry as dr
17-
from homeassistant.helpers.aiohttp_client import async_get_clientsession
1817
from homeassistant.util import dt as dt_util
1918
import voluptuous as vol
2019

@@ -1039,7 +1038,7 @@ async def async_http_request_raw(
10391038
self.TRACE_TX,
10401039
)
10411040
try:
1042-
response = await http.async_request_message(request)
1041+
response = await http.async_request_raw(request.json())
10431042
self.device_response_size_min = max(
10441043
self.device_response_size_min, len(response.json())
10451044
)
@@ -1104,13 +1103,13 @@ async def async_http_request_raw(
11041103
ProtocolSensor.ATTR_HTTP
11051104
)
11061105
elif namespace is mc.NS_APPLIANCE_CONTROL_UNBIND:
1107-
if isinstance(exception, ServerDisconnectedError):
1106+
if isinstance(exception, aiohttp.ServerDisconnectedError):
11081107
# this is expected when issuing the UNBIND
11091108
# so this is an indication we're dead
11101109
self._set_offline()
11111110
return None
11121111
elif namespace is mc.NS_APPLIANCE_CONTROL_MULTIPLE:
1113-
if isinstance(exception, ServerDisconnectedError):
1112+
if isinstance(exception, aiohttp.ServerDisconnectedError):
11141113
# this happens (instead of JSONDecodeError)
11151114
# on my msl120. I guess the (older) fw behaves
11161115
# differently than those responding incomplete json.
@@ -1129,8 +1128,14 @@ async def async_http_request_raw(
11291128
)
11301129
return None
11311130

1132-
if isinstance(exception, asyncio.TimeoutError):
1131+
if isinstance(exception, asyncio.TimeoutError) or isinstance(
1132+
exception, aiohttp.ServerTimeoutError
1133+
):
11331134
return None
1135+
1136+
# for any other exception we could guess the device
1137+
# is stalling a bit so we just wait a bit before re-issuing
1138+
await asyncio.sleep(0.5)
11341139
else:
11351140
return None
11361141

@@ -1326,7 +1331,7 @@ async def _async_polling_callback(self, namespace: str):
13261331
self._timezone_next_check = (
13271332
epoch + PARAM_TIMEZONE_CHECK_NOTOK_PERIOD
13281333
)
1329-
if self.device_timedelta < PARAM_TIMESTAMP_TOLERANCE:
1334+
if abs(self.device_timedelta) < PARAM_TIMESTAMP_TOLERANCE:
13301335
with self.exception_warning("_check_device_timerules"):
13311336
if self._check_device_timerules():
13321337
# timezone trans not good..fix and check again soon
@@ -1356,7 +1361,9 @@ async def _async_polling_callback(self, namespace: str):
13561361
ns_all_response = await self.async_http_request(*ns_all)
13571362

13581363
if ns_all_response:
1359-
self.polling_strategies[mc.NS_APPLIANCE_SYSTEM_ALL].response_size = len(ns_all_response.json())
1364+
self.polling_strategies[
1365+
mc.NS_APPLIANCE_SYSTEM_ALL
1366+
].response_size = len(ns_all_response.json())
13601367
await self._async_request_updates(epoch, mc.NS_APPLIANCE_SYSTEM_ALL)
13611368
else:
13621369
if self._polling_delay < PARAM_HEARTBEAT_PERIOD:
@@ -1503,11 +1510,7 @@ def _check_protocol(self):
15031510
self.sensor_protocol.update_attr_inactive(ProtocolSensor.ATTR_HTTP)
15041511
else:
15051512
if host := self.host:
1506-
self._http = MerossHttpClient(
1507-
host,
1508-
self.key,
1509-
async_get_clientsession(self.hass),
1510-
)
1513+
self._http = MerossHttpClient(host, self.key)
15111514

15121515
if conf_protocol is CONF_PROTOCOL_AUTO:
15131516
# When using CONF_PROTOCOL_AUTO we try to use our 'preferred' (pref_protocol)
@@ -1570,21 +1573,19 @@ def _receive(self, epoch: float, message: MerossResponse):
15701573
# We ignore delays below PARAM_TIMESTAMP_TOLERANCE since
15711574
# we'll always be a bit late in processing
15721575
self.device_timestamp = header[mc.KEY_TIMESTAMP]
1573-
device_timedelta = epoch - self.device_timestamp
1574-
if abs(device_timedelta) > PARAM_TIMESTAMP_TOLERANCE:
1575-
if (
1576-
abs(self.device_timedelta - device_timedelta)
1577-
> PARAM_TIMESTAMP_TOLERANCE
1578-
):
1579-
# big step so we're not averaging
1580-
self.device_timedelta = device_timedelta
1581-
else: # average the sampled timedelta
1582-
self.device_timedelta = (
1583-
4 * self.device_timedelta + device_timedelta
1584-
) / 5
1585-
self._config_device_timestamp(epoch)
1586-
else:
1587-
self.device_timedelta = 0
1576+
self.device_timedelta = (
1577+
9 * self.device_timedelta + (epoch - self.device_timestamp)
1578+
) / 10
1579+
if abs(self.device_timedelta) > PARAM_TIMESTAMP_TOLERANCE:
1580+
if not self._config_device_timestamp(epoch):
1581+
if (epoch - self.device_timedelta_log_epoch) > 604800: # 1 week lockout
1582+
self.device_timedelta_log_epoch = epoch
1583+
self.log(
1584+
self.WARNING,
1585+
"Incorrect timestamp: %d seconds behind HA (%d on average)",
1586+
int(epoch - self.device_timestamp),
1587+
int(self.device_timedelta),
1588+
)
15881589

15891590
if self.isEnabledFor(self.DEBUG):
15901591
# it appears sometimes the devices
@@ -1746,11 +1747,7 @@ def _handle_Appliance_System_All(self, header: dict, payload: dict):
17461747
if _http := self._http:
17471748
_http.host = host
17481749
else:
1749-
self._http = MerossHttpClient(
1750-
host,
1751-
self.key,
1752-
async_get_clientsession(self.hass),
1753-
)
1750+
self._http = MerossHttpClient(host, self.key)
17541751

17551752
if self.conf_protocol is CONF_PROTOCOL_AUTO:
17561753
if self._mqtt_active:
@@ -1814,18 +1811,12 @@ def _config_device_timestamp(self, epoch):
18141811
# the procedure too often
18151812
self.mqtt_request(*request_push(mc.NS_APPLIANCE_SYSTEM_CLOCK))
18161813
self.device_timedelta_config_epoch = epoch
1817-
return
1814+
return True
18181815
if last_config_delay < 30:
18191816
# 30 sec 'deadzone' where we allow the timestamp
18201817
# transaction to complete (should really be like few seconds)
1821-
return
1822-
if (epoch - self.device_timedelta_log_epoch) > 604800: # 1 week lockout
1823-
self.device_timedelta_log_epoch = epoch
1824-
self.log(
1825-
self.WARNING,
1826-
"Incorrect timestamp: %d seconds behind HA",
1827-
int(self.device_timedelta),
1828-
)
1818+
return True
1819+
return False
18291820

18301821
def _check_device_timerules(self) -> bool:
18311822
"""

0 commit comments

Comments
 (0)