gocan

package module
v2.1.0 Latest Latest
Warning

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

Go to latest
Published: Aug 14, 2026 License: MIT Imports: 9 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.

README

GoCAN v2

A CAN bus library for Go with pluggable hardware adapters.

v2 is a redesign of GoCAN with a smaller, more idiomatic API. Migrating from v1? See MIGRATION.md.

go get github.com/roffe/gocan/v2

Quick start

import (
	gocan "github.com/roffe/gocan/v2"
	_ "github.com/roffe/gocan/v2/adapters/canusb" // registers "CANUSB VCP"
)

bus, err := gocan.Open(ctx, "CANUSB VCP", gocan.Config{
	Port:    "/dev/ttyUSB0",
	CANRate: 500,
})
if err != nil {
	return err
}
defer bus.Close()

// Fire and forget
err = bus.Send(ctx, gocan.NewFrame(0x240, []byte{0x3F, 0x81}))

// Request / reply, bounded by the context
ctx, cancel := context.WithTimeout(ctx, 200*time.Millisecond)
defer cancel()
reply, err := bus.Request(ctx, gocan.NewFrame(0x240, data), 0x258, 0x266)

// Stream frames
for frame := range bus.Frames(ctx, 0x1A0, 0x280) {
	fmt.Println(frame)
}

Design

  • The core is dependency-free. github.com/roffe/gocan/v2 is pure stdlib. Adapters live in their own packages (adapters/<name>) that register themselves on import, like database/sql drivers — you compile and link only the hardware support you actually import.
  • Frame is a plain value. 16 bytes, no pointers, no hidden state. Copy it, reuse it, share it between goroutines freely.
  • Contexts are the only timeout mechanism. No timeout parameters, no library-specific timeout errors. context.WithTimeout bounds Recv, Request and friends; cancelling a subscription's context ends it.
  • Adapters are three methods. Open, Send, Close. Incoming traffic is pushed to the bus (bus.Deliver), notifications are events (bus.Emit), and an unrecoverable failure (bus.Fatal) terminates the bus. No channel plumbing.
  • Send confirms the write. The bus serializes senders and an adapter returns from Send once the frame reached the hardware, giving natural inter-frame pacing without a separate sync API.

Receiving frames

// One frame, any of the given IDs (empty = any frame at all)
frame, err := bus.Recv(ctx, 0x258)

// Channel, for use in a select loop. Closed when ctx ends or the bus dies.
ch := bus.Subscribe(ctx, 0x258)

// Iterator over the same thing
for frame := range bus.Frames(ctx, 0x258) { ... }

Delivery is non-blocking: a subscriber that stops draining loses frames (and a warning event tells you so).

Events and lifecycle

bus, err := gocan.Open(ctx, name, cfg,
	gocan.WithLogger(slog.Default()),          // forward events to slog
	gocan.WithEventFunc(func(e gocan.Event) {  // or handle them yourself
		fmt.Println(e)
	}),
)

stop := bus.OnEvent(func(e gocan.Event) { ... }) // add/remove at runtime
defer stop()

err = bus.Wait(ctx) // block until the bus dies; returns the fatal error, if any

bus.Done() / bus.Err() / bus.Context() expose the same lifecycle for select loops. A clean Close reports nil from Err.

Adapters

Adapters register themselves when their package is imported. Native v2 adapters:

Name Import Description
CANUSB VCP github.com/roffe/gocan/v2/adapters/canusb Lawicel CANUSB over FTDI virtual COM port
loopback built into the core Virtual echo adapter for tests

adapters/all blank-imports every native adapter, for GUI apps that list them at runtime.

gocan.Adapters() / gocan.AdapterNames() list what is registered, with descriptions and capabilities for building UIs.

Scripting (CANLang)

canlang embeds Lua so request/response flows can be scripted against a bus without recompiling the host — see its README for the script API. Like the adapters, it is a separate package: the core stays dependency-free unless you import it.

