Repository: actions-on-google/smart-home-local Branch: master Commit: b60fe100d9f0 Files: 42 Total size: 90.8 KB Directory structure: gitextract_3ky85hap/ ├── .gitignore ├── CONTRIBUTING.md ├── LICENSE ├── README.md ├── app/ │ ├── app.ts │ ├── discovery_mdns.ts │ ├── discovery_udp.ts │ ├── discovery_upnp.ts │ ├── execution_http.ts │ ├── execution_tcp.ts │ ├── execution_udp.ts │ ├── firebase.json │ ├── index.template.html │ ├── index.ts │ ├── package.json │ ├── serve.js │ ├── test.ts │ ├── test.ts.md │ ├── test.ts.snap │ ├── tsconfig.json │ ├── tslint.json │ ├── types.ts │ ├── webpack.config.node.js │ └── webpack.config.web.js ├── device/ │ ├── README.md │ ├── discovery_mdns.ts │ ├── discovery_udp.ts │ ├── discovery_upnp.ts │ ├── execution_http.ts │ ├── execution_tcp.ts │ ├── execution_udp.ts │ ├── opc_device.ts │ ├── package.json │ ├── server.ts │ ├── tsconfig.json │ ├── tslint.json │ └── types.ts └── functions/ ├── firebase.json ├── index.ts ├── package.json ├── tsconfig.json └── tslint.json ================================================ FILE CONTENTS ================================================ ================================================ FILE: .gitignore ================================================ dist/ node_modules/ .firebase/ coverage/ device/**.js device/**.js.map functions/**.js functions/**.js.map firebase-debug.log ================================================ FILE: CONTRIBUTING.md ================================================ # How to become a contributor and submit your own code ## Contributor License Agreements We'd love to accept your sample apps and patches! Before we can take them, we have to jump a couple of legal hurdles. Please fill out either the individual or corporate Contributor License Agreement (CLA). * If you are an individual writing original source code and you're sure you own the intellectual property, then you'll need to sign an [individual CLA](https://developers.google.com/open-source/cla/individual). * If you work for a company that wants to allow you to contribute your work, then you'll need to sign a [corporate CLA](https://developers.google.com/open-source/cla/corporate). Follow either of the two links above to access the appropriate CLA and instructions for how to sign and return it. Once we receive it, we'll be able to accept your pull requests. ## Contributing A Patch 1. Submit an issue describing your proposed change to the repo in question. 1. The repo owner will respond to your issue promptly. 1. If your proposed change is accepted, and you haven't already done so, sign a Contributor License Agreement (see details above). 1. Fork the desired repo, develop and test your code changes. 1. Ensure that your code adheres to the existing style in the sample to which you are contributing. Refer to the [Google Cloud Platform Samples Style Guide](https://github.com/GoogleCloudPlatform/Template/wiki/style.html) for the recommended coding standards for this organization. 1. Ensure that your code has an appropriate set of unit tests which all pass. 1. Submit a pull request. ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright {yyyy} {name of copyright owner} Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: README.md ================================================ # Local Home SDK sample This project contains the source for the [Smart Home local fulfillment codelab](https://developers.home.google.com/codelabs/smarthome-local), which demonstrates integrating a Cloud-to-cloud integration with the [Local Home SDK](https://developers.google.com/assistant/smarthome/concepts/local). ## Support - Stack Overflow: https://stackoverflow.com/questions/tagged/google-smart-home If you've found an error in the sample or the codelab, please file an issue: https://github.com/google-home/smart-home-local/issues ## License See [LICENSE](LICENSE). ## Terms Your use of this sample is subject to, and by using or downloading the sample files you agree to comply with, the [Google APIs Terms of Service](https://developers.google.com/terms/). ================================================ FILE: app/app.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// import * as discoveryUdp from './discovery_udp'; import * as discoveryMdns from './discovery_mdns'; import * as discoveryUpnp from './discovery_upnp'; import * as executionUdp from './execution_udp'; import * as executionTcp from './execution_tcp'; import * as executionHttp from './execution_http'; import type {ICustomData, ControlKind} from './types'; export class HomeApp { private readonly appDiscoveryUdp: discoveryUdp.HomeApp; private readonly appDiscoveryMdns: discoveryMdns.HomeApp; private readonly appDiscoveryUpnp: discoveryUpnp.HomeApp; private readonly appExecutionUdp: executionUdp.HomeApp; private readonly appExecutionTcp: executionTcp.HomeApp; private readonly appExecutionHttp: executionHttp.HomeApp; constructor(app: smarthome.App) { this.appDiscoveryUdp = new discoveryUdp.HomeApp(app); this.appDiscoveryMdns = new discoveryMdns.HomeApp(app); this.appDiscoveryUpnp = new discoveryUpnp.HomeApp(app); this.appExecutionUdp = new executionUdp.HomeApp(app); this.appExecutionTcp = new executionTcp.HomeApp(app); this.appExecutionHttp = new executionHttp.HomeApp(app); } public identifyHandler = (identifyRequest: smarthome.IntentFlow.IdentifyRequest): Promise => { console.log('IDENTIFY request:', identifyRequest); const identifyResponse = (() => { // Infer discovery protocol from scan data. const device = identifyRequest.inputs[0].payload.device; if (device.udpScanData !== undefined) { // UDP discovery return this.appDiscoveryUdp.identifyHandler(identifyRequest); } else if (device.mdnsScanData !== undefined) { // mDNS discovery return this.appDiscoveryMdns.identifyHandler(identifyRequest); } else if (device.udpScanData !== undefined) { // UDP discovery return this.appDiscoveryUpnp.identifyHandler(identifyRequest); } else { throw new Error(`Missing or incorrect scan data for intent requestId ${identifyRequest.requestId}`); } })(); console.log('IDENTIFY response:', identifyResponse); return identifyResponse; } public reachableDevicesHandler = (reachableDevicesRequest: smarthome.IntentFlow.ReachableDevicesRequest): Promise => { console.log('REACHABLE_DEVICES request:', reachableDevicesRequest); const reachableDevicesResponse = (() => { // Infer discovery protocol from scan data. const device = reachableDevicesRequest.inputs[0].payload.device; if (device.udpScanData !== undefined) { // UDP discovery return this.appDiscoveryUdp.reachableDevicesHandler(reachableDevicesRequest); } else if (device.mdnsScanData !== undefined) { // mDNS discovery return this.appDiscoveryMdns.reachableDevicesHandler(reachableDevicesRequest); } else if (device.udpScanData !== undefined) { // UDP discovery return this.appDiscoveryUpnp.reachableDevicesHandler(reachableDevicesRequest); } else { throw new Error(`Missing or incorrect scan data for intent requestId ${reachableDevicesRequest.requestId}`); } })(); console.log('REACHABLE_DEVICES response:', reachableDevicesResponse); return reachableDevicesResponse; } public executeHandler = (executeRequest: smarthome.IntentFlow.ExecuteRequest): Promise => { console.log('EXECUTE request:', executeRequest); const executeResponse = (() => { // Infer execution protocol from the first device custom data. const device = executeRequest.inputs[0].payload.commands[0].devices[0]; const customData = device.customData as ICustomData; switch (customData.control_protocol) { case 'UDP': return this.appExecutionUdp.executeHandler(executeRequest); case 'TCP': return this.appExecutionTcp.executeHandler(executeRequest); case 'HTTP': return this.appExecutionHttp.executeHandler(executeRequest); default: throw new Error(`Unsupported protocol for EXECUTE intent requestId ${executeRequest.requestId}: ${customData.control_protocol}`); } })(); console.log('EXECUTE response:', executeResponse); return executeResponse; } public queryHandler = (queryRequest: smarthome.IntentFlow.QueryRequest): Promise => { console.log('QUERY request:', queryRequest); const queryResponse = (() => { // Infer execution protocol from the first device custom data. const device = queryRequest.inputs[0].payload.devices[0]; const customData = device.customData as ICustomData; switch (customData.control_protocol) { case 'UDP': return this.appExecutionUdp.queryHandler(queryRequest); case 'TCP': return this.appExecutionTcp.queryHandler(queryRequest); case 'HTTP': return this.appExecutionHttp.queryHandler(queryRequest); default: throw new Error(`Unsupported protocol for QUERY intent requestId ${queryRequest.requestId}: ${customData.control_protocol}`); } })(); console.log('QUERY response:', queryResponse); return queryResponse; } } ================================================ FILE: app/discovery_mdns.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// require('array.prototype.flatmap/auto'); import type {IDiscoveryData, ICustomData} from './types'; export class HomeApp { constructor(private readonly app: smarthome.App) { this.app = app; } async identifyHandler(identifyRequest: smarthome.IntentFlow.IdentifyRequest): Promise { // TODO(proppy): handle multiple inputs. const device = identifyRequest.inputs[0].payload.device; const scanData = device.mdnsScanData as smarthome.IntentFlow.MdnsScanData; const discoveryData: IDiscoveryData = { id: scanData.txt.id, model: scanData.txt.model, hw_rev: scanData.txt.hw_rev, fw_rev: scanData.txt.fw_rev, channels: scanData.txt.channels .split(',') .map((channel) => parseInt(channel, 10)), }; console.debug('discoveryData:', discoveryData); return { requestId: identifyRequest.requestId, intent: smarthome.Intents.IDENTIFY, payload: { device: { deviceInfo: { manufacturer: 'fakecandy corp', model: discoveryData.model, hwVersion: discoveryData.hw_rev || '', swVersion: discoveryData.fw_rev || '', }, ...((discoveryData.channels.length > 1) ? {id: discoveryData.id, isProxy: true, isLocalOnly: true} : { id: discoveryData.id || 'deviceId', verificationId: discoveryData.id, }), }, }, }; } async reachableDevicesHandler( reachableDevicesRequest: smarthome.IntentFlow.ReachableDevicesRequest): Promise { const proxyDeviceId = reachableDevicesRequest.inputs[0].payload.device.id; const devices = reachableDevicesRequest.devices.flatMap((d) => { const customData = d.customData as ICustomData; if (customData.proxy === proxyDeviceId) { return [{verificationId: `${proxyDeviceId}-${customData.channel}`}]; } return []; }); return { intent: smarthome.Intents.REACHABLE_DEVICES, requestId: reachableDevicesRequest.requestId, payload: { devices, }, }; } } ================================================ FILE: app/discovery_udp.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// require('array.prototype.flatmap/auto'); import cbor from 'cbor'; import type {ICustomData, IDiscoveryData} from './types'; export class HomeApp { constructor(private readonly app: smarthome.App) { this.app = app; } async identifyHandler(identifyRequest: smarthome.IntentFlow.IdentifyRequest): Promise { // TODO(proppy): handle multiple inputs. const device = identifyRequest.inputs[0].payload.device; const discoveryData = await cbor.decodeFirst(Buffer.from(device.udpScanData!.data, 'hex')) as IDiscoveryData; console.debug('discoveryData:', JSON.stringify(discoveryData, null, 2)); return { requestId: identifyRequest.requestId, intent: smarthome.Intents.IDENTIFY, payload: { device: { deviceInfo: { manufacturer: 'fakecandy corp', model: discoveryData.model, hwVersion: discoveryData.hw_rev || '', swVersion: discoveryData.fw_rev || '', }, ...((discoveryData.channels.length > 1) ? {id: discoveryData.id, isProxy: true, isLocalOnly: true} : { id: discoveryData.id || 'deviceId', verificationId: discoveryData.id, }), }, }, }; } async reachableDevicesHandler( reachableDevicesRequest: smarthome.IntentFlow.ReachableDevicesRequest): Promise { const proxyDeviceId = reachableDevicesRequest.inputs[0].payload.device.id; const devices = reachableDevicesRequest.devices.flatMap((d) => { const customData = d.customData as ICustomData; if (customData.proxy === proxyDeviceId) { return [{verificationId: `${proxyDeviceId}-${customData.channel}`}]; } return []; }); return { intent: smarthome.Intents.REACHABLE_DEVICES, requestId: reachableDevicesRequest.requestId, payload: { devices, }, }; } } ================================================ FILE: app/discovery_upnp.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// require('array.prototype.flatmap/auto'); import {DOMParser} from 'xmldom'; import type {ICustomData, IDiscoveryData} from './types'; export class HomeApp { constructor(private readonly app: smarthome.App) { this.app = app; } async identifyHandler(identifyRequest: smarthome.IntentFlow.IdentifyRequest): Promise { // TODO(proppy): handle multiple inputs. const device = identifyRequest.inputs[0].payload.device; const scanData = device.upnpScanData as smarthome.IntentFlow.UpnpScanData; // Request and parse XML device description const deviceCommand = new smarthome.DataFlow.HttpRequestData(); deviceCommand.requestId = identifyRequest.requestId; deviceCommand.deviceId = ''; deviceCommand.port = scanData.port; deviceCommand.method = smarthome.Constants.HttpOperation.GET; deviceCommand.path = scanData.location; console.debug('UPnP HTTP command: ', deviceCommand); // Request the XML device description const httpResponseData = await this.app.getDeviceManager().send(deviceCommand) as smarthome.DataFlow.HttpResponseData; const xmlResponse = httpResponseData.httpResponse.body as string; console.debug('XML device description', xmlResponse); const deviceDescription = new DOMParser() .parseFromString(xmlResponse, 'text/xml'); // Parse UPnP type strings const deviceElement = deviceDescription.getElementsByTagName('device')[0]; const deviceId = deviceElement.getElementsByTagName('UDN')[0] .textContent?.match(/uuid:([a-zA-Z0-9]+)/)?.[1] || ''; const deviceModel = deviceElement.getElementsByTagName('modelName')[0] .textContent || ''; const serviceElements = deviceElement.getElementsByTagName('service'); const channelList = Array.from(serviceElements).map((service) => { const channel = service.getElementsByTagName('serviceId')[0] .textContent?.match(/urn:sample:serviceId:strand-([0-9]+)/); return channel ? parseInt(channel[1], 10) : 0; }); const discoveryData: IDiscoveryData = { id: deviceId, model: deviceModel, channels: channelList, }; console.debug('discoveryData:', discoveryData); return { requestId: identifyRequest.requestId, intent: smarthome.Intents.IDENTIFY, payload: { device: { deviceInfo: { manufacturer: 'fakecandy corp', model: discoveryData.model, hwVersion: discoveryData.hw_rev || '', swVersion: discoveryData.fw_rev || '', }, ...((discoveryData.channels.length > 1) ? {id: discoveryData.id, isProxy: true, isLocalOnly: true} : { id: discoveryData.id || 'deviceId', verificationId: discoveryData.id, }), }, }, }; } async reachableDevicesHandler( reachableDevicesRequest: smarthome.IntentFlow.ReachableDevicesRequest): Promise { const proxyDeviceId = reachableDevicesRequest.inputs[0].payload.device.id; const devices = reachableDevicesRequest.devices.flatMap((d) => { const customData = d.customData as ICustomData; if (customData.proxy === proxyDeviceId) { return [{verificationId: `${proxyDeviceId}-${customData.channel}`}]; } return []; }); return { intent: smarthome.Intents.REACHABLE_DEVICES, requestId: reachableDevicesRequest.requestId, payload: { devices, }, }; } } ================================================ FILE: app/execution_http.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// const opcStream = require('opc'); const opcStrand = require('opc/strand'); import type {IColorAbsolute, ICustomData} from './types'; export class HomeApp { constructor(private readonly app: smarthome.App) { this.app = app; } async executeHandler(executeRequest: smarthome.IntentFlow.ExecuteRequest): Promise { // TODO(proppy): handle multiple inputs/commands. const command = executeRequest.inputs[0].payload.commands[0]; // TODO(proppy): handle multiple executions. const execution = command.execution[0]; if (execution.command !== 'action.devices.commands.ColorAbsolute') { throw new Error(`Unsupported command: ${execution.command}`); } // Create execution response to capture individual command // success/failure for each devices. const executeResponse = new smarthome.Execute.Response.Builder().setRequestId( executeRequest.requestId); // Handle light device commands for all devices. await Promise.all(command.devices.map(async (device) => { // Create OPC set-pixel-color 8-bit message from ColorAbsolute command. const params = execution.params as IColorAbsolute const customData = device.customData as ICustomData; const rgb = params.color.spectrumRGB; const colorBuf = Buffer.alloc(customData.leds * 3); for (let i = 0; i < colorBuf.length; i += 3) { colorBuf.writeUInt8(rgb >> 16 & 0xff, i + 0); // R colorBuf.writeUInt8(rgb >> 8 & 0xff, i + 1); // G colorBuf.writeUInt8(rgb >> 0 & 0xff, i + 2); // B } const stream = opcStream(); stream.writePixels(customData.channel, colorBuf); const opcMessage = stream.read(); const setPixelColorCommand = new smarthome.DataFlow.HttpRequestData(); setPixelColorCommand.requestId = executeRequest.requestId; setPixelColorCommand.deviceId = device.id; setPixelColorCommand.port = customData.port; setPixelColorCommand.method = smarthome.Constants.HttpOperation.POST; setPixelColorCommand.path = `/${customData.channel}` setPixelColorCommand.dataType = 'application/octet-stream'; setPixelColorCommand.data = colorBuf.toString('base64'); console.debug('HTTP setPixelColorCommand:', setPixelColorCommand); // Dispatch command. try { const setPixelColorResponse = await this.app.getDeviceManager().send(setPixelColorCommand); console.debug('HTTP setPixelColorResponse:', setPixelColorResponse); const state = { ...params, online: true, }; executeResponse.setSuccessState(setPixelColorResponse.deviceId, state); } catch (e) { executeResponse.setErrorState(device.id, e.errorCode); } })); // Return execution response to smarthome infrastructure. return executeResponse.build(); } async queryHandler(queryRequest: smarthome.IntentFlow.QueryRequest): Promise { // TODO(proppy): handle multiple devices. const device = queryRequest.inputs[0].payload.devices[0]; const customData = device.customData as ICustomData; const stream = opcStream(); stream.writeMessage(customData.channel, 0xff, // SYSEX Buffer.from([ 0x00, 0x03, // System IDs 0x00, 0x01 // get-pixel-color ])); const opcMessage = stream.read(); const getPixelColorCommand = new smarthome.DataFlow.HttpRequestData(); getPixelColorCommand.requestId = queryRequest.requestId; getPixelColorCommand.deviceId = device.id; getPixelColorCommand.port = customData.port; getPixelColorCommand.method = smarthome.Constants.HttpOperation.GET; getPixelColorCommand.path = `/${customData.channel}` console.debug('HTTP getPixelColorCommand:', getPixelColorCommand); const getPixelColorResponse = await this.app.getDeviceManager().send(getPixelColorCommand) as smarthome.DataFlow.HttpResponseData; console.debug('HTTP getPixelColorResponse:', getPixelColorResponse); if (getPixelColorResponse.httpResponse.statusCode !== 200) { throw new Error(`Unsupported protocol for OPC get-pixel-color: HTTP`); } const opcPayload = Buffer.from(getPixelColorResponse.httpResponse.body as string, 'base64'); console.debug('HTTP opcPayload:', opcPayload); const opcChannel = opcPayload.readUInt8(0); const opcCommand = opcPayload.readUInt8(1); // SYSEX const opcDataSize = opcPayload.readUInt16BE(2); const opcData = opcPayload.slice(4); if (opcDataSize !== opcData.length) { throw new Error(`Unexpected message size: expected: ${opcDataSize} got: ${opcData.length}`); } const strand = opcStrand(opcData); const pixel = strand.getPixel(0); // get first pixel of the strand. const rgb = pixel[0] << 16 | pixel[1] << 8 | pixel[2]; return { requestId: queryRequest.requestId, payload: { devices: { [device.id]: { online: true, color: { spectrumRgb: rgb } } } } }; } } ================================================ FILE: app/execution_tcp.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// const opcStream = require('opc'); const opcStrand = require('opc/strand'); import type {IColorAbsolute, ICustomData} from './types'; export class HomeApp { constructor(private readonly app: smarthome.App) { this.app = app; } async executeHandler(executeRequest: smarthome.IntentFlow.ExecuteRequest): Promise { // TODO(proppy): handle multiple inputs/commands. const command = executeRequest.inputs[0].payload.commands[0]; // TODO(proppy): handle multiple executions. const execution = command.execution[0]; if (execution.command !== 'action.devices.commands.ColorAbsolute') { throw new Error(`Unsupported command: ${execution.command}`); } // Create execution response to capture individual command // success/failure for each devices. const executeResponse = new smarthome.Execute.Response.Builder().setRequestId( executeRequest.requestId); // Handle light device commands for all devices. await Promise.all(command.devices.map(async (device) => { // Create OPC set-pixel-color 8-bit message from ColorAbsolute command. const params = execution.params as IColorAbsolute const customData = device.customData as ICustomData; const rgb = params.color.spectrumRGB; const colorBuf = Buffer.alloc(customData.leds * 3); for (let i = 0; i < colorBuf.length; i += 3) { colorBuf.writeUInt8(rgb >> 16 & 0xff, i + 0); // R colorBuf.writeUInt8(rgb >> 8 & 0xff, i + 1); // G colorBuf.writeUInt8(rgb >> 0 & 0xff, i + 2); // B } const stream = opcStream(); stream.writePixels(customData.channel, colorBuf); const opcMessage = stream.read(); const setPixelColorCommand = new smarthome.DataFlow.TcpRequestData(); setPixelColorCommand.requestId = executeRequest.requestId; setPixelColorCommand.deviceId = device.id; setPixelColorCommand.port = customData.port; setPixelColorCommand.operation = smarthome.Constants.TcpOperation.WRITE; setPixelColorCommand.data = opcMessage.toString('hex'); console.debug('TCP setPixelColorCommand:', setPixelColorCommand); // Dispatch command. try { const setPixelColorResponse = await this.app.getDeviceManager().send(setPixelColorCommand); console.debug('TCP setPixelColorResponse:', setPixelColorResponse); const state = { ...params, online: true, }; executeResponse.setSuccessState(setPixelColorResponse.deviceId, state); } catch (e) { executeResponse.setErrorState(device.id, e.errorCode || 'hardError'); } })); // Return execution response to smarthome infrastructure. return executeResponse.build(); } async queryHandler(queryRequest: smarthome.IntentFlow.QueryRequest): Promise { // TODO(proppy): handle multiple devices. const device = queryRequest.inputs[0].payload.devices[0]; const customData = device.customData as ICustomData; const stream = opcStream(); stream.writeMessage(customData.channel, 0xff, // SYSEX Buffer.from([ 0x00, 0x03, // System IDs 0x00, 0x01 // get-pixel-color ])); const opcMessage = stream.read(); const getPixelColorCommand = new smarthome.DataFlow.TcpRequestData(); getPixelColorCommand.requestId = queryRequest.requestId; getPixelColorCommand.deviceId = device.id; getPixelColorCommand.port = customData.port; getPixelColorCommand.operation = smarthome.Constants.TcpOperation.WRITE; getPixelColorCommand.data = opcMessage.toString('hex'); console.debug('TCP getPixelColorCommand:', getPixelColorCommand); const getPixelColorResponse = await this.app.getDeviceManager().send(getPixelColorCommand); console.debug('TCP getPixelColorResponse:', getPixelColorResponse); const readHeaderCommand = new smarthome.DataFlow.TcpRequestData(); readHeaderCommand.operation = smarthome.Constants.TcpOperation.READ; readHeaderCommand.requestId = queryRequest.requestId; readHeaderCommand.deviceId = device.id; readHeaderCommand.port = customData.port; const opcHeaderSize = 4; readHeaderCommand.bytesToRead = opcHeaderSize + customData.leds * 3; console.debug('TCP readHeaderCommand:', readHeaderCommand); const readHeaderResponse = await this.app.getDeviceManager().send(readHeaderCommand) as smarthome.DataFlow.TcpResponseData; console.debug('TCP readHeaderResponse:', readHeaderResponse); const opcPayload = Buffer.from(readHeaderResponse.tcpResponse.data, 'hex'); console.debug('TCP opcPayload:', opcPayload); const opcChannel = opcPayload.readUInt8(0); const opcCommand = opcPayload.readUInt8(1); // SYSEX const opcDataSize = opcPayload.readUInt16BE(2); console.debug('TCP opcDataSize:', opcDataSize); const opcData = opcPayload.slice(4); console.debug('TCP opcData:', opcData); if (opcDataSize !== opcData.length) { throw new Error(`Unexpected message size: expected: ${opcDataSize} got: ${opcData.length}`); } const strand = opcStrand(opcData); const pixel = strand.getPixel(0); // get first pixel of the strand. const rgb = pixel[0] << 16 | pixel[1] << 8 | pixel[2]; return { requestId: queryRequest.requestId, payload: { devices: { [device.id]: { online: true, color: { spectrumRgb: rgb } } } } }; } } ================================================ FILE: app/execution_udp.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// const opcStream = require('opc'); const opcStrand = require('opc/strand'); import type {IColorAbsolute, ICustomData} from './types'; export class HomeApp { constructor(private readonly app: smarthome.App) { this.app = app; } async executeHandler(executeRequest: smarthome.IntentFlow.ExecuteRequest): Promise { // TODO(proppy): handle multiple inputs/commands. const command = executeRequest.inputs[0].payload.commands[0]; // TODO(proppy): handle multiple executions. const execution = command.execution[0]; if (execution.command !== 'action.devices.commands.ColorAbsolute') { throw new Error(`Unsupported command: ${execution.command}`); } // Create execution response to capture individual command // success/failure for each devices. const executeResponse = new smarthome.Execute.Response.Builder().setRequestId( executeRequest.requestId); // Handle light device commands for all devices. await Promise.all(command.devices.map(async (device) => { // Create OPC set-pixel-color 8-bit message from ColorAbsolute command. const params = execution.params as IColorAbsolute const customData = device.customData as ICustomData; const rgb = params.color.spectrumRGB; const colorBuf = Buffer.alloc(customData.leds * 3); for (let i = 0; i < colorBuf.length; i += 3) { colorBuf.writeUInt8(rgb >> 16 & 0xff, i + 0); // R colorBuf.writeUInt8(rgb >> 8 & 0xff, i + 1); // G colorBuf.writeUInt8(rgb >> 0 & 0xff, i + 2); // B } const stream = opcStream(); stream.writePixels(customData.channel, colorBuf); const opcMessage = stream.read(); const setPixelColorCommand = new smarthome.DataFlow.UdpRequestData(); setPixelColorCommand.requestId = executeRequest.requestId; setPixelColorCommand.deviceId = device.id; setPixelColorCommand.port = customData.port; setPixelColorCommand.data = opcMessage.toString('hex'); console.debug('UDP setPixelColorCommand:', setPixelColorCommand); // Dispatch command. try { const setPixelColorResponse = await this.app.getDeviceManager().send(setPixelColorCommand); console.debug('UDP setPixelColorResponse:', setPixelColorResponse); const state = { ...params, online: true, }; executeResponse.setSuccessState(setPixelColorResponse.deviceId, state); } catch (e) { executeResponse.setErrorState(device.id, e.errorCode); } })); console.log('EXECUTE response:', executeResponse); // Return execution response to smarthome infrastructure. return executeResponse.build(); } async queryHandler(queryRequest: smarthome.IntentFlow.QueryRequest): Promise { // TODO(proppy): handle multiple devices. const device = queryRequest.inputs[0].payload.devices[0]; const customData = device.customData as ICustomData; const stream = opcStream(); stream.writeMessage(customData.channel, 0xff, // SYSEX Buffer.from([ 0x00, 0x03, // System IDs 0x00, 0x01 // get-pixel-color ])); const opcMessage = stream.read(); const getPixelColorCommand = new smarthome.DataFlow.UdpRequestData(); getPixelColorCommand.requestId = queryRequest.requestId; getPixelColorCommand.deviceId = device.id; getPixelColorCommand.port = customData.port; getPixelColorCommand.data = opcMessage.toString('hex'); getPixelColorCommand.expectedResponsePackets = 1; console.debug('UDP getPixelColorCommand:', getPixelColorCommand); const getPixelColorResponse = await this.app.getDeviceManager().send(getPixelColorCommand) as smarthome.DataFlow.UdpResponseData; console.debug('UDP getPixelColorResponse:', getPixelColorResponse); const opcPayload = Buffer.from(getPixelColorResponse.udpResponse.responsePackets![0], 'hex'); console.debug('UDP opcPayload:', opcPayload); const opcChannel = opcPayload.readUInt8(0); const opcCommand = opcPayload.readUInt8(1); // SYSEX const opcDataSize = opcPayload.readUInt16BE(2); const opcData = opcPayload.slice(4); if (opcDataSize !== opcData.length) { throw new Error(`Unexpected message size: expected: ${opcDataSize} got: ${opcData.length}`); } const strand = opcStrand(opcData); const pixel = strand.getPixel(0); // get first pixel of the strand. const rgb = pixel[0] << 16 | pixel[1] << 8 | pixel[2]; return { requestId: queryRequest.requestId, payload: { devices: { [device.id]: { online: true, color: { spectrumRgb: rgb } } } } }; } } ================================================ FILE: app/firebase.json ================================================ { "hosting": { "public": "dist", "ignore": [ "firebase.json", "**/.*", "**/node_modules/**" ] } } ================================================ FILE: app/index.template.html ================================================ Local Home SDK App ================================================ FILE: app/index.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// import {HomeApp} from './app'; const smarthomeApp: smarthome.App = new smarthome.App('0.0.1'); const homeApp = new HomeApp(smarthomeApp); smarthomeApp .onIdentify(homeApp.identifyHandler) .onReachableDevices(homeApp.reachableDevicesHandler) .onExecute(homeApp.executeHandler) .onQuery(homeApp.queryHandler) .listen() .then(() => { console.log('Ready'); }); ================================================ FILE: app/package.json ================================================ { "name": "local-home-sdk-sample", "version": "0.0.1", "description": "Sample for the Local Home SDK.", "private": true, "author": "Google", "license": "Apache-2.0", "dependencies": { "@google/local-home-sdk": "^1.4.0", "array.prototype.flatmap": "^1.2.3", "cbor": "^5.0.2", "opc": "^1.1.3", "xmldom": "^0.3.0" }, "devDependencies": { "@types/cbor": "^5.0.0", "@types/xmldom": "^0.1.29", "array.prototype.flat": "^1.2.3", "ava": "^3.4.0", "c8": "^7.1.2", "express": "^4.17.1", "firebase-tools": "^8.4.2", "html-webpack-plugin": "^3.2.0", "ts-loader": "^7.0.5", "ts-node": "^8.10.2", "tslint": "^6.1.2", "typescript": "^3.9.5", "webpack": "^4.41.6", "webpack-cli": "^3.3.11", "webpack-dev-middleware": "^3.7.2" }, "scripts": { "compile": "tsc --noEmit", "test": "c8 ava test.ts", "lint": "tslint --project .", "build": "npm run build-web && npm run build-node", "build-web": "webpack --config webpack.config.web.js", "build-node": "webpack --config webpack.config.node.js", "start": "node serve.js", "deploy": "firebase deploy --only hosting" }, "ava": { "extensions": [ "ts" ], "require": [ "ts-node/register" ] } } ================================================ FILE: app/serve.js ================================================ /** * Copyright 2020, Google LLC * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const os = require('os'); const path = require('path'); require('array.prototype.flat/auto'); const app = require('express')(); const webpack = require('webpack'); const middleware = require('webpack-dev-middleware'); const arg = (process.argv[2] || ':8080').split(':') const port = arg.pop(); const addr = arg.pop() || firstPublicAddress() || '0.0.0.0'; function firstPublicAddress() { return Object.values(os.networkInterfaces()) .flat() .filter((iface) => iface.family === 'IPv4' && iface.internal === false) .map((iface) => iface.address) .shift(); } const webpack_web = webpack(require('./webpack.config.web')); webpack_web.hooks.done.tap('webpack.serve.js', () => { console.log(`[local-home-app] Chrome ondevice testing URL: http://${addr}:${port}/web/index.html`); }); const webpack_node = webpack(require('./webpack.config.node')); webpack_node.hooks.done.tap('webpack.serve.js', () => { console.log(`[local-home-app] Node ondevice testing URL: http://${addr}:${port}/node/bundle.js`); }); app.use('/web', middleware(webpack_web)) .use('/node', middleware(webpack_node)) .listen(port); ================================================ FILE: app/test.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// import test from 'ava'; import cbor from 'cbor'; import {HomeApp} from './app'; import {IColorAbsolute, IDiscoveryData} from './types'; function smarthomeDeviceManagerStub(deviceId: string, error?: any) { const DeviceManager = class { public commands = new Array(); public send(command: smarthome.DataFlow.TcpRequestData): Promise { if (error) { return Promise.reject(error); } this.commands.push(command); return Promise.resolve({ deviceId, }); } }; return new DeviceManager(); } function smarthomeAppStub(deviceManager?: any) { const App = class { private version: string; constructor(version: string) { this.version = version; } public getDeviceManager() { return deviceManager; } public listen() { return Promise.resolve(); } public on(eventType: any, handler: any) { return this; } public onExecute(handler: any) { return this; } public onIdentify(handler: any) { return this; } public onIndicate(handler: any) { return this; } public onParseNotification(handler: any) { return this; } public onProvision(handler: any) { return this; } public onProxySelected(handler: any) { return this; } public onQuery(handler: any) { return this; } public onReachableDevices(handler: any) { return this; } public onRegister(handler: any) { return this; } public onUnprovision(handler: any) { return this; } public onUpdate(handler: any) { return this; } }; return new App('test-version'); } test.before((t) => { (global as any).smarthome = { Intents: { IDENTIFY: 'action.devices.IDENTIFY', EXECUTE: 'action.devices.EXECUTE', }, DataFlow: { TcpRequestData: class {}, }, Constants: { TcpOperation: { WRITE: 'WRITE', }, }, Execute: { Response: { Builder: class { private requestId: string = ''; private commands: smarthome.IntentFlow.ExecuteResponseCommands[] = []; public setRequestId(requestId: string) { this.requestId = requestId; return this; } public setSuccessState(deviceId: string, state: object) { this.commands.push({ ids: [deviceId], status: 'SUCCESS', states: state, }); } public setErrorState(deviceId: string, errorCode: smarthome.IntentFlow.ExecuteErrors) { this.commands.push({ ids: [deviceId], status: 'ERROR', errorCode, }); } public build() { return { requestId: this.requestId, payload: { commands: this.commands, }, }; } }, }, }, }; }); // TODO(proppy): add IDENTIFY hub test test('IDENTIFY handler', async (t) => { const app = new HomeApp(smarthomeAppStub()); const deviceData: IDiscoveryData = { id: 'device-local-id', model: 'device-mode', hw_rev: 'hw-rev', fw_rev: 'fw-rev', channels: [1], }; const udpScanPayload = cbor.encode(deviceData); const identifyResponse = await app.identifyHandler({ requestId: 'request-id', inputs: [ { intent: smarthome.Intents.IDENTIFY, payload: { device: { radioTypes: [], udpScanData: { data: udpScanPayload.toString('hex'), }, }, structureData: {}, params: {}, }, }, ], devices: [], }); t.is((identifyResponse.payload.device as {verificationId: string}).verificationId, deviceData.id); }); // TODO(proppy): add REACHEABLE_DEVICES hub test // TODO(proppy): add EXECUTE hub test test('EXECUTE handler ColorAbsolute', async (t) => { const deviceId = 'device-id'; const command = 'action.devices.commands.ColorAbsolute'; const params = { color: { name: 'magenta', spectrumRGB: 0xff00ff, }, }; const deviceManager = smarthomeDeviceManagerStub(deviceId); const smarthomeApp = smarthomeAppStub(deviceManager); const app = new HomeApp(smarthomeApp); const executeResponse = await app.executeHandler({ requestId: 'request-id', inputs: [ { intent: smarthome.Intents.EXECUTE, payload: { commands: [{ devices: [{ id: deviceId, customData: { channel: 1, leds: 8, control_protocol: 'TCP', }, }], execution: [{ command, params, }], }], structureData: {}, }, }, ], }); t.deepEqual(executeResponse.payload.commands, [{ ids: [deviceId], status: 'SUCCESS', states: { ...params, online: true, }, }]); t.is(deviceManager.commands.length, 1); t.is(deviceManager.commands[0].deviceId, deviceId); t.is(deviceManager.commands[0].operation, 'WRITE'); t.snapshot(deviceManager.commands[0].data); }); test('EXECUTE handler failure', async (t) => { const deviceId = 'device-id'; const command = 'action.devices.commands.ColorAbsolute'; const params = { color: { name: 'magenta', spectrumRGB: 0xff00ff, }, }; const deviceManager = smarthomeDeviceManagerStub(deviceId, {errorCode: 'some-error'}); const smarthomeApp = smarthomeAppStub(deviceManager); const app = new HomeApp(smarthomeApp); const executeResponse = await app.executeHandler({ requestId: 'request-id', inputs: [ { intent: smarthome.Intents.EXECUTE, payload: { commands: [{ devices: [{ id: deviceId, customData: { channel: 1, leds: 8, control_protocol: 'TCP', }, }], execution: [{ command, params, }], }], structureData: {}, }, }, ], }); t.deepEqual(executeResponse.payload.commands, [{ ids: [deviceId], status: 'ERROR', errorCode: 'some-error' as smarthome.IntentFlow.ExecuteErrors, }]); t.is(deviceManager.commands.length, 0); }); ================================================ FILE: app/test.ts.md ================================================ # Snapshot report for `test.ts` The actual snapshot is saved in `test.ts.snap`. Generated by [AVA](https://ava.li). ## opcMessageFromCommand: BrightnessAbsolute > Snapshot 1 Buffer @Uint8Array [ 00ff0020 00010001 7b227768 69746570 6f696e74 223a5b30 2e352c30 2e352c30 2e355d7d ] ## opcMessageFromCommand: ColorAbsolute > Snapshot 1 Buffer @Uint8Array [ 00000030 ff00ffff 00ffff00 ffff00ff ff00ffff 00ffff00 ffff00ff ff00ffff 00ffff00 ffff00ff ff00ffff 00ffff00 ffff00ff ] ## opcMessageFromCommand: OnOff > Snapshot 1 Buffer @Uint8Array [ 00ff001a 00010001 7b227768 69746570 6f696e74 223a5b31 2c312c31 5d7d ] ## EXECUTE handler ColorAbsolute > Snapshot 1 '01000018ff00ffff00ffff00ffff00ffff00ffff00ffff00ffff00ff' ================================================ FILE: app/tsconfig.json ================================================ { "compilerOptions": { "target": "es2018", "moduleResolution": "node", "strict": true, "lib": [ "ESNext.Array", "DOM" ], "esModuleInterop": true }, "files" : [ "index.ts", "app.ts", "discovery_udp.ts", "discovery_mdns.ts", "discovery_upnp.ts", "execution_udp.ts", "execution_tcp.ts", "execution_http.ts", "test.ts", "types.ts", "../device/types.ts" ] } ================================================ FILE: app/tslint.json ================================================ { "defaultSeverity": "error", "extends": [ "tslint:recommended" ], "rules": { "max-classes-per-file": false, "no-console": false, "no-bitwise": false, "no-var-requires": false, "object-literal-sort-keys": false } } ================================================ FILE: app/types.ts ================================================ /** * Copyright 2021, Google LLC * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import type {ControlKind, IDiscoveryData} from '../device/types'; export {ControlKind, IDiscoveryData}; export interface ICustomData { channel: number; leds: number; port: number; proxy: string; control_protocol: ControlKind; } export interface IColorAbsolute { color: {name: string; spectrumRGB: number;}; } ================================================ FILE: app/webpack.config.node.js ================================================ /** * Copyright 2020, Google LLC * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const path = require('path'); module.exports = { mode: 'production', target: 'node', entry: './index.ts', output: { path: path.resolve(__dirname, 'dist/node/'), filename: 'bundle.js' }, module: { rules: [ { test: /\.ts$/, loader: 'ts-loader' } ] }, resolve: { extensions: [ '.ts', '.js' ] }, }; ================================================ FILE: app/webpack.config.web.js ================================================ /** * Copyright 2020, Google LLC * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin') module.exports = { mode: 'production', target: 'web', entry: './index.ts', output: { path: path.resolve(__dirname, 'dist/web/'), filename: 'bundle.js' }, module: { rules: [ { test: /\.ts$/, loader: 'ts-loader' } ] }, resolve: { extensions: [ '.ts', '.js' ] }, plugins: [ new HtmlWebpackPlugin({ template: 'index.template.html' }) ] }; ================================================ FILE: device/README.md ================================================ # Local Home SDK Virtual Device ## Configuration The virtual device supports the following configuration parameters. ### Discovery parameters | Attribute | Value | Description | Default Value | | ------------- | ----- | ----------- | ------------- | | `discovery_protocol` | `MDNS`, `UPNP`, or `UDP` | Required. Protocol to use for discovery. | | `udp_discovery_packet` | Hex-encoded string | Broadcast packet expected for UDP discovery. | `A5A5A5A5` | | `udp_discovery_port` | Number | Port to listen for UDP discovery packet. | `3311` | | `mdns_service_name` | String | Service name to broadcast for mDNS. | `_sample._tcp.local` | | `mdns_instance_name` | String | Unique name of the mDNS service instance. | `strand1._sample._tcp.local` | | `upnp_service_type` | String | Service type to broadcast for UPnP. | `urn:sample:service:strand:1` | | `upnp_device_type` | String | Device type to broadcast for UPnP. | `urn:sample:device:strand:1` | | `upnp_server_port` | Number | Port to use for local UPnP server. |`8080` | ### Control parameters | Attribute | Value | Description | Default Value | | ------------- | ----- | ----------- | ------------- | | `control_protocol` | `UDP`, `TCP`, or `HTTP` | Required. Protocol to use for control. | | `opc_port` | Number | Optional. Port to use for local control server. | `7890` | ### Device parameters | Attribute | Value | Description | Default Value | | ------------- | ----- | ----------- | ------------- | |`device_id` | String | Required. Local device ID for the virtual device. | |`channel` | Number | Required. Add a new LED strand with the corresponding channel number. | |`device_model` | String | Optional. Manufacturer's model name for the device. | `fakecandy` | |`hardware_revision` | String | Optional. Manufacturer's hardware version. | `evt-1` | |`firmware_revision` | String | Optional. Manufacturer's firmware version. | `v1-beta` | |`led_char` | String | Optional. Character to display for each LED strand. | `◉` | |`led_count` | Number | Optional. Number of LEDs per strand. | `16` | ## Device protocol The virtual device uses the [Open Pixel Control](http://openpixelcontrol.org/) protocol for controlling RGB LEDs. The control procotol you have configured affects how the virtual devices expects to receives the OPC commands. | Protocol | Operation | Payload | | -------- | --------- | ------- | | UDP | WRITE | Raw OPC command | | TCP | WRITE | Raw OPC command | | HTTP | POST | OPC command as hex-encoded string | The following OPC commands are supported: ### Set 8-bit pixel colors (0x00) Below is an example OPC command to set a strand of 2 LEDs to white on channel 1: `0x01 0x00 0x00 0x06 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF` ================================================ FILE: device/discovery_mdns.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ const bonjour = require('bonjour'); const mdnsParser = require('multicast-dns-service-types'); import type {IDiscoveryData} from './types'; export function start(port: number, serviceName: string, discoveryData: IDiscoveryData) { // Validate and parse the input string const serviceParts = mdnsParser.parse(serviceName); // Publish the DNS-SD service const mdnsServer = bonjour(); mdnsServer.publish({ name: discoveryData.id, type: serviceParts.name, protocol: serviceParts.protocol, port, txt: discoveryData, }); // Log query events from internal mDNS server mdnsServer._server.mdns.on('query', (query: any) => { if (query.questions[0].name === serviceName) { console.debug(`Received mDNS query for ${serviceName}`); } }); console.log(`mDNS discovery advertising ${serviceName}`); } ================================================ FILE: device/discovery_udp.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import dgram from 'dgram'; import cbor from 'cbor'; import type {IDiscoveryData} from './types'; export function start(port: number, discoveryPayload: string, discoveryData: IDiscoveryData) { const discoveryPacket = Buffer.from(discoveryPayload, 'hex'); const socket = dgram.createSocket('udp4'); // Handle discovery request. socket.on('message', (msg, rinfo) => { if (msg.compare(discoveryPacket) !== 0) { console.warn('UDP received unknown payload:', msg, 'from:', rinfo); return; } console.debug('UDP received discovery payload:', msg, 'from:', rinfo); // Reply to discovery request with device parameters encoded in CBOR. // note: any encoding/properties could be used as long as the app-side can // interpret the payload. const responsePacket = cbor.encode(discoveryData); socket.send(responsePacket, rinfo.port, rinfo.address, (error) => { if (error !== null) { console.error('UDP failed to send ack:', error); return; } console.debug( 'UDP sent discovery response:', responsePacket, 'to:', rinfo); }); }); socket.on('listening', () => { console.log('UDP discovery listening', socket.address()); }); socket.bind(port); } ================================================ FILE: device/discovery_upnp.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import express from 'express'; import upnp from 'node-ssdp'; import xmlBuilder from 'xmlbuilder2'; import type {IDiscoveryData} from './types'; export function start(port: number, deviceType: string, serviceType: string, discoveryData: IDiscoveryData) { const descriptionPath = '/device.xml'; // HTTP server to response to description requests const server = express(); server.get(descriptionPath, (req, res) => { console.debug(`UPnP: received device description request.`); // UPnP HTTP server should return XML with device description // in compliance with schemas-upnp-org. See // http://upnp.org/specs/arch/UPnP-arch-DeviceArchitecture-v1.1.pdf const deviceDescription = xmlBuilder.create({ root: { '@xmlns': 'urn:schemas-upnp-org:device-1-0', 'specVersion': { major: '1', minor: '1', }, 'device': { deviceType, friendlyName: 'Virtual Light Device', UDN: `uuid:${discoveryData.id}`, modelName: discoveryData.model, serviceList: { service: discoveryData.channels.map((channel) => { return { serviceType, serviceId: `urn:sample:serviceId:strand-${channel}`, }; }), }, }, }, }).end({ prettyPrint: true }); res.status(200).send(deviceDescription); }); server.listen(port, () => { console.log(`UPnP: HTTP server listening on port ${port}`); }); // Start the UPnP advertisements const upnpServer = new upnp.Server({ location: { path: descriptionPath, port, }, udn: `uuid:${discoveryData.id}`, }); upnpServer.addUSN('upnp:rootdevice'); upnpServer.addUSN(deviceType); upnpServer.addUSN(serviceType); upnpServer.start(); console.log(`UPnP discovery advertising ${serviceType}`); } ================================================ FILE: device/execution_http.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import express from 'express'; import * as opcDevice from './opc_device'; export function start(port: number, opcHandler: opcDevice.Handler) { const server = express(); server.use(express.text({ type: 'application/octet-stream', })); server.post('/:channel', (req, res) => { console.debug(`HTTP: received ${req.method} request.`); const buf = Buffer.from(req.body, 'base64'); const message: opcDevice.IMessage = { channel: parseInt(req.params.channel, 10), command: 0x00, // set-pixel-color data: buf, }; opcHandler.handle(message); res.status(200) .set('Content-Type', 'text/plain') .send('OK'); }); server.get('/:channel', (req, res) => { console.debug(`HTTP: received ${req.method} request.`); const message: opcDevice.IMessage = { channel: parseInt(req.params.channel, 10), command: 0xff, // SYSEX data: Buffer.from([ 0x00, 0x03, // System IDs 0x00, 0x01// get-pixel-color ]), }; const response = opcHandler.handle(message); res.status(200) .set('Content-Type', 'application/octet-stream') .send(response!.toString('base64')); console.debug(`HTTP: sent response:`, response); }); server.listen(port, () => { console.log(`HTTP control listening on port ${port}`); }); } ================================================ FILE: device/execution_tcp.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import net from 'net'; const opcParser = require('opc/parser'); import * as opcDevice from './opc_device'; export function start(port: number, opcHandler: opcDevice.Handler) { const server = net.createServer((conn) => { conn.pipe(opcParser()).on('data', (message: opcDevice.IMessage) => { const response = opcHandler.handle(message); if (response !== undefined) { conn.write(response); console.debug(`TCP: sent response:`, response); } }); }); server.listen(port, () => { console.log(`TCP control listening on port ${port}`); }); } ================================================ FILE: device/execution_udp.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import dgram from 'dgram'; import {Readable} from 'stream'; const opcParser = require('opc/parser'); import * as opcDevice from './opc_device'; export function start(port: number, opcHandler: opcDevice.Handler) { const server = dgram.createSocket('udp4'); server.on('message', (msg: Buffer, rinfo: dgram.RemoteInfo) => { console.debug(`UDP: from ${rinfo.address} got`, msg); Readable.from(msg).pipe(opcParser()).on('data', (message: opcDevice.IMessage) => { opcHandler.handle(message); const response = opcHandler.handle(message); if (response !== undefined) { server.send(response, rinfo.port, rinfo.address, (error) => { if (error !== null) { console.error('UDP failed to send OPC command response:', error); return; } console.debug(`UDP: sent response to ${rinfo.address}:${rinfo.port}:`, response); }); } }); }); server.on('listening', () => { console.log(`UDP control listening on port ${port}`); }); server.bind(port); } ================================================ FILE: device/opc_device.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import chalk from 'chalk'; const opcStream = require('opc'); const opcParser = require('opc/parser'); const opcStrand = require('opc/strand'); export interface IMessage { channel: number; command: number; data: Buffer; } interface IStrand { buffer: Buffer; length: number; getPixel(i: number): [number, number, number]; } export class Handler { private readonly strands: Map; private readonly char: string; constructor(char: string, count: number, channel: number[]) { this.char = char; // Default strands color is white. this.strands = new Map( channel.map((c) => [c, opcStrand(Buffer.alloc(count * 3).fill(0xff))]), ); } handle(message: IMessage): Buffer|undefined { console.debug('received command:', message.command, message.data); switch (message.command) { case 0: { // set-pixel-color // TODO(proppy): implement channel 0 broadcast if (!this.strands.has(message.channel)) { console.warn('unknown OPC channel:', message.command); return; } this.strands.set(message.channel, opcStrand(message.data)); // Display updated strands to the console. for (const [c, strand] of this.strands) { for (let i = 0; i < strand.length; i++) { const pixel = strand.getPixel(i); process.stdout.write(chalk.rgb( pixel[0], pixel[1], pixel[2], )(this.char)); } process.stdout.write('\n'); } break; } case 0xff: { // SYSEX if (message.data[0] === 0x00 && // System IDs[0] message.data[1] === 0x03 && // System IDs[1] message.data[2] === 0x00 && // get-pixel-color[0] message.data[3] === 0x01) { // get-pixel-color[1] const stream = opcStream(); stream.writeMessage(message.channel, 0xff, // SYSEX this.strands.get(message.channel)!.buffer); return stream.read(); } break; } default: console.warn('Unsupported OPC command:', message.command); break; } } } ================================================ FILE: device/package.json ================================================ { "name": "fakecandy", "version": "0.0.1", "description": "fakecandy is a fake openpixelcontrol server that prints led state on standard output.", "private": true, "main": "server.js", "author": "Google", "license": "Apache-2.0", "scripts": { "lint": "tslint --project .", "compile": "tsc --noEmit", "build": "tsc", "start": "ts-node server.ts" }, "dependencies": { "bonjour": "^3.5.0", "cbor": "^5.0.2", "chalk": "^4.0.0", "express": "^4.17.1", "multicast-dns-service-types": "^1.1.0", "node-ssdp": "^4.0.0", "opc": "^1.1.3", "xmlbuilder2": "^2.1.2", "yargs": "^15.3.1" }, "devDependencies": { "@types/cbor": "^5.0.0", "@types/express": "^4.17.6", "@types/node": "^14.0.11", "@types/node-ssdp": "^3.3.1", "@types/yargs": "^15.0.5", "ts-node": "^8.10.2", "tslint": "^6.1.2", "typescript": "^3.9.5" } } ================================================ FILE: device/server.ts ================================================ /** * Copyright 2019, Google LLC * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import yargs from 'yargs'; import * as discoveryUdp from './discovery_udp'; import * as discoveryMdns from './discovery_mdns'; import * as discoveryUpnp from './discovery_upnp'; import * as executionUdp from './execution_udp'; import * as executionTcp from './execution_tcp'; import * as executionHttp from './execution_http'; import * as opcDevice from './opc_device'; import {ControlKind, DiscoveryKind} from './types'; const argv = yargs.usage('Usage: $0 --device_id ID [protocol settings]') .option('discovery_protocol', { describe: 'Discovery Protocol', alias: 'd', type: 'string', demandOption: true, default: DiscoveryKind.UDP, choices: Object.values(DiscoveryKind), }) .option('control_protocol', { describe: 'Control Protocol', alias: 'c', type: 'string', demandOption: true, default: ControlKind.TCP, choices: Object.values(ControlKind), }) .option('mdns_service_name', { describe: 'MDNS service name', type: 'string', default: '_sample._tcp.local', }) .option('mdns_instance_name', { describe: 'MDNS instance name.', type: 'string', default: 'strand1._sample._tcp.local', }) .option('upnp_server_port', { describe: 'Port to serve XML UPnP configuration by HTTP server', type: 'number', default: 8080, }) .option('upnp_service_type', { describe: 'UPnP service type', type: 'string', default: 'urn:sample:service:strand:1', }) .option('upnp_device_type', { describe: 'UPnP device type', type: 'string', default: 'urn:sample:device:strand:1', }) .option('udp_discovery_port', { describe: 'port to listen on for UDP discovery query', type: 'number', default: 3311, }) .option('udp_discovery_packet', { describe: 'hex encoded packet content to match for UDP discovery query', type: 'string', default: 'A5A5A5A5', }) .option('device_id', { describe: 'device id to return in the discovery response', type: 'string', demandOption: true, }) .option('device_model', { describe: 'device model to return in the discovery response', default: 'fakecandy', }) .option('hardware_revision', { describe: 'hardware revision to return in the discovery response', default: 'evt-1', }) .option('firmware_revision', { describe: 'firmware revision to return in the discovery response', default: 'v1-beta', }) .option('opc_port', { describe: 'port to listen on for openpixelcontrol messages', default: 7890, }) .option('led_char', { describe: 'character to show for each strand leds', default: '◉', }) .option('led_count', { describe: 'number of leds per strands', default: 16, }) .option('channel', { describe: 'add a new led strand with the corresponding channel number', default: [1], array: true, }) .argv; const opcHandler = new opcDevice.Handler( argv.led_char, argv.led_count, argv.channel, ); const discoveryData = { id: argv.device_id, model: argv.device_model, hw_rev: argv.hardware_revision, fw_rev: argv.firmware_revision, channels: argv.channel, }; switch (argv.discovery_protocol) { case DiscoveryKind.UDP: discoveryUdp.start(argv.udp_discovery_port, argv.udp_discovery_packet, discoveryData); break; case DiscoveryKind.MDNS: discoveryMdns.start(5353, argv.mdns_service_name, discoveryData); break; case DiscoveryKind.UPNP: discoveryUpnp.start(argv.upnp_server_port, argv.upnp_device_type, argv.upnp_service_type, discoveryData); break; } switch (argv.control_protocol) { case ControlKind.TCP: executionTcp.start(argv.opc_port, opcHandler); break; case ControlKind.UDP: executionUdp.start(argv.opc_port, opcHandler); break; case ControlKind.HTTP: executionHttp.start(argv.opc_port, opcHandler) break; } ================================================ FILE: device/tsconfig.json ================================================ { "compilerOptions": { "target": "es2018", "module": "commonjs", "moduleResolution": "node", "strict": true, "types": [ "node" ], "esModuleInterop": true }, "files" : [ "discovery_mdns.ts", "discovery_udp.ts", "discovery_upnp.ts", "execution_http.ts", "execution_tcp.ts", "execution_udp.ts", "opc_device.ts", "server.ts", "types.ts" ] } ================================================ FILE: device/tslint.json ================================================ { "defaultSeverity": "error", "extends": ["tslint:recommended"], "jsRules": {}, "rules": { "no-console": false, "no-bitwise": false, "object-literal-sort-keys": false, "no-var-requires": false, "quotemark": [true, "single"] }, "rulesDirectory": [] } ================================================ FILE: device/types.ts ================================================ /** * Copyright 2020, Google LLC * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ export enum DiscoveryKind { UDP = 'UDP', UPNP = 'UPNP', MDNS = 'MDNS', } export enum ControlKind { UDP = 'UDP', TCP = 'TCP', HTTP = 'HTTP', } export interface IDiscoveryData { id: string; model: string; hw_rev?: string; fw_rev?: string; channels: number[]; } ================================================ FILE: functions/firebase.json ================================================ { "functions": { "source": ".", "predeploy": [ "npm run lint", "npm run build" ] } } ================================================ FILE: functions/index.ts ================================================ /** * Copyright 2020, Google LLC * Licensed under the Apache License, Version 2.0 (the 'License'); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import 'ts-polyfill/lib/es2019-array'; import {smarthome} from 'actions-on-google'; import * as functions from 'firebase-functions'; const controlKinds = ['TCP', 'UDP', 'HTTP']; const config = functions.config(); const devices = Object.entries(config).flatMap(([deviceId, deviceConf]: [string, any]) => { const port = parseInt(deviceConf.port || '7890', 10); const leds = parseInt(deviceConf.leds || '16', 10); const controlProtocol = controlKinds.includes(deviceConf.control_protocol) ? deviceConf.control_protocol : 'TCP'; const channels = deviceConf.channel ? deviceConf.channel.split(',') : ['1']; const proxy = channels.length > 1 ? deviceId : undefined; return channels.map((c: string) => ({ id: proxy ? `${deviceId}-${c}` : deviceId, name: `${deviceId} #${c}`, channel: parseInt(c, 10), proxy, leds, port, control_protocol: controlProtocol, })); }); const app = smarthome(); app.onSync((body, headers) => { functions.logger.log('User account linked from Google Assistant'); return { requestId: body.requestId, payload: { agentUserId: 'placeholder-user-id', devices: devices.map((device) => ({ type: 'action.devices.types.LIGHT', traits: [ 'action.devices.traits.ColorSetting', ], id: device.id, otherDeviceIds: [{ deviceId: device.id, }], name: { name: device.name, defaultNames: [], nicknames: [], }, willReportState: false, attributes: { colorModel: 'rgb' }, customData: { channel: device.channel, leds: device.leds, port: device.port, proxy: device.proxy, control_protocol: device.control_protocol, }, })), }, }; }); app.onQuery((body, headers) => { functions.logger.log('Cloud Fulfillment received QUERY'); // Always show the devices as online. return { requestId: body.requestId, payload: { devices: devices.reduce((result, device) => { result[device.id] = { status: 'SUCCESS', online: true }; return result; }, {}), }, }; }); app.onExecute((body, headers) => { functions.logger.log('Cloud Fulfillment received EXECUTE'); // EXECUTE requests should be handled by local fulfillment return { requestId: body.requestId, payload: { commands: body.inputs[0].payload.commands.map((command) => { functions.logger.error(`Cloud fallback for ${command.execution[0].command}.`, `EXECUTE received for device ids: ${command.devices.map((device) => device.id)}.`); return { ids: command.devices.map((device) => device.id), status: 'ERROR', errorCode: 'actionNotAvailable', debugString: `Ensure devices are locally identified.`, }; }), }, }; }); app.onDisconnect((body, headers) => { functions.logger.log('User account unlinked from Google Assistant'); // Return empty response return {}; }); exports.smarthome = functions.https.onRequest(app); exports.authorize = functions.https.onRequest((req, res) => { const redirectUri = req.query.redirect_uri as string; res.status(200).send(`Complete Account Linking`); }); exports.token = functions.https.onRequest((req, res) => { res.status(200).send({ token_type: 'bearer', access_token: 'placeholder-access-token', refresh_token: 'placeholder-refresh-token', expires_in: 3600, }); }); ================================================ FILE: functions/package.json ================================================ { "name": "smarthome-provider-placeholder", "version": "0.0.1", "description": "Placeholder backend for the Local Home SDK sample.", "private": true, "author": "Google", "license": "Apache-2.0", "engines": { "node": "10" }, "main": "index.js", "scripts": { "build": "tsc", "lint": "tslint --project .", "compile": "tsc --noEmit", "deploy": "firebase deploy --only functions", "firebase": "firebase" }, "dependencies": { "actions-on-google": "^2.12.0", "firebase-admin": "^8.12.1", "firebase-functions": "^3.8.0", "ts-polyfill": "^3.8.2" }, "devDependencies": { "firebase-tools": "^8.4.2", "tslint": "^6.1.2", "typescript": "^3.9.5" } } ================================================ FILE: functions/tsconfig.json ================================================ { "compilerOptions": { "target": "es2017", "lib": ["es2019.array"], "moduleResolution": "node", "strict": true, "sourceMap": true, "module": "commonjs" } } ================================================ FILE: functions/tslint.json ================================================ { "defaultSeverity": "error", "extends": ["tslint:recommended"], "jsRules": {}, "rules": { "no-console": false, "no-bitwise": false, "object-literal-sort-keys": false, "no-var-requires": false, "ordered-imports": false, "max-classes-per-file": [true, 1, "exclude-class-expressions"], "quotemark": [true, "single"] }, "rulesDirectory": [] }