Skip to content

Instantly share code, notes, and snippets.

@r41d
Last active April 6, 2017 16:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save r41d/65be2c7a111ac6c32f24d762ba38612c to your computer and use it in GitHub Desktop.
Save r41d/65be2c7a111ac6c32f24d762ba38612c to your computer and use it in GitHub Desktop.
Minimal flask Trådfri server
#!/usr/bin/env python
# -*- coding: utf-8 *-*
# TradPy, minimal working example for Trådfri web interface
# Copyright (C) 2017 Lennart Buhl
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
# Create a file tradconf.py with the content:
# GATEWAY_IP="192.168.XXX.YYY"
# GATEWAY_KEY="ZZZZZZZZZZZZZZ"
# Without this, nothing will work
from tradconf import *
import json
import subprocess
from flask import Flask
from flask import request
app = Flask(__name__)
def query(path='15001'):
coap = './libcoap/examples/coap-client -u Client_identity -k '+GATEWAY_KEY+' -v 0 -m get "coaps://'+GATEWAY_IP+':5684/'+path+'"'
out = subprocess.check_output(coap, shell=1)
return out.split("\n")[-2]
def send(path, lightdata):
data = json.dumps({"3311": [lightdata]})
coap = './libcoap/examples/coap-client -u Client_identity -k '+GATEWAY_KEY+' -v 0 -m put "coaps://'+GATEWAY_IP+':5684/'+path+'" -f -'
command = 'echo \'%s\' | %s' % (data, coap)
print command
out = subprocess.check_output(command, shell=1)
return out.split("\n")[-2]
@app.route("/")
def hello():
if len(request.args.keys()) == 1:
#print app.logger.info(request.args[0])
bulb, value = list(request.args.iterlists())[0]
print bulb
print value
send("15001/%s" % bulb, {"5851": int(value[0])})
out = "<html><body>"
devs = json.loads(query('15001'))
for devID in devs:
dev = json.loads(query("15001/%d"%devID))
if not 'bulb' in dev['3']['1']: continue
out += '%d: %s (%s) <form><input type="number" name="%d"><input type="submit" value="SEND!"/></form><br/>\n' % (devID, dev['9001'], dev['3']['1'], devID)
out += "</body></html>"
return out
if __name__ == "__main__":
app.debug = True
app.run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment