gotelemetry

package module
v0.4.2 Latest Latest
Warning

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

Go to latest
Published: Nov 10, 2026 License: MIT Imports: 18 Imported by: 0 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.

README

Telemetry Library in Go

This repository provides a Go implementation of a telemetry system based on framing, CRC validation, and topic-based message handling. It is compatible with the Overdrivr/Telemetry protocol, making it interoperable with Python implementations. It is designed for serial communication and supports attaching variables, subscribing to topics, and publishing data.

Features

  • CRC16 Validation: Ensures message integrity with a 16-bit cyclic redundancy check.
  • Framing Protocol: Supports custom start-of-frame (SOF), end-of-frame (EOF), and escape sequences.
  • Topic-Based Messaging:
    • Attach variables to topics.
    • Subscribe to topics with callbacks.
    • Publish messages to topics.
  • Serial Communication: Native serial ports and USB discovery on Linux, Windows and macOS, without cgo.

Installation

Clone the repository and ensure you have Go installed.

# Clone the repository
git clone <repository-url>
cd <repository>

# Build the project
go build

Usage

Automatic USB sources

USBTelemetrySource owns device discovery, the serial session, health checks, and recovery. Applications can embed it in an accessory type and supply their own USB identity, serial settings, handshake, identification, and callbacks:

type Accessory struct {
    *gotelemetry.USBTelemetrySource
}

func NewAccessory(vendorID, productID string, onMessage func(gotelemetry.TMMsg)) *Accessory {
    return &Accessory{gotelemetry.NewUSBTelemetrySource(gotelemetry.USBTelemetrySourceOptions{
        VendorID: vendorID,
        ProductID: productID,
        Serial: gotelemetry.SerialTransportOptions{BaudRate: 115200},
        OnMessage: onMessage,
    })}
}

Call Start() to begin detection and Stop() to cancel and join all work. Both are idempotent. IsRunning() reports whether detection is running, including while waiting for a device. Separate source instances have independent sessions. Lifecycle methods must be called outside source callbacks.

On Linux, the source watches /dev before its initial scan, then responds to USB serial device changes without periodic scans while waiting normally. After a disconnect, failed open, rejected identity, or silent connection, it also retries indefinitely with exponential delays from one to thirty seconds. Device events bypass that delay. If device events are unavailable, including on Windows and macOS, the source polls while no device is connected. A connected session is supervised by its health deadline and is never polled.

The default connection timeout is eight seconds. Each valid frame resets the health deadline, including an unchanged value. An optional Handshake is sent after starting the reader; Identify can wait for the expected descriptor or reject the device. Without Identify, the first valid message connects it. OnConnected runs before replaying identification messages to OnMessage. OnDisconnected also runs at startup with nil and at shutdown with cancellation. Callbacks are synchronous and should return promptly.

Set Product to only open adapters whose USB product string descriptor matches (case-insensitive). A trailing % matches a product prefix, so Accessory.% accepts both Accessory.02 and Accessory.03. Selectors without % continue to match exactly. Set SerialNumber to select a particular adapter. When several adapters still match, the most recently attached one is used. Port renumbering is handled on discovery. Timeouts and retry delays are configurable in USBTelemetrySourceOptions.

Sessions managed by the application

Use OpenSerialTransport to open a selected port once, and Run(ctx) to receive until cancellation or a read error. These APIs do not discover USB devices or reconnect; the caller owns those policies. Serial parameters are typed options (9600 baud, 8N1, one-second I/O timeouts by default).

transport, err := gotelemetry.OpenSerialTransport(portName, gotelemetry.SerialTransportOptions{
    BaudRate: 115200,
    ReadTimeout: time.Second,
    WriteTimeout: time.Second,
})
if err != nil {
    return err
}
telemetry := gotelemetry.NewTelemetry(transport)
telemetry.SetMessageHandler(func(msg gotelemetry.TMMsg) {
    value, _ := msg.Value()
    log.Printf("%s: %v", msg.Topic, value)
})
return telemetry.Run(ctx)

Import github.com/ashajkofci/gotelemetry for this example. The port name and serial settings belong to the calling application.