for f in bus:frames(0x1A0) do
	print("rpm " .. f:u16(1))
end

Run scripts standalone with cmd/canlang, or embed with canlang.Run(ctx, bus, "script.lua").

Writing an adapter

Implement three methods and register a constructor from your own package. The loopback adapter is the minimal example; adapters/canusb is a complete serial adapter with a reply parser and hardware-free tests.

type Adapter interface {
	Open(ctx context.Context, bus *Bus) error // start; push frames via bus.Deliver
	Send(ctx context.Context, f Frame) error  // write one frame; never called concurrently
	Close() error
}

func init() {
	gocan.Register(gocan.AdapterInfo{
		Name: "my adapter",
		New:  func(cfg gocan.Config) (gocan.Adapter, error) { ... },
	})
}

Rules of thumb:

  • Goroutines started in Open should exit when ctx is done.
  • A read error while ctx is still alive is a dead port: call bus.Fatal. If ctx is already done it's a shutdown: just return.
  • Recoverable trouble is an event (bus.Emit), not an error return.

Documentation

Overview

Package gocan v2 is a CAN bus library with pluggable hardware adapters.

Compared to v1 the API is smaller and more idiomatic:

  • Frame is a plain value (no pointers, no hidden per-send state).
  • Contexts are the only timeout/cancellation mechanism.
  • Adapters implement three methods (Open, Send, Close) and push traffic back through the Bus instead of exposing four channels.
  • Subscriptions are channels or range-over-func iterators whose lifetime is the context they were created with.

Quick start:

bus, err := gocan.Open(ctx, "loopback", gocan.Config{})
if err != nil { ... }
defer bus.Close()

reply, err := bus.Request(ctx, gocan.NewFrame(0x240, data), 0x258)

for frame := range bus.Frames(ctx, 0x1A0) {
	fmt.Println(frame)
}

This core package is pure stdlib. Hardware adapters live in subpackages under adapters/ and register themselves on import.

Migrating from v1? See MIGRATION.md for a complete v1-to-v2 mapping.

Example
package main

import (
	"context"
	"fmt"

	gocan "github.com/roffe/gocan/v2"
)

func main() {
	ctx := context.Background()
	bus, err := gocan.Open(ctx, "loopback", gocan.Config{})
	if err != nil {
		panic(err)
	}
	defer bus.Close()

	reply, err := bus.Request(ctx, gocan.NewFrame(0x123, []byte("hello")), 0x123)
	if err != nil {
		panic(err)
	}
	fmt.Printf("0x%03X %s\n", reply.ID, reply.Bytes())
}
Output:
0x123 hello

Index

Examples

Constants

This section is empty.

Variables

View Source
var ErrClosed = errors.New("gocan: bus closed")

ErrClosed is the context cause set when a bus is shut down via Close. It is reported as a clean shutdown (Bus.Err returns nil) rather than a failure.

Functions

func AdapterName

func AdapterName(a Adapter) string

AdapterName reports the registry name the adapter was constructed under (NewAdapter / Open), the adapter's own Name() when it provides one, or the Go type name as a last resort. Use it wherever a human-readable adapter name is needed before a Bus exists; Bus.AdapterName reports the same name after opening.

func AdapterNames

func AdapterNames() []string

AdapterNames returns the names of all registered adapters, sorted case-insensitively.

func ExpectedResponses

func ExpectedResponses(ctx context.Context) int

ExpectedResponses returns the reply-count hint carried by ctx, or 0 when none is set. For adapter implementations.

func Register

func Register(info AdapterInfo) error

Register adds an adapter to the registry, typically from an init function. It fails if the name is already taken.

func RegisterScanner

func RegisterScanner(scan func() []AdapterInfo)

RegisterScanner adds a function that enumerates currently attached devices, and runs it once immediately. Adapters whose registry entries depend on what hardware is plugged in should register a scanner from their init function instead of calling Register directly, so Rescan can pick up devices plugged in after startup.

