All articles
13 min read

Fixing my sleep with technology

How, after many years, I fought against my sleep and finally solved it using technology

By Aloïs

Listen to this article

AI-generated narration · English

yes it was AI generated, but it was the perfect image for my post, sorry !

TL;DR: For years, I was exhausted and tried every sleep hack and supplement. A home sleep test finally showed sleep apnea (AHI 26), but where I live, it wasn't enough to get a CPAP prescription. So I bought a second-hand CPAP and tuned it myself, with LLMs and my own self-hosted sleep-tracking setup (SleepTrace). My energy went from 1–6 to 6–9 out of 10, and my AHI from 26 to under 8.

Contents


During my college studies, I became aware that something wasn't working well in my body.

Middle school and high school were barely bearable, but in college things got astonishingly harder. You explore way more difficult concepts, have to organize yourself, the beginning of adult life!

I was always tired, pale, and had headaches. Sadly, this was the only state I knew. Almost sleeping in exams, having legit 0 mental energy, difficulties doing super simple calculations.

The worst part is that, over the years, this became my “personality”. I just accepted that I was the tired guy, that this was how I was.

I still remember the day I asked my cousin if it was “normal” to have migraines and headaches every morning.
Of course, he answered no. Then it really clicked, and I started trying to optimize my sleep (orthosomnia [1]).

I read a ton of posts on Reddit, especially on the brainfog sub [2].

Trying everything

I tried everything I could:

But I was still waking up completely tired every other day.

For a long time, I thought I just had a hyperactive brain (I've never been able to nap) and no OSA, and that's why I tried all those GABA things, etc. But then I learned that sedatives can increase the number of apneas and their severity [11].

One thing that helped was to move to a calmer flat. I knew I had a very light sleep, so minimizing the external factors helped.

The first diagnosis, which misled me

In 2023, I went through a polygraphy [12] and got an AHI [13] of ~10. The doctor just told me I didn't have anything to treat.

That's when my descent into hell began.


A polygraphy is not a PSG [14]. It only looks at your breathing, oxygen and heart rate… not your brain. So it has no idea if you're actually asleep, and it misses the micro-awakenings that end a lot of hypopneas. Result: it tends to underestimate the AHI [15].
And the funny part? An AHI of ~10 is already mild OSA [16] (it starts at 5 per hour). So, yeah… “nothing to treat”.

I started becoming more and more frustrated, because I couldn't f*cking understand what was going on.

I worked as a freelancer. The days were horrible; I was tired all the time. I had a lot of digestive issues. I couldn't understand why I needed twice the time to heal from my injuries, sicknesses…

My mood was horrible too. I was grumpy, irritable for nothing… not the best version of me, at all.


And I couldn't remember stuff. What I said to someone, a conversation I had, technical details at work, etc. etc. New information just didn't stick, it was super hard to encode anything. I was kind of “absent”: there, but not really there. And anyone who went through it knows that you cannot “escape” it.

All of this, plus personal issues, led to a burnout. I hurt some people alongside and feel bad every day for it. I think emotions, impulsivity, etc. are highly related to sleep.

I wish I had solved this earlier.

The second diagnosis

3 years and a breakdown later, my psychiatrist and I noticed that I often mentioned my sleep. After a session with him, we agreed I had to check my sleep again.

Thus, I went to a clinic and saw a sleep specialist, who gave me the stuff for an at-home PSG [14].

I don't know why, but I had to wait 3 months between the exam and the results... which led to more frustration.

However, the AHI went from 10 to 26, and 32 during REM [17]. This time I really believed I had the answer to my fatigue !

I was prescribed a MAD [18]. When I was a child, I got braces for my teeth, and then a retainer, but I didn't like it at all and wasn't able to sleep with it.

So I mentioned the CPAP [19], and he told me it wouldn't be possible to get it.

Where I live, you have to have an AHI > 30 to get the CPAP prescription, or really, really bad OSA [20] symptoms alongside a lower AHI.

A bit frustrated after all those years and the last 3 months waiting for the results, I just asked GPT if it was safe to use CPAP at home with my settings. I figured out it was not so “hard” to set, unless you have a very specific condition (which I assumed wasn't my case).

Not medical advice!

And then I entered the world of CPAP

I immediately looked for a second-hand CPAP on a classified ad website. I found one (ResMed AirSense 10) near where I live, instantly bought it and was able to get it that evening (was almost crying tears of joy when it was time to pick it up).

Then I tried it immediately, using LLMs [21] to put the most “generic” settings for the first night (I don't have a prescription, sooo…).

  • First night: quite special: I had aerophagy [22], but felt I was more rested than usual.
  • Second night: lowered the pressure.
  • Third night: fixed the mask… and I felt energy rising… which convinced me to keep going in that direction.

I've also identified that one of the supplements I was taking interacted with my other medication, which slowed my CPAP settings exploration (be careful if you take any; I used to underestimate the effects they could introduce).

Then, from ~27 Sept., I found really good settings.

Now, my mask is a ResMed AirFit F20, with a ClimateLineAir tube.
I almost don't have any OSA anymore. A few central apneas [23], but I'm trying to reduce their number every night.

My energy levels are between 6 and 9 every day !! when before they would be between 1 and 6 on average.

We can see in the 2 following images (AutoSleep app, “quality sleep” metric) how irregular my sleep was before vs now (I got the CPAP on the 31st of August) :)

“Quality sleep” from April to the end of July

“Quality sleep” from August

What I did to find my settings, here's the story

As you may know, LLMs are getting increasingly smart and can interact with your whole computer.

As an ex-data scientist with a CS degree, now a dev, I use them every day for work, and I'm well informed of their current capabilities.

Once you understand how APIs [24] work, that everything is exposed via them, via BLE [25], etc., you kind of understand that your LLM agent can parse it all, and interact with it.

I already had my smartwatch (an Apple Watch Ultra 2), an IR camera, and a running belt + an old phone.

For extra metrics, I bought an oximeter and an EEG device.

My own “sleep lab” :)

Basically, I have my own set of self-hosted apps, running on a Raspberry Pi. One of them I called “SleepTrace”. It does my sleep tracking.

I also work out, so I use LiftTrace for my training, and other “…Trace” apps (meals, mood) to complete my tracking. TraceApps gave me the idea of continuing with more apps like this. Worth checking out if you want a well made open source tracking app :)

