/
lunch-schedule.py
69 lines (52 loc) · 2.31 KB
/
lunch-schedule.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
## Fetch the IDX Lunch Menu and put it into a sensor
import appdaemon.plugins.hass.hassapi as hass
import re, datetime, json, requests
class Lunch(hass.Hass):
def initialize(self):
time = datetime.time(0, 0, 0)
self.run_daily(self.lunchState, time)
self.lunchState(time)
self.log("Lunch sensor initialized.")
def lunchState(self, kwargs):
# get the menu as a list
lunchList = self.fetchMenu().get("data")
# Turn it from a list of dictionaries into a single, useful, dictionary
lunchDict = self.formatMenu(lunchList)
# set the home assistant sensor
self.setSensor(lunchDict)
def fetchMenu(self):
# @TODO handle get errors
# @TODO handle unexpected data from api
r = requests.get(self.get_state("input_text.appdaemon_lunch_api_endpoint"))
lunchJson = r.json()
return lunchJson
def formatMenu(self, menuJson):
menuDict = {}
for dayInfo in menuJson:
for lunchDateString, item in dayInfo.items():
lunchDate = datetime.datetime.strptime(lunchDateString, "%m-%d-%y").date()
menuDict[lunchDate.strftime("%Y%m%d")] = {
"item": item,
"dateObj": lunchDate
}
return menuDict
def setSensor(self, lunchDict):
today = datetime.date.today()
sensorState = "none"
nextThree = []
nextCount = 0
for dateString, lunchInfo in lunchDict.items():
if lunchInfo["dateObj"] == today:
sensorState = self.stripEmoji(lunchInfo["item"])
if lunchInfo["dateObj"] >= today and nextCount < 3:
nextThree.append(lunchInfo["dateObj"].strftime("%A, %m/%d") + ": "+self.stripEmoji(lunchInfo["item"]))
nextCount+=1
lastUpdated = datetime.datetime.now()
lastUpdated = lastUpdated.strftime("%Y-%m-%d %H:%M:%S")
self.set_state("sensor.janet_api_idx_lunch", state = sensorState, attributes = {
"nextThree": nextThree,
"lastUpdated": lastUpdated
})
def stripEmoji(self, itemString):
emoji_pattern = re.compile("[\U00010000-\U0010ffff]+", flags=re.UNICODE)
return emoji_pattern.sub(r'', itemString)