智慧住宅動作通知

透過通知,smart home 動作就能使用 Google Assistant 與使用者溝通的重要裝置相關事件或異動。您可以設定通知,提醒使用者即時裝置事件,例如當有人來訪,或回報所要求的裝置狀態變更時 (例如門鎖螺絲成功互動或卡住)。

您的 smart home 動作可向使用者傳送以下類型的通知:

  • 主動通知:在收到 smart home 裝置事件時通知使用者,而不先向其裝置發出任何要求,例如門鈴響鈴。

  • 後續回應:裝置指令要求成功或失敗的確認訊息,例如將門鎖上。針對需要一段時間才能完成的裝置指令,請用這些快訊。只有在智慧音箱和智慧螢幕傳送裝置指令要求時,系統才會支援後續回應。

Assistant 會在智慧音箱和智慧螢幕上以公告的形式向使用者提供這些通知。主動式通知預設為關閉。 使用者可以從 Google Home app (GHA) 開啟或關閉所有主動通知。

觸發通知的事件

發生裝置事件時,您的動作執行要求會向 Google 傳送通知要求。smart home 動作支援的裝置特徵會決定可用的通知事件類型,以及可在這些通知中加入的資料。

下列特性支援主動通知:

特徵 活動
ObjectDetection 裝置偵測到的物件,例如在門前偵測到辨識出的臉孔。例如:「小艾和志明在前門。」
RunCycle 裝置完成一項循環。例如:「洗衣機週期已完成。」
SensorState 裝置偵測到支援的感應器狀態。例如: "煙霧偵測器偵測到煙霧。"
TemperatureControl 裝置達到了溫度設定點。例如:「烤箱已預熱至 350 度」。
ArmDisarm 系統進入鬧鐘前狀態,並會顯示進入倒數計時,而這是由開放式門所觸發。
CameraStream 裝置在偵測到物體或動作後提供攝影機即時影像連結。
MotionDetection 「系統在 2020 年 7 月 1 日晚上 12 點偵測到動作。」

下列特徵支援後續回應:

特徵 活動
ArmDisarm 執行 action.devices.commands.ArmDisarm 裝置指令後,完成狀態和狀態變更。例如: 「保全系統已啟動。」
LockUnlock 執行 action.devices.commands.LockUnlock 裝置指令後,完成狀態和狀態變更。例如:「前門已上鎖」或「前門卡住了」
NetworkControl 執行 action.devices.commands.TestNetworkSpeed 裝置指令後,完成狀態和狀態變更。例如:「您的網路速度測試已完成。辦公室路由器的下載速度目前為 80.2 Kbps,上傳速度為 9.3 Kbps。」
OpenClose 執行 action.devices.commands.OpenClose 裝置指令後,完成狀態和狀態變更。例如:「前門已開啟」或「無法打開前門」。
StartStop 執行 action.devices.commands.StartStop 裝置指令後,完成狀態和狀態變更。例如:"吸塵器已啟動。"

所有裝置類型都支援適用特徵的通知。

建立智慧型住宅動作的通知

請在以下階段為 smart home 動作新增通知:

  1. 向 Google 表明是否已啟用 smart home 裝置應用程式的通知功能。如果使用者在應用程式中開啟或關閉通知功能,請傳送 SYNC 要求通知 Google 裝置已變更。
  2. 如果發生會觸發通知的相關裝置事件或狀態變更,請呼叫 Report State reportStateAndNotification API 來傳送通知要求。如果裝置狀態有所變更,您可以在 Report State 和通知呼叫中同時傳送狀態和通知酬載。

以下各節將詳細說明這些步驟。

指出應用程式是否已啟用通知功能

使用者可以在 GHA 中啟用此功能,選擇是否要接收主動通知。您也可以選擇在 smart home 裝置的應用程式中,選擇讓使用者明確切換裝置通知,例如透過應用程式設定。

發出 Request SYNC 呼叫以更新裝置資料,向 Google 表明裝置已啟用通知。每當使用者在應用程式中變更這項設定時,您應該傳送這類 SYNC 要求。

在您的 SYNC 回覆中,傳送下列其中一項最新資訊:

  • 如果使用者已在裝置應用程式中明確開啟通知,或是您未提供切換選項,請將 devices.notificationSupportedByAgent 屬性設為 true
  • 如果使用者在裝置應用程式中明確關閉通知,請將 devices.notificationSupportedByAgent 屬性設為 false

以下程式碼片段示範如何設定 SYNC 回應:

devices: [{
   id: 'device123',
   ...
   notificationSupportedByAgent: true,
}]

傳送通知要求給 Google

為了在 Assistant 上觸發通知,您的執行要求會透過 Report State 和 Notification API 呼叫將通知酬載傳送至 Google Home Graph

