简体   繁体   中英

Telegram-bot sensor data

I'm trying to write simple telegram bot which returns temperature or humidity values from sensor installed on raspberry pi. The problem is that I'm getting constant velue for temp and hum all the time. Basically loop is not working and bot do not read new values for temp and hum. What I'm doing wrong?

import bme680 # sensor lib
import telebot

bot = telebot.TeleBot('TOKEN')

sensor = bme680.BME680()
sensor.set_humidity_oversample(bme680.OS_2X)
sensor.set_pressure_oversample(bme680.OS_4X)
sensor.set_temperature_oversample(bme680.OS_8X)
sensor.set_filter(bme680.FILTER_SIZE_3)

def temp():
    temp = sensor.data.temperature
    return temp

def hum():
    hum = sensor.data.humidity
    return hum

while True:
    if sensor.get_sensor_data():
    
        @bot.message_handler(commands=['start'])
        def start_message(message):
            bot.send_message(message.chat.id, 'Hi! Temp or Hum?')
                        
        @bot.message_handler(content_types=['text'])
        def send_text(message):
            if message.text == 'Temp':
                bot.send_message(message.chat.id, 'Temp ' + str(temp()))
            elif message.text == 'Hum':
                bot.send_message(message.chat.id, 'Hum '+str(hum()))
                
        bot.polling()

The problem is that sensor.get_sensor_data() gets the data from the device and stores its value in data and this value never refreshes. The solution is to put sensor.get_sensor_data() at he beginning of Temp and Hum functions:

def temp():
    if sensor.get_sensor_data():
        temp = sensor.data.temperature
        return temp

def hum():
    if sensor.get_sensor_data():
        hum = sensor.data.humidity
        return hum

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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