gocan

package module
v1.4.8 Latest Latest
Warning

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

Go to latest
Published: Jul 5, 2026 License: MIT Imports: 30 Imported by: 6 modules, 25 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

A Go CAN bus library for Linux, Windows and macOS with support for a wide range of CAN adapters — from cheap ELM327/STN serial dongles to SocketCAN, J2534 passthru devices, Kvaser, PCAN and more.

Linux maintainer wanted! Please contact me at gocan@roffe.nu if you want to help out.

Installation

go get github.com/roffe/gocan@latest
import "github.com/roffe/gocan"

Some adapter backends need vendor libraries and are only compiled in when you build with their tag (go build -tags "combi,j2534"):

Build tag Enables Requires
ftdi d2xx based FTDI adapters FTDI D2XX driver
canlib Kvaser Canlib canlib32.dll
canusb Lawicel CANUSB via DLL canusbdrv(64).dll
combi CombiAdapter via libusb libusb-1.0.dll
j2534 J2534 passthru devices vendor J2534 DLL
pcan PCAN-USB PCANBasic.dll

Serial adapters (ELM327/STN/OBDLink, slcan, CANUSB in VCP mode, txbridge…) and SocketCAN on Linux are always available without tags.

Quick start

Adapters are looked up by name from a registry. gocan.ListAdapterNames() returns everything compiled into your binary; names include e.g. "ELM327", "CombiAdapterNew", "txbridge wifi" and on Linux one "SocketCAN <dev>" entry per interface found.

package main

import (
	"context"
	"log"
	"time"

	"github.com/roffe/gocan"
)

func main() {
	ctx := context.Background()

	c, err := gocan.New(ctx, "ELM327", &gocan.AdapterConfig{
		Port:         "COM3",   // or /dev/ttyUSB0
		PortBaudrate: 115200,   // serial adapters only
		CANRate:      500,      // CAN bit rate in kbit/s
		CANFilter:    []uint32{0x7E8}, // receive only these IDs (empty = everything)
	})
	if err != nil {
		log.Fatal(err)
	}
	defer c.Close()

	// Fire-and-forget send: queues the frame to the adapter
	if err := c.Send(0x7DF, []byte{0x02, 0x01, 0x0C, 0, 0, 0, 0, 0}, gocan.Outgoing); err != nil {
		log.Fatal(err)
	}

	// Wait for a single frame with one of the given IDs
	resp, err := c.Recv(ctx, 500*time.Millisecond, 0x7E8)
	if err != nil {
		log.Fatal(err)
	}
	log.Printf("id %03X data %X", resp.Identifier, resp.Data)
}

If you already have an Adapter instance (e.g. from gocan.NewAdapter) use gocan.NewWithOpts, which also takes options such as WithEventFunc / WithLogger:

dev, _ := gocan.NewAdapter("ELM327", cfg)
c, err := gocan.NewWithOpts(ctx, dev, gocan.WithEventFunc(func(e gocan.Event) {
	log.Println(e.String())
}))

Receiving frames

For a stream of frames instead of a one-shot Recv, create a subscription filtered on zero or more CAN IDs (no IDs = all traffic):

sub := c.Subscribe(ctx, 0x238, 0x258)
defer sub.Close()
for frame := range sub.Chan() {
	log.Printf("%03X %X", frame.Identifier, frame.Data)
}

SubscribeFunc runs a callback per frame instead, and SubscribeChan feeds a channel you own:

sub := c.SubscribeFunc(ctx, func(f *gocan.CANFrame) {
	log.Printf("%03X %X", f.Identifier, f.Data)
}, 0x238)
defer sub.Close()

Request / response

SendAndWait sends a frame and blocks until a frame with one of the given IDs arrives (or the timeout/context fires) — the everyday primitive for ECU protocols:

frame := gocan.NewFrame(0x005, []byte{0xC9, 0, 0, 0, 0, 0, 0, 0}, gocan.ResponseRequired)
resp, err := c.SendAndWait(ctx, frame, 1*time.Second, 0x00C)
Frame types