func ResponseTimeout

func ResponseTimeout(ctx context.Context) time.Duration

ResponseTimeout returns the reply-wait hint carried by ctx, or 0 when none is set. For adapter implementations.

func WithExpectedResponses

func WithExpectedResponses(ctx context.Context, n int) context.Context

WithExpectedResponses hints buffered adapters (the ELM/STN family) that a Send using this context should gather n reply frames before returning to command mode. Adapters without reply buffering ignore it.

Request stamps a hint of 1 automatically; set a higher count for commands that answer with multiple frames:

ctx = gocan.WithExpectedResponses(ctx, 4)
first, err := bus.Request(ctx, frame, 0x258)

func WithResponseTimeout

func WithResponseTimeout(ctx context.Context, d time.Duration) context.Context

WithResponseTimeout hints buffered adapters (the ELM/STN family) how long to wait on the wire for the hinted reply frames of a single exchange — the v2 form of v1's per-command timeout variable. Without it such adapters use their own default (250 ms). Request stamps it automatically from its context deadline when that deadline is near; the ctx deadline itself is never used as a wire timeout (an operation-lifetime deadline says nothing about one frame's reply).

Types

type Adapter

type Adapter interface {
	Open(ctx context.Context, bus *Bus) error
	// Send writes one frame to the hardware, returning once it has been
	// written (or ctx is done). The Bus never calls Send concurrently.
	Send(ctx context.Context, f Frame) error
	Close() error
}

Adapter is a hardware (or virtual) CAN interface backend.

The Bus drives the adapter: it calls Open once, serializes calls to Send and calls Close on shutdown. The adapter pushes traffic back through the Bus: incoming frames via Bus.Deliver, notifications via Bus.Emit, and an unrecoverable failure via Bus.Fatal, which terminates the bus. Goroutines started in Open should stop when the ctx given to Open is done.

func NewAdapter

func NewAdapter(adapterName string, cfg Config) (Adapter, error)

NewAdapter constructs the named adapter from the registry with cfg, without opening it. Construction only validates configuration — no hardware is touched until OpenAdapter — so it is safe to do early, e.g. in a settings dialog, and hand the adapter to the code that will open it.

type AdapterInfo

type AdapterInfo struct {
	Name               string
	Description        string
	RequiresSerialPort bool
	SerialPortOptional bool
	Capabilities       Capabilities
	New                func(Config) (Adapter, error)
}

AdapterInfo describes a registered adapter: its registry name, what it needs and what it can do.

func Adapters

func Adapters() []AdapterInfo

Adapters returns every registered adapter's info, sorted by name.

func Rescan

func Rescan() []AdapterInfo

Rescan re-runs every registered device scanner and replaces their previous registry entries, picking up devices plugged in (or removed) since startup or the last rescan. Adapters added with Register are untouched, as are Adapter instances already opened on a Bus. It returns the updated registry like Adapters.

func (AdapterInfo) String

func (a AdapterInfo) String() string

type Bus

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

Bus is a connection to a CAN bus through an adapter. It fans incoming frames out to subscribers and serializes outgoing frames to the adapter.

func Open

func Open(ctx context.Context, adapterName string, cfg Config, opts ...Option) (*Bus, error)

Open constructs the named adapter from the registry (see AdapterNames) with cfg and connects to it.

func OpenAdapter

func OpenAdapter(ctx context.Context, adapter Adapter, opts ...Option) (*Bus, error)

OpenAdapter connects to an already-constructed adapter. Options can register event listeners before the adapter starts. AdapterName reports the name the adapter was constructed under (see gocan.AdapterName).

func (*Bus) Adapter

func (b *Bus) Adapter() Adapter

Adapter returns the underlying adapter.

func (*Bus) AdapterName

func (b *Bus) AdapterName() string

AdapterName returns the registry name the bus was opened with.

func (*Bus) Close

func (b *Bus) Close() (err error)

