A Node.js client & server implementation of the WAMP-like RPC-over-websocket system defined in the OCPP-J protcols.

Overview

OCPP-RPC

Coverage Status GitHub Workflow Status GitHub issues GitHub license GitHub stars GitHub forks

OCPP-RPC

A client & server implementation of the WAMP-like RPC-over-websocket system defined in the OCPP-J protcols (e.g. OCPP1.6J and OCPP2.0.1J).

Requires Node.js >= 17.2.0

This module is built for Node.js and does not currently work in browsers.

Who is this for?

  • Anyone building an OCPP-based Charging Station or Charging Station Management System (CSMS) using Node.js.
  • Anyone looking for a simple yet robust symmetrical RPC framework that runs over WebSockets.

Features

  • Authentication - Optional authentication step for initiating session data and filtering incoming clients.
  • Strict Validation - Optionally enforce subprotocol schemas to prevent invalid calls & responses.
  • Automatic reconnects - Client supports automatic exponential-backoff reconnects.
  • Automatic keep-alive - Regularly performs pings, and drops dangling TCP connections.
  • Serve multiple subprotocols - Simultaneously serve multiple different subprotocols from the same service endpoint.
  • HTTP Basic Auth - Easy-to-use HTTP Basic Auth compatible with OCPP security profiles 1 & 2.
  • Graceful shutdowns - Supports waiting for all in-flight messages to be responded to before closing sockets.
  • Clean closing of websockets - Supports sending & receiving WebSocket close codes & reasons.
  • Embraces abort signals - AbortSignals can be passed to most async methods.
  • Optional HTTP server - Bring your own HTTP server if you want to, or let RPCServer create one for you.

Table of Contents

Installing

npm install ocpp-rpc

Usage Examples

Barebones OCPP1.6J server

const { RPCServer, createRPCError } = require('ocpp-rpc');

const server = new RPCServer({
    protocols: ['ocpp1.6'],
    strictMode: true,
});

server.auth((accept, reject, handshake) => {
    accept({
        sessionId: 'XYZ123'
    });
});

server.on('client', async (client) => {
    console.log(`${client.session.sessionId} connected!`); // `XYZ123 connected!`

    client.handle(({method, params}) => {
        console.log(`Server got ${method} from ${client.identity}:`, params);
        throw createRPCError("NotImplemented");
    });

    client.handle('BootNotification', ({params}) => {
        console.log(`Server got BootNotification from ${client.identity}:`, params);
        return {status: "Accepted", interval: 300, currentTime: new Date().toISOString()};
    });
    
    client.handle('Heartbeat', ({params}) => {
        console.log(`Server got Heartbeat from ${client.identity}:`, params);
        return {currentTime: new Date().toISOString()};
    });
    
    client.handle('StatusNotification', ({params}) => {
        console.log(`Server got StatusNotification from ${client.identity}:`, params);
        return {};
    });
});

await server.listen(3000);

Barebones OCPP1.6J client

const { RPCClient } = require('ocpp-rpc');

const cli = new RPCClient({
    endpoint: 'ws://localhost:3000',
    identity: 'EXAMPLE',
    protocols: ['ocpp1.6'],
    strictMode: true,
});

await cli.connect();

await cli.call('BootNotification', {
    "chargePointVendor": "ocpp-rpc",
    "chargePointModel": "ocpp-rpc",
});

await cli.call('Heartbeat', {});

await cli.call('StatusNotification', {
    connectorId: 0,
    errorCode: "NoError",
    status: "Available",
});

Using with Express.js

const {RPCServer, RPCClient} = require('ocpp-rpc');
const express = require("express");

const app = express();
const httpServer = app.listen(3000, 'localhost');

const rpcServer = new RPCServer();
httpServer.on('upgrade', rpcServer.handleUpgrade);

rpcServer.on('client', client => {
    client.call('Say', `Hello, ${client.identity}!`);
});

const cli = new RPCClient({
    endpoint: 'ws://localhost:3000',
    identity: 'XYZ123'
});

cli.handle('Say', ({params}) => {
    console.log('Server said:', params);
})

cli.connect();

API Docs

Class: RPCServer

new RPCServer(options)

  • options {Object}
    • protocols {Array<String>} - Array of subprotocols supported by this server. Can be overridden in an auth callback. Defaults to [].
    • callTimeoutMs {Number} - Milliseconds to wait before unanswered outbound calls are rejected automatically. Defaults to 60000.
    • pingIntervalMs {Number} - Milliseconds between WebSocket pings to connected clients. Defaults to 30000.
    • respondWithDetailedErrors {Boolean} - Specifies whether to send detailed errors (including stack trace) to remote party upon an error being thrown by a handler. Defaults to false.
    • callConcurrency {Number} - The number of concurrent in-flight outbound calls permitted at any one time. Additional calls are queued. (There is no limit on inbound calls.) Defaults to 1.
    • strictMode {Boolean} - Enable strict validation of calls & responses. Defaults to false. (See Strict Validation to understand how this works.)
    • strictModeValidators {Array<Validator>} - Optional additional validators to be used in conjunction with strictMode. (See Strict Validation to understand how this works.)
    • maxBadMessages {Number} - The maximum number of non-conforming RPC messages which can be tolerated by the server before the client is automatically closed. Defaults to Infinity.
    • wssOptions {Object} - Additional WebSocketServer options.

Event: 'client'

  • client {RPCServerClient}

Emitted when a client has connected and been accepted. By default, a client will be automatically accepted if it connects with a matching subprotocol offered by the server (as per the protocols option in the server constructor). This behaviour can be overriden by setting an auth handler.

Event: 'error'

  • error {Error}

Emitted when the underlying WebSocketServer emits an error.

Event: 'close'

Emitted when the server has fully closed and all clients have been disconnected.

Event: 'closing'

Emitted when the server has begun closing. Beyond this point, no more clients will be accepted and the 'client' event will no longer fire.

server.auth(callback)

  • callback {Function}

Sets an authentication callback to be called before each client is accepted by the server. Setting an authentication callback is optional. By default, clients are accepted if they simply support a matching subprotocol.

The callback function is called with the following three arguments:

  • accept {Function} - A function with the signature accept([session[, protocol]]). Call this function to accept the client, causing the server to emit a 'client' event.

    • session {*} - Optional data to save as the client's 'session'. This data can later be retrieved from the session property of the client.
    • protocol {String} - Optionally explicitly set the subprotocol to use for this connection. If not set, the subprotocol will be decided automatically as the first mutual subprotocol (in order of the RPCServer constructor's protocols value). If a non mutually-agreeable subprotocol value is set, the client will be rejected instead.
  • reject {Function} - A function with the signature reject([code[, message]])

    • code {Number} - The HTTP error code to reject the upgrade. Defaults to 400.
    • message {String} - An optional message to send as the response body. Defaults to ''.
  • handshake {Object} - A handshake object

    • protocols {Set} - A set of subprotocols purportedly supported by the client.
    • identity {String} - The identity portion of the connection URL, decoded.
    • password {String} - If HTTP Basic auth was used in the connection, and the username correctly matches the identity, this field will contain the password (otherwise undefined). Read HTTP Basic Auth for more details of how this works.
    • endpoint {String} - The endpoint path portion of the connection URL. This is the part of the path before the identity.
    • query {URLSearchParams} - The query string parsed as URLSearchParams.
    • remoteAddress {String} - The remote IP address of the socket.
    • headers {Object} - The HTTP headers sent in the upgrade request.
    • request {http.IncomingMessage} - The full HTTP request received by the underlying webserver.

Example:

const rpcServer = new RPCServer();
rpcServer.auth((accept, reject, handshake) => {
    if (handshake.identity === 'TEST') {
        accept();
    } else {
        reject(401, "I don't recognise you");
    }
});

server.handleUpgrade(request, socket, head)

  • request {http.IncomingMessage}
  • socket {stream.Duplex} - Network socket between the server and client
  • head {Buffer} - The first packet of the upgraded stream (may be empty)

Converts an HTTP upgrade request into a WebSocket client to be handled by this RPCServer. This method is bound to the server instance, so it is suitable to pass directly as an http.Server's 'upgrade' event handler.

This is typically only needed if you are creating your own HTTP server. HTTP servers created by listen() have their 'upgrade' event attached to this method automatically.

Example:

const rpcServer = new RPCServer();
const httpServer = http.createServer();
httpServer.on('upgrade', rpcServer.handleUpgrade);

server.reconfigure(options)

  • options {Object}

Use this method to change any of the options that can be passed to the RPCServer's constructor.

server.listen([port[, host[, options]]])

  • port {Number} - The port number to listen on. If not set, the operating system will assign an unused port.
  • host {String} - The host address to bind to. If not set, connections will be accepted on all interfaces.
  • options {Object}
    • signal {AbortSignal} - An AbortSignal used to abort the listen() call of the underlying net.Server.

Creates a simple HTTP server which only accepts websocket upgrades and returns a 404 response to any other request.

Returns a Promise which resolves to an instance of http.Server or rejects with an Error on failure.

server.close([options])

  • options {Object}
    • code {Number} - The WebSocket close code to pass to all connected clients. Defaults to 1000.
    • reason {String} - The reason for closure to pass to all connected clients. Defaults to ''.
    • awaitPending {Boolean} - If true, each connected client won't be fully closed until any outstanding in-flight (inbound & outbound) calls are responded to. Additional calls will be rejected in the meantime. Defaults to false.
    • force {Boolean} - If true, terminates all client WebSocket connections instantly and uncleanly. Defaults to false.

This blocks new clients from connecting, calls client.close() on all connected clients, and then finally closes any listening HTTP servers which were created using server.listen().

Returns a Promise which resolves when the server has completed closing.

Class: RPCClient

new RPCClient(options)

  • options {Object}
    • endpoint {String} - The RPC server's endpoint (a websocket URL). Required.
    • identity {String} - The RPC client's identity. Will be automatically encoded. Required.
    • protocols {Array<String>} - Array of subprotocols supported by this client. Defaults to [].
    • password {String} - Optional password to use in HTTP Basic auth. (The username will always be the identity).
    • headers {Object} - Additional HTTP headers to send along with the websocket upgrade request. Defaults to {}.
    • query {Object|String} - An optional query string or object to append as the query string of the connection URL. Defaults to ''.
    • callTimeoutMs {Number} - Milliseconds to wait before unanswered outbound calls are rejected automatically. Defaults to 60000.
    • pingIntervalMs {Number} - Milliseconds between WebSocket pings. Defaults to 30000.
    • strictMode {Boolean} - Enable strict validation of calls & responses. Defaults to false. (See Strict Validation to understand how this works.)
    • strictModeValidators {Array<Validator>} - Optional additional validators to be used in conjunction with strictMode. (See Strict Validation to understand how this works.)
    • respondWithDetailedErrors {Boolean} - Specifies whether to send detailed errors (including stack trace) to remote party upon an error being thrown by a handler. Defaults to false.
    • callConcurrency {Number} - The number of concurrent in-flight outbound calls permitted at any one time. Additional calls are queued. There is no concurrency limit imposed on inbound calls. Defaults to 1.
    • reconnect {Boolean} - If true, the client will attempt to reconnect after losing connection to the RPCServer. Only works after making one initial successful connection. Defaults to true.
    • maxReconnects {Number} - If reconnect is true, specifies the number of times to try reconnecting before failing and emitting a close event. Defaults to Infinity
    • backoff {Object} - If reconnect is true, specifies the options for an ExponentialStrategy backoff strategy, used for reconnects.
    • maxBadMessages {Number} - The maximum number of non-conforming RPC messages which can be tolerated by the client before the client is automatically closed. Defaults to Infinity.
    • wsOptions {Object} - Additional WebSocket options.

Event: 'badMessage'

  • event {Object}
    • payload {Buffer} - The raw discarded "bad" message payload.
    • error {Error} - An error describing what went wrong when handling the payload.
    • response {Array|null} - A copy of the response sent in reply to the bad message (if applicable).

This event is emitted when a "bad message" is received. A "bad message" is simply one which does not structurally conform to the RPC protocol or violates some other principle of the framework (such as a response to a call which was not made). If appropriate, the client will respond with a "RpcFrameworkError" or similar error code (depending upon the violation) as required by the spec.

(To be clear, this event will not simply be emitted upon receipt of an error response or invalid call. The message itself must actually be non-conforming to the spec to be considered "bad".)

If too many bad messages are received in succession, the client will be closed with a close code of 1002. The number of bad messages tolerated before automatic closure is determined by the maxBadMessages option. After receiving a valid (non-bad) message, the "bad message" counter will be reset.

Event: 'strictValidationFailure'

This event is emitted in strict mode when an inbound call or outbound response does not satisfy the subprotocol schema validator. See Effects of strictMode to understand what happens in response to the invalid message.

Event: 'call'

  • call {Object}
    • messageId {String} - The RPC message ID
    • outbound {Boolean} - This will be true if the call originated locally.
    • payload {Array} - The RPC call payload array.

Emitted immediately before a call request is sent, or in the case of an inbound call, immediately before the call is processed. Useful for logging or debugging.

If you want to handle (and respond) to the call, you should register a handler using client.handle() instead.

Event: 'close'

  • event {Object}
    • code {Number} - The close code received.
    • reason {String} - The reason for the connection closing.

Emitted after client.close() completes.

Event: 'closing'

Emitted when the client is closing and does not plan to reconnect.

Event: 'connecting'

Emitted when the client is trying to establish a new WebSocket connection. If sucessful, the this should be followed by an 'open' event.

Event: 'disconnect'

  • event {Object}
    • code {Number} - The close code received.
    • reason {String} - The reason for the connection closing.

Emitted when the underlying WebSocket has disconnected. If the client is configured to reconnect, this should be followed by a 'connecting' event, otherwise a 'closing' event.

Event: 'message'

  • event {Object}
    • message {Buffer|String} - The message payload.
    • outbound {Boolean} - This will be true if the message originated locally.

Emitted whenever a message is sent or received over client's WebSocket. Useful for logging or debugging.

If you want to handle (and respond) to a call, you should register a handler using client.handle() instead.

Event: 'open'

  • result {Object}
    • response {http.ServerResponse} - The response to the client's upgrade request.

Emitted when the client is connected to the server and ready to send & receive calls.

Event: 'ping'

  • event {Object}
    • rtt {Number} - The round trip time (in milliseconds) between when the ping was sent and the pong was received.

Emitted when the client has received a response to a ping.

Event: 'protocol'

  • protocol {String} - The mutually agreed websocket subprotocol.

Emitted when the client protocol has been set. Once set, this cannot change. This event only occurs once per connect().

Event: 'response'

  • response {Object}
    • outbound {Boolean} - This will be true if the response originated locally.
    • payload {Array} - The RPC response payload array.

Emitted immediately before a response request is sent, or in the case of an inbound response, immediately before the response is processed. Useful for logging or debugging.

Event: 'socketError'

  • error {Error}

Emitted when the underlying WebSocket instance fires an 'error' event.

client.identity

  • {String}

The decoded client identity.

client.state

  • {Number}

The client's state. See state lifecycle

Enum Value
CONNECTING 0
OPEN 1
CLOSING 2
CLOSED 3

client.protocol

  • {String}

The agreed subprotocol. Once connected for the first time, this subprotocol becomes fixed and will be expected upon automatic reconnects (even if the server changes the available subprotocol options).

client.reconfigure(options)

  • options {Object}

Use this method to change any of the options that can be passed to the RPCClient's constructor.

When changing identity, the RPCClient must be explicitly close()d and then connect()ed for the change to take effect.

client.connect()

The client will attempt to connect to the RPCServer specified in options.url.

Returns a Promise which will either resolve to a result object upon successfully connecting, or reject if the connection fails.

  • result {Object}
    • response {http.ServerResponse} - The response to the client's upgrade request.

client.sendRaw(message)

  • message {Array|Number|Object|String|ArrayBuffer|Buffer|DataView|TypedArray} - A raw message to send across the WebSocket.

Send arbitrary data across the websocket. Not intended for general use.

client.close([options])

  • options {Object}
    • code {Number} - The WebSocket close code. Defaults to 1000.
    • reason {String} - The reason for closure. Defaults to ''.
    • awaitPending {Boolean} - If true, the connection won't be fully closed until any outstanding in-flight (inbound & outbound) calls are responded to. Additional calls will be rejected in the meantime. Defaults to false.
    • force {Boolean} - If true, terminates the WebSocket connection instantly and uncleanly. Defaults to false.

Close the underlying connection. Unless awaitPending is true, all in-flight outbound calls will be instantly rejected and any inbound calls in process will have their signal aborted. Unless force is true, close() will wait until all calls are settled before returning the final code and reason for closure.

Returns a Promise which resolves to an Object with properties code and reason.

In some circumstances, the final code and reason returned may be different from those which were requested. For instance, if close() is called twice, the first code provided is canonical. Also, if close() is called while in the CONNECTING state during the first connect, the code will always be 1001, with the reason of 'Connection aborted'.

client.handle([method,] handler)

  • method {String} - The name of the method to be handled. If not provided, acts as a wildcard handler which will handle any call that doesn't have a more specific handler already registered.
  • handler {Function} - The function to be invoked when attempting to handle a call. Can return a Promise.

Register a call handler. Only one wildcard handler and one method-specific handler can be registered at a time. Attempting to register a handler with a duplicate method will override the former.

When the handler function is invoked, it will be passed an object with the following properties:

  • method {String} - The name of the method being invoked (useful for wildcard handlers).
  • params {*} - The params value passed to the call.
  • signal {AbortSignal} - A signal which will abort if the underlying connection is dropped (therefore, the response will never be received by the caller). You may choose whether to ignore the signal or not, but it could save you some time if you use it to abort the call early.

If the invocation of the handler resolves or returns, the resolved value will be returned to the caller. If the invocation of the handler rejects or throws, an error will be passed to the caller. By default, the error will be an instance of RPCGenericError, although additional error types are possible (see createRPCError).

client.call(method[, params[, options]])

  • method {String} - The name of the method to call.
  • params {*} - Parameters to send to the call handler.
  • options {Object}
    • callTimeoutMs {Number} - Milliseconds before unanswered call is rejected. Defaults to the same value as the option passed to the client/server constructor.
    • signal {AbortSignal} - AbortSignal to abort the call.

Calls a remote method. Returns a Promise which either:

  • resolves to the value returned by the remote handler.
  • rejects with an error.

If the underlying connection is interrupted while waiting for a response, the Promise will reject with an Error.

It's tempting to set callTimeoutMs to Infinity but this could be a mistake; If the remote handler never returns a response, the RPC communications will be blocked as soon as callConcurrency is exhausted (which is 1 by default). (While this is still an unlikely outcome when using this module for both client and server components - interoperability with real world systems can sometimes be unpredictable.)

Class: RPCServerClient : RPCClient

The RPCServerClient is a subclass of RPCClient. This represents an RPCClient from the server's perspective. It has all the same properties and methods as RPCClient but with a couple of additional properties...

client.handshake

  • {Object}
    • protocols {Set} - A set of subprotocols purportedly supported by the client.
    • identity {String} - The identity portion of the connection URL, decoded.
    • endpoint {String} - The endpoint path portion of the connection URL. This is the part of the path before the identity. Defaults to 'ws://localhost'.
    • query {URLSearchParams} - The query string parsed as URLSearchParams.
    • remoteAddress {String} - The remote IP address of the socket.
    • headers {Object} - The HTTP headers sent in the upgrade request.
    • request {http.IncomingMessage} - The full HTTP request received by the underlying webserver.

This property holds information collected during the WebSocket connection handshake.

client.session

  • {*}

This property can be anything. This is the value passed to accept() during the authentication callback.

createValidator(subprotocol, schema)

  • subprotocol {String} - The name of the subprotocol that this schema can validate.
  • schema {Array} - An array of json schemas.

Returns a Validator object which can be used for strict mode.

Class: RPCError : Error

An error representing a violation of the RPC protocol.

Throwing an RPCError from within a registered handler will pass the RPCError back to the caller.

To create an RPCError, it is recommended to use the utility method createRPCError().

err.rpcErrorCode

  • {String}

The OCPP-J RPC error code.

err.details

  • {Object}

An object containing additional error details.

createRPCError(type[, message[, details]])

  • type {String} - One of the supported error types (see below).
  • message {String} - The error's message.
  • details {Object} - The details object to pass along with the error. Defaults to {}.

This is a utility function to create a special type of RPC Error to be thrown from a call handler to return a non-generic error response.

Returns an RPCError which corresponds to the specified type:

Type Description
GenericError A generic error when no more specific error is appropriate
NotImplemented Requested method is not known
NotSupported Requested method is recognised but not supported
InternalError An internal error occurred and the receiver was not able to process the requested method successfully
ProtocolError Payload for method is incomplete
SecurityError During the processing of method a security issue occurred preventing receiver from completing the method successfully
FormationViolation Payload for the method is syntactically incorrect or not conform the PDU structure for the method
PropertyConstraintViolation Payload is syntactically correct but at least one field contains an invalid value
OccurenceConstraintViolation Payload for the method is syntactically correct but at least one of the fields violates occurence constraints
TypeConstraintViolation Payload for the method is syntactically correct but at least one of the fields violates data type constraints
MessageTypeNotSupported A message with a Message Type Number received is not supported by this implementation.
RpcFrameworkError Content of the call is not a valid RPC Request, for example: MessageId could not be read.

Strict Validation

RPC clients can operate in "strict mode", validating calls & responses according to subprotocol schemas. The goal of strict mode is to eliminate the possibility of invalid data structures being sent through RPC.

To enable strict mode, pass strictMode: true in the options to the RPCServer or RPCClient constructor. Alternately, you can limit strict mode to specific protocols by passing an array for strictMode instead. The schema ultimately used for validation is determined by whichever subprotocol is agreed between client and server.

Examples:

// enable strict mode for all subprotocols
const server = new RPCServer({
    protocols: ['ocpp1.6', 'ocpp2.0.1'],
    strictMode: true,
});
// only enable strict mode for ocpp1.6
const server = new RPCServer({
    protocols: ['ocpp1.6', 'proprietary0.1'],
    strictMode: ['ocpp1.6'],
});

Effects of strictMode

As a caller, strictMode has the following effects:

  • If your method or params fail validation, your call will reject immediately with an RPCError. The call will not be sent.
  • If a response to your call fails validation, the call will reject with an RPCError.

As a callee, strictMode has the following effects:

  • If an inbound call's params fail validation, the call will not be passed to a handler. Instead, an error response will be automatically issued to the caller with an appropriate RPC error. A 'strictValidationFailure' event will be emitted with an RPCError.
  • If your response to a call fails validation, the response will be discarded and an "InternalError" RPC error will be sent instead. A 'strictValidationFailure' event will be emitted with an RPCError.

Important: If you are using strictMode, you are strongly encouraged to listen for 'strictValidationFailure' events, otherwise you may not know if your responses or inbound calls are being dropped for failing validation.

Supported validation schemas

This module natively supports the following validation schemas:

Subprotocol
ocpp1.6
ocpp2.0.1

Adding additional validation schemas

If you want to use strictMode with a subprotocol which is not included in the list above, you will need to add the appropriate schemas yourself. To do this, you must create a Validator for each subprotocol(s) and pass them to the RPC constructor using the strictModeValidators option. (It is also possible to override the built-in validators this way.)

To create a Validator, you should pass the name of the subprotocol and a well-formed json schema to createValidator(). An example of a well-formed schema can be found at ./lib/schemas/ocpp1.6json or in the example below.

Example:

// define a validator for subprotocol 'echo1.0'
const echoValidator = createValidator('echo1.0', [
    {
        $schema: "http://json-schema.org/draft-07/schema",
        $id: "urn:Echo.req",
        type: "object",
        properties: {
            val: { type: "string" }
        },
        additionalProperties: false,
        required: ["val"]
    },
    {
        $schema: "http://json-schema.org/draft-07/schema",
        $id: "urn:Echo.conf",
        type: "object",
        properties: {
            val: { type: "string" }
        },
        additionalProperties: false,
        required: ["val"]
    }
]);

const server = new RPCServer({
    protocols: ['echo1.0'],
    strictModeValidators: [echoValidator],
    strictMode: true,
});

/*
client.call('Echo', {val: 'foo'}); // returns {val: foo}
client.call('Echo', ['bar']); // throws RPCError
*/

Once created, the Validator is immutable and can be reused as many times as is required.

HTTP Basic Auth

Usage Example

const cli = new RPCClient({
    identity: "AzureDiamond",
    password: "hunter2",
});

const server = new RPCServer();
server.auth((accept, reject, handshake) => {
    if (handshake.identity === "AzureDiamond" && handshake.password === "hunter2") {
        accept();
    } else {
        reject(401);
    }
});

await server.listen(80);
await cli.connect();

Identities containing colons

This module supports HTTP Basic auth slightly differently than how it is specified in RFC7617. In that spec, it is made clear that usernames cannot contain colons (:) as a colon is used to delineate where a username ends and a password begins.

In the context of OCPP, the basic-auth username must always be equal to the client's identity. However, since OCPP does not forbid colons in identities, this can possibly lead to a conflict and unexpected behaviours.

In practice, it's not uncommon to see violations of RFC7617 in the wild. All major browsers allow basic-auth usernames to contain colons, despite the fact that this won't make any sense to the server. RFC7617 acknowledges this fact. The prevalent solution to this problem seems to be to simply ignore it.

However, in OCPP, since we have the luxury of knowing that the username must always be equal to the client's identity, it is no longer necessary to rely upon a colon to delineate the username from the password. This module makes use of this guarantee to enable identities and passwords to contain as many or as few colons as you wish.

const cli = new RPCClient({
    identity: "this:is:ok",
    password: "as:is:this",
});

const server = new RPCServer();
server.auth((accept, reject, handshake) => {
    console.log(handshake.identity); // "this:is:ok"
    console.log(handshake.password); // "as:is:this"
    accept();
});

await server.listen(80);
await cli.connect();

If you prefer to use the more conventional (broken) way of parsing the authorization header using something like the basic-auth module, you can do that too.

const auth = require('basic-auth');

const cli = new RPCClient({
    identity: "this:is:broken",
    password: "as:is:this",
});

const server = new RPCServer();
server.auth((accept, reject, handshake) => {
    const cred = auth.parse(handshake.headers.authorization);

    console.log(cred.name); // "this"
    console.log(cred.pass); // "is:broken:as:is:this"
    accept();
});

await server.listen(80);
await cli.connect();

RPCClient state lifecycle

RPCClient state lifecycle

CLOSED

  • RPC calls while in this state are rejected.
  • RPC responses will be silently dropped.

CONNECTING

  • RPC calls & responses while in this state will be queued.

OPEN

  • Previously queued messages are sent to the server upon entering this state.
  • RPC calls & responses now flow freely.

CLOSING

  • RPC calls while in this state are rejected.
  • RPC responses will be silently dropped.

License

MIT

Comments
  • How am I able to trigger an remote start and stop?

    How am I able to trigger an remote start and stop?

    Hi @mikuso ,

    I have a question,

    I have this scenario 1 server(Websocket), 1 client(Charging Station) and an application(HTML implementation) that will trigger to the client. In ocpp-rpc what is the specific syntax that I will use in my application to trigger the action like remote start and stop that will send to my client?

    opened by rowellcodizal 9
  • Issue on the data return

    Issue on the data return

    Hi @mikuso ,

    Can you help me with my issue regarding this line of code.

    When I try this, the TransactionIdentity in the return function is always zero, even though I assign the TRANSACTIONID of the query return. Could you please assist me in resolving this? 

    var TransactionIdentity = 0
    client.handle('StartTransaction', ({params, signal, messageId}) => {
        var requestTransactionId = new sql.Request();
    
        requestTransactionId.query(`EXEC SP_EVO_CreateOrUpdate_RemoteStart '${client.identity}', ` + params.connectorId + `,'` + params.idTag + `', ` + params.meterStart + `,'` + params.timestamp + `'`, function(err,records){
            if(err) {console.log(err)}
            else {
    
                console.log(records.recordset[0])
                TransactionIdentity = records.recordset[0].TRANSACTIONID;
                
                server._clients.forEach(function each(clientrecord) {
                    if(clientrecord.identity == client.identity + 'USER' + params.connectorId){
                        clientrecord.call('StartTransactionResponse', {"timeStamp": params.timestamp})
                    }
                });
            }
        })
        const stringdata = '{"expiryDate": "2022-11-02T12:35:24Z", "parentIdTag": "", "status": "Accepted"}';
        
        return {
            "idTagInfo": JSON.parse(stringdata),
            "transactionId": TransactionIdentity
        }
    });
    
    opened by rowellcodizal 7
  • Facing Issue While calling custom method from Server and shows ProtocolError

    Facing Issue While calling custom method from Server and shows ProtocolError

    Hi @mikuso,

    I can not call custom method defined client method from server and while calling it will give me ProtocolError.

    I have two separate apps once is server and another is client on both I have installed ocpp-rpc package and also using NodeJS version 18.1.0 Now, I want to call customer method as below:

    On the Client end Say method is defined:

    const cli = new RPCClient({
        endpoint: "ws://localhost:3000",
        identity: "EXAMPLE123",
        protocols: ["ocpp1.6"],
        strictMode: true,
    });
    
    cli.handle("Say", ({ params }) => {
        console.log("Server said:", params);
    });
    

    And when I called "Say" method from Server as below, It is returning me an error and aborted both server and client.

    const server = new RPCServer({
        protocols: ['ocpp1.6'],
        strictMode: true,
    });
    
    server.on('client', async (client) => {
         await client.call("Say", `Hello, ${client.identity}!`);
    });
    

    Error as below:

    server_app\node_modules\ocpp-rpc\lib\util.js:44
       const err = new E(message ?? '');
                   ^
    
    RPCProtocolError: Schema 'urn:Say.req' is missing from subprotocol schema 'ocpp1.6'
       at createRPCError (\server_app\node_modules\ocpp-rpc\lib\util.js:44:17)
       at Validator.validate (\server_app\node_modules\ocpp-rpc\lib\validator.js:39:19)
       at RPCServerClient._call (\server_app\node_modules\ocpp-rpc\lib\client.js:287:27)
       at Queue._next (\server_app\node_modules\ocpp-rpc\lib\queue.js:39:35)
       at \server_app\node_modules\ocpp-rpc\lib\queue.js:22:18
       at new Promise (<anonymous>)
       at Queue.push (\server_app\node_modules\ocpp-rpc\lib\queue.js:15:16)
       at RPCServerClient.call (\server_app\node_modules\ocpp-rpc\lib\client.js:270:38)
       at RPCServer.<anonymous> (\server_app\app.js:50:18)
       at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
     rpcErrorMessage: 'Payload for method is incomplete',
     rpcErrorCode: 'ProtocolError',
     details: {}
    }
    

    Thanks

    opened by kvext 5
  • How to get response from server to client? When any method has been called from client?

    How to get response from server to client? When any method has been called from client?

    Hi @mikuso ,

    I used the package ocpp-rpc and have query regarding receiving response from server to client. so can you please provide your suggestion on it?

    I have created two separate folder one is for server and another is for client and install the ocpp-rpc library on both app.

    On the server end, I have already handled the method as below:

    server.on('client', async (client) => {
           await client.handle('MeterValues', ({params}) => {
            console.log(`Server got MeterValues from ${client.identity}:`, params);
            return {};
        });
    });
    

    Here, If I will return JSON object with any properties, It will not allow me and generate error on client end and aborted it. event if I will return like return { status: "Accepted" } on server end then it will show error on client as below: So, here how can we get response from server to client end? and Make sure that the method has been called successfully.

    \node_modules\ocpp-rpc\lib\util.js:44
        const err = new E(message ?? '');
                    ^
    
    RPCPropertyConstraintViolationError: data must NOT have additional properties
        at createRPCError (\client_app\node_modules\ocpp-rpc\lib\util.js:44:17)
        at Validator.validate (\client_app\node_modules\ocpp-rpc\lib\validator.js:47:19)
        at RPCClient._onCallResult (\client_app\node_modules\ocpp-rpc\lib\client.js:822:31)
        at RPCClient._onMessage (\client_app\node_modules\ocpp-rpc\lib\client.js:644:26)
        at WebSocket.<anonymous> (\client_app\node_modules\ocpp-rpc\lib\client.js:369:42)
        at WebSocket.emit (node:events:527:28)
        at Receiver.receiverOnMessage (\client_app\node_modules\ws\lib\websocket.js:1169:20)
        at Receiver.emit (node:events:527:28)
        at Receiver.dataMessage (\client_app\node_modules\ws\lib\receiver.js:528:14)
        at Receiver.getData (\client_app\node_modules\ws\lib\receiver.js:446:17) {
      rpcErrorMessage: 'Payload is syntactically correct but at least one field contains an invalid value',
      rpcErrorCode: 'PropertyConstraintViolation',
      details: {
        errors: [
          {
            instancePath: '',
            schemaPath: '#/additionalProperties',
            keyword: 'additionalProperties',
            params: { additionalProperty: 'status' },
            message: 'must NOT have additional properties'
          }
        ],
        data: { status: 'Accepted' }
      }
    }
    

    Calling the method from Client as below:

    const cli = new RPCClient({
        endpoint: "ws://localhost:3000",
        identity: "EXAMPLE123",
        protocols: ["ocpp1.6"],
        strictMode: true,
    });
    
    cli.call("MeterValues", {
        connectorId: 0,
        transactionId: 12345,
        meterValue: [
            {
                sampledValue: [
                    {
                        unit: "Celsius",
                        context: "Sample.Clock",
                        measurand: "Temperature",
                        location: "Body",
                        value: "33.8,18.6",
                    },
                ],
                timestamp: new Date().toISOString(),
            },
        ],
    });
    

    Thanks,

    opened by kvext 4
  • Error with remote command SendLocalList

    Error with remote command SendLocalList

    Hello, I have a problem with the SendLocalList command. I think my json structor is good but the function returns me an error. Here is the code of my function

     const SendLocalList = await client.call("SendLocalList", {
           "listVersion": 1,
           "localAuthorisationList": [
            {
              "idTag":"044943121F1D80",
               "idTagInfo":{
                "expiryDate":"2023-02-01T15:09:18Z",
                "parentIdTag":"",
                "status":"Accepted",
                }
             }],
            "updateType":"Full"
    });
    

    Error message:

    
      rpcErrorMessage: 'Payload is syntactically correct but at least one field contains an invalid value',
      rpcErrorCode: 'PropertyConstraintViolation',
      details: {
        errors: [
          {
            instancePath: '',
            schemaPath: '#/additionalProperties',
            keyword: 'additionalProperties',
            params: { additionalProperty: 'localAuthorisationList' },
            message: 'must NOT have additional properties'
          }
        ],
        data: {
          listVersion: 1,
          localAuthorisationList: [
            {
              idTag: '044943121F1D80',
              idTagInfo: {
                expiryDate: '2023-02-01T15:09:18Z',
                parentIdTag: '',
                status: 'Accepted'
              }
            }
          ],
          updateType: 'Full'
        }
      }
    }
    
    opened by zelix25 3
  • Example for remoteStopTransaction / remoteStartTransaction

    Example for remoteStopTransaction / remoteStartTransaction

    Hello, could you explain to me which function I must use to carry out the remoteStopTransaction / remoteStartTransaction commands via the central server? I can't figure out how it works...

    Thanks

    opened by zelix25 3
  • About strict mode and ajv

    About strict mode and ajv

    nodejs version: v18.2.0

            const server = new RPCServer({
                protocols: ['ocpp2.0.1'],
                strictMode: true,
            });
           
           // after client connected
           client.call('RequestStartTransaction', requestStartTransactionPayload);
    

    After I lauch server, I tried to call "RequestStartTransaction" request. And I got Error: strict mode: "additionalItems" is ignored when "items" is not an array of schemas. So I delete the all of "additionalItems" attirbutes in "ocpp2_0_1.json" and it works.

    I think it is because of this: https://ajv.js.org/strict-mode.html#ignored-additionalitems-keyword

    opened by alex1290 3
  • 500 Internal Server Error

    500 Internal Server Error

    Hi,

    have used both examples for Server and Client. Run Server, run Client.. Got 500 Internal Server Error!?

    Node.js v18.9.0

    How can i improve my issue ticket? I can not see anything on the console for the server-part.

    opened by RcRaCk2k 2
  • Facing Issue for RPCGenericError: Assignment to constant variable

    Facing Issue for RPCGenericError: Assignment to constant variable

    Hi @mikuso,

    Hope you're doing good!

    I am trying to call one of method "StartTransaction" from server and want to receive response from client, but I am receiving error as below:

    \node_modules\ocpp-rpc\lib\util.js:44
        const err = new E(message ?? '');
                    ^
    
    RPCGenericError: Assignment to constant variable.
        at createRPCError (D:\node_apps\node_ocpp_demo\node_modules\ocpp-rpc\lib\util.js:44:17)
        at RPCServerClient._onCallError (D:\node_apps\node_ocpp_demo\node_modules\ocpp-rpc\lib\client.js:841:25)
        at RPCServerClient._onMessage (D:\node_apps\node_ocpp_demo\node_modules\ocpp-rpc\lib\client.js:649:26)
        at WebSocket.<anonymous> (D:\node_apps\node_ocpp_demo\node_modules\ocpp-rpc\lib\client.js:369:42)
        at WebSocket.emit (node:events:527:28)
        at Receiver.receiverOnMessage (D:\node_apps\node_ocpp_demo\node_modules\ws\lib\websocket.js:1169:20)
        at Receiver.emit (node:events:527:28)
        at Receiver.dataMessage (D:\node_apps\node_ocpp_demo\node_modules\ws\lib\receiver.js:528:14)
        at Receiver.getData (D:\node_apps\node_ocpp_demo\node_modules\ws\lib\receiver.js:446:17)
        at Receiver.startLoop (D:\node_apps\node_ocpp_demo\node_modules\ws\lib\receiver.js:148:22) {
      rpcErrorMessage: '',
      rpcErrorCode: 'GenericError',
      details: {}
    }
    

    My Server Script as below:

    const app = express();
    const port = 3000;
    const httpServer = app.listen(port, "localhost");
    console.log(`OCPP Server started and listening on port ${port}...`);
    
    const server = new RPCServer({
        protocols: ["ocpp1.6"],
        strictMode: false,
    });
    httpServer.on("upgrade", server.handleUpgrade);
    
    server.auth((accept, reject, handshake) => {
        accept({
            sessionId: "XYZ123",
        });
    });
    server.on("client", async (client) => {
             client.handle(({ method, params }) => {
                    console.log(`Server got ${method} from ${client.identity}:`, params);
                throw createRPCError("NotImplemented");
            });
    
           // Server Methods
           client.handle("BootNotification", ({ params }) => {
                 console.log(
                   `Server got BootNotification from ${client.identity}:`,
                   params
                );
                 return {
                   status: "Accepted",
                   interval: 300,
                   currentTime: new Date().toISOString(),
                };
           });
        
             let resTrans = await client.call("StartTransaction", {
                connectorId: 0,
                idTag: "50-D6-BF-1A-D6-CC",
                meterStart: 20,
                timestamp: new Date().toISOString(),
            });
            console.log("Start Transaction Response: ", resTrans);
    });
    

    Client Script as below:

    const app = express();
    const httpServer = app.listen(3001, "localhost");
    
    async function main() {
        const cli = new RPCClient({
            endpoint: "ws://localhost:3000",
            identity: "EXAMPLE123",
            protocols: ["ocpp1.6"],
            strictMode: false,
        });
        
        const transactionId = 0;
        
        cli.handle("StartTransaction", async ({ params }) => {
            if (params.idTag === "50-D6-BF-1A-D6-CC") {
                transactionId = Math.floor(Math.random() * 999999);
                return {
                    idTagInfo: { status: "Accepted" },
                    transactionId: transactionId,
                };
            } else {
                return { idTagInfo: { status: "Invalid" }, transactionId: -1 };
            }
        });
    
        cli.connect();
        
        try {
        
                  let respBootNotification = await cli.call("BootNotification", {
                    chargePointVendor: "ocpp-rpc",
                    chargePointModel: "ocpp-rpc",
                });
    
                console.log(
                   "Response from Server (BootNotification) => ",
                   respBootNotification
               );
         } catch (err) {
            // Call failed
            console.error("Call failed because:", err.message);
            console.error("RPC Error code:", err.rpcErrorCode);
            console.error("Error details:", err.details);
            throw err;
        }
    }
    
    main().catch(console.error);     
    

    Can you please provide me suggestion regarding to required to do changes on above?

    Thanks,

    opened by kvext 2
  • Send messages as string

    Send messages as string

    Hello is there any reason to send the messages as buffer? because my charger doesn't understand buffer responses and work fine when messages are sent as string

    opened by chr314 2
  • Add support for idempotency

    Add support for idempotency

    To mitigate an issue raised in #7, the RPC client should perhaps support a level of idempotency.

    A constructor option such as idempotencyCacheSize could allow a configurable size of idempotency cache per client. If a call is repeated with the same ID, method, params (& optional signature), then the previous response should be repeated without passing the call to a handler.

    If the message ID is reused with a different method, params or signature, then the call should reject with an RPC error as defined in the spec as normal.

    invalid 
    opened by mikuso 1
  • Other way to notify the client?

    Other way to notify the client?

    Hi @mikuso ,

    asking if you have an optimized way of calling an action to the client instead of the code below:

    server._clients.forEach(function each(clientrecord) { if(clientrecord.identity == 'SampleIdentity'){ clientrecord.call('StartTransactionResponse', {"timeStamp": params.timestamp}) } });

    opened by rowellcodizal 0
  • WIP: Add Typescript types

    WIP: Add Typescript types

    This is still a draft.

    Hi Do you have the plan to add the Typescript types? I hope this library can be used in Typescript withourt adding additional type declaretion by user.

    Please advise.

    opened by alex1290 3
  • Add call retry option to retry calls which fail due to connection error

    Add call retry option to retry calls which fail due to connection error

    It would be good to have an option to opaquely retry calls which fail due to connection-related errors.

    Perhaps a call option {maxRetries: 3} and/or an option in the RPC client/server constructors to set a default.

    By default, maxRetries should probably be 0 since there's a chance that retries could have undesirable effects if the call has been handled.

    enhancement 
    opened by mikuso 2
  • Add support for JWS signed messages

    Add support for JWS signed messages

    Section 7.1 of the OCPP2.0.1J specification describes a "signed message format" which extends the RPC framework.

    Support for this could be added with an option to the client.call() method.

    e.g.

    await client.call('MeterValues', {/** params **/}, { sign: true });`
    
    enhancement 
    opened by mikuso 0
Owner
Mikuso
Mikuso
Patronum: Ethereum RPC proxy that verifies RPC responses against given trusted block hashes

Patronum Ethereum RPC proxy that verifies RPC responses against given trusted block hashes. Currently, most of the DAPPs and Wallets interact with Eth

null 14 Dec 7, 2022
Run RPC over a MessagePort object from a Worker thread (or WebWorker)

thread-rpc Run RPC over a MessagePort object from a Worker thread (or WebWorker) npm install thread-rpc Usage First in the parent thread const Thread

Mathias Buus 9 May 31, 2022
it is websocket-store for using easily websocket

Socket-Store It is Websocket Store How to use 1. Install # npm npm install socket-store # yarn yarn add socket-store 2. Create MessageHandler and

nerdchanii 4 Sep 13, 2022
Performant WebSocket Server & Client

Socketich ?? Performant WebSocket server and persistent client powered by uWebSockets.js and PersistentWebSocket Install npm i @geut/socketich Usage S

GEUT 6 Aug 15, 2022
The Frontend of Escobar's Inventory Management System, Employee Management System, Ordering System, and Income & Expense System

Usage Create an App # with npx $ npx create-nextron-app my-app --example with-javascript # with yarn $ yarn create nextron-app my-app --example with-

Viver Bungag 4 Jan 2, 2023
my ethereum RPC node setup & notes

UBUNTU RPC (scaffold-rpc) sudo add-apt-repository -y ppa:ethereum/ethereum sudo apt-get update sudo apt-get install ethereum = created geth script = g

Austin Griffith 10 Jul 4, 2022
A MITM cache between RPCs and a a dAPP. Useful to allow for better performance on a public RPC node

better-cosmos-rpcs A cheaper way to allow for public RPCs as a service WITHOUT scaling issues. No need to rate limit either. How it is done: User GET

Reece Williams 3 Nov 19, 2022
🐬 A simplified implementation of TypeScript's type system written in TypeScript's type system

?? HypeScript Introduction This is a simplified implementation of TypeScript's type system that's written in TypeScript's type annotations. This means

Ronen Amiel 1.8k Dec 20, 2022
Renders and SVG schema of SARS-CoV-2 clade as defined by Neststrain

ncov-clade-schema https://ncov-clades-schema.vercel.app/ Visualizes current tree of SARS-CoV-2 clades. Allows to generate an SVG image of this tree. C

Nextstrain 5 Nov 3, 2022
Sample AWS microservices app with service discovery defined using the CDK. Uses Docker + Fargate & ELB.

AWS Microservices Demo with CDK and Fargate About Simple AWS microservice-based app. Consists of two Spring Boot based services: Name Service GET /nam

Nick Klaene 7 Nov 23, 2022
Calculates maximum composite SLA for a list of sequentially provided cloud services or your custom-defined services.

SlaMax Calculates maximum composite SLA for a list of sequentially provided cloud services or your custom-defined services. Here are a few use-cases y

Mikael Vesavuori 4 Sep 19, 2022
A lightweight jQuery custom scrollbar plugin, that triggers event when reached the defined point.

Scrollbox A lightweight jQuery custom scrollbar plugin, that triggers event when reached the defined point. Demo Page Table of contents Browser compat

null 15 Jul 22, 2022
CSS-based animations triggered by JS, defined in your stylesheet

Anim-x CSS-based animations triggered by JS, defined in your stylesheet. $ npm i https://github.com/LTBL-Studio/anim-x.git Quick start An animation is

LTBL 2 Sep 29, 2021
Invadium runs exploit playbooks against vulnerable target applications in an intuitive, reproducible, and well-defined manner.

Invadium Invadium runs exploits against one or more target applications in an intuitive, reproducable, and well-defined manner. It focuses on bridging

Dynatrace Open Source 10 Nov 6, 2022
jQuery plugin to show a tabs bar for navigation. The tabs can be defined once, and shared across multiple HTML pages.

jquery.simpletabs v1.2.3 The jquery.simpletabs plugin shows a tabs bar for navigation. The tabs can be defined once, and shared across multiple HTML p

Peter Thoeny 1 Feb 23, 2022
Improve the security of your API by detecting common vulnerabilities as defined by OWASP and enforced with Spectral.

Spectral OWASP API Security Scan an OpenAPI document to detect security issues. As OpenAPI is only describing the surface level of the API it cannot s

Stoplight 23 Dec 8, 2022
Tampermonkey script which adds the ability to add a user-defined label/tag/flair on a user, shown throughout Hacker News.

Hacker News User Tags Hacker News User Tags is a Tampermonkey userscript which allows the user to associate a custom coloured label/tag on usernames t

Lachlan McDonald 2 Oct 7, 2022
API client to test endpoints over HTTP. Uses superagent under the hood

@japa/client API client to test endpoints over HTTP. Uses superagent under the hood The API client plugin of Japa makes it super simple to test your A

Japa.dev 8 Apr 13, 2022
Collection of JSON-RPC APIs provided by Ethereum 1.0 clients

Ethereum JSON-RPC Specification View the spec The Ethereum JSON-RPC is a collection of methods that all clients implement. This interface allows downs

null 557 Jan 8, 2023