def get_daytime(self): import config if config.now().hour < 12: return self.morning if config.now().hour > 17: return self.evening return []
def __call__(self, now=config.now(), previous=None): '''Returns the next time that this should occur.''' if previous: next = previous + self.interval if next > now: return next return now
def __init__(self, test=None): self.start_time = config.now() if config.NAME == "KLBFAX": points.add_one_random(printing=True) if not os.path.isdir(config.config_dir): os.mkdir(config.config_dir) self.test = test
def __call__(self, now=config.now(), previous=None): if isinstance(self.offset, numbers.Number): offset = self.offset else: offset = self.offset() delta = datetime.timedelta(minutes=offset) next = self.wrapped(now=now - delta, previous=previous) return next + delta
def schedule(self, when, action): '''schedule causes action to be performed according to the specified when.''' self.scheduler.enterabs(schedTime(when), 0, action) _log_scheduler_message(scheduler_operation='EVENT_SCHEDULED', sender=self, timestamp=config.now(), when=when, action=action)
def __call__(self, now=config.now(), previous=None): '''Returns the next time that this should occur.''' if previous: assert previous <= now at = datetime.datetime(now.year, now.month, now.day, self.hour, self.minute, now.second, 0, now.tzinfo) if at > now: return at return at + self.__class__.delta
def sendCommand(self, command): assert isinstance(command, bytearray) # dispatch results are ignored. dispatcher.send(signal='MODEM_COMMAND', sender=self, timestamp=config.now(), bytes=command) if debug: print("sending command %s" % hexdump(command)) self.serial.write(command)
def handle_input(self, the_input): if the_input == "pub": return self.build(special.PubPage) if the_input == "strike": return self.build(special.StrikePage) if the_input == "lunch": return self.build(special.LunchPage) if the_input == "1337" or the_input == "0026360488" or the_input == "0082620488": import computer computer.git_pull() if the_input == "00488a0488": import computer computer.reboot() if the_input == "....": import computer computer.kill_ceefax() if len(the_input)>6: from page.special import NamePage namefile_path = "/home/pi/cards/" + the_input extra = "" from functions import greetings if os.path.isfile(namefile_path): _name, house, twitter = points.get_name_house(namefile_path) else: _name, house, twitter = None,None,None if _name is not None: if house is None: extra = "Error finding your house. Please report to Scroggs." if twitter is not None: deets = greetings.random_twitter() + " @"+twitter+"!" elif _name is not None: deets = greetings.random_twitter() + " " + _name else: deets = "" time = config.now().strftime("%H") name_file = points.read_name_file(namefile_path) if points.should_add_morning_points(time, house, name_file, the_input): points_added = points.add_morning_points(time, house, the_input, deets) extra = str(points_added) + " points to " + house + "!" if points_added < 0: extra += "\nIt's the weekend, go home!" name_page = self.build(NamePage, _name, extra=extra) else: name_page = self.build(NamePage, the_input, large=False) return name_page try: while len(the_input)<3: the_input = "0"+str(the_input) return self.pages[the_input] except KeyError: return self.build(FailPage,"Page "+the_input+" does not exist. Try the index in page 100.",False)
def background(self): import json import config from dateutil import parser self.events = url_handler.load_json( "http://www.mscroggs.co.uk/room_list.json") now = config.now().replace(tzinfo=None) for e in self.events: e[0] = parser.parse(e[0]) e[1] = parser.parse(e[1]) self.events = [e for e in self.events if e[1] > now]
def generate_content(self): self.add_title("Lunchtime!", fg="RED", bg="BLACK") if config.now().strftime("%a") == "Fri": self.add_newline() self.add_title("It's Fancy Friday!", bg="RED", fg="BLACK") self.add_newline() self.add_text("Press 7 to pick a restaurant!") self.add_newline() self.add_text("Press 8 to pick a restaurant if you are Olly!") self.add_newline() self.add_title("HUDA HUNGRY", fg="RED", bg="BLACK")
def schedule_row(event): return SCHEDULE_ROW_TEMPLATE.format( **{ 'NEXT_TIME': html.escape(event.when.strftime(WEB_TIME_FORMAT)) if event. when else '', 'ACTION': html.escape("%r" % event.action_function), 'DESCRIPTION': html.escape(describe_event(event)), 'OVERDUE': 'overdue' if event.when < now() else '' })
def __call__(self, now=config.now(), previous=None): '''A NextTimeFunction is called to compute the next time that it's associated Event should be scheduled for. Returns a datetime.Datetime if the associated event is to be rescheduled. now is a function to return the current time. previous is a datetime.Datetime of the most recent firing of the associated Event so that the next firing can be scheduled relative to it if necessary. ''' pass
def doAction(self): _log_scheduler_message(scheduler_operation='EVENT_ACTION', sender=self, timestamp=config.now()) now_ = config.now() success = False try: self.action_function() self.schedule(previous=self.when) success = True except Exception as e: # TODO Include the error in the log. _log_scheduler_message( scheduler_operation='SCHEDULED_ACTION_FAILED', sender=self, timestamp=now_, when=self.when, action=self) if success: _log_scheduler_message(scheduler_operation='SCHEDULED_ACTION_DONE', sender=self, timestamp=now_, when=self.when, action=self)
def readResponse(self): msg = bytearray() while True: b = self.serial.read(1) if not b: break msg.append(ord(b)) if debug: print("receiving response %s" % hexdump(msg)) if len(msg) > 0: # dispatch results are ignored. dispatcher.send(signal='MODEM_RESPONSE', sender=self, timestamp=config.now(), bytes=msg) return msg
def process_message_from_me(self, msg): assert isinstance(msg, Translator) pattern1 = StandardMessageReceived(StartByte(), StandardMessageReceivedCode(), FromAddress(self.address), MatchVariable("to_address"), MatchVariable("message_flags"), MatchVariable("cmd1"), MatchVariable("cmd2")) m = match(msg, pattern1) if m == False: return self.received_timestamp = config.now() self.cmd1 = m["cmd1"] self.cmd2 = m["cmd2"]
def schedule(self, previous=None): # It is expected that the next_time_function will not return a time # in the past. now_ = config.now() next = self.next_time_function(now=now_, previous=previous) if next: if next < now_: _log_scheduler_message( scheduler_operation='SCHEDULED_NEXT_BEFORE_NOW', # action would be the same as sender in this case. action=self.action_function, sender=self, timestamp=now_, when=next) else: self.when = next Scheduler().schedule(next, self)
def main_loop(self): from time import sleep import sys import select inp = "100" while True: self.clear_input() if inp is not None: page = self.handle_input(inp) elif config.now().strftime("%Y-%m-%d") in ["2018-02-22","2018-02-23","2018-02-26","2018-02-27","2018-02-28","2018-03-05", "2018-03-06","2018-03-07","2018-03-08","2018-03-12","2018-03-13","2018-03-14", "2018-03-15","2018-03-16"]: page = self.build(special.StrikePage) elif config.now().strftime("%H") == "12" and config.now().minute < 20: page = self.build(special.LunchPage) elif config.now().strftime("%H:%M") == "13:37": page = self.build(special.LeetPage) page.cupt = self.screen.cupt elif config.now().strftime("%a%H") == "Fri17" and config.now().minute < 20: page = self.build(special.PubPage) else: page = self.get_loaded_random() self.show(page) signal.signal(signal.SIGALRM, alarm) signal.alarm(30) try: key = None inp = "" while key != curses.KEY_ENTER and key != 10: key = self.screen.getch() try: if key==263: inp = inp[:-1] else: inp += get_chr(key) self.show_input(inp) except ValueError: pass signal.alarm(0) signal.signal(signal.SIGALRM, pass_f) except TimeUp: inp = None
def main_page(): def group_device(device): return '{ADDRESS} {LOCATION} <br />'.format( **{ 'ADDRESS': html.escape(device.address.address_string()), 'LOCATION': html.escape(device.location) }) def lg_row(link_group): return LINK_GROUP_ROW_TEMPLATE.format( **{ 'GROUP_DEVICE_COUNT': str(len(link_group.devices)), 'GROUP_NUMBER': str(link_group.link_group.byte), 'DEVICE_ROWS': '\n'.join([group_device(d) for d in link_group.devices]) }) def device_row(device): da = device.address if device.cmd1 == OnCmd(): on_off_icon = 'web_resources/on.svg' on_off_text = ("On as of %s" % device.received_timestamp.strftime(WEB_TIME_FORMAT)) elif device.cmd1 == OffCmd(): on_off_icon = 'web_resources/off.svg' on_off_text = ("Off as of %s" % device.received_timestamp.strftime(WEB_TIME_FORMAT)) else: on_off_icon = 'web_resources/unknown_status.svg' on_off_text = "Unknown status" return INSTEON_DEVICE_ROW_TEMPLATE.format( **{ 'ADDRESS': html.escape(device.address.address_string()), 'CATEGORY': device.category or '', 'SUBCATEGORY': device.subcategory or '', 'FIRMWARE_VERSION': device.firmware_version or '', 'LOCATION': html.escape(device.location) or '', 'ON_OFF_ICON': on_off_icon, 'ON_OFF_TEXT': on_off_text }) def schedule_row(event): return SCHEDULE_ROW_TEMPLATE.format( **{ 'NEXT_TIME': html.escape(event.when.strftime(WEB_TIME_FORMAT)) if event. when else '', 'ACTION': html.escape("%r" % event.action_function), 'DESCRIPTION': html.escape(describe_event(event)), 'OVERDUE': 'overdue' if event.when < now() else '' }) return DEFAULT_PAGE_TEMPLATE.format( **{ 'TIME': now().strftime(WEB_TIME_FORMAT), 'LINK_GROUP_ROWS': '\n'.join( [lg_row(g) for g in modem.InsteonLinkGroup.groups.values()]), 'DEVICE_ROWS': '\n'.join( [device_row(d) for d in modem.InsteonDevice.devices.values()]), 'SCHEDULE_ROWS': '\n'.join([schedule_row(e) for e in Scheduler().queued_events()]) })
def __call__(self): _log_scheduler_message(scheduler_operation='SCHEDULER_STARTED', sender=self, timestamp=config.now()) self.scheduler.run(True)
def schedTime(t=None): if t == None: t = config.now() return (t - TIME_ZERO).total_seconds()
def generate_content(self, debug=False): from file_handler import load_file clock = load_file("clock.txt").split("\n") clock = [[j == "X" for j in i] for i in clock] minute = [[False] * len(i) for i in clock] hour = [[False] * len(i) for i in clock] current_minute = float(now().strftime("%M")) current_hour = float(now().strftime("%I")) current_weekday = now().strftime("%a") if current_weekday == "Mon": bgcolor = "LIGHTRED" if current_weekday == "Tue": bgcolor = "YELLOW" if current_weekday == "Wed": bgcolor = "LIGHTCYAN" if current_weekday == "Thu": bgcolor = "LIGHTGREEN" if current_weekday == "Fri": bgcolor = "PINK" if current_weekday == "Sat": bgcolor = "LIGHTBLUE" if current_weekday == "Sun": bgcolor = "RED" self.add_title(now().strftime("%A %-d %b"), bg=bgcolor, fg="BLACK") circle_radius = 19 screen_radius = 19 d = .3 num_points = 25 current_hourtopointat = current_hour + current_minute / 60. for a in range(0, num_points + 1): r = circle_radius * a * .5 / num_points hx = r * cos(pi / 2 - current_hourtopointat * 2 * pi / 12) hy = r * sin(pi / 2 - current_hourtopointat * 2 * pi / 12) for dx in [-d, d]: for dy in [-d, d]: hour_x = screen_radius + int(floor(hx + .5 + dx)) hour_y = screen_radius - int(floor(hy + .5 + dy)) hour[hour_y][hour_x] = True r = circle_radius * a * .8 / num_points mx = r * cos(pi / 2 - current_minute * 2 * pi / 60) my = r * sin(pi / 2 - current_minute * 2 * pi / 60) for dx in [-d, d]: for dy in [-d, d]: minute_x = screen_radius + int(floor(mx + .5 + dx)) minute_y = screen_radius - int(floor(my + .5 + dy)) minute[minute_y][minute_x] = True output = "" for y in range(0, 2 * screen_radius + 1): for x in range(0, 2 * screen_radius + 1): if clock[y][x] or minute[y][x] or hour[y][x]: output += "X" else: output += " " output = output + " " * (2 * screen_radius + 1) output2 = "" for y in range(0, 2 * screen_radius + 1, 2): output2 = output2 + " " * (screen_radius + 1) for x in range(0, 2 * screen_radius + 1): letter0 = output[y * (2 * screen_radius + 1) + x] letter1 = output[(y + 1) * (2 * screen_radius + 1) + x] if letter0 == " " and letter1 == " ": output2 = output2 + " " elif letter0 == "X" and letter1 == "X": output2 = output2 + u"\u2588" elif letter0 == "X" and letter1 == " ": output2 = output2 + u"\u2580" else: output2 = output2 + u"\u2584" if y != 2 * screen_radius: output2 = output2 + "\n" self.add_text(output2)
def generate_content(self): from functions import klb_replace import config from time import strftime def friendly_date(date): if date.date() == datetime.today().date(): return "Today" elif date.date() == datetime.today().date() + timedelta(days=1): return "Tomorrow" else: return date.strftime("%A %-d") self.add_title("Muirhead Room") self.add_newline() now = config.now().replace(tzinfo=None) occupied = False for event in self.events: if event[0] < now and event[1] > now: occupied = True if occupied: self.start_fg_color("WHITE") self.start_bg_color("RED") next_free = 0 i = 0 while next_free == 0: if self.events[i + 1][0] != self.events[i][1]: next_free = self.events[i][1] i += 1 message = "Busy until " + next_free.strftime("%H:%M") else: try: next_occupied = self.events[0][0] except: next_occupied = datetime.today() + timedelta(days=300) if next_occupied.date() != now.date(): message = "Free all day" else: message = "Free until " + next_occupied.strftime("%H:%M") if next_occupied.date() - now.date() <= timedelta(hours=1): self.start_fg_color("BLACK") self.start_bg_color("YELLOW") else: self.start_fg_color("BLACK") self.start_bg_color("GREEN") left_banner = " " * int((config.WIDTH - len(message)) / 2) right_banner = " " * int(round((config.WIDTH - len(message)) / 2)) self.add_text(left_banner + message + right_banner) self.end_fg_color() self.end_bg_color() self.add_newline() previous_date = datetime(2015, 3, 14).date() for event in self.events: start_time = event[0] end_time = event[1] _name = event[2] if end_time.date() != previous_date: self.add_newline() self.start_fg_color("GREEN") self.add_text(friendly_date(end_time)) self.end_fg_color() self.add_newline() self.start_fg_color("RED") self.add_text( start_time.strftime("%H:%M") + "-" + end_time.strftime("%H:%M") + " ") self.end_fg_color() self.add_text(klb_replace(_name)) self.add_newline() previous_date = end_time.date()
def info(message): '''Add message to the log.''' logging.getLogger(__name__).info( '%s: %s' % (config.now().strftime(config.TIME_FORMAT), message))
def __call__(self, now=config.now(), previous=None): '''Returns the next time that this should occur.''' at = self.calc(now) if at > now: return at return self.calc(now + datetime.timedelta(days=1))
def add_work(conn, type, path, remote_id = '', remote_parent_id = '', priority = 1, postwork = 'n'): conn.execute('INSERT INTO tasks ' '(task_type, local_path, remote_id, remote_parent_id, priority, date_created, postwork) VALUES ' '(?, ?, ?, ?, ?, ?, ?)', (type, path, remote_id, remote_parent_id, priority, config.time_to_str(config.now()), postwork)) conn.commit()
def show_page_number(self, n): txt = n + " " + config.NAME + " " + config.now().strftime( "%a %d %b %H:%M") pad = curses.newpad(1, len(txt) + 1) pad.addstr(0, 0, txt, csty()) pad.refresh(0, 0, 0, self.WIDTH - len(txt) - 1, 0, self.WIDTH)
def now(self): return config.now()
def add_notify(conn, side, path, action): path = path.replace(config.APP_CONFIG['base_path'], '', 1) conn.execute('INSERT INTO notifications ' '(side, display_path, action, time) VALUES ' '(?, ?, ?, ?)', (side, path, action, config.time_to_str(config.now())))