Close shuts down the bus and the underlying adapter. The bus context is cancelled first so adapter read loops can distinguish a clean shutdown (bus already done) from a dead port (report via Fatal).

func (*Bus) Context

func (b *Bus) Context() context.Context

Context returns the bus context. It is cancelled when the bus is closed or the adapter fails fatally; context.Cause reports why (ErrClosed on a clean shutdown, otherwise the fatal adapter error).

func (*Bus) Deliver

func (b *Bus) Deliver(f Frame)

Deliver hands an incoming frame from the adapter to every matching subscriber. Delivery is non-blocking; subscribers that have fallen behind lose the frame.

func (*Bus) Done

func (b *Bus) Done() <-chan struct{}

Done returns a channel that is closed when the bus terminates, for use in a select alongside your own work.

func (*Bus) Emit

func (b *Bus) Emit(e Event)

Emit forwards an adapter event to every registered listener, in registration order, on the calling goroutine.

func (*Bus) Err

func (b *Bus) Err() error

Err returns the fatal adapter error that terminated the bus, or nil if it is still running or was shut down cleanly (via Close or context cancellation).

func (*Bus) Fatal

func (b *Bus) Fatal(err error)

Fatal reports an unrecoverable adapter failure: it emits a final fatal event and terminates the bus with err as the cause.

func (*Bus) Frames

func (b *Bus) Frames(ctx context.Context, identifiers ...uint32) iter.Seq[Frame]

Frames returns an iterator over frames carrying one of the given identifiers. It ends when ctx is cancelled, the bus terminates, or the loop breaks.

func (*Bus) OnEvent

func (b *Bus) OnEvent(fn func(Event)) (cancel func())

OnEvent registers fn to receive subsequent events and returns a function that unregisters it. Unlike the construction-time options it can be called at any time and supports multiple independent listeners.

func (*Bus) Recv

func (b *Bus) Recv(ctx context.Context, identifiers ...uint32) (Frame, error)

Recv waits for a single frame carrying one of the given identifiers (no identifiers = any frame). Bound it with a context deadline.

func (*Bus) Request

func (b *Bus) Request(ctx context.Context, frame Frame, replyIdentifiers ...uint32) (Frame, error)

Request sends frame and waits for a reply carrying one of the given identifiers. Bound it with a context deadline. Unless the caller already set one, an expected-responses hint of 1 is stamped for buffered adapters, and a near deadline (≤ 10 s) is stamped as their reply-wait; use WithExpectedResponses / WithResponseTimeout to override.

func (*Bus) Send

func (b *Bus) Send(ctx context.Context, f Frame) error

Send writes one frame to the bus, returning once the adapter has written it (or ctx is done). Concurrent callers are serialized, giving natural inter-frame pacing.

func (*Bus) Subscribe

func (b *Bus) Subscribe(ctx context.Context, identifiers ...uint32) <-chan Frame

Subscribe returns a channel delivering frames that carry one of the given identifiers (no identifiers = all traffic). Delivery is non-blocking: a subscriber that stops draining loses frames. The channel is closed when ctx is cancelled or the bus terminates.

func (*Bus) Wait

func (b *Bus) Wait(ctx context.Context) error

Wait blocks until ctx is done or the bus terminates, returning the fatal adapter error if one occurred (nil on a clean shutdown or ctx cancellation).

type Capabilities

type Capabilities struct {
	HSCAN bool
	SWCAN bool
	KLine bool
}

Capabilities describes what a registered adapter can do.

func (Capabilities) String

func (c Capabilities) String() string

type Config

type Config struct {
	Port          string            // port name, or path to dll/so/dylib
	PortBaudrate  int               // serial port baudrate in bps
	CANRate       float64           // CAN bus rate in kbit/s
	CANFilter     []uint32          // CAN ID filters
	UseExtendedID bool              // use 29-bit IDs when setting up frame filters
	Debug         bool              // enable debug logging
	Extra         map[string]string // adapter specific key/value configuration
}

