Compare commits

..

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

12 changed files with 409 additions and 134 deletions

View File

@ -1,17 +1,15 @@
# InfiniTime # 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 This is a go library for interfacing with InfiniTime firmware
over BLE on Linux. 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 ### Importing
This library's import path is `go.elara.ws/infinitime`. This library's import path is `go.arsenm.dev/infinitime`.
--- ---

View File

@ -5,6 +5,7 @@ import (
bt "github.com/muka/go-bluetooth/api" bt "github.com/muka/go-bluetooth/api"
"github.com/muka/go-bluetooth/bluez/profile/adapter" "github.com/muka/go-bluetooth/bluez/profile/adapter"
"github.com/muka/go-bluetooth/bluez/profile/agent" "github.com/muka/go-bluetooth/bluez/profile/agent"
"github.com/muka/go-bluetooth/hw/linux/btmgmt"
) )
var defaultAdapter *adapter.Adapter1 var defaultAdapter *adapter.Adapter1
@ -32,6 +33,9 @@ func Init(adapterID string) {
panic(err) panic(err)
} }
daMgmt := btmgmt.NewBtMgmt(adapterID)
daMgmt.SetPowered(true)
defaultAdapter = da defaultAdapter = da
itdAgent = ag itdAgent = ag
} }
@ -73,7 +77,7 @@ func (a *Agent) RequestPasskey(device dbus.ObjectPath) (uint32, *dbus.Error) {
if a.ReqPasskey == nil { if a.ReqPasskey == nil {
return 0, errAuthFailed return 0, errAuthFailed
} }
log.Debug("Passkey requested, calling onReqPasskey callback").Send() log.Debug().Msg("Passkey requested, calling onReqPasskey callback")
passkey, err := a.ReqPasskey() passkey, err := a.ReqPasskey()
if err != nil { if err != nil {
return 0, errAuthFailed return 0, errAuthFailed
@ -106,9 +110,9 @@ func (*Agent) Cancel() *dbus.Error {
return nil return nil
} }
// Path returns "/ws/elara/infinitime/Agent" // Path returns "/dev/arsenm/infinitime/Agent"
func (*Agent) Path() dbus.ObjectPath { func (*Agent) Path() dbus.ObjectPath {
return "/ws/elara/infinitime/Agent" return "/dev/arsenm/infinitime/Agent"
} }
// Interface returns "org.bluez.Agent1" // 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 // on waits for the given command to be received on
// the control point characteristic, then runs the callback. // the control point characteristic, then runs the callback.
func (dfu *DFU) on(cmd []byte, onCmdCb func(data []byte) error) error { 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 // Use for loop in case of invalid property
for { for {
select { select {
@ -325,10 +325,10 @@ func (dfu *DFU) on(cmd []byte, onCmdCb func(data []byte) error) error {
} }
// Assert propery value as byte slice // Assert propery value as byte slice
data := propChanged.Value.([]byte) data := propChanged.Value.([]byte)
log.Debug("Received DFU command"). log.Debug().
Bytes("expecting", cmd). Hex("expecting", cmd).
Bytes("received", data). Hex("received", data).
Send() Msg("Received DFU command")
// If command has prefix of given command // If command has prefix of given command
if bytes.HasPrefix(data, cmd) { if bytes.HasPrefix(data, cmd) {
// Return callback with data after command // Return callback with data after command
@ -413,7 +413,7 @@ func (dfu *DFU) stepSeven() error {
if err != nil { if err != nil {
return err return err
} }
log.Debug("Sent firmware image segment").Send() log.Debug().Msg("Sent firmware image segment")
// Increment bytes sent by amount read // Increment bytes sent by amount read
dfu.bytesSent += len(segment) dfu.bytesSent += len(segment)
} }
@ -421,10 +421,10 @@ func (dfu *DFU) stepSeven() error {
err := dfu.on(DFUNotifPktRecvd, func(data []byte) error { err := dfu.on(DFUNotifPktRecvd, func(data []byte) error {
// Set bytes received to data returned by InfiniTime // Set bytes received to data returned by InfiniTime
dfu.bytesRecvd = int(binary.LittleEndian.Uint32(data)) dfu.bytesRecvd = int(binary.LittleEndian.Uint32(data))
log.Debug("Received packet receipt notification"). log.Debug().
Int("sent", dfu.bytesSent). Int("sent", dfu.bytesSent).
Int("rcvd", dfu.bytesRecvd). Int("rcvd", dfu.bytesRecvd).
Send() Msg("Received packet receipt notification")
if dfu.bytesRecvd != dfu.bytesSent { if dfu.bytesRecvd != dfu.bytesSent {
return ErrDFUSizeMismatch return ErrDFUSizeMismatch
} }

4
go.mod
View File

@ -1,4 +1,4 @@
module go.elara.ws/infinitime module go.arsenm.dev/infinitime
go 1.16 go 1.16
@ -6,6 +6,6 @@ require (
github.com/fxamacker/cbor/v2 v2.4.0 github.com/fxamacker/cbor/v2 v2.4.0
github.com/godbus/dbus/v5 v5.0.6 github.com/godbus/dbus/v5 v5.0.6
github.com/muka/go-bluetooth v0.0.0-20220819140550-1d8857e3b268 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 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.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 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 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 h1:ri0ArlOR+5XunOP8CRUowT0pSJOwhW098ZCUyskZD88=
github.com/fxamacker/cbor/v2 v2.4.0/go.mod h1:TA1xS00nchWmaBnEIxPSE5oHLuJBAVvqrtAnWBwBCVo= 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.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 h1:mkgN1ofwASrYnJ5W6U/BxG15eXXXjirgZc7CLqkcaro=
github.com/godbus/dbus/v5 v5.0.6/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= 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/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 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8=
github.com/konsorten/go-windows-terminal-sequences v1.0.3/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= 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/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/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 h1:kOnq7TfaAO2Vc/MHxPqFIXe00y1qBxJAvhctXdko6vo=
github.com/muka/go-bluetooth v0.0.0-20220819140550-1d8857e3b268/go.mod h1:dMCjicU6vRBk34dqOmIZm0aod6gUwZXOXzBROqGous0= 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= 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/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 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= 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 h1:UBcNElsrwanuuMsnGSlYmtmgbb23qDR5dG+6X6Oo89I=
github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= 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.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.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.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/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 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM=
github.com/x448/float16 v0.8.4/go.mod h1:14CWIYCyZA/cWjXOioeEpHeN/83MdbZDRQHoFcYsOfg= 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= github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
go.elara.ws/logger v0.0.0-20230928062203-85e135cf02ae h1:d+gJUhEWSrOjrrfgeydYWEr8TTnx0DLvcVhghaOsFeE= github.com/yuin/goldmark v1.4.0/go.mod h1:mwnBkeHKe2W/ZEtQ+71ViKU8L12m81fl3OWwC1Zlc8k=
go.elara.ws/logger v0.0.0-20230928062203-85e135cf02ae/go.mod h1:qng49owViqsW5Aey93lwBXONw20oGbJIoLVscB16mPM=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= 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-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-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.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-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-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-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-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-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-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-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-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-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-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-20201119102817-f84b799fce68/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-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210927094055-39ccf1dd6fa6/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 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 h1:rm+CHSpPEEW2IsXUib1ThaHIjuBVZjxNgSKmBLFfD4c=
golang.org/x/sys v0.0.0-20220209214540-3681064d5158/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= 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.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-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.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-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-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20200804184101-5ec99f83aff1/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 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/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.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/adapter"
"github.com/muka/go-bluetooth/bluez/profile/device" "github.com/muka/go-bluetooth/bluez/profile/device"
"github.com/muka/go-bluetooth/bluez/profile/gatt" "github.com/muka/go-bluetooth/bluez/profile/gatt"
"go.elara.ws/infinitime/blefs" "github.com/rs/zerolog"
"go.elara.ws/logger" "go.arsenm.dev/infinitime/blefs"
) )
// This global is used to store the logger. // This global is used to store the logger.
// log.Logger is not used as it would interfere // log.Logger is not used as it would interfere
// with the package importing the library // with the package importing the library
var log logger.Logger var log zerolog.Logger
const BTName = "InfiniTime" const BTName = "InfiniTime"
@ -33,7 +33,6 @@ const (
MotionValChar = "00030002-78fc-48fe-8e23-433b3a1942d0" MotionValChar = "00030002-78fc-48fe-8e23-433b3a1942d0"
FirmwareVerChar = "00002a26-0000-1000-8000-00805f9b34fb" FirmwareVerChar = "00002a26-0000-1000-8000-00805f9b34fb"
CurrentTimeChar = "00002a2b-0000-1000-8000-00805f9b34fb" CurrentTimeChar = "00002a2b-0000-1000-8000-00805f9b34fb"
LocalTimeChar = "00002a0f-0000-1000-8000-00805f9b34fb"
BatteryLvlChar = "00002a19-0000-1000-8000-00805f9b34fb" BatteryLvlChar = "00002a19-0000-1000-8000-00805f9b34fb"
HeartRateChar = "00002a37-0000-1000-8000-00805f9b34fb" HeartRateChar = "00002a37-0000-1000-8000-00805f9b34fb"
FSTransferChar = "adaf0200-4669-6c65-5472-616e73666572" FSTransferChar = "adaf0200-4669-6c65-5472-616e73666572"
@ -48,7 +47,6 @@ var charNames = map[string]string{
MotionValChar: "Motion Values", MotionValChar: "Motion Values",
FirmwareVerChar: "Firmware Version", FirmwareVerChar: "Firmware Version",
CurrentTimeChar: "Current Time", CurrentTimeChar: "Current Time",
LocalTimeChar: "Local Time",
BatteryLvlChar: "Battery Level", BatteryLvlChar: "Battery Level",
HeartRateChar: "Heart Rate", HeartRateChar: "Heart Rate",
FSTransferChar: "Filesystem Transfer", FSTransferChar: "Filesystem Transfer",
@ -68,7 +66,6 @@ type Device struct {
motionValChar *gatt.GattCharacteristic1 motionValChar *gatt.GattCharacteristic1
fwVersionChar *gatt.GattCharacteristic1 fwVersionChar *gatt.GattCharacteristic1
currentTimeChar *gatt.GattCharacteristic1 currentTimeChar *gatt.GattCharacteristic1
localTimeChar *gatt.GattCharacteristic1
battLevelChar *gatt.GattCharacteristic1 battLevelChar *gatt.GattCharacteristic1
heartRateChar *gatt.GattCharacteristic1 heartRateChar *gatt.GattCharacteristic1
fsVersionChar *gatt.GattCharacteristic1 fsVersionChar *gatt.GattCharacteristic1
@ -104,14 +101,15 @@ type Options struct {
Whitelist []string Whitelist []string
OnReqPasskey func() (uint32, error) OnReqPasskey func() (uint32, error)
OnReconnect func() OnReconnect func()
Logger logger.Logger Logger zerolog.Logger
LogLevel logger.LogLevel LogLevel zerolog.Level
} }
var DefaultOptions = &Options{ var DefaultOptions = &Options{
AttemptReconnect: true, AttemptReconnect: true,
WhitelistEnabled: false, WhitelistEnabled: false,
Logger: logger.NewNop(), Logger: zerolog.Nop(),
LogLevel: zerolog.Disabled,
} }
// Connect will attempt to connect to a // Connect will attempt to connect to a
@ -125,8 +123,7 @@ func Connect(ctx context.Context, opts *Options) (*Device, error) {
opts = DefaultOptions opts = DefaultOptions
} }
log = opts.Logger log = opts.Logger.Level(opts.LogLevel)
opts.Logger.SetLevel(opts.LogLevel)
// Set passkey request callback // Set passkey request callback
setOnPasskeyReq(opts.OnReqPasskey) setOnPasskeyReq(opts.OnReqPasskey)
@ -168,25 +165,25 @@ func connect(ctx context.Context, opts *Options, first bool) (dev *device.Device
// device, skip // device, skip
if opts.WhitelistEnabled && if opts.WhitelistEnabled &&
!contains(opts.Whitelist, listDev.Properties.Address) { !contains(opts.Whitelist, listDev.Properties.Address) {
log.Debug("InfiniTime device skipped as it is not in whitelist"). log.Debug().
Str("mac", listDev.Properties.Address). Str("mac", listDev.Properties.Address).
Send() Msg("InfiniTime device skipped as it is not in whitelist")
continue continue
} }
// Set device // Set device
dev = listDev dev = listDev
log.Debug("InfiniTime device found in list"). log.Debug().
Str("mac", dev.Properties.Address). Str("mac", dev.Properties.Address).
Send() Msg("InfiniTime device found in list")
break break
} }
// If device not set // If device not set
if dev == nil { 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 // Discover devices on adapter
discoverCh, cancel, err := bt.Discover(defaultAdapter, &adapter.DiscoveryFilter{Transport: "le"}) discoverCh, cancel, err := bt.Discover(defaultAdapter, &adapter.DiscoveryFilter{Transport: "le"})
if err != nil { if err != nil {
@ -216,18 +213,18 @@ func connect(ctx context.Context, opts *Options, first bool) (dev *device.Device
// device, skip // device, skip
if opts.WhitelistEnabled && if opts.WhitelistEnabled &&
!contains(opts.Whitelist, discovered.Properties.Address) { !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). Str("mac", discovered.Properties.Address).
Send() Msg("Discovered InfiniTime device skipped as it is not in whitelist")
continue continue
} }
// Set device // Set device
dev = discovered dev = discovered
log.Debug("InfiniTime device discovered"). log.Debug().
Str("mac", dev.Properties.Address). Str("mac", dev.Properties.Address).
Send() Msg("InfiniTime device discovered")
break discoverLoop break discoverLoop
case <-ctx.Done(): case <-ctx.Done():
break discoverLoop break discoverLoop
@ -249,7 +246,7 @@ func connect(ctx context.Context, opts *Options, first bool) (dev *device.Device
reconnRequired := false reconnRequired := false
// If device is not connected // If device is not connected
if !dev.Properties.Connected { if !dev.Properties.Connected {
log.Debug("Device not connected, connecting").Send() log.Debug().Msg("Device not connected, connecting")
// Connect to device // Connect to device
err = dev.Connect() err = dev.Connect()
if err != nil { if err != nil {
@ -261,7 +258,7 @@ func connect(ctx context.Context, opts *Options, first bool) (dev *device.Device
// If device is not paired // If device is not paired
if !dev.Properties.Paired { if !dev.Properties.Paired {
log.Debug("Device not paired, pairing").Send() log.Debug().Msg("Device not paired, pairing")
// Pair device // Pair device
err = dev.Pair() err = dev.Pair()
if err != nil { if err != nil {
@ -279,7 +276,7 @@ func connect(ctx context.Context, opts *Options, first bool) (dev *device.Device
// was required, and the OnReconnect callback exists, // was required, and the OnReconnect callback exists,
// run it // run it
if !first && reconnRequired && opts.OnReconnect != nil { 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() opts.OnReconnect()
} }
@ -312,7 +309,7 @@ func reconnect(ctx context.Context, opts *Options, dev *device.Device1) {
// If less than 3 seconds have passed and more than 6 // If less than 3 seconds have passed and more than 6
// disconnects have occurred, remove the device and reset // disconnects have occurred, remove the device and reset
if secsSince <= 3 && amtDisconnects >= 6 { 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) lastDisconnect = time.Unix(0, 0)
amtDisconnects = 0 amtDisconnects = 0
} }
@ -324,7 +321,7 @@ func reconnect(ctx context.Context, opts *Options, dev *device.Device1) {
for i := 0; i < 6; i++ { for i := 0; i < 6; i++ {
// If three tries failed, remove device // If three tries failed, remove device
if i == 3 { 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 // Connect to device
newDev, err := connect(ctx, opts, false) newDev, err := connect(ctx, opts, false)
@ -424,8 +421,6 @@ func (i *Device) resolveChars() error {
i.fwVersionChar = char i.fwVersionChar = char
case CurrentTimeChar: case CurrentTimeChar:
i.currentTimeChar = char i.currentTimeChar = char
case LocalTimeChar:
i.localTimeChar = char
case BatteryLvlChar: case BatteryLvlChar:
i.battLevelChar = char i.battLevelChar = char
case HeartRateChar: case HeartRateChar:
@ -454,10 +449,10 @@ func (i *Device) resolveChars() error {
charResolved = false charResolved = false
} }
if charResolved { if charResolved {
log.Debug("Resolved characteristic"). log.Debug().
Str("uuid", char.Properties.UUID). Str("uuid", char.Properties.UUID).
Str("name", charNames[char.Properties.UUID]). Str("name", charNames[char.Properties.UUID]).
Send() Msg("Resolved characteristic")
} }
} }
return nil return nil
@ -559,7 +554,7 @@ func (i *Device) WatchHeartRate(ctx context.Context) (<-chan uint8, error) {
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():
log.Debug("Received done signal").Str("func", "WatchMotion").Send() log.Debug().Str("func", "WatchMotion").Msg("Received done signal")
close(out) close(out)
i.heartRateChar.StopNotify() i.heartRateChar.StopNotify()
return return
@ -569,7 +564,7 @@ func (i *Device) WatchHeartRate(ctx context.Context) (<-chan uint8, error) {
// Send heart rate to channel // Send heart rate to channel
out <- uint8(event.Value.([]byte)[1]) out <- uint8(event.Value.([]byte)[1])
} else if event.Name == "Notifying" && !event.Value.(bool) { } 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() i.heartRateChar.StartNotify()
} }
} }
@ -603,7 +598,7 @@ func (i *Device) WatchBatteryLevel(ctx context.Context) (<-chan uint8, error) {
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():
log.Debug("Received done signal").Str("func", "WatchMotion").Send() log.Debug().Str("func", "WatchMotion").Msg("Received done signal")
close(out) close(out)
i.battLevelChar.StopNotify() i.battLevelChar.StopNotify()
return return
@ -613,7 +608,7 @@ func (i *Device) WatchBatteryLevel(ctx context.Context) (<-chan uint8, error) {
// Send heart rate to channel // Send heart rate to channel
out <- uint8(event.Value.([]byte)[0]) out <- uint8(event.Value.([]byte)[0])
} else if event.Name == "Notifying" && !event.Value.(bool) { } 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() i.battLevelChar.StartNotify()
} }
} }
@ -647,7 +642,7 @@ func (i *Device) WatchStepCount(ctx context.Context) (<-chan uint32, error) {
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():
log.Debug("Received done signal").Str("func", "WatchMotion").Send() log.Debug().Str("func", "WatchMotion").Msg("Received done signal")
close(out) close(out)
i.stepCountChar.StopNotify() i.stepCountChar.StopNotify()
return return
@ -657,7 +652,7 @@ func (i *Device) WatchStepCount(ctx context.Context) (<-chan uint32, error) {
// Send step count to channel // Send step count to channel
out <- binary.LittleEndian.Uint32(event.Value.([]byte)) out <- binary.LittleEndian.Uint32(event.Value.([]byte))
} else if event.Name == "Notifying" && !event.Value.(bool) { } 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() i.stepCountChar.StartNotify()
} }
} }
@ -691,7 +686,7 @@ func (i *Device) WatchMotion(ctx context.Context) (<-chan MotionValues, error) {
for { for {
select { select {
case <-ctx.Done(): case <-ctx.Done():
log.Debug("Received done signal").Str("func", "WatchMotion").Send() log.Debug().Str("func", "WatchMotion").Msg("Received done signal")
close(out) close(out)
i.motionValChar.StopNotify() i.motionValChar.StopNotify()
return return
@ -703,7 +698,7 @@ func (i *Device) WatchMotion(ctx context.Context) (<-chan MotionValues, error) {
// Send step count to channel // Send step count to channel
out <- motionVals out <- motionVals
} else if event.Name == "Notifying" && !event.Value.(bool) { } 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() i.motionValChar.StartNotify()
} }
} }
@ -713,9 +708,7 @@ func (i *Device) WatchMotion(ctx context.Context) (<-chan MotionValues, error) {
return out, nil return out, nil
} }
// SetTime sets the watch's // SetTime sets the watch's time using the Current Time Service
// * time using the Current Time Service's current time characteristic
// * timezone information using the CTS's local time characteristic
func (i *Device) SetTime(t time.Time) error { func (i *Device) SetTime(t time.Time) error {
if err := i.checkStatus(i.currentTimeChar, CurrentTimeChar); err != nil { if err := i.checkStatus(i.currentTimeChar, CurrentTimeChar); err != nil {
return err return err
@ -730,38 +723,7 @@ func (i *Device) SetTime(t time.Time) error {
binary.Write(buf, binary.LittleEndian, uint8(t.Weekday())) 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((t.Nanosecond()/1000)/1e6*256))
binary.Write(buf, binary.LittleEndian, uint8(0b0001)) binary.Write(buf, binary.LittleEndian, uint8(0b0001))
if err := i.currentTimeChar.WriteValue(buf.Bytes(), nil); err != nil { return i.currentTimeChar.WriteValue(buf.Bytes(), 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)
} }
// Notify sends a notification to InfiniTime via // Notify sends a notification to InfiniTime via
@ -866,13 +828,13 @@ func (i *Device) AddWeatherEvent(event interface{}) error {
return err 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 // Write data to weather data characteristic
return i.weatherDataChar.WriteValue(data, nil) return i.weatherDataChar.WriteValue(data, nil)
} }
func (i *Device) checkStatus(char *gatt.GattCharacteristic1, uuid string) error { 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() connected, err := i.device.GetConnected()
if err != nil { if err != nil {
return err return err
@ -881,12 +843,12 @@ func (i *Device) checkStatus(char *gatt.GattCharacteristic1, uuid string) error
return ErrNotConnected return ErrNotConnected
} }
if char == nil { if char == nil {
log.Debug("Characteristic not available (nil)").Send() log.Debug().Msg("Characteristic not available (nil)")
return ErrCharNotAvail{uuid} return ErrCharNotAvail{uuid}
} }
log.Debug("Characteristic available"). log.Debug().
Str("uuid", char.Properties.UUID). Str("uuid", char.Properties.UUID).
Str("name", charNames[char.Properties.UUID]). Str("name", charNames[char.Properties.UUID]).
Send() Msg("Characteristic available")
return nil 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 { for event := range ch {
// If value changes // If value changes
if event.Name == "Value" { 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 // Send music event to channel
musicEventCh <- MusicEvent(event.Value.([]byte)[0]) musicEventCh <- MusicEvent(event.Value.([]byte)[0])
} }

View File

@ -2,7 +2,6 @@ package infinitime
import ( import (
"errors" "errors"
"github.com/muka/go-bluetooth/bluez/profile/gatt" "github.com/muka/go-bluetooth/bluez/profile/gatt"
) )
@ -120,7 +119,7 @@ const (
) )
func (n *NavigationService) SetFlag(flag NavFlag) error { func (n *NavigationService) SetFlag(flag NavFlag) error {
log.Debug("Sending flag").Str("func", "SetFlag").Send() log.Debug().Str("func", "SetFlag").Msg("Sending flag")
if err := n.dev.checkStatus(n.flagsChar, NavFlagsChar); err != nil { if err := n.dev.checkStatus(n.flagsChar, NavFlagsChar); err != nil {
return err return err
} }
@ -128,7 +127,7 @@ func (n *NavigationService) SetFlag(flag NavFlag) error {
} }
func (n *NavigationService) SetNarrative(narrative string) error { func (n *NavigationService) SetNarrative(narrative string) error {
log.Debug("Sending narrative").Str("func", "SetNarrative").Send() log.Debug().Str("func", "SetNarrative").Msg("Sending narrative")
if err := n.dev.checkStatus(n.narrativeChar, NavNarrativeChar); err != nil { if err := n.dev.checkStatus(n.narrativeChar, NavNarrativeChar); err != nil {
return err return err
} }
@ -136,7 +135,7 @@ func (n *NavigationService) SetNarrative(narrative string) error {
} }
func (n *NavigationService) SetManDist(manDist string) error { func (n *NavigationService) SetManDist(manDist string) error {
log.Debug("Sending maneuver distance").Str("func", "SetNarrative").Send() log.Debug().Str("func", "SetNarrative").Msg("Sending maneuver distance")
if err := n.dev.checkStatus(n.mandistChar, NavManDistChar); err != nil { if err := n.dev.checkStatus(n.mandistChar, NavManDistChar); err != nil {
return err return err
} }
@ -144,7 +143,7 @@ func (n *NavigationService) SetManDist(manDist string) error {
} }
func (n *NavigationService) SetProgress(progress uint8) error { func (n *NavigationService) SetProgress(progress uint8) error {
log.Debug("Sending progress").Str("func", "SetNarrative").Send() log.Debug().Str("func", "SetNarrative").Msg("Sending progress")
if err := n.dev.checkStatus(n.progressChar, NavProgressChar); err != nil { if err := n.dev.checkStatus(n.progressChar, NavProgressChar); err != nil {
return err return err
} }

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

@ -0,0 +1,271 @@
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
}
func VolUp(percent uint) error {
player, err := getPlayerObj()
if err != nil {
return err
}
if player != nil {
currentVal, err := player.GetProperty("org.mpris.MediaPlayer2.Player.Volume")
if err != nil {
return err
}
newVal := currentVal.Value().(float64) + (float64(percent) / 100)
err = player.SetProperty("org.mpris.MediaPlayer2.Player.Volume", newVal)
if err != nil {
return err
}
}
return nil
}
func VolDown(percent uint) error {
player, err := getPlayerObj()
if err != nil {
return err
}
if player != nil {
currentVal, err := player.GetProperty("org.mpris.MediaPlayer2.Player.Volume")
if err != nil {
return err
}
newVal := currentVal.Value().(float64) - (float64(percent) / 100)
err = player.SetProperty("org.mpris.MediaPlayer2.Player.Volume", newVal)
if err != nil {
return 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" "os"
"path/filepath" "path/filepath"
"go.elara.ws/infinitime/blefs" "go.arsenm.dev/infinitime/blefs"
) )
// ResourceOperation represents an operation performed during // ResourceOperation represents an operation performed during
@ -80,7 +80,7 @@ func LoadResources(file *os.File, fs *blefs.FS) (<-chan ResourceLoadProgress, er
m.Close() m.Close()
log.Debug("Decoded manifest file").Send() log.Debug().Msg("Decoded manifest file")
go func() { go func() {
defer close(out) defer close(out)
@ -88,7 +88,7 @@ func LoadResources(file *os.File, fs *blefs.FS) (<-chan ResourceLoadProgress, er
for _, file := range manifest.Obsolete { for _, file := range manifest.Obsolete {
name := filepath.Base(file.Path) 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) err := fs.RemoveAll(file.Path)
if err != nil { if err != nil {
@ -100,7 +100,7 @@ func LoadResources(file *os.File, fs *blefs.FS) (<-chan ResourceLoadProgress, er
return return
} }
log.Debug("Removed file").Str("file", file.Path).Send() log.Debug().Str("file", file.Path).Msg("Removed file")
out <- ResourceLoadProgress{ out <- ResourceLoadProgress{
Name: name, Name: name,
@ -131,11 +131,11 @@ func LoadResources(file *os.File, fs *blefs.FS) (<-chan ResourceLoadProgress, er
return 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)) err = fs.MkdirAll(filepath.Dir(file.Path))
if err != nil { if err != nil {
log.Debug("Error making directories").Err(err).Send() log.Debug().Err(err).Msg("Error making directories")
out <- ResourceLoadProgress{ out <- ResourceLoadProgress{
Name: file.Name, Name: file.Name,
Operation: ResourceOperationUpload, Operation: ResourceOperationUpload,
@ -146,14 +146,14 @@ func LoadResources(file *os.File, fs *blefs.FS) (<-chan ResourceLoadProgress, er
return return
} }
log.Debug("Creating file"). log.Debug().
Str("file", file.Path). Str("file", file.Path).
Int64("size", srcFi.Size()). Int64("size", srcFi.Size()).
Send() Msg("Creating file")
dst, err := fs.Create(file.Path, uint32(srcFi.Size())) dst, err := fs.Create(file.Path, uint32(srcFi.Size()))
if err != nil { if err != nil {
log.Debug("Error creating file").Err(err).Send() log.Debug().Err(err).Msg("Error creating file")
out <- ResourceLoadProgress{ out <- ResourceLoadProgress{
Name: file.Name, Name: file.Name,
Operation: ResourceOperationUpload, Operation: ResourceOperationUpload,
@ -167,10 +167,10 @@ func LoadResources(file *os.File, fs *blefs.FS) (<-chan ResourceLoadProgress, er
progCh := dst.Progress() progCh := dst.Progress()
go func() { go func() {
for sent := range progCh { for sent := range progCh {
log.Debug("Progress event sent"). log.Debug().
Int64("total", srcFi.Size()). Int64("total", srcFi.Size()).
Uint32("sent", sent). Uint32("sent", sent).
Send() Msg("Progress event sent")
out <- ResourceLoadProgress{ out <- ResourceLoadProgress{
Name: file.Name, Name: file.Name,
@ -187,7 +187,7 @@ func LoadResources(file *os.File, fs *blefs.FS) (<-chan ResourceLoadProgress, er
n, err := io.Copy(dst, src) n, err := io.Copy(dst, src)
if err != nil { if err != nil {
log.Debug("Error writing to file").Err(err).Send() log.Debug().Err(err).Msg("Error writing to file")
out <- ResourceLoadProgress{ out <- ResourceLoadProgress{
Name: file.Name, Name: file.Name,
Operation: ResourceOperationUpload, Operation: ResourceOperationUpload,

View File

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