ace/lib/webrtcconnection/datachannel.go

50 lines
1.1 KiB
Go
Raw Normal View History

2022-09-26 03:04:07 +00:00
package webrtcconnection
import (
"encoding/json"
"time"
"github.com/pion/webrtc/v3"
"github.com/sirupsen/logrus"
)
2022-09-27 02:21:06 +00:00
func (c *Connection) dataChannel(d *webrtc.DataChannel) {
2022-09-26 03:04:07 +00:00
d.OnOpen(func() {
for {
2022-09-27 02:21:06 +00:00
status := c.QEMU.GetStatus().String()
2022-09-26 03:04:07 +00:00
currentTime := time.Now().UnixMilli()
b, err := json.Marshal(map[string]any{
"qemu_status": status,
"server_time": currentTime,
})
if err != nil {
logrus.Errorf(
"failed to parse to json on '%s-%d' with error: %v",
d.Label(), *d.ID(), err,
)
}
if err := d.Send(b); err != nil {
logrus.Errorf(
"failed to send qemu status to '%s-%d' with error: %v",
d.Label(), *d.ID(), err,
)
}
time.Sleep(time.Second)
}
})
d.OnMessage(func(msg webrtc.DataChannelMessage) {
logrus.Debugf("received %d bytes message from '%s-%d'", len(msg.Data), d.Label(), *d.ID())
if !msg.IsString {
return
}
2022-09-27 02:21:06 +00:00
if err := c.QEMU.SendEvent(msg.Data); err != nil {
2022-09-26 03:04:07 +00:00
logrus.Errorf(
"cannot parse message from '%s-%d' to qemu controll event: %v",
d.Label(), *d.ID(), err,
)
}
})
}