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