Config holds settings applied when an adapter is opened. Not every field applies to every adapter.

type Event

type Event struct {
	Type    EventType
	Details string
	// Err holds the underlying error for error and fatal events. It may be
	// nil for events raised from a plain message.
	Err error
}

Event is an out-of-band notification from an adapter: connection progress, recoverable errors, or the final fatal failure.

func (Event) IsFatal

func (e Event) IsFatal() bool

IsFatal reports whether the event signals an unrecoverable adapter failure.

func (Event) String

func (e Event) String() string

type EventType

type EventType int

EventType orders event severities from least to most severe.

const (
	EventTypeDebug EventType = iota
	EventTypeInfo
	EventTypeWarning
	EventTypeError
	// EventTypeFatal signals an unrecoverable adapter failure. It is always
	// the last event delivered before the bus terminates.
	EventTypeFatal
)

func (EventType) Level

func (et EventType) Level() slog.Level

Level maps the event type to the matching slog level so events can be forwarded to an slog.Logger with WithLogger.

func (EventType) String

func (et EventType) String() string

type Frame

type Frame struct {
	ID       uint32
	Extended bool // 29-bit identifier
	Remote   bool // remote transmission request
	Length   uint8
	Data     [8]byte
}

Frame is a single classic CAN frame. It is a plain value: copy it freely, reuse it across sends and share it between goroutines without locking.

func NewExtendedFrame

func NewExtendedFrame(id uint32, data []byte) Frame

NewExtendedFrame builds a 29-bit frame carrying data. Data beyond 8 bytes is truncated.

func NewFrame

func NewFrame(id uint32, data []byte) Frame

NewFrame builds an 11-bit frame carrying data. Data beyond 8 bytes is truncated; classic CAN cannot carry more.

func (*Frame) Bytes

func (f *Frame) Bytes() []byte

Bytes returns the payload as a slice over the frame's Data array.

func (Frame) String

func (f Frame) String() string

type Loopback

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

Loopback is a virtual adapter that delivers every sent frame back to the bus, for tests and examples.

func (*Loopback) Close

func (l *Loopback) Close() error

func (*Loopback) Open

func (l *Loopback) Open(_ context.Context, bus *Bus) error

func (*Loopback) Send

func (l *Loopback) Send(_ context.Context, f Frame) error

type Option

type Option func(*Bus)

Option configures a Bus before its adapter is opened.

func WithEventFunc

func WithEventFunc(fn func(Event)) Option

WithEventFunc registers fn as a synchronous event handler. Handlers run in registration order on the goroutine that raised the event; keep them quick.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger forwards every adapter event to l at the matching slog level. Error and fatal events attach the underlying error under the "err" key.

Directories

