通知可讓 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 裝置指令後,完成狀態和狀態變更。例如:「保全系統已啟動」 |
LockLock | 執行 action.devices.commands.LockUnlock 裝置指令後,完成狀態和狀態變更。例如:「前門已上鎖」或「前門卡住了」。 |
網路控制 | 執行 action.devices.commands.TestNetworkSpeed 裝置指令後,完成狀態和狀態變更。例如:「您的網路速度測試已完成。辦公室路由器的下載速度目前為 80.2 Kbps,上傳速度為 9.3 Kbps。」
|
OpenClose | 執行 action.devices.commands.OpenClose 裝置指令後,完成狀態和狀態變更。例如:「前門打開了」或「前門無法開啟」。 |
StartStop | 執行 action.devices.commands.StartStop 裝置指令後,完成狀態和狀態變更。例如:「吸塵器已開始。」
|
所有裝置類型都支援適用的特徵。
為智慧型住宅動作建立通知
請在以下階段為「smart home」動作新增通知:
- 請通知 Google 您的 smart home 裝置應用程式是否已啟用通知功能。如果使用者在您的應用程式中開啟或關閉通知,請傳送
SYNC
要求以通知 Google 裝置異動。 - 當相關裝置事件或狀態變更觸發通知時,請呼叫 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
-
前往 Google Cloud Platform Console 中的「HomeGraph API」頁面。
前往 HomeGraph API 頁面 - 選取與您的 smart home 專案 ID 相符的專案。
- 按一下 [啟用]。
建立服務帳戶金鑰
請按照下列操作說明,從 GCP Console 產生服務帳戶金鑰:
-
前往 GCP Console 中的「Create service account key」(建立服務帳戶金鑰) 頁面。
前往「Create Service Account Key」(建立服務帳戶金鑰) 頁面。 - 從 [服務帳戶] 清單中選取 [新增服務帳戶]。
- 在 [Service account name] (服務帳戶名稱) 欄位中輸入一個名稱。
- 在 [服務帳戶 ID] 欄位中輸入 ID。
從 [角色] 清單中,依序選取 [服務帳戶] > [服務帳戶符記建立者]。
在「Key type」(金鑰類型) 部分,選取 [JSON] 選項。
- 按一下「建立」,包含金鑰的 JSON 檔案會下載到您的電腦。
傳送通知
使用 devices.reportStateAndNotification
API 發出通知要求呼叫。JSON 要求必須包含 eventId
,這是平台為觸發通知的事件產生的專屬 ID。eventId
應為隨機 ID,每當您傳送通知要求時都會不同。
請在 API 呼叫中傳遞的 notifications
物件中加入 priority
值,以定義通知的顯示方式。notifications
物件可能包含不同欄位 (視裝置特性而定)。
請按照下列路徑設定酬載,並呼叫 API:
傳送主動通知通知酬載
如要呼叫 API,請從下列任一分頁中選取一個:
HTTP
Home Graph API 提供 HTTP 端點
- 使用下載的服務帳戶 JSON 檔案建立 JSON Web Token (JWT)。詳情請參閱使用服務帳戶進行驗證一文。
- 使用 oauth2l 取得具有
https://www.googleapis.com/auth/homegraph
範圍的 OAuth 2.0 存取憑證: - 使用
agentUserId
建立 JSON 要求。 以下是 Report State 和通知的 JSON 要求範例: - 將 HTTP POST 要求中的 Report State 與通知 JSON 與憑證合併至 Google Home Graph 端點。以下示範如何使用指令列在
curl
中發出要求,以進行測試:
oauth2l fetch --credentials service-account.json \ --scope https://www.googleapis.com/auth/homegraph
{ "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 } } } } } } }
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 端點
- 取得 Home Graph API 的通訊協定緩衝區服務定義。
- 請按照 gRPC 開發人員說明文件,為其中一種支援的語言產生虛設常式。
- 呼叫 ReportStateAndNotification 方法。
Node.js
Google API Node.js 用戶端提供 Home Graph API 的繫結。
- 使用應用程式預設憑證來初始化
google.homegraph
服務。 - 使用 ReportStateAndNotificationRequest 呼叫
reportStateAndNotification
方法。其會傳回含有 ReportStateAndNotificationResponse 的Promise
。
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 的繫結。
- 使用應用程式預設憑證來初始化
HomeGraphApiService
。 - 使用
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);
傳送後續回應酬載
後續回應的酬載包含要求狀態、事件失敗的錯誤代碼 (如適用) 以及有效的 followUpToken
(於 EXECUTE
意圖要求期間提供)。您必須在五分鐘內使用 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 端點
- 使用下載的服務帳戶 JSON 檔案建立 JSON Web Token (JWT)。詳情請參閱使用服務帳戶進行驗證一文。
- 使用 oauth2l 取得具有
https://www.googleapis.com/auth/homegraph
範圍的 OAuth 2.0 存取憑證: - 使用
agentUserId
建立 JSON 要求。 以下是 Report State 和通知的 JSON 要求範例: - 將 HTTP POST 要求中的 Report State 與通知 JSON 與憑證合併至 Google Home Graph 端點。以下示範如何使用指令列在
curl
中發出要求,以進行測試:
oauth2l fetch --credentials service-account.json \ --scope https://www.googleapis.com/auth/homegraph
{ "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 } } } } } } }
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 端點
- 取得 Home Graph API 的通訊協定緩衝區服務定義。
- 請按照 gRPC 開發人員說明文件,為其中一種支援的語言產生虛設常式。
- 呼叫 ReportStateAndNotification 方法。
Node.js
Google API Node.js 用戶端提供 Home Graph API 的繫結。
- 使用應用程式預設憑證來初始化
google.homegraph
服務。 - 使用 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 的繫結。
- 使用應用程式預設憑證來初始化
HomeGraphApiService
- 使用
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
)。