啟用 Google HomeGraph API

  1. 前往 Google Cloud Console 的「HomeGraph API」頁面。

    前往 HomeGraph API 頁面
  2. 選取與 smart home 專案 ID 相符的專案。
  3. 按一下「ENABLE」(啟用)

建立服務帳戶金鑰

請按照下列操作說明,從 Google Cloud Console 產生服務帳戶金鑰:

注意:執行下列步驟時,請務必使用正確的 GCP 專案。這個專案與您的 smart home 專案 ID 相符。
  1. 前往 Google Cloud Console 的「建立服務帳戶金鑰」頁面。

    前往「Create Service Account Key」(建立服務帳戶金鑰) 頁面。
  2. 從「Service account」(服務帳戶) 清單中選取「New service account」(新增服務帳戶)
  3. 在 [Service account name] (服務帳戶名稱) 欄位中輸入一個名稱。
  4. 在「Service account ID」(服務帳戶 ID) 欄位中輸入 ID。
  5. 從「角色」清單中,依序選取「服務帳戶」 >「服務帳戶憑證建立者」

  6. 針對「Key type」(金鑰類型),選取「JSON」選項。

  7. 按一下「建立」,內含金鑰的 JSON 檔案會下載至電腦。

傳送通知

使用 devices.reportStateAndNotification API 發出通知要求。JSON 要求必須包含 eventId,這是平台為觸發通知的事件所產生的專屬 ID。eventId 應為隨機 ID,且每次傳送通知要求時都不相同。

在您傳入 API 呼叫的 notifications 物件中,加入 priority 值以定義通知的顯示方式。視裝置特性而定,notifications 物件可能會包含不同的欄位。

請按照下列其中一種路徑設定酬載並呼叫 API:

傳送主動通知酬載

如要呼叫 API,請從下列其中一個分頁標籤中選取一個選項:

HTTP

Home Graph API 提供 HTTP 端點

  1. 使用下載的服務帳戶 JSON 檔案建立 JSON Web Token (JWT)。詳情請參閱「 使用服務帳戶驗證」。
  2. 使用 OAuth2lhttps://www.googleapis.com/auth/homegraph 範圍取得 OAuth 2.0 存取權杖:
  3. oauth2l fetch --credentials service-account.json \
      --scope https://www.googleapis.com/auth/homegraph
    
  4. 使用 agentUserId 建立 JSON 要求。以下是 Report State 和 Notification 的 JSON 要求範例:
  5. {
      "agentUserId": "PLACEHOLDER-USER-ID",
      "eventId": "PLACEHOLDER-EVENT-ID",
      "requestId": "PLACEHOLDER-REQUEST-ID",
      "payload": {
        "devices": {
          "notifications": {
            "PLACEHOLDER-DEVICE-ID": {
              "ObjectDetection": {
                "priority": 0,
                "detectionTimestamp": 1534875126750,
                "objects": {
                  "named": [
                    "Alice"
                  ],
                  "unclassified": 2
                }
              }
            }
          }
        }
      }
    }
    
  6. Report State 和通知 JSON 和 HTTP POST 要求中的權杖結合至 Google Home Graph 端點。以下範例說明如何在指令列中使用 curl 來進行測試:
  7. curl -X POST -H "Authorization: Bearer ACCESS_TOKEN" \
      -H "Content-Type: application/json" \
      -d @request-body.json \
      "https://homegraph.googleapis.com/v1/devices:reportStateAndNotification"
    

gRPC

Home Graph API 提供 gRPC 端點

  1. 取得 Home Graph API 的通訊協定緩衝區服務定義
  2. 請按照 gRPC 開發人員說明文件,為其中一種支援的語言產生用戶端虛設常式。
  3. 呼叫 ReportStateAndNotification 方法。

Node.js

Google API Node.js 用戶端提供 Home Graph API 的繫結。

  1. 使用應用程式預設憑證來初始化 google.homegraph 服務。
  2. 使用 ReportStateAndNotificationRequest 呼叫 reportStateAndNotification 方法。它會傳回包含 ReportStateAndNotificationResponsePromise
const homegraphClient = homegraph({
  version: 'v1',
  auth: new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/homegraph'
  })
});

const res = await homegraphClient.devices.reportStateAndNotification({
  requestBody: {
    agentUserId: 'PLACEHOLDER-USER-ID',
    eventId: 'PLACEHOLDER-EVENT-ID',
    requestId: 'PLACEHOLDER-REQUEST-ID',
    payload: {
      devices: {
        notifications: {
          'PLACEHOLDER-DEVICE-ID': {
            ObjectDetection: {
              priority: 0,
              detectionTimestamp: 1534875126750,
              objects: {
                named: ['Alice'],
                unclassified: 2
              }
            }
          }
        }
      }
    }
  }
});
    

Java

