-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit.py
More file actions
2130 lines (1814 loc) · 83.3 KB
/
Copy pathinit.py
File metadata and controls
2130 lines (1814 loc) · 83.3 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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Smart Helmet Camera System v27.13-ULTIMATE (JSON GPS + location payload upload)
"""
import time
import os
import csv
import json
import datetime
import sys
import threading
import glob
import socket
import shutil
import logging
import logging.handlers
import re
import cv2
import numpy as np
import subprocess
import requests
from flask import Flask, Response, render_template, request, jsonify, send_from_directory, send_file
from dotenv import load_dotenv
import google.generativeai as genai
load_dotenv()
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
if GEMINI_API_KEY:
genai.configure(api_key=GEMINI_API_KEY)
from picamera2 import Picamera2
from picamera2.encoders import H264Encoder
from libcamera import Transform
from uploader import upload_to_cloud
from uploader import upload_image_to_cloud
try:
from gpiozero import Button, LED
GPIO_AVAILABLE = True
except Exception:
GPIO_AVAILABLE = False
VERSION = "v27.13-ULTIMATE"
RECORD_FOLDER = "recordings"
LOG_DIR = "logs"
PORT = 5001
CAM_WIDTH, CAM_HEIGHT = 1640, 1232
FPS = 24.0
STREAM_WIDTH = 1280
STREAM_HEIGHT = 720
MJPEG_QUALITY = 80
VIDEO_BITRATE = 1500000
AUTO_CHUNK_ENABLED = True
CHUNK_SIZE_MB = 60
CHUNK_CHECK_INTERVAL = 10
AUDIO_ENABLED_DEFAULT = True
AUDIO_SAMPLE_RATE = 44100
AUDIO_CHANNELS = 1
USB_MIC_DEVICE = "hw:3,0"
GPS_RECORD_INTERVAL = 5.0
DEVICE_ID = "smart_hm_02"
def get_serial_number():
try:
with open('/proc/cpuinfo', 'r') as f:
for line in f:
if line.startswith('Serial'):
return line.split(':')[1].strip()
except:
pass
return "smart_hm_02"
DEVICE_ID = get_serial_number()
GPIO_RECORD_BUTTON = int(os.getenv("GPIO_RECORD_BUTTON", "6"))
GPIO_PHOTO_BUTTON = int(os.getenv("GPIO_PHOTO_BUTTON", "13"))
GPIO_STREAM_LED = int(os.getenv("GPIO_STREAM_LED", "19"))
GPIO_RECORD_LED = int(os.getenv("GPIO_RECORD_LED", "26"))
OFFLINE_SYNC_INTERVAL = int(os.getenv("OFFLINE_SYNC_INTERVAL", "60"))
def get_lan_addresses():
addresses = []
try:
host = socket.gethostname()
for info in socket.getaddrinfo(host, None, socket.AF_INET):
ip = info[4][0]
if ip not in addresses and not ip.startswith("127."):
addresses.append(ip)
except Exception:
pass
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect(("8.8.8.8", 80))
ip = sock.getsockname()[0]
sock.close()
if ip not in addresses and not ip.startswith("127."):
addresses.append(ip)
except Exception:
pass
return addresses
def internet_available():
try:
socket.create_connection(("8.8.8.8", 53), timeout=3).close()
return True
except Exception:
return False
def gpio_control_worker():
global req_start_rec, req_stop_rec
if not GPIO_AVAILABLE:
logging.warning("[GPIO] gpiozero not available; GPIO controls disabled")
return
record_button = Button(GPIO_RECORD_BUTTON, pull_up=True, bounce_time=0.25)
photo_button = Button(GPIO_PHOTO_BUTTON, pull_up=True, bounce_time=0.25)
stream_led = LED(GPIO_STREAM_LED)
record_led = LED(GPIO_RECORD_LED)
def toggle_recording():
global req_start_rec, req_stop_rec
if is_recording_active:
req_stop_rec = True
logging.info("[GPIO] Stop recording requested")
else:
req_start_rec = True
logging.info("[GPIO] Start recording requested")
def capture_from_button():
try:
capture_photo()
record_led.off()
time.sleep(0.12)
record_led.on()
time.sleep(0.12)
if not is_recording_active:
record_led.off()
logging.info("[GPIO] Photo capture requested")
except Exception as exc:
logging.error(f"[GPIO] Photo capture failed: {exc}")
record_button.when_pressed = toggle_recording
photo_button.when_pressed = capture_from_button
while app_running:
stream_led.value = latest_frame_time and (time.time() - latest_frame_time) < 2.0
if is_recording_active:
record_led.on()
else:
record_led.off()
time.sleep(0.25)
def gps_logger_worker():
global current_gps_data, is_recording_active, app_running, recording_start_time
last_video = None
pts = []
while app_running:
if is_recording_active and recording_start_time:
try:
videos = sorted(glob.glob(os.path.join(RECORD_FOLDER, "video_*.mp4")))
# Only consider videos created after recording started
valid_videos = [v for v in videos if os.path.getmtime(v) >= recording_start_time - 5]
if valid_videos:
latest_video = valid_videos[-1]
# If this is a new video file, reset points
if latest_video != last_video:
last_video = latest_video
pts = []
# Optionally load existing points if we restarted the script
base_name = os.path.basename(latest_video)
json_name = base_name.replace('video_', 'gps_').replace('.mp4', '.json')
json_path = os.path.join(RECORD_FOLDER, json_name)
if os.path.exists(json_path):
try:
with open(json_path, 'r') as f:
pts = json.load(f).get("points", [])
except:
pass
ts_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
try:
lat = float(current_gps_data.get("lat", 0.0))
lon = float(current_gps_data.get("lon", 0.0))
acc = float(current_gps_data.get("accuracy", 0.0))
spd = float(current_gps_data.get("speed", 0.0))
except:
lat, lon, acc, spd = 0.0, 0.0, 0.0, 0.0
site_id = current_gps_data.get("site_id", "")
beacon_mac = current_gps_data.get("beacon_mac", "")
location_name = current_gps_data.get("location_name", "Unknown")
pts.append({
"timestamp": ts_str,
"lat": lat,
"lon": lon,
"accuracy": acc,
"speed": spd,
"site_id": site_id,
"beacon_mac": beacon_mac,
"location_name": location_name
})
base_name = os.path.basename(latest_video)
json_name = base_name.replace('video_', 'gps_').replace('.mp4', '.json')
json_path = os.path.join(RECORD_FOLDER, json_name)
_write_gps_json_file(json_path, pts)
except Exception as e:
logging.error(f"[GPS Logger] Error: {e}")
else:
last_video = None
pts = []
time.sleep(GPS_RECORD_INTERVAL)
def offline_sync_worker():
while app_running:
try:
if internet_available():
files = sorted(glob.glob(os.path.join(RECORD_FOLDER, "video_*.mp4")) + glob.glob(os.path.join(RECORD_FOLDER, "img_*.jpg")))
for path in files:
if not app_running or is_recording_active:
break
name = os.path.basename(path)
endpoint = "upload_image" if name.startswith("img_") else "upload_cloud"
try:
requests.post(
f"http://127.0.0.1:{PORT}/api/{endpoint}",
json={"filename": name},
timeout=10,
)
time.sleep(1)
except Exception as exc:
logging.warning(f"[SYNC] Deferred {name}: {exc}")
break
except Exception as exc:
logging.warning(f"[SYNC] Offline sync error: {exc}")
time.sleep(OFFLINE_SYNC_INTERVAL)
DISCOVERY_PORT = 5002
MAGIC_WORD = "WHO_IS_RPI_CAM?"
RESPONSE_PREFIX = "I_AM_RPI_CAM"
os.environ["LIBCAMERA_RPI_TUNING_FILE"] = "/usr/share/libcamera/ipa/rpi/vc4/imx219.json"
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
class SuppressedLogFilter(logging.Filter):
def filter(self, record):
return 'SSLEOFError' not in str(record.getMessage())
werkzeug_logger = logging.getLogger('werkzeug')
werkzeug_logger.addFilter(SuppressedLogFilter())
if not os.path.exists(RECORD_FOLDER):
os.makedirs(RECORD_FOLDER)
if not os.path.exists(LOG_DIR):
os.makedirs(LOG_DIR)
root_logger = logging.getLogger()
file_handler = logging.handlers.RotatingFileHandler(os.path.join(LOG_DIR, "app.log"), maxBytes=2*1024*1024, backupCount=5)
file_handler.setLevel(logging.INFO)
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
root_logger.addHandler(file_handler)
try:
from flask_sock import Sock
except ImportError:
Sock = None
app = Flask(__name__)
if Sock:
sock = Sock(app)
else:
sock = None
frame_lock = threading.Lock()
frame_condition = threading.Condition(frame_lock)
latest_frame_jpeg = None
latest_frame_time = 0.0
stream_frame_count = 0
camera_error = None
current_gps_data = {"lat": 0.0, "lon": 0.0, "accuracy": 0.0, "speed": 0.0}
app_running = True
req_start_rec = False
req_stop_rec = False
is_recording_active = False
recording_start_time = None
audio_enabled = AUDIO_ENABLED_DEFAULT
audio_process = None
upload_status = {}
upload_status_lock = threading.Lock()
chunk_number = 0
last_chunk_check = 0
current_recording_files = []
current_recording_lock = threading.Lock()
converting_files = set()
converting_files_lock = threading.Lock()
incomplete_files = set()
incomplete_files_lock = threading.Lock()
def extract_timestamp(filename):
match = re.search(r'(\d{8}_\d{6})', filename)
return match.group(1) if match else None
def _write_gps_json_file(path, points):
try:
with open(path, "w") as jf:
json.dump({"points": points}, jf)
return True
except:
return False
def _load_gps_json_points(path):
try:
with open(path, "r") as jf:
data = json.load(jf)
pts = data.get("points", [])
if not isinstance(pts, list):
return []
out = []
for p in pts:
try:
lat = float(p.get("lat", 0.0))
lon = float(p.get("lon", 0.0))
ts = p.get("timestamp", "")
if (lat != 0.0 or lon != 0.0) and ts:
out.append({"lat": lat, "lon": lon, "timestamp": ts})
except:
continue
return out
except:
return []
def _gps_json_variations_for_video(filename):
return [
filename.replace('video_', 'gps_').replace('.mp4', '.json'),
filename.replace('uploaded_', 'gps_').replace('.mp4', '.json'),
filename.replace('uploaded_', 'uploaded_gps_').replace('.mp4', '.json'),
filename.replace('failed_upload_', 'gps_').replace('.mp4', '.json'),
filename.replace('failed_upload_', 'failed_upload_gps_').replace('.mp4', '.json'),
]
def _find_existing_gps_json_for_video(filename):
for name in _gps_json_variations_for_video(filename):
p = os.path.join(RECORD_FOLDER, name)
if os.path.exists(p):
return p
return None
def finalize_local_media_name(filename, site_id):
import re
# Dynamic site_id parsing from gps logs
pass
# If already finalized, skip
if filename.startswith("site_") or "_to_" in filename:
return filename
# Calculate end time from file modification
video_path = os.path.join(RECORD_FOLDER, filename)
if not os.path.exists(video_path):
return filename
try:
mtime = os.path.getmtime(video_path)
end_str = datetime.datetime.fromtimestamp(mtime).strftime("%H%M%S")
except Exception:
end_str = "000000"
# Extract start time
m = re.search(r"(\d{8}_\d{6})", filename)
if not m:
return filename
start_str = m.group(1)
new_filename = filename.replace(start_str, f"{start_str}_to_{end_str}")
if site_id:
new_filename = f"site_{site_id}_{new_filename}"
new_video_path = os.path.join(RECORD_FOLDER, new_filename)
# Rename the video
try:
os.rename(video_path, new_video_path)
except Exception as e:
logging.error(f"Error renaming video: {e}")
return filename
# Find and rename the matching json
json_path = _find_existing_gps_json_for_video(filename)
if json_path and os.path.exists(json_path):
base_json = os.path.basename(json_path)
new_json_name = base_json.replace(start_str, f"{start_str}_to_{end_str}")
if site_id:
new_json_name = f"site_{site_id}_{new_json_name}"
try:
os.rename(json_path, os.path.join(RECORD_FOLDER, new_json_name))
except Exception as e:
logging.error(f"Error renaming json: {e}")
# Same for CSV
csv_path = _find_existing_gps_json_for_video(filename).replace('.json', '.csv') if _find_existing_gps_json_for_video(filename) else None
if csv_path and os.path.exists(csv_path):
base_csv = os.path.basename(csv_path)
new_csv_name = base_csv.replace(start_str, f"{start_str}_to_{end_str}")
if site_id:
new_csv_name = f"site_{site_id}_{new_csv_name}"
try:
os.rename(csv_path, os.path.join(RECORD_FOLDER, new_csv_name))
except Exception:
pass
return new_filename
def recover_orphaned_files():
orphaned = glob.glob(os.path.join(RECORD_FOLDER, "temp_*.h264"))
if not orphaned:
logging.info("[RECOVERY] ✓ No orphaned files found")
return
logging.info(f"[RECOVERY] Found {len(orphaned)} orphaned file(s)")
for temp_file in orphaned:
try:
temp_name = os.path.basename(temp_file)
incomplete_name = temp_name.replace('temp_', 'incomplete_')
incomplete_path = os.path.join(RECORD_FOLDER, incomplete_name)
os.rename(temp_file, incomplete_path)
with incomplete_files_lock:
incomplete_files.add(incomplete_name)
json_name = temp_name.replace('temp_', 'gps_').replace('.h264', '.json')
json_path = os.path.join(RECORD_FOLDER, json_name)
if os.path.exists(json_path):
incomplete_json = json_name.replace('gps_', 'incomplete_gps_')
incomplete_json_path = os.path.join(RECORD_FOLDER, incomplete_json)
os.rename(json_path, incomplete_json_path)
csv_name = temp_name.replace('temp_', 'gps_').replace('.h264', '.csv')
csv_path = os.path.join(RECORD_FOLDER, csv_name)
if os.path.exists(csv_path):
incomplete_csv = csv_name.replace('gps_', 'incomplete_gps_')
incomplete_csv_path = os.path.join(RECORD_FOLDER, incomplete_csv)
os.rename(csv_path, incomplete_csv_path)
audio_name = temp_name.replace('temp_', 'audio_').replace('.h264', '.wav')
audio_path = os.path.join(RECORD_FOLDER, audio_name)
if os.path.exists(audio_path):
incomplete_audio = audio_name.replace('audio_', 'incomplete_audio_')
incomplete_audio_path = os.path.join(RECORD_FOLDER, incomplete_audio)
os.rename(audio_path, incomplete_audio_path)
logging.info(f"[RECOVERY] ⚠️ Marked as incomplete: {incomplete_name}")
except Exception as e:
logging.error(f"[RECOVERY] Error processing {temp_file}: {e}")
logging.info(f"[RECOVERY] ✓ Marked {len(orphaned)} orphaned files as incomplete")
def generate_ssl_certificates():
if os.path.exists('cert.pem') and os.path.exists('key.pem'):
logging.info("[SSL] ✓ Certificates already exist")
return True
logging.info("[SSL] Generating self-signed certificates...")
try:
cmd = [
'openssl', 'req', '-x509', '-newkey', 'rsa:2048',
'-keyout', 'key.pem', '-out', 'cert.pem',
'-days', '365', '-nodes',
'-subj', '/C=IN/ST=Maharashtra/L=Nagpur/O=ThinkingRobot/OU=SmartHelmet/CN=raspberrypi'
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0 and os.path.exists('cert.pem') and os.path.exists('key.pem'):
os.chmod('key.pem', 0o600)
os.chmod('cert.pem', 0o600)
logging.info("[SSL] ✓ Certificates generated successfully")
return True
else:
logging.warning(f"[SSL] ✗ Certificate generation failed: {result.stderr}")
return False
except Exception as e:
logging.warning(f"[SSL] ✗ Could not generate certificates: {e}")
return False
def start_audio_recording(audio_file):
global audio_process
if not audio_enabled:
return None
try:
check_cmd = ["arecord", "-l"]
result = subprocess.run(check_cmd, capture_output=True, text=True)
if f"card {USB_MIC_DEVICE.split(':')[1].split(',')[0]}" not in result.stdout:
logging.warning(f"[AUDIO] USB microphone not found at {USB_MIC_DEVICE}, skipping audio")
return None
cmd = [
"arecord",
"-D", USB_MIC_DEVICE,
"-f", "S16_LE",
"-c", str(AUDIO_CHANNELS),
"-r", str(AUDIO_SAMPLE_RATE),
audio_file
]
audio_process = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
return audio_process
except Exception as e:
logging.error(f"[AUDIO] Failed to start: {e}")
return None
def stop_audio_recording():
global audio_process
if audio_process:
try:
audio_process.terminate()
audio_process.wait(timeout=5)
except Exception:
try:
audio_process.kill()
except:
pass
finally:
audio_process = None
def convert_and_merge(h264_path, audio_path, mp4_path):
h264_name = os.path.basename(h264_path)
mp4_name = os.path.basename(mp4_path)
with converting_files_lock:
converting_files.add(mp4_name)
time.sleep(2.0)
try:
has_audio = os.path.exists(audio_path) and os.path.getsize(audio_path) > 1000
if has_audio:
cmd = [
"nice", "-n", "19",
"ffmpeg",
"-r", str(int(FPS)),
"-i", h264_path,
"-i", audio_path,
"-c:v", "copy",
"-c:a", "aac",
"-b:a", "128k",
"-shortest",
"-y", mp4_path
]
else:
cmd = [
"nice", "-n", "19",
"ffmpeg",
"-r", str(int(FPS)),
"-i", h264_path,
"-c:v", "copy",
"-y", mp4_path
]
subprocess.run(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
if os.path.exists(mp4_path) and os.path.getsize(mp4_path) > 0:
try:
os.remove(h264_path)
except:
pass
if has_audio:
try:
os.remove(audio_path)
except:
pass
except Exception as e:
logging.error(f"[CONVERT] ✗ Error: {e}")
finally:
with converting_files_lock:
converting_files.discard(mp4_name)
def camera_worker():
global latest_frame_jpeg, latest_frame_time, stream_frame_count, camera_error
global is_recording_active, req_start_rec, req_stop_rec, current_gps_data
global chunk_number, last_chunk_check, recording_start_time, audio_process
global current_recording_files
gps_json_path = None
gps_points = []
last_gps_time = 0
current_h264_name = None
current_audio_name = None
current_mp4_name = None
current_encoder = None
recording_session_start = None
try:
picam2 = Picamera2()
config = picam2.create_video_configuration(
main={"size": (CAM_WIDTH, CAM_HEIGHT), "format": "YUV420"},
lores={"size": (STREAM_WIDTH, STREAM_HEIGHT), "format": "YUV420"},
transform=Transform(hflip=True, vflip=True),
controls={"FrameRate": FPS},
buffer_count=6
)
config["sensor"]["output_size"] = (CAM_WIDTH, CAM_HEIGHT)
picam2.configure(config)
picam2.start()
picam2.set_controls({"ScalerCrop": (0, 0, 3280, 2464)})
time.sleep(0.5)
except Exception as e:
camera_error = str(e)
logging.critical(f"[CAMERA] ✗ Hardware Error: {e}")
return
camera_error = None
while app_running:
try:
if req_start_rec:
req_start_rec = False
if not is_recording_active:
chunk_number = 0
recording_session_start = datetime.datetime.now()
recording_start_time = time.time()
last_chunk_check = time.time()
ts = recording_session_start.strftime("%Y%m%d_%H%M%S")
current_h264_name = os.path.join(RECORD_FOLDER, f"temp_{ts}_chunk{chunk_number:03d}.h264")
current_audio_name = os.path.join(RECORD_FOLDER, f"audio_{ts}_chunk{chunk_number:03d}.wav")
current_mp4_name = os.path.join(RECORD_FOLDER, f"video_{ts}_chunk{chunk_number:03d}.mp4")
gps_json_path = os.path.join(RECORD_FOLDER, f"gps_{ts}_chunk{chunk_number:03d}.json")
gps_points = []
_write_gps_json_file(gps_json_path, gps_points)
try:
current_encoder = H264Encoder(bitrate=VIDEO_BITRATE, profile="high")
picam2.start_recording(current_encoder, current_h264_name)
start_audio_recording(current_audio_name)
is_recording_active = True
with current_recording_lock:
current_recording_files.append({
"h264": os.path.basename(current_h264_name),
"mp4": os.path.basename(current_mp4_name),
"started": recording_session_start.strftime("%Y-%m-%d %H:%M:%S")
})
except Exception as rec_err:
logging.error(f"[RECORD] ✗ Start failed: {rec_err}")
is_recording_active = False
if is_recording_active and AUTO_CHUNK_ENABLED:
now = time.time()
if (now - last_chunk_check) >= CHUNK_CHECK_INTERVAL:
last_chunk_check = now
try:
if os.path.exists(current_h264_name):
file_size_mb = os.path.getsize(current_h264_name) / (1024 * 1024)
if file_size_mb >= CHUNK_SIZE_MB:
picam2.stop_recording()
stop_audio_recording()
if current_h264_name and current_mp4_name:
t = threading.Thread(
target=convert_and_merge,
args=(current_h264_name, current_audio_name, current_mp4_name)
)
t.daemon = True
t.start()
chunk_number += 1
ts = recording_session_start.strftime("%Y%m%d_%H%M%S")
current_h264_name = os.path.join(RECORD_FOLDER, f"temp_{ts}_chunk{chunk_number:03d}.h264")
current_audio_name = os.path.join(RECORD_FOLDER, f"audio_{ts}_chunk{chunk_number:03d}.wav")
current_mp4_name = os.path.join(RECORD_FOLDER, f"video_{ts}_chunk{chunk_number:03d}.mp4")
gps_json_path = os.path.join(RECORD_FOLDER, f"gps_{ts}_chunk{chunk_number:03d}.json")
gps_points = []
_write_gps_json_file(gps_json_path, gps_points)
current_encoder = H264Encoder(bitrate=VIDEO_BITRATE, profile="high")
picam2.start_recording(current_encoder, current_h264_name)
start_audio_recording(current_audio_name)
with current_recording_lock:
current_recording_files.append({
"h264": os.path.basename(current_h264_name),
"mp4": os.path.basename(current_mp4_name),
"started": datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
})
except Exception as chunk_err:
logging.error(f"[CHUNK] ✗ Size check failed: {chunk_err}")
if req_stop_rec:
req_stop_rec = False
if is_recording_active:
try:
picam2.stop_recording()
stop_audio_recording()
picam2.start()
except Exception as stop_err:
logging.error(f"[RECORD] ✗ Stop error: {stop_err}")
is_recording_active = False
recording_start_time = None
current_encoder = None
with current_recording_lock:
current_recording_files = []
if current_h264_name and current_mp4_name:
t = threading.Thread(
target=convert_and_merge,
args=(current_h264_name, current_audio_name, current_mp4_name)
)
t.daemon = True
t.start()
# Keep loop delay low so 720p MJPEG can sustain the target FPS.
time.sleep(0.005)
try:
raw_yuv = picam2.capture_array("lores")
if raw_yuv is not None:
frame_bgr = cv2.cvtColor(raw_yuv, cv2.COLOR_YUV2BGR_I420)
if is_recording_active:
now = time.time()
if (now - last_gps_time) >= GPS_RECORD_INTERVAL:
ts_str = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f")
try:
lat = float(current_gps_data.get("lat", 0.0))
lon = float(current_gps_data.get("lon", 0.0))
acc = float(current_gps_data.get("accuracy", 0.0))
spd = float(current_gps_data.get("speed", 0.0))
except:
lat, lon, acc, spd = 0.0, 0.0, 0.0, 0.0
site_id = current_gps_data.get("site_id", "")
beacon_mac = current_gps_data.get("beacon_mac", "")
location_name = current_gps_data.get("location_name", "Unknown")
gps_points.append({
"timestamp": ts_str,
"lat": lat,
"lon": lon,
"accuracy": acc,
"speed": spd,
"site_id": site_id,
"beacon_mac": beacon_mac,
"location_name": location_name
})
if gps_json_path:
_write_gps_json_file(gps_json_path, gps_points)
last_gps_time = now
ret, buf = cv2.imencode('.jpg', frame_bgr, [int(cv2.IMWRITE_JPEG_QUALITY), MJPEG_QUALITY])
if ret:
with frame_lock:
latest_frame_jpeg = buf.tobytes()
latest_frame_time = time.time()
stream_frame_count += 1
frame_condition.notify_all()
except Exception:
pass
time.sleep(0.005)
except Exception as e:
logging.error(f"[CAMERA] Loop error: {e}")
time.sleep(0.1)
try:
if is_recording_active:
try:
picam2.stop_recording()
stop_audio_recording()
except:
pass
picam2.stop()
except:
pass
def discovery_service():
try:
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind(('', DISCOVERY_PORT))
reply = f"{RESPONSE_PREFIX}|{socket.gethostname()}".encode('utf-8')
while app_running:
try:
sock.settimeout(1.0)
data, addr = sock.recvfrom(1024)
if data.decode().strip() == MAGIC_WORD:
sock.sendto(reply, addr)
except socket.timeout:
continue
except Exception:
time.sleep(1)
except Exception as e:
logging.error(f"[DISCOVERY] Error: {e}")
@app.route('/')
def index():
return render_template('index.html', version=VERSION)
@app.route('/video_feed')
def video_feed():
def generate():
while True:
with frame_condition:
frame_condition.wait(timeout=1.0)
frame = latest_frame_jpeg
if frame:
try:
yield (b'--frame\r\nContent-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
except Exception:
break
response = Response(generate(), mimetype='multipart/x-mixed-replace; boundary=frame')
response.headers["Cache-Control"] = "no-store, no-cache, must-revalidate, max-age=0"
response.headers["Pragma"] = "no-cache"
return response
@app.route('/api/stream_info')
def stream_info():
now = time.time()
with frame_lock:
has_frame = latest_frame_jpeg is not None
age = round(now - latest_frame_time, 3) if latest_frame_time else None
frame_size = len(latest_frame_jpeg) if latest_frame_jpeg else 0
return jsonify({
"stream": "mjpeg",
"status": "online" if has_frame and age is not None and age < 2.0 else "warming" if not camera_error else "error",
"url": "/video_feed",
"host_urls": [f"http://{ip}:{PORT}/video_feed" for ip in get_lan_addresses()],
"width": STREAM_WIDTH,
"height": STREAM_HEIGHT,
"fps_target": FPS,
"fps_estimated": round((1.0 / age), 2) if age and age > 0 else None,
"jpeg_quality": MJPEG_QUALITY,
"has_frame": has_frame,
"last_frame_age_seconds": age,
"last_frame_bytes": frame_size,
"frame_count": stream_frame_count,
"camera_error": camera_error
})
@app.route('/api/health')
def health():
now = time.time()
with frame_lock:
stream_age = round(now - latest_frame_time, 3) if latest_frame_time else None
return jsonify({
"ok": camera_error is None,
"version": VERSION,
"device_id": DEVICE_ID,
"hostname": socket.gethostname(),
"lan_addresses": get_lan_addresses(),
"http_port": PORT,
"discovery_port": DISCOVERY_PORT,
"stream_url": "/video_feed",
"recording": is_recording_active,
"audio_enabled": audio_enabled,
"stream_frame_count": stream_frame_count,
"last_frame_age_seconds": stream_age,
"camera_error": camera_error
})
receiver_running = receiver_service_active or receiver_process_running
return jsonify({
"running": bridge_running or receiver_running,
"bridge_running": bridge_running,
"receiver_running": receiver_running,
"service_active": bridge_service_active,
"process_running": bridge_process_running,
"service_name": "livekit-audio-bridge" if bridge_running else "livekit-audio-receiver",
"input_device": "system default",
"output_device": "system default"
})
@app.route('/api/stream/pause', methods=['POST'])
def pause_stream():
import subprocess
subprocess.run(["sudo", "systemctl", "stop", "srs-publisher.service"], check=False)
return jsonify({"success": True})
@app.route('/api/stream/resume', methods=['POST'])
def resume_stream():
import subprocess
subprocess.run(["sudo", "systemctl", "start", "srs-publisher.service"], check=False)
return jsonify({"success": True})
record_proc = None
@app.route('/api/start_record', methods=['GET', 'POST'])
def start_record():
global record_proc, is_recording_active, recording_start_time
if not is_recording_active:
is_recording_active = True
if not record_proc:
import subprocess, time
subprocess.run(["sudo", "systemctl", "stop", "srs-publisher.service"], check=False)
time.sleep(3.0)
os.makedirs(RECORD_FOLDER, exist_ok=True)
subprocess.run(["sudo", "chmod", "777", RECORD_FOLDER], check=False)
# Create a flag file to tell gpio_offline_capture.py to turn on the LED
try:
open(os.path.join(RECORD_FOLDER, ".ui_recording"), "w").close()
except Exception:
pass
abs_record_folder = os.path.abspath(RECORD_FOLDER)
path_mp4_pattern = os.path.join(abs_record_folder, "video_%Y%m%d_%H%M%S.mp4")
log_path = os.path.join(abs_record_folder, 'camera.log')
# Use same high quality settings and pipe to ffmpeg to mux with audio!
cmd = (
f"rpicam-vid --width 1280 --height 720 --framerate 24 --codec h264 --profile high "
f"--bitrate 1100000 --denoise cdn_hq --inline --timeout 0 --nopreview -o - | "
f"ffmpeg -y -use_wallclock_as_timestamps 1 -thread_queue_size 1024 -f h264 -i - "
f"-use_wallclock_as_timestamps 1 -thread_queue_size 1024 -f alsa -channels 1 -i hw:3,0 "
f"-c:v copy -c:a aac -ar 44100 -b:a 128k -async 1 -f segment -segment_time 300 -strftime 1 -reset_timestamps 1 '{path_mp4_pattern}' > '{log_path}' 2>&1"
)
recording_start_time = time.time()
record_proc = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid)
global current_record_mp4
current_record_mp4 = None
return "OK"
@app.route('/api/stop_record', methods=['POST'])
def stop_record():
global record_proc, is_recording_active, current_record_mp4
if is_recording_active:
is_recording_active = False
if record_proc:
import os, signal, subprocess
try:
os.killpg(os.getpgid(record_proc.pid), signal.SIGTERM)
record_proc.wait(timeout=5)
except Exception:
pass
record_proc = None
try:
flag_file = os.path.join(RECORD_FOLDER, ".ui_recording")
if os.path.exists(flag_file):
os.remove(flag_file)
except Exception:
pass
subprocess.run(["sudo", "systemctl", "start", "srs-publisher.service"], check=False)
return "OK"
@app.route('/api/toggle_audio', methods=['POST'])
def toggle_audio():
global audio_enabled
data = request.json or {}
audio_enabled = data.get('enabled', True)
return jsonify({"success": True, "audio_enabled": audio_enabled})
@app.route('/api/capture_photo', methods=['GET', 'POST'])
def capture_photo():
import subprocess
was_streaming = subprocess.run(["systemctl", "is-active", "--quiet", "srs-publisher.service"]).returncode == 0
if was_streaming:
subprocess.run(["sudo", "systemctl", "stop", "srs-publisher.service"], check=False)
time.sleep(1)