-
-
Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathowl.py
More file actions
executable file
·1615 lines (1383 loc) · 78.7 KB
/
owl.py
File metadata and controls
executable file
·1615 lines (1383 loc) · 78.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
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 python
import os
import sys
import logging
import argparse
import time
import threading
from collections import deque
try:
import serial
except ImportError:
serial = None
from datetime import datetime
from multiprocessing import Process, Value
from pathlib import Path
from utils.error_manager import MJPEGStreamError
def get_python_env():
"""Get current Python environment status"""
venv = os.environ.get('VIRTUAL_ENV')
if venv:
return f"Virtual environment: {venv}"
return "No virtual environment active (using system Python)"
def setup_basic_logger():
"""Simple startup logger that uses the same file as LogManager"""
log_dir = Path(os.getcwd()) / 'logs'
log_dir.mkdir(exist_ok=True)
file_handler = logging.FileHandler(log_dir / 'owl.jsonl')
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
console_handler = logging.StreamHandler(sys.stdout)
console_handler.setFormatter(logging.Formatter('%(asctime)s - %(levelname)s - %(message)s'))
root_logger = logging.getLogger()
root_logger.setLevel(logging.INFO)
root_logger.addHandler(file_handler)
root_logger.addHandler(console_handler)
return logging.getLogger('owl_startup')
logger = setup_basic_logger()
logger.info("Starting OWL - checking imports...")
try:
import utils.error_manager as errors
except ImportError:
logger.critical("Cannot import from utils package! Not in correct directory.")
logger.critical(f"Current working directory: {os.getcwd()}")
print("\nERROR: Cannot import from utils package!")
print("This usually means you are not in the correct directory.")
print("\nTo fix:")
print("1. Ensure owl environment is active: workon owl")
print("2. Navigate to owl directory: cd /home/owl/owl")
sys.exit(1)
try:
import cv2
except ImportError as e:
logger.error("OpenCV import failed - likely not in `owl` virtual environment")
logger.error(f"Error details: {str(e)}")
logger.error(f"Python environment: {get_python_env()}")
raise errors.OpenCVError(str(e)) from None
try:
import numpy as np
from utils.input_manager import UteController, AdvancedController, get_rpi_version
from utils.output_manager import RelayController, HeadlessStatusIndicator, UteStatusIndicator, AdvancedStatusIndicator, GPSStatusLED, GPSLEDState
from utils.directory_manager import DirectorySetup
from utils.video_manager import VideoStream, StreamingHandler, ThreadedHTTPServer
from utils.image_sampler import ImageRecorder
from utils.algorithms import fft_blur
from utils.greenonbrown import GreenOnBrown
from utils.frame_reader import FrameReader
from utils.config_manager import ConfigValidator
from utils.log_manager import LogManager, MQTTLogHandler
from utils.shared_types import Sensitivity
import utils.error_manager as errors
from utils.gps_manager import GPSState, parse_sentence
from version import SystemInfo, VERSION
except ImportError as e:
missing_module = str(e).split("'")[1]
logger.error(f"Failed to import required module: {missing_module}")
logger.error(f"Error details: {str(e)}")
logger.error(f"Current virtual env: {os.environ.get('VIRTUAL_ENV', 'None')}")
logger.error(f"Current working directory: {os.getcwd()}")
raise errors.DependencyError(missing_module, str(e)) from None
logger.info("All required modules imported successfully")
def nothing(x):
pass
class Owl:
def __init__(self, show_display=False,
input_file_or_directory=None,
config_file='config/GENERAL_CONFIG.ini'):
# set up the logger
log_dir = Path(os.path.join(os.path.dirname(__file__), 'logs'))
LogManager.setup(log_dir=log_dir, log_level='INFO')
self.logger = LogManager.get_logger(__name__)
self.logger.info("Initializing OWL...")
self._log_system_info()
# read the config file
self._config_path = Path(__file__).parent / config_file
try:
self.config = ConfigValidator.load_and_validate_config(self._config_path)
except errors.OWLConfigError as e:
self.logger.error(f"Configuration error: {e}", exc_info=True)
raise
self.config.read(self._config_path)
self.config.read(Path(__file__).parent / 'config' / 'CONTROLLER.ini')
self.RPI_VERSION = get_rpi_version()
self.logger.info(msg=f'Raspberry Pi version: {self.RPI_VERSION}')
# is the source a directory/file
self.input_file_or_directory = input_file_or_directory
# visualise the detections with video feed
self.show_display = show_display
# threshold parameters for different algorithms
self.exg_min = self.config.getint('GreenOnBrown', 'exg_min')
self.exg_max = self.config.getint('GreenOnBrown', 'exg_max')
self.hue_min = self.config.getint('GreenOnBrown', 'hue_min')
self.hue_max = self.config.getint('GreenOnBrown', 'hue_max')
self.saturation_min = self.config.getint('GreenOnBrown', 'saturation_min')
self.saturation_max = self.config.getint('GreenOnBrown', 'saturation_max')
self.brightness_min = self.config.getint('GreenOnBrown', 'brightness_min')
self.brightness_max = self.config.getint('GreenOnBrown', 'brightness_max')
self.min_detection_area = self.config.getint('GreenOnBrown', 'min_detection_area')
self.invert_hue = self.config.getboolean('GreenOnBrown', 'invert_hue')
# Sensitivity preset manager
from utils.sensitivity_manager import SensitivityManager
self.sensitivity_manager = SensitivityManager(self.config, self._config_path)
active_preset = self.sensitivity_manager.get_active_preset()
self.sensitivity_manager.apply_preset(active_preset, self)
self.logger.info(f"Sensitivity preset '{active_preset}' applied")
# time spent on each image when looping over a directory
self.image_loop_time = self.config.getint('Visualisation', 'image_loop_time')
# setup the track bars if show_display is True
if self.show_display:
# create trackbars for the threshold calculation
self.window_name = "Adjust Detection Thresholds"
cv2.namedWindow("Adjust Detection Thresholds", cv2.WINDOW_AUTOSIZE)
cv2.createTrackbar("ExG-Min", self.window_name, self.exg_min, 255, nothing)
cv2.createTrackbar("ExG-Max", self.window_name, self.exg_max, 255, nothing)
cv2.createTrackbar("Hue-Min", self.window_name, self.hue_min, 179, nothing)
cv2.createTrackbar("Hue-Max", self.window_name, self.hue_max, 179, nothing)
cv2.createTrackbar("Sat-Min", self.window_name, self.saturation_min, 255, nothing)
cv2.createTrackbar("Sat-Max", self.window_name, self.saturation_max, 255, nothing)
cv2.createTrackbar("Bright-Min", self.window_name, self.brightness_min, 255, nothing)
cv2.createTrackbar("Bright-Max", self.window_name, self.brightness_max, 255, nothing)
self.resolution = (self.config.getint('Camera', 'resolution_width'),
self.config.getint('Camera', 'resolution_height'))
self.exp_compensation = self.config.getint('Camera', 'exp_compensation')
self.camera_type = self.config.get('Camera', 'camera_type', fallback='auto')
# Relay Dict maps the reference relay number to a boardpin on the embedded device
self.relay_dict = {}
# use the [Relays] section to build the dictionary
for key, value in self.config['Relays'].items():
self.relay_dict[int(key)] = int(value)
# instantiate the relay controller - successful start should beep the buzzer
try:
self.relay_controller = RelayController(relay_dict=self.relay_dict)
except errors.OWLAlreadyRunningError:
self.logger.critical("OWL initialization failed: GPIO pin conflict. Another OWL instance may be running.",
exc_info=True)
raise
### Data collection only ###
self.detection_enable = Value('b', self.config.getboolean('DataCollection', 'detection_enable', fallback=False))
self.image_sample_enable = Value('b', self.config.getboolean('DataCollection', 'image_sample_enable',
fallback=False))
# Local cached versions for performance
self._detection_enable = self.detection_enable.value
self._image_sample_enable = self.image_sample_enable.value
self._STATE_CHECK_INTERVAL = 0.1
self.stop_state_update = threading.Event()
####################### DASHBOARD ############################
self.dash = None
self.stream_active = None
self.latest_stream_frame = None
mqtt_enable = self.config.getboolean('MQTT', 'enable', fallback=False)
broker_ip = self.config.get('MQTT', 'broker_ip', fallback='localhost')
broker_port = self.config.getint('MQTT', 'broker_port', fallback=1883)
device_id = self.config.get('MQTT', 'device_id', fallback='auto')
network_mode = self.config.get('Network', 'mode', fallback=None)
static_ip = self.config.get('Network', 'static_ip', fallback=None)
client_id = f"client_{device_id}"
if mqtt_enable:
try:
from utils.mqtt_manager import OWLMQTTPublisher
self.dash = OWLMQTTPublisher(
broker_host=broker_ip,
broker_port=broker_port,
client_id=client_id,
device_id=device_id,
network_mode=network_mode,
static_ip=static_ip)
self.dash.set_owl_instance(self)
self.dash.start()
# Enhanced logging
mode = 'NETWORKED' if self.dash.networked_mode else 'STANDALONE'
self.logger.info(f"MQTT enabled - Mode: {mode}")
self.logger.info(f"MQTT Broker: {broker_ip}:{broker_port}")
self.logger.info(f"Device ID: {device_id}")
self.logger.info(f"Client ID: {client_id}")
# Only attach log handler if broker is already reachable
if self.dash.connected:
LogManager.add_mqtt_handler(
mqtt_client=self.dash.client,
mqtt_error_topic=self.dash.topics['errors']
)
except Exception as e:
self.dash = None
self.logger.warning(f"Failed to initialize MQTT: {e}. Dashboard disabled, OWL continues.")
try:
self.stream_lock = threading.Lock()
self.start_streaming_server()
self.stream_active = True # IMPORTANT: Set status to True on success
self.logger.info("MJPEG video streaming server started successfully")
except MJPEGStreamError as e:
self.logger.warning(f"Could not start MJPEG stream, but core functions will continue: {e}")
self.stream_active = False
if self.dash:
self.dash.set_stream_status(self.stream_active)
# GPS setup
self.gps_source = self.config.get('GPS', 'source', fallback='none').lower()
self.gps_data = None
self._gps_state = None
self._gps_serial = None
self._gps_running = False
self.gps_status_led = None
if self.gps_source == 'serial':
self.gps_port = self.config.get('GPS', 'port', fallback='/dev/ttyUSB1')
self.gps_baudrate = self.config.getint('GPS', 'baudrate', fallback=115200)
if serial is None:
self.logger.error("pyserial not installed — serial GPS disabled. Install with: pip install pyserial")
# Fall back to dashboard (browser geolocation) if available, otherwise disable
if self.dash:
self.gps_source = 'dashboard'
self.logger.info("Falling back to dashboard GPS (browser geolocation)")
else:
self.gps_source = 'none'
else:
self._gps_state = GPSState()
self._gps_running = True
gps_led_raw = self.config.get('Controller', 'gps_led_pin', fallback='38').strip("'\" ").lower()
if gps_led_raw not in ('', 'none'):
self.gps_status_led = GPSStatusLED(pin=f"BOARD{int(gps_led_raw)}")
self._gps_thread = threading.Thread(target=self._serial_gps_reader, daemon=True)
self._gps_thread.start()
self.logger.info(f"Serial GPS reader started on {self.gps_port} @ {self.gps_baudrate}")
elif self.gps_source != 'none':
# Non-serial, non-none source (e.g. 'tcp') — fall back to dashboard GPS
if self.dash:
self.gps_source = 'dashboard'
# Create GPS status LED on hardware setups (UTE/Advanced controller) even if GPS
# source is 'none' — the LED shows whether dashboard browser GPS is active.
# The LED state is driven by _get_best_gps_data() in the update_state loop.
if self.gps_status_led is None:
controller_type_check = self.config.get('Controller', 'controller_type', fallback='none').strip("'\" ").lower()
if controller_type_check in ('ute', 'advanced'):
gps_led_raw = self.config.get('Controller', 'gps_led_pin', fallback='38').strip("'\" ").lower()
if gps_led_raw not in ('', 'none'):
self.gps_status_led = GPSStatusLED(pin=f"BOARD{int(gps_led_raw)}")
# if a controller is connected, sample images must be true to set up directories correctly
self.controller_type = self.config.get('Controller', 'controller_type').strip("'\" ").lower()
self.switch_purpose = self.config.get('Controller', 'switch_purpose', fallback='recording').strip("'\" ").lower()
if self.controller_type not in {'none', 'ute', 'advanced'}:
self.logger.error(f"Invalid controller type: {self.controller_type}")
raise errors.ControllerTypeError(self.controller_type, valid_types=list({'none', 'ute', 'advanced'}))
# Create status indicator EARLY so it can signal boot errors via LED.
# save_directory is set to None for now; updated after storage setup succeeds.
# status_led_pin can be 'none' or empty to disable the LED.
status_led_raw = self.config.get('Controller', 'status_led_pin', fallback='40').strip("'\" ").lower()
status_led_pin = f"BOARD{int(status_led_raw)}" if status_led_raw not in ('', 'none') else None
if self.controller_type == 'ute':
self.status_indicator = UteStatusIndicator(save_directory=None,
status_led_pin=status_led_pin)
elif self.controller_type == 'advanced':
self.status_indicator = AdvancedStatusIndicator(save_directory=None,
status_led_pin=status_led_pin)
else:
self.status_indicator = HeadlessStatusIndicator(save_directory=None, no_save=True)
if self.controller_type != 'none' and not self.dash:
self.detection_enable = Value('b', False)
self.image_sample_enable = Value('b', False)
self.sensitivity_level = Value('i', Sensitivity.HIGH.value)
if self.controller_type != 'none' or self.dash:
# Force infrastructure setup (directories, ImageRecorder) so
# controller/dashboard can toggle recording when ready.
# Actual recording state is set after setup — see below.
self._image_sample_enable = True
# if controller is 'none' but _image_sample_enable is True, then it will set everything up
if self._image_sample_enable:
self.sample_method = self.config.get('DataCollection', 'sample_method')
self.sample_frequency = self.config.getint('DataCollection', 'sample_frequency')
self.save_directory = self.config.get('DataCollection', 'save_directory')
self.camera_name = self.config.get('DataCollection', 'camera_name')
try:
self.directory_manager = DirectorySetup(save_directory=self.save_directory)
self.save_directory, self.save_subdirectory = self.directory_manager.setup_directories()
self.image_recorder = ImageRecorder(save_directory=self.save_subdirectory, mode=self.sample_method)
# Update status indicator with the resolved save_directory for storage monitoring
self.status_indicator.save_directory = self.save_directory
except (errors.NoWritableUSBError, errors.USBMountError, errors.USBWriteError,
errors.StorageSystemError) as e:
self.logger.critical(str(e))
# Flash both LEDs in sync to signal boot error — process stays alive
self.status_indicator.error(6)
if self.gps_status_led:
self.gps_status_led.set_state(GPSLEDState.ERROR)
self.logger.critical("Both LEDs flashing — storage error. Fix USB drive and restart.")
# Block here so LEDs keep flashing (systemd will not restart while process is alive)
try:
while True:
time.sleep(5)
except KeyboardInterrupt:
self.stop()
raise
############################
# initialise controller buttons and async management
if self.controller_type == 'ute':
# Status indicator already created above — just set up controller
self.controller = UteController(
detection_state=self.detection_enable,
sample_state=self.image_sample_enable,
stop_flag=Value('b', False),
owl_instance=self,
status_indicator=self.status_indicator,
switch_purpose=self.config.get('Controller', 'switch_purpose', fallback='recording').strip("'\" ").lower(),
switch_board_pin=f"BOARD{self.config.getint('Controller', 'switch_pin', fallback=36)}"
)
self.controller_process = Process(target=self.controller.run)
self.controller_process.start()
elif self.controller_type == 'advanced':
if not hasattr(self, 'sensitivity_level'):
self.sensitivity_level = Value('i', Sensitivity.HIGH.value)
# Status indicator already created above
self.controller = AdvancedController(
recording_state=self.image_sample_enable,
sensitivity_level=self.sensitivity_level,
detection_mode_state=Value('i', 1),
stop_flag=Value('b', False),
owl_instance=self,
status_indicator=self.status_indicator,
sensitivity_manager=self.sensitivity_manager,
recording_bpin=f"BOARD{self.config.getint('Controller', 'recording_pin', fallback=38)}",
sensitivity_bpin=f"BOARD{self.config.getint('Controller', 'sensitivity_pin', fallback=40)}",
detection_mode_bpin_up=f"BOARD{self.config.getint('Controller', 'detection_mode_pin_up', fallback=36)}",
detection_mode_bpin_down=f"BOARD{self.config.getint('Controller', 'detection_mode_pin_down', fallback=35)}"
)
self.controller_process = Process(target=self.controller.run)
self.controller_process.start()
else:
self.controller = None
# Status indicator already created above; start storage monitoring if recording
if self._image_sample_enable:
self.status_indicator.start_storage_indicator()
# Infrastructure is set up. Now set the actual initial recording state.
# Dashboard-only (no hardware controller): start OFF — user enables via dashboard.
# Hardware controllers: switch position was read during controller init above.
if self.dash and self.controller_type == 'none':
self._image_sample_enable = False
with self.image_sample_enable.get_lock():
self.image_sample_enable.value = False
self.dash.set_image_sample_enable(False)
if self.dash or self.controller_type != 'none':
threading.Thread(target=self.update_state, daemon=True).start()
self.logger.info("State monitoring thread started")
# Actuation timing — read from [Actuation] (CONTROLLER.ini), fall back to [System]
if self.config.has_section('Actuation'):
self.actuation_duration = self.config.getfloat('Actuation', 'actuation_duration',
fallback=self.config.getfloat('System', 'actuation_duration'))
self.delay = self.config.getfloat('Actuation', 'delay',
fallback=self.config.getfloat('System', 'delay'))
else:
self.actuation_duration = self.config.getfloat('System', 'actuation_duration')
self.delay = self.config.getfloat('System', 'delay')
# Loop time tracking (30-frame rolling window)
self._loop_times = deque(maxlen=30)
self._avg_loop_time_ms = 0.0
self.relay_vis = None
# Check which Raspberry Pi is being used and adjust the resolution accordingly.
# Use `cat /proc-device-tree/model` to check the model of the Raspberry Pi.
total_pixels = self.resolution[0] * self.resolution[1]
if (self.RPI_VERSION in ['rpi-3', 'rpi-4']) and total_pixels > (832 * 640):
# change here if you want to test higher resolutions, but be warned, backup your current image!
# the older versions of the Pi are known to 'brick' and become unusable if too high resolutions are used.
self.resolution = (640, 480)
self.logger.warning(f"Resolution {self.config.getint('Camera', 'resolution_width')}, "
f"{self.config.getint('Camera', 'resolution_height')} selected is dangerously high. ")
else:
self.logger.warning(
f'High resolution, expect low framerate. Resolution set to {self.resolution[0]}x{self.resolution[1]}.')
self.frame_width = None
self.frame_height = None
try:
self.cam = self.setup_media_source(input_file_or_directory, camera_type=self.camera_type)
self.logger.info('Media source successfully set up...')
time.sleep(1.0)
except (errors.MediaPathError, errors.InvalidMediaError, errors.MediaInitError, errors.CameraInitError) as e:
self.logger.error(str(e))
self.stop()
# sensitivity and weed size to be added
self.sensitivity = None
self.lane_coords = {}
# add the total number of relays being controlled. This can be changed easily, but the relay_dict and physical relays would need
# to be updated too. Fairly straightforward, so an opportunity for more precise application
self.relay_num = self.config.getint('System', 'relay_num')
self.actuation_zone = self.config.getint('System', 'actuation_zone', fallback=100)
# GreenOnGreen / hybrid config
self.inference_resolution = self.config.getint('GreenOnGreen', 'inference_resolution', fallback=320)
self.crop_buffer_px = self.config.getint('GreenOnGreen', 'crop_buffer_px', fallback=20)
self._pending_algorithm = None
self._pending_trackbar_updates = {}
self._pending_model = None
self._pending_detect_classes = None
self._gog_detector = None
# Tracking config (ByteTrack + class smoothing + crop mask persistence)
self.tracking_enabled = self.config.getboolean('Tracking', 'tracking_enabled', fallback=False)
self.track_high_thresh = self.config.getfloat('Tracking', 'track_high_thresh', fallback=0.2)
self.track_low_thresh = self.config.getfloat('Tracking', 'track_low_thresh', fallback=0.05)
self.new_track_thresh = self.config.getfloat('Tracking', 'new_track_thresh', fallback=0.2)
self.track_buffer = self.config.getint('Tracking', 'track_buffer', fallback=60)
self.match_thresh = self.config.getfloat('Tracking', 'match_thresh', fallback=0.7)
self._track_class_window = self.config.getint('Tracking', 'track_class_window', fallback=5)
self._track_crop_persist = self.config.getint('Tracking', 'track_crop_persist', fallback=3)
self.detection_persist_frames = self.config.getint(
'Tracking', 'detection_persist_frames', fallback=5)
self._class_smoother = None
self._crop_stabilizer = None
if self.tracking_enabled:
from utils.tracker import ClassSmoother, CropMaskStabilizer
# Both created regardless of algorithm — smoother unused in hybrid mode
# but algorithm can change mid-session, so both must be ready
self._class_smoother = ClassSmoother(window=self._track_class_window)
self._crop_stabilizer = CropMaskStabilizer(max_age=self._track_crop_persist)
self.logger.info(f'Tracking enabled: class_window={self._track_class_window}, '
f'crop_persist={self._track_crop_persist}')
# Crop factors to reduce edge artifacts (0.1 = 10% crop from each side)
self.crop_factor_horizontal = self.config.getfloat('Camera', 'crop_factor_horizontal', fallback=0.1)
self.crop_factor_vertical = self.config.getfloat('Camera', 'crop_factor_vertical', fallback=0.1)
self.logger.info(f'[INFO] Crop factor: X {self.crop_factor_horizontal} | Y {self.crop_factor_vertical}')
if self.frame_width and self.frame_height:
# Calculate cropped dimensions
crop_left = int(self.frame_width * self.crop_factor_horizontal)
crop_right = int(self.frame_width - crop_left)
crop_top = int(self.frame_height * self.crop_factor_vertical)
crop_bottom = int(self.frame_height - crop_top)
self.cropped_width = crop_right - crop_left
self.cropped_height = crop_bottom - crop_top
self.logger.info(f'[INFO] Image cropped to {crop_left}x{crop_right}x{crop_top}x{crop_bottom}.')
# Store crop boundaries for slicing
self.crop_slice = (slice(crop_top, crop_bottom), slice(crop_left, crop_right))
# Calculate lane width based on cropped width
self.lane_width = self.cropped_width / self.relay_num
# Calculate actuation zone Y threshold
self.actuation_y_thresh = int(self.cropped_height * (1.0 - self.actuation_zone / 100.0))
# Calculate lane coords relative to cropped frame
for i in range(self.relay_num):
laneX = int(i * self.lane_width)
self.lane_coords[i] = laneX
# Precompute the integer lane coordinates for reuse
self.lane_coords_int = {k: int(v) for k, v in self.lane_coords.items()}
else:
self.logger.error('[ERROR] No frame width or frame height provided.')
@property
def config_path(self):
return self._config_path
def hoot(self):
# Signal successful boot with LED blink
if hasattr(self, 'status_indicator') and hasattr(self.status_indicator, 'setup_success'):
self.status_indicator.setup_success()
self.record_video = False # Flag to control video recording
self.video_writer = None
image_out = None
algorithm = self.config.get('System', 'algorithm')
log_fps = self.config.getboolean('DataCollection', 'log_fps')
if self.controller:
self.controller.update_state()
# track framecount
frame_count = 0
last_fps_time = time.time()
fps_frame_count = 0
# GoG shared config (used by both gog and gog-hybrid)
self._model_path = self.config.get('GreenOnGreen', 'model_path')
self._gog_confidence = self.config.getfloat('GreenOnGreen', 'confidence')
detect_classes_str = self.config.get('GreenOnGreen', 'detect_classes', fallback='')
self._detect_classes_list = [c.strip() for c in detect_classes_str.split(',') if c.strip()]
detect_classes = self._detect_classes_list or None
actuation_mode = self.config.get('GreenOnGreen', 'actuation_mode', fallback='centre')
min_detection_pixels = self.config.getint('GreenOnGreen', 'min_detection_pixels', fallback=50)
_zone_tracking_warned = False
# GoB shared config — already initialised in __init__() and may have been
# updated by SensitivityManager.apply_preset(), so do NOT re-read from config.
def _create_detector(algo):
"""Three-way detector factory."""
current_classes = self._detect_classes_list or None
if algo == 'gog':
from utils.greenongreen import GreenOnGreen
return GreenOnGreen(
model_path=self._model_path,
confidence=self._gog_confidence,
detect_classes=current_classes,
tracking_enabled=self.tracking_enabled,
detection_persist_frames=self.detection_persist_frames,
)
elif algo == 'gog-hybrid':
from utils.greenongreen import GreenOnGreen
return GreenOnGreen(
model_path=self._model_path,
confidence=self._gog_confidence,
detect_classes=current_classes,
hybrid_mode=True,
inference_resolution=self.inference_resolution,
crop_buffer_px=self.crop_buffer_px,
tracking_enabled=self.tracking_enabled,
crop_stabilizer=self._crop_stabilizer,
detection_persist_frames=self.detection_persist_frames,
)
else:
return GreenOnBrown(algorithm=algo)
try:
weed_detector = _create_detector(algorithm)
if algorithm in ('gog', 'gog-hybrid'):
self._gog_detector = weed_detector
except Exception as e:
self.logger.error(f"[ERROR] Failed to create detector for '{algorithm}': {e}")
self.logger.error("[ERROR] OWL will continue running without detection. Change algorithm via dashboard to recover.")
weed_detector = None
if self.dash:
self.dash.state['algorithm_error'] = str(e)
if self.show_display:
self.relay_vis = self.relay_controller.relay_vis
self.relay_vis.setup()
self.relay_controller.vis = True
prev_detection_enable = False
prev_recording_enable = False
try:
while True:
loop_start = time.time()
frame = self.cam.read()
if frame is None:
self.logger.info("[INFO] Frame is None. Stopped.")
self.stop()
break
# Reset tracker when detection toggled off
if prev_detection_enable and not self._detection_enable:
if (self.tracking_enabled and weed_detector
and hasattr(weed_detector, 'reset_tracker')):
weed_detector.reset_tracker()
if self._class_smoother:
self._class_smoother.reset()
self.logger.info("Tracker state reset (detection disabled)")
prev_detection_enable = self._detection_enable
# Create new session directory when recording starts
if self._image_sample_enable and not prev_recording_enable:
if hasattr(self, 'save_directory') and self.save_directory:
session_name = f"session_{datetime.now().strftime('%H%M%S')}"
date_dir = os.path.join(self.save_directory, datetime.now().strftime('%Y%m%d'))
session_dir = os.path.join(date_dir, session_name)
os.makedirs(session_dir, exist_ok=True)
# Stop old ImageRecorder, create new one for this session
if hasattr(self, 'image_recorder') and self.image_recorder:
self.image_recorder.stop()
self.image_recorder = ImageRecorder(
save_directory=session_dir, mode=self.sample_method)
self.logger.info(f"New recording session: {session_dir}")
prev_recording_enable = self._image_sample_enable
# Drain queued trackbar updates from MQTT thread (thread-safe)
if self.show_display and self._pending_trackbar_updates:
pending = self._pending_trackbar_updates
self._pending_trackbar_updates = {}
for tb_name, tb_val in pending.items():
cv2.setTrackbarPos(tb_name, self.window_name, tb_val)
# retrieve the trackbar positions for thresholds
if self.show_display:
self.exg_min = cv2.getTrackbarPos("ExG-Min", self.window_name)
self.exg_max = cv2.getTrackbarPos("ExG-Max", self.window_name)
self.hue_min = cv2.getTrackbarPos("Hue-Min", self.window_name)
self.hue_max = cv2.getTrackbarPos("Hue-Max", self.window_name)
self.saturation_min = cv2.getTrackbarPos("Sat-Min", self.window_name)
self.saturation_max = cv2.getTrackbarPos("Sat-Max", self.window_name)
self.brightness_min = cv2.getTrackbarPos("Bright-Min", self.window_name)
self.brightness_max = cv2.getTrackbarPos("Bright-Max", self.window_name)
# Pre-load detectors/models outside detection guard so they're
# ready instantly when the user enables detection.
# Live algorithm switching
if self._pending_algorithm and (weed_detector is None or self._pending_algorithm != algorithm):
try:
weed_detector = _create_detector(self._pending_algorithm)
algorithm = self._pending_algorithm
if algorithm in ('gog', 'gog-hybrid'):
self._gog_detector = weed_detector
self.logger.info(f"Live algorithm switch to: {algorithm}")
if self.dash:
self.dash.state.pop('algorithm_error', None)
except Exception as e:
self.logger.error(f"Failed to load detector for {self._pending_algorithm}: {e}")
# Revert — keep using current weed_detector and algorithm
if self.dash:
self.dash.state['algorithm'] = algorithm
self.dash.state['algorithm_error'] = str(e)
self._pending_algorithm = None
# Live model switching
if self._pending_model:
new_model = self._pending_model
self._pending_model = None
try:
self._model_path = new_model
weed_detector = _create_detector(algorithm)
if algorithm in ('gog', 'gog-hybrid'):
self._gog_detector = weed_detector
self.logger.info(f"Live model switch to: {new_model}")
if self.dash:
self.dash.state.pop('algorithm_error', None)
except Exception as e:
self.logger.error(f"Failed to switch model: {e}")
if self.dash:
self.dash.state['algorithm_error'] = str(e)
# Live detect_classes update
if self._pending_detect_classes is not None:
new_classes = self._pending_detect_classes
self._pending_detect_classes = None
self._detect_classes_list = new_classes
if weed_detector and hasattr(weed_detector, 'update_detect_classes'):
weed_detector.update_detect_classes(new_classes or None)
self.logger.info(f"detect_classes updated: {new_classes}")
# Live crop buffer update (hybrid mode only)
if (algorithm == 'gog-hybrid'
and weed_detector
and hasattr(weed_detector, 'set_crop_buffer')
and weed_detector.crop_buffer_px != self.crop_buffer_px):
weed_detector.set_crop_buffer(self.crop_buffer_px)
if self._detection_enable and weed_detector is not None:
cropped_frame = frame[self.crop_slice]
return_image_out = self.show_display or bool(self.dash)
if algorithm == 'gog':
cnts, boxes, weed_centres, image_out = weed_detector.inference(
cropped_frame,
confidence=self._gog_confidence,
show_display=return_image_out,
build_mask=(actuation_mode == 'zone' and not self.tracking_enabled)
)
if (self.tracking_enabled and actuation_mode == 'zone'
and not _zone_tracking_warned):
self.logger.warning(
'Zone actuation disabled while tracking is enabled — '
'using centre-based actuation instead')
_zone_tracking_warned = True
# Apply class smoothing: filter to target classes using majority-vote
if (self.tracking_enabled
and self._class_smoother
and weed_detector.last_track_ids):
smoothed = self._class_smoother.update(
weed_detector.last_track_ids,
weed_detector.last_class_ids,
weed_detector.last_confidences,
frame_count=frame_count
)
target_ids = set(weed_detector._detect_class_ids or [])
if target_ids:
filtered_boxes = []
filtered_centres = []
for tid, raw_box in zip(
weed_detector.last_track_ids,
weed_detector.last_raw_boxes):
if smoothed.get(tid, -1) in target_ids:
x, y, w, h = raw_box
filtered_centres.append([x + w // 2, y + h // 2])
filtered_boxes.append(raw_box)
boxes = filtered_boxes
weed_centres = filtered_centres
elif algorithm == 'gog-hybrid':
cnts, boxes, weed_centres, image_out = weed_detector.inference(
cropped_frame,
confidence=self._gog_confidence,
show_display=return_image_out,
exg_min=self.exg_min, exg_max=self.exg_max,
hue_min=self.hue_min, hue_max=self.hue_max,
saturation_min=self.saturation_min, saturation_max=self.saturation_max,
brightness_min=self.brightness_min, brightness_max=self.brightness_max,
min_detection_area=self.min_detection_area, invert_hue=self.invert_hue
)
else:
cnts, boxes, weed_centres, image_out = weed_detector.inference(
cropped_frame,
exg_min=self.exg_min,
exg_max=self.exg_max,
hue_min=self.hue_min,
hue_max=self.hue_max,
saturation_min=self.saturation_min,
saturation_max=self.saturation_max,
brightness_min=self.brightness_min,
brightness_max=self.brightness_max,
show_display=return_image_out,
algorithm=algorithm,
min_detection_area=self.min_detection_area,
invert_hue=self.invert_hue,
label='WEED'
)
# Merge Kalman-predicted lost tracks into detection output
# Only for pure gog mode — in hybrid, lost_stracks are crops not weeds
if (self.tracking_enabled
and self.detection_persist_frames > 0
and algorithm == 'gog'
and hasattr(weed_detector, 'get_lost_tracks')):
lost = weed_detector.get_lost_tracks(
max_age=self.detection_persist_frames)
target_ids = set(weed_detector._detect_class_ids or [])
persisted_boxes = []
for lt in lost:
smoothed_cls = (self._class_smoother.get_class(lt['track_id'])
if self._class_smoother else lt['cls'])
if target_ids and smoothed_cls not in target_ids:
continue
x1, y1, x2, y2 = [int(v) for v in lt['xyxy']]
w, h = x2 - x1, y2 - y1
boxes.append([x1, y1, w, h])
weed_centres.append([int((x1 + x2) / 2), int((y1 + y2) / 2)])
cls_name = weed_detector.model.names.get(lt['cls'], 'unknown')
persisted_boxes.append({
'x': x1, 'y': y1, 'w': w, 'h': h,
'track_id': lt['track_id'], 'age': lt['age'],
'conf': lt['score'], 'cls_name': cls_name,
})
# Draw persisted boxes on image_out with dimmed colour
if persisted_boxes and image_out is not None and return_image_out:
for pb in persisted_boxes:
cv2.rectangle(image_out,
(pb['x'], pb['y']),
(pb['x'] + pb['w'], pb['y'] + pb['h']),
(0, 120, 0), 2)
lbl = (f"ID{pb['track_id']} [{pb['age']}] "
f"{int(pb['conf'] * 100)}% {pb['cls_name']}")
cv2.putText(image_out, lbl,
(pb['x'], pb['y'] - 10),
cv2.FONT_HERSHEY_SIMPLEX, 0.5,
(0, 120, 0), 1)
if len(weed_centres) > 0:
if self.dash:
self.dash.weed_detect_indicator()
if self.controller:
self.controller.weed_detect_indicator()
# Zone-based actuation (segmentation models with gog/gog-hybrid)
if (algorithm.startswith('gog')
and actuation_mode == 'zone'
and hasattr(weed_detector, 'detection_mask')
and weed_detector.detection_mask is not None):
actuation_time = time.time()
for i in range(self.relay_num):
lane_start = self.lane_coords_int[i]
lane_end = int(lane_start + self.lane_width)
lane_pixels = np.count_nonzero(
weed_detector.detection_mask[self.actuation_y_thresh:, lane_start:lane_end]
)
if lane_pixels >= min_detection_pixels:
self.relay_controller.receive(
relay=i,
delay=self.delay,
time_stamp=actuation_time,
duration=self.actuation_duration)
else:
# Centre-based actuation (default, works for all model types)
# One timestamp per frame, deduplicated relay calls (at most relay_num)
if weed_centres:
actuation_time = time.time()
fired = set()
for centre in weed_centres:
if centre[1] >= self.actuation_y_thresh:
relay_id = min(int(centre[0] / self.lane_width), self.relay_num - 1)
fired.add(relay_id)
for relay_id in fired:
self.relay_controller.receive(
relay=relay_id,
delay=self.delay,
time_stamp=actuation_time,
duration=self.actuation_duration)
##### Update Dashboard Stream #####
if frame_count % 90 == 0: # Every 90 frames (~3 seconds at 30fps)
if self.dash and hasattr(self.dash, 'update_system_stats'):
try:
stats = self.get_system_stats()
self.dash.update_system_stats(stats)
except Exception as e:
self.logger.debug(f"Error updating system stats: {e}")
if self.dash and frame_count % 5 == 0: # send every 5th frame to the streamer to reduce overhead
try:
if self._detection_enable and image_out is not None:
final_frame_to_stream = image_out
else:
final_frame_to_stream = frame
if self.actuation_zone < 100:
cv2.line(final_frame_to_stream,
(0, self.actuation_y_thresh),
(final_frame_to_stream.shape[1], self.actuation_y_thresh),
(0, 255, 255), 1)
self.set_latest_stream_frame(final_frame_to_stream)
except Exception as e:
self.logger.error(f"Error sending frame to dashboard: {e}")
##### IMAGE SAMPLER #####
# record sample images if required of weeds detected. sampleFreq specifies how often
if self._image_sample_enable:
# only record every sampleFreq number of frames.
# If sample_frequency = 60, this will activate every 60th frame
if frame_count % self.sample_frequency == 0:
save_boxes = None
save_centres = None
if self.sample_method != 'whole' and self._detection_enable:
save_boxes = boxes
save_centres = weed_centres
self.image_recorder.add_frame(frame=frame,
frame_id=frame_count,
boxes=save_boxes,
centres=save_centres,
gps_data=self.gps_data)
if self.controller:
self.status_indicator.image_write_indicator()
if self.dash:
self.dash.image_write_indicator()
if self.status_indicator.DRIVE_FULL:
if self.dash:
self.dash.set_image_sample_enable(False)
self.dash.drive_full_indicator()
self.logger.info("Drive full: Image sampling disabled via MQTT")
else:
with self.image_sample_enable.get_lock():
self.image_sample_enable.value = False
self.logger.info("Drive full: Image sampling disabled locally")
self._image_sample_enable = False
self.image_recorder.stop()
self.status_indicator.error(5)
self.logger.info("Drive full: Image sampling disabled permanently due to storage full")
frame_count += 1
# Loop time tracking
loop_time_ms = (time.time() - loop_start) * 1000
self._loop_times.append(loop_time_ms)
self._avg_loop_time_ms = sum(self._loop_times) / len(self._loop_times)
# FPS logging (time-based, replaces imutils FPS)
if log_fps:
fps_frame_count += 1
elapsed = time.time() - last_fps_time
if elapsed >= 30.0:
approx_fps = fps_frame_count / elapsed
self.logger.info(f"[INFO] Approximate FPS: {approx_fps:.2f} | Avg loop: {self._avg_loop_time_ms:.1f}ms")
fps_frame_count = 0
last_fps_time = time.time()
if self.show_display:
if not self._detection_enable:
image_out = frame.copy()
if self.record_video:
if self.video_writer is None:
# Initialize video writer
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
video_filename = f"owl_recording_{timestamp}.mp4"
self.video_writer = cv2.VideoWriter(video_filename, fourcc, 30.0,
(frame.shape[1], frame.shape[0]))
# Write the frame with detections
self.video_writer.write(image_out)
cv2.putText(image_out, f'OWL-gorithm: {algorithm}', (20, 35), cv2.FONT_HERSHEY_SIMPLEX, 0.75,
(80, 80, 255), 1)
cv2.putText(image_out, f'Press "S" to save {algorithm} thresholds to file.',
(20, int(image_out.shape[1] * 0.72)), cv2.FONT_HERSHEY_SIMPLEX, 0.6, (80, 80, 255), 1)
h, w = image_out.shape[:2]
display_frame = cv2.resize(image_out, (600, int(h * 600 / w))) if w != 600 else image_out
cv2.imshow("Detection Output", display_frame)
k = cv2.waitKey(1) & 0xFF
if k == ord('s'):
self.save_parameters()
self.logger.info("[INFO] Parameters saved.")
elif k == ord('r'):