Skip to content

Commit

Permalink
work towards graceful stopping and adding additional topics
Browse files Browse the repository at this point in the history
  • Loading branch information
mikey0000 committed Sep 17, 2024
1 parent 16fbf33 commit eb12c86
Show file tree
Hide file tree
Showing 13 changed files with 285 additions and 114 deletions.
44 changes: 43 additions & 1 deletion pymammotion/aliyun/cloud_gateway.py
Original file line number Diff line number Diff line change
Expand Up @@ -436,6 +436,49 @@ def session_by_auth_code(self):

return response.body

def sign_out(self) -> None:
config = Config(
app_key=self._app_key,
app_secret=self._app_secret,
domain=self._region_response.data.apiGatewayEndpoint,
)
client = Client(config)

# build request
request = CommonParams(api_ver="1.0.4", language="en-US")
body = IoTApiRequest(
id=str(uuid.uuid4()),
params={
"request": {
"refreshToken": self._session_by_authcode_response.data.refreshToken,
"identityId": self._session_by_authcode_response.data.identityId,
}
},
request=request,
version="1.0",
)

# send request
# possibly need to do this ourselves
response = client.do_request(
"/iotx/account/invalidSession",
"https",
"POST",
None,
body,
RuntimeOptions(),
)
logger.debug(response.status_message)
logger.debug(response.headers)
logger.debug(response.status_code)
logger.debug(response.body)

# Decode the response body
response_body_str = response.body.decode("utf-8")

# Load the JSON string into a dictionary
response_body_dict = json.loads(response_body_str)

def check_or_refresh_session(self):
"""Check or refresh the session."""
logger.debug("Try to refresh token")
Expand Down Expand Up @@ -628,7 +671,6 @@ def send_cloud_command(self, iot_id: str, command: bytes) -> str:
version="1.0",
)
logger.debug(self.converter.printBase64Binary(command))

