Using trust Copilot (As it's next to me and I'm lazy today) guiding it along but not checked myself, again no database.
Pi side (EDIT, if to handle your other messages plus easier to debug at the start)
Pi side (EDIT, if to handle your other messages plus easier to debug at the start)
Code:
import serialimport mariadbimport jsonimport sys# Establish connection to MariaDBdef connect_to_db(): try: conn = mariadb.connect( user="your_username", password="your_password", host="127.0.0.1", port=3306, database="your_database" ) return conn except mariadb.Error as e: print(f"Error connecting to MariaDB: {e}") sys.exit(1)# Insert data into the databasedef insert_data(cursor, data): try: # Prepare the query dynamically based on the fields in the JSON fields = ", ".join(data.keys()) placeholders = ", ".join(["?"] * len(data)) query = f"INSERT INTO weather_data ({fields}) VALUES ({placeholders})" cursor.execute(query, list(data.values())) except mariadb.Error as e: print(f"Error inserting data into MariaDB: {e}")# Read and process data from the serial portdef read_from_serial(serial_port): try: line = serial_port.readline().decode('utf-8').strip() print(f"Received message: {line}") # Print all incoming messages # Attempt to parse the line as JSON try: data = json.loads(line) return data except json.JSONDecodeError: print("Non-JSON message received.") return None except UnicodeDecodeError as e: print(f"Error decoding serial input: {e}") return Nonedef main(): # Configure the serial port serial_port = serial.Serial('/dev/ttyACM0', 9600, timeout=1) # Connect to the database conn = connect_to_db() cursor = conn.cursor() print("Listening for data...") while True: # Read and process data from the serial port data = read_from_serial(serial_port) if data: # Insert valid JSON data into the database insert_data(cursor, data) conn.commit() print(f"Data inserted into database: {data}") # Close the connection when exiting conn.close()if __name__ == "__main__": main()Statistics: Posted by bensimmo — Tue Apr 15, 2025 3:07 pm