智慧住宅動作通知

通知功能可讓 Cloud-to-cloud 整合服務使用 Google Assistant,向使用者傳達與裝置相關的重要事件或變更。您可以導入通知功能,及時提醒使用者裝置事件,例如有人在門口,或回報要求的裝置狀態變更,例如門鎖栓已成功上鎖或卡住。

Cloud-to-cloud 整合功能可向使用者傳送下列類型的通知:

  • 主動通知:在使用者未向裝置提出任何要求的情況下,向使用者發出 smart home 裝置事件快訊,例如門鈴響起。

  • 後續回覆:確認裝置指令要求成功或失敗,例如鎖門時。這類快訊適用於需要一段時間才能完成的裝置指令。只有從智慧音箱和智慧螢幕傳送裝置指令要求時,才支援後續回覆。

Assistant 會透過智慧音箱和智慧螢幕,向使用者提供這些通知。主動通知預設為關閉。使用者可以透過 Google Home app (GHA) 開啟或關閉所有主動通知。

觸發通知的事件

發生裝置事件時,執行要求會傳送通知要求給 Google。Cloud-to-cloud 整合支援的裝置特徵,會決定可用的通知事件類型,以及可在通知中加入的資料。

下列特性能支援主動通知:

Trait 事件
ObjectDetection 裝置偵測到的物體,例如在門口偵測到已辨識的臉孔。例如:「麗麗和小柏在前門。」
RunCycle 裝置完成一個週期。例如:「洗衣機已完成洗衣程序。」
SensorState 裝置偵測到支援的感應器狀態。例如: 「煙霧偵測器偵測到煙霧。」

下列特質支援後續回覆:

Trait 事件
LockUnlock 執行 action.devices.commands.LockUnlock 裝置指令後的完成狀態和狀態變更。例如:「前門已上鎖」或「前門卡住了」。
NetworkControl 執行 action.devices.commands.TestNetworkSpeed 裝置指令後的完成狀態和狀態變更。例如:「您的網路速度測試已完成。辦公室路由器目前的下載速度為 80.2 Kbps,上傳速度為 9.3 Kbps。
OpenClose 執行 action.devices.commands.OpenClose 裝置指令後的完成狀態和狀態變更。例如:「前門已打開」或「無法打開前門」。

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

為雲端對雲端整合項目建立通知

在下列階段,為 Cloud-to-cloud 整合新增通知:

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

下列章節將詳細說明上述步驟。

指出應用程式是否啟用通知

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

請發出要求同步呼叫來更新裝置資料,向 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. 按一下「啟用」。

建立服務帳戶金鑰

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

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

    前往「Service Accounts」(服務帳戶) 頁面。

    您可能需要先選取專案,才能前往「服務帳戶」頁面。

  2. 按一下「 Create service account」(建立服務帳戶)。

  3. 在 [Service account name] (服務帳戶名稱) 欄位中輸入一個名稱。

  4. 在「Service account ID」(服務帳戶 ID) 欄位中輸入 ID。

  5. 在「Service account description」(服務帳戶說明) 欄位中輸入說明。

  6. 按一下 [建立並繼續]。

  7. 在「Role」(角色) 下拉式選單中,依序選取「Service Accounts」(服務帳戶) >「Service Account OpenID Connect Identity Token Creator」(服務帳戶 OpenID Connect 身分識別權杖建立者)。

  8. 按一下「繼續」。

  9. 按一下「完成」。

  10. 從服務帳戶清單中選取您剛建立的服務帳戶,然後從 「Actions」(動作) 選單中選取「Manage keys」(管理金鑰)。

  11. 依序選取「新增金鑰」 >「建立新的金鑰」。

  12. 在「金鑰類型」部分,選取「JSON」選項。

  13. 按一下「建立」,系統會將含有金鑰的 JSON 檔案下載到您的電腦。

如需建立服務帳戶金鑰的詳細操作說明和資訊,請參閱 Google Cloud 控制台說明網站上的「建立及刪除服務帳戶金鑰」。

傳送通知

使用 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. 使用 oauth2l 取得具有 https://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 和通知的 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. 在傳送至 Google Home Graph 端點的 HTTP POST 要求中,合併 Report State 和通知 JSON 以及權杖。以下範例說明如何使用 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 方法。系統會傳回 Promise,其中包含 ReportStateAndNotificationResponse。
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. 使用 oauth2l 取得具有 https://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 和通知的 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. 在傳送至 Google Home Graph 端點的 HTTP POST 要求中,合併 Report State 和通知 JSON 以及權杖。以下範例說明如何使用 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 方法。系統會傳回含有 ReportStateAndNotificationResponse 的 Promise。
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-to-cloud 的 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)。