So, I recently took to Twitter to share the latest re-design of my Lovelace dashboard:
Among the responses I received, there was a significant amount of interest in finding out how I was able to pull in and display the live MLB scores, so I agreed to write up a little tutorial. Hopefully this is something that a few of you out there can benefit from.
Before I begin, though, I should acknowledge the real brains behind this solution. When I first got the RGB bulbs for my basement, I was looking to build the smart home equivalent to the Budweiser goal light and stumbled upon the following reddit post:
So, full credit goes to the the the fine folks in that thread. I merely copied what they did and extended / personalized the solution for my own purposes. That said, I’m happy to pass along the details of what I’ve done.
At it’s heart, this solution relies on a series of REST sensors that call a public API at predefined intervals. Here is the code for them:
https://paste.ubuntu.com/p/SrHNfHzMS8/
.
As you can see from the code, I’m a Red Sox fan. If you are not, that’s okay… Here are the steps to adapt this solution to your favourite team:
-
Visit the following URL and find the three-digit ID for your team of choice:
http://statsapi.mlb.com/api/v1/schedule?sportId=1 -
Replace the teamID at the end of line 3.
-
Rename the sensors to your liking by finding and replacing any references to “boston” or “red sox” in my code to the equivalents for your team.
With the sensors in place, we now need to make sure they are kept up-to-date. At the same time, it’s also fun to kick off a little celebration when your team scores a run. Here is the script and automations that I use:
https://paste.ubuntu.com/p/WkCYQYdpBH/
Again, simply find and replace any references to my team with your own. Also, a couple of my automations rely on an input boolean that acts as a flag to have the scores update more frequently when I’m actually watching the game. If you copy my code directly, you’ll want to create one of your own in your configuration.
Lastly, here is the code I use to display the scores on my dashboard:
columns: 3
show_name: false
type: glance
filter:
exclude:
- state: No_Game
- state: unknown
include:
- entity_id: sensor.boston_home_score
- entity_id: sensor.boston_away_score
- entity_id: sensor.boston_game_status
show_empty: false
type: 'custom:auto-entities'
My full implementation actually tracks a couple of teams, so I use the auto-entities card to ensure that only teams that are playing on a given day show up on the dashboard.
So, that’s it. But before I go, I should mention that I haven’t figured out a good way to handle double-headers. With this solution, only the first game of a double-header will update, while the second one will be ignored. If any of you find an elegant way to address this, please do let me know.