-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathbirdnet_display.py
More file actions
747 lines (649 loc) · 27.7 KB
/
Copy pathbirdnet_display.py
File metadata and controls
747 lines (649 loc) · 27.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
import requests
from flask import Flask, render_template, url_for, send_file, request, jsonify
from urllib.parse import urljoin
from datetime import datetime, timedelta
import os
import random
import socket
import qrcode
import io
import json
import sys
import subprocess
import re
# Import variables and functions from the new cache builder script
from cache_builder import CACHE_DIRECTORY, SPECIES_FILE, load_species_from_file
# --- Constants and Configuration ---
BASE_URL = "http://localhost:8080/"
API_ENDPOINT = "api/v2/detections/recent"
HEADERS = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
'Accept': 'application/json'
}
PROXIES = {"http": None, "https": None}
SERVER_PORT = 5000
PINNED_SPECIES_FILE = "pinned_species.json"
PINNED_DURATION_HOURS = 24
# --- Flask App Initialization ---
app = Flask(__name__, template_folder='static')
# --- Caching & Status Globals ---
DETECTION_CACHE = { "id": None, "raw_data": [] }
# --- Pinned Species Management ---
def load_pinned_species():
"""Load pinned species from JSON file."""
if not os.path.exists(PINNED_SPECIES_FILE):
return {}
try:
with open(PINNED_SPECIES_FILE, 'r', encoding='utf-8') as f:
return json.load(f)
except (IOError, json.JSONDecodeError) as e:
print(f"Error loading pinned species file: {e}")
return {}
def save_pinned_species(pinned_data):
"""Save pinned species to JSON file."""
try:
with open(PINNED_SPECIES_FILE, 'w', encoding='utf-8') as f:
json.dump(pinned_data, f, indent=2)
except IOError as e:
print(f"Error saving pinned species file: {e}")
def add_pinned_species(species_name):
"""Add a species to the pinned list with 24-hour expiration."""
pinned = load_pinned_species()
# Only add if not already present (dismissed or not)
if species_name not in pinned:
pinned[species_name] = {
'pinned_until': (datetime.now() + timedelta(hours=PINNED_DURATION_HOURS)).isoformat(),
'dismissed': False
}
save_pinned_species(pinned)
def dismiss_pinned_species(species_name):
"""Mark a pinned species as dismissed."""
pinned = load_pinned_species()
if species_name in pinned:
pinned[species_name]['dismissed'] = True
save_pinned_species(pinned)
return True
return False
def get_active_pinned_species():
"""Get list of currently active (not expired, not dismissed) pinned species."""
pinned = load_pinned_species()
active = {}
now = datetime.now()
for species_name, data in list(pinned.items()):
pinned_until = datetime.fromisoformat(data['pinned_until'])
if not data.get('dismissed', False) and now < pinned_until:
active[species_name] = data
elif now >= pinned_until:
# Clean up expired entries
del pinned[species_name]
if len(pinned) != len(active):
save_pinned_species(pinned)
return active
# --- IP and QR Code Helpers ---
def get_local_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
def get_interface_ip(interface):
"""Get IP address for a specific network interface."""
try:
result = subprocess.run(
['ip', 'addr', 'show', interface],
capture_output=True, text=True, timeout=5
)
# Parse output for inet address
match = re.search(r'inet\s+(\d+\.\d+\.\d+\.\d+)', result.stdout)
if match:
return match.group(1)
except Exception as e:
print(f"[INFO] Could not get IP for {interface}: {e}")
return None
def is_wlan0_connected():
"""Check if wlan0 is connected to a WiFi network."""
try:
result = subprocess.run(
['nmcli', '-t', '-f', 'DEVICE,STATE', 'device', 'status'],
capture_output=True, text=True, timeout=5
)
for line in result.stdout.strip().split('\n'):
if line.startswith('wlan0:'):
state = line.split(':')[1]
return state == 'connected'
except Exception as e:
print(f"[INFO] Could not check wlan0 status: {e}")
return False
def get_ap_info():
"""Get Access Point information for wlan1."""
try:
# Get wlan1 IP address
wlan1_ip = get_interface_ip('wlan1')
if not wlan1_ip:
wlan1_ip = "10.42.0.1" # Default AP IP
# Get AP SSID from NetworkManager connection
ssid = None
password = None
# Try to get active AP connection on wlan1
result = subprocess.run(
['nmcli', '-t', '-f', 'NAME,DEVICE', 'connection', 'show', '--active'],
capture_output=True, text=True, timeout=5
)
ap_connection_name = None
for line in result.stdout.strip().split('\n'):
if 'wlan1' in line:
ap_connection_name = line.split(':')[0]
break
if ap_connection_name:
# Get SSID
result = subprocess.run(
['nmcli', '-t', '-f', '802-11-wireless.ssid', 'connection', 'show', ap_connection_name],
capture_output=True, text=True, timeout=5
)
ssid_line = result.stdout.strip()
if ssid_line and ':' in ssid_line:
ssid = ssid_line.split(':', 1)[1]
# Get password
result = subprocess.run(
['nmcli', '-s', '-t', '-f', '802-11-wireless-security.psk', 'connection', 'show', ap_connection_name],
capture_output=True, text=True, timeout=5
)
password_line = result.stdout.strip()
if password_line and ':' in password_line:
password = password_line.split(':', 1)[1]
return {
'ssid': ssid or 'Birdhost',
'password': password or 'birdnetpass',
'ip': wlan1_ip
}
except Exception as e:
print(f"[INFO] Could not get AP info: {e}")
return {
'ssid': 'Birdhost',
'password': 'birdnetpass',
'ip': '10.42.0.1'
}
@app.route('/qr_code.png')
def qr_code():
ip = get_local_ip()
url = f"http://{ip}:8080"
img = qrcode.make(url)
buf = io.BytesIO()
img.save(buf)
buf.seek(0)
return send_file(buf, mimetype='image/png')
@app.route('/api/connection_info')
def connection_info():
"""Return connection information based on wlan0 status."""
wlan0_connected = is_wlan0_connected()
if wlan0_connected:
# Normal mode - show regular IP and QR
ip = get_local_ip()
return jsonify({
'mode': 'connected',
'ip': ip,
'url': f"http://{ip}:8080"
})
else:
# AP mode - show AP details
ap_info = get_ap_info()
return jsonify({
'mode': 'ap',
'ssid': ap_info['ssid'],
'password': ap_info['password'],
'ip': ap_info['ip'],
'url': f"http://{ap_info['ip']}:5000"
})
# --- Time Helper Functions ---
def parse_absolute_time_to_seconds_ago(time_str):
if not time_str: return 0
try:
time_format = "%Y-%m-%d %H:%M:%S"
detection_time = datetime.strptime(time_str, time_format)
time_difference = datetime.now() - detection_time
return max(0, time_difference.total_seconds())
except (ValueError, TypeError):
return 0
def format_seconds_ago(total_seconds):
if total_seconds < 60: return f"{int(total_seconds)}s ago"
minutes = total_seconds / 60
if minutes < 60: return f"{int(minutes)}m ago"
hours = minutes / 60
if hours < 24: return f"{int(hours)}h ago"
return f"{int(hours / 24)}d ago"
# --- Data Parsing and API Helpers ---
def check_image_url_fast(url):
"""Quick check if an image URL is accessible with very short timeout."""
try:
response = requests.head(url, timeout=0.5)
return response.status_code == 200
except requests.exceptions.RequestException:
return False
def parse_v2_detection_item(detection, server_ip):
try:
name = detection.get('commonName', 'Unknown Species')
time_raw = f"{detection.get('date', '')} {detection.get('time', '')}".strip()
confidence_value = int(detection.get('confidence', 0.0) * 100)
species_code = detection.get('speciesCode')
image_url = f"http://{server_ip}:8080/api/v2/species/{species_code}/thumbnail" if species_code else ""
is_new_species = detection.get('isNewSpecies', False)
return {
"name": name, "time_raw": time_raw, "confidence_value": confidence_value,
"image_url": image_url, "copyright": "", "is_new_species": is_new_species
}
except (AttributeError, TypeError, KeyError) as e:
print(f"Warning: Could not parse a v2 detection item, skipping. Error: {e}, Data: {detection}")
return None
# --- Core Data Fetching Logic ---
def get_cached_image(species_name):
species_folder_name = "".join(c for c in species_name if c.isalnum() or c in ' _').rstrip().replace(' ', '_')
species_dir = os.path.join(CACHE_DIRECTORY, species_folder_name)
if os.path.isdir(species_dir):
images = sorted([f for f in os.listdir(species_dir) if f.lower().endswith(('.png', '.jpg', '.jpeg'))])
if not images: return None
chosen_image = random.choice(images)
attr_path = os.path.join(species_dir, f"{os.path.splitext(chosen_image)[0]}.txt")
copyright_info = ""
if os.path.exists(attr_path):
with open(attr_path, 'r', encoding='utf-8') as f: copyright_info = f.read().strip()
image_url = url_for('static', filename=os.path.join(os.path.basename(CACHE_DIRECTORY), species_folder_name, chosen_image).replace('\\', '/'))
return {"image_url": image_url, "copyright": copyright_info}
return None
def get_offline_fallback_data():
print("[INFO] Loading data from local cache.")
species_list = load_species_from_file(SPECIES_FILE)
if not species_list: return []
# Filter species to only those with cached images
species_with_images = []
for common_name, scientific_name in species_list:
cached_asset = get_cached_image(common_name)
if cached_asset:
species_with_images.append((common_name, scientific_name, cached_asset))
if not species_with_images:
print("[WARNING] No cached images found for any species")
return []
# Sample from species that actually have images
num_to_sample = min(len(species_with_images), 4)
sampled_species = random.sample(species_with_images, num_to_sample)
fallback_data = []
for common_name, scientific_name, cached_asset in sampled_species:
fallback_data.append({
"name": common_name, "time_display": "Offline", "confidence": "0%",
"confidence_value": 0, "image_url": cached_asset['image_url'],
"copyright": cached_asset['copyright'], "time_raw": "", "is_offline": True
})
return fallback_data
def get_bird_data():
server_ip = get_local_ip()
api_url = urljoin(BASE_URL, API_ENDPOINT)
params = {'limit': 200} # Increased from 50 to get more detection history
try:
response = requests.get(api_url, headers=HEADERS, proxies=PROXIES, timeout=10, params=params)
response.raise_for_status()
detections = response.json()
if not isinstance(detections, list) or not detections:
return get_offline_fallback_data(), True
all_parsed = [d for d in [parse_v2_detection_item(item, server_ip) for item in detections] if d]
if not all_parsed:
return get_offline_fallback_data(), True
# Process new species and add to pinned list
for bird in all_parsed:
if bird.get('is_new_species', False):
add_pinned_species(bird['name'])
# Get currently active pinned species
active_pinned = get_active_pinned_species()
# Separate pinned and unpinned birds
pinned_birds = []
unpinned_birds = []
for bird in all_parsed:
if bird['name'] in active_pinned:
bird['is_pinned'] = True
if bird['name'] not in [b['name'] for b in pinned_birds]:
pinned_birds.append(bird)
else:
bird['is_pinned'] = False
unpinned_birds.append(bird)
# Get unique unpinned species (deduplicate by name)
unique_unpinned = []
seen_names = set()
for bird in unpinned_birds:
if bird['name'] not in seen_names:
unique_unpinned.append(bird)
seen_names.add(bird['name'])
print(f"[DEBUG] Found {len(pinned_birds)} pinned birds and {len(unique_unpinned)} unique unpinned species from {len(all_parsed)} total detections")
# Combine: pinned first, then unpinned
combined_list = pinned_birds + unique_unpinned
# Check image URLs and filter out birds without valid images
final_list = []
for bird in combined_list:
has_valid_image = False
if bird.get('image_url'):
if check_image_url_fast(bird['image_url']):
has_valid_image = True
else:
# API image not available, try cache
cached_asset = get_cached_image(bird['name'])
if cached_asset:
bird['image_url'] = cached_asset['image_url']
bird['copyright'] = cached_asset['copyright']
has_valid_image = True
else:
# No image URL from API, use cache
cached_asset = get_cached_image(bird['name'])
if cached_asset:
bird['image_url'] = cached_asset['image_url']
bird['copyright'] = cached_asset['copyright']
has_valid_image = True
# Only include birds with valid images
if has_valid_image:
final_list.append(bird)
if len(final_list) >= 4:
break
print(f"[DEBUG] Final list has {len(final_list)} birds with valid images")
new_id = "-".join([f"{d['name']}_{d['time_raw']}" for d in final_list])
if new_id == DETECTION_CACHE["id"]:
data_to_process = DETECTION_CACHE["raw_data"]
else:
DETECTION_CACHE["raw_data"] = final_list
DETECTION_CACHE["id"] = new_id
data_to_process = final_list
display_data = []
for bird in data_to_process:
bird_display_copy = bird.copy()
bird_display_copy['time_display'] = format_seconds_ago(parse_absolute_time_to_seconds_ago(bird['time_raw']))
bird_display_copy['confidence'] = f"{bird['confidence_value']}%"
display_data.append(bird_display_copy)
return display_data, False
except requests.exceptions.RequestException:
print("[INFO] BirdNET-Go API unavailable, using offline mode")
return get_offline_fallback_data(), True
# --- Flask Routes ---
@app.route('/')
def index():
bird_data, api_is_down = get_bird_data()
if not os.path.exists('static'): os.makedirs('static')
template_path = 'index.html'
if not os.path.exists(os.path.join('static', template_path)):
with open(os.path.join('static', template_path), 'w') as f:
f.write('<h1>Template file not found. Please create an index.html file.</h1>')
refresh_interval = 30 if api_is_down else 5
server_url = f"http://{get_local_ip()}:8080"
return render_template(
template_path, birds=bird_data, refresh_interval=refresh_interval,
api_is_down=api_is_down, server_url=server_url
)
@app.route('/data')
def data():
bird_data, api_is_down = get_bird_data()
return jsonify({'birds': bird_data, 'api_is_down': api_is_down})
@app.route('/audio_status')
def audio_status():
try:
status_url = "http://10.42.0.50/api/status"
response = requests.get(status_url, timeout=5)
response.raise_for_status()
status_data = response.json()
is_connected = status_data.get("streaming") is True
rssi = status_data.get("wifi_rssi", 0) # Get WiFi RSSI value, default to 0 if not present
except (requests.exceptions.RequestException, json.JSONDecodeError, KeyError):
print("[INFO] Microphone status unavailable")
is_connected = False
rssi = 0
return jsonify({"connected": is_connected, "rssi": rssi})
@app.route('/shutdown', methods=['POST'])
def shutdown():
shutdown_func = request.environ.get('werkzeug.server.shutdown')
if shutdown_func:
print("Shutdown request received. Shutting down server...")
shutdown_func()
return 'Server is shutting down...'
else:
print('Error: Not running with the Werkzeug Server. Cannot shut down.')
return 'Server not running with Werkzeug.', 500
@app.route('/brightness', methods=['POST'])
def set_brightness():
try:
brightness = request.json.get('brightness')
if brightness is not None and 0 <= int(brightness) <= 255:
command = f"echo {brightness} | sudo tee /sys/class/backlight/10-0045/brightness"
print(f"Executing brightness command: {command}")
os.system(command)
return jsonify({'status': 'success', 'brightness': brightness})
return jsonify({'status': 'error', 'message': 'Invalid brightness value'}), 400
except Exception as e:
print(f"Error setting brightness: {e}")
return jsonify({'status': 'error', 'message': str(e)}), 500
@app.route('/reboot', methods=['POST'])
def reboot_system():
print("Executing reboot command...")
os.system('sudo reboot')
return jsonify({'status': 'rebooting'})
@app.route('/poweroff', methods=['POST'])
def poweroff_system():
print("Executing power off command...")
os.system('sudo poweroff')
return jsonify({'status': 'shutting down'})
@app.route('/api/pinned_species')
def get_pinned_species():
"""Return list of currently pinned species with time remaining."""
active_pinned = get_active_pinned_species()
now = datetime.now()
result = []
for species_name, data in active_pinned.items():
pinned_until = datetime.fromisoformat(data['pinned_until'])
time_remaining = pinned_until - now
hours_remaining = int(time_remaining.total_seconds() / 3600)
result.append({
'name': species_name,
'hours_remaining': hours_remaining,
'pinned_until': data['pinned_until']
})
return jsonify(result)
@app.route('/api/dismiss_pinned/<species_name>', methods=['POST'])
def dismiss_pinned(species_name):
"""Dismiss a pinned species."""
success = dismiss_pinned_species(species_name)
if success:
return jsonify({'status': 'success', 'message': f'{species_name} dismissed'})
else:
return jsonify({'status': 'error', 'message': f'{species_name} not found in pinned list'}), 404
@app.route('/api/dismiss_all_pinned', methods=['POST'])
def dismiss_all_pinned():
"""Dismiss all pinned species."""
try:
pinned = load_pinned_species()
for species_name in pinned:
pinned[species_name]['dismissed'] = True
save_pinned_species(pinned)
return jsonify({'status': 'success', 'message': 'All pinned species dismissed'})
except Exception as e:
return jsonify({'status': 'error', 'message': str(e)}), 500
@app.route('/api/wifi/scan', methods=['GET'])
def wifi_scan():
"""Scan for available WiFi networks using nmcli on wlan0."""
try:
result = subprocess.run(
['nmcli', '-t', '-f', 'SSID,SIGNAL,SECURITY', 'dev', 'wifi', 'list', 'ifname', 'wlan0'],
capture_output=True,
text=True,
timeout=10
)
if result.returncode != 0:
return jsonify({'status': 'error', 'message': 'Failed to scan WiFi networks'}), 500
networks = []
seen_ssids = set()
for line in result.stdout.strip().split('\n'):
if not line:
continue
parts = line.split(':')
if len(parts) >= 3:
ssid = parts[0].strip()
signal = parts[1].strip()
security = parts[2].strip()
# Skip empty SSIDs and duplicates
if ssid and ssid not in seen_ssids:
networks.append({
'ssid': ssid,
'signal': signal,
'security': security if security else 'Open'
})
seen_ssids.add(ssid)
# Sort by signal strength (descending)
networks.sort(key=lambda x: int(x['signal']) if x['signal'].isdigit() else 0, reverse=True)
return jsonify({'status': 'success', 'networks': networks})
except subprocess.TimeoutExpired:
return jsonify({'status': 'error', 'message': 'WiFi scan timeout'}), 500
except Exception as e:
print(f"Error scanning WiFi: {e}")
return jsonify({'status': 'error', 'message': str(e)}), 500
@app.route('/api/wifi/connect', methods=['POST'])
def wifi_connect():
"""Connect to a WiFi network using nmcli on wlan0."""
try:
data = request.json
ssid = data.get('ssid')
password = data.get('password', '')
if not ssid:
return jsonify({'status': 'error', 'message': 'SSID is required'}), 400
# First, try to delete any existing connection with this SSID to avoid conflicts
subprocess.run(
['nmcli', 'con', 'delete', ssid],
capture_output=True,
text=True,
timeout=5
)
# Ignore errors from delete - connection might not exist
# Scan to find the network and its security type
scan_result = subprocess.run(
['nmcli', '-t', '-f', 'SSID,SECURITY', 'dev', 'wifi', 'list', 'ifname', 'wlan0'],
capture_output=True,
text=True,
timeout=10
)
security_type = None
if scan_result.returncode == 0:
for line in scan_result.stdout.strip().split('\n'):
if line.startswith(f"{ssid}:"):
parts = line.split(':')
if len(parts) >= 2:
security_type = parts[1].strip()
break
# Connect to network on wlan0 interface
if not password or security_type == '' or security_type == 'Open':
# Connect to open network (no password)
result = subprocess.run(
['nmcli', 'dev', 'wifi', 'connect', ssid, 'ifname', 'wlan0'],
capture_output=True,
text=True,
timeout=30
)
else:
# For WPA/WPA2 networks, use connection add with explicit security settings
# Delete any auto-created connection first
subprocess.run(['nmcli', 'con', 'delete', ssid], capture_output=True, timeout=5)
# Create connection with explicit WPA-PSK security
result = subprocess.run(
['nmcli', 'con', 'add',
'type', 'wifi',
'ifname', 'wlan0',
'con-name', ssid,
'ssid', ssid,
'wifi-sec.key-mgmt', 'wpa-psk',
'wifi-sec.psk', password],
capture_output=True,
text=True,
timeout=10
)
if result.returncode != 0:
error_msg = result.stderr.strip() if result.stderr else 'Failed to create connection'
return jsonify({'status': 'error', 'message': error_msg}), 500
# Now activate the connection
result = subprocess.run(
['nmcli', 'con', 'up', ssid, 'ifname', 'wlan0'],
capture_output=True,
text=True,
timeout=30
)
if result.returncode == 0:
return jsonify({'status': 'success', 'message': f'Connected to {ssid}'})
else:
error_msg = result.stderr.strip() if result.stderr else 'Connection failed'
return jsonify({'status': 'error', 'message': error_msg}), 500
except subprocess.TimeoutExpired:
return jsonify({'status': 'error', 'message': 'Connection timeout'}), 500
except Exception as e:
print(f"Error connecting to WiFi: {e}")
return jsonify({'status': 'error', 'message': str(e)}), 500
@app.route('/api/wifi/current', methods=['GET'])
def wifi_current():
"""Get currently connected WiFi network on wlan0."""
try:
# Get connection status for wlan0 device
result = subprocess.run(
['nmcli', '-t', '-f', 'GENERAL.CONNECTION', 'dev', 'show', 'wlan0'],
capture_output=True,
text=True,
timeout=5
)
if result.returncode != 0:
return jsonify({'status': 'error', 'message': 'Failed to get current network'}), 500
# Parse the connection name
for line in result.stdout.strip().split('\n'):
if line.startswith('GENERAL.CONNECTION:'):
connection = line.split(':', 1)[1].strip()
if connection and connection != '--':
# Connection name is usually the SSID
return jsonify({'status': 'success', 'ssid': connection})
return jsonify({'status': 'success', 'ssid': None})
except Exception as e:
print(f"Error getting current WiFi: {e}")
return jsonify({'status': 'error', 'message': str(e)}), 500
@app.route('/api/wifi/signal', methods=['GET'])
def wifi_signal():
"""Get WiFi signal strength for wlan0."""
try:
# Check if wlan0 is connected
state_result = subprocess.run(
['nmcli', '-g', 'GENERAL.STATE', 'dev', 'show', 'wlan0'],
capture_output=True,
text=True,
timeout=5
)
if state_result.returncode != 0:
return jsonify({'status': 'error', 'message': 'Failed to check WiFi state', 'signal': 0}), 200
state = state_result.stdout.strip()
# State will be something like "100 (connected)" or "30 (disconnected)"
if 'connected' not in state.lower():
return jsonify({'status': 'error', 'message': 'WiFi disconnected', 'signal': 0}), 200
# Get signal strength for active connection on wlan0
result = subprocess.run(
['nmcli', '-t', '-f', 'ACTIVE,SIGNAL', 'dev', 'wifi', 'list', 'ifname', 'wlan0'],
capture_output=True,
text=True,
timeout=5
)
if result.returncode != 0:
return jsonify({'status': 'error', 'message': 'Failed to get signal strength', 'signal': 0}), 200
# Find the active connection (marked with 'yes' in ACTIVE field)
lines = result.stdout.strip().split('\n')
for line in lines:
if line.startswith('yes:'):
signal_str = line.split(':')[1].strip()
if signal_str:
signal = int(signal_str)
return jsonify({'status': 'success', 'signal': signal})
return jsonify({'status': 'error', 'message': 'No active connection', 'signal': 0}), 200
except Exception as e:
print(f"Error getting WiFi signal: {e}")
return jsonify({'status': 'error', 'message': str(e), 'signal': 0}), 200
# --- Main Execution ---
if __name__ == '__main__':
if '--build-cache' in sys.argv:
print("To build the cache, please run 'python cache_builder.py' directly.")
sys.exit()
print(f"Starting Flask server on http://0.0.0.0:{SERVER_PORT}")
app.run(host='0.0.0.0', port=SERVER_PORT)