csms

package
v0.1.7 Latest Latest
Warning

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

Go to latest
Published: Jun 18, 2026 License: MIT Imports: 21 Imported by: 0

Documentation

Overview

Package csms implements the OCPP Central System (CSMS / server) side.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Call

func Call[Req, Resp any](ctx context.Context, c *Conn, m ocppj.Message[Req, Resp], req Req) (Resp, error)

Call sends a typed message to a connected charge point and returns the response.

func CallAsync added in v0.1.3

func CallAsync[Req, Resp any](ctx context.Context, c *Conn, m ocppj.Message[Req, Resp], req Req, cb func(Resp, error)) error

CallAsync sends a typed message to a connected charge point without blocking and delivers the typed response (or error) to cb. With WithSerializedCalls the calls are queued FIFO and sent one outstanding at a time; otherwise they run concurrently. It returns synchronously only if the call could not be accepted (e.g. ocppj.ErrQueueFull, ocppj.ErrConnClosed). See dispatcher.DoCallAsync.

func CallRaw

func CallRaw(ctx context.Context, c *Conn, action string, payload []byte) ([]byte, error)

CallRaw sends an action with a raw JSON payload to a connected charge point and returns the raw response. Used by tools/tests that operate on untyped messages (the typed Call is preferred for application code).

func CallRawAsync added in v0.1.3

func CallRawAsync(ctx context.Context, c *Conn, action string, payload []byte, cb func([]byte, error)) error

CallRawAsync is the untyped form of CallAsync.

func On

func On[Req, Resp any](s *Server, m ocppj.Message[Req, Resp], h func(ctx context.Context, c *Conn, req Req) (Resp, error)) error

On registers a typed handler for an inbound message (sent by the charge point).

func OnSend added in v0.1.7

func OnSend[Req any](s *Server, m ocppj.SendMessage[Req], h func(ctx context.Context, c *Conn, req Req) error) error

OnSend registers a typed handler for an OCPP 2.1 SEND a CSMS receives.

func Send added in v0.1.7

func Send[Req any](ctx context.Context, c *Conn, m ocppj.SendMessage[Req], req Req) error

Send sends a typed OCPP 2.1 SEND from the CSMS to a connected charge point.

Types

type CPIDExtractor

type CPIDExtractor func(r *http.Request) (cpID string, ok bool)

CPIDExtractor extracts the charge point id from an HTTP upgrade request.

type Conn

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

Conn is a CSMS-side connection to a charge point.

func (*Conn) ID

func (c *Conn) ID() string

ID returns the charge point identifier.

func (*Conn) RemoteAddr

func (c *Conn) RemoteAddr() string

RemoteAddr returns the peer network address from the HTTP upgrade request.

func (*Conn) RequestHeader

func (c *Conn) RequestHeader() http.Header

RequestHeader returns a copy of the HTTP upgrade request headers.

func (*Conn) Subprotocol

func (c *Conn) Subprotocol() string

Subprotocol returns the negotiated WebSocket subprotocol.

func (*Conn) TLS

func (c *Conn) TLS() *tls.ConnectionState

TLS returns a copy of the HTTP upgrade TLS connection state, if available.

func (*Conn) Version

func (c *Conn) Version() ocppj.Version

Version returns the negotiated OCPP version.

type DuplicatePolicy

type DuplicatePolicy int

DuplicatePolicy controls how the CSMS handles a second connection for the same charge point id.

const (
	// DuplicatePolicyCloseExisting closes the existing connection and accepts
	// the new one. This is the default behavior.
	DuplicatePolicyCloseExisting DuplicatePolicy = iota
	// DuplicatePolicyRejectNew rejects the incoming duplicate and keeps the
	// existing connection.
	DuplicatePolicyRejectNew
)

type Option

type Option interface {
	// contains filtered or unexported methods
}

Option configures a Server.

func WithAsyncQueueSize added in v0.1.3

func WithAsyncQueueSize(n int) Option