Data pipeline: 7 sensors, grouped by how they reach it, feed a Raspberry Pi; a daily GPU run computes the pages; an LLM agent reads the private website to fine-tune the CPAP and sleep settings

One night, every signal on one clock, next to the infrared video (mock data)
Zoomed on a wave of central apneas: every breath, every flagged event (mock data)
Deep dive: one wave, breath by breath, next to the brain waves (mock data)
What happens around an apnea, averaged over every event (mock data)
The week view: averages and the seven nights side by side (mock data)
Every data source, night by night
One night, every signal on one clock, next to the infrared video (mock data)

How the loop works

Every day, the run builds my night pages. Then I open Claude Code and ask the agent to read them: CPAP airflow, events, EEG stages, oxygen, video… everything on the same clock. It tells me what it sees, I change one setting, and the next nights tell us if it worked. Simple.

Five periods of CPAP use: AHI 12.5, 21.2, 14.5, 8.8, 7.6; central index 9.6, 13.4, 13.4, 7.5, 6.0; obstructive index 2.0, 4.5, 0.4, 0.9, 0.4; hours per night 4.8, 5.5, 3.6, 5.3, 6.1.

What's left? Mostly central apneas. Today I asked the agent to do a deep dive on 3 nights to investigate further the CAs.
Looks like they come in waves (one every ~38 s), mostly right after a big breath or a micro-awakening: when I fall back asleep after putting the mask back on, during REM, and sometimes when the machine climbs to 11–12 cmH₂O at the end of REM.


Though my central apnea index already went from ~14/h (mid-Sept) to ~6/h.

Next test: EPR from 2 to 1 (or off) for a week… and we'll see.

My sleep lab, device by device

ResMed AirSense 10 AutoSet

ResMed AirSense 10 AutoSet · CPAP

A few hundred $, second-hand

Use: The treatment itself, plus airflow (25 Hz), pressure, leaks and apnea flags.

How reliable? Its apnea count tracks the sleep-lab count closely (r = 0.87–0.95 [26]), but it can't tell whether I'm asleep or awake.

Muse S Athena

Muse S Athena · EEG headband

$475

Use: Sleep stages, brain waves, head position and movement.

How reliable? Muse's own staging matched a full PSG with κ = 0.76 [27]; my stages come from a YASA-based algorithm coded by Claude Opus 5.5.

Wellue Checkme O2 Ultra

Wellue Checkme O2 Ultra · wrist oximeter

~$150

Use: Blood oxygen and pulse, every second.

How reliable? Good for overnight trends and drops, with ±2% precision.

Apple Watch Ultra 2

Apple Watch Ultra 2 · smartwatch

~$800

Use: Sleep stages, heart rate, HRV, breathing disturbances.

How reliable? Stages validated by Apple against PSG (white paper [28]); best of six wearables in an independent test [29] (κ = 0.53), but it under-counts deep sleep and wake.

Tapo C100

Tapo C100 · IR camera

~$30

Use: Body movement, sound, chest movement from the video.

How reliable? Video analysis coded by Claude Opus 5.5, cross-checked against the CPAP, not validated.

Old Android phone on a chest belt

Old Android phone on a chest belt · accelerometer

~$50

Use: Breathing effort and movement.

How reliable? Algorithm coded by Claude Opus 5.5; it follows the CPAP airflow closely (r ≈ 0.95 on a test night), not validated.

Apollo AIR-1

Apollo AIR-1 · Home Assistant

~$110

Use: Bedroom CO₂, temperature, humidity, particles.

How reliable? CO₂ accurate to ±(50 ppm + 5 %) (Sensirion SCD40 [30]).