Java 適用的 HomeGraph API 用戶端程式庫提供 Home Graph API 的繫結。

  1. 使用應用程式預設憑證來初始化 HomeGraphApiService
  2. 使用 ReportStateAndNotificationRequest 呼叫 reportStateAndNotification 方法。而會回傳 ReportStateAndNotificationResponse
// Get Application Default credentials.
GoogleCredentials credentials =
    GoogleCredentials.getApplicationDefault()
        .createScoped(List.of("https://www.googleapis.com/auth/homegraph"));

// Create Home Graph service client.
HomeGraphService homegraphService =
    new HomeGraphService.Builder(
            GoogleNetHttpTransport.newTrustedTransport(),
            GsonFactory.getDefaultInstance(),
            new HttpCredentialsAdapter(credentials))
        .setApplicationName("HomeGraphExample/1.0")
        .build();

// Build device notification payload.
Map<?, ?> notifications =
    Map.of(
        "ObjectDetection",
        Map.of(
            "priority", 0,
            "detectionTimestamp", 1534875126,
            "objects", Map.of("named", List.of("Alice"), "unclassifed", 2)));

// Send notification.
ReportStateAndNotificationRequest request =
    new ReportStateAndNotificationRequest()
        .setRequestId("PLACEHOLDER-REQUEST-ID")
        .setAgentUserId("PLACEHOLDER-USER-ID")
        .setEventId("PLACEHOLDER-EVENT-ID")
        .setPayload(
            new StateAndNotificationPayload()
                .setDevices(
                    new ReportStateAndNotificationDevice()
                        .setNotifications(Map.of("PLACEHOLDER-DEVICE-ID", notifications))));
homegraphService.devices().reportStateAndNotification(request);
    
傳送後續回應酬載

後續回應的酬載包含要求狀態、事件失敗的錯誤代碼 (如適用),以及 EXECUTE 意圖要求期間提供的有效 followUpToken。您必須在五分鐘內使用 followUpToken,以維持有效,並將回應與原始要求正確建立關聯。

以下程式碼片段範例顯示包含 followUpToken 欄位的 EXECUTE 要求酬載。

{
  "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
  "inputs": [{
    "intent": "action.devices.EXECUTE",
    "payload": {
      "commands": [{
        "devices": [{
          "id": "123",
        }],
        "execution": [{
          "command": "action.devices.commands.TestNetworkSpeed",
          "params": {
            "testDownloadSpeed": true,
            "testUploadSpeed": false,
            "followUpToken": "PLACEHOLDER"
          }
        }]
      }]
    }
  }]
};

Google 會使用 followUpToken,只在使用者原先互動的裝置上輸出通知,而不會在所有使用者的裝置上廣播。

如要呼叫 API,請從下列其中一個分頁標籤中選取一個選項:

HTTP

Home Graph API 提供 HTTP 端點

  1. 使用下載的服務帳戶 JSON 檔案建立 JSON Web Token (JWT)。詳情請參閱「 使用服務帳戶驗證」。
  2. 使用 OAuth2lhttps://www.googleapis.com/auth/homegraph 範圍取得 OAuth 2.0 存取權杖:
  3. oauth2l fetch --credentials service-account.json \
      --scope https://www.googleapis.com/auth/homegraph
    
  4. 使用 agentUserId 建立 JSON 要求。以下是 Report State 和 Notification 的 JSON 要求範例:
  5. {
      "agentUserId": "PLACEHOLDER-USER-ID",
      "eventId": "PLACEHOLDER-EVENT-ID",
      "requestId": "PLACEHOLDER-REQUEST-ID",
      "payload": {
        "devices": {
          "notifications": {
            "PLACEHOLDER-DEVICE-ID": {
              "NetworkControl": {
                "priority": 0,
                "followUpResponse": {
                  "status": "SUCCESS",
                  "followUpToken": "PLACEHOLDER",
                  "networkDownloadSpeedMbps": 23.3,
                  "networkUploadSpeedMbps": 10.2
                }
              }
            }
          }
        }
      }
    }
    
  6. Report State 和通知 JSON 和 HTTP POST 要求中的權杖結合至 Google Home Graph 端點。以下範例說明如何在指令列中使用 curl 來進行測試:
  7. curl -X POST -H "Authorization: Bearer ACCESS_TOKEN" \
      -H "Content-Type: application/json" \
      -d @request-body.json \
      "https://homegraph.googleapis.com/v1/devices:reportStateAndNotification"
    

gRPC

Home Graph API 提供 gRPC 端點

  1. 取得 Home Graph API 的通訊協定緩衝區服務定義
  2. 請按照 gRPC 開發人員說明文件,為其中一種支援的語言產生用戶端虛設常式。
  3. 呼叫 ReportStateAndNotification 方法。

Node.js

