-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsensor_api.py
More file actions
72 lines (55 loc) · 2.02 KB
/
sensor_api.py
File metadata and controls
72 lines (55 loc) · 2.02 KB
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
import os
import bme280
from flask import Flask, jsonify
from dotenv import load_dotenv
from paho.mqtt import publish as mqtt_publish
load_dotenv()
app = Flask(__name__)
app.json.sort_keys = False
MQTT_BROKER_HOST = os.environ.get('MQTT_BROKER_HOST', 'localhost')
MQTT_USERNAME = os.environ.get('MQTT_USERNAME', '')
MQTT_PASSWORD = os.environ.get('MQTT_PASSWORD', '')
MQTT_CLIENT_ID = os.environ.get('MQTT_CLIENT_ID', 'rpi-bme280')
TEMPERATURE_TOPIC = 'sensor/bme280_temperature'
HUMIDITY_TOPIC = 'sensor/bme280_humidity'
PRESSURE_TOPIC = 'sensor/bme280_pressure'
@app.route('/health')
def health():
return jsonify({'status': 'ok'})
@app.route('/')
def index():
return jsonify({})
@app.route('/bme280')
def bme280_action():
try:
return jsonify(bme280.sensor())
except OSError as e:
return jsonify({'error': 'Sensor unavailable', 'detail': str(e)}), 503
@app.route('/bme280/publish')
def bme280_publish_action():
try:
data = bme280.sensor()
except OSError as e:
return jsonify({'error': 'Sensor unavailable', 'detail': str(e)}), 503
auth = {'username': MQTT_USERNAME, 'password': MQTT_PASSWORD} if MQTT_USERNAME else None
try:
mqtt_publish.multiple(
[
{'topic': TEMPERATURE_TOPIC, 'payload': str(data['data']['temperature'])},
{'topic': HUMIDITY_TOPIC, 'payload': str(data['data']['humidity'])},
{'topic': PRESSURE_TOPIC, 'payload': str(data['data']['pressure'])},
],
hostname=MQTT_BROKER_HOST,
auth=auth,
client_id=MQTT_CLIENT_ID,
)
except Exception as e:
return jsonify({'error': 'MQTT publish failed', 'detail': str(e)}), 502
return jsonify({
'published': True,
'topics': [TEMPERATURE_TOPIC, HUMIDITY_TOPIC, PRESSURE_TOPIC],
})
if __name__ == '__main__':
port = int(os.environ.get('FLASK_PORT', '5000'))
debug = os.environ.get('FLASK_DEBUG', 'false').lower() == 'true'
app.run(host='0.0.0.0', port=port, debug=debug)