Skip to content

Commit 07c775c

Browse files
committed
Refactor search_device function
1 parent 307e732 commit 07c775c

File tree

6 files changed

+212
-58
lines changed

6 files changed

+212
-58
lines changed

Makefile

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,13 @@ install:
33
poetry install
44
poetry run python scripts/download-tools.py
55

6+
test:
7+
poetry run pytest tests/
8+
69
app:
710
poetry run python openandroidinstaller/openandroidinstaller.py
811

9-
build-app: install
12+
build-app:
1013
poetry run pyinstaller openandroidinstaller/openandroidinstaller.py --noconsole --noconfirm --onefile --icon "/assets/favicon.ico" --add-data "openandroidinstaller/assets:assets" --add-binary "openandroidinstaller/bin/adb:bin" --add-binary "openandroidinstaller/bin/fastboot:bin" --add-binary "openandroidinstaller/bin/heimdall:bin"
1114

1215

openandroidinstaller/openandroidinstaller.py

Lines changed: 24 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
from loguru import logger
1919
from subprocess import STDOUT, CalledProcessError, call, check_output
2020
from time import sleep
21-
from typing import Callable
21+
from typing import Callable, Optional
2222
from pathlib import Path
2323

2424
import flet
@@ -50,6 +50,7 @@
5050
)
5151
from installer_config import InstallerConfig, Step
5252
from widgets import call_button, confirm_button, get_title
53+
from tool_utils import search_device, call_tool_with_command
5354

5455
# Toggle to True for development purposes
5556
DEVELOPMENT = False
@@ -178,66 +179,34 @@ def close_developer_options_dlg(self, e):
178179

179180
def search_devices(self, e):
180181
"""Search the device when the button is clicked."""
181-
logger.info("Search devices...")
182-
try:
183-
# read device properties
184-
# TODO: This is not windows ready...
185-
if PLATFORM in ("linux", "darwin"):
186-
output = check_output(
187-
[
188-
str(BIN_PATH.joinpath(Path("adb"))),
189-
"shell",
190-
"getprop",
191-
"|",
192-
"grep",
193-
"ro.product.device"
194-
],
195-
stderr=STDOUT,
196-
).decode()
197-
elif PLATFORM == "windows":
198-
output = check_output(
199-
[
200-
str(BIN_PATH.joinpath(Path("adb"))),
201-
"shell",
202-
"getprop",
203-
"|",
204-
"findstr",
205-
"ro.product.device"
206-
],
207-
stderr=STDOUT,
208-
).decode()
182+
# search the device
183+
if DEVELOPMENT:
184+
# this only happens for testing
185+
device_code = DEVELOPMENT_CONFIG
186+
logger.info(f"Running search in development mode and loading config {device_code}.yaml.")
187+
else:
188+
device_code = search_device(platform=PLATFORM, bin_path=BIN_PATH)
189+
if device_code:
190+
self.device_name.value = device_code
209191
else:
210-
raise Exception(f"Unknown platform {PLATFORM}.")
192+
self.device_name.value = "No device detected! Connect to USB and try again."
211193

212-
output = output.split("[")[-1][:-2]
213-
logger.info(f"Detected {output}")
214-
# write the device code to the text shown in the box
215-
self.device_name.value = output.strip()
194+
# load the config, if a device is detected
195+
if device_code:
196+
self.device_name.value = device_code
216197
# load config from file
217-
path = CONFIG_PATH.joinpath(Path(f"{output.strip()}.yaml"))
218-
load_config_success = self.load_config(path)
198+
path = CONFIG_PATH.joinpath(Path(f"{device_code}.yaml"))
199+
device_name = self.load_config(path)
200+
219201
# display success in the application
220-
if load_config_success:
202+
if device_name:
221203
self.config_found_box.value = True
222204
self.continue_button.disabled = False
223205
# overwrite the text field with the real name from the config
224-
self.device_name.value = f"{load_config_success} (code: {output.strip()})"
206+
self.device_name.value = f"{device_name} (code: {device_code})"
225207
else:
226-
# show alternative configs here
227-
# select a new path and load again
228-
pass
229-
except CalledProcessError:
230-
logger.info(f"Did not detect a device.")
231-
if DEVELOPMENT:
232-
path = CONFIG_PATH.joinpath(Path(f"{DEVELOPMENT_CONFIG}.yaml"))
233-
load_config_success = self.load_config(path)
234-
if load_config_success:
235-
self.config_found_box.value = True
236-
self.continue_button.disabled = False
237-
else:
238-
self.device_name.value = (
239-
"No device detected! Connect to USB and try again."
240-
)
208+
# failed to load config
209+
logger.info(f"Failed to load config from {path}.")
241210
self.view.update()
242211

