> 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/live-data/trigger-an-inspection-from-ignition.md).

# Ignitionから検査をトリガーする

HTTP 経由で Ignition から Roboflow エッジデバイスに検査を要求できるようにし、Workflow の結果を Ignition のタグに書き戻します。

Ignition 側で検査のタイミングを決める場合（例：部品検出センサーや HMI ボタン）は、この方法を使用します。Ignition が HTTP 経由でデバイスを呼び出すと、デバイスは最新のカメラフレームに対して Workflow を実行し、結果を含む応答を Ignition に返します。

{% hint style="info" %}
OPC UA Writer Sink、OPC UA Reader、OPC UA Server は、Enterprise のお客様のみご利用いただけます。 [詳しくは Roboflow の営業チームに](https://roboflow.com/sales) お問い合わせください。
{% endhint %}

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

## タグの例

このページでは、手順を説明するために 5 つのタグを使用します。これらは説明用の例です。実際のラインに合わせて名前、フォルダー、データ型を定義し、スクリプト内の設定と一致させてください。

<table data-search="false"><thead><tr><th>タグ</th><th>データ型</th><th>説明</th></tr></thead><tbody><tr><td><code>Roboflow/Inspect</code></td><td>ブール値</td><td>検査を要求するには <code>true</code> に設定します（例：部品検出センサーや HMI ボタンから）。結果が返ると、スクリプトによって <code>false</code> に戻されます。</td></tr><tr><td><code>Roboflow/DeviceTriggerUrl</code></td><td>文字列</td><td>デバイス上のストリームのトリガーアドレス</td></tr><tr><td><code>Roboflow/LastDetections</code></td><td>整数（Int4）</td><td>直近の検査で検出されたオブジェクトの数。失敗した場合は <code>-1</code> その数</td></tr><tr><td><code>Roboflow/LastResult</code></td><td>文字列</td><td>直近の検査で検出された各クラスの数を JSON 形式で表したもの（例： <code>{"bottle":12}</code>)</td></tr><tr><td><code>Roboflow/LastError</code></td><td>文字列</td><td>直近の検査が失敗した理由。成功した場合は空欄</td></tr></tbody></table>

## トリガー付きストリームを追加する

Deployment Manager でデバイスを開き、「Add Stream」をクリックします。「Workflow ID」で Workflow を選択し、「Mode」を「Triggered」に設定して、カメラの「RTSP URL」を入力したら、「Create Stream」をクリックします。トリガー付きストリームはカメラを接続した状態に保ち、モデルを読み込みますが、トリガーされたときにのみ Workflow を実行します。Ignition は Workflow の出力をそのまま受け取るため、どの Workflow でも使用できます。そのため、OPC UA Writer Sink は含めないでください。

<figure><img src="https://4077895066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoO0Ceoy9R0lHDZATcPyh%2Fuploads%2Fgit-blob-c659a1d5fbbdc157a8c0df330b310925ac344ab3%2Fignition-dm-add-stream-triggered.png?alt=media" alt="The Deployment Manager Add New Video Stream dialog with Name line-1-camera, the Workflow selected, Mode Triggered, Stream Type RTSP Stream, and an RTSP URL" width="400"><figcaption><p>トリガー付きストリームは Ignition からの呼び出しを待機します。</p></figcaption></figure>

ストリームのトリガーアドレスは `http://<device-ip>:8000/inference_pipelines/<pipeline-id>/trigger`です。パイプライン ID は Deployment Manager のストリーム詳細で確認できます。

## Ignition でタグを作成する

Designer の Tag Browser で `default` プロバイダーを選択します。 `Roboflow`という名前のフォルダーを作成し、上記のデータ型を指定したメモリータグとしてサンプルタグを追加します。フォルダーを右クリックし、「New Tag」>「Memory Tag」を選択して、Tag Editor で「Name」と「Data Type」を設定します。 `DeviceTriggerUrl` の値をストリームのトリガーアドレスに設定します。

<figure><img src="https://4077895066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoO0Ceoy9R0lHDZATcPyh%2Fuploads%2Fgit-blob-2dd6de0e5a8eedacbea39630449ba110c2074c15%2Fignition-designer-inspect-tags.png?alt=media" alt="The Ignition Designer Tag Browser with the Roboflow folder expanded, showing DeviceTriggerUrl set to the device trigger address, Inspect false, LastDetections 12, an empty LastError, and LastResult {&#x22;bottle&#x22;:12}"><figcaption><p>検査後のサンプルタグ。フォルダーには他のタグも含まれています。</p></figcaption></figure>

## 検査スクリプトを追加する

