強化智慧住宅動作

1. 事前準備

智慧型住宅動作會使用裝置類型,讓 Google 助理知道裝置應使用何種文法。裝置特徵會定義裝置類型的功能。每個裝置會沿用新增至動作的所有裝置特徵狀態。

dc8dce0dea87cd5c.png

您可以將任何支援的 traits 連結至您選擇的裝置類型,即可自訂使用者裝置的功能。如要實作裝置結構定義中目前未提供的自訂特徵,「模式」和「切換鈕」特徵可讓您以您定義的自訂名稱控管特定設定。

除了類型和特徵提供的基本控制項功能外,Smart Home API 還提供其他可改善使用者體驗的功能。意圖失敗時,錯誤回應會提供詳細的使用者意見回饋。次要使用者驗證可以延伸回覆內容,還可為你選擇的裝置特性多添一層防護。傳送特定錯誤回應至 Google 助理發出的挑戰區塊,智慧型住宅動作可能會需要額外授權才能完成指令。

必要條件

建構項目

在本程式碼研究室中,您將透過 Firebase 部署預先建立的智慧型住宅整合服務,然後瞭解如何在負載大小和強化模式模式下加入智慧型住宅洗衣機。此外,您也將導入錯誤和例外狀況回報功能,並學習如何透過雙重使用者驗證,強制進行口頭確認來開啟洗衣機。

課程內容

  • 如何在動作中新增「模式」和「切換特徵」
  • 如何回報錯誤和例外狀況
  • 如何套用雙重使用者驗證

軟硬體需求

2. 開始使用

啟用活動控制項

如要使用 Google 助理,您必須將特定活動資料提供給 Google。Google 助理需要這類資料才能正常運作;不過,共用資料的要求不只適用於 SDK。如要共用這項資料,請建立 Google 帳戶 (如果還沒有帳戶)。您可以使用任何 Google 帳戶,不一定要是開發人員帳戶。

開啟要搭配 Google 助理使用的 Google 帳戶,並開啟該帳戶的「活動控制項」頁面

請確保已啟用下列切換開關:

  • 網路和應用程式活動:此外,請務必勾選「包括 Chrome 歷史記錄以及採用 Google 服務的網站、應用程式和裝置中的活動記錄」核取方塊。
  • 裝置資訊
  • 語音和音訊活動

建立動作專案

  1. 前往 Actions on Google Developer Console
  2. 按一下「新增專案」並輸入專案名稱,然後按一下「建立專案」

3d6b68ca79afd54c.png

選取智慧型住宅應用程式

在動作控制台的總覽畫面上,選取「智慧型住宅」

2fa4988f44f8914b.png

如果選擇「智慧型住宅」體驗資訊卡,按一下「開始建築物」,系統就會將您帶往專案控制台。

安裝 Firebase CLI

Firebase 指令列介面 (CLI) 可讓您在本機提供網頁應用程式,並將網頁應用程式部署至 Firebase 託管服務。

如要安裝 CLI,請從終端機執行下列 npm 指令:

npm install -g firebase-tools

如要驗證 CLI 是否已正確安裝,請執行:

firebase --version

執行下列指令,以您的 Google 帳戶授權 Firebase CLI:

firebase login

啟用 HomeGraph API

HomeGraph API 可用於儲存及查詢使用者的 Home Graph 中的裝置及其狀態。如要使用這個 API,請先開啟 Google Cloud 控制台並啟用 HomeGraph API

在 Google Cloud 控制台中,請務必選取與「動作」<project-id>. 相符的專案,然後在 HomeGraph API 的 API 程式庫畫面中按一下「啟用」

ee198858a6eac112.png

3. 執行範例應用程式

現在您已設定開發環境,可以部署範例專案,確認所有設定皆正確無誤。

取得原始碼

點選下方連結,即可在開發機器上下載這個程式碼研究室的範例:

...或透過指令列複製 GitHub 存放區:

git clone https://github.com/google-home/smarthome-traits.git

將下載的 ZIP 檔案解壓縮。

關於專案

範例專案包含下列子目錄:

  • public: 前端 UI 可讓您輕鬆控制及監控智慧型洗衣機的狀態。
  • functions:完全導入的雲端服務,使用 Cloud Functions for Firebase 和 Firebase 即時資料庫管理智慧洗衣服務。

提供的 Cloud 執行要求在 index.js 中包含下列函式:

  • fakeauth:帳戶連結的授權端點
  • faketoken:帳戶連結的權杖端點
  • smarthome:智慧型住宅意圖執行要求端點
  • reportstate:在裝置狀態變更時叫用 Home Graph API
  • requestsync:不必重新連結帳戶即可更新使用者裝置

連結至 Firebase

前往 washer-start 目錄,然後搭配 Actions 專案設定 Firebase CLI:

cd washer-start
firebase use <project-id>

設定 Firebase 專案

初始化 Firebase 專案。

firebase init

選取 CLI 功能、即時資料庫函式,以及含有 Firebase 託管的代管功能。

? Which Firebase CLI features do you want to set up for this directory? Press Space to select features, then
 Enter to confirm your choices.
❯◉ Realtime Database: Configure a security rules file for Realtime Database and (optionally) provision default instance
 ◯ Firestore: Configure security rules and indexes files for Firestore
 ◉ Functions: Configure a Cloud Functions directory and its files
 ◉ Hosting: Configure files for Firebase Hosting and (optionally) set up GitHub Action deploys
 ◯ Hosting: Set up GitHub Action deploys
 ◯ Storage: Configure a security rules file for Cloud Storage
 ◯ Emulators: Set up local emulators for Firebase products
 ◯ Remote Config: Configure a template file for Remote Config
 ◯ Extensions: Set up an empty Extensions manifest

這項操作會為專案初始化必要的 API 和功能。

出現提示時,初始化即時資料庫。您可以使用資料庫執行個體的預設位置。

? It seems like you haven't initialized Realtime Database in your project yet. Do you want to set it up?
Yes

? Please choose the location for your default Realtime Database instance:
us-central1

由於您使用範例專案程式碼,請選擇安全性規則的預設檔案,並確保不會覆寫現有的資料庫規則檔案。

? File database.rules.json already exists. Do you want to overwrite it with the Realtime Database Security Rules for <project-ID>-default-rtdb from the Firebase Console?
No

如要重新初始化專案,請在系統詢問是否要初始化或覆寫程式碼集時,選取「Overwrite」

? Would you like to initialize a new codebase, or overwrite an existing one?
Overwrite

設定函式時,您應使用預設檔案,並確保不會覆寫專案範例中現有的 index.jspackage.json 檔案。

? What language would you like to use to write Cloud Functions?
JavaScript

? Do you want to use ESLint to catch probable bugs and enforce style?
No

? File functions/package.json already exists. Overwrite?
No

? File functions/index.js already exists. Overwrite?
No

如要重新初始化專案,請在系統詢問是否要初始化或覆寫 function/.gitignore 時,選取「否」

? File functions/.gitignore already exists. Overwrite?
No
? Do you want to install dependencies with npm now?
Yes

最後,將「託管」設定設為使用專案程式碼中的 public 目錄,並使用現有的 index.html 檔案。當系統要求使用 ESLint 時,請選取「否」

? What do you want to use as your public directory?
public

? Configure as a single-page app (rewrite all urls to /index.html)?
Yes

? Set up automatic builds and deploys with GitHub?
No

? File public/index.html already exists. Overwrite?
 No

如果不小心啟用了 ESLint,您可以透過兩種方法停用 ESLint:

  1. 使用 GUI 前往專案下方的 ../functions 資料夾,選取隱藏的檔案 .eslintrc.js,然後刪除該檔案。請勿將其誤認為 .eslintrc.json 名稱類似。
  2. 使用指令列:
    cd functions
    rm .eslintrc.js
    

部署至 Firebase

安裝依附元件並設定專案後,即可開始首次執行應用程式。

firebase deploy

以下是您應該會看到的主控台輸出內容:

...

✔ Deploy complete!

Project Console: https://console.firebase.google.com/project/<project-id>/overview
Hosting URL: https://<project-id>.web.app

這個指令會部署網頁應用程式和數個 Cloud Functions for Firebase

在瀏覽器中開啟代管網址 (https://<project-id>.web.app) 查看網路應用程式。您會看到以下介面:

5845443e94705557.png

此網頁版 UI 代表可查看或修改裝置狀態的第三方平台。如要開始在資料庫中填入裝置資訊,請按一下「更新」。您不會在頁面上看到任何變更,但洗衣機目前的狀態將儲存在資料庫中。

現在可以使用 Actions 主控台將部署的雲端服務連結至 Google 助理了。

設定 Actions 主控台專案

在「Overview」>「Build your Action」下方,選取「Add Action(s)」。輸入可為智慧型住宅意圖提供執行要求的 Cloud 函式網址,然後按一下「Save」

https://us-central1-<project-id>.cloudfunctions.net/smarthome

9d7b223427f587ca.png

在「開發」>「叫用」分頁中,為動作新增「顯示名稱」,然後按一下「儲存」。這個名稱會顯示在 Google Home 應用程式中。

774d0c40c351c7da.png

a8c4673eb11d76ee.png

如要啟用帳戶連結功能,請在左側導覽面板中依序選取「開發」>「帳戶連結」選項。使用下列帳戶連結設定:

用戶端 ID

ABC123

用戶端密碼

DEF456

驗證網址

https://us-central1-<project-id>.cloudfunctions.net/fakeauth

權杖網址

https://us-central1-<project-id>.cloudfunctions.net/faketoken

9730d20b90bcc038.png

按一下「儲存」儲存帳戶連結設定,然後點選「測試」為專案啟用測試功能。

ee0547f05b5efd98.png

系統會將您重新導向至模擬工具。如果沒有看到「立即測試已啟用」,請按一下「重設測試」,確認測試已啟用。

d0495810dbadf059.png

如要測試智慧型住宅動作,你必須將專案連結至 Google 帳戶。如此一來,即可透過已登入相同帳戶的 Google 助理介面和 Google Home 應用程式進行測試。

  1. 在手機上開啟 Google 助理設定。請注意,您登入的帳戶必須與控制台相同。
  2. 依序前往「Google 助理」>「設定」>「居家控制系統」 (位於「Google 助理」下方)。
  3. 按一下右上方的「搜尋」圖示
  4. 使用 [test] 前置字串搜尋測試版應用程式,找出特定的測試應用程式。
  5. 選取該項目。接著,Google 助理會向您的服務進行驗證並傳送 SYNC 要求,要求您的服務為使用者提供裝置清單。

開啟 Google Home 應用程式,確認可看到你的洗衣裝置。

ae252220753726f6.png

確認可以透過 Google Home 應用程式中的語音指令控制洗衣機。您也應該會在雲端執行要求的前端網頁 UI 中看到裝置狀態變更。

基本洗衣機部署完成後,您就可以自訂裝置上可用的模式。

4. 新增模式

action.devices.traits.Modes 特徵可讓裝置有任意數量的模式設定,而且一次只能設定一個模式。您將在洗衣機中新增一種模式,以定義洗衣機的負載大小:小、中或大。

更新 SYNC 回應

您必須在 functions/index.jsSYNC 回應中加入新特徵的相關資訊。這項資料會顯示在 traits 陣列和 attributes 物件中,如以下程式碼片段所示。

index.js

app.onSync(body => {
  return {
    requestId: 'ff36a3cc-ec34-11e6-b1a0-64510650abcf',
    payload: {
      agentUserId: USER_ID,
      devices: [{
        id: 'washer',
        type: 'action.devices.types.WASHER',
        traits: [
          'action.devices.traits.OnOff',
          'action.devices.traits.StartStop',
          'action.devices.traits.RunCycle',
          // Add Modes trait
          'action.devices.traits.Modes',
        ],
        name: { ... },
        deviceInfo: { ... },
        attributes: {
          pausable: true,
          //Add availableModes
          availableModes: [{
            name: 'load',
            name_values: [{
              name_synonym: ['load'],
              lang: 'en',
            }],
            settings: [{
              setting_name: 'small',
              setting_values: [{
                setting_synonym: ['small'],
                lang: 'en',
              }]
            }, {
              setting_name: 'medium',
              setting_values: [{
                setting_synonym: ['medium'],
                lang: 'en',
              }]
            }, {
              setting_name: 'large',
              setting_values: [{
                setting_synonym: ['large'],
                lang: 'en',
              }]
            }],
            ordered: true,
          }],
        },
      }],
    },
  };
});

新增 EXECUTE 意圖指令

EXECUTE 意圖中新增 action.devices.commands.SetModes 指令,如以下程式碼片段所示。

index.js

const updateDevice = async (execution,deviceId) => {
  const {params,command} = execution;
  let state, ref;
  switch (command) {
    case 'action.devices.commands.OnOff':
      state = {on: params.on};
      ref = firebaseRef.child(deviceId).child('OnOff');
      break;
    case 'action.devices.commands.StartStop':
      state = {isRunning: params.start};
      ref = firebaseRef.child(deviceId).child('StartStop');
      break;
    case 'action.devices.commands.PauseUnpause':
      state = {isPaused: params.pause};
      ref = firebaseRef.child(deviceId).child('StartStop');
      Break;
    // Add SetModes command
    case 'action.devices.commands.SetModes':
      state = {load: params.updateModeSettings.load};
      ref = firebaseRef.child(deviceId).child('Modes');
      break;
}

更新 QUERY 回應

接著,更新 QUERY 回應,回報洗衣機目前的狀態。

將更新後的變更新增至 queryFirebasequeryDevice 函式,以取得即時資料庫中儲存的狀態。

index.js

const queryFirebase = async (deviceId) => {
  const snapshot = await firebaseRef.child(deviceId).once('value');
  const snapshotVal = snapshot.val();
  return {
    on: snapshotVal.OnOff.on,
    isPaused: snapshotVal.StartStop.isPaused,
    isRunning: snapshotVal.StartStop.isRunning,
    // Add Modes snapshot
    load: snapshotVal.Modes.load,
  };
}

const queryDevice = async (deviceId) => {
  const data = await queryFirebase(deviceId);
  return {
    on: data.on,
    isPaused: data.isPaused,
    isRunning: data.isRunning,
    currentRunCycle: [{ ... }],
    currentTotalRemainingTime: 1212,
    currentCycleRemainingTime: 301,
    // Add currentModeSettings
    currentModeSettings: {
      load: data.load,
    },
  };
};

更新報表狀態

最後,更新 reportstate 函式,將洗衣機目前的負載設定回報給 Home Graph。

index.js

const requestBody = {
  requestId: 'ff36a3cc', /* Any unique ID */
  agentUserId: USER_ID,
  payload: {
    devices: {
      states: {
        /* Report the current state of your washer */
        [context.params.deviceId]: {
          on: snapshot.OnOff.on,
          isPaused: snapshot.StartStop.isPaused,
          isRunning: snapshot.StartStop.isRunning,
          // Add currentModeSettings
          currentModeSettings: {
            load: snapshot.Modes.load,
          },
        },
      },
    },
  },
};

部署至 Firebase

執行下列指令來部署更新後的動作:

firebase deploy --only functions

部署完成後,前往網頁版 UI,然後點選工具列中的「Refresh」按鈕 ae8d3b25777a5e30.png。這會觸發要求同步處理作業,讓 Google 助理能接收最新的 SYNC 回應資料。

bf4f6a866160a982.png

現在您可以下達指令來設定洗衣機的模式,例如:

「Ok Google,將洗衣機負載設為大」

此外,您也可以詢問洗衣機相關問題,例如:

「Ok Google,洗衣機是什麼?」

5. 新增切換鈕

action.devices.traits.Toggles 特徵代表具有 True 或 False 狀態的裝置已命名切面,例如洗衣機是否處於 Turbo 模式。

更新 SYNC 回應

您必須在 SYNC 回應中加入新裝置特性的相關資訊。它將顯示在 traits 陣列和 attributes 物件中,如以下程式碼片段所示。

index.js

app.onSync(body => {
  return {
    requestId: 'ff36a3cc-ec34-11e6-b1a0-64510650abcf',
    payload: {
      agentUserId: USER_ID,
      devices: [{
        id: 'washer',
        type: 'action.devices.types.WASHER',
        traits: [
          'action.devices.traits.OnOff',
          'action.devices.traits.StartStop',
          'action.devices.traits.RunCycle',
          'action.devices.traits.Modes',
          // Add Toggles trait
          'action.devices.traits.Toggles',
        ],
        name: { ... },
        deviceInfo: { ... },
        attributes: {
          pausable: true,
          availableModes: [{
            name: 'load',
            name_values: [{
              name_synonym: ['load'],
              lang: 'en'
            }],
            settings: [{ ... }],
            ordered: true,
          }],
          //Add availableToggles
          availableToggles: [{
            name: 'Turbo',
            name_values: [{
              name_synonym: ['turbo'],
              lang: 'en',
            }],
          }],
        },
      }],
    },
  };
});

新增 EXECUTE 意圖指令

EXECUTE 意圖中新增 action.devices.commands.SetToggles 指令,如以下程式碼片段所示。

index.js

const updateDevice = async (execution,deviceId) => {
  const {params,command} = execution;
  let state, ref;
  switch (command) {
    case 'action.devices.commands.OnOff':
      state = {on: params.on};
      ref = firebaseRef.child(deviceId).child('OnOff');
      break;
    case 'action.devices.commands.StartStop':
      state = {isRunning: params.start};
      ref = firebaseRef.child(deviceId).child('StartStop');
      break;
    case 'action.devices.commands.PauseUnpause':
      state = {isPaused: params.pause};
      ref = firebaseRef.child(deviceId).child('StartStop');
      break;
    case 'action.devices.commands.SetModes':
      state = {load: params.updateModeSettings.load};
      ref = firebaseRef.child(deviceId).child('Modes');
      break;
    // Add SetToggles command
    case 'action.devices.commands.SetToggles':
      state = {Turbo: params.updateToggleSettings.Turbo};
      ref = firebaseRef.child(deviceId).child('Toggles');
      break;
  }

更新 QUERY 回應

最後,您必須更新 QUERY 回應,才能回報洗衣機的 Turbo 模式。將更新後的變更新增至 queryFirebasequeryDevice 函式,以取得即時資料庫中儲存的切換狀態。

index.js

const queryFirebase = async (deviceId) => {
  const snapshot = await firebaseRef.child(deviceId).once('value');
  const snapshotVal = snapshot.val();
  return {
    on: snapshotVal.OnOff.on,
    isPaused: snapshotVal.StartStop.isPaused,
    isRunning: snapshotVal.StartStop.isRunning,
    load: snapshotVal.Modes.load,
    // Add Toggles snapshot
    Turbo: snapshotVal.Toggles.Turbo,
  };
}

const queryDevice = async (deviceId) => {
  const data = queryFirebase(deviceId);
  return {
    on: data.on,
    isPaused: data.isPaused,
    isRunning: data.isRunning,
    currentRunCycle: [{ ... }],
    currentTotalRemainingTime: 1212,
    currentCycleRemainingTime: 301,
    currentModeSettings: {
      load: data.load,
    },
    // Add currentToggleSettings
    currentToggleSettings: {
      Turbo: data.Turbo,
    },
  };
};

更新報表狀態

最後,更新 reportstate 函式,向 Home Graph 回報 (洗衣機是否已設為 Turbo)

index.js

const requestBody = {
  requestId: 'ff36a3cc', /* Any unique ID */
  agentUserId: USER_ID,
  payload: {
    devices: {
      states: {
        /* Report the current state of your washer */
        [context.params.deviceId]: {
          on: snapshot.OnOff.on,
          isPaused: snapshot.StartStop.isPaused,
          isRunning: snapshot.StartStop.isRunning,
          currentModeSettings: {
            load: snapshot.Modes.load,
          },
          // Add currentToggleSettings
          currentToggleSettings: {
            Turbo: snapshot.Toggles.Turbo,
          },
        },
      },
    },
  },
};

部署至 Firebase

執行下列指令來部署更新後的函式:

firebase deploy --only functions

按一下網頁版 UI 中的「Refresh」 ae8d3b25777a5e30.png 按鈕,即可在部署完成後觸發「Request Sync」(要求同步) 動作。

您現在可以說出以下指令,將洗衣機設為 Turbo 模式:

「Ok Google,打開洗衣機的渦輪機。」

你也可以說出以下問題,確認洗衣機是否已處於 Turbo 模式:

「Ok Google,我的洗衣機是否處於 Turbo 模式?」

6. 回報錯誤和例外狀況

智慧型住宅動作中的錯誤處理功能可讓您在問題導致 EXECUTEQUERY 回應失敗時回報使用者。這些通知可在使用者與智慧型裝置和動作互動時,提供更優質的使用者體驗。

只要 EXECUTEQUERY 要求失敗,動作應傳回錯誤代碼。舉例來說,如果您想在使用者嘗試透過蓋子打開洗衣機啟動洗衣機時擲回錯誤,EXECUTE 回應會如以下程式碼片段所示:

{
  "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
  "payload": {
    "commands": [
      {
        "ids": [
          "456"
        ],
        "status": "ERROR",
        "errorCode": "deviceLidOpen"
      }
    ]
  }
}

現在,當使用者要求啟動洗衣機時,Google 助理會說出以下內容:

「洗衣機的蓋子打開了。請關閉後再試一次。」

例外狀況與錯誤類似,但會在快訊與指令建立關聯時,指出該指令不一定能成功執行。例外狀況可以透過 StatusReport 特徵提供相關資訊,例如電池電量或近期狀態變更。非封鎖的例外狀況代碼會傳回 SUCCESS 狀態,而封鎖的例外狀況代碼會傳回 EXCEPTIONS 狀態。

例外狀況回應範例位於以下程式碼片段:

{
  "requestId": "ff36a3cc-ec34-11e6-b1a0-64510650abcf",
  "payload": {
    "commands": [{
      "ids": ["123"],
      "status": "SUCCESS",
      "states": {
        "online": true,
        "isPaused": false,
        "isRunning": false,
        "exceptionCode": "runCycleFinished"
      }
    }]
  }
}

Google 助理會說出以下內容來回應:

「洗衣機已完成執行。」

如要為洗衣機新增錯誤報告,請開啟 functions/index.js 並新增錯誤類別定義,如以下程式碼片段所示:

index.js

app.onQuery(async (body) => {...});

// Add SmartHome error handling
class SmartHomeError extends Error {
  constructor(errorCode, message) {
    super(message);
    this.name = this.constructor.name;
    this.errorCode = errorCode;
  }
}

更新執行回應,以傳回錯誤代碼和錯誤狀態:

index.js

const executePromises = [];
const intent = body.inputs[0];
for (const command of intent.payload.commands) {
  for (const device of command.devices) {
    for (const execution of command.execution) {
      executePromises.push( ... )
          //Add error response handling
          .catch((error) => {
            functions.logger.error('EXECUTE', device.id, error);
            result.ids.push(device.id);
            if(error instanceof SmartHomeError) {
              result.status = 'ERROR';
              result.errorCode = error.errorCode;
            }
          })
      );
    }
  }
}

現在起,Google 助理可以告知使用者你回報的任何錯誤代碼。下節將說明具體範例。

7. 新增雙重使用者驗證

如果裝置有任何需要確保安全的模式,或是僅適用於特定授權使用者群組 (例如軟體更新或鎖定不接觸),您應在動作中實作次要使用者驗證

您可以在所有裝置類型和特徵上實施雙重使用者驗證,自訂是否每次或符合特定條件時都會發生安全性驗證問題。

共有三種支援的驗證類型

  • No challenge:未使用驗證驗證方式的要求和回應 (這是預設行為)
  • ackNeeded:需要明確確認的次要使用者驗證 (是或否)
  • pinNeeded:需要個人識別號碼 (PIN 碼) 的次要使用者驗證

在本程式碼研究室中,請在開啟洗衣機的指令中加入 ackNeeded 驗證,並在次要驗證驗證失敗時傳回錯誤的功能。

開啟 functions/index.js 並新增錯誤類別定義,此定義會傳回錯誤代碼和驗證類型,如以下程式碼片段所示:

index.js

class SmartHomeError extends Error { ... }

// Add secondary user verification error handling
class ChallengeNeededError extends SmartHomeError {
  /**
   * Create a new ChallengeNeededError
   * @param {string} suvType secondary user verification challenge type
   */
  constructor(suvType) {
    super('challengeNeeded', suvType);
    this.suvType = suvType;
  }
}

您也必須更新執行回應以傳回 challengeNeeded 錯誤,如下所示:

index.js

const executePromises = [];
const intent = body.inputs[0];
for (const command of intent.payload.commands) {
  for (const device of command.devices) {
    for (const execution of command.execution) {
      executePromises.push( ... )
          .catch((error) => {
            functions.logger.error('EXECUTE', device.id, error);
            result.ids.push(device.id);
            if(error instanceof SmartHomeError) {
              result.status = 'ERROR';
              result.errorCode = error.errorCode;
              //Add error response handling
              if(error instanceof ChallengeNeededError) {
                result.challengeNeeded = {
                  type: error.suvType
                };
              }
            }
          })
      );
    }
  }
}

最後,修改 updateDevice 以要求明確確認來開啟或關閉洗衣機。

index.js

const updateDevice = async (execution,deviceId) => {
  const {challenge,params,command} = execution; //Add secondary user challenge
  let state, ref;
  switch (command) {
    case 'action.devices.commands.OnOff':
      //Add secondary user verification challenge
      if (!challenge || !challenge.ack) {
        throw new ChallengeNeededError('ackNeeded');
      }
      state = {on: params.on};
      ref = firebaseRef.child(deviceId).child('OnOff');
      break;
    ...
  }

  return ref.update(state)
      .then(() => state);
};

部署至 Firebase

執行下列指令來部署更新後的函式:

firebase deploy --only functions

部署更新後的程式碼後,當您要求 Google 助理開啟或關閉洗衣機時,必須口頭確認動作,如下所示:

你: 「Ok Google,打開洗衣機。」

Google 助理: 「確定要打開洗衣機嗎?」

你: 「可以。」

您也可以開啟 Firebase 記錄,查看次要使用者驗證流程中各步驟的詳細回應。

289dbe48f4bb8106.png

8. 恭喜

674c4f4392e98c1.png

恭喜!您已透過 ModesToggles 特徵擴充智慧型住宅動作的功能,並透過次要使用者驗證程序確保其執行安全。

瞭解詳情

不妨採納下列建議,進一步瞭解這些做法:

  • 為裝置新增本機執行功能。
  • 請改用其他次要使用者驗證驗證類型修改裝置狀態。
  • 更新 RunCycle trait QUERY 回應以動態更新。
  • 請查看這個 GitHub 範例