Run is blocking, returns the transport error or ctx.Err(), and closes its transport on exit. Cancellation closes it and joins pending reads. Serial I/O uses finite timeouts so closure is synchronized with the serial driver. Serial ports are supported natively, without cgo, on:

  • Linux: ttys of USB devices are found through sysfs, and watched in /dev. OpenSerialTransport does not lock the port for exclusive use, so other processes can still open it.
  • Windows: COM ports of USB devices are found through SetupAPI, including ports created by function drivers such as FTDI's; port names are COM3 or \\.\COM10. Windows serial drivers only allow one open handle per port. Serial numbers come from device instance IDs, which Windows upper-cases, and no manufacturer string is reported.
  • macOS: callout devices (/dev/cu.*) of USB devices are found with ioreg. The port is not locked for exclusive use. Mark and space parity are not supported.

On other platforms OpenSerialTransport, GetTransport and USB sources return an unsupported error; the protocol itself works with any custom TMTransport. To check a real port, run GOTELEMETRY_TEST_PORT=COM3 go test -run TestSerialTransportHardware; it only reads from the port. Custom transports should supply a Close function that unblocks reads, or use bounded read timeouts. Serial transports returned by OpenSerialTransport have an idempotent Close. Use a new telemetry instance after reconnecting; only one reader may run per instance.

SetMessageHandler receives every valid message, including repeated values. Subscribe retains its existing new-or-changed-value behavior: a specific topic callback takes precedence over the general callback. A new topic notifies even at zero; an attached, unchanged value does not notify. The message handler runs after change subscriptions, including when no subscription fires. Both callbacks run synchronously outside the data mutex and may call GetValue, GetAvailableTopics, Subscribe, and Publish. Return promptly and do not wait for the reader to exit inside a callback. Retained messages own their payload bytes. Invalid CRCs, message types, and payload sizes do not invoke handlers.

The existing GetTransport and UpdateTelemetry APIs remain available. GetTransportContext(ctx, options...) adds cancellation to legacy discovery. A retry count of one performs one attempt without a sleep. New application supervisors should use Run to avoid competing reconnect policies.

Import the Library
import "path/to/telemetry"
Example
package main

import (
	"log"
	"time"
	"path/to/telemetry"
)

func main() {
	// Get the transport for the USB device
	transport, err := telemetry.GetTransport("", "")
	if err != nil {
		log.Fatalf("Failed to get USB transport: %v", err)
	}

	// Initialize telemetry
	tele := telemetry.NewTelemetry(transport)

	// Attach a variable to a topic
	value := uint8(42)
	tele.Attach("example_topic", &value)

	// Subscribe to a topic
	tele.Subscribe("example_topic", func(msg telemetry.TMMsg) {
		log.Printf("Received message on topic '%s': %X", msg.Topic, msg.Payload)
	})

	// Publish a message
	err = tele.Publish("example_topic", telemetry.TMUint8, []byte{value})
	if err != nil {
		log.Printf("Failed to publish: %v", err)
	}

	// Start listening for incoming messages
	stopChan := make(chan struct{})
	tele.UpdateTelemetry(stopChan)

	// Keep the program running
	select {}
}
Attaching variables to topics
package main

import (
    "log"
    "path/to/telemetry"
)

func main() {
    // Initialize telemetry with a mock transport for testing
    mockTransport := &telemetry.MockTransport{}
    tele := telemetry.NewTelemetry(&telemetry.TMTransport{
        Read:  mockTransport.Read,
        Write: mockTransport.Write,
    })

    // Attach variables to topics
    var intValue int32
    var floatValue float32
    tele.Attach("int_topic", &intValue)
    tele.Attach("float_topic", &floatValue)

    // Simulate receiving messages
    tele.TryUpdateHashTable(telemetry.TMMsg{
        Type:    telemetry.TMInt32,
        Topic:   "int_topic",
        Payload: []byte{0, 0, 0, 42},
    })
    tele.TryUpdateHashTable(telemetry.TMMsg{
        Type:    telemetry.TMFloat32,
        Topic:   "float_topic",
        Payload: []byte{0, 0, 128, 63},
    })

    log.Printf("int_topic value: %d", intValue)
    log.Printf("float_topic value: %f", floatValue)
}
Publishing and subscribing to multiple topics
package main

import (
    "log"
    "path/to/telemetry"
)

func main() {
    // Initialize telemetry with a mock transport for testing
    mockTransport := &telemetry.MockTransport{}
    tele := telemetry.NewTelemetry(&telemetry.TMTransport{
        Read:  mockTransport.Read,
        Write: mockTransport.Write,
    })

    // Subscribe to multiple topics
    tele.Subscribe("topic1", func(msg telemetry.TMMsg) {
        log.Printf("Received on topic1: %s", msg.Payload)
    })
    tele.Subscribe("topic2", func(msg telemetry.TMMsg) {
        log.Printf("Received on topic2: %s", msg.Payload)
    })

    // Publish messages to different topics
    tele.Publish("topic1", telemetry.TMString, []byte("Hello Topic 1"))
    tele.Publish("topic2", telemetry.TMString, []byte("Hello Topic 2"))

    // Start listening for incoming messages
    stopChan := make(chan struct{})
    tele.UpdateTelemetry(stopChan)

    // Keep the program running
    select {}
}