Every frame carries a CANFrameType that tells the adapter how to treat it:

  • gocan.Outgoing — fire and forget.
  • gocan.ResponseRequired — tells buffered adapters (ELM/STN family) to wait for one response frame; use ResponseRequiredWithResponses(n) when a request yields several.
  • gocan.Incoming — frames received from the bus.
Synchronous sends

Send / SendFrame only queue a frame into the adapter's send buffer. When you need to know the frame has actually been written to the hardware (e.g. to pace frames against a slow ECU without guessing at sleeps), use SendSync:

err := c.SendSync(ctx, frame, 100*time.Millisecond)

It blocks until the adapter confirms the write, the context is cancelled or the timeout fires. Adapters that confirm write-completion report it via SupportsSync(); on adapters that don't, SendSync degrades to a plain SendFrame.

Errors and lifecycle

The client owns the adapter: c.Close() shuts both down. If the adapter dies on its own (unplugged USB, fatal driver error), the client's context is cancelled — c.Done() / c.Err() / c.Wait(ctx) let you observe that:

go func() {
	<-c.Done()
	log.Println("bus gone:", c.Err())
}()

Non-fatal adapter noise (status messages, recoverable errors) is delivered as Events via WithEventFunc/WithEventChan options or c.OnEvent(fn) at any time.

Writing your own adapter

Implement the gocan.Adapter interface (embed gocan.BaseAdapter for the channel plumbing) and register it with gocan.RegisterAdapter from an init(). If your send path can confirm that a frame has been written to the hardware, construct with NewSyncBaseAdapter and call frame.markSent() on every exit path of the send routine — that enables SendSync for your adapter. adapter_template.go is a minimal starting point.

Showcase

Supported Adapters

USB Serial
d2xx based FTDI adapters

these adapters can be accessible directly using the d2xx api from FTDI

libusb
  • CombiAdapter
Canusb DLL

Supported via goCANUSB

Lawicel canusbdrv.dll for both 32 and 64bit is supported

Kvaser Canlib

Supported via goCANlib, Tested with the following adapters

J2534

Support for both 32 & 64bit DLL's. Your GOARCH will controll which DLL it will look for.

Do note that not all vendors provide 64bit DLL's so you migh need to build your software with GOARCH=386 to be able to use the j2534 DLL. I've made a experimental CAN gateway that can be accessed over gRCP on linux or named pipes on windows to be able to use 32bit DLL's on 64bit systems. See goCANGateway

Most adapters that comes with a J2534 DLL will work. The list given is just ones verified to work.

Windows
Linux
Other
  • SocketCAN, note. to run from user space set cap_net_admin for target application sudo setcap cap_net_admin=eip APPNAME
  • OBDX Pro GT BLE & Wifi
  • Combiadapter via libusb

Documentation

Overview

Package gocan is a CAN bus client library with interchangeable hardware adapter backends: ELM327/STN serial dongles, SocketCAN, J2534 passthru devices, Kvaser, PCAN, CombiAdapter and more.

A Client is created with New (adapter looked up by registry name, see ListAdapterNames) or NewWithOpts (adapter constructed by the caller):

c, err := gocan.New(ctx, "ELM327", &gocan.AdapterConfig{Port: "COM3", CANRate: 500})

Frames are sent with Send, SendFrame, SendAndWait (request/response) and SendSync (blocks until the frame reaches the hardware). Frames are received one-shot with Recv or streamed with Subscribe, SubscribeFunc and SubscribeChan, filtered on CAN identifiers.

Frame ownership

Outgoing frames are single-use: send methods attach per-send state to the frame, so build a fresh frame for every send. Frames received from the bus are shared by every matching subscriber and must be treated as read-only, including the Data slice.

Lifecycle

