# Custom OEE Tags

Kanoa writes each OEE asset's `Current Run` and `Current Shift` to the [kanoaMES OEE tags](../configuration/kanoa-tags.md#asset-oee-tags). When you want other windows, such as the last 7 days or this month, or one figure for a group of assets, build your own tags: a folder of memory tags in the `Kanoa` provider, and a [tagTimer](../configuration/kanoa-tags.md#tagtimer) that recalculates them on an interval.

This page builds `Molding Last 7 Days`, combining two presses. Repeat it for each window or group you need.

## 1. Add the Script

In the project set as the Gateway Scripting Project, create a script library named `customOEE` with this function. It reads the folder's settings, gets each asset's OEE for the range with [`getOEESummary`](../systemFunctions/event/getOEESummary.md), combines them, and writes the results back to the folder.

```python
def update(basePath):
    """Recalculate one custom OEE folder, e.g. '[Kanoa]Analysis/Molding Last 7 Days'."""
    assetPaths, dateRange, timeZone = [qv.value for qv in system.tag.readBlocking(
        [basePath + '/assetPaths', basePath + '/dateRange', basePath + '/timeZone'])]
    startDate, endDate = system.kanoa.date.getDateRange({'selectedDateRange': dateRange, 'clientTimeZone': timeZone})

    timeCols = ['runtimeSecs', 'unplannedDowntimeSecs', 'plannedDowntimeSecs']
    countCols = ['infeedCount', 'outfeedCount', 'wasteCount']
    headers = ['assetPath'] + timeCols + countCols + ['availability', 'performance', 'quality', 'oee']
    totals = dict.fromkeys(timeCols + countCols, 0.0)
    idealSecs = 0.0      # Running time at the standard rate: performance x runtime
    goodIdealSecs = 0.0  # the part of idealSecs that made good parts: quality x idealSecs
    rows = []

    for assetPath in assetPaths:
        assetId = system.kanoa.asset.getAssets({'assetPath': assetPath}).getValueAt(0, 'assetId')
        data = system.kanoa.event.getOEESummary({'assetId': assetId, 'startDate': startDate, 'endDate': endDate})
        if data.rowCount == 0:
            continue
        row = dict((col, data.getValueAt(0, col) or 0.0) for col in timeCols + countCols + ['availability', 'performance', 'quality'])
        for col in timeCols + countCols:
            totals[col] += row[col]
        idealSecs += row['performance'] * row['runtimeSecs']
        goodIdealSecs += row['quality'] * row['performance'] * row['runtimeSecs']
        oee = row['availability'] * row['performance'] * row['quality']
        rows.append([assetPath] + [row[col] for col in headers[1:-1]] + [oee])

    plannedSecs = totals['runtimeSecs'] + totals['unplannedDowntimeSecs']
    availability = totals['runtimeSecs'] / plannedSecs if plannedSecs else 0.0
    performance = idealSecs / totals['runtimeSecs'] if totals['runtimeSecs'] else 0.0
    quality = goodIdealSecs / idealSecs if idealSecs else 1.0

    names = ['startDate', 'endDate'] + timeCols + countCols + ['availability', 'performance', 'quality', 'oee', 'assets', 'lastUpdated']
    values = [startDate, endDate] + [totals[col] for col in timeCols + countCols] + [
        availability, performance, quality, availability * performance * quality,
        system.dataset.toDataSet(headers, rows), system.date.now()]
    system.tag.writeBlocking([basePath + '/' + name for name in names], values)
```

## 2. Create the Tags

In the `Kanoa` provider, create a folder for your custom tags, for example `Analysis`, and inside it a folder named after the window: `Analysis/Molding Last 7 Days`. Add these memory tags to it.

**Settings**, which you fill in:

| Tag | Type | Example |
| --- | --- | --- |
| `assetPaths` | String Array | `CoreForge\Philadelphia\Molding\Injection Press 1`, `CoreForge\Philadelphia\Molding\Injection Press 2` |
| `dateRange` | String | `Last 7 Days`. Any range [`getDateRange`](../systemFunctions/date/getDateRange.md) accepts apart from `Current Run`, `Current Shift` and `Previous Shift`, which belong to one asset |
| `timeZone` | String | `America/New_York`, the site's time zone. It sets where `Today` or `This Week` start |

**Results**, which the script writes:

| Tag | Type | What it holds |
| --- | --- | --- |
| `startDate`, `endDate` | DateTime | The window the results cover |
| `runtimeSecs`, `unplannedDowntimeSecs`, `plannedDowntimeSecs` | Float | Times, added up across the assets |
| `infeedCount`, `outfeedCount`, `wasteCount` | Float | Counts, added up across the assets |
| `availability`, `performance`, `quality`, `oee` | Float | The combined OEE factors, 0 to 1 |
| `assets` | Dataset | One row per asset with its own times, counts and OEE |
| `lastUpdated` | DateTime | When the script last ran |

The result tags use the same names as `OEE/Current Run`, so a screen built for one asset's current run can show them too.

## 3. Add the Timer

Add a `tagTimer` instance to the folder, from `[Kanoa]_types_/Kanoa`, and name it `timer`. Override its `update` tag's value changed script, replacing the `pass` line with:

```python
customOEE.update('[Kanoa]Analysis/Molding Last 7 Days')
```

Set `intervalSecs` and turn on `enable`. Write `true` to `update` to run it straight away, and check its `error` tag if the results don't fill in.

Choose the interval for the window. A 7-day window barely moves in a minute, and each run queries every asset over the whole range, so 300 to 900 seconds is plenty. Keep 60 seconds for short windows like `Today` or `Last 24 Hrs`.

:::tip[Read the timer's own tags]
A timer's `error` and `lastUpdated` tags show whether its last run worked. Set its `debug` tag to `true` to log how long each run takes, which is worth checking for a long window over many assets.
:::

## How the Assets Are Combined

The combined OEE isn't the average of each asset's OEE. An idle press with a high OEE would pull the figure up as much as a busy one. Instead, each factor is weighted by the time behind it:

| Factor | Combined as |
| --- | --- |
| Availability | Total Running time ÷ total Running and unplanned downtime |
| Performance | Each asset's performance weighted by its Running time |
| Quality | Each asset's quality weighted by its Running time at the standard rate (performance × Running time) |
| OEE | Availability × Performance × Quality |

This gives the same answer as treating the assets as one: the time spent making good parts at the standard rate, as a share of the time they should all have been running.

:::warning[Counts in different units]
The counts are added up as they are. If the assets count in different units, for example parts on one and kilograms on another, the totals are meaningless. The OEE factors are still right, because they don't depend on the units.
:::
