From 87b90f8015773423e94b10c2c581488da8f05d26 Mon Sep 17 00:00:00 2001 From: lucarin91 Date: Sat, 13 Jan 2024 14:55:03 +0100 Subject: [PATCH] initial commit --- .gitignore | 2 + .golangci.yml | 16 ++++ Makefile | 13 +++ README.md | 15 ++++ go.mod | 23 +++++ go.sum | 87 ++++++++++++++++++ jsonrpc/jsonrpc.go | 145 ++++++++++++++++++++++++++++++ main.go | 51 +++++++++++ scratchlink/ble.go | 92 +++++++++++++++++++ scratchlink/handler.go | 198 +++++++++++++++++++++++++++++++++++++++++ scratchlink/types.go | 101 +++++++++++++++++++++ 11 files changed, 743 insertions(+) create mode 100644 .gitignore create mode 100644 .golangci.yml create mode 100644 Makefile create mode 100644 README.md create mode 100644 go.mod create mode 100644 go.sum create mode 100644 jsonrpc/jsonrpc.go create mode 100644 main.go create mode 100644 scratchlink/ble.go create mode 100644 scratchlink/handler.go create mode 100644 scratchlink/types.go diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6a04849 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +.bin/ +./scratch-link4linux \ No newline at end of file diff --git a/.golangci.yml b/.golangci.yml new file mode 100644 index 0000000..f5dd5e2 --- /dev/null +++ b/.golangci.yml @@ -0,0 +1,16 @@ +linters: + disable-all: true + # Enable specific linter + # https://golangci-lint.run/usage/linters/#enabled-by-default + enable: + - gofmt + - gosec + - govet + - goimports + - misspell + - unconvert + - unparam + - goconst + - gocritic + - gochecknoinits + - gochecknoinits diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..9b2b76c --- /dev/null +++ b/Makefile @@ -0,0 +1,13 @@ + +init: + go install golang.org/x/tools/cmd/goimports@v0.17.0 + curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh | sh -s -- -b ./bin v1.55.2 + +fmt: + goimports -w . + +test: + go test -v ./... + +lint: + ./bin/golangci-lint run ./... diff --git a/README.md b/README.md new file mode 100644 index 0000000..c35a626 --- /dev/null +++ b/README.md @@ -0,0 +1,15 @@ +# Scratch-link for Linux + +>**Note:** This repositiory is in early stage and not all features are yet implemented. + +This project is a linux implementation of the [Scratch Link](https://github.com/scratchfoundation/scratch-link). + +## How to run + +Make sure [golang](https://go.dev/doc/install) is installed in you machine. + +Open a terminal navigate to the project directory, then run the following command: + +```bash +go run . +``` diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..8b27e22 --- /dev/null +++ b/go.mod @@ -0,0 +1,23 @@ +module github.com/lucarin91/scratch-link4linux + +go 1.21.0 + +require ( + github.com/google/uuid v1.5.0 + github.com/rs/zerolog v1.31.0 + golang.org/x/net v0.20.0 + tinygo.org/x/bluetooth v0.8.0 +) + +require ( + github.com/fatih/structs v1.1.0 // indirect + github.com/go-ole/go-ole v1.2.6 // indirect + github.com/godbus/dbus/v5 v5.1.0 // indirect + github.com/mattn/go-colorable v0.1.13 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/muka/go-bluetooth v0.0.0-20221213043340-85dc80edc4e1 // indirect + github.com/saltosystems/winrt-go v0.0.0-20230921082907-2ab5b7d431e1 // indirect + github.com/sirupsen/logrus v1.9.3 // indirect + github.com/tinygo-org/cbgo v0.0.4 // indirect + golang.org/x/sys v0.16.0 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..06649d7 --- /dev/null +++ b/go.sum @@ -0,0 +1,87 @@ +github.com/coreos/go-systemd/v22 v22.5.0/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= +github.com/fatih/structs v1.1.0 h1:Q7juDM0QtcnhCpeyLGQKyg4TOIghuNXrkL32pHAUMxo= +github.com/fatih/structs v1.1.0/go.mod h1:9NiDSp5zOcgEDl+j00MP/WkGVPOlPRLejGD8Ga6PJ7M= +github.com/go-ole/go-ole v1.2.6 h1:/Fpf6oFPoeFik9ty7siob0G6Ke8QvQEuVcuChpwXzpY= +github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= +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.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk= +github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA= +github.com/google/uuid v1.1.1/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU= +github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/konsorten/go-windows-terminal-sequences v1.0.1/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/text v0.1.0/go.mod h1:4Jbv+DJW3UT/LiOwJeYQe1efqtUx/iVham/4vfdArNI= +github.com/mattn/go-colorable v0.1.13 h1:fFA4WZxdEF4tXPZVKMLwD8oUnCTTo08duU7wxecdEvA= +github.com/mattn/go-colorable v0.1.13/go.mod h1:7S9/ev0klgBDR4GtXTXX8a3vIGJpMovkB8vQcUbaXHg= +github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/muka/go-bluetooth v0.0.0-20221213043340-85dc80edc4e1 h1:BuVRHr4HHJbk1DHyWkArJ7E8J/VA8ncCr/VLnQFazBo= +github.com/muka/go-bluetooth v0.0.0-20221213043340-85dc80edc4e1/go.mod h1:dMCjicU6vRBk34dqOmIZm0aod6gUwZXOXzBROqGous0= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= +github.com/paypal/gatt v0.0.0-20151011220935-4ae819d591cf/go.mod h1:+AwQL2mK3Pd3S+TUwg0tYQjid0q1txyNUJuuSmz8Kdk= +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.5.0/go.mod h1:trrq9SKmegXys3aeAKXMUTdJsYXVwGY3RLcfgqegfbg= +github.com/rs/zerolog v1.31.0 h1:FcTR3NnLWW+NnTwwhFWiJSZr4ECLpqCm6QsEnyvbV4A= +github.com/rs/zerolog v1.31.0/go.mod h1:/7mN4D5sKwJLZQ2b/znpjC3/GQWY/xaDXUM0kKWRHss= +github.com/saltosystems/winrt-go v0.0.0-20230921082907-2ab5b7d431e1 h1:L2YoWezgwpAZ2SEKjXk6yLnwOkM3u7mXq/mKuJeEpFM= +github.com/saltosystems/winrt-go v0.0.0-20230921082907-2ab5b7d431e1/go.mod h1:CIltaIm7qaANUIvzr0Vmz71lmQMAIbGJ7cvgzX7FMfA= +github.com/sirupsen/logrus v1.5.0/go.mod h1:+F7Ogzej0PZc/94MaYx/nvG9jOFMD2osvC3s+Squfpo= +github.com/sirupsen/logrus v1.6.0/go.mod h1:7uNnSEd1DgxDLC74fIahvMZmmYsHGZGEOFrfsX/uA88= +github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ= +github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs= +github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.5 h1:s5PTfem8p8EbKQOctVV53k6jCJt3UX4IEJzwh+C324Q= +github.com/stretchr/testify v1.7.5/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/suapapa/go_eddystone v1.3.1/go.mod h1:bXC11TfJOS+3g3q/Uzd7FKd5g62STQEfeEIhcKe4Qy8= +github.com/tinygo-org/cbgo v0.0.4 h1:3D76CRYbH03Rudi8sEgs/YO0x3JIMdyq8jlQtk/44fU= +github.com/tinygo-org/cbgo v0.0.4/go.mod h1:7+HgWIHd4nbAz0ESjGlJ1/v9LDU1Ox8MGzP9mah/fLk= +github.com/yuin/goldmark v1.2.1/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74= +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/mod v0.3.0/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.20.0 h1:aCL9BSgETF1k+blQaYUBx9hJ9LOGP3gAVemcZlf1Kpo= +golang.org/x/net v0.20.0/go.mod h1:z8BVo6PvndSri0LbOE3hAn0apkU+1YvI6E70E9jsnvY= +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/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-20190916202348-b4ddaad3f8a3/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-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.16.0 h1:xWw16ngr6ZMtmxDyKyIgsE93KNKz5HKmMa3b8ALHidU= +golang.org/x/sys v0.16.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +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/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/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= +tinygo.org/x/bluetooth v0.8.0 h1:WmuRebsODcUUIlGhesyuNRIAEIUCErhKlrZ9K9aimdI= +tinygo.org/x/bluetooth v0.8.0/go.mod h1:cfsVc0/nGo3nzi6+CeQaXb+anNlmEnSABkKsxer8OAE= diff --git a/jsonrpc/jsonrpc.go b/jsonrpc/jsonrpc.go new file mode 100644 index 0000000..950ccdc --- /dev/null +++ b/jsonrpc/jsonrpc.go @@ -0,0 +1,145 @@ +/* +Simple implementation of JSONRPC 2.0. +*/ +package jsonrpc + +import ( + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "sync/atomic" + + "github.com/rs/zerolog/log" + "golang.org/x/net/websocket" +) + +var MsgID int64 = 0 + +type Msg struct { + ID int64 `json:"id"` + Jsonrpc string `json:"jsonrpc"` + Method string `json:"method"` + Params json.RawMessage `json:"params"` +} + +type Result struct { + ID int64 `json:"id"` + Jsonrpc string `json:"jsonrpc"` + Result interface{} `json:"result"` + Encoding string `json:"encoding,omitempty"` +} + +type Error struct { + ID int64 `json:"id"` + Jsonrpc string `json:"jsonrpc"` + Error string `json:"error"` +} + +func NewMsg(method string, params interface{}) Msg { + buff, err := json.Marshal(params) + if err != nil { + panic(err) + } + return Msg{ + ID: atomic.AddInt64(&MsgID, 1), + Jsonrpc: "2.0", + Method: method, + Params: json.RawMessage(buff), + } +} + +func (m Msg) RespondBytes(buf []byte) Result { + return Result{ + ID: m.ID, + Jsonrpc: "2.0", + Encoding: "base64", + Result: base64.StdEncoding.EncodeToString(buf), + } +} + +func (m Msg) Respond(data interface{}) Result { + return Result{ + ID: m.ID, + Jsonrpc: "2.0", + Result: data, + } +} + +func (m Msg) Error(err string) Error { + return Error{ + ID: m.ID, + Jsonrpc: "2.0", + Error: err, + } +} + +func (m Msg) DebugParams() map[string]interface{} { + var out map[string]interface{} + err := json.Unmarshal(m.Params, &out) + if err != nil { + panic(err) + } + return out +} + +func WsSend[T Msg | Error | Result](c *websocket.Conn, data T) error { + buff, err := json.Marshal(data) + if err != nil { + panic(err) + } + + _, err = c.Write(buff) + if err != nil { + return fmt.Errorf("ws write error: %w", err) + } + + return nil +} + +func WsReadLoop(c *websocket.Conn) <-chan Msg { + out := make(chan Msg, 100) + + go func() { + defer close(out) + for { + msg, err := wsRead(c) + if errors.Is(err, io.EOF) { + break + } + if err != nil { + log.Warn().Err(err).Msg("read loop error, ignore") + return + } + out <- msg + } + }() + + return out +} + +func wsRead(c *websocket.Conn) (Msg, error) { + buff := make([]byte, 512) + var msg Msg + for { + n, err := c.Read(buff) + if err != nil { + return msg, fmt.Errorf("ws read: %w", err) + } + if n >= 512 { + panic("too big") + } + + err = json.Unmarshal(buff[:n], &msg) + if err != nil { + return msg, fmt.Errorf("ws read error: %w", err) + } + if len(msg.Method) == 0 { + // ignore response messages + continue + } + + return msg, nil + } +} diff --git a/main.go b/main.go new file mode 100644 index 0000000..1b0da10 --- /dev/null +++ b/main.go @@ -0,0 +1,51 @@ +package main + +import ( + "flag" + "net/http" + "os" + "time" + + "github.com/rs/zerolog" + "github.com/rs/zerolog/log" + "tinygo.org/x/bluetooth" + + "github.com/lucarin91/scratch-link4linux/scratchlink" +) + +func setLogger(debug bool) { + log.Logger = log.Output(zerolog.ConsoleWriter{Out: os.Stdout}) + zerolog.TimeFieldFormat = zerolog.TimeFormatUnix + + if debug { + zerolog.SetGlobalLevel(zerolog.DebugLevel) + } else { + zerolog.SetGlobalLevel(zerolog.InfoLevel) + } +} + +func main() { + debug := flag.Bool("debug", false, "sets log level to debug") + flag.Parse() + + setLogger(*debug) + + var adapter = bluetooth.DefaultAdapter + if err := adapter.Enable(); err != nil { + log.Fatal().Err(err).Msgf("BLE cannot be enabled") + } + + http.Handle("/scratch/ble", scratchlink.GetHandler(adapter)) + + server := &http.Server{ + Addr: ":20111", + ReadHeaderTimeout: 3 * time.Second, + } + + log.Info().Msgf("Starting scratch server on %q", server.Addr) + + err := server.ListenAndServe() + if err != nil { + log.Fatal().Err(err).Msg("server stopped") + } +} diff --git a/scratchlink/ble.go b/scratchlink/ble.go new file mode 100644 index 0000000..ec49a06 --- /dev/null +++ b/scratchlink/ble.go @@ -0,0 +1,92 @@ +package scratchlink + +import ( + "encoding/base64" + + "github.com/google/uuid" + "github.com/rs/zerolog/log" + "golang.org/x/net/websocket" + "tinygo.org/x/bluetooth" + + "github.com/lucarin91/scratch-link4linux/jsonrpc" +) + +func matchDevice(device bluetooth.ScanResult, filters []DiscoverFilter) bool { + //TODO: implement match device + + for _, filter := range filters { + if len(filter.Name) != 0 && filter.Name != device.LocalName() { + return false + } + + for _, service := range filter.Services { + if !device.HasServiceUUID(bluetooth.NewUUID(service)) { + return false + } + } + } + return true +} + +func getDeviceCharacteristic(device bluetooth.Device, serviceID, characteristicID bluetooth.UUID) (bluetooth.DeviceCharacteristic, error) { + services, err := device.DiscoverServices([]bluetooth.UUID{serviceID}) + if err != nil { + return bluetooth.DeviceCharacteristic{}, err + } + + chars, err := services[0].DiscoverCharacteristics([]bluetooth.UUID{characteristicID}) + if err != nil { + return bluetooth.DeviceCharacteristic{}, err + } + + return chars[0], nil +} + +func notificationCallback(c *websocket.Conn, serviceID, characteristicID uuid.UUID) func(buf []byte) { + return func(buf []byte) { + _ = jsonrpc.WsSend(c, jsonrpc.NewMsg("characteristicDidChange", UpdateParams{ + ServiceID: serviceID, + CharacteristicID: characteristicID, + Message: base64.StdEncoding.EncodeToString(buf), + Encoding: "base64", + })) + } +} + +func startAsyncScan(adapter *bluetooth.Adapter, filter []DiscoverFilter) <-chan Device { + // Stop previus scan (if any). + _ = adapter.StopScan() + + devices := make(chan Device, 10) + + go func() { + defer close(devices) + + err := adapter.Scan(func(adapter *bluetooth.Adapter, device bluetooth.ScanResult) { + if len(device.LocalName()) == 0 { + return + } + + log.Debug(). + Str("name", device.LocalName()). + Str("address", device.Address.String()). + Int16("RSSI", device.RSSI). + Msg("found device") + + if !matchDevice(device, filter) { + return + } + + devices <- Device{ + PeripheralID: device.Address.String(), + Name: device.LocalName(), + RSSI: device.RSSI, + } + }) + if err != nil { + log.Error().Err(err).Msg("scan error") + } + }() + + return devices +} diff --git a/scratchlink/handler.go b/scratchlink/handler.go new file mode 100644 index 0000000..ea81120 --- /dev/null +++ b/scratchlink/handler.go @@ -0,0 +1,198 @@ +package scratchlink + +import ( + "encoding/base64" + + "github.com/lucarin91/scratch-link4linux/jsonrpc" + "github.com/rs/zerolog/log" + "golang.org/x/net/websocket" + "tinygo.org/x/bluetooth" +) + +func GetHandler(adapter *bluetooth.Adapter) websocket.Handler { + return websocket.Handler(func(c *websocket.Conn) { + log.Info().Msgf("client connected from %q", c.RemoteAddr()) + + var DEVICE *bluetooth.Device + + msgs := jsonrpc.WsReadLoop(c) + + for msg := range msgs { + log.Debug().Msgf("get message: %v", msg) + + switch msg.Method { + case "getVersion": + _ = jsonrpc.WsSend(c, msg.Respond(map[string]string{"protocol": "1.3"})) + + case "discover": + params, err := DiscoverParamsFromJSON(msg.Params) + if err != nil { + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + + devices := startAsyncScan(adapter, params.Filters) + go func() { + for device := range devices { + _ = jsonrpc.WsSend(c, jsonrpc.NewMsg("didDiscoverPeripheral", device)) + } + }() + + _ = jsonrpc.WsSend(c, msg.Respond(nil)) + + case "connect": + params, err := ConnectParamsFromJSON(msg.Params) + if err != nil { + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + + _ = adapter.StopScan() + + mac := bluetooth.Address{} + mac.Set(params.PeripheralID) + DEVICE, err = adapter.Connect(mac, bluetooth.ConnectionParams{ + ConnectionTimeout: 0, + MinInterval: 0, + MaxInterval: 0, + }) + if err != nil { + log.Error().Msgf("ble connect error: %s", err) + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + + _ = jsonrpc.WsSend(c, msg.Respond(nil)) + + case "startNotifications": + params, err := NotificationsParamsFromJSON(msg.Params) + if err != nil { + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + log.Debug().Msgf("startNotifications params: %+v", params) + + char, err := getDeviceCharacteristic(*DEVICE, bluetooth.NewUUID(params.ServiceID), bluetooth.NewUUID(params.CharacteristicID)) + if err != nil { + log.Error().Msgf("get device characteristic error: %s", err) + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + + err = char.EnableNotifications(notificationCallback(c, params.CharacteristicID, params.CharacteristicID)) + if err != nil { + log.Error().Msgf("enable notification error: %s", err) + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + + _ = jsonrpc.WsSend(c, msg.Respond(nil)) + + case "write": + params, err := UpdateParamsFromJSON(msg.Params) + if err != nil { + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + log.Debug().Msgf("write params: %+v", params) + + if params.Encoding != "base64" { + log.Error().Msgf("encoding format %q not supported", params.Encoding) + continue + } + + services, err := DEVICE.DiscoverServices([]bluetooth.UUID{bluetooth.NewUUID(params.ServiceID)}) + if err != nil { + log.Error().Msgf("discover service error: %s", err) + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + + chars, err := services[0].DiscoverCharacteristics([]bluetooth.UUID{bluetooth.NewUUID(params.CharacteristicID)}) + if err != nil { + log.Error().Msgf("discovert characteristics error: %s", err) + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + char := chars[0] + + buf, err := base64.StdEncoding.DecodeString(params.Message) + if err != nil { + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + + // TODO: handle params.WithResponse + n, err := char.WriteWithoutResponse(buf) + if err != nil { + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + + _ = jsonrpc.WsSend(c, msg.Respond(n)) + + case "read": + params, err := ReadParamsFromJSON(msg.Params) + if err != nil { + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + log.Debug().Msgf("read params: %+v", params) + + char, err := getDeviceCharacteristic(*DEVICE, bluetooth.NewUUID(params.ServiceID), bluetooth.NewUUID(params.CharacteristicID)) + if err != nil { + log.Error().Msgf("get device characteristic error: %s", err) + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + + if params.StartNotifications { + err = char.EnableNotifications(notificationCallback(c, params.CharacteristicID, params.CharacteristicID)) + if err != nil { + log.Error().Msgf("enable notification error: %s", err) + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + } + + buf := make([]byte, 512) + n, err := char.Read(buf) + if err != nil { + log.Error().Msgf("read characteristic error: %s", err) + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + + _ = jsonrpc.WsSend(c, msg.RespondBytes(buf[:n])) + + case "stopNotifications": + params, err := NotificationsParamsFromJSON(msg.Params) + if err != nil { + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + log.Debug().Msgf("stopNotifications params: %+v", params) + + char, err := getDeviceCharacteristic(*DEVICE, bluetooth.NewUUID(params.ServiceID), bluetooth.NewUUID(params.CharacteristicID)) + if err != nil { + log.Error().Msgf("get device characteristic error: %s", err) + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + + err = char.EnableNotifications(nil) + if err != nil { + _ = jsonrpc.WsSend(c, msg.Error(err.Error())) + continue + } + + _ = jsonrpc.WsSend(c, msg.Respond(nil)) + + default: + log.Error().Msgf("unknown command '%s' with params: %+v", msg.Method, msg.DebugParams()) + } + } + + log.Info().Msgf("client disconnected from %q", c.RemoteAddr()) + }) +} diff --git a/scratchlink/types.go b/scratchlink/types.go new file mode 100644 index 0000000..8a0feba --- /dev/null +++ b/scratchlink/types.go @@ -0,0 +1,101 @@ +package scratchlink + +import ( + "encoding/json" + + "github.com/google/uuid" +) + +type Device struct { + PeripheralID string `json:"peripheralId"` + Name string `json:"name"` + RSSI int16 `json:"rssi"` +} + +type DiscoverParams struct { + Filters []DiscoverFilter `json:"filters"` +} + +func DiscoverParamsFromJSON(j json.RawMessage) (DiscoverParams, error) { + var params DiscoverParams + + err := json.Unmarshal(j, ¶ms) + if err != nil { + return DiscoverParams{}, err + } + + return params, nil +} + +type DiscoverFilter struct { + Name string `json:"name"` + NamePrefix string `json:"namePrefix"` + Services []uuid.UUID `json:"services"` +} + +type ConnectParams struct { + PeripheralID string `json:"peripheralId"` +} + +func ConnectParamsFromJSON(j json.RawMessage) (ConnectParams, error) { + var params ConnectParams + + err := json.Unmarshal(j, ¶ms) + if err != nil { + return ConnectParams{}, err + } + + return params, nil +} + +type NotificationsParams struct { + ServiceID uuid.UUID `json:"serviceId"` + CharacteristicID uuid.UUID `json:"characteristicId"` +} + +func NotificationsParamsFromJSON(j json.RawMessage) (NotificationsParams, error) { + var params NotificationsParams + + err := json.Unmarshal(j, ¶ms) + if err != nil { + return NotificationsParams{}, err + } + + return params, nil +} + +type UpdateParams struct { + ServiceID uuid.UUID `json:"serviceId"` + CharacteristicID uuid.UUID `json:"characteristicId"` + Message string `json:"message"` + Encoding string `json:"encoding,omitempty"` + WithResponse bool `json:"withResponse"` +} + +func UpdateParamsFromJSON(j json.RawMessage) (UpdateParams, error) { + var params UpdateParams + + err := json.Unmarshal(j, ¶ms) + if err != nil { + return UpdateParams{}, err + } + + return params, nil +} + +type ReadParams struct { + ServiceID uuid.UUID `json:"serviceId"` + CharacteristicID uuid.UUID `json:"characteristicId"` + StartNotifications bool `json:"startNotifications"` +} + +func ReadParamsFromJSON(j json.RawMessage) (ReadParams, error) { + var params ReadParams + + err := json.Unmarshal(j, ¶ms) + if err != nil { + return ReadParams{}, err + } + + return params, nil +}