Created
September 14, 2014 12:07
-
-
Save tjoskar/ce061987249866b64c39 to your computer and use it in GitHub Desktop.
Tellstick server
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os | |
import datetime | |
import pytz | |
from flask import Flask | |
from astral import Astral | |
app = Flask(__name__) | |
__TELLSTICK_PATH__ = '/usr/bin/tdtool' | |
__WINDOW_ID__ = ['1', '2', '3'] | |
__SOFT_LIGHTING__ = ['4', '5', '6'] | |
__ALL__ = __WINDOW_ID__ + __SOFT_LIGHTING__ | |
__CITY_NAME__ = 'Stockholm' | |
@app.route('/') | |
def index(): | |
return 'Start' | |
@app.route('/on/<lamp_id>', methods=['GET', 'POST']) | |
def on(lamp_id): | |
if turn_on_lamps(lamp_id.split(',')) == 0: | |
return 'success' | |
else: | |
return 'error' | |
@app.route('/on/<lamp_id>/sunset', methods=['GET', 'POST']) | |
def on_sunset(lamp_id): | |
if after_sunset(): | |
return on(lamp_id) | |
else: | |
return 'The sun is still up' | |
@app.route('/off/<lamp_id>', methods=['GET', 'POST']) | |
def off(lamp_id): | |
if turn_off_lamps(lamp_id.split(',')) == 0: | |
return 'success' | |
else: | |
return 'error' | |
@app.route('/window/<on_off>', methods=['GET', 'POST']) | |
def window(on_off): | |
command = create_command(__WINDOW_ID__, on_off) | |
if (on_off == 'on' or on_off == 'off') and execute_command(command) == 0: | |
return 'success' | |
else: | |
return 'error' | |
@app.route('/onsoft', methods=['GET', 'POST']) | |
def on_soft(): | |
if after_sunset(): | |
if execute_command(create_command(__SOFT_LIGHTING__, 'on')) == 0: | |
return 'success' | |
else: | |
return 'error' | |
return 'The sun is still up, no need for soft, indoor lighting' | |
@app.route('/alloff', methods=['GET', 'POST']) | |
def all_off(): | |
if turn_off_lamps(__ALL__) == 0: | |
return 'success' | |
else: | |
return 'error' | |
def after_sunset(): | |
astral = Astral() | |
astral.solar_depression = 'civil' | |
city = astral[__CITY_NAME__] | |
sunset = city.sun(date=datetime.datetime.now(), local=True)['sunset'] | |
now = datetime.datetime.now(pytz.timezone(city.timezone)) | |
return now > sunset | |
def turn_on_lamps(lamp_id): | |
return execute_command( | |
create_command(lamp_id, 'on') | |
) | |
def turn_off_lamps(lamp_id): | |
return execute_command( | |
create_command(lamp_id, 'off') | |
) | |
def execute_command(command): | |
return os.system(command) | |
def create_command(lamp_ids, command): | |
return __TELLSTICK_PATH__ + ' ' + ' '.join(map((lambda x: '--' + command + ' ' + x), lamp_ids)) | |
if __name__ == '__main__': | |
app.run(host='0.0.0.0', port=8000, debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment