繁体   English   中英

每秒读取一次读数时发出一次警报 Python

[英]Alerting one time on a reading taken every second Python

我正在研究 Raspberry Pi 4B 并连接了 BME680 空气质量传感器。 我的读数每秒读取一次并写入 MySQL 数据库。

如果空气质量、温度等超出最佳范围,我希望能够发出警报。 我遇到的问题是传感器每秒读取一次,所以如果我尝试建立警报,它会每秒关闭一次,直到范围恢复到最佳状态。 我想知道如何仅在值更改超出范围时发出警报。

# SPDX-FileCopyrightText: 2021 ladyada for Adafruit Industries
# SPDX-License-Identifier: MIT

import time
import board
from busio import I2C
import adafruit_bme680
import subprocess
import mysql.connector
from datetime import datetime

#SQL Setup
mydb = mysql.connector.connect(
  host="localhost",
  user="some_user",
  password="some_pass",
  database="some_db"
)
# Create library object using our Bus I2C port
i2c = I2C(board.SCL, board.SDA)
bme680 = adafruit_bme680.Adafruit_BME680_I2C(i2c, debug=False)

# change this to match the location's pressure (hPa) at sea level
bme680.sea_level_pressure = 1013.25

# You will usually have to add an offset to account for the temperature of
# the sensor. This is usually around 5 degrees but varies by use. Use a
# separate temperature sensor to calibrate this one.
temperature_offset = -1

while True:
    now = datetime.now()
    formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')
#    print("\nTemperature: %0.1f C" % (bme680.temperature + temperature_offset))
#    print("Gas: %d ohm" % bme680.gas)
#    print("Humidity: %0.1f %%" % bme680.relative_humidity)
#    print("Pressure: %0.3f hPa" % bme680.pressure)
#    print("Altitude = %0.2f meters" % bme680.altitude)
#    print (formatted_date)
    tmp = (bme680.temperature + temperature_offset)
    real_temp = (tmp * 1.8) + 32
#    print(real_temp)
    gas = (bme680.gas)
    humid = (bme680.relative_humidity)
    pres = (bme680.pressure)
    mycursor = mydb.cursor()
    sql = "INSERT INTO data (Temperature, Gas, Humidity, Pressure, DT) VALUES (%s, %s, %s, %s, %s)"
    val = (real_temp, gas, humid, pres, formatted_date)
    mycursor.execute(sql, val)
    mydb.commit()
##    if ( tmp > 19 ):
##        subprocess.call(['python3', 'alert.py'])
#    else:
#        print ("nothing to do")
    time.sleep(1)

这是我的代码。 同样,我不想每秒钟都调用我的alert.py ,这会使我正在警告的服务器不堪重负,我希望在温度降至 19 摄氏度以下时发出一次警报。

谢谢

您可以添加 function 以获取存在温度的范围。 如果范围已更改,请再次发送警报。 您的 state 是您的温度下降范围。

请看下面:

import bisect
temp_ranges = [15, 20, 25, 30]
temp_states = ['Severe', 'Normal', 'Rising', 'High', 'Gonna Blow up!']

def get_range(temp):
    return bisect.bisect_left(temp_ranges, temp)

for temp in [10, 13, 15, 16, 20, 21, 25, 26, 30, 35]:
    print(f'Temp is: {temp}: Label is {temp_states[get_range(temp)]}')

计算出温度tmp后,然后在while True循环中调用 function 。 像这样:

state = temp_states[get_range(tmp)]
if state is not previous_state:
    subprocess.call(['python3', 'alert.py'])
    previous_state = state # define previous_state = None before your loop begins.
else:
    print ("nothing to do")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM