-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.py
87 lines (65 loc) · 1.64 KB
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
from MQ2 import MQ2
from network import WLAN
from umqtt.simple import MQTTClient
import wifimgr
import machine
import utime
import ujson
import sys
# MQ2 Sensor Analog Pin is connected to this pin on the ESP32
pin = machine.Pin(34)
# This runs on a Lipo battery, 3.7V
sensor = MQ2(pinData = pin, baseVoltage = 3.3)
print("Calibrating")
sensor.calibrate()
print("Calibration completed")
print("Base resistance:{0}".format(sensor._ro))
while True:
# WiFi setup
wlan = wifimgr.get_connection()
if wlan is None:
print("Could not initialize the network connection.")
while True:
pass # you shall not pass :D
# Read Sensor data
gotValues = False
retries = 4
retry = 0
try:
smokeValue = sensor.readSmoke()
lpgValue = sensor.readLPG()
methaneValue = sensor.readMethane()
hydrogenValue = sensor.readHydrogen()
gotValues = True
except Exception as e:
print(e)
gotValues = False
retry = retry + 1
if retry == retries:
print("Retries exceeded, restarting...")
machine.reset()
if gotValues:
# MQTT Message
message = {}
message["smoke"] = smokeValue
message["lpg"] = lpgValue
message["methane"] = methaneValue
message["hydrogen"] = hydrogenValue
print(message)
# Publish message to MQTT
client = MQTTClient(client_id="kitchen-mq2", server="10.0.1.200", user="mqtt", password="hassio")
connected = False
while not connected:
try:
client.connect()
connected = True
except:
connected = False
utime.sleep(5)
topic = "/kitchen/mq2"
data = bytes(ujson.dumps(message),"utf-8")
client.publish(topic=topic, msg=data)
if connected:
client.disconnect()
# Wait
utime.sleep(60)