Skip to content

Additions #6

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Dec 9, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -127,3 +127,4 @@ dmypy.json

# Pyre type checker
.pyre/
.vscode/
4 changes: 2 additions & 2 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ repos:
- --skip="./.*,*.csv,*.json,*.md"
- --quiet-level=2
exclude_types: [csv, json]
- repo: https://gitlab.com/pycqa/flake8
- repo: https://github.com/pycqa/flake8
rev: 3.8.4
hooks:
- id: flake8
Expand All @@ -34,6 +34,6 @@ repos:
hooks:
- id: yamllint
- repo: https://github.com/PyCQA/isort
rev: 5.5.3
rev: 5.12.0
hooks:
- id: isort
40 changes: 37 additions & 3 deletions sagemcom_api/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
UnknownException,
UnknownPathException,
)
from .models import Device, DeviceInfo, PortMapping
from .models import Device, DeviceInfo, PortMapping, SpeedTestResult


class SagemcomClient:
Expand Down Expand Up @@ -168,7 +168,7 @@ def __get_response_value(self, response, index=0):

return value

async def __api_request_async(self, actions, priority=False):
async def __api_request_async(self, actions, priority=False, **request_kwargs):
"""Build request to the internal JSON-req API."""
self.__generate_request_id()
self.__generate_nonce()
Expand All @@ -188,7 +188,9 @@ async def __api_request_async(self, actions, priority=False):
}

async with self.session.post(
api_host, data="req=" + json.dumps(payload, separators=(",", ":"))
api_host,
data="req=" + json.dumps(payload, separators=(",", ":")),
**request_kwargs,
) as response:

if response.status == 400:
Expand Down Expand Up @@ -408,3 +410,35 @@ async def reboot(self):
data = self.__get_response_value(response)

return data

async def run_speed_test(self, block_traffic: bool = False):
"""Run Speed Test on Sagemcom F@st device."""
actions = [
{
"id": 0,
"method": "speedTestClient",
"xpath": "Device/IP/Diagnostics/SpeedTest",
"parameters": {"BlockTraffic": block_traffic},
}
]
return await self.__api_request_async(actions, False, timeout=100)

async def get_speed_test_results(self):
"""Retrieve Speed Test results from Sagemcom F@st device."""
ret = await self.get_value_by_xpath("Device/IP/Diagnostics/SpeedTest")
history = ret["speed_test"]["history"]
if history:
timestamps = (int(k) for k in history["timestamp"].split(","))
server_address = history["selected_server_address"].split(",")
block_traffic = history["block_traffic"].split(",")
latency = history["latency"].split(",")
upload = (float(k) for k in history["upload"].split(","))
download = (float(k) for k in history["download"].split(","))
results = [
SpeedTestResult(*data)
for data in zip(
timestamps, server_address, block_traffic, latency, upload, download
)
]
return results
return []
28 changes: 28 additions & 0 deletions sagemcom_api/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import dataclasses
from dataclasses import dataclass
import time
from typing import Any, List, Optional


Expand Down Expand Up @@ -162,3 +163,30 @@ def __init__(self, **kwargs):
def id(self):
"""Return unique ID for port mapping."""
return self.uid


@dataclass
class SpeedTestResult:
"""Representation of a speedtest result."""

timestamp: str
selected_server_address: str
block_traffic: bool
latency: str
upload: str
download: str

def __post_init__(self):
"""Process data after init."""
# Convert timestamp to datetime object.
self.timestamp = time.strftime(
"%Y-%m-%d %H:%M:%S", time.localtime(self.timestamp)
)
self.block_traffic = bool(self.block_traffic)

def __str__(self) -> str:
"""Return string representation of speedtest result."""
return (
f"timestamp: {self.timestamp}, latency: {self.latency}, "
f"upload: {self.upload}, download: {self.download}"
)