2
2
import cv2
3
3
import time
4
4
from PyQt5 import QtCore , QtGui , QtWidgets
5
- from ui .new_gui import Ui_MainWindow
5
+ from PyQt5 .QtWidgets import QMessageBox
6
+ from ui .new_gui3 import Ui_MainWindow
6
7
from sqlalchemy import create_engine , text
7
8
from datetime import datetime
8
9
import logging
9
10
import queue
10
11
from onnxmodules .yolov8onnx import YOLOv8
11
12
12
- # Logging configuration
13
13
logging .basicConfig (level = logging .INFO ,
14
14
format = '%(asctime)s - %(levelname)s - %(message)s' ,
15
15
handlers = [
16
- logging .FileHandler ("yeni .log" ),
16
+ logging .FileHandler ("new .log" ),
17
17
logging .StreamHandler ()
18
18
])
19
19
@@ -44,7 +44,6 @@ def get(self):
44
44
except queue .Empty :
45
45
logging .error ("Error LatestFrame get function." )
46
46
47
-
48
47
class DatabaseThread (QtCore .QThread ):
49
48
def __init__ (self , detected_dict , db_manager ):
50
49
super ().__init__ ()
@@ -88,7 +87,7 @@ def update_detection_in_database(self, detected_dict):
88
87
def log_thread_finished (self ):
89
88
logging .info ("DatabaseThread successfully finished." )
90
89
91
- class DatabaseManager () :
90
+ class DatabaseManager :
92
91
def __init__ (self ):
93
92
super ().__init__ ()
94
93
self .engine = None
@@ -97,18 +96,18 @@ def __init__(self):
97
96
def connect (self ):
98
97
try :
99
98
if not self .connected :
100
- server = 'server_ip '
101
- database = 'database_name '
102
- username = 'username '
103
- password = 'password '
99
+ server = '10.161.112.70 '
100
+ database = 'AIDATA '
101
+ username = 'majorskt '
102
+ password = 'gargara '
104
103
driver = 'ODBC Driver 17 for SQL Server'
105
104
connection_string = f"mssql+pyodbc://{ username } :{ password } @{ server } /{ database } ?driver={ driver } "
106
105
self .engine = create_engine (
107
106
connection_string ,
108
- pool_size = 20 ,
109
- max_overflow = 40 ,
110
- pool_timeout = 30 ,
111
- pool_recycle = 1800
107
+ pool_size = 20 , # Varsayılan değeri artırın
108
+ max_overflow = 40 , # Varsayılan değeri artırın
109
+ pool_timeout = 30 , # Zaman aşımı süresini gerektiğinde artırın
110
+ pool_recycle = 1800 # Bağlantıların geri dönüşüm süresini ayarlayın
112
111
)
113
112
self .connected = True
114
113
logging .info ("Database connected" )
@@ -177,6 +176,7 @@ class CameraThread(QtCore.QThread):
177
176
change_pixmap_signal = QtCore .pyqtSignal (QtGui .QImage )
178
177
update_fps_signal = QtCore .pyqtSignal (float )
179
178
update_person_count_signal = QtCore .pyqtSignal (int )
179
+ error_signal = QtCore .pyqtSignal (str ) # Add signal for errors
180
180
181
181
def __init__ (self , source , yolo_model , latest_frame , db_manager ):
182
182
super ().__init__ ()
@@ -198,21 +198,16 @@ def __init__(self, source, yolo_model, latest_frame, db_manager):
198
198
def run (self ):
199
199
try :
200
200
logging .info ("CameraThread started" )
201
- start_time = time .time ()
202
201
self .cap = cv2 .VideoCapture (self .source )
203
- end_time = time .time ()
204
- logging .info (f"Camera access time: { end_time - start_time :.2f} seconds" )
205
-
206
202
if not self .cap .isOpened ():
207
- try :
208
- logging .error ("Failed to open camera" )
209
- self .retry_connection ()
210
- return
211
- except Exception as e :
212
- logging .error (f"Kamera tekrar açılamadı: { e } " )
203
+ logging .error ("Failed to open camera initially" )
204
+ self .error_signal .emit ("Failed to open camera initially. Please check the camera connection." )
205
+ return
206
+
213
207
self .cap .set (cv2 .CAP_PROP_FRAME_WIDTH , 640 )
214
208
self .cap .set (cv2 .CAP_PROP_FRAME_HEIGHT , 640 )
215
209
self .running = True
210
+
216
211
while not self .isInterruptionRequested ():
217
212
ret , frame = self .cap .read ()
218
213
if ret :
@@ -235,7 +230,7 @@ def run(self):
235
230
detected_dict = {
236
231
'Tespit Edilme Saati' : datetime .strptime (tespit_zamani , "%Y-%m-%d %H:%M:%S" ),
237
232
'Tespit Durumu' : tespit_durumu ,
238
- 'ID' : 2
233
+ 'ID' : 2 # Güncellenecek kaydın ID'si
239
234
}
240
235
db_thread = DatabaseThread (detected_dict , self .db_manager )
241
236
db_thread .start ()
@@ -254,11 +249,17 @@ def run(self):
254
249
else :
255
250
logging .warning ("Cannot read frame from camera" )
256
251
self .stop ()
257
- self .retry_connection ()
252
+ if not self .retry_connection ():
253
+ logging .error ("Failed to reconnect to camera" )
254
+ self .error_signal .emit ("Failed to reconnect to camera. Please check the camera connection." )
255
+ break
256
+
258
257
self .cap .release ()
259
- self .processing_frames = False
258
+ self .processing_frames = False # Indicate that processing is done
259
+
260
260
except Exception as e :
261
261
logging .error (f"Error in CameraThread: { e } " )
262
+ self .error_signal .emit (str (e ))
262
263
if self .cap :
263
264
self .cap .release ()
264
265
@@ -271,26 +272,33 @@ def stop(self):
271
272
logging .error (f"Error in CameraThread.stop: { e } " )
272
273
273
274
def retry_connection (self ):
274
- try :
275
- while not self .running :
275
+ retry_count = 0
276
+ max_retry_duration = 20 # seconds
277
+ start_time = time .time ()
278
+
279
+ while time .time () - start_time < max_retry_duration :
280
+ try :
276
281
logging .info ("Attempting to reconnect to camera..." )
277
- self .cap .release ()
282
+ if self .cap :
283
+ self .cap .release ()
278
284
time .sleep (2 )
279
285
self .cap = cv2 .VideoCapture (self .source )
280
- self .cap .set (cv2 .CAP_PROP_FRAME_WIDTH , 640 )
281
- self .cap .set (cv2 .CAP_PROP_FRAME_HEIGHT , 640 )
282
286
if self .cap .isOpened ():
283
287
logging .info ("Reconnected to camera" )
284
- self .running = True
285
- break
288
+ return True
286
289
else :
287
- logging .warning ("Failed to reconnect to camera" )
288
- except Exception as e :
289
- logging .error (f"Error in CameraThread.retry_connection: { e } " )
290
+ logging .warning (f"Failed to reconnect to camera (attempt { retry_count + 1 } )" )
291
+ retry_count += 1
292
+ except Exception as e :
293
+ logging .error (f"Error in CameraThread.retry_connection: { e } " )
294
+
295
+ logging .error ("Failed to reconnect to camera after maximum retry duration. Please check the camera connection." )
296
+ return False
290
297
291
298
def log_thread_finished (self ):
292
299
logging .info ("CameraThread successfully finished." )
293
300
301
+
294
302
class MainWindow (QtWidgets .QMainWindow , Ui_MainWindow ):
295
303
stop_signal = QtCore .pyqtSignal ()
296
304
@@ -326,8 +334,6 @@ def init_ui(self):
326
334
self .model_box .addItems (['yolov8n' , 'yolov8m' , 'yolov8l' , 'yolov8x' ])
327
335
self .model_box .currentTextChanged .connect (self .change_model )
328
336
329
- self .camera_box .addItems (['your_rtsp_ip' ])
330
-
331
337
self .open_camera .clicked .connect (self .start_camera )
332
338
self .stop_camera .clicked .connect (self .stop_camera_stream )
333
339
except Exception as e :
@@ -363,14 +369,11 @@ def change_model(self, model_name):
363
369
def start_camera (self ):
364
370
try :
365
371
if self .camera_thread is None :
366
- camera_source = self .camera_box .currentText ()
367
- camera_url = 'rtsp://admin:admin1admin1@192.168.1.108:554/cam/realmonitor?channel=1&subtype=1'
368
- '''if camera_source == '0':
369
- camera_url = 0
370
- else:
371
- camera_url = camera_source'''
372
-
373
- self .camera_thread = CameraThread (camera_url , self .yolo_model , self .latest_frame , self .db_manager )
372
+ camera_source = self .camera_line .text ()
373
+ if camera_source .isdigit ():
374
+ camera_source = int (camera_source )
375
+ self .camera_thread = CameraThread (camera_source , self .yolo_model , self .latest_frame , self .db_manager )
376
+ self .camera_thread .error_signal .connect (self .show_error_message ) # Connect error signal to slot
374
377
time .sleep (0.2 )
375
378
self .camera_thread .change_pixmap_signal .connect (self .update_image )
376
379
self .camera_thread .update_fps_signal .connect (self .update_fps )
@@ -471,6 +474,7 @@ def update_provider_label(self, provider):
471
474
472
475
def format_provider (self , provider_value ):
473
476
return f"<html><head/><body><p align=\" center\" ><span style=\" font-size:12pt;\" >PROVİDER</span></p><hr/><p align=\" center\" ><span style=\" font-size:12pt;\" >{ provider_value } </span></p></body></html>"
477
+
474
478
def format_fps (self , fps_value ):
475
479
return f"<html><head/><body><p align=\" center\" ><span style=\" font-size:12pt;\" >Fps</span></p><hr/><p align=\" center\" ><span style=\" font-size:12pt;\" >{ fps_value } </span></p></body></html>"
476
480
@@ -480,6 +484,14 @@ def format_model(self, model_value):
480
484
def format_person (self , person_value ):
481
485
return f"<html><head/><body><p align=\" center\" ><span style=\" font-size:12pt;\" >Detection Person</span></p><hr/><p align=\" center\" ><span style=\" font-size:12pt;\" >{ person_value } </span></p></body></html>"
482
486
487
+ def show_error_message (self , message ):
488
+ self .stop_camera_stream () # Ensure all threads are terminated
489
+ msg_box = QMessageBox ()
490
+ msg_box .setIcon (QMessageBox .Critical )
491
+ msg_box .setText (message )
492
+ msg_box .setWindowTitle ("Camera Connection Error" )
493
+ msg_box .exec_ ()
494
+
483
495
try :
484
496
if __name__ == "__main__" :
485
497
app = QtWidgets .QApplication (sys .argv )
0 commit comments