Skip to content

Commit

Permalink
* Added integration for Matilda/webmenu.foodit.se * Deprecated "forma…
Browse files Browse the repository at this point in the history
…t" config parameter * Simplified url's for data sources
  • Loading branch information
Kaptensanders committed Aug 29, 2022
1 parent c40e4e1 commit ec68c95
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 54 deletions.
19 changes: 13 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
Skolmat custom component for the food menu in Swedish schools

## Description
This component is only valid in Sweden. It leverages data from skolmaten.se, IST AB, Andreas Egerup, to create a sensor entity from a configured rss feed.
This component is only valid in Sweden. It leverages data from skolmaten.se or Matilda/webmenu.foodit.se to create a sensor entity from a configured rss feed.
The sensor state will be todays available course(es) and the attributes will contain the full menu for the next two weeks.

You can use the sensor as you please or install the lovelace custom card to display the menu for today or for the week (https://github.com/Kaptensanders/skolmat-card)
Expand All @@ -23,8 +23,15 @@ sensor:
5. Your sensor entity will show up as skolmat.[school name]
3. Optionally, also with HACS, install the corresponding lovelace card: skolmat-card
### Find the rss feed
1. Go to https://skolmaten.se/ and follow the links to find your school.
2. When you arrive at the page where you can see the menu, click the RSS link at the end and choose the link for the current **week**.
Like: `https://skolmaten.se/skutehagens-skolan/rss/weeks` (shold end with `/rss/weeks`)

## Find the rss feed
### skolmaten.se ###
1. Open https://skolmaten.se/ and follow the links to find your school.
2. When you arrive at the page with this weeks menu, copy the url
Like: `https://skolmaten.se/skutehagens-skolan/`

### Matilda/webmenu.foodit.se / ###
1. Open https://webmenu.foodit.se/ and follow the links to find your school.
2. When you arrive at the page with this weeks menu, copy the url
Like: https://webmenu.foodit.se/?r=6&m=617&p=883&c=10023&w=0&v=Week&l=undefined

2 changes: 1 addition & 1 deletion custom_components/skolmat/manifest.json
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"version": "1.1.1",
"version": "1.2.0",
"domain": "skolmat",
"name": "Skolmat",
"issue_tracker": "https://github.com/Kaptensanders/skolmat/issues",
Expand Down
64 changes: 17 additions & 47 deletions custom_components/skolmat/sensor.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
Avanza Personal - Anders Sandberg
"""

import feedparser, voluptuous as vol, json
import feedparser, voluptuous as vol
from .menu import Menu
from datetime import datetime
from logging import getLogger

Expand All @@ -16,11 +17,8 @@

PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
{
vol.Required("name"): cv.string,
vol.Required("rss"): cv.string,
# first, second, both - formats the state from the available course alternatives (normal/veg)
# courses will be separated with "|"
vol.Optional("format", default = "first"): cv.string
vol.Required("name"): cv.string,
vol.Required("rss"): cv.string
}
)

Expand All @@ -32,19 +30,17 @@ async def async_setup_platform(hass, conf, async_add_entities, discovery_info=No
class SkolmenySensor(Entity):
def __init__(self, hass, conf):
super().__init__()
self.hass = hass # will be set again by homeassistant after added to hass
self._rss = conf.get("rss")
self._weeks = 2
self.hass = hass # will be set again by homeassistant after added to hass
self._name = conf.get("name")
self._stateFormat = conf.get("format")
self._last_menu_fetch = None
self._state = None
self._state_attributes = {}
self.entity_id = generate_entity_id (
entity_id_format = AP_ENTITY_DOMAIN + '.{}',
name = self._name,
hass = hass
)

self.menu = Menu(rss = conf.get("rss"))

@property
def name(self):
Expand All @@ -70,54 +66,28 @@ def force_update(self) -> bool:
return False
@property
def should_poll(self) -> bool:
if isinstance(self._last_menu_fetch, datetime):
return self._last_menu_fetch.date() != datetime.now().date()
if isinstance(self.menu.last_menu_fetch, datetime):
return self.menu.last_menu_fetch.date() != datetime.now().date()
return True

async def async_update(self):
await self.hass.async_add_executor_job(self.loadMenu)

# does io, call in separate
def loadMenu(self):
global last_load_date

try:
menu = feedparser.parse(f"{self._rss}?limit={self._weeks}")
calendar = {}
today = datetime.now().date()
menuToday = None
for day in menu["entries"]:

weekday = day['title'].split()[0]
date = datetime(day['published_parsed'][0], day['published_parsed'][1], day['published_parsed'][2]).date()
week = date.isocalendar().week
if not week in calendar:
calendar[week] = []
dayEntry = {
"weekday": weekday,
"date" : date.isoformat(),
"week": week,
"courses": day['summary'].split('<br />')
}
calendar[week].append(dayEntry)
if date == today:
if self._stateFormat == "first":
menuToday = dayEntry["courses"][0]
elif self._stateFormat == "second":
menuToday = dayEntry["courses"][1] if len(dayEntry["courses"]) > 1 else dayEntry["courses"][0]
else: #"both"
menuToday = "\n".join(dayEntry["courses"])

if menuToday is None:
self._state = "Ingen mat"
else:
self._state = menuToday
self.menu.loadMenu()

if self.menu.menuToday is None:
self._state = "Ingen mat"
else:
self._state = "\n".join(self.menu.menuToday)

self._state_attributes = {
"calendar": calendar,
"calendar": self.menu.menu,
"name": self._name
}

self._last_menu_fetch = datetime.now()

except Exception as e:
log.critical (f"Error fetching/parsing {self._rss}\n{e}")

0 comments on commit ec68c95

Please sign in to comment.