<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Martin Moen on Medium]]></title>
        <description><![CDATA[Stories by Martin Moen on Medium]]></description>
        <link>https://medium.com/@martinmoen?source=rss-617fafcce9ac------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*0aenxkKzISG7IZyM7f0ytg.jpeg</url>
            <title>Stories by Martin Moen on Medium</title>
            <link>https://medium.com/@martinmoen?source=rss-617fafcce9ac------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 16:57:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@martinmoen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[From a Blank Canvas to a Live Portfolio: The Story of Building My Site from Scratch]]></title>
            <link>https://medium.com/@martinmoen/from-a-blank-canvas-to-a-live-portfolio-the-story-of-building-my-site-from-scratch-186c9759f159?source=rss-617fafcce9ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/186c9759f159</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[homelab]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[portfolio]]></category>
            <dc:creator><![CDATA[Martin Moen]]></dc:creator>
            <pubDate>Sat, 18 Oct 2025 16:10:38 GMT</pubDate>
            <atom:updated>2025-10-18T16:10:38.843Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>In an age of instant gratification and one-click templates, what is the value of building something from scratch? This is the story of a project that’s part portfolio, part homelab experiment, and a complete answer to that question. It’s a journey through modern web development, self-hosting, and the simple satisfaction of owning every line of code.</blockquote><figure><img alt="The atmospheric landing page of my site" src="https://cdn-images-1.medium.com/max/1024/1*jMu8ymX2hFcOYPJtxGctmA.png" /><figcaption>The atmospheric landing page of my site</figcaption></figure><p>In a world overflowing with portfolio templates and site builders, the first question is always, ‘Why bother building from scratch?’ For me, the answer was simple, but powerful: I wanted to own every single pixel. My journey into full-stack development at work and my passion for my personal homelab at home were on a collision course. This project is what happened when they met.</p><p>At work, I’ve been diving deeper into full-stack development with React and Vue, while at home, my personal homelab has become a passion project. These two interests went hand-in-hand when I decided I wanted a space to write about my projects. What started as a simple blog idea quickly grew into a full-fledged portfolio, and the homelab was the perfect place to build and host it.</p><h3>The Technology Stack</h3><p>I chose a modern, performant, and scalable stack that reflects the tools I use daily and wanted to showcase and learn more about.</p><h4>Frontend Application</h4><ul><li>Framework: Next.js 15 with the App Router, chosen for its powerful server-side rendering capabilities, performance-first approach, and seamless developer experience.</li><li>Styling: Tailwind CSS v4 with a custom, theme-aware design system using CSS variables.</li><li>Components: Headless UI for accessible components like the modals and mobile menu.</li><li>Animations: Framer Motion for subtle, polished UI animations.</li><li>Blog: Statically generated from local Markdown files, parsed with unified and rehype, with syntax highlighting powered by shiki.</li></ul><h4>Self-Hosted Infrastructure</h4><ul><li>Hypervisor: Proxmox VE running on an ASUS PN64 Mini PC.</li><li>Web Server: A lightweight Nginx container serves the static site files.</li><li>Proxy: Nginx Proxy Manager handles SSL and acts as the secure gateway for all traffic.</li><li>Analytics: A self-hosted instance of Plausible Analytics provides privacy-focused site tracking.</li></ul><figure><img alt="The blog that was originally intended to be the only aspect of the website" src="https://cdn-images-1.medium.com/max/1024/1*iTyHFaTNx6GfzkO-v73NXQ.png" /><figcaption>The blog that was originally intended to be the only aspect of the website</figcaption></figure><h3>Design and Layout</h3><p>My goal was a clean, modern, and professional aesthetic that felt personal and unique.</p><ul><li>The Landing Page: I opted for an “Atmospheric Focus” design — a minimalist portal with a dynamic, multi-layered background and interactive buttons to guide visitors to the main sections of the site.</li><li>The Portfolio: A single, filterable grid inspired by modern portfolio sites. Users can filter by category (Code, Art, Game) and view project details in a tabbed modal without leaving the page.</li><li>The About Page: A portfolio needs a CV portion (at least so I was thinking). This is heavily inspired by the elegant, scroll-spy navigation of designers like Brittany Chiang. A sticky left column provides context and navigation, while the right column tells my professional story.</li><li>The Blog: A minimalist, typography-focused layout designed for maximum readability, powered by the @tailwindcss/typography plugin.</li></ul><h3>Components of Note</h3><p>Beyond the overall layour, a lot of effort went into crafting the core interactive components to be reusable, theme-aware and user-friendly. A core principle for this project was clean architecture. I intentionally separated the presentation layer (React components) from the business logic and data sources. All project details, work experience, and social links are stored in dedicated .js files, which are then fetched and passed into the components as props. This approach makes the site easier to update and maintain without touching the component code itself, and sticking to the DRY principle.</p><ul><li>The Project Card: The project card is the centerpiece of the portfolio. My goal was to make it more than just a static link. It needed to be interactive and visually tied to the content it represents:</li><li>Dynamic Theming: Instead of a single color, the card’s border and hover glow are dynamically colored based on its primary tag (e.g., ‘Code’, ‘Art’, ‘Game’). This is handled by a helper function that pulls from a centralized set of CSS theme variables, ensuring colors are consistent and theme-aware.</li><li>Interactive Feedback: On hover, the card gently scales up and emits a soft glow matching its category color, providing clear and satisfying feedback.</li><li>The Project Modal: Clicking a project card doesn’t navigate away from the page. Instead, it opens a detailed modal, keeping the user in context. This component had to be flexible enough to handle different types of media.</li><li>Dynamic Tabs: To avoid a cluttered, long-scrolling modal, I implemented a dynamic tab system using Headless UI. The modal checks if a project has extra media, like a Sketchfab model or a YouTube video. If it does, it automatically generates tabs for “Details,” “Sketchfab,” and “YouTube,” keeping the content neatly organized.</li><li>Scrollable Content: For projects with a lot of text and images, the main content area of the modal becomes scrollable while the header image and footer button remain fixed. This was achieved with a nested flexbox layout, ensuring the modal is always easy to use and never overflows the screen.</li><li>The Experience Item: These are used in the About page to create the different experience items: such as the different employment and education cards.</li></ul><figure><img alt="showcasing the highlighting in the portfolio section" src="https://cdn-images-1.medium.com/max/1024/1*KWINShpNlK_LdYk2Aa96SQ.gif" /><figcaption>showcasing the highlighting in the portfolio section</figcaption></figure><h3>Challenges &amp; Solutions</h3><p>Building from scratch is never without its hurdles. Here are a few of the most interesting challenges I encountered:</p><h4>Making up my mind</h4><p>Probably the biggest challenge was to find out “what did I want with this”; what could I attempt to make that would be fun enough to build and yet something good looking enough to be “worth” showcasing. The entire layout went through several iterations and there were many occasions I was ready to say “well this was fun enough, but on to the next thing”. One of the earliest challenges was translating a ‘blank canvas’ into a concrete design. My approach was iterative; I went through several layout concepts, wireframes, and color palettes. Sticking with key decisions, like the ‘Atmospheric Focus’ landing page, created a foundation that guided the rest of the site’s design.</p><h4>The Bane of CSS</h4><p>Now I am not a frontend developer by trade: I am dabbling more and more in it at work, but the frontend is just an aspect of many of the things I touch upon at work. But whenever I do, there is this constant battle of getting things center, sitting nicely in place, or just in general behaving as I envision it. Now TailwindCSS was AMAZING, don&#39;t get me wrong, but there was still a constant battle of having one div formatted one way, while the next div formatted differently to get it to look as I want it. Then we add on embedding from other sites like Sketchfab, and making that play nicely within my format. It did not help that I did the rookie mistake of first hard-coding all the colors when setting up, which gave me a good cleanup job when I remembered that &quot;light mode&quot; is a thing.</p><h4>It works on my computer</h4><p>The unending hurdles one has to face going from running npm run dev to having the site finish built accessible through the web. First hurdle was getting the URL to work properly: This is not the first container that I have opened to the web, but it is by far the hardest one I have had to get working. I ran into constant &quot;502 Bad Gateway&quot; that would randomly take the site down mid debugging and setups. Only for me to figure out I did the rookie mistake of forgetting to reserve the static IP for the container, meaning my Pixel Tablet would sometime operate on the same IP. I also ran into the other classic gatchas with running an SPA: with how the routing works differently, especially with the dynamicly generated content for the blog. But like anything, I got to it one problem at a time, setting up the proxy correctly, automating the deployment so no typos would creep in and ensuring routing and refreshing works as you expect on a modern site.</p><figure><img alt="GIF showcasing the filtering" src="https://cdn-images-1.medium.com/max/1024/1*UsY1LC6Nw23w-VQWugUeQA.gif" /><figcaption>GIF showcasing the filtering</figcaption></figure><h3>Pragmatic Decisions &amp; Trade-offs</h3><p>Every project requires balancing ideal solutions with practical constraints. For this portfolio, a key architectural decision was how to handle media assets, particularly the high-resolution images from my art projects. While Next.js offers a fantastic built-in image optimization pipeline, I made a strategic choice to serve these assets from their original sources, like Artstation. Now that might sound a bit weird considering a big portfion of the portfolio section is dedicated to my artistic projects. However, the primary benefit of this approach is a significantly smaller and more lightweight repository. This simplifies the build and deployment pipeline, reduces hosting costs, and avoids content duplication. The trade-off, of course, is a dependency on external services and a potential increase in load time as browsers fetch images or render embeds from third-party domains. For the goals of this project, I determined that the operational simplicity and maintainability benefits outweighed the minor performance impact for the end-user.</p><h3>Final Thoughts</h3><p>This project was an incredible learning experience that went far beyond just building a React application. It was a journey through networking, server administration, design systems, and debugging deep, complex issues. The result is a site that I have 100% control over, from the hardware it runs on to the last line of CSS.</p><p>And that, to me, is why you bother.</p><p>Thank you for reading. If you’re interested in checking out the site you can do so <a href="http://martin.dvalin.dev/">here</a></p><p>PS: Below I have pasted the project layout for those interested in seeing how all of this is organized</p><h3>Project Structure</h3><pre>frontend-root/<br>├── src/<br>│   ├── app/<br>│   │   ├── (main)/              # Route Group for pages with the main layout<br>│   │   │   ├── about/<br>│   │   │   │   └── [id]/        # Slug for generated blog articles from .md<br>│   │   │   ├── blog/<br>│   │   │   ├── portfolio/<br>│   │   │   └── layout.js        # Layout WITH the Navbar<br>│   │   │<br>│   │   ├── globals.css          # Global styles, Tailwind config, and theme variables<br>│   │   ├── layout.js            # Root layout (WITHOUT Navbar) for the splash page<br>│   │   └── page.jsx             # The main landing/splash page<br>│   │<br>│   ├── components/<br>│   │   ├── about/<br>│   │   │   ├── EducationItem.jsx               # Reusable Eductation element to use in the about page<br>│   │   │   ├── VolunteerExperienceItem.jsx     # Reusable Volunteering Experience element to use in the about page <br>│   │   │   └── WorkExperienceItem.jsx          # Reusable Work Experience element to use in the about page <br>│   │   ├── portfolio/  <br>│   │   │   ├── PortfolioFilters.jsx            # Project Filtering Component to filter per category<br>│   │   │   ├── ProjectCard.jsx                 # Reusable card component for projects<br>│   │   │   └── ProjectModal.jsx                # Reusable modal component for projects<br>│   │   ├── shared/<br>│   │   │   ├── HeroButton.jsx                  # The main animated buttons for the landing page<br>│   │   │   ├── Navbar.jsx                      # The site&#39;s main navigation bar<br>│   │   │   └── ThemeSwitch.jsx  <br>│   │   │<br>│   │   └── ThemeProvider.jsx      # Light / Dark <br>│   │<br>│   ├── data/<br>│   │   ├── experiences.js          # JS file holding objects with all the experiences for the about page   <br>│   │   ├── projects.js             # JS file holding objects with all the projects   <br>│   │   └── socials.js              # JS file holding objects with all the social links and icons   <br>│   │   <br>│   └── lib/<br>│       └── color-helper.js         # Helper function that returns colors based on tags<br>|<br>├── posts/                          # Where all the blog post are stored in .md<br>|<br>├── package.json<br>└── README.md</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=186c9759f159" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Lights Out: Building a Real-Time F1 Lighting System in my Smart Home (Part 2)]]></title>
            <link>https://medium.com/@martinmoen/going-lights-out-building-a-real-time-f1-lighting-system-in-my-smart-home-part-2-ff2cf60a6763?source=rss-617fafcce9ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff2cf60a6763</guid>
            <category><![CDATA[mqtt]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[home-assistant]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[formula-1]]></category>
            <dc:creator><![CDATA[Martin Moen]]></dc:creator>
            <pubDate>Thu, 16 Oct 2025 14:44:46 GMT</pubDate>
            <atom:updated>2025-10-16T18:12:38.578Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="A formula 1 car with code text overlaid on it" src="https://cdn-images-1.medium.com/max/1024/1*4PqsNR1rUW3J5FngRPb3-g.jpeg" /></figure><blockquote>This is Part 2 of a three-part series on how I built a real-time lighting system for my smart home that reacts to live Formula 1 races. In the previous part I talked about the inspiration for the project. In this part, I’ll dive into the Python code, the struggles of parsing long string of text data and my final achievement of conquering time itself. In the next and final part, we’ll deeper into the Home Assistant configuration</blockquote><p>In part 1 I explained what inspired me to look for a live F1 expansion, my struggles finding a fitting solution, and how even making something myself seemed like a bridge too far. But as I was about to give up I found the magic command in the FastF1 API:</p><pre>fastf1.livetiming save - append cache.txt</pre><p>Not that it was obvious to begin with. When I first tried out the FastF1 library it was pretty clear that the main intended use was for previous broadcasts, and even the documentation for the livetiming function stated that you were not able to process the data as it was being recorded. But having nothing to lose anyways I sneakily got it running during a free practice session while I was at work. To my great delight line after line started to appear in the cache file: ‘RaceControlMessage’, ‘WeatherData’, ‘TimingData’. None of it truly made sense yet, but clearly I could use this somehow. Then it happened; A yellow flag was waving on track, eagerly I dove into the cache file searching for it, and that is when I found it:</p><pre>[&#39;RaceControlMessages&#39;, {&#39;Messages&#39;: {&#39;56&#39;: {&#39;Utc&#39;: &#39;2025–07–05T11:39:56&#39;, &#39;Category&#39;: &#39;Flag&#39;, &#39;Flag&#39;: &#39;YELLOW&#39;, &#39;Scope&#39;: &#39;Sector&#39;, &#39;Sector&#39;: 2, &#39;Message&#39;: &#39;YELLOW IN TRACK SECTOR 2&#39;}}}, &#39;2025–07–05T11:39:56.262Z&#39;]</pre><p>It was a messy, cryptic line buried in a jungle of text, but it was a signal. It was proof that this data could be read, parsed and acted upon. <strong>The project was on</strong>.</p><h3><strong>Challenge 1: The Parsing</strong></h3><p>It was clear that to make this work I had to cache the livetiming, and simultaneously read the cache. Then in the reader I would have to parse the incoming lines of data, ignore 95% of it and only parse the data of interest. Since there was no documentation I had to figure out these things for my setup to work:</p><ul><li>Who is in the lead: So what does the lead look like in the data? Is it a “Now this driver leads the session!” or do I have to manually figure this out myself?</li><li>Events on track: flags, incidents and safety cars. How are they recorded, and how are they neutralized?</li><li>Custom session events: Things like race start vs. start of Free practice, or how to go from Q1 to Q2 in a qualifying session.</li></ul><p>This challenge was actually two-fold; 1 was the sheer amount of lines I had to look through, but the second was that even reading the lines didn’t inherently make any sense. Take this line for example:</p><pre>[&#39;TimingData&#39;, {&#39;Lines&#39;: {&#39;5&#39;: {&#39;TimeDiffToPositionAhead&#39;: &#39;+1.566&#39;}, &#39;10&#39;: {&#39;TimeDiffToFastest&#39;: &#39;+1.719&#39;, &#39;TimeDiffToPositionAhead&#39;: &#39;+0.383&#39;, &#39;Line&#39;: 16, &#39;Position&#39;: &#39;16&#39;, &#39;NumberOfLaps&#39;: 11, &#39;Sectors&#39;: {&#39;2&#39;: {&#39;Value&#39;: &#39;25.189&#39;, &#39;PersonalFastest&#39;: True}}, &#39;Speeds&#39;: {&#39;FL&#39;: {&#39;Value&#39;: &#39;337&#39;, &#39;PersonalFastest&#39;: True}}, &#39;BestLapTime&#39;: {&#39;Value&#39;: &#39;1:44.073&#39;, &#39;Lap&#39;: 10}, &#39;LastLapTime&#39;: {&#39;Value&#39;: &#39;1:44.073&#39;, &#39;PersonalFastest&#39;: True}}, &#39;18&#39;: {&#39;Line&#39;: 19, &#39;Position&#39;: &#39;19&#39;}, &#39;27&#39;: {&#39;TimeDiffToPositionAhead&#39;: &#39;+0.181&#39;, &#39;Line&#39;: 17, &#39;Position&#39;: &#39;17&#39;}, &#39;43&#39;: {&#39;Line&#39;: 18, &#39;Position&#39;: &#39;18&#39;}}}, &#39;2025–09–20T09:07:19.672Z&#39;]</pre><p>It indicates that this is a timing entry, but is it for a sector, a full lap, and is the data broken down into deltas, pure timestamp or a finished parsed laptime? It became a tedious process of slowly figuring out what to look for in the data; one screen with action going on, the other with the lines of data coming in. Together with clear instructions to an AI it slowly started to unravel, and the tedious process of reverse-engineering slowly turned into concrete Python functions, like this one determining the fastest lap:</p><pre>def process_lap_time_line(line: str, state: SessionState, mqtt_handler: MQTTHandler) -&gt; None:<br>    category, payload, _ = ast.literal_eval(line)<br>    if category == &#39;TimingData&#39; and &#39;Lines&#39; in payload:<br>        for num, data in payload[&#39;Lines&#39;].items():<br>            if &#39;LastLapTime&#39; in data and isinstance(data[&#39;LastLapTime&#39;], dict):<br>                lap_time_str = data[&#39;LastLapTime&#39;].get(&#39;Value&#39;)<br>                if lap_time_str and (lap_time := parse_lap_time(lap_time_str)) and lap_time &lt; state.fastest_lap_info.time:<br>                    driver_info = state.drivers_data[num]<br>                    driver_abbreviation = driver_info[&#39;abbreviation&#39;]<br>                    team_key = driver_info[&#39;team_key&#39;]<br>                    state.set_fastest_lap(lap_time, driver_abbreviation, team_name)<br>                    state.set_session_lead(driver=driver_abbreviation, driver_number=num, team=team_name)<br>                    payload = json.dumps({&quot;driver&quot;: driver_abbreviation, &quot;driver_number&quot;: num, &quot;team&quot;: team_name})</pre><p>As more and more lines and logic started to take form, this main loop became the heart of the service, continuously reading new lines from the cache file and feeding them to the correct processing functions.</p><pre># from the main loop<br>with open(cache_file, &#39;r&#39;, encoding=&#39;utf-8&#39;, errors=&#39;replace&#39;) as f:<br>    logging.info(f&quot;DRS {DRS_VERSION} started {session_state.session_type} session. Reading live data from &#39;{cache_file}&#39;…&quot;)<br>    f.seek(0, 2)<br>    while True:<br>        line = f.readline()<br>        if not line:<br>            time.sleep(0.1)<br>        else:<br>            try:<br>                f1_utils.process_session_data_line(line, session_state, mqtt)<br>                race_lead_process(line, session_state, mqtt) # this function is set depending on session (practice, qualifying or race)<br>                f1_utils.process_race_control_line(line, session_state, mqtt)<br>            except Exception as e:<br>                logging.error(f&quot;Error processing line: {e}&quot;)</pre><p>As I got more and more information from more and more sessions I started to get a more complete picture of the <em>”API”</em>, and soon I had logic for resetting between qualifying sessions, safety cars and most of the events that I wanted highlighted in my setup.</p><h3><strong>Challenge 2: The Testing.</strong></h3><p>A great challenge in my development was testing. To begin with, the only way to test the logic was during the live sessions. This meant that in the early stages I had to decide if I wanted to mainly watch the action on screen, or action in data. I decided relatively quickly to start gathering a little library of test strings fetched from the live sessions, and these proved invaluable during the development to test and verify business logic of the service. I still couldn’t test unknown events, though. So I had to be there by my computer every session to log, and hope that as much as possible would happen.</p><p>Soon I could then do some testing as I developed. It was slow and tedious, but would ensure that when I made changes to the scripts I knew that the whole thing wouldn’t be completely broken by the start of next session. With this “line library” I could also start writing unit tests for the application using pytests for even more robust development. This allowed me to create a suite of tests to validate core logic, like ensuring a yellow flag message correctly updates the system’s state:</p><pre>def test_yellow_flag(state: SessionState, mock_mqtt: Mock):<br>    &quot;&quot;&quot;Testing when yellow flags are raised&quot;&quot;&quot;<br>    # Set yellow flag in sector 2<br>    yellow_flag_line = &quot;[&#39;RaceControlMessages&#39;, {&#39;Messages&#39;: {&#39;56&#39;: {&#39;Utc&#39;: &#39;2025–07–05T11:39:56&#39;, &#39;Category&#39;: &#39;Flag&#39;, &#39;Flag&#39;: &#39;YELLOW&#39;, &#39;Scope&#39;: &#39;Sector&#39;, &#39;Sector&#39;: 2, &#39;Message&#39;: &#39;YELLOW IN TRACK SECTOR 2&#39;}}}, &#39;2025–07–05T11:39:56.262Z&#39;]&quot;<br>    process_race_control_line(yellow_flag_line, state, mock_mqtt)<br>    # Assert<br>    ## States<br>    assert state.race_state == &#39;YELLOW&#39;<br>    assert 2 in state.yellow_flags<br>    ## MQTT<br>    mock_mqtt.queue_message.assert_called_once()<br>    expected_payload = json.dumps({&quot;flag&quot;: &quot;YELLOW&quot;, &quot;message&quot;: &quot;YELLOW IN TRACK SECTOR 2&quot;})<br>    mock_mqtt.queue_message.assert_called_with(MqttTopics.FLAG_TOPIC, expected_payload)</pre><p>and even better yet, I now have a full simulation run with a “whole session” full of events so I can test everything in an orderly fashion: Lead change, flags and safety cars out and in!</p><pre>for event in SIMULATION_EVENTS:<br>    time.sleep(DELAY_SECONDS)<br>    description = event[&#39;description&#39;]<br>    line_to_write = event[&#39;line&#39;]<br>    logging.info(f&quot;SIMULATING: {description}&quot;)<br>    f.write(line_to_write + &#39;\n&#39;)<br>    f.flush()</pre><h3><strong>Challenge 3:</strong> <strong>̶T̶h̶e̶ ̶N̶o̶b̶e̶l̶ ̶P̶r̶i̶z̶e̶ The Syncing.</strong></h3><p>The tool was starting to get quite stable, and I could actually let the tool run while I fully watched the action on TV when the lights suddenly started flashing yellow. I sighed and walked over to the PC to see what was wrong when I hear all the commotion from the TV: Yellow flag is out. For a moment I see things ticking in on the PC <strong>before</strong> they happened on the TV!</p><p>It took a moment before I understood: I could see into the future, and my computer was a time vortex bending reality. I rushed to the phone to call the Nobel committee when another thought struck: I rely on the same data that the broadcasters do. I just have to send this data across my local network while the broadcasters have to process, add graphics, composite it all together to a broadcast before pushing it out. So there was a small chance this wasn’t a groundbreaking new discovery that would redefine physics, but simply a syncing issue.</p><p>After some more research, I had to face the fact that this was yet again not going to be the year I won a Nobel Prize, as it was, in fact, a sync issue. And we weren’t talking about a couple of seconds off, but up to a minute! The solution for this one was pretty self-explanatory: a simple <strong>PUBLISH_DELAY </strong>config variable that would queue the messages as they came in so they would broadcast at the right moments without missing any action. That would have been it, had the delay just been a constant.</p><p>The delay seemed to vary from week-to-week, day-to-day or just depending on the mood of my cats. I set a delay in seconds and just had to HOPE that it was close enough when the session starts, because as any F1 fan knows: Seconds are a <strong>LONG</strong> time in racing. When the delay was set just right it was an epic experience with the lights reacting in sync with the action on TV, but if it was off by even a second it felt like a jarring mismatch of the drummer who cannot keep the beat.</p><p>In my frustration I went through several grand ideas: What if I could somehow query the broadcasting delay from the publisher, or if the PC could be watching the race too and use image analysis to detect when things happen on that broadcast to calculate the delay. It all felt a lot more complicated than I thought it ought to be, that was when a new idea struck me: Instead of it being a one way street of information, what if I could adjust the delay mid-race from my phone? Even better, what if I could find sync points from the good old live cache?</p><pre># The Session info<br>[&#39;SessionInfo&#39;, {&#39;Meeting&#39;: {&#39;Key&#39;: 1268, &#39;Name&#39;: &#39;Italian Grand Prix&#39;, &#39;OfficialName&#39;: &#39;FORMULA 1 PIRELLI GRAN PREMIO D�ITALIA 2025&#39;, &#39;Location&#39;: &#39;Monza&#39;, &#39;Number&#39;: 16, &#39;Country&#39;: {&#39;Key&#39;: 13, &#39;Code&#39;: &#39;ITA&#39;, &#39;Name&#39;: &#39;Italy&#39;}, &#39;Circuit&#39;: {&#39;Key&#39;: 39, &#39;ShortName&#39;: &#39;Monza&#39;}}, &#39;SessionStatus&#39;: &#39;Started&#39;, &#39;ArchiveStatus&#39;: {&#39;Status&#39;: &#39;Generating&#39;}, &#39;Key&#39;: 9912, &#39;Type&#39;: &#39;Race&#39;, &#39;Name&#39;: &#39;Race&#39;, &#39;StartDate&#39;: &#39;2025–09–07T15:00:00&#39;, &#39;EndDate&#39;: &#39;2025–09–07T17:00:00&#39;, &#39;GmtOffset&#39;: &#39;02:00:00&#39;, &#39;Path&#39;: &#39;2025/2025–09–07_Italian_Grand_Prix/2025–09–07_Race/&#39;, &#39;_kf&#39;: True}, &#39;2025–09–07T13:03:34.805Z&#39;]<br># The gold nugget, notice how it is 3 min after race start meaning it is the exact moment they go lights out!<br>[&#39;SessionData&#39;, {&#39;StatusSeries&#39;: {&#39;4&#39;: {&#39;Utc&#39;: &#39;2025–09–07T13:03:34.805Z&#39;, &#39;SessionStatus&#39;: &#39;Started&#39;}}}, &#39;2025–09–07T13:03:34.805Z&#39;]</pre><p>And with that I had a relatively simple and easy solution for a problem that had plagued me for quite a while: We set a good guestimate delay in the config, the PC detects the race start, I <em>see</em> the race start on TV and press a button: Simply Lovely. On top of that I have some more buttons that allow me to adjust the delay more granularly in different intervals, giving close to perfect precision for the delay!</p><pre>def _on_message(self, client, userdata, msg):<br>    &quot;&quot;&quot;Handles incoming MQTT messages. Mainly for DRS CONTROL&quot;&quot;&quot;<br>    try:<br>        |command = msg.payload.decode(&#39;utf-8&#39;)<br>        if command == &quot;CALIBRATE_START&quot;:<br>            self.command_queue.put(&quot;CALIBRATE_START&quot;)<br>        elif command.startswith(&quot;ADJUST:&quot;):<br>            &quot;&quot;&quot;Split incoming message, make it a value and do a simple calculation for new delay&quot;&quot;&quot;<br>            _, value_str = command.split(&quot;:&quot;)<br>            adjustment = float(value_str)<br>            current_delay_sec = self.publish_delay.total_seconds()<br>            self.set_delay(current_delay_sec + adjustment)</pre><p>And there we have it: a Python service born from a mountain of cryptic data, hardened by a robust testing suite, and perfected with a solution to a time-bending sync problem. The engine is built, tested, and ready to go.</p><p>In the final part of this series, we’ll leave the terminal behind and jump into Home Assistant. I’ll share the YAML, scripts, and automations needed to bring this data to life and finally get our smart lights reacting to the race.</p><p><em>interested in checking out the full code, maybe even try it yourself? Check out the Github repo </em><a href="https://github.com/Moeren588/Dashboard-Reaction-Service"><em>here</em></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff2cf60a6763" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Going Lights Out: Building a Real-Time F1 Lighting System in My Smart Home (Part 1)]]></title>
            <link>https://medium.com/@martinmoen/going-lights-out-building-a-real-time-f1-lighting-system-in-my-smart-home-part-1-0434f0d92886?source=rss-617fafcce9ac------2</link>
            <guid isPermaLink="false">https://medium.com/p/0434f0d92886</guid>
            <category><![CDATA[formula-1]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[smart-home]]></category>
            <category><![CDATA[home-assistant]]></category>
            <dc:creator><![CDATA[Martin Moen]]></dc:creator>
            <pubDate>Mon, 29 Sep 2025 12:59:52 GMT</pubDate>
            <atom:updated>2025-09-29T13:18:04.511Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="Illustration of a stylized F1 car on a TV with matching lighting around it" src="https://cdn-images-1.medium.com/max/1024/1*EgoOcV4OjQtQjIpVEMN2KA.png" /><figcaption>Illustration of a stylized F1 car on a TV with matching lighting around it</figcaption></figure><blockquote>This is Part 1 of a three-part series on how I built a real-time lighting system for my smart home that reacts to live Formula 1 races. In this part, I’ll cover the spark of the idea and the frustrating search for a solution. In future parts, we’ll dive into the Python code and the final Home Assistant configuration</blockquote><p>This spring I got a couple of new obsessions: Setting up my own HomeLab server! It was quite the sudden obsession that I jumped on, but before I knew it I had a mini-PC with a full fledged home server running; all of this definitely a story for another time! But by far one of the best setup: Home Assistant!</p><p>Suddenly we only need 1 app to control <em>all </em>(™) smart devices in our home; no more “app fatigue” of slow apps trying to remember “which had the bathroom lights again?!”. Scaling the smart home was now no longer locked behind “which app we already have”. We could finally start looking for the devices we needed for the prices we felt were fair. Before long I had custom dashboards made, individual spotlights grouped into fixtures. Automations set up to ease the day to day life, and scripts written to avoid repetition.</p><p>It was then during my second obsessions, Formula 1, that I had a bit of a (smart) light bulb moment: With all of this setup now, all under my own control, why isn’t my home able to <em>react </em>to what is happening on the TV? When Max takes pole the lights should switch to Red Bull colors, if there’s a safety car the lights should turn yellow and when we get a red flag interruptions the lights should flash red! That started me on an exploratory route to see: what already exists, and how hard is it to implement it?</p><p>As it turned out, this was not at all as simple as I had initially thought.</p><p>Don’t get me wrong, the Home Assistant community is truly amazing. I dove through forums and plugins, finding brilliant solutions and setups at every turn. There were custom dashboards for the F1 Grid and standings, custom sensors that integrated perfectly into the HA ecosystem, and even someone who made a HA device that shows the timing and date for the next race on a small e-ink display! The creativity was endless, but they all lacked the one thing I was looking for: Live connection to the <em>current</em> race I was seeing on screen.</p><p>From here I realised that I had to look a bit outside “pure” HA setup, I started looking for external services. I was digging through countless fan-made F1-projects, and again I was blown away by the ingenuity of the F1 fanbase. But I kept hitting the same wall: No one solution that fit my simple need. Even when I looked into doing “all the work” myself, using my own PC to follow, process and queue events, the best option was the OpenF1 API which had just put their live feed behind a paywall.</p><p>It was a dead end. I was genuinely starting to give up, reasoning that F1 would never let this kind of real-time data be available for free. I resigned myself to that fate and started instead half automating the setup with pre-made buttons to trigger the events myself.</p><figure><img alt="Screengrab of the manual button setup in Home Assistant" src="https://cdn-images-1.medium.com/max/1024/1*W9zlhHrikSPCZajjomXy6w.png" /><figcaption>Screengrab of the manual button setup in Home Assistant</figcaption></figure><p>And that was when I found it.</p><p>Buried deep in the documentation for another Python API called <em>FastF1</em>: A command that would be the key to my entire project.</p><p>I thought the hardest part was over, I was wrong... In Part 2, I’ll explain the strange world of broadcast delays, string parsing live data and the code I wrote to finally tame them. Want to sneak peak the results already? Check out the GitHub repository <a href="https://github.com/Moeren588/Dashboard-Reaction-Service">here</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=0434f0d92886" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>