跳转至

利用TypeScript编写一个简单的Homebridge插件

前言

本教程是通过TypeScript编写的hb-plugin,这是一个简单的教程,但是需要具备编程基础。为什么用typescript,因为ts支持异步函数,避免产生大量的回调。 homebridge

A.需求分析

需求: 实现在homekit中去控制一盏灯的开关。
分析: 基于homebridge框架进行开发,利用socket跟主机进行网络通信,进而实现控制。

homebridge原理图

B.前期准备

C.进行开发

1. 注册Accessory设备

将Light插件注入到homebridge,Lightbulb是一个对象

// 注册Accessory设备
export default function(homebridge: any) {
  Service = homebridge.hap.Service;
  Characteristic = homebridge.hap.Characteristic;
  homebridge.registerAccessory("homebridge-Lightbulb", "Lightbulb", Lightbulb);
}

2. 实例化Service服务

注册switch时涉及到的两个service:

  • AccessoryInformation service:每个Accessory都需要广播与设备本身相关的信息,无论其类型如何;它包含了Manufacturer(生产厂家)、SerialNumber(序列号)等特性
  • Lightbulb service:真正的灯光service,Lightbulb设备具有布尔特性On,百分比特性Brightness 等;这里我们只做一个开关灯。
    constructor(log, config) {
        this.log = log;
        this.name = config["name"];
    
        const informationService = new Service.AccessoryInformation();
        const LightbulbService = new Service.Lightbulb(this.name);
        LightbulbService
          .getCharacteristic(Characteristic.On)
          .on("get", this.getLightOnCharacteristic.bind(this))
          .on("set", this.setLightOnCharacteristic.bind(this));
        this.LightbulbService = LightbulbService;
    
      }
    
      getServices() {
        const { LightbulbService } = this;
        return [LightbulbService];
      }
    

homekit支持的Accessory

3. 实例化Characteristic

就是将上面注册的Service中的getCharacteristic这一部分具体实现。在编程上的意思就是,实现声明函数的方法。

// get请求  
  getLightOnCharacteristic(callback: (arg0: any) => void) {
    console.log("**************Get on Function**************");
    callback(null);
  }

// set请求 
  setLightOnCharacteristic(on: boolean, callback: (arg0: any) => void) {
    console.log("**************Set on Function:" + on + "**************");

    if (on) {
      this.socket.write(onbuf);
    } else {
      this.socket.write(offbuf);
    }
    setTimeout(function() {
      console.log(inibuf);
    }, 500); //500ms Rest init statue

    callback(null);
  }

4. 建立socket

这一部分需要先导入typescript的net包,然后要在构造函数里创建。

  constructor(log, config) {
    this.log = log;
    this.name = config["name"];

    this.socket = new net.Socket();
    this.socket.connect(8989, "localhost", function() {
      console.log("Connecte Server OK!"); 
    });
    this.socket.on("error", console.error); // logs socket error messages
  }

5. 完整代码

//mySwitch完整index.js代码
import net from "net";

let Service: any, Characteristic: any;
let onbuf = "turn on"; //cmd: turn on
let offbuf = "turn off"; //cmd: turn off
let inibuf = "check"; //cmd: reset


// 注册Accessory设备
export default function(homebridge: any) {
  Service = homebridge.hap.Service;
  Characteristic = homebridge.hap.Characteristic;
  homebridge.registerAccessory("homebridge-Lightbulb", "Lightbulb", Lightbulb);
}

class Lightbulb {
  log: Function;
  name: string;
  LightbulbService: any;
  socket: net.Socket;

  constructor(log, config) {
    this.log = log;
    this.name = config["name"];

    const informationService = new Service.AccessoryInformation();
    const LightbulbService = new Service.Lightbulb(this.name);
    LightbulbService
      .getCharacteristic(Characteristic.On)
      .on("get", this.getLightOnCharacteristic.bind(this))
      .on("set", this.setLightOnCharacteristic.bind(this));
    this.LightbulbService = LightbulbService;

    this.socket = new net.Socket();
    this.socket.connect(8989, "localhost", function() {
      console.log("Connecte Server OK!"); //connect ser2net
    });
    this.socket.on("error", console.error); // logs socket error messages
  }

  getServices() {
    const { LightbulbService } = this;
    return [LightbulbService];
  }

  getLightOnCharacteristic(callback: (arg0: any) => void) {
    console.log("**************Get on Function**************");
    callback(null);
  }

  setLightOnCharacteristic(on: boolean, callback: (arg0: any) => void) {
    console.log("**************Set on Function:" + on + "**************");

    if (on) {
      this.socket.write(onbuf);
    } else {
      this.socket.write(offbuf);
    }

    setTimeout(function() {
      console.log(inibuf);
    }, 500); //500ms Rest init statue

    callback(null);
  }
}

6. 打包编译

由于使用的是typescript,所以要利用rollup和babel将其编译成js,这样homebridge才能识别你的插件。 这一步挺难的,因为要配置一些乱七八糟的,我自己也没搞懂,所以大家上github看我的demo配置就好了。

7. 其他

大致开发的流程就是这样,不是太理解的可以先运行我写的插件homebridge-lightbulb-ts-demo

1.去github上下载我上传的项目,别忘记给个star

2.在你解压后的文件夹下运行,npm install

3.然后运行npm run build

4.编译完毕后,如果没问题的话,把这个文件夹放到与homebridge平级的目录下。

image.png

5.配置config.json

config.json

{
  "bridge": {
      "name": "Homebridge",
      "username": "94:A1:A2:BE:0B:30",
      "port": 59376,
      "pin": "031-45-666"
  },
  "accessories": [
      {
          "accessory": "MyLightbulb",
          "name": "灯"
      }
  ],
  "platforms": []
}

6.在cmd窗口运行homebridge

运行成功

7.扫二维码添加设备

succeess

8.习题

ok, now you can use siri to control your light,it will very fun.

你可以将这个灯更改为调光灯

8. 参考文献