> For the complete documentation index, see [llms.txt](https://docs.roboflow.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.roboflow.com/workflows/ja/chtoriaru/integrate-with-ignition/historical-data.md).

# 履歴データ

Roboflow デバイスの Event Store にある検査イベントとその画像を Ignition に表示し、履歴用にデータベースへコピーします。

Roboflowエッジデバイスは、Workflowが書き込むすべてのイベントと、その画像およびデータを [イベントストア](https://docs.roboflow.com/deployment/self-hosted/enterprise/deployment-manager/services/event-store)に保存します。IgnitionはHTTP経由で読み取るため、オペレーターは各検査とモデルが判定した画像を確認できます。

<figure><img src="https://4077895066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoO0Ceoy9R0lHDZATcPyh%2Fuploads%2Fgit-blob-d1b94701b8ac10dd6493371ce0c9802ba3ec293e%2Fignition-events-table.png?alt=media" alt="A Perspective view with a table of recent inspections from the Roboflow Event Store and the image of the selected event"><figcaption><p>イベントストアの最近の検査結果と、選択したイベントの画像。</p></figcaption></figure>

このページでは、イベントを利用する2つの方法を説明します。

* デバイスから直接Perspectiveのテーブルにイベントを表示します。最新のイベント、または現在のシフトなどの時間範囲を指定できます。Ignitionには何も保存されないため、データベースは不要です。
* ゲートウェイスクリプトを使ってすべてのイベントをデータベースにコピーし、レポートや、デバイスに保存されなくなった履歴に利用します。

代わりに最新の結果をIgnitionタグとして取得する場合（例：直近の結果や不良品数）は、 [ライブデータ](https://docs.roboflow.com/workflows/ja/chtoriaru/integrate-with-ignition/live-data.md).

## 前提条件

* デバイス上でストリームとして実行され、 [Roboflow Vision Events](https://docs.roboflow.com/workflows/ja/burokku/blocks/data-storage/roboflow-vision-events.md) ブロックで「Write to Local Event Store」が有効になっているWorkflow。このモードでは、ブロックは各イベントをデバイスのイベントストア（ `http://localhost:8001` ）に書き込みます。Roboflow APIキーは不要です。
* Ignitionゲートウェイがポート `8001`.
* データベースを使用する場合は、Ignitionでデータベース接続を設定しておく必要があります。

{% hint style="info" %}
以下の手順とスクリーンショットはIgnition 8.1（Designer 8.1.55）を使用しています。メニュー名、ダイアログ、プロパティ名は、8.3を含む他のバージョンでは異なる場合があります。
{% endhint %}

## イベントを確認する

ブラウザーで `http://<device-ip>:8001/v2/events?limit=5` を開きます。レスポンスには、新しい順にイベントが表示されます。

```json
{
  "events": [
    {
      "id": "3714e263-8159-4748-83db-ad804dde25cc",
      "stream_id": "bottle-line-1",
      "event_schema": "quality_check",
      "event_data": {"result": "fail", "externalId": "CASE-20437"},
      "custom_metadata": {"bottleCount": 11, "line": "Line 1"},
      "images": [{"file_id": "a1f0c2...", "label": "workflow"}],
      "created_at": "2026-11-13T15:42:10.512Z"
    }
  ],
  "count": 1,
  "next_timestamp": "2026-11-13T15:42:10.512Z"
}
```

`event_data` には、ブロックで選択したイベントタイプのフィールドが含まれます（例：Quality Checkの場合は「Result」と「External ID」）。また、 `custom_metadata` には、ブロックの「Custom Metadata」が含まれます。各画像は `http://<device-ip>:8001/images/<file_id>`で提供されます。詳しくは [イベントストアREST API](https://docs.roboflow.com/deployment/self-hosted/enterprise/deployment-manager/services/event-store/rest-api).

## Perspectiveに最近のイベントを表示する

1. Perspectiveビューに「Table」コンポーネントを追加します。
2. テーブルの `props.data` の横にあるバインディングアイコンをクリックし、「HTTP」を選択します。
   * URL： `"http://<device-ip>:8001/v2/events?limit=20"`URLは式なので、引用符で囲みます。
   * メソッド： `GET`.
   * 「Polling」を有効にし、値を次のように設定します `5` 秒。
   * 「キャッシュと共有」を有効にすると、ビューを表示するすべてのセッションに対して、1 回のリクエストでデータを取得できます。

<figure><img src="https://4077895066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoO0Ceoy9R0lHDZATcPyh%2Fuploads%2Fgit-blob-a642b31e56d24007c5f9e72da1b151e9a1c64fcc%2Fignition-designer-http-binding.png?alt=media" alt="The Edit Binding dialog for Events.props.data with an HTTP binding: a URL expression to port 8001, Method GET, Cache and Share and Polling every 5 seconds turned on, and a binding preview of the response"><figcaption><p>HTTP バインディングです。プレビューには、Event Store の応答と、変換処理で生成される行が表示されます。</p></figcaption></figure>

3. 「変換を追加」をクリックし、「スクリプト」を選択して、各イベントを行に変換するスクリプトを貼り付けます。

```python
def transform(self, value, quality, timestamp):
    if value is None:
        return []
    return [
        {
            "time": e["created_at"][11:19],
            "case": e["event_data"].get("externalId"),
            "result": e["event_data"].get("result"),
            "bottles": e["custom_metadata"].get("bottleCount"),
            "image_id": e["images"][0]["file_id"] if e["images"] else None,
        }
        for e in value["events"]
    ]
```

<figure><img src="https://4077895066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoO0Ceoy9R0lHDZATcPyh%2Fuploads%2Fgit-blob-4899a888613e6b261ba8ebc58f27bb7bec1caed7%2Fignition-designer-http-transform.png?alt=media" alt="The Script transform in the HTTP binding dialog, with the transform function that maps each event to time, case, result, bottles and image_id"><figcaption><p>バインディングダイアログのスクリプト変換。</p></figcaption></figure>

フィールドを実際のイベントに合わせて変更してください。 `event_data` にはイベントタイプのフィールドが格納され、 `custom_metadata` には独自のメタデータ（例： `bottleCount`). `created_at` は UTC です。

バインディングはゲートウェイ上で実行されるため、ポートにアクセスする必要があるのはゲートウェイだけです。 `8001` テーブルについては、 [HTTP バインディング](https://docs.inductiveautomation.com/docs/8.3/ignition-modules/perspective/working-with-perspective-components/bindings-in-perspective/http-bindings-in-perspective).

### 時間範囲を表示する

ある時点（例：シフト開始時）以降のイベントを表示するには、 `start_time` をバインディングの URL に追加します。

```
"http://<device-ip>:8001/v2/events?limit=1000&start_time="
  + replace(dateFormat(setTime(now(60000), 6, 0, 0), "yyyy-MM-dd'T'HH:mm:ssXXX"), "+", "%2B")
```

`setTime(now(60000), 6, 0, 0)` はゲートウェイのタイムゾーンで今日の 6:00 を示し、この式は毎分再実行されます。直近の一定時間を対象にするには、代わりに `addHours(now(60000), -8)` を使用します。同じ方法で `end_time` を追加すると、時間範囲の終点を指定できます。

書式の `XXX` はそのままにしてください。タイムゾーンのオフセット（例： `-05:00`）が追加されます。オフセットのない時刻は、Event Store によってデバイスのタイムゾーンとして扱われます。 `replace` は、正のオフセットの `+` をエンコードします。これをしないと、URL では空白として扱われます。

各リクエストで返されるイベントは最大 1,000 件で、新しいものから順に並びます。対象期間内のイベント数がそれを超える場合は、期間を短くするか、イベントをデータベースにコピーしてください。

### イベントの画像を表示する

オペレーターがクリックした行の画像を表示します。

1. ビューに次の名前のカスタムプロパティを追加します。 `selectedImage`値として空の文字列を指定します。
2. テーブルを右クリックし、「イベントを設定...」を選択します。「コンポーネントイベント」で「onRowClick」を選択し、「スクリプト」アクションを追加して、本文に次の行を追加します。

```python
self.view.custom.selectedImage = event.value.image_id
```

<figure><img src="https://4077895066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoO0Ceoy9R0lHDZATcPyh%2Fuploads%2Fgit-blob-0c018ca1c9d3983aee10fedac27701663ec506b9%2Fignition-designer-onrowclick.png?alt=media" alt="The Event Configuration dialog on the Events table with onRowClick selected and a Script action that sets self.view.custom.selectedImage"><figcaption><p>テーブルの <code>onRowClick</code> スクリプトです。</p></figcaption></figure>

3. 「画像」コンポーネントを追加し、 `props.source` を次の式にバインドします。

```
if({view.custom.selectedImage} = "", "", "http://<device-ip>:8001/images/" + {view.custom.selectedImage})
```

非表示にするには、 `image_id` 列をテーブルの `props.columns` に追加し、 `visible` を `false`.

次のポーリングで行が追加されたときも、スクリプトによって画像は所定の位置に保たれます。テーブルの `props.selection` 新しいデータによって選択が解除されるため、選択が失われます。

画像はオペレーターのブラウザーで読み込まれるため、オペレーターのコンピューターからポートにアクセスできる必要があります。 `8001`.

## イベントをデータベースにコピーする

ライブクエリで取得できるのは、デバイス上に残っているデータだけです。ストレージがいっぱいになると、古いイベントは削除されます。履歴をより長く保持したり、複数のデバイスをまたいでレポートを作成したりするには、イベントをデータベースにコピーします。ゲートウェイのタイマースクリプトは、誰もセッションを開いていないときも実行されます。これを使って新しいイベントを自分で用意したテーブルにコピーし、そのテーブルを基にレポートを作成します。

### テーブルを作成する

この例では PostgreSQL を使用します。使用するデータベースに合わせて型を調整してください。

```sql
CREATE TABLE roboflow_events (
  id TEXT PRIMARY KEY,
  created_at TIMESTAMPTZ NOT NULL,
  stream_id TEXT,
  event_schema TEXT,
  event_data TEXT,
  image_id TEXT
);
```

イベントの `id` は主キーなので、スクリプトが同じイベントを2回読み取っても、保存されるのは1回だけです。

### カーソルタグを作成する

String型のメモリータグを作成します（例: `[default]Roboflow/EventCursor`）。スクリプトは、コピーした最新イベントの時刻をここに保存します。

### タイマースクリプトを追加する

1. Designerで、プロジェクトブラウザーの「Scripting」>「Gateway Events」を開き、「Timer」を選択します。
2. タイマースクリプトを追加します。「Choose Timer Settings」で名前を付け、「Delay (ms)」を `5000`に設定し、「Fixed Delay」はそのままにします。

<figure><img src="https://4077895066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoO0Ceoy9R0lHDZATcPyh%2Fuploads%2Fgit-blob-9f84be3b9062822351af742ae2b4e9a82d271073%2Fignition-designer-timer-settings.png?alt=media" alt="The Choose Timer Settings dialog with the name Copy Roboflow Events, Delay 5,000 ms, Enabled, Fixed Delay and Shared threading"><figcaption><p>タイマーの設定。</p></figcaption></figure>

3. 次のスクリプトを貼り付け、デバイスのアドレスとデータベース接続名を置き換えます。

```python
DEVICE = "http://192.168.1.50:8001"
DB = "MyDatabase"
CURSOR_TAG = "[default]Roboflow/EventCursor"

client = system.net.httpClient(timeout=10000, version="HTTP_1_1")
cursor = system.tag.readBlocking([CURSOR_TAG])[0].value or "1970-01-01T00:00:00Z"

response = client.get(DEVICE + "/v2/events", params={
    "start_time": cursor,
    "sort_direction": "asc",
    "limit": 1000,
})

if response.good:
    body = response.json
    for event in body["events"]:
        if system.db.runScalarPrepQuery("SELECT 1 FROM roboflow_events WHERE id = ?", [event["id"]], DB):
            continue
        images = event["images"]
        system.db.runPrepUpdate(
            "INSERT INTO roboflow_events (id, created_at, stream_id, event_schema, event_data, image_id) "
            "VALUES (?, CAST(? AS TIMESTAMPTZ), ?, ?, ?, ?)",
            [event["id"], event["created_at"], event["stream_id"], event["event_schema"],
             system.util.jsonEncode(event["event_data"]), images[0]["file_id"] if images else None],
            DB)
    if body["events"]:
        system.tag.writeBlocking([CURSOR_TAG], [body["next_timestamp"]])
else:
    system.util.getLogger("Roboflow").warn("Event Store returned %s" % response.statusCode)
```

<figure><img src="https://4077895066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoO0Ceoy9R0lHDZATcPyh%2Fuploads%2Fgit-blob-bbfd9fb20f6bb1e2bd6bb6ecc30a2118477be1d2%2Fignition-designer-gateway-timer-script.png?alt=media" alt="The Gateway Event Scripts window with the Timer section selected, a timer named Copy Roboflow Events at 5,000 ms, and the script that copies events into the roboflow_events table"><figcaption><p>「Gateway Event Scripts」のタイマースクリプト。</p></figcaption></figure>

実行のたびに、カーソル時刻以降のイベントを古い順に最大1,000件取得します。新しいイベントを保存し、カーソルを最新のイベントに進めます。1,000件を超えるイベントが届いていた場合、次回の実行で残りをコピーします。カーソル時刻のイベントは毎回返されますが、 `SELECT` でスキップされます。

一部のイベントだけをコピーするには、 `params` （例： `"event_schema": "quality_check"` または `"metadata_filter": "line:eq:Line 1"`).

{% hint style="warning" %}
デバイスは、ストレージがいっぱいになると古い画像を削除します。それより古い行のデータは残りますが、画像は読み込めなくなります。画像をより長く保持するには、スクリプト内で `client.get(DEVICE + "/images/" + file_id).body` を使ってダウンロードし、データベースにバイト列を保存します。
{% endhint %}

## Event Storeでキーが必要な場合

サービスに `API_KEY` が設定されていない限り、Event Storeはキーなしのリクエストを受け付けます。設定されている場合は、 `X-API-Key` ヘッダーでキーを送信します。 `headers={"X-API-Key": key}` を `client.get(...)`に追加するか、HTTPバインディングにヘッダーを追加してください。キーはビューに置かず、バインディングが読み取るタグなどに置いてください。

## トラブルシューティング

<table data-search="false"><thead><tr><th>問題</th><th>対処方法</th></tr></thead><tbody><tr><td>ステータス <code>401</code></td><td>Event Storeに <code>API_KEY</code>。送信 <code>X-API-Key</code>.</td></tr><tr><td>テーブルが空のままです</td><td>ゲートウェイのホストから、次を実行します <code>curl http://&#x3C;device-ip>:8001/health</code>。失敗する場合、ゲートウェイはデバイスに接続できません。</td></tr><tr><td>データベースに行が追加されなくなる</td><td>カーソルタグを確認します。未来の時刻が設定されている場合は、クリアしてください。</td></tr><tr><td>新しいイベントの画像が読み込まれない</td><td>オペレーターのコンピューターからポートに接続できない <code>8001</code>、またはセッションで HTTPS が使用されています。詳しくは、 <a href="https://docs.roboflow.com/workflows/ja/chtoriaru/integrate-with-ignition/live-video.md#perspective-over-https">HTTPS 経由の Perspective</a>.</td></tr><tr><td>古いイベントの画像が読み込まれない</td><td>デバイスによって削除されています。「イベントをデータベースにコピー」の下にある警告を参照してください。</td></tr></tbody></table>

## 関連項目

* [ライブ動画](https://docs.roboflow.com/workflows/ja/chtoriaru/integrate-with-ignition/live-video.md)
* [ライブデータ](https://docs.roboflow.com/workflows/ja/chtoriaru/integrate-with-ignition/live-data.md)