For the nerds: the tech stack
  • Language: Python 3.13, NumPy, SciPy, Pillow and Matplotlib.
  • Pipeline: bronze - silver - gold layers; each stage is cached by a fingerprint of its code and inputs, and only reruns when one of them changes.
  • Orchestration: Prefect 3 flow, with a worker that runs the heavy stages on a GPU.
  • Video: FFmpeg with CUDA decoding; movement, sound and breathing effort computed with NumPy.
  • CPAP: home-made parser for ResMed EDF files (25 Hz flow and pressure, events), using OSCAR [31]'s ResMed loader as a reference.
  • EEG: raw Bluetooth LE packets decoded with OpenMuse; sleep stages with YASA and MNE.
  • Oximeter: Viatom Bluetooth protocol, written with bleak.
  • Chest belt: accelerometer stream received with websockets.
  • Other sources: Apple Health Auto Export JSON and the Home Assistant REST API.
  • Front-end: static, self-contained HTML pages with vanilla JS canvas charts (synced cursor and zoom), published atomically as immutable releases.

100% vibe-coded, and a bit more than that

SleepTrace is 100% vibe-coded. The whole pipeline I just talked about, the sensors, the parsers, the pages… all of it. Opus 5.5 and Sol 6.1 did very well.

And as a dev, of course (I still sometimes) read through the code. Honestly, nothing to flag. That doesn't mean every algorithm is medically validated (I mentioned the limits above), but code-wise, I didn't see anything that made me raise an eyebrow. It does feel quite special to watch a tool this specific to my life take shape like that :)

It makes me optimistic about the future of medicine. I'm not saying my little lab replaces a doctor. But being able to bring together what happens between appointments, better understand what we're going through, show up with data instead of an “I'm tired”… I feel like there's so much we can do. After all those years of not understanding, it gives me a bit of hope :)

And I don't even have the lifestyle you'd typically associate with OSA. I work out, eat well, don't drink, don't smoke, don't even snore… so for years, sleep apnea just wasn't on my radar.

That's the part I keep thinking about. If I'd had the tech to figure this out when I was younger, I really don't think I would have had the same life.

My studies, work, relationships… all those years where I thought being exhausted was just who I was. I can't redo them, but the idea that someone else might get an answer earlier makes me pretty optimistic :)

What's next

I'm still waiting for my MAD [18], and I'm curious to try it. But as I've already waited for more than a month, I don't regret using a CPAP for now. And when I receive it, I'll be able to reproduce the same tuning process for the MAD.

But honestly, the real next step isn't technical.
It's grieving all those “lost” years. Years where I was there, but not really there… tired, grumpy, absent. I can't get them back, and that's kind of hard to accept.

But I was able to refocus on my life, what I truly want, etc. Instead of surviving, I'm simply living.
Now I just want to make the most of the years to come :)

Sources
  1. Wikipedia: Orthosomnia
  2. Reddit: r/brainfog
  3. Wikipedia: Mouth taping
  4. Singh S et al. Blue-light filtering spectacle lenses for visual performance, sleep, and macular health in adults. Cochrane Database Syst Rev, 2023
  5. Wikipedia: Light therapy
  6. Wikipedia: Melatonin as a medication and supplement
  7. Wikipedia: Glycine
  8. Wikipedia: Withania somnifera
  9. Wikipedia: Magnesium glycinate
  10. Wikipedia: Gamma-Aminobutyric acid
  11. Wikipedia: Obstructive sleep apnea (Medication and lifestyle)
  12. Wikipedia: Sleep study (Home sleep test)
  13. Wikipedia: Apnea–hypopnea index
  14. Wikipedia: Polysomnography
  15. Kapur VK et al. Clinical Practice Guideline for Diagnostic Testing for Adult Obstructive Sleep Apnea: an AASM Clinical Practice Guideline. J Clin Sleep Med, 2017
  16. Wikipedia: Obstructive sleep apnea (Criteria)
  17. Wikipedia: Rapid eye movement sleep
  18. Wikipedia: Mandibular advancement splint
  19. Wikipedia: Continuous positive airway pressure
  20. Wikipedia: Obstructive sleep apnea
  21. Wikipedia: Large language model
  22. Wikipedia: Aerophagia
  23. Wikipedia: Central sleep apnea
  24. Wikipedia: API
  25. Wikipedia: Bluetooth Low Energy
  26. Comparison of ResMed AutoSet (version 3.03) with polysomnography in the diagnosis of the sleep apnoea/hypopnoea syndrome. Eur Respir J, 1997
  27. Lanthier M et al. Assessing the performance of a portable electroencephalographic sleep monitor against level 1 polysomnography. Sleep Advances, 2025
  28. Apple. Estimating Sleep Stages from Apple Watch (white paper), October 2025
  29. Schyvens AM et al. A performance validation of six commercial wrist-worn wearable sleep-tracking devices for sleep stage scoring compared to polysomnography. Sleep Advances, 2025
  30. Sensirion. SCD40 CO₂ sensor datasheet
  31. OSCAR: Open Source CPAP Analysis Reporter