The Client owns its adapter. Close shuts both down. If the adapter fails fatally the client's context is cancelled: Done, Err and Wait report the failure, and every registered event listener receives a final EventTypeFatal event. Recoverable adapter noise is delivered as Events via the WithEventFunc, WithEventChan and WithLogger options or OnEvent.

Some backends require build tags (combi, j2534, canlib, canusb, pcan, ftdi); see the README for the full matrix and supported hardware.

Index

Constants

View Source
const (
	ELM327_OK      = "OK\r\r"
	ELM327_UNKNOWN = "?\r\r"
)
View Source
const (
	OBDLinkSX = "OBDLink SX"
	OBDLinkEX = "OBDLink EX"
	STN1170   = "STN1170"
	STN2120   = "STN2120"
)
View Source
const (
	SystemMsg uint32 = 0x80000000 + iota
	SystemMsgError
	SystemMsgUnrecoverableError
	SystemMsgWBLReading
	SystemMsgDataResponse
	SystemMsgDataRequest
	SystemMsgWriteResponse
	SystemMsgUnknown
)

We have 3 bits allowing 8 different system messages hidden in a 29bit can id stored in a uint32

Variables

View Source
var (
	Incoming         = CANFrameType{Type: ResponseTypeIncoming, Responses: 0}
	Outgoing         = CANFrameType{Type: ResponseTypeOutgoing, Responses: 0}
	ResponseRequired = CANFrameType{Type: ResponseTypeResponseRequired, Responses: 1} // Used for ELM and STN adapters to signal we want the adapter to wait for a response
)

Treat these as constants; mutating them affects every user in the process.

View Source
var (
	// ErrDroppedFrame is raised as an error event by adapters when an incoming
	// frame had to be dropped because the receive buffer was full.
	ErrDroppedFrame = errors.New("adapter incoming channel full")

	// ErrResponseChannelClosed is returned when a wait ended because the
	// subscription's delivery channel was closed.
	ErrResponseChannelClosed = errors.New("response channel closed")

	// Deprecated: use ErrResponseChannelClosed.
	ErrResponsechannelClosed = ErrResponseChannelClosed
)
View Source
var ErrClosed = errors.New("gocan: client closed")

ErrClosed is the context cause set when a client is shut down via Close. It is reported as a clean shutdown (Client.Err returns nil) rather than a fatal error.

Functions

func CANUSBAccept11 added in v1.0.7

func CANUSBAccept11(ids []uint32) (ac, am [4]byte, err error)

func CANUSBCmds11 added in v1.0.7

func CANUSBCmds11(ids []uint32) (mCmd, maskCmd string, err error)

Helper to produce the actual CANUSB ASCII commands for 11-bit IDs. Example output for ids 0x300..0x3FF:

M00006000
m00001FF0

func ListAdapterNames added in v1.0.7

func ListAdapterNames() []string

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

func NewGRPCClient added in v1.0.7

func NewGRPCClient() (*grpc.ClientConn, proto.GocanClient, error)

func NewScantoolVCP added in v1.0.7

func NewScantoolVCP(name string) func(cfg *AdapterConfig) (Adapter, error)

func NewTxbridge added in v1.0.7

func NewTxbridge(name string) func(cfg *AdapterConfig) (Adapter, error)

func RegisterAdapter added in v1.0.7

func RegisterAdapter(adapter *AdapterInfo) error

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

func SetLatencyTimer added in v1.3.4

func SetLatencyTimer(device string, latency int) error

Types

type ADCCapable added in v1.0.7

type ADCCapable interface {
	GetADCValue(ctx context.Context, channel int) (float64, error)
}

