Skip to content

Instantly share code, notes, and snippets.

@m0nochr0me
Created December 27, 2020 19:55
Show Gist options
  • Save m0nochr0me/bf0ea0b5b3c59741971196e78526f76c to your computer and use it in GitHub Desktop.
Save m0nochr0me/bf0ea0b5b3c59741971196e78526f76c to your computer and use it in GitHub Desktop.
AirQualitySensor
import gc
import network
import esp
esp.osdebug(None)
gc.collect()
essid = "yourWiFiSSID"
password = "yourWiFiPassword"
TIMEZONE = 8
server = "192.168.0.10"
port = 19780
mqttuser = "mqttlogin"
mqttpwd = "MQttPassWord123"
TOPIC_PREFIX = 'sensor0/'
import machine
import time
import ntptime
import ubinascii
from umqtt.simple import MQTTClient
import bmp280
from ccs811 import CCS811
from si7021 import Si7021
from config import *
def initmqtt():
client_id = ubinascii.hexlify(machine.unique_id())
client = MQTTClient(client_id, server, port, mqttuser, mqttpwd)
client.connect()
print("MQTT Connected")
return client
def connect():
sta_if = network.WLAN(network.STA_IF)
if not sta_if.isconnected():
print("Connecting to {}...".format(essid))
sta_if.active(True)
sta_if.connect(essid, password)
while not sta_if.isconnected():
pass
print("Network config:", sta_if.ifconfig())
connect()
rtc = machine.RTC()
try:
ntptime.settime()
except:
print('Error setting time')
time.sleep(10)
machine.reset()
try:
client = initmqtt()
except:
print('Error initializing MQTT')
time.sleep(10)
machine.reset()
sec = time.time() + TIMEZONE * 3600
localtime = time.localtime(sec)
i2c = machine.I2C(scl=machine.Pin(5), sda=machine.Pin(4), freq=400000)
data = {}
ccs = CCS811(i2c=i2c, addr=0x5a)
si = Si7021(i2c, address=0x40)
bmp = bmp280.BMP280(i2c, addr=0x76)
bmp.power_mode = bmp280.BMP280_POWER_NORMAL
bmp.temp_os = bmp280.BMP280_TEMP_OS_8
bmp.press_os = bmp280.BMP280_PRES_OS_16
bmp.standby = bmp280.BMP280_STANDBY_500
bmp.iir = bmp280.BMP280_IIR_FILTER_16
time.sleep(1)
ccs.data_ready()
data['eCO2'] = str(ccs.eCO2)
data['tVOC'] = str(ccs.tVOC)
data['t0'] = str(round(si.temperature, 2))
data['h0'] = str(round(si.relative_humidity, 2))
data['t1'] = str(bmp.temperature)
data['p0'] = str(round(bmp.pressure / 133.32, 2))
for val in data:
print(TOPIC_PREFIX + val, data[val])
try:
client.publish(TOPIC_PREFIX + val, data[val], retain=True)
except:
machine.reset()
time.sleep(1)
rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
rtc.alarm(rtc.ALARM0, time.ticks_ms() + 300*1000)
print('Entering deepsleep')
machine.deepsleep()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment