Untuk mendukung fulfillment lokal, Anda perlu membuat aplikasi untuk menangani intent smart home berikut:
IDENTIFY: Mendukung penemuan perangkat smart yang dapat dikontrol secara lokal. Pengendali intent mengekstrak data yang ditampilkan perangkat smart Anda selama penemuan dan mengirimkannya dalam respons ke Google.EXECUTE: Mendukung eksekusi perintah.QUERY: Mendukung kueri status perangkat.REACHABLE_DEVICES: (Opsional) Mendukung penemuan perangkat akhir yang dapat dikontrol secara lokal di balik perangkat hub (atau bridge).
Aplikasi ini berjalan di perangkat Google Home atau perangkat Google Nest pengguna dan menghubungkan perangkat smart Anda ke Asisten. Anda dapat membuat aplikasi menggunakan TypeScript (lebih disarankan) atau JavaScript.
TypeScript direkomendasikan karena Anda dapat memanfaatkan binding untuk memastikan secara statis bahwa data yang ditampilkan aplikasi Anda cocok dengan jenis yang diharapkan platform.
Untuk mengetahui detail selengkapnya tentang API, lihat referensi API Local Home SDK.
Cuplikan berikut menunjukkan cara menginisialisasi aplikasi fulfillment lokal dan melampirkan pengendali Anda.
import App = smarthome.App; const localHomeApp: App = new App("1.0.0"); localHomeApp .onIdentify(identifyHandler) .onExecute(executeHandler) .listen() .then(() => { console.log("Ready"); });
import App = smarthome.App; const localHomeApp: App = new App("1.0.0"); localHomeApp .onIdentify(identifyHandler) .onReachableDevices(reachableDevicesHandler) .onExecute(executeHandler) .listen() .then(() => { console.log("Ready"); });
Buat project Anda
Untuk men-deploy aplikasi fulfillment lokal, Anda harus membuat paket JavaScript untuk kode Anda dan semua dependensinya.
Gunakan penginisialisasi project aplikasi fulfillment lokal untuk melakukan bootstrap struktur project yang sesuai dengan konfigurasi pemaket pilihan Anda.
Template project
Untuk memilih konfigurasi bundler, jalankan perintah npm init seperti yang ditunjukkan dalam contoh berikut:
TypeScript tanpa konfigurasi pemaket:
npm init @google/local-home-app project-directory/ --bundler none
Struktur project:
project-directory/ ├── node_modules/ ├── package.json ├── .gitignore ├── index.ts ├── test.ts ├── tsconfig.json ├── tslint.json └── serve.js
Ganti project-directory dengan direktori baru yang akan berisi project aplikasi fulfillment lokal.
Konfigurasi TypeScript dengan bundler webpack:
npm init @google/local-home-app project-directory/ --bundler webpack
Struktur project:
project-directory/ ├── node_modules/ ├── package.json ├── .gitignore ├── index.ts ├── test.ts ├── tsconfig.json ├── tslint.json ├── webpack.config.web.js ├── webpack.config.node.js └── serve.js
Ganti project-directory dengan direktori baru yang akan berisi project aplikasi fulfillment lokal.
Konfigurasi pemaket TypeScript dengan Rollup:
npm init @google/local-home-app project-directory/ --bundler rollup
Struktur project:
project-directory/ ├── node_modules/ ├── package.json ├── .gitignore ├── index.ts ├── test.ts ├── tsconfig.json ├── tslint.json ├── rollup.config.js └── serve.js
Ganti project-directory dengan direktori baru yang akan berisi project aplikasi fulfillment lokal.
Konfigurasi pemaket Parcel dengan TypeScript:
npm init @google/local-home-app project-directory/ --bundler parcel
Struktur project:
project-directory/ ├── node_modules/ ├── package.json ├── .gitignore ├── index.ts ├── test.ts ├── tsconfig.json ├── tslint.json └── serve.js
Ganti project-directory dengan direktori baru yang akan berisi project aplikasi fulfillment lokal.
Melakukan tugas umum level project
Project yang dihasilkan mendukung skrip npm berikut:
cd project-directory/ npm run build
Skrip ini mengompilasi sumber TypeScript, dan memaketkan aplikasi Anda dengan dependensinya untuk lingkungan runtime Chrome di subdirektori dist/web dan lingkungan runtime Node.js di subdirektori dist/node.
cd project-directory/ npm run lint npm run compile npm test
Skrip ini memverifikasi sintaksis kode TypeScript Anda, mengompilasinya tanpa menghasilkan output apa pun di subdirektori dist/, dan menjalankan pengujian otomatis dari test.ts.
cd project-directory/ npm run start
Selama pengembangan, skrip ini menyajikan paket aplikasi Anda untuk lingkungan runtime Chrome dan Node.js secara lokal.
Mengimplementasikan pengendali IDENTIFY
Pengendali IDENTIFY akan dipicu saat perangkat Google Home atau perangkat Google Nest dimulai ulang dan melihat perangkat lokal yang belum diverifikasi (termasuk perangkat akhir yang terhubung ke hub). Platform
Local Home akan memindai perangkat lokal menggunakan informasi konfigurasi pemindaian
yang Anda tentukan sebelumnya dan memanggil pengendali IDENTIFY dengan hasil pemindaian.
IdentifyRequest
dari platform Local Home berisi data pemindaian instance
LocalIdentifiedDevice. Hanya satu instance device yang diisi, berdasarkan konfigurasi pemindaian
yang menemukan perangkat.
Jika hasil pemindaian cocok dengan perangkat Anda, pengendali IDENTIFY harus menampilkan objek
IdentifyResponsePayload, yang menyertakan objek device dengan
metadata smart home (seperti jenis, karakteristik, dan status laporan).
Google akan membuat pengaitan perangkat jika
verificationId dari respons IDENTIFY cocok dengan salah satu
nilai otherDeviceIds yang ditampilkan oleh respons SYNC.
Contoh
Cuplikan berikut menunjukkan cara membuat pengendali IDENTIFY untuk
integrasi perangkat mandiri dan hub.
const identifyHandler = (request: IntentFlow.IdentifyRequest): IntentFlow.IdentifyResponse => { // Obtain scan data from protocol defined in your scan config const device = request.inputs[0].payload.device; if (device.udpScanData === undefined) { throw Error("Missing discovery response"); } const scanData = device.udpScanData.data; // Decode scan data to obtain metadata about local device const verificationId = "local-device-id"; // Return a response const response: IntentFlow.IdentifyResponse = { intent: Intents.IDENTIFY, requestId: request.requestId, payload: { device: { id: device.id || "", verificationId, // Must match otherDeviceIds in SYNC response }, }, }; return response; };
const identifyHandler = (request: IntentFlow.IdentifyRequest): IntentFlow.IdentifyResponse => { // Obtain scan data from protocol defined in your scan config const device = request.inputs[0].payload.device; if (device.udpScanData === undefined) { throw Error("Missing discovery response"); } const scanData = device.udpScanData.data; // Decode scan data to obtain metadata about local device const proxyDeviceId = "local-hub-id"; // Return a response const response: IntentFlow.IdentifyResponse = { intent: Intents.IDENTIFY, requestId: request.requestId, payload: { device: { id: proxyDeviceId, isProxy: true, // Device can control other local devices isLocalOnly: true, // Device not present in `SYNC` response }, }, }; return response; };
Mengidentifikasi perangkat di balik hub
Jika Google mengidentifikasi perangkat hub, Google akan memperlakukan hub sebagai saluran ke perangkat akhir yang terhubung ke hub dan mencoba memverifikasi perangkat akhir tersebut.
Agar Google dapat mengonfirmasi bahwa perangkat hub ada, ikuti petunjuk berikut untuk pengendali IDENTIFY Anda:
- Jika respons
SYNCAnda melaporkan ID perangkat akhir lokal yang terhubung ke hub, tetapkanisProxysebagaitruediIdentifyResponsePayload. - Jika respons
SYNCAnda tidak melaporkan perangkat hub, tetapkanisLocalOnlysebagaitruediIdentifyResponsePayload. - Kolom
device.idberisi ID perangkat lokal untuk perangkat hub itu sendiri.
Mengimplementasikan pengendali REACHABLE_DEVICES (khusus integrasi hub)
Intent REACHABLE_DEVICES dikirim oleh Google untuk mengonfirmasi perangkat akhir mana yang
dapat dikontrol secara lokal. Intent ini dipicu setiap kali Google menjalankan
pemindaian penemuan (kira-kira sekali setiap menit), selama hub terdeteksi
online.
Anda mengimplementasikan pengendali REACHABLE_DEVICES dengan cara yang mirip dengan pengendali IDENTIFY,
kecuali bahwa pengendali Anda perlu mengumpulkan ID perangkat tambahan
yang dapat dijangkau oleh perangkat proxy lokal (yaitu hub). Kolom
device.verificationId berisi ID perangkat lokal untuk perangkat akhir
yang terhubung ke hub.
ReachableDevicesRequest
dari Local Home Platform berisi instance
LocalIdentifiedDevice.
Melalui instance ini, Anda bisa mendapatkan ID perangkat proxy serta data dari
hasil pemindaian.
Pengendali REACHABLE_DEVICES Anda harus menampilkan objek
ReachableDevicesPayload
yang menyertakan objek devices yang berisi array nilai
verificationId yang mewakili perangkat akhir yang dikontrol hub. Nilai
verificationId harus cocok dengan salah satu otherDeviceIds dari
respons SYNC.
Cuplikan berikut menunjukkan cara membuat pengendali REACHABLE_DEVICES.
const reachableDevicesHandler = (request: IntentFlow.ReachableDevicesRequest): IntentFlow.ReachableDevicesResponse => { // Reference to the local proxy device const proxyDeviceId = request.inputs[0].payload.device.id; // Gather additional device ids reachable by local proxy device // ... const reachableDevices = [ // Each verificationId must match one of the otherDeviceIds // in the SYNC response { verificationId: "local-device-id-1" }, { verificationId: "local-device-id-2" }, ]; // Return a response const response: IntentFlow.ReachableDevicesResponse = { intent: Intents.REACHABLE_DEVICES, requestId: request.requestId, payload: { devices: reachableDevices, }, }; return response; };
Mengimplementasikan pengendali EXECUTE
Pengendali EXECUTE Anda di aplikasi memproses perintah pengguna dan menggunakan
Local Home SDK untuk mengakses perangkat smart Anda melalui protokol yang ada.
Platform Local Home meneruskan payload input yang sama ke fungsi pengendali EXECUTE
seperti untuk intent EXECUTE
ke fulfillment cloud Anda. Demikian pula, pengendali EXECUTE Anda menampilkan
data output dalam format yang sama seperti dari pemrosesan intent EXECUTE.
Untuk menyederhanakan pembuatan respons, Anda dapat menggunakan class Execute.Response.Builder yang disediakan oleh Local Home SDK.
Aplikasi Anda tidak memiliki akses langsung ke alamat IP perangkat. Sebagai gantinya,
gunakan antarmuka
CommandRequest
untuk membuat perintah berdasarkan salah satu protokol berikut: UDP, TCP, atau HTTP. Kemudian, panggil fungsi
deviceManager.send()
untuk mengirim perintah.
Saat menargetkan perintah ke perangkat, gunakan ID perangkat (dan parameter dari kolom customData, jika disertakan) dari respons SYNC untuk berkomunikasi dengan perangkat.
Contoh
Cuplikan kode berikut menunjukkan cara membuat pengendali EXECUTE.
const executeHandler = (request: IntentFlow.ExecuteRequest): Promise<IntentFlow.ExecuteResponse> => { // Extract command(s) and device target(s) from request const command = request.inputs[0].payload.commands[0]; const execution = command.execution[0]; const response = new Execute.Response.Builder() .setRequestId(request.requestId); const result = command.devices.map((device) => { // Target id of the device provided in the SYNC response const deviceId = device.id; // Metadata for the device provided in the SYNC response // Use customData to provide additional required execution parameters const customData: any = device.customData; // Convert execution command into payload for local device let devicePayload: string; // ... // Construct a local device command over TCP const deviceCommand = new DataFlow.TcpRequestData(); deviceCommand.requestId = request.requestId; deviceCommand.deviceId = deviceId; deviceCommand.data = devicePayload; deviceCommand.port = customData.port; deviceCommand.operation = Constants.TcpOperation.WRITE; // Send command to the local device return localHomeApp.getDeviceManager() .send(deviceCommand) .then((result) => { response.setSuccessState(result.deviceId, state); }) .catch((err: IntentFlow.HandlerError) => { err.errorCode = err.errorCode || IntentFlow.ErrorCode.INVALID_REQUEST; response.setErrorState(device.id, err.errorCode); }); }); // Respond once all commands complete return Promise.all(result) .then(() => response.build()); };
Mengimplementasikan pengendali QUERY
Pengendali QUERY Anda di aplikasi memproses permintaan pengguna dan menggunakan
Local Home SDK untuk melaporkan status perangkat smart Anda.
Platform Local Home meneruskan payload permintaan yang sama ke fungsi pengendali 'QUERY'
seperti untuk intent QUERY
ke fulfillment cloud Anda. Demikian pula, pengendali QUERY Anda menampilkan data
dalam format yang sama seperti dari pemrosesan intent QUERY.
Mengirim perintah ke perangkat di belakang hub
Untuk mengontrol perangkat akhir di balik hub, Anda mungkin perlu memberikan informasi tambahan
dalam payload perintah khusus protokol yang dikirim ke hub agar hub
dapat mengidentifikasi perangkat yang dituju oleh perintah tersebut. Dalam beberapa kasus, hal ini dapat
disimpulkan langsung dari nilai device.id, tetapi jika tidak demikian,
Anda harus menyertakan data tambahan ini sebagai bagian dari kolom customData.
Jika Anda membuat aplikasi menggunakan TypeScript, jangan lupa untuk mengompilasi aplikasi ke JavaScript. Anda dapat menggunakan sistem modul pilihan Anda untuk menulis kode. Pastikan target Anda didukung oleh browser Chrome.