ADCCapable is implemented by adapters that expose analog inputs (e.g. the CombiAdapter's ADC channels).

type Adapter

type Adapter interface {
	Name() string
	Open(context.Context) error
	Close() error
	Send() chan<- *CANFrame
	Recv() <-chan *CANFrame
	Err() <-chan error
	Event() <-chan Event
}

Adapter is a hardware (or virtual) CAN interface backend. The Client owns the adapter: it drains Recv, Err and Event and feeds Send. Implementations deliver incoming frames on Recv, report recoverable problems on Event and signal an unrecoverable failure on Err, which terminates the client.

func NewAdapter added in v1.0.7

func NewAdapter(adapterName string, cfg *AdapterConfig) (Adapter, error)

NewAdapter constructs a registered adapter by name without opening it. Use ListAdapterNames to discover what is available in this build.

func NewCanusbVCP added in v1.0.7

func NewCanusbVCP(cfg *AdapterConfig) (Adapter, error)

func NewDrewtech added in v1.3.4

func NewDrewtech(cfg *AdapterConfig) (Adapter, error)

func NewELM327 added in v1.0.7

func NewELM327(cfg *AdapterConfig) (Adapter, error)

func NewJust4Trionic added in v1.0.7

func NewJust4Trionic(cfg *AdapterConfig) (Adapter, error)

func NewMock added in v1.0.7

func NewMock(name string, cfg *AdapterConfig) (Adapter, error)

Create a new Mock adapter used for testing. Frames written to Send() are echoed back on Recv() as Incoming frames.

func NewOBDXProWifi added in v1.0.7

func NewOBDXProWifi(cfg *AdapterConfig) (Adapter, error)

func NewSLCan added in v1.0.7

func NewSLCan(cfg *AdapterConfig) (Adapter, error)

func NewTemplate added in v1.0.7

func NewTemplate(name string, cfg *AdapterConfig) (Adapter, error)

func NewYACA added in v1.0.7

func NewYACA(cfg *AdapterConfig) (Adapter, error)

type AdapterCapabilities added in v1.0.7

type AdapterCapabilities struct {
	HSCAN bool
	SWCAN bool
	KLine bool
}

func (*AdapterCapabilities) String added in v1.0.7

func (a *AdapterCapabilities) String() string

type AdapterConfig

type AdapterConfig struct {
	Debug            bool              // enable debug logging
	Port             string            // port name or path to dll/so/dylib
	PortBaudrate     int               // port baudrate in bps (only used for serial based adapters)
	CANRate          float64           // CAN bus rate in kbit/s
	CANFilter        []uint32          // CAN ID filters
	UseExtendedID    bool              // only used for j2534 when setting upp frame filters
	PrintVersion     bool              // print adapter version info on open
	AdditionalConfig map[string]string // Key value pairs for adapter specific configuration
}

AdapterConfig holds settings applied when an adapter is opened. Not every field applies to every adapter; the comments note the main consumers.

type AdapterInfo added in v1.0.7

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

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

func ListAdapters added in v1.0.7

func ListAdapters() []AdapterInfo

ListAdapters returns a copy of every registered adapter's info.

func (*AdapterInfo) String added in v1.0.7

func (a *AdapterInfo) String() string

type BaseAdapter added in v1.0.7

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

func NewBaseAdapter added in v1.0.7

func NewBaseAdapter(name string, cfg *AdapterConfig) *BaseAdapter

func NewSyncBaseAdapter added in v1.4.7

func NewSyncBaseAdapter(name string, cfg *AdapterConfig) *BaseAdapter

NewSyncBaseAdapter is NewBaseAdapter for adapters that call markSent after writing each frame to hardware, enabling Client.SendSync (see SupportsSync).

func (*BaseAdapter) Close added in v1.0.7

func (base *BaseAdapter) Close()

func (*BaseAdapter) Debug added in v1.0.7

func (base *BaseAdapter) Debug(debug string)

Debug emits a debug event.

func (*BaseAdapter) Err added in v1.0.7

func (base *BaseAdapter) Err() <-chan error

Err returns the channel a fatal adapter error is reported on.

func (*BaseAdapter) Error added in v1.0.7

func (base *BaseAdapter) Error(err error)

Error emits a recoverable error as an event.

func (*BaseAdapter) Event added in v1.0.7

func (base *BaseAdapter) Event() <-chan Event

func (*BaseAdapter) Fatal added in v1.0.7

func (base *BaseAdapter) Fatal(err error)

Fatal reports an unrecoverable adapter error: communication is broken and the client will terminate. Only the first call has any effect.

func (*BaseAdapter) Info added in v1.0.7

func (base *BaseAdapter) Info(info string)

Info emits an informational event.

func (*BaseAdapter) Name added in v1.0.7

func (base *BaseAdapter) Name() string

Name returns the adapter name.

func (*BaseAdapter) Recv added in v1.0.7

func (base *BaseAdapter) Recv() <-chan *CANFrame

Recv returns the channel incoming frames are delivered on.

func (*BaseAdapter) Send added in v1.0.7

func (base *BaseAdapter) Send() chan<- *CANFrame

Send returns the channel the client queues outgoing frames on.

func (*BaseAdapter) SupportsSync added in v1.4.7

func (base *BaseAdapter) SupportsSync() bool

SupportsSync reports whether this adapter confirms frame write-completion (i.e. calls markSent), which Client.SendSync relies on.

func (*BaseAdapter) Warn added in v1.0.7

func (base *BaseAdapter) Warn(warn string)

Warn emits a warning event.

type CANFrame

type CANFrame struct {
	Identifier uint32
	Extended   bool
	RTR        bool
	Data       []byte
	FrameType  CANFrameType
	// Timeout in milliseconds is a hint for buffered adapters waiting on a
	// response. It is stamped by Client.SendAndWait.
	Timeout uint32
	// contains filtered or unexported fields
}

CANFrame is a single CAN bus frame.

Frames are single-use: the send methods attach per-send state (SendAndWait stamps Timeout, SendSync installs a completion signal), so build a fresh frame for every send instead of reusing one, especially across goroutines. Frames received from the bus are shared by every matching subscriber and must be treated as read-only, including the Data slice.

func NewExtendedFrame added in v1.0.7

func NewExtendedFrame(identifier uint32, data []byte, frameType CANFrameType) *CANFrame

NewExtendedFrame creates a new 29-bit CANFrame and copies the data slice.

func NewFrame

func NewFrame(identifier uint32, data []byte, frameType CANFrameType) *CANFrame

NewFrame creates a new CANFrame and copies the data slice.

func (*CANFrame) DLC added in v1.0.7

func (f *CANFrame) DLC() int

DLC returns the length of the data.

func (*CANFrame) String

func (f *CANFrame) String() string

type CANFrameType

type CANFrameType struct {
	Type      ResponseType
	Responses int
}

CANFrameType tells the adapter how to treat an outgoing frame: fire and forget (Outgoing) or, on buffered adapters like the ELM/STN family, wait for Responses response frames (ResponseRequired).

func ResponseRequiredWithResponses added in v1.0.7

func ResponseRequiredWithResponses(responses int) CANFrameType

ResponseRequiredWithResponses is ResponseRequired for commands that yield more than one response frame.

type CanusbVCP added in v1.0.7

type CanusbVCP struct {
	*BaseAdapter
	// contains filtered or unexported fields
}

func (*CanusbVCP) Close added in v1.0.7

func (cu *CanusbVCP) Close() error

func (*CanusbVCP) Open added in v1.0.7

func (cu *CanusbVCP) Open(ctx context.Context) error

func (*CanusbVCP) SetFilter added in v1.0.7

func (cu *CanusbVCP) SetFilter(filters []uint32) error

SetFilter reconfigures the SJA1000 acceptance filter at runtime. The channel must be closed to set M/m, so we bounce C -> M -> m -> O.

type Client

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

func New added in v1.0.7

func New(ctx context.Context, adapterName string, cfg *AdapterConfig) (*Client, error)

New creates a CAN client using the named adapter from the registry (see ListAdapterNames) opened with the given config.

func NewWithOpts

func NewWithOpts(ctx context.Context, adapter Adapter, opts ...Opt) (*Client, error)

NewWithOpts creates a CAN client around an already-constructed adapter and opens it. Options can register event listeners before the adapter starts.

func (*Client) Adapter

func (c *Client) Adapter() Adapter

Adapter returns the underlying adapter.

func (*Client) AdapterName added in v1.0.7

func (c *Client) AdapterName() string

AdapterName returns the name of the underlying adapter.

func (*Client) Close

func (c *Client) Close() (err error)

Close shuts down the client and the underlying adapter.

func (*Client) Context added in v1.4.1

func (c *Client) Context() context.Context

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

func (*Client) Done added in v1.4.1

func (c *Client) Done() <-chan struct{}

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

func (*Client) Err

func (c *Client) Err() error

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

func (*Client) OnEvent added in v1.4.1

func (c *Client) 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 (*Client) Recv added in v1.0.7

func (c *Client) Recv(ctx context.Context, timeout time.Duration, identifiers ...uint32) (*CANFrame, error)

Recv waits up to timeout for a single frame carrying one of the given identifiers (no identifiers = any frame).

func (*Client) Send

func (c *Client) Send(identifier uint32, data []byte, f CANFrameType) error

Send builds and queues a standard 11-bit frame.

func (*Client) SendAndWait

func (c *Client) SendAndWait(ctx context.Context, frame *CANFrame, timeout time.Duration, identifiers ...uint32) (*CANFrame, error)

SendAndWait sends frame and waits up to timeout for a reply carrying one of the given identifiers. It stamps frame.Timeout as a hint for buffered adapters; frames are single-use and must not be sent again.

func (*Client) SendExtended added in v1.0.7

func (c *Client) SendExtended(identifier uint32, data []byte, f CANFrameType) error

SendExtended builds and queues an extended 29-bit frame.

func (*Client) SendFrame

func (c *Client) SendFrame(msg *CANFrame) error

SendFrame queues a frame to the adapter's send buffer. It returns once the frame is queued, not when it reaches the bus; use SendSync for that.

func (*Client) SendSync added in v1.4.7

func (c *Client) SendSync(ctx context.Context, frame *CANFrame, timeout time.Duration) error

SendSync sends a frame and blocks until the adapter has written it to the hardware (or ctx / timeout fires). This gives natural inter-frame pacing that plain async Send does not, since Send only queues into the adapter buffer. On adapters that don't confirm write-completion it degrades to a plain Send.

func (*Client) Subscribe

func (c *Client) Subscribe(ctx context.Context, identifiers ...uint32) *Subscriber

Subscribe returns a Subscriber receiving frames that carry one of the given identifiers (no identifiers = all traffic). The subscription is released and its channel closed when ctx is cancelled or Close is called.

func (*Client) SubscribeChan

func (c *Client) SubscribeChan(ctx context.Context, channel chan *CANFrame, identifiers ...uint32) *Subscriber

SubscribeChan delivers frames carrying one of the given identifiers to channel. The caller owns the channel: the library never closes it, and delivery is non-blocking, so frames are dropped if it is full. The subscription is released when ctx is cancelled or Close is called.

func (*Client) SubscribeFunc

func (c *Client) SubscribeFunc(ctx context.Context, fn func(*CANFrame), identifiers ...uint32) *Subscriber

SubscribeFunc invokes fn from a dedicated goroutine for every frame carrying one of the given identifiers, until ctx is cancelled or the returned Subscriber is closed.

func (*Client) Wait

func (c *Client) Wait(ctx context.Context) error

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

type Drewtech added in v1.3.4

type Drewtech struct {
	*BaseAdapter
	// contains filtered or unexported fields
}

Drewtech adapts the native Mongoose Pro GM II client (pkg/drewtech) to the gocan Adapter interface.

func (*Drewtech) Close added in v1.3.4

func (a *Drewtech) Close() error

func (*Drewtech) Open added in v1.3.4

func (a *Drewtech) Open(ctx context.Context) error

func (*Drewtech) SetFilter added in v1.3.4

func (a *Drewtech) SetFilter(filters []uint32) error

SetFilter replaces the installed PASS filters. A filter per CAN id is required: with none installed the device forwards nothing.

type ELM327 added in v1.0.7

type ELM327 struct {
	*BaseAdapter
	// contains filtered or unexported fields
}

func (*ELM327) Close added in v1.0.7

func (el *ELM327) Close() error

func (*ELM327) Open added in v1.0.7

func (el *ELM327) Open(ctx context.Context) error

type Event added in v1.0.7

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

func (Event) IsFatal added in v1.4.1

func (e Event) IsFatal() bool

IsFatal reports whether the event signals an unrecoverable adapter failure.

func (Event) Raw added in v1.0.7

func (e Event) Raw() string

Returns the raw details of the event.

func (Event) String added in v1.0.7

func (e Event) String() string

Returns a formatted string representation of the event.

type EventType added in v1.0.7

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

func (EventType) Level added in v1.4.1

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 added in v1.0.7

func (et EventType) String() string

type GWClient added in v1.0.7

type GWClient struct {
	*BaseAdapter
	// contains filtered or unexported fields
}

func NewGWClient added in v1.0.7

func NewGWClient(adapterName string, cfg *AdapterConfig) (*GWClient, error)

func (*GWClient) Close added in v1.0.7

func (c *GWClient) Close() error

func (*GWClient) Open added in v1.0.7

func (c *GWClient) Open(gctx context.Context) error

func (*GWClient) SetFilter added in v1.0.7

func (c *GWClient) SetFilter([]uint32) error

type Just4Trionic added in v1.0.7

type Just4Trionic struct {
	*BaseAdapter
	// contains filtered or unexported fields
}

func (*Just4Trionic) Close added in v1.0.7

func (a *Just4Trionic) Close() error

func (*Just4Trionic) Open added in v1.0.7

func (a *Just4Trionic) Open(ctx context.Context) error

func (*Just4Trionic) SetFilter added in v1.0.7

func (a *Just4Trionic) SetFilter(filters []uint32) error

type Mock added in v1.0.7

type Mock struct {
	*BaseAdapter
}

func (*Mock) Close added in v1.0.7

func (v *Mock) Close() error

func (*Mock) Open added in v1.0.7

func (v *Mock) Open(ctx context.Context) error

type OBDXProWifi added in v1.0.7

type OBDXProWifi struct {
	*BaseAdapter
	// contains filtered or unexported fields
}

func (*OBDXProWifi) Close added in v1.0.7

func (a *OBDXProWifi) Close() error

func (*OBDXProWifi) Open added in v1.0.7

func (a *OBDXProWifi) Open(ctx context.Context) error

func (*OBDXProWifi) SetFilter added in v1.0.7

func (a *OBDXProWifi) SetFilter(filters []uint32) error

type Opt added in v1.0.7

type Opt func(*Client)

func WithEventChan added in v1.4.1

func WithEventChan(ch chan<- Event) Opt

WithEventChan forwards every adapter event to ch. Sends are non-blocking: if ch is full the event is dropped, so size the buffer for your consumer. The channel is never closed by the client; range with a select on Client.Done.

func WithEventFunc added in v1.4.1

func WithEventFunc(fn func(Event)) Opt

WithEventFunc registers fn as a synchronous event handler. It is called in order, from a single goroutine, for every adapter event (including the final fatal event). Keep it quick; a slow handler delays subsequent events.

func WithEventHandler deprecated added in v1.0.7

func WithEventHandler(fn func(Event)) Opt

Deprecated: use WithEventFunc. Retained for backwards compatibility; note the callback is now invoked synchronously and in order rather than per-goroutine.

func WithLogger added in v1.4.1

func WithLogger(l *slog.Logger) Opt

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

type ResponseType added in v1.0.7

type ResponseType int
const (
	ResponseTypeIncoming         ResponseType = 0
	ResponseTypeOutgoing         ResponseType = 1
	ResponseTypeResponseRequired ResponseType = 2 // Used for ELM and STN adapters to signal we want the adapter to wait for a response
)

type SLCan added in v1.0.7

type SLCan struct {
	*BaseAdapter
	// contains filtered or unexported fields
}

func (*SLCan) Close added in v1.0.7

func (sl *SLCan) Close() error

func (*SLCan) Open added in v1.0.7

func (sl *SLCan) Open(ctx context.Context) error

func (*SLCan) SetFilter added in v1.0.7

func (sl *SLCan) SetFilter(filters []uint32) error

type ScantoolVCP added in v1.0.7

type ScantoolVCP struct {
	*BaseAdapter
	// contains filtered or unexported fields
}

func (*ScantoolVCP) Close added in v1.0.7

func (stn *ScantoolVCP) Close() error

func (*ScantoolVCP) Open added in v1.0.7

func (stn *ScantoolVCP) Open(ctx context.Context) error

func (*ScantoolVCP) SetFilter added in v1.0.7

func (stn *ScantoolVCP) SetFilter(filters []uint32) error

type Subscriber added in v1.0.7

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

Subscriber receives CAN frames matching a set of identifiers. Create one with Client.Subscribe, Client.SubscribeFunc or Client.SubscribeChan and release it with Close.

func (*Subscriber) Chan added in v1.0.7

func (s *Subscriber) Chan() <-chan *CANFrame

Chan returns the channel frames are delivered on.

func (*Subscriber) Close added in v1.0.7

func (s *Subscriber) Close()

Close unregisters the subscriber. If the delivery channel was created by the library it is closed, ending any range over Chan. Close is safe to call multiple times and is also invoked automatically when the context given at subscription time is cancelled.

type Template added in v1.0.7

type Template struct {
	*BaseAdapter
}

func (*Template) Close added in v1.0.7

func (a *Template) Close() error

func (*Template) Open added in v1.0.7

func (a *Template) Open(ctx context.Context) error

func (*Template) SetFilter added in v1.0.7

func (a *Template) SetFilter(filters []uint32) error

type TimeoutError added in v1.0.7

type TimeoutError struct {
	Timeout time.Duration
	Frames  []uint32
	Type    string // operation that timed out, e.g. "send"
}

TimeoutError is returned when a send or receive operation times out.

func (*TimeoutError) Error added in v1.0.7

func (e *TimeoutError) Error() string

type Txbridge added in v1.0.7

type Txbridge struct {
	*BaseAdapter
	// contains filtered or unexported fields
}

func (*Txbridge) Close added in v1.0.7

func (tx *Txbridge) Close() error

func (*Txbridge) Open added in v1.0.7

func (tx *Txbridge) Open(ctx context.Context) error

func (*Txbridge) SetFilter added in v1.0.7

func (tx *Txbridge) SetFilter(filters []uint32) error

SetFilter installs the adapter's dynamic whitelist: only frames whose ID is listed are forwarded over the link (the KWP IDs the firmware handles itself are always passed). Can be called at any time. An empty list is a no-op so the firmware keeps its boot default whitelist rather than going silent.

type YACA added in v1.0.7

type YACA struct {
	*BaseAdapter
	// contains filtered or unexported fields
}

func (*YACA) Close added in v1.0.7

func (ya *YACA) Close() error

func (*YACA) Open added in v1.0.7

func (ya *YACA) Open(ctx context.Context) error

func (*YACA) SetFilter added in v1.0.7

func (ya *YACA) SetFilter(filters []uint32) error

Directories

Path Synopsis
cmd
testsuite command
examples
list_adapters command
passthru command
pingpong/client command
pingpong/server command
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
gmlan
see GMW3110 gmw3110-2010.pdf
see GMW3110 gmw3110-2010.pdf
pcan/cmd command
w32

Jump to

Keyboard shortcuts

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