API Documentation

Telemetry Structure
  • NewTelemetry(transport *TMTransport) *Telemetry: Creates a new telemetry instance.

  • Attach(topic string, variable interface{}): Links a variable to a topic for automatic updates.

  • Subscribe(topic string, callback func(TMMsg)): Registers a callback for a specific topic.

  • Publish(topic string, msgType TMType, payload []byte) error: Sends a message to a topic.

  • UpdateTelemetry(stopChan chan struct{}): Starts listening for incoming messages.

  • PrintHashTable(): Prints the current values in the hash table.

  • GetValue(topic string) interface{}: Returns the value of a topic in the hash table.

  • GetAvailableTopics() []string: Returns a list of all received topics.

Message Types (TMType)
Type Description
TMFloat32 32-bit float
TMUint8 Unsigned 8-bit
TMUint16 Unsigned 16-bit
TMUint32 Unsigned 32-bit
TMInt8 Signed 8-bit
TMInt16 Signed 16-bit
TMInt32 Signed 32-bit
TMString String

Framing Protocol

  • Start of Frame (SOF): 0xF7
  • End of Frame (EOF): 0x7F
  • Escape Character (ESC): 0x7D

CRC16 Validation

Uses the polynomial 0x1021 (CRC-CCITT). Both Python and Go implementations are compatible for validation.

Contributing

Contributions are welcome! Please open issues or submit pull requests.

License

This project is licensed under the MIT License.

Documentation

Index

Constants

View Source
const (
	SOF = 0xF7
	EOF = 0x7F
	ESC = 0x7D
)

Frame handling

View Source
const (
	IncomingBufferSize = 128
	OutgoingBufferSize = 128
	TopicBufferSize    = 64
)

Telemetry Core

View Source
const (
	VendorID  = "0403" // Default vendor for FTDI devices
	ProductID = "6015" // Default product for FTDI devices
)

Variables

View Source
var (
	MaxRetries = 1000             // Maximum number of retries for connections
	RetryDelay = 10 * time.Second // Delay between retry attempts
)

Functions

func CRC16

func CRC16(data []byte) uint16

CRC16 computes the CRC-CCITT (0x1021) checksum for the given data.

func CRC16Recursive

func CRC16Recursive(byteVal byte, remainder uint16) uint16

CRC16Recursive performs the CRC-CCITT (0x1021) computation for a single byte.

Types

type Frame

type Frame struct {
	// IncomingBuffer stores the bytes of the incoming frame.
	IncomingBuffer []byte
	// OutgoingBuffer stores the bytes of the outgoing frame.
	OutgoingBuffer []byte
	// IncomingState represents the current state of the frame parsing.
	IncomingState FramingState
	// OnFrame is called when a complete frame is received.
	OnFrame func(data []byte)
	// OnError is called when an error occurs during frame parsing.
	OnError func(err error)
}

Frame represents the framing protocol for handling incoming and outgoing data.

func NewFrame

func NewFrame() *Frame

NewFrame creates a new Frame instance.

func (*Frame) AppendByte

func (f *Frame) AppendByte(b byte)

AppendByte appends a byte to the outgoing buffer, escaping it if necessary.

func (*Frame) AppendUint16

func (f *Frame) AppendUint16(value uint16)

AppendUint16 appends a 16-bit unsigned integer to the outgoing buffer, escaping it if necessary.

func (*Frame) BeginFrame

func (f *Frame) BeginFrame()

BeginFrame initializes the outgoing buffer with the Start of Frame (SOF) byte.

func (*Frame) EndFrame

func (f *Frame) EndFrame()

EndFrame appends the End of Frame (EOF) byte to the outgoing buffer.

func (*Frame) FeedByte

func (f *Frame) FeedByte(b byte)

FeedByte processes an incoming byte and updates the frame state accordingly.

type FramingState

type FramingState int
const (
	Idle FramingState = iota
	Escaping
	Active
)

type Parity added in v0.4.0

type Parity int

Parity selects the serial parity bit. The zero value is NoParity.

const (
	NoParity Parity = iota
	OddParity
	EvenParity
	MarkParity
	SpaceParity
)

