在 HomeBridge 上使用 WebSocket 开发一个扩展配件


Step.1 - 安装 Node.js & NPM

1
2
curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh | bash
nvm install node

Step.2 - 安装 HomeBridge

1
npm install -g homebridge hap-nodejs node-gyp homebridge-websocket

Step.3 - 设置 HomeBridge-WebSocket

打开 /home/pi/.homebridge

新建一个叫做 config.json 的文件

填入内容

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
"bridge":{
"name":"HomeBridge设备名字",
"username":"CC:22:3D:E3:CE:30",
"port":51826,
"pin":"031-45-154"
},
"platforms":[
{
"platform":"websocket",
"name":"websocket",
"port":2333 //WebSocket端口
}
]
}

Step.4 - 运行 HomeBridge

1
homebridge -U /home/pi/.homebridge/config.json

然后打开 iOS 上的 Home,并扫码添加 HomeBridge 显示的二维码

2019-04-02 01.10.10.jpg

等添加完成之后就可以开始使用 WebSocket 接口了

Step.5 - 第一个扩展配件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var ws = new WebSocket("ws://树莓派内网IP:WebSocket端口")
//添加一个新的配件
ws.send(JSON.stringify({
"topic": "add",
"payload": {
"name": "lamp", //扩展配件名字
"service": "Switch" //服务类型
}}
))
ws.onmessage = function(message) {
var data = JSON.parse(message.data)
console.log(data)
if(data.topic == 'set' && data.payload.name == 'lamp') {
console.log("Device: "+data.payload.name + ", Status: " + data.payload.value)
}
}
演示视频

更多的接口可以参考 homebridge-websocket 提供的文档

Author: Akechi Satori
Link: https://satori.moe/homekit-with-raspberry-and-websocket/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.