python测试温度传感器写入数据库

测试数据库写入功能,可以用随机数生成模拟温度数据。以下是修改后的代码:

import pymysql
import time
from datetime import datetime
import logging
import random

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    filename='temperature_monitor.log'
)

# 数据库配置
DB_CONFIG = {
    'host': 'localhost',
    'user': 'your_username',
    'password': 'your_password',
    'database': 'greenhouse',
    'charset': 'utf8mb4',
    'cursorclass': pymysql.cursors.DictCursor
}

# 温度数据范围(模拟真实环境)
MIN_TEMP = 18.0
MAX_TEMP = 32.0

def create_database_table():
    """创建数据库表(如果不存在)"""
    try:
        conn = pymysql.connect(**DB_CONFIG)
        with conn.cursor() as cursor:
            cursor.execute("""
                CREATE TABLE IF NOT EXISTS temperature_data (
                    id INT AUTO_INCREMENT PRIMARY KEY,
                    timestamp DATETIME NOT NULL,
                    temperature FLOAT NOT NULL,
                    sensor_id VARCHAR(50) DEFAULT 'sensor1',
                    status ENUM('normal', 'warning', 'error') DEFAULT 'normal'
                )
            """)
        conn.commit()
        logging.info("数据库表检查/创建成功")
        return conn
    except Exception as e:
        logging.error(f"数据库初始化失败: {e}")
        raise

def generate_random_temperature():
    """生成模拟温度数据(带小幅波动)"""
    # 基础温度(可根据实际场景调整)
    base_temp = 25.0
    
    # 添加随机波动(-3℃到+3℃)
    fluctuation = round(random.uniform(-3, 3), 1)
    
    # 生成最终温度(确保在合理范围内)
    temperature = max(MIN_TEMP, min(MAX_TEMP, base_temp + fluctuation))
    
    # 偶尔生成异常值用于测试
    if random.random() < 0.05:  # 5%概率生成异常值
        return random.choice([MIN_TEMP - 5, MAX_TEMP + 5])
    
    return temperature

def validate_temperature(temperature):
    """验证温度数据有效性"""
    if MIN_TEMP <= temperature <= MAX_TEMP:
        return temperature, "normal"
    elif (temperature >= MIN_TEMP - 10) and (temperature <= MAX_TEMP + 10):
        return temperature, "warning"  # 轻微超出范围
    else:
        return None, "error"  # 严重异常

def write_to_database(conn, temperature, status="normal"):
    """将温度数据写入数据库"""
    try:
        with conn.cursor() as cursor:
            sql = """
                INSERT INTO temperature_data 
                (timestamp, temperature, status) 
                VALUES (%s, %s, %s)
            """
            cursor.execute(sql, (datetime.now(), temperature, status))
        conn.commit()
        logging.info(f"数据写入成功: {temperature}°C ({status})")
    except Exception as e:
        logging.error(f"数据库写入失败: {e}")
        conn.rollback()

def main():
    """主程序:生成随机温度数据并写入数据库"""
    db_conn = None
    
    try:
        # 初始化数据库
        db_conn = create_database_table()
        
        print("温度模拟系统已启动,按Ctrl+C停止")
        
        while True:
            # 生成随机温度
            temp_value = generate_random_temperature()
            
            # 验证温度
            temperature, status = validate_temperature(temp_value)
            
            if temperature is not None:
                # 写入数据库
                write_to_database(db_conn, temperature, status)
                print(f"{datetime.now().strftime('%H:%M:%S')} - {temperature}°C ({status})")
            else:
                print(f"错误: 温度异常 - {temp_value}°C")
            
            # 等待下一次生成
            time.sleep(1)  # 每秒生成一次
    
    except KeyboardInterrupt:
        print("\n程序已停止")
    except Exception as e:
        logging.critical(f"程序崩溃: {e}")
        print(f"致命错误: {e}")
    finally:
        # 关闭数据库连接
        if db_conn:
            db_conn.close()
            logging.info("数据库连接已关闭")

if __name__ == "__main__":
    main()

主要修改说明:

  1. 移除串口依赖

    • 不再需要serial
    • 删除了所有串口相关代码
  2. 添加随机温度生成

    • generate_random_temperature()函数生成模拟温度数据
    • 包含基础温度和随机波动
    • 偶尔生成异常值用于测试边界情况
  3. 增强数据验证

    • 添加三级状态分类(normal/warning/error)
    • 数据库表中增加status字段记录数据状态
  4. 优化模拟数据

    • 温度波动更符合实际环境(围绕25℃上下波动)
    • 保留了原有日志和数据库结构

使用说明:

  1. 安装依赖
pip install pymysql
  1. 配置修改
  • 修改DB_CONFIG中的数据库连接信息
  • 可调整MIN_TEMPMAX_TEMP定义温度范围
  1. 运行程序
python temperature_monitor.py

控制台输出示例:

温度模拟系统已启动,按Ctrl+C停止
14:32:15 - 23.7°C (normal)
14:32:16 - 24.9°C (normal)
14:32:17 - 22.1°C (normal)
14:32:18 - 27.8°C (normal)
14:32:19 - 26.3°C (normal)
14:32:20 - 24.5°C (normal)
14:32:21 - 34.2°C (warning)  # 偶尔出现的异常值
14:32:22 - 25.1°C (normal)

这个版本适合在没有实际硬件的情况下测试数据库写入逻辑,也便于观察不同温度状态下的系统行为。

你可能感兴趣的:(数据库,python,sql)