Use go modules instead of third party dependency tool

We have go modules now built in. Let's use it!
This commit is contained in:
Stefan Tatschner 2019-06-30 22:11:23 +02:00
parent 4a96bf641a
commit fe7e103387
1325 changed files with 167 additions and 433316 deletions

400
Gopkg.lock generated
View file

@ -1,400 +0,0 @@
# This file is autogenerated, do not edit; changes may be undone by the next 'dep ensure'.
[[projects]]
digest = "1:4132a4623657c2ba93a7cf83dccc6869b3e3bb91dc2afefa7c7032e10ceeaa12"
name = "github.com/adrianmo/go-nmea"
packages = ["."]
pruneopts = "UT"
revision = "a32116e4989e2b0e17c057ee378b4d5246add74e"
version = "v1.1.0"
[[projects]]
branch = "master"
digest = "1:1d692605b66a4fbe2a3de27131619e8e2c88ccf142ee43a7a8c902339942e0cc"
name = "github.com/antchfx/jsonquery"
packages = ["."]
pruneopts = "UT"
revision = "a2896be8c82bb2229d1cf26204863180e34b2b31"
[[projects]]
branch = "master"
digest = "1:3a4202162c0d85f2a5fed5675bd35e6686c8b379c63e40ef105bf3e7d76d97f5"
name = "github.com/antchfx/xpath"
packages = ["."]
pruneopts = "UT"
revision = "ce1d48779e67a1ddfb380995fe532b2e0015919c"
[[projects]]
branch = "master"
digest = "1:67f303802ce14d56880d9f2142adc00511441f0fcf7b7fd4ad5856e234963f15"
name = "github.com/bettercap/gatt"
packages = [
".",
"linux",
"linux/cmd",
"linux/evt",
"linux/gioctl",
"linux/socket",
"linux/util",
"xpc",
]
pruneopts = "UT"
revision = "fac16c0ad797bbccae1fe4acf49761b98f7516e7"
[[projects]]
branch = "master"
digest = "1:c93fdd8820c13c2e2000d3064c510dde1397edca5ca1533fd15943402dab92b0"
name = "github.com/bettercap/nrf24"
packages = ["."]
pruneopts = "UT"
revision = "aa37e6d0e0eb125cee9ec71ed694db2ad58b509a"
[[projects]]
digest = "1:b95738a1e6ace058b5b8544303c0871fc01d224ef0d672f778f696265d0f2917"
name = "github.com/bettercap/readline"
packages = ["."]
pruneopts = "UT"
revision = "62c6fe6193755f722b8b8788aa7357be55a50ff1"
version = "v1.4"
[[projects]]
digest = "1:6b01d6818554363a129a2504033feacdfd8b9ddba998831fa57781eb90e60f32"
name = "github.com/bettercap/recording"
packages = ["."]
pruneopts = "UT"
revision = "3ce1dcf032e391eb321311b34cdf31c6fc9523f5"
[[projects]]
branch = "master"
digest = "1:8efd09ca363b01b7dca5baf091d65473df5f08f107b7c3fcd93c605189e031ed"
name = "github.com/chifflier/nfqueue-go"
packages = ["nfqueue"]
pruneopts = "UT"
revision = "61ca646babef3bd4dea1deb610bfb0005c0a1298"
[[projects]]
branch = "master"
digest = "1:6f9339c912bbdda81302633ad7e99a28dfa5a639c864061f1929510a9a64aa74"
name = "github.com/dustin/go-humanize"
packages = ["."]
pruneopts = "UT"
revision = "9f541cc9db5d55bce703bd99987c9d5cb8eea45e"
[[projects]]
branch = "master"
digest = "1:d754d24358cf013301a804cdab95cbcbe0da83902dc24ee20e98a899c4dd48e0"
name = "github.com/elazarl/goproxy"
packages = ["."]
pruneopts = "UT"
revision = "9d40249d3c2f14d1a9d75e070a738362adeb5a83"
[[projects]]
digest = "1:a6346055dbca49d489f048f55c6efb0451642c8f94e649160b50e571ac6ce738"
name = "github.com/evilsocket/islazy"
packages = [
"async",
"data",
"fs",
"log",
"ops",
"plugin",
"str",
"tui",
"zip",
]
pruneopts = "UT"
revision = "c5c7a41bb1c20e6df409825ed24af8de5fb7fb70"
version = "v1.10.4"
[[projects]]
branch = "master"
digest = "1:e5e45557e1871c967a6ccaa5b95d1233a2c01ab00615621825d1aca7383dc022"
name = "github.com/gobwas/glob"
packages = [
".",
"compiler",
"match",
"syntax",
"syntax/ast",
"syntax/lexer",
"util/runes",
"util/strings",
]
pruneopts = "UT"
revision = "e7a84e9525fe90abcda167b604e483cc959ad4aa"
[[projects]]
digest = "1:51bee9f1987dcdb9f9a1b4c20745d78f6bf6f5f14ad4e64ca883eb64df4c0045"
name = "github.com/google/go-github"
packages = ["github"]
pruneopts = "UT"
revision = "e48060a28fac52d0f1cb758bc8b87c07bac4a87d"
version = "v15.0.0"
[[projects]]
digest = "1:a63cff6b5d8b95638bfe300385d93b2a6d9d687734b863da8e09dc834510a690"
name = "github.com/google/go-querystring"
packages = ["query"]
pruneopts = "UT"
revision = "44c6ddd0a2342c386950e880b658017258da92fc"
version = "v1.0.0"
[[projects]]
digest = "1:b23296076e13a960263285b98907623e5d45f12fc405b14da19c6afa2a113deb"
name = "github.com/google/gopacket"
packages = [
".",
"layers",
"pcap",
"pcapgo",
]
pruneopts = "UT"
revision = "v1.1.16"
[[projects]]
branch = "master"
digest = "1:2ef895ea08a0af10ad6f1e1faf631c82fa5413dcf0ada93eb62ab5ad02df4979"
name = "github.com/google/gousb"
packages = ["."]
pruneopts = "UT"
revision = "64d82086770b8b671e1e7f162372dd37f1f5efba"
[[projects]]
digest = "1:d5f97fc268267ec1b61c3453058c738246fc3e746f14b1ae25161513b7367b0c"
name = "github.com/gorilla/mux"
packages = ["."]
pruneopts = "UT"
revision = "c5c6c98bc25355028a63748a498942a6398ccd22"
version = "v1.7.1"
[[projects]]
digest = "1:7b5c6e2eeaa9ae5907c391a91c132abfd5c9e8a784a341b5625e750c67e6825d"
name = "github.com/gorilla/websocket"
packages = ["."]
pruneopts = "UT"
revision = "66b9c49e59c6c48f0ffce28c2d8b8a5678502c6d"
version = "v1.4.0"
[[projects]]
digest = "1:89d41e902c8415f538d75e9d3008b286d30fe853ccf32def2dd37b82dd2ade14"
name = "github.com/hashicorp/mdns"
packages = ["."]
pruneopts = "UT"
revision = "06dd1a31b32c42d4d6c2cf8dbce70597d1118f54"
version = "v1.0.1"
[[projects]]
branch = "master"
digest = "1:6480de9b8abc75bfb06947e139aa07429dfed37f95a258e90865c4c84a9e188b"
name = "github.com/inconshreveable/go-vhost"
packages = ["."]
pruneopts = "UT"
revision = "06d84117953b22058c096b49a429ebd4f3d3d97b"
[[projects]]
branch = "master"
digest = "1:45da610fe81bb89b25555d0111fa338dcdbf2346afdb2b7296c8c49e554a9d32"
name = "github.com/jpillora/go-tld"
packages = ["."]
pruneopts = "UT"
revision = "f16ca3b7b383d3f0373109cac19147de3e8ae2d1"
[[projects]]
digest = "1:7ad278b575635babef38e4ad4219500c299a58ea14b30eb21383d0efca00b369"
name = "github.com/kr/binarydist"
packages = ["."]
pruneopts = "UT"
revision = "88f551ae580780cc79d12ab4c218ba1ca346b83a"
version = "v0.1.0"
[[projects]]
digest = "1:4701b2acabe16722ecb1e387d39741a29269386bfc4ba6283ecda362d289eff1"
name = "github.com/malfunkt/iprange"
packages = ["."]
pruneopts = "UT"
revision = "3a31f5ed42d2d8a1fc46f1be91fd693bdef2dd52"
version = "v0.9.0"
[[projects]]
digest = "1:2fa7b0155cd54479a755c629de26f888a918e13f8857a2c442205d825368e084"
name = "github.com/mattn/go-colorable"
packages = ["."]
pruneopts = "UT"
revision = "3a70a971f94a22f2fa562ffcc7a0eb45f5daf045"
version = "v0.1.1"
[[projects]]
digest = "1:e150b5fafbd7607e2d638e4e5cf43aa4100124e5593385147b0a74e2733d8b0d"
name = "github.com/mattn/go-isatty"
packages = ["."]
pruneopts = "UT"
revision = "c2a7a6ca930a4cd0bc33a3f298eb71960732a3a7"
version = "v0.0.7"
[[projects]]
branch = "master"
digest = "1:b2a92f887089bda5ea0b5c885d6e785581756da3e24ed86df5566c60721a70ec"
name = "github.com/mdlayher/dhcp6"
packages = [
".",
"dhcp6opts",
"internal/buffer",
]
pruneopts = "UT"
revision = "2a67805d7d0b0bad6c1103058981afdea583b459"
[[projects]]
digest = "1:34fe44dd2bbe5723068e0a7a266847965a88297d383fe611e0358e556d82de09"
name = "github.com/mdlayher/raw"
packages = ["."]
pruneopts = "UT"
revision = "480b93709cce56651807d3fdeb260a5a7c4e2d5f"
[[projects]]
branch = "master"
digest = "1:2b32af4d2a529083275afc192d1067d8126b578c7a9613b26600e4df9c735155"
name = "github.com/mgutz/ansi"
packages = ["."]
pruneopts = "UT"
revision = "9520e82c474b0a04dd04f8a40959027271bab992"
[[projects]]
digest = "1:17bc403348b60bd01bfd2e507fcb23463e76f4b1f433d50b0872b8219df1250d"
name = "github.com/mgutz/logxi"
packages = ["v1"]
pruneopts = "UT"
revision = "aebf8a7d67ab4625e0fd4a665766fef9a709161b"
version = "v1"
[[projects]]
digest = "1:3a3bc3c022d600ed4aced1d220d92c80bf3e42ff5acf95b59839f7af9ac53346"
name = "github.com/miekg/dns"
packages = ["."]
pruneopts = "UT"
revision = "8aa92d4e02c501ba21e26fb92cf2fb9f23f56917"
version = "v1.1.9"
[[projects]]
digest = "1:cf31692c14422fa27c83a05292eb5cbe0fb2775972e8f1f8446a71549bd8980b"
name = "github.com/pkg/errors"
packages = ["."]
pruneopts = "UT"
revision = "ba968bfe8b2f7e042a574c888954fccecfa385b4"
version = "v0.8.1"
[[projects]]
branch = "master"
digest = "1:dbfe572cc258e5bcf54cb650a06d90edd0da04e42ca1ed909cc1d49f00011c63"
name = "github.com/robertkrimen/otto"
packages = [
".",
"ast",
"dbg",
"file",
"parser",
"registry",
"token",
]
pruneopts = "UT"
revision = "15f95af6e78dcd2030d8195a138bd88d4f403546"
[[projects]]
branch = "master"
digest = "1:52b21e6be25049834aea5ecdde35d723c00fbdad3ea0357f2072dfb105836e02"
name = "github.com/tarm/serial"
packages = ["."]
pruneopts = "UT"
revision = "98f6abe2eb07edd42f6dfa2a934aea469acc29b7"
[[projects]]
branch = "master"
digest = "1:d5891c5bca9c62e5d394ca26491d2b710a1dc08cedeb0ca8f9ac4c3305120b02"
name = "golang.org/x/crypto"
packages = [
"ed25519",
"ed25519/internal/edwards25519",
]
pruneopts = "UT"
revision = "a29dc8fdc73485234dbef99ebedb95d2eced08de"
[[projects]]
branch = "master"
digest = "1:c72eab4f1e3a7f4f544d4ab0c973a95893f9b7623617dba96dd4cc56ae96e80a"
name = "golang.org/x/net"
packages = [
"bpf",
"html",
"html/atom",
"internal/iana",
"internal/socket",
"ipv4",
"ipv6",
]
pruneopts = "UT"
revision = "9ce7a6920f093fc0b908c4a5f66ae049110f417e"
[[projects]]
branch = "master"
digest = "1:dcd2e9de31e20e01b156288ce4fc239498564295bdbb59d8aaf591af94778162"
name = "golang.org/x/sys"
packages = ["unix"]
pruneopts = "UT"
revision = "d89cdac9e8725f2aefce25fcbfef41134c9ad412"
[[projects]]
digest = "1:9935525a8c49b8434a0b0a54e1980e94a6fae73aaff45c5d33ba8dff69de123e"
name = "gopkg.in/sourcemap.v1"
packages = [
".",
"base64vlq",
]
pruneopts = "UT"
revision = "6e83acea0053641eff084973fee085f0c193c61a"
version = "v1.0.5"
[solve-meta]
analyzer-name = "dep"
analyzer-version = 1
input-imports = [
"github.com/adrianmo/go-nmea",
"github.com/antchfx/jsonquery",
"github.com/bettercap/gatt",
"github.com/bettercap/nrf24",
"github.com/bettercap/readline",
"github.com/bettercap/recording",
"github.com/chifflier/nfqueue-go/nfqueue",
"github.com/dustin/go-humanize",
"github.com/elazarl/goproxy",
"github.com/evilsocket/islazy/async",
"github.com/evilsocket/islazy/data",
"github.com/evilsocket/islazy/fs",
"github.com/evilsocket/islazy/log",
"github.com/evilsocket/islazy/ops",
"github.com/evilsocket/islazy/plugin",
"github.com/evilsocket/islazy/str",
"github.com/evilsocket/islazy/tui",
"github.com/evilsocket/islazy/zip",
"github.com/gobwas/glob",
"github.com/google/go-github/github",
"github.com/google/gopacket",
"github.com/google/gopacket/layers",
"github.com/google/gopacket/pcap",
"github.com/google/gopacket/pcapgo",
"github.com/google/gousb",
"github.com/gorilla/mux",
"github.com/gorilla/websocket",
"github.com/hashicorp/mdns",
"github.com/inconshreveable/go-vhost",
"github.com/jpillora/go-tld",
"github.com/malfunkt/iprange",
"github.com/mdlayher/dhcp6",
"github.com/mdlayher/dhcp6/dhcp6opts",
"github.com/mdlayher/raw",
"github.com/miekg/dns",
"github.com/robertkrimen/otto",
"github.com/tarm/serial",
"golang.org/x/net/html",
]
solver-name = "gps-cdcl"
solver-version = 1

View file

@ -1,85 +0,0 @@
required = ["github.com/mdlayher/raw"]
[[constraint]]
name = "github.com/evilsocket/islazy"
version = "1.9.1"
[[constraint]]
branch = "master"
name = "github.com/bettercap/gatt"
[[constraint]]
name = "github.com/bettercap/readline"
version = "1.4.0"
[[constraint]]
name = "github.com/bettercap/recording"
revision = "3ce1dcf032e391eb321311b34cdf31c6fc9523f5"
[[constraint]]
branch = "master"
name = "github.com/chifflier/nfqueue-go"
[[constraint]]
branch = "master"
name = "github.com/dustin/go-humanize"
[[constraint]]
branch = "master"
name = "github.com/elazarl/goproxy"
[[constraint]]
branch = "master"
name = "github.com/gobwas/glob"
[[constraint]]
name = "github.com/google/go-github"
version = "15.0.0"
[[constraint]]
name = "github.com/google/gopacket"
revision = "v1.1.16"
[[constraint]]
name = "github.com/gorilla/mux"
version = "1.6.1"
[[constraint]]
name = "github.com/gorilla/websocket"
version = "1.2.0"
[[constraint]]
branch = "master"
name = "github.com/inconshreveable/go-vhost"
[[constraint]]
branch = "master"
name = "github.com/jpillora/go-tld"
[[constraint]]
name = "github.com/malfunkt/iprange"
version = "0.9.0"
[[constraint]]
revision = "480b93709cce56651807d3fdeb260a5a7c4e2d5f"
name = "github.com/mdlayher/raw"
[[constraint]]
branch = "master"
name = "github.com/mdlayher/dhcp6"
[[constraint]]
branch = "master"
name = "github.com/robertkrimen/otto"
[[constraint]]
branch = "master"
name = "github.com/tarm/serial"
[[constraint]]
name = "github.com/adrianmo/go-nmea"
version = "1.1.0"
[prune]
go-tests = true
unused-packages = true

47
go.mod Normal file
View file

@ -0,0 +1,47 @@
module github.com/bettercap/bettercap
go 1.12
require (
github.com/adrianmo/go-nmea v1.1.0
github.com/antchfx/jsonquery v0.0.0-20180821084212-a2896be8c82b
github.com/antchfx/xpath v1.0.0 // indirect
github.com/bettercap/gatt v0.0.0-20190418085356-fac16c0ad797
github.com/bettercap/nrf24 v0.0.0-20190219153547-aa37e6d0e0eb
github.com/bettercap/readline v0.0.0-20180208083827-9cec905dd291
github.com/bettercap/recording v0.0.0-20190408083647-3ce1dcf032e3
github.com/chifflier/nfqueue-go v0.0.0-20170228160439-61ca646babef
github.com/chzyer/logex v1.1.10 // indirect
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/dustin/go-humanize v1.0.0
github.com/elazarl/goproxy v0.0.0-20190421051319-9d40249d3c2f
github.com/elazarl/goproxy/ext v0.0.0-20190421051319-9d40249d3c2f // indirect
github.com/evilsocket/islazy v1.10.4
github.com/gobwas/glob v0.0.0-20181002190808-e7a84e9525fe
github.com/google/go-github v17.0.0+incompatible
github.com/google/go-querystring v1.0.0 // indirect
github.com/google/gopacket v1.1.17
github.com/google/gousb v0.0.0-20190525092738-2dc560e6bea3
github.com/gorilla/mux v1.7.2
github.com/gorilla/websocket v1.4.0
github.com/hashicorp/mdns v1.0.1
github.com/inconshreveable/go-vhost v0.0.0-20160627193104-06d84117953b
github.com/jpillora/go-tld v0.0.0-20190202073305-f16ca3b7b383
github.com/kr/binarydist v0.1.0 // indirect
github.com/malfunkt/iprange v0.9.0
github.com/mattn/go-colorable v0.1.2 // indirect
github.com/mdlayher/dhcp6 v0.0.0-20190311162359-2a67805d7d0b
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b // indirect
github.com/mgutz/logxi v0.0.0-20161027140823-aebf8a7d67ab // indirect
github.com/miekg/dns v1.1.14
github.com/pkg/errors v0.8.1 // indirect
github.com/robertkrimen/otto v0.0.0-20180617131154-15f95af6e78d
github.com/stretchr/testify v1.3.0 // indirect
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07
golang.org/x/crypto v0.0.0-20190621222207-cc06ce4a13d4 // indirect
golang.org/x/net v0.0.0-20190620200207-3b0461eec859
golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb // indirect
gopkg.in/sourcemap.v1 v1.0.5 // indirect
honnef.co/go/tools v0.0.0-2019.2.1 // indirect
)

120
go.sum Normal file
View file

@ -0,0 +1,120 @@
github.com/BurntSushi/toml v0.3.1 h1:WXkYYl6Yr3qBf1K79EBnL4mak0OimBfB0XUf9Vl28OQ=
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
github.com/adrianmo/go-nmea v1.1.0 h1:0NILSj14nj6LvVQHo/afHbyPgGz5qvp5PM6jmMyAQzY=
github.com/adrianmo/go-nmea v1.1.0/go.mod h1:HHPxPAm2kmev+61qmkZh7xgZF/7qHtSpsWppip2Ipv8=
github.com/antchfx/jsonquery v0.0.0-20180821084212-a2896be8c82b h1:oREWiN8d6BYorETYz2PH2Kk0CtUdp0RETyab7ep4jNY=
github.com/antchfx/jsonquery v0.0.0-20180821084212-a2896be8c82b/go.mod h1:h7950pvPrUZzJIflNqsELgDQovTpPNa0rAHf8NwjegY=
github.com/antchfx/xpath v1.0.0 h1:Q5gFgh2O40VTSwMOVbFE7nFNRBu3tS21Tn0KAWeEjtk=
github.com/antchfx/xpath v1.0.0/go.mod h1:Yee4kTMuNiPYJ7nSNorELQMr1J33uOpXDMByNYhvtNk=
github.com/bettercap/gatt v0.0.0-20190418085356-fac16c0ad797 h1:P9DK7Ij21WQAPFTUix8rblTVKDdwJEimCVO5foIr2ik=
github.com/bettercap/gatt v0.0.0-20190418085356-fac16c0ad797/go.mod h1:xbRFD+l8RcbQ3DscCiYX0dgEnXbwozZgm6oP2GXic+0=
github.com/bettercap/nrf24 v0.0.0-20190219153547-aa37e6d0e0eb h1:JWAAJk4ny+bT3VrtcX+e7mcmWtWUeUM0xVcocSAUuWc=
github.com/bettercap/nrf24 v0.0.0-20190219153547-aa37e6d0e0eb/go.mod h1:g6WiaSRgMTiChuk7jYyFSEtpgaw1F0wAsBfspG3bu0M=
github.com/bettercap/readline v0.0.0-20180208083827-9cec905dd291 h1:6GtREdpf6N/trykGvhwfr0nyo3V/yncz0JvNbu+z7S8=
github.com/bettercap/readline v0.0.0-20180208083827-9cec905dd291/go.mod h1:03rWiUf60r1miMVzMEtgtkq7RdZniecZFw3/Zgvyxcs=
github.com/bettercap/recording v0.0.0-20190408083647-3ce1dcf032e3 h1:pC4ZAk7UtDIbrRKzMMiIL1TVkiKlgtgcJodqKB53Rl4=
github.com/bettercap/recording v0.0.0-20190408083647-3ce1dcf032e3/go.mod h1:kqVwnx6DKuOHMZcBnzsgp2Lq2JZHDtFtm92b5hxdRaM=
github.com/chifflier/nfqueue-go v0.0.0-20170228160439-61ca646babef h1:uhLIhHeIRlFbAI1mOHkz3vN23T+QdhA9MgnvnJaQyL0=
github.com/chifflier/nfqueue-go v0.0.0-20170228160439-61ca646babef/go.mod h1:xn8SYXvxzI99iSN8+Kh3wCvt2fhr27vPPf8ju9FwRS0=
github.com/chzyer/logex v1.1.10 h1:Swpa1K6QvQznwJRcfTfQJmTE72DqScAa40E+fbHEXEE=
github.com/chzyer/logex v1.1.10/go.mod h1:+Ywpsq7O8HXn0nuIou7OrIPyXbp3wmkHB+jjWRnGsAI=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1 h1:q763qf9huN11kDQavWsoZXJNW3xEE4JJyHa5Q25/sd8=
github.com/chzyer/test v0.0.0-20180213035817-a1ea475d72b1/go.mod h1:Q3SI9o4m/ZMnBNeIyt5eFwwo7qiLfzFZmjNmxjkiQlU=
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/dustin/go-humanize v1.0.0 h1:VSnTsYCnlFHaM2/igO1h6X3HA71jcobQuxemgkq4zYo=
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
github.com/elazarl/goproxy v0.0.0-20190421051319-9d40249d3c2f h1:8GDPb0tCY8LQ+OJ3dbHb5sA6YZWXFORQYZx5sdsTlMs=
github.com/elazarl/goproxy v0.0.0-20190421051319-9d40249d3c2f/go.mod h1:/Zj4wYkgs4iZTTu3o/KG3Itv/qCCa8VVMlb3i9OVuzc=
github.com/elazarl/goproxy/ext v0.0.0-20190421051319-9d40249d3c2f h1:AUj1VoZUfhPhOPHULCQQDnGhRelpFWHMLhQVWDsS0v4=
github.com/elazarl/goproxy/ext v0.0.0-20190421051319-9d40249d3c2f/go.mod h1:gNh8nYJoAm43RfaxurUnxr+N1PwuFV3ZMl/efxlIlY8=
github.com/evilsocket/islazy v1.10.4 h1:Z5373Kn5Gh2EWch1Tb/Qxb6vyQ7lw704bmKi7sY4Ecs=
github.com/evilsocket/islazy v1.10.4/go.mod h1:OrwQGYg3DuZvXUfmH+KIZDjwTCbrjy48T24TUpGqVVw=
github.com/gobwas/glob v0.0.0-20181002190808-e7a84e9525fe h1:8P+/htb3mwwpeGdJg69yBF/RofK7c6Fjz5Ypa/bTqbY=
github.com/gobwas/glob v0.0.0-20181002190808-e7a84e9525fe/go.mod h1:d3Ez4x06l9bZtSvzIay5+Yzi0fmZzPgnTbPcKjJAkT8=
github.com/google/go-github v17.0.0+incompatible h1:N0LgJ1j65A7kfXrZnUDaYCs/Sf4rEjNlfyDHW9dolSY=
github.com/google/go-github v17.0.0+incompatible/go.mod h1:zLgOLi98H3fifZn+44m+umXrS52loVEgC2AApnigrVQ=
github.com/google/go-querystring v1.0.0 h1:Xkwi/a1rcvNg1PPYe5vI8GbeBY/jrVuDX5ASuANWTrk=
github.com/google/go-querystring v1.0.0/go.mod h1:odCYkC5MyYFN7vkCjXpyrEuKhc/BUO6wN/zVPAxq5ck=
github.com/google/gopacket v1.1.17 h1:rMrlX2ZY2UbvT+sdz3+6J+pp2z+msCq9MxTU6ymxbBY=
github.com/google/gopacket v1.1.17/go.mod h1:UdDNZ1OO62aGYVnPhxT1U6aI7ukYtA/kB8vaU0diBUM=
github.com/google/gousb v0.0.0-20190525092738-2dc560e6bea3 h1:3RtjTHQgWbD7dsPreVSkA5/LGfNnAZyjOtDXhargyEE=
github.com/google/gousb v0.0.0-20190525092738-2dc560e6bea3/go.mod h1:Tl4HdAs1ThE3gECkNwz+1MWicX6FXddhJEw7L8jRDiI=
github.com/google/renameio v0.1.0/go.mod h1:KWCgfxg9yswjAJkECMjeO8J8rahYeXnNhOm40UhjYkI=
github.com/gorilla/mux v1.7.2 h1:zoNxOV7WjqXptQOVngLmcSQgXmgk4NMz1HibBchjl/I=
github.com/gorilla/mux v1.7.2/go.mod h1:1lud6UwP+6orDFRuTfBEV8e9/aOM/c4fVVCaMa2zaAs=
github.com/gorilla/websocket v1.4.0 h1:WDFjx/TMzVgy9VdMMQi2K2Emtwi2QcUQsztZ/zLaH/Q=
github.com/gorilla/websocket v1.4.0/go.mod h1:E7qHFY5m1UJ88s3WnNqhKjPHQ0heANvMoAMk2YaljkQ=
github.com/hashicorp/mdns v1.0.1 h1:XFSOubp8KWB+Jd2PDyaX5xUd5bhSP/+pTDZVDMzZJM8=
github.com/hashicorp/mdns v1.0.1/go.mod h1:4gW7WsVCke5TE7EPeYliwHlRUyBtfCwuFwuMg2DmyNY=
github.com/inconshreveable/go-vhost v0.0.0-20160627193104-06d84117953b h1:IpLPmn6Re21F0MaV6Zsc5RdSE6KuoFpWmHiUSEs3PrE=
github.com/inconshreveable/go-vhost v0.0.0-20160627193104-06d84117953b/go.mod h1:aA6DnFhALT3zH0y+A39we+zbrdMC2N0X/q21e6FI0LU=
github.com/jpillora/go-tld v0.0.0-20190202073305-f16ca3b7b383 h1:/ODEnccTd4m/1YbCDCZBIoo+W1BC+PjOzvfX8y++b5s=
github.com/jpillora/go-tld v0.0.0-20190202073305-f16ca3b7b383/go.mod h1:7H/4k+TVAFSXCq+KcvelJ5hClsXnabjF52BLYqgaqcQ=
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
github.com/kr/binarydist v0.1.0 h1:6kAoLA9FMMnNGSehX0s1PdjbEaACznAv/W219j2uvyo=
github.com/kr/binarydist v0.1.0/go.mod h1:DY7S//GCoz1BCd0B0EVrinCKAZN3pXe+MDaIZbXQVgM=
github.com/kr/pretty v0.1.0/go.mod h1:dAy3ld7l9f0ibDNOQOHHMYYIIbhfbHSm3C4ZsoJORNo=
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/malfunkt/iprange v0.9.0 h1:VCs0PKLUPotNVQTpVNszsut4lP7OCGNBwX+lOYBrnVQ=
github.com/malfunkt/iprange v0.9.0/go.mod h1:TRGqO/f95gh3LOndUGTL46+W0GXA91WTqyZ0Quwvt4U=
github.com/mattn/go-colorable v0.1.2 h1:/bC9yWikZXAL9uJdulbSfyVNIR3n3trXl+v8+1sx8mU=
github.com/mattn/go-colorable v0.1.2/go.mod h1:U0ppj6V5qS13XJ6of8GYAs25YV2eR4EVcfRqFIhoBtE=
github.com/mattn/go-isatty v0.0.8 h1:HLtExJ+uU2HOZ+wI0Tt5DtUDrx8yhUqDcp7fYERX4CE=
github.com/mattn/go-isatty v0.0.8/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
github.com/mdlayher/dhcp6 v0.0.0-20190311162359-2a67805d7d0b h1:r12blE3QRYlW1WBiBEe007O6NrTb/P54OjR5d4WLEGk=
github.com/mdlayher/dhcp6 v0.0.0-20190311162359-2a67805d7d0b/go.mod h1:p4K2+UAoap8Jzsadsxc0KG0OZjmmCthTPUyZqAVkjBY=
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b h1:j7+1HpAFS1zy5+Q4qx1fWh90gTKwiN4QCGoY9TWyyO4=
github.com/mgutz/ansi v0.0.0-20170206155736-9520e82c474b/go.mod h1:01TrycV0kFyexm33Z7vhZRXopbI8J3TDReVlkTgMUxE=
github.com/mgutz/logxi v0.0.0-20161027140823-aebf8a7d67ab h1:n8cgpHzJ5+EDyDri2s/GC7a9+qK3/YEGnBsd0uS/8PY=
github.com/mgutz/logxi v0.0.0-20161027140823-aebf8a7d67ab/go.mod h1:y1pL58r5z2VvAjeG1VLGc8zOQgSOzbKN7kMHPvFXJ+8=
github.com/miekg/dns v1.0.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/miekg/dns v1.1.14 h1:wkQWn9wIp4mZbwW8XV6Km6owkvRPbOiV004ZM2CkGvA=
github.com/miekg/dns v1.1.14/go.mod h1:W1PPwlIAgtquWBMBEV9nkV9Cazfe8ScdGz/Lj7v3Nrg=
github.com/pkg/errors v0.8.1 h1:iURUrRGxPUNPdy5/HRSm+Yj6okJ6UtLINN0Q9M4+h3I=
github.com/pkg/errors v0.8.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/robertkrimen/otto v0.0.0-20180617131154-15f95af6e78d h1:1VUlQbCfkoSGv7qP7Y+ro3ap1P1pPZxgdGVqiTVy5C4=
github.com/robertkrimen/otto v0.0.0-20180617131154-15f95af6e78d/go.mod h1:xvqspoSXJTIpemEonrMDFq6XzwHYYgToXWj5eRX1OtY=
github.com/rogpeppe/go-charset v0.0.0-20180617210344-2471d30d28b4/go.mod h1:qgYeAmZ5ZIpBWTGllZSQnw97Dj+woV0toclVaRGI8pc=
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
github.com/stretchr/testify v1.2.1/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
github.com/stretchr/testify v1.3.0 h1:TivCn/peBQ7UY8ooIcPgZFpTNSz0Q2U6UrFlUfqbe0Q=
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07 h1:UyzmZLoiDWMRywV4DUYb9Fbt8uiOSooupjTq10vpvnU=
github.com/tarm/serial v0.0.0-20180830185346-98f6abe2eb07/go.mod h1:kDXzergiv9cbyO7IOYJZWg1U88JhDg3PB6klq9Hg2pA=
golang.org/x/crypto v0.0.0-20181029021203-45a5f77698d3/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20190510104115-cbcb75029529/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/crypto v0.0.0-20190621222207-cc06ce4a13d4 h1:ydJNl0ENAG67pFbB+9tfhiL2pYqLhfoaZFw/cjLhY4A=
golang.org/x/crypto v0.0.0-20190621222207-cc06ce4a13d4/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
golang.org/x/mod v0.0.0-20190513183733-4bf6d317e70e/go.mod h1:mXi4GBBbnImb6dmsKGUJ2LatrhH/nqhxcFungHvyanc=
golang.org/x/net v0.0.0-20181023162649-9b4f9f5ad519/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190310074541-c10a0554eabf/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190311183353-d8887717615a/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 h1:R/3boaszxrf1GEUWTVDzSKVwLmSJpwZ1yqXm8j0v2QI=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58 h1:8gQV6CLnAEikrhgkHFbMAEhagSSnXWGV915qUMm9mrU=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20181026203630-95b1ffbd15a5/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-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190405154228-4b34438f7a67/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb h1:fgwFCsaw9buMuxNd6+DQfAuSFqbNiQZpcgJQAgJsK6k=
golang.org/x/sys v0.0.0-20190626221950-04f50cda93cb/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac h1:MQEvx39qSf8vyrx3XRaOe+j1UDIzKwkYOVObRgGPVqI=
golang.org/x/tools v0.0.0-20190621195816-6e04913cbbac/go.mod h1:/rFqwRUd4F7ZHNgwSSTFct+R/Kf4OFW1sUzUTQQTgfc=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/errgo.v2 v2.1.0/go.mod h1:hNsd1EY+bozCKY1Ytp96fpM3vjJbqLJn88ws8XvfDNI=
gopkg.in/sourcemap.v1 v1.0.5 h1:inv58fC9f9J3TK2Y2R1NPntXEn3/wjWHkonhIUODNTI=
gopkg.in/sourcemap.v1 v1.0.5/go.mod h1:2RlvNNSMglmRrcvhfuzp4hQHwOtjxlbjX7UPY/GXb78=
honnef.co/go/tools v0.0.0-2019.2.1 h1:fW1wbZIKRbRK56ETe5SYloH5SdLzhXOFet2KlpRKDqg=
honnef.co/go/tools v0.0.0-2019.2.1/go.mod h1:a3bituU0lyd329TUQxRnasdCoJDkEUEAqEt0JzvZhAg=

View file

@ -1,33 +0,0 @@
# Travis CI (http://travis-ci.org/) is a continuous integration
# service for open source projects. This file configures it
# to run unit tests for go-nmea.
language: go
go:
- 1.7.x
- 1.8.x
- 1.9.x
- 1.10.x
- tip
matrix:
fast_finish: true
before_install:
- go get golang.org/x/tools/cmd/cover
- go get github.com/golang/lint/golint
- go get github.com/mattn/goveralls
- go get github.com/stretchr/testify/assert
install:
- go get -d -v ./... && go build -v ./...
script:
- go vet -x ./...
- $HOME/gopath/bin/golint -set_exit_status ./...
- go test -v ./...
- go test -covermode=count -coverprofile=profile.cov .
after_script:
- $HOME/gopath/bin/goveralls -coverprofile=profile.cov -service=travis-ci

View file

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) 2015 Adrian Moreno
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,85 +0,0 @@
# go-nmea [![Build Status](https://travis-ci.org/adrianmo/go-nmea.svg?branch=master)](https://travis-ci.org/adrianmo/go-nmea) [![Go Report Card](https://goreportcard.com/badge/github.com/adrianmo/go-nmea)](https://goreportcard.com/report/github.com/adrianmo/go-nmea) [![Coverage Status](https://coveralls.io/repos/adrianmo/go-nmea/badge.svg?branch=master&service=github)](https://coveralls.io/github/adrianmo/go-nmea?branch=master) [![GoDoc](https://godoc.org/github.com/adrianmo/go-nmea?status.svg)](https://godoc.org/github.com/adrianmo/go-nmea)
This is a NMEA library for the Go programming language (http://golang.org).
## Installing
### Using `go get`
go get github.com/adrianmo/go-nmea
After this command *go-nmea* is ready to use. Its source will be in:
$GOPATH/src/github.com/adrianmo/go-nmea
## Supported sentences
At this moment, this library supports the following sentence types:
- [GPRMC](http://aprs.gids.nl/nmea/#rmc) - Recommended Minimum Specific GPS/Transit data
- [GNRMC](http://aprs.gids.nl/nmea/#rmc) - Recommended Minimum Specific GNSS data
- [GPGGA](http://aprs.gids.nl/nmea/#gga) - GPS Positioning System Fix Data
- [GNGGA](http://aprs.gids.nl/nmea/#gga) - GNSS Positioning System Fix Data
- [GPGSA](http://aprs.gids.nl/nmea/#gsa) - GPS DOP and active satellites
- [GPGSV](http://aprs.gids.nl/nmea/#gsv) - GPS Satellites in view
- [GLGSV](http://aprs.gids.nl/nmea/#gsv) - GLONASS Satellites in view
- [GPGLL](http://aprs.gids.nl/nmea/#gll) - Geographic Position, Latitude / Longitude and time
- [GPVTG](http://aprs.gids.nl/nmea/#vtg) - Track Made Good and Ground Speed
- [GPZDA](http://aprs.gids.nl/nmea/#zda) - Date & time data
- [PGRME](http://aprs.gids.nl/nmea/#rme) - Estimated Position Error (Garmin proprietary sentence)
- [GPHDT](http://aprs.gids.nl/nmea/#hdt) - Actual vessel heading in degrees True
## Example
```go
package main
import (
"fmt"
"log"
"github.com/adrianmo/go-nmea"
)
func main() {
sentence := "$GPRMC,220516,A,5133.82,N,00042.24,W,173.8,231.8,130694,004.2,W*70"
s, err := nmea.Parse(sentence)
if err != nil {
log.Fatal(err)
}
m := s.(nmea.GPRMC)
fmt.Printf("Raw sentence: %v\n", m)
fmt.Printf("Time: %s\n", m.Time)
fmt.Printf("Validity: %s\n", m.Validity)
fmt.Printf("Latitude GPS: %s\n", nmea.FormatGPS(m.Latitude))
fmt.Printf("Latitude DMS: %s\n", nmea.FormatDMS(m.Latitude))
fmt.Printf("Longitude GPS: %s\n", nmea.FormatGPS(m.Longitude))
fmt.Printf("Longitude DMS: %s\n", nmea.FormatDMS(m.Longitude))
fmt.Printf("Speed: %f\n", m.Speed)
fmt.Printf("Course: %f\n", m.Course)
fmt.Printf("Date: %s\n", m.Date)
fmt.Printf("Variation: %f\n", m.Variation)
}
```
Output:
```
$ go run main/main.go
Raw sentence: $GPRMC,220516,A,5133.82,N,00042.24,W,173.8,231.8,130694,004.2,W*70
Time: 22:05:16.0000
Validity: A
Latitude GPS: 5133.8200
Latitude DMS: 51° 33' 49.200000"
Longitude GPS: 042.2400
Longitude DMS: 0° 42' 14.400000"
Speed: 173.800000
Course: 231.800000
Date: 13/06/94
Variation: -4.200000
```
## Contributions
Please, feel free to implement support for new sentences, fix bugs, refactor code, etc. and send a pull-request to update the library.

View file

@ -1 +0,0 @@
v1.1.0

View file

@ -1,47 +0,0 @@
package nmea
const (
// PrefixGLGSV prefix
PrefixGLGSV = "GLGSV"
)
// GLGSV represents the GPS Satellites in view
// http://aprs.gids.nl/nmea/#glgsv
type GLGSV struct {
BaseSentence
TotalMessages int64 // Total number of messages of this type in this cycle
MessageNumber int64 // Message number
NumberSVsInView int64 // Total number of SVs in view
Info []GLGSVInfo // visible satellite info (0-4 of these)
}
// GLGSVInfo represents information about a visible satellite
type GLGSVInfo struct {
SVPRNNumber int64 // SV PRN number, pseudo-random noise or gold code
Elevation int64 // Elevation in degrees, 90 maximum
Azimuth int64 // Azimuth, degrees from true north, 000 to 359
SNR int64 // SNR, 00-99 dB (null when not tracking)
}
// newGLGSV constructor
func newGLGSV(s BaseSentence) (GLGSV, error) {
p := newParser(s, PrefixGLGSV)
m := GLGSV{
BaseSentence: s,
TotalMessages: p.Int64(0, "total number of messages"),
MessageNumber: p.Int64(1, "message number"),
NumberSVsInView: p.Int64(2, "number of SVs in view"),
}
for i := 0; i < 4; i++ {
if 5*i+4 > len(m.Fields) {
break
}
m.Info = append(m.Info, GLGSVInfo{
SVPRNNumber: p.Int64(3+i*4, "SV prn number"),
Elevation: p.Int64(4+i*4, "elevation"),
Azimuth: p.Int64(5+i*4, "azimuth"),
SNR: p.Int64(6+i*4, "SNR"),
})
}
return m, p.Err()
}

View file

@ -1,39 +0,0 @@
package nmea
const (
// PrefixGNGGA prefix
PrefixGNGGA = "GNGGA"
)
// GNGGA is the Time, position, and fix related data of the receiver.
type GNGGA struct {
BaseSentence
Time Time // Time of fix.
Latitude float64 // Latitude.
Longitude float64 // Longitude.
FixQuality string // Quality of fix.
NumSatellites int64 // Number of satellites in use.
HDOP float64 // Horizontal dilution of precision.
Altitude float64 // Altitude.
Separation float64 // Geoidal separation
DGPSAge string // Age of differential GPD data.
DGPSId string // DGPS reference station ID.
}
// newGNGGA constructor
func newGNGGA(s BaseSentence) (GNGGA, error) {
p := newParser(s, PrefixGNGGA)
return GNGGA{
BaseSentence: s,
Time: p.Time(0, "time"),
Latitude: p.LatLong(1, 2, "latitude"),
Longitude: p.LatLong(3, 4, "longitude"),
FixQuality: p.EnumString(5, "fix quality", Invalid, GPS, DGPS, PPS, RTK, FRTK),
NumSatellites: p.Int64(6, "number of satellites"),
HDOP: p.Float64(7, "hdop"),
Altitude: p.Float64(8, "altitude"),
Separation: p.Float64(10, "separation"),
DGPSAge: p.String(12, "dgps age"),
DGPSId: p.String(13, "dgps id"),
}, p.Err()
}

View file

@ -1,40 +0,0 @@
package nmea
const (
// PrefixGNRMC prefix of GNRMC sentence type
PrefixGNRMC = "GNRMC"
)
// GNRMC is the Recommended Minimum Specific GNSS data.
// http://aprs.gids.nl/nmea/#rmc
type GNRMC struct {
BaseSentence
Time Time // Time Stamp
Validity string // validity - A-ok, V-invalid
Latitude float64 // Latitude
Longitude float64 // Longitude
Speed float64 // Speed in knots
Course float64 // True course
Date Date // Date
Variation float64 // Magnetic variation
}
// newGNRMC constructor
func newGNRMC(s BaseSentence) (GNRMC, error) {
p := newParser(s, PrefixGNRMC)
m := GNRMC{
BaseSentence: s,
Time: p.Time(0, "time"),
Validity: p.EnumString(1, "validity", ValidRMC, InvalidRMC),
Latitude: p.LatLong(2, 3, "latitude"),
Longitude: p.LatLong(4, 5, "longitude"),
Speed: p.Float64(6, "speed"),
Course: p.Float64(7, "course"),
Date: p.Date(8, "date"),
Variation: p.Float64(9, "variation"),
}
if p.EnumString(10, "direction", West, East) == West {
m.Variation = 0 - m.Variation
}
return m, p.Err()
}

View file

@ -1,3 +0,0 @@
module github.com/adrianmo/go-nmea
require github.com/stretchr/testify v1.2.1

View file

@ -1,53 +0,0 @@
package nmea
const (
// PrefixGPGGA prefix
PrefixGPGGA = "GPGGA"
// Invalid fix quality.
Invalid = "0"
// GPS fix quality
GPS = "1"
// DGPS fix quality
DGPS = "2"
// PPS fix
PPS = "3"
// RTK real time kinematic fix
RTK = "4"
// FRTK float RTK fix
FRTK = "5"
)
// GPGGA represents fix data.
// http://aprs.gids.nl/nmea/#gga
type GPGGA struct {
BaseSentence
Time Time // Time of fix.
Latitude float64 // Latitude.
Longitude float64 // Longitude.
FixQuality string // Quality of fix.
NumSatellites int64 // Number of satellites in use.
HDOP float64 // Horizontal dilution of precision.
Altitude float64 // Altitude.
Separation float64 // Geoidal separation
DGPSAge string // Age of differential GPD data.
DGPSId string // DGPS reference station ID.
}
// newGPGGA parses the GPGGA sentence into this struct.
// e.g: $GPGGA,034225.077,3356.4650,S,15124.5567,E,1,03,9.7,-25.0,M,21.0,M,,0000*58
func newGPGGA(s BaseSentence) (GPGGA, error) {
p := newParser(s, PrefixGPGGA)
return GPGGA{
BaseSentence: s,
Time: p.Time(0, "time"),
Latitude: p.LatLong(1, 2, "latitude"),
Longitude: p.LatLong(3, 4, "longitude"),
FixQuality: p.EnumString(5, "fix quality", Invalid, GPS, DGPS, PPS, RTK, FRTK),
NumSatellites: p.Int64(6, "number of satellites"),
HDOP: p.Float64(7, "hdap"),
Altitude: p.Float64(8, "altitude"),
Separation: p.Float64(10, "separation"),
DGPSAge: p.String(12, "dgps age"),
DGPSId: p.String(13, "dgps id"),
}, p.Err()
}

View file

@ -1,32 +0,0 @@
package nmea
const (
// PrefixGPGLL prefix for GPGLL sentence type
PrefixGPGLL = "GPGLL"
// ValidGLL character
ValidGLL = "A"
// InvalidGLL character
InvalidGLL = "V"
)
// GPGLL is Geographic Position, Latitude / Longitude and time.
// http://aprs.gids.nl/nmea/#gll
type GPGLL struct {
BaseSentence
Latitude float64 // Latitude
Longitude float64 // Longitude
Time Time // Time Stamp
Validity string // validity - A-valid
}
// newGPGLL constructor
func newGPGLL(s BaseSentence) (GPGLL, error) {
p := newParser(s, PrefixGPGLL)
return GPGLL{
BaseSentence: s,
Latitude: p.LatLong(0, 1, "latitude"),
Longitude: p.LatLong(2, 3, "longitude"),
Time: p.Time(4, "time"),
Validity: p.EnumString(5, "validity", ValidGLL, InvalidGLL),
}, p.Err()
}

View file

@ -1,49 +0,0 @@
package nmea
const (
// PrefixGPGSA prefix of GPGSA sentence type
PrefixGPGSA = "GPGSA"
// Auto - Field 1, auto or manual fix.
Auto = "A"
// Manual - Field 1, auto or manual fix.
Manual = "M"
// FixNone - Field 2, fix type.
FixNone = "1"
// Fix2D - Field 2, fix type.
Fix2D = "2"
// Fix3D - Field 2, fix type.
Fix3D = "3"
)
// GPGSA represents overview satellite data.
// http://aprs.gids.nl/nmea/#gsa
type GPGSA struct {
BaseSentence
Mode string // The selection mode.
FixType string // The fix type.
SV []string // List of satellite PRNs used for this fix.
PDOP float64 // Dilution of precision.
HDOP float64 // Horizontal dilution of precision.
VDOP float64 // Vertical dilution of precision.
}
// newGPGSA parses the GPGSA sentence into this struct.
func newGPGSA(s BaseSentence) (GPGSA, error) {
p := newParser(s, PrefixGPGSA)
m := GPGSA{
BaseSentence: s,
Mode: p.EnumString(0, "selection mode", Auto, Manual),
FixType: p.EnumString(1, "fix type", FixNone, Fix2D, Fix3D),
}
// Satellites in view.
for i := 2; i < 14; i++ {
if v := p.String(i, "satellite in view"); v != "" {
m.SV = append(m.SV, v)
}
}
// Dilution of precision.
m.PDOP = p.Float64(14, "pdop")
m.HDOP = p.Float64(15, "hdop")
m.VDOP = p.Float64(16, "vdop")
return m, p.Err()
}

View file

@ -1,47 +0,0 @@
package nmea
const (
// PrefixGPGSV prefix
PrefixGPGSV = "GPGSV"
)
// GPGSV represents the GPS Satellites in view
// http://aprs.gids.nl/nmea/#gpgsv
type GPGSV struct {
BaseSentence
TotalMessages int64 // Total number of messages of this type in this cycle
MessageNumber int64 // Message number
NumberSVsInView int64 // Total number of SVs in view
Info []GPGSVInfo // visible satellite info (0-4 of these)
}
// GPGSVInfo represents information about a visible satellite
type GPGSVInfo struct {
SVPRNNumber int64 // SV PRN number, pseudo-random noise or gold code
Elevation int64 // Elevation in degrees, 90 maximum
Azimuth int64 // Azimuth, degrees from true north, 000 to 359
SNR int64 // SNR, 00-99 dB (null when not tracking)
}
// newGPGSV constructor
func newGPGSV(s BaseSentence) (GPGSV, error) {
p := newParser(s, PrefixGPGSV)
m := GPGSV{
BaseSentence: s,
TotalMessages: p.Int64(0, "total number of messages"),
MessageNumber: p.Int64(1, "message number"),
NumberSVsInView: p.Int64(2, "number of SVs in view"),
}
for i := 0; i < 4; i++ {
if 5*i+4 > len(m.Fields) {
break
}
m.Info = append(m.Info, GPGSVInfo{
SVPRNNumber: p.Int64(3+i*4, "SV prn number"),
Elevation: p.Int64(4+i*4, "elevation"),
Azimuth: p.Int64(5+i*4, "azimuth"),
SNR: p.Int64(6+i*4, "SNR"),
})
}
return m, p.Err()
}

View file

@ -1,25 +0,0 @@
package nmea
const (
// PrefixGPHDT prefix of GPHDT sentence type
PrefixGPHDT = "GPHDT"
)
// GPHDT is the Actual vessel heading in degrees True.
// http://aprs.gids.nl/nmea/#hdt
type GPHDT struct {
BaseSentence
Heading float64 // Heading in degrees
True bool // Heading is relative to true north
}
// newGPHDT constructor
func newGPHDT(s BaseSentence) (GPHDT, error) {
p := newParser(s, PrefixGPHDT)
m := GPHDT{
BaseSentence: s,
Heading: p.Float64(0, "heading"),
True: p.EnumString(1, "true", "T") == "T",
}
return m, p.Err()
}

View file

@ -1,44 +0,0 @@
package nmea
const (
// PrefixGPRMC prefix of GPRMC sentence type
PrefixGPRMC = "GPRMC"
// ValidRMC character
ValidRMC = "A"
// InvalidRMC character
InvalidRMC = "V"
)
// GPRMC is the Recommended Minimum Specific GNSS data.
// http://aprs.gids.nl/nmea/#rmc
type GPRMC struct {
BaseSentence
Time Time // Time Stamp
Validity string // validity - A-ok, V-invalid
Latitude float64 // Latitude
Longitude float64 // Longitude
Speed float64 // Speed in knots
Course float64 // True course
Date Date // Date
Variation float64 // Magnetic variation
}
// newGPRMC constructor
func newGPRMC(s BaseSentence) (GPRMC, error) {
p := newParser(s, PrefixGPRMC)
m := GPRMC{
BaseSentence: s,
Time: p.Time(0, "time"),
Validity: p.EnumString(1, "validity", ValidRMC, InvalidRMC),
Latitude: p.LatLong(2, 3, "latitude"),
Longitude: p.LatLong(4, 5, "longitude"),
Speed: p.Float64(6, "speed"),
Course: p.Float64(7, "course"),
Date: p.Date(8, "date"),
Variation: p.Float64(9, "variation"),
}
if p.EnumString(10, "variation", West, East) == West {
m.Variation = 0 - m.Variation
}
return m, p.Err()
}

View file

@ -1,29 +0,0 @@
package nmea
const (
// PrefixGPVTG prefix
PrefixGPVTG = "GPVTG"
)
// GPVTG represents track & speed data.
// http://aprs.gids.nl/nmea/#vtg
type GPVTG struct {
BaseSentence
TrueTrack float64
MagneticTrack float64
GroundSpeedKnots float64
GroundSpeedKPH float64
}
// newGPVTG parses the GPVTG sentence into this struct.
// e.g: $GPVTG,360.0,T,348.7,M,000.0,N,000.0,K*43
func newGPVTG(s BaseSentence) (GPVTG, error) {
p := newParser(s, PrefixGPVTG)
return GPVTG{
BaseSentence: s,
TrueTrack: p.Float64(0, "true track"),
MagneticTrack: p.Float64(2, "magnetic track"),
GroundSpeedKnots: p.Float64(4, "ground speed (knots)"),
GroundSpeedKPH: p.Float64(6, "ground speed (km/h)"),
}, p.Err()
}

View file

@ -1,32 +0,0 @@
package nmea
const (
// PrefixGPZDA prefix
PrefixGPZDA = "GPZDA"
)
// GPZDA represents date & time data.
// http://aprs.gids.nl/nmea/#zda
type GPZDA struct {
BaseSentence
Time Time
Day int64
Month int64
Year int64
OffsetHours int64 // Local time zone offset from GMT, hours
OffsetMinutes int64 // Local time zone offset from GMT, minutes
}
// newGPZDA constructor
func newGPZDA(s BaseSentence) (GPZDA, error) {
p := newParser(s, PrefixGPZDA)
return GPZDA{
BaseSentence: s,
Time: p.Time(0, "time"),
Day: p.Int64(1, "day"),
Month: p.Int64(2, "month"),
Year: p.Int64(3, "year"),
OffsetHours: p.Int64(4, "offset (hours)"),
OffsetMinutes: p.Int64(5, "offset (minutes)"),
}, p.Err()
}

View file

@ -1,141 +0,0 @@
package nmea
import (
"fmt"
"strconv"
)
// parser provides a simple way of accessing and parsing
// sentence fields
type parser struct {
BaseSentence
prefix string
err error
}
// newParser constructor
func newParser(s BaseSentence, prefix string) *parser {
p := &parser{BaseSentence: s, prefix: prefix}
if p.Type != prefix {
p.SetErr("prefix", p.Type)
}
return p
}
// Err returns the first error encountered during the parser's usage.
func (p *parser) Err() error {
return p.err
}
// SetErr assigns an error. Calling this method has no
// effect if there is already an error.
func (p *parser) SetErr(context, value string) {
if p.err == nil {
p.err = fmt.Errorf("nmea: %s invalid %s: %s", p.prefix, context, value)
}
}
// String returns the field value at the specified index.
func (p *parser) String(i int, context string) string {
if p.err != nil {
return ""
}
if i < 0 || i >= len(p.Fields) {
p.SetErr(context, "index out of range")
return ""
}
return p.Fields[i]
}
// EnumString returns the field value at the specified index.
// An error occurs if the value is not one of the options and not empty.
func (p *parser) EnumString(i int, context string, options ...string) string {
s := p.String(i, context)
if p.err != nil || s == "" {
return ""
}
for _, o := range options {
if o == s {
return s
}
}
p.SetErr(context, s)
return ""
}
// Int64 returns the int64 value at the specified index.
// If the value is an empty string, 0 is returned.
func (p *parser) Int64(i int, context string) int64 {
s := p.String(i, context)
if p.err != nil {
return 0
}
if s == "" {
return 0
}
v, err := strconv.ParseInt(s, 10, 64)
if err != nil {
p.SetErr(context, s)
}
return v
}
// Float64 returns the float64 value at the specified index.
// If the value is an empty string, 0 is returned.
func (p *parser) Float64(i int, context string) float64 {
s := p.String(i, context)
if p.err != nil {
return 0
}
if s == "" {
return 0
}
v, err := strconv.ParseFloat(s, 64)
if err != nil {
p.SetErr(context, s)
}
return v
}
// Time returns the Time value at the specified index.
// If the value is empty, the Time is marked as invalid.
func (p *parser) Time(i int, context string) Time {
s := p.String(i, context)
if p.err != nil {
return Time{}
}
v, err := ParseTime(s)
if err != nil {
p.SetErr(context, s)
}
return v
}
// Date returns the Date value at the specified index.
// If the value is empty, the Date is marked as invalid.
func (p *parser) Date(i int, context string) Date {
s := p.String(i, context)
if p.err != nil {
return Date{}
}
v, err := ParseDate(s)
if err != nil {
p.SetErr(context, s)
}
return v
}
// LatLong returns the coordinate value of the specified fields.
func (p *parser) LatLong(i, j int, context string) float64 {
a := p.String(i, context)
b := p.String(j, context)
if p.err != nil {
return 0
}
s := fmt.Sprintf("%s %s", a, b)
v, err := ParseLatLong(s)
if err != nil {
p.SetErr(context, err.Error())
}
return v
}

View file

@ -1,38 +0,0 @@
package nmea
const (
// PrefixPGRME prefix for PGRME sentence type
PrefixPGRME = "PGRME"
// ErrorUnit must be meters (M)
ErrorUnit = "M"
)
// PGRME is Estimated Position Error (Garmin proprietary sentence)
// http://aprs.gids.nl/nmea/#rme
type PGRME struct {
BaseSentence
Horizontal float64 // Estimated horizontal position error (HPE) in metres
Vertical float64 // Estimated vertical position error (VPE) in metres
Spherical float64 // Overall spherical equivalent position error in meters
}
// newPGRME constructor
func newPGRME(s BaseSentence) (PGRME, error) {
p := newParser(s, PrefixPGRME)
horizontal := p.Float64(0, "horizontal error")
_ = p.EnumString(1, "horizontal error unit", ErrorUnit)
vertial := p.Float64(2, "vertical error")
_ = p.EnumString(3, "vertical error unit", ErrorUnit)
spherical := p.Float64(4, "spherical error")
_ = p.EnumString(5, "spherical error unit", ErrorUnit)
return PGRME{
BaseSentence: s,
Horizontal: horizontal,
Vertical: vertial,
Spherical: spherical,
}, p.Err()
}

View file

@ -1,112 +0,0 @@
package nmea
import (
"fmt"
"strings"
)
const (
// SentenceStart is the token to indicate the start of a sentence.
SentenceStart = "$"
// FieldSep is the token to delimit fields of a sentence.
FieldSep = ","
// ChecksumSep is the token to delimit the checksum of a sentence.
ChecksumSep = "*"
)
// Sentence interface for all NMEA sentence
type Sentence interface {
fmt.Stringer
Prefix() string
}
// BaseSentence contains the information about the NMEA sentence
type BaseSentence struct {
Type string // The sentence type (e.g $GPGSA)
Fields []string // Array of fields
Checksum string // The Checksum
Raw string // The raw NMEA sentence received
}
// Prefix returns the type of the message
func (s BaseSentence) Prefix() string { return s.Type }
// String formats the sentence into a string
func (s BaseSentence) String() string { return s.Raw }
// parseSentence parses a raw message into it's fields
func parseSentence(raw string) (BaseSentence, error) {
startIndex := strings.Index(raw, SentenceStart)
if startIndex != 0 {
return BaseSentence{}, fmt.Errorf("nmea: sentence does not start with a '$'")
}
sumSepIndex := strings.Index(raw, ChecksumSep)
if sumSepIndex == -1 {
return BaseSentence{}, fmt.Errorf("nmea: sentence does not contain checksum separator")
}
var (
fieldsRaw = raw[startIndex+1 : sumSepIndex]
fields = strings.Split(fieldsRaw, FieldSep)
checksumRaw = strings.ToUpper(raw[sumSepIndex+1:])
checksum = xorChecksum(fieldsRaw)
)
// Validate the checksum
if checksum != checksumRaw {
return BaseSentence{}, fmt.Errorf(
"nmea: sentence checksum mismatch [%s != %s]", checksum, checksumRaw)
}
return BaseSentence{
Type: fields[0],
Fields: fields[1:],
Checksum: checksumRaw,
Raw: raw,
}, nil
}
// xor all the bytes in a string an return it
// as an uppercase hex string
func xorChecksum(s string) string {
var checksum uint8
for i := 0; i < len(s); i++ {
checksum ^= s[i]
}
return fmt.Sprintf("%02X", checksum)
}
// Parse parses the given string into the correct sentence type.
func Parse(raw string) (Sentence, error) {
s, err := parseSentence(raw)
if err != nil {
return nil, err
}
switch s.Type {
case PrefixGPRMC:
return newGPRMC(s)
case PrefixGNRMC:
return newGNRMC(s)
case PrefixGPGGA:
return newGPGGA(s)
case PrefixGNGGA:
return newGNGGA(s)
case PrefixGPGSA:
return newGPGSA(s)
case PrefixGPGLL:
return newGPGLL(s)
case PrefixGPVTG:
return newGPVTG(s)
case PrefixGPZDA:
return newGPZDA(s)
case PrefixPGRME:
return newPGRME(s)
case PrefixGPGSV:
return newGPGSV(s)
case PrefixGLGSV:
return newGLGSV(s)
case PrefixGPHDT:
return newGPHDT(s)
default:
return nil, fmt.Errorf("nmea: sentence type '%s' not implemented", s.Type)
}
}

View file

@ -1,249 +0,0 @@
package nmea
// Latitude / longitude representation.
import (
"errors"
"fmt"
"math"
"strconv"
"strings"
"unicode"
)
const (
// Degrees value
Degrees = '\u00B0'
// Minutes value
Minutes = '\''
// Seconds value
Seconds = '"'
// Point value
Point = '.'
// North value
North = "N"
// South value
South = "S"
// East value
East = "E"
// West value
West = "W"
)
// ParseLatLong parses the supplied string into the LatLong.
//
// Supported formats are:
// - DMS (e.g. 33° 23' 22")
// - Decimal (e.g. 33.23454)
// - GPS (e.g 15113.4322S)
//
func ParseLatLong(s string) (float64, error) {
var l float64
if v, err := ParseDMS(s); err == nil {
l = v
} else if v, err := ParseGPS(s); err == nil {
l = v
} else if v, err := ParseDecimal(s); err == nil {
l = v
} else {
return 0, fmt.Errorf("cannot parse [%s], unknown format", s)
}
if l < -180.0 || 180.0 < l {
return 0, errors.New("coordinate is not in range -180, 180")
}
return l, nil
}
// ParseGPS parses a GPS/NMEA coordinate.
// e.g 15113.4322S
func ParseGPS(s string) (float64, error) {
parts := strings.Split(s, " ")
if len(parts) != 2 {
return 0, fmt.Errorf("invalid format: %s", s)
}
dir := parts[1]
value, err := strconv.ParseFloat(parts[0], 64)
if err != nil {
return 0, fmt.Errorf("parse error: %s", err.Error())
}
degrees := math.Floor(value / 100)
minutes := value - (degrees * 100)
value = degrees + minutes/60
if dir == North || dir == East {
return value, nil
} else if dir == South || dir == West {
return 0 - value, nil
} else {
return 0, fmt.Errorf("invalid direction [%s]", dir)
}
}
// FormatGPS formats a GPS/NMEA coordinate
func FormatGPS(l float64) string {
padding := ""
degrees := math.Floor(math.Abs(l))
fraction := (math.Abs(l) - degrees) * 60
if fraction < 10 {
padding = "0"
}
return fmt.Sprintf("%d%s%.4f", int(degrees), padding, fraction)
}
// ParseDecimal parses a decimal format coordinate.
// e.g: 151.196019
func ParseDecimal(s string) (float64, error) {
// Make sure it parses as a float.
l, err := strconv.ParseFloat(s, 64)
if err != nil || s[0] != '-' && len(strings.Split(s, ".")[0]) > 3 {
return 0.0, errors.New("parse error (not decimal coordinate)")
}
return l, nil
}
// ParseDMS parses a coordinate in degrees, minutes, seconds.
// - e.g. 33° 23' 22"
func ParseDMS(s string) (float64, error) {
degrees := 0
minutes := 0
seconds := 0.0
// Whether a number has finished parsing (i.e whitespace after it)
endNumber := false
// Temporary parse buffer.
tmpBytes := []byte{}
var err error
for i, r := range s {
switch {
case unicode.IsNumber(r) || r == '.':
if !endNumber {
tmpBytes = append(tmpBytes, s[i])
} else {
return 0, errors.New("parse error (no delimiter)")
}
case unicode.IsSpace(r) && len(tmpBytes) > 0:
endNumber = true
case r == Degrees:
if degrees, err = strconv.Atoi(string(tmpBytes)); err != nil {
return 0, errors.New("parse error (degrees)")
}
tmpBytes = tmpBytes[:0]
endNumber = false
case s[i] == Minutes:
if minutes, err = strconv.Atoi(string(tmpBytes)); err != nil {
return 0, errors.New("parse error (minutes)")
}
tmpBytes = tmpBytes[:0]
endNumber = false
case s[i] == Seconds:
if seconds, err = strconv.ParseFloat(string(tmpBytes), 64); err != nil {
return 0, errors.New("parse error (seconds)")
}
tmpBytes = tmpBytes[:0]
endNumber = false
case unicode.IsSpace(r) && len(tmpBytes) == 0:
continue
default:
return 0, fmt.Errorf("parse error (unknown symbol [%d])", s[i])
}
}
if len(tmpBytes) > 0 {
return 0, fmt.Errorf("parse error (trailing data [%s])", string(tmpBytes))
}
val := float64(degrees) + (float64(minutes) / 60.0) + (float64(seconds) / 60.0 / 60.0)
return val, nil
}
// FormatDMS returns the degrees, minutes, seconds format for the given LatLong.
func FormatDMS(l float64) string {
val := math.Abs(l)
degrees := int(math.Floor(val))
minutes := int(math.Floor(60 * (val - float64(degrees))))
seconds := 3600 * (val - float64(degrees) - (float64(minutes) / 60))
return fmt.Sprintf("%d\u00B0 %d' %f\"", degrees, minutes, seconds)
}
// Time type
type Time struct {
Valid bool
Hour int
Minute int
Second int
Millisecond int
}
// String representation of Time
func (t Time) String() string {
return fmt.Sprintf("%02d:%02d:%02d.%04d", t.Hour, t.Minute, t.Second, t.Millisecond)
}
// ParseTime parses wall clock time.
// e.g. hhmmss.ssss
// An empty time string will result in an invalid time.
func ParseTime(s string) (Time, error) {
if s == "" {
return Time{}, nil
}
ms := "0000"
hhmmss := s
if parts := strings.SplitN(s, ".", 2); len(parts) > 1 {
hhmmss, ms = parts[0], parts[1]
}
if len(hhmmss) != 6 {
return Time{}, fmt.Errorf("parse time: exptected hhmmss.ss format, got '%s'", s)
}
hour, err := strconv.Atoi(hhmmss[0:2])
if err != nil {
return Time{}, errors.New(hhmmss)
}
minute, err := strconv.Atoi(hhmmss[2:4])
if err != nil {
return Time{}, errors.New(hhmmss)
}
second, err := strconv.Atoi(hhmmss[4:6])
if err != nil {
return Time{}, errors.New(hhmmss)
}
millisecond, err := strconv.Atoi(ms)
if err != nil {
return Time{}, errors.New(hhmmss)
}
return Time{true, hour, minute, second, millisecond}, nil
}
// Date type
type Date struct {
Valid bool
DD int
MM int
YY int
}
// String representation of date
func (d Date) String() string {
return fmt.Sprintf("%02d/%02d/%02d", d.DD, d.MM, d.YY)
}
// ParseDate field ddmmyy format
func ParseDate(ddmmyy string) (Date, error) {
if ddmmyy == "" {
return Date{}, nil
}
if len(ddmmyy) != 6 {
return Date{}, fmt.Errorf("parse date: exptected ddmmyy format, got '%s'", ddmmyy)
}
dd, err := strconv.Atoi(ddmmyy[0:2])
if err != nil {
return Date{}, errors.New(ddmmyy)
}
mm, err := strconv.Atoi(ddmmyy[2:4])
if err != nil {
return Date{}, errors.New(ddmmyy)
}
yy, err := strconv.Atoi(ddmmyy[4:6])
if err != nil {
return Date{}, errors.New(ddmmyy)
}
return Date{true, dd, mm, yy}, nil
}

View file

@ -1,32 +0,0 @@
# vscode
.vscode
debug
*.test
./build
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof

View file

@ -1,14 +0,0 @@
language: go
go:
- 1.6
- 1.7
- 1.8
- 1.9
install:
- go get github.com/antchfx/xpath
- go get github.com/mattn/goveralls
script:
- $HOME/gopath/bin/goveralls -service=travis-ci

View file

@ -1,17 +0,0 @@
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -1,169 +0,0 @@
jsonquery
====
[![Build Status](https://travis-ci.org/antchfx/jsonquery.svg?branch=master)](https://travis-ci.org/antchfx/jsonquery)
[![Coverage Status](https://coveralls.io/repos/github/antchfx/jsonquery/badge.svg?branch=master)](https://coveralls.io/github/antchfx/jsonquery?branch=master)
[![GoDoc](https://godoc.org/github.com/antchfx/jsonquery?status.svg)](https://godoc.org/github.com/antchfx/jsonquery)
[![Go Report Card](https://goreportcard.com/badge/github.com/antchfx/jsonquery)](https://goreportcard.com/report/github.com/antchfx/jsonquery)
Overview
===
jsonquery is an XPath query package for JSON document, lets you extract data from JSON documents through an XPath expression.
Getting Started
===
### Install Package
> $ go get github.com/antchfx/jsonquery
#### Load JSON document from URL.
```go
doc, err := jsonquery.LoadURL("http://www.example.com/feed?json")
```
#### Load JSON document from string.
```go
s :=`{
"name":"John",
"age":31,
"city":"New York"
}`
doc, err := jsonquery.Parse(strings.NewReader(s))
```
#### Load JSON document from io.Reader.
```go
f, err := os.Open("./books.json")
doc, err := jsonquery.Parse(f)
```
#### Find authors of all books in the store.
```go
list := jsonquery.Find(doc, "store/book/*/author")
// or equal to
list := jsonquery.Find(doc, "//author")
```
#### Find the third book.
```go
book := jsonquery.Find(doc, "//book/*[3]")
```
#### Find the last book.
```go
book := jsonquery.Find(doc, "//book/*[last()]")
```
#### Find all books with isbn number.
```go
list := jsonquery.Find(doc, "//book/*[isbn]")
```
#### Find all books cheapier than 10.
```go
list := jsonquery.Find(doc, "//book/*[price<10]")
```
Quick Tutorial
===
```go
func main() {
s := `{
"name": "John",
"age" : 26,
"address" : {
"streetAddress": "naist street",
"city" : "Nara",
"postalCode" : "630-0192"
},
"phoneNumbers": [
{
"type" : "iPhone",
"number": "0123-4567-8888"
},
{
"type" : "home",
"number": "0123-4567-8910"
}
]
}`
doc, _ := jsonquery.Parse(strings.NewReader(s))
name := jsonquery.FindOne(doc, "name")
fmt.Printf("name: %s\n", name.InnerText())
var a []string
for _, n := range jsonquery.Find(doc, "phoneNumbers/*/number") {
a = append(a, n.InnerText())
}
fmt.Printf("phone number: %s\n", strings.Join(a, ","))
if n := jsonquery.FindOne(doc, "address/streetAddress"); n != nil {
fmt.Printf("address: %s\n", n.InnerText())
}
}
```
Implement Principle
===
If you are familiar with XPath and XML, you can quick start to known how
write your XPath expression.
```json
{
"name":"John",
"age":30,
"cars": [
{ "name":"Ford", "models":[ "Fiesta", "Focus", "Mustang" ] },
{ "name":"BMW", "models":[ "320", "X3", "X5" ] },
{ "name":"Fiat", "models":[ "500", "Panda" ] }
]
}
```
The above JSON document will be convert to similar to XML document by the *JSONQuery*, like below:
```XML
<name>John</name>
<age>30</age>
<cars>
<element>
<name>Ford</name>
<models>
<element>Fiesta</element>
<element>Focus</element>
<element>Mustang</element>
</models>
</element>
<element>
<name>BMW</name>
<models>
<element>320</element>
<element>X3</element>
<element>X5</element>
</models>
</element>
<element>
<name>Fiat</name>
<models>
<element>500</element>
<element>Panda</element>
</models>
</element>
</cars>
```
Notes: `element` is empty element that have no any name.
List of supported XPath query packages
===
|Name |Description |
|--------------------------|----------------|
|[htmlquery](https://github.com/antchfx/htmlquery) | XPath query package for the HTML document|
|[xmlquery](https://github.com/antchfx/xmlquery) | XPath query package for the XML document|
|[jsonquery](https://github.com/antchfx/jsonquery) | XPath query package for the JSON document|

View file

@ -1,36 +0,0 @@
{
"store": {
"book": [
{
"category": "reference",
"author": "Nigel Rees",
"title": "Sayings of the Century",
"price": 8.95
},
{
"category": "fiction",
"author": "Evelyn Waugh",
"title": "Sword of Honour",
"price": 12.99
},
{
"category": "fiction",
"author": "Herman Melville",
"title": "Moby Dick",
"isbn": "0-553-21311-3",
"price": 8.99
},
{
"category": "fiction",
"author": "J. R. R. Tolkien",
"title": "The Lord of the Rings",
"isbn": "0-395-19395-8",
"price": 22.99
}
],
"bicycle": {
"color": "red",
"price": 19.95
}
}
}

View file

@ -1,157 +0,0 @@
package jsonquery
import (
"bytes"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"sort"
"strconv"
)
// A NodeType is the type of a Node.
type NodeType uint
const (
// DocumentNode is a document object that, as the root of the document tree,
// provides access to the entire XML document.
DocumentNode NodeType = iota
// ElementNode is an element.
ElementNode
// TextNode is the text content of a node.
TextNode
)
// A Node consists of a NodeType and some Data (tag name for
// element nodes, content for text) and are part of a tree of Nodes.
type Node struct {
Parent, PrevSibling, NextSibling, FirstChild, LastChild *Node
Type NodeType
Data string
level int
}
// ChildNodes gets all child nodes of the node.
func (n *Node) ChildNodes() []*Node {
var a []*Node
for nn := n.FirstChild; nn != nil; nn = nn.NextSibling {
a = append(a, nn)
}
return a
}
// InnerText gets the value of the node and all its child nodes.
func (n *Node) InnerText() string {
var output func(*bytes.Buffer, *Node)
output = func(buf *bytes.Buffer, n *Node) {
if n.Type == TextNode {
buf.WriteString(n.Data)
return
}
for child := n.FirstChild; child != nil; child = child.NextSibling {
output(buf, child)
}
}
var buf bytes.Buffer
output(&buf, n)
return buf.String()
}
// SelectElement finds the first of child elements with the
// specified name.
func (n *Node) SelectElement(name string) *Node {
for nn := n.FirstChild; nn != nil; nn = nn.NextSibling {
if nn.Data == name {
return nn
}
}
return nil
}
// LoadURL loads the JSON document from the specified URL.
func LoadURL(url string) (*Node, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return Parse(resp.Body)
}
func parseValue(x interface{}, top *Node, level int) {
addNode := func(n *Node) {
if n.level == top.level {
top.NextSibling = n
n.PrevSibling = top
n.Parent = top.Parent
if top.Parent != nil {
top.Parent.LastChild = n
}
} else if n.level > top.level {
n.Parent = top
if top.FirstChild == nil {
top.FirstChild = n
top.LastChild = n
} else {
t := top.LastChild
t.NextSibling = n
n.PrevSibling = t
top.LastChild = n
}
}
}
switch v := x.(type) {
case []interface{}:
for _, vv := range v {
n := &Node{Type: ElementNode, level: level}
addNode(n)
parseValue(vv, n, level+1)
}
case map[string]interface{}:
// The Gos map iteration order is random.
// (https://blog.golang.org/go-maps-in-action#Iteration-order)
var keys []string
for key := range v {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
n := &Node{Data: key, Type: ElementNode, level: level}
addNode(n)
parseValue(v[key], n, level+1)
}
case string:
n := &Node{Data: v, Type: TextNode, level: level}
addNode(n)
case float64:
s := strconv.FormatFloat(v, 'f', -1, 64)
n := &Node{Data: s, Type: TextNode, level: level}
addNode(n)
case bool:
s := strconv.FormatBool(v)
n := &Node{Data: s, Type: TextNode, level: level}
addNode(n)
}
}
func parse(b []byte) (*Node, error) {
var v interface{}
if err := json.Unmarshal(b, &v); err != nil {
return nil, err
}
doc := &Node{Type: DocumentNode}
parseValue(v, doc, 1)
return doc, nil
}
// Parse JSON document.
func Parse(r io.Reader) (*Node, error) {
b, err := ioutil.ReadAll(r)
if err != nil {
return nil, err
}
return parse(b)
}

View file

@ -1,149 +0,0 @@
package jsonquery
import (
"fmt"
"github.com/antchfx/xpath"
)
var _ xpath.NodeNavigator = &NodeNavigator{}
// CreateXPathNavigator creates a new xpath.NodeNavigator for the specified html.Node.
func CreateXPathNavigator(top *Node) *NodeNavigator {
return &NodeNavigator{cur: top, root: top}
}
// Find searches the Node that matches by the specified XPath expr.
func Find(top *Node, expr string) []*Node {
exp, err := xpath.Compile(expr)
if err != nil {
panic(err)
}
t := exp.Select(CreateXPathNavigator(top))
var elems []*Node
for t.MoveNext() {
elems = append(elems, (t.Current().(*NodeNavigator)).cur)
}
return elems
}
// FindOne searches the Node that matches by the specified XPath expr,
// and returns first element of matched.
func FindOne(top *Node, expr string) *Node {
exp, err := xpath.Compile(expr)
if err != nil {
panic(err)
}
t := exp.Select(CreateXPathNavigator(top))
var elem *Node
if t.MoveNext() {
elem = (t.Current().(*NodeNavigator)).cur
}
return elem
}
// NodeNavigator is for navigating JSON document.
type NodeNavigator struct {
root, cur *Node
}
func (a *NodeNavigator) Current() *Node {
return a.cur
}
func (a *NodeNavigator) NodeType() xpath.NodeType {
switch a.cur.Type {
case TextNode:
return xpath.TextNode
case DocumentNode:
return xpath.RootNode
case ElementNode:
return xpath.ElementNode
default:
panic(fmt.Sprintf("unknown node type %v", a.cur.Type))
}
}
func (a *NodeNavigator) LocalName() string {
return a.cur.Data
}
func (a *NodeNavigator) Prefix() string {
return ""
}
func (a *NodeNavigator) Value() string {
switch a.cur.Type {
case ElementNode:
return a.cur.InnerText()
case TextNode:
return a.cur.Data
}
return ""
}
func (a *NodeNavigator) Copy() xpath.NodeNavigator {
n := *a
return &n
}
func (a *NodeNavigator) MoveToRoot() {
a.cur = a.root
}
func (a *NodeNavigator) MoveToParent() bool {
if n := a.cur.Parent; n != nil {
a.cur = n
return true
}
return false
}
func (x *NodeNavigator) MoveToNextAttribute() bool {
return false
}
func (a *NodeNavigator) MoveToChild() bool {
if n := a.cur.FirstChild; n != nil {
a.cur = n
return true
}
return false
}
func (a *NodeNavigator) MoveToFirst() bool {
for n := a.cur.PrevSibling; n != nil; n = n.PrevSibling {
a.cur = n
}
return true
}
func (a *NodeNavigator) String() string {
return a.Value()
}
func (a *NodeNavigator) MoveToNext() bool {
if n := a.cur.NextSibling; n != nil {
a.cur = n
return true
}
return false
}
func (a *NodeNavigator) MoveToPrevious() bool {
if n := a.cur.PrevSibling; n != nil {
a.cur = n
return true
}
return false
}
func (a *NodeNavigator) MoveTo(other xpath.NodeNavigator) bool {
node, ok := other.(*NodeNavigator)
if !ok || node.root != a.root {
return false
}
a.cur = node.cur
return true
}

View file

@ -1,32 +0,0 @@
# vscode
.vscode
debug
*.test
./build
# Compiled Object files, Static and Dynamic libs (Shared Objects)
*.o
*.a
*.so
# Folders
_obj
_test
# Architecture specific extensions/prefixes
*.[568vq]
[568vq].out
*.cgo1.go
*.cgo2.c
_cgo_defun.c
_cgo_gotypes.go
_cgo_export.*
_testmain.go
*.exe
*.test
*.prof

View file

@ -1,12 +0,0 @@
language: go
go:
- 1.6
- 1.9
- '1.10'
install:
- go get github.com/mattn/goveralls
script:
- $HOME/gopath/bin/goveralls -service=travis-ci

View file

@ -1,17 +0,0 @@
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View file

@ -1,167 +0,0 @@
XPath
====
[![GoDoc](https://godoc.org/github.com/antchfx/xpath?status.svg)](https://godoc.org/github.com/antchfx/xpath)
[![Coverage Status](https://coveralls.io/repos/github/antchfx/xpath/badge.svg?branch=master)](https://coveralls.io/github/antchfx/xpath?branch=master)
[![Build Status](https://travis-ci.org/antchfx/xpath.svg?branch=master)](https://travis-ci.org/antchfx/xpath)
[![Go Report Card](https://goreportcard.com/badge/github.com/antchfx/xpath)](https://goreportcard.com/report/github.com/antchfx/xpath)
XPath is Go package provides selecting nodes from XML, HTML or other documents using XPath expression.
Implementation
===
- [htmlquery](https://github.com/antchfx/htmlquery) - an XPath query package for HTML document
- [xmlquery](https://github.com/antchfx/xmlquery) - an XPath query package for XML document.
- [jsonquery](https://github.com/antchfx/jsonquery) - an XPath query package for JSON document
Supported Features
===
#### The basic XPath patterns.
> The basic XPath patterns cover 90% of the cases that most stylesheets will need.
- `node` : Selects all child elements with nodeName of node.
- `*` : Selects all child elements.
- `@attr` : Selects the attribute attr.
- `@*` : Selects all attributes.
- `node()` : Matches an org.w3c.dom.Node.
- `text()` : Matches a org.w3c.dom.Text node.
- `comment()` : Matches a comment.
- `.` : Selects the current node.
- `..` : Selects the parent of current node.
- `/` : Selects the document node.
- `a[expr]` : Select only those nodes matching a which also satisfy the expression expr.
- `a[n]` : Selects the nth matching node matching a When a filter's expression is a number, XPath selects based on position.
- `a/b` : For each node matching a, add the nodes matching b to the result.
- `a//b` : For each node matching a, add the descendant nodes matching b to the result.
- `//b` : Returns elements in the entire document matching b.
- `a|b` : All nodes matching a or b, union operation(not boolean or).
- `(a, b, c)` : Evaluates each of its operands and concatenates the resulting sequences, in order, into a single result sequence
#### Node Axes
- `child::*` : The child axis selects children of the current node.
- `descendant::*` : The descendant axis selects descendants of the current node. It is equivalent to '//'.
- `descendant-or-self::*` : Selects descendants including the current node.
- `attribute::*` : Selects attributes of the current element. It is equivalent to @*
- `following-sibling::*` : Selects nodes after the current node.
- `preceding-sibling::*` : Selects nodes before the current node.
- `following::*` : Selects the first matching node following in document order, excluding descendants.
- `preceding::*` : Selects the first matching node preceding in document order, excluding ancestors.
- `parent::*` : Selects the parent if it matches. The '..' pattern from the core is equivalent to 'parent::node()'.
- `ancestor::*` : Selects matching ancestors.
- `ancestor-or-self::*` : Selects ancestors including the current node.
- `self::*` : Selects the current node. '.' is equivalent to 'self::node()'.
#### Expressions
The gxpath supported three types: number, boolean, string.
- `path` : Selects nodes based on the path.
- `a = b` : Standard comparisons.
* a = b True if a equals b.
* a != b True if a is not equal to b.
* a < b True if a is less than b.
* a <= b True if a is less than or equal to b.
* a > b True if a is greater than b.
* a >= b True if a is greater than or equal to b.
- `a + b` : Arithmetic expressions.
* `- a` Unary minus
* a + b Add
* a - b Substract
* a * b Multiply
* a div b Divide
* a mod b Floating point mod, like Java.
- `a or b` : Boolean `or` operation.
- `a and b` : Boolean `and` operation.
- `(expr)` : Parenthesized expressions.
- `fun(arg1, ..., argn)` : Function calls:
| Function | Supported |
| --- | --- |
`boolean()`| ✓ |
`ceiling()`| ✓ |
`choose()`| ✗ |
`concat()`| ✓ |
`contains()`| ✓ |
`count()`| ✓ |
`current()`| ✗ |
`document()`| ✗ |
`element-available()`| ✗ |
`ends-with()`| ✓ |
`false()`| ✓ |
`floor()`| ✓ |
`format-number()`| ✗ |
`function-available()`| ✗ |
`generate-id()`| ✗ |
`id()`| ✗ |
`key()`| ✗ |
`lang()`| ✗ |
`last()`| ✓ |
`local-name()`| ✓ |
`name()`| ✓ |
`namespace-uri()`| ✓ |
`normalize-space()`| ✓ |
`not()`| ✓ |
`number()`| ✓ |
`position()`| ✓ |
`round()`| ✓ |
`starts-with()`| ✓ |
`string()`| ✓ |
`string-length()`| ✓ |
`substring()`| ✓ |
`substring-after()`| ✓ |
`substring-before()`| ✓ |
`sum()`| ✓ |
`system-property()`| ✗ |
`translate()`| ✓ |
`true()`| ✓ |
`unparsed-entity-url()` | ✗ |
Changelogs
===
2019-01-29
- improvement `normalize-space` function. [#32](https://github.com/antchfx/xpath/issues/32)
2018-12-07
- supports XPath 2.0 Sequence expressions. [#30](https://github.com/antchfx/xpath/pull/30) by [@minherz](https://github.com/minherz).

View file

@ -1,483 +0,0 @@
package xpath
import (
"errors"
"fmt"
)
type flag int
const (
noneFlag flag = iota
filterFlag
)
// builder provides building an XPath expressions.
type builder struct {
depth int
flag flag
firstInput query
}
// axisPredicate creates a predicate to predicating for this axis node.
func axisPredicate(root *axisNode) func(NodeNavigator) bool {
// get current axix node type.
typ := ElementNode
switch root.AxeType {
case "attribute":
typ = AttributeNode
case "self", "parent":
typ = allNode
default:
switch root.Prop {
case "comment":
typ = CommentNode
case "text":
typ = TextNode
// case "processing-instruction":
// typ = ProcessingInstructionNode
case "node":
typ = allNode
}
}
nametest := root.LocalName != "" || root.Prefix != ""
predicate := func(n NodeNavigator) bool {
if typ == n.NodeType() || typ == allNode || typ == TextNode {
if nametest {
if root.LocalName == n.LocalName() && root.Prefix == n.Prefix() {
return true
}
} else {
return true
}
}
return false
}
return predicate
}
// processAxisNode processes a query for the XPath axis node.
func (b *builder) processAxisNode(root *axisNode) (query, error) {
var (
err error
qyInput query
qyOutput query
predicate = axisPredicate(root)
)
if root.Input == nil {
qyInput = &contextQuery{}
} else {
if root.AxeType == "child" && (root.Input.Type() == nodeAxis) {
if input := root.Input.(*axisNode); input.AxeType == "descendant-or-self" {
var qyGrandInput query
if input.Input != nil {
qyGrandInput, _ = b.processNode(input.Input)
} else {
qyGrandInput = &contextQuery{}
}
qyOutput = &descendantQuery{Input: qyGrandInput, Predicate: predicate, Self: true}
return qyOutput, nil
}
}
qyInput, err = b.processNode(root.Input)
if err != nil {
return nil, err
}
}
switch root.AxeType {
case "ancestor":
qyOutput = &ancestorQuery{Input: qyInput, Predicate: predicate}
case "ancestor-or-self":
qyOutput = &ancestorQuery{Input: qyInput, Predicate: predicate, Self: true}
case "attribute":
qyOutput = &attributeQuery{Input: qyInput, Predicate: predicate}
case "child":
filter := func(n NodeNavigator) bool {
v := predicate(n)
switch root.Prop {
case "text":
v = v && n.NodeType() == TextNode
case "node":
v = v && (n.NodeType() == ElementNode || n.NodeType() == TextNode)
case "comment":
v = v && n.NodeType() == CommentNode
}
return v
}
qyOutput = &childQuery{Input: qyInput, Predicate: filter}
case "descendant":
qyOutput = &descendantQuery{Input: qyInput, Predicate: predicate}
case "descendant-or-self":
qyOutput = &descendantQuery{Input: qyInput, Predicate: predicate, Self: true}
case "following":
qyOutput = &followingQuery{Input: qyInput, Predicate: predicate}
case "following-sibling":
qyOutput = &followingQuery{Input: qyInput, Predicate: predicate, Sibling: true}
case "parent":
qyOutput = &parentQuery{Input: qyInput, Predicate: predicate}
case "preceding":
qyOutput = &precedingQuery{Input: qyInput, Predicate: predicate}
case "preceding-sibling":
qyOutput = &precedingQuery{Input: qyInput, Predicate: predicate, Sibling: true}
case "self":
qyOutput = &selfQuery{Input: qyInput, Predicate: predicate}
case "namespace":
// haha,what will you do someting??
default:
err = fmt.Errorf("unknown axe type: %s", root.AxeType)
return nil, err
}
return qyOutput, nil
}
// processFilterNode builds query for the XPath filter predicate.
func (b *builder) processFilterNode(root *filterNode) (query, error) {
b.flag |= filterFlag
qyInput, err := b.processNode(root.Input)
if err != nil {
return nil, err
}
qyCond, err := b.processNode(root.Condition)
if err != nil {
return nil, err
}
qyOutput := &filterQuery{Input: qyInput, Predicate: qyCond}
return qyOutput, nil
}
// processFunctionNode processes query for the XPath function node.
func (b *builder) processFunctionNode(root *functionNode) (query, error) {
var qyOutput query
switch root.FuncName {
case "starts-with":
arg1, err := b.processNode(root.Args[0])
if err != nil {
return nil, err
}
arg2, err := b.processNode(root.Args[1])
if err != nil {
return nil, err
}
qyOutput = &functionQuery{Input: b.firstInput, Func: startwithFunc(arg1, arg2)}
case "ends-with":
arg1, err := b.processNode(root.Args[0])
if err != nil {
return nil, err
}
arg2, err := b.processNode(root.Args[1])
if err != nil {
return nil, err
}
qyOutput = &functionQuery{Input: b.firstInput, Func: endwithFunc(arg1, arg2)}
case "contains":
arg1, err := b.processNode(root.Args[0])
if err != nil {
return nil, err
}
arg2, err := b.processNode(root.Args[1])
if err != nil {
return nil, err
}
qyOutput = &functionQuery{Input: b.firstInput, Func: containsFunc(arg1, arg2)}
case "substring":
//substring( string , start [, length] )
if len(root.Args) < 2 {
return nil, errors.New("xpath: substring function must have at least two parameter")
}
var (
arg1, arg2, arg3 query
err error
)
if arg1, err = b.processNode(root.Args[0]); err != nil {
return nil, err
}
if arg2, err = b.processNode(root.Args[1]); err != nil {
return nil, err
}
if len(root.Args) == 3 {
if arg3, err = b.processNode(root.Args[2]); err != nil {
return nil, err
}
}
qyOutput = &functionQuery{Input: b.firstInput, Func: substringFunc(arg1, arg2, arg3)}
case "substring-before", "substring-after":
//substring-xxxx( haystack, needle )
if len(root.Args) != 2 {
return nil, errors.New("xpath: substring-before function must have two parameters")
}
var (
arg1, arg2 query
err error
)
if arg1, err = b.processNode(root.Args[0]); err != nil {
return nil, err
}
if arg2, err = b.processNode(root.Args[1]); err != nil {
return nil, err
}
qyOutput = &functionQuery{
Input: b.firstInput,
Func: substringIndFunc(arg1, arg2, root.FuncName == "substring-after"),
}
case "string-length":
// string-length( [string] )
if len(root.Args) < 1 {
return nil, errors.New("xpath: string-length function must have at least one parameter")
}
arg1, err := b.processNode(root.Args[0])
if err != nil {
return nil, err
}
qyOutput = &functionQuery{Input: b.firstInput, Func: stringLengthFunc(arg1)}
case "normalize-space":
if len(root.Args) == 0 {
return nil, errors.New("xpath: normalize-space function must have at least one parameter")
}
argQuery, err := b.processNode(root.Args[0])
if err != nil {
return nil, err
}
qyOutput = &functionQuery{Input: argQuery, Func: normalizespaceFunc}
case "translate":
//translate( string , string, string )
if len(root.Args) != 3 {
return nil, errors.New("xpath: translate function must have three parameters")
}
var (
arg1, arg2, arg3 query
err error
)
if arg1, err = b.processNode(root.Args[0]); err != nil {
return nil, err
}
if arg2, err = b.processNode(root.Args[1]); err != nil {
return nil, err
}
if arg3, err = b.processNode(root.Args[2]); err != nil {
return nil, err
}
qyOutput = &functionQuery{Input: b.firstInput, Func: translateFunc(arg1, arg2, arg3)}
case "not":
if len(root.Args) == 0 {
return nil, errors.New("xpath: not function must have at least one parameter")
}
argQuery, err := b.processNode(root.Args[0])
if err != nil {
return nil, err
}
qyOutput = &functionQuery{Input: argQuery, Func: notFunc}
case "name", "local-name", "namespace-uri":
inp := b.firstInput
if len(root.Args) > 1 {
return nil, fmt.Errorf("xpath: %s function must have at most one parameter", root.FuncName)
}
if len(root.Args) == 1 {
argQuery, err := b.processNode(root.Args[0])
if err != nil {
return nil, err
}
inp = argQuery
}
f := &functionQuery{Input: inp}
switch root.FuncName {
case "name":
f.Func = nameFunc
case "local-name":
f.Func = localNameFunc
case "namespace-uri":
f.Func = namespaceFunc
}
qyOutput = f
case "true", "false":
val := root.FuncName == "true"
qyOutput = &functionQuery{
Input: b.firstInput,
Func: func(_ query, _ iterator) interface{} {
return val
},
}
case "last":
qyOutput = &functionQuery{Input: b.firstInput, Func: lastFunc}
case "position":
qyOutput = &functionQuery{Input: b.firstInput, Func: positionFunc}
case "boolean", "number", "string":
inp := b.firstInput
if len(root.Args) > 1 {
return nil, fmt.Errorf("xpath: %s function must have at most one parameter", root.FuncName)
}
if len(root.Args) == 1 {
argQuery, err := b.processNode(root.Args[0])
if err != nil {
return nil, err
}
inp = argQuery
}
f := &functionQuery{Input: inp}
switch root.FuncName {
case "boolean":
f.Func = booleanFunc
case "string":
f.Func = stringFunc
case "number":
f.Func = numberFunc
}
qyOutput = f
case "count":
//if b.firstInput == nil {
// return nil, errors.New("xpath: expression must evaluate to node-set")
//}
if len(root.Args) == 0 {
return nil, fmt.Errorf("xpath: count(node-sets) function must with have parameters node-sets")
}
argQuery, err := b.processNode(root.Args[0])
if err != nil {
return nil, err
}
qyOutput = &functionQuery{Input: argQuery, Func: countFunc}
case "sum":
if len(root.Args) == 0 {
return nil, fmt.Errorf("xpath: sum(node-sets) function must with have parameters node-sets")
}
argQuery, err := b.processNode(root.Args[0])
if err != nil {
return nil, err
}
qyOutput = &functionQuery{Input: argQuery, Func: sumFunc}
case "ceiling", "floor", "round":
if len(root.Args) == 0 {
return nil, fmt.Errorf("xpath: ceiling(node-sets) function must with have parameters node-sets")
}
argQuery, err := b.processNode(root.Args[0])
if err != nil {
return nil, err
}
f := &functionQuery{Input: argQuery}
switch root.FuncName {
case "ceiling":
f.Func = ceilingFunc
case "floor":
f.Func = floorFunc
case "round":
f.Func = roundFunc
}
qyOutput = f
case "concat":
if len(root.Args) < 2 {
return nil, fmt.Errorf("xpath: concat() must have at least two arguments")
}
var args []query
for _, v := range root.Args {
q, err := b.processNode(v)
if err != nil {
return nil, err
}
args = append(args, q)
}
qyOutput = &functionQuery{Input: b.firstInput, Func: concatFunc(args...)}
default:
return nil, fmt.Errorf("not yet support this function %s()", root.FuncName)
}
return qyOutput, nil
}
func (b *builder) processOperatorNode(root *operatorNode) (query, error) {
left, err := b.processNode(root.Left)
if err != nil {
return nil, err
}
right, err := b.processNode(root.Right)
if err != nil {
return nil, err
}
var qyOutput query
switch root.Op {
case "+", "-", "div", "mod": // Numeric operator
var exprFunc func(interface{}, interface{}) interface{}
switch root.Op {
case "+":
exprFunc = plusFunc
case "-":
exprFunc = minusFunc
case "div":
exprFunc = divFunc
case "mod":
exprFunc = modFunc
}
qyOutput = &numericQuery{Left: left, Right: right, Do: exprFunc}
case "=", ">", ">=", "<", "<=", "!=":
var exprFunc func(iterator, interface{}, interface{}) interface{}
switch root.Op {
case "=":
exprFunc = eqFunc
case ">":
exprFunc = gtFunc
case ">=":
exprFunc = geFunc
case "<":
exprFunc = ltFunc
case "<=":
exprFunc = leFunc
case "!=":
exprFunc = neFunc
}
qyOutput = &logicalQuery{Left: left, Right: right, Do: exprFunc}
case "or", "and":
isOr := false
if root.Op == "or" {
isOr = true
}
qyOutput = &booleanQuery{Left: left, Right: right, IsOr: isOr}
case "|":
qyOutput = &unionQuery{Left: left, Right: right}
}
return qyOutput, nil
}
func (b *builder) processNode(root node) (q query, err error) {
if b.depth = b.depth + 1; b.depth > 1024 {
err = errors.New("the xpath expressions is too complex")
return
}
switch root.Type() {
case nodeConstantOperand:
n := root.(*operandNode)
q = &constantQuery{Val: n.Val}
case nodeRoot:
q = &contextQuery{Root: true}
case nodeAxis:
q, err = b.processAxisNode(root.(*axisNode))
b.firstInput = q
case nodeFilter:
q, err = b.processFilterNode(root.(*filterNode))
case nodeFunction:
q, err = b.processFunctionNode(root.(*functionNode))
case nodeOperator:
q, err = b.processOperatorNode(root.(*operatorNode))
}
return
}
// build builds a specified XPath expressions expr.
func build(expr string) (q query, err error) {
defer func() {
if e := recover(); e != nil {
switch x := e.(type) {
case string:
err = errors.New(x)
case error:
err = x
default:
err = errors.New("unknown panic")
}
}
}()
root := parse(expr)
b := &builder{}
return b.processNode(root)
}

View file

@ -1,484 +0,0 @@
package xpath
import (
"errors"
"fmt"
"math"
"regexp"
"strconv"
"strings"
)
// The XPath function list.
func predicate(q query) func(NodeNavigator) bool {
type Predicater interface {
Test(NodeNavigator) bool
}
if p, ok := q.(Predicater); ok {
return p.Test
}
return func(NodeNavigator) bool { return true }
}
// positionFunc is a XPath Node Set functions position().
func positionFunc(q query, t iterator) interface{} {
var (
count = 1
node = t.Current()
)
test := predicate(q)
for node.MoveToPrevious() {
if test(node) {
count++
}
}
return float64(count)
}
// lastFunc is a XPath Node Set functions last().
func lastFunc(q query, t iterator) interface{} {
var (
count = 0
node = t.Current()
)
node.MoveToFirst()
test := predicate(q)
for {
if test(node) {
count++
}
if !node.MoveToNext() {
break
}
}
return float64(count)
}
// countFunc is a XPath Node Set functions count(node-set).
func countFunc(q query, t iterator) interface{} {
var count = 0
test := predicate(q)
switch typ := q.Evaluate(t).(type) {
case query:
for node := typ.Select(t); node != nil; node = typ.Select(t) {
if test(node) {
count++
}
}
}
return float64(count)
}
// sumFunc is a XPath Node Set functions sum(node-set).
func sumFunc(q query, t iterator) interface{} {
var sum float64
switch typ := q.Evaluate(t).(type) {
case query:
for node := typ.Select(t); node != nil; node = typ.Select(t) {
if v, err := strconv.ParseFloat(node.Value(), 64); err == nil {
sum += v
}
}
case float64:
sum = typ
case string:
v, err := strconv.ParseFloat(typ, 64)
if err != nil {
panic(errors.New("sum() function argument type must be a node-set or number"))
}
sum = v
}
return sum
}
func asNumber(t iterator, o interface{}) float64 {
switch typ := o.(type) {
case query:
node := typ.Select(t)
if node == nil {
return float64(0)
}
if v, err := strconv.ParseFloat(node.Value(), 64); err == nil {
return v
}
case float64:
return typ
case string:
v, err := strconv.ParseFloat(typ, 64)
if err != nil {
panic(errors.New("ceiling() function argument type must be a node-set or number"))
}
return v
}
return 0
}
// ceilingFunc is a XPath Node Set functions ceiling(node-set).
func ceilingFunc(q query, t iterator) interface{} {
val := asNumber(t, q.Evaluate(t))
return math.Ceil(val)
}
// floorFunc is a XPath Node Set functions floor(node-set).
func floorFunc(q query, t iterator) interface{} {
val := asNumber(t, q.Evaluate(t))
return math.Floor(val)
}
// roundFunc is a XPath Node Set functions round(node-set).
func roundFunc(q query, t iterator) interface{} {
val := asNumber(t, q.Evaluate(t))
//return math.Round(val)
return round(val)
}
// nameFunc is a XPath functions name([node-set]).
func nameFunc(q query, t iterator) interface{} {
v := q.Select(t)
if v == nil {
return ""
}
ns := v.Prefix()
if ns == "" {
return v.LocalName()
}
return ns + ":" + v.LocalName()
}
// localNameFunc is a XPath functions local-name([node-set]).
func localNameFunc(q query, t iterator) interface{} {
v := q.Select(t)
if v == nil {
return ""
}
return v.LocalName()
}
// namespaceFunc is a XPath functions namespace-uri([node-set]).
func namespaceFunc(q query, t iterator) interface{} {
v := q.Select(t)
if v == nil {
return ""
}
return v.Prefix()
}
func asBool(t iterator, v interface{}) bool {
switch v := v.(type) {
case nil:
return false
case *NodeIterator:
return v.MoveNext()
case bool:
return bool(v)
case float64:
return v != 0
case string:
return v != ""
case query:
return v.Select(t) != nil
default:
panic(fmt.Errorf("unexpected type: %T", v))
}
}
func asString(t iterator, v interface{}) string {
switch v := v.(type) {
case nil:
return ""
case bool:
if v {
return "true"
}
return "false"
case float64:
return strconv.FormatFloat(v, 'g', -1, 64)
case string:
return v
case query:
node := v.Select(t)
if node == nil {
return ""
}
return node.Value()
default:
panic(fmt.Errorf("unexpected type: %T", v))
}
}
// booleanFunc is a XPath functions boolean([node-set]).
func booleanFunc(q query, t iterator) interface{} {
v := q.Evaluate(t)
return asBool(t, v)
}
// numberFunc is a XPath functions number([node-set]).
func numberFunc(q query, t iterator) interface{} {
v := q.Evaluate(t)
return asNumber(t, v)
}
// stringFunc is a XPath functions string([node-set]).
func stringFunc(q query, t iterator) interface{} {
v := q.Evaluate(t)
return asString(t, v)
}
// startwithFunc is a XPath functions starts-with(string, string).
func startwithFunc(arg1, arg2 query) func(query, iterator) interface{} {
return func(q query, t iterator) interface{} {
var (
m, n string
ok bool
)
switch typ := arg1.Evaluate(t).(type) {
case string:
m = typ
case query:
node := typ.Select(t)
if node == nil {
return false
}
m = node.Value()
default:
panic(errors.New("starts-with() function argument type must be string"))
}
n, ok = arg2.Evaluate(t).(string)
if !ok {
panic(errors.New("starts-with() function argument type must be string"))
}
return strings.HasPrefix(m, n)
}
}
// endwithFunc is a XPath functions ends-with(string, string).
func endwithFunc(arg1, arg2 query) func(query, iterator) interface{} {
return func(q query, t iterator) interface{} {
var (
m, n string
ok bool
)
switch typ := arg1.Evaluate(t).(type) {
case string:
m = typ
case query:
node := typ.Select(t)
if node == nil {
return false
}
m = node.Value()
default:
panic(errors.New("ends-with() function argument type must be string"))
}
n, ok = arg2.Evaluate(t).(string)
if !ok {
panic(errors.New("ends-with() function argument type must be string"))
}
return strings.HasSuffix(m, n)
}
}
// containsFunc is a XPath functions contains(string or @attr, string).
func containsFunc(arg1, arg2 query) func(query, iterator) interface{} {
return func(q query, t iterator) interface{} {
var (
m, n string
ok bool
)
switch typ := arg1.Evaluate(t).(type) {
case string:
m = typ
case query:
node := typ.Select(t)
if node == nil {
return false
}
m = node.Value()
default:
panic(errors.New("contains() function argument type must be string"))
}
n, ok = arg2.Evaluate(t).(string)
if !ok {
panic(errors.New("contains() function argument type must be string"))
}
return strings.Contains(m, n)
}
}
var (
regnewline = regexp.MustCompile(`[\r\n\t]`)
regseqspace = regexp.MustCompile(`\s{2,}`)
)
// normalizespaceFunc is XPath functions normalize-space(string?)
func normalizespaceFunc(q query, t iterator) interface{} {
var m string
switch typ := q.Evaluate(t).(type) {
case string:
m = typ
case query:
node := typ.Select(t)
if node == nil {
return ""
}
m = node.Value()
}
m = strings.TrimSpace(m)
m = regnewline.ReplaceAllString(m, " ")
m = regseqspace.ReplaceAllString(m, " ")
return m
}
// substringFunc is XPath functions substring function returns a part of a given string.
func substringFunc(arg1, arg2, arg3 query) func(query, iterator) interface{} {
return func(q query, t iterator) interface{} {
var m string
switch typ := arg1.Evaluate(t).(type) {
case string:
m = typ
case query:
node := typ.Select(t)
if node == nil {
return ""
}
m = node.Value()
}
var start, length float64
var ok bool
if start, ok = arg2.Evaluate(t).(float64); !ok {
panic(errors.New("substring() function first argument type must be int"))
} else if start < 1 {
panic(errors.New("substring() function first argument type must be >= 1"))
}
start--
if arg3 != nil {
if length, ok = arg3.Evaluate(t).(float64); !ok {
panic(errors.New("substring() function second argument type must be int"))
}
}
if (len(m) - int(start)) < int(length) {
panic(errors.New("substring() function start and length argument out of range"))
}
if length > 0 {
return m[int(start):int(length+start)]
}
return m[int(start):]
}
}
// substringIndFunc is XPath functions substring-before/substring-after function returns a part of a given string.
func substringIndFunc(arg1, arg2 query, after bool) func(query, iterator) interface{} {
return func(q query, t iterator) interface{} {
var str string
switch v := arg1.Evaluate(t).(type) {
case string:
str = v
case query:
node := v.Select(t)
if node == nil {
return ""
}
str = node.Value()
}
var word string
switch v := arg2.Evaluate(t).(type) {
case string:
word = v
case query:
node := v.Select(t)
if node == nil {
return ""
}
word = node.Value()
}
if word == "" {
return ""
}
i := strings.Index(str, word)
if i < 0 {
return ""
}
if after {
return str[i+len(word):]
}
return str[:i]
}
}
// stringLengthFunc is XPATH string-length( [string] ) function that returns a number
// equal to the number of characters in a given string.
func stringLengthFunc(arg1 query) func(query, iterator) interface{} {
return func(q query, t iterator) interface{} {
switch v := arg1.Evaluate(t).(type) {
case string:
return float64(len(v))
case query:
node := v.Select(t)
if node == nil {
break
}
return float64(len(node.Value()))
}
return float64(0)
}
}
// translateFunc is XPath functions translate() function returns a replaced string.
func translateFunc(arg1, arg2, arg3 query) func(query, iterator) interface{} {
return func(q query, t iterator) interface{} {
str := asString(t, arg1.Evaluate(t))
src := asString(t, arg2.Evaluate(t))
dst := asString(t, arg3.Evaluate(t))
var replace []string
for i, s := range src {
d := ""
if i < len(dst) {
d = string(dst[i])
}
replace = append(replace, string(s), d)
}
return strings.NewReplacer(replace...).Replace(str)
}
}
// notFunc is XPATH functions not(expression) function operation.
func notFunc(q query, t iterator) interface{} {
switch v := q.Evaluate(t).(type) {
case bool:
return !v
case query:
node := v.Select(t)
return node == nil
default:
return false
}
}
// concatFunc is the concat function concatenates two or more
// strings and returns the resulting string.
// concat( string1 , string2 [, stringn]* )
func concatFunc(args ...query) func(query, iterator) interface{} {
return func(q query, t iterator) interface{} {
var a []string
for _, v := range args {
switch v := v.Evaluate(t).(type) {
case string:
a = append(a, v)
case query:
node := v.Select(t)
if node != nil {
a = append(a, node.Value())
}
}
}
return strings.Join(a, "")
}
}

View file

@ -1,9 +0,0 @@
// +build go1.10
package xpath
import "math"
func round(f float64) int {
return int(math.Round(f))
}

View file

@ -1,15 +0,0 @@
// +build !go1.10
package xpath
import "math"
// math.Round() is supported by Go 1.10+,
// This method just compatible for version <1.10.
// https://github.com/golang/go/issues/20100
func round(f float64) int {
if math.Abs(f) < 0.5 {
return 0
}
return int(f + math.Copysign(0.5, f))
}

View file

@ -1,295 +0,0 @@
package xpath
import (
"fmt"
"reflect"
"strconv"
)
// The XPath number operator function list.
// valueType is a return value type.
type valueType int
const (
booleanType valueType = iota
numberType
stringType
nodeSetType
)
func getValueType(i interface{}) valueType {
v := reflect.ValueOf(i)
switch v.Kind() {
case reflect.Float64:
return numberType
case reflect.String:
return stringType
case reflect.Bool:
return booleanType
default:
if _, ok := i.(query); ok {
return nodeSetType
}
}
panic(fmt.Errorf("xpath unknown value type: %v", v.Kind()))
}
type logical func(iterator, string, interface{}, interface{}) bool
var logicalFuncs = [][]logical{
{cmpBooleanBoolean, nil, nil, nil},
{nil, cmpNumericNumeric, cmpNumericString, cmpNumericNodeSet},
{nil, cmpStringNumeric, cmpStringString, cmpStringNodeSet},
{nil, cmpNodeSetNumeric, cmpNodeSetString, cmpNodeSetNodeSet},
}
// number vs number
func cmpNumberNumberF(op string, a, b float64) bool {
switch op {
case "=":
return a == b
case ">":
return a > b
case "<":
return a < b
case ">=":
return a >= b
case "<=":
return a <= b
case "!=":
return a != b
}
return false
}
// string vs string
func cmpStringStringF(op string, a, b string) bool {
switch op {
case "=":
return a == b
case ">":
return a > b
case "<":
return a < b
case ">=":
return a >= b
case "<=":
return a <= b
case "!=":
return a != b
}
return false
}
func cmpBooleanBooleanF(op string, a, b bool) bool {
switch op {
case "or":
return a || b
case "and":
return a && b
}
return false
}
func cmpNumericNumeric(t iterator, op string, m, n interface{}) bool {
a := m.(float64)
b := n.(float64)
return cmpNumberNumberF(op, a, b)
}
func cmpNumericString(t iterator, op string, m, n interface{}) bool {
a := m.(float64)
b := n.(string)
num, err := strconv.ParseFloat(b, 64)
if err != nil {
panic(err)
}
return cmpNumberNumberF(op, a, num)
}
func cmpNumericNodeSet(t iterator, op string, m, n interface{}) bool {
a := m.(float64)
b := n.(query)
for {
node := b.Select(t)
if node == nil {
break
}
num, err := strconv.ParseFloat(node.Value(), 64)
if err != nil {
panic(err)
}
if cmpNumberNumberF(op, a, num) {
return true
}
}
return false
}
func cmpNodeSetNumeric(t iterator, op string, m, n interface{}) bool {
a := m.(query)
b := n.(float64)
for {
node := a.Select(t)
if node == nil {
break
}
num, err := strconv.ParseFloat(node.Value(), 64)
if err != nil {
panic(err)
}
if cmpNumberNumberF(op, num, b) {
return true
}
}
return false
}
func cmpNodeSetString(t iterator, op string, m, n interface{}) bool {
a := m.(query)
b := n.(string)
for {
node := a.Select(t)
if node == nil {
break
}
if cmpStringStringF(op, b, node.Value()) {
return true
}
}
return false
}
func cmpNodeSetNodeSet(t iterator, op string, m, n interface{}) bool {
return false
}
func cmpStringNumeric(t iterator, op string, m, n interface{}) bool {
a := m.(string)
b := n.(float64)
num, err := strconv.ParseFloat(a, 64)
if err != nil {
panic(err)
}
return cmpNumberNumberF(op, b, num)
}
func cmpStringString(t iterator, op string, m, n interface{}) bool {
a := m.(string)
b := n.(string)
return cmpStringStringF(op, a, b)
}
func cmpStringNodeSet(t iterator, op string, m, n interface{}) bool {
a := m.(string)
b := n.(query)
for {
node := b.Select(t)
if node == nil {
break
}
if cmpStringStringF(op, a, node.Value()) {
return true
}
}
return false
}
func cmpBooleanBoolean(t iterator, op string, m, n interface{}) bool {
a := m.(bool)
b := n.(bool)
return cmpBooleanBooleanF(op, a, b)
}
// eqFunc is an `=` operator.
func eqFunc(t iterator, m, n interface{}) interface{} {
t1 := getValueType(m)
t2 := getValueType(n)
return logicalFuncs[t1][t2](t, "=", m, n)
}
// gtFunc is an `>` operator.
func gtFunc(t iterator, m, n interface{}) interface{} {
t1 := getValueType(m)
t2 := getValueType(n)
return logicalFuncs[t1][t2](t, ">", m, n)
}
// geFunc is an `>=` operator.
func geFunc(t iterator, m, n interface{}) interface{} {
t1 := getValueType(m)
t2 := getValueType(n)
return logicalFuncs[t1][t2](t, ">=", m, n)
}
// ltFunc is an `<` operator.
func ltFunc(t iterator, m, n interface{}) interface{} {
t1 := getValueType(m)
t2 := getValueType(n)
return logicalFuncs[t1][t2](t, "<", m, n)
}
// leFunc is an `<=` operator.
func leFunc(t iterator, m, n interface{}) interface{} {
t1 := getValueType(m)
t2 := getValueType(n)
return logicalFuncs[t1][t2](t, "<=", m, n)
}
// neFunc is an `!=` operator.
func neFunc(t iterator, m, n interface{}) interface{} {
t1 := getValueType(m)
t2 := getValueType(n)
return logicalFuncs[t1][t2](t, "!=", m, n)
}
// orFunc is an `or` operator.
var orFunc = func(t iterator, m, n interface{}) interface{} {
t1 := getValueType(m)
t2 := getValueType(n)
return logicalFuncs[t1][t2](t, "or", m, n)
}
func numericExpr(m, n interface{}, cb func(float64, float64) float64) float64 {
typ := reflect.TypeOf(float64(0))
a := reflect.ValueOf(m).Convert(typ)
b := reflect.ValueOf(n).Convert(typ)
return cb(a.Float(), b.Float())
}
// plusFunc is an `+` operator.
var plusFunc = func(m, n interface{}) interface{} {
return numericExpr(m, n, func(a, b float64) float64 {
return a + b
})
}
// minusFunc is an `-` operator.
var minusFunc = func(m, n interface{}) interface{} {
return numericExpr(m, n, func(a, b float64) float64 {
return a - b
})
}
// mulFunc is an `*` operator.
var mulFunc = func(m, n interface{}) interface{} {
return numericExpr(m, n, func(a, b float64) float64 {
return a * b
})
}
// divFunc is an `DIV` operator.
var divFunc = func(m, n interface{}) interface{} {
return numericExpr(m, n, func(a, b float64) float64 {
return a / b
})
}
// modFunc is an 'MOD' operator.
var modFunc = func(m, n interface{}) interface{} {
return numericExpr(m, n, func(a, b float64) float64 {
return float64(int(a) % int(b))
})
}

File diff suppressed because it is too large Load diff

View file

@ -1,824 +0,0 @@
package xpath
import (
"bytes"
"fmt"
"hash/fnv"
"reflect"
)
type iterator interface {
Current() NodeNavigator
}
// An XPath query interface.
type query interface {
// Select traversing iterator returns a query matched node NodeNavigator.
Select(iterator) NodeNavigator
// Evaluate evaluates query and returns values of the current query.
Evaluate(iterator) interface{}
Clone() query
}
// contextQuery is returns current node on the iterator object query.
type contextQuery struct {
count int
Root bool // Moving to root-level node in the current context iterator.
}
func (c *contextQuery) Select(t iterator) (n NodeNavigator) {
if c.count == 0 {
c.count++
n = t.Current().Copy()
if c.Root {
n.MoveToRoot()
}
}
return n
}
func (c *contextQuery) Evaluate(iterator) interface{} {
c.count = 0
return c
}
func (c *contextQuery) Clone() query {
return &contextQuery{count: 0, Root: c.Root}
}
// ancestorQuery is an XPath ancestor node query.(ancestor::*|ancestor-self::*)
type ancestorQuery struct {
iterator func() NodeNavigator
Self bool
Input query
Predicate func(NodeNavigator) bool
}
func (a *ancestorQuery) Select(t iterator) NodeNavigator {
for {
if a.iterator == nil {
node := a.Input.Select(t)
if node == nil {
return nil
}
first := true
a.iterator = func() NodeNavigator {
if first && a.Self {
first = false
if a.Predicate(node) {
return node
}
}
for node.MoveToParent() {
if !a.Predicate(node) {
continue
}
return node
}
return nil
}
}
if node := a.iterator(); node != nil {
return node
}
a.iterator = nil
}
}
func (a *ancestorQuery) Evaluate(t iterator) interface{} {
a.Input.Evaluate(t)
a.iterator = nil
return a
}
func (a *ancestorQuery) Test(n NodeNavigator) bool {
return a.Predicate(n)
}
func (a *ancestorQuery) Clone() query {
return &ancestorQuery{Self: a.Self, Input: a.Input.Clone(), Predicate: a.Predicate}
}
// attributeQuery is an XPath attribute node query.(@*)
type attributeQuery struct {
iterator func() NodeNavigator
Input query
Predicate func(NodeNavigator) bool
}
func (a *attributeQuery) Select(t iterator) NodeNavigator {
for {
if a.iterator == nil {
node := a.Input.Select(t)
if node == nil {
return nil
}
node = node.Copy()
a.iterator = func() NodeNavigator {
for {
onAttr := node.MoveToNextAttribute()
if !onAttr {
return nil
}
if a.Predicate(node) {
return node
}
}
}
}
if node := a.iterator(); node != nil {
return node
}
a.iterator = nil
}
}
func (a *attributeQuery) Evaluate(t iterator) interface{} {
a.Input.Evaluate(t)
a.iterator = nil
return a
}
func (a *attributeQuery) Test(n NodeNavigator) bool {
return a.Predicate(n)
}
func (a *attributeQuery) Clone() query {
return &attributeQuery{Input: a.Input.Clone(), Predicate: a.Predicate}
}
// childQuery is an XPath child node query.(child::*)
type childQuery struct {
posit int
iterator func() NodeNavigator
Input query
Predicate func(NodeNavigator) bool
}
func (c *childQuery) Select(t iterator) NodeNavigator {
for {
if c.iterator == nil {
c.posit = 0
node := c.Input.Select(t)
if node == nil {
return nil
}
node = node.Copy()
first := true
c.iterator = func() NodeNavigator {
for {
if (first && !node.MoveToChild()) || (!first && !node.MoveToNext()) {
return nil
}
first = false
if c.Predicate(node) {
return node
}
}
}
}
if node := c.iterator(); node != nil {
c.posit++
return node
}
c.iterator = nil
}
}
func (c *childQuery) Evaluate(t iterator) interface{} {
c.Input.Evaluate(t)
c.iterator = nil
return c
}
func (c *childQuery) Test(n NodeNavigator) bool {
return c.Predicate(n)
}
func (c *childQuery) Clone() query {
return &childQuery{Input: c.Input.Clone(), Predicate: c.Predicate}
}
// position returns a position of current NodeNavigator.
func (c *childQuery) position() int {
return c.posit
}
// descendantQuery is an XPath descendant node query.(descendant::* | descendant-or-self::*)
type descendantQuery struct {
iterator func() NodeNavigator
posit int
Self bool
Input query
Predicate func(NodeNavigator) bool
}
func (d *descendantQuery) Select(t iterator) NodeNavigator {
for {
if d.iterator == nil {
d.posit = 0
node := d.Input.Select(t)
if node == nil {
return nil
}
node = node.Copy()
level := 0
first := true
d.iterator = func() NodeNavigator {
if first && d.Self {
first = false
if d.Predicate(node) {
return node
}
}
for {
if node.MoveToChild() {
level++
} else {
for {
if level == 0 {
return nil
}
if node.MoveToNext() {
break
}
node.MoveToParent()
level--
}
}
if d.Predicate(node) {
return node
}
}
}
}
if node := d.iterator(); node != nil {
d.posit++
return node
}
d.iterator = nil
}
}
func (d *descendantQuery) Evaluate(t iterator) interface{} {
d.Input.Evaluate(t)
d.iterator = nil
return d
}
func (d *descendantQuery) Test(n NodeNavigator) bool {
return d.Predicate(n)
}
// position returns a position of current NodeNavigator.
func (d *descendantQuery) position() int {
return d.posit
}
func (d *descendantQuery) Clone() query {
return &descendantQuery{Self: d.Self, Input: d.Input.Clone(), Predicate: d.Predicate}
}
// followingQuery is an XPath following node query.(following::*|following-sibling::*)
type followingQuery struct {
iterator func() NodeNavigator
Input query
Sibling bool // The matching sibling node of current node.
Predicate func(NodeNavigator) bool
}
func (f *followingQuery) Select(t iterator) NodeNavigator {
for {
if f.iterator == nil {
node := f.Input.Select(t)
if node == nil {
return nil
}
node = node.Copy()
if f.Sibling {
f.iterator = func() NodeNavigator {
for {
if !node.MoveToNext() {
return nil
}
if f.Predicate(node) {
return node
}
}
}
} else {
var q query // descendant query
f.iterator = func() NodeNavigator {
for {
if q == nil {
for !node.MoveToNext() {
if !node.MoveToParent() {
return nil
}
}
q = &descendantQuery{
Self: true,
Input: &contextQuery{},
Predicate: f.Predicate,
}
t.Current().MoveTo(node)
}
if node := q.Select(t); node != nil {
return node
}
q = nil
}
}
}
}
if node := f.iterator(); node != nil {
return node
}
f.iterator = nil
}
}
func (f *followingQuery) Evaluate(t iterator) interface{} {
f.Input.Evaluate(t)
return f
}
func (f *followingQuery) Test(n NodeNavigator) bool {
return f.Predicate(n)
}
func (f *followingQuery) Clone() query {
return &followingQuery{Input: f.Input.Clone(), Sibling: f.Sibling, Predicate: f.Predicate}
}
// precedingQuery is an XPath preceding node query.(preceding::*)
type precedingQuery struct {
iterator func() NodeNavigator
Input query
Sibling bool // The matching sibling node of current node.
Predicate func(NodeNavigator) bool
}
func (p *precedingQuery) Select(t iterator) NodeNavigator {
for {
if p.iterator == nil {
node := p.Input.Select(t)
if node == nil {
return nil
}
node = node.Copy()
if p.Sibling {
p.iterator = func() NodeNavigator {
for {
for !node.MoveToPrevious() {
return nil
}
if p.Predicate(node) {
return node
}
}
}
} else {
var q query
p.iterator = func() NodeNavigator {
for {
if q == nil {
for !node.MoveToPrevious() {
if !node.MoveToParent() {
return nil
}
}
q = &descendantQuery{
Self: true,
Input: &contextQuery{},
Predicate: p.Predicate,
}
t.Current().MoveTo(node)
}
if node := q.Select(t); node != nil {
return node
}
q = nil
}
}
}
}
if node := p.iterator(); node != nil {
return node
}
p.iterator = nil
}
}
func (p *precedingQuery) Evaluate(t iterator) interface{} {
p.Input.Evaluate(t)
return p
}
func (p *precedingQuery) Test(n NodeNavigator) bool {
return p.Predicate(n)
}
func (p *precedingQuery) Clone() query {
return &precedingQuery{Input: p.Input.Clone(), Sibling: p.Sibling, Predicate: p.Predicate}
}
// parentQuery is an XPath parent node query.(parent::*)
type parentQuery struct {
Input query
Predicate func(NodeNavigator) bool
}
func (p *parentQuery) Select(t iterator) NodeNavigator {
for {
node := p.Input.Select(t)
if node == nil {
return nil
}
node = node.Copy()
if node.MoveToParent() && p.Predicate(node) {
return node
}
}
}
func (p *parentQuery) Evaluate(t iterator) interface{} {
p.Input.Evaluate(t)
return p
}
func (p *parentQuery) Clone() query {
return &parentQuery{Input: p.Input.Clone(), Predicate: p.Predicate}
}
func (p *parentQuery) Test(n NodeNavigator) bool {
return p.Predicate(n)
}
// selfQuery is an Self node query.(self::*)
type selfQuery struct {
Input query
Predicate func(NodeNavigator) bool
}
func (s *selfQuery) Select(t iterator) NodeNavigator {
for {
node := s.Input.Select(t)
if node == nil {
return nil
}
if s.Predicate(node) {
return node
}
}
}
func (s *selfQuery) Evaluate(t iterator) interface{} {
s.Input.Evaluate(t)
return s
}
func (s *selfQuery) Test(n NodeNavigator) bool {
return s.Predicate(n)
}
func (s *selfQuery) Clone() query {
return &selfQuery{Input: s.Input.Clone(), Predicate: s.Predicate}
}
// filterQuery is an XPath query for predicate filter.
type filterQuery struct {
Input query
Predicate query
}
func (f *filterQuery) do(t iterator) bool {
val := reflect.ValueOf(f.Predicate.Evaluate(t))
switch val.Kind() {
case reflect.Bool:
return val.Bool()
case reflect.String:
return len(val.String()) > 0
case reflect.Float64:
pt := float64(getNodePosition(f.Input))
return int(val.Float()) == int(pt)
default:
if q, ok := f.Predicate.(query); ok {
return q.Select(t) != nil
}
}
return false
}
func (f *filterQuery) Select(t iterator) NodeNavigator {
for {
node := f.Input.Select(t)
if node == nil {
return node
}
node = node.Copy()
//fmt.Println(node.LocalName())
t.Current().MoveTo(node)
if f.do(t) {
return node
}
}
}
func (f *filterQuery) Evaluate(t iterator) interface{} {
f.Input.Evaluate(t)
return f
}
func (f *filterQuery) Clone() query {
return &filterQuery{Input: f.Input.Clone(), Predicate: f.Predicate.Clone()}
}
// functionQuery is an XPath function that call a function to returns
// value of current NodeNavigator node.
type functionQuery struct {
Input query // Node Set
Func func(query, iterator) interface{} // The xpath function.
}
func (f *functionQuery) Select(t iterator) NodeNavigator {
return nil
}
// Evaluate call a specified function that will returns the
// following value type: number,string,boolean.
func (f *functionQuery) Evaluate(t iterator) interface{} {
return f.Func(f.Input, t)
}
func (f *functionQuery) Clone() query {
return &functionQuery{Input: f.Input.Clone(), Func: f.Func}
}
// constantQuery is an XPath constant operand.
type constantQuery struct {
Val interface{}
}
func (c *constantQuery) Select(t iterator) NodeNavigator {
return nil
}
func (c *constantQuery) Evaluate(t iterator) interface{} {
return c.Val
}
func (c *constantQuery) Clone() query {
return c
}
// logicalQuery is an XPath logical expression.
type logicalQuery struct {
Left, Right query
Do func(iterator, interface{}, interface{}) interface{}
}
func (l *logicalQuery) Select(t iterator) NodeNavigator {
// When a XPath expr is logical expression.
node := t.Current().Copy()
val := l.Evaluate(t)
switch val.(type) {
case bool:
if val.(bool) == true {
return node
}
}
return nil
}
func (l *logicalQuery) Evaluate(t iterator) interface{} {
m := l.Left.Evaluate(t)
n := l.Right.Evaluate(t)
return l.Do(t, m, n)
}
func (l *logicalQuery) Clone() query {
return &logicalQuery{Left: l.Left.Clone(), Right: l.Right.Clone(), Do: l.Do}
}
// numericQuery is an XPath numeric operator expression.
type numericQuery struct {
Left, Right query
Do func(interface{}, interface{}) interface{}
}
func (n *numericQuery) Select(t iterator) NodeNavigator {
return nil
}
func (n *numericQuery) Evaluate(t iterator) interface{} {
m := n.Left.Evaluate(t)
k := n.Right.Evaluate(t)
return n.Do(m, k)
}
func (n *numericQuery) Clone() query {
return &numericQuery{Left: n.Left.Clone(), Right: n.Right.Clone(), Do: n.Do}
}
type booleanQuery struct {
IsOr bool
Left, Right query
iterator func() NodeNavigator
}
func (b *booleanQuery) Select(t iterator) NodeNavigator {
if b.iterator == nil {
var list []NodeNavigator
i := 0
root := t.Current().Copy()
if b.IsOr {
for {
node := b.Left.Select(t)
if node == nil {
break
}
node = node.Copy()
list = append(list, node)
}
t.Current().MoveTo(root)
for {
node := b.Right.Select(t)
if node == nil {
break
}
node = node.Copy()
list = append(list, node)
}
} else {
var m []NodeNavigator
var n []NodeNavigator
for {
node := b.Left.Select(t)
if node == nil {
break
}
node = node.Copy()
list = append(m, node)
}
t.Current().MoveTo(root)
for {
node := b.Right.Select(t)
if node == nil {
break
}
node = node.Copy()
list = append(n, node)
}
for _, k := range m {
for _, j := range n {
if k == j {
list = append(list, k)
}
}
}
}
b.iterator = func() NodeNavigator {
if i >= len(list) {
return nil
}
node := list[i]
i++
return node
}
}
return b.iterator()
}
func (b *booleanQuery) Evaluate(t iterator) interface{} {
m := b.Left.Evaluate(t)
left := asBool(t, m)
if b.IsOr && left {
return true
} else if !b.IsOr && !left {
return false
}
m = b.Right.Evaluate(t)
return asBool(t, m)
}
func (b *booleanQuery) Clone() query {
return &booleanQuery{IsOr: b.IsOr, Left: b.Left.Clone(), Right: b.Right.Clone()}
}
type unionQuery struct {
Left, Right query
iterator func() NodeNavigator
}
func (u *unionQuery) Select(t iterator) NodeNavigator {
if u.iterator == nil {
var m = make(map[uint64]NodeNavigator)
root := t.Current().Copy()
for {
node := u.Left.Select(t)
if node == nil {
break
}
code := getHashCode(node.Copy())
if _, ok := m[code]; !ok {
m[code] = node.Copy()
}
}
t.Current().MoveTo(root)
for {
node := u.Right.Select(t)
if node == nil {
break
}
code := getHashCode(node.Copy())
if _, ok := m[code]; !ok {
m[code] = node.Copy()
}
}
list := make([]NodeNavigator, len(m))
var i int
for _, v := range m {
list[i] = v
i++
}
i = 0
u.iterator = func() NodeNavigator {
if i >= len(list) {
return nil
}
node := list[i]
i++
return node
}
}
return u.iterator()
}
func (u *unionQuery) Evaluate(t iterator) interface{} {
u.iterator = nil
u.Left.Evaluate(t)
u.Right.Evaluate(t)
return u
}
func (u *unionQuery) Clone() query {
return &unionQuery{Left: u.Left.Clone(), Right: u.Right.Clone()}
}
func getHashCode(n NodeNavigator) uint64 {
var sb bytes.Buffer
switch n.NodeType() {
case AttributeNode, TextNode, CommentNode:
sb.WriteString(fmt.Sprintf("%s=%s", n.LocalName(), n.Value()))
if n.MoveToParent() {
sb.WriteString(n.LocalName())
}
case ElementNode:
sb.WriteString(n.Prefix() + n.LocalName())
d := 1
for n.MoveToPrevious() {
d++
}
sb.WriteString(fmt.Sprintf("-%d", d))
for n.MoveToParent() {
d = 1
for n.MoveToPrevious() {
d++
}
sb.WriteString(fmt.Sprintf("-%d", d))
}
}
h := fnv.New64a()
h.Write([]byte(sb.String()))
return h.Sum64()
}
func getNodePosition(q query) int {
type Position interface {
position() int
}
if count, ok := q.(Position); ok {
return count.position()
}
return 1
}

View file

@ -1,157 +0,0 @@
package xpath
import (
"errors"
)
// NodeType represents a type of XPath node.
type NodeType int
const (
// RootNode is a root node of the XML document or node tree.
RootNode NodeType = iota
// ElementNode is an element, such as <element>.
ElementNode
// AttributeNode is an attribute, such as id='123'.
AttributeNode
// TextNode is the text content of a node.
TextNode
// CommentNode is a comment node, such as <!-- my comment -->
CommentNode
// allNode is any types of node, used by xpath package only to predicate match.
allNode
)
// NodeNavigator provides cursor model for navigating XML data.
type NodeNavigator interface {
// NodeType returns the XPathNodeType of the current node.
NodeType() NodeType
// LocalName gets the Name of the current node.
LocalName() string
// Prefix returns namespace prefix associated with the current node.
Prefix() string
// Value gets the value of current node.
Value() string
// Copy does a deep copy of the NodeNavigator and all its components.
Copy() NodeNavigator
// MoveToRoot moves the NodeNavigator to the root node of the current node.
MoveToRoot()
// MoveToParent moves the NodeNavigator to the parent node of the current node.
MoveToParent() bool
// MoveToNextAttribute moves the NodeNavigator to the next attribute on current node.
MoveToNextAttribute() bool
// MoveToChild moves the NodeNavigator to the first child node of the current node.
MoveToChild() bool
// MoveToFirst moves the NodeNavigator to the first sibling node of the current node.
MoveToFirst() bool
// MoveToNext moves the NodeNavigator to the next sibling node of the current node.
MoveToNext() bool
// MoveToPrevious moves the NodeNavigator to the previous sibling node of the current node.
MoveToPrevious() bool
// MoveTo moves the NodeNavigator to the same position as the specified NodeNavigator.
MoveTo(NodeNavigator) bool
}
// NodeIterator holds all matched Node object.
type NodeIterator struct {
node NodeNavigator
query query
}
// Current returns current node which matched.
func (t *NodeIterator) Current() NodeNavigator {
return t.node
}
// MoveNext moves Navigator to the next match node.
func (t *NodeIterator) MoveNext() bool {
n := t.query.Select(t)
if n != nil {
if !t.node.MoveTo(n) {
t.node = n.Copy()
}
return true
}
return false
}
// Select selects a node set using the specified XPath expression.
// This method is deprecated, recommend using Expr.Select() method instead.
func Select(root NodeNavigator, expr string) *NodeIterator {
exp, err := Compile(expr)
if err != nil {
panic(err)
}
return exp.Select(root)
}
// Expr is an XPath expression for query.
type Expr struct {
s string
q query
}
type iteratorFunc func() NodeNavigator
func (f iteratorFunc) Current() NodeNavigator {
return f()
}
// Evaluate returns the result of the expression.
// The result type of the expression is one of the follow: bool,float64,string,NodeIterator).
func (expr *Expr) Evaluate(root NodeNavigator) interface{} {
val := expr.q.Evaluate(iteratorFunc(func() NodeNavigator { return root }))
switch val.(type) {
case query:
return &NodeIterator{query: expr.q.Clone(), node: root}
}
return val
}
// Select selects a node set using the specified XPath expression.
func (expr *Expr) Select(root NodeNavigator) *NodeIterator {
return &NodeIterator{query: expr.q.Clone(), node: root}
}
// String returns XPath expression string.
func (expr *Expr) String() string {
return expr.s
}
// Compile compiles an XPath expression string.
func Compile(expr string) (*Expr, error) {
if expr == "" {
return nil, errors.New("expr expression is nil")
}
qy, err := build(expr)
if err != nil {
return nil, err
}
return &Expr{s: expr, q: qy}, nil
}
// MustCompile compiles an XPath expression string and ignored error.
func MustCompile(expr string) *Expr {
exp, err := Compile(expr)
if err != nil {
return nil
}
return exp
}

View file

@ -1,3 +0,0 @@
c.out
c/*-ble
sample

View file

@ -1,27 +0,0 @@
Copyright (c) 2014 PayPal Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following disclaimer
in the documentation and/or other materials provided with the
distribution.
* Neither the name of PayPal Inc. nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

2163
vendor/github.com/bettercap/gatt/adv.go generated vendored

File diff suppressed because it is too large Load diff

View file

@ -1,163 +0,0 @@
package gatt
import "log"
// attr is a BLE attribute. It is not exported;
// managing attributes is an implementation detail.
type attr struct {
h uint16 // attribute handle
typ UUID // attribute type in UUID
props Property // attripute property
secure Property // attribute secure (implementation specific usage)
value []byte // attribute value
pvt interface{} // point to the corresponsing Serveice/Characteristic/Descriptor
}
// A attrRange is a contiguous range of attributes.
type attrRange struct {
aa []attr
base uint16 // handle for first attr in aa
}
const (
tooSmall = -1
tooLarge = -2
)
// idx returns the index into aa corresponding to attr a.
// If h is too small, idx returns tooSmall (-1).
// If h is too large, idx returns tooLarge (-2).
func (r *attrRange) idx(h int) int {
if h < int(r.base) {
return tooSmall
}
if int(h) >= int(r.base)+len(r.aa) {
return tooLarge
}
return h - int(r.base)
}
// At returns attr a.
func (r *attrRange) At(h uint16) (a attr, ok bool) {
i := r.idx(int(h))
if i < 0 {
return attr{}, false
}
return r.aa[i], true
}
// Subrange returns attributes in range [start, end]; it may
// return an empty slice. Subrange does not panic for
// out-of-range start or end.
func (r *attrRange) Subrange(start, end uint16) []attr {
startidx := r.idx(int(start))
switch startidx {
case tooSmall:
startidx = 0
case tooLarge:
return []attr{}
}
endidx := r.idx(int(end) + 1) // [start, end] includes its upper bound!
switch endidx {
case tooSmall:
return []attr{}
case tooLarge:
endidx = len(r.aa)
}
return r.aa[startidx:endidx]
}
func dumpAttributes(aa []attr) {
log.Printf("Generating attribute table:")
log.Printf("handle\ttype\tprops\tsecure\tpvt\tvalue")
for _, a := range aa {
log.Printf("0x%04X\t0x%s\t0x%02X\t0x%02x\t%T\t[ % X ]",
a.h, a.typ, int(a.props), int(a.secure), a.pvt, a.value)
}
}
func generateAttributes(ss []*Service, base uint16) *attrRange {
var aa []attr
h := base
last := len(ss) - 1
for i, s := range ss {
var a []attr
h, a = generateServiceAttributes(s, h, i == last)
aa = append(aa, a...)
}
dumpAttributes(aa)
return &attrRange{aa: aa, base: base}
}
func generateServiceAttributes(s *Service, h uint16, last bool) (uint16, []attr) {
s.h = h
// endh set later
a := attr{
h: h,
typ: attrPrimaryServiceUUID,
value: s.uuid.b,
props: CharRead,
pvt: s,
}
aa := []attr{a}
h++
for _, c := range s.Characteristics() {
var a []attr
h, a = generateCharAttributes(c, h)
aa = append(aa, a...)
}
s.endh = h - 1
if last {
h = 0xFFFF
s.endh = h
}
return h, aa
}
func generateCharAttributes(c *Characteristic, h uint16) (uint16, []attr) {
c.h = h
c.vh = h + 1
ca := attr{
h: c.h,
typ: attrCharacteristicUUID,
value: append([]byte{byte(c.props), byte(c.vh), byte((c.vh) >> 8)}, c.uuid.b...),
props: c.props,
pvt: c,
}
va := attr{
h: c.vh,
typ: c.uuid,
value: c.value,
props: c.props,
pvt: c,
}
h += 2
aa := []attr{ca, va}
for _, d := range c.descs {
aa = append(aa, generateDescAttributes(d, h))
h++
}
return h, aa
}
func generateDescAttributes(d *Descriptor, h uint16) attr {
d.h = h
a := attr{
h: h,
typ: d.uuid,
value: d.value,
props: d.props,
pvt: d,
}
if len(d.valuestr) > 0 {
a.value = []byte(d.valuestr)
}
return a
}

View file

@ -1,152 +0,0 @@
package gatt
import (
"bytes"
"errors"
"fmt"
"sync"
)
// Central is the interface that represent a remote central device.
type Central interface {
ID() string // ID returns platform specific ID of the remote central device.
Close() error // Close disconnects the connection.
MTU() int // MTU returns the current connection mtu.
}
type ResponseWriter interface {
// Write writes data to return as the characteristic value.
Write([]byte) (int, error)
// SetStatus reports the result of the read operation. See the Status* constants.
SetStatus(byte)
}
// responseWriter is the default implementation of ResponseWriter.
type responseWriter struct {
capacity int
buf *bytes.Buffer
status byte
}
func newResponseWriter(c int) *responseWriter {
return &responseWriter{
capacity: c,
buf: new(bytes.Buffer),
status: StatusSuccess,
}
}
func (w *responseWriter) Write(b []byte) (int, error) {
if avail := w.capacity - w.buf.Len(); avail < len(b) {
return 0, fmt.Errorf("requested write %d bytes, %d available", len(b), avail)
}
return w.buf.Write(b)
}
func (w *responseWriter) SetStatus(status byte) { w.status = status }
func (w *responseWriter) bytes() []byte { return w.buf.Bytes() }
// A ReadHandler handles GATT read requests.
type ReadHandler interface {
ServeRead(resp ResponseWriter, req *ReadRequest)
}
// ReadHandlerFunc is an adapter to allow the use of
// ordinary functions as ReadHandlers. If f is a function
// with the appropriate signature, ReadHandlerFunc(f) is a
// ReadHandler that calls f.
type ReadHandlerFunc func(resp ResponseWriter, req *ReadRequest)
// ServeRead returns f(r, maxlen, offset).
func (f ReadHandlerFunc) ServeRead(resp ResponseWriter, req *ReadRequest) {
f(resp, req)
}
// A WriteHandler handles GATT write requests.
// Write and WriteNR requests are presented identically;
// the server will ensure that a response is sent if appropriate.
type WriteHandler interface {
ServeWrite(r Request, data []byte) (status byte)
}
// WriteHandlerFunc is an adapter to allow the use of
// ordinary functions as WriteHandlers. If f is a function
// with the appropriate signature, WriteHandlerFunc(f) is a
// WriteHandler that calls f.
type WriteHandlerFunc func(r Request, data []byte) byte
// ServeWrite returns f(r, data).
func (f WriteHandlerFunc) ServeWrite(r Request, data []byte) byte {
return f(r, data)
}
// A NotifyHandler handles GATT notification requests.
// Notifications can be sent using the provided notifier.
type NotifyHandler interface {
ServeNotify(r Request, n Notifier)
}
// NotifyHandlerFunc is an adapter to allow the use of
// ordinary functions as NotifyHandlers. If f is a function
// with the appropriate signature, NotifyHandlerFunc(f) is a
// NotifyHandler that calls f.
type NotifyHandlerFunc func(r Request, n Notifier)
// ServeNotify calls f(r, n).
func (f NotifyHandlerFunc) ServeNotify(r Request, n Notifier) {
f(r, n)
}
// A Notifier provides a means for a GATT server to send
// notifications about value changes to a connected device.
// Notifiers are provided by NotifyHandlers.
type Notifier interface {
// Write sends data to the central.
Write(data []byte) (int, error)
// Done reports whether the central has requested not to
// receive any more notifications with this notifier.
Done() bool
// Cap returns the maximum number of bytes that may be sent
// in a single notification.
Cap() int
}
type notifier struct {
central *central
a *attr
maxlen int
donemu sync.RWMutex
done bool
}
func newNotifier(c *central, a *attr, maxlen int) *notifier {
return &notifier{central: c, a: a, maxlen: maxlen}
}
func (n *notifier) Write(b []byte) (int, error) {
n.donemu.RLock()
defer n.donemu.RUnlock()
if n.done {
return 0, errors.New("central stopped notifications")
}
return n.central.sendNotification(n.a, b)
}
func (n *notifier) Cap() int {
return n.maxlen
}
func (n *notifier) Done() bool {
n.donemu.RLock()
defer n.donemu.RUnlock()
return n.done
}
func (n *notifier) stop() {
n.donemu.Lock()
n.done = true
n.donemu.Unlock()
}

View file

@ -1,70 +0,0 @@
package gatt
import (
"sync"
"github.com/bettercap/gatt/xpc"
)
type central struct {
dev *device
uuid UUID
mtu int
notifiers map[uint16]*notifier
notifiersmu *sync.Mutex
}
func newCentral(d *device, u UUID) *central {
return &central{
dev: d,
mtu: 23,
uuid: u,
notifiers: make(map[uint16]*notifier),
notifiersmu: &sync.Mutex{},
}
}
func (c *central) ID() string { return c.uuid.String() }
func (c *central) Close() error { return nil }
func (c *central) MTU() int { return c.mtu }
func (c *central) sendNotification(a *attr, b []byte) (int, error) {
data := make([]byte, len(b))
copy(data, b) // have to make a copy, why?
c.dev.sendCmd(15, xpc.Dict{
// "kCBMsgArgUUIDs": [][]byte{reverse(c.uuid.b)}, // connection interrupted
// "kCBMsgArgUUIDs": [][]byte{c.uuid.b}, // connection interrupted
// "kCBMsgArgUUIDs": []xpc.UUID{xpc.UUID(reverse(c.uuid.b))},
// "kCBMsgArgUUIDs": []xpc.UUID{xpc.UUID(c.uuid.b)},
// "kCBMsgArgUUIDs": reverse(c.uuid.b),
//
// FIXME: Sigh... tried to targeting the central, but couldn't get work.
// So, broadcast to all subscribed centrals. Either of the following works.
// "kCBMsgArgUUIDs": []xpc.UUID{},
"kCBMsgArgUUIDs": [][]byte{},
"kCBMsgArgAttributeID": a.h,
"kCBMsgArgData": data,
})
return len(b), nil
}
func (c *central) startNotify(a *attr, maxlen int) {
c.notifiersmu.Lock()
defer c.notifiersmu.Unlock()
if _, found := c.notifiers[a.h]; found {
return
}
n := newNotifier(c, a, maxlen)
c.notifiers[a.h] = n
char := a.pvt.(*Characteristic)
go char.nhandler.ServeNotify(Request{Central: c}, n)
}
func (c *central) stopNotify(a *attr) {
c.notifiersmu.Lock()
defer c.notifiersmu.Unlock()
if n, found := c.notifiers[a.h]; found {
n.stop()
delete(c.notifiers, a.h)
}
}

View file

@ -1,461 +0,0 @@
package gatt
import (
"encoding/binary"
"io"
"net"
"sync"
)
type security int
const (
securityLow = iota
securityMed
securityHigh
)
type central struct {
attrs *attrRange
mtu uint16
addr net.HardwareAddr
security security
l2conn io.ReadWriteCloser
notifiers map[uint16]*notifier
notifiersmu *sync.Mutex
}
func newCentral(a *attrRange, addr net.HardwareAddr, l2conn io.ReadWriteCloser) *central {
return &central{
attrs: a,
mtu: 23,
addr: addr,
security: securityLow,
l2conn: l2conn,
notifiers: make(map[uint16]*notifier),
notifiersmu: &sync.Mutex{},
}
}
func (c *central) ID() string {
return c.addr.String()
}
func (c *central) Close() error {
c.notifiersmu.Lock()
defer c.notifiersmu.Unlock()
for _, n := range c.notifiers {
n.stop()
}
return c.l2conn.Close()
}
func (c *central) MTU() int {
return int(c.mtu)
}
func (c *central) loop() {
for {
// L2CAP implementations shall support a minimum MTU size of 48 bytes.
// The default value is 672 bytes
b := make([]byte, 672)
n, err := c.l2conn.Read(b)
if n == 0 || err != nil {
c.Close()
break
}
if rsp := c.handleReq(b[:n]); rsp != nil {
c.l2conn.Write(rsp)
}
}
}
// handleReq dispatches a raw request from the central shim
// to an appropriate handler, based on its type.
// It panics if len(b) == 0.
func (c *central) handleReq(b []byte) []byte {
var resp []byte
switch reqType, req := b[0], b[1:]; reqType {
case attOpMtuReq:
resp = c.handleMTU(req)
case attOpFindInfoReq:
resp = c.handleFindInfo(req)
case attOpFindByTypeValueReq:
resp = c.handleFindByTypeValue(req)
case attOpReadByTypeReq:
resp = c.handleReadByType(req)
case attOpReadReq:
resp = c.handleRead(req)
case attOpReadBlobReq:
resp = c.handleReadBlob(req)
case attOpReadByGroupReq:
resp = c.handleReadByGroup(req)
case attOpWriteReq, attOpWriteCmd:
resp = c.handleWrite(reqType, req)
case attOpReadMultiReq, attOpPrepWriteReq, attOpExecWriteReq, attOpSignedWriteCmd:
fallthrough
default:
resp = attErrorRsp(reqType, 0x0000, AttEcodeReqNotSupp)
}
return resp
}
func (c *central) handleMTU(b []byte) []byte {
c.mtu = binary.LittleEndian.Uint16(b[:2])
if c.mtu < 23 {
c.mtu = 23
}
if c.mtu >= 256 {
c.mtu = 256
}
return []byte{attOpMtuRsp, uint8(c.mtu), uint8(c.mtu >> 8)}
}
// REQ: FindInfoReq(0x04), StartHandle, EndHandle
// RSP: FindInfoRsp(0x05), UUIDFormat, Handle, UUID, Handle, UUID, ...
func (c *central) handleFindInfo(b []byte) []byte {
start, end := readHandleRange(b[:4])
w := newL2capWriter(c.mtu)
w.WriteByteFit(attOpFindInfoRsp)
uuidLen := -1
for _, a := range c.attrs.Subrange(start, end) {
if uuidLen == -1 {
uuidLen = a.typ.Len()
if uuidLen == 2 {
w.WriteByteFit(0x01) // TODO: constants for 16bit vs 128bit uuid magic numbers here
} else {
w.WriteByteFit(0x02)
}
}
if a.typ.Len() != uuidLen {
break
}
w.Chunk()
w.WriteUint16Fit(a.h)
w.WriteUUIDFit(a.typ)
if ok := w.Commit(); !ok {
break
}
}
if uuidLen == -1 {
return attErrorRsp(attOpFindInfoReq, start, AttEcodeAttrNotFound)
}
return w.Bytes()
}
// REQ: FindByTypeValueReq(0x06), StartHandle, EndHandle, Type(UUID), Value
// RSP: FindByTypeValueRsp(0x07), AttrHandle, GroupEndHandle, AttrHandle, GroupEndHandle, ...
func (c *central) handleFindByTypeValue(b []byte) []byte {
start, end := readHandleRange(b[:4])
t := UUID{b[4:6]}
u := UUID{b[6:]}
// Only support the ATT ReadByGroupReq for GATT Primary Service Discovery.
// More sepcifically, the "Discover Primary Services By Service UUID" sub-procedure
if !t.Equal(attrPrimaryServiceUUID) {
return attErrorRsp(attOpFindByTypeValueReq, start, AttEcodeAttrNotFound)
}
w := newL2capWriter(c.mtu)
w.WriteByteFit(attOpFindByTypeValueRsp)
var wrote bool
for _, a := range c.attrs.Subrange(start, end) {
if !a.typ.Equal(attrPrimaryServiceUUID) {
continue
}
if !(UUID{a.value}.Equal(u)) {
continue
}
s := a.pvt.(*Service)
w.Chunk()
w.WriteUint16Fit(s.h)
w.WriteUint16Fit(s.endh)
if ok := w.Commit(); !ok {
break
}
wrote = true
}
if !wrote {
return attErrorRsp(attOpFindByTypeValueReq, start, AttEcodeAttrNotFound)
}
return w.Bytes()
}
// REQ: ReadByType(0x08), StartHandle, EndHandle, Type(UUID)
// RSP: ReadByType(0x09), LenOfEachDataField, DataField, DataField, ...
func (c *central) handleReadByType(b []byte) []byte {
start, end := readHandleRange(b[:4])
t := UUID{b[4:]}
w := newL2capWriter(c.mtu)
w.WriteByteFit(attOpReadByTypeRsp)
uuidLen := -1
for _, a := range c.attrs.Subrange(start, end) {
if !a.typ.Equal(t) {
continue
}
if (a.secure&CharRead) != 0 && c.security > securityLow {
return attErrorRsp(attOpReadByTypeReq, start, AttEcodeAuthentication)
}
v := a.value
if v == nil {
rsp := newResponseWriter(int(c.mtu - 1))
req := &ReadRequest{
Request: Request{Central: c},
Cap: int(c.mtu - 1),
Offset: 0,
}
if c, ok := a.pvt.(*Characteristic); ok {
c.rhandler.ServeRead(rsp, req)
} else if d, ok := a.pvt.(*Descriptor); ok {
d.rhandler.ServeRead(rsp, req)
}
v = rsp.bytes()
}
if uuidLen == -1 {
uuidLen = len(v)
w.WriteByteFit(byte(uuidLen) + 2)
}
if len(v) != uuidLen {
break
}
w.Chunk()
w.WriteUint16Fit(a.h)
w.WriteFit(v)
if ok := w.Commit(); !ok {
break
}
}
if uuidLen == -1 {
return attErrorRsp(attOpReadByTypeReq, start, AttEcodeAttrNotFound)
}
return w.Bytes()
}
// REQ: ReadReq(0x0A), Handle
// RSP: ReadRsp(0x0B), Value
func (c *central) handleRead(b []byte) []byte {
h := binary.LittleEndian.Uint16(b)
a, ok := c.attrs.At(h)
if !ok {
return attErrorRsp(attOpReadReq, h, AttEcodeInvalidHandle)
}
if a.props&CharRead == 0 {
return attErrorRsp(attOpReadReq, h, AttEcodeReadNotPerm)
}
if a.secure&CharRead != 0 && c.security > securityLow {
return attErrorRsp(attOpReadReq, h, AttEcodeAuthentication)
}
v := a.value
if v == nil {
req := &ReadRequest{
Request: Request{Central: c},
Cap: int(c.mtu - 1),
Offset: 0,
}
rsp := newResponseWriter(int(c.mtu - 1))
if c, ok := a.pvt.(*Characteristic); ok {
c.rhandler.ServeRead(rsp, req)
} else if d, ok := a.pvt.(*Descriptor); ok {
d.rhandler.ServeRead(rsp, req)
}
v = rsp.bytes()
}
w := newL2capWriter(c.mtu)
w.WriteByteFit(attOpReadRsp)
w.Chunk()
w.WriteFit(v)
w.CommitFit()
return w.Bytes()
}
// FIXME: check this, untested, might be broken
func (c *central) handleReadBlob(b []byte) []byte {
h := binary.LittleEndian.Uint16(b)
offset := binary.LittleEndian.Uint16(b[2:])
a, ok := c.attrs.At(h)
if !ok {
return attErrorRsp(attOpReadBlobReq, h, AttEcodeInvalidHandle)
}
if a.props&CharRead == 0 {
return attErrorRsp(attOpReadBlobReq, h, AttEcodeReadNotPerm)
}
if a.secure&CharRead != 0 && c.security > securityLow {
return attErrorRsp(attOpReadBlobReq, h, AttEcodeAuthentication)
}
v := a.value
if v == nil {
req := &ReadRequest{
Request: Request{Central: c},
Cap: int(c.mtu - 1),
Offset: int(offset),
}
rsp := newResponseWriter(int(c.mtu - 1))
if c, ok := a.pvt.(*Characteristic); ok {
c.rhandler.ServeRead(rsp, req)
} else if d, ok := a.pvt.(*Descriptor); ok {
d.rhandler.ServeRead(rsp, req)
}
v = rsp.bytes()
offset = 0 // the server has already adjusted for the offset
}
w := newL2capWriter(c.mtu)
w.WriteByteFit(attOpReadBlobRsp)
w.Chunk()
w.WriteFit(v)
if ok := w.ChunkSeek(offset); !ok {
return attErrorRsp(attOpReadBlobReq, h, AttEcodeInvalidOffset)
}
w.CommitFit()
return w.Bytes()
}
func (c *central) handleReadByGroup(b []byte) []byte {
start, end := readHandleRange(b)
t := UUID{b[4:]}
// Only support the ATT ReadByGroupReq for GATT Primary Service Discovery.
// More specifically, the "Discover All Primary Services" sub-procedure.
if !t.Equal(attrPrimaryServiceUUID) {
return attErrorRsp(attOpReadByGroupReq, start, AttEcodeUnsuppGrpType)
}
w := newL2capWriter(c.mtu)
w.WriteByteFit(attOpReadByGroupRsp)
uuidLen := -1
for _, a := range c.attrs.Subrange(start, end) {
if !a.typ.Equal(attrPrimaryServiceUUID) {
continue
}
if uuidLen == -1 {
uuidLen = len(a.value)
w.WriteByteFit(byte(uuidLen + 4))
}
if uuidLen != len(a.value) {
break
}
s := a.pvt.(*Service)
w.Chunk()
w.WriteUint16Fit(s.h)
w.WriteUint16Fit(s.endh)
w.WriteFit(a.value)
if ok := w.Commit(); !ok {
break
}
}
if uuidLen == -1 {
return attErrorRsp(attOpReadByGroupReq, start, AttEcodeAttrNotFound)
}
return w.Bytes()
}
func (c *central) handleWrite(reqType byte, b []byte) []byte {
h := binary.LittleEndian.Uint16(b[:2])
value := b[2:]
a, ok := c.attrs.At(h)
if !ok {
return attErrorRsp(reqType, h, AttEcodeInvalidHandle)
}
noRsp := reqType == attOpWriteCmd
charFlag := CharWrite
if noRsp {
charFlag = CharWriteNR
}
if a.props&charFlag == 0 {
return attErrorRsp(reqType, h, AttEcodeWriteNotPerm)
}
if a.secure&charFlag == 0 && c.security > securityLow {
return attErrorRsp(reqType, h, AttEcodeAuthentication)
}
// Props of Service and Characteristic declration are read only.
// So we only need deal with writable descriptors here.
// (Characteristic's value is implemented with descriptor)
if !a.typ.Equal(attrClientCharacteristicConfigUUID) {
// Regular write, not CCC
r := Request{Central: c}
result := byte(0)
if c, ok := a.pvt.(*Characteristic); ok {
result = c.whandler.ServeWrite(r, value)
} else if d, ok := a.pvt.(*Characteristic); ok {
result = d.whandler.ServeWrite(r, value)
}
if noRsp {
return nil
} else {
resultEcode := AttEcode(result)
if resultEcode == AttEcodeSuccess {
return []byte{attOpWriteRsp}
} else {
return attErrorRsp(reqType, h, resultEcode)
}
}
}
// CCC/descriptor write
if len(value) != 2 {
return attErrorRsp(reqType, h, AttEcodeInvalAttrValueLen)
}
ccc := binary.LittleEndian.Uint16(value)
// char := a.pvt.(*Descriptor).char
if ccc&(gattCCCNotifyFlag|gattCCCIndicateFlag) != 0 {
c.startNotify(&a, int(c.mtu-3))
} else {
c.stopNotify(&a)
}
if noRsp {
return nil
}
return []byte{attOpWriteRsp}
}
func (c *central) sendNotification(a *attr, data []byte) (int, error) {
w := newL2capWriter(c.mtu)
added := 0
if w.WriteByteFit(attOpHandleNotify) {
added += 1
}
if w.WriteUint16Fit(a.pvt.(*Descriptor).char.vh) {
added += 2
}
w.WriteFit(data)
n, err := c.l2conn.Write(w.Bytes())
if err != nil {
return n, err
}
return n - added, err
}
func readHandleRange(b []byte) (start, end uint16) {
return binary.LittleEndian.Uint16(b), binary.LittleEndian.Uint16(b[2:])
}
func (c *central) startNotify(a *attr, maxlen int) {
c.notifiersmu.Lock()
defer c.notifiersmu.Unlock()
if _, found := c.notifiers[a.h]; found {
return
}
char := a.pvt.(*Descriptor).char
n := newNotifier(c, a, maxlen)
c.notifiers[a.h] = n
go char.nhandler.ServeNotify(Request{Central: c}, n)
}
func (c *central) stopNotify(a *attr) {
c.notifiersmu.Lock()
defer c.notifiersmu.Unlock()
// char := a.pvt.(*Characteristic)
if n, found := c.notifiers[a.h]; found {
n.stop()
delete(c.notifiers, a.h)
}
}

View file

@ -1,424 +0,0 @@
package gatt
// Supported statuses for GATT characteristic read/write operations.
// These correspond to att constants in the BLE spec
const (
StatusSuccess = 0
StatusInvalidOffset = 1
StatusUnexpectedError = 2
)
// A Request is the context for a request from a connected central device.
// TODO: Replace this with more general context, such as:
// http://godoc.org/golang.org/x/net/context
type Request struct {
Central Central
}
// A ReadRequest is a characteristic read request from a connected device.
type ReadRequest struct {
Request
Cap int // maximum allowed reply length
Offset int // request value offset
}
type Property int
// Characteristic property flags (spec 3.3.3.1)
const (
CharBroadcast Property = 0x01 // may be brocasted
CharRead Property = 0x02 // may be read
CharWriteNR Property = 0x04 // may be written to, with no reply
CharWrite Property = 0x08 // may be written to, with a reply
CharNotify Property = 0x10 // supports notifications
CharIndicate Property = 0x20 // supports Indications
CharSignedWrite Property = 0x40 // supports signed write
CharExtended Property = 0x80 // supports extended properties
)
func (p Property) String() (result string) {
if (p & CharBroadcast) != 0 {
result += "broadcast "
}
if (p & CharRead) != 0 {
result += "read "
}
if (p & CharWriteNR) != 0 {
result += "writeWithoutResponse "
}
if (p & CharWrite) != 0 {
result += "write "
}
if (p & CharNotify) != 0 {
result += "notify "
}
if (p & CharIndicate) != 0 {
result += "indicate "
}
if (p & CharSignedWrite) != 0 {
result += "authenticateSignedWrites "
}
if (p & CharExtended) != 0 {
result += "extendedProperties "
}
return
}
// A Service is a BLE service.
type Service struct {
uuid UUID
chars []*Characteristic
h uint16
endh uint16
}
// NewService creates and initialize a new Service using u as it's UUID.
func NewService(u UUID) *Service {
return &Service{uuid: u}
}
// AddCharacteristic adds a characteristic to a service.
// AddCharacteristic panics if the service already contains another
// characteristic with the same UUID.
func (s *Service) AddCharacteristic(u UUID) *Characteristic {
for _, c := range s.chars {
if c.uuid.Equal(u) {
panic("service already contains a characteristic with uuid " + u.String())
}
}
c := &Characteristic{uuid: u, svc: s}
s.chars = append(s.chars, c)
return c
}
// UUID returns the UUID of the service.
func (s *Service) UUID() UUID { return s.uuid }
// Name returns the specificatin name of the service according to its UUID.
// If the UUID is not assigne, Name returns an empty string.
func (s *Service) Name() string {
return knownServices[s.uuid.String()].Name
}
// Handle returns the Handle of the service.
func (s *Service) Handle() uint16 { return s.h }
// EndHandle returns the End Handle of the service.
func (s *Service) EndHandle() uint16 { return s.endh }
// SetHandle sets the Handle of the service.
func (s *Service) SetHandle(h uint16) { s.h = h }
// SetEndHandle sets the End Handle of the service.
func (s *Service) SetEndHandle(endh uint16) { s.endh = endh }
// SetCharacteristics sets the Characteristics of the service.
func (s *Service) SetCharacteristics(chars []*Characteristic) { s.chars = chars }
// Characteristic returns the contained characteristic of this service.
func (s *Service) Characteristics() []*Characteristic { return s.chars }
// A Characteristic is a BLE characteristic.
type Characteristic struct {
uuid UUID
props Property // enabled properties
secure Property // security enabled properties
svc *Service
cccd *Descriptor
descs []*Descriptor
value []byte
// All the following fields are only used in peripheral/server implementation.
rhandler ReadHandler
whandler WriteHandler
nhandler NotifyHandler
h uint16
vh uint16
endh uint16
}
// NewCharacteristic creates and returns a Characteristic.
func NewCharacteristic(u UUID, s *Service, props Property, h uint16, vh uint16) *Characteristic {
c := &Characteristic{
uuid: u,
svc: s,
props: props,
h: h,
vh: vh,
}
return c
}
// Handle returns the Handle of the characteristic.
func (c *Characteristic) Handle() uint16 { return c.h }
// VHandle returns the Value Handle of the characteristic.
func (c *Characteristic) VHandle() uint16 { return c.vh }
// EndHandle returns the End Handle of the characteristic.
func (c *Characteristic) EndHandle() uint16 { return c.endh }
// Descriptor returns the Descriptor of the characteristic.
func (c *Characteristic) Descriptor() *Descriptor { return c.cccd }
// SetHandle sets the Handle of the characteristic.
func (c *Characteristic) SetHandle(h uint16) { c.h = h }
// SetVHandle sets the Value Handle of the characteristic.
func (c *Characteristic) SetVHandle(vh uint16) { c.vh = vh }
// SetEndHandle sets the End Handle of the characteristic.
func (c *Characteristic) SetEndHandle(endh uint16) { c.endh = endh }
// SetDescriptor sets the Descriptor of the characteristic.
func (c *Characteristic) SetDescriptor(cccd *Descriptor) { c.cccd = cccd }
// SetDescriptors sets the list of Descriptor of the characteristic.
func (c *Characteristic) SetDescriptors(descs []*Descriptor) { c.descs = descs }
// UUID returns the UUID of the characteristic.
func (c *Characteristic) UUID() UUID {
return c.uuid
}
// Name returns the specificatin name of the characteristic.
// If the UUID is not assigned, Name returns empty string.
func (c *Characteristic) Name() string {
return knownCharacteristics[c.uuid.String()].Name
}
// Service returns the containing service of this characteristic.
func (c *Characteristic) Service() *Service {
return c.svc
}
// Properties returns the properties of this characteristic.
func (c *Characteristic) Properties() Property {
return c.props
}
// Descriptors returns the contained descriptors of this characteristic.
func (c *Characteristic) Descriptors() []*Descriptor {
return c.descs
}
// AddDescriptor adds a descriptor to a characteristic.
// AddDescriptor panics if the characteristic already contains another
// descriptor with the same UUID.
func (c *Characteristic) AddDescriptor(u UUID) *Descriptor {
for _, d := range c.descs {
if d.uuid.Equal(u) {
panic("service already contains a characteristic with uuid " + u.String())
}
}
d := &Descriptor{uuid: u, char: c}
c.descs = append(c.descs, d)
return d
}
// SetValue makes the characteristic support read requests, and returns a
// static value. SetValue must be called before the containing service is
// added to a server.
// SetValue panics if the characteristic has been configured with a ReadHandler.
func (c *Characteristic) SetValue(b []byte) {
if c.rhandler != nil {
panic("charactristic has been configured with a read handler")
}
c.props |= CharRead
// c.secure |= CharRead
c.value = make([]byte, len(b))
copy(c.value, b)
}
// HandleRead makes the characteristic support read requests, and routes read
// requests to h. HandleRead must be called before the containing service is
// added to a server.
// HandleRead panics if the characteristic has been configured with a static value.
func (c *Characteristic) HandleRead(h ReadHandler) {
if c.value != nil {
panic("charactristic has been configured with a static value")
}
c.props |= CharRead
// c.secure |= CharRead
c.rhandler = h
}
// HandleReadFunc calls HandleRead(ReadHandlerFunc(f)).
func (c *Characteristic) HandleReadFunc(f func(rsp ResponseWriter, req *ReadRequest)) {
c.HandleRead(ReadHandlerFunc(f))
}
func (c *Characteristic) GetReadHandler() ReadHandler {
return c.rhandler
}
// HandleWrite makes the characteristic support write and write-no-response
// requests, and routes write requests to h.
// The WriteHandler does not differentiate between write and write-no-response
// requests; it is handled automatically.
// HandleWrite must be called before the containing service is added to a server.
func (c *Characteristic) HandleWrite(h WriteHandler) {
c.props |= CharWrite | CharWriteNR
// c.secure |= CharWrite | CharWriteNR
c.whandler = h
}
// HandleWriteFunc calls HandleWrite(WriteHandlerFunc(f)).
func (c *Characteristic) HandleWriteFunc(f func(r Request, data []byte) (status byte)) {
c.HandleWrite(WriteHandlerFunc(f))
}
func (c *Characteristic) GetWriteHandler() WriteHandler {
return c.whandler
}
// HandleNotify makes the characteristic support notify requests, and routes
// notification requests to h. HandleNotify must be called before the
// containing service is added to a server.
func (c *Characteristic) HandleNotify(h NotifyHandler) {
if c.cccd != nil {
return
}
p := CharNotify | CharIndicate
c.props |= p
c.nhandler = h
// add ccc (client characteristic configuration) descriptor
secure := Property(0)
// If the characteristic requested secure notifications,
// then set ccc security to r/w.
if c.secure&p != 0 {
secure = CharRead | CharWrite
}
cd := &Descriptor{
uuid: attrClientCharacteristicConfigUUID,
props: CharRead | CharWrite | CharWriteNR,
secure: secure,
// FIXME: currently, we always return 0, which is inaccurate.
// Each connection should have it's own copy of this value.
value: []byte{0x00, 0x00},
char: c,
}
c.cccd = cd
c.descs = append(c.descs, cd)
}
// HandleNotifyFunc calls HandleNotify(NotifyHandlerFunc(f)).
func (c *Characteristic) HandleNotifyFunc(f func(r Request, n Notifier)) {
c.HandleNotify(NotifyHandlerFunc(f))
}
func (c *Characteristic) GetNotifyHandler() NotifyHandler {
return c.nhandler
}
// TODO
// func (c *Characteristic) SubscribedCentrals() []Central{
// }
// Descriptor is a BLE descriptor
type Descriptor struct {
uuid UUID
char *Characteristic
props Property // enabled properties
secure Property // security enabled properties
h uint16
value []byte
valuestr string
rhandler ReadHandler
whandler WriteHandler
}
// Handle returns the Handle of the descriptor.
func (d *Descriptor) Handle() uint16 { return d.h }
// SetHandle sets the Handle of the descriptor.
func (d *Descriptor) SetHandle(h uint16) { d.h = h }
// NewDescriptor creates and returns a Descriptor.
func NewDescriptor(u UUID, h uint16, char *Characteristic) *Descriptor {
cd := &Descriptor{
uuid: u,
h: h,
char: char,
}
return cd
}
// UUID returns the UUID of the descriptor.
func (d *Descriptor) UUID() UUID {
return d.uuid
}
// Name returns the specificatin name of the descriptor.
// If the UUID is not assigned, returns an empty string.
func (d *Descriptor) Name() string {
return knownDescriptors[d.uuid.String()].Name
}
// Characteristic returns the containing characteristic of the descriptor.
func (d *Descriptor) Characteristic() *Characteristic {
return d.char
}
// SetValue makes the descriptor support read requests, and returns a static value.
// SetValue must be called before the containing service is added to a server.
// SetValue panics if the descriptor has already configured with a ReadHandler.
func (d *Descriptor) SetValue(b []byte) {
if d.rhandler != nil {
panic("descriptor has been configured with a read handler")
}
d.props |= CharRead
// d.secure |= CharRead
d.value = make([]byte, len(b))
copy(d.value, b)
}
// SetStringValue makes the descriptor support read requests, and returns a static value.
// SetStringValue must be called before the containing service is added to a server.
// SetStringValue panics if the descriptor has already configured with a ReadHandler.
func (d *Descriptor) SetStringValue(s string) {
if d.rhandler != nil {
panic("descriptor has been configured with a read handler")
}
d.props |= CharRead
// d.secure |= CharRead
d.valuestr = s
}
// HandleRead makes the descriptor support read requests, and routes read requests to h.
// HandleRead must be called before the containing service is added to a server.
// HandleRead panics if the descriptor has been configured with a static value.
func (d *Descriptor) HandleRead(h ReadHandler) {
if d.value != nil {
panic("descriptor has been configured with a static value")
}
d.props |= CharRead
// d.secure |= CharRead
d.rhandler = h
}
// HandleReadFunc calls HandleRead(ReadHandlerFunc(f)).
func (d *Descriptor) HandleReadFunc(f func(rsp ResponseWriter, req *ReadRequest)) {
d.HandleRead(ReadHandlerFunc(f))
}
// HandleWrite makes the descriptor support write and write-no-response requests, and routes write requests to h.
// The WriteHandler does not differentiate between write and write-no-response requests; it is handled automatically.
// HandleWrite must be called before the containing service is added to a server.
func (d *Descriptor) HandleWrite(h WriteHandler) {
d.props |= CharWrite | CharWriteNR
// d.secure |= CharWrite | CharWriteNR
d.whandler = h
}
// HandleWriteFunc calls HandleWrite(WriteHandlerFunc(f)).
func (d *Descriptor) HandleWriteFunc(f func(r Request, data []byte) (status byte)) {
d.HandleWrite(WriteHandlerFunc(f))
}

View file

@ -1,153 +0,0 @@
package gatt
// This file includes constants from the BLE spec.
var (
attrGAPUUID = UUID16(0x1800)
attrGATTUUID = UUID16(0x1801)
attrPrimaryServiceUUID = UUID16(0x2800)
attrSecondaryServiceUUID = UUID16(0x2801)
attrIncludeUUID = UUID16(0x2802)
attrCharacteristicUUID = UUID16(0x2803)
attrClientCharacteristicConfigUUID = UUID16(0x2902)
attrServerCharacteristicConfigUUID = UUID16(0x2903)
attrDeviceNameUUID = UUID16(0x2A00)
attrAppearanceUUID = UUID16(0x2A01)
attrPeripheralPrivacyUUID = UUID16(0x2A02)
attrReconnectionAddrUUID = UUID16(0x2A03)
attrPeferredParamsUUID = UUID16(0x2A04)
attrServiceChangedUUID = UUID16(0x2A05)
)
const (
gattCCCNotifyFlag = 0x0001
gattCCCIndicateFlag = 0x0002
)
const (
attOpError = 0x01
attOpMtuReq = 0x02
attOpMtuRsp = 0x03
attOpFindInfoReq = 0x04
attOpFindInfoRsp = 0x05
attOpFindByTypeValueReq = 0x06
attOpFindByTypeValueRsp = 0x07
attOpReadByTypeReq = 0x08
attOpReadByTypeRsp = 0x09
attOpReadReq = 0x0a
attOpReadRsp = 0x0b
attOpReadBlobReq = 0x0c
attOpReadBlobRsp = 0x0d
attOpReadMultiReq = 0x0e
attOpReadMultiRsp = 0x0f
attOpReadByGroupReq = 0x10
attOpReadByGroupRsp = 0x11
attOpWriteReq = 0x12
attOpWriteRsp = 0x13
attOpWriteCmd = 0x52
attOpPrepWriteReq = 0x16
attOpPrepWriteRsp = 0x17
attOpExecWriteReq = 0x18
attOpExecWriteRsp = 0x19
attOpHandleNotify = 0x1b
attOpHandleInd = 0x1d
attOpHandleCnf = 0x1e
attOpSignedWriteCmd = 0xd2
)
type AttEcode byte
const (
AttEcodeSuccess AttEcode = 0x00 // Success
AttEcodeInvalidHandle AttEcode = 0x01 // The attribute handle given was not valid on this server.
AttEcodeReadNotPerm AttEcode = 0x02 // The attribute cannot be read.
AttEcodeWriteNotPerm AttEcode = 0x03 // The attribute cannot be written.
AttEcodeInvalidPDU AttEcode = 0x04 // The attribute PDU was invalid.
AttEcodeAuthentication AttEcode = 0x05 // The attribute requires authentication before it can be read or written.
AttEcodeReqNotSupp AttEcode = 0x06 // Attribute server does not support the request received from the client.
AttEcodeInvalidOffset AttEcode = 0x07 // Offset specified was past the end of the attribute.
AttEcodeAuthorization AttEcode = 0x08 // The attribute requires authorization before it can be read or written.
AttEcodePrepQueueFull AttEcode = 0x09 // Too many prepare writes have been queued.
AttEcodeAttrNotFound AttEcode = 0x0a // No attribute found within the given attribute handle range.
AttEcodeAttrNotLong AttEcode = 0x0b // The attribute cannot be read or written using the Read Blob Request.
AttEcodeInsuffEncrKeySize AttEcode = 0x0c // The Encryption Key Size used for encrypting this link is insufficient.
AttEcodeInvalAttrValueLen AttEcode = 0x0d // The attribute value length is invalid for the operation.
AttEcodeUnlikely AttEcode = 0x0e // The attribute request that was requested has encountered an error that was unlikely, and therefore could not be completed as requested.
AttEcodeInsuffEnc AttEcode = 0x0f // The attribute requires encryption before it can be read or written.
AttEcodeUnsuppGrpType AttEcode = 0x10 // The attribute type is not a supported grouping attribute as defined by a higher layer specification.
AttEcodeInsuffResources AttEcode = 0x11 // Insufficient Resources to complete the request.
)
func (a AttEcode) Error() string {
switch i := int(a); {
case i < 0x11:
return AttEcodeName[a]
case i >= 0x12 && i <= 0x7F: // Reserved for future use
return "reserved error code"
case i >= 0x80 && i <= 0x9F: // Application Error, defined by higher level
return "reserved error code"
case i >= 0xA0 && i <= 0xDF: // Reserved for future use
return "reserved error code"
case i >= 0xE0 && i <= 0xFF: // Common profile and service error codes
return "profile or service error"
default: // can't happen, just make compiler happy
return "unknown error"
}
}
var AttEcodeName = map[AttEcode]string{
AttEcodeSuccess: "success",
AttEcodeInvalidHandle: "invalid handle",
AttEcodeReadNotPerm: "read not permitted",
AttEcodeWriteNotPerm: "write not permitted",
AttEcodeInvalidPDU: "invalid PDU",
AttEcodeAuthentication: "insufficient authentication",
AttEcodeReqNotSupp: "request not supported",
AttEcodeInvalidOffset: "invalid offset",
AttEcodeAuthorization: "insufficient authorization",
AttEcodePrepQueueFull: "prepare queue full",
AttEcodeAttrNotFound: "attribute not found",
AttEcodeAttrNotLong: "attribute not long",
AttEcodeInsuffEncrKeySize: "insufficient encryption key size",
AttEcodeInvalAttrValueLen: "invalid attribute value length",
AttEcodeUnlikely: "unlikely error",
AttEcodeInsuffEnc: "insufficient encryption",
AttEcodeUnsuppGrpType: "unsupported group type",
AttEcodeInsuffResources: "insufficient resources",
}
func attErrorRsp(op byte, h uint16, s AttEcode) []byte {
return attErr{opcode: op, attr: h, status: s}.Marshal()
}
// attRspFor maps from att request
// codes to att response codes.
var attRspFor = map[byte]byte{
attOpMtuReq: attOpMtuRsp,
attOpFindInfoReq: attOpFindInfoRsp,
attOpFindByTypeValueReq: attOpFindByTypeValueRsp,
attOpReadByTypeReq: attOpReadByTypeRsp,
attOpReadReq: attOpReadRsp,
attOpReadBlobReq: attOpReadBlobRsp,
attOpReadMultiReq: attOpReadMultiRsp,
attOpReadByGroupReq: attOpReadByGroupRsp,
attOpWriteReq: attOpWriteRsp,
attOpPrepWriteReq: attOpPrepWriteRsp,
attOpExecWriteReq: attOpExecWriteRsp,
}
type attErr struct {
opcode uint8
attr uint16
status AttEcode
}
// TODO: Reformulate in a way that lets the caller avoid allocs.
// Accept a []byte? Write directly to an io.Writer?
func (e attErr) Marshal() []byte {
// little-endian encoding for attr
return []byte{attOpError, e.opcode, byte(e.attr), byte(e.attr >> 8), byte(e.status)}
}

View file

@ -1,172 +0,0 @@
package gatt
import "errors"
var notImplemented = errors.New("not implemented")
type State int
const (
StateUnknown State = 0
StateResetting State = 1
StateUnsupported State = 2
StateUnauthorized State = 3
StatePoweredOff State = 4
StatePoweredOn State = 5
)
func (s State) String() string {
str := []string{
"Unknown",
"Resetting",
"Unsupported",
"Unauthorized",
"PoweredOff",
"PoweredOn",
}
return str[int(s)]
}
// Device defines the interface for a BLE device.
// Since an interface can't define fields(properties). To implement the
// callback support for cerntain events, deviceHandler is defined and
// implementation of Device on different platforms should embed it in
// order to keep have keep compatible in API level.
// Package users can use the Handler to set these handlers.
type Device interface {
Init(stateChanged func(Device, State)) error
// Advertise advertise AdvPacket
Advertise(a *AdvPacket) error
// AdvertiseNameAndServices advertises device name, and specified service UUIDs.
// It tres to fit the UUIDs in the advertising packet as much as possible.
// If name doesn't fit in the advertising packet, it will be put in scan response.
AdvertiseNameAndServices(name string, ss []UUID) error
// AdvertiseIBeaconData advertise iBeacon with given manufacturer data.
AdvertiseIBeaconData(b []byte) error
// AdvertisingIbeacon advertises iBeacon with specified parameters.
AdvertiseIBeacon(u UUID, major, minor uint16, pwr int8) error
// StopAdvertising stops advertising.
StopAdvertising() error
// RemoveAllServices removes all services that are currently in the database.
RemoveAllServices() error
// Add Service add a service to database.
AddService(s *Service) error
// SetServices set the specified service to the database.
// It removes all currently added services, if any.
SetServices(ss []*Service) error
// Scan discovers surounding remote peripherals that have the Service UUID specified in ss.
// If ss is set to nil, all devices scanned are reported.
// dup specifies weather duplicated advertisement should be reported or not.
// When a remote peripheral is discovered, the PeripheralDiscovered Handler is called.
Scan(ss []UUID, dup bool)
// StopScanning stops scanning.
StopScanning()
// Stop calls OS specific close calls
Stop() error
// Connect connects to a remote peripheral.
Connect(p Peripheral)
// CancelConnection disconnects a remote peripheral.
CancelConnection(p Peripheral)
// Handle registers the specified handlers.
Handle(h ...Handler)
// Option sets the options specified.
Option(o ...Option) error
}
// deviceHandler is the handlers(callbacks) of the Device.
type deviceHandler struct {
// stateChanged is called when the device states changes.
stateChanged func(d Device, s State)
// connect is called when a remote central device connects to the device.
centralConnected func(c Central)
// disconnect is called when a remote central device disconnects to the device.
centralDisconnected func(c Central)
// peripheralDiscovered is called when a remote peripheral device is found during scan procedure.
peripheralDiscovered func(p Peripheral, a *Advertisement, rssi int)
// peripheralConnected is called when a remote peripheral is conneted.
peripheralConnected func(p Peripheral, err error)
// peripheralConnected is called when a remote peripheral is disconneted.
peripheralDisconnected func(p Peripheral, err error)
}
func getDeviceHandler(d Device) *deviceHandler {
switch t := d.(type) {
case *device:
return &t.deviceHandler
case *simDevice:
return &t.deviceHandler
default:
return nil
}
}
// A Handler is a self-referential function, which registers the options specified.
// See http://commandcenter.blogspot.com.au/2014/01/self-referential-functions-and-design.html for more discussion.
type Handler func(Device)
// Handle registers the specified handlers.
func (d *device) Handle(hh ...Handler) {
for _, h := range hh {
h(d)
}
}
// CentralConnected returns a Handler, which sets the specified function to be called when a device connects to the server.
func CentralConnected(f func(Central)) Handler {
return func(d Device) { getDeviceHandler(d).centralConnected = f }
}
// CentralDisconnected returns a Handler, which sets the specified function to be called when a device disconnects from the server.
func CentralDisconnected(f func(Central)) Handler {
return func(d Device) { getDeviceHandler(d).centralDisconnected = f }
}
// PeripheralDiscovered returns a Handler, which sets the specified function to be called when a remote peripheral device is found during scan procedure.
func PeripheralDiscovered(f func(Peripheral, *Advertisement, int)) Handler {
return func(d Device) { getDeviceHandler(d).peripheralDiscovered = f }
}
// PeripheralConnected returns a Handler, which sets the specified function to be called when a remote peripheral device connects.
func PeripheralConnected(f func(Peripheral, error)) Handler {
return func(d Device) { getDeviceHandler(d).peripheralConnected = f }
}
// PeripheralDisconnected returns a Handler, which sets the specified function to be called when a remote peripheral device disconnects.
func PeripheralDisconnected(f func(Peripheral, error)) Handler {
return func(d Device) { getDeviceHandler(d).peripheralDisconnected = f }
}
// An Option is a self-referential function, which sets the option specified.
// Most Options are platform-specific, which gives more fine-grained control over the device at a cost of losing portibility.
// See http://commandcenter.blogspot.com.au/2014/01/self-referential-functions-and-design.html for more discussion.
type Option func(Device) error
// Option sets the options specified.
// Some options can only be set before the device is initialized; they are best used with NewDevice instead of Option.
func (d *device) Option(opts ...Option) error {
var err error
for _, opt := range opts {
err = opt(d)
}
return err
}

View file

@ -1,521 +0,0 @@
package gatt
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"log"
"sync"
"time"
"github.com/bettercap/gatt/xpc"
)
const (
peripheralDiscovered = 37
peripheralConnected = 38
peripheralDisconnected = 40
// below constants for Yosemite
rssiRead = 55
includedServicesDiscovered = 63
serviceDiscovered = 56
characteristicsDiscovered = 64
characteristicRead = 71
characteristicWritten = 72
notificationValueSet = 74
descriptorsDiscovered = 76
descriptorRead = 79
descriptorWritten = 80
)
type device struct {
deviceHandler
conn xpc.XPC
role int // 1: peripheralManager (server), 0: centralManager (client)
reqc chan message
rspc chan message
// Only used in client/centralManager implementation
plist map[string]*peripheral
plistmu *sync.Mutex
// Only used in server/peripheralManager implementation
attrN int
attrs map[int]*attr
subscribers map[string]*central
}
func NewDevice(opts ...Option) (Device, error) {
d := &device{
reqc: make(chan message),
rspc: make(chan message),
plist: map[string]*peripheral{},
plistmu: &sync.Mutex{},
attrN: 1,
attrs: make(map[int]*attr),
subscribers: make(map[string]*central),
}
d.Option(opts...)
d.conn = xpc.XpcConnect("com.apple.blued", d)
return d, nil
}
func (d *device) Init(f func(Device, State)) error {
go d.loop()
rsp := d.sendReq(1, xpc.Dict{
"kCBMsgArgName": fmt.Sprintf("gopher-%v", time.Now().Unix()),
"kCBMsgArgOptions": xpc.Dict{"kCBInitOptionShowPowerAlert": 1},
"kCBMsgArgType": d.role,
})
d.stateChanged = f
go d.stateChanged(d, State(rsp.MustGetInt("kCBMsgArgState")))
return nil
}
func (d *device) Advertise(a *AdvPacket) error {
rsp := d.sendReq(8, xpc.Dict{
"kCBAdvDataAppleMfgData": a.b, // not a.Bytes(). should be slice
})
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
return errors.New("FIXME: Advertise error")
}
return nil
}
func (d *device) AdvertiseNameAndServices(name string, ss []UUID) error {
us := uuidSlice(ss)
rsp := d.sendReq(8, xpc.Dict{
"kCBAdvDataLocalName": name,
"kCBAdvDataServiceUUIDs": us},
)
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
return errors.New("FIXME: Advertise error")
}
return nil
}
func (d *device) AdvertiseIBeaconData(data []byte) error {
var utsname xpc.Utsname
xpc.Uname(&utsname)
var rsp xpc.Dict
if utsname.Release >= "14." {
l := len(data)
buf := bytes.NewBuffer([]byte{byte(l + 5), 0xFF, 0x4C, 0x00, 0x02, byte(l)})
buf.Write(data)
rsp = d.sendReq(8, xpc.Dict{"kCBAdvDataAppleMfgData": buf.Bytes()})
} else {
rsp = d.sendReq(8, xpc.Dict{"kCBAdvDataAppleBeaconKey": data})
}
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
return errors.New("FIXME: Advertise error")
}
return nil
}
func (d *device) AdvertiseIBeacon(u UUID, major, minor uint16, pwr int8) error {
b := make([]byte, 21)
copy(b, reverse(u.b)) // Big endian
binary.BigEndian.PutUint16(b[16:], major) // Big endian
binary.BigEndian.PutUint16(b[18:], minor) // Big endian
b[20] = uint8(pwr) // Measured Tx Power
return d.AdvertiseIBeaconData(b)
}
func (d *device) StopAdvertising() error {
rsp := d.sendReq(9, nil)
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
return errors.New("FIXME: Stop Advertise error")
}
return nil
}
func (d *device) Stop() error {
// No Implementation
defer d.stateChanged(d, StatePoweredOff)
return errors.New("FIXME: Advertise error")
}
func (d *device) RemoveAllServices() error {
d.sendCmd(12, nil)
return nil
}
func (d *device) AddService(s *Service) error {
if s.uuid.Equal(attrGAPUUID) || s.uuid.Equal(attrGATTUUID) {
// skip GATT and GAP services
return nil
}
xs := xpc.Dict{
"kCBMsgArgAttributeID": d.attrN,
"kCBMsgArgAttributeIDs": []int{},
"kCBMsgArgCharacteristics": nil,
"kCBMsgArgType": 1, // 1 => primary, 0 => excluded
"kCBMsgArgUUID": reverse(s.uuid.b),
}
d.attrN++
xcs := xpc.Array{}
for _, c := range s.Characteristics() {
props := 0
perm := 0
if c.props&CharRead != 0 {
props |= 0x02
if CharRead&c.secure != 0 {
perm |= 0x04
} else {
perm |= 0x01
}
}
if c.props&CharWriteNR != 0 {
props |= 0x04
if c.secure&CharWriteNR != 0 {
perm |= 0x08
} else {
perm |= 0x02
}
}
if c.props&CharWrite != 0 {
props |= 0x08
if c.secure&CharWrite != 0 {
perm |= 0x08
} else {
perm |= 0x02
}
}
if c.props&CharNotify != 0 {
if c.secure&CharNotify != 0 {
props |= 0x100
} else {
props |= 0x10
}
}
if c.props&CharIndicate != 0 {
if c.secure&CharIndicate != 0 {
props |= 0x200
} else {
props |= 0x20
}
}
xc := xpc.Dict{
"kCBMsgArgAttributeID": d.attrN,
"kCBMsgArgUUID": reverse(c.uuid.b),
"kCBMsgArgAttributePermissions": perm,
"kCBMsgArgCharacteristicProperties": props,
"kCBMsgArgData": c.value,
}
d.attrs[d.attrN] = &attr{h: uint16(d.attrN), value: c.value, pvt: c}
d.attrN++
xds := xpc.Array{}
for _, d := range c.Descriptors() {
if d.uuid.Equal(attrClientCharacteristicConfigUUID) {
// skip CCCD
continue
}
var v interface{}
if len(d.valuestr) > 0 {
v = d.valuestr
} else {
v = d.value
}
xd := xpc.Dict{
"kCBMsgArgData": v,
"kCBMsgArgUUID": reverse(d.uuid.b),
}
xds = append(xds, xd)
}
xc["kCBMsgArgDescriptors"] = xds
xcs = append(xcs, xc)
}
xs["kCBMsgArgCharacteristics"] = xcs
rsp := d.sendReq(10, xs)
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
return errors.New("FIXME: Add Srvice error")
}
return nil
}
func (d *device) SetServices(ss []*Service) error {
d.RemoveAllServices()
for _, s := range ss {
d.AddService(s)
}
return nil
}
func (d *device) Scan(ss []UUID, dup bool) {
args := xpc.Dict{
"kCBMsgArgUUIDs": uuidSlice(ss),
"kCBMsgArgOptions": xpc.Dict{
"kCBScanOptionAllowDuplicates": map[bool]int{true: 1, false: 0}[dup],
},
}
d.sendCmd(29, args)
}
func (d *device) StopScanning() {
d.sendCmd(30, nil)
}
func (d *device) Connect(p Peripheral) {
pp := p.(*peripheral)
d.plist[pp.id.String()] = pp
d.sendCmd(31,
xpc.Dict{
"kCBMsgArgDeviceUUID": pp.id,
"kCBMsgArgOptions": xpc.Dict{
"kCBConnectOptionNotifyOnDisconnection": 1,
},
})
}
func (d *device) respondToRequest(id int, args xpc.Dict) {
switch id {
case 19: // ReadRequest
u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
t := args.MustGetInt("kCBMsgArgTransactionID")
a := args.MustGetInt("kCBMsgArgAttributeID")
o := args.MustGetInt("kCBMsgArgOffset")
attr := d.attrs[a]
v := attr.value
if v == nil {
c := newCentral(d, u)
req := &ReadRequest{
Request: Request{Central: c},
Cap: int(c.mtu - 1),
Offset: o,
}
rsp := newResponseWriter(int(c.mtu - 1))
if c, ok := attr.pvt.(*Characteristic); ok {
c.rhandler.ServeRead(rsp, req)
v = rsp.bytes()
}
}
d.sendCmd(13, xpc.Dict{
"kCBMsgArgAttributeID": a,
"kCBMsgArgData": v,
"kCBMsgArgTransactionID": t,
"kCBMsgArgResult": 0,
})
case 20: // WriteRequest
u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
t := args.MustGetInt("kCBMsgArgTransactionID")
a := 0
result := byte(0)
noRsp := false
xxws := args.MustGetArray("kCBMsgArgATTWrites")
for _, xxw := range xxws {
xw := xxw.(xpc.Dict)
if a == 0 {
a = xw.MustGetInt("kCBMsgArgAttributeID")
}
o := xw.MustGetInt("kCBMsgArgOffset")
i := xw.MustGetInt("kCBMsgArgIgnoreResponse")
b := xw.MustGetBytes("kCBMsgArgData")
_ = o
attr := d.attrs[a]
c := newCentral(d, u)
r := Request{Central: c}
result = attr.pvt.(*Characteristic).whandler.ServeWrite(r, b)
if i == 1 {
noRsp = true
}
}
if noRsp {
break
}
d.sendCmd(13, xpc.Dict{
"kCBMsgArgAttributeID": a,
"kCBMsgArgData": nil,
"kCBMsgArgTransactionID": t,
"kCBMsgArgResult": result,
})
case 21: // subscribed
u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
a := args.MustGetInt("kCBMsgArgAttributeID")
attr := d.attrs[a]
c := newCentral(d, u)
d.subscribers[u.String()] = c
c.startNotify(attr, c.mtu)
case 22: // unubscribed
u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
a := args.MustGetInt("kCBMsgArgAttributeID")
attr := d.attrs[a]
if c := d.subscribers[u.String()]; c != nil {
c.stopNotify(attr)
}
case 23: // notificationSent
}
}
func (d *device) CancelConnection(p Peripheral) {
d.sendCmd(32, xpc.Dict{"kCBMsgArgDeviceUUID": p.(*peripheral).id})
}
// process device events and asynchronous errors
// (implements XpcEventHandler)
func (d *device) HandleXpcEvent(event xpc.Dict, err error) {
if err != nil {
log.Println("error:", err)
return
}
id := event.MustGetInt("kCBMsgId")
args := event.MustGetDict("kCBMsgArgs")
//log.Printf(">> %d, %v", id, args)
switch id {
case // device event
6, // StateChanged
16, // AdvertisingStarted
17, // AdvertisingStopped
18: // ServiceAdded
d.rspc <- message{id: id, args: args}
case
19, // ReadRequest
20, // WriteRequest
21, // Subscribe
22, // Unubscribe
23: // Confirmation
d.respondToRequest(id, args)
case peripheralDiscovered:
xa := args.MustGetDict("kCBMsgArgAdvertisementData")
if len(xa) == 0 {
return
}
u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
a := &Advertisement{
LocalName: xa.GetString("kCBAdvDataLocalName", args.GetString("kCBMsgArgName", "")),
TxPowerLevel: xa.GetInt("kCBAdvDataTxPowerLevel", 0),
ManufacturerData: xa.GetBytes("kCBAdvDataManufacturerData", nil),
}
rssi := args.MustGetInt("kCBMsgArgRssi")
if xu, ok := xa["kCBAdvDataServiceUUIDs"]; ok {
for _, xs := range xu.(xpc.Array) {
s := UUID{reverse(xs.([]byte))}
a.Services = append(a.Services, s)
}
}
if xsds, ok := xa["kCBAdvDataServiceData"]; ok {
xsd := xsds.(xpc.Array)
for i := 0; i < len(xsd); i += 2 {
sd := ServiceData{
UUID: UUID{xsd[i].([]byte)},
Data: xsd[i+1].([]byte),
}
a.ServiceData = append(a.ServiceData, sd)
}
}
if d.peripheralDiscovered != nil {
go d.peripheralDiscovered(&peripheral{id: xpc.UUID(u.b), d: d}, a, rssi)
}
case peripheralConnected:
u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
p := &peripheral{
id: xpc.UUID(u.b),
d: d,
reqc: make(chan message),
rspc: make(chan message),
quitc: make(chan struct{}),
sub: newSubscriber(),
}
d.plistmu.Lock()
d.plist[u.String()] = p
d.plistmu.Unlock()
go p.loop()
if d.peripheralConnected != nil {
go d.peripheralConnected(p, nil)
}
case peripheralDisconnected:
u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
d.plistmu.Lock()
p := d.plist[u.String()]
delete(d.plist, u.String())
d.plistmu.Unlock()
if p != nil {
if d.peripheralDisconnected != nil {
d.peripheralDisconnected(p, nil) // TODO: Get Result as error?
}
close(p.quitc)
}
case // Peripheral events
rssiRead,
serviceDiscovered,
includedServicesDiscovered,
characteristicsDiscovered,
characteristicRead,
characteristicWritten,
notificationValueSet,
descriptorsDiscovered,
descriptorRead,
descriptorWritten:
u := UUID{args.MustGetUUID("kCBMsgArgDeviceUUID")}
d.plistmu.Lock()
p := d.plist[u.String()]
d.plistmu.Unlock()
if p != nil {
p.rspc <- message{id: id, args: args}
}
default:
//log.Printf("Unhandled event: %#v", event)
}
}
func (d *device) sendReq(id int, args xpc.Dict) xpc.Dict {
m := message{id: id, args: args, rspc: make(chan xpc.Dict)}
d.reqc <- m
return <-m.rspc
}
func (d *device) sendCmd(id int, args xpc.Dict) {
d.reqc <- message{id: id, args: args}
}
func (d *device) loop() {
for req := range d.reqc {
d.sendCBMsg(req.id, req.args)
if req.rspc == nil {
continue
}
m := <-d.rspc
req.rspc <- m.args
}
}
func (d *device) sendCBMsg(id int, args xpc.Dict) {
// log.Printf("<< %d, %v", id, args)
d.conn.Send(xpc.Dict{"kCBMsgId": id, "kCBMsgArgs": args}, false)
}

View file

@ -1,234 +0,0 @@
package gatt
import (
"encoding/binary"
"net"
"github.com/bettercap/gatt/linux"
"github.com/bettercap/gatt/linux/cmd"
)
type device struct {
deviceHandler
hci *linux.HCI
state State
// All the following fields are only used peripheralManager (server) implementation.
svcs []*Service
attrs *attrRange
devID int
chkLE bool
maxConn int
advData *cmd.LESetAdvertisingData
scanResp *cmd.LESetScanResponseData
advParam *cmd.LESetAdvertisingParameters
scanParam *cmd.LESetScanParameters
}
func NewDevice(opts ...Option) (Device, error) {
d := &device{
maxConn: 1, // Support 1 connection at a time.
devID: -1, // Find an available HCI device.
chkLE: true, // Check if the device supports LE.
advParam: &cmd.LESetAdvertisingParameters{
AdvertisingIntervalMin: 0x800, // [0x0800]: 0.625 ms * 0x0800 = 1280.0 ms
AdvertisingIntervalMax: 0x800, // [0x0800]: 0.625 ms * 0x0800 = 1280.0 ms
AdvertisingType: 0x00, // [0x00]: ADV_IND, 0x01: DIRECT(HIGH), 0x02: SCAN, 0x03: NONCONN, 0x04: DIRECT(LOW)
OwnAddressType: 0x00, // [0x00]: public, 0x01: random
DirectAddressType: 0x00, // [0x00]: public, 0x01: random
DirectAddress: [6]byte{}, // Public or Random Address of the device to be connected
AdvertisingChannelMap: 0x7, // [0x07] 0x01: ch37, 0x2: ch38, 0x4: ch39
AdvertisingFilterPolicy: 0x00,
},
scanParam: &cmd.LESetScanParameters{
LEScanType: 0x01, // [0x00]: passive, 0x01: active
LEScanInterval: 0x0010, // [0x10]: 0.625ms * 16
LEScanWindow: 0x0010, // [0x10]: 0.625ms * 16
OwnAddressType: 0x00, // [0x00]: public, 0x01: random
ScanningFilterPolicy: 0x00, // [0x00]: accept all, 0x01: ignore non-white-listed.
},
}
d.Option(opts...)
h, err := linux.NewHCI(d.devID, d.chkLE, d.maxConn)
if err != nil {
return nil, err
}
d.hci = h
return d, nil
}
func (d *device) Init(f func(Device, State)) error {
d.hci.AcceptMasterHandler = func(pd *linux.PlatData) {
a := pd.Address
c := newCentral(d.attrs, net.HardwareAddr([]byte{a[5], a[4], a[3], a[2], a[1], a[0]}), pd.Conn)
if d.centralConnected != nil {
d.centralConnected(c)
}
c.loop()
if d.centralDisconnected != nil {
d.centralDisconnected(c)
}
}
d.hci.AcceptSlaveHandler = func(pd *linux.PlatData) {
p := &peripheral{
d: d,
pd: pd,
l2c: pd.Conn,
reqc: make(chan message),
quitc: make(chan struct{}),
sub: newSubscriber(),
}
if d.peripheralConnected != nil {
go d.peripheralConnected(p, nil)
}
p.loop()
if d.peripheralDisconnected != nil {
d.peripheralDisconnected(p, nil)
}
}
d.hci.AdvertisementHandler = func(pd *linux.PlatData) {
a := &Advertisement{}
a.unmarshall(pd.Data)
a.Connectable = pd.Connectable
p := &peripheral{pd: pd, d: d}
if d.peripheralDiscovered != nil {
pd.Name = a.LocalName
d.peripheralDiscovered(p, a, int(pd.RSSI))
}
}
d.state = StatePoweredOn
d.stateChanged = f
go d.stateChanged(d, d.state)
return nil
}
func (d *device) Stop() error {
d.state = StatePoweredOff
defer d.stateChanged(d, d.state)
return d.hci.Close()
}
func (d *device) AddService(s *Service) error {
d.svcs = append(d.svcs, s)
d.attrs = generateAttributes(d.svcs, uint16(1)) // ble attrs start at 1
return nil
}
func (d *device) RemoveAllServices() error {
d.svcs = nil
d.attrs = nil
return nil
}
func (d *device) SetServices(s []*Service) error {
d.RemoveAllServices()
d.svcs = append(d.svcs, s...)
d.attrs = generateAttributes(d.svcs, uint16(1)) // ble attrs start at 1
return nil
}
func (d *device) Advertise(a *AdvPacket) error {
d.advData = &cmd.LESetAdvertisingData{
AdvertisingDataLength: uint8(a.Len()),
AdvertisingData: a.Bytes(),
}
if err := d.update(); err != nil {
return err
}
return d.hci.SetAdvertiseEnable(true)
}
func (d *device) AdvertiseNameAndServices(name string, uu []UUID) error {
a := &AdvPacket{}
a.AppendFlags(flagGeneralDiscoverable | flagLEOnly)
a.AppendUUIDFit(uu)
if len(a.b)+len(name)+2 < MaxEIRPacketLength {
a.AppendName(name)
d.scanResp = nil
} else {
a := &AdvPacket{}
a.AppendName(name)
d.scanResp = &cmd.LESetScanResponseData{
ScanResponseDataLength: uint8(a.Len()),
ScanResponseData: a.Bytes(),
}
}
return d.Advertise(a)
}
func (d *device) AdvertiseIBeaconData(b []byte) error {
a := &AdvPacket{}
a.AppendFlags(flagGeneralDiscoverable | flagLEOnly)
a.AppendManufacturerData(0x004C, b)
return d.Advertise(a)
}
func (d *device) AdvertiseIBeacon(u UUID, major, minor uint16, pwr int8) error {
b := make([]byte, 23)
b[0] = 0x02 // Data type: iBeacon
b[1] = 0x15 // Data length: 21 bytes
copy(b[2:], reverse(u.b)) // Big endian
binary.BigEndian.PutUint16(b[18:], major) // Big endian
binary.BigEndian.PutUint16(b[20:], minor) // Big endian
b[22] = uint8(pwr) // Measured Tx Power
return d.AdvertiseIBeaconData(b)
}
func (d *device) StopAdvertising() error {
return d.hci.SetAdvertiseEnable(false)
}
func (d *device) Scan(ss []UUID, dup bool) {
// TODO: filter
d.hci.SetScanEnable(true, dup)
}
func (d *device) StopScanning() {
d.hci.SetScanEnable(false, true)
}
func (d *device) Connect(p Peripheral) {
d.hci.Connect(p.(*peripheral).pd)
}
func (d *device) CancelConnection(p Peripheral) {
d.hci.CancelConnection(p.(*peripheral).pd)
}
func (d *device) SendHCIRawCommand(c cmd.CmdParam) ([]byte, error) {
return d.hci.SendRawCommand(c)
}
// Flush pending advertising settings to the device.
func (d *device) update() error {
if d.advParam != nil {
if err := d.hci.SendCmdWithAdvOff(d.advParam); err != nil {
return err
}
d.advParam = nil
}
if d.scanResp != nil {
if err := d.hci.SendCmdWithAdvOff(d.scanResp); err != nil {
return err
}
d.scanResp = nil
}
if d.advData != nil {
if err := d.hci.SendCmdWithAdvOff(d.advData); err != nil {
return err
}
d.advData = nil
}
return nil
}

View file

@ -1,88 +0,0 @@
// Package gatt provides a Bluetooth Low Energy gatt implementation.
//
// Gatt (Generic Attribute Profile) is the protocol used to write
// BLE peripherals (servers) and centrals (clients).
//
// STATUS
//
// This package is a work in progress. The API will change.
//
// As a peripheral, you can create services, characteristics, and descriptors,
// advertise, accept connections, and handle requests.
// As a central, you can scan, connect, discover services, and make requests.
//
// SETUP
//
// gatt supports both Linux and OS X.
//
// On Linux:
// To gain complete and exclusive control of the HCI device, gatt uses
// HCI_CHANNEL_USER (introduced in Linux v3.14) instead of HCI_CHANNEL_RAW.
// Those who must use an older kernel may patch in these relevant commits
// from Marcel Holtmann:
//
// Bluetooth: Introduce new HCI socket channel for user operation
// Bluetooth: Introduce user channel flag for HCI devices
// Bluetooth: Refactor raw socket filter into more readable code
//
// Note that because gatt uses HCI_CHANNEL_USER, once gatt has opened the
// device no other program may access it.
//
// Before starting a gatt program, make sure that your BLE device is down:
//
// sudo hciconfig
// sudo hciconfig hci0 down # or whatever hci device you want to use
//
// If you have BlueZ 5.14+ (or aren't sure), stop the built-in
// bluetooth server, which interferes with gatt, e.g.:
//
// sudo service bluetooth stop
//
// Because gatt programs administer network devices, they must
// either be run as root, or be granted appropriate capabilities:
//
// sudo <executable>
// # OR
// sudo setcap 'cap_net_raw,cap_net_admin=eip' <executable>
// <executable>
//
// USAGE
//
// # Start a simple server.
// sudo go run example/server.go
//
// # Discover surrounding peripherals.
// sudo go run example/discoverer.go
//
// # Connect to and explorer a peripheral device.
// sudo go run example/explorer.go <peripheral ID>
//
// See the server.go, discoverer.go, and explorer.go in the examples/
// directory for writing server or client programs that run on Linux
// and OS X.
//
// Users, especially on Linux platforms, seeking finer-grained control
// over the devices can see the examples/server_lnx.go for the usage
// of Option, which are platform specific.
//
// See the rest of the docs for other options and finer-grained control.
//
// Note that some BLE central devices, particularly iOS, may aggressively
// cache results from previous connections. If you change your services or
// characteristics, you may need to reboot the other device to pick up the
// changes. This is a common source of confusion and apparent bugs. For an
// OS X central, see http://stackoverflow.com/questions/20553957.
//
//
// REFERENCES
//
// gatt started life as a port of bleno, to which it is indebted:
// https://github.com/sandeepmistry/bleno. If you are having
// problems with gatt, particularly around installation, issues
// filed with bleno might also be helpful references.
//
// To try out your GATT server, it is useful to experiment with a
// generic BLE client. LightBlue is a good choice. It is available
// free for both iOS and OS X.
//
package gatt

View file

@ -1,132 +0,0 @@
package gatt
// A dictionary of known service names and type (keyed by service uuid)
var knownServices = map[string]struct{ Name, Type string }{
"1800": {Name: "Generic Access", Type: "org.bluetooth.service.generic_access"},
"1801": {Name: "Generic Attribute", Type: "org.bluetooth.service.generic_attribute"},
"1802": {Name: "Immediate Alert", Type: "org.bluetooth.service.immediate_alert"},
"1803": {Name: "Link Loss", Type: "org.bluetooth.service.link_loss"},
"1804": {Name: "Tx Power", Type: "org.bluetooth.service.tx_power"},
"1805": {Name: "Current Time Service", Type: "org.bluetooth.service.current_time"},
"1806": {Name: "Reference Time Update Service", Type: "org.bluetooth.service.reference_time_update"},
"1807": {Name: "Next DST Change Service", Type: "org.bluetooth.service.next_dst_change"},
"1808": {Name: "Glucose", Type: "org.bluetooth.service.glucose"},
"1809": {Name: "Health Thermometer", Type: "org.bluetooth.service.health_thermometer"},
"180a": {Name: "Device Information", Type: "org.bluetooth.service.device_information"},
"180d": {Name: "Heart Rate", Type: "org.bluetooth.service.heart_rate"},
"180e": {Name: "Phone Alert Status Service", Type: "org.bluetooth.service.phone_alert_service"},
"180f": {Name: "Battery Service", Type: "org.bluetooth.service.battery_service"},
"1810": {Name: "Blood Pressure", Type: "org.bluetooth.service.blood_pressuer"},
"1811": {Name: "Alert Notification Service", Type: "org.bluetooth.service.alert_notification"},
"1812": {Name: "Human Interface Device", Type: "org.bluetooth.service.human_interface_device"},
"1813": {Name: "Scan Parameters", Type: "org.bluetooth.service.scan_parameters"},
"1814": {Name: "Running Speed and Cadence", Type: "org.bluetooth.service.running_speed_and_cadence"},
"1815": {Name: "Cycling Speed and Cadence", Type: "org.bluetooth.service.cycling_speed_and_cadence"},
"d0611e78bbb44591a5f8487910ae4366": {Name: "Apple Continuity Service"},
"7905f431b5ce4e99a40f4b1e122d00d0": {Name: "Apple Notification Center Service"},
"69d1d8f345e149a898219bbdfdaad9d9": {Name: "Control Point"},
"9fbf120d630142d98c5825e699a21dbd": {Name: "Notification Source"},
"22eac6e924d64bb5be44b36ace7c7bfb": {Name: "Data Source"},
"89d3502b0f36433a8ef4c502ad55f8dc": {Name: "Apple Media Service"},
"9b3c81d857b14a8ab8df0e56f7ca51c2": {Name: "Remote Command"},
"2f7cabce808d411f9a0cbb92ba96c102": {Name: "Entity Update"},
"c6b2f38c23ab46d8a6aba3a870bbd5d7": {Name: "Entity Attribute"},
}
// A dictionary of known descriptor names and type (keyed by attribute uuid)
var knownAttributes = map[string]struct{ Name, Type string }{
"2800": {Name: "Primary Service", Type: "org.bluetooth.attribute.gatt.primary_service_declaration"},
"2801": {Name: "Secondary Service", Type: "org.bluetooth.attribute.gatt.secondary_service_declaration"},
"2802": {Name: "Include", Type: "org.bluetooth.attribute.gatt.include_declaration"},
"2803": {Name: "Characteristic", Type: "org.bluetooth.attribute.gatt.characteristic_declaration"},
}
// A dictionary of known descriptor names and type (keyed by descriptor uuid)
var knownDescriptors = map[string]struct{ Name, Type string }{
"2900": {Name: "Characteristic Extended Properties", Type: "org.bluetooth.descriptor.gatt.characteristic_extended_properties"},
"2901": {Name: "Characteristic User Description", Type: "org.bluetooth.descriptor.gatt.characteristic_user_description"},
"2902": {Name: "Client Characteristic Configuration", Type: "org.bluetooth.descriptor.gatt.client_characteristic_configuration"},
"2903": {Name: "Server Characteristic Configuration", Type: "org.bluetooth.descriptor.gatt.server_characteristic_configuration"},
"2904": {Name: "Characteristic Presentation Format", Type: "org.bluetooth.descriptor.gatt.characteristic_presentation_format"},
"2905": {Name: "Characteristic Aggregate Format", Type: "org.bluetooth.descriptor.gatt.characteristic_aggregate_format"},
"2906": {Name: "Valid Range", Type: "org.bluetooth.descriptor.valid_range"},
"2907": {Name: "External Report Reference", Type: "org.bluetooth.descriptor.external_report_reference"},
"2908": {Name: "Report Reference", Type: "org.bluetooth.descriptor.report_reference"},
}
// A dictionary of known characteristic names and type (keyed by characteristic uuid)
var knownCharacteristics = map[string]struct{ Name, Type string }{
"2a00": {Name: "Device Name", Type: "org.bluetooth.characteristic.gap.device_name"},
"2a01": {Name: "Appearance", Type: "org.bluetooth.characteristic.gap.appearance"},
"2a02": {Name: "Peripheral Privacy Flag", Type: "org.bluetooth.characteristic.gap.peripheral_privacy_flag"},
"2a03": {Name: "Reconnection Address", Type: "org.bluetooth.characteristic.gap.reconnection_address"},
"2a04": {Name: "Peripheral Preferred Connection Parameters", Type: "org.bluetooth.characteristic.gap.peripheral_preferred_connection_parameters"},
"2a05": {Name: "Service Changed", Type: "org.bluetooth.characteristic.gatt.service_changed"},
"2a06": {Name: "Alert Level", Type: "org.bluetooth.characteristic.alert_level"},
"2a07": {Name: "Tx Power Level", Type: "org.bluetooth.characteristic.tx_power_level"},
"2a08": {Name: "Date Time", Type: "org.bluetooth.characteristic.date_time"},
"2a09": {Name: "Day of Week", Type: "org.bluetooth.characteristic.day_of_week"},
"2a0a": {Name: "Day Date Time", Type: "org.bluetooth.characteristic.day_date_time"},
"2a0c": {Name: "Exact Time 256", Type: "org.bluetooth.characteristic.exact_time_256"},
"2a0d": {Name: "DST Offset", Type: "org.bluetooth.characteristic.dst_offset"},
"2a0e": {Name: "Time Zone", Type: "org.bluetooth.characteristic.time_zone"},
"2a0f": {Name: "Local Time Information", Type: "org.bluetooth.characteristic.local_time_information"},
"2a11": {Name: "Time with DST", Type: "org.bluetooth.characteristic.time_with_dst"},
"2a12": {Name: "Time Accuracy", Type: "org.bluetooth.characteristic.time_accuracy"},
"2a13": {Name: "Time Source", Type: "org.bluetooth.characteristic.time_source"},
"2a14": {Name: "Reference Time Information", Type: "org.bluetooth.characteristic.reference_time_information"},
"2a16": {Name: "Time Update Control Point", Type: "org.bluetooth.characteristic.time_update_control_point"},
"2a17": {Name: "Time Update State", Type: "org.bluetooth.characteristic.time_update_state"},
"2a18": {Name: "Glucose Measurement", Type: "org.bluetooth.characteristic.glucose_measurement"},
"2a19": {Name: "Battery Level", Type: "org.bluetooth.characteristic.battery_level"},
"2a1c": {Name: "Temperature Measurement", Type: "org.bluetooth.characteristic.temperature_measurement"},
"2a1d": {Name: "Temperature Type", Type: "org.bluetooth.characteristic.temperature_type"},
"2a1e": {Name: "Intermediate Temperature", Type: "org.bluetooth.characteristic.intermediate_temperature"},
"2a21": {Name: "Measurement Interval", Type: "org.bluetooth.characteristic.measurement_interval"},
"2a22": {Name: "Boot Keyboard Input Report", Type: "org.bluetooth.characteristic.boot_keyboard_input_report"},
"2a23": {Name: "System ID", Type: "org.bluetooth.characteristic.system_id"},
"2a24": {Name: "Model Number String", Type: "org.bluetooth.characteristic.model_number_string"},
"2a25": {Name: "Serial Number String", Type: "org.bluetooth.characteristic.serial_number_string"},
"2a26": {Name: "Firmware Revision String", Type: "org.bluetooth.characteristic.firmware_revision_string"},
"2a27": {Name: "Hardware Revision String", Type: "org.bluetooth.characteristic.hardware_revision_string"},
"2a28": {Name: "Software Revision String", Type: "org.bluetooth.characteristic.software_revision_string"},
"2a29": {Name: "Manufacturer Name String", Type: "org.bluetooth.characteristic.manufacturer_name_string"},
"2a2a": {Name: "IEEE 11073-20601 Regulatory Certification Data List", Type: "org.bluetooth.characteristic.ieee_11073-20601_regulatory_certification_data_list"},
"2a2b": {Name: "Current Time", Type: "org.bluetooth.characteristic.current_time"},
"2a31": {Name: "Scan Refresh", Type: "org.bluetooth.characteristic.scan_refresh"},
"2a32": {Name: "Boot Keyboard Output Report", Type: "org.bluetooth.characteristic.boot_keyboard_output_report"},
"2a33": {Name: "Boot Mouse Input Report", Type: "org.bluetooth.characteristic.boot_mouse_input_report"},
"2a34": {Name: "Glucose Measurement Context", Type: "org.bluetooth.characteristic.glucose_measurement_context"},
"2a35": {Name: "Blood Pressure Measurement", Type: "org.bluetooth.characteristic.blood_pressure_measurement"},
"2a36": {Name: "Intermediate Cuff Pressure", Type: "org.bluetooth.characteristic.intermediate_blood_pressure"},
"2a37": {Name: "Heart Rate Measurement", Type: "org.bluetooth.characteristic.heart_rate_measurement"},
"2a38": {Name: "Body Sensor Location", Type: "org.bluetooth.characteristic.body_sensor_location"},
"2a39": {Name: "Heart Rate Control Point", Type: "org.bluetooth.characteristic.heart_rate_control_point"},
"2a3f": {Name: "Alert Status", Type: "org.bluetooth.characteristic.alert_status"},
"2a40": {Name: "Ringer Control Point", Type: "org.bluetooth.characteristic.ringer_control_point"},
"2a41": {Name: "Ringer Setting", Type: "org.bluetooth.characteristic.ringer_setting"},
"2a42": {Name: "Alert Category ID Bit Mask", Type: "org.bluetooth.characteristic.alert_category_id_bit_mask"},
"2a43": {Name: "Alert Category ID", Type: "org.bluetooth.characteristic.alert_category_id"},
"2a44": {Name: "Alert Notification Control Point", Type: "org.bluetooth.characteristic.alert_notification_control_point"},
"2a45": {Name: "Unread Alert Status", Type: "org.bluetooth.characteristic.unread_alert_status"},
"2a46": {Name: "New Alert", Type: "org.bluetooth.characteristic.new_alert"},
"2a47": {Name: "Supported New Alert Category", Type: "org.bluetooth.characteristic.supported_new_alert_category"},
"2a48": {Name: "Supported Unread Alert Category", Type: "org.bluetooth.characteristic.supported_unread_alert_category"},
"2a49": {Name: "Blood Pressure Feature", Type: "org.bluetooth.characteristic.blood_pressure_feature"},
"2a4a": {Name: "HID Information", Type: "org.bluetooth.characteristic.hid_information"},
"2a4b": {Name: "Report Map", Type: "org.bluetooth.characteristic.report_map"},
"2a4c": {Name: "HID Control Point", Type: "org.bluetooth.characteristic.hid_control_point"},
"2a4d": {Name: "Report", Type: "org.bluetooth.characteristic.report"},
"2a4e": {Name: "Protocol Mode", Type: "org.bluetooth.characteristic.protocol_mode"},
"2a4f": {Name: "Scan Interval Window", Type: "org.bluetooth.characteristic.scan_interval_window"},
"2a50": {Name: "PnP ID", Type: "org.bluetooth.characteristic.pnp_id"},
"2a51": {Name: "Glucose Feature", Type: "org.bluetooth.characteristic.glucose_feature"},
"2a52": {Name: "Record Access Control Point", Type: "org.bluetooth.characteristic.record_access_control_point"},
"2a53": {Name: "RSC Measurement", Type: "org.bluetooth.characteristic.rsc_measurement"},
"2a54": {Name: "RSC Feature", Type: "org.bluetooth.characteristic.rsc_feature"},
"2a55": {Name: "SC Control Point", Type: "org.bluetooth.characteristic.sc_control_point"},
"2a5b": {Name: "CSC Measurement", Type: "org.bluetooth.characteristic.csc_measurement"},
"2a5c": {Name: "CSC Feature", Type: "org.bluetooth.characteristic.csc_feature"},
"2a5d": {Name: "Sensor Location", Type: "org.bluetooth.characteristic.sensor_location"},
}

View file

@ -1,156 +0,0 @@
package gatt
import "encoding/binary"
// l2capWriter helps create l2cap responses.
// It is not meant to be used with large writes.
// TODO: benchmark the number of allocs here.
// Reduce by letting WriteByteFit, WriteUint16Fit, etc.
// extend b/chunk and write into it directly.
type l2capWriter struct {
mtu int
b []byte
chunk []byte
chunked bool
}
func newL2capWriter(mtu uint16) *l2capWriter {
return &l2capWriter{mtu: int(mtu), b: make([]byte, 0, mtu)}
}
// Chunk starts writing a new chunk. This chunk
// is not committed until Commit is called.
// Chunk panics if another chunk has already been
// started and not committed.
func (w *l2capWriter) Chunk() {
if w.chunked {
panic("l2capWriter: chunk called twice without committing")
}
w.chunked = true
if w.chunk == nil {
w.chunk = make([]byte, 0, w.mtu)
}
}
// Commit writes the current chunk and reports whether the
// write succeeded. The write succeeds iff there is enough room.
// Commit panics if no chunk has been started.
func (w *l2capWriter) Commit() bool {
if !w.chunked {
panic("l2capWriter: commit without starting a chunk")
}
var success bool
if len(w.b)+len(w.chunk) <= w.mtu {
success = true
w.b = append(w.b, w.chunk...)
}
w.chunk = w.chunk[:0]
w.chunked = false
return success
}
// CommitFit writes as much of the current chunk as possible,
// truncating as needed.
// CommitFit panics if no chunk has been started.
func (w *l2capWriter) CommitFit() {
if !w.chunked {
panic("l2capWriter: CommitFit without starting a chunk")
}
writeable := w.mtu - len(w.b)
if writeable > len(w.chunk) {
writeable = len(w.chunk)
}
w.b = append(w.b, w.chunk[:writeable]...)
w.chunk = w.chunk[:0]
w.chunked = false
}
// WriteByteFit writes b.
// It reports whether the write succeeded,
// using the criteria of WriteFit.
func (w *l2capWriter) WriteByteFit(b byte) bool {
return w.WriteFit([]byte{b})
}
// WriteUint16Fit writes v using BLE (LittleEndian) encoding.
// It reports whether the write succeeded, using the
// criteria of WriteFit.
func (w *l2capWriter) WriteUint16Fit(v uint16) bool {
b := make([]byte, 2)
binary.LittleEndian.PutUint16(b, v)
return w.WriteFit(b)
}
// WriteUUIDFit writes uuid using BLE (reversed) encoding.
// It reports whether the write succeeded, using the
// criteria of WriteFit.
func (w *l2capWriter) WriteUUIDFit(u UUID) bool {
return w.WriteFit(u.b)
}
// Writeable returns the number of bytes from b
// that would be written if pad bytes were written,
// then as much of b as fits were written. When
// writing to a chunk, any amount of bytes may be
// written.
func (w *l2capWriter) Writeable(pad int, b []byte) int {
if w.chunked {
return len(b)
}
avail := w.mtu - len(w.b) - pad
if avail > len(b) {
return len(b)
}
if avail < 0 {
return 0
}
return avail
}
// WriteFit writes as much of b as fits.
// It reports whether the write succeeded without
// truncation. A write succeeds without truncation
// iff a chunk write is in progress or the entire
// contents were written (without exceeding the mtu).
func (w *l2capWriter) WriteFit(b []byte) bool {
if w.chunked {
w.chunk = append(w.chunk, b...)
return true
}
avail := w.mtu - len(w.b)
if avail >= len(b) {
w.b = append(w.b, b...)
return true
}
w.b = append(w.b, b[:avail]...)
return false
}
// ChunkSeek discards the first offset bytes from the
// current chunk. It reports whether there were at least
// offset bytes available to discard.
// It panics if a chunked write is not in progress.
func (w *l2capWriter) ChunkSeek(offset uint16) bool {
if !w.chunked {
panic("l2capWriter: ChunkSeek requested without chunked write in progress")
}
if len(w.chunk) < int(offset) {
w.chunk = w.chunk[:0]
return false
}
w.chunk = w.chunk[offset:]
return true
}
// Bytes returns the written bytes.
// It will panic if a chunked write
// is in progress.
// It is meant to be used when writing
// is completed. It does not return a copy.
// Don't abuse this, it's not worth it.
func (w *l2capWriter) Bytes() []byte {
if w.chunked {
panic("l2capWriter: Bytes requested while chunked write in progress")
}
return w.b
}

View file

@ -1,995 +0,0 @@
package cmd
import (
"bytes"
"errors"
"fmt"
"io"
"log"
"github.com/bettercap/gatt/linux/evt"
"github.com/bettercap/gatt/linux/util"
)
type CmdParam interface {
Marshal([]byte)
Opcode() int
Len() int
}
func NewCmd(d io.Writer) *Cmd {
c := &Cmd{
dev: d,
sent: []*cmdPkt{},
compc: make(chan evt.CommandCompleteEP),
statusc: make(chan evt.CommandStatusEP),
}
go c.processCmdEvents()
return c
}
type cmdPkt struct {
op int
cp CmdParam
done chan []byte
}
func (c cmdPkt) Marshal() []byte {
b := make([]byte, 1+2+1+c.cp.Len())
b[0] = byte(0x1) // typCommandPkt
b[1] = byte(c.op)
b[2] = byte(c.op >> 8)
b[3] = byte(c.cp.Len())
c.cp.Marshal(b[4:])
return b
}
type Cmd struct {
dev io.Writer
sent []*cmdPkt
compc chan evt.CommandCompleteEP
statusc chan evt.CommandStatusEP
}
func (c Cmd) trace(fmt string, v ...interface{}) {}
func (c *Cmd) HandleComplete(b []byte) error {
var e evt.CommandCompleteEP
if err := e.Unmarshal(b); err != nil {
return err
}
c.compc <- e
return nil
}
func (c *Cmd) HandleStatus(b []byte) error {
var e evt.CommandStatusEP
if err := e.Unmarshal(b); err != nil {
return err
}
c.statusc <- e
return nil
}
func (c *Cmd) Send(cp CmdParam) ([]byte, error) {
op := cp.Opcode()
p := &cmdPkt{op: op, cp: cp, done: make(chan []byte)}
raw := p.Marshal()
c.sent = append(c.sent, p)
if n, err := c.dev.Write(raw); err != nil {
return nil, err
} else if n != len(raw) {
return nil, errors.New("Failed to send whole Cmd pkt to HCI socket")
}
return <-p.done, nil
}
func (c *Cmd) SendAndCheckResp(cp CmdParam, exp []byte) error {
rsp, err := c.Send(cp)
if err != nil {
return err
}
// Don't care about the response
if len(exp) == 0 {
return nil
}
// Check the if status is one of the expected value
if !bytes.Contains(exp, rsp[0:1]) {
return fmt.Errorf("HCI command: '0x%04x' return 0x%02X, expect: [%X] ", cp.Opcode(), rsp[0], exp)
}
return nil
}
func (c *Cmd) processCmdEvents() {
for {
select {
case status := <-c.statusc:
found := false
for i, p := range c.sent {
if uint16(p.op) == status.CommandOpcode {
found = true
c.sent = append(c.sent[:i], c.sent[i+1:]...)
close(p.done)
break
}
}
if !found {
log.Printf("Can't find the cmdPkt for this CommandStatusEP: %v", status)
}
case comp := <-c.compc:
found := false
for i, p := range c.sent {
if uint16(p.op) == comp.CommandOPCode {
found = true
c.sent = append(c.sent[:i], c.sent[i+1:]...)
p.done <- comp.ReturnParameters
break
}
}
if !found {
log.Printf("Can't find the cmdPkt for this CommandCompleteEP: %v", comp)
}
}
}
}
const (
linkCtl = 0x01
linkPolicy = 0x02
hostCtl = 0x03
infoParam = 0x04
statusParam = 0x05
testingCmd = 0X3E
leCtl = 0x08
vendorCmd = 0X3F
)
const (
opInquiry = linkCtl<<10 | 0x0001 // Inquiry
opInquiryCancel = linkCtl<<10 | 0x0002 // Inquiry Cancel
opPeriodicInquiry = linkCtl<<10 | 0x0003 // Periodic Inquiry Mode
opExitPeriodicInquiry = linkCtl<<10 | 0x0004 // Exit Periodic Inquiry Mode
opCreateConn = linkCtl<<10 | 0x0005 // Create Connection
opDisconnect = linkCtl<<10 | 0x0006 // Disconnect
opCreateConnCancel = linkCtl<<10 | 0x0008 // Create Connection Cancel
opAcceptConnReq = linkCtl<<10 | 0x0009 // Accept Connection Request
opRejectConnReq = linkCtl<<10 | 0x000A // Reject Connection Request
opLinkKeyReply = linkCtl<<10 | 0x000B // Link Key Request Reply
opLinkKeyNegReply = linkCtl<<10 | 0x000C // Link Key Request Negative Reply
opPinCodeReply = linkCtl<<10 | 0x000D // PIN Code Request Reply
opPinCodeNegReply = linkCtl<<10 | 0x000E // PIN Code Request Negative Reply
opSetConnPtype = linkCtl<<10 | 0x000F // Change Connection Packet Type
opAuthRequested = linkCtl<<10 | 0x0011 // Authentication Request
opSetConnEncrypt = linkCtl<<10 | 0x0013 // Set Connection Encryption
opChangeConnLinkKey = linkCtl<<10 | 0x0015 // Change Connection Link Key
opMasterLinkKey = linkCtl<<10 | 0x0017 // Master Link Key
opRemoteNameReq = linkCtl<<10 | 0x0019 // Remote Name Request
opRemoteNameReqCancel = linkCtl<<10 | 0x001A // Remote Name Request Cancel
opReadRemoteFeatures = linkCtl<<10 | 0x001B // Read Remote Supported Features
opReadRemoteExtFeatures = linkCtl<<10 | 0x001C // Read Remote Extended Features
opReadRemoteVersion = linkCtl<<10 | 0x001D // Read Remote Version Information
opReadClockOffset = linkCtl<<10 | 0x001F // Read Clock Offset
opReadLMPHandle = linkCtl<<10 | 0x0020 // Read LMP Handle
opSetupSyncConn = linkCtl<<10 | 0x0028 // Setup Synchronous Connection
opAcceptSyncConnReq = linkCtl<<10 | 0x0029 // Aceept Synchronous Connection
opRejectSyncConnReq = linkCtl<<10 | 0x002A // Recject Synchronous Connection
opIOCapabilityReply = linkCtl<<10 | 0x002B // IO Capability Request Reply
opUserConfirmReply = linkCtl<<10 | 0x002C // User Confirmation Request Reply
opUserConfirmNegReply = linkCtl<<10 | 0x002D // User Confirmation Negative Reply
opUserPasskeyReply = linkCtl<<10 | 0x002E // User Passkey Request Reply
opUserPasskeyNegReply = linkCtl<<10 | 0x002F // User Passkey Request Negative Reply
opRemoteOOBDataReply = linkCtl<<10 | 0x0030 // Remote OOB Data Request Reply
opRemoteOOBDataNegReply = linkCtl<<10 | 0x0033 // Remote OOB Data Request Negative Reply
opIOCapabilityNegReply = linkCtl<<10 | 0x0034 // IO Capability Request Negative Reply
opCreatePhysicalLink = linkCtl<<10 | 0x0035 // Create Physical Link
opAcceptPhysicalLink = linkCtl<<10 | 0x0036 // Accept Physical Link
opDisconnectPhysicalLink = linkCtl<<10 | 0x0037 // Disconnect Physical Link
opCreateLogicalLink = linkCtl<<10 | 0x0038 // Create Logical Link
opAcceptLogicalLink = linkCtl<<10 | 0x0039 // Accept Logical Link
opDisconnectLogicalLink = linkCtl<<10 | 0x003A // Disconnect Logical Link
opLogicalLinkCancel = linkCtl<<10 | 0x003B // Logical Link Cancel
opFlowSpecModify = linkCtl<<10 | 0x003C // Flow Spec Modify
)
const (
opHoldMode = linkPolicy<<10 | 0x0001 // Hold Mode
opSniffMode = linkPolicy<<10 | 0x0003 // Sniff Mode
opExitSniffMode = linkPolicy<<10 | 0x0004 // Exit Sniff Mode
opParkMode = linkPolicy<<10 | 0x0005 // Park State
opExitParkMode = linkPolicy<<10 | 0x0006 // Exit Park State
opQoSSetup = linkPolicy<<10 | 0x0007 // QoS Setup
opRoleDiscovery = linkPolicy<<10 | 0x0009 // Role Discovery
opSwitchRole = linkPolicy<<10 | 0x000B // Switch Role
opReadLinkPolicy = linkPolicy<<10 | 0x000C // Read Link Policy Settings
opWriteLinkPolicy = linkPolicy<<10 | 0x000D // Write Link Policy Settings
opReadDefaultLinkPolicy = linkPolicy<<10 | 0x000E // Read Default Link Policy Settings
opWriteDefaultLinkPolicy = linkPolicy<<10 | 0x000F // Write Default Link Policy Settings
opFlowSpecification = linkPolicy<<10 | 0x0010 // Flow Specification
opSniffSubrating = linkPolicy<<10 | 0x0011 // Sniff Subrating
)
const (
opSetEventMask = hostCtl<<10 | 0x0001 // Set Event Mask
opReset = hostCtl<<10 | 0x0003 // Reset
opSetEventFlt = hostCtl<<10 | 0x0005 // Set Event Filter
opFlush = hostCtl<<10 | 0x0008 // Flush
opReadPinType = hostCtl<<10 | 0x0009 // Read PIN Type
opWritePinType = hostCtl<<10 | 0x000A // Write PIN Type
opCreateNewUnitKey = hostCtl<<10 | 0x000B // Create New Unit Key
opReadStoredLinkKey = hostCtl<<10 | 0x000D // Read Stored Link Key
opWriteStoredLinkKey = hostCtl<<10 | 0x0011 // Write Stored Link Key
opDeleteStoredLinkKey = hostCtl<<10 | 0x0012 // Delete Stored Link Key
opWriteLocalName = hostCtl<<10 | 0x0013 // Write Local Name
opReadLocalName = hostCtl<<10 | 0x0014 // Read Local Name
opReadConnAcceptTimeout = hostCtl<<10 | 0x0015 // Read Connection Accept Timeout
opWriteConnAcceptTimeout = hostCtl<<10 | 0x0016 // Write Connection Accept Timeout
opReadPageTimeout = hostCtl<<10 | 0x0017 // Read Page Timeout
opWritePageTimeout = hostCtl<<10 | 0x0018 // Write Page Timeout
opReadScanEnable = hostCtl<<10 | 0x0019 // Read Scan Enable
opWriteScanEnable = hostCtl<<10 | 0x001A // Write Scan Enable
opReadPageActivity = hostCtl<<10 | 0x001B // Read Page Scan Activity
opWritePageActivity = hostCtl<<10 | 0x001C // Write Page Scan Activity
opReadInqActivity = hostCtl<<10 | 0x001D // Read Inquiry Scan Activity
opWriteInqActivity = hostCtl<<10 | 0x001E // Write Inquiry Scan Activity
opReadAuthEnable = hostCtl<<10 | 0x001F // Read Authentication Enable
opWriteAuthEnable = hostCtl<<10 | 0x0020 // Write Authentication Enable
opReadEncryptMode = hostCtl<<10 | 0x0021
opWriteEncryptMode = hostCtl<<10 | 0x0022
opReadClassOfDev = hostCtl<<10 | 0x0023 // Read Class of Device
opWriteClassOfDevice = hostCtl<<10 | 0x0024 // Write Class of Device
opReadVoiceSetting = hostCtl<<10 | 0x0025 // Read Voice Setting
opWriteVoiceSetting = hostCtl<<10 | 0x0026 // Write Voice Setting
opReadAutomaticFlushTimeout = hostCtl<<10 | 0x0027 // Read Automatic Flush Timeout
opWriteAutomaticFlushTimeout = hostCtl<<10 | 0x0028 // Write Automatic Flush Timeout
opReadNumBroadcastRetrans = hostCtl<<10 | 0x0029 // Read Num Broadcast Retransmissions
opWriteNumBroadcastRetrans = hostCtl<<10 | 0x002A // Write Num Broadcast Retransmissions
opReadHoldModeActivity = hostCtl<<10 | 0x002B // Read Hold Mode Activity
opWriteHoldModeActivity = hostCtl<<10 | 0x002C // Write Hold Mode Activity
opReadTransmitPowerLevel = hostCtl<<10 | 0x002D // Read Transmit Power Level
opReadSyncFlowEnable = hostCtl<<10 | 0x002E // Read Synchronous Flow Control
opWriteSyncFlowEnable = hostCtl<<10 | 0x002F // Write Synchronous Flow Control
opSetControllerToHostFC = hostCtl<<10 | 0x0031 // Set Controller To Host Flow Control
opHostBufferSize = hostCtl<<10 | 0x0033 // Host Buffer Size
opHostNumCompPkts = hostCtl<<10 | 0x0035 // Host Number Of Completed Packets
opReadLinkSupervisionTimeout = hostCtl<<10 | 0x0036 // Read Link Supervision Timeout
opWriteLinkSupervisionTimeout = hostCtl<<10 | 0x0037 // Write Link Supervision Timeout
opReadNumSupportedIAC = hostCtl<<10 | 0x0038 // Read Number Of Supported IAC
opReadCurrentIACLAP = hostCtl<<10 | 0x0039 // Read Current IAC LAP
opWriteCurrentIACLAP = hostCtl<<10 | 0x003A // Write Current IAC LAP
opReadPageScanPeriodMode = hostCtl<<10 | 0x003B
opWritePageScanPeriodMode = hostCtl<<10 | 0x003C
opReadPageScanMode = hostCtl<<10 | 0x003D
opWritePageScanMode = hostCtl<<10 | 0x003E
opSetAFHClassification = hostCtl<<10 | 0x003F // Set AFH Host Channel Classification
opReadInquiryScanType = hostCtl<<10 | 0x0042 // Read Inquiry Scan Type
opWriteInquiryScanType = hostCtl<<10 | 0x0043 // Write Inquiry Scan Type
opReadInquiryMode = hostCtl<<10 | 0x0044 // Read Inquiry Mode
opWriteInquiryMode = hostCtl<<10 | 0x0045 // Write Inquiry Mode
opReadPageScanType = hostCtl<<10 | 0x0046 // Read Page Scan Type
opWritePageScanType = hostCtl<<10 | 0x0047 // Write Page Scan Type
opReadAFHMode = hostCtl<<10 | 0x0048 // Read AFH Channel Assessment Mode
opWriteAFHMode = hostCtl<<10 | 0x0049 // Write AFH Channel Assesment Mode
opReadExtInquiryResponse = hostCtl<<10 | 0x0051 // Read Extended Inquiry Response
opWriteExtInquiryResponse = hostCtl<<10 | 0x0052 // Write Extended Inquiry Response
opRefreshEncryptionKey = hostCtl<<10 | 0x0053 // Refresh Encryption Key
opReadSimplePairingMode = hostCtl<<10 | 0x0055 // Read Simple Pairing Mode
opWriteSimplePairingMode = hostCtl<<10 | 0x0056 // Write Simple Pairing Mode
opReadLocalOobData = hostCtl<<10 | 0x0057 // Read Local OOB Data
opReadInqResponseTransmitPowerLevel = hostCtl<<10 | 0x0058 // Read Inquiry Response Transmit Power Level
opWriteInquiryTransmitPowerLevel = hostCtl<<10 | 0x0059 // Write Inquiry Response Transmit Power Level
opReadDefaultErrorDataReporting = hostCtl<<10 | 0x005A // Read Default Erroneous Data Reporting
opWriteDefaultErrorDataReporting = hostCtl<<10 | 0x005B // Write Default Erroneous Data Reporting
opEnhancedFlush = hostCtl<<10 | 0x005F // Enhanced Flush
opSendKeypressNotify = hostCtl<<10 | 0x0060 // send Keypress Notification
opReadLogicalLinkAcceptTimeout = hostCtl<<10 | 0x0061 // Read Logical Link Accept Timeout
opWriteLogicalLinkAcceptTimeout = hostCtl<<10 | 0x0062 // Write Logical Link Accept Timeout
opSetEventMaskPage2 = hostCtl<<10 | 0x0063 // Set Event Mask Page 2
opReadLocationData = hostCtl<<10 | 0x0064 // Read Location Data
opWriteLocationData = hostCtl<<10 | 0x0065 // Write Location Data
opReadFlowControlMode = hostCtl<<10 | 0x0066 // Read Flow Control Mode
opWriteFlowControlMode = hostCtl<<10 | 0x0067 // Write Flow Control Mode
opReadEnhancedTransmitpowerLevel = hostCtl<<10 | 0x0068 // Read Enhanced Transmit Power Level
opReadBestEffortFlushTimeout = hostCtl<<10 | 0x0069 // Read Best Effort Flush Timeout
opWriteBestEffortFlushTimeout = hostCtl<<10 | 0x006A // Write Best Effort Flush Timeout
opReadLEHostSupported = hostCtl<<10 | 0x006C // Read LE Host Supported
opWriteLEHostSupported = hostCtl<<10 | 0x006D // Write LE Host Supported
)
const (
opReadLocalVersionInformation = infoParam<<10 | 0x0001 // Read Local Version Information
opReadLocalSupportedCommands = infoParam<<10 | 0x0002 // Read Local Supported Commands
opReadLocalSupportedFeatures = infoParam<<10 | 0x0003 // Read Local Supported Features
opReadLocalExtendedFeatures = infoParam<<10 | 0x0004 // Read Local Extended Features
opReadBufferSize = infoParam<<10 | 0x0005 // Read Buffer Size
opReadBDADDR = infoParam<<10 | 0x0009 // Read BD_ADDR
opReadDataBlockSize = infoParam<<10 | 0x000A // Read Data Block Size
opReadLocalSupportedCodecs = infoParam<<10 | 0x000B // Read Local Supported Codecs
)
const (
opLESetEventMask = leCtl<<10 | 0x0001 // LE Set Event Mask
opLEReadBufferSize = leCtl<<10 | 0x0002 // LE Read Buffer Size
opLEReadLocalSupportedFeatures = leCtl<<10 | 0x0003 // LE Read Local Supported Features
opLESetRandomAddress = leCtl<<10 | 0x0005 // LE Set Random Address
opLESetAdvertisingParameters = leCtl<<10 | 0x0006 // LE Set Advertising Parameters
opLEReadAdvertisingChannelTxPower = leCtl<<10 | 0x0007 // LE Read Advertising Channel Tx Power
opLESetAdvertisingData = leCtl<<10 | 0x0008 // LE Set Advertising Data
opLESetScanResponseData = leCtl<<10 | 0x0009 // LE Set Scan Response Data
opLESetAdvertiseEnable = leCtl<<10 | 0x000a // LE Set Advertising Enable
opLESetScanParameters = leCtl<<10 | 0x000b // LE Set Scan Parameters
opLESetScanEnable = leCtl<<10 | 0x000c // LE Set Scan Enable
opLECreateConn = leCtl<<10 | 0x000d // LE Create Connection
opLECreateConnCancel = leCtl<<10 | 0x000e // LE Create Connection Cancel
opLEReadWhiteListSize = leCtl<<10 | 0x000f // LE Read White List Size
opLEClearWhiteList = leCtl<<10 | 0x0010 // LE Clear White List
opLEAddDeviceToWhiteList = leCtl<<10 | 0x0011 // LE Add Device To White List
opLERemoveDeviceFromWhiteList = leCtl<<10 | 0x0012 // LE Remove Device From White List
opLEConnUpdate = leCtl<<10 | 0x0013 // LE Connection Update
opLESetHostChannelClassification = leCtl<<10 | 0x0014 // LE Set Host Channel Classification
opLEReadChannelMap = leCtl<<10 | 0x0015 // LE Read Channel Map
opLEReadRemoteUsedFeatures = leCtl<<10 | 0x0016 // LE Read Remote Used Features
opLEEncrypt = leCtl<<10 | 0x0017 // LE Encrypt
opLERand = leCtl<<10 | 0x0018 // LE Rand
opLEStartEncryption = leCtl<<10 | 0x0019 // LE Star Encryption
opLELTKReply = leCtl<<10 | 0x001a // LE Long Term Key Request Reply
opLELTKNegReply = leCtl<<10 | 0x001b // LE Long Term Key Request Negative Reply
opLEReadSupportedStates = leCtl<<10 | 0x001c // LE Read Supported States
opLEReceiverTest = leCtl<<10 | 0x001d // LE Reciever Test
opLETransmitterTest = leCtl<<10 | 0x001e // LE Transmitter Test
opLETestEnd = leCtl<<10 | 0x001f // LE Test End
opLERemoteConnectionParameterReply = leCtl<<10 | 0x0020 // LE Remote Connection Parameter Request Reply
opLERemoteConnectionParameterNegReply = leCtl<<10 | 0x0021 // LE Remote Connection Parameter Request Negative Reply
)
var o = util.Order
// Link Control Commands
// Disconnect (0x0006)
type Disconnect struct {
ConnectionHandle uint16
Reason uint8
}
func (c Disconnect) Opcode() int { return opDisconnect }
func (c Disconnect) Len() int { return 3 }
func (c Disconnect) Marshal(b []byte) {
o.PutUint16(b[0:], c.ConnectionHandle)
b[2] = c.Reason
}
// No Return Parameters, Check for Disconnection Complete Event
type DisconnectRP struct{}
// Link Policy Commands
// Write Default Link Policy
type WriteDefaultLinkPolicy struct{ DefaultLinkPolicySettings uint16 }
func (c WriteDefaultLinkPolicy) Opcode() int { return opWriteDefaultLinkPolicy }
func (c WriteDefaultLinkPolicy) Len() int { return 2 }
func (c WriteDefaultLinkPolicy) Marshal(b []byte) { o.PutUint16(b, c.DefaultLinkPolicySettings) }
type WriteDefaultLinkPolicyRP struct{ Status uint8 }
// Host Control Commands
// Set Event Mask (0x0001)
type SetEventMask struct{ EventMask uint64 }
func (c SetEventMask) Opcode() int { return opSetEventMask }
func (c SetEventMask) Len() int { return 8 }
func (c SetEventMask) Marshal(b []byte) { o.PutUint64(b, c.EventMask) }
type SetEventMaskRP struct{ Status uint8 }
// Reset (0x0002)
type Reset struct{}
func (c Reset) Opcode() int { return opReset }
func (c Reset) Len() int { return 0 }
func (c Reset) Marshal(b []byte) {}
type ResetRP struct{ Status uint8 }
// Set Event Filter (0x0003)
// FIXME: This structures are overloading.
// Both Marshal() and Len() are just placeholder.
// Need more effort for decoding.
// type SetEventFlt struct {
// FilterType uint8
// FilterConditionType uint8
// Condition uint8
// }
// func (c SetEventFlt) Opcode() int { return opSetEventFlt }
// func (c SetEventFlt) Len() int { return 0 }
// func (c SetEventFlt) Marshal(b []byte) {}
type SetEventFltRP struct{ Status uint8 }
// Flush (0x0008)
type Flush struct{ ConnectionHandle uint16 }
func (c Flush) Opcode() int { return opFlush }
func (c Flush) Len() int { return 2 }
func (c Flush) Marshal(b []byte) { o.PutUint16(b, c.ConnectionHandle) }
type flushRP struct{ status uint8 }
// Write Page Timeout (0x0018)
type WritePageTimeout struct{ PageTimeout uint16 }
func (c WritePageTimeout) Opcode() int { return opWritePageTimeout }
func (c WritePageTimeout) Len() int { return 2 }
func (c WritePageTimeout) Marshal(b []byte) { o.PutUint16(b, c.PageTimeout) }
type WritePageTimeoutRP struct{}
// Write Class of Device (0x0024)
type WriteClassOfDevice struct{ ClassOfDevice [3]byte }
func (c WriteClassOfDevice) Opcode() int { return opWriteClassOfDevice }
func (c WriteClassOfDevice) Len() int { return 3 }
func (c WriteClassOfDevice) Marshal(b []byte) { copy(b, c.ClassOfDevice[:]) }
type WriteClassOfDevRP struct{ status uint8 }
// Write Host Buffer Size (0x0033)
type HostBufferSize struct {
HostACLDataPacketLength uint16
HostSynchronousDataPacketLength uint8
HostTotalNumACLDataPackets uint16
HostTotalNumSynchronousDataPackets uint16
}
func (c HostBufferSize) Opcode() int { return opHostBufferSize }
func (c HostBufferSize) Len() int { return 7 }
func (c HostBufferSize) Marshal(b []byte) {
o.PutUint16(b[0:], c.HostACLDataPacketLength)
o.PutUint8(b[2:], c.HostSynchronousDataPacketLength)
o.PutUint16(b[3:], c.HostTotalNumACLDataPackets)
o.PutUint16(b[5:], c.HostTotalNumSynchronousDataPackets)
}
type HostBufferSizeRP struct{ Status uint8 }
// Write Inquiry Scan Type (0x0043)
type WriteInquiryScanType struct{ ScanType uint8 }
func (c WriteInquiryScanType) Opcode() int { return opWriteInquiryScanType }
func (c WriteInquiryScanType) Len() int { return 1 }
func (c WriteInquiryScanType) Marshal(b []byte) { b[0] = c.ScanType }
type WriteInquiryScanTypeRP struct{ Status uint8 }
// Write Inquiry Mode (0x0045)
type WriteInquiryMode struct {
InquiryMode uint8
}
func (c WriteInquiryMode) Opcode() int { return opWriteInquiryMode }
func (c WriteInquiryMode) Len() int { return 1 }
func (c WriteInquiryMode) Marshal(b []byte) { b[0] = c.InquiryMode }
type WriteInquiryModeRP struct{ Status uint8 }
// Write Page Scan Type (0x0046)
type WritePageScanType struct{ PageScanType uint8 }
func (c WritePageScanType) Opcode() int { return opWritePageScanType }
func (c WritePageScanType) Len() int { return 1 }
func (c WritePageScanType) Marshal(b []byte) { b[0] = c.PageScanType }
type WritePageScanTypeRP struct{ Status uint8 }
// Write Simple Pairing Mode (0x0056)
type WriteSimplePairingMode struct{ SimplePairingMode uint8 }
func (c WriteSimplePairingMode) Opcode() int { return opWriteSimplePairingMode }
func (c WriteSimplePairingMode) Len() int { return 1 }
func (c WriteSimplePairingMode) Marshal(b []byte) { b[0] = c.SimplePairingMode }
type WriteSimplePairingModeRP struct{}
// Set Event Mask Page 2 (0x0063)
type SetEventMaskPage2 struct{ EventMaskPage2 uint64 }
func (c SetEventMaskPage2) Opcode() int { return opSetEventMaskPage2 }
func (c SetEventMaskPage2) Len() int { return 8 }
func (c SetEventMaskPage2) Marshal(b []byte) { o.PutUint64(b, c.EventMaskPage2) }
type SetEventMaskPage2RP struct{ Status uint8 }
// Write LE Host Supported (0x006D)
type WriteLEHostSupported struct {
LESupportedHost uint8
SimultaneousLEHost uint8
}
func (c WriteLEHostSupported) Opcode() int { return opWriteLEHostSupported }
func (c WriteLEHostSupported) Len() int { return 2 }
func (c WriteLEHostSupported) Marshal(b []byte) { b[0], b[1] = c.LESupportedHost, c.SimultaneousLEHost }
type WriteLeHostSupportedRP struct{ Status uint8 }
// LE Controller Commands
// LE Set Event Mask (0x0001)
type LESetEventMask struct{ LEEventMask uint64 }
func (c LESetEventMask) Opcode() int { return opLESetEventMask }
func (c LESetEventMask) Len() int { return 8 }
func (c LESetEventMask) Marshal(b []byte) { o.PutUint64(b, c.LEEventMask) }
type LESetEventMaskRP struct{ Status uint8 }
// LE Read Buffer Size (0x0002)
type LEReadBufferSize struct{}
func (c LEReadBufferSize) Opcode() int { return opLEReadBufferSize }
func (c LEReadBufferSize) Len() int { return 1 }
func (c LEReadBufferSize) Marshal(b []byte) {}
type LEReadBufferSizeRP struct {
Status uint8
HCLEACLDataPacketLength uint16
HCTotalNumLEACLDataPackets uint8
}
// LE Read Local Supported Features (0x0003)
type LEReadLocalSupportedFeatures struct{}
func (c LEReadLocalSupportedFeatures) Opcode() int { return opLEReadLocalSupportedFeatures }
func (c LEReadLocalSupportedFeatures) Len() int { return 0 }
func (c LEReadLocalSupportedFeatures) Marshal(b []byte) {}
type LEReadLocalSupportedFeaturesRP struct {
Status uint8
LEFeatures uint64
}
// LE Set Random Address (0x0005)
type LESetRandomAddress struct{ RandomAddress [6]byte }
func (c LESetRandomAddress) Opcode() int { return opLESetRandomAddress }
func (c LESetRandomAddress) Len() int { return 6 }
func (c LESetRandomAddress) Marshal(b []byte) { o.PutMAC(b, c.RandomAddress) }
type LESetRandomAddressRP struct{ Status uint8 }
// LE Set Advertising Parameters (0x0006)
type LESetAdvertisingParameters struct {
AdvertisingIntervalMin uint16
AdvertisingIntervalMax uint16
AdvertisingType uint8
OwnAddressType uint8
DirectAddressType uint8
DirectAddress [6]byte
AdvertisingChannelMap uint8
AdvertisingFilterPolicy uint8
}
func (c LESetAdvertisingParameters) Opcode() int { return opLESetAdvertisingParameters }
func (c LESetAdvertisingParameters) Len() int { return 15 }
func (c LESetAdvertisingParameters) Marshal(b []byte) {
o.PutUint16(b[0:], c.AdvertisingIntervalMin)
o.PutUint16(b[2:], c.AdvertisingIntervalMax)
o.PutUint8(b[4:], c.AdvertisingType)
o.PutUint8(b[5:], c.OwnAddressType)
o.PutUint8(b[6:], c.DirectAddressType)
o.PutMAC(b[7:], c.DirectAddress)
o.PutUint8(b[13:], c.AdvertisingChannelMap)
o.PutUint8(b[14:], c.AdvertisingFilterPolicy)
}
type LESetAdvertisingParametersRP struct{ Status uint8 }
// LE Read Advertising Channel Tx Power (0x0007)
type LEReadAdvertisingChannelTxPower struct{}
func (c LEReadAdvertisingChannelTxPower) Opcode() int { return opLEReadAdvertisingChannelTxPower }
func (c LEReadAdvertisingChannelTxPower) Len() int { return 0 }
func (c LEReadAdvertisingChannelTxPower) Marshal(b []byte) {}
type LEReadAdvertisingChannelTxPowerRP struct {
Status uint8
TransmitPowerLevel uint8
}
// LE Set Advertising Data (0x0008)
type LESetAdvertisingData struct {
AdvertisingDataLength uint8
AdvertisingData [31]byte
}
func (c LESetAdvertisingData) Opcode() int { return opLESetAdvertisingData }
func (c LESetAdvertisingData) Len() int { return 32 }
func (c LESetAdvertisingData) Marshal(b []byte) {
b[0] = c.AdvertisingDataLength
copy(b[1:], c.AdvertisingData[:c.AdvertisingDataLength])
}
type LESetAdvertisingDataRP struct{ Status uint8 }
// LE Set Scan Response Data (0x0009)
type LESetScanResponseData struct {
ScanResponseDataLength uint8
ScanResponseData [31]byte
}
func (c LESetScanResponseData) Opcode() int { return opLESetScanResponseData }
func (c LESetScanResponseData) Len() int { return 32 }
func (c LESetScanResponseData) Marshal(b []byte) {
b[0] = c.ScanResponseDataLength
copy(b[1:], c.ScanResponseData[:c.ScanResponseDataLength])
}
type LESetScanResponseDataRP struct{ Status uint8 }
// LE Set Advertising Enable (0x000A)
type LESetAdvertiseEnable struct{ AdvertisingEnable uint8 }
func (c LESetAdvertiseEnable) Opcode() int { return opLESetAdvertiseEnable }
func (c LESetAdvertiseEnable) Len() int { return 1 }
func (c LESetAdvertiseEnable) Marshal(b []byte) { b[0] = c.AdvertisingEnable }
type LESetAdvertiseEnableRP struct{ Status uint8 }
// LE Set Scan Parameters (0x000B)
type LESetScanParameters struct {
LEScanType uint8
LEScanInterval uint16
LEScanWindow uint16
OwnAddressType uint8
ScanningFilterPolicy uint8
}
func (c LESetScanParameters) Opcode() int { return opLESetScanParameters }
func (c LESetScanParameters) Len() int { return 7 }
func (c LESetScanParameters) Marshal(b []byte) {
o.PutUint8(b[0:], c.LEScanType)
o.PutUint16(b[1:], c.LEScanInterval)
o.PutUint16(b[3:], c.LEScanWindow)
o.PutUint8(b[5:], c.OwnAddressType)
o.PutUint8(b[6:], c.ScanningFilterPolicy)
}
type LESetScanParametersRP struct{ Status uint8 }
// LE Set Scan Enable (0x000C)
type LESetScanEnable struct {
LEScanEnable uint8
FilterDuplicates uint8
}
func (c LESetScanEnable) Opcode() int { return opLESetScanEnable }
func (c LESetScanEnable) Len() int { return 2 }
func (c LESetScanEnable) Marshal(b []byte) { b[0], b[1] = c.LEScanEnable, c.FilterDuplicates }
type LESetScanEnableRP struct{ Status uint8 }
// LE Create Connection (0x000D)
type LECreateConn struct {
LEScanInterval uint16
LEScanWindow uint16
InitiatorFilterPolicy uint8
PeerAddressType uint8
PeerAddress [6]byte
OwnAddressType uint8
ConnIntervalMin uint16
ConnIntervalMax uint16
ConnLatency uint16
SupervisionTimeout uint16
MinimumCELength uint16
MaximumCELength uint16
}
func (c LECreateConn) Opcode() int { return opLECreateConn }
func (c LECreateConn) Len() int { return 25 }
func (c LECreateConn) Marshal(b []byte) {
o.PutUint16(b[0:], c.LEScanInterval)
o.PutUint16(b[2:], c.LEScanWindow)
o.PutUint8(b[4:], c.InitiatorFilterPolicy)
o.PutUint8(b[5:], c.PeerAddressType)
o.PutMAC(b[6:], c.PeerAddress)
o.PutUint8(b[12:], c.OwnAddressType)
o.PutUint16(b[13:], c.ConnIntervalMin)
o.PutUint16(b[15:], c.ConnIntervalMax)
o.PutUint16(b[17:], c.ConnLatency)
o.PutUint16(b[19:], c.SupervisionTimeout)
o.PutUint16(b[21:], c.MinimumCELength)
o.PutUint16(b[23:], c.MaximumCELength)
}
type LECreateConnRP struct{}
// LE Create Connection Cancel (0x000E)
type LECreateConnCancel struct{}
func (c LECreateConnCancel) Opcode() int { return opLECreateConnCancel }
func (c LECreateConnCancel) Len() int { return 0 }
func (c LECreateConnCancel) Marshal(b []byte) {}
type LECreateConnCancelRP struct{ Status uint8 }
// LE Read White List Size (0x000F)
type LEReadWhiteListSize struct{}
func (c LEReadWhiteListSize) Opcode() int { return opLEReadWhiteListSize }
func (c LEReadWhiteListSize) Len() int { return 0 }
func (c LEReadWhiteListSize) Marshal(b []byte) {}
type LEReadWhiteListSizeRP struct {
Status uint8
WhiteListSize uint8
}
// LE Clear White List (0x0010)
type LEClearWhiteList struct{}
func (c LEClearWhiteList) Opcode() int { return opLEClearWhiteList }
func (c LEClearWhiteList) Len() int { return 0 }
func (c LEClearWhiteList) Marshal(b []byte) {}
type LEClearWhiteListRP struct{ Status uint8 }
// LE Add Device To White List (0x0011)
type LEAddDeviceToWhiteList struct {
AddressType uint8
Address [6]byte
}
func (c LEAddDeviceToWhiteList) Opcode() int { return opLEAddDeviceToWhiteList }
func (c LEAddDeviceToWhiteList) Len() int { return 7 }
func (c LEAddDeviceToWhiteList) Marshal(b []byte) {
b[0] = c.AddressType
o.PutMAC(b[1:], c.Address)
}
type LEAddDeviceToWhiteListRP struct{ Status uint8 }
// LE Remove Device From White List (0x0012)
type LERemoveDeviceFromWhiteList struct {
AddressType uint8
Address [6]byte
}
func (c LERemoveDeviceFromWhiteList) Opcode() int { return opLERemoveDeviceFromWhiteList }
func (c LERemoveDeviceFromWhiteList) Len() int { return 7 }
func (c LERemoveDeviceFromWhiteList) Marshal(b []byte) {
b[0] = c.AddressType
o.PutMAC(b[1:], c.Address)
}
type LERemoveDeviceFromWhiteListRP struct{ Status uint8 }
// LE Connection Update (0x0013)
type LEConnUpdate struct {
ConnectionHandle uint16
ConnIntervalMin uint16
ConnIntervalMax uint16
ConnLatency uint16
SupervisionTimeout uint16
MinimumCELength uint16
MaximumCELength uint16
}
func (c LEConnUpdate) Opcode() int { return opLEConnUpdate }
func (c LEConnUpdate) Len() int { return 14 }
func (c LEConnUpdate) Marshal(b []byte) {
o.PutUint16(b[0:], c.ConnectionHandle)
o.PutUint16(b[2:], c.ConnIntervalMin)
o.PutUint16(b[4:], c.ConnIntervalMax)
o.PutUint16(b[6:], c.ConnLatency)
o.PutUint16(b[8:], c.SupervisionTimeout)
o.PutUint16(b[10:], c.MinimumCELength)
o.PutUint16(b[12:], c.MaximumCELength)
}
type LEConnUpdateRP struct{}
// LE Set Host Channel Classification (0x0014)
type LESetHostChannelClassification struct{ ChannelMap [5]byte }
func (c LESetHostChannelClassification) Opcode() int { return opLESetHostChannelClassification }
func (c LESetHostChannelClassification) Len() int { return 5 }
func (c LESetHostChannelClassification) Marshal(b []byte) { copy(b, c.ChannelMap[:]) }
type LESetHostChannelClassificationRP struct{ Status uint8 }
// LE Read Channel Map (0x0015)
type LEReadChannelMap struct{ ConnectionHandle uint16 }
func (c LEReadChannelMap) Opcode() int { return opLEReadChannelMap }
func (c LEReadChannelMap) Len() int { return 2 }
func (c LEReadChannelMap) Marshal(b []byte) { o.PutUint16(b, c.ConnectionHandle) }
type LEReadChannelMapRP struct {
Status uint8
ConnectionHandle uint16
ChannelMap [5]byte
}
// LE Read Remote Used Features (0x0016)
type LEReadRemoteUsedFeatures struct{ ConnectionHandle uint16 }
func (c LEReadRemoteUsedFeatures) Opcode() int { return opLEReadRemoteUsedFeatures }
func (c LEReadRemoteUsedFeatures) Len() int { return 8 }
func (c LEReadRemoteUsedFeatures) Marshal(b []byte) { o.PutUint16(b, c.ConnectionHandle) }
type LEReadRemoteUsedFeaturesRP struct{}
// LE Encrypt (0x0017)
type LEEncrypt struct {
Key [16]byte
PlaintextData [16]byte
}
func (c LEEncrypt) Opcode() int { return opLEEncrypt }
func (c LEEncrypt) Len() int { return 32 }
func (c LEEncrypt) Marshal(b []byte) {
copy(b[0:], c.Key[:])
copy(b[16:], c.PlaintextData[:])
}
type LEEncryptRP struct {
Stauts uint8
EncryptedData [16]byte
}
// LE Rand (0x0018)
type LERand struct{}
func (c LERand) Opcode() int { return opLERand }
func (c LERand) Len() int { return 0 }
func (c LERand) Marshal(b []byte) {}
type LERandRP struct {
Status uint8
RandomNumber uint64
}
// LE Start Encryption (0x0019)
type LEStartEncryption struct {
ConnectionHandle uint16
RandomNumber uint64
EncryptedDiversifier uint16
LongTermKey [16]byte
}
func (c LEStartEncryption) Opcode() int { return opLEStartEncryption }
func (c LEStartEncryption) Len() int { return 28 }
func (c LEStartEncryption) Marshal(b []byte) {
o.PutUint16(b[0:], c.ConnectionHandle)
o.PutUint64(b[2:], c.RandomNumber)
o.PutUint16(b[10:], c.EncryptedDiversifier)
copy(b[12:], c.LongTermKey[:])
}
type LEStartEncryptionRP struct{}
// LE Long Term Key Reply (0x001A)
type LELTKReply struct {
ConnectionHandle uint16
LongTermKey [16]byte
}
func (c LELTKReply) Opcode() int { return opLELTKReply }
func (c LELTKReply) Len() int { return 18 }
func (c LELTKReply) Marshal(b []byte) {
o.PutUint16(b[0:], c.ConnectionHandle)
copy(b[2:], c.LongTermKey[:])
}
type LELTKReplyRP struct {
Status uint8
ConnectionHandle uint16
}
// LE Long Term Key Negative Reply (0x001B)
type LELTKNegReply struct{ ConnectionHandle uint16 }
func (c LELTKNegReply) Opcode() int { return opLELTKNegReply }
func (c LELTKNegReply) Len() int { return 2 }
func (c LELTKNegReply) Marshal(b []byte) { o.PutUint16(b, c.ConnectionHandle) }
type LELTKNegReplyRP struct {
Status uint8
ConnectionHandle uint16
}
// LE Read Supported States (0x001C)
type LEReadSupportedStates struct{}
func (c LEReadSupportedStates) Opcode() int { return opLEReadSupportedStates }
func (c LEReadSupportedStates) Len() int { return 0 }
func (c LEReadSupportedStates) Marshal(b []byte) {}
type LEReadSupportedStatesRP struct {
Status uint8
LEStates [8]byte
}
// LE Reciever Test (0x001D)
type LEReceiverTest struct{ RxChannel uint8 }
func (c LEReceiverTest) Opcode() int { return opLEReceiverTest }
func (c LEReceiverTest) Len() int { return 1 }
func (c LEReceiverTest) Marshal(b []byte) { b[0] = c.RxChannel }
type LEReceiverTestRP struct{ Status uint8 }
// LE Transmitter Test (0x001E)
type LETransmitterTest struct {
TxChannel uint8
LengthOfTestData uint8
PacketPayload uint8
}
func (c LETransmitterTest) Opcode() int { return opLETransmitterTest }
func (c LETransmitterTest) Len() int { return 3 }
func (c LETransmitterTest) Marshal(b []byte) {
b[0], b[1], b[2] = c.TxChannel, c.LengthOfTestData, c.PacketPayload
}
type LETransmitterTestRP struct{ Status uint8 }
// LE Test End (0x001F)
type LETestEnd struct{}
func (c LETestEnd) Opcode() int { return opLETestEnd }
func (c LETestEnd) Len() int { return 0 }
func (c LETestEnd) Marshal(b []byte) {}
type LETestEndRP struct {
Status uint8
NumberOfPackets uint16
}
// LE Remote Connection Parameters Reply (0x0020)
type LERemoteConnectionParameterReply struct {
ConnectionHandle uint16
IntervalMin uint16
IntervalMax uint16
Latency uint16
Timeout uint16
MinimumCELength uint16
MaximumCELength uint16
}
func (c LERemoteConnectionParameterReply) Opcode() int { return opLERemoteConnectionParameterReply }
func (c LERemoteConnectionParameterReply) Len() int { return 14 }
func (c LERemoteConnectionParameterReply) Marshal(b []byte) {
o.PutUint16(b[0:], c.ConnectionHandle)
o.PutUint16(b[2:], c.IntervalMin)
o.PutUint16(b[4:], c.IntervalMax)
o.PutUint16(b[6:], c.Latency)
o.PutUint16(b[8:], c.Timeout)
o.PutUint16(b[10:], c.MinimumCELength)
o.PutUint16(b[12:], c.MaximumCELength)
}
type LERemoteConnectionParameterReplyRP struct {
Status uint8
ConnectionHandle uint16
}
// LE Remote Connection Parameters Negative Reply (0x0021)
type LERemoteConnectionParameterNegReply struct {
ConnectionHandle uint16
Reason uint8
}
func (c LERemoteConnectionParameterNegReply) Opcode() int {
return opLERemoteConnectionParameterNegReply
}
func (c LERemoteConnectionParameterNegReply) Len() int { return 3 }
func (c LERemoteConnectionParameterNegReply) Marshal(b []byte) {
o.PutUint16(b[0:], c.ConnectionHandle)
b[2] = c.Reason
}
type LERemoteConnectionParameterNegReplyRP struct {
Status uint8
ConnectionHandle uint16
}

View file

@ -1,21 +0,0 @@
package linux
type packetType uint8
// HCI Packet types
const (
typCommandPkt packetType = 0X01
typACLDataPkt = 0X02
typSCODataPkt = 0X03
typEventPkt = 0X04
typVendorPkt = 0XFF
)
// Event Type
const (
advInd = 0x00 // Connectable undirected advertising (ADV_IND).
advDirectInd = 0x01 // Connectable directed advertising (ADV_DIRECT_IND)
advScanInd = 0x02 // Scannable undirected advertising (ADV_SCAN_IND)
advNonconnInd = 0x03 // Non connectable undirected advertising (ADV_NONCONN_IND)
scanRsp = 0x04 // Scan Response (SCAN_RSP)
)

View file

@ -1,117 +0,0 @@
package linux
import (
"errors"
"log"
"sync"
"syscall"
"unsafe"
"github.com/bettercap/gatt/linux/gioctl"
"github.com/bettercap/gatt/linux/socket"
)
type device struct {
fd int
dev int
name string
rmu *sync.Mutex
wmu *sync.Mutex
}
func newDevice(n int, chk bool) (*device, error) {
fd, err := socket.Socket(socket.AF_BLUETOOTH, syscall.SOCK_RAW, socket.BTPROTO_HCI)
if err != nil {
log.Printf("could not create AF_BLUETOOTH raw socket")
return nil, err
}
if n != -1 {
return newSocket(fd, n, chk)
}
req := devListRequest{devNum: hciMaxDevices}
if err := gioctl.Ioctl(uintptr(fd), hciGetDeviceList, uintptr(unsafe.Pointer(&req))); err != nil {
log.Printf("hciGetDeviceList failed")
return nil, err
}
log.Printf("got %d devices", req.devNum)
for i := 0; i < int(req.devNum); i++ {
d, err := newSocket(fd, i, chk)
if err == nil {
log.Printf("dev: %s opened", d.name)
return d, err
} else {
log.Printf("error while opening device %d: %v", i, err)
}
}
return nil, errors.New("no supported devices available")
}
func newSocket(fd, n int, chk bool) (*device, error) {
i := hciDevInfo{id: uint16(n)}
if err := gioctl.Ioctl(uintptr(fd), hciGetDeviceInfo, uintptr(unsafe.Pointer(&i))); err != nil {
log.Printf("hciGetDeviceInfo failed")
return nil, err
}
name := string(i.name[:])
// Check the feature list returned feature list.
if chk && i.features[4]&0x40 == 0 {
err := errors.New("does not support LE")
log.Printf("dev: %s %s", name, err)
return nil, err
}
log.Printf("dev: %s up", name)
if err := gioctl.Ioctl(uintptr(fd), hciUpDevice, uintptr(n)); err != nil {
if err != syscall.EALREADY {
return nil, err
}
log.Printf("dev: %s reset", name)
if err := gioctl.Ioctl(uintptr(fd), hciResetDevice, uintptr(n)); err != nil {
log.Printf("hciResetDevice failed")
return nil, err
}
}
log.Printf("dev: %s down", name)
if err := gioctl.Ioctl(uintptr(fd), hciDownDevice, uintptr(n)); err != nil {
return nil, err
}
// Attempt to use the linux 3.14 feature, if this fails with EINVAL fall back to raw access
// on older kernels.
sa := socket.SockaddrHCI{Dev: n, Channel: socket.HCI_CHANNEL_USER}
if err := socket.Bind(fd, &sa); err != nil {
if err != syscall.EINVAL {
return nil, err
}
log.Printf("dev: %s can't bind to hci user channel, err: %s.", name, err)
sa := socket.SockaddrHCI{Dev: n, Channel: socket.HCI_CHANNEL_RAW}
if err := socket.Bind(fd, &sa); err != nil {
log.Printf("dev: %s can't bind to hci raw channel, err: %s.", name, err)
return nil, err
}
}
return &device{
fd: fd,
dev: n,
name: name,
rmu: &sync.Mutex{},
wmu: &sync.Mutex{},
}, nil
}
func (d device) Read(b []byte) (int, error) {
d.rmu.Lock()
defer d.rmu.Unlock()
return syscall.Read(d.fd, b)
}
func (d device) Write(b []byte) (int, error) {
d.wmu.Lock()
defer d.wmu.Unlock()
return syscall.Write(d.fd, b)
}
func (d device) Close() error {
log.Printf("linux.device.Close()")
return syscall.Close(d.fd)
}

View file

@ -1,58 +0,0 @@
package linux
import "github.com/bettercap/gatt/linux/gioctl"
const (
ioctlSize = uintptr(4)
hciMaxDevices = 16
typHCI = 72 // 'H'
)
var (
hciUpDevice = gioctl.IoW(typHCI, 201, ioctlSize) // HCIDEVUP
hciDownDevice = gioctl.IoW(typHCI, 202, ioctlSize) // HCIDEVDOWN
hciResetDevice = gioctl.IoW(typHCI, 203, ioctlSize) // HCIDEVRESET
hciGetDeviceList = gioctl.IoR(typHCI, 210, ioctlSize) // HCIGETDEVLIST
hciGetDeviceInfo = gioctl.IoR(typHCI, 211, ioctlSize) // HCIGETDEVINFO
)
type devRequest struct {
id uint16
opt uint32
}
type devListRequest struct {
devNum uint16
devRequest [hciMaxDevices]devRequest
}
type hciDevInfo struct {
id uint16
name [8]byte
bdaddr [6]byte
flags uint32
devType uint8
features [8]uint8
pktType uint32
linkPolicy uint32
linkMode uint32
aclMtu uint16
aclPkts uint16
scoMtu uint16
scoPkts uint16
stats hciDevStats
}
type hciDevStats struct {
errRx uint32
errTx uint32
cmdTx uint32
evtRx uint32
aclTx uint32
aclRx uint32
scoTx uint32
scoRx uint32
byteRx uint32
byteTx uint32
}

View file

@ -1,5 +0,0 @@
// Package linux provides linux-specific support for gatt.
//
// This package is work in progress. We expect the APIs to change significantly before stabilizing.
package linux

View file

@ -1,401 +0,0 @@
package evt
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"github.com/bettercap/gatt/linux/util"
)
type EventHandler interface {
HandleEvent([]byte) error
}
type HandlerFunc func(b []byte) error
func (f HandlerFunc) HandleEvent(b []byte) error {
return f(b)
}
type Evt struct {
evtHandlers map[int]EventHandler
}
func NewEvt() *Evt {
return &Evt{
evtHandlers: map[int]EventHandler{},
}
}
func (e *Evt) HandleEvent(c int, h EventHandler) {
e.evtHandlers[c] = h
}
func (e *Evt) Dispatch(b []byte) error {
h := &EventHeader{}
if err := h.Unmarshal(b); err != nil {
return err
}
b = b[2:] // Skip Event Header (uint8 + uint8)
if f, found := e.evtHandlers[h.code]; found {
e.trace("> HCI Event: %s (0x%02X) plen %d: [ % X ])\n", h.code, uint8(h.code), h.plen, b)
return f.HandleEvent(b)
}
e.trace("> HCI Event: no handler for %s (0x%02X)\n", h.code, uint8(h.code))
return nil
}
func (e *Evt) trace(fmt string, v ...interface{}) {}
const (
InquiryComplete = 0x01 // Inquiry Complete
InquiryResult = 0x02 // Inquiry Result
ConnectionComplete = 0x03 // Connection Complete
ConnectionRequest = 0x04 // Connection Request
DisconnectionComplete = 0x05 // Disconnection Complete
AuthenticationComplete = 0x06 // Authentication
RemoteNameReqComplete = 0x07 // Remote Name Request Complete
EncryptionChange = 0x08 // Encryption Change
ChangeConnectionLinkKeyComplete = 0x09 // Change Conection Link Key Complete
MasterLinkKeyComplete = 0x0A // Master Link Keye Complete
ReadRemoteSupportedFeaturesComplete = 0x0B // Read Remote Supported Features Complete
ReadRemoteVersionInformationComplete = 0x0C // Read Remote Version Information Complete
QoSSetupComplete = 0x0D // QoSSetupComplete
CommandComplete = 0x0E // Command Complete
CommandStatus = 0x0F // Command status
HardwareError = 0x10 // Hardware Error
FlushOccurred = 0x11 // Flush Occured
RoleChange = 0x12 // Role Change
NumberOfCompletedPkts = 0x13 // Number Of Completed Packets
ModeChange = 0x14 // Mode Change
ReturnLinkKeys = 0x15 // Return Link Keys
PinCodeRequest = 0x16 // PIN Code Request
LinkKeyRequest = 0x17 // Link Key Request
LinkKeyNotification = 0x18 // Link Key Notification
LoopbackCommand = 0x19 // Loopback Command
DataBufferOverflow = 0x1A // Data Buffer Overflow
MaxSlotsChange = 0x1B // Max Slots Change
ReadClockOffsetComplete = 0x1C // Read Clock Offset Complete
ConnectionPtypeChanged = 0x1D // Connection Packet Type Changed
QoSViolation = 0x1E // QoS Violation
PageScanRepetitionModeChange = 0x20 // Page Scan Repetition Mode Change
FlowSpecificationComplete = 0x21 // Flow Specification
InquiryResultWithRssi = 0x22 // Inquery Result with RSSI
ReadRemoteExtendedFeaturesComplete = 0x23 // Read Remote Extended Features Complete
SyncConnectionComplete = 0x2C // Synchronous Connection Complete
SyncConnectionChanged = 0x2D // Synchronous Connection Changed
SniffSubrating = 0x2E // Sniff Subrating
ExtendedInquiryResult = 0x2F // Extended Inquiry Result
EncryptionKeyRefreshComplete = 0x30 // Encryption Key Refresh Complete
IOCapabilityRequest = 0x31 // IO Capability Request
IOCapabilityResponse = 0x32 // IO Capability Changed
UserConfirmationRequest = 0x33 // User Confirmation Request
UserPasskeyRequest = 0x34 // User Passkey Request
RemoteOOBDataRequest = 0x35 // Remote OOB Data
SimplePairingComplete = 0x36 // Simple Pairing Complete
LinkSupervisionTimeoutChanged = 0x38 // Link Supervision Timeout Changed
EnhancedFlushComplete = 0x39 // Enhanced Flush Complete
UserPasskeyNotify = 0x3B // User Passkey Notification
KeypressNotify = 0x3C // Keypass Notification
RemoteHostFeaturesNotify = 0x3D // Remote Host Supported Features Notification
LEMeta = 0x3E // LE Meta
PhysicalLinkComplete = 0x40 // Physical Link Complete
ChannelSelected = 0x41 // Channel Selected
DisconnectionPhysicalLinkComplete = 0x42 // Disconnection Physical Link Complete
PhysicalLinkLossEarlyWarning = 0x43 // Physical Link Loss Early Warning
PhysicalLinkRecovery = 0x44 // Physical Link Recovery
LogicalLinkComplete = 0x45 // Logical Link Complete
DisconnectionLogicalLinkComplete = 0x46 // Disconnection Logical Link Complete
FlowSpecModifyComplete = 0x47 // Flow Spec Modify Complete
NumberOfCompletedBlocks = 0x48 // Number Of Completed Data Blocks
AMPStartTest = 0x49 // AMP Start Test
AMPTestEnd = 0x4A // AMP Test End
AMPReceiverReport = 0x4b // AMP Receiver Report
AMPStatusChange = 0x4D // AMP status Change
TriggeredClockCapture = 0x4e // Triggered Clock Capture
SynchronizationTrainComplete = 0x4F // Synchronization Train Complete
SynchronizationTrainReceived = 0x50 // Synchronization Train Received
ConnectionlessSlaveBroadcastReceive = 0x51 // Connectionless Slave Broadcast Receive
ConnectionlessSlaveBroadcastTimeout = 0x52 // Connectionless Slave Broadcast Timeout
TruncatedPageComplete = 0x53 // Truncated Page Complete
SlavePageResponseTimeout = 0x54 // Slave Page Response Timeout
ConnectionlessSlaveBroadcastChannelMapChange = 0x55 // Connectionless Slave Broadcast Channel Map Change
InquiryResponseNotification = 0x56 // Inquiry Response Notification
AuthenticatedPayloadTimeoutExpired = 0x57 // Authenticated Payload Timeout Expired
)
type LEEventCode int
const (
LEConnectionComplete LEEventCode = 0x01 // LE Connection Complete
LEAdvertisingReport = 0x02 // LE Advertising Report
LEConnectionUpdateComplete = 0x03 // LE Connection Update Complete
LEReadRemoteUsedFeaturesComplete = 0x04 // LE Read Remote Used Features Complete
LELTKRequest = 0x05 // LE LTK Request
LERemoteConnectionParameterRequest = 0x06 // LE Remote Connection Parameter Request
)
type EventHeader struct {
code int
plen uint8
}
func (h *EventHeader) Unmarshal(b []byte) error {
if len(b) < 2 {
return errors.New("malformed header")
}
h.code = int(b[0])
h.plen = b[1]
if uint8(len(b)) != 2+h.plen {
return errors.New("wrong length")
}
return nil
}
var o = util.Order
// Event Parameters
type InquiryCompleteEP struct {
Status uint8
}
type InquiryResultEP struct {
NumResponses uint8
BDAddr [][6]byte
PageScanRepetitionMode []uint8
Reserved1 []byte
Reserved2 []byte
ClassOfDevice [][3]byte
ClockOffset []uint16
}
type ConnectionCompleteEP struct {
Status uint8
ConnectionHandle uint16
BDAddr [6]byte
LinkType uint8
EncryptionEnabled uint8
}
type ConnectionRequestEP struct {
BDAddr [6]byte
ClassofDevice [3]byte
LinkType uint8
}
type DisconnectionCompleteEP struct {
Status uint8
ConnectionHandle uint16
Reason uint8
}
func (e *DisconnectionCompleteEP) Unmarshal(b []byte) error {
buf := bytes.NewBuffer(b)
binary.Read(buf, binary.LittleEndian, &e.Status)
binary.Read(buf, binary.LittleEndian, &e.ConnectionHandle)
return binary.Read(buf, binary.LittleEndian, &e.Reason)
}
type CommandCompleteEP struct {
NumHCICommandPackets uint8
CommandOPCode uint16
ReturnParameters []byte
}
func (e *CommandCompleteEP) Unmarshal(b []byte) error {
buf := bytes.NewBuffer(b)
if err := binary.Read(buf, binary.LittleEndian, &e.NumHCICommandPackets); err != nil {
return err
}
if err := binary.Read(buf, binary.LittleEndian, &e.CommandOPCode); err != nil {
return err
}
e.ReturnParameters = buf.Bytes()
return nil
}
type CommandStatusEP struct {
Status uint8
NumHCICommandPackets uint8
CommandOpcode uint16
}
func (e *CommandStatusEP) Unmarshal(b []byte) error {
buf := bytes.NewBuffer(b)
binary.Read(buf, binary.LittleEndian, &e.Status)
binary.Read(buf, binary.LittleEndian, &e.NumHCICommandPackets)
return binary.Read(buf, binary.LittleEndian, &e.CommandOpcode)
}
type NumOfCompletedPkt struct {
ConnectionHandle uint16
NumOfCompletedPkts uint16
}
type NumberOfCompletedPktsEP struct {
NumberOfHandles uint8
Packets []NumOfCompletedPkt
}
func (e *NumberOfCompletedPktsEP) Unmarshal(b []byte) error {
e.NumberOfHandles = b[0]
n := int(e.NumberOfHandles)
buf := bytes.NewBuffer(b[1:])
e.Packets = make([]NumOfCompletedPkt, n)
for i := 0; i < n; i++ {
binary.Read(buf, binary.LittleEndian, &e.Packets[i].ConnectionHandle)
binary.Read(buf, binary.LittleEndian, &e.Packets[i].NumOfCompletedPkts)
e.Packets[i].ConnectionHandle &= 0xfff
}
return nil
}
// LE Meta Subevents
type LEConnectionCompleteEP struct {
SubeventCode uint8
Status uint8
ConnectionHandle uint16
Role uint8
PeerAddressType uint8
PeerAddress [6]byte
ConnInterval uint16
ConnLatency uint16
SupervisionTimeout uint16
MasterClockAccuracy uint8
}
func (e *LEConnectionCompleteEP) Unmarshal(b []byte) error {
if len(b) < 18 {
return fmt.Errorf("expected at least 18 bytes, got %d", len(b))
}
e.SubeventCode = o.Uint8(b[0:])
e.Status = o.Uint8(b[1:])
e.ConnectionHandle = o.Uint16(b[2:])
e.Role = o.Uint8(b[4:])
e.PeerAddressType = o.Uint8(b[5:])
e.PeerAddress = o.MAC(b[6:])
e.ConnInterval = o.Uint16(b[12:])
e.ConnLatency = o.Uint16(b[14:])
e.SupervisionTimeout = o.Uint16(b[16:])
e.MasterClockAccuracy = o.Uint8(b[17:])
return nil
}
type LEAdvertisingReportEP struct {
SubeventCode uint8
NumReports uint8
EventType []uint8
AddressType []uint8
Address [][6]byte
Length []uint8
Data [][]byte
RSSI []int8
}
func (e *LEAdvertisingReportEP) Unmarshal(b []byte) error {
if len(b) < 2 {
return errors.New("expected at least 2 bytes")
}
e.SubeventCode = o.Uint8(b)
b = b[1:]
e.NumReports = o.Uint8(b)
b = b[1:]
n := int(e.NumReports)
e.EventType = make([]uint8, n)
e.AddressType = make([]uint8, n)
e.Address = make([][6]byte, n)
e.Length = make([]uint8, n)
e.Data = make([][]byte, n)
e.RSSI = make([]int8, n)
if len(b) < (1+1+6+1)*n {
return fmt.Errorf("expected %d more bytes, got %d", (1+1+6+1)*n, len(b))
}
for i := 0; i < n; i++ {
e.EventType[i] = o.Uint8(b)
b = b[1:]
}
for i := 0; i < n; i++ {
e.AddressType[i] = o.Uint8(b)
b = b[1:]
}
for i := 0; i < n; i++ {
e.Address[i] = o.MAC(b)
b = b[6:]
}
var sumLength int
for i := 0; i < n; i++ {
e.Length[i] = o.Uint8(b)
sumLength += int(e.Length[i])
b = b[1:]
}
if len(b) < sumLength+(1)*n {
return fmt.Errorf("expected %d more bytes, got %d", sumLength+(1)*n, len(b))
}
for i := 0; i < n; i++ {
e.Data[i] = make([]byte, e.Length[i])
copy(e.Data[i], b)
b = b[e.Length[i]:]
}
for i := 0; i < n; i++ {
e.RSSI[i] = o.Int8(b)
b = b[1:]
}
return nil
}
type LEConnectionUpdateCompleteEP struct {
SubeventCode uint8
Status uint8
ConnectionHandle uint16
ConnInterval uint16
ConnLatency uint16
SupervisionTimeout uint16
}
func (e *LEConnectionUpdateCompleteEP) Unmarshal(b []byte) error {
return binary.Read(bytes.NewBuffer(b), binary.LittleEndian, e)
}
type LEReadRemoteUsedFeaturesCompleteEP struct {
SubeventCode uint8
Status uint8
ConnectionHandle uint16
LEFeatures uint64
}
func (e *LEReadRemoteUsedFeaturesCompleteEP) Unmarshal(b []byte) error {
return binary.Read(bytes.NewBuffer(b), binary.LittleEndian, e)
}
type LELTKRequestEP struct {
SubeventCode uint8
ConnectionHandle uint16
RandomNumber uint64
EncryptionDiversifier uint16
}
func (e *LELTKRequestEP) Unmarshal(b []byte) error {
return binary.Read(bytes.NewBuffer(b), binary.LittleEndian, e)
}
type LERemoteConnectionParameterRequestEP struct {
SubeventCode uint8
ConnectionHandle uint16
IntervalMin uint16
IntervalMax uint16
Latency uint16
Timeout uint16
}
func (e *LERemoteConnectionParameterRequestEP) Unmarshal(b []byte) error {
return binary.Read(bytes.NewBuffer(b), binary.LittleEndian, e)
}

View file

@ -1,22 +0,0 @@
Copyright (c) 2012 Mark Wolfe
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.

View file

@ -1,12 +0,0 @@
# gioctl [![GoDoc](https://img.shields.io/badge/godoc-Reference-brightgreen.svg?style=flat)](http://godoc.org/github.com/wolfeidau/gioctl)
Simple library which provides golang versions of the ioctl macros in linux.
# References
* https://github.com/luismesas/goPi started with the IOCTL stuff from this project initally.
* http://www.circlemud.org/jelson/software/fusd/docs/node31.html good information on IOCTL macros.
# License
This code is Copyright (c) 2014 Mark Wolfe and licenced under the MIT licence. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE.md file for more details.

View file

@ -1,57 +0,0 @@
package gioctl
import "syscall"
const (
typeBits = 8
numberBits = 8
sizeBits = 14
directionBits = 2
typeMask = (1 << typeBits) - 1
numberMask = (1 << numberBits) - 1
sizeMask = (1 << sizeBits) - 1
directionMask = (1 << directionBits) - 1
directionNone = 0
directionWrite = 1
directionRead = 2
numberShift = 0
typeShift = numberShift + numberBits
sizeShift = typeShift + typeBits
directionShift = sizeShift + sizeBits
)
func ioc(dir, t, nr, size uintptr) uintptr {
return (dir << directionShift) | (t << typeShift) | (nr << numberShift) | (size << sizeShift)
}
// Io used for a simple ioctl that sends nothing but the type and number, and receives back nothing but an (integer) retval.
func Io(t, nr uintptr) uintptr {
return ioc(directionNone, t, nr, 0)
}
// IoR used for an ioctl that reads data from the device driver. The driver will be allowed to return sizeof(data_type) bytes to the user.
func IoR(t, nr, size uintptr) uintptr {
return ioc(directionRead, t, nr, size)
}
// IoW used for an ioctl that writes data to the device driver.
func IoW(t, nr, size uintptr) uintptr {
return ioc(directionWrite, t, nr, size)
}
// IoRW a combination of IoR and IoW. That is, data is both written to the driver and then read back from the driver by the client.
func IoRW(t, nr, size uintptr) uintptr {
return ioc(directionRead|directionWrite, t, nr, size)
}
// Ioctl simplified ioct call
func Ioctl(fd, op, arg uintptr) error {
_, _, ep := syscall.Syscall(syscall.SYS_IOCTL, fd, op, arg)
if ep != 0 {
return syscall.Errno(ep)
}
return nil
}

View file

@ -1,444 +0,0 @@
package linux
import (
"fmt"
"io"
"log"
"sync"
"github.com/bettercap/gatt/linux/cmd"
"github.com/bettercap/gatt/linux/evt"
"github.com/bettercap/gatt/linux/util"
)
type HCI struct {
AcceptMasterHandler func(pd *PlatData)
AcceptSlaveHandler func(pd *PlatData)
AdvertisementHandler func(pd *PlatData)
d io.ReadWriteCloser
c *cmd.Cmd
e *evt.Evt
plist map[bdaddr]*PlatData
plistmu *sync.Mutex
bufCnt chan struct{}
bufSize int
pool *util.BytePool
loopDone chan bool
maxConn int
connsmu *sync.Mutex
conns map[uint16]*conn
adv bool
advmu *sync.Mutex
}
type bdaddr [6]byte
type PlatData struct {
Name string
AddressType uint8
Address [6]byte
Data []byte
Connectable bool
RSSI int8
Conn io.ReadWriteCloser
}
func NewHCI(devID int, chk bool, maxConn int) (*HCI, error) {
d, err := newDevice(devID, chk)
if err != nil {
return nil, err
}
c := cmd.NewCmd(d)
e := evt.NewEvt()
h := &HCI{
d: d,
c: c,
e: e,
plist: make(map[bdaddr]*PlatData),
plistmu: &sync.Mutex{},
bufCnt: make(chan struct{}, 15-1),
bufSize: 27,
pool: util.NewBytePool(4096, 16),
loopDone: make(chan bool),
maxConn: maxConn,
connsmu: &sync.Mutex{},
conns: map[uint16]*conn{},
advmu: &sync.Mutex{},
}
e.HandleEvent(evt.LEMeta, evt.HandlerFunc(h.handleLEMeta))
e.HandleEvent(evt.DisconnectionComplete, evt.HandlerFunc(h.handleDisconnectionComplete))
e.HandleEvent(evt.NumberOfCompletedPkts, evt.HandlerFunc(h.handleNumberOfCompletedPkts))
e.HandleEvent(evt.CommandComplete, evt.HandlerFunc(c.HandleComplete))
e.HandleEvent(evt.CommandStatus, evt.HandlerFunc(c.HandleStatus))
go h.mainLoop()
h.resetDevice()
return h, nil
}
func (h *HCI) Close() error {
log.Printf("hci.Close()")
h.pool.Put(nil)
<-h.loopDone
log.Printf("mainLoop exited")
for _, c := range h.conns {
log.Printf("closing connection %v", c)
c.Close()
}
log.Printf("closing %v", h.d)
return h.d.Close()
}
func (h *HCI) SetAdvertiseEnable(en bool) error {
h.advmu.Lock()
h.adv = en
h.advmu.Unlock()
return h.setAdvertiseEnable(en)
}
func (h *HCI) setAdvertiseEnable(en bool) error {
h.advmu.Lock()
defer h.advmu.Unlock()
if en && h.adv && (len(h.conns) == h.maxConn) {
return nil
}
return h.c.SendAndCheckResp(
cmd.LESetAdvertiseEnable{
AdvertisingEnable: btoi(en),
}, []byte{0x00})
}
func (h *HCI) SendCmdWithAdvOff(c cmd.CmdParam) error {
h.setAdvertiseEnable(false)
err := h.c.SendAndCheckResp(c, nil)
if h.adv {
h.setAdvertiseEnable(true)
}
return err
}
func (h *HCI) SetScanEnable(en bool, dup bool) error {
return h.c.SendAndCheckResp(
cmd.LESetScanEnable{
LEScanEnable: btoi(en),
FilterDuplicates: btoi(!dup),
}, []byte{0x00})
}
func (h *HCI) Connect(pd *PlatData) error {
h.c.Send(
cmd.LECreateConn{
LEScanInterval: 0x0004, // N x 0.625ms
LEScanWindow: 0x0004, // N x 0.625ms
InitiatorFilterPolicy: 0x00, // white list not used
PeerAddressType: pd.AddressType, // public or random
PeerAddress: pd.Address, //
OwnAddressType: 0x00, // public
ConnIntervalMin: 0x0006, // N x 0.125ms
ConnIntervalMax: 0x0006, // N x 0.125ms
ConnLatency: 0x0000, //
SupervisionTimeout: 0x0048, // N x 10ms
MinimumCELength: 0x0000, // N x 0.625ms
MaximumCELength: 0x0000, // N x 0.625ms
})
return nil
}
func (h *HCI) CancelConnection(pd *PlatData) error {
if pd != nil && pd.Conn != nil {
return pd.Conn.Close()
}
return nil
}
func (h *HCI) SendRawCommand(c cmd.CmdParam) ([]byte, error) {
return h.c.Send(c)
}
func btoi(b bool) uint8 {
if b {
return 1
}
return 0
}
func (h *HCI) mainLoop() {
log.Printf("hci.mainLoop started")
defer func() {
h.loopDone <- true
}()
for {
// log.Printf("hci.mainLoop pool.Get")
b := h.pool.Get()
if b == nil {
log.Printf("got nil buffer, breaking mainLoop")
break
}
// log.Printf("hci.mainLoop Read(%d)", len(b))
n, err := h.d.Read(b)
if err != nil {
log.Printf("mainloop err: %v", err)
return
}
if n == 0 {
log.Printf("mainLoop failed to read")
return
}
// log.Printf("hci.mainLoop -> handlePacket")
h.handlePacket(b, n)
}
log.Printf("hci.mainLoop stopped")
}
func (h *HCI) handlePacket(buf []byte, n int) {
b := buf[:n]
t, b := packetType(b[0]), b[1:]
var err error
handled := true
switch t {
case typCommandPkt:
op := uint16(b[0]) | uint16(b[1])<<8
log.Printf("unmanaged cmd: opcode (%04x) [ % X ]\n", op, b)
case typACLDataPkt:
err = h.handleL2CAP(b)
case typSCODataPkt:
err = fmt.Errorf("SCO packet not supported")
case typEventPkt:
handled = false
go func() {
err := h.e.Dispatch(b)
if err != nil {
log.Printf("hci: %s, [ % X]", err, b)
}
h.pool.Put(buf)
}()
case typVendorPkt:
err = fmt.Errorf("Vendor packet not supported")
default:
log.Fatalf("Unknown event: 0x%02X [ % X ]\n", t, b)
}
if err != nil {
log.Printf("hci: %s, [ % X]", err, b)
}
if handled {
h.pool.Put(buf)
}
}
func (h *HCI) resetDevice() error {
seq := []cmd.CmdParam{
cmd.Reset{},
cmd.SetEventMask{EventMask: 0x3dbff807fffbffff},
cmd.LESetEventMask{LEEventMask: 0x000000000000001F},
cmd.WriteSimplePairingMode{SimplePairingMode: 1},
cmd.WriteLEHostSupported{LESupportedHost: 1, SimultaneousLEHost: 0},
cmd.WriteInquiryMode{InquiryMode: 2},
cmd.WritePageScanType{PageScanType: 1},
cmd.WriteInquiryScanType{ScanType: 1},
cmd.WriteClassOfDevice{ClassOfDevice: [3]byte{0x40, 0x02, 0x04}},
cmd.WritePageTimeout{PageTimeout: 0x2000},
cmd.WriteDefaultLinkPolicy{DefaultLinkPolicySettings: 0x5},
cmd.HostBufferSize{
HostACLDataPacketLength: 0x1000,
HostSynchronousDataPacketLength: 0xff,
HostTotalNumACLDataPackets: 0x0014,
HostTotalNumSynchronousDataPackets: 0x000a},
cmd.LESetScanParameters{
LEScanType: 0x01, // [0x00]: passive, 0x01: active
LEScanInterval: 0x0010, // [0x10]: 0.625ms * 16
LEScanWindow: 0x0010, // [0x10]: 0.625ms * 16
OwnAddressType: 0x00, // [0x00]: public, 0x01: random
ScanningFilterPolicy: 0x00, // [0x00]: accept all, 0x01: ignore non-white-listed.
},
}
for _, s := range seq {
if err := h.c.SendAndCheckResp(s, []byte{0x00}); err != nil {
return err
}
}
return nil
}
func (h *HCI) handleAdvertisement(b []byte) {
// If no one is interested, don't bother.
if h.AdvertisementHandler == nil {
return
}
ep := &evt.LEAdvertisingReportEP{}
if err := ep.Unmarshal(b); err != nil {
return
}
for i := 0; i < int(ep.NumReports); i++ {
addr := bdaddr(ep.Address[i])
et := ep.EventType[i]
connectable := et == advInd || et == advDirectInd
scannable := et == advInd || et == advScanInd
if et == scanRsp {
h.plistmu.Lock()
pd, ok := h.plist[addr]
h.plistmu.Unlock()
if ok {
pd.Data = append(pd.Data, ep.Data[i]...)
h.AdvertisementHandler(pd)
}
continue
}
pd := &PlatData{
AddressType: ep.AddressType[i],
Address: ep.Address[i],
Data: ep.Data[i],
Connectable: connectable,
RSSI: ep.RSSI[i],
}
h.plistmu.Lock()
h.plist[addr] = pd
h.plistmu.Unlock()
if scannable {
continue
}
h.AdvertisementHandler(pd)
}
}
func (h *HCI) handleNumberOfCompletedPkts(b []byte) error {
ep := &evt.NumberOfCompletedPktsEP{}
if err := ep.Unmarshal(b); err != nil {
return err
}
for _, r := range ep.Packets {
for i := 0; i < int(r.NumOfCompletedPkts); i++ {
<-h.bufCnt
}
}
return nil
}
func (h *HCI) handleConnection(b []byte) {
ep := &evt.LEConnectionCompleteEP{}
if err := ep.Unmarshal(b); err != nil {
return // FIXME
}
hh := ep.ConnectionHandle
c := newConn(h, hh)
h.connsmu.Lock()
h.conns[hh] = c
h.connsmu.Unlock()
h.setAdvertiseEnable(true)
// FIXME: sloppiness. This call should be called by the package user once we
// flesh out the support of l2cap signaling packets (CID:0x0001,0x0005)
if ep.ConnLatency != 0 || ep.ConnInterval > 0x18 {
c.updateConnection()
}
// master connection
if ep.Role == 0x01 {
pd := &PlatData{
Address: ep.PeerAddress,
Conn: c,
}
h.AcceptMasterHandler(pd)
return
}
h.plistmu.Lock()
if pd := h.plist[ep.PeerAddress]; pd != nil {
h.plistmu.Unlock()
pd.Conn = c
h.AcceptSlaveHandler(pd)
} else {
log.Printf("HCI: can't find data for %v", ep.PeerAddress)
}
}
func (h *HCI) handleDisconnectionComplete(b []byte) error {
ep := &evt.DisconnectionCompleteEP{}
if err := ep.Unmarshal(b); err != nil {
return err
}
hh := ep.ConnectionHandle
h.connsmu.Lock()
defer h.connsmu.Unlock()
c, found := h.conns[hh]
if !found {
// should not happen, just be cautious for now.
log.Printf("l2conn: disconnecting a disconnected 0x%04X connection", hh)
return nil
}
delete(h.conns, hh)
close(c.aclc)
h.setAdvertiseEnable(true)
return nil
}
func (h *HCI) handleLTKRequest(b []byte) {
ep := &evt.LELTKRequestEP{}
if err := ep.Unmarshal(b); err != nil {
log.Printf("ltkrequest: error, parsing request")
return
}
hh := ep.ConnectionHandle
h.connsmu.Lock()
defer h.connsmu.Unlock()
_, found := h.conns[hh]
if !found {
// should not happen, just be cautious for now.
log.Printf("ltkrequest: error, connection 0x%04X probably expired", hh)
return
}
h.c.Send(cmd.LELTKNegReply{ConnectionHandle: hh})
// TODO: implement proper key management
}
func (h *HCI) handleLEMeta(b []byte) error {
code := evt.LEEventCode(b[0])
switch code {
case evt.LEConnectionComplete:
go h.handleConnection(b)
case evt.LEConnectionUpdateComplete:
// anything to do here?
case evt.LEAdvertisingReport:
go h.handleAdvertisement(b)
// case evt.LEReadRemoteUsedFeaturesComplete:
case evt.LELTKRequest:
go h.handleLTKRequest(b)
// case evt.LERemoteConnectionParameterRequest:
default:
return fmt.Errorf("Unhandled LE event: 0x%02x, [ % X ]", code, b)
}
return nil
}
func (h *HCI) handleL2CAP(b []byte) error {
a := &aclData{}
if err := a.unmarshal(b); err != nil {
return err
}
h.connsmu.Lock()
defer h.connsmu.Unlock()
c, found := h.conns[a.attr]
if !found {
// should not happen, just be cautious for now.
log.Printf("l2conn: got data for disconnected handle: 0x%04x", a.attr)
return nil
}
c.aclc <- a
return nil
}

View file

@ -1,196 +0,0 @@
package linux
import (
"fmt"
"io"
"log"
"github.com/bettercap/gatt/linux/cmd"
)
type aclData struct {
attr uint16
flags uint8
dlen uint16
b []byte
}
func (a *aclData) unmarshal(b []byte) error {
if len(b) < 4 {
return fmt.Errorf("malformed acl packet")
}
attr := uint16(b[0]) | (uint16(b[1]&0x0f) << 8)
flags := b[1] >> 4
dlen := uint16(b[2]) | (uint16(b[3]) << 8)
if len(b) != 4+int(dlen) {
return fmt.Errorf("malformed acl packet")
}
*a = aclData{attr: attr, flags: flags, dlen: dlen, b: b[4:]}
return nil
}
type conn struct {
hci *HCI
attr uint16
aclc chan *aclData
datac chan []byte
}
func newConn(hci *HCI, hh uint16) *conn {
c := &conn{
hci: hci,
attr: hh,
aclc: make(chan *aclData),
datac: make(chan []byte, 32),
}
go c.loop()
return c
}
func (c *conn) loop() {
defer close(c.datac)
for a := range c.aclc {
if len(a.b) < 4 {
log.Printf("l2conn: short/corrupt packet, %v [% X]", a, a.b)
return
}
cid := uint16(a.b[2]) | (uint16(a.b[3]) << 8)
if cid == 5 {
c.handleSignal(a)
continue
}
b := make([]byte, 512)
tlen := int(uint16(a.b[0]) | uint16(a.b[1])<<8)
d := a.b[4:] // skip l2cap header
copy(b, d)
n := len(d)
// Keep receiving and reassemble continued l2cap segments
for n != tlen {
a, ok := <-c.aclc
if !ok || (a.flags&0x1) == 0 {
return
}
n += copy(b[n:], a.b)
}
c.datac <- b[:n]
}
}
func (c *conn) updateConnection() (int, error) {
b := []byte{
0x12, // Code (Connection Param Update)
0x02, // ID
0x08, 0x00, // DataLength
0x08, 0x00, // IntervalMin
0x18, 0x00, // IntervalMax
0x00, 0x00, // SlaveLatency
0xC8, 0x00} // TimeoutMultiplier
return c.write(0x05, b)
}
// write writes the l2cap payload to the controller.
// It first prepend the l2cap header (4-bytes), and diassemble the payload
// if it is larger than the HCI LE buffer size that the conntroller can support.
func (c *conn) write(cid int, b []byte) (int, error) {
flag := uint8(0) // ACL data continuation flag
tlen := len(b) // Total length of the l2cap payload
logger.Info("l2cap", "W", fmt.Sprintf("[% X]", b))
w := append(
[]byte{
0, // packet type
0, 0, // attr
0, 0, // dlen
uint8(tlen), uint8(tlen >> 8), // l2cap header
uint8(cid), uint8(cid >> 8), // l2cap header
}, b...)
n := 4 + tlen // l2cap header + l2cap payload
for n > 0 {
dlen := n
if dlen > c.hci.bufSize {
dlen = c.hci.bufSize
}
w[0] = 0x02 // packetTypeACL
w[1] = uint8(c.attr)
w[2] = uint8(c.attr>>8) | flag
w[3] = uint8(dlen)
w[4] = uint8(dlen >> 8)
// make sure we don't send more buffers than the controller can handdle
c.hci.bufCnt <- struct{}{}
c.hci.d.Write(w[:5+dlen])
w = w[dlen:] // advance the pointer to the next segment, if any.
flag = 0x10 // the rest of iterations attr continued segments, if any.
n -= dlen
}
return len(b), nil
}
func (c *conn) Read(b []byte) (int, error) {
d, ok := <-c.datac
if !ok {
return 0, io.EOF
}
if len(d) > len(b) {
return copy(b, d), io.ErrShortBuffer
}
logger.Info("l2cap", "R", fmt.Sprintf("[% X]", d))
n := copy(b, d)
return n, nil
}
func (c *conn) Write(b []byte) (int, error) {
return c.write(0x04, b)
}
// Close disconnects the connection by sending HCI disconnect command to the device.
func (c *conn) Close() error {
h := c.hci
hh := c.attr
h.connsmu.Lock()
defer h.connsmu.Unlock()
_, found := h.conns[hh]
if !found {
log.Printf("l2conn: 0x%04x already disconnected", hh)
return nil
}
if err, _ := h.c.Send(cmd.Disconnect{ConnectionHandle: hh, Reason: 0x13}); err != nil {
return fmt.Errorf("l2conn: failed to disconnect, %s", err)
}
return nil
}
// Signal Packets
// 0x00 Reserved Any
// 0x01 Command reject 0x0001 and 0x0005
// 0x02 Connection request 0x0001
// 0x03 Connection response 0x0001
// 0x04 Configure request 0x0001
// 0x05 Configure response 0x0001
// 0x06 Disconnection request 0x0001 and 0x0005
// 0x07 Disconnection response 0x0001 and 0x0005
// 0x08 Echo request 0x0001
// 0x09 Echo response 0x0001
// 0x0A Information request 0x0001
// 0x0B Information response 0x0001
// 0x0C Create Channel request 0x0001
// 0x0D Create Channel response 0x0001
// 0x0E Move Channel request 0x0001
// 0x0F Move Channel response 0x0001
// 0x10 Move Channel Confirmation 0x0001
// 0x11 Move Channel Confirmation response 0x0001
// 0x12 Connection Parameter Update request 0x0005
// 0x13 Connection Parameter Update response 0x0005
// 0x14 LE Credit Based Connection request 0x0005
// 0x15 LE Credit Based Connection response 0x0005
// 0x16 LE Flow Control Credit 0x0005
func (c *conn) handleSignal(a *aclData) error {
log.Printf("ignore l2cap signal:[ % X ]", a.b)
// FIXME: handle LE signaling channel (CID: 5)
return nil
}

View file

@ -1,7 +0,0 @@
package linux
import (
"github.com/mgutz/logxi/v1"
)
var logger = log.New("linux")

View file

@ -1,8 +0,0 @@
// Copyright 2014 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include "textflag.h"
TEXT ·use(SB),NOSPLIT,$0
RET

View file

@ -1,33 +0,0 @@
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
#include "textflag.h"
//
// System calls for 386, Linux
//
// Just jump to package syscall's implementation for all these functions.
// The runtime may know about them.
TEXT ·Syscall(SB),NOSPLIT,$0-28
JMP syscall·Syscall(SB)
TEXT ·Syscall6(SB),NOSPLIT,$0-40
JMP syscall·Syscall6(SB)
TEXT ·RawSyscall(SB),NOSPLIT,$0-28
JMP syscall·RawSyscall(SB)
TEXT ·RawSyscall6(SB),NOSPLIT,$0-40
JMP syscall·RawSyscall6(SB)
TEXT ·socketcall(SB),NOSPLIT,$0-36
JMP syscall·socketcall(SB)
TEXT ·rawsocketcall(SB),NOSPLIT,$0-36
JMP syscall·rawsocketcall(SB)
TEXT ·seek(SB),NOSPLIT,$0-28
JMP syscall·seek(SB)

View file

@ -1,121 +0,0 @@
// Package socket implements a minimal set of function of the HCI Socket,
// which is not yet supported by the Go standard library. Most of the code
// follow suit the existing code in the standard library. Once it gets
// supported officially, we can get rid of this package entirely.
package socket
import (
"errors"
"syscall"
"time"
"unsafe"
)
// Bluetooth Protocols
const (
BTPROTO_L2CAP = 0
BTPROTO_HCI = 1
BTPROTO_SCO = 2
BTPROTO_RFCOMM = 3
BTPROTO_BNEP = 4
BTPROTO_CMTP = 5
BTPROTO_HIDP = 6
BTPROTO_AVDTP = 7
)
const (
HCI_CHANNEL_RAW = 0
HCI_CHANNEL_USER = 1
HCI_CHANNEL_MONITOR = 2
HCI_CHANNEL_CONTROL = 3
)
var (
ErrSocketOpenFailed = errors.New("unable to open bluetooth socket to device")
ErrSocketBindTimeout = errors.New("timeout occured binding to bluetooth device")
)
type _Socklen uint32
type Sockaddr interface {
sockaddr() (ptr unsafe.Pointer, len _Socklen, err error) // lowercase; only we can define Sockaddrs
}
type rawSockaddrHCI struct {
Family uint16
Dev uint16
Channel uint16
}
type SockaddrHCI struct {
Dev int
Channel uint16
raw rawSockaddrHCI
}
const sizeofSockaddrHCI = unsafe.Sizeof(rawSockaddrHCI{})
func (sa *SockaddrHCI) sockaddr() (unsafe.Pointer, _Socklen, error) {
if sa.Dev < 0 || sa.Dev > 0xFFFF {
return nil, 0, syscall.EINVAL
}
if sa.Channel < 0 || sa.Channel > 0xFFFF {
return nil, 0, syscall.EINVAL
}
sa.raw.Family = AF_BLUETOOTH
sa.raw.Dev = uint16(sa.Dev)
sa.raw.Channel = sa.Channel
return unsafe.Pointer(&sa.raw), _Socklen(sizeofSockaddrHCI), nil
}
func Socket(domain, typ, proto int) (int, error) {
for i := 0; i < 5; i++ {
if fd, err := syscall.Socket(domain, typ, proto); err == nil || err != syscall.EBUSY {
return fd, err
}
time.Sleep(time.Second)
}
return 0, ErrSocketOpenFailed
}
func Bind(fd int, sa Sockaddr) (err error) {
ptr, n, err := sa.sockaddr()
if err != nil {
return err
}
for i := 0; i < 5; i++ {
if err = bind(fd, ptr, n); err == nil || err != syscall.EBUSY {
return err
}
time.Sleep(time.Second)
}
return ErrSocketBindTimeout
}
// Socket Level
const (
SOL_HCI = 0
SOL_L2CAP = 6
SOL_SCO = 17
SOL_RFCOMM = 18
SOL_BLUETOOTH = 274
)
// HCI Socket options
const (
HCI_DATA_DIR = 1
HCI_FILTER = 2
HCI_TIME_STAMP = 3
)
type HCIFilter struct {
TypeMask uint32
EventMask [2]uint32
opcode uint16
}
func SetsockoptFilter(fd int, f *HCIFilter) (err error) {
return setsockopt(fd, SOL_HCI, HCI_FILTER, unsafe.Pointer(f), unsafe.Sizeof(*f))
}

View file

@ -1,24 +0,0 @@
// +build !386
package socket
import (
"syscall"
"unsafe"
)
func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, _, e1 := syscall.Syscall(syscall.SYS_BIND, uintptr(s), uintptr(addr), uintptr(addrlen))
if e1 != 0 {
err = e1
}
return
}
func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {
_, _, e1 := syscall.Syscall6(syscall.SYS_SETSOCKOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), uintptr(vallen), 0)
if e1 != 0 {
err = e1
}
return
}

View file

@ -1,6 +0,0 @@
// +build darwin
package socket
// For compile time compatibility
const AF_BLUETOOTH = 0

View file

@ -1,7 +0,0 @@
// +build linux
package socket
import "syscall"
const AF_BLUETOOTH = syscall.AF_BLUETOOTH

View file

@ -1,31 +0,0 @@
// +build linux,386
package socket
import (
"syscall"
"unsafe"
)
const (
BIND = 2
SETSOCKETOPT = 14
)
func bind(s int, addr unsafe.Pointer, addrlen _Socklen) (err error) {
_, e1 := socketcall(BIND, uintptr(s), uintptr(addr), uintptr(addrlen), 0, 0, 0)
if e1 != 0 {
err = e1
}
return
}
func setsockopt(s int, level int, name int, val unsafe.Pointer, vallen uintptr) (err error) {
_, e1 := socketcall(SETSOCKETOPT, uintptr(s), uintptr(level), uintptr(name), uintptr(val), vallen, 0)
if e1 != 0 {
err = e1
}
return
}
func socketcall(call int, a0, a1, a2, a3, a4, a5 uintptr) (n int, err syscall.Errno)

View file

@ -1,29 +0,0 @@
package util
type BytePool struct {
pool chan []byte
width int
}
func NewBytePool(width int, depth int) *BytePool {
return &BytePool{
pool: make(chan []byte, depth),
width: width,
}
}
func (p *BytePool) Get() (b []byte) {
select {
case b = <-p.pool:
default:
b = make([]byte, p.width)
}
return b
}
func (p *BytePool) Put(b []byte) {
select {
case p.pool <- b:
default:
}
}

View file

@ -1,16 +0,0 @@
package util
import "encoding/binary"
type order struct{ binary.ByteOrder }
var Order = order{binary.LittleEndian}
func (o order) Int8(b []byte) int8 { return int8(b[0]) }
func (o order) Uint8(b []byte) uint8 { return b[0] }
func (o order) MAC(b []byte) [6]byte { return [6]byte{b[5], b[4], b[3], b[2], b[1], b[0]} }
func (o order) PutUint8(b []byte, v uint8) { b[0] = v }
func (o order) PutMAC(b []byte, m [6]byte) {
b[0], b[1], b[2], b[3], b[4], b[5] = m[5], m[4], m[3], m[2], m[1], m[0]
}

View file

@ -1,15 +0,0 @@
package gatt
const (
CentralManager = 0 // Client functions (default)
PeripheralManager = 1 // Server functions
)
// MacDeviceRole specify the XPC connection type to connect blued.
// THis option can only be used with NewDevice on OS X implementation.
func MacDeviceRole(r int) Option {
return func(d Device) error {
d.(*device).role = r
return nil
}
}

View file

@ -1,87 +0,0 @@
package gatt
import (
"errors"
"io"
"github.com/bettercap/gatt/linux/cmd"
)
// LnxDeviceID specifies which HCI device to use.
// If n is set to -1, all the available HCI devices will be probed.
// If chk is set to true, LnxDeviceID checks the LE support in the feature list of the HCI device.
// This is to filter devices that does not support LE. In case some LE driver that doesn't correctly
// set the LE support in its feature list, user can turn off the check.
// This option can only be used with NewDevice on Linux implementation.
func LnxDeviceID(n int, chk bool) Option {
return func(d Device) error {
d.(*device).devID = n
d.(*device).chkLE = chk
return nil
}
}
// LnxMaxConnections is an optional parameter.
// If set, it overrides the default max connections supported.
// This option can only be used with NewDevice on Linux implementation.
func LnxMaxConnections(n int) Option {
return func(d Device) error {
d.(*device).maxConn = n
return nil
}
}
// LnxSetAdvertisingEnable sets the advertising data to the HCI device.
// This option can be used with Option on Linux implementation.
func LnxSetAdvertisingEnable(en bool) Option {
return func(d Device) error {
dd := d.(*device)
if dd == nil {
return errors.New("device is not initialized")
}
if err := dd.update(); err != nil {
return err
}
return dd.hci.SetAdvertiseEnable(en)
}
}
// LnxSetAdvertisingData sets the advertising data to the HCI device.
// This option can be used with NewDevice or Option on Linux implementation.
func LnxSetAdvertisingData(c *cmd.LESetAdvertisingData) Option {
return func(d Device) error {
d.(*device).advData = c
return nil
}
}
// LnxSetScanResponseData sets the scan response data to the HXI device.
// This option can be used with NewDevice or Option on Linux implementation.
func LnxSetScanResponseData(c *cmd.LESetScanResponseData) Option {
return func(d Device) error {
d.(*device).scanResp = c
return nil
}
}
// LnxSetAdvertisingParameters sets the advertising parameters to the HCI device.
// This option can be used with NewDevice or Option on Linux implementation.
func LnxSetAdvertisingParameters(c *cmd.LESetAdvertisingParameters) Option {
return func(d Device) error {
d.(*device).advParam = c
return nil
}
}
// LnxSendHCIRawCommand sends a raw command to the HCI device
// This option can be used with NewDevice or Option on Linux implementation.
func LnxSendHCIRawCommand(c cmd.CmdParam, rsp io.Writer) Option {
return func(d Device) error {
b, err := d.(*device).SendHCIRawCommand(c)
if rsp == nil {
return err
}
rsp.Write(b)
return err
}
}

View file

@ -1,102 +0,0 @@
package gatt
import (
"errors"
"sync"
)
// Peripheral is the interface that represent a remote peripheral device.
type Peripheral interface {
// Device returns the underlying device.
Device() Device
// ID is the platform specific unique ID of the remote peripheral, e.g. MAC for Linux, Peripheral UUID for MacOS.
ID() string
// Name returns the name of the remote peripheral.
// This can be the advertised name, if exists, or the GAP device name, which takes priority
Name() string
// Services returnns the services of the remote peripheral which has been discovered.
Services() []*Service
// DiscoverServices discover the specified services of the remote peripheral.
// If the specified services is set to nil, all the available services of the remote peripheral are returned.
DiscoverServices(s []UUID) ([]*Service, error)
// DiscoverIncludedServices discovers the specified included services of a service.
// If the specified services is set to nil, all the included services of the service are returned.
DiscoverIncludedServices(ss []UUID, s *Service) ([]*Service, error)
// DiscoverCharacteristics discovers the specified characteristics of a service.
// If the specified characterstics is set to nil, all the characteristic of the service are returned.
DiscoverCharacteristics(c []UUID, s *Service) ([]*Characteristic, error)
// DiscoverDescriptors discovers the descriptors of a characteristic.
// If the specified descriptors is set to nil, all the descriptors of the characteristic are returned.
DiscoverDescriptors(d []UUID, c *Characteristic) ([]*Descriptor, error)
// ReadCharacteristic retrieves the value of a specified characteristic.
ReadCharacteristic(c *Characteristic) ([]byte, error)
// ReadLongCharacteristic retrieves the value of a specified characteristic that is longer than the
// MTU.
ReadLongCharacteristic(c *Characteristic) ([]byte, error)
// ReadDescriptor retrieves the value of a specified characteristic descriptor.
ReadDescriptor(d *Descriptor) ([]byte, error)
// WriteCharacteristic writes the value of a characteristic.
WriteCharacteristic(c *Characteristic, b []byte, noRsp bool) error
// WriteDescriptor writes the value of a characteristic descriptor.
WriteDescriptor(d *Descriptor, b []byte) error
// SetNotifyValue sets notifications for the value of a specified characteristic.
SetNotifyValue(c *Characteristic, f func(*Characteristic, []byte, error)) error
// SetIndicateValue sets indications for the value of a specified characteristic.
SetIndicateValue(c *Characteristic, f func(*Characteristic, []byte, error)) error
// ReadRSSI retrieves the current RSSI value for the remote peripheral.
ReadRSSI() int
// SetMTU sets the mtu for the remote peripheral.
SetMTU(mtu uint16) error
}
type subscriber struct {
sub map[uint16]subscribefn
mu *sync.Mutex
}
type subscribefn func([]byte, error)
func newSubscriber() *subscriber {
return &subscriber{
sub: make(map[uint16]subscribefn),
mu: &sync.Mutex{},
}
}
func (s *subscriber) subscribe(h uint16, f subscribefn) {
s.mu.Lock()
s.sub[h] = f
s.mu.Unlock()
}
func (s *subscriber) unsubscribe(h uint16) {
s.mu.Lock()
delete(s.sub, h)
s.mu.Unlock()
}
func (s *subscriber) fn(h uint16) subscribefn {
s.mu.Lock()
defer s.mu.Unlock()
return s.sub[h]
}
var (
ErrInvalidLength = errors.New("invalid length")
)

View file

@ -1,277 +0,0 @@
package gatt
import (
"errors"
"log"
"github.com/bettercap/gatt/xpc"
)
type peripheral struct {
// NameChanged is called whenever the peripheral GAP Device name has changed.
NameChanged func(Peripheral)
// ServicesModified is called when one or more service of a peripheral have changed.
// A list of invalid service is provided in the parameter.
ServicesModified func(Peripheral, []*Service)
d *device
svcs []*Service
sub *subscriber
id xpc.UUID
name string
reqc chan message
rspc chan message
quitc chan struct{}
}
func NewPeripheral(u UUID) Peripheral { return &peripheral{id: xpc.UUID(u.b)} }
func (p *peripheral) Device() Device { return p.d }
func (p *peripheral) ID() string { return p.id.String() }
func (p *peripheral) Name() string { return p.name }
func (p *peripheral) Services() []*Service { return p.svcs }
func (p *peripheral) DiscoverServices(ss []UUID) ([]*Service, error) {
rsp := p.sendReq(45, xpc.Dict{
"kCBMsgArgDeviceUUID": p.id,
"kCBMsgArgUUIDs": uuidSlice(ss),
})
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
return nil, AttEcode(res)
}
svcs := []*Service{}
for _, xss := range rsp["kCBMsgArgServices"].(xpc.Array) {
xs := xss.(xpc.Dict)
u := MustParseUUID(xs.MustGetHexBytes("kCBMsgArgUUID"))
h := uint16(xs.MustGetInt("kCBMsgArgServiceStartHandle"))
endh := uint16(xs.MustGetInt("kCBMsgArgServiceEndHandle"))
svcs = append(svcs, &Service{uuid: u, h: h, endh: endh})
}
p.svcs = svcs
return svcs, nil
}
func (p *peripheral) DiscoverIncludedServices(ss []UUID, s *Service) ([]*Service, error) {
rsp := p.sendReq(60, xpc.Dict{
"kCBMsgArgDeviceUUID": p.id,
"kCBMsgArgServiceStartHandle": s.h,
"kCBMsgArgServiceEndHandle": s.endh,
"kCBMsgArgUUIDs": uuidSlice(ss),
})
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
return nil, AttEcode(res)
}
// TODO
return nil, notImplemented
}
func (p *peripheral) DiscoverCharacteristics(cs []UUID, s *Service) ([]*Characteristic, error) {
rsp := p.sendReq(62, xpc.Dict{
"kCBMsgArgDeviceUUID": p.id,
"kCBMsgArgServiceStartHandle": s.h,
"kCBMsgArgServiceEndHandle": s.endh,
"kCBMsgArgUUIDs": uuidSlice(cs),
})
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
return nil, AttEcode(res)
}
for _, xcs := range rsp.MustGetArray("kCBMsgArgCharacteristics") {
xc := xcs.(xpc.Dict)
u := MustParseUUID(xc.MustGetHexBytes("kCBMsgArgUUID"))
ch := uint16(xc.MustGetInt("kCBMsgArgCharacteristicHandle"))
vh := uint16(xc.MustGetInt("kCBMsgArgCharacteristicValueHandle"))
props := Property(xc.MustGetInt("kCBMsgArgCharacteristicProperties"))
c := &Characteristic{uuid: u, svc: s, props: props, h: ch, vh: vh}
s.chars = append(s.chars, c)
}
return s.chars, nil
}
func (p *peripheral) DiscoverDescriptors(ds []UUID, c *Characteristic) ([]*Descriptor, error) {
rsp := p.sendReq(70, xpc.Dict{
"kCBMsgArgDeviceUUID": p.id,
"kCBMsgArgCharacteristicHandle": c.h,
"kCBMsgArgCharacteristicValueHandle": c.vh,
"kCBMsgArgUUIDs": uuidSlice(ds),
})
for _, xds := range rsp.MustGetArray("kCBMsgArgDescriptors") {
xd := xds.(xpc.Dict)
u := MustParseUUID(xd.MustGetHexBytes("kCBMsgArgUUID"))
h := uint16(xd.MustGetInt("kCBMsgArgDescriptorHandle"))
d := &Descriptor{uuid: u, char: c, h: h}
c.descs = append(c.descs, d)
}
return c.descs, nil
}
func (p *peripheral) ReadCharacteristic(c *Characteristic) ([]byte, error) {
rsp := p.sendReq(65, xpc.Dict{
"kCBMsgArgDeviceUUID": p.id,
"kCBMsgArgCharacteristicHandle": c.h,
"kCBMsgArgCharacteristicValueHandle": c.vh,
})
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
return nil, AttEcode(res)
}
b := rsp.MustGetBytes("kCBMsgArgData")
return b, nil
}
func (p *peripheral) ReadLongCharacteristic(c *Characteristic) ([]byte, error) {
return nil, errors.New("Not implemented")
}
func (p *peripheral) WriteCharacteristic(c *Characteristic, b []byte, noRsp bool) error {
args := xpc.Dict{
"kCBMsgArgDeviceUUID": p.id,
"kCBMsgArgCharacteristicHandle": c.h,
"kCBMsgArgCharacteristicValueHandle": c.vh,
"kCBMsgArgData": b,
"kCBMsgArgType": map[bool]int{false: 0, true: 1}[noRsp],
}
if noRsp {
p.sendCmd(66, args)
return nil
}
rsp := p.sendReq(66, args)
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
return AttEcode(res)
}
return nil
}
func (p *peripheral) ReadDescriptor(d *Descriptor) ([]byte, error) {
rsp := p.sendReq(77, xpc.Dict{
"kCBMsgArgDeviceUUID": p.id,
"kCBMsgArgDescriptorHandle": d.h,
})
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
return nil, AttEcode(res)
}
b := rsp.MustGetBytes("kCBMsgArgData")
return b, nil
}
func (p *peripheral) WriteDescriptor(d *Descriptor, b []byte) error {
rsp := p.sendReq(78, xpc.Dict{
"kCBMsgArgDeviceUUID": p.id,
"kCBMsgArgDescriptorHandle": d.h,
"kCBMsgArgData": b,
})
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
return AttEcode(res)
}
return nil
}
func (p *peripheral) SetNotifyValue(c *Characteristic, f func(*Characteristic, []byte, error)) error {
set := 1
if f == nil {
set = 0
}
// To avoid race condition, registeration is handled before requesting the server.
if f != nil {
// Note: when notified, core bluetooth reports characteristic handle, not value's handle.
p.sub.subscribe(c.h, func(b []byte, err error) { f(c, b, err) })
}
rsp := p.sendReq(68, xpc.Dict{
"kCBMsgArgDeviceUUID": p.id,
"kCBMsgArgCharacteristicHandle": c.h,
"kCBMsgArgCharacteristicValueHandle": c.vh,
"kCBMsgArgState": set,
})
if res := rsp.MustGetInt("kCBMsgArgResult"); res != 0 {
return AttEcode(res)
}
// To avoid race condition, unregisteration is handled after server responses.
if f == nil {
p.sub.unsubscribe(c.h)
}
return nil
}
func (p *peripheral) SetIndicateValue(c *Characteristic,
f func(*Characteristic, []byte, error)) error {
// TODO: Implement set indications logic for darwin (https://github.com/paypal/gatt/issues/32)
return nil
}
func (p *peripheral) ReadRSSI() int {
rsp := p.sendReq(43, xpc.Dict{"kCBMsgArgDeviceUUID": p.id})
return rsp.MustGetInt("kCBMsgArgData")
}
func (p *peripheral) SetMTU(mtu uint16) error {
return errors.New("Not implemented")
}
func uuidSlice(uu []UUID) [][]byte {
us := [][]byte{}
for _, u := range uu {
us = append(us, reverse(u.b))
}
return us
}
type message struct {
id int
args xpc.Dict
rspc chan xpc.Dict
}
func (p *peripheral) sendCmd(id int, args xpc.Dict) {
p.reqc <- message{id: id, args: args}
}
func (p *peripheral) sendReq(id int, args xpc.Dict) xpc.Dict {
m := message{id: id, args: args, rspc: make(chan xpc.Dict)}
p.reqc <- m
return <-m.rspc
}
func (p *peripheral) loop() {
rspc := make(chan message)
go func() {
for {
select {
case req := <-p.reqc:
p.d.sendCBMsg(req.id, req.args)
if req.rspc == nil {
break
}
m := <-rspc
req.rspc <- m.args
case <-p.quitc:
return
}
}
}()
for {
select {
case rsp := <-p.rspc:
// Notification
if rsp.id == 71 && rsp.args.GetInt("kCBMsgArgIsNotification", 0) != 0 {
// While we're notified with the value's handle, blued reports the characteristic handle.
ch := uint16(rsp.args.MustGetInt("kCBMsgArgCharacteristicHandle"))
b := rsp.args.MustGetBytes("kCBMsgArgData")
f := p.sub.fn(ch)
if f == nil {
log.Printf("notified by unsubscribed handle")
// FIXME: should terminate the connection?
} else {
go f(b, nil)
}
break
}
rspc <- rsp
case <-p.quitc:
return
}
}
}

View file

@ -1,475 +0,0 @@
package gatt
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"log"
"net"
"strings"
"github.com/bettercap/gatt/linux"
)
type peripheral struct {
// NameChanged is called whenever the peripheral GAP device name has changed.
NameChanged func(*peripheral)
// ServicedModified is called when one or more service of a peripheral have changed.
// A list of invalid service is provided in the parameter.
ServicesModified func(*peripheral, []*Service)
d *device
svcs []*Service
sub *subscriber
mtu uint16
l2c io.ReadWriteCloser
reqc chan message
quitc chan struct{}
pd *linux.PlatData // platform specific data
}
func (p *peripheral) Device() Device { return p.d }
func (p *peripheral) ID() string { return strings.ToUpper(net.HardwareAddr(p.pd.Address[:]).String()) }
func (p *peripheral) Name() string { return p.pd.Name }
func (p *peripheral) Services() []*Service { return p.svcs }
func finish(op byte, h uint16, b []byte) (bool, error) {
done := b[0] == attOpError && b[1] == op && b[2] == byte(h) && b[3] == byte(h>>8)
var err error
if b[0] == attOpError {
err = AttEcode(b[4])
if err == AttEcodeAttrNotFound {
// Expect attribute not found errors
err = nil
} else {
// log.Printf("unexpected protocol error: %s", e)
// FIXME: terminate the connection
}
}
return done, err
}
func (p *peripheral) DiscoverServices(ds []UUID) ([]*Service, error) {
// p.pd.Conn.Write([]byte{0x02, 0x87, 0x00}) // MTU
done := false
start := uint16(0x0001)
var err error
for !done {
op := byte(attOpReadByGroupReq)
b := make([]byte, 7)
b[0] = op
binary.LittleEndian.PutUint16(b[1:3], start)
binary.LittleEndian.PutUint16(b[3:5], 0xFFFF)
binary.LittleEndian.PutUint16(b[5:7], 0x2800)
b = p.sendReq(op, b)
done, err = finish(op, start, b)
if done {
break
}
b = b[1:]
l, b := int(b[0]), b[1:]
switch {
case l == 6 && (len(b)%6 == 0):
case l == 20 && (len(b)%20 == 0):
default:
return nil, ErrInvalidLength
}
for len(b) != 0 {
endh := binary.LittleEndian.Uint16(b[2:4])
u := UUID{b[4:l]}
if UUIDContains(ds, u) {
s := &Service{
uuid: u,
h: binary.LittleEndian.Uint16(b[:2]),
endh: endh,
}
p.svcs = append(p.svcs, s)
}
b = b[l:]
done = endh == 0xFFFF
start = endh + 1
}
}
return p.svcs, err
}
func (p *peripheral) DiscoverIncludedServices(ss []UUID, s *Service) ([]*Service, error) {
// TODO
return nil, nil
}
func (p *peripheral) DiscoverCharacteristics(cs []UUID, s *Service) ([]*Characteristic, error) {
done := false
start := s.h
var prev *Characteristic
var err error
for !done {
op := byte(attOpReadByTypeReq)
b := make([]byte, 7)
b[0] = op
binary.LittleEndian.PutUint16(b[1:3], start)
binary.LittleEndian.PutUint16(b[3:5], s.endh)
binary.LittleEndian.PutUint16(b[5:7], 0x2803)
b = p.sendReq(op, b)
if done = b[0] != byte(attOpReadByTypeRsp); done {
break
}
b = b[1:]
l, b := int(b[0]), b[1:]
switch {
case l == 7 && (len(b)%7 == 0):
case l == 21 && (len(b)%21 == 0):
default:
return nil, ErrInvalidLength
}
for len(b) != 0 {
h := binary.LittleEndian.Uint16(b[:2])
props := Property(b[2])
vh := binary.LittleEndian.Uint16(b[3:5])
u := UUID{b[5:l]}
s := searchService(p.svcs, h, vh)
if s == nil {
log.Printf("Can't find service range that contains 0x%04X - 0x%04X", h, vh)
return nil, fmt.Errorf("Can't find service range that contains 0x%04X - 0x%04X", h, vh)
}
c := &Characteristic{
uuid: u,
svc: s,
props: props,
h: h,
vh: vh,
}
if UUIDContains(cs, u) {
s.chars = append(s.chars, c)
}
b = b[l:]
done = vh == s.endh
start = vh + 1
if prev != nil {
prev.endh = c.h - 1
}
prev = c
}
}
if len(s.chars) > 1 {
s.chars[len(s.chars)-1].endh = s.endh
}
return s.chars, err
}
func (p *peripheral) DiscoverDescriptors(ds []UUID, c *Characteristic) ([]*Descriptor, error) {
done := false
start := c.vh + 1
var err error
for !done {
if c.endh == 0 {
c.endh = c.svc.endh
}
op := byte(attOpFindInfoReq)
b := make([]byte, 5)
b[0] = op
binary.LittleEndian.PutUint16(b[1:3], start)
binary.LittleEndian.PutUint16(b[3:5], c.endh)
b = p.sendReq(op, b)
done, err = finish(op, start, b)
if done {
break
}
b = b[1:]
var l int
f, b := int(b[0]), b[1:]
switch {
case f == 1 && (len(b)%4 == 0):
l = 4
case f == 2 && (len(b)%18 == 0):
l = 18
default:
return nil, ErrInvalidLength
}
for len(b) != 0 {
h := binary.LittleEndian.Uint16(b[:2])
u := UUID{b[2:l]}
d := &Descriptor{uuid: u, h: h, char: c}
if UUIDContains(ds, u) {
c.descs = append(c.descs, d)
}
if u.Equal(attrClientCharacteristicConfigUUID) {
c.cccd = d
}
b = b[l:]
done = h == c.endh
start = h + 1
}
}
return c.descs, err
}
func (p *peripheral) ReadCharacteristic(c *Characteristic) ([]byte, error) {
b := make([]byte, 3)
op := byte(attOpReadReq)
b[0] = op
binary.LittleEndian.PutUint16(b[1:3], c.vh)
b = p.sendReq(op, b)
_, err := finish(op, c.vh, b)
b = b[1:]
return b, err
}
func (p *peripheral) ReadLongCharacteristic(c *Characteristic) ([]byte, error) {
// The spec says that a read blob request should fail if the characteristic
// is smaller than mtu - 1. To simplify the API, the first read is done
// with a regular read request. If the buffer received is equal to mtu -1,
// then we read the rest of the data using read blob.
firstRead, err := p.ReadCharacteristic(c)
if err != nil {
return nil, err
}
if len(firstRead) < int(p.mtu)-1 {
return firstRead, nil
}
var buf bytes.Buffer
buf.Write(firstRead)
off := uint16(len(firstRead))
done := false
err = AttEcodeSuccess
for {
b := make([]byte, 5)
op := byte(attOpReadBlobReq)
b[0] = op
binary.LittleEndian.PutUint16(b[1:3], c.vh)
binary.LittleEndian.PutUint16(b[3:5], off)
b = p.sendReq(op, b)
done, err = finish(op, c.vh, b)
if done {
break
}
b = b[1:]
if len(b) == 0 {
break
}
buf.Write(b)
off += uint16(len(b))
if len(b) < int(p.mtu)-1 {
break
}
}
return buf.Bytes(), err
}
func (p *peripheral) WriteCharacteristic(c *Characteristic, value []byte, noRsp bool) error {
b := make([]byte, 3+len(value))
op := byte(attOpWriteReq)
b[0] = op
if noRsp {
b[0] = attOpWriteCmd
}
binary.LittleEndian.PutUint16(b[1:3], c.vh)
copy(b[3:], value)
if noRsp {
p.sendCmd(op, b)
return nil
}
b = p.sendReq(op, b)
_, err := finish(op, c.vh, b)
b = b[1:]
return err
}
func (p *peripheral) ReadDescriptor(d *Descriptor) ([]byte, error) {
b := make([]byte, 3)
op := byte(attOpReadReq)
b[0] = op
binary.LittleEndian.PutUint16(b[1:3], d.h)
b = p.sendReq(op, b)
_, err := finish(op, d.h, b)
b = b[1:]
return b, err
}
func (p *peripheral) WriteDescriptor(d *Descriptor, value []byte) error {
b := make([]byte, 3+len(value))
op := byte(attOpWriteReq)
b[0] = op
binary.LittleEndian.PutUint16(b[1:3], d.h)
copy(b[3:], value)
b = p.sendReq(op, b)
_, err := finish(op, d.h, b)
b = b[1:]
return err
}
func (p *peripheral) setNotifyValue(c *Characteristic, flag uint16,
f func(*Characteristic, []byte, error)) error {
if c.cccd == nil {
return errors.New("no cccd") // FIXME
}
ccc := uint16(0)
if f != nil {
ccc = flag
p.sub.subscribe(c.vh, func(b []byte, err error) { f(c, b, err) })
}
b := make([]byte, 5)
op := byte(attOpWriteReq)
b[0] = op
binary.LittleEndian.PutUint16(b[1:3], c.cccd.h)
binary.LittleEndian.PutUint16(b[3:5], ccc)
b = p.sendReq(op, b)
_, err := finish(op, c.cccd.h, b)
b = b[1:]
if f == nil {
p.sub.unsubscribe(c.vh)
}
return err
}
func (p *peripheral) SetNotifyValue(c *Characteristic,
f func(*Characteristic, []byte, error)) error {
return p.setNotifyValue(c, gattCCCNotifyFlag, f)
}
func (p *peripheral) SetIndicateValue(c *Characteristic,
f func(*Characteristic, []byte, error)) error {
return p.setNotifyValue(c, gattCCCIndicateFlag, f)
}
func (p *peripheral) ReadRSSI() int {
// TODO: implement
return -1
}
func searchService(ss []*Service, start, end uint16) *Service {
for _, s := range ss {
if s.h < start && s.endh >= end {
return s
}
}
return nil
}
// TODO: unifiy the message with OS X pots and refactor
type message struct {
op byte
b []byte
rspc chan []byte
}
func (p *peripheral) sendCmd(op byte, b []byte) {
p.reqc <- message{op: op, b: b}
}
func (p *peripheral) sendReq(op byte, b []byte) []byte {
m := message{op: op, b: b, rspc: make(chan []byte)}
p.reqc <- m
return <-m.rspc
}
func (p *peripheral) loop() {
// Serialize the request.
rspc := make(chan []byte)
// Dequeue request loop
go func() {
for {
select {
case req := <-p.reqc:
p.l2c.Write(req.b)
if req.rspc == nil {
break
}
for {
r := <-rspc
reqOp, rspOp := req.b[0], r[0]
if rspOp == attRspFor[reqOp] || (rspOp == attOpError && r[1] == reqOp) {
req.rspc <- r
break
}
log.Printf("Request 0x%02x got a mismatched response: 0x%02x", reqOp, rspOp)
p.l2c.Write(attErrorRsp(rspOp, 0x0000, AttEcodeReqNotSupp))
}
case <-p.quitc:
return
}
}
}()
// L2CAP implementations shall support a minimum MTU size of 48 bytes.
// The default value is 672 bytes
buf := make([]byte, 672)
// Handling response or notification/indication
for {
n, err := p.l2c.Read(buf)
if n == 0 || err != nil {
close(p.quitc)
return
}
b := make([]byte, n)
copy(b, buf)
if (b[0] != attOpHandleNotify) && (b[0] != attOpHandleInd) {
log.Printf("response 0x%x", b[0])
rspc <- b
continue
}
h := binary.LittleEndian.Uint16(b[1:3])
f := p.sub.fn(h)
if f == nil {
log.Printf("notified by unsubscribed handle")
// FIXME: terminate the connection?
} else {
go f(b[3:], nil)
}
if b[0] == attOpHandleInd {
// write aknowledgement for indication
p.l2c.Write([]byte{attOpHandleCnf})
}
}
}
func (p *peripheral) SetMTU(mtu uint16) error {
b := make([]byte, 3)
op := byte(attOpMtuReq)
b[0] = op
h := uint16(mtu)
binary.LittleEndian.PutUint16(b[1:3], h)
b = p.sendReq(op, b)
done, err := finish(op, h, b)
if !done {
serverMTU := binary.LittleEndian.Uint16(b[1:3])
if serverMTU < mtu {
mtu = serverMTU
}
p.mtu = mtu
}
return err
}

View file

@ -1,115 +0,0 @@
# Package gatt provides a Bluetooth Low Energy GATT implementation.
Gatt (Generic Attribute Profile) is the protocol used to write BLE peripherals (servers) and centrals (clients).
As a peripheral, you can create services, characteristics, and descriptors,
advertise, accept connections, and handle requests.
As a central, you can scan, connect, discover services, and make requests.
## SETUP
### gatt supports both Linux and OS X.
### On Linux:
To gain complete and exclusive control of the HCI device, gatt uses
HCI_CHANNEL_USER (introduced in Linux v3.14) instead of HCI_CHANNEL_RAW.
Those who must use an older kernel may patch in these relevant commits
from Marcel Holtmann:
Bluetooth: Introduce new HCI socket channel for user operation
Bluetooth: Introduce user channel flag for HCI devices
Bluetooth: Refactor raw socket filter into more readable code
Note that because gatt uses HCI_CHANNEL_USER, once gatt has opened the
device no other program may access it.
Before starting a gatt program, make sure that your BLE device is down:
sudo hciconfig
sudo hciconfig hci0 down # or whatever hci device you want to use
If you have BlueZ 5.14+ (or aren't sure), stop the built-in
bluetooth server, which interferes with gatt, e.g.:
sudo service bluetooth stop
Because gatt programs administer network devices, they must
either be run as root, or be granted appropriate capabilities:
sudo <executable>
# OR
sudo setcap 'cap_net_raw,cap_net_admin=eip' <executable>
<executable>
## Usage
Please see [godoc.org](http://godoc.org/github.com/paypal/gatt) for documentation.
## Examples
### Build and run the examples on a native environment (Linux or OS X)
Go is a compiled language, which means to run the examples you need to build them first.
# Build the sample server.
go build examples/server.go
# Start the sample server.
sudo ./server
Alternatively, you can use "go run" to build and run the examples in a single step:
# Build and run the sample server.
sudo go run examples/server.go
Discoverer and explorer demonstrates central (client) functions:
# Discover surrounding peripherals.
sudo go run examples/discoverer.go
# Connect to and explorer a peripheral device.
sudo go run examples/explorer.go <peripheral ID>
### Cross-compile and deploy to a target device
# Build and run the server example on a ARMv5 target device.
GOARCH=arm GOARM=5 GOOS=linux go build examples/server.go
cp server <target device>
# Start the server on the target device
sudo ./server
See the server.go, discoverer.go, and explorer.go in the examples/
directory for writing server or client programs that run on Linux
and OS X.
Users, especially on Linux platforms, seeking finer-grained control
over the devices can see the examples/server_lnx.go for the usage
of Option, which are platform specific.
See the rest of the docs for other options and finer-grained control.
## Note
Note that some BLE central devices, particularly iOS, may aggressively
cache results from previous connections. If you change your services or
characteristics, you may need to reboot the other device to pick up the
changes. This is a common source of confusion and apparent bugs. For an
OS X central, see http://stackoverflow.com/questions/20553957.
## Known Issues
Currently OS X vesion does not support subscribing to indications.
Please check [#32](https://github.com/paypal/gatt/issues/32) for the status of this issue.
## REFERENCES
gatt started life as a port of bleno, to which it is indebted:
https://github.com/sandeepmistry/bleno. If you are having
problems with gatt, particularly around installation, issues
filed with bleno might also be helpful references.
To try out your GATT server, it is useful to experiment with a
generic BLE client. LightBlue is a good choice. It is available
free for both iOS and OS X.
gatt is similar to [bleno](https://github.com/sandeepmistry/bleno) and [noble](https://github.com/sandeepmistry/noble), which offer BLE GATT implementations for node.js.
Gatt is released under a [BSD-style license](./LICENSE.md).

View file

@ -1,204 +0,0 @@
package gatt
import (
"errors"
)
const (
DefaultMTU = 1024
)
type simDevice struct {
deviceHandler
s *Service
advertisedName string
}
func NewSimDeviceClient(service *Service, advertisedName string) *simDevice {
return &simDevice{
s: service,
advertisedName: advertisedName,
}
}
func (d *simDevice) Init(stateChanged func(Device, State)) error {
d.stateChanged = stateChanged
go stateChanged(d, StatePoweredOn)
return nil
}
func (d *simDevice) Advertise(a *AdvPacket) error {
return errors.New("Method not supported")
}
func (d *simDevice) AdvertiseNameAndServices(name string, ss []UUID) error {
return errors.New("Method not supported")
}
func (d *simDevice) AdvertiseIBeaconData(b []byte) error {
return errors.New("Method not supported")
}
func (d *simDevice) AdvertiseIBeacon(u UUID, major, minor uint16, pwr int8) error {
return errors.New("Method not supported")
}
func (d *simDevice) StopAdvertising() error {
return errors.New("Method not supported")
}
func (d *simDevice) RemoveAllServices() error {
return errors.New("Method not supported")
}
func (d *simDevice) AddService(s *Service) error {
return errors.New("Method not supported")
}
func (d *simDevice) SetServices(ss []*Service) error {
return errors.New("Method not supported")
}
func (d *simDevice) Scan(ss []UUID, dup bool) {
for _, s := range ss {
if s.Equal(d.s.UUID()) {
go d.peripheralDiscovered(
&simPeripheral{d},
&Advertisement{LocalName: d.advertisedName},
0,
)
}
}
}
func (d *simDevice) StopScanning() {
}
func (d *simDevice) Stop() error {
go d.stateChanged(d, StatePoweredOff)
return nil
}
func (d *simDevice) Connect(p Peripheral) {
go d.peripheralConnected(p, nil)
}
func (d *simDevice) CancelConnection(p Peripheral) {
go d.peripheralDisconnected(p, nil)
}
func (d *simDevice) Handle(hh ...Handler) {
for _, h := range hh {
h(d)
}
}
func (d *simDevice) Option(o ...Option) error {
return errors.New("Method not supported")
}
type simPeripheral struct {
d *simDevice
}
func (p *simPeripheral) Device() Device {
return p.d
}
func (p *simPeripheral) ID() string {
return "Sim ID"
}
func (p *simPeripheral) Name() string {
return "Sim"
}
func (p *simPeripheral) Services() []*Service {
return []*Service{p.d.s}
}
func (p *simPeripheral) DiscoverServices(ss []UUID) ([]*Service, error) {
for _, s := range ss {
if s.Equal(p.d.s.UUID()) {
return []*Service{p.d.s}, nil
}
}
return []*Service{}, nil
}
func (p *simPeripheral) DiscoverIncludedServices(ss []UUID, s *Service) ([]*Service, error) {
return nil, errors.New("Method not supported")
}
func (p *simPeripheral) DiscoverCharacteristics(cc []UUID, s *Service) ([]*Characteristic, error) {
requestedUUIDs := make(map[string]bool)
for _, c := range cc {
requestedUUIDs[c.String()] = true
}
foundChars := make([]*Characteristic, 0)
for _, c := range p.d.s.Characteristics() {
if _, present := requestedUUIDs[c.UUID().String()]; present {
foundChars = append(foundChars, c)
}
}
return foundChars, nil
}
func (p *simPeripheral) DiscoverDescriptors(d []UUID, c *Characteristic) ([]*Descriptor, error) {
return nil, errors.New("Method not supported")
}
func (p *simPeripheral) ReadCharacteristic(c *Characteristic) ([]byte, error) {
rhandler := c.GetReadHandler()
if rhandler != nil {
rsp := newResponseWriter(DefaultMTU)
req := &ReadRequest{}
rhandler.ServeRead(rsp, req)
return rsp.buf.Bytes(), nil
} else {
return nil, AttEcodeReadNotPerm
}
}
func (p *simPeripheral) ReadLongCharacteristic(c *Characteristic) ([]byte, error) {
return p.ReadCharacteristic(c)
}
func (p *simPeripheral) ReadDescriptor(d *Descriptor) ([]byte, error) {
return nil, errors.New("Method not supported")
}
func (p *simPeripheral) WriteCharacteristic(c *Characteristic, b []byte, noRsp bool) error {
whandler := c.GetWriteHandler()
if whandler != nil {
r := Request{}
if res := whandler.ServeWrite(r, b); res != 0 {
return AttEcode(res)
} else {
return nil
}
} else {
return AttEcodeWriteNotPerm
}
}
func (p *simPeripheral) WriteDescriptor(d *Descriptor, b []byte) error {
return errors.New("Method not supported")
}
func (p *simPeripheral) SetNotifyValue(c *Characteristic, f func(*Characteristic, []byte, error)) error {
return errors.New("Method not supported")
}
func (p *simPeripheral) SetIndicateValue(c *Characteristic, f func(*Characteristic, []byte, error)) error {
return errors.New("Method not supported")
}
func (p *simPeripheral) ReadRSSI() int {
return 0
}
func (p *simPeripheral) SetMTU(mtu uint16) error {
return errors.New("Method not supported")
}

View file

@ -1,105 +0,0 @@
package gatt
import (
"bytes"
"encoding/binary"
"encoding/hex"
"fmt"
"strings"
)
// A UUID is a BLE UUID.
type UUID struct {
// Hide the bytes, so that we can enforce that they have length 2 or 16,
// and that they are immutable. This simplifies the code and API.
b []byte
}
// UUID16 converts a uint16 (such as 0x1800) to a UUID.
func UUID16(i uint16) UUID {
b := make([]byte, 2)
binary.LittleEndian.PutUint16(b, i)
return UUID{b}
}
// ParseUUID parses a standard-format UUID string, such
// as "1800" or "34DA3AD1-7110-41A1-B1EF-4430F509CDE7".
func ParseUUID(s string) (UUID, error) {
s = strings.Replace(s, "-", "", -1)
b, err := hex.DecodeString(s)
if err != nil {
return UUID{}, err
}
if err := lenErr(len(b)); err != nil {
return UUID{}, err
}
return UUID{reverse(b)}, nil
}
// MustParseUUID parses a standard-format UUID string,
// like ParseUUID, but panics in case of error.
func MustParseUUID(s string) UUID {
u, err := ParseUUID(s)
if err != nil {
panic(err)
}
return u
}
// lenErr returns an error if n is an invalid UUID length.
func lenErr(n int) error {
switch n {
case 2, 16:
return nil
}
return fmt.Errorf("UUIDs must have length 2 or 16, got %d", n)
}
// Len returns the length of the UUID, in bytes.
// BLE UUIDs are either 2 or 16 bytes.
func (u UUID) Len() int {
return len(u.b)
}
// String hex-encodes a UUID.
func (u UUID) String() string {
return fmt.Sprintf("%x", reverse(u.b))
}
func (u UUID) Bytes() []byte {
return u.b
}
// Equal returns a boolean reporting whether v represent the same UUID as u.
func (u UUID) Equal(v UUID) bool {
return bytes.Equal(u.b, v.b)
}
// UUIDContains returns a boolean reporting whether u is in the slice s.
func UUIDContains(s []UUID, u UUID) bool {
if s == nil {
return true
}
for _, a := range s {
if a.Equal(u) {
return true
}
}
return false
}
// reverse returns a reversed copy of u.
func reverse(u []byte) []byte {
// Special-case 16 bit UUIDS for speed.
l := len(u)
if l == 2 {
return []byte{u[1], u[0]}
}
b := make([]byte, l)
for i := 0; i < l/2+1; i++ {
b[i], b[l-i-1] = u[l-i-1], u[i]
}
return b
}

View file

@ -1,21 +0,0 @@
The MIT License (MIT)
Copyright (c) {{{year}}} {{{fullname}}}
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -1,8 +0,0 @@
// Package xpc provides minimal OS X XPC support required for gatt
//
// This is adapted from [goble], by Raffaele Sena.
//
// http://godoc.org/github.com/raff/goble
// https://github.com/raff/goble
package xpc

View file

@ -1,371 +0,0 @@
package xpc
/*
#include "xpc_wrapper_darwin.h"
#include "sys/utsname.h"
*/
import "C"
import (
"errors"
"fmt"
"log"
r "reflect"
"unsafe"
)
type XPC struct {
conn C.xpc_connection_t
}
func (x *XPC) Send(msg interface{}, verbose bool) {
// verbose == true converts the type from bool to C._Bool
C.XpcSendMessage(x.conn, goToXpc(msg), true, verbose == true)
}
//
// minimal XPC support required for BLE
//
// a dictionary of things
type Dict map[string]interface{}
func (d Dict) Contains(k string) bool {
_, ok := d[k]
return ok
}
func (d Dict) MustGetDict(k string) Dict {
return d[k].(Dict)
}
func (d Dict) MustGetArray(k string) Array {
return d[k].(Array)
}
func (d Dict) MustGetBytes(k string) []byte {
switch t := d[k].(type) {
case string:
return []byte(d[k].(string))
case []byte:
return d[k].([]byte)
default:
panic(fmt.Sprintf("unknown type %v", t))
}
}
func (d Dict) MustGetHexBytes(k string) string {
return fmt.Sprintf("%x", d[k].([]byte))
}
func (d Dict) MustGetInt(k string) int {
return int(d[k].(int64))
}
func (d Dict) MustGetUUID(k string) []byte {
u := d[k].(UUID)
return u[:]
}
func (d Dict) GetString(k, defv string) string {
if v := d[k]; v != nil {
//log.Printf("GetString %s %#v\n", k, v)
return v.(string)
} else {
//log.Printf("GetString %s default %#v\n", k, defv)
return defv
}
}
func (d Dict) GetBytes(k string, defv []byte) []byte {
if v := d[k]; v != nil {
//log.Printf("GetBytes %s %#v\n", k, v)
return v.([]byte)
} else {
//log.Printf("GetBytes %s default %#v\n", k, defv)
return defv
}
}
func (d Dict) GetInt(k string, defv int) int {
if v := d[k]; v != nil {
//log.Printf("GetString %s %#v\n", k, v)
return int(v.(int64))
} else {
//log.Printf("GetString %s default %#v\n", k, defv)
return defv
}
}
func (d Dict) GetUUID(k string) UUID {
return GetUUID(d[k])
}
// an array of things
type Array []interface{}
func (a Array) GetUUID(k int) UUID {
return GetUUID(a[k])
}
// a UUID
type UUID []byte
func MakeUUID(s string) UUID {
var sl []byte
fmt.Sscanf(s, "%32x", &sl)
var uuid [16]byte
copy(uuid[:], sl)
return UUID(uuid[:])
}
func (uuid UUID) String() string {
return fmt.Sprintf("%x", []byte(uuid))
}
func GetUUID(v interface{}) UUID {
if v == nil {
return UUID{}
}
if uuid, ok := v.(UUID); ok {
return uuid
}
if bytes, ok := v.([]byte); ok {
uuid := UUID{}
for i, b := range bytes {
uuid[i] = b
}
return uuid
}
if bytes, ok := v.([]uint8); ok {
uuid := UUID{}
for i, b := range bytes {
uuid[i] = b
}
return uuid
}
log.Fatalf("invalid type for UUID: %#v", v)
return UUID{}
}
var (
CONNECTION_INVALID = errors.New("connection invalid")
CONNECTION_INTERRUPTED = errors.New("connection interrupted")
CONNECTION_TERMINATED = errors.New("connection terminated")
TYPE_OF_UUID = r.TypeOf(UUID{})
TYPE_OF_BYTES = r.TypeOf([]byte{})
handlers = map[uintptr]XpcEventHandler{}
)
type XpcEventHandler interface {
HandleXpcEvent(event Dict, err error)
}
func XpcConnect(service string, eh XpcEventHandler) XPC {
ctx := uintptr(unsafe.Pointer(&eh))
handlers[ctx] = eh
cservice := C.CString(service)
defer C.free(unsafe.Pointer(cservice))
return XPC{conn: C.XpcConnect(cservice, C.uintptr_t(ctx))}
}
//export handleXpcEvent
func handleXpcEvent(event C.xpc_object_t, p C.ulong) {
//log.Printf("handleXpcEvent %#v %#v\n", event, p)
t := C.xpc_get_type(event)
eh := handlers[uintptr(p)]
if eh == nil {
//log.Println("no handler for", p)
return
}
if t == C.TYPE_ERROR {
if event == C.ERROR_CONNECTION_INVALID {
// The client process on the other end of the connection has either
// crashed or cancelled the connection. After receiving this error,
// the connection is in an invalid state, and you do not need to
// call xpc_connection_cancel(). Just tear down any associated state
// here.
//log.Println("connection invalid")
eh.HandleXpcEvent(nil, CONNECTION_INVALID)
} else if event == C.ERROR_CONNECTION_INTERRUPTED {
//log.Println("connection interrupted")
eh.HandleXpcEvent(nil, CONNECTION_INTERRUPTED)
} else if event == C.ERROR_CONNECTION_TERMINATED {
// Handle per-connection termination cleanup.
//log.Println("connection terminated")
eh.HandleXpcEvent(nil, CONNECTION_TERMINATED)
} else {
//log.Println("got some error", event)
eh.HandleXpcEvent(nil, fmt.Errorf("%v", event))
}
} else {
eh.HandleXpcEvent(xpcToGo(event).(Dict), nil)
}
}
// goToXpc converts a go object to an xpc object
func goToXpc(o interface{}) C.xpc_object_t {
return valueToXpc(r.ValueOf(o))
}
// valueToXpc converts a go Value to an xpc object
//
// note that not all the types are supported, but only the subset required for Blued
func valueToXpc(val r.Value) C.xpc_object_t {
if !val.IsValid() {
return nil
}
var xv C.xpc_object_t
switch val.Kind() {
case r.Int, r.Int8, r.Int16, r.Int32, r.Int64:
xv = C.xpc_int64_create(C.int64_t(val.Int()))
case r.Uint, r.Uint8, r.Uint16, r.Uint32:
xv = C.xpc_int64_create(C.int64_t(val.Uint()))
case r.String:
xv = C.xpc_string_create(C.CString(val.String()))
case r.Map:
xv = C.xpc_dictionary_create(nil, nil, 0)
for _, k := range val.MapKeys() {
v := valueToXpc(val.MapIndex(k))
C.xpc_dictionary_set_value(xv, C.CString(k.String()), v)
if v != nil {
C.xpc_release(v)
}
}
case r.Array, r.Slice:
if val.Type() == TYPE_OF_UUID {
// array of bytes
var uuid [16]byte
r.Copy(r.ValueOf(uuid[:]), val)
xv = C.xpc_uuid_create(C.ptr_to_uuid(unsafe.Pointer(&uuid[0])))
} else if val.Type() == TYPE_OF_BYTES {
// slice of bytes
if val.Len() > 0 {
v := val.Interface().([]byte)
xv = C.xpc_data_create(unsafe.Pointer(&v[0]), C.size_t(val.Len()))
} else {
xv = C.xpc_data_create(nil, C.size_t(0))
}
} else {
xv = C.xpc_array_create(nil, 0)
l := val.Len()
for i := 0; i < l; i++ {
v := valueToXpc(val.Index(i))
C.xpc_array_append_value(xv, v)
if v != nil {
C.xpc_release(v)
}
}
}
case r.Interface, r.Ptr:
xv = valueToXpc(val.Elem())
default:
log.Fatalf("unsupported %#v", val.String())
}
return xv
}
//export arraySet
func arraySet(u C.uintptr_t, i C.int, v C.xpc_object_t) {
a := *(*Array)(unsafe.Pointer(uintptr(u)))
a[i] = xpcToGo(v)
}
//export dictSet
func dictSet(u C.uintptr_t, k *C.char, v C.xpc_object_t) {
d := *(*Dict)(unsafe.Pointer(uintptr(u)))
d[C.GoString(k)] = xpcToGo(v)
}
// xpcToGo converts an xpc object to a go object
//
// note that not all the types are supported, but only the subset required for Blued
func xpcToGo(v C.xpc_object_t) interface{} {
t := C.xpc_get_type(v)
switch t {
case C.TYPE_ARRAY:
a := make(Array, C.int(C.xpc_array_get_count(v)))
p := uintptr(unsafe.Pointer(&a))
C.XpcArrayApply(C.uintptr_t(p), v)
return a
case C.TYPE_DATA:
return C.GoBytes(C.xpc_data_get_bytes_ptr(v), C.int(C.xpc_data_get_length(v)))
case C.TYPE_DICT:
d := make(Dict)
p := uintptr(unsafe.Pointer(&d))
C.XpcDictApply(C.uintptr_t(p), v)
return d
case C.TYPE_INT64:
return int64(C.xpc_int64_get_value(v))
case C.TYPE_STRING:
return C.GoString(C.xpc_string_get_string_ptr(v))
case C.TYPE_UUID:
a := [16]byte{}
C.XpcUUIDGetBytes(unsafe.Pointer(&a), v)
return UUID(a[:])
default:
log.Fatalf("unexpected type %#v, value %#v", t, v)
}
return nil
}
// xpc_release is needed by tests, since they can't use CGO
func xpc_release(xv C.xpc_object_t) {
C.xpc_release(xv)
}
// this is used to check the OS version
type Utsname struct {
Sysname string
Nodename string
Release string
Version string
Machine string
}
func Uname(utsname *Utsname) error {
var cstruct C.struct_utsname
if err := C.uname(&cstruct); err != 0 {
return errors.New("utsname error")
}
// XXX: this may crash if any value is exactly 256 characters (no 0 terminator)
utsname.Sysname = C.GoString(&cstruct.sysname[0])
utsname.Nodename = C.GoString(&cstruct.nodename[0])
utsname.Release = C.GoString(&cstruct.release[0])
utsname.Version = C.GoString(&cstruct.version[0])
utsname.Machine = C.GoString(&cstruct.machine[0])
return nil
}

View file

@ -1,85 +0,0 @@
#include <dispatch/dispatch.h>
#include <xpc/xpc.h>
#include <xpc/connection.h>
#include <Block.h>
#include <stdlib.h>
#include <stdio.h>
#include "_cgo_export.h"
//
// types and errors are implemented as macros
// create some real objects to make them accessible to Go
//
xpc_type_t TYPE_ERROR = XPC_TYPE_ERROR;
xpc_type_t TYPE_ARRAY = XPC_TYPE_ARRAY;
xpc_type_t TYPE_DATA = XPC_TYPE_DATA;
xpc_type_t TYPE_DICT = XPC_TYPE_DICTIONARY;
xpc_type_t TYPE_INT64 = XPC_TYPE_INT64;
xpc_type_t TYPE_STRING = XPC_TYPE_STRING;
xpc_type_t TYPE_UUID = XPC_TYPE_UUID;
xpc_object_t ERROR_CONNECTION_INVALID = (xpc_object_t) XPC_ERROR_CONNECTION_INVALID;
xpc_object_t ERROR_CONNECTION_INTERRUPTED = (xpc_object_t) XPC_ERROR_CONNECTION_INTERRUPTED;
xpc_object_t ERROR_CONNECTION_TERMINATED = (xpc_object_t) XPC_ERROR_TERMINATION_IMMINENT;
const ptr_to_uuid_t ptr_to_uuid(void *p) { return (ptr_to_uuid_t)p; }
//
// connect to XPC service
//
xpc_connection_t XpcConnect(char *service, uintptr_t ctx) {
dispatch_queue_t queue = dispatch_queue_create(service, 0);
xpc_connection_t conn = xpc_connection_create_mach_service(service, queue, XPC_CONNECTION_MACH_SERVICE_PRIVILEGED);
// making a local copy, that should be made "persistent" with the following Block_copy
// GoInterface ictx = *((GoInterface*)ctx);
xpc_connection_set_event_handler(conn,
Block_copy(^(xpc_object_t event) {
handleXpcEvent(event, ctx);
})
);
xpc_connection_resume(conn);
return conn;
}
void XpcSendMessage(xpc_connection_t conn, xpc_object_t message, bool release, bool reportDelivery) {
xpc_connection_send_message(conn, message);
xpc_connection_send_barrier(conn, ^{
// Block is invoked on connection's target queue
// when 'message' has been sent.
if (reportDelivery) { // maybe this could be a callback
puts("message delivered");
}
});
if (release) {
xpc_release(message);
}
}
void XpcArrayApply(uintptr_t v, xpc_object_t arr) {
xpc_array_apply(arr, ^bool(size_t index, xpc_object_t value) {
arraySet(v, index, value);
return true;
});
}
void XpcDictApply(uintptr_t v, xpc_object_t dict) {
xpc_dictionary_apply(dict, ^bool(const char *key, xpc_object_t value) {
dictSet(v, (char *)key, value);
return true;
});
}
void XpcUUIDGetBytes(void *v, xpc_object_t uuid) {
const uint8_t *src = xpc_uuid_get_bytes(uuid);
uint8_t *dest = (uint8_t *)v;
for (int i=0; i < sizeof(uuid_t); i++) {
dest[i] = src[i];
}
}

View file

@ -1,32 +0,0 @@
#ifndef _XPC_WRAPPER_H_
#define _XPC_WRAPPER_H_
#include <stdlib.h>
#include <stdio.h>
#include <xpc/xpc.h>
extern xpc_type_t TYPE_ERROR;
extern xpc_type_t TYPE_ARRAY;
extern xpc_type_t TYPE_DATA;
extern xpc_type_t TYPE_DICT;
extern xpc_type_t TYPE_INT64;
extern xpc_type_t TYPE_STRING;
extern xpc_type_t TYPE_UUID;
extern xpc_object_t ERROR_CONNECTION_INVALID;
extern xpc_object_t ERROR_CONNECTION_INTERRUPTED;
extern xpc_object_t ERROR_CONNECTION_TERMINATED;
extern xpc_connection_t XpcConnect(char *, uintptr_t);
extern void XpcSendMessage(xpc_connection_t, xpc_object_t, bool, bool);
extern void XpcArrayApply(uintptr_t, xpc_object_t);
extern void XpcDictApply(uintptr_t, xpc_object_t);
extern void XpcUUIDGetBytes(void *, xpc_object_t);
// the input type for xpc_uuid_create should be uuid_t but CGO instists on unsigned char *
// typedef uuid_t * ptr_to_uuid_t;
typedef unsigned char * ptr_to_uuid_t;
extern const ptr_to_uuid_t ptr_to_uuid(void *p);
#endif

View file

@ -1,2 +0,0 @@
sniffer
scanner

View file

@ -1,596 +0,0 @@
GNU GENERAL PUBLIC LICENSE
==========================
Version 3, 29 June 2007
Copyright &copy; 2007 Free Software Foundation, Inc. &lt;<https://www.fsf.org/>&gt;
Everyone is permitted to copy and distribute verbatim copies of this license
document, but changing it is not allowed.
## Preamble
The GNU General Public License is a free, copyleft license for software and other
kinds of works.
The licenses for most software and other practical works are designed to take away
your freedom to share and change the works. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change all versions of a
program--to make sure it remains free software for all its users. We, the Free
Software Foundation, use the GNU General Public License for most of our software; it
applies also to any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not price. Our General
Public Licenses are designed to make sure that you have the freedom to distribute
copies of free software (and charge for them if you wish), that you receive source
code or can get it if you want it, that you can change the software or use pieces of
it in new free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you these rights or
asking you to surrender the rights. Therefore, you have certain responsibilities if
you distribute copies of the software, or if you modify it: responsibilities to
respect the freedom of others.
For example, if you distribute copies of such a program, whether gratis or for a fee,
you must pass on to the recipients the same freedoms that you received. You must make
sure that they, too, receive or can get the source code. And you must show them these
terms so they know their rights.
Developers that use the GNU GPL protect your rights with two steps: (1) assert
copyright on the software, and (2) offer you this License giving you legal permission
to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains that there is
no warranty for this free software. For both users' and authors' sake, the GPL
requires that modified versions be marked as changed, so that their problems will not
be attributed erroneously to authors of previous versions.
Some devices are designed to deny users access to install or run modified versions of
the software inside them, although the manufacturer can do so. This is fundamentally
incompatible with the aim of protecting users' freedom to change the software. The
systematic pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we have designed
this version of the GPL to prohibit the practice for those products. If such problems
arise substantially in other domains, we stand ready to extend this provision to
those domains in future versions of the GPL, as needed to protect the freedom of
users.
Finally, every program is threatened constantly by software patents. States should
not allow patents to restrict development and use of software on general-purpose
computers, but in those that do, we wish to avoid the special danger that patents
applied to a free program could make it effectively proprietary. To prevent this, the
GPL assures that patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and modification follow.
## TERMS AND CONDITIONS
### 0. Definitions.
&ldquo;This License&rdquo; refers to version 3 of the GNU General Public License.
&ldquo;Copyright&rdquo; also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
&ldquo;The Program&rdquo; refers to any copyrightable work licensed under this
License. Each licensee is addressed as &ldquo;you&rdquo;. &ldquo;Licensees&rdquo; and
&ldquo;recipients&rdquo; may be individuals or organizations.
To &ldquo;modify&rdquo; a work means to copy from or adapt all or part of the work in
a fashion requiring copyright permission, other than the making of an exact copy. The
resulting work is called a &ldquo;modified version&rdquo; of the earlier work or a
work &ldquo;based on&rdquo; the earlier work.
A &ldquo;covered work&rdquo; means either the unmodified Program or a work based on
the Program.
To &ldquo;propagate&rdquo; a work means to do anything with it that, without
permission, would make you directly or secondarily liable for infringement under
applicable copyright law, except executing it on a computer or modifying a private
copy. Propagation includes copying, distribution (with or without modification),
making available to the public, and in some countries other activities as well.
To &ldquo;convey&rdquo; a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through a computer
network, with no transfer of a copy, is not conveying.
An interactive user interface displays &ldquo;Appropriate Legal Notices&rdquo; to the
extent that it includes a convenient and prominently visible feature that (1)
displays an appropriate copyright notice, and (2) tells the user that there is no
warranty for the work (except to the extent that warranties are provided), that
licensees may convey the work under this License, and how to view a copy of this
License. If the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
### 1. Source Code.
The &ldquo;source code&rdquo; for a work means the preferred form of the work for
making modifications to it. &ldquo;Object code&rdquo; means any non-source form of a
work.
A &ldquo;Standard Interface&rdquo; means an interface that either is an official
standard defined by a recognized standards body, or, in the case of interfaces
specified for a particular programming language, one that is widely used among
developers working in that language.
The &ldquo;System Libraries&rdquo; of an executable work include anything, other than
the work as a whole, that (a) is included in the normal form of packaging a Major
Component, but which is not part of that Major Component, and (b) serves only to
enable use of the work with that Major Component, or to implement a Standard
Interface for which an implementation is available to the public in source code form.
A &ldquo;Major Component&rdquo;, in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system (if any) on which
the executable work runs, or a compiler used to produce the work, or an object code
interpreter used to run it.
The &ldquo;Corresponding Source&rdquo; for a work in object code form means all the
source code needed to generate, install, and (for an executable work) run the object
code and to modify the work, including scripts to control those activities. However,
it does not include the work's System Libraries, or general-purpose tools or
generally available free programs which are used unmodified in performing those
activities but which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for the work, and
the source code for shared libraries and dynamically linked subprograms that the work
is specifically designed to require, such as by intimate data communication or
control flow between those subprograms and other parts of the work.
The Corresponding Source need not include anything that users can regenerate
automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same work.
### 2. Basic Permissions.
All rights granted under this License are granted for the term of copyright on the
Program, and are irrevocable provided the stated conditions are met. This License
explicitly affirms your unlimited permission to run the unmodified Program. The
output from running a covered work is covered by this License only if the output,
given its content, constitutes a covered work. This License acknowledges your rights
of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey, without
conditions so long as your license otherwise remains in force. You may convey covered
works to others for the sole purpose of having them make modifications exclusively
for you, or provide you with facilities for running those works, provided that you
comply with the terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for you must do so
exclusively on your behalf, under your direction and control, on terms that prohibit
them from making any copies of your copyrighted material outside their relationship
with you.
Conveying under any other circumstances is permitted solely under the conditions
stated below. Sublicensing is not allowed; section 10 makes it unnecessary.
### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological measure under any
applicable law fulfilling obligations under article 11 of the WIPO copyright treaty
adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention
of such measures.
When you convey a covered work, you waive any legal power to forbid circumvention of
technological measures to the extent such circumvention is effected by exercising
rights under this License with respect to the covered work, and you disclaim any
intention to limit operation or modification of the work as a means of enforcing,
against the work's users, your or third parties' legal rights to forbid circumvention
of technological measures.
### 4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you receive it, in any
medium, provided that you conspicuously and appropriately publish on each copy an
appropriate copyright notice; keep intact all notices stating that this License and
any non-permissive terms added in accord with section 7 apply to the code; keep
intact all notices of the absence of any warranty; and give all recipients a copy of
this License along with the Program.
You may charge any price or no price for each copy that you convey, and you may offer
support or warranty protection for a fee.
### 5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to produce it from
the Program, in the form of source code under the terms of section 4, provided that
you also meet all of these conditions:
* **a)** The work must carry prominent notices stating that you modified it, and giving a
relevant date.
* **b)** The work must carry prominent notices stating that it is released under this
License and any conditions added under section 7. This requirement modifies the
requirement in section 4 to &ldquo;keep intact all notices&rdquo;.
* **c)** You must license the entire work, as a whole, under this License to anyone who
comes into possession of a copy. This License will therefore apply, along with any
applicable section 7 additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no permission to license the
work in any other way, but it does not invalidate such permission if you have
separately received it.
* **d)** If the work has interactive user interfaces, each must display Appropriate Legal
Notices; however, if the Program has interactive interfaces that do not display
Appropriate Legal Notices, your work need not make them do so.
A compilation of a covered work with other separate and independent works, which are
not by their nature extensions of the covered work, and which are not combined with
it such as to form a larger program, in or on a volume of a storage or distribution
medium, is called an &ldquo;aggregate&rdquo; if the compilation and its resulting
copyright are not used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work in an aggregate
does not cause this License to apply to the other parts of the aggregate.
### 6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of sections 4 and
5, provided that you also convey the machine-readable Corresponding Source under the
terms of this License, in one of these ways:
* **a)** Convey the object code in, or embodied in, a physical product (including a
physical distribution medium), accompanied by the Corresponding Source fixed on a
durable physical medium customarily used for software interchange.
* **b)** Convey the object code in, or embodied in, a physical product (including a
physical distribution medium), accompanied by a written offer, valid for at least
three years and valid for as long as you offer spare parts or customer support for
that product model, to give anyone who possesses the object code either (1) a copy of
the Corresponding Source for all the software in the product that is covered by this
License, on a durable physical medium customarily used for software interchange, for
a price no more than your reasonable cost of physically performing this conveying of
source, or (2) access to copy the Corresponding Source from a network server at no
charge.
* **c)** Convey individual copies of the object code with a copy of the written offer to
provide the Corresponding Source. This alternative is allowed only occasionally and
noncommercially, and only if you received the object code with such an offer, in
accord with subsection 6b.
* **d)** Convey the object code by offering access from a designated place (gratis or for
a charge), and offer equivalent access to the Corresponding Source in the same way
through the same place at no further charge. You need not require recipients to copy
the Corresponding Source along with the object code. If the place to copy the object
code is a network server, the Corresponding Source may be on a different server
(operated by you or a third party) that supports equivalent copying facilities,
provided you maintain clear directions next to the object code saying where to find
the Corresponding Source. Regardless of what server hosts the Corresponding Source,
you remain obligated to ensure that it is available for as long as needed to satisfy
these requirements.
* **e)** Convey the object code using peer-to-peer transmission, provided you inform
other peers where the object code and Corresponding Source of the work are being
offered to the general public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded from the
Corresponding Source as a System Library, need not be included in conveying the
object code work.
A &ldquo;User Product&rdquo; is either (1) a &ldquo;consumer product&rdquo;, which
means any tangible personal property which is normally used for personal, family, or
household purposes, or (2) anything designed or sold for incorporation into a
dwelling. In determining whether a product is a consumer product, doubtful cases
shall be resolved in favor of coverage. For a particular product received by a
particular user, &ldquo;normally used&rdquo; refers to a typical or common use of
that class of product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected to use, the
product. A product is a consumer product regardless of whether the product has
substantial commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
&ldquo;Installation Information&rdquo; for a User Product means any methods,
procedures, authorization keys, or other information required to install and execute
modified versions of a covered work in that User Product from a modified version of
its Corresponding Source. The information must suffice to ensure that the continued
functioning of the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or specifically for
use in, a User Product, and the conveying occurs as part of a transaction in which
the right of possession and use of the User Product is transferred to the recipient
in perpetuity or for a fixed term (regardless of how the transaction is
characterized), the Corresponding Source conveyed under this section must be
accompanied by the Installation Information. But this requirement does not apply if
neither you nor any third party retains the ability to install modified object code
on the User Product (for example, the work has been installed in ROM).
The requirement to provide Installation Information does not include a requirement to
continue to provide support service, warranty, or updates for a work that has been
modified or installed by the recipient, or for the User Product in which it has been
modified or installed. Access to a network may be denied when the modification itself
materially and adversely affects the operation of the network or violates the rules
and protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided, in accord with
this section must be in a format that is publicly documented (and with an
implementation available to the public in source code form), and must require no
special password or key for unpacking, reading or copying.
### 7. Additional Terms.
&ldquo;Additional permissions&rdquo; are terms that supplement the terms of this
License by making exceptions from one or more of its conditions. Additional
permissions that are applicable to the entire Program shall be treated as though they
were included in this License, to the extent that they are valid under applicable
law. If additional permissions apply only to part of the Program, that part may be
used separately under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option remove any
additional permissions from that copy, or from any part of it. (Additional
permissions may be written to require their own removal in certain cases when you
modify the work.) You may place additional permissions on material, added by you to a
covered work, for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you add to a
covered work, you may (if authorized by the copyright holders of that material)
supplement the terms of this License with terms:
* **a)** Disclaiming warranty or limiting liability differently from the terms of
sections 15 and 16 of this License; or
* **b)** Requiring preservation of specified reasonable legal notices or author
attributions in that material or in the Appropriate Legal Notices displayed by works
containing it; or
* **c)** Prohibiting misrepresentation of the origin of that material, or requiring that
modified versions of such material be marked in reasonable ways as different from the
original version; or
* **d)** Limiting the use for publicity purposes of names of licensors or authors of the
material; or
* **e)** Declining to grant rights under trademark law for use of some trade names,
trademarks, or service marks; or
* **f)** Requiring indemnification of licensors and authors of that material by anyone
who conveys the material (or modified versions of it) with contractual assumptions of
liability to the recipient, for any liability that these contractual assumptions
directly impose on those licensors and authors.
All other non-permissive additional terms are considered &ldquo;further
restrictions&rdquo; within the meaning of section 10. If the Program as you received
it, or any part of it, contains a notice stating that it is governed by this License
along with a term that is a further restriction, you may remove that term. If a
license document contains a further restriction but permits relicensing or conveying
under this License, you may add to a covered work material governed by the terms of
that license document, provided that the further restriction does not survive such
relicensing or conveying.
If you add terms to a covered work in accord with this section, you must place, in
the relevant source files, a statement of the additional terms that apply to those
files, or a notice indicating where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the form of a
separately written license, or stated as exceptions; the above requirements apply
either way.
### 8. Termination.
You may not propagate or modify a covered work except as expressly provided under
this License. Any attempt otherwise to propagate or modify it is void, and will
automatically terminate your rights under this License (including any patent licenses
granted under the third paragraph of section 11).
However, if you cease all violation of this License, then your license from a
particular copyright holder is reinstated (a) provisionally, unless and until the
copyright holder explicitly and finally terminates your license, and (b) permanently,
if the copyright holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is reinstated permanently
if the copyright holder notifies you of the violation by some reasonable means, this
is the first time you have received notice of violation of this License (for any
work) from that copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the licenses of
parties who have received copies or rights from you under this License. If your
rights have been terminated and not permanently reinstated, you do not qualify to
receive new licenses for the same material under section 10.
### 9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run a copy of the
Program. Ancillary propagation of a covered work occurring solely as a consequence of
using peer-to-peer transmission to receive a copy likewise does not require
acceptance. However, nothing other than this License grants you permission to
propagate or modify any covered work. These actions infringe copyright if you do not
accept this License. Therefore, by modifying or propagating a covered work, you
indicate your acceptance of this License to do so.
### 10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically receives a license
from the original licensors, to run, modify and propagate that work, subject to this
License. You are not responsible for enforcing compliance by third parties with this
License.
An &ldquo;entity transaction&rdquo; is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an organization, or
merging organizations. If propagation of a covered work results from an entity
transaction, each party to that transaction who receives a copy of the work also
receives whatever licenses to the work the party's predecessor in interest had or
could give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if the predecessor
has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the rights granted or
affirmed under this License. For example, you may not impose a license fee, royalty,
or other charge for exercise of rights granted under this License, and you may not
initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging
that any patent claim is infringed by making, using, selling, offering for sale, or
importing the Program or any portion of it.
### 11. Patents.
A &ldquo;contributor&rdquo; is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The work thus
licensed is called the contributor's &ldquo;contributor version&rdquo;.
A contributor's &ldquo;essential patent claims&rdquo; are all patent claims owned or
controlled by the contributor, whether already acquired or hereafter acquired, that
would be infringed by some manner, permitted by this License, of making, using, or
selling its contributor version, but do not include claims that would be infringed
only as a consequence of further modification of the contributor version. For
purposes of this definition, &ldquo;control&rdquo; includes the right to grant patent
sublicenses in a manner consistent with the requirements of this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free patent license
under the contributor's essential patent claims, to make, use, sell, offer for sale,
import and otherwise run, modify and propagate the contents of its contributor
version.
In the following three paragraphs, a &ldquo;patent license&rdquo; is any express
agreement or commitment, however denominated, not to enforce a patent (such as an
express permission to practice a patent or covenant not to sue for patent
infringement). To &ldquo;grant&rdquo; such a patent license to a party means to make
such an agreement or commitment not to enforce a patent against the party.
If you convey a covered work, knowingly relying on a patent license, and the
Corresponding Source of the work is not available for anyone to copy, free of charge
and under the terms of this License, through a publicly available network server or
other readily accessible means, then you must either (1) cause the Corresponding
Source to be so available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner consistent with
the requirements of this License, to extend the patent license to downstream
recipients. &ldquo;Knowingly relying&rdquo; means you have actual knowledge that, but
for the patent license, your conveying the covered work in a country, or your
recipient's use of the covered work in a country, would infringe one or more
identifiable patents in that country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or arrangement, you
convey, or propagate by procuring conveyance of, a covered work, and grant a patent
license to some of the parties receiving the covered work authorizing them to use,
propagate, modify or convey a specific copy of the covered work, then the patent
license you grant is automatically extended to all recipients of the covered work and
works based on it.
A patent license is &ldquo;discriminatory&rdquo; if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on the
non-exercise of one or more of the rights that are specifically granted under this
License. You may not convey a covered work if you are a party to an arrangement with
a third party that is in the business of distributing software, under which you make
payment to the third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties who would receive
the covered work from you, a discriminatory patent license (a) in connection with
copies of the covered work conveyed by you (or copies made from those copies), or (b)
primarily for and in connection with specific products or compilations that contain
the covered work, unless you entered into that arrangement, or that patent license
was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting any implied
license or other defenses to infringement that may otherwise be available to you
under applicable patent law.
### 12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or otherwise)
that contradict the conditions of this License, they do not excuse you from the
conditions of this License. If you cannot convey a covered work so as to satisfy
simultaneously your obligations under this License and any other pertinent
obligations, then as a consequence you may not convey it at all. For example, if you
agree to terms that obligate you to collect a royalty for further conveying from
those to whom you convey the Program, the only way you could satisfy both those terms
and this License would be to refrain entirely from conveying the Program.
### 13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have permission to link or
combine any covered work with a work licensed under version 3 of the GNU Affero
General Public License into a single combined work, and to convey the resulting work.
The terms of this License will continue to apply to the part which is the covered
work, but the special requirements of the GNU Affero General Public License, section
13, concerning interaction through a network will apply to the combination as such.
### 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of the GNU
General Public License from time to time. Such new versions will be similar in spirit
to the present version, but may differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program specifies that
a certain numbered version of the GNU General Public License &ldquo;or any later
version&rdquo; applies to it, you have the option of following the terms and
conditions either of that numbered version or of any later version published by the
Free Software Foundation. If the Program does not specify a version number of the GNU
General Public License, you may choose any version ever published by the Free
Software Foundation.
If the Program specifies that a proxy can decide which future versions of the GNU
General Public License can be used, that proxy's public statement of acceptance of a
version permanently authorizes you to choose that version for the Program.
Later license versions may give you additional or different permissions. However, no
additional obligations are imposed on any author or copyright holder as a result of
your choosing to follow a later version.
### 15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM &ldquo;AS IS&rdquo; WITHOUT WARRANTY OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE
QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
### 16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY
COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS
PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL,
INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE
OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE
WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
### 17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided above cannot be
given local legal effect according to their terms, reviewing courts shall apply local
law that most closely approximates an absolute waiver of all civil liability in
connection with the Program, unless a warranty or assumption of liability accompanies
a copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
## How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest possible use to
the public, the best way to achieve this is to make it free software which everyone
can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest to attach them
to the start of each source file to most effectively state the exclusion of warranty;
and each file should have at least the &ldquo;copyright&rdquo; line and a pointer to
where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short notice like this
when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type 'show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type 'show c' for details.
The hypothetical commands 'show w' and 'show c' should show the appropriate parts of
the General Public License. Of course, your program's commands might be different;
for a GUI interface, you would use an &ldquo;about box&rdquo;.
You should also get your employer (if you work as a programmer) or school, if any, to
sign a &ldquo;copyright disclaimer&rdquo; for the program, if necessary. For more
information on this, and how to apply and follow the GNU GPL, see
&lt;<https://www.gnu.org/licenses/>&gt;.
The GNU General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may consider it
more useful to permit linking proprietary applications with the library. If this is
what you want to do, use the GNU Lesser General Public License instead of this
License. But first, please read
&lt;<https://www.gnu.org/philosophy/why-not-lgpl.html>&gt;.

View file

@ -1,16 +0,0 @@
# NRF24
This package allows interaction with nRF24LU1+ based dongles and the [RFStorm firmware](https://github.com/BastilleResearch/nrf-research-firmware).
## Dependencies
sudo apt-get install libusb-1.0
go get -v github.com/google/gousb
## Example
See the `examples` folder.
## License
This package is made with ♥ by [evilsocket](https://github.com/evilsocket) and it's released under the GPL 3 license.

View file

@ -1,42 +0,0 @@
package nrf24
import (
"github.com/google/gousb"
)
const (
VendorID gousb.ID = 0x1915
ProductID gousb.ID = 0x0102
)
const (
PacketSize = 64
MinChannel = 1
TopChannel = 83
MaxChannel = 125
)
type Command byte
// USB commands
const (
CmdTransmitPayload Command = 0x04
CmdEnterSnifferMode Command = 0x05
CmdEnterPromiscMode Command = 0x06
CmdEnterToneTestMode Command = 0x07
CmdTransmitAckPayload Command = 0x08
CmdSetChannel Command = 0x09
CmdGetChannel Command = 0x0A
CmdEnableLNAPA Command = 0x0B
CmdTransmitPayloadGeneric Command = 0x0C
CmdEnterPromiscModeGeneric Command = 0x0D
CmdReceivePayload Command = 0x12
)
type RfRate byte
const (
RfRate250K RfRate = 0
RfRate1M RfRate = 1
RfRate2M RfRate = 2
)

View file

@ -1,3 +0,0 @@
// Package nrf24 allows interaction with nRF24LU1+ based dongles and RFStorm firmware.
// Ref. https://github.com/BastilleResearch/nrf-research-firmware
package nrf24

View file

@ -1,224 +0,0 @@
package nrf24
import (
"fmt"
"github.com/google/gousb"
)
type Dongle struct {
ctx *gousb.Context
dev *gousb.Device
iface *gousb.Interface
ifaceDoneFunc func()
writer *gousb.OutEndpoint
reader *gousb.InEndpoint
}
func Open() (dongle *Dongle, err error) {
dongle = &Dongle{ctx: gousb.NewContext()}
if dongle.dev, err = dongle.ctx.OpenDeviceWithVIDPID(VendorID, ProductID); dongle.dev == nil {
err = fmt.Errorf("usb device %s:%s not found", VendorID, ProductID)
}
if err != nil {
dongle.Close()
return nil, err
}
if dongle.iface, dongle.ifaceDoneFunc, err = dongle.dev.DefaultInterface(); err != nil {
dongle.Close()
return nil, err
} else if dongle.writer, err = dongle.iface.OutEndpoint(1); err != nil {
dongle.Close()
return nil, err
} else if dongle.reader, err = dongle.iface.InEndpoint(0x81); err != nil {
dongle.Close()
return nil, err
}
return dongle, nil
}
func (d *Dongle) String() string {
return d.iface.String()
}
func (d *Dongle) Command(cmd Command, data []byte) (int, error) {
return d.writer.Write(append([]byte{byte(cmd)}, data...))
}
func (d *Dongle) Read() (int, []byte, error) {
buf := make([]byte, PacketSize)
read, err := d.reader.Read(buf)
return read, buf, err
}
func (d *Dongle) consumePacket() error {
_, _, err := d.Read()
return err
}
func (d *Dongle) EnterPromiscModeFor(prefix []byte) error {
prData := []byte{0}
if prefix != nil {
prData = append([]byte{byte(len(prefix) & 0xff)}, prefix...)
}
if _, err := d.Command(CmdEnterPromiscMode, prData); err != nil {
return err
}
return d.consumePacket()
}
func (d *Dongle) EnterPromiscMode() error {
return d.EnterPromiscModeFor(nil)
}
func (d *Dongle) EnterPromiscModeGenericFor(prefix []byte, rate RfRate, payloadLength int) error {
prData := []byte{0, byte(rate & 0xff), byte(payloadLength & 0xff)}
if prefix != nil {
prData[0] = byte(len(prefix) & 0xff)
prData = append(prData, prefix...)
}
if _, err := d.Command(CmdEnterPromiscModeGeneric, prData); err != nil {
return err
}
return d.consumePacket()
}
func (d *Dongle) EnterPromiscModeGenericDefaultFor(prefix []byte) error {
return d.EnterPromiscModeGenericFor(prefix, RfRate2M, 32)
}
func (d *Dongle) EnterPromiscModeGeneric() error {
return d.EnterPromiscModeGenericDefaultFor(nil)
}
func (d *Dongle) EnterSnifferModeFor(address []byte) error {
adData := []byte{0}
if address != nil {
adData = append([]byte{byte(len(address) & 0xff)}, address...)
}
if _, err := d.Command(CmdEnterSnifferMode, adData); err != nil {
return err
}
return d.consumePacket()
}
func (d *Dongle) EnterSnifferMode() error {
return d.EnterSnifferModeFor(nil)
}
func (d *Dongle) EnterToneTestMode() error {
if _, err := d.Command(CmdEnterToneTestMode, []byte{}); err != nil {
return err
}
return d.consumePacket()
}
func (d *Dongle) ReceivePayload() ([]byte, error) {
if _, err := d.Command(CmdReceivePayload, []byte{}); err != nil {
return nil, err
} else if read, buf, err := d.Read(); err != nil {
return nil, err
} else {
return buf[:read], nil
}
}
func (d *Dongle) checkResponseCode() error {
if read, buf, err := d.Read(); err != nil {
return err
} else if read < 1 {
return fmt.Errorf("invalid read value %d", read)
} else if buf[0] == 0 {
return fmt.Errorf("unexpected response %x", buf[:read])
}
return nil
}
func (d *Dongle) TransmitPayloadGeneric(payload []byte, address []byte) error {
data := []byte{
byte(len(payload) & 0xff),
byte(len(address) & 0xff),
}
data = append(data, payload...)
data = append(data, address...)
if _, err := d.Command(CmdTransmitPayloadGeneric, data); err != nil {
return err
}
return d.checkResponseCode()
}
func (d *Dongle) TransmitPayload(payload []byte, timeout int, retransmits int) error {
data := []byte{
byte(len(payload) & 0xff),
byte(timeout & 0xff),
byte(retransmits & 0xff),
}
data = append(data, payload...)
if _, err := d.Command(CmdTransmitPayload, data); err != nil {
return err
}
return d.checkResponseCode()
}
func (d *Dongle) TransmitAckPayload(payload []byte) error {
data := append([]byte{byte(len(payload) & 0xff)}, payload...)
if _, err := d.Command(CmdTransmitAckPayload, data); err != nil {
return err
}
return d.checkResponseCode()
}
func (d *Dongle) SetChannel(ch int) error {
if ch > MaxChannel {
ch = MaxChannel
}
if _, err := d.Command(CmdSetChannel, []byte{byte(ch & 0xff)}); err != nil {
return err
}
return d.consumePacket()
}
func (d *Dongle) GetChannel() (int, error) {
if _, err := d.Command(CmdGetChannel, []byte{}); err != nil {
return 0, err
} else if read, buf, err := d.Read(); err != nil {
return 0, err
} else if read < 1 {
return 0, fmt.Errorf("invalid read value %d", read)
} else {
return int(buf[0]), nil
}
}
func (d *Dongle) EnableLNA() error {
if _, err := d.Command(CmdEnableLNAPA, []byte{}); err != nil {
return err
}
return d.consumePacket()
}
func (d *Dongle) Close() {
if d.dev != nil {
d.dev.Close()
d.dev = nil
}
if d.iface != nil {
d.ifaceDoneFunc()
d.iface.Close()
d.iface = nil
}
if d.ctx != nil {
d.ctx.Close()
d.ctx = nil
}
}

View file

@ -1,43 +0,0 @@
package nrf24
import (
"encoding/hex"
"fmt"
"regexp"
"strings"
)
var addrParser = regexp.MustCompile(`(?i)^[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}:[a-f0-9]{2}$`)
func NthChannel(idx int) int {
return idx % TopChannel
}
func LoopChannels(idx *int) int {
ch := NthChannel(*idx)
*idx++
return ch
}
func ConvertAddress(address string) (error, []byte) {
if address == "" {
return fmt.Errorf("no address provided"), nil
} else if addrParser.MatchString(address) == false {
return fmt.Errorf("address '%s' is not in the form XX:XX:XX:XX:XX", address), nil
}
// remove ':', decode as hex and reverse the bytes order
clean := strings.Replace(address, ":", "", -1)
raw, err := hex.DecodeString(clean)
if err != nil {
return err, nil
} else if len(raw) != 5 {
return fmt.Errorf("address must be composed of 5 octets"), nil
}
for i := 5/2 - 1; i >= 0; i-- {
opp := 4 - i
raw[i], raw[opp] = raw[opp], raw[i]
}
return nil, raw
}

View file

@ -1,2 +0,0 @@
*.exe
*.tmp

Some files were not shown because too many files have changed in this diff Show more