55 lines
1.3 KiB
Python
55 lines
1.3 KiB
Python
'''
|
|
HTTP API to trigger unlock through MQTT
|
|
'''
|
|
|
|
import time
|
|
import configparser
|
|
from bottle import Bottle, get, request, run
|
|
import paho.mqtt.client as mqtt
|
|
|
|
config = configparser.ConfigParser()
|
|
|
|
try:
|
|
config.read_file(open('../doorcontrol.ini'))
|
|
except FileNotFoundError:
|
|
print("Can't find config file. \n\n")
|
|
raise
|
|
|
|
|
|
try:
|
|
mqttc = mqtt.Client(client_id="", clean_session=True, userdata=None, transport="tcp")
|
|
mqttc.username_pw_set(config['mqtt']['User'], password=config['mqtt']['Password'])
|
|
|
|
mqttc.connect(config['mqtt']['Server'], int(config['mqtt']['Port']))
|
|
except:
|
|
print("Error connecting to mqtt broker, check configuration.\n\n")
|
|
raise
|
|
|
|
mqttc.loop_start()
|
|
|
|
app = application = Bottle()
|
|
|
|
@app.route('/unlock')
|
|
def unlock():
|
|
deviceID = request.query.get('deviceID')
|
|
apiKey = request.query.get('apiKey')
|
|
delay = request.query.get('delay')
|
|
|
|
if apiKey == config['api']['key']:
|
|
try:
|
|
if int(delay) > 0:
|
|
time.sleep(int(delay))
|
|
except:
|
|
pass
|
|
result = mqttc.publish("devices/main-door/unlock/unlock/set", "true")
|
|
result.wait_for_publish()
|
|
return '{"message": "Unlocked"}'
|
|
return '{"message": "Unauthorized!"}'
|
|
|
|
if __name__ == '__main__':
|
|
run(
|
|
app=app,
|
|
host='localhost',
|
|
port=8000)
|
|
|