import time
import serial
import mysql.connector
while True:
def get_temperature_and_humidity(ser):
# Send the “read” command to the device via the serial port
ser.write(b”read\n”)
# Read the response from the device
response = ser.readline().decode(‘utf-8′, errors=’ignore’)
# If the response is received successfully, split temperature and humidity and return them as floats
if response:
temperature, humidity = response.split(“,”)
return float(temperature), float(humidity)
else:
return None, None
def get_light_value(ser):
# Send the “read_light” command to the device via the serial port
ser.write(b”read_light\n”)
# Read the response from the device
response = ser.readline().decode(‘utf-8′, errors=’ignore’)
# If the response is received successfully, return the light value as a float
if response:
return float(response)
else:
return None
def insert_data_into_database(temperature, humidity, light):
# Check that temperature, humidity, and light values are not None
if temperature is not None and humidity is not None and light is not None:
# Connect to the MySQL database
connection = mysql.connector.connect(
host=”localhost”,
user=”*”,
password=”*”,
database=”*”
)
# Create a cursor object to execute SQL queries
cursor = connection.cursor()
# Create the table if it doesn’t exist
create_table_query = ”’
CREATE TABLE IF NOT EXISTS temperature_and_humidity (
id INT AUTO_INCREMENT PRIMARY KEY,
timestamp DATETIME NOT NULL,
temperature FLOAT NOT NULL,
humidity FLOAT NOT NULL,
light FLOAT NOT NULL
)
”’
cursor.execute(create_table_query)
# Get the current time for inserting into the database
current_time = time.strftime(‘%Y-%m-%d %H:%M:%S’)
# Use a parameterized query for safe data insertion
insert_query = ”’
INSERT INTO temperature_and_humidity (timestamp, temperature, humidity, light)
VALUES (%s, %s, %s, %s)
”’
values = (current_time, temperature, humidity, light)
cursor.execute(insert_query, values)
# Commit the changes to the database and close the connection
connection.commit()
cursor.close()
connection.close()
else:
print(“Error: Temperature, humidity, or light data not available.”)
# Example usage of the functions
if __name__ == “__main__”:
# Connect to the serial port
ser_port = serial.Serial(“COM7”, 9600, timeout=2)
temperature, humidity = get_temperature_and_humidity(ser_port)
light = get_light_value(ser_port)
insert_data_into_database(temperature, humidity, light)
ser_port.close()
# Подождать 15 минуту перед следующим измерением
time.sleep(900)