@totemsdk/edge-ocpp 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +202 -0
- package/NOTICE +60 -0
- package/README.md +119 -2
- package/dist/cjs/gateway.d.ts +49 -0
- package/dist/cjs/gateway.js +184 -0
- package/dist/cjs/governed/adapter.d.ts +32 -0
- package/dist/cjs/governed/adapter.js +537 -0
- package/dist/cjs/governed/capabilities.d.ts +32 -0
- package/dist/cjs/governed/capabilities.js +53 -0
- package/dist/cjs/governed/effects.d.ts +22 -0
- package/dist/cjs/governed/effects.js +27 -0
- package/dist/cjs/governed/index.d.ts +20 -0
- package/dist/cjs/governed/index.js +35 -0
- package/dist/cjs/governed/meter.d.ts +39 -0
- package/dist/cjs/governed/meter.js +81 -0
- package/dist/cjs/governed/profile.d.ts +40 -0
- package/dist/cjs/governed/profile.js +175 -0
- package/dist/cjs/governed/transport.d.ts +104 -0
- package/dist/cjs/governed/transport.js +33 -0
- package/dist/cjs/index.d.ts +7 -0
- package/dist/cjs/index.js +15 -0
- package/dist/cjs/ocpp.d.ts +40 -0
- package/dist/cjs/ocpp.js +101 -0
- package/dist/cjs/package.json +1 -0
- package/dist/cjs/sensor-bridge.d.ts +32 -0
- package/dist/cjs/sensor-bridge.js +72 -0
- package/dist/cjs/transport.d.ts +16 -0
- package/dist/cjs/transport.js +9 -0
- package/dist/gateway.d.ts +49 -0
- package/dist/gateway.js +181 -0
- package/dist/governed/adapter.d.ts +32 -0
- package/dist/governed/adapter.js +533 -0
- package/dist/governed/capabilities.d.ts +32 -0
- package/dist/governed/capabilities.js +48 -0
- package/dist/governed/effects.d.ts +22 -0
- package/dist/governed/effects.js +24 -0
- package/dist/governed/index.d.ts +20 -0
- package/dist/governed/index.js +14 -0
- package/dist/governed/meter.d.ts +39 -0
- package/dist/governed/meter.js +77 -0
- package/dist/governed/profile.d.ts +40 -0
- package/dist/governed/profile.js +167 -0
- package/dist/governed/transport.d.ts +104 -0
- package/dist/governed/transport.js +28 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +3 -0
- package/dist/ocpp.d.ts +40 -0
- package/dist/ocpp.js +92 -0
- package/dist/sensor-bridge.d.ts +32 -0
- package/dist/sensor-bridge.js +69 -0
- package/dist/transport.d.ts +16 -0
- package/dist/transport.js +8 -0
- package/package.json +77 -3
package/dist/cjs/ocpp.js
ADDED
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* OCPP-J framing (OCPP 1.6J and 2.0.1).
|
|
4
|
+
*
|
|
5
|
+
* CALL [2, messageId, action, payload]
|
|
6
|
+
* CALLRESULT [3, messageId, payload]
|
|
7
|
+
* CALLERROR [4, messageId, errorCode, errorDescription, errorDetails]
|
|
8
|
+
*/
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
10
|
+
exports.OcppError = exports.OcppProtocolError = exports.OCPP_ERROR_CODES = void 0;
|
|
11
|
+
exports.encodeCall = encodeCall;
|
|
12
|
+
exports.encodeCallResult = encodeCallResult;
|
|
13
|
+
exports.encodeCallError = encodeCallError;
|
|
14
|
+
exports.parseOcppFrame = parseOcppFrame;
|
|
15
|
+
exports.OCPP_ERROR_CODES = [
|
|
16
|
+
'NotSupported',
|
|
17
|
+
'InternalError',
|
|
18
|
+
'ProtocolError',
|
|
19
|
+
'SecurityError',
|
|
20
|
+
'FormationViolation',
|
|
21
|
+
'PropertyConstraintViolation',
|
|
22
|
+
'OccurrenceConstraintViolation',
|
|
23
|
+
'TypeConstraintViolation',
|
|
24
|
+
'GenericError',
|
|
25
|
+
];
|
|
26
|
+
class OcppProtocolError extends Error {
|
|
27
|
+
constructor(message) {
|
|
28
|
+
super(message);
|
|
29
|
+
this.name = 'OcppProtocolError';
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
exports.OcppProtocolError = OcppProtocolError;
|
|
33
|
+
class OcppError extends Error {
|
|
34
|
+
constructor(code, message, details = {}) {
|
|
35
|
+
super(message);
|
|
36
|
+
this.code = code;
|
|
37
|
+
this.details = details;
|
|
38
|
+
this.name = 'OcppError';
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
exports.OcppError = OcppError;
|
|
42
|
+
function encodeCall(messageId, action, payload) {
|
|
43
|
+
return JSON.stringify([2, messageId, action, payload]);
|
|
44
|
+
}
|
|
45
|
+
function encodeCallResult(messageId, payload) {
|
|
46
|
+
return JSON.stringify([3, messageId, payload]);
|
|
47
|
+
}
|
|
48
|
+
function encodeCallError(messageId, errorCode, errorDescription, errorDetails = {}) {
|
|
49
|
+
return JSON.stringify([4, messageId, errorCode, errorDescription, errorDetails]);
|
|
50
|
+
}
|
|
51
|
+
function parseOcppFrame(raw) {
|
|
52
|
+
let value;
|
|
53
|
+
try {
|
|
54
|
+
value = JSON.parse(raw);
|
|
55
|
+
}
|
|
56
|
+
catch {
|
|
57
|
+
throw new OcppProtocolError('OCPP frame is not valid JSON');
|
|
58
|
+
}
|
|
59
|
+
if (!Array.isArray(value) || value.length < 3)
|
|
60
|
+
throw new OcppProtocolError('OCPP frame must be an array');
|
|
61
|
+
const [type, messageId] = value;
|
|
62
|
+
if (typeof messageId !== 'string' || messageId.length === 0)
|
|
63
|
+
throw new OcppProtocolError('OCPP message id must be a non-empty string');
|
|
64
|
+
if (type === 2) {
|
|
65
|
+
if (value.length !== 4)
|
|
66
|
+
throw new OcppProtocolError('OCPP CALL must have four elements');
|
|
67
|
+
const [, , action, payload] = value;
|
|
68
|
+
if (typeof action !== 'string' || action.length === 0)
|
|
69
|
+
throw new OcppProtocolError('OCPP CALL action must be a non-empty string');
|
|
70
|
+
if (!isRecord(payload))
|
|
71
|
+
throw new OcppProtocolError('OCPP CALL payload must be an object');
|
|
72
|
+
return { type: 2, messageId, action, payload };
|
|
73
|
+
}
|
|
74
|
+
if (type === 3) {
|
|
75
|
+
if (value.length !== 3)
|
|
76
|
+
throw new OcppProtocolError('OCPP CALLRESULT must have three elements');
|
|
77
|
+
const payload = value[2];
|
|
78
|
+
if (!isRecord(payload))
|
|
79
|
+
throw new OcppProtocolError('OCPP CALLRESULT payload must be an object');
|
|
80
|
+
return { type: 3, messageId, payload };
|
|
81
|
+
}
|
|
82
|
+
if (type === 4) {
|
|
83
|
+
if (value.length !== 5)
|
|
84
|
+
throw new OcppProtocolError('OCPP CALLERROR must have five elements');
|
|
85
|
+
const [, , errorCode, errorDescription, errorDetails] = value;
|
|
86
|
+
if (typeof errorCode !== 'string' || !isErrorCode(errorCode))
|
|
87
|
+
throw new OcppProtocolError(`Invalid OCPP error code ${String(errorCode)}`);
|
|
88
|
+
if (typeof errorDescription !== 'string')
|
|
89
|
+
throw new OcppProtocolError('OCPP error description must be a string');
|
|
90
|
+
if (!isRecord(errorDetails))
|
|
91
|
+
throw new OcppProtocolError('OCPP error details must be an object');
|
|
92
|
+
return { type: 4, messageId, errorCode, errorDescription, errorDetails };
|
|
93
|
+
}
|
|
94
|
+
throw new OcppProtocolError(`Unsupported OCPP message type ${String(type)}`);
|
|
95
|
+
}
|
|
96
|
+
function isRecord(value) {
|
|
97
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value);
|
|
98
|
+
}
|
|
99
|
+
function isErrorCode(value) {
|
|
100
|
+
return exports.OCPP_ERROR_CODES.includes(value);
|
|
101
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"type":"commonjs"}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OCPP Sensor Bridge — publishes locally sampled meter values as both OCPP
|
|
3
|
+
* MeterValues and Edge proofs.
|
|
4
|
+
*/
|
|
5
|
+
import type { EdgeRuntime } from '@totemsdk/edge';
|
|
6
|
+
import type { OcppGateway } from './gateway.js';
|
|
7
|
+
export interface OcppMeterSample {
|
|
8
|
+
value: number;
|
|
9
|
+
unit: string;
|
|
10
|
+
measurand?: string;
|
|
11
|
+
context?: string;
|
|
12
|
+
timestamp?: number;
|
|
13
|
+
transactionId?: number;
|
|
14
|
+
}
|
|
15
|
+
export interface OcppMeterBinding {
|
|
16
|
+
sensorId: string;
|
|
17
|
+
connectorId: number;
|
|
18
|
+
intervalMs: number;
|
|
19
|
+
/** Read the current sample(s) for this connector. */
|
|
20
|
+
read: () => Promise<OcppMeterSample[]>;
|
|
21
|
+
}
|
|
22
|
+
export interface OcppSensorBridgeConfig {
|
|
23
|
+
runtime: EdgeRuntime;
|
|
24
|
+
gateway: OcppGateway;
|
|
25
|
+
bindings: OcppMeterBinding[];
|
|
26
|
+
}
|
|
27
|
+
export interface OcppSensorBridge {
|
|
28
|
+
start(): Promise<void>;
|
|
29
|
+
stop(): Promise<void>;
|
|
30
|
+
poll(): Promise<void>;
|
|
31
|
+
}
|
|
32
|
+
export declare function createOcppSensorBridge(config: OcppSensorBridgeConfig): OcppSensorBridge;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* OCPP Sensor Bridge — publishes locally sampled meter values as both OCPP
|
|
4
|
+
* MeterValues and Edge proofs.
|
|
5
|
+
*/
|
|
6
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
7
|
+
exports.createOcppSensorBridge = createOcppSensorBridge;
|
|
8
|
+
function createOcppSensorBridge(config) {
|
|
9
|
+
const timers = [];
|
|
10
|
+
let running = false;
|
|
11
|
+
async function pollBinding(binding) {
|
|
12
|
+
try {
|
|
13
|
+
const samples = await binding.read();
|
|
14
|
+
if (samples.length === 0)
|
|
15
|
+
return;
|
|
16
|
+
const proof = config.runtime.ports.proof;
|
|
17
|
+
if (proof) {
|
|
18
|
+
for (const sample of samples) {
|
|
19
|
+
await proof.createProof({
|
|
20
|
+
subject: `sensor:${binding.sensorId}`,
|
|
21
|
+
claims: [{
|
|
22
|
+
sensorId: binding.sensorId,
|
|
23
|
+
connectorId: binding.connectorId,
|
|
24
|
+
value: sample.value,
|
|
25
|
+
unit: sample.unit,
|
|
26
|
+
measurand: sample.measurand ?? 'Energy.Active.Import.Register',
|
|
27
|
+
context: sample.context ?? 'Sample.Periodic',
|
|
28
|
+
timestamp: sample.timestamp ?? Date.now(),
|
|
29
|
+
...(sample.transactionId !== undefined ? { transactionId: sample.transactionId } : {}),
|
|
30
|
+
}],
|
|
31
|
+
}).catch(() => { });
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const timestamp = new Date().toISOString();
|
|
35
|
+
await config.gateway.call('MeterValues', {
|
|
36
|
+
connectorId: binding.connectorId,
|
|
37
|
+
...(samples[0].transactionId !== undefined ? { transactionId: samples[0].transactionId } : {}),
|
|
38
|
+
meterValue: [{
|
|
39
|
+
timestamp,
|
|
40
|
+
sampledValue: samples.map((sample) => ({
|
|
41
|
+
value: String(sample.value),
|
|
42
|
+
unit: sample.unit,
|
|
43
|
+
...(sample.measurand ? { measurand: sample.measurand } : {}),
|
|
44
|
+
...(sample.context ? { context: sample.context } : {}),
|
|
45
|
+
})),
|
|
46
|
+
}],
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
catch { /* non-fatal */ }
|
|
50
|
+
}
|
|
51
|
+
return {
|
|
52
|
+
async start() {
|
|
53
|
+
if (running)
|
|
54
|
+
return;
|
|
55
|
+
for (const binding of config.bindings) {
|
|
56
|
+
await pollBinding(binding);
|
|
57
|
+
timers.push(setInterval(() => pollBinding(binding), binding.intervalMs));
|
|
58
|
+
}
|
|
59
|
+
running = true;
|
|
60
|
+
},
|
|
61
|
+
async stop() {
|
|
62
|
+
for (const timer of timers)
|
|
63
|
+
clearInterval(timer);
|
|
64
|
+
timers.length = 0;
|
|
65
|
+
running = false;
|
|
66
|
+
},
|
|
67
|
+
async poll() {
|
|
68
|
+
for (const binding of config.bindings)
|
|
69
|
+
await pollBinding(binding);
|
|
70
|
+
},
|
|
71
|
+
};
|
|
72
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OCPP transport port — injected by the caller.
|
|
3
|
+
*
|
|
4
|
+
* The caller supplies a WebSocket (or test) transport that carries OCPP-J text
|
|
5
|
+
* frames. The connector owns framing, correlation, CALL handling, heartbeats
|
|
6
|
+
* and proof shaping.
|
|
7
|
+
*/
|
|
8
|
+
export interface OcppTransportPort {
|
|
9
|
+
connect(url: string, protocols?: string[]): Promise<void>;
|
|
10
|
+
close(): Promise<void>;
|
|
11
|
+
send(message: string): Promise<void>;
|
|
12
|
+
onMessage(handler: (message: string) => void): () => void;
|
|
13
|
+
onClose(handler: () => void): () => void;
|
|
14
|
+
onError(handler: (err: Error) => void): () => void;
|
|
15
|
+
readonly state?: 'closed' | 'connecting' | 'open';
|
|
16
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
/**
|
|
3
|
+
* OCPP transport port — injected by the caller.
|
|
4
|
+
*
|
|
5
|
+
* The caller supplies a WebSocket (or test) transport that carries OCPP-J text
|
|
6
|
+
* frames. The connector owns framing, correlation, CALL handling, heartbeats
|
|
7
|
+
* and proof shaping.
|
|
8
|
+
*/
|
|
9
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OCPP Edge Gateway — charge-point side of OCPP-J.
|
|
3
|
+
*
|
|
4
|
+
* The gateway owns framing, CALL/CALLRESULT/CALLERROR correlation, inbound CALL
|
|
5
|
+
* dispatch, boot notification and heartbeat. It has no decision, authority or
|
|
6
|
+
* physical-effect policy: starting/stopping a charging session must go through
|
|
7
|
+
* the governed `@totemsdk/edge-ocpp/governed` profile (RFC-024).
|
|
8
|
+
*/
|
|
9
|
+
import type { EdgeRuntime, EdgeOperationResult } from '@totemsdk/edge';
|
|
10
|
+
import type { OcppTransportPort } from './transport.js';
|
|
11
|
+
export type OcppVersion = '1.6J' | '2.0.1';
|
|
12
|
+
export interface OcppGatewayConfig {
|
|
13
|
+
runtime: EdgeRuntime;
|
|
14
|
+
transport: OcppTransportPort;
|
|
15
|
+
url: string;
|
|
16
|
+
chargePointId: string;
|
|
17
|
+
version?: OcppVersion;
|
|
18
|
+
protocols?: string[];
|
|
19
|
+
/** Heartbeat interval; 0 disables automatic heartbeats. Default 30s. */
|
|
20
|
+
heartbeatIntervalMs?: number;
|
|
21
|
+
callTimeoutMs?: number;
|
|
22
|
+
/** Send BootNotification during start. Default true. */
|
|
23
|
+
bootOnStart?: boolean;
|
|
24
|
+
bootNotification?: Record<string, unknown>;
|
|
25
|
+
}
|
|
26
|
+
export type OcppCallHandler = (payload: Record<string, unknown>) => Promise<Record<string, unknown>> | Record<string, unknown>;
|
|
27
|
+
export interface OcppGateway {
|
|
28
|
+
start(): Promise<void>;
|
|
29
|
+
stop(): Promise<void>;
|
|
30
|
+
readonly status: 'stopped' | 'running' | 'error';
|
|
31
|
+
call(action: string, payload?: Record<string, unknown>, timeoutMs?: number): Promise<EdgeOperationResult<{
|
|
32
|
+
payload: Record<string, unknown>;
|
|
33
|
+
}>>;
|
|
34
|
+
/** Register a handler for an inbound CSMS CALL. */
|
|
35
|
+
onCall(action: string, handler: OcppCallHandler): () => void;
|
|
36
|
+
sendBootNotification(payload?: Record<string, unknown>): Promise<EdgeOperationResult<{
|
|
37
|
+
payload: Record<string, unknown>;
|
|
38
|
+
}>>;
|
|
39
|
+
sendHeartbeat(): Promise<EdgeOperationResult<{
|
|
40
|
+
payload: Record<string, unknown>;
|
|
41
|
+
}>>;
|
|
42
|
+
sendStatusNotification(connectorId: number, status: string, errorCode?: string): Promise<EdgeOperationResult<{
|
|
43
|
+
payload: Record<string, unknown>;
|
|
44
|
+
}>>;
|
|
45
|
+
authorize(idTag: string): Promise<EdgeOperationResult<{
|
|
46
|
+
payload: Record<string, unknown>;
|
|
47
|
+
}>>;
|
|
48
|
+
}
|
|
49
|
+
export declare function createOcppGateway(config: OcppGatewayConfig): OcppGateway;
|
package/dist/gateway.js
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OCPP Edge Gateway — charge-point side of OCPP-J.
|
|
3
|
+
*
|
|
4
|
+
* The gateway owns framing, CALL/CALLRESULT/CALLERROR correlation, inbound CALL
|
|
5
|
+
* dispatch, boot notification and heartbeat. It has no decision, authority or
|
|
6
|
+
* physical-effect policy: starting/stopping a charging session must go through
|
|
7
|
+
* the governed `@totemsdk/edge-ocpp/governed` profile (RFC-024).
|
|
8
|
+
*/
|
|
9
|
+
import { encodeCall, encodeCallError, encodeCallResult, OcppError, parseOcppFrame, } from './ocpp.js';
|
|
10
|
+
export function createOcppGateway(config) {
|
|
11
|
+
let status = 'stopped';
|
|
12
|
+
let sequence = 0;
|
|
13
|
+
let heartbeatTimer;
|
|
14
|
+
let unsubMessage;
|
|
15
|
+
let unsubClose;
|
|
16
|
+
let unsubError;
|
|
17
|
+
const pending = new Map();
|
|
18
|
+
const callHandlers = new Map();
|
|
19
|
+
const callTimeoutMs = config.callTimeoutMs ?? 10000;
|
|
20
|
+
const bootPayload = config.bootNotification ?? { chargePointVendor: 'Totem', chargePointModel: 'Edge' };
|
|
21
|
+
function rejectAll(error) {
|
|
22
|
+
for (const [, entry] of pending) {
|
|
23
|
+
clearTimeout(entry.timer);
|
|
24
|
+
entry.reject(error);
|
|
25
|
+
}
|
|
26
|
+
pending.clear();
|
|
27
|
+
}
|
|
28
|
+
function result(payload) {
|
|
29
|
+
return { ok: true, data: payload };
|
|
30
|
+
}
|
|
31
|
+
function failure(error) {
|
|
32
|
+
if (error instanceof OcppError)
|
|
33
|
+
return { ok: false, error: error.message, errorCode: error.code };
|
|
34
|
+
return { ok: false, error: error instanceof Error ? error.message : String(error) };
|
|
35
|
+
}
|
|
36
|
+
function sendCall(action, payload = {}, timeoutMs = callTimeoutMs) {
|
|
37
|
+
return call(action, payload, timeoutMs);
|
|
38
|
+
}
|
|
39
|
+
async function call(action, payload = {}, timeoutMs = callTimeoutMs) {
|
|
40
|
+
const messageId = `${config.chargePointId}-${++sequence}`;
|
|
41
|
+
return new Promise((resolve) => {
|
|
42
|
+
const timer = setTimeout(() => {
|
|
43
|
+
pending.delete(messageId);
|
|
44
|
+
resolve({ ok: false, error: `OCPP ${action} timed out` });
|
|
45
|
+
}, timeoutMs);
|
|
46
|
+
pending.set(messageId, {
|
|
47
|
+
resolve: (response) => resolve(result({ payload: response })),
|
|
48
|
+
reject: (error) => resolve({ ok: false, error: error.message, errorCode: error.code }),
|
|
49
|
+
timer,
|
|
50
|
+
});
|
|
51
|
+
void config.transport.send(encodeCall(messageId, action, payload)).catch((error) => {
|
|
52
|
+
const entry = pending.get(messageId);
|
|
53
|
+
if (!entry)
|
|
54
|
+
return;
|
|
55
|
+
pending.delete(messageId);
|
|
56
|
+
clearTimeout(entry.timer);
|
|
57
|
+
resolve(failure(error));
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
async function handleRaw(raw) {
|
|
62
|
+
let frame;
|
|
63
|
+
try {
|
|
64
|
+
frame = parseOcppFrame(raw);
|
|
65
|
+
}
|
|
66
|
+
catch {
|
|
67
|
+
status = 'error';
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
if (frame.type === 3) {
|
|
71
|
+
const entry = pending.get(frame.messageId);
|
|
72
|
+
if (!entry)
|
|
73
|
+
return;
|
|
74
|
+
pending.delete(frame.messageId);
|
|
75
|
+
clearTimeout(entry.timer);
|
|
76
|
+
status = 'running';
|
|
77
|
+
entry.resolve(frame.payload);
|
|
78
|
+
return;
|
|
79
|
+
}
|
|
80
|
+
if (frame.type === 4) {
|
|
81
|
+
const entry = pending.get(frame.messageId);
|
|
82
|
+
if (!entry)
|
|
83
|
+
return;
|
|
84
|
+
pending.delete(frame.messageId);
|
|
85
|
+
clearTimeout(entry.timer);
|
|
86
|
+
entry.reject(new OcppError(frame.errorCode, frame.errorDescription, frame.errorDetails));
|
|
87
|
+
return;
|
|
88
|
+
}
|
|
89
|
+
const handlers = callHandlers.get(frame.action);
|
|
90
|
+
let response = {};
|
|
91
|
+
try {
|
|
92
|
+
if (!handlers || handlers.size === 0) {
|
|
93
|
+
await config.transport.send(encodeCallError(frame.messageId, 'NotSupported', `No handler for ${frame.action}`));
|
|
94
|
+
return;
|
|
95
|
+
}
|
|
96
|
+
for (const handler of handlers)
|
|
97
|
+
response = await handler(frame.payload);
|
|
98
|
+
await config.transport.send(encodeCallResult(frame.messageId, response));
|
|
99
|
+
}
|
|
100
|
+
catch (error) {
|
|
101
|
+
const code = error instanceof OcppError ? error.code : 'InternalError';
|
|
102
|
+
const description = error instanceof Error ? error.message : String(error);
|
|
103
|
+
const details = error instanceof OcppError ? error.details : {};
|
|
104
|
+
await config.transport.send(encodeCallError(frame.messageId, code, description, details)).catch(() => { });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
return {
|
|
108
|
+
get status() { return status; },
|
|
109
|
+
async start() {
|
|
110
|
+
if (status === 'running')
|
|
111
|
+
return;
|
|
112
|
+
try {
|
|
113
|
+
await config.transport.connect(config.url, config.protocols);
|
|
114
|
+
unsubMessage = config.transport.onMessage((raw) => { void handleRaw(raw); });
|
|
115
|
+
unsubClose = config.transport.onClose(() => {
|
|
116
|
+
status = 'error';
|
|
117
|
+
rejectAll(new OcppError('GenericError', 'OCPP connection closed'));
|
|
118
|
+
});
|
|
119
|
+
unsubError = config.transport.onError(() => { status = 'error'; });
|
|
120
|
+
if (config.bootOnStart ?? true) {
|
|
121
|
+
const boot = await call('BootNotification', bootPayload);
|
|
122
|
+
const bootStatus = boot.ok ? boot.data?.payload.status : undefined;
|
|
123
|
+
if (!boot.ok || bootStatus !== 'Accepted') {
|
|
124
|
+
await this.stop();
|
|
125
|
+
status = 'error';
|
|
126
|
+
throw new Error(`OCPP boot rejected: ${boot.ok ? String(bootStatus) : boot.error}`);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
status = 'running';
|
|
130
|
+
const heartbeatInterval = config.heartbeatIntervalMs ?? 30000;
|
|
131
|
+
if (heartbeatInterval > 0) {
|
|
132
|
+
heartbeatTimer = setInterval(() => {
|
|
133
|
+
void call('Heartbeat', {}).then((response) => {
|
|
134
|
+
if (!response.ok)
|
|
135
|
+
status = 'error';
|
|
136
|
+
});
|
|
137
|
+
}, heartbeatInterval);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
catch (error) {
|
|
141
|
+
status = 'error';
|
|
142
|
+
throw error;
|
|
143
|
+
}
|
|
144
|
+
},
|
|
145
|
+
async stop() {
|
|
146
|
+
if (heartbeatTimer) {
|
|
147
|
+
clearInterval(heartbeatTimer);
|
|
148
|
+
heartbeatTimer = undefined;
|
|
149
|
+
}
|
|
150
|
+
unsubMessage?.();
|
|
151
|
+
unsubClose?.();
|
|
152
|
+
unsubError?.();
|
|
153
|
+
unsubMessage = undefined;
|
|
154
|
+
unsubClose = undefined;
|
|
155
|
+
unsubError = undefined;
|
|
156
|
+
rejectAll(new OcppError('GenericError', 'OCPP gateway stopped'));
|
|
157
|
+
try {
|
|
158
|
+
await config.transport.close();
|
|
159
|
+
}
|
|
160
|
+
catch { /* already closed */ }
|
|
161
|
+
status = 'stopped';
|
|
162
|
+
},
|
|
163
|
+
call,
|
|
164
|
+
onCall(action, handler) {
|
|
165
|
+
const handlers = callHandlers.get(action) ?? new Set();
|
|
166
|
+
handlers.add(handler);
|
|
167
|
+
callHandlers.set(action, handlers);
|
|
168
|
+
return () => {
|
|
169
|
+
handlers.delete(handler);
|
|
170
|
+
if (handlers.size === 0)
|
|
171
|
+
callHandlers.delete(action);
|
|
172
|
+
};
|
|
173
|
+
},
|
|
174
|
+
sendBootNotification(payload = bootPayload) { return sendCall('BootNotification', payload); },
|
|
175
|
+
sendHeartbeat() { return sendCall('Heartbeat', {}); },
|
|
176
|
+
sendStatusNotification(connectorId, connectorStatus, errorCode = 'NoError') {
|
|
177
|
+
return sendCall('StatusNotification', { connectorId, status: connectorStatus, errorCode });
|
|
178
|
+
},
|
|
179
|
+
authorize(idTag) { return sendCall('Authorize', { idTag }); },
|
|
180
|
+
};
|
|
181
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RFC-024 §5.3 — governed OCPP operations.
|
|
3
|
+
*
|
|
4
|
+
* Each definition prepares a deterministic, commitment-bound OCPP command and
|
|
5
|
+
* derives its physical effects from that prepared command (never from hints).
|
|
6
|
+
* `startSession`/`stopSession` are asynchronous: acceptance is not completion,
|
|
7
|
+
* and completion is established by charger meter/transaction readback.
|
|
8
|
+
*
|
|
9
|
+
* Configuration writes (`setLimit`, `clearProfile`, `reserveConnector`) use
|
|
10
|
+
* `confirmation: 'completed'` because the CSMS acknowledgement *is* the terminal
|
|
11
|
+
* state for a profile/ reservation change; only a session has a later physical
|
|
12
|
+
* outcome to observe.
|
|
13
|
+
*/
|
|
14
|
+
import { type IndustrialActionDefinition, type UnitRegistry } from '@totemsdk/act-core';
|
|
15
|
+
import type { OcppCapabilitySet } from './capabilities.js';
|
|
16
|
+
import { type ChargingConnector } from './profile.js';
|
|
17
|
+
import { type OcppTransportPort } from './transport.js';
|
|
18
|
+
export interface OcppAdapterOptions {
|
|
19
|
+
transport: OcppTransportPort;
|
|
20
|
+
site: string;
|
|
21
|
+
connectors: readonly ChargingConnector[];
|
|
22
|
+
capabilities?: OcppCapabilitySet;
|
|
23
|
+
units?: UnitRegistry;
|
|
24
|
+
}
|
|
25
|
+
interface ChargingCommand {
|
|
26
|
+
action: string;
|
|
27
|
+
connectorId: number;
|
|
28
|
+
[key: string]: unknown;
|
|
29
|
+
}
|
|
30
|
+
export declare function createOcppDefinitions(options: OcppAdapterOptions): IndustrialActionDefinition[];
|
|
31
|
+
export declare function errorCodeOf(error: unknown): string | undefined;
|
|
32
|
+
export type { ChargingCommand };
|