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 ¶
- Variables
- func AdapterName(a Adapter) string
- func AdapterNames() []string
- func ExpectedResponses(ctx context.Context) int
- func Register(info AdapterInfo) error
- func RegisterScanner(scan func() []AdapterInfo)
- func ResponseTimeout(ctx context.Context) time.Duration
- func WithExpectedResponses(ctx context.Context, n int) context.Context
- func WithResponseTimeout(ctx context.Context, d time.Duration) context.Context
- type Adapter
- type AdapterInfo
- type Bus
- func (b *Bus) Adapter() Adapter
- func (b *Bus) AdapterName() string
- func (b *Bus) Close() (err error)
- func (b *Bus) Context() context.Context
- func (b *Bus) Deliver(f Frame)
- func (b *Bus) Done() <-chan struct{}
- func (b *Bus) Emit(e Event)
- func (b *Bus) Err() error
- func (b *Bus) Fatal(err error)
- func (b *Bus) Frames(ctx context.Context, identifiers ...uint32) iter.Seq[Frame]
- func (b *Bus) OnEvent(fn func(Event)) (cancel func())
- func (b *Bus) Recv(ctx context.Context, identifiers ...uint32) (Frame, error)
- func (b *Bus) Request(ctx context.Context, frame Frame, replyIdentifiers ...uint32) (Frame, error)
- func (b *Bus) Send(ctx context.Context, f Frame) error
- func (b *Bus) Subscribe(ctx context.Context, identifiers ...uint32) <-chan Frame
- func (b *Bus) Wait(ctx context.Context) error
- type Capabilities
- type Config
- type Event
- type EventType
- type Frame
- type Loopback
- type Option
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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 ¶
ResponseTimeout returns the reply-wait hint carried by ctx, or 0 when none is set. For adapter implementations.
func WithExpectedResponses ¶
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 ¶
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 ¶
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 ¶
Open constructs the named adapter from the registry (see AdapterNames) with cfg and connects to it.
func OpenAdapter ¶
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) AdapterName ¶
AdapterName returns the registry name the bus was opened with.
func (*Bus) Close ¶
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 ¶
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 ¶
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 ¶
Emit forwards an adapter event to every registered listener, in registration order, on the calling goroutine.
func (*Bus) Err ¶
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 ¶
Fatal reports an unrecoverable adapter failure: it emits a final fatal event and terminates the bus with err as the cause.
func (*Bus) Frames ¶
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 ¶
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 ¶
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 ¶
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 ¶
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.
type Capabilities ¶
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.
type EventType ¶
type EventType int
EventType orders event severities from least to most severe.
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 ¶
NewExtendedFrame builds a 29-bit frame carrying data. Data beyond 8 bytes is truncated.
func NewFrame ¶
NewFrame builds an 11-bit frame carrying data. Data beyond 8 bytes is truncated; classic CAN cannot carry more.
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.
type Option ¶
type Option func(*Bus)
Option configures a Bus before its adapter is opened.
func WithEventFunc ¶
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 ¶
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. |