をダブルクリックして `Inspect` Tag Editor を開き、「Scripting」>「Value Changed」に移動して、スクリプト本文に次のコードを貼り付けます。このコードは、Workflow に `predictions`:

```python
という名前の物体検出出力があることを前提としています。
if initialChange or not currentValue.value:
    return
import java.lang
def run():
    log = system.util.getLogger("Roboflow")
    base = "[default]Roboflow/"
    try:
        url = system.tag.readBlocking([base + "DeviceTriggerUrl"])[0].value
        # HTTP/1.1: the device rejects the HTTP/2 upgrade Ignition sends by default.
        resp = system.net.httpClient(timeout=300000, version="HTTP_1_1").post(url, data="{}", headers={"Content-Type": "application/json"})
        body = resp.json if resp.good else None
        if not body or not body.get("success"):
            raise ValueError("HTTP %s: %s" % (resp.statusCode, resp.text[:300]))
        preds = body["data"]["workflow_output"][0]["predictions"]["predictions"]
        counts = {}
        for p in preds:
            counts[p["class"]] = counts.get(p["class"], 0) + 1
        system.tag.writeBlocking([base + "LastDetections", base + "LastResult", base + "LastError"], [len(preds), system.util.jsonEncode(counts), ""])
    except (Exception, java.lang.Exception) as e:
        system.tag.writeBlocking([base + "LastDetections", base + "LastResult", base + "LastError"], [-1, "", str(e)[:500]])
        log.warn("Roboflow inspect failed: %s" % e)
    finally:
        system.tag.writeBlocking([base + "Inspect"], [False])
# The HTTP call blocks until the Workflow finishes, so run it off the tag event thread.
system.util.invokeAsynchronous(run)
```

<figure><img src="https://4077895066-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2FoO0Ceoy9R0lHDZATcPyh%2Fuploads%2Fgit-blob-7cf6d0e9f1d15a439f53f4f81440406cbacef11a%2Fignition-designer-inspect-script.png?alt=media" alt="The Ignition Tag Editor for the Inspect tag, on Scripting > Value Changed, with the script that posts to the device trigger URL and writes LastDetections, LastResult, and LastError"><figcaption><p>の値変更スクリプトで <code>Inspect</code>.</p></figcaption></figure>

設定 `Inspect` を `true` HMIボタン、PLCタグ変更スクリプト、または任意のOPC UAクライアントから設定します。値が再び `false`になったら、結果タグ（例： `LastDetections` は `12` 、 `LastResult` は `{"bottle":12}` は12本のボトルを示します）を読み取ります。実行ごとの入力値（例：製品コード）を渡すには、リクエスト本文に `{"workflows_parameters": {...}}`として含めます。詳細は [エッジトリガー](https://docs.roboflow.com/deployment/self-hosted/enterprise/deployment-manager/making-changes/trigger-a-stream#edge-trigger).

## 実行中のワークフローに値を渡す

すでに実行中のワークフローにIgnitionから値を渡すには、代わりにOPC UA Readerブロックを使用します。このブロックを使うには、デバイスの推論イメージに `roboflow-workflows` 0.2.13以降が必要です。ブロックが見つからない場合はデバイスを更新してください。このブロックは1つのタグをサブスクライブし、実行ごとにその最新の `value` を返し、 `is_new` と `error_status`。フラグがオフのときに推論をスキップするには、Continue Ifブロックと組み合わせます（例： `LineRunning` タグ）。そのサーバーのWriter Sinkと同じ方法で、「Url」「Namespace」「Object Name」「Variable Name」「Node Lookup Mode」を設定します。Ignitionタグの場合は「direct」、Roboflow OPC UA Server上のタグの場合は「hierarchical」にします。

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

<table data-search="false"><thead><tr><th>症状</th><th>原因</th><th>対処方法</th></tr></thead><tbody><tr><td><code>LastError</code> に <code>HTTP 400: Invalid HTTP request received.</code></td><td>IgnitionのHTTPクライアントがHTTP/2を使用している</td><td>スクリプト内の <code>version="HTTP_1_1"</code> をそのまま使用してください</td></tr><tr><td>Deployment Managerで最初のトリガーがタイムアウトする</td><td>モデルの初回実行時にTensorRTエンジンがビルドされるため、数分かかることがあります</td><td>そのままお待ちください。実行は完了し、エンジンは以降の実行のためにキャッシュされます。</td></tr></tbody></table>

## セキュリティ

ポート8000のデバイスのトリガーエンドポイントには認証がないため、アクセス可能な人は誰でもストリームをトリガーできます。また、リクエストボディによって、その実行に限りストリームのWorkflow入力が置き換えられます。ポート8000へのアクセスを制限してください。
