#!/usr/bin/env python from urllib.request import urlopen import json import time import os.path from os import rename from credentials import * from twitter import * from datetime import datetime SEPARATOR = ' - ' DATE_MSG = 'Last change was on' 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)) STATEFILE = os.path.join('/', 'tmp', 'sublab-doorstatus.last') CSS = ''' #statusimage { background: url(../img/{0}) ; height: 40px; width: 40px; margin: 5px; }''' class SublabStatus(object): def __init__(self): self.json = None self.door = None self.state = STATES[2] self.old_state = None self.last_change = None # 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() def update(self): # read current state try: self.fetch_state() except: return self.update_state() self.save_statefile() self.update_css() self.tweet_state() 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 def fetch_state(self): if not self.json : try: with 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') 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 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) 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)) if __name__ == '__main__': s = SublabStatus() s.update()