forked from robmarkcole/bme680-mqtt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bme680-mqtt.py
executable file
·242 lines (190 loc) · 8.74 KB
/
bme680-mqtt.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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# see https://github.com/robmarkcole/bme680-mqtt
# requirements: pip install bme680 smbus paho-mqtt
import bme680
import time
import json
import socket
import os
import sys
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
import yaml
print("""Estimate indoor air quality
Runs the sensor for a burn-in period, then uses a
combination of relative humidity and gas resistance
to estimate indoor air quality as a percentage.
Press Ctrl+C to exit
""")
# location is set at command invocation.
__location__ = os.path.dirname(os.path.abspath(sys.argv[0]))
config_location=os.path.join(__location__,'../etc/bme680-mqtt/bme680.yaml')
### MQTT
with open(config_location) as stream:
mqtt_config = yaml.safe_load(stream)
broker = mqtt_config['broker_server']
sensor_name = mqtt_config['sensor_name']
mqtt_username = mqtt_config['mqtt_user']
mqtt_password= mqtt_config['mqtt_pass']
ha_state_prefix = "homeassistant/sensor/"+sensor_name+"/"+sensor_name
ha_sensor_prefix ="homeassistant/sensor/"+sensor_name+"/"+sensor_name
#set MQTT LWT
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.publish(sensor_name+"/tele/LWT","Online",qos=0,retain=True)
#get local_IP
def get_ip():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
IP = s.getsockname()[0]
except Exception:
IP = '127.0.0.1'
finally:
s.close()
return IP
client = mqtt.Client(sensor_name)
client.username_pw_set(username=mqtt_username,password=mqtt_password)
client.on_connect = on_connect
client.will_set(sensor_name+"/tele/LWT","Offline",qos=0,retain=True)
client.connect(broker)
client.loop_start()
### bme680
sensor = bme680.BME680()
# These oversampling settings can be tweaked to
# change the balance between accuracy and noise in the data.
# BME680 temperature is often higher than normal. Offset it accordingly
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)
sensor.set_gas_status(bme680.ENABLE_GAS_MEAS)
sensor.set_gas_heater_temperature(320)
sensor.set_gas_heater_duration(150)
sensor.select_gas_heater_profile(0)
sensor.set_temp_offset(-6)
# start_time and curr_time ensure that the
# burn_in_time (in seconds) is kept track of.
start_time = time.time()
curr_time = time.time()
burn_in_time = 1 # burn_in_time (in seconds) is kept track of.
burn_in_data = []
try:
# Collect gas resistance burn-in values, then use the average
# of the last 50 values to set the upper limit for calculating
# gas_baseline.
while curr_time - start_time < burn_in_time:
curr_time = time.time()
if sensor.get_sensor_data() and sensor.data.heat_stable:
gas = sensor.data.gas_resistance
burn_in_data.append(gas)
time.sleep(1)
gas_baseline = sum(burn_in_data[-50:]) / 50.0
# Set the humidity baseline to 40%, an optimal indoor humidity.
hum_baseline = 40.0
# This sets the balance between humidity and gas reading in the
# calculation of air_quality_score (25:75, humidity:gas)
hum_weighting = 0.25
while True:
if sensor.get_sensor_data() and sensor.data.heat_stable:
gas = sensor.data.gas_resistance
gas_offset = gas_baseline - gas
hum = sensor.data.humidity
hum_offset = hum - hum_baseline
# Calculate hum_score as the distance from the hum_baseline.
if hum_offset > 0:
hum_score = (100 - hum_baseline - hum_offset) / (100 - hum_baseline) * (hum_weighting * 100)
else:
hum_score = (hum_baseline + hum_offset) / hum_baseline * (hum_weighting * 100)
# Calculate gas_score as the distance from the gas_baseline.
if gas_offset > 0:
gas_score = (gas / gas_baseline) * (100 - (hum_weighting * 100))
else:
gas_score = 100 - (hum_weighting * 100)
# Calculate air_quality_score.
air_quality_score = hum_score + gas_score
humidity = str(round(hum, 2))
temperature = str(round(sensor.data.temperature, 2))
pressure = str(round(sensor.data.pressure, 2))
air_qual = str(round(air_quality_score, 2))
## get some local info
local_hostname = socket.gethostname()
local_ip = get_ip()
##HASS autodiscovery
device_class= { "name": sensor_name+" status",
"stat_t": sensor_name+"/tele/HASS_STATE",
"json_attr_t": sensor_name+"/tele/HASS_STATE",
"avty_t": sensor_name+"/tele/LWT",
"pl_avail": "Online",
"pl_not_avail": "Offline",
"unit_of_meas":"%",
"val_tpl": "{{value_json['RSSI']}}",
"uniq_id": sensor_name+"_status",
"dev": {"ids": [sensor_name],
"name": sensor_name,
"mdl": "bme680",
"sw": "bme680",
"mf": "Pimoroni"
}
}
client.publish(ha_state_prefix+'_status'+'/config', json.dumps(device_class))
air_qual_class= { "name": sensor_name+" Air Quality",
"stat_t": sensor_name+"/tele/SENSOR",
"uniq_id": sensor_name+"_air_qual",
"dev": {"ids": [sensor_name],
},
"unit_of_meas": "%",
"dev_cla": "pressure",
"val_tpl": "{{ value_json.airqual}}"
}
client.publish(ha_sensor_prefix+'_air_qual'+'/config', json.dumps(air_qual_class))
humidity_class= { "name": sensor_name+" humidity",
"stat_t": sensor_name+"/tele/SENSOR",
"uniq_id": sensor_name+"_humidity",
"dev": {"ids": [sensor_name],
},
"unit_of_meas": "%",
"dev_cla": "humidity",
"val_tpl": "{{ value_json.humidity}}"
}
client.publish(ha_sensor_prefix+'_humidity'+'/config', json.dumps(humidity_class))
temperature_class= { "name": sensor_name+" temperature",
"stat_t": sensor_name+"/tele/SENSOR",
"uniq_id": sensor_name+"_temperature",
"dev": {"ids": [sensor_name],
},
"unit_of_meas": "°C",
"dev_cla": "temperature",
"val_tpl": "{{ value_json.temperature}}"
}
client.publish(ha_sensor_prefix+'_temperature'+'/config', json.dumps(temperature_class))
pressure_class= { "name": sensor_name+" pressure",
"stat_t": sensor_name+"/tele/SENSOR",
"uniq_id": sensor_name+"_pressure",
"dev": {"ids": [sensor_name],
},
"unit_of_meas": "mbar",
"dev_cla": "pressure",
"val_tpl": "{{ value_json.pressure}}"
}
client.publish(ha_sensor_prefix+'_pressure'+'/config', json.dumps(pressure_class))
ip_class = { "name": sensor_name+" IP",
"stat_t": sensor_name+"/tele/HASS_STATE",
"uniq_id": sensor_name+"_ip",
"dev": {"ids": [sensor_name],
},
"val_tpl": "{{ value_json.IPAddress}}",
"ic":"mdi:ip-network"
}
client.publish(ha_sensor_prefix+'_ip'+'/config', json.dumps(ip_class))
#local machine info
hass_status = { "Hostname": local_hostname, "IPAddress": local_ip, "RSSI": "74",}
client.publish(sensor_name+"/tele/HASS_STATE", json.dumps(hass_status))
#standard MQTT Sensor states
all_sensor_state= { "airqual": air_qual, "humidity": humidity, "temperature": temperature, "pressure": pressure }
client.publish(sensor_name+"/tele/SENSOR", json.dumps(all_sensor_state))
time.sleep(60)
except KeyboardInterrupt:
pass