gotelemetry

package module
v0.3.3 Latest Latest
Warning

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

Go to latest
Published: Sep 15, 2025 License: MIT Imports: 11 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: Uses github.com/albenik/go-serial for serial port interaction.

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

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 TMMsg

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

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
}

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)

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
}

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

Jump to

Keyboard shortcuts

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