微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

智能家居插件中处理函数的奇怪行为

如何解决智能家居插件中处理函数的奇怪行为

我正在尝试创建一个 homebridge plugin 来控制灯光和其他配件,例如由 HDL 总线供电的运动传感器。我正在使用 this library 中的函数与 HDL 设备和 homebridge 建议的 template plugin 交换命令和数据。

到目前为止,我已经成功地实现了对光控的支持,但遇到了传感器的问题,我认为对于异步编程在 javascript 中的工作方式存在一些根本性的误解(我实际上既不在 js 中编写代码,也从未尝试创建任何东西)像这样,所以这可能是一个非常幼稚的问题)。

我的代码与总线上的任何设备之间的交互如下所示:

    //import library
    var SmartBus = require('smart-bus');
    //access sensor by its id in the bus
    var bus = new SmartBus({
      device: '1.50',//register bus with a virtual command device '1.50'
      gateway: '10.0.1.70',port: 6000
    });
    var sensor = bus.device('1.21'); //access sensor by its id in the bus
    

    //send request to return current readings from multi-sensor
    bus.send({ 
      sender: '1.50',target: sensor,command: 0x1645,},function(err) {
      if (err) console.error('Failed to send command');
      else console.log('Success');
    });
    //custom function that reacts to actions from multi-sensor
    var myfunc = function(command) {
      console.log(command.data);
      return command.data;
    };
    //attaching this function as a handler to our sensor
    sensor.on(0x1646,myfunc);
    
    setTimeout((function() {
        return process.exit(22);
    }),1000);

如果作为节点进程运行并在 console.log 中返回以下内容,则此代码始终有效:

Success
{
  success: true,temperature: 26,brightness: 7,movement: false,dryContacts: [
    { number: 1,status: false },{ number: 2,{ number: 3,status: false }
  ],sonic: false
}

控制灯的代码几乎相同,唯一的区别是它需要不同的事件代码(0x1646 -> 0x0032)。但是由于某种原因,当它们作为插件功能的一部分进行编码时,它们的行为截然不同。在我的传感器附件类中,我定义了以下异步函数

  async sensorUpdater()  {
    let sensordata = await this.bus.device(this.devicestr).on(0x1646,function(command) {
      let data = command.data;
      let temperature = data.temperature;
      if (data) {
        return data;
      } else {
        return false;
      };
    });
    this.SensorStates.Temperature = sensordata.temperature;
    this.temp_service.getCharacteristic(this.platform.Characteristic.CurrentTemperature).updateValue(this.SensorStates.Temperature);
  }

理论上它应该通过覆盖传感器类中的当前 SensorStates.Temperature 值来响应来自传感器的任何反馈。 但这个函数实际上永远不会更新这个温度值,这很令人困惑,因为我在这文件中有一个相同的函数,它返回当前灯泡状态并且工作正常很好,没有问题。这些实例之间的唯一区别是,由于用户通过 onSet 命令触发它,因此总线始终响应灯状态,而必须以一定的时间间隔扫描传感器,为此我实现了我的类的构造函数中的以下请求代码

setInterval(() => {
      this.platform.log.debug('asking for update');
      this.bus.send({
        sender: this.cdnstr,target: this.devicestr,command: 0x1645
      },function(err) {});
    },10000);

调试器消息确实每 10 秒显示一次,因此请求似乎按应发送的方式发送。所有证据都表明我看不到 sensorUpdater 功能存在一些问题。我尝试了很多不同的事情,包括尝试从处理程序内部更改 this.SensorStates.Temperature,但没有任何帮助 - 插件中的温度值保持为 0。

那么我编写处理程序函数响应的方式有什么问题?这里是 full code,问题部分位于 PlatformAccessory.js 中的 Sensor8in1 类下。如果您对此问题有任何想法,我将不胜感激。

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