type SerialTransportOptions added in v0.4.0

type SerialTransportOptions struct {
	BaudRate     int
	DataBits     int
	Parity       Parity
	StopBits     StopBits
	ReadTimeout  time.Duration
	WriteTimeout time.Duration
}

SerialTransportOptions configure a port without device-specific assumptions. Zero values select 9600 baud, 8N1 and one-second read/write timeouts. Timeouts must be finite and positive so Close can safely join pending I/O operations.

type StopBits added in v0.4.0

type StopBits int

StopBits selects the number of serial stop bits. The zero value is OneStopBit.

const (
	OneStopBit StopBits = iota
	TwoStopBits
)

type TMMsg

type TMMsg struct {
	Type    TMType
	Topic   string
	Payload []byte
}

func (TMMsg) Value added in v0.4.0

func (m TMMsg) Value() (interface{}, error)

Value decodes a message payload. Invalid types and payload lengths are errors.

type TMTransport

type TMTransport struct {
	Read         func([]byte) (int, error)
	Write        func([]byte) (int, error)
	ProductID    string
	VendorID     string
	Manufacturer string
	Product      string
	SerialNumber string
	PortName     string
	// Close releases the transport and joins pending I/O operations.
	Close func() error
}

func GetTransport

func GetTransport(options ...interface{}) (*TMTransport, error)

GetTransport scans for available USB ports and returns the first one that matches the specified VendorID and ProductID. All parameters are optional: - vendorId (default: VendorID constant "0403") - productId (default: ProductID constant "6015") - maxRetries (default: MaxRetries variable) - retryDelay (default: RetryDelay variable)

func GetTransportContext added in v0.4.0

func GetTransportContext(ctx context.Context, options ...interface{}) (*TMTransport, error)

GetTransportContext performs legacy USB discovery with cancellable retries. A count of one performs a single attempt without a retry delay.

func OpenSerialTransport added in v0.4.0

func OpenSerialTransport(name string, options SerialTransportOptions) (*TMTransport, error)

OpenSerialTransport opens exactly the named port without discovery or retries. Serial ports are supported on Linux, Windows and macOS. Linux and macOS do not lock the port for exclusive use; Windows serial drivers only allow one open handle per port. Close is idempotent and joins pending I/O operations.

type TMType

type TMType int
const (
	TMFloat32 TMType = iota
	TMUint8
	TMUint16
	TMUint32
	TMInt8
	TMInt16
	TMInt32
	TMString
)

type Telemetry

type Telemetry struct {
	// Frame handles the framing protocol for incoming and outgoing messages.
	Frame *Frame
	// HashTable stores the values of attached variables by topic.
	HashTable map[string]interface{}
	// TopicCallbacks stores the callbacks for specific topics.
	TopicCallbacks map[string]func(TMMsg)
	// GeneralCallback is called for any received message if no specific topic callback is registered.
	GeneralCallback func(TMMsg)
	// Transport handles the read and write operations for the telemetry system.
	Transport *TMTransport
	// Mutex ensures thread-safe access to the telemetry system's data structures.
	Mutex sync.Mutex
	// ReceivedTopics keeps track of all received topics.
	ReceivedTopics map[string]bool
	// contains filtered or unexported fields
}

Telemetry represents the core telemetry system, handling frame parsing, topic-based messaging, and CRC validation.

func NewTelemetry

func NewTelemetry(transport *TMTransport) *Telemetry

NewTelemetry creates a new telemetry instance with the provided transport.

func (*Telemetry) Attach

func (t *Telemetry) Attach(topic string, variable interface{})

Attach links a variable to a topic for automatic updates.

func (*Telemetry) GetAvailableTopics

func (t *Telemetry) GetAvailableTopics() []string

GetAvailableTopics returns a list of all received topics.

func (*Telemetry) GetValue

func (t *Telemetry) GetValue(topic string) interface{}

GetValue returns the value of a topic in the hash table.

func (*Telemetry) PrintHashTable

func (t *Telemetry) PrintHashTable()

PrintHashTable prints the current values stored in the telemetry's hash table.

func (*Telemetry) Publish

func (t *Telemetry) Publish(topic string, msgType TMType, payload []byte) error

Publish sends a message to a topic with the specified type and payload.

func (*Telemetry) Run added in v0.4.0

func (t *Telemetry) Run(ctx context.Context) error

Run receives telemetry until cancellation or a transport error. It never discovers devices or reconnects. It owns and closes the current transport on return, including on cancellation. Close must unblock Read; without Close, reads must have a timeout so cancellation can be observed.

