From 79042a13540ac6189f2fab42d93bdcf366f6663f Mon Sep 17 00:00:00 2001 From: ZanSara Date: Fri, 20 Dec 2024 15:40:29 +0000 Subject: [PATCH 1/4] Restore 1.3.2 --- .github/workflows/ci.yml | 2 +- .gitignore | 2 - tests/conftest.py | 1 + tests/unit_tests/test_webcam_system.py | 63 ++++++++++++++++- zanzocam/constants.py | 8 +-- zanzocam/data/send-logs.flag | 1 - zanzocam/data/upload_interval.txt | 1 - zanzocam/web_ui/api.py | 9 +++ zanzocam/web_ui/pages.py | 4 +- zanzocam/web_ui/templates/home.html | 63 +++++++++++++++++ zanzocam/web_ui/templates/network.html | 57 +++++++++++++-- zanzocam/webcam/system.py | 98 ++++++++++++++------------ 12 files changed, 247 insertions(+), 62 deletions(-) delete mode 100644 zanzocam/data/send-logs.flag delete mode 100644 zanzocam/data/upload_interval.txt diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0ef4d667..6577cd7b 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -22,7 +22,7 @@ jobs: - name: Install ZanzoCam run: | sudo apt-get install language-pack-it wireless-tools - pip install Pillow requests piexif pytest pytest-coverage pytest-subprocess freezegun coveralls + pip install Pillow requests piexif pytest pytest-coverage pytest-subprocess freezegun coveralls flask pip install --no-deps -e . - name: Unit tests diff --git a/.gitignore b/.gitignore index 430367c2..0e092e6f 100644 --- a/.gitignore +++ b/.gitignore @@ -4,8 +4,6 @@ **/wpa_supplicant.conf zanzocam/web_ui/static/previews/* zanzocam/data/* -!zanzocam/data/send-logs.flag -!zanzocam/data/upload_interval.txt **/build/*.* diff --git a/tests/conftest.py b/tests/conftest.py index 4a85148c..70cb1636 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -94,6 +94,7 @@ def mock_modules_apart_config(monkeypatch): monkeypatch.setattr(main, 'Server', MockServer) monkeypatch.setattr(main, 'Camera', MockCamera) monkeypatch.setattr(main, 'WAIT_AFTER_CAMERA_FAIL', 1) + monkeypatch.setattr(server.server, 'RANDOM_UPLOAD_INTERVAL', 0) monkeypatch.setattr(utils, "sleep", lambda *a, **k: None) diff --git a/tests/unit_tests/test_webcam_system.py b/tests/unit_tests/test_webcam_system.py index 331c68c0..e331d1a3 100644 --- a/tests/unit_tests/test_webcam_system.py +++ b/tests/unit_tests/test_webcam_system.py @@ -73,6 +73,66 @@ def test_get_uptime_exception(fake_process, logs): assert in_logs(logs, "Could not get last reboot time information") +def test_check_hotspot_allowed_flag_set_to_yes(logs): + """ + Check if the hotspot is allowed, test YES flag + """ + with open(constants.HOTSPOT_FLAG, 'w') as f: + f.write("yes") + allowed = system.check_hotspot_allowed() + assert allowed + assert len(logs) == 0 + + +def test_check_hotspot_allowed_flag_set_to_no(logs): + """ + Check if the hotspot is allowed, test NO flag + """ + with open(constants.HOTSPOT_FLAG, 'w') as f: + f.write("no") + allowed = system.check_hotspot_allowed() + assert not allowed + assert len(logs) == 0 + + +def test_check_hotspot_allowed_flag_set_to_other(logs): + """ + Check if the hotspot is allowed, test unexpected flag + """ + with open(constants.HOTSPOT_FLAG, 'w') as f: + f.write("Other") + allowed = system.check_hotspot_allowed() + assert allowed + assert len(logs) == 1 + assert in_logs(logs, "The hostpot flag contains neither YES nor NO") + + +def test_check_hotspot_allowed_permission_error(logs): + """ + Check if the hotspot is allowed, test permission errors + """ + with open(constants.HOTSPOT_FLAG, 'w') as f: + f.write("no") + os.chmod(constants.HOTSPOT_FLAG, 0o222) + allowed = system.check_hotspot_allowed() + assert allowed + assert len(logs) == 1 + assert in_logs(logs, "Failed to check if the hotspot is allowed") + + +def test_check_hotspot_allowed_no_file(logs): + """ + Check if the hotspot is allowed, no file + """ + assert not os.path.exists(constants.HOTSPOT_FLAG) + allowed = system.check_hotspot_allowed() + assert allowed + assert len(logs) == 1 + assert in_logs(logs, "Hotspot flag file not found") + assert os.path.exists(constants.HOTSPOT_FLAG) + assert open(constants.HOTSPOT_FLAG, 'r').read() == "YES" + + def test_run_hotspot_on_wifi_1(fake_process, logs): """ Check if the hotspot runs, normal behavior on wifi. @@ -348,13 +408,14 @@ def test_report_general_status(monkeypatch): class Empty(): def __getattr__(self, attr): - return lambda *a, **k: None + return lambda *a, **k: None monkeypatch.setattr(webcam, "system", Empty()) status = original_system.report_general_status() assert "version" in status.keys() assert "last reboot" in status.keys() assert "uptime" in status.keys() + assert "hotspot allowed" in status.keys() assert "wifi data" in status.keys() assert "internet access" in status.keys() assert "disk size" in status.keys() diff --git a/zanzocam/constants.py b/zanzocam/constants.py index be02f783..3e3f50d0 100644 --- a/zanzocam/constants.py +++ b/zanzocam/constants.py @@ -5,7 +5,7 @@ #: ZanzoCam version -VERSION = "1.3.4" +VERSION = "1.3.2" # Executables constants @@ -50,6 +50,9 @@ #: Temporary camera logs for the web UI PICTURE_LOGS = DATA_PATH / "picture_logs.txt" +#: Whether the hotspot is allowed +HOTSPOT_FLAG = DATA_PATH / "hotspot.flag" + #: Whether to send the logs to the server SEND_LOGS_FLAG = DATA_PATH / "send-logs.flag" @@ -97,9 +100,6 @@ #: Path to the autohotspot script AUTOHOTSPOT_BINARY_PATH = "/usr/bin/autohotspot" -#: Interval to wait before retrying the autohotspot script -AUTOHOTSPOT_RETRY_TIME = 5 * 60 # 5 minutes - #: Ecoding of the FTP server files FTP_CONFIG_FILE_ENCODING = 'utf-8' diff --git a/zanzocam/data/send-logs.flag b/zanzocam/data/send-logs.flag deleted file mode 100644 index d2bb3234..00000000 --- a/zanzocam/data/send-logs.flag +++ /dev/null @@ -1 +0,0 @@ -YES \ No newline at end of file diff --git a/zanzocam/data/upload_interval.txt b/zanzocam/data/upload_interval.txt deleted file mode 100644 index 7813681f..00000000 --- a/zanzocam/data/upload_interval.txt +++ /dev/null @@ -1 +0,0 @@ -5 \ No newline at end of file diff --git a/zanzocam/web_ui/api.py b/zanzocam/web_ui/api.py index 9120ba4a..7c969963 100644 --- a/zanzocam/web_ui/api.py +++ b/zanzocam/web_ui/api.py @@ -110,6 +110,15 @@ def set_upload_interval(value: int) -> str: except ValueError as e: abort(500, f"invalid value for the random interval field: {value}") +def toggle_hotspot(value: str) -> str: + """ + Allow the initial hotspot to turn on in case no known wifi network is detected. + """ + value = value.upper().strip() + if value == "YES" or value == "NO": + return "", toggle_flag(HOTSPOT_FLAG, value) + abort(404) + def toggle_send_logs(value: str) -> str: """ diff --git a/zanzocam/web_ui/pages.py b/zanzocam/web_ui/pages.py index 3b06ea73..0a51d913 100644 --- a/zanzocam/web_ui/pages.py +++ b/zanzocam/web_ui/pages.py @@ -13,12 +13,14 @@ def home_page(): """ The initial page with the summary """ + hotspot_value = read_flag_file(HOTSPOT_FLAG, "YES") network_data = read_network_data() network_data["wifi_data"] = get_wifi_data() server_data = read_setup_data_file(CONFIGURATION_FILE).get('server', {}) return render_template("home.html", title="Setup", - version=VERSION, + version=VERSION, + hotspot_value=hotspot_value, network_data=network_data, server_data=server_data) diff --git a/zanzocam/web_ui/templates/home.html b/zanzocam/web_ui/templates/home.html index cc76daea..c173b369 100644 --- a/zanzocam/web_ui/templates/home.html +++ b/zanzocam/web_ui/templates/home.html @@ -83,6 +83,24 @@

Logs:

+
+
+

Hotspot:

+ + +
+
+

NOTA BENE: Questo switch serve per permettere a ZanzoCam di generare o meno un hotspot quando perde contatto + con qualunque rete WiFi nota. Questo switch NON attiva l'hotspot se ZanzoCam è gia' in grado di collegarsi + con un'altra rete WiFi o è collegata via rete Ethernet.
+

+

Riavvia ZanzoCam:

@@ -120,6 +138,51 @@

Riavvia ZanzoCam:

field.innerHTML=""; } } + + function hotspotNO() { + confirmation = confirm("ATTENZIONE! Una volta premuto questo bottone, " + + "ZanzoCam smettera' di produrre il suo hotspot in caso di " + + "assenza di WiFi.\n\n" + + "Sei sicuro\a di voler proseguire?"); + if(confirmation){ + fetch("/configure/hotspot/NO", { + method:'POST', + }) + .then(r => { + if (r.status === 200){ + alert("Modifica completata con successo."); + } else { + alert("Qualcosa è andato storto! " + + "ZanzoCam ha risposto con un codice "+ r.status +"."); + } + }).catch(r => { + alert("Qualcosa è andato storto! " + + "ZanzoCam non è raggiungibile."); + }) + } + } + function hotspotYES() { + confirmation = confirm("ATTENZIONE! Una volta premuto questo bottone, " + + "ZanzoCam comincera' a produrre il suo hotspot in caso di " + + "assenza di WiFi.\n\n" + + "Sei sicuro\a di voler proseguire?"); + if(confirmation){ + fetch("/configure/hotspot/YES", { + method:'POST', + }) + .then(r => { + if (r.status === 200){ + alert("Modifica completata con successo."); + } else { + alert("Qualcosa è andato storto! " + + "ZanzoCam ha risposto con un codice "+ r.status +"."); + } + }).catch(r => { + alert("Qualcosa è andato storto! " + + "ZanzoCam non è raggiungibile."); + }) + } + } {% endblock %} diff --git a/zanzocam/web_ui/templates/network.html b/zanzocam/web_ui/templates/network.html index 514fbec7..1eda05b4 100644 --- a/zanzocam/web_ui/templates/network.html +++ b/zanzocam/web_ui/templates/network.html @@ -2,22 +2,53 @@ {% block content %}
+
- - + + + + + +
+ + +
+ +
Indietro
+
+
+ {% endblock %} diff --git a/zanzocam/webcam/system.py b/zanzocam/webcam/system.py index b96f9046..3da78628 100644 --- a/zanzocam/webcam/system.py +++ b/zanzocam/webcam/system.py @@ -9,7 +9,6 @@ import requests import datetime import subprocess -from time import sleep from pathlib import Path from textwrap import dedent @@ -18,18 +17,13 @@ from zanzocam.web_ui.utils import read_flag_file -class RaceConditionError(Exception): - pass - - def log_general_status() -> bool: """ Returns True if the execution was successful, False in case of errors """ - status = None return_value = True - report = "Status report:\n" try: + report = "Status report:\n" status = report_general_status() col_width = 16 @@ -41,26 +35,19 @@ def log_general_status() -> bool: continue report += f"- {key}: {' ' * (col_width - len(key))}{value}\n" - except RaceConditionError as e: - log_error("Another Zanzocam is running.", e) - raise e - except Exception as e: - log_error( - "Something unexpected happened during the system status check. " - "This might be a symptom of deeper issues, don't ignore this!", e - ) + log_error("Something unexpected happened during the system " + "status check. This might be " + "a symptom of deeper issues, don't ignore this!", e) return_value = False finally: log(report) - if status and not status.get('internet access', False): - log_error("No Internet access detected on this WiFi network. Skipping this photo.") - raise RuntimeError("No Internet access detected on this WiFi network.") return return_value + def report_general_status() -> Dict: """ Collect general system data like version, uptime, internet connectivity. @@ -74,27 +61,23 @@ def report_general_status() -> Dict: status["last reboot"] = get_last_reboot_time() status["uptime"] = get_uptime() - race_condition = check_race_condition() - if race_condition: - log_error("Another Zanzocam process is running (probably waiting for WiFi). Skipping this photo.") - raise RaceConditionError() + hotspot_allowed = check_hotspot_allowed() + if hotspot_allowed: + status["hotspot allowed"] = "YES" + else: + status["hotspot allowed"] = "NO" - status['wifi data'] = get_wifi_data() - if status['wifi data'] and "ssid" in status['wifi data'] and status['wifi data']["ssid"] == "n/a": - + if status["hotspot allowed"] != "NO": autohotspot_status = run_autohotspot() if autohotspot_status is None: status["hotspot status"] = "FAILED (see stacktrace)" else: - while not autohotspot_status: - log(f"Hotspot is active. Waiting for {AUTOHOTSPOT_RETRY_TIME} minutes and retrying to connect to WiFi.") - sleep(AUTOHOTSPOT_RETRY_TIME) - autohotspot_status = run_autohotspot() - - # Once we connect, let's collect the WiFi data again. - status["hotspot status"] = "OFF (connected to WiFi)" - status['wifi data'] = get_wifi_data() + if autohotspot_status: + status["hotspot status"] = "OFF (connected to WiFi)" + else: + status["hotspot status"] = "ON (no known WiFi in range)" + status['wifi data'] = get_wifi_data() status['internet access'] = check_internet_connectivity() status['max upload wait'] = get_max_random_upload_interval() @@ -105,18 +88,6 @@ def report_general_status() -> Dict: return status -def check_race_condition(): - """ - Check whether there's any other Zanzocam process already running. - """ - try: - ps_proc = subprocess.Popen(['/bin/ps', 'aux'], stdout=subprocess.PIPE) - ps_output, _ = ps_proc.communicate() - return ps_output.decode('utf-8').count("z-webcam") > 2 - except Exception as e: - log_error("Could not check for other processes. Something is wrong, aborting the script.", e) - - def get_max_random_upload_interval(): try: random_upload_interval = int(read_flag_file(DATA_PATH / "upload_interval.txt", default="5")) @@ -165,6 +136,41 @@ def get_uptime() -> Optional[datetime.timedelta]: except Exception as e: log_error("Could not get uptime information", e) return None + + + +def check_hotspot_allowed() -> Optional[str]: + """ + Checks whether ZANZOCAM can turn on its hotspot at need. + True if it can, False otherwise. + If the file was not found, it creates it with a value YES. + In case of exceptions, defaults to True. + """ + if os.path.exists(HOTSPOT_FLAG): + try: + with open(HOTSPOT_FLAG, "r+") as h: + content = h.read().strip() + if content.upper() == "YES": + return True + elif content.upper() == "NO": + return False + else: + log("The hostpot flag contains neither YES nor NO " + f"(it contains '{content}'). Please fix. " + "Assuming YES.") + return True + + except Exception as e: + log_error("Failed to check if the hotspot is allowed. " + "Assuming YES", e) + return True + + log(f"Hotspot flag file not found. Creating it under {HOTSPOT_FLAG}" + f" with value YES") + with open(HOTSPOT_FLAG, "w") as h: + h.write("YES") + return True + def run_autohotspot() -> Optional[bool]: @@ -559,3 +565,5 @@ def prepare_crontab_string(time: Dict, length: Optional[int] = None) -> List[str start_total_minutes += frequency return cron_strings + + From e7d09e1b8339b7074aceefab4a3cc9e3c3299f99 Mon Sep 17 00:00:00 2001 From: ZanSara Date: Fri, 20 Dec 2024 15:52:59 +0000 Subject: [PATCH 2/4] remove possibility to deactivate hotspot --- .gitignore | 2 + tests/unit_tests/test_webcam_system.py | 62 ------------------------- zanzocam/constants.py | 10 +--- zanzocam/data/send-logs.flag | 1 + zanzocam/web_ui/api.py | 9 ---- zanzocam/web_ui/pages.py | 2 - zanzocam/web_ui/templates/home.html | 63 -------------------------- zanzocam/webcam/system.py | 58 ++++-------------------- 8 files changed, 12 insertions(+), 195 deletions(-) create mode 100644 zanzocam/data/send-logs.flag diff --git a/.gitignore b/.gitignore index 0e092e6f..430367c2 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,8 @@ **/wpa_supplicant.conf zanzocam/web_ui/static/previews/* zanzocam/data/* +!zanzocam/data/send-logs.flag +!zanzocam/data/upload_interval.txt **/build/*.* diff --git a/tests/unit_tests/test_webcam_system.py b/tests/unit_tests/test_webcam_system.py index e331d1a3..2da82edf 100644 --- a/tests/unit_tests/test_webcam_system.py +++ b/tests/unit_tests/test_webcam_system.py @@ -72,67 +72,6 @@ def test_get_uptime_exception(fake_process, logs): assert in_logs(logs, "Could not get uptime information") assert in_logs(logs, "Could not get last reboot time information") - -def test_check_hotspot_allowed_flag_set_to_yes(logs): - """ - Check if the hotspot is allowed, test YES flag - """ - with open(constants.HOTSPOT_FLAG, 'w') as f: - f.write("yes") - allowed = system.check_hotspot_allowed() - assert allowed - assert len(logs) == 0 - - -def test_check_hotspot_allowed_flag_set_to_no(logs): - """ - Check if the hotspot is allowed, test NO flag - """ - with open(constants.HOTSPOT_FLAG, 'w') as f: - f.write("no") - allowed = system.check_hotspot_allowed() - assert not allowed - assert len(logs) == 0 - - -def test_check_hotspot_allowed_flag_set_to_other(logs): - """ - Check if the hotspot is allowed, test unexpected flag - """ - with open(constants.HOTSPOT_FLAG, 'w') as f: - f.write("Other") - allowed = system.check_hotspot_allowed() - assert allowed - assert len(logs) == 1 - assert in_logs(logs, "The hostpot flag contains neither YES nor NO") - - -def test_check_hotspot_allowed_permission_error(logs): - """ - Check if the hotspot is allowed, test permission errors - """ - with open(constants.HOTSPOT_FLAG, 'w') as f: - f.write("no") - os.chmod(constants.HOTSPOT_FLAG, 0o222) - allowed = system.check_hotspot_allowed() - assert allowed - assert len(logs) == 1 - assert in_logs(logs, "Failed to check if the hotspot is allowed") - - -def test_check_hotspot_allowed_no_file(logs): - """ - Check if the hotspot is allowed, no file - """ - assert not os.path.exists(constants.HOTSPOT_FLAG) - allowed = system.check_hotspot_allowed() - assert allowed - assert len(logs) == 1 - assert in_logs(logs, "Hotspot flag file not found") - assert os.path.exists(constants.HOTSPOT_FLAG) - assert open(constants.HOTSPOT_FLAG, 'r').read() == "YES" - - def test_run_hotspot_on_wifi_1(fake_process, logs): """ Check if the hotspot runs, normal behavior on wifi. @@ -415,7 +354,6 @@ def __getattr__(self, attr): assert "version" in status.keys() assert "last reboot" in status.keys() assert "uptime" in status.keys() - assert "hotspot allowed" in status.keys() assert "wifi data" in status.keys() assert "internet access" in status.keys() assert "disk size" in status.keys() diff --git a/zanzocam/constants.py b/zanzocam/constants.py index 3e3f50d0..e893fc52 100644 --- a/zanzocam/constants.py +++ b/zanzocam/constants.py @@ -1,12 +1,7 @@ -import logging from pathlib import Path -#from zanzocam.web_ui.utils import read_flag_file, write_text_file - - #: ZanzoCam version -VERSION = "1.3.2" - +VERSION = "1.3.5" # Executables constants # ##################### @@ -50,9 +45,6 @@ #: Temporary camera logs for the web UI PICTURE_LOGS = DATA_PATH / "picture_logs.txt" -#: Whether the hotspot is allowed -HOTSPOT_FLAG = DATA_PATH / "hotspot.flag" - #: Whether to send the logs to the server SEND_LOGS_FLAG = DATA_PATH / "send-logs.flag" diff --git a/zanzocam/data/send-logs.flag b/zanzocam/data/send-logs.flag new file mode 100644 index 00000000..d2bb3234 --- /dev/null +++ b/zanzocam/data/send-logs.flag @@ -0,0 +1 @@ +YES \ No newline at end of file diff --git a/zanzocam/web_ui/api.py b/zanzocam/web_ui/api.py index 7c969963..9120ba4a 100644 --- a/zanzocam/web_ui/api.py +++ b/zanzocam/web_ui/api.py @@ -110,15 +110,6 @@ def set_upload_interval(value: int) -> str: except ValueError as e: abort(500, f"invalid value for the random interval field: {value}") -def toggle_hotspot(value: str) -> str: - """ - Allow the initial hotspot to turn on in case no known wifi network is detected. - """ - value = value.upper().strip() - if value == "YES" or value == "NO": - return "", toggle_flag(HOTSPOT_FLAG, value) - abort(404) - def toggle_send_logs(value: str) -> str: """ diff --git a/zanzocam/web_ui/pages.py b/zanzocam/web_ui/pages.py index 0a51d913..b7aa2641 100644 --- a/zanzocam/web_ui/pages.py +++ b/zanzocam/web_ui/pages.py @@ -13,14 +13,12 @@ def home_page(): """ The initial page with the summary """ - hotspot_value = read_flag_file(HOTSPOT_FLAG, "YES") network_data = read_network_data() network_data["wifi_data"] = get_wifi_data() server_data = read_setup_data_file(CONFIGURATION_FILE).get('server', {}) return render_template("home.html", title="Setup", version=VERSION, - hotspot_value=hotspot_value, network_data=network_data, server_data=server_data) diff --git a/zanzocam/web_ui/templates/home.html b/zanzocam/web_ui/templates/home.html index c173b369..cc76daea 100644 --- a/zanzocam/web_ui/templates/home.html +++ b/zanzocam/web_ui/templates/home.html @@ -83,24 +83,6 @@

Logs:

-
-
-

Hotspot:

- - -
-
-

NOTA BENE: Questo switch serve per permettere a ZanzoCam di generare o meno un hotspot quando perde contatto - con qualunque rete WiFi nota. Questo switch NON attiva l'hotspot se ZanzoCam è gia' in grado di collegarsi - con un'altra rete WiFi o è collegata via rete Ethernet.
-

-

Riavvia ZanzoCam:

@@ -138,51 +120,6 @@

Riavvia ZanzoCam:

field.innerHTML=""; } } - - function hotspotNO() { - confirmation = confirm("ATTENZIONE! Una volta premuto questo bottone, " + - "ZanzoCam smettera' di produrre il suo hotspot in caso di " + - "assenza di WiFi.\n\n" + - "Sei sicuro\a di voler proseguire?"); - if(confirmation){ - fetch("/configure/hotspot/NO", { - method:'POST', - }) - .then(r => { - if (r.status === 200){ - alert("Modifica completata con successo."); - } else { - alert("Qualcosa è andato storto! " + - "ZanzoCam ha risposto con un codice "+ r.status +"."); - } - }).catch(r => { - alert("Qualcosa è andato storto! " + - "ZanzoCam non è raggiungibile."); - }) - } - } - function hotspotYES() { - confirmation = confirm("ATTENZIONE! Una volta premuto questo bottone, " + - "ZanzoCam comincera' a produrre il suo hotspot in caso di " + - "assenza di WiFi.\n\n" + - "Sei sicuro\a di voler proseguire?"); - if(confirmation){ - fetch("/configure/hotspot/YES", { - method:'POST', - }) - .then(r => { - if (r.status === 200){ - alert("Modifica completata con successo."); - } else { - alert("Qualcosa è andato storto! " + - "ZanzoCam ha risposto con un codice "+ r.status +"."); - } - }).catch(r => { - alert("Qualcosa è andato storto! " + - "ZanzoCam non è raggiungibile."); - }) - } - } {% endblock %} diff --git a/zanzocam/webcam/system.py b/zanzocam/webcam/system.py index 3da78628..3e97e607 100644 --- a/zanzocam/webcam/system.py +++ b/zanzocam/webcam/system.py @@ -61,21 +61,14 @@ def report_general_status() -> Dict: status["last reboot"] = get_last_reboot_time() status["uptime"] = get_uptime() - hotspot_allowed = check_hotspot_allowed() - if hotspot_allowed: - status["hotspot allowed"] = "YES" - else: - status["hotspot allowed"] = "NO" - - if status["hotspot allowed"] != "NO": - autohotspot_status = run_autohotspot() - if autohotspot_status is None: - status["hotspot status"] = "FAILED (see stacktrace)" - else: - if autohotspot_status: - status["hotspot status"] = "OFF (connected to WiFi)" - else: - status["hotspot status"] = "ON (no known WiFi in range)" + autohotspot_status = run_autohotspot() + if autohotspot_status is None: + status["hotspot status"] = "FAILED (see stacktrace)" + else: + if autohotspot_status: + status["hotspot status"] = "OFF (connected to WiFi)" + else: + status["hotspot status"] = "ON (no known WiFi in range)" status['wifi data'] = get_wifi_data() status['internet access'] = check_internet_connectivity() @@ -136,41 +129,6 @@ def get_uptime() -> Optional[datetime.timedelta]: except Exception as e: log_error("Could not get uptime information", e) return None - - - -def check_hotspot_allowed() -> Optional[str]: - """ - Checks whether ZANZOCAM can turn on its hotspot at need. - True if it can, False otherwise. - If the file was not found, it creates it with a value YES. - In case of exceptions, defaults to True. - """ - if os.path.exists(HOTSPOT_FLAG): - try: - with open(HOTSPOT_FLAG, "r+") as h: - content = h.read().strip() - if content.upper() == "YES": - return True - elif content.upper() == "NO": - return False - else: - log("The hostpot flag contains neither YES nor NO " - f"(it contains '{content}'). Please fix. " - "Assuming YES.") - return True - - except Exception as e: - log_error("Failed to check if the hotspot is allowed. " - "Assuming YES", e) - return True - - log(f"Hotspot flag file not found. Creating it under {HOTSPOT_FLAG}" - f" with value YES") - with open(HOTSPOT_FLAG, "w") as h: - h.write("YES") - return True - def run_autohotspot() -> Optional[bool]: From 2f87f4c64d35bbda6bff1f9bdc7a9e0e22efff7f Mon Sep 17 00:00:00 2001 From: ZanSara Date: Fri, 20 Dec 2024 15:58:58 +0000 Subject: [PATCH 3/4] rename upload interval file --- .gitignore | 2 +- zanzocam/data/upload-interval.txt | 1 + zanzocam/web_ui/api.py | 2 +- zanzocam/web_ui/pages.py | 5 +++-- zanzocam/webcam/server/server.py | 2 +- zanzocam/webcam/system.py | 2 +- 6 files changed, 8 insertions(+), 6 deletions(-) create mode 100644 zanzocam/data/upload-interval.txt diff --git a/.gitignore b/.gitignore index 430367c2..79a77549 100644 --- a/.gitignore +++ b/.gitignore @@ -5,7 +5,7 @@ zanzocam/web_ui/static/previews/* zanzocam/data/* !zanzocam/data/send-logs.flag -!zanzocam/data/upload_interval.txt +!zanzocam/data/upload-interval.txt **/build/*.* diff --git a/zanzocam/data/upload-interval.txt b/zanzocam/data/upload-interval.txt new file mode 100644 index 00000000..7813681f --- /dev/null +++ b/zanzocam/data/upload-interval.txt @@ -0,0 +1 @@ +5 \ No newline at end of file diff --git a/zanzocam/web_ui/api.py b/zanzocam/web_ui/api.py index 9120ba4a..23656e09 100644 --- a/zanzocam/web_ui/api.py +++ b/zanzocam/web_ui/api.py @@ -106,7 +106,7 @@ def set_upload_interval(value: int) -> str: """ try: int(value) - return "", write_text_file(Path(__file__).parent.parent / "data" / "upload_interval.txt", value) + return "", write_text_file(Path(__file__).parent.parent / "data" / "upload-interval.txt", value) except ValueError as e: abort(500, f"invalid value for the random interval field: {value}") diff --git a/zanzocam/web_ui/pages.py b/zanzocam/web_ui/pages.py index b7aa2641..2bd69b0c 100644 --- a/zanzocam/web_ui/pages.py +++ b/zanzocam/web_ui/pages.py @@ -1,5 +1,6 @@ import os import shutil +import logging from datetime import datetime from typing import OrderedDict @@ -34,9 +35,9 @@ def server_page(): """ The page with the server data forms """ server_data = read_setup_data_file(CONFIGURATION_FILE).get('server', {}) try: - server_data["random_upload_interval"] = int(read_flag_file(DATA_PATH / "upload_interval.txt", default="5")) + server_data["random_upload_interval"] = int(read_flag_file(DATA_PATH / "upload-interval.txt", default="5")) except Exception as e: - logging.exception("data/upload_interval.txt does not contain an integer value. Overwriting its value with 5 seconds.") + logging.exception("data/upload-interval.txt does not contain an integer value. Overwriting its value with 5 seconds.") server_data["random_upload_interval"] = 5 return render_template("server.html", title="Setup Server", diff --git a/zanzocam/webcam/server/server.py b/zanzocam/webcam/server/server.py index 0fcda43f..1447305e 100644 --- a/zanzocam/webcam/server/server.py +++ b/zanzocam/webcam/server/server.py @@ -155,7 +155,7 @@ def upload_picture(self, image_path: Path, image_name: str, """ # Wait a random time, if enabled try: - random_upload_interval = int(read_flag_file(DATA_PATH / "upload_interval.txt", default="5")) + random_upload_interval = int(read_flag_file(DATA_PATH / "upload-interval.txt", default="5")) except Exception as e: log_error("Can't read the upload interval value. Defaulting to 5 seconds.", e) random_upload_interval = 5 diff --git a/zanzocam/webcam/system.py b/zanzocam/webcam/system.py index 3e97e607..9625bea7 100644 --- a/zanzocam/webcam/system.py +++ b/zanzocam/webcam/system.py @@ -83,7 +83,7 @@ def report_general_status() -> Dict: def get_max_random_upload_interval(): try: - random_upload_interval = int(read_flag_file(DATA_PATH / "upload_interval.txt", default="5")) + random_upload_interval = int(read_flag_file(DATA_PATH / "upload-interval.txt", default="5")) except Exception as e: log_error("Can't read the upload interval value. Defaulting to 5 seconds.", e) random_upload_interval = 5 From f6e25fd3a8ab21e4934c7e0d217f57664e294e50 Mon Sep 17 00:00:00 2001 From: ZanSara Date: Fri, 20 Dec 2024 16:06:28 +0000 Subject: [PATCH 4/4] remove stray attr --- tests/conftest.py | 1 - 1 file changed, 1 deletion(-) diff --git a/tests/conftest.py b/tests/conftest.py index 70cb1636..4a85148c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -94,7 +94,6 @@ def mock_modules_apart_config(monkeypatch): monkeypatch.setattr(main, 'Server', MockServer) monkeypatch.setattr(main, 'Camera', MockCamera) monkeypatch.setattr(main, 'WAIT_AFTER_CAMERA_FAIL', 1) - monkeypatch.setattr(server.server, 'RANDOM_UPLOAD_INTERVAL', 0) monkeypatch.setattr(utils, "sleep", lambda *a, **k: None)