윤영준 윤영준 05-29
1. main server database data uploader.
@2a2eed6ad67b97f16e708d55d2bbdc570e6a4608
postprocess_draft.py
--- postprocess_draft.py
+++ postprocess_draft.py
@@ -33,9 +33,6 @@
 # Namespace definition
 ns = api.namespace('postprocess', description='Postprocessing of inference results')
 
-with open('config_files/MAIN_DB_ENDPOINT.json', 'r') as file:
-    db_config = json.load(file)
-
 class StreamSources():
     def __init__(self, buffer_size, normal_send_interval, failure_mode_thres, failure_mode_check_past_n, normal_mode_thres, normal_mode_check_past_n):
         assert failure_mode_thres <= failure_mode_check_past_n,\
@@ -89,6 +86,7 @@
                 "normal_to_failure_mode_change_alert" : False,
                 "failure_to_normal_mode_change_alert" : False
             }
+            self.cache_cctv_info = None
         else : 
             raise KeyError(f"Error! Source {key} already initialized.")
         # Update logic here if needed
@@ -99,7 +97,7 @@
     def __call__(self):
         return self.sources
 
-    def add_status(self, source, status, image, seg_image):
+    def add_status(self, source, status, cctv_info, image, seg_image):
         assert status in ["OK", "FAIL"],\
             f"Invalid status was given!, status must be one of 'OK' or 'FAIL', but given '{status}'!"
         
@@ -109,6 +107,8 @@
         flag_send_event = False
 
         status_value = 1 if status == "OK" else 0
+
+        self.cache_cctv_info = cctv_info
 
         self.sources[source]["status_counts"].append(status_value)
         if len(self.sources[source]["status_counts"]) > self.buffer_size:
@@ -161,25 +161,63 @@
             self.sources[source]["normal_to_failure_mode_change_alert"] = False
 
     def send_event(self, source):
-        try :
+        source_data = self.sources[source]
+        try:
+            # Connect to the database
             conn = psycopg2.connect(**db_config)
             cursor = conn.cursor()
 
-            upload_data_sql_query = """
-                INSERT INTO 
+            # Set the search path for the schema
+            cursor.execute("SET search_path TO ai_camera_v0_1;")
+
+            # Prepare the SQL query
+            insert_sql = """
+            INSERT INTO flooding_detect_event (
+                ocrn_dt, 
+                eqpmn_nm, 
+                flooding_result, 
+                flooding_per, 
+                image, 
+                image_seg, 
+                eqpmn_lat, 
+                eqpmn_lon, 
+                norm_to_alert_flag, 
+                alert_to_norm_flag
+            ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s);
             """
 
-            cursor.close()
-            conn.close()
+            # Prepare data to insert
+            data_tuple = (
+                time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(source_data["last_send_before"])),
+                source_data["cctv_info"]["cctv_name"],
+                "FAIL" if source_data["failure_counts"] >= self.failure_mode_thres else "OK",
+                source_data["cctv_info"]["area_percent"],
+                source_data["most_recent_image"],
+                source_data["most_recent_seg_image"],
+                source_data["cctv_info"]["cctv_latitude"],
+                source_data["cctv_info"]["cctv_longitude"],
+                source_data["normal_to_failure_mode_change_alert"],
+                source_data["failure_to_normal_mode_change_alert"]
+            )
 
-        except ValueError as e:
-            print(e)
+            # Execute the query
+            cursor.execute(insert_sql, data_tuple)
+            conn.commit()
+
+            print(f"EVENT: Sent for {source} - Data inserted successfully.")
+
         except Exception as e:
-            print(e)
+            print(f"Database operation failed: {e}")
+        finally:
+            if cursor:
+                cursor.close()
+            if conn:
+                conn.close()
 
-        self.sources[source]["last_send_before"] = 0
-        print(f"EVENT : SENDING {source}!!")
-        pass
+        # Reset the image data after sending to avoid re-sending the same image
+        source_data["most_recent_image"] = None
+        source_data["most_recent_seg_image"] = None
+        source_data["last_send_before"] = 0
 
 
 memory = StreamSources(
@@ -276,7 +314,7 @@
                 pass
             pass_fail = self.pass_fail()
 
-            memory.add_status(self.cctv_name, pass_fail, image_b64, seg_image_b64)
+            memory.add_status(self.cctv_name, pass_fail, self.cctv_info, image_b64, seg_image_b64)
 
             if debug:
                 print(memory())
Add a comment
List