Only one reader may run per Telemetry. Configure Frame before starting Run; do not feed Frame concurrently with Run. Publish and subscription methods may be called concurrently. Use a new Telemetry instance for a new connection.

func (*Telemetry) SetMessageHandler added in v0.4.0

func (t *Telemetry) SetMessageHandler(callback func(TMMsg))

SetMessageHandler receives every valid decoded message, including unchanged values, after change subscriptions. It does not change Subscribe behavior. Handlers run synchronously outside the mutex and should return promptly.

func (*Telemetry) Subscribe

func (t *Telemetry) Subscribe(topic string, callback func(TMMsg))

Subscribe registers a callback for a specific topic. If the topic is an empty string, the callback is called for any received message.

func (*Telemetry) TryUpdateHashTable

func (t *Telemetry) TryUpdateHashTable(msg TMMsg)

TryUpdateHashTable updates the hash table with the received message and calls the appropriate callbacks.

func (*Telemetry) UpdateTelemetry

func (t *Telemetry) UpdateTelemetry(stopChan chan struct{})

UpdateTelemetry starts listening for incoming messages and processes them. New applications should use Run and own their reconnect policy.

type USBDevice added in v0.4.0

type USBDevice struct {
	Name         string
	SerialNumber string
	Product      string // USB product string descriptor.
	Path         string
	Attached     time.Time // When the device appeared; zero if unknown.
}

USBDevice identifies one enumerated USB serial port: a tty on Linux, a COM port on Windows or a callout device (/dev/cu.*) on macOS. Path is a sysfs path, a device instance ID or an I/O Registry entry ID; it distinguishes device nodes reused after unplugging, except on Windows where the instance ID stays the same. SerialNumber permits port renumbering; Windows reports it upper-cased.

type USBTelemetrySource added in v0.4.0

type USBTelemetrySource struct {
	// contains filtered or unexported fields
}

USBTelemetrySource watches USB serial devices and owns a single telemetry session. Start performs one discovery scan; a healthy watcher then wakes it on device changes. After errors or disconnection it also retries indefinitely with capped exponential backoff. When several devices match, the most recently attached one is used. Stop cancels and joins all its work.

Options are copied at construction. Callbacks run synchronously on the supervisor; return promptly and do not call lifecycle methods from them.

func NewUSBTelemetrySource added in v0.4.0

func NewUSBTelemetrySource(options USBTelemetrySourceOptions) *USBTelemetrySource

func (*USBTelemetrySource) IsRunning added in v0.4.0

func (s *USBTelemetrySource) IsRunning() bool

func (*USBTelemetrySource) Publish added in v0.4.2

func (s *USBTelemetrySource) Publish(ctx context.Context, msg TMMsg) error

Publish sends once on the current connected session. It never retries a command. Do not call it from supervisor callbacks. Cancellation after delivery begins cannot retract the write; a timeout must not be treated as proof of non-delivery.

func (*USBTelemetrySource) Restart added in v0.4.0

func (s *USBTelemetrySource) Restart() error

func (*USBTelemetrySource) Start added in v0.4.0

func (s *USBTelemetrySource) Start() error

func (*USBTelemetrySource) Stop added in v0.4.0

func (s *USBTelemetrySource) Stop() error

type USBTelemetrySourceOptions added in v0.4.0

type USBTelemetrySourceOptions struct {
	Name                  string
	VendorID              string
	ProductID             string
	SerialNumber          string // Optional selector when adapters share VID/PID.
	Product               string // Optional USB product string selector; a trailing % matches a prefix.
	Serial                SerialTransportOptions
	ConnectionTimeout     time.Duration // Includes opening and identifying.
	ReconnectInitialDelay time.Duration
	ReconnectMaxDelay     time.Duration

	// Handshake, when non-nil, is published after starting the session reader.
	Handshake *TMMsg
	// Identify returns true once this is the expected accessory, false while
	// waiting for more descriptors, or an error to reject it. If nil, the first
	// valid telemetry message establishes connectivity.
	Identify       func(TMMsg) (bool, error)
	OnConnected    func(USBDevice)
	OnDisconnected func(error) // Also called at startup (nil) and shutdown.
	OnMessage      func(TMMsg) // Includes unchanged values and handshake metadata.
}

USBTelemetrySourceOptions describes an accessory without imposing a protocol handshake, project name, USB identity, or application status representation.

Jump to

Keyboard shortcuts

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