diff options
-rwxr-xr-x | scripts/status_script.py | 184 |
1 files changed, 86 insertions, 98 deletions
diff --git a/scripts/status_script.py b/scripts/status_script.py index e57860b..5de27f6 100755 --- a/scripts/status_script.py +++ b/scripts/status_script.py @@ -1,128 +1,116 @@ #!/usr/bin/env python -import urllib -import contextlib +from urllib.request import urlopen import json import time -import os +import os.path +from os import rename from credentials import * from twitter import * from datetime import datetime -class SublabStatus(object): - json = None - def get_json(self): - if self.json is not None: - return self.json - try: - with contextlib.closing(urllib.urlopen('http://[2a02:238:f02a:9800:caa0:30ff:feb4:2185]/')) as response: - self.json = json.load(response) - return self.json - except IOError: - with contextlib.closing(urllib.urlopen('http://beaglebone.local.sublab.org/')) as response: - self.json = json.load(response) - return self.json - - def door_status(self): - try: - self.get_json() - except Exception: - return 'unkown' +SEPARATOR = ' - ' +DATE_MSG = 'Last change was on' - door_status = self.json['door.lock'] +STATES = ["closed", "open", "unknown"] +STATE_IMAGE = "status-{0}.png" +MESSAGES = ['OH NOEZ! sublab is now closed.' + SEPARATOR + DATE_MSG + ' ', + 'YAY! sublab is now open' + SEPARATOR + DATE_MSG + ' ', + "DAMN SON! Current status of @sublab couldn't be retrieved" + ' '] +STATE_MESSAGE = dict(zip(STATES, MESSAGES)) - if door_status['ts'] + 120 < time.time(): - return 'unknown' +STATEFILE = os.path.join('/', 'tmp', 'sublab-doorstatus.last') - if not door_status['value']: - return 'open' - else: - return 'closed' +CSS = ''' + #statusimage { + background: url(../img/{0}) ; + height: 40px; + width: 40px; + margin: 5px; + }''' -def tweet(status, last_change): - # Contents of the status tweet - # Max. 110 Characters, or tweet will be too long! - SEPARATOR = ' - ' - DATE_MSG = 'Last change was on' - SUBLAB_CLOSED = 'OH NOEZ! sublab is now closed.' + SEPARATOR + DATE_MSG + ' ' - SUBLAB_OPEN = 'YAY! sublab is now open' + SEPARATOR + DATE_MSG + ' ' - SUBLAB_UNKNOWN = "DAMN SON! Current status of @sublab couldn't be retrieved" + ' ' +class SublabStatus(object): - if status == 'open': - tweet = SUBLAB_OPEN + last_change - elif status == 'closed': - tweet = SUBLAB_CLOSED + last_change - elif status == 'unknown': - tweet = SUBLAB_UNKNOWN + def __init__(self): + self.json = None + self.door = None + self.state = STATES[2] + self.old_state = None + self.last_change = None - if len(tweet) <= 140: + # read file with last state + try: + with open(STATEFILE, 'r') as state_file: + self.old_state = state_file.readline().rstrip() + self.last_change = state_file.readline().rstrip() + except Exception: + self.save_statefile() + exit() - #instance of the twitter-class to post status changes - t = Twitter(auth=OAuth(token, - token_key, - con_secret, - con_secret_key)) + def update(self): + # read current state + try: + self.fetch_state() + except: + return + self.update_state() + self.save_statefile() + self.update_css() + self.tweet_state() - t.statuses.update(status=tweet) - else: - print "Message too long: " + tweet -def update_css(statusimage): - css = ''' -#statusimage { - background: url(../img/%s) ; - height: 40px; - width: 40px; - margin: 5px; -} + def update_state(self): + if self.door.get('ts') + 120 < time.time(): + return + if not self.door.get('value'): # lock == True => door is open, lock == False ==> door is closed + self.status = STATES[1] # open + else: + self.status = STATES[0] # closed -''' % statusimage - path = os.path.realpath(os.path.dirname(__file__)) - path = os.path.join(path, '..', 'public', 'css', 'sublab.status.css') - path_new = path + '.new' + def fetch_state(self): + if not self.json : + try: + with urlopen('http://192.168.2.214:9000') as response: + #with contextlib.closing(urllib.urlopen('http://[2a02:238:f02a:9800:caa0:30ff:feb4:2185]/')) as response: + self.json = json.loads(response.readall().decode('utf-8')) + except IOError: + with urlopen('http://beaglebone.local.sublab.org/') as response: + self.json = json.loads(response.readall().decode('utf-8')) + self.door = self.json.get('door.lock') - with open(path_new, 'w') as css_file: - css_file.write(css) - os.rename(path_new, path) + def save_statefile(self): + now = datetime.now().strftime("%c") + with open(STATEFILE, 'w') as state_file: + state_file.write(self.state + '\n' + now + '\n') -def save_statusfile(STATUSFILE, status): - date_now = datetime.now().strftime("%a %d. %b %Y at %H:%M") - with open(STATUSFILE, 'w') as status_file: - status_file.write(status + '\n' + date_now + '\n') + def update_css(self): + path = os.path.realpath(os.path.dirname(__file__)) + css_path = os.path.join(path, '..', 'public', 'css', 'sublab.status.css') + css_path_new = css_path + '.new' + with open(path_new, 'w') as css_file: + css_file.write(CSS.format(STATE_IMAGE(self.state))) + os.rename(css_path_new, path) -if __name__ == '__main__': - STATUSFILE = 'sublab-doorstatus.last' + def tweet_state(self): + tweet = STATE_MESSAGE[self.state] + self.last_change + if len(tweet) <= 140: + t = Twitter(auth=OAuth(token, + token_key, + con_secret, + con_secret_key)) + t.statuses.update(status=tweet) + else: + raise ValueError("Tweet too long: {0}".format(tweet)) - # instance of class which gets current status - s = SublabStatus() - # read file with last status - try: - with open(STATUSFILE, 'r') as status_file: - old_status = status_file.readline().rstrip() - last_change = status_file.readline().rstrip() - except Exception: - save_statusfile(STATUSFILE, s.door_status()) - exit() - - # check if status changed, if yes, update css and tweet it - if s.door_status() != old_status: - if s.door_status() == 'open': - update_css('status-open.png') - save_statusfile(STATUSFILE, s.door_status()) - tweet('open', last_change) - elif s.door_status() == 'closed': - save_statusfile(STATUSFILE, s.door_status()) - update_css('status-closed.png') - tweet('closed', last_change) - else: - save_statusfile(STATUSFILE, s.door_status()) - update_css('status-unknown.png') - tweet('unknown', last_change) +if __name__ == '__main__': + + s = SublabStatus() + s.update() |