Skip to content
Snippets Groups Projects
input_new_data.py 4.14 KiB
import json
import os
from datetime import datetime
from server.data_processing.process_lidar_data import calculate_area_data, about_laz_file

# input_new_Lidar_data send new data gathered from the lidar and send it to the database (from the drone, most likely)
def input_new_Lidar_data(self, cursor, sensorId, bodyOfWater):
    try:
        print("name=",bodyOfWater)
        # hard coded coordinates
        latitude = 60.816848
        longitude = 10.723823

        # data about the file read from
        about_laz = about_laz_file()
        scale_factor = max(about_laz[2])

        # create a new measurement with the time the data is sent, sensor type, where
        # and an estimate of average thickness of ice on water body
        cursor.execute('''
            INSERT INTO Measurement(MeasurementID, SensorID, TimeMeasured, WaterBodyName, CenterLat, CenterLon) VALUES 
                (?,?,?,?,?,?);
        ''', (1, sensorId, datetime.utcnow().replace(microsecond=0), bodyOfWater, latitude, longitude))

        # auto generate new measurement id
        measurement_id = cursor.lastrowid

        # calculate the area of to be calculated based on the coordinates given to the calculation model
        areas_data = calculate_area_data((latitude, longitude), bodyOfWater)

        lidar_json_data = []

        if(areas_data):
            # store lidar data in jason formate
            # calculate data for each zone within the area
            for area in areas_data:
                # lng and lat relative to map
                subId = int(area[0])
                map_lat, map_lng = area[1]
                heights = area[2]

                if(len(heights) != 0 or sum(heights) == 0):
                    average = sum(heights)/len(heights)
                    minimum_thickness = min(heights)
                else:
                    average = 0
                    minimum_thickness = 0

                time_measured = datetime.utcnow().replace(microsecond=0)
                # input the data into the database
                cursor.execute('''
                INSERT INTO SubdivisionMeasurementData(MeasurementID, TimeMeasured, SubdivID, WaterBodyName, MinimumThickness, AverageThickness, CalculatedSafety, Accuracy) VALUES
                    (?,?,?,?,?,?,?,?);
                ''', (measurement_id, time_measured, subId, bodyOfWater, float(minimum_thickness), float(average), float(0.0), scale_factor))
                sub_center = (map_lat, map_lng)
                # set up json formate
                lidar_read = {
                    'MeasurementId': str(measurement_id),
                    'SubId': str(subId),
                    'SubCenter': str(sub_center),
                    'Heights': str(heights)
                }

                lidar_json_data.append(lidar_read)

            # input the newly generated measurement_id and whole average thickness
            cursor.execute('''
                UPDATE Measurement
                SET measurementID = ?
                WHERE MeasurementID IS NULL;
            ''', (int(measurement_id),))
        else:
            print('No data found, line 79')

        # send the changes to the database
        cursor.connection.commit()

        # Send response
        self.send_response(200)
        self.send_header('Content-type', "application/json")
        self.end_headers()
        file_path = "./server/map_handler/lake_relations/"+bodyOfWater+"_lidar_data.json"
        content = None

        current_directory = os.getcwd()
        print("Current working directory:", current_directory)

        if len(lidar_json_data) > 0:
            if os.path.exists(file_path):
                os.remove(file_path)

            # convert list of lidar data to json
            content = json.dumps(lidar_json_data)
            with open(file_path, "w") as file:
                file.write(content)
        else:
            print('No data found, line 101')
            content = json.dumps([])


        # Write content data to response object
        self.wfile.write(content.encode('utf-8'))

    # error handling
    except Exception as e:
        print("An error occurred: ", e)
        # rollback in case of error
        cursor.connection.rollback()