Skip to content

Commit

Permalink
log connected devices
Browse files Browse the repository at this point in the history
  • Loading branch information
suurkivi committed Oct 20, 2024
1 parent e79ccf0 commit 3bdf144
Show file tree
Hide file tree
Showing 12 changed files with 177 additions and 74 deletions.
27 changes: 18 additions & 9 deletions app/bthandler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,35 +4,39 @@ import (
"context"
"fmt"
"github.com/minor-industries/rtgraph"
"github.com/minor-industries/rtgraph/broker"
"github.com/minor-industries/rtgraph/database/sqlite"
"github.com/minor-industries/z2/lib/data"
"github.com/minor-industries/z2/lib/source"
"github.com/pkg/errors"
"time"
)

type BluetoothIsConnected struct {
DeviceInfo source.DeviceInfo
}

func (b *BluetoothIsConnected) Name() string {
return "BluetoothIsConnected"
}

type BTHandler struct {
graph *rtgraph.Graph
broker *broker.Broker
rawValues *sqlite.Backend
source source.Source
cancel context.CancelFunc
ctx context.Context

ctx context.Context
t0 time.Time
lastMsg time.Time
writeRawValues bool
}

func NewBTHandler(
graph *rtgraph.Graph,
rawValues *sqlite.Backend,
source source.Source,
writeRawValues bool,
cancel context.CancelFunc,
ctx context.Context,
) *BTHandler {
func NewBTHandler(graph *rtgraph.Graph, br *broker.Broker, rawValues *sqlite.Backend, source source.Source, writeRawValues bool, cancel context.CancelFunc, ctx context.Context) *BTHandler {
return &BTHandler{
graph: graph,
broker: br,
rawValues: rawValues,
source: source,
cancel: cancel,
Expand Down Expand Up @@ -69,6 +73,11 @@ func (h *BTHandler) Handle(
Msg: msg,
})

if len(srs) > 0 {
m := &BluetoothIsConnected{DeviceInfo: info}
h.broker.Publish(m)
}

for _, s := range srs {
err := h.graph.CreateValue(s.Name, s.Timestamp, s.Value)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ export interface Env {

maybeStartFrontendBLE(): Promise<void>,

streamEvents(path: string, callback: (event: string) => void): void,
streamEvents(path: string, callbacks: { [key: string]: (data: string) => void }): void;
}
13 changes: 9 additions & 4 deletions frontend/src/stream_events.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
export function streamEvents(
path: string,
callback: (data: string) => void
callbacks: { [key: string]: (data: string) => void }
): void {
const es = new EventSource(path);
es.addEventListener("play-sound", (event) => {
callback(event.data);
});

for (const eventType in callbacks) {
if (callbacks.hasOwnProperty(eventType)) {
es.addEventListener(eventType, (event: MessageEvent) => {
callbacks[eventType](event.data);
});
}
}
}
39 changes: 32 additions & 7 deletions frontend/templates/sound-events.html
Original file line number Diff line number Diff line change
@@ -1,15 +1,40 @@
{{ define "sound-events" }}

<script type="module">
import {getEnv} from "/z2/env.js";

const bluetoothConnectedHandler = (() => {
const seen = {};

return (data) => {
const msg = JSON.parse(data);
const key = msg.address;
if (key === "") {
return;
}
if (seen[key]) {
return;
}
seen[key] = true;

const kind = msg.kind;
const name = msg.name ? " " + msg.name : "";

const info = `${kind}${name} is connected`;
console.log(info);
};
})();

document.addEventListener("DOMContentLoaded", async () => {
const env = await getEnv();
env.streamEvents("/events", data => {
const audio = document.getElementById(`sound-${data}`);
audio.play();

// Use the `bluetoothConnectedHandler` in `streamEvents`
env.streamEvents("/events", {
"play-sound": (data) => {
const audio = document.getElementById(`sound-${data}`);
if (audio) {
audio.play();
}
},
"bluetooth-is-connected": bluetoothConnectedHandler
});
});
</script>

{{ end }}
30 changes: 27 additions & 3 deletions frontend/z2/pages/bike.html
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,33 @@

document.addEventListener("DOMContentLoaded", async () => {
const env = await getEnv();
env.streamEvents("/events", data => {
const audio = document.getElementById(`sound-${data}`);
audio.play();

const seen = {};

env.streamEvents("/events", {
"play-sound": (data) => {
const audio = document.getElementById(`sound-${data}`);
if (audio) {
audio.play();
}
},
"bluetooth-is-connected": (data) => {
const msg = JSON.parse(data);
const key = msg.address;
if (key === "") {
return;
}
if (seen[key]) {
return;
}
seen[key] = true;

const kind = msg.kind;
const name = msg.name ? " " + msg.name : "";

const info = `${kind}${name} is connected`;
console.log(info);
},
});
});
</script>
Expand Down
30 changes: 27 additions & 3 deletions frontend/z2/pages/rower.html
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,33 @@

document.addEventListener("DOMContentLoaded", async () => {
const env = await getEnv();
env.streamEvents("/events", data => {
const audio = document.getElementById(`sound-${data}`);
audio.play();

const seen = {};

env.streamEvents("/events", {
"play-sound": (data) => {
const audio = document.getElementById(`sound-${data}`);
if (audio) {
audio.play();
}
},
"bluetooth-is-connected": (data) => {
const msg = JSON.parse(data);
const key = msg.address;
if (key === "") {
return;
}
if (seen[key]) {
return;
}
seen[key] = true;

const kind = msg.kind;
const name = msg.name ? " " + msg.name : "";

const info = `${kind}${name} is connected`;
console.log(info);
},
});
});
</script>
Expand Down
12 changes: 8 additions & 4 deletions frontend/z2/z2-bundle.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file modified frontend/z2/z2.wasm
Binary file not shown.
1 change: 1 addition & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ func run() error {

btHandler := app.NewBTHandler(
graph,
br,
backends.RawValues,
multiSource,
opts.WriteRawValues,
Expand Down
9 changes: 1 addition & 8 deletions main_wasm.go
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,7 @@ func run() error {
}
}

btHandler := app.NewBTHandler(
graph,
nil,
multiSource,
opts.WriteRawValues,
cancel,
ctx,
)
btHandler := app.NewBTHandler(graph, nil, nil, multiSource, opts.WriteRawValues, cancel, ctx)

br := broker.NewBroker()
go br.Start()
Expand Down
47 changes: 12 additions & 35 deletions server/routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ package server

import (
"bytes"
"encoding/json"
"fmt"
"github.com/gin-gonic/gin"
"github.com/minor-industries/backup/restic"
Expand Down Expand Up @@ -147,6 +148,17 @@ func SetupRoutes(
switch msg := m.(type) {
case *app.PlaySound:
_ = send("play-sound", fmt.Sprintf("%s", msg.Sound))
case *app.BluetoothIsConnected:
info := msg.DeviceInfo
if info.Kind == "" || info.Address == "" {
continue
}
payload, _ := json.Marshal(map[string]string{
"kind": info.Kind,
"address": info.Address,
"name": info.Name,
})
_ = send("bluetooth-is-connected", string(payload))
}
}

Expand Down Expand Up @@ -220,38 +232,3 @@ func SetupRoutes(

return nil
}

func sse(
router *gin.Engine,
path string,
handler func(
c *gin.Context,
send func(eventName, data string) error,
),
) {
router.GET(path, func(c *gin.Context) {
c.Writer.Header().Set("Content-Type", "text/event-stream")
c.Writer.Header().Set("Cache-Control", "no-cache")
c.Writer.Header().Set("Connection", "keep-alive")

send := func(eventName, data string) error {
if eventName != "" {
_, err := c.Writer.Write([]byte("event: " + eventName + "\n"))
if err != nil {
return errors.Wrap(err, "write event")
}
}

_, err := c.Writer.Write([]byte("data: " + data + "\n\n"))
if err != nil {
if err != nil {
return errors.Wrap(err, "write data")
}
}
c.Writer.Flush()
return nil
}

handler(c, send)
})
}
41 changes: 41 additions & 0 deletions server/sse.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package server

import (
"github.com/gin-gonic/gin"
"github.com/pkg/errors"
)

func sse(
router *gin.Engine,
path string,
handler func(
c *gin.Context,
send func(eventName, data string) error,
),
) {
router.GET(path, func(c *gin.Context) {
c.Writer.Header().Set("Content-Type", "text/event-stream")
c.Writer.Header().Set("Cache-Control", "no-cache")
c.Writer.Header().Set("Connection", "keep-alive")

send := func(eventName, data string) error {
if eventName != "" {
_, err := c.Writer.Write([]byte("event: " + eventName + "\n"))
if err != nil {
return errors.Wrap(err, "write event")
}
}

_, err := c.Writer.Write([]byte("data: " + data + "\n\n"))
if err != nil {
if err != nil {
return errors.Wrap(err, "write data")
}
}
c.Writer.Flush()
return nil
}

handler(c, send)
})
}

0 comments on commit 3bdf144

Please sign in to comment.