Documentation
¶
Overview ¶
Package csms implements the OCPP Central System (CSMS / server) side.
Index ¶
- func Call[Req, Resp any](ctx context.Context, c *Conn, m ocppj.Message[Req, Resp], req Req) (Resp, error)
- func CallAsync[Req, Resp any](ctx context.Context, c *Conn, m ocppj.Message[Req, Resp], req Req, ...) error
- func CallRaw(ctx context.Context, c *Conn, action string, payload []byte) ([]byte, error)
- func CallRawAsync(ctx context.Context, c *Conn, action string, payload []byte, ...) error
- func On[Req, Resp any](s *Server, m ocppj.Message[Req, Resp], ...) error
- func OnSend[Req any](s *Server, m ocppj.SendMessage[Req], ...) error
- func Send[Req any](ctx context.Context, c *Conn, m ocppj.SendMessage[Req], req Req) error
- type CPIDExtractor
- type Conn
- type DuplicatePolicy
- type Option
- func WithAsyncQueueSize(n int) Option
- func WithAuthenticator(a auth.Authenticator) Option
- func WithCPIDExtractor(extract CPIDExtractor) Option
- func WithCallTimeout(d time.Duration) Option
- func WithCheckOrigin(fn func(r *http.Request) bool) Option
- func WithCompression(m transport.CompressionMode) Option
- func WithConfigStore(s storage.ConfigStore) Option
- func WithConnectionRegistry(r storage.ConnectionRegistry) Option
- func WithDuplicatePolicy(p DuplicatePolicy) Option
- func WithGlobalConcurrencyLimit(n int) Option
- func WithInsecureSkipVerifyOrigin() Option
- func WithInstanceID(id string) Option
- func WithLenientSchema() Option
- func WithLogger(l *slog.Logger) Option
- func WithMessageRouter(r storage.MessageRouter) Option
- func WithMetrics(m observability.Metrics) Option
- func WithOnConnect(fn func(*Conn)) Option
- func WithOnDisconnect(fn func(*Conn, error)) Option
- func WithOriginPatterns(patterns ...string) Option
- func WithPath(p string) Option
- func WithRequireSignature(require bool) Option
- func WithSchemaRegistry(r *schema.Registry) Option
- func WithSerializedCalls() Option
- func WithSigner(s *signing.Signer) Option
- func WithStrictSchema(strict bool) Option
- func WithSubProtocols(p ...string) Option
- func WithTolerantSchema() Option
- func WithTracerProvider(tp trace.TracerProvider) Option
- func WithTransactionStore(s storage.TransactionStore) Option
- func WithVerifier(v *signing.Verifier) Option
- func WithWebSocketPingInterval(d time.Duration) Option
- func WithWebSocketPongWait(d time.Duration) Option
- func WithWebSocketReadTimeout(d time.Duration) Option
- func WithWriteTimeout(d time.Duration) Option
- type Server
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 ¶
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).
Types ¶
type CPIDExtractor ¶
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) RemoteAddr ¶
RemoteAddr returns the peer network address from the HTTP upgrade request.
func (*Conn) RequestHeader ¶
RequestHeader returns a copy of the HTTP upgrade request headers.
func (*Conn) Subprotocol ¶
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.
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
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 ¶
WithCallTimeout sets the per-call timeout.
func WithCheckOrigin ¶ added in v0.1.5
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 ¶
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 ¶
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 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
WithOnConnect registers a callback fired after a charge point connection is accepted.
func WithOnDisconnect ¶ added in v0.1.2
WithOnDisconnect registers a callback fired after a charge point connection drops.
func WithOriginPatterns ¶ added in v0.1.5
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 WithRequireSignature ¶ added in v0.1.7
WithRequireSignature rejects inbound signed messages that fail verification.
func WithSchemaRegistry ¶
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
WithSigner signs outbound CSMS->CP CALL/SEND messages (OCPP 2.1 Signed Messages).
func WithStrictSchema ¶
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 ¶
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
WithVerifier verifies inbound signed CP->CSMS messages.
func WithWebSocketPingInterval ¶
WithWebSocketPingInterval sets the transport ping interval.
func WithWebSocketPongWait ¶ added in v0.1.2
WithWebSocketPongWait sets the transport pong timeout.
func WithWebSocketReadTimeout ¶ added in v0.1.6
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 ¶
WithWriteTimeout sets the per-write timeout.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is an OCPP CSMS (central system).
func (*Server) Close ¶
func (s *Server) Close()
Close shuts down the server and all connections immediately.
func (*Server) ListenAndServe ¶
ListenAndServe starts an HTTP server on addr.
func (*Server) Shutdown ¶ added in v0.1.5
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.