# send request
response = client.do_request("/thing/service/invoke", "https", "POST", None, body, RuntimeOptions())
logger.debug(response.status_message)
Expand Down
16 changes: 9 additions & 7 deletions pymammotion/bluetooth/ble_message.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,6 @@
from pymammotion.bluetooth.data.framectrldata import FrameCtrlData
from pymammotion.bluetooth.data.notifydata import BlufiNotifyData
from pymammotion.data.model.execute_boarder import ExecuteBorder
from pymammotion.mammotion.commands.messages.navigation import MessageNavigation
from pymammotion.proto import (
dev_net_pb2,
luba_msg_pb2,
Expand Down Expand Up @@ -49,7 +48,6 @@ class BleMessage:
mReadSequence: iter
mAck: queue
notification: BlufiNotifyData
messageNavigation: MessageNavigation = MessageNavigation()

def __init__(self, client: BleakClient) -> None:
self.client = client
Expand Down Expand Up @@ -123,9 +121,9 @@ async def send_device_info(self) -> None:

async def requestDeviceStatus(self) -> None:
request = False
type = self.messageNavigation.getTypeValue(0, 5)
type = self.getTypeValue(0, 5)
try:
request = await self.messageNavigation.post(BleMessage.mEncrypted, BleMessage.mChecksum, False, type, None)
request = await self.post(BleMessage.mEncrypted, BleMessage.mChecksum, False, type, None)
# _LOGGER.debug(request)
except Exception as err:
# Log.w(TAG, "post requestDeviceStatus interrupted")
Expand All @@ -137,17 +135,17 @@ async def requestDeviceStatus(self) -> None:

async def requestDeviceVersion(self) -> None:
request = False
type = self.messageNavigation.getTypeValue(0, 7)
type = self.getTypeValue(0, 7)
try:
request = await self.messageNavigation.post(BleMessage.mEncrypted, BleMessage.mChecksum, False, type, None)
request = await self.post(BleMessage.mEncrypted, BleMessage.mChecksum, False, type, None)
# _LOGGER.debug(request)
except Exception as err:
# Log.w(TAG, "post requestDeviceStatus interrupted")
request = False
_LOGGER.error(err)

async def sendBorderPackage(self, executeBorder: ExecuteBorder) -> None:
await self.messageNavigation.post_custom_data(serialize(executeBorder))
await self.post_custom_data(serialize(executeBorder))

async def gatt_write(self, data: bytes) -> None:
await self.client.write_gatt_char(UUID_WRITE_CHARACTERISTIC, data, True)
Expand Down Expand Up @@ -340,6 +338,10 @@ async def post_custom_data(self, data_str: str) -> None:
# onPostCustomDataResult(status, data)
except Exception as err:
_LOGGER.debug(err)
# we might be constantly connected and in a bad state
self.mSendSequence = itertools.count()
self.mReadSequence = itertools.count()
await self.client.disconnect()

async def post(
self,
Expand Down
10 changes: 10 additions & 0 deletions pymammotion/data/model/device.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,17 @@ def update_report_data(self, toapp_report_data: ReportInfoData) -> None:
self.report_data = self.report_data.from_dict(toapp_report_data.to_dict(casing=betterproto.Casing.SNAKE))

def run_state_update(self, rapid_state: SystemRapidStateTunnelMsg) -> None:
coordinate_converter = CoordinateConverter(self.location.RTK.latitude, self.location.RTK.longitude)
self.mowing_state = RapidState().from_raw(rapid_state.rapid_state_data)
self.location.position_type = self.mowing_state.pos_type
self.location.orientation = self.mowing_state.toward / 10000
self.location.device = coordinate_converter.enu_to_lla(
parse_double(self.mowing_state.pos_y, 4.0), parse_double(self.mowing_state.pos_x, 4.0)
)
if self.mowing_state.zone_hash:
self.location.work_zone = (
self.mowing_state.zone_hash if self.report_data.dev.sys_status == WorkMode.MODE_WORKING else 0
)

def mow_info(self, toapp_mow_info: MowToAppInfoT) -> None:
pass
Expand Down
8 changes: 7 additions & 1 deletion pymammotion/data/state_manager.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Manage state from notifications into MowingDevice."""

from datetime import datetime
from typing import Any, Awaitable, Callable, Optional

import betterproto
Expand All @@ -8,19 +9,22 @@
from pymammotion.data.model.hash_list import AreaHashNameList
from pymammotion.proto.luba_msg import LubaMsg
from pymammotion.proto.mctrl_nav import AppGetAllAreaHashName, NavGetCommDataAck, NavGetHashListAck
from pymammotion.utility.constant import WorkMode


class StateManager:
"""Manage state."""

_device: MowingDevice
last_updated_at: datetime = datetime.now()

def __init__(self, device: MowingDevice) -> None:
self._device = device
self.gethash_ack_callback: Optional[Callable[[NavGetHashListAck], Awaitable[None]]] = None
self.get_commondata_ack_callback: Optional[Callable[[NavGetCommDataAck], Awaitable[None]]] = None
self.on_notification_callback: Optional[Callable[[], Awaitable[None]]] = None
self.queue_command_callback: Optional[Callable[[str, dict[str, Any]], Awaitable[bytes]]] = None
self.last_updated_at = datetime.now()

def get_device(self) -> MowingDevice:
"""Get device."""
Expand All @@ -33,6 +37,7 @@ def set_device(self, device: MowingDevice) -> None:
async def notification(self, message: LubaMsg) -> None:
"""Handle protobuf notifications."""
res = betterproto.which_one_of(message, "LubaSubMsg")
self.last_updated_at = datetime.now()

match res[0]:
case "nav":
Expand Down Expand Up @@ -78,7 +83,8 @@ async def _update_sys_data(self, message) -> None:
case "toapp_report_data":
self._device.update_report_data(sys_msg[1])
if self.queue_command_callback:
await self.queue_command_callback("get_report_cfg", stop=True)
if self._device.sys.toapp_report_data.dev.sys_status != WorkMode.MODE_WORKING:
await self.queue_command_callback("get_report_cfg_stop")
case "mow_to_app_info":
self._device.mow_info(sys_msg[1])
case "system_tard_state_tunnel":
Expand Down
30 changes: 15 additions & 15 deletions pymammotion/mammotion/commands/messages/network.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# === sendOrderMsg_Net ===

from pymammotion import logger
from pymammotion.mammotion.commands.messages.navigation import MessageNavigation
from pymammotion.proto import dev_net_pb2, luba_msg_pb2

Expand Down Expand Up @@ -34,12 +34,12 @@ def get_device_base_info(self):

def get_4g_module_info(self) -> bytes:
build = dev_net_pb2.DevNet(todev_get_mnet_cfg_req=dev_net_pb2.DevNet().todev_get_mnet_cfg_req)
print("Send command -- Get device 4G network module information")
logger.debug("Send command -- Get device 4G network module information")
return self.send_order_msg_net(build)

def get_4g_info(self) -> bytes:
build = dev_net_pb2.DevNet(todev_mnet_info_req=dev_net_pb2.DevNet().todev_mnet_info_req)
print("Send command -- Get device 4G network information")
logger.debug("Send command -- Get device 4G network information")
return self.send_order_msg_net(build)

def set_zmq_enable(self) -> bytes:
Expand All @@ -50,12 +50,12 @@ def set_zmq_enable(self) -> bytes:
tx_zmq_url="tcp://0.0.0.0:5555",
)
)
print("Send command -- Set vision ZMQ to enable")
logger.debug("Send command -- Set vision ZMQ to enable")
return self.send_order_msg_net(build)

def set_iot_setting(self, iot_control_type: dev_net_pb2.iot_conctrl_type) -> bytes:
build = dev_net_pb2.DevNet(todev_set_iot_offline_req=iot_control_type)
print("Send command -- Device re-online")
logger.debug("Send command -- Device re-online")
return self.send_order_msg_net(build)

def set_device_log_upload(
Expand All @@ -75,7 +75,7 @@ def set_device_log_upload(
num=number,
type=type,
)
print(
logger.debug(
f"Send log====Feedback====Command======requestID:{request_id} operation:{operation} serverIp:{server_ip} type:{type}"
)
return self.send_order_msg_net(dev_net_pb2.DevNet(todev_ble_sync=1, todev_uploadfile_req=build))
Expand All @@ -98,7 +98,7 @@ def set_device_socket_request(
num=number,
type=type,
)
print(
logger.debug(
f"Send log====Feedback====Command======requestID:{request_id} operation:{operation} serverIp:{server_ip} type:{type}"
)
return self.send_order_msg_net(dev_net_pb2.DevNet(todev_ble_sync=1, todev_uploadfile_req=build))
Expand Down Expand Up @@ -126,7 +126,7 @@ def cancel_log_update(self, biz_id: str) -> bytes:

def get_device_network_info(self) -> bytes:
build = dev_net_pb2.DevNet(todev_networkinfo_req=dev_net_pb2.GetNetworkInfoReq(req_ids=1))
print("Send command - get device network information")
logger.debug("Send command - get device network information")
return self.send_order_msg_net(build)

def set_device_4g_enable_status(self, new_4g_status: bool) -> bytes:
Expand All @@ -141,27 +141,27 @@ def set_device_4g_enable_status(self, new_4g_status: bool) -> bytes:
),
)

print(f"Send command - set 4G (on/off status). newWifiStatus={new_4g_status}")
logger.debug(f"Send command - set 4G (on/off status). newWifiStatus={new_4g_status}")
return self.send_order_msg_net(build)

def set_device_wifi_enable_status(self, new_wifi_status: bool) -> bytes:
build = dev_net_pb2.DevNet(
todev_ble_sync=1,
todev_Wifi_Configuration=dev_net_pb2.DrvWifiSet(configParam=4, wifi_enable=new_wifi_status),
)
print(f"szNetwork: Send command - set network (on/off status). newWifiStatus={new_wifi_status}")
logger.debug(f"szNetwork: Send command - set network (on/off status). newWifiStatus={new_wifi_status}")
return self.send_order_msg_net(build)

def wifi_connectinfo_update(self, device_name: str, is_binary: bool) -> bytes:
print(
logger.debug(
f"Send command - get Wifi connection information.wifiConnectinfoUpdate().deviceName={device_name}.isBinary={is_binary}"
)
if is_binary:
build = dev_net_pb2.DevNet(
todev_ble_sync=1,
todev_WifiMsgUpload=dev_net_pb2.DrvWifiUpload(wifi_msg_upload=1),
)
print("Send command - get Wifi connection information")
logger.debug("Send command - get Wifi connection information")
return self.send_order_msg_net(build)
self.wifi_connectinfo_update2()

Expand All @@ -171,10 +171,10 @@ def wifi_connectinfo_update2(self) -> None:
# 68, hash_map)) # ToDo: Fix this

def get_record_wifi_list(self, is_binary: bool) -> bytes:
print(f"getRecordWifiList().isBinary={is_binary}")
logger.debug(f"getRecordWifiList().isBinary={is_binary}")
if is_binary:
build = dev_net_pb2.DevNet(todev_ble_sync=1, todev_WifiListUpload=dev_net_pb2.DrvWifiList())
print("Send command - get memorized WiFi list upload command")
logger.debug("Send command - get memorized WiFi list upload command")
return self.send_order_msg_net(build)
self.get_record_wifi_list2()

Expand All @@ -189,7 +189,7 @@ def close_clear_connect_current_wifi(self, ssid: str, status: int, is_binary: bo
todev_ble_sync=1,
todev_Wifi_Configuration=dev_net_pb2.DrvWifiSet(configParam=status, Confssid=ssid),
)
print(
logger.debug(
f"Send command - set network (disconnect, direct connect, forget, no operation reconnect) operation command (downlink ssid={ssid}, status={status})"
)
return self.send_order_msg_net(build)
Expand Down
Loading

0 comments on commit eb12c86

Please sign in to comment.