Path Synopsis
adapters
all
Package all registers every native v2 adapter, for applications that list adapters at runtime (e.g.
Package all registers every native v2 adapter, for applications that list adapters at runtime (e.g.
canlib
Package canlib registers Kvaser CAN channels ("CANlib #0 ...", one per attached channel, virtual channels skipped) via Kvaser's CANlib SDK.
Package canlib registers Kvaser CAN channels ("CANlib #0 ...", one per attached channel, virtual channels skipped) via Kvaser's CANlib SDK.
canusb
Package canusb drives the Lawicel CANUSB over its FTDI Virtual COM Port, implemented from the CANUSB Manual (Version 1.0D, November 2011).
Package canusb drives the Lawicel CANUSB over its FTDI Virtual COM Port, implemented from the CANUSB Manual (Version 1.0D, November 2011).
combi
Package combi drives the CombiAdapter over USB via gotmc/libusb (cgo; requires libusb-1.0).
Package combi drives the CombiAdapter over USB via gotmc/libusb (cgo; requires libusb-1.0).
drewtech
Package drewtech drives the Drewtech Mongoose Pro GM II over its native serial protocol (no J2534 DLL needed) via gocan/v2/pkg/drewtech.
Package drewtech drives the Drewtech Mongoose Pro GM II over its native serial protocol (no J2534 DLL needed) via gocan/v2/pkg/drewtech.
elm327
Package elm327 drives generic ELM327 CAN adapters over their virtual COM port.
Package elm327 drives generic ELM327 CAN adapters over their virtual COM port.
j2534
Package j2534 registers J2534 PassThru DLL interfaces found in the Windows registry ("J2534 #0 <name>", one per installed DLL).
Package j2534 registers J2534 PassThru DLL interfaces found in the Windows registry ("J2534 #0 <name>", one per installed DLL).
just4trionic
Package just4trionic drives the Just4Trionic STM32F103C8T6 CAN adapter over its virtual COM port (115200 baud).
Package just4trionic drives the Just4Trionic STM32F103C8T6 CAN adapter over its virtual COM port (115200 baud).
obdx
Package obdx drives the OBDX Pro Wifi over its TCP AP (192.168.4.1:23) using the binary DVI command protocol (framing reused from gocan v1's pkg/dvi).
Package obdx drives the OBDX Pro Wifi over its TCP AP (192.168.4.1:23) using the binary DVI command protocol (framing reused from gocan v1's pkg/dvi).
pcan
Package pcan registers PEAK-System PCAN channels ("PCAN #0 ...", one per attached channel) on Windows via PCANBasic.dll.
Package pcan registers PEAK-System PCAN channels ("PCAN #0 ...", one per attached channel) on Windows via PCANBasic.dll.
rcan
Package rcan drives the rCAN USB device (roffe.nu, VID:PID ffff:1337).
Package rcan drives the rCAN USB device (roffe.nu, VID:PID ffff:1337).
scantool
Package scantool drives ScanTool.net STN11xx/STN21xx based adapters (OBDLink SX/EX, generic STN1170/STN2120 boards) over their virtual COM port.
Package scantool drives ScanTool.net STN11xx/STN21xx based adapters (OBDLink SX/EX, generic STN1170/STN2120 boards) over their virtual COM port.
slcan
Package slcan drives CANable-style SLCAN adapters over their virtual COM port.
Package slcan drives CANable-style SLCAN adapters over their virtual COM port.
socketcan
Package socketcan registers Linux SocketCAN network interfaces as gocan adapters ("SocketCAN can0", ...), one per interface found at import time.
Package socketcan registers Linux SocketCAN network interfaces as gocan adapters ("SocketCAN can0", ...), one per interface found at import time.
txbridge
Package txbridge drives the txbridge dongle over TCP (192.168.4.1:1337 or tcp://host[:1337] from cfg.Port).
Package txbridge drives the txbridge dongle over TCP (192.168.4.1:1337 or tcp://host[:1337] from cfg.Port).
yaca
Package yaca drives the YACA ("Yet Another CANbus Adapter") over its virtual COM port.
Package yaca drives the YACA ("Yet Another CANbus Adapter") over its virtual COM port.
Package canlang embeds a Lua interpreter (gopher-lua) bound to a gocan Bus, so request/response CAN flows can be scripted without recompiling the host application.
Package canlang embeds a Lua interpreter (gopher-lua) bound to a gocan Bus, so request/response CAN flows can be scripted without recompiling the host application.
cmd
canlang command
Command canlang runs a CANLang (Lua) script against a CAN bus.
Command canlang runs a CANLang (Lua) script against a CAN bus.
Package gmlan implements the GMLAN (GMW3110) diagnostic services on a gocan v2 bus.
Package gmlan implements the GMLAN (GMW3110) diagnostic services on a gocan v2 bus.
pkg
drewtech
Package drewtech is a native (no Windows DLL) J2534 client for the DrewTech Mongoose Pro GM II.
Package drewtech is a native (no Windows DLL) J2534 client for the DrewTech Mongoose Pro GM II.
dvi
w32

Jump to

Keyboard shortcuts

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