Skip to content

Commit 9719ced

Browse files
committed
add stop call so when unloading integration it can be stopped properly, start tracking iotToken error, use cloud client token instead of self._iot_token
1 parent 14781b7 commit 9719ced

File tree

4 files changed

+39
-9
lines changed

4 files changed

+39
-9
lines changed

pymammotion/mammotion/devices/mammotion.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,13 @@ def __init__(self) -> None:
4141
self.devices: dict[str, MammotionMowerDeviceManager] = {}
4242
self.rtk_devices: dict[str, MammotionRTKDeviceManager] = {}
4343

44+
async def stop(self) -> None:
45+
for mower in self.devices.values():
46+
if cloud := mower.cloud:
47+
cloud.stop()
48+
if ble := mower.ble:
49+
await ble.stop()
50+
4451
def _should_disconnect_mqtt(self, device_for_removal: AbstractDeviceManager) -> bool:
4552
"""Check if MQTT connection should be disconnected.
4653
@@ -128,7 +135,7 @@ async def remove_device(self, name: str) -> None:
128135
if device_for_removal.cloud:
129136
if self._should_disconnect_mqtt(device_for_removal):
130137
await loop.run_in_executor(None, device_for_removal.cloud.mqtt.disconnect)
131-
await device_for_removal.cloud.stop()
138+
device_for_removal.cloud.stop()
132139

133140
if device_for_removal.ble:
134141
await device_for_removal.ble.stop()
@@ -144,7 +151,7 @@ async def remove_rtk_device(self, name: str) -> None:
144151
if device_for_removal.cloud:
145152
if self._should_disconnect_mqtt(device_for_removal):
146153
await loop.run_in_executor(None, device_for_removal.cloud.mqtt.disconnect)
147-
await device_for_removal.cloud.stop()
154+
device_for_removal.cloud.stop()
148155

149156
if device_for_removal.ble:
150157
await device_for_removal.ble.stop()
@@ -433,6 +440,12 @@ async def login(self, account: str, password: str) -> CloudIOTGateway:
433440
await self.connect_iot(cloud_client)
434441
return cloud_client
435442

443+
async def stop(self) -> None:
444+
await self.device_manager.stop()
445+
for mqtt in self.mqtt_list.values():
446+
if mqtt.is_connected():
447+
mqtt.disconnect()
448+
436449
@staticmethod
437450
async def connect_iot(cloud_client: CloudIOTGateway) -> None:
438451
"""Connect to aliyun cloud and fetch device info."""

pymammotion/mammotion/devices/mammotion_cloud.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,14 @@ async def _parse_mqtt_response(self, topic: str, payload: dict, iot_id: str) ->
126126
payload (dict): The payload data of the MQTT message.
127127
128128
"""
129+
if topic.endswith("/app/down/account/bind_reply"):
130+
code = payload.get("code", 0)
131+
if code != 200:
132+
_LOGGER.error("Failed to bind account: %s", payload)
133+
# TODO send message to re login to aliyun mqtt
134+
self._disconnect_error = payload
135+
return
136+
129137
if topic.endswith("/app/down/thing/events"):
130138
_LOGGER.debug("Thing event received")
131139
event = ThingEventMessage.from_dicts(payload)
@@ -233,9 +241,11 @@ async def on_disconnect(self) -> None:
233241
async def on_connect(self) -> None:
234242
"""On connect callback"""
235243

236-
async def stop(self) -> None:
244+
def stop(self) -> None:
237245
"""Stop all tasks and disconnect."""
238246
# self._mqtt._mqtt_client.unsubscribe()
247+
if self.mqtt.is_connected():
248+
self._mqtt.disconnect()
239249
self.stopped = True
240250

241251
async def start(self) -> None:

pymammotion/mqtt/aliyun_mqtt.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,6 @@ def __init__(
4949
self._product_key = product_key
5050
self._device_name = device_name
5151
self._device_secret = device_secret
52-
self._iot_token = iot_token
5352
self._mqtt_username = f"{device_name}&{product_key}"
5453
# linkkit provides the correct MQTT service for all of this and uses paho under the hood
5554
if client_id is None:
@@ -81,6 +80,12 @@ def __init__(
8180
self._linkkit_client.on_topic_message = self._thing_on_topic_message
8281
self._mqtt_host = f"{self._product_key}.iot-as-mqtt.{region_id}.aliyuncs.com"
8382

83+
@property
84+
def iot_token(self) -> str:
85+
if authcode_response := self._cloud_client.session_by_authcode_response.data:
86+
return authcode_response.iotToken
87+
return ""
88+
8489
def connect_async(self) -> None:
8590
"""Connect async to MQTT Server."""
8691
logger.info("Connecting...")
@@ -129,7 +134,7 @@ def _thing_on_thing_enable(self, user_data) -> None:
129134
"id": "msgid1",
130135
"version": "1.0",
131136
"request": {"clientId": self._mqtt_username},
132-
"params": {"iotToken": self._iot_token},
137+
"params": {"iotToken": self.iot_token},
133138
}
134139
),
135140
)

pymammotion/mqtt/linkkit/linkkit.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030
import sys
3131
import threading
3232
import time
33+
from typing import Any
3334
import urllib.parse
3435
import urllib.request
3536

@@ -1189,19 +1190,19 @@ def destruct(self) -> None:
11891190
def destroy(self) -> None:
11901191
self.destruct()
11911192

1192-
def check_state(self):
1193+
def check_state(self) -> LinkKitState:
11931194
return self.__linkkit_state
11941195

11951196
@staticmethod
1196-
def __generate_random_str(randomlength=16):
1197+
def __generate_random_str(randomlength: int = 16) -> str:
11971198
"""Generate radom string"""
11981199
random_str = ""
11991200
for i in range(randomlength):
12001201
random_str += random.choice(string.digits + string.ascii_letters)
12011202
return random_str
12021203

12031204
# 基于HTTPS的一型一密预注册
1204-
def __dynamic_register_device(self):
1205+
def __dynamic_register_device(self) -> tuple[int, Any] | None:
12051206
pk = self.__product_key
12061207
ps = self.__product_secret
12071208
dn = self.__device_name
@@ -1222,8 +1223,9 @@ def __dynamic_register_device(self):
12221223
return 0, reply_obj_data["deviceSecret"]
12231224
else:
12241225
return 1, reply_obj["message"]
1226+
return None
12251227

1226-
def __config_mqtt_client_internal(self):
1228+
def __config_mqtt_client_internal(self) -> None:
12271229
self.__link_log.info("start connect")
12281230

12291231
timestamp = str(int(time.time()))

0 commit comments

Comments
 (0)