Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement WebSocket for HomeKit Device Discovery #395

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
156 changes: 118 additions & 38 deletions internal/homekit/api.go
Original file line number Diff line number Diff line change
@@ -1,60 +1,63 @@
package homekit

import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"sync"

"github.com/AlexxIT/go2rtc/internal/app/store"
"github.com/AlexxIT/go2rtc/internal/streams"
"github.com/AlexxIT/go2rtc/pkg/hap"
"github.com/AlexxIT/go2rtc/pkg/hap/mdns"
"net/http"
"net/url"
"github.com/gorilla/websocket"

"strings"
"time"
)

var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}

var activeConnections int
var activeConnectionsMutex sync.Mutex

func apiHandler(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
items := make([]any, 0)

for name, src := range store.GetDict("streams") {
if src := src.(string); strings.HasPrefix(src, "homekit") {
u, err := url.Parse(src)
if err != nil {
continue
}
device := Device{
Name: name,
Addr: u.Host,
Paired: true,
}
items = append(items, device)
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Error().Err(err).Caller().Send()
_, err = w.Write([]byte(err.Error()))
return
}

for info := range mdns.GetAll() {
if !strings.HasSuffix(info.Name, mdns.Suffix) {
continue
}
name := info.Name[:len(info.Name)-len(mdns.Suffix)]
device := Device{
Name: strings.ReplaceAll(name, "\\", ""),
Addr: fmt.Sprintf("%s:%d", info.AddrV4, info.Port),
activeConnectionsMutex.Lock()
activeConnections++
activeConnectionsMutex.Unlock()

done := make(chan struct{})
go hkDiscoverDevices(conn, done)

for {
_, _, err := conn.ReadMessage()
if err != nil {
log.Debug().Err(err).Caller().Send()
_, err = w.Write([]byte(err.Error()))
break
}
for _, field := range info.InfoFields {
switch field[:2] {
case "id":
device.ID = field[3:]
case "md":
device.Model = field[3:]
case "sf":
device.Paired = field[3] == '0'
}
}
items = append(items, device)
}

_ = json.NewEncoder(w).Encode(items)
close(done)
activeConnectionsMutex.Lock()
activeConnections--
activeConnectionsMutex.Unlock()
conn.Close()

case "POST":
// TODO: post params...
Expand All @@ -76,6 +79,83 @@ func apiHandler(w http.ResponseWriter, r *http.Request) {
}
}

func hkDiscoverDevices(conn *websocket.Conn, done chan struct{}) {
queryCounter := 0
for {
select {
case <-done:
return
default:
log.Trace().Int("active connections: ", activeConnections).Msg("[homekit] ")
activeConnectionsMutex.Lock()
if activeConnections <= 0 {
activeConnectionsMutex.Unlock()
return
}
activeConnectionsMutex.Unlock()

queryCounter++
timeout := time.Second
if queryCounter%10 == 0 {
timeout = 5 * time.Second
}

entries := mdns.GetAll(timeout)

for name, src := range store.GetDict("streams") {
if src := src.(string); strings.HasPrefix(src, "homekit") {
u, err := url.Parse(src)
if err != nil {
continue
}
device := Device{
Name: name,
Addr: u.Host,
Paired: true,
}
err = conn.WriteJSON(device)
if err != nil {
log.Error().Err(err).Caller().Send()

return
}
}
}

for entry := range entries {
if !strings.HasSuffix(entry.Name, mdns.Suffix) {
continue
}

name := entry.Name[:len(entry.Name)-len(mdns.Suffix)]
device := Device{
Name: strings.ReplaceAll(name, "\\", ""),
Addr: fmt.Sprintf("%s:%d", entry.AddrV4, entry.Port),
}
for _, field := range entry.InfoFields {
switch field[:2] {
case "id":
device.ID = field[3:]
case "md":
device.Model = field[3:]
case "sf":
device.Paired = field[3] == '0'
}
}

err := conn.WriteJSON(device)
if err != nil {
log.Debug().Err(err).Caller().Send()

return
}
}

time.Sleep(timeout)
}
}
}

func hkPair(deviceID, pin, name string) (err error) {
var conn *hap.Conn

Expand Down
12 changes: 9 additions & 3 deletions pkg/hap/mdns/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,22 @@ package mdns

import (
"fmt"
"github.com/hashicorp/mdns"
"strings"
"time"

"github.com/hashicorp/mdns"
)

const Suffix = "._hap._tcp.local."

func GetAll() chan *mdns.ServiceEntry {
func GetAll(timeout_opt ...time.Duration) chan *mdns.ServiceEntry {
timeout := time.Second
if len(timeout_opt) > 0 {
timeout = timeout_opt[0]
}
entries := make(chan *mdns.ServiceEntry)
params := &mdns.QueryParam{
Service: "_hap._tcp", Entries: entries, DisableIPv6: true,
Service: "_hap._tcp", Entries: entries, DisableIPv6: true, Timeout: timeout,
}

go func() {
Expand Down
56 changes: 36 additions & 20 deletions www/add.html
Original file line number Diff line number Diff line change
Expand Up @@ -125,29 +125,45 @@
<script>
document.getElementById('homekit').addEventListener('click', async ev => {
ev.target.nextElementSibling.style.display = 'block'
const r = await fetch('api/homekit', {cache: 'no-cache'})

/** @type {Array<{id:string,name:string,addr:string,model:string,paired:boolean}>} */
const data = await r.json()
const homekitTable = document.getElementById("homekit-body");

const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:';
const socket = new WebSocket(`${protocol}//${window.location.host}/api/homekit`);

socket.onmessage = function (event) {
const device = JSON.parse(event.data);
console.log("Discovered device:", device);
addOrUpdateRow(device);
};

function addOrUpdateRow(device) {
const existingRow = document.getElementById(`device-${device.id}`);
if (existingRow) {
existingRow.innerHTML = createRow(device);
} else {
const newRow = document.createElement("tr");
newRow.id = `device-${device.id}`;
newRow.innerHTML = createRow(device);
homekitTable.appendChild(newRow);
}
}

const tbody = document.getElementById('homekit-body')
tbody.innerHTML =
data.reduce((res, item) => {
let commands = ''
if (item.id === "") {
commands = `<a href="#" onclick="unpair('${item.name}')">unpair</a>`
} else if (item.paired === false) {
commands = `<a href="#" onclick="pair('${item.id}','${item.name}')">pair</a>`
}
return res + `<tr>
<td>${item.name}</td>
<td>${item.addr}</td>
<td>${item.model}</td>
<td>${commands}</td>
</tr>`
}, '')
function createRow(device) {
let commands = "";
if (device.id === "") {
commands = `<a href="#" onclick="unpair('${device.name}')">unpair</a>`;
} else if (device.paired === false) {
commands = `<a href="#" onclick="pair('${device.id}','${device.name}')">pair</a>`;
}
return `<td>${device.name}</td>
<td>${device.addr}</td>
<td>${device.model}</td>
<td>${commands}</td>`;
}
})



function pair(id, name) {
const pin = document.querySelector('#pin').value
fetch(`api/homekit?id=${id}&name=${name}&pin=${pin}`, {method: 'POST'})
Expand Down