243212

@@ -422,7 +391,7 @@ def confirm(self, e):
422391
self.view.controls.append(self.final_view)
423392
self.view.update()
424393

425-
def load_config(self, path: str):
394+
def load_config(self, path: str) -> Optional[str]:
426395
"""Function to load a config file from path."""
427396
try:
428397
self.config = InstallerConfig.from_file(path)
@@ -432,7 +401,7 @@ def load_config(self, path: str):
432401
return self.config.metadata.get("devicename", "No device name in config.")
433402
except FileNotFoundError:
434403
logger.info(f"No device config found for {path}.")
435-
return False
404+
return None
436405

437406
def pick_image_result(self, e: FilePickerResultEvent):
438407
self.selected_image.value = (

openandroidinstaller/tool_utils.py

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
"""This module contains functions to deal with tools like adb, fastboot and heimdall."""
2+
3+
# This file is part of OpenAndroidInstaller.
4+
# OpenAndroidInstaller is free software: you can redistribute it and/or modify it under the terms of
5+
# the GNU General Public License as published by the Free Software Foundation,
6+
# either version 3 of the License, or (at your option) any later version.
7+
8+
# OpenAndroidInstaller is distributed in the hope that it will be useful, but WITHOUT ANY
9+
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
10+
# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
11+
12+
# You should have received a copy of the GNU General Public License along with OpenAndroidInstaller.
13+
# If not, see <https://www.gnu.org/licenses/>."""
14+
# Author: Tobias Sterbak
15+
16+
from typing import Optional
17+
from loguru import logger
18+
from pathlib import Path
19+
from subprocess import STDOUT, CalledProcessError, call, check_output
20+
21+
22+
def call_tool_with_command(command: str, bin_path: Path):
23+
"""Call an executable with a specific command."""
24+
25+
26+
def search_device(platform: str, bin_path: Path) -> Optional[str]:
27+
"""Search for a connected device."""
28+
logger.info(f"Search devices on {platform} with {bin_path}...")
29+
try:
30+
# read device properties
31+
# TODO: This is not windows ready...
32+
if platform in ("linux", "darwin"):
33+
output = check_output(
34+
[
35+
str(bin_path.joinpath(Path("adb"))),
36+
"shell",
37+
"getprop",
38+
"|",
39+
"grep",
40+
"ro.product.device"
41+
],
42+
stderr=STDOUT,
43+
).decode()
44+
elif platform == "windows":
45+
output = check_output(
46+
[
47+
str(bin_path.joinpath(Path("adb"))),
48+
"shell",
49+
"getprop",
50+
"|",
51+
"findstr",
52+
"ro.product.device"
53+
],
54+
stderr=STDOUT,
55+
).decode()
56+
else:
57+
raise Exception(f"Unknown platform {platform}.")
58+
return output.split("[")[-1][:-2].strip()
59+
except CalledProcessError:
60+
logger.info(f"Did not detect a device.")
61+
return None

poetry.lock

Lines changed: 107 additions & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

pyproject.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ PyYAML = "^6.0"
1717
isort = "^5.10.1"
1818
loguru = "^0.6.0"
1919
requests = "^2.28.1"
20+
pytest = "^7.1.3"
2021

2122
[tool.poetry.dev-dependencies]
2223

0 commit comments

Comments
 (0)