Compare commits

...

No commits in common. "master" and "master" have entirely different histories.

14 changed files with 398 additions and 320 deletions

View File

@ -1,40 +1,38 @@
# InfiniTime
> **Warning** This library is no longer maintained. A rewrite has been merged into the ITD repo in [the infinitime subpackage](https://gitea.elara.ws/Elara6331/itd/src/branch/master/infinitime)
This is a go library for interfacing with InfiniTime firmware
over BLE on Linux.
[![Go Reference](https://pkg.go.dev/badge/go.elara.ws/infinitime.svg)](https://pkg.go.dev/go.elara.ws/infinitime)
[![Go Reference](https://pkg.go.dev/badge/go.arsenm.dev/infinitime.svg)](https://pkg.go.dev/go.arsenm.dev/infinitime)
---
### Importing
This library's import path is `go.elara.ws/infinitime`.
This library's import path is `go.arsenm.dev/infinitime`.
---
### Dependencies
This library requires `dbus`, and `bluez` to function. These allow the library to use bluetooth, control media, control volume, etc.
This library requires `dbus`, `bluez`, and `pactl` to function. These allow the library to use bluetooth, control media, control volume, etc.
#### Arch
```shell
sudo pacman -S dbus bluez --needed
sudo pacman -S dbus bluez libpulse --needed
```
#### Debian/Ubuntu
```shell
sudo apt install dbus bluez
sudo apt install dbus bluez pulseaudio-utils
```
#### Fedora
```shell
sudo dnf install dbus bluez
sudo dnf install dbus bluez pulseaudio-utils
```
---
@ -49,10 +47,9 @@ This library currently supports the following features:
- Battery level
- Music control
- OTA firmware upgrades
- Navigation
---
### Mentions
The DFU process used in this library was created with the help of [siglo](https://github.com/alexr4535/siglo)'s source code. Specifically, this file: [ble_dfu.py](https://github.com/alexr4535/siglo/blob/main/src/ble_dfu.py)
The DFU process used in this library was created with the help of [siglo](https://github.com/alexr4535/siglo)'s source code. Specifically, this file: [ble_dfu.py](https://github.com/alexr4535/siglo/blob/main/src/ble_dfu.py)

View File

@ -199,13 +199,7 @@ func decode(data []byte, vals ...interface{}) error {
// to send in a packet. Subtracting 20 ensures that the MTU
// is never exceeded.
func (blefs *FS) maxData() uint16 {
mtu := blefs.transferChar.Properties.MTU
// If MTU is zero, the current version of BlueZ likely
// doesn't support the MTU property, so assume 256.
if mtu == 0 {
mtu = 256
}
return mtu - 20
return blefs.transferChar.Properties.MTU - 20
}
// padding returns a slice of len amount of 0x00.

View File

@ -5,6 +5,7 @@ import (
bt "github.com/muka/go-bluetooth/api"
"github.com/muka/go-bluetooth/bluez/profile/adapter"
"github.com/muka/go-bluetooth/bluez/profile/agent"
"github.com/muka/go-bluetooth/hw/linux/btmgmt"
)
var defaultAdapter *adapter.Adapter1
@ -32,6 +33,9 @@ func Init(adapterID string) {
panic(err)
}
daMgmt := btmgmt.NewBtMgmt(adapterID)
daMgmt.SetPowered(true)
defaultAdapter = da
itdAgent = ag
}
@ -73,7 +77,7 @@ func (a *Agent) RequestPasskey(device dbus.ObjectPath) (uint32, *dbus.Error) {
if a.ReqPasskey == nil {
return 0, errAuthFailed
}
log.Debug("Passkey requested, calling onReqPasskey callback").Send()
log.Debug().Msg("Passkey requested, calling onReqPasskey callback")
passkey, err := a.ReqPasskey()
if err != nil {
return 0, errAuthFailed
@ -106,9 +110,9 @@ func (*Agent) Cancel() *dbus.Error {
return nil
}
// Path returns "/ws/elara/infinitime/Agent"
// Path returns "/dev/arsenm/infinitime/Agent"
func (*Agent) Path() dbus.ObjectPath {
return "/ws/elara/infinitime/Agent"
return "/dev/arsenm/infinitime/Agent"
}
// Interface returns "org.bluez.Agent1"

16
dfu.go
View File

@ -313,7 +313,7 @@ func (dfu *DFU) Reset() {
// on waits for the given command to be received on
// the control point characteristic, then runs the callback.
func (dfu *DFU) on(cmd []byte, onCmdCb func(data []byte) error) error {
log.Debug("Waiting for DFU command").Bytes("expecting", cmd).Send()
log.Debug().Hex("expecting", cmd).Msg("Waiting for DFU command")
// Use for loop in case of invalid property
for {
select {
@ -325,10 +325,10 @@ func (dfu *DFU) on(cmd []byte, onCmdCb func(data []byte) error) error {
}
// Assert propery value as byte slice
data := propChanged.Value.([]byte)
log.Debug("Received DFU command").
Bytes("expecting", cmd).
Bytes("received", data).
Send()
log.Debug().
Hex("expecting", cmd).
Hex("received", data).
Msg("Received DFU command")
// If command has prefix of given command
if bytes.HasPrefix(data, cmd) {
// Return callback with data after command
@ -413,7 +413,7 @@ func (dfu *DFU) stepSeven() error {
if err != nil {
return err
}
log.Debug("Sent firmware image segment").Send()
log.Debug().Msg("Sent firmware image segment")
// Increment bytes sent by amount read
dfu.bytesSent += len(segment)
}
@ -421,10 +421,10 @@ func (dfu *DFU) stepSeven() error {
err := dfu.on(DFUNotifPktRecvd, func(data []byte) error {
// Set bytes received to data returned by InfiniTime
dfu.bytesRecvd = int(binary.LittleEndian.Uint32(data))
log.Debug("Received packet receipt notification").
log.Debug().
Int("sent", dfu.bytesSent).
Int("rcvd", dfu.bytesRecvd).
Send()
Msg("Received packet receipt notification")
if dfu.bytesRecvd != dfu.bytesSent {
return ErrDFUSizeMismatch
}

4
go.mod
View File

@ -1,4 +1,4 @@
module go.elara.ws/infinitime
module go.arsenm.dev/infinitime
go 1.16
@ -6,6 +6,6 @@ require (
github.com/fxamacker/cbor/v2 v2.4.0
github.com/godbus/dbus/v5 v5.0.6
github.com/muka/go-bluetooth v0.0.0-20220819140550-1d8857e3b268
go.elara.ws/logger v0.0.0-20230928062203-85e135cf02ae
github.com/rs/zerolog v1.26.1
golang.org/x/sys v0.0.0-20220209214540-3681064d5158 // indirect
)

39
go.sum
View File

@ -1,3 +1,4 @@
github.com/coreos/go-systemd/v22 v22.3.2/go.mod h1:Y58oyj3AT4RCenI/lSvhwexgC+NSVTIJ3seZv2GcEnc=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
@ -6,17 +7,14 @@ github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga
github.com/fxamacker/cbor/v2 v2.4.0 h1:ri0ArlOR+5XunOP8CRUowT0pSJOwhW098ZCUyskZD88=
github.com/fxamacker/cbor/v2 v2.4.0/go.mod h1:TA1xS00nchWmaBnEIxPSE5oHLuJBAVvqrtAnWBwBCVo=
github.com/godbus/dbus/v5 v5.0.3/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/godbus/dbus/v5 v5.0.4/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/godbus/dbus/v5 v5.0.6 h1:mkgN1ofwASrYnJ5W6U/BxG15eXXXjirgZc7CLqkcaro=
github.com/godbus/dbus/v5 v5.0.6/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
github.com/gookit/color v1.5.1 h1:Vjg2VEcdHpwq+oY63s/ksHrgJYCTo0bwWvmmYWdE9fQ=
github.com/gookit/color v1.5.1/go.mod h1:wZFzea4X8qN6vHOSP2apMb4/+w/orMznEzYsIHPaqKM=
github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
github.com/kr/pty v1.1.1/go.mod h1:pFQYn66WHrOpPYNljwOMqo10TkYh1fy3cYio2l3bCsQ=
github.com/kr/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI=
github.com/mattn/go-isatty v0.0.14 h1:yVuAays6BHfxijgZPzw+3Zlu5yQgKGP2/hcQbHb7S9Y=
github.com/mattn/go-isatty v0.0.14/go.mod h1:7GGIvUiUoEMVVmxf/4nioHXj79iQHKdU27kJ6hsGG94=
github.com/muka/go-bluetooth v0.0.0-20220819140550-1d8857e3b268 h1:kOnq7TfaAO2Vc/MHxPqFIXe00y1qBxJAvhctXdko6vo=
github.com/muka/go-bluetooth v0.0.0-20220819140550-1d8857e3b268/go.mod h1:dMCjicU6vRBk34dqOmIZm0aod6gUwZXOXzBROqGous0=
github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno=
@ -24,51 +22,56 @@ github.com/paypal/gatt v0.0.0-20151011220935-4ae819d591cf/go.mod h1:+AwQL2mK3Pd3
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/rs/xid v1.3.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg=
github.com/rs/zerolog v1.26.1 h1:/ihwxqH+4z8UxyI70wM1z9yCvkWcfz/a3mj48k/Zngc=
github.com/rs/zerolog v1.26.1/go.mod h1:/wSSJWX7lVrsOwlbyTRSOJvqRlc+WjWlfes+CiJ+tmc=
github.com/sirupsen/logrus v1.6.0 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.6.1 h1:hDPOHmpOpP40lSULcqw7IrRb/u7w6RpDC9399XyoNd0=
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.7.2/go.mod h1:R6va5+xMeoiuVRoj+gSkQ7d3FALtqAAGI1FQKckRals=
github.com/stretchr/testify v1.8.0 h1:pSgiaMZlXftHpm5L7V1+rVB+AZJydKsMxsQBIJw4PKk=
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
github.com/suapapa/go_eddystone v1.3.1/go.mod h1:bXC11TfJOS+3g3q/Uzd7FKd5g62STQEfeEIhcKe4Qy8=
github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg=
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778 h1:QldyIu/L63oPpyvQmHgvgickp1Yw510KJOqX7H24mg8=
github.com/xo/terminfo v0.0.0-20210125001918-ca9a967f8778/go.mod h1:2MuV+tbUrU1zIOPMxZ5EncGwgmMJsa+9ucAQZXxsObs=
github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
go.elara.ws/logger v0.0.0-20230928062203-85e135cf02ae h1:d+gJUhEWSrOjrrfgeydYWEr8TTnx0DLvcVhghaOsFeE=
go.elara.ws/logger v0.0.0-20230928062203-85e135cf02ae/go.mod h1:qng49owViqsW5Aey93lwBXONw20oGbJIoLVscB16mPM=
github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.0.0-20211215165025-cf75a172585e/go.mod h1:P+XmwS30IXTQdn5tA2iutPOUgjI07+tq3H3K9MVA1s8=
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/mod v0.4.2/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20200822124328-c89045814202/go.mod h1:/O7V0waA8r7cgGh81Ro3o1hOxt32SMVPicZroKQ2sZA=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210805182204-aaa1db679c0d/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20200625203802-6e8e738ad208/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20210220032951-036812b2e83c/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190422165155-953cdadca894/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200728102440-3e129f6d46b1/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210330210617-4fbd30eecc44/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210630005230-0f9fa26af87c/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210809222454-d867a43fc93e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220209214540-3681064d5158 h1:rm+CHSpPEEW2IsXUib1ThaHIjuBVZjxNgSKmBLFfD4c=
golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.0.0-20200925191224-5d1fdd8fa346/go.mod h1:z6u4i615ZeAfBE4XtMziQW1fSVJXACjjbWkB/mvPzlU=
golang.org/x/tools v0.1.7/go.mod h1:LGqMHiF4EqQNHR1JncWGqT5BVaXmza+X+BDGol+dOxo=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c h1:dUUwHk2QECo/6vqA44rthZ8ie2QXMNeKRTHCNY2nXvo=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@ -15,14 +15,14 @@ import (
"github.com/muka/go-bluetooth/bluez/profile/adapter"
"github.com/muka/go-bluetooth/bluez/profile/device"
"github.com/muka/go-bluetooth/bluez/profile/gatt"
"go.elara.ws/infinitime/blefs"
"go.elara.ws/logger"
"github.com/rs/zerolog"
"go.arsenm.dev/infinitime/blefs"
)
// This global is used to store the logger.
// log.Logger is not used as it would interfere
// with the package importing the library
var log logger.Logger
var log zerolog.Logger
const BTName = "InfiniTime"
@ -33,7 +33,6 @@ const (
MotionValChar = "00030002-78fc-48fe-8e23-433b3a1942d0"
FirmwareVerChar = "00002a26-0000-1000-8000-00805f9b34fb"
CurrentTimeChar = "00002a2b-0000-1000-8000-00805f9b34fb"
LocalTimeChar = "00002a0f-0000-1000-8000-00805f9b34fb"
BatteryLvlChar = "00002a19-0000-1000-8000-00805f9b34fb"
HeartRateChar = "00002a37-0000-1000-8000-00805f9b34fb"
FSTransferChar = "adaf0200-4669-6c65-5472-616e73666572"
@ -42,22 +41,17 @@ const (
)
var charNames = map[string]string{
NewAlertChar: "New Alert",
NotifEventChar: "Notification Event",
StepCountChar: "Step Count",
MotionValChar: "Motion Values",
FirmwareVerChar: "Firmware Version",
CurrentTimeChar: "Current Time",
LocalTimeChar: "Local Time",
BatteryLvlChar: "Battery Level",
HeartRateChar: "Heart Rate",
FSTransferChar: "Filesystem Transfer",
FSVersionChar: "Filesystem Version",
WeatherDataChar: "Weather Data",
NavFlagsChar: "Navigation Icon",
NavNarrativeChar: "Navigation Instruction",
NavManDistChar: "Navigation Distance to next event",
NavProgressChar: "Navigation Progress",
NewAlertChar: "New Alert",
NotifEventChar: "Notification Event",
StepCountChar: "Step Count",
MotionValChar: "Motion Values",
FirmwareVerChar: "Firmware Version",
CurrentTimeChar: "Current Time",
BatteryLvlChar: "Battery Level",
HeartRateChar: "Heart Rate",
FSTransferChar: "Filesystem Transfer",
FSVersionChar: "Filesystem Version",
WeatherDataChar: "Weather Data",
}
type Device struct {
@ -68,17 +62,14 @@ type Device struct {
motionValChar *gatt.GattCharacteristic1
fwVersionChar *gatt.GattCharacteristic1
currentTimeChar *gatt.GattCharacteristic1
localTimeChar *gatt.GattCharacteristic1
battLevelChar *gatt.GattCharacteristic1
heartRateChar *gatt.GattCharacteristic1
fsVersionChar *gatt.GattCharacteristic1
fsTransferChar *gatt.GattCharacteristic1
weatherDataChar *gatt.GattCharacteristic1
weatherdataChar *gatt.GattCharacteristic1
notifEventCh chan uint8
notifEventDone bool
Music MusicCtrl
Navigation NavigationService
DFU DFU
}
@ -104,14 +95,15 @@ type Options struct {
Whitelist []string
OnReqPasskey func() (uint32, error)
OnReconnect func()
Logger logger.Logger
LogLevel logger.LogLevel
Logger zerolog.Logger
LogLevel zerolog.Level
}
var DefaultOptions = &Options{
AttemptReconnect: true,
WhitelistEnabled: false,
Logger: logger.NewNop(),
Logger: zerolog.Nop(),
LogLevel: zerolog.Disabled,
}
// Connect will attempt to connect to a
@ -125,8 +117,7 @@ func Connect(ctx context.Context, opts *Options) (*Device, error) {
opts = DefaultOptions
}
log = opts.Logger
opts.Logger.SetLevel(opts.LogLevel)
log = opts.Logger.Level(opts.LogLevel)
// Set passkey request callback
setOnPasskeyReq(opts.OnReqPasskey)
@ -139,7 +130,6 @@ func Connect(ctx context.Context, opts *Options) (*Device, error) {
// Create new device
out := &Device{device: btDev}
out.Navigation = NavigationService{dev: out}
// Resolve characteristics
err = out.resolveChars()
@ -168,25 +158,25 @@ func connect(ctx context.Context, opts *Options, first bool) (dev *device.Device
// device, skip
if opts.WhitelistEnabled &&
!contains(opts.Whitelist, listDev.Properties.Address) {
log.Debug("InfiniTime device skipped as it is not in whitelist").
log.Debug().
Str("mac", listDev.Properties.Address).
Send()
Msg("InfiniTime device skipped as it is not in whitelist")
continue
}
// Set device
dev = listDev
log.Debug("InfiniTime device found in list").
log.Debug().
Str("mac", dev.Properties.Address).
Send()
Msg("InfiniTime device found in list")
break
}
// If device not set
if dev == nil {
log.Debug("No device found in list, attempting to discover").Send()
log.Debug().Msg("No device found in list, attempting to discover")
// Discover devices on adapter
discoverCh, cancel, err := bt.Discover(defaultAdapter, &adapter.DiscoveryFilter{Transport: "le"})
if err != nil {
@ -216,18 +206,18 @@ func connect(ctx context.Context, opts *Options, first bool) (dev *device.Device
// device, skip
if opts.WhitelistEnabled &&
!contains(opts.Whitelist, discovered.Properties.Address) {
log.Debug("Discovered InfiniTime device skipped as it is not in whitelist").
log.Debug().
Str("mac", discovered.Properties.Address).
Send()
Msg("Discovered InfiniTime device skipped as it is not in whitelist")
continue
}
// Set device
dev = discovered
log.Debug("InfiniTime device discovered").
log.Debug().
Str("mac", dev.Properties.Address).
Send()
Msg("InfiniTime device discovered")
break discoverLoop
case <-ctx.Done():
break discoverLoop
@ -249,7 +239,7 @@ func connect(ctx context.Context, opts *Options, first bool) (dev *device.Device
reconnRequired := false
// If device is not connected
if !dev.Properties.Connected {
log.Debug("Device not connected, connecting").Send()
log.Debug().Msg("Device not connected, connecting")
// Connect to device
err = dev.Connect()
if err != nil {
@ -261,7 +251,7 @@ func connect(ctx context.Context, opts *Options, first bool) (dev *device.Device
// If device is not paired
if !dev.Properties.Paired {
log.Debug("Device not paired, pairing").Send()
log.Debug().Msg("Device not paired, pairing")
// Pair device
err = dev.Pair()
if err != nil {
@ -279,7 +269,7 @@ func connect(ctx context.Context, opts *Options, first bool) (dev *device.Device
// was required, and the OnReconnect callback exists,
// run it
if !first && reconnRequired && opts.OnReconnect != nil {
log.Debug("Reconnected to device, running OnReconnect callback").Send()
log.Debug().Msg("Reconnected to device, running OnReconnect callback")
opts.OnReconnect()
}
@ -312,7 +302,7 @@ func reconnect(ctx context.Context, opts *Options, dev *device.Device1) {
// If less than 3 seconds have passed and more than 6
// disconnects have occurred, remove the device and reset
if secsSince <= 3 && amtDisconnects >= 6 {
opts.Logger.Warn("At least 6 disconnects have occurred in the last three seconds. If this continues, try removing the InfiniTime device from bluetooth.").Send()
opts.Logger.Warn().Msg("At least 6 disconnects have occurred in the last three seconds. If this continues, try removing the InfiniTime device from bluetooth.")
lastDisconnect = time.Unix(0, 0)
amtDisconnects = 0
}
@ -324,7 +314,7 @@ func reconnect(ctx context.Context, opts *Options, dev *device.Device1) {
for i := 0; i < 6; i++ {
// If three tries failed, remove device
if i == 3 {
opts.Logger.Warn("Multiple connection attempts have failed. If this continues, try removing the InfiniTime device from bluetooth.").Send()
opts.Logger.Warn().Msg("Multiple connection attempts have failed. If this continues, try removing the InfiniTime device from bluetooth.")
}
// Connect to device
newDev, err := connect(ctx, opts, false)
@ -404,14 +394,6 @@ func (i *Device) resolveChars() error {
charResolved := true
// Set correct characteristics
switch char.Properties.UUID {
case NavFlagsChar:
i.Navigation.flagsChar = char
case NavNarrativeChar:
i.Navigation.narrativeChar = char
case NavManDistChar:
i.Navigation.mandistChar = char
case NavProgressChar:
i.Navigation.progressChar = char
case NewAlertChar:
i.newAlertChar = char
case NotifEventChar:
@ -424,8 +406,6 @@ func (i *Device) resolveChars() error {
i.fwVersionChar = char
case CurrentTimeChar:
i.currentTimeChar = char
case LocalTimeChar:
i.localTimeChar = char
case BatteryLvlChar:
i.battLevelChar = char
case HeartRateChar:
@ -454,10 +434,10 @@ func (i *Device) resolveChars() error {
charResolved = false
}
if charResolved {
log.Debug("Resolved characteristic").
log.Debug().
Str("uuid", char.Properties.UUID).
Str("name", charNames[char.Properties.UUID]).
Send()
Msg("Resolved characteristic")
}
}
return nil
@ -559,7 +539,7 @@ func (i *Device) WatchHeartRate(ctx context.Context) (<-chan uint8, error) {
for {
select {
case <-ctx.Done():
log.Debug("Received done signal").Str("func", "WatchMotion").Send()
log.Debug().Str("func", "WatchMotion").Msg("Received done signal")
close(out)
i.heartRateChar.StopNotify()
return
@ -569,7 +549,7 @@ func (i *Device) WatchHeartRate(ctx context.Context) (<-chan uint8, error) {
// Send heart rate to channel
out <- uint8(event.Value.([]byte)[1])
} else if event.Name == "Notifying" && !event.Value.(bool) {
log.Debug("Notifications stopped, restarting").Str("func", "WatchMotion").Send()
log.Debug().Str("func", "WatchMotion").Msg("Notifications stopped, restarting")
i.heartRateChar.StartNotify()
}
}
@ -603,7 +583,7 @@ func (i *Device) WatchBatteryLevel(ctx context.Context) (<-chan uint8, error) {
for {
select {
case <-ctx.Done():
log.Debug("Received done signal").Str("func", "WatchMotion").Send()
log.Debug().Str("func", "WatchMotion").Msg("Received done signal")
close(out)
i.battLevelChar.StopNotify()
return
@ -613,7 +593,7 @@ func (i *Device) WatchBatteryLevel(ctx context.Context) (<-chan uint8, error) {
// Send heart rate to channel
out <- uint8(event.Value.([]byte)[0])
} else if event.Name == "Notifying" && !event.Value.(bool) {
log.Debug("Notifications stopped, restarting").Str("func", "WatchMotion").Send()
log.Debug().Str("func", "WatchMotion").Msg("Notifications stopped, restarting")
i.battLevelChar.StartNotify()
}
}
@ -647,7 +627,7 @@ func (i *Device) WatchStepCount(ctx context.Context) (<-chan uint32, error) {
for {
select {
case <-ctx.Done():
log.Debug("Received done signal").Str("func", "WatchMotion").Send()
log.Debug().Str("func", "WatchMotion").Msg("Received done signal")
close(out)
i.stepCountChar.StopNotify()
return
@ -657,7 +637,7 @@ func (i *Device) WatchStepCount(ctx context.Context) (<-chan uint32, error) {
// Send step count to channel
out <- binary.LittleEndian.Uint32(event.Value.([]byte))
} else if event.Name == "Notifying" && !event.Value.(bool) {
log.Debug("Notifications stopped, restarting").Str("func", "WatchMotion").Send()
log.Debug().Str("func", "WatchMotion").Msg("Notifications stopped, restarting")
i.stepCountChar.StartNotify()
}
}
@ -691,7 +671,7 @@ func (i *Device) WatchMotion(ctx context.Context) (<-chan MotionValues, error) {
for {
select {
case <-ctx.Done():
log.Debug("Received done signal").Str("func", "WatchMotion").Send()
log.Debug().Str("func", "WatchMotion").Msg("Received done signal")
close(out)
i.motionValChar.StopNotify()
return
@ -703,7 +683,7 @@ func (i *Device) WatchMotion(ctx context.Context) (<-chan MotionValues, error) {
// Send step count to channel
out <- motionVals
} else if event.Name == "Notifying" && !event.Value.(bool) {
log.Debug("Notifications stopped, restarting").Str("func", "WatchMotion").Send()
log.Debug().Str("func", "WatchMotion").Msg("Notifications stopped, restarting")
i.motionValChar.StartNotify()
}
}
@ -713,9 +693,7 @@ func (i *Device) WatchMotion(ctx context.Context) (<-chan MotionValues, error) {
return out, nil
}
// SetTime sets the watch's
// * time using the Current Time Service's current time characteristic
// * timezone information using the CTS's local time characteristic
// SetTime sets the watch's time using the Current Time Service
func (i *Device) SetTime(t time.Time) error {
if err := i.checkStatus(i.currentTimeChar, CurrentTimeChar); err != nil {
return err
@ -730,38 +708,7 @@ func (i *Device) SetTime(t time.Time) error {
binary.Write(buf, binary.LittleEndian, uint8(t.Weekday()))
binary.Write(buf, binary.LittleEndian, uint8((t.Nanosecond()/1000)/1e6*256))
binary.Write(buf, binary.LittleEndian, uint8(0b0001))
if err := i.currentTimeChar.WriteValue(buf.Bytes(), nil); err != nil {
return err
}
if err := i.checkStatus(i.localTimeChar, LocalTimeChar); err != nil {
// If the characteristic is unavailable,
// fail silently, as many people may be on
// older InfiniTime versions. A warning
// may be added later.
if _, ok := err.(ErrCharNotAvail); ok {
return nil
} else {
return err
}
}
_, offset := t.Zone()
dst := 0
// Local time expects two values: the timezone offset and the dst offset, both
// expressed in quarters of an hour.
// Timezone offset is to be constant over DST, with dst offset holding the offset != 0
// when DST is in effect.
// As there is no standard way in go to get the actual dst offset, we assume it to be 1h
// when DST is in effect
if t.IsDST() {
dst = 3600
offset -= 3600
}
bufTz := &bytes.Buffer{}
binary.Write(bufTz, binary.LittleEndian, uint8(offset/3600*4))
binary.Write(bufTz, binary.LittleEndian, uint8(dst/3600*4))
return i.localTimeChar.WriteValue(bufTz.Bytes(), nil)
return i.currentTimeChar.WriteValue(buf.Bytes(), nil)
}
// Notify sends a notification to InfiniTime via
@ -866,13 +813,13 @@ func (i *Device) AddWeatherEvent(event interface{}) error {
return err
}
log.Debug("Adding weather event").Any("event", event).Send()
log.Debug().Interface("event", event).Msg("Adding weather event")
// Write data to weather data characteristic
return i.weatherDataChar.WriteValue(data, nil)
}
func (i *Device) checkStatus(char *gatt.GattCharacteristic1, uuid string) error {
log.Debug("Checking characteristic status").Send()
log.Debug().Msg("Checking characteristic status")
connected, err := i.device.GetConnected()
if err != nil {
return err
@ -881,12 +828,12 @@ func (i *Device) checkStatus(char *gatt.GattCharacteristic1, uuid string) error
return ErrNotConnected
}
if char == nil {
log.Debug("Characteristic not available (nil)").Send()
log.Debug().Msg("Characteristic not available (nil)")
return ErrCharNotAvail{uuid}
}
log.Debug("Characteristic available").
log.Debug().
Str("uuid", char.Properties.UUID).
Str("name", charNames[char.Properties.UUID]).
Send()
Msg("Characteristic available")
return nil
}

37
internal/utils/dbus.go Normal file
View File

@ -0,0 +1,37 @@
package utils
import "github.com/godbus/dbus/v5"
func NewSystemBusConn() (*dbus.Conn, error) {
// Connect to dbus session bus
conn, err := dbus.SystemBusPrivate()
if err != nil {
return nil, err
}
err = conn.Auth(nil)
if err != nil {
return nil, err
}
err = conn.Hello()
if err != nil {
return nil, err
}
return conn, nil
}
func NewSessionBusConn() (*dbus.Conn, error) {
// Connect to dbus session bus
conn, err := dbus.SessionBusPrivate()
if err != nil {
return nil, err
}
err = conn.Auth(nil)
if err != nil {
return nil, err
}
err = conn.Hello()
if err != nil {
return nil, err
}
return conn, nil
}

View File

@ -72,7 +72,7 @@ func (mc MusicCtrl) WatchEvents() (<-chan MusicEvent, error) {
for event := range ch {
// If value changes
if event.Name == "Value" {
log.Debug("Received music event from watch").Bytes("value", event.Value.([]byte)).Send()
log.Debug().Bytes("value", event.Value.([]byte)).Msg("Received music event from watch")
// Send music event to channel
musicEventCh <- MusicEvent(event.Value.([]byte)[0])
}

View File

@ -1,152 +0,0 @@
package infinitime
import (
"errors"
"github.com/muka/go-bluetooth/bluez/profile/gatt"
)
var ErrNavProgress = errors.New("progress needs to be between 0 and 100")
const (
NavFlagsChar = "00010001-78fc-48fe-8e23-433b3a1942d0"
NavNarrativeChar = "00010002-78fc-48fe-8e23-433b3a1942d0"
NavManDistChar = "00010003-78fc-48fe-8e23-433b3a1942d0"
NavProgressChar = "00010004-78fc-48fe-8e23-433b3a1942d0"
)
type NavigationService struct {
dev *Device
flagsChar *gatt.GattCharacteristic1
narrativeChar *gatt.GattCharacteristic1
mandistChar *gatt.GattCharacteristic1
progressChar *gatt.GattCharacteristic1
}
type NavFlag string
const (
NavFlagArrive NavFlag = "arrive"
NavFlagArriveLeft NavFlag = "arrive-left"
NavFlagArriveRight NavFlag = "arrive-right"
NavFlagArriveStraight NavFlag = "arrive-straight"
NavFlagClose NavFlag = "close"
NavFlagContinue NavFlag = "continue"
NavFlagContinueLeft NavFlag = "continue-left"
NavFlagContinueRight NavFlag = "continue-right"
NavFlagContinueSlightLeft NavFlag = "continue-slight-left"
NavFlagContinueSlightRight NavFlag = "continue-slight-right"
NavFlagContinueStraight NavFlag = "continue-straight"
NavFlagContinueUturn NavFlag = "continue-uturn"
NavFlagDepart NavFlag = "depart"
NavFlagDepartLeft NavFlag = "depart-left"
NavFlagDepartRight NavFlag = "depart-right"
NavFlagDepartStraight NavFlag = "depart-straight"
NavFlagEndOfRoadLeft NavFlag = "end-of-road-left"
NavFlagEndOfRoadRight NavFlag = "end-of-road-right"
NavFlagFerry NavFlag = "ferry"
NavFlagFlag NavFlag = "flag"
NavFlagFork NavFlag = "fork"
NavFlagForkLeft NavFlag = "fork-left"
NavFlagForkRight NavFlag = "fork-right"
NavFlagForkSlightLeft NavFlag = "fork-slight-left"
NavFlagForkSlightRight NavFlag = "fork-slight-right"
NavFlagForkStraight NavFlag = "fork-straight"
NavFlagInvalid NavFlag = "invalid"
NavFlagInvalidLeft NavFlag = "invalid-left"
NavFlagInvalidRight NavFlag = "invalid-right"
NavFlagInvalidSlightLeft NavFlag = "invalid-slight-left"
NavFlagInvalidSlightRight NavFlag = "invalid-slight-right"
NavFlagInvalidStraight NavFlag = "invalid-straight"
NavFlagInvalidUturn NavFlag = "invalid-uturn"
NavFlagMergeLeft NavFlag = "merge-left"
NavFlagMergeRight NavFlag = "merge-right"
NavFlagMergeSlightLeft NavFlag = "merge-slight-left"
NavFlagMergeSlightRight NavFlag = "merge-slight-right"
NavFlagMergeStraight NavFlag = "merge-straight"
NavFlagNewNameLeft NavFlag = "new-name-left"
NavFlagNewNameRight NavFlag = "new-name-right"
NavFlagNewNameSharpLeft NavFlag = "new-name-sharp-left"
NavFlagNewNameSharpRight NavFlag = "new-name-sharp-right"
NavFlagNewNameSlightLeft NavFlag = "new-name-slight-left"
NavFlagNewNameSlightRight NavFlag = "new-name-slight-right"
NavFlagNewNameStraight NavFlag = "new-name-straight"
NavFlagNotificationLeft NavFlag = "notification-left"
NavFlagNotificationRight NavFlag = "notification-right"
NavFlagNotificationSharpLeft NavFlag = "notification-sharp-left"
NavFlagNotificationSharpRight NavFlag = "notification-sharp-right"
NavFlagNotificationSlightLeft NavFlag = "notification-slight-left"
NavFlagNotificationSlightRight NavFlag = "notification-slight-right"
NavFlagNotificationStraight NavFlag = "notification-straight"
NavFlagOffRampLeft NavFlag = "off-ramp-left"
NavFlagOffRampRight NavFlag = "off-ramp-right"
NavFlagOffRampSharpLeft NavFlag = "off-ramp-sharp-left"
NavFlagOffRampSharpRight NavFlag = "off-ramp-sharp-right"
NavFlagOffRampSlightLeft NavFlag = "off-ramp-slight-left"
NavFlagOffRampSlightRight NavFlag = "off-ramp-slight-right"
NavFlagOffRampStraight NavFlag = "off-ramp-straight"
NavFlagOnRampLeft NavFlag = "on-ramp-left"
NavFlagOnRampRight NavFlag = "on-ramp-right"
NavFlagOnRampSharpLeft NavFlag = "on-ramp-sharp-left"
NavFlagOnRampSharpRight NavFlag = "on-ramp-sharp-right"
NavFlagOnRampSlightLeft NavFlag = "on-ramp-slight-left"
NavFlagOnRampSlightRight NavFlag = "on-ramp-slight-right"
NavFlagOnRampStraight NavFlag = "on-ramp-straight"
NavFlagRotary NavFlag = "rotary"
NavFlagRotaryLeft NavFlag = "rotary-left"
NavFlagRotaryRight NavFlag = "rotary-right"
NavFlagRotarySharpLeft NavFlag = "rotary-sharp-left"
NavFlagRotarySharpRight NavFlag = "rotary-sharp-right"
NavFlagRotarySlightLeft NavFlag = "rotary-slight-left"
NavFlagRotarySlightRight NavFlag = "rotary-slight-right"
NavFlagRotaryStraight NavFlag = "rotary-straight"
NavFlagRoundabout NavFlag = "roundabout"
NavFlagRoundaboutLeft NavFlag = "roundabout-left"
NavFlagRoundaboutRight NavFlag = "roundabout-right"
NavFlagRoundaboutSharpLeft NavFlag = "roundabout-sharp-left"
NavFlagRoundaboutSharpRight NavFlag = "roundabout-sharp-right"
NavFlagRoundaboutSlightLeft NavFlag = "roundabout-slight-left"
NavFlagRoundaboutSlightRight NavFlag = "roundabout-slight-right"
NavFlagRoundaboutStraight NavFlag = "roundabout-straight"
NavFlagTurnLeft NavFlag = "turn-left"
NavFlagTurnRight NavFlag = "turn-right"
NavFlagTurnSharpLeft NavFlag = "turn-sharp-left"
NavFlagTurnSharpRight NavFlag = "turn-sharp-right"
NavFlagTurnSlightLeft NavFlag = "turn-slight-left"
NavFlagTurnSlightRight NavFlag = "turn-slight-right"
NavFlagTurnStright NavFlag = "turn-stright"
NavFlagUpdown NavFlag = "updown"
NavFlagUturn NavFlag = "uturn"
)
func (n *NavigationService) SetFlag(flag NavFlag) error {
log.Debug("Sending flag").Str("func", "SetFlag").Send()
if err := n.dev.checkStatus(n.flagsChar, NavFlagsChar); err != nil {
return err
}
return n.flagsChar.WriteValue([]byte(flag), nil)
}
func (n *NavigationService) SetNarrative(narrative string) error {
log.Debug("Sending narrative").Str("func", "SetNarrative").Send()
if err := n.dev.checkStatus(n.narrativeChar, NavNarrativeChar); err != nil {
return err
}
return n.narrativeChar.WriteValue([]byte(narrative), nil)
}
func (n *NavigationService) SetManDist(manDist string) error {
log.Debug("Sending maneuver distance").Str("func", "SetNarrative").Send()
if err := n.dev.checkStatus(n.mandistChar, NavManDistChar); err != nil {
return err
}
return n.mandistChar.WriteValue([]byte(manDist), nil)
}
func (n *NavigationService) SetProgress(progress uint8) error {
log.Debug("Sending progress").Str("func", "SetNarrative").Send()
if err := n.dev.checkStatus(n.progressChar, NavProgressChar); err != nil {
return err
}
return n.progressChar.WriteValue([]byte{progress}, nil)
}

16
pkg/player/pactl.go Normal file
View File

@ -0,0 +1,16 @@
package player
import (
"fmt"
"os/exec"
)
// VolUp uses pactl to increase the volume of the default sink
func VolUp(percent uint) error {
return exec.Command("pactl", "set-sink-volume", "@DEFAULT_SINK@", fmt.Sprintf("+%d%%", percent)).Run()
}
// VolDown uses pactl to decrease the volume of the default sink
func VolDown(percent uint) error {
return exec.Command("pactl", "set-sink-volume", "@DEFAULT_SINK@", fmt.Sprintf("-%d%%", percent)).Run()
}

231
pkg/player/player.go Normal file
View File

@ -0,0 +1,231 @@
package player
import (
"strings"
"sync"
"github.com/godbus/dbus/v5"
"go.arsenm.dev/infinitime/internal/utils"
)
var (
method, monitor *dbus.Conn
monitorCh chan *dbus.Message
onChangeOnce sync.Once
)
// Init makes required connections to DBis and
// initializes change monitoring channel
func Init() error {
// Connect to session bus for monitoring
monitorConn, err := utils.NewSessionBusConn()
if err != nil {
return err
}
// Add match rule for PropertiesChanged on media player
monitorConn.AddMatchSignal(
dbus.WithMatchObjectPath("/org/mpris/MediaPlayer2"),
dbus.WithMatchInterface("org.freedesktop.DBus.Properties"),
dbus.WithMatchMember("PropertiesChanged"),
)
monitorCh = make(chan *dbus.Message, 10)
monitorConn.Eavesdrop(monitorCh)
// Connect to session bus for method calls
methodConn, err := utils.NewSessionBusConn()
if err != nil {
return err
}
method, monitor = methodConn, monitorConn
return nil
}
// Exit closes all connections and channels
func Exit() {
close(monitorCh)
method.Close()
monitor.Close()
}
// Play uses MPRIS to play media
func Play() error {
player, err := getPlayerObj()
if err != nil {
return err
}
if player != nil {
call := player.Call("org.mpris.MediaPlayer2.Player.Play", 0)
if call.Err != nil {
return call.Err
}
}
return nil
}
// Pause uses MPRIS to pause media
func Pause() error {
player, err := getPlayerObj()
if err != nil {
return err
}
if player != nil {
call := player.Call("org.mpris.MediaPlayer2.Player.Pause", 0)
if call.Err != nil {
return call.Err
}
}
return nil
}
// Next uses MPRIS to skip to next media
func Next() error {
player, err := getPlayerObj()
if err != nil {
return err
}
if player != nil {
call := player.Call("org.mpris.MediaPlayer2.Player.Next", 0)
if call.Err != nil {
return call.Err
}
}
return nil
}
// Prev uses MPRIS to skip to previous media
func Prev() error {
player, err := getPlayerObj()
if err != nil {
return err
}
if player != nil {
call := player.Call("org.mpris.MediaPlayer2.Player.Previous", 0)
if call.Err != nil {
return call.Err
}
}
return nil
}
type ChangeType int
const (
ChangeTypeTitle ChangeType = iota
ChangeTypeArtist
ChangeTypeAlbum
ChangeTypeStatus
)
func (ct ChangeType) String() string {
switch ct {
case ChangeTypeTitle:
return "Title"
case ChangeTypeAlbum:
return "Album"
case ChangeTypeArtist:
return "Artist"
case ChangeTypeStatus:
return "Status"
}
return ""
}
// OnChange runs cb when a value changes
func OnChange(cb func(ChangeType, string)) {
go onChangeOnce.Do(func() {
// For every message on channel
for msg := range monitorCh {
// Parse PropertiesChanged
iface, changed, ok := parsePropertiesChanged(msg)
if !ok || iface != "org.mpris.MediaPlayer2.Player" {
continue
}
// For every property changed
for name, val := range changed {
// If metadata changed
if name == "Metadata" {
// Get fields
fields := val.Value().(map[string]dbus.Variant)
// For every field
for name, val := range fields {
// Handle each field appropriately
if strings.HasSuffix(name, "title") {
title := val.Value().(string)
if title == "" {
title = "Unknown " + ChangeTypeTitle.String()
}
cb(ChangeTypeTitle, title)
} else if strings.HasSuffix(name, "album") {
album := val.Value().(string)
if album == "" {
album = "Unknown " + ChangeTypeAlbum.String()
}
cb(ChangeTypeAlbum, album)
} else if strings.HasSuffix(name, "artist") {
var artists string
switch artistVal := val.Value().(type) {
case string:
artists = artistVal
case []string:
artists = strings.Join(artistVal, ", ")
}
if artists == "" {
artists = "Unknown " + ChangeTypeArtist.String()
}
cb(ChangeTypeArtist, artists)
}
}
} else if name == "PlaybackStatus" {
// Handle status change
cb(ChangeTypeStatus, val.Value().(string))
}
}
}
})
}
// getPlayerNames gets all DBus MPRIS player bus names
func getPlayerNames(conn *dbus.Conn) ([]string, error) {
var names []string
err := conn.BusObject().Call("org.freedesktop.DBus.ListNames", 0).Store(&names)
if err != nil {
return nil, err
}
var players []string
for _, name := range names {
if strings.HasPrefix(name, "org.mpris.MediaPlayer2") {
players = append(players, name)
}
}
return players, nil
}
// GetPlayerObj gets the object corresponding to the first
// bus name found in DBus
func getPlayerObj() (dbus.BusObject, error) {
players, err := getPlayerNames(method)
if err != nil {
return nil, err
}
if len(players) == 0 {
return nil, nil
}
return method.Object(players[0], "/org/mpris/MediaPlayer2"), nil
}
// parsePropertiesChanged parses a DBus PropertiesChanged signal
func parsePropertiesChanged(msg *dbus.Message) (iface string, changed map[string]dbus.Variant, ok bool) {
if len(msg.Body) != 3 {
return "", nil, false
}
iface, ok = msg.Body[0].(string)
if !ok {
return
}
changed, ok = msg.Body[1].(map[string]dbus.Variant)
if !ok {
return
}
return
}

View File

@ -7,7 +7,7 @@ import (
"os"
"path/filepath"
"go.elara.ws/infinitime/blefs"
"go.arsenm.dev/infinitime/blefs"
)
// ResourceOperation represents an operation performed during
@ -80,7 +80,7 @@ func LoadResources(file *os.File, fs *blefs.FS) (<-chan ResourceLoadProgress, er
m.Close()
log.Debug("Decoded manifest file").Send()
log.Debug().Msg("Decoded manifest file")
go func() {
defer close(out)
@ -88,7 +88,7 @@ func LoadResources(file *os.File, fs *blefs.FS) (<-chan ResourceLoadProgress, er
for _, file := range manifest.Obsolete {
name := filepath.Base(file.Path)
log.Debug("Removing file").Str("file", file.Path).Send()
log.Debug().Str("file", file.Path).Msg("Removing file")
err := fs.RemoveAll(file.Path)
if err != nil {
@ -100,7 +100,7 @@ func LoadResources(file *os.File, fs *blefs.FS) (<-chan ResourceLoadProgress, er
return
}
log.Debug("Removed file").Str("file", file.Path).Send()
log.Debug().Str("file", file.Path).Msg("Removed file")
out <- ResourceLoadProgress{
Name: name,
@ -131,11 +131,11 @@ func LoadResources(file *os.File, fs *blefs.FS) (<-chan ResourceLoadProgress, er
return
}
log.Debug("Making directories").Str("file", file.Path).Send()
log.Debug().Str("file", file.Path).Msg("Making directories")
err = fs.MkdirAll(filepath.Dir(file.Path))
if err != nil {
log.Debug("Error making directories").Err(err).Send()
log.Debug().Err(err).Msg("Error making directories")
out <- ResourceLoadProgress{
Name: file.Name,
Operation: ResourceOperationUpload,
@ -146,14 +146,14 @@ func LoadResources(file *os.File, fs *blefs.FS) (<-chan ResourceLoadProgress, er
return
}
log.Debug("Creating file").
log.Debug().
Str("file", file.Path).
Int64("size", srcFi.Size()).
Send()
Msg("Creating file")
dst, err := fs.Create(file.Path, uint32(srcFi.Size()))
if err != nil {
log.Debug("Error creating file").Err(err).Send()
log.Debug().Err(err).Msg("Error creating file")
out <- ResourceLoadProgress{
Name: file.Name,
Operation: ResourceOperationUpload,
@ -167,10 +167,10 @@ func LoadResources(file *os.File, fs *blefs.FS) (<-chan ResourceLoadProgress, er
progCh := dst.Progress()
go func() {
for sent := range progCh {
log.Debug("Progress event sent").
log.Debug().
Int64("total", srcFi.Size()).
Uint32("sent", sent).
Send()
Msg("Progress event sent")
out <- ResourceLoadProgress{
Name: file.Name,
@ -187,7 +187,7 @@ func LoadResources(file *os.File, fs *blefs.FS) (<-chan ResourceLoadProgress, er
n, err := io.Copy(dst, src)
if err != nil {
log.Debug("Error writing to file").Err(err).Send()
log.Debug().Err(err).Msg("Error writing to file")
out <- ResourceLoadProgress{
Name: file.Name,
Operation: ResourceOperationUpload,

View File

@ -81,12 +81,13 @@ type TimelineHeader struct {
// NewHeader creates and populates a new timeline header
// and returns it
func NewHeader(t time.Time, evtType EventType, expires time.Duration) TimelineHeader {
_, offset := t.Zone()
t = t.Add(time.Duration(offset) * time.Second)
func NewHeader(evtType EventType, expires time.Duration) TimelineHeader {
now := time.Now()
_, offset := now.Zone()
now = now.Add(time.Duration(offset) * time.Second)
return TimelineHeader{
Timestamp: uint64(t.Unix()),
Timestamp: uint64(now.Unix()),
Expires: uint32(expires.Seconds()),
EventType: evtType,
}