Google Smarthome履行无法在Firebase之外运行

如何解决Google Smarthome履行无法在Firebase之外运行

我目前正在尝试构建自己的Google家用设备。

我正在使用本教程:https://codelabs.developers.google.com/codelabs/smarthome-washer#0。如果我将代码部署到firebase,它会很好地工作,但是我想在自己的服务器上运行它。因此,我重写了代码以在正常的nodejs环境中工作。身份验证和令牌部分可以正常工作,但是如果google home应用调用“ / smarthome”(实现网址“输入用于处理智能家居意图的webhook。”,在google action控制台中设置),则正文和查询对象为空的。至少应该有requestId。如果我在firebase中运行它,身体看起来会很好。

在firebase中有效的代码:

exports.smarthome = functions.https.onRequest((req,res) => {
  functions.logger.info(req.body.requestId);
});

我重写的代码(整个身体都是空的):

app.all("/smarthome",urlencodedParser,function(req,res){
    console.log(req.body);
    console.log(req.query);
    console.log(req.body.requestId);
});

现在我的问题是:我做错什么了吗?还是根本不可能在另一台服务器上完成任务。

Googles代码(稍作修改,但可以使用):

/**
 * Copyright 2018 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License,Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,software
 * distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

'use strict';

const functions = require('firebase-functions');
const {smarthome} = require('actions-on-google');
const {google} = require('googleapis');
const util = require('util');
const admin = require('firebase-admin');
// Initialize Firebase
admin.initializeApp();
const firebaseRef = admin.database().ref('/');
// Initialize Homegraph
const auth = new google.auth.GoogleAuth({
  scopes: ['https://www.googleapis.com/auth/homegraph'],});
const homegraph = google.homegraph({
  version: 'v1',auth: auth,});
// Hardcoded user ID
const USER_ID = '123';

exports.login = functions.https.onRequest((request,response) => {
  functions.logger.log('Requesting login page');
  if (request.method === 'GET') {
    functions.logger.log('Requesting login page');
    response.send(`
    <html>
      <meta name="viewport" content="width=device-width,initial-scale=1">
      <body>
        <form action="/login" method="post">
          <input type="hidden"
            name="responseurl" value="${request.query.responseurl}" />
          <button type="submit" style="font-size:14pt">
            Link this service to Google
          </button>
        </form>
      </body>
    </html>
  `);
  } else if (request.method === 'POST') {
    // Here,you should validate the user account.
    // In this sample,we do not do that.
    const responseurl = decodeURIComponent(request.body.responseurl);
    functions.logger.log(`Redirect to ${responseurl}`);
    return response.redirect(responseurl);
  } else {
    // Unsupported method
    response.send(405,'Method Not Allowed');
  }
});

exports.fakeauth = functions.https.onRequest((request,response) => {
  const responseurl = util.format('%s?code=%s&state=%s',decodeURIComponent(request.query.redirect_uri),'xxxxxx',request.query.state);
  functions.logger.log(`Set redirect as ${responseurl}`);
  return response.redirect(
      `/login?responseurl=${encodeURIComponent(responseurl)}`);
});

exports.faketoken = functions.https.onRequest((request,response) => {
  const grantType = request.query.grant_type ?
    request.query.grant_type : request.body.grant_type;
  const secondsInDay = 86400; // 60 * 60 * 24
  const HTTP_STATUS_OK = 200;
  functions.logger.log(`Grant type ${grantType}`);

  let obj;
  if (grantType === 'authorization_code') {
    obj = {
      token_type: 'bearer',access_token: '123access',refresh_token: '123refresh',expires_in: secondsInDay,};
  } else if (grantType === 'refresh_token') {
    obj = {
      token_type: 'bearer',};
  }
  response.status(HTTP_STATUS_OK)
      .json(obj);
});

const app = smarthome();

app.onSync((body,headers) => {

  return {};
});

const queryFirebase = async (deviceId) => {
  const snapshot = await firebaseRef.child(deviceId).once('value');
  const snapshotVal = snapshot.val();
  // TODO: Define device states to return
  return {};
};

// eslint-disable-next-line
const queryDevice = async (deviceId) => {
  const data = await queryFirebase(deviceId);
  // TODO: Define device states to return
  return {};
};

app.onQuery((body) => {
  // TODO: Implement QUERY response
  return {};
});

const updateDevice = async (execution,deviceId) => {
  // TODO: Add commands to change device states
};

app.onExecute((body) => {
  // TODO: Implement EXECUTE response
  return {};
});

app.onDisconnect((body,headers) => {
  functions.logger.log('User account unlinked from Google Assistant');
  // Return empty response
  return {};
});

 //exports.smarthome = functions.https.onRequest(home); Normal method (deactivated for testing)

exports.smarthome = functions.https.onRequest((req,res) => {
  functions.logger.info(req.body.requestId);
});

exports.requestsync = functions.https.onRequest(async (req,res) => {
  res.set('Access-Control-Allow-Origin','*');
  functions.logger.info(`Request SYNC for user ${USER_ID}`);
  try {
    const res = await homegraph.devices.requestSync({
      requestBody: {
        agentUserId: USER_ID,},});
    functions.logger.info('Request sync response:',res.status,res.data);
    res.json(res.data);
  } catch (err) {
    functions.logger.error(err);
    res.status(500).send(`Error requesting sync: ${err}`);
  }
});

/**
 * Send a REPORT STATE call to the homegraph when data for any device id
 * has been changed.
 */
