bthome

package
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 11, 2026 License: Apache-2.0 Imports: 12 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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

Examples

Constants

View Source
const (
	UUID            uint16 = 0xFCD2 // version 2
	UUIDv1          uint16 = 0x181C // version 1, not encrypted
	UUIDv1Encrypted uint16 = 0x181E // version 1, encrypted
)

Service UUIDs (16-bit).

View Source
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.

View Source
const (
	ADFlags         = 0x01
	ADShortName     = 0x08
	ADCompleteName  = 0x09
	ADServiceData16 = 0x16
	ADManufacturer  = 0xFF
)

Advertising data types used here.

Variables

View Source
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")
)
View Source
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

func Advertising(serviceData []byte, name string) []byte

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

func ButtonEvent(name string) (byte, bool)

ButtonEvent is the code of a button event name ("press", "long_press", ...), for Builder.

func CommandEvent

func CommandEvent(name string) (byte, bool)

CommandEvent is the code of a command ("on", "off", "toggle", "step_up", "step_down").

func DimmerEvent

func DimmerEvent(name string) (byte, bool)

DimmerEvent is the code of "rotate_left" or "rotate_right".

func FormatMAC

func FormatMAC(m [6]byte) string

FormatMAC writes an address as "AA:BB:CC:DD:EE:FF".

func LocalName

func LocalName(ads []AD) string

LocalName returns the complete or shortened local name in ads.

func Manufacturer

func Manufacturer(ads []AD) map[uint16][]byte

Manufacturer collects the manufacturer-specific data of ads by company identifier.

func ParseMAC

func ParseMAC(s string) ([6]byte, error)

ParseMAC reads an address written as "AA:BB:CC:DD:EE:FF", "aa-bb-cc-dd-ee-ff" or "AABBCCDDEEFF".

func ServiceData16

func ServiceData16(ads []AD) map[uint16][]byte

ServiceData16 collects the 16-bit UUID service data of ads by UUID.

Types

type AD struct {
	Type byte
	Data []byte
}

AD is one advertising data structure: its type and its data.

func ParseAD

func ParseAD(b []byte) ([]AD, error)

ParseAD splits advertising data into its structures. It stops at a zero length (padding) and returns what it read with an error when a structure runs past the end.

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

func (b *Builder) Add(id byte, v float64) *Builder

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

func (b *Builder) Button(code byte) *Builder

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) Command

func (b *Builder) Command(code byte, args ...byte) *Builder

Command writes a command event with up to 31 argument bytes.

func (*Builder) DeviceType

func (b *Builder) DeviceType(id uint16) *Builder

DeviceType writes the device type id object (0xF0).

func (*Builder) Dimmer

func (b *Builder) Dimmer(code byte, steps uint8) *Builder

Dimmer writes a dimmer event with the steps turned.

func (*Builder) Firmware

func (b *Builder) Firmware(parts ...byte) *Builder

Firmware writes a firmware version object: three parts (0xF2) or four (0xF1), most significant first, such as Firmware(1, 0, 21).

func (*Builder) Raw

func (b *Builder) Raw(p []byte) *Builder

Raw writes a raw object (up to 255 bytes).

func (*Builder) Seal

func (b *Builder) Seal(key []byte, addr string, counter uint32) ([]byte, error)

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

func (b *Builder) ServiceData() ([]byte, error)

ServiceData returns the plain service data (the bytes after the UUID).

func (*Builder) Text

func (b *Builder) Text(s string) *Builder

Text writes a text object (up to 255 bytes of UTF-8).

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.

func (*Guard) Accept

func (g *Guard) Accept(mac string, counter uint32) bool

Accept reports whether counter is newer than the last one accepted for mac, and remembers it when it is.

func (*Guard) Reset

func (g *Guard) Reset(mac string)

Reset forgets mac's counter (after the sender's key and counter were reset).

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
)

func (Kind) String

func (k Kind) String() string

String names the kind.

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.

func (Object) Bool

func (o Object) Bool() bool

Bool reports a Binary object's state.

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.

func Objects

func Objects() []ObjectInfo

Objects lists every known object id in order.

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

func Decode(uuid uint16, data []byte, addr string, key []byte) (*Packet, error)

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

func DecodeAdvertising(adv []byte, addr string, key []byte) (*Packet, error)

DecodeAdvertising finds BTHome service data in raw advertising data (the advertisement and the scan response, concatenated) and decodes it.

func (*Packet) Find

func (p *Packet) Find(id byte, index int) (Object, bool)

Find returns the index-th occurrence (from 0) of object id.

func (*Packet) PacketID

func (p *Packet) PacketID() (int, bool)

PacketID returns the packet id object (0x00), which senders count up so that receivers can drop repeats.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL