Documentation
¶
Overview ¶
Package bthome reads and writes BTHome advertisements: the open Bluetooth LE sensor format that Shelly BLU devices (buttons, door and window, motion, H&T, remote, wall switch, distance) and many DIY sensors send. It decodes version 2 (service UUID 0xFCD2, with or without AES-CCM encryption) and the older version 1 (0x181C, 0x181E), finds the service data in raw advertising data, and builds plain and encrypted version 2 packets for simulators and tests.
It needs no Bluetooth stack: the advertising bytes come from the application's own scanner, or from a Shelly Gen2+ device relaying what it hears (see shelly.ParseBLEScanResult). Standard library only; AES-CCM is implemented here because the standard library has none.
The format is described at https://bthome.io; the object table here was written from that description and checked against bthome-ble 3.24.0. Not affiliated with the BTHome project.
Index ¶
- Constants
- Variables
- func Advertising(serviceData []byte, name string) []byte
- func ButtonEvent(name string) (byte, bool)
- func CommandEvent(name string) (byte, bool)
- func DimmerEvent(name string) (byte, bool)
- func FormatMAC(m [6]byte) string
- func LocalName(ads []AD) string
- func Manufacturer(ads []AD) map[uint16][]byte
- func ParseMAC(s string) ([6]byte, error)
- func ServiceData16(ads []AD) map[uint16][]byte
- type AD
- type Builder
- func (b *Builder) Add(id byte, v float64) *Builder
- func (b *Builder) Button(code byte) *Builder
- func (b *Builder) Command(code byte, args ...byte) *Builder
- func (b *Builder) DeviceType(id uint16) *Builder
- func (b *Builder) Dimmer(code byte, steps uint8) *Builder
- func (b *Builder) Firmware(parts ...byte) *Builder
- func (b *Builder) Raw(p []byte) *Builder
- func (b *Builder) Seal(key []byte, addr string, counter uint32) ([]byte, error)
- func (b *Builder) ServiceData() ([]byte, error)
- func (b *Builder) Text(s string) *Builder
- type Guard
- type Kind
- type Object
- type ObjectInfo
- type Packet
Examples ¶
Constants ¶
const ( UUID uint16 = 0xFCD2 // version 2 UUIDv1 uint16 = 0x181C // version 1, not encrypted UUIDv1Encrypted uint16 = 0x181E // version 1, encrypted )
Service UUIDs (16-bit).
const ( FlagEncrypted = 0x01 // the objects are encrypted FlagMACPresent = 0x02 // the sender's address follows the information byte FlagTrigger = 0x04 // the device sends at irregular times, on events )
Bits of the version 2 device information byte.
const ( ADFlags = 0x01 ADShortName = 0x08 ADCompleteName = 0x09 ADServiceData16 = 0x16 ADManufacturer = 0xFF )
Advertising data types used here.
Variables ¶
var ( // ErrNotBTHome means the advertising data carries no BTHome service // data. ErrNotBTHome = errors.New("bthome: no BTHome service data") // ErrNoKey means the packet is encrypted and no key was given. ErrNoKey = errors.New("bthome: encrypted packet and no key") // ErrTruncated means an object runs past the end of the packet. ErrTruncated = errors.New("bthome: truncated packet") )
var ErrAuth = errors.New("bthome: message integrity check failed")
ErrAuth means an encrypted packet failed its integrity check: a wrong key, a wrong address, or a damaged or forged packet.
Functions ¶
func Advertising ¶
Advertising builds advertising data around version 2 service data: the flags, the service data and, when name is not empty, the complete local name.
func ButtonEvent ¶
ButtonEvent is the code of a button event name ("press", "long_press", ...), for Builder.
func CommandEvent ¶
CommandEvent is the code of a command ("on", "off", "toggle", "step_up", "step_down").
func DimmerEvent ¶
DimmerEvent is the code of "rotate_left" or "rotate_right".
func Manufacturer ¶
Manufacturer collects the manufacturer-specific data of ads by company identifier.
func ParseMAC ¶
ParseMAC reads an address written as "AA:BB:CC:DD:EE:FF", "aa-bb-cc-dd-ee-ff" or "AABBCCDDEEFF".
func ServiceData16 ¶
ServiceData16 collects the 16-bit UUID service data of ads by UUID.
Types ¶
type Builder ¶
type Builder struct {
Trigger bool // set the trigger-based flag
MAC string // when set, carry this address in the payload
// contains filtered or unexported fields
}
Builder builds version 2 service data, for simulators, tests and devices written in Go. Objects are written in object id order, as the format asks, whatever order they are added in (objects with the same id keep their order). The zero value is ready to use.
Example ¶
Building a door sensor's packet with a button press.
package main
import (
"fmt"
"github.com/cB-Sigma/shelly/bthome"
)
func main() {
var b bthome.Builder
b.Trigger = true
press, _ := bthome.ButtonEvent("press")
sd, _ := b.Add(0x01, 90).Add(0x2D, 1).Button(press).ServiceData()
fmt.Printf("%x\n", sd)
}
Output: 44015a2d013a01
func (*Builder) Add ¶
Add writes a Sensor, Binary or Time object: v is the value in the object's unit (for Binary, 0 or 1; for Time, Unix seconds).
func (*Builder) Button ¶
Button writes a button event (ButtonEvent gives the codes; 0 is "no event", which a multi-button device sends for the buttons not pressed).
func (*Builder) DeviceType ¶
DeviceType writes the device type id object (0xF0).
func (*Builder) Firmware ¶
Firmware writes a firmware version object: three parts (0xF2) or four (0xF1), most significant first, such as Firmware(1, 0, 21).
func (*Builder) Seal ¶
Seal returns encrypted service data: the objects encrypted with key (16 bytes) for the sender addr and counter. Use a counter that goes up with every packet; receivers drop repeats.
func (*Builder) ServiceData ¶
ServiceData returns the plain service data (the bytes after the UUID).
type Guard ¶
type Guard struct {
// contains filtered or unexported fields
}
Guard drops encrypted packets whose counter did not go up since the last accepted packet of the same sender, as the format asks receivers to. The zero value is ready to use and safe for concurrent use.
type Kind ¶
type Kind int
Kind says how an object's bytes are read.
const ( // Sensor is a number: an integer of Size bytes, little-endian, times // Factor. Sensor Kind = iota // Binary is an on or off state (one byte, 0 or 1). Binary // Event is a button, dimmer or command event (see Object.Event). Event // Text is a UTF-8 string with a length byte in front. Text // Raw is bytes with a length byte in front. Raw // Time is a Unix time in seconds, four bytes. Time // DeviceInfo is information about the sender (type, firmware), not a // reading. DeviceInfo )
type Object ¶
type Object struct {
ID byte
Info ObjectInfo
Index int // which occurrence of this object id in the packet, from 0
Data []byte // the value's bytes as sent (for a command: opcode then arguments)
Value float64 // Sensor; Binary (0 or 1); Event (its code); Time (Unix seconds); DeviceInfo (type id)
Text string // Text; Raw as lower-case hexadecimal; DeviceInfo firmware as "a.b.c(.d)"
Event string // Event: "press", "long_press", "rotate_left", "on", ...; "" for no event
Steps int // dimmer events: the steps turned
Args []byte // command events: the arguments
Time time.Time // Time
}
Object is one reading or event of a packet.
type ObjectInfo ¶
type ObjectInfo struct {
ID byte
Name string // our own short name, such as "temperature"
Unit string // "" for none
Kind Kind //
Size int // bytes of value; 0 for objects with a length byte
Signed bool // the integer is two's complement
Factor float64 // the integer times Factor is the value (1 when not scaled)
}
ObjectInfo describes one object id of the BTHome v2 format.
func Info ¶
func Info(id byte) (ObjectInfo, bool)
Info describes object id, or reports false for an id this package does not know.
type Packet ¶
type Packet struct {
Version int // 1 or 2
Encrypted bool // it was encrypted (and was decrypted)
Trigger bool // the device sends on events rather than at a regular interval
MAC string // the address carried in the payload (upper case, colons), or ""
Counter uint32 // encrypted packets: the sender's counter
Objects []Object
// Rest holds the bytes from the first object id this package does not
// know; the format asks receivers to stop there, since lengths of
// unknown objects cannot be told.
Rest []byte
}
Packet is one decoded advertisement.
func Decode ¶
Decode reads the service data of one of the BTHome UUIDs (the bytes after the UUID). addr is the sender's Bluetooth address; it is needed only for an encrypted packet that does not carry its address. key is the 16-byte bind key of an encrypted sender, or nil.
Example ¶
The encrypted example of the format's description: the service data, the sender's address and its bind key give temperature and humidity.
package main
import (
"encoding/hex"
"fmt"
"github.com/cB-Sigma/shelly/bthome"
)
func main() {
sd, _ := hex.DecodeString("41e445f3c9962b332211006c7c4519")
key, _ := hex.DecodeString("231d39c1d7cc1ab1aee224cd096db932")
p, err := bthome.Decode(bthome.UUID, sd, "54:48:E6:8F:80:A5", key)
if err != nil {
fmt.Println(err)
return
}
for _, o := range p.Objects {
fmt.Println(o.Info.Name, o.Value, o.Info.Unit)
}
}
Output: temperature 25.06 °C humidity 50.55 %
func DecodeAdvertising ¶
DecodeAdvertising finds BTHome service data in raw advertising data (the advertisement and the scan response, concatenated) and decodes it.