import serial from datetime import datetime import json from models import Data, db from app import app # Open the COM port ser = serial.Serial('COM14', 9600, timeout=1) # Check if the port is open if ser.is_open: print(f"Connected to {ser.name}") try: while True: # Read data from the COM port if ser.in_waiting > 0: data = ser.readline().decode('utf-8').rstrip() parsed = json.loads(data) rawDataTime = parsed["dataTime"] parsedDataTime = str(rawDataTime).split("-") #datetime(2012, 3, 3, 10, 10, 10) dataTime =datetime(int(parsedDataTime[0]), int(parsedDataTime[1]), int(parsedDataTime[2]), int(parsedDataTime[3]), int(parsedDataTime[4]), int(parsedDataTime[5]), ) with app.app_context(): dt = db.session.add(Data(temp1=float(parsed["temp1"]), vlaz1=float(parsed["hum1"]), temp2=float(parsed["temp2"]), vlaz2=float(parsed["hum2"]), addTime=dataTime)) db.session.commit() except KeyboardInterrupt: print("Exiting...") finally: # Close the COM port ser.close() print("Serial port closed")