# Build a Sensor Dashboard

> Build an application from a Worker, a Function, an API, and an App that read a sensor, summarize its readings, and show them on a live page.

URL: https://www.trakhound.com/docs/trakhound-framework/tutorials/sensor-dashboard

In this tutorial you'll build an application from four Packages: a Worker that reads a sensor, a Function that summarizes its readings, an API that serves them, and an App that shows them on a page that updates itself. You'll run each one on your computer, then install all four on an Instance. It takes about 30 minutes.

Diagram: On the Instance, the Worker reads a sensor and writes the recent readings to the linemonitor Volume. The API and the Function read the same Volume. The App calls the API through its Client, and the API runs the Function to summarize the readings.

## Before You Start

Complete the [Quick Start](https://www.trakhound.com/docs/trakhound-framework/getting-started) first. You'll need the same .NET 10 SDK, Instance, TrakHound CLI (`th`), and templates, and you should know how to build a Package and upload it.

> The finished code is the `TrakHound.Example` Packages in the Framework repository's [examples](https://github.com/TrakHound/TrakHound.Framework/tree/main/examples) folder (see [First-Party Packages](https://www.trakhound.com/docs/trakhound-framework/first-party-packages)). This tutorial uses the name `LineMonitor` so your Packages don't conflict with the examples if they're installed.

## What You'll Build

| Package | Kind | Its job |
| --- | --- | --- |
| `LineMonitor.Worker` | [Worker](https://www.trakhound.com/docs/trakhound-framework/workers) | Runs all the time. Reads a (simulated) sensor every 5 seconds and writes the recent readings to the `linemonitor` Volume. |
| `LineMonitor.Summary` | [Function](https://www.trakhound.com/docs/trakhound-framework/functions) | Runs when it's asked. Calculates the count, minimum, maximum, and average of the last few minutes of readings. |
| `LineMonitor.Api` | [API](https://www.trakhound.com/docs/trakhound-framework/apis) | Serves the readings and the summary at `/linemonitor/api`, for the App, other systems, and AI assistants. |
| `LineMonitor.App` | [App](https://www.trakhound.com/docs/trakhound-framework/apps) | Shows the latest reading, a summary, and recent readings at `/linemonitor`. It only talks to the API. |

Each Package can be updated, restarted, and secured on its own. The App never reads the Volume directly, so you can change how readings are stored without changing the App, and anything the App can show is also available from the API.

## 1. Create the Projects

Create a folder for the application, and a project for each Package in it:

```
mkdir LineMonitor
cd LineMonitor
dotnet new trakhound.worker -n LineMonitor.Worker
dotnet new trakhound.function -n LineMonitor.Summary
dotnet new trakhound.api -n LineMonitor.Api
dotnet new trakhound.app -n LineMonitor.App
```

Each command creates a folder with the project, its `trakhound.package.json` manifest, and a `trakhound.debug.json` for running it on your computer.

## 2. Share the Reading Model

All four Packages use the same reading. Create `LineMonitor.Worker/SensorReading.cs`:

```
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using TrakHound.Volumes;

namespace LineMonitor
{
    public class SensorReading
    {
        // The file in the shared Volume that the Worker writes the recent Readings to (oldest first)
        public const string ReadingsPath = "readings.json";

        public DateTime Timestamp { get; set; }

        public double Value { get; set; }


        // Reads the recent Readings from the Volume. Returns an empty list if there are none yet
        public static async Task<List<SensorReading>> ReadAll(ITrakHoundVolume volume)
        {
            if (volume == null) return new List<SensorReading>();

            try
            {
                return await volume.ReadJson<List<SensorReading>>(ReadingsPath) ?? new List<SensorReading>();
            }
            catch
            {
                // The Worker may be writing the file
                return new List<SensorReading>();
            }
        }
    }
}
```

Link the file into the other three projects by adding this to `LineMonitor.Summary.csproj`, `LineMonitor.Api.csproj`, and `LineMonitor.App.csproj`:

```
<ItemGroup>
    <Compile Include="..\LineMonitor.Worker\SensorReading.cs" Link="SensorReading.cs" />
</ItemGroup>
```

A linked file is compiled into each Package, so there's no shared library to install. If you change it, rebuild every Package that uses it.

### Use the Same Volume

The Worker, Function, and API share data through a [Volume](https://www.trakhound.com/docs/trakhound-framework/volumes-and-variables). Give each of them the same default Volume by adding `.defaultVolumeId` to `metadata` in its `trakhound.package.json`:

```
"metadata": {
    ...
    ".defaultVolumeId": "linemonitor"
}
```

When you run them on your computer, point them at the same folder instead by adding `volumePath` to the `trakhound.debug.json` of the same three projects. The path is relative to the build output (`bin/Debug/net10.0`), so this is a `volume` folder in `LineMonitor`:

```
"volumePath": "../../../../volume",
```

## 3. Write the Worker

Replace `LineMonitor.Worker/Worker.cs`:

```
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using LineMonitor;
using TrakHound;
using TrakHound.Workers;

public class Worker : TrakHoundWorker
{
    private const int DefaultInterval = 5000;
    private const int HistorySize = 720; // 1 hour at the default interval

    private readonly Random _random = new Random();
    private readonly List<SensorReading> _readings = new List<SensorReading>();

    private CancellationTokenSource _stop;
    private Task _loop;


    public Worker(ITrakHoundWorkerConfiguration configuration) : base(configuration) { }


    protected override async Task OnStartAsync()
    {
        var interval = Configuration.GetParameter<int>("interval");
        if (interval <= 0) interval = DefaultInterval;

        // Continue from the Readings written before a restart
        _readings.AddRange(await SensorReading.ReadAll(Volume));

        _stop = new CancellationTokenSource();
        _loop = Run(TimeSpan.FromMilliseconds(interval), _stop.Token);
    }

    protected override async Task OnStopAsync()
    {
        _stop.Cancel();
        await _loop;
        _stop.Dispose();
    }

    private async Task Run(TimeSpan interval, CancellationToken cancellationToken)
    {
        using var timer = new PeriodicTimer(interval);
        try
        {
            while (await timer.WaitForNextTickAsync(cancellationToken))
            {
                try
                {
                    _readings.Add(ReadSensor());
                    if (_readings.Count > HistorySize) _readings.RemoveRange(0, _readings.Count - HistorySize);

                    await Volume.WriteJson(SensorReading.ReadingsPath, _readings);
                }
                catch (Exception ex)
                {
                    // Log and continue, so one failure doesn't stop the Worker
                    Log(TrakHoundLogLevel.Error, ex.Message);
                }
            }
        }
        catch (OperationCanceledException) { }
    }

    // A temperature that rises and falls over 10 minutes. A real Worker would read a device here
    private SensorReading ReadSensor()
    {
        var now = DateTime.UtcNow;
        var cycle = now.TimeOfDay.TotalMinutes / 10 * 2 * Math.PI;
        var value = 20 + 5 * Math.Sin(cycle) + (_random.NextDouble() - 0.5);

        return new SensorReading { Timestamp = now, Value = Math.Round(value, 2) };
    }
}
```

Run it, and leave it running while you build the rest:

```
cd LineMonitor.Worker
dotnet run
```

Every 5 seconds the Worker adds a reading to `LineMonitor/volume/readings.json`.

## 4. Write the Function

Replace `LineMonitor.Summary/Function.cs`:

```
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using LineMonitor;
using TrakHound;
using TrakHound.Functions;

[FunctionParameter("minutes", Description = "How many minutes of Readings to summarize", Type = TrakHoundFunctionParameterType.Integer, DefaultValue = "10")]
public class Function : TrakHoundFunction
{
    public Function(ITrakHoundFunctionConfiguration configuration) : base(configuration) { }

    protected override async Task<TrakHoundFunctionResponse> OnRun(IReadOnlyDictionary<string, string> parameters, CancellationToken cancellationToken)
    {
        if (!int.TryParse(parameters.GetValueOrDefault("minutes"), out var minutes) || minutes <= 0)
        {
            return BadRequest("minutes must be a whole number greater than 0");
        }

        var from = DateTime.UtcNow.AddMinutes(-minutes);
        var readings = (await SensorReading.ReadAll(Volume)).Where(o => o.Timestamp >= from).ToList();

        if (readings.Count == 0) return NotFound("No Readings found. Is LineMonitor.Worker running with the same Volume?");

        // Response Parameters are strings, read by name by whatever runs the Function
        var response = Ok();
        response.AddParameter("count", readings.Count.ToString(CultureInfo.InvariantCulture));
        response.AddParameter("minimum", readings.Min(o => o.Value).ToString(CultureInfo.InvariantCulture));
        response.AddParameter("maximum", readings.Max(o => o.Value).ToString(CultureInfo.InvariantCulture));
        response.AddParameter("average", Math.Round(readings.Average(o => o.Value), 2).ToString(CultureInfo.InvariantCulture));
        return response;
    }
}
```

`[FunctionParameter]` describes the input, so the admin UI shows a field for it and the Instance fills in the default. In `LineMonitor.Summary/trakhound.debug.json`, change `input` to the parameter the Function now takes:

```
"input": {
    "minutes": "10"
}
```

In a second terminal, run it once:

```
cd LineMonitor.Summary
dotnet run
```

It prints the Response with the `count`, `minimum`, `maximum`, and `average` of the readings the Worker has written so far.

## 5. Write the API

Replace `LineMonitor.Api/Controller.cs`:

```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using LineMonitor;
using TrakHound;
using TrakHound.Api;

public class Controller : TrakHoundApiController
{
    private const string DefaultFunctionId = "LineMonitor.Summary";


    [ApiGet("readings/latest", Description = "Gets the most recent sensor Reading.")]
    [ApiMcpTool]
    public async Task<TrakHoundApiResponse> GetLatestReading()
    {
        var reading = (await SensorReading.ReadAll(Volume)).LastOrDefault();
        return reading != null ? Ok(reading) : NotFound("No Readings found. Is LineMonitor.Worker running with the same Volume?");
    }

    [ApiGet("readings", Description = "Lists the most recent sensor Readings, newest first.")]
    [ApiMcpTool]
    public async Task<TrakHoundApiResponse> GetReadings(
        [FromQuery(Description = "The most Readings to return (1 to 1,000)")] int take = 100)
    {
        var readings = await SensorReading.ReadAll(Volume);
        return Ok(Enumerable.Reverse(readings).Take(Math.Clamp(take, 1, 1000)));
    }

    [ApiGet("summary", Description = "Gets the count, minimum, maximum, and average of the recent Readings.")]
    [ApiMcpTool]
    public async Task<TrakHoundApiResponse> GetSummary(
        [FromQuery(Description = "How many minutes of Readings to summarize")] int minutes = 10)
    {
        // The "functionId" parameter in the API's configuration, for when the Function was added with a different ID
        var functionId = Configuration?.GetParameter("functionId");
        if (string.IsNullOrEmpty(functionId)) functionId = DefaultFunctionId;

        var response = await Client.Functions.Run(functionId, new Dictionary<string, string> { ["minutes"] = minutes.ToString() });
        if (!response.Success)
        {
            var message = response.GetParameter("message") ?? $"{functionId} returned {response.StatusCode}";
            return new TrakHoundApiResponse(response.StatusCode, message.ToUtf8Bytes(), "text/plain");
        }

        return Ok(response.Parameters);
    }
}
```

The API doesn't calculate the summary itself: it runs the Function, so the same calculation can also be run from the admin UI, on a schedule, or by an AI assistant. `[ApiMcpTool]` offers each endpoint to AI assistants through the Instance's [MCP Server](https://www.trakhound.com/docs/trakhound-framework/mcp-server).

In a second terminal, run it and call it:

```
cd LineMonitor.Api
dotnet run
```

```
curl http://localhost:5091/readings/latest
{"timestamp":"2026-11-11T19:30:05.0012345Z","value":22.41}

curl "http://localhost:5091/readings?take=3"
```

`summary` runs the Function on the Instance in `trakhound.debug.json`, so it returns an error until you install the Function in step 7. Open the Api Debugger at `http://localhost:5091/_debug` to see the endpoints and their descriptions. Stop the API with Ctrl+C.

## 6. Write the App

The template's default route is `linemonitor/app`. To serve the App at `/linemonitor`, change `.defaultRoute` in `LineMonitor.App/trakhound.package.json`, and add the other three Packages as dependencies:

```
{
  "id": "LineMonitor.App",
  "category": "app",
  "metadata": {
    ...
    ".defaultName": "Line Monitor",
    ".defaultRoute": "linemonitor"
  },
  "dependencies": [
    { "id": "LineMonitor.Api", "version": "0.*" },
    { "id": "LineMonitor.Summary", "version": "0.*" },
    { "id": "LineMonitor.Worker", "version": "0.*" }
  ]
}
```

With the dependencies, installing the App from a [Package server](https://www.trakhound.com/docs/trakhound-framework/packages#publishing) installs the whole application. The App finds the API through an `apiRoute` parameter. Add it to `parameters` in `LineMonitor.App/trakhound.debug.json`:

```
"parameters": {
    "apiRoute": "linemonitor/api"
},
```

Replace `LineMonitor.App/Pages/Index.razor`:

```
@page "/"
@inherits TrakHoundComponentBase
@layout Layout
@using System.Threading
@using LineMonitor

<h3>Line Monitor</h3>

@if (_error != null)
{
    <p style="color: var(--rz-danger)">@_error</p>
}

<p>Latest Reading: <b>@(_latest != null ? _latest.Value.ToString("0.00") : "--")</b></p>

<p>
    <RadzenButton Text="Summarize" Size="ButtonSize.Small" IsBusy="@_summarizing" Click="Summarize" />
    @if (_summary != null)
    {
        <span>Last 10 minutes : @_summary.GetValueOrDefault("count") readings, min @_summary.GetValueOrDefault("minimum"), max @_summary.GetValueOrDefault("maximum"), average @_summary.GetValueOrDefault("average")</span>
    }
</p>

<table>
    <thead><tr><th>Timestamp</th><th>Value</th></tr></thead>
    <tbody>
        @foreach (var reading in _readings ?? Enumerable.Empty<SensorReading>())
        {
            <tr><td>@reading.Timestamp.ToLocalTime().ToString("G")</td><td>@reading.Value.ToString("0.00")</td></tr>
        }
    </tbody>
</table>

@code {

    private readonly CancellationTokenSource _stop = new CancellationTokenSource();

    private string _apiRoute;
    private SensorReading _latest;
    private List<SensorReading> _readings;
    private Dictionary<string, string> _summary;
    private bool _summarizing;
    private string _error;


    protected override void OnInitialized()
    {
        _apiRoute = GetParameter("apiRoute");
        if (string.IsNullOrEmpty(_apiRoute)) _apiRoute = "linemonitor/api";

        _ = RefreshLoop(_stop.Token);
    }

    public override void Dispose()
    {
        _stop.Cancel();
        _stop.Dispose();
        base.Dispose();
    }

    // Reads the recent Readings from the API every 2 seconds while the page is open
    private async Task RefreshLoop(CancellationToken cancellationToken)
    {
        using var timer = new PeriodicTimer(TimeSpan.FromSeconds(2));
        try
        {
            do
            {
                try
                {
                    _readings = await Client.Api.GetJson<List<SensorReading>>(Url.Combine(_apiRoute, "readings"), new Dictionary<string, string> { ["take"] = "20" });
                    _latest = _readings?.FirstOrDefault();
                    _error = null;
                }
                catch (Exception ex)
                {
                    _error = $"Unable to read from {_apiRoute} : {ex.Message}";
                }

                await InvokeAsync(StateHasChanged);
            }
            while (await timer.WaitForNextTickAsync(cancellationToken));
        }
        catch (OperationCanceledException) { }
    }

    private async Task Summarize()
    {
        _summarizing = true;

        var response = await Client.Api.Get(Url.Combine(_apiRoute, "summary"), new Dictionary<string, string> { ["minutes"] = "10" });
        if (response.Success)
        {
            _summary = response.GetJsonContentObject<Dictionary<string, string>>();
            _error = null;
        }
        else
        {
            _error = response.GetContentUtf8String() ?? $"Summary returned {response.StatusCode}";
        }

        _summarizing = false;
    }
}
```

The App calls the API through `Client.Api`, the same way it would call any API on the Instance. The call runs as the signed-in user, so if you protect the API with a [security profile](https://www.trakhound.com/docs/trakhound-framework/security), the App's users need access to it too. You'll run the App once the API is installed, since it calls the API on the Instance.

## 7. Build and Install All Four

From the `LineMonitor` folder, build each Package into the same folder:

```
th packages dotnet LineMonitor.Worker --output ./out
th packages dotnet LineMonitor.Summary --output ./out
th packages dotnet LineMonitor.Api --output ./out
th packages dotnet LineMonitor.App --output ./out
```

Stop the Worker you started in step 3 (Ctrl+C). Then, in the admin UI, open **Packages > Upload**, drop the four `.thp` files from `out` onto the page, and click **Install 4 Packages**. The Instance adds a configuration for each Package:

| Configuration | Route / ID | Volume |
| --- | --- | --- |
| App | `linemonitor` |  |
| Api | `linemonitor/api` | `linemonitor` |
| Function | `LineMonitor.Summary` | `linemonitor` |
| Worker |  | `linemonitor` |

Open **Explorer > Workers** to check that `LineMonitor.Worker` is running. The `linemonitor` Volume on the Instance is separate from the folder you used on your computer, so the readings start again from the first one.

## 8. Open It

Open `http://localhost:8472/linemonitor`. A new reading appears every 5 seconds, and **Summarize** runs the Function through the API. The same data is available to anything that can call the API:

```
curl http://localhost:8472/linemonitor/api/readings/latest

curl "http://localhost:8472/linemonitor/api/summary?minutes=5"
{"count":"60","minimum":"18.62","maximum":"24.97","average":"21.85"}
```

You can also run `LineMonitor.Summary` by itself from **Explorer > Functions**, and see each Package's requests, runs, and logs in the Explorer. To work on the App with breakpoints now that the API is installed, run `dotnet run` in `LineMonitor.App` and open `http://localhost:5092`.

## 9. Change One Package

Each Package is updated on its own. To show more readings, change `["take"] = "20"` to `"50"` in the App's `Index.razor`, then build and install only the App as a new version:

```
th packages dotnet LineMonitor.App --output ./out --version 0.0.2
```

The Worker keeps running and the API keeps answering while the App updates. Pages that are already open show a banner that an update is available (see [Updates and Open Pages](https://www.trakhound.com/docs/trakhound-framework/apps#updates)).

## Troubleshooting

| Problem | What to do |
| --- | --- |
| The API or Function returns *No Readings found* | The Packages don't use the same Volume. Check that the Worker, Function, and API configurations all have the Volume `linemonitor` under **Config**, and that the Worker is running. |
| The App shows *Unable to read from linemonitor/api* | The API is at a different route. Set the App configuration's `apiRoute` parameter to the API's route. |
| `summary` returns 404 for the Function | The Function was added with a different ID. Set the API configuration's `functionId` parameter to it. |
| A project doesn't compile (ex. `SensorReading` not found) | Check the `<Compile Include>` path in its `.csproj` and that the file has `using LineMonitor;` (or `@using LineMonitor` in Razor). |
| A Package doesn't load | Open **Explorer > Diagnostics > Modules** to see the load error (see the [Quick Start's](https://www.trakhound.com/docs/trakhound-framework/getting-started) Troubleshooting). |

## Next Steps

[Next Tutorial: Build a Time Clock Let operators start and stop work on jobs from a station screen, and store the time in a database Table.](https://www.trakhound.com/docs/trakhound-framework/tutorials/time-clock) [Store Readings in a Database Write the readings to a Time Series Service instead of a Volume, to keep more history and query it.](https://www.trakhound.com/docs/trakhound-framework/services) [Run the Summary on a Schedule Run `LineMonitor.Summary` every hour with a CRON schedule.](https://www.trakhound.com/docs/trakhound-framework/functions) [Secure It Choose who can open the App and call the API with security profiles.](https://www.trakhound.com/docs/trakhound-framework/security) [Ask an AI Assistant Let Claude read the latest reading and the summary through the API's MCP Tools.](https://www.trakhound.com/docs/trakhound-framework/mcp-server) [Test Before Production Try new versions on a test Instance before installing them for the plant.](https://www.trakhound.com/docs/trakhound-framework/environments) [Deploy to More Instances Copy the four Packages and their configurations to other Instances with a Deployment.](https://www.trakhound.com/docs/trakhound-framework/configuration#deployments)