exports.reportstate = functions.database.ref('{deviceId}').onWrite(
    async (change,context) => {
      functions.logger.info('Firebase write event triggered Report State');

      // TODO: Get latest state and call HomeGraph API
    });

我的整个代码:

const hostname = '0.0.0.0';
const port = 8080;

var https = require("https");
const util = require('util');
var express = require('express');
var bodyParser = require('body-parser')
const {google} = require('googleapis');
const {smarthome} = require('actions-on-google');

var app = express();
var jsonParser = bodyParser.json()
var urlencodedParser = bodyParser.urlencoded({ extended: false })

const USER_ID = '123';


const auth = new google.auth.GoogleAuth({
    scopes: ['https://www.googleapis.com/auth/homegraph'],});
const homegraph = google.homegraph({
    version: 'v1',});


app.get('/login',res) {
    console.log('login_get');
        res.send(`
    <html>
      <meta name="viewport" content="width=device-width,initial-scale=1">
      <body>
        <form action="/login" method="post">
          <input type="hidden"
            name="responseurl" id="responseurl" value="${req.query.responseurl}" />
          <button type="submit" style="font-size:14pt">
            Link this service to Google
          </button>
        </form>
      </body>
    </html>
  `);

});

app.post("/login",res){
    console.log('login_post');
    const responseurl = decodeURIComponent(req.body.responseurl);
    return res.redirect(responseurl);
});

app.all('/auth',res) {
    console.log('auth');
    const responseurl = util.format('%s?code=%s&state=%s',decodeURIComponent(req.query.redirect_uri),req.query.state);
    return res.redirect(
        `/login?responseurl=${encodeURIComponent(responseurl)}`);
});

app.all('/token',res) {
    console.log('token');
    const grantType = req.query.grant_type ?
        req.query.grant_type : req.body.grant_type;
    const secondsInDay = 86400; // 60 * 60 * 24
    const HTTP_STATUS_OK = 200;

    let obj;
    if (grantType === 'authorization_code') {
        obj = {
            token_type: 'bearer',};
    } else if (grantType === 'refresh_token') {
        obj = {
            token_type: 'bearer',};
    }
    res.status(HTTP_STATUS_OK)
        .json(obj);
});


app.all('/requestsync',async function(req,res) {
    console.log("requestsync");
    res.set('Access-Control-Allow-Origin','*');
    try {
        const res = await homegraph.devices.requestSync({
            requestBody: {
                agentUserId: USER_ID,});
        console.log('Request sync response:',res.data);
        res.json(res.data);
    } catch (err) {
        console.log(err);
        res.status(500).send(`Error requesting sync: ${err}`);
    }

});



const home = smarthome();
home.onSync((body,headers) => {
    console.log("onSync");
    return {};
});

home.onQuery((body) => {
    console.log("onQuery");
    return {};
});
home.onExecute((body) => {
    console.log("onExecute");
    return {};
});

home.onDisconnect((body,headers) => {
    console.log("onDisconnect");
    return {};
});

//exports.smarthome = home;

//exports.smarthome = https.onRequest(home);



app.all("/smarthome",res){
    console.log(req.body);
    console.log(req.query);
    console.log(req.body.requestId);
    home(req,res);
});



app.listen(port,hostname,() => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

请分享一些想法。 乔纳斯(Jonas)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-