Skip to content

Commit

Permalink
Merge pull request #36 from ZanzoCam/restore-1.3.2
Browse files Browse the repository at this point in the history
Restore state at 1.3.2 with minor changes
  • Loading branch information
ZanSara authored Dec 20, 2024
2 parents 46a5d74 + f6e25fd commit 4b977b9
Show file tree
Hide file tree
Showing 10 changed files with 77 additions and 74 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -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/*.*

Expand Down
3 changes: 1 addition & 2 deletions tests/unit_tests/test_webcam_system.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +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_run_hotspot_on_wifi_1(fake_process, logs):
"""
Check if the hotspot runs, normal behavior on wifi.
Expand Down Expand Up @@ -348,7 +347,7 @@ 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()
Expand Down
10 changes: 1 addition & 9 deletions zanzocam/constants.py
Original file line number Diff line number Diff line change
@@ -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.4"

VERSION = "1.3.5"

# Executables constants
# #####################
Expand Down Expand Up @@ -97,9 +92,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'

Expand Down
File renamed without changes.
2 changes: 1 addition & 1 deletion zanzocam/web_ui/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}")

Expand Down
7 changes: 4 additions & 3 deletions zanzocam/web_ui/pages.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import os
import shutil
import logging
from datetime import datetime
from typing import OrderedDict

Expand All @@ -18,7 +19,7 @@ def home_page():
server_data = read_setup_data_file(CONFIGURATION_FILE).get('server', {})
return render_template("home.html",
title="Setup",
version=VERSION,
version=VERSION,
network_data=network_data,
server_data=server_data)

Expand All @@ -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",
Expand Down
57 changes: 51 additions & 6 deletions zanzocam/web_ui/templates/network.html
Original file line number Diff line number Diff line change
Expand Up @@ -2,22 +2,53 @@

{% block content %}
<div id="page">

<form id="config" method="POST" action="/configure/network">
<label for="network_ssid">Nome della rete (SSID):</label>
<input type="text" name="network_ssid" value="{{ network_data.ssid }}">
<!--div class="row">
<p style="margin-top: 1rem; margin-bottom: 1rem; margin-right:3rem;">Tipo di connessione:</p>
<label class="toggle">
<input type="radio" value="WiFi" name="network_type" {% if network_data.type=="WiFI" %}checked{%endif%} onclick="javascript:toggle_network_type('wifi')" style="display:none;">
<span class="label">WiFI</span>
</label>
<label class="toggle">
<input type="radio" value="Ethernet" name="network_type" {% if network_data.type=="Ethernet" %}checked{%endif%} onclick="javascript:toggle_network_type('ethernet')" style="display:none;">
<span class="label">Ethernet</span>
</label>
<label class="toggle">
<input type="radio" value="SIM" name="network_type" {% if network_data.type=="SIM" %}checked{%endif%} onclick="javascript:toggle_network_type('sim')" style="display:none;">
<span class="label">SIM</span>
</label>
</div>
<div id="wifi-vars" style="display: none; flex-direction:column!important;"-->
<label for="network_ssid">Nome della rete (SSID):</label>
<input type="text" name="network_ssid" value="{{ network_data.ssid }}">

<label for="network_password">Password:</label>
<div class="row">
<input type="password" name="network_password" value="{{ network_data.password }}">
<button onclick="toggle_password(this)" type="button">Mostra</button>
</div>
<!--/div>
<label for="network_password">Password:</label>
<div class="row">
<input type="password" name="network_password" value="{{ network_data.password }}">
<button onclick="toggle_password(this)" type="button">Mostra</button>
<div id="ethernet-vars" style="display: none;">
</div>
<div id="sim-vars" style="display: none;">
<label for="network_apn">APN:</label>
<input type="text" name="network_apn" value="{{ network_data.apn }}">
</div-->

<div class="center">
<button id="configure-network" class="button setup-button">Configura la rete</button>
<a href="/" class="button button-outline setup-button">Indietro</a>
</div>

</form>

</div>


<script>
function toggle_password(button) {
if( button.innerHTML == 'Mostra' ) {
Expand All @@ -28,6 +59,20 @@
button.previousElementSibling.type="password";
}
}

function toggle_network_type(value){
// Toggle wifi, ethernet or sim blocks on the page
var wifi_block = document.getElementById("wifi-vars");
var ethernet_block = document.getElementById("ethernet-vars");
var sim_block = document.getElementById("sim-vars");

value = value.toLowerCase()
wifi_block.style.display = value==="wifi" ? "block" : "none";
ethernet_block.style.display = value==="ethernet" ? "block" : "none";
sim_block.style.display = value==="sim" ? "block" : "none";
}
toggle_network_type("{{ network_data.type }}");

</script>

{% endblock %}
2 changes: 1 addition & 1 deletion zanzocam/webcam/server/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
66 changes: 16 additions & 50 deletions zanzocam/webcam/system.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import requests
import datetime
import subprocess
from time import sleep
from pathlib import Path
from textwrap import dedent

Expand All @@ -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
Expand All @@ -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.
Expand All @@ -74,27 +61,16 @@ 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()

status['wifi data'] = get_wifi_data()
if status['wifi data'] and "ssid" in status['wifi data'] and status['wifi data']["ssid"] == "n/a":

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.
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)"
status['wifi data'] = get_wifi_data()
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()

Expand All @@ -105,21 +81,9 @@ 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"))
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
Expand Down Expand Up @@ -559,3 +523,5 @@ def prepare_crontab_string(time: Dict, length: Optional[int] = None) -> List[str
start_total_minutes += frequency

return cron_strings


0 comments on commit 4b977b9

Please sign in to comment.