Google API Node.js 用戶端提供 Home Graph API 的繫結。

  1. 使用應用程式預設憑證來初始化 google.homegraph 服務。
  2. 使用 ReportStateAndNotificationRequest 呼叫 reportStateAndNotification 方法。它會傳回包含 ReportStateAndNotificationResponsePromise
const followUpToken = executionRequest.inputs[0].payload.commands[0].execution[0].params.followUpToken;

const homegraphClient = homegraph({
  version: 'v1',
  auth: new GoogleAuth({
    scopes: 'https://www.googleapis.com/auth/homegraph'
  })
});

const res = await homegraphClient.devices.reportStateAndNotification({
  requestBody: {
    agentUserId: 'PLACEHOLDER-USER-ID',
    eventId: 'PLACEHOLDER-EVENT-ID',
    requestId: 'PLACEHOLDER-REQUEST-ID',
    payload: {
      devices: {
        notifications: {
          'PLACEHOLDER-DEVICE-ID': {
            NetworkControl: {
              priority: 0,
              followUpResponse: {
                status: 'SUCCESS',
                followUpToken,
                networkDownloadSpeedMbps: 23.3,
                networkUploadSpeedMbps: 10.2,
              }
            }
          }
        }
      }
    }
  }
});
    

Java

Java 適用的 HomeGraph API 用戶端程式庫提供 Home Graph API 的繫結。

  1. 使用應用程式預設憑證初始化 HomeGraphApiService
  2. 使用 ReportStateAndNotificationRequest 呼叫 reportStateAndNotification 方法。其會傳回 ReportStateAndNotificationResponse
// Get Application Default credentials.
GoogleCredentials credentials =
    GoogleCredentials.getApplicationDefault()
        .createScoped(List.of("https://www.googleapis.com/auth/homegraph"));

// Create Home Graph service client.
HomeGraphService homegraphService =
    new HomeGraphService.Builder(
            GoogleNetHttpTransport.newTrustedTransport(),
            GsonFactory.getDefaultInstance(),
            new HttpCredentialsAdapter(credentials))
        .setApplicationName("HomeGraphExample/1.0")
        .build();

// Extract follow-up token.
ExecuteRequest.Inputs executeInputs = (Inputs) executeRequest.getInputs()[0];
String followUpToken =
    (String)
        executeInputs
            .getPayload()
            .getCommands()[0]
            .getExecution()[0]
            .getParams()
            .get("followUpToken");

// Build device follow-up response payload.
Map<?, ?> followUpResponse =
    Map.of(
        "NetworkControl",
        Map.of(
            "priority",
            0,
            "followUpResponse",
            Map.of(
                "status",
                "SUCCESS",
                "followUpToken",
                followUpToken,
                "networkDownloadSpeedMbps",
                23.3,
                "networkUploadSpeedMbps",
                10.2)));

// Send follow-up response.
ReportStateAndNotificationRequest request =
    new ReportStateAndNotificationRequest()
        .setRequestId("PLACEHOLDER-REQUEST-ID")
        .setAgentUserId("PLACEHOLDER-USER-ID")
        .setEventId("PLACEHOLDER-EVENT-ID")
        .setPayload(
            new StateAndNotificationPayload()
                .setDevices(
                    new ReportStateAndNotificationDevice()
                        .setNotifications(Map.of("PLACEHOLDER-DEVICE-ID", followUpResponse))));
homegraphService.devices().reportStateAndNotification(request);
    

記錄

通知支援事件記錄功能,詳情請參閱透過 Cloud Logging 存取事件記錄。這些記錄有助於測試及維護動作中的通知品質。

以下是 notificationLog 項目的結構定義:

屬性 說明
requestId 通知要求 ID。
structName 通知結構的名稱,例如「ObjectDetection」。
status 指出通知的狀態

status 欄位包含多種狀態,可能表示通知酬載發生錯誤。其中部分選項可能僅適用於尚未正式發布的動作。

範例狀態包括:

狀態 說明
EVENT_ID_MISSING 表示缺少必要的 eventId 欄位。
PRIORITY_MISSING 表示缺少 priority 欄位。
NOTIFICATION_SUPPORTED_BY_AGENT_FALSE 表示通知裝置的 SYNC 中提供的 notificationSupportedByAgent 屬性為 false。
NOTIFICATION_ENABLED_BY_USER_FALSE 表示使用者尚未在 GHA 中啟用通知裝置的通知功能。這個狀態僅適用於尚未推出正式版的動作。
NOTIFYING_DEVICE_NOT_IN_STRUCTURE 表示使用者尚未將通知裝置指派給住家/住家結構體。這個狀態僅適用於尚未推出正式版的動作。

除了可適用於所有通知的一般狀態以外,status 欄位也可能在適用情況下提供特定特徵專屬狀態 (例如 OBJECT_DETECTION_DETECTION_TIMESTAMP_MISSING)。