WithAsyncQueueSize bounds the per-connection FIFO queue used by CallAsync when WithSerializedCalls is set (default 64). Enqueuing beyond it returns ocppj.ErrQueueFull.

func WithAuthenticator

func WithAuthenticator(a auth.Authenticator) Option

WithAuthenticator sets the connection authenticator (default auth.None).

func WithCPIDExtractor

func WithCPIDExtractor(extract CPIDExtractor) Option

WithCPIDExtractor sets a custom charge point id extractor. When set, it replaces the default WithPath prefix + trailing path segment behavior. The returned id must be non-empty and must not contain a slash.

func WithCallTimeout

func WithCallTimeout(d time.Duration) Option

WithCallTimeout sets the per-call timeout.

func WithCheckOrigin added in v0.1.5

func WithCheckOrigin(fn func(r *http.Request) bool) Option

WithCheckOrigin sets a custom WebSocket origin validator. When set, the function is called for every upgrade request; returning false rejects it with 403 Forbidden, and gocpp bypasses coder/websocket's built-in origin check (the supplied function is fully responsible for the decision). Use this for logic that WithOriginPatterns can't express; otherwise prefer WithOriginPatterns.

func WithCompression added in v0.1.7

func WithCompression(m transport.CompressionMode) Option

WithCompression sets the RFC 7692 permessage-deflate mode the server offers. Defaults to transport.CompressionNoContextTakeover; pass transport.CompressionDisabled to opt out.

func WithConfigStore

func WithConfigStore(s storage.ConfigStore) Option

WithConfigStore sets the configuration store (default in-memory).

func WithConnectionRegistry

func WithConnectionRegistry(r storage.ConnectionRegistry) Option

WithConnectionRegistry sets the connection registry (default in-memory).

func WithDuplicatePolicy

func WithDuplicatePolicy(p DuplicatePolicy) Option

WithDuplicatePolicy sets how duplicate charge point connections are handled.

func WithGlobalConcurrencyLimit

func WithGlobalConcurrencyLimit(n int) Option

WithGlobalConcurrencyLimit caps the total number of inbound handlers running concurrently across all connections. This is a server-wide bound applied in addition to the per-connection handler budget; when the cap is reached, further inbound calls wait (backpressure) until a slot frees. A value <= 0 disables the global cap (the default), leaving only per-connection limits.

func WithInsecureSkipVerifyOrigin added in v0.1.5

func WithInsecureSkipVerifyOrigin() Option

WithInsecureSkipVerifyOrigin disables WebSocket origin verification entirely, accepting upgrades from any origin. This mirrors disabling the origin check in other OCPP stacks. Use with care: enabling it on a browser-reachable endpoint exposes it to cross-site WebSocket hijacking. Prefer WithOriginPatterns when you only need to allow specific origins.

func WithInstanceID

func WithInstanceID(id string) Option

WithInstanceID sets the CSMS instance identifier (multi-instance deployments).

func WithLenientSchema added in v0.1.4

func WithLenientSchema() Option

WithLenientSchema enables lenient JSON-Schema validation: structurally broken messages are rejected, while benign violations are logged and passed, and enum case mismatches are normalized to canonical values. Last-wins with WithStrictSchema / WithTolerantSchema.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger sets the structured logger.

func WithMessageRouter

func WithMessageRouter(r storage.MessageRouter) Option

WithMessageRouter sets the inter-instance message router (default no-op).

func WithMetrics

func WithMetrics(m observability.Metrics) Option

WithMetrics sets the observability metrics sink (default NoOp).

func WithOnConnect added in v0.1.2

func WithOnConnect(fn func(*Conn)) Option

WithOnConnect registers a callback fired after a charge point connection is accepted.

func WithOnDisconnect added in v0.1.2

func WithOnDisconnect(fn func(*Conn, error)) Option

WithOnDisconnect registers a callback fired after a charge point connection drops.

func WithOriginPatterns added in v0.1.5

func WithOriginPatterns(patterns ...string) Option

