Skip to content

Commit

Permalink
Implement Stream Subscription Retrieval and Response Handling (#60)
Browse files Browse the repository at this point in the history
* Implement 'get stream subscription'

* Correct function 'get_stream_subscription' name

* Fixed double quote on '"Authorization": f"{cls._headers['Authorization']}"' and remove print

* Update pymammotion/http/http.py

Co-authored-by: Michael Arthur <[email protected]>

* Update pymammotion/http/http.py

Co-authored-by: Michael Arthur <[email protected]>

* Update pymammotion/http/http.py

Co-authored-by: Michael Arthur <[email protected]>

* Update pymammotion/http/http.py

Co-authored-by: Michael Arthur <[email protected]>

* Update pymammotion/mammotion/devices/mammotion.py

Co-authored-by: Michael Arthur <[email protected]>

* Update pymammotion/mammotion/devices/mammotion.py

Co-authored-by: Michael Arthur <[email protected]>

* Update pymammotion/mammotion/devices/mammotion.py

Co-authored-by: Michael Arthur <[email protected]>

* Update pymammotion/mammotion/devices/mammotion.py

Co-authored-by: Michael Arthur <[email protected]>

* Update pymammotion/mammotion/devices/mammotion.py

Co-authored-by: Michael Arthur <[email protected]>

* Update pymammotion/mammotion/devices/mammotion.py

Co-authored-by: Michael Arthur <[email protected]>

* remove cloud_client

* fix signature

* Update pymammotion/http/http.py

* Apply suggestions from code review

* Update pymammotion/mammotion/devices/mammotion.py

* Delete pymammotion/http/dataclass/stream_subscription_response.py

---------

Co-authored-by: Andrea Cagnola <[email protected]>
Co-authored-by: Michael Arthur <[email protected]>
  • Loading branch information
3 people authored Sep 16, 2024
1 parent 99662c6 commit b0c7d17
Show file tree
Hide file tree
Showing 3 changed files with 83 additions and 1 deletion.
24 changes: 24 additions & 0 deletions pymammotion/http/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from aiohttp import ClientSession

from pymammotion.http.dataclass.stream_subscription_response import StreamSubscriptionResponse
from pymammotion.const import (
MAMMOTION_API_DOMAIN,
MAMMOTION_CLIENT_ID,
Expand All @@ -13,12 +14,14 @@


class MammotionHTTP:

def __init__(self, response: Response) -> None:
self._headers = dict()
self.login_info = LoginResponseData.from_dict(response.data) if response.data else None
self._headers["Authorization"] = f"Bearer {self.login_info.access_token}" if response.data else None
self.msg = response.msg
self.code = response.code


async def get_all_error_codes(self) -> list[ErrorInfo]:
async with ClientSession(MAMMOTION_API_DOMAIN) as session:
Expand All @@ -43,6 +46,27 @@ async def oauth_check(self) -> None:
data = await resp.json()
response = Response.from_dict(data)


async def get_stream_subscription(self, iot_id: str) -> Response[StreamSubscriptionResponse]:
"""Get agora.io data for view camera stream"""
async with ClientSession(DOMESTIC_MAMMOTION_URL) as session:
async with session.post(
"/device-server/v1/stream/subscription",
json={
"deviceId" : iot_id
},
headers={
"Authorization": f"{self._headers.get('Authorization', "")}",
"Content-Type": "application/json"
}
) as resp:
if resp.status == 200:
data = await resp.json()
# TODO catch errors from mismatch like token expire etc
# Assuming the data format matches the expected structure
return StreamSubscriptionResponse.from_dict(data)


@classmethod
async def login(cls, session: ClientSession, username: str, password: str) -> Response[LoginResponseData]:
async with session.post(
Expand Down
10 changes: 9 additions & 1 deletion pymammotion/mammotion/devices/mammotion.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,7 +221,7 @@ def set_disconnect_strategy(self, disconnect: bool) -> None:

async def login(self, account: str, password: str) -> CloudIOTGateway:
"""Login to mammotion cloud."""
cloud_client = CloudIOTGateway()

async with ClientSession(MAMMOTION_DOMAIN) as session:
mammotion_http = await connect_http(account, password)
country_code = mammotion_http.login_info.userInformation.domainAbbreviation
Expand Down Expand Up @@ -283,6 +283,14 @@ async def start_map_sync(self, name: str):
if device.preference is ConnectionPreference.WIFI:
return await device.cloud().start_map_sync()
# TODO work with both with EITHER

async def get_stream_subscription(self, name: str):
device = self.get_device_by_name(name)
if self._preference is ConnectionPreference.WIFI:
if device.has_cloud():
_stream_response = await self.cloud().cloud_client.get_stream_subscription(device.cloud().iot_id)
_LOGGER.debug(_stream_response)
return _stream_response

def mower(self, name: str):
device = self.get_device_by_name(name)
Expand Down
50 changes: 50 additions & 0 deletions tests/login_and_get_stream_token.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import asyncio
import logging
import os

from aiohttp import ClientSession
import traceback

from pymammotion import MammotionHTTP
from pymammotion.aliyun.cloud_gateway import CloudIOTGateway
from pymammotion.const import MAMMOTION_DOMAIN
from pymammotion.http.http import connect_http
from pymammotion.mammotion.commands.mammotion_command import MammotionCommand
from pymammotion.mqtt.mammotion_mqtt import MammotionMQTT, logger
from pymammotion.mammotion.devices.mammotion import MammotionBaseCloudDevice
from pymammotion.data.model.account import Credentials
from pymammotion.mammotion.devices.mammotion import create_devices, ConnectionPreference, Mammotion

logger = logging.getLogger(__name__)


async def run():
EMAIL = os.environ.get('EMAIL')
PASSWORD = os.environ.get('PASSWORD')
DEVICE_NAME = "Luba-VSXXXXXX"

try:
credentials = Credentials(
email=EMAIL,
password=PASSWORD
)
_mammotion = await create_devices(ble_device=None, cloud_credentials=credentials, preference=ConnectionPreference.WIFI)



await _mammotion.get_stream_subscription(DEVICE_NAME)

return _mammotion
except Exception as ex:
logger.error(f"{ex}")
logger.error(traceback.format_exc())
return None


if __name__ == '__main__':
logging.basicConfig(level=logging.DEBUG)
logger.getChild("paho").setLevel(logging.WARNING)
event_loop = asyncio.new_event_loop()
asyncio.set_event_loop(event_loop)
cloud_client = event_loop.run_until_complete(run())
event_loop.run_forever()

0 comments on commit b0c7d17

Please sign in to comment.