blood-sugar-management
How to Create a Custom Dashboard for Monitoring Openaps Data in Real-time
Table of Contents
Why Build a Custom OpenAPS Dashboard?
Managing type 1 diabetes with an OpenAPS (Open Artificial Pancreas System) setup produces a constant stream of data—blood glucose values, insulin-on-board, reservoir levels, battery status, and system alarms. Off-the-shelf diabetes applications often lack the flexibility to present this information exactly as you need it, especially when you want to correlate multiple metrics in a single view. Building a custom real-time dashboard gives you full control over layout, update frequency, alert thresholds, and data persistence. This guide walks you through the entire process, from accessing raw OpenAPS data to deploying a production-ready monitoring interface that you can trust for daily use. You will learn how to design a dashboard that fits your workflow, integrate real-time updates, and avoid common pitfalls that can compromise reliability.
Many existing tools like Nightscout offer a baseline of functionality, but they may not expose every raw data point you care about, or they force you into a particular visual design. A custom dashboard lets you strip away unnecessary elements and focus on what matters most to you. For example, you can highlight trend arrows and IOB numbers in large fonts for quick glances, while still providing detailed history graphs for deeper analysis. The goal is to build something that becomes a natural part of your daily management routine—something that reduces cognitive load rather than adding to it.
Understanding OpenAPS Data Sources
Before writing any code, you need to know where your OpenAPS data lives. The system runs on a Raspberry Pi (or similar single-board computer) executing a closed-loop algorithm that communicates with a continuous glucose monitor (CGM) and an insulin pump. The key data points include:
- Blood glucose (BG) readings – typically every 5 minutes from the CGM (e.g., Dexcom, Medtronic).
- Insulin delivery history – temp basal rates, boluses, and insulin-on-board (IOB) calculations.
- System status – loop state (enabled/disabled), pump battery, reservoir volume, and sensor age.
- Alerts and errors – out-of-range BG, low battery, communication failures.
OpenAPS stores this data locally in JSON files (e.g., pumphistory.json, glucose.json) and also exposes it through a built-in REST API on the rig’s local network. The API is the preferred method for real-time dashboards because it allows secure, request-based access without touching the filesystem directly. Refer to the official OpenAPS API documentation for endpoint details and authentication options. Additionally, some users rely on MQTT bridges to publish OpenAPS data to a broker, which can then be subscribed to by multiple dashboard instances. This approach is especially useful in multi-rig or caregiver scenarios.
One common mistake is assuming the data will always be available in real time. In practice, the CGM transmitter may temporarily lose connection, the pump may fail to acknowledge a command, or the Raspberry Pi might run out of memory. Your dashboard must handle all these edge cases gracefully. Always validate timestamps and reject stale readings. Build in warnings when data does not arrive as expected, and log such events for later review.
Technology Stack Overview
Your dashboard will be a web application running on a server or a cloud platform. The typical stack includes:
- Backend – a lightweight server (Node.js, Python Flask, or Go) that proxies requests to the OpenAPS rig and optionally caches data.
- Frontend – a single-page application built with React, Vue.js, or plain JavaScript.
- Data visualization – a library such as Chart.js, D3.js, or ApexCharts for graphing BG trends and insulin delivery.
- Real-time updates – achieved through periodic polling (setInterval) or persistent WebSocket connections.
- Hosting – a VPS, Raspberry Pi (local), or a serverless platform (e.g., Vercel, Netlify) with WebSocket support.
If you prefer to avoid building a full backend, you can host the dashboard entirely on the rig itself using a static site generator that fetches data directly from the rig’s API (CORS must be enabled). Choose the approach that best matches your network security requirements and personal comfort level. Many developers start with polling and later switch to WebSockets for reduced latency. For low-power environments, consider using a binary protocol like Protocol Buffers over WebSockets to minimize bandwidth.
A growing trend is to combine the dashboard with a time-series database such as InfluxDB or TimescaleDB. This gives you the ability to zoom far back in time (weeks or months) while still offering live updates. The backend can batch-write recent data points into the database and serve historical queries from it, reducing load on the OpenAPS rig. This approach is especially valuable if you want to perform retrospective analysis or share aggregated data with your endocrinologist.
Step 1: Accessing OpenAPS Data via API
The OpenAPS rig listens for HTTP requests on port 8080 by default. To fetch glucose data, call GET /api/v1/glucose.json. The response contains an array of recent BG readings with timestamps and trend directions. Similarly, GET /api/v1/status.json returns the current loop status, IOB, battery level, and more. Test these endpoints with tools like curl or Postman to confirm the data format and update frequency. Pay special attention to the timestamp format—OpenAPS typically uses Unix epoch in milliseconds or seconds, so you may need to convert to JavaScript Date objects on the frontend.
If your rig is behind a firewall or you need remote access, consider using a secure tunnel (e.g., ngrok) or a VPN. Never expose the OpenAPS API directly to the public internet without authentication. For production dashboards, implement a proxy server that adds an API key, validates requests, and throttles traffic to prevent abuse. You can also use a VPN server on the Raspberry Pi itself, allowing only encrypted connections to the API endpoint. This is a good balance between convenience and security.
Another consideration is the rate at which you poll the API. The OpenAPS rig can handle a few requests per second, but constant hammering may interfere with the loop algorithm. A safe polling interval is every 5 to 10 seconds. If you need faster updates, use WebSockets instead, which push data only when the rig updates. Many rigs can be configured to emit a WebSocket message each time new glucose data is recorded, giving you near-instantaneous updates without wasting resources on idle polling.
Step 2: Designing the Dashboard Layout
Start with a wireframe that places the most critical metric—current blood glucose—at the top or center. Common dashboard layouts for diabetes monitoring include:
- Top row – BG value (large), trend arrow, time since last reading.
- Second row – IOB, current basal rate, reservoir level.
- Main area – a 3‑hour or 24‑hour BG chart with color-coded zones (yellow for caution, red for danger).
- Side panel – recent alerts and system health indicators (battery, sensor age).
Use responsive CSS frameworks like Bootstrap or Tailwind CSS to ensure the dashboard works on mobile screens—many users want to glance at it from their phone. Consider using a dashboard-specific library like GridStack.js to allow drag-and-drop layout customization, enabling you to rearrange widgets as priorities change. For example, during exercise you might want to enlarge the BG chart and reduce the IOB display. A grid system also makes it easier to add new widgets later without breaking the layout.
Accessibility is critical. Use high-contrast color schemes that are still distinguishable for colorblind users (avoid relying on red/green alone). Add text labels next to color indicators. Consider using a dark mode for nighttime viewing. Place the most important information where it catches the eye first—usually the upper left for left-to-right languages. Test the layout on various screen sizes, especially the phone you use most often. You may find that a portrait orientation is more natural for mobile, while landscape serves better on a tablet mounted on your desk.
Step 3: Building the Backend Proxy (Optional but Recommended)
A backend proxy adds a layer of security and caching. For example, a Node.js Express server can:
- Fetch OpenAPS data every 5 seconds (or as fast as the rig updates).
- Store the latest state in memory to reduce load on the rig and provide instant responses to the frontend.
- Expose endpoints like
/api/glucoseand/api/statusto the frontend. - Add CORS headers and rate limiting.
Here’s a minimal Node.js snippet using node-fetch:
const express = require('express');
const fetch = require('node-fetch');
const app = express();
let cache = {};
setInterval(async () => {
const res = await fetch('http://openaps-rig:8080/api/v1/status.json');
cache.status = await res.json();
}, 5000);
app.get('/api/status', (req, res) => res.json(cache.status));
app.listen(3000);
This approach also lets you aggregate data from multiple rigs if you have a spare system or are monitoring another person’s loop. For additional security, implement JWT-based authentication on the proxy endpoints. You can also integrate a simple in-memory cache that stores the last 24 hours of data so the frontend can request historical ranges without hitting the rig repeatedly.
When writing the proxy, pay attention to error handling. If the rig is unreachable, the proxy should return a cached version (or a 503) rather than crashing. Log all errors to a file or a monitoring service. You may also want to expose a health check endpoint that other monitoring tools (like UptimeRobot) can ping to verify the proxy and rig are both alive.
Step 4: Frontend Implementation with Real-Time Updates
Use a modern JavaScript UI library to manage state and re-render components efficiently. React is a popular choice because of its lifecycle methods and hooks. Create a Dashboard component that calls your backend every 5 seconds (useEffect with setInterval) and updates the state. For true real-time experiences, replace polling with a WebSocket connection—both Node.js and Python support this easily using libraries like ws or socket.io. WebSockets reduce bandwidth and latency, which is important when you need immediate alerts for hypoglycemia. However, they add complexity in deployment (some hosting platforms charge extra for WebSocket support).
For charting, install Chart.js (with the React wrapper react-chartjs-2) or ApexCharts for smoother animations. Plot BG values on a line chart with a time X-axis and glucose Y-axis. Overlay the insulin delivery as a bar chart or area to show correlations. Color each data point based on the trend arrow direction (flat, up, down). You can also add a shaded region for target range (e.g., 70-180 mg/dL) to make it immediately obvious when the user is out of range. For performance, limit the number of displayed data points to the most recent 288 (one day of 5-minute readings) to avoid slow rendering.
Don’t forget to handle missing data gracefully—show a “stale data” warning if the last reading is older than 10 minutes. Implement reconnection logic if WebSocket drops, and always display the timestamp of the last successful update. Use a loading spinner during the initial fetch, and show a clear error message if the backend is unreachable. For mobile devices, consider using a service worker to cache the latest data offline, so the dashboard still shows the last known state even without a network connection.
Step 5: Deployment and Hosting Options
You have several viable deployment targets:
- Local Raspberry Pi – run the dashboard server on the same Pi as OpenAPS. This is the simplest and most private. Access it via a local IP like
http://192.168.1.100:3000. Be aware that running both OpenAPS and a dashboard server on the same Pi can strain the hardware if you add too many features. Consider using a separate Pi Zero 2 W for the dashboard. - Cloud VPS (DigitalOcean, AWS, Linode) – use a minimal Ubuntu droplet, install Node.js or Python, and run the app behind a reverse proxy (Nginx) with SSL. This lets you view the dashboard from anywhere but requires security hardening (firewall, fail2ban, HTTPS). Use a tool like Let's Encrypt to obtain free SSL certificates.
- Serverless platforms (Vercel, Netlify, Cloudflare Workers) – good for static frontends, but they struggle with persistent WebSocket connections. You would need to rely on polling and a separate backend for data aggregation. You can also use Cloudflare Workers with Durable Objects for WebSocket support, but that adds complexity and cost.
For remote access without a public IP, consider using ngrok to create a secure tunnel to your local dashboard. Pair it with an authentication layer (HTTP basic auth or token-based) to prevent unauthorized viewing. Alternatively, set up a WireGuard VPN to your home network. WireGuard is lightweight and secure, and it can be configured on a low-power device like a Raspberry Pi. This gives you encrypted access to your local dashboard from any device while keeping the data off public servers.
If you choose to host in the cloud, be mindful of HIPAA or GDPR regulations if you are handling health data. At a minimum, encrypt data in transit (TLS) and at rest (encrypted database). Consider data retention policies: you may not need to store more than a few weeks of historical readings on a cloud server. Regularly purge old data to minimize risk.
Best Practices for Diabetes Data Monitoring
Your dashboard will be used for life-critical decisions, so reliability and accuracy are essential. Follow these guidelines:
- Redundancy – if the dashboard fails, the user should still get alerts from their CGM receiver or pump. Never rely solely on a custom dashboard for alarms. The dashboard should serve as a complementary tool, not a primary alerting system.
- Data validation – reject readings with impossible values (e.g., BG < 20 mg/dL or > 600 mg/dL). Display a warning if data seems corrupt. Implement sanity checks on IOB (should not exceed known maximums).
- Time zone handling – use UTC for storage and convert to the user’s local time on the frontend. OpenAPS timestamps are typically UTC. Be careful with daylight saving time transitions; always store and process timestamps in UTC to avoid ambiguity.
- Accessibility – use high-contrast colors, large fonts, and optional sound alerts (via Web Audio API) for critical lows. Also consider haptic feedback on mobile devices using the Vibration API.
- Logging – record historical data for later review (e.g., CSV exports). A time-series database like InfluxDB can be connected for long-term analytics and trend analysis. Set up automated daily backups of the database.
Test your dashboard under real-world conditions: what happens when the rig reboots? What if the pump runs out of insulin? Simulate these scenarios to ensure the dashboard recovers without manual intervention. Implement health check endpoints that can be monitored externally. Run the dashboard for a week before trusting it for critical use. Have a fallback plan—keep the official CGM display app open on your phone alongside your custom dashboard.
Advanced Features to Consider
Once you have a basic dashboard running, consider adding these enhancements:
- Predictive lines – use a simple linear regression on past BG readings to project the next 30 minutes. More advanced users can integrate machine learning models via a separate microservice. Clearly label predictions as such to avoid confusion with actual readings.
- Voice announcements – integrate the browser’s speech synthesis to read out current BG and IOB every 10 minutes, which is helpful during physical activity. Allow the user to choose a quiet mode (no speech) for nighttime or meetings.
- Remote control – with extreme caution, you could add buttons to trigger temporary basals or snooze alarms through the OpenAPS API. This requires rigorous authentication and a confirmation dialog to prevent accidental changes. Log every remote action with a timestamp and user identity.
- Multi-user support – allow caregivers to view the dashboard from their own devices with different permissions (e.g., read-only for parents, full control for the primary user). Implement role-based access control (RBAC) on the backend. Use secure password hashing (bcrypt) and session management.
Each of these features adds complexity and potential risk. Always test in a safe environment (e.g., using historical data or a rig running in “enacted” but safe mode) before relying on them for everyday use. Consider using feature flags to roll out new capabilities gradually. For example, you could enable predictive lines for a subset of users first and gather feedback before enabling for everyone.
Troubleshooting Common Issues
During development, you may encounter several common problems. Here are solutions:
- Data not updating – Check network connectivity between the dashboard server and the rig. Verify that the OpenAPS API is responding by curling the endpoint directly. Ensure CORS headers are set if making cross-origin requests. Check firewall rules and that the rig's port 8080 is accessible.
- Stale data warnings – If readings are older than expected, increase the polling interval or reduce the cache TTL. Also confirm that the CGM device is transmitting correctly. Review the rig's logs for any errors related to the CGM receiver.
- WebSocket disconnects – Implement automatic reconnection with exponential backoff. Check for proxy settings or firewall rules that may drop idle connections. Use WebSocket-level keep-alive pings every 30 seconds.
- Charts not rendering – Validate the JSON data structure. Use console logs to inspect the data before passing it to the charting library. Ensure timestamps are in a format that the library expects (e.g., milliseconds for Chart.js). Check that your chart component is re-rendering on state changes.
Add logging to both the backend and frontend to capture error conditions. Consider setting up a monitoring service like UptimeRobot for the dashboard itself. Create a simple “health” page that lists all known statuses (rig reachable, last data update, WebSocket status) so you can quickly diagnose problems. Keep a development environment separate from production to test changes safely.
Conclusion
A custom OpenAPS dashboard is more than a technical exercise—it’s a tool that can improve your confidence and quality of life by putting actionable data at your fingertips. Start small: fetch one endpoint and display a single graph. Then iterate by adding more metrics, alerts, and visual refinements. The combination of OpenAPS’s open data and modern web technologies gives you unparalleled flexibility to create exactly the monitoring experience you need. With careful design and rigorous testing, your dashboard can become a reliable companion for managing diabetes in real time. Remember that the ultimate goal is not just to display numbers, but to help you make informed decisions quickly and confidently. Share your dashboard with your healthcare team and ask for feedback—they may spot features that improve your daily management even further.