WithOriginPatterns lists host patterns for authorized WebSocket origins (cross-origin allowlist). The request host is always authorized. Patterns are matched per coder/websocket's AcceptOptions.OriginPatterns. Charge points are non-browser clients and usually send no Origin header (always allowed), so this is mainly relevant for browser-based clients.

func WithPath

func WithPath(p string) Option

WithPath sets the HTTP path prefix charge points connect to.

func WithRequireSignature added in v0.1.7

func WithRequireSignature(require bool) Option

WithRequireSignature rejects inbound signed messages that fail verification.

func WithSchemaRegistry

func WithSchemaRegistry(r *schema.Registry) Option

WithSchemaRegistry sets the schema registry used for first-layer validation.

func WithSerializedCalls added in v0.1.2

func WithSerializedCalls() Option

WithSerializedCalls limits outbound OCPP Calls to one outstanding request.

func WithSigner added in v0.1.7

func WithSigner(s *signing.Signer) Option

WithSigner signs outbound CSMS->CP CALL/SEND messages (OCPP 2.1 Signed Messages).

func WithStrictSchema

func WithStrictSchema(strict bool) Option

WithStrictSchema controls whether schema validation failures reject the message. Passing false turns schema validation off. If WithStrictSchema and WithTolerantSchema are both used, the last option in the list wins.

func WithSubProtocols

func WithSubProtocols(p ...string) Option

WithSubProtocols sets the offered WebSocket subprotocols (in preference order).

func WithTolerantSchema

func WithTolerantSchema() Option

WithTolerantSchema enables schema validation that logs validation failures but continues processing messages. If WithStrictSchema and WithTolerantSchema are both used, the last option in the list wins.

func WithTracerProvider

func WithTracerProvider(tp trace.TracerProvider) Option

WithTracerProvider sets the OpenTelemetry tracer provider (default no-op).

func WithTransactionStore

func WithTransactionStore(s storage.TransactionStore) Option

WithTransactionStore sets the transaction store (default in-memory).

func WithVerifier added in v0.1.7

func WithVerifier(v *signing.Verifier) Option

WithVerifier verifies inbound signed CP->CSMS messages.

func WithWebSocketPingInterval

func WithWebSocketPingInterval(d time.Duration) Option

WithWebSocketPingInterval sets the transport ping interval.

func WithWebSocketPongWait added in v0.1.2

func WithWebSocketPongWait(d time.Duration) Option

WithWebSocketPongWait sets the transport pong timeout.

func WithWebSocketReadTimeout added in v0.1.6

func WithWebSocketReadTimeout(d time.Duration) Option

WithWebSocketReadTimeout sets the read idle timeout: the connection is closed if no inbound frame (data, ping, or pong) arrives within d. 0 disables it.

func WithWriteTimeout

func WithWriteTimeout(d time.Duration) Option

WithWriteTimeout sets the per-write timeout.

type Server

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

Server is an OCPP CSMS (central system).

func NewServer

func NewServer(opts ...Option) *Server

NewServer creates a CSMS server.

func (*Server) Close

func (s *Server) Close()

Close shuts down the server and all connections immediately.

func (*Server) Get

func (s *Server) Get(id string) (*Conn, bool)

Get returns the live connection for a charge point, if connected.

func (*Server) Handler

func (s *Server) Handler() http.Handler

Handler returns the http.Handler that upgrades charge point connections.

func (*Server) ListenAndServe

func (s *Server) ListenAndServe(addr string) error

ListenAndServe starts an HTTP server on addr.

func (*Server) Shutdown added in v0.1.5

func (s *Server) Shutdown(ctx context.Context) error

Shutdown gracefully closes all live charge-point connections with a normal WebSocket close and waits for them to drain, up to the deadline of ctx. If ctx is cancelled or times out first, remaining connections are force-closed and ctx.Err() is returned. New upgrade attempts during shutdown still go through the normal accept path; stop accepting them by shutting down the HTTP server hosting Handler() before calling Shutdown.

Jump to

Keyboard shortcuts

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