From 09b41419d37e7f5433556dab6f46c150b6ea7ad2 Mon Sep 17 00:00:00 2001 From: Anurag Singh Date: Fri, 19 Jul 2024 17:58:53 +0530 Subject: [PATCH] feat: Add error handling for camera initialization. --- activity.py | 37 ++++++++++++++++++++++++++++++------- 1 file changed, 30 insertions(+), 7 deletions(-) diff --git a/activity.py b/activity.py index cb09f61..3b8456d 100644 --- a/activity.py +++ b/activity.py @@ -119,18 +119,23 @@ def flip_cb(self, b, flip_direction): #SECTION Camera operations #========================================================================== def start_camera_preview(self): + try: #* Initialize Camera - self.picam2 = Picamera2() - if not hasattr(self, 'preview_config'): - self.preview_config = self.picam2.create_preview_configuration({ + self.picam2 = Picamera2() + if not hasattr(self, 'preview_config'): + self.preview_config = self.picam2.create_preview_configuration({ 'size': self._size, 'format': self._format}, transform=Transform(hflip=self._hflip, vflip=self._vflip)) - self.picam2.configure(self.preview_config) - self.picam2.start() + self.picam2.configure(self.preview_config) + self.picam2.start() # Update the preview continuously: 30ms - GLib.timeout_add(30, self.update_preview) + GLib.timeout_add(30, self.update_preview) + + except Exception as e: + self.show_error_message("Failed to initialize the camera. Please check your connection.") + print(f"Error starting camera preview: {e}") def update_config(self): config = self.picam2.create_preview_configuration({ @@ -143,8 +148,26 @@ def update_config(self): print('changed preview config') def update_preview(self): - self.drawing_area.queue_draw() + if hasattr(self, 'picam2'): + try: + self.drawing_area.queue_draw() + except Exception as e: + self.show_error_message("Error updating preview.") + print(f"Error updating preview: {e}") return True + + def show_error_message(self, message): + # Create an error dialog + dialog = Gtk.MessageDialog( + parent=self, + flags=Gtk.DialogFlags.MODAL, + type=Gtk.MessageType.ERROR, + buttons=Gtk.ButtonsType.OK, + message_format=message + ) + dialog.run() + dialog.destroy() + def calculate_stride_and_scale(self, width, height, widget): stride = cairo.ImageSurface.format_stride_for_width(cairo.FORMAT_RGB24,