mqtt-sensord/mqtt_sensord/sensorlib/esp_sensors.py

44 lines
1.1 KiB
Python

import dht
import ds18x20
import machine
import onewire
import time
from .base import Sensor, sensor
@sensor
class DS18B20(Sensor):
sensor_class = 'esp-ds18b20'
def __init__(self, **sensor_conf):
super(DS18B20, self).__init__(**sensor_conf)
self.o = onewire.OneWire(machine.Pin(self.pin))
self.ds = ds18x20.DS18X20(self.o)
self.sID = self.ds.scan()[0]
def get_data(self):
self.ds.convert_temp()
time.sleep(0.1)
return {"temp": self.ds.read_temp(self.sID)}
@sensor
class DHT(Sensor):
sensor_class = 'esp-dht'
def __init__(self, **sensor_conf):
super(DHT, self).__init__(**sensor_conf)
if sensor_conf["dht_type"] == "dht11":
self.dht = dht.DHT11(machine.Pin(self.pin))
elif sensor_conf["dht_type"] == "dht22":
self.dht = dht.DHT22(machine.Pin(self.pin))
else:
raise ValueError("Unknown type")
def get_data(self):
self.dht.measure()
time.sleep(0.1)
return {"temp": self.dht.temperature(), "humidity": self.dht.humidity()}