feat(ocpp): implement BootNotification, Heartbeat, and StatusNotification actions with database integration
This commit is contained in:
172
apps/csms/drizzle/0002_melodic_moondragon.sql
Normal file
172
apps/csms/drizzle/0002_melodic_moondragon.sql
Normal file
@@ -0,0 +1,172 @@
|
|||||||
|
CREATE TABLE "jwks" (
|
||||||
|
"id" text PRIMARY KEY NOT NULL,
|
||||||
|
"public_key" text NOT NULL,
|
||||||
|
"private_key" text NOT NULL,
|
||||||
|
"created_at" timestamp NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "charge_point" (
|
||||||
|
"id" varchar PRIMARY KEY NOT NULL,
|
||||||
|
"charge_point_identifier" varchar(255) NOT NULL,
|
||||||
|
"charge_point_serial_number" varchar(25),
|
||||||
|
"charge_point_model" varchar(20) NOT NULL,
|
||||||
|
"charge_point_vendor" varchar(20) NOT NULL,
|
||||||
|
"firmware_version" varchar(50),
|
||||||
|
"iccid" varchar(20),
|
||||||
|
"imsi" varchar(20),
|
||||||
|
"meter_serial_number" varchar(25),
|
||||||
|
"meter_type" varchar(25),
|
||||||
|
"registration_status" varchar DEFAULT 'Pending' NOT NULL,
|
||||||
|
"heartbeat_interval" integer DEFAULT 60,
|
||||||
|
"last_heartbeat_at" timestamp with time zone,
|
||||||
|
"last_boot_notification_at" timestamp with time zone,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "charge_point_charge_point_identifier_unique" UNIQUE("charge_point_identifier")
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "charging_profile" (
|
||||||
|
"id" integer PRIMARY KEY NOT NULL,
|
||||||
|
"charge_point_id" varchar NOT NULL,
|
||||||
|
"connector_id" varchar,
|
||||||
|
"connector_number" integer NOT NULL,
|
||||||
|
"transaction_id" integer,
|
||||||
|
"stack_level" integer NOT NULL,
|
||||||
|
"charging_profile_purpose" varchar NOT NULL,
|
||||||
|
"charging_profile_kind" varchar NOT NULL,
|
||||||
|
"recurrency_kind" varchar,
|
||||||
|
"valid_from" timestamp with time zone,
|
||||||
|
"valid_to" timestamp with time zone,
|
||||||
|
"charging_schedule" jsonb NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "connector" (
|
||||||
|
"id" varchar PRIMARY KEY NOT NULL,
|
||||||
|
"charge_point_id" varchar NOT NULL,
|
||||||
|
"connector_id" integer NOT NULL,
|
||||||
|
"status" varchar DEFAULT 'Unavailable' NOT NULL,
|
||||||
|
"error_code" varchar DEFAULT 'NoError' NOT NULL,
|
||||||
|
"info" varchar(50),
|
||||||
|
"vendor_id" varchar(255),
|
||||||
|
"vendor_error_code" varchar(50),
|
||||||
|
"last_status_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "connector_status_history" (
|
||||||
|
"id" varchar PRIMARY KEY NOT NULL,
|
||||||
|
"connector_id" varchar NOT NULL,
|
||||||
|
"connector_number" integer NOT NULL,
|
||||||
|
"status" varchar NOT NULL,
|
||||||
|
"error_code" varchar NOT NULL,
|
||||||
|
"info" varchar(50),
|
||||||
|
"vendor_id" varchar(255),
|
||||||
|
"vendor_error_code" varchar(50),
|
||||||
|
"status_timestamp" timestamp with time zone,
|
||||||
|
"received_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "id_tag" (
|
||||||
|
"id_tag" varchar(20) PRIMARY KEY NOT NULL,
|
||||||
|
"parent_id_tag" varchar(20),
|
||||||
|
"status" varchar DEFAULT 'Accepted' NOT NULL,
|
||||||
|
"expiry_date" timestamp with time zone,
|
||||||
|
"user_id" text,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "local_auth_list" (
|
||||||
|
"id" varchar PRIMARY KEY NOT NULL,
|
||||||
|
"charge_point_id" varchar NOT NULL,
|
||||||
|
"list_version" integer NOT NULL,
|
||||||
|
"id_tag" varchar(20) NOT NULL,
|
||||||
|
"parent_id_tag" varchar(20),
|
||||||
|
"id_tag_status" varchar NOT NULL,
|
||||||
|
"expiry_date" timestamp with time zone,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "meter_value" (
|
||||||
|
"id" varchar PRIMARY KEY NOT NULL,
|
||||||
|
"transaction_id" integer,
|
||||||
|
"connector_id" varchar NOT NULL,
|
||||||
|
"charge_point_id" varchar NOT NULL,
|
||||||
|
"connector_number" integer NOT NULL,
|
||||||
|
"timestamp" timestamp with time zone NOT NULL,
|
||||||
|
"sampled_values" jsonb NOT NULL,
|
||||||
|
"received_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "reservation" (
|
||||||
|
"id" integer PRIMARY KEY NOT NULL,
|
||||||
|
"charge_point_id" varchar NOT NULL,
|
||||||
|
"connector_id" varchar,
|
||||||
|
"connector_number" integer NOT NULL,
|
||||||
|
"expiry_date" timestamp with time zone NOT NULL,
|
||||||
|
"id_tag" varchar(20) NOT NULL,
|
||||||
|
"parent_id_tag" varchar(20),
|
||||||
|
"status" varchar DEFAULT 'Active' NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "transaction" (
|
||||||
|
"id" serial PRIMARY KEY NOT NULL,
|
||||||
|
"charge_point_id" varchar NOT NULL,
|
||||||
|
"connector_id" varchar NOT NULL,
|
||||||
|
"connector_number" integer NOT NULL,
|
||||||
|
"id_tag" varchar(20) NOT NULL,
|
||||||
|
"id_tag_status" varchar,
|
||||||
|
"start_timestamp" timestamp with time zone NOT NULL,
|
||||||
|
"start_meter_value" integer NOT NULL,
|
||||||
|
"stop_id_tag" varchar(20),
|
||||||
|
"stop_timestamp" timestamp with time zone,
|
||||||
|
"stop_meter_value" integer,
|
||||||
|
"stop_reason" varchar,
|
||||||
|
"reservation_id" integer,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
ALTER TABLE "user" ALTER COLUMN "role" DROP DEFAULT;--> statement-breakpoint
|
||||||
|
ALTER TABLE "session" ADD COLUMN "impersonated_by" text;--> statement-breakpoint
|
||||||
|
ALTER TABLE "user" ADD COLUMN "banned" boolean DEFAULT false;--> statement-breakpoint
|
||||||
|
ALTER TABLE "user" ADD COLUMN "ban_reason" text;--> statement-breakpoint
|
||||||
|
ALTER TABLE "user" ADD COLUMN "ban_expires" timestamp;--> statement-breakpoint
|
||||||
|
ALTER TABLE "charging_profile" ADD CONSTRAINT "charging_profile_charge_point_id_charge_point_id_fk" FOREIGN KEY ("charge_point_id") REFERENCES "public"."charge_point"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "charging_profile" ADD CONSTRAINT "charging_profile_connector_id_connector_id_fk" FOREIGN KEY ("connector_id") REFERENCES "public"."connector"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "charging_profile" ADD CONSTRAINT "charging_profile_transaction_id_transaction_id_fk" FOREIGN KEY ("transaction_id") REFERENCES "public"."transaction"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "connector" ADD CONSTRAINT "connector_charge_point_id_charge_point_id_fk" FOREIGN KEY ("charge_point_id") REFERENCES "public"."charge_point"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "connector_status_history" ADD CONSTRAINT "connector_status_history_connector_id_connector_id_fk" FOREIGN KEY ("connector_id") REFERENCES "public"."connector"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "id_tag" ADD CONSTRAINT "id_tag_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "local_auth_list" ADD CONSTRAINT "local_auth_list_charge_point_id_charge_point_id_fk" FOREIGN KEY ("charge_point_id") REFERENCES "public"."charge_point"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "meter_value" ADD CONSTRAINT "meter_value_transaction_id_transaction_id_fk" FOREIGN KEY ("transaction_id") REFERENCES "public"."transaction"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "meter_value" ADD CONSTRAINT "meter_value_connector_id_connector_id_fk" FOREIGN KEY ("connector_id") REFERENCES "public"."connector"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "meter_value" ADD CONSTRAINT "meter_value_charge_point_id_charge_point_id_fk" FOREIGN KEY ("charge_point_id") REFERENCES "public"."charge_point"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "reservation" ADD CONSTRAINT "reservation_charge_point_id_charge_point_id_fk" FOREIGN KEY ("charge_point_id") REFERENCES "public"."charge_point"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "reservation" ADD CONSTRAINT "reservation_connector_id_connector_id_fk" FOREIGN KEY ("connector_id") REFERENCES "public"."connector"("id") ON DELETE set null ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "transaction" ADD CONSTRAINT "transaction_charge_point_id_charge_point_id_fk" FOREIGN KEY ("charge_point_id") REFERENCES "public"."charge_point"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "transaction" ADD CONSTRAINT "transaction_connector_id_connector_id_fk" FOREIGN KEY ("connector_id") REFERENCES "public"."connector"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_charging_profile_charge_point_id" ON "charging_profile" USING btree ("charge_point_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_charging_profile_connector_id" ON "charging_profile" USING btree ("connector_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_charging_profile_purpose_stack" ON "charging_profile" USING btree ("connector_number","charging_profile_purpose","stack_level");--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_connector_charge_point_id" ON "connector" USING btree ("charge_point_id");--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "idx_connector_charge_point_connector" ON "connector" USING btree ("charge_point_id","connector_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_status_history_connector_id" ON "connector_status_history" USING btree ("connector_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_status_history_timestamp" ON "connector_status_history" USING btree ("status_timestamp");--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_status_history_received_at" ON "connector_status_history" USING btree ("received_at");--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "idx_local_auth_list_charge_point_id_tag" ON "local_auth_list" USING btree ("charge_point_id","id_tag");--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_meter_value_transaction_id" ON "meter_value" USING btree ("transaction_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_meter_value_connector_id" ON "meter_value" USING btree ("connector_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_meter_value_timestamp" ON "meter_value" USING btree ("timestamp");--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_reservation_charge_point_id" ON "reservation" USING btree ("charge_point_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_reservation_status" ON "reservation" USING btree ("status");--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_reservation_expiry_date" ON "reservation" USING btree ("expiry_date");--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_transaction_charge_point_id" ON "transaction" USING btree ("charge_point_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_transaction_connector_id" ON "transaction" USING btree ("connector_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_transaction_id_tag" ON "transaction" USING btree ("id_tag");--> statement-breakpoint
|
||||||
|
CREATE INDEX "idx_transaction_start_timestamp" ON "transaction" USING btree ("start_timestamp");
|
||||||
1660
apps/csms/drizzle/meta/0002_snapshot.json
Normal file
1660
apps/csms/drizzle/meta/0002_snapshot.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -15,6 +15,13 @@
|
|||||||
"when": 1763319683557,
|
"when": 1763319683557,
|
||||||
"tag": "0001_gorgeous_invisible_woman",
|
"tag": "0001_gorgeous_invisible_woman",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 2,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1773109529038,
|
||||||
|
"tag": "0002_melodic_moondragon",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -5,48 +5,85 @@ import {
|
|||||||
integer,
|
integer,
|
||||||
text,
|
text,
|
||||||
index,
|
index,
|
||||||
|
serial,
|
||||||
|
jsonb,
|
||||||
|
uniqueIndex,
|
||||||
} from 'drizzle-orm/pg-core'
|
} from 'drizzle-orm/pg-core'
|
||||||
|
import { user } from './auth-schema.ts'
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 充电桩 / Charge Point
|
||||||
|
// OCPP 1.6-J Section 4.2 BootNotification
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
/**
|
|
||||||
* 充电桩表
|
|
||||||
* 对应OCPP 1.6-J BootNotification.req中的基本信息
|
|
||||||
*/
|
|
||||||
export const chargePoint = pgTable('charge_point', {
|
export const chargePoint = pgTable('charge_point', {
|
||||||
|
/** 内部 UUID 主键 */
|
||||||
id: varchar('id').primaryKey(),
|
id: varchar('id').primaryKey(),
|
||||||
|
/**
|
||||||
|
* 充电桩唯一标识符(chargeBoxIdentity)
|
||||||
|
* TLS/WebSocket 连接路径中的最后一段,CiString255Type
|
||||||
|
*/
|
||||||
chargePointIdentifier: varchar('charge_point_identifier', {
|
chargePointIdentifier: varchar('charge_point_identifier', {
|
||||||
length: 100,
|
length: 255,
|
||||||
})
|
})
|
||||||
.unique()
|
.unique()
|
||||||
.notNull(),
|
.notNull(),
|
||||||
|
/** BootNotification.req: chargePointSerialNumber, CiString25Type */
|
||||||
chargePointSerialNumber: varchar('charge_point_serial_number', {
|
chargePointSerialNumber: varchar('charge_point_serial_number', {
|
||||||
length: 25,
|
length: 25,
|
||||||
}),
|
}),
|
||||||
|
/** BootNotification.req: chargePointModel, CiString20Type (required) */
|
||||||
chargePointModel: varchar('charge_point_model', { length: 20 }).notNull(),
|
chargePointModel: varchar('charge_point_model', { length: 20 }).notNull(),
|
||||||
|
/** BootNotification.req: chargePointVendor, CiString20Type (required) */
|
||||||
chargePointVendor: varchar('charge_point_vendor', { length: 20 }).notNull(),
|
chargePointVendor: varchar('charge_point_vendor', { length: 20 }).notNull(),
|
||||||
|
/** BootNotification.req: firmwareVersion, CiString50Type */
|
||||||
firmwareVersion: varchar('firmware_version', { length: 50 }),
|
firmwareVersion: varchar('firmware_version', { length: 50 }),
|
||||||
|
/** BootNotification.req: iccid (SIM card), CiString20Type */
|
||||||
iccid: varchar('iccid', { length: 20 }),
|
iccid: varchar('iccid', { length: 20 }),
|
||||||
|
/** BootNotification.req: imsi, CiString20Type */
|
||||||
imsi: varchar('imsi', { length: 20 }),
|
imsi: varchar('imsi', { length: 20 }),
|
||||||
|
/** BootNotification.req: meterSerialNumber, CiString25Type */
|
||||||
meterSerialNumber: varchar('meter_serial_number', { length: 25 }),
|
meterSerialNumber: varchar('meter_serial_number', { length: 25 }),
|
||||||
|
/** BootNotification.req: meterType, CiString25Type */
|
||||||
meterType: varchar('meter_type', { length: 25 }),
|
meterType: varchar('meter_type', { length: 25 }),
|
||||||
createdAt: timestamp('created_at').notNull().defaultNow(),
|
/**
|
||||||
updatedAt: timestamp('updated_at')
|
* BootNotification.conf: status
|
||||||
|
* Accepted = 正常运行,Pending = 等待配置,Rejected = 拒绝(不提供服务)
|
||||||
|
*/
|
||||||
|
registrationStatus: varchar('registration_status', {
|
||||||
|
enum: ['Accepted', 'Pending', 'Rejected'],
|
||||||
|
})
|
||||||
|
.notNull()
|
||||||
|
.default('Pending'),
|
||||||
|
/**
|
||||||
|
* BootNotification.conf: heartbeatInterval(秒)
|
||||||
|
* CSMS 通知充电桩应以此间隔发送心跳
|
||||||
|
*/
|
||||||
|
heartbeatInterval: integer('heartbeat_interval').default(60),
|
||||||
|
/** 最后一次收到 Heartbeat.req 的时间(UTC) */
|
||||||
|
lastHeartbeatAt: timestamp('last_heartbeat_at', { withTimezone: true }),
|
||||||
|
/** 最后一次收到 BootNotification.req 的时间(UTC) */
|
||||||
|
lastBootNotificationAt: timestamp('last_boot_notification_at', {
|
||||||
|
withTimezone: true,
|
||||||
|
}),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
updatedAt: timestamp('updated_at', { withTimezone: true })
|
||||||
.notNull()
|
.notNull()
|
||||||
.defaultNow()
|
.defaultNow()
|
||||||
.$onUpdate(() => new Date()),
|
.$onUpdate(() => new Date()),
|
||||||
})
|
})
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 连接器 / Connector
|
||||||
|
// OCPP 1.6-J Section 4.6 StatusNotification
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 连接器表
|
* 连接器 ID 规范(OCPP 1.6-J Section 2.2):
|
||||||
* OCPP 1.6-J 2.2术语定义:
|
* - connectorId = 0:主控制器(StatusNotification 中用于报告整桩状态)
|
||||||
* "Connector" 指充电桩上可独立操作和管理的电气插座。通常对应单个物理连接器,
|
* - connectorId ≥ 1:实际插口,从 1 开始按顺序编号,不能跳号
|
||||||
* 但某些情况下一个插座可能有多个物理插座类型和/或拴住的电缆/连接器安排
|
|
||||||
* 以适应不同的车辆类型(如四轮电动汽车和电动滑板车)。
|
|
||||||
*
|
|
||||||
* 连接器ID规范:
|
|
||||||
* - 第一个连接器的ID必须是1
|
|
||||||
* - 额外的连接器必须按顺序编号(不能跳过)
|
|
||||||
* - 连接器ID不能超过充电桩的总连接器数
|
|
||||||
* - ID为0保留用于主控制器(在报告时)或整个充电桩(在中央系统的操作时)
|
|
||||||
*/
|
*/
|
||||||
export const connector = pgTable(
|
export const connector = pgTable(
|
||||||
'connector',
|
'connector',
|
||||||
@@ -55,26 +92,12 @@ export const connector = pgTable(
|
|||||||
chargePointId: varchar('charge_point_id')
|
chargePointId: varchar('charge_point_id')
|
||||||
.notNull()
|
.notNull()
|
||||||
.references(() => chargePoint.id, { onDelete: 'cascade' }),
|
.references(() => chargePoint.id, { onDelete: 'cascade' }),
|
||||||
/**
|
/** OCPP connectorId(0 = 主控制器,≥1 = 实际插口) */
|
||||||
* 连接器编号(connectorId)
|
|
||||||
* OCPP 1.6-J 6.47 StatusNotification.req:
|
|
||||||
* "The id of the connector for which the status is reported.
|
|
||||||
* Id '0' (zero) is used if the status is for the Charge Point main controller."
|
|
||||||
* connectorId > 0 对实际连接器, connectorId = 0 表示主控制器
|
|
||||||
*/
|
|
||||||
connectorId: integer('connector_id').notNull(),
|
connectorId: integer('connector_id').notNull(),
|
||||||
/**
|
/**
|
||||||
* 当前状态(status字段)
|
* 当前状态 — OCPP 1.6-J Section 7.7 ChargePointStatus
|
||||||
* OCPP 1.6-J 7.7 ChargePointStatus:
|
* Available / Preparing / Charging / SuspendedEVSE / SuspendedEV /
|
||||||
* - Available: 连接器可用于新用户
|
* Finishing / Reserved / Unavailable / Faulted
|
||||||
* - Preparing: 用户提示卡、插入电缆或车辆占用停泊位时
|
|
||||||
* - Charging: 接触器闭合,允许车辆充电
|
|
||||||
* - SuspendedEVSE: EV连接但EVSE不提供能量
|
|
||||||
* - SuspendedEV: EVSE提供能量但EV不取用
|
|
||||||
* - Finishing: 交易已停止但连接器未准备好新用户
|
|
||||||
* - Reserved: 连接器因ReserveNow命令被保留
|
|
||||||
* - Unavailable: 因ChangeAvailability命令不可用(非运行态)
|
|
||||||
* - Faulted: 充电桩或连接器报告错误且不可用(非运行态)
|
|
||||||
*/
|
*/
|
||||||
status: varchar('status', {
|
status: varchar('status', {
|
||||||
enum: [
|
enum: [
|
||||||
@@ -88,11 +111,10 @@ export const connector = pgTable(
|
|||||||
'Unavailable',
|
'Unavailable',
|
||||||
'Faulted',
|
'Faulted',
|
||||||
],
|
],
|
||||||
}).notNull(),
|
})
|
||||||
/**
|
.notNull()
|
||||||
* 错误代码(errorCode字段)
|
.default('Unavailable'),
|
||||||
* OCPP 1.6-J 7.6 ChargePointErrorCode
|
/** 错误码 — OCPP 1.6-J Section 7.6 ChargePointErrorCode */
|
||||||
*/
|
|
||||||
errorCode: varchar('error_code', {
|
errorCode: varchar('error_code', {
|
||||||
enum: [
|
enum: [
|
||||||
'NoError',
|
'NoError',
|
||||||
@@ -115,32 +137,20 @@ export const connector = pgTable(
|
|||||||
})
|
})
|
||||||
.notNull()
|
.notNull()
|
||||||
.default('NoError'),
|
.default('NoError'),
|
||||||
/**
|
/** StatusNotification.req: info, CiString50Type */
|
||||||
* 供应商标识(vendorId字段)
|
|
||||||
* OCPP 1.6-J 6.47: "This identifies the vendor-specific implementation."
|
|
||||||
* CiString255Type - 不超过255个字符
|
|
||||||
*/
|
|
||||||
vendorId: varchar('vendor_id', { length: 255 }),
|
|
||||||
/**
|
|
||||||
* 供应商特定错误代码(vendorErrorCode字段)
|
|
||||||
* OCPP 1.6-J 6.47: "This contains the vendor-specific error code."
|
|
||||||
* CiString50Type - 不超过50个字符
|
|
||||||
*/
|
|
||||||
vendorErrorCode: varchar('vendor_error_code', { length: 50 }),
|
|
||||||
/**
|
|
||||||
* 附加信息(info字段)
|
|
||||||
* OCPP 1.6-J 6.47: "Additional free format information related to the error."
|
|
||||||
* CiString50Type - 不超过50个字符
|
|
||||||
*/
|
|
||||||
info: varchar('info', { length: 50 }),
|
info: varchar('info', { length: 50 }),
|
||||||
/**
|
/** StatusNotification.req: vendorId, CiString255Type */
|
||||||
* 最后一次状态更新时间
|
vendorId: varchar('vendor_id', { length: 255 }),
|
||||||
* OCPP 1.6-J 6.47: "The time for which the status is reported.
|
/** StatusNotification.req: vendorErrorCode, CiString50Type */
|
||||||
* If absent time of receipt of the message will be assumed."
|
vendorErrorCode: varchar('vendor_error_code', { length: 50 }),
|
||||||
*/
|
/** StatusNotification.req: timestamp(充电桩报告的状态时间,UTC) */
|
||||||
lastStatusUpdate: timestamp('last_status_update').notNull().defaultNow(),
|
lastStatusAt: timestamp('last_status_at', { withTimezone: true })
|
||||||
createdAt: timestamp('created_at').notNull().defaultNow(),
|
.notNull()
|
||||||
updatedAt: timestamp('updated_at')
|
.defaultNow(),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
updatedAt: timestamp('updated_at', { withTimezone: true })
|
||||||
.notNull()
|
.notNull()
|
||||||
.defaultNow()
|
.defaultNow()
|
||||||
.$onUpdate(() => new Date()),
|
.$onUpdate(() => new Date()),
|
||||||
@@ -149,18 +159,18 @@ export const connector = pgTable(
|
|||||||
chargePointIdIdx: index('idx_connector_charge_point_id').on(
|
chargePointIdIdx: index('idx_connector_charge_point_id').on(
|
||||||
table.chargePointId
|
table.chargePointId
|
||||||
),
|
),
|
||||||
connectorIdIdx: index('idx_connector_connector_id').on(
|
/** 同一充电桩内 connectorId 唯一 */
|
||||||
table.chargePointId,
|
chargePointConnectorUniq: uniqueIndex(
|
||||||
table.connectorId
|
'idx_connector_charge_point_connector'
|
||||||
),
|
).on(table.chargePointId, table.connectorId),
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|
||||||
/**
|
// ---------------------------------------------------------------------------
|
||||||
* 连接器状态历史表
|
// 连接器状态历史 / Connector Status History
|
||||||
* 记录StatusNotification.req的完整消息内容,用于审计和历史查询
|
// 完整记录每条 StatusNotification.req,用于审计与历史回溯
|
||||||
* 对应 OCPP 1.6-J 6.47 StatusNotification.req 消息
|
// ---------------------------------------------------------------------------
|
||||||
*/
|
|
||||||
export const connectorStatusHistory = pgTable(
|
export const connectorStatusHistory = pgTable(
|
||||||
'connector_status_history',
|
'connector_status_history',
|
||||||
{
|
{
|
||||||
@@ -168,15 +178,8 @@ export const connectorStatusHistory = pgTable(
|
|||||||
connectorId: varchar('connector_id')
|
connectorId: varchar('connector_id')
|
||||||
.notNull()
|
.notNull()
|
||||||
.references(() => connector.id, { onDelete: 'cascade' }),
|
.references(() => connector.id, { onDelete: 'cascade' }),
|
||||||
/**
|
/** OCPP connectorId(冗余存储,方便直接查询) */
|
||||||
* 连接器编号(connectorId)
|
|
||||||
* OCPP 1.6-J 6.47: connectorId >= 0
|
|
||||||
*/
|
|
||||||
connectorNumber: integer('connector_number').notNull(),
|
connectorNumber: integer('connector_number').notNull(),
|
||||||
/**
|
|
||||||
* 状态值
|
|
||||||
* OCPP 1.6-J 7.7 ChargePointStatus
|
|
||||||
*/
|
|
||||||
status: varchar('status', {
|
status: varchar('status', {
|
||||||
enum: [
|
enum: [
|
||||||
'Available',
|
'Available',
|
||||||
@@ -190,10 +193,6 @@ export const connectorStatusHistory = pgTable(
|
|||||||
'Faulted',
|
'Faulted',
|
||||||
],
|
],
|
||||||
}).notNull(),
|
}).notNull(),
|
||||||
/**
|
|
||||||
* 错误代码
|
|
||||||
* OCPP 1.6-J 7.6 ChargePointErrorCode
|
|
||||||
*/
|
|
||||||
errorCode: varchar('error_code', {
|
errorCode: varchar('error_code', {
|
||||||
enum: [
|
enum: [
|
||||||
'NoError',
|
'NoError',
|
||||||
@@ -214,31 +213,15 @@ export const connectorStatusHistory = pgTable(
|
|||||||
'WeakSignal',
|
'WeakSignal',
|
||||||
],
|
],
|
||||||
}).notNull(),
|
}).notNull(),
|
||||||
/**
|
|
||||||
* 附加信息
|
|
||||||
* OCPP 1.6-J 6.47: "Additional free format information related to the error."
|
|
||||||
*/
|
|
||||||
info: varchar('info', { length: 50 }),
|
info: varchar('info', { length: 50 }),
|
||||||
/**
|
|
||||||
* 供应商标识
|
|
||||||
* OCPP 1.6-J 6.47: "This identifies the vendor-specific implementation."
|
|
||||||
*/
|
|
||||||
vendorId: varchar('vendor_id', { length: 255 }),
|
vendorId: varchar('vendor_id', { length: 255 }),
|
||||||
/**
|
|
||||||
* 供应商错误代码
|
|
||||||
* OCPP 1.6-J 6.47: "This contains the vendor-specific error code."
|
|
||||||
*/
|
|
||||||
vendorErrorCode: varchar('vendor_error_code', { length: 50 }),
|
vendorErrorCode: varchar('vendor_error_code', { length: 50 }),
|
||||||
/**
|
/** StatusNotification.req: timestamp(充电桩上报的状态时间) */
|
||||||
* 状态报告时间戳
|
statusTimestamp: timestamp('status_timestamp', { withTimezone: true }),
|
||||||
* OCPP 1.6-J 6.47: "The time for which the status is reported.
|
/** CSMS 收到消息的时间 */
|
||||||
* If absent time of receipt of the message will be assumed."
|
receivedAt: timestamp('received_at', { withTimezone: true })
|
||||||
*/
|
.notNull()
|
||||||
statusTimestamp: timestamp('status_timestamp'),
|
.defaultNow(),
|
||||||
/**
|
|
||||||
* 消息接收时间
|
|
||||||
*/
|
|
||||||
receivedAt: timestamp('received_at').notNull().defaultNow(),
|
|
||||||
},
|
},
|
||||||
(table) => ({
|
(table) => ({
|
||||||
connectorIdIdx: index('idx_status_history_connector_id').on(
|
connectorIdIdx: index('idx_status_history_connector_id').on(
|
||||||
@@ -252,3 +235,481 @@ export const connectorStatusHistory = pgTable(
|
|||||||
),
|
),
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 认证标签 / IdTag
|
||||||
|
// OCPP 1.6-J Section 4.1 Authorize / Section 7.15 IdTagInfo
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export const idTag = pgTable('id_tag', {
|
||||||
|
/**
|
||||||
|
* RFID 卡号或 App 生成的令牌,CiString20Type
|
||||||
|
* 对应 OCPP Authorize.req.idTag
|
||||||
|
*/
|
||||||
|
idTag: varchar('id_tag', { length: 20 }).primaryKey(),
|
||||||
|
/**
|
||||||
|
* 父标签(用于分组授权),CiString20Type
|
||||||
|
* 当 parentIdTag 在本地列表被接受时,子标签同样被接受
|
||||||
|
*/
|
||||||
|
parentIdTag: varchar('parent_id_tag', { length: 20 }),
|
||||||
|
/**
|
||||||
|
* 标签当前状态 — OCPP 1.6-J Section 7.14 AuthorizationStatus
|
||||||
|
* Accepted / Blocked / Expired / Invalid / ConcurrentTx
|
||||||
|
*/
|
||||||
|
status: varchar('status', {
|
||||||
|
enum: ['Accepted', 'Blocked', 'Expired', 'Invalid', 'ConcurrentTx'],
|
||||||
|
})
|
||||||
|
.notNull()
|
||||||
|
.default('Accepted'),
|
||||||
|
/**
|
||||||
|
* 过期时间(UTC)
|
||||||
|
* 若设置,CSMS 在 Authorize.conf 中会返回此字段供充电桩离线缓存使用
|
||||||
|
*/
|
||||||
|
expiryDate: timestamp('expiry_date', { withTimezone: true }),
|
||||||
|
/**
|
||||||
|
* 关联的平台用户(可选)
|
||||||
|
* 允许将 RFID 卡与注册用户绑定,支持 Web/App 远程查询充电记录
|
||||||
|
*/
|
||||||
|
userId: text('user_id').references(() => user.id, { onDelete: 'set null' }),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
updatedAt: timestamp('updated_at', { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow()
|
||||||
|
.$onUpdate(() => new Date()),
|
||||||
|
})
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 充电事务 / Transaction
|
||||||
|
// OCPP 1.6-J Section 4.3 StartTransaction / Section 4.4 StopTransaction
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export const transaction = pgTable(
|
||||||
|
'transaction',
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* OCPP transactionId(整型,自增)
|
||||||
|
* OCPP 1.6-J Section 4.3: "The transaction id MAY be a number ... it MUST be unique."
|
||||||
|
* 使用 serial 保证全局唯一且自动递增
|
||||||
|
*/
|
||||||
|
id: serial('id').primaryKey(),
|
||||||
|
chargePointId: varchar('charge_point_id')
|
||||||
|
.notNull()
|
||||||
|
.references(() => chargePoint.id, { onDelete: 'cascade' }),
|
||||||
|
connectorId: varchar('connector_id')
|
||||||
|
.notNull()
|
||||||
|
.references(() => connector.id, { onDelete: 'cascade' }),
|
||||||
|
/** OCPP connectorId(冗余存储,方便直接查询) */
|
||||||
|
connectorNumber: integer('connector_number').notNull(),
|
||||||
|
/**
|
||||||
|
* 发起充电的 idTag,CiString20Type
|
||||||
|
* StartTransaction.req.idTag
|
||||||
|
*/
|
||||||
|
idTag: varchar('id_tag', { length: 20 }).notNull(),
|
||||||
|
/**
|
||||||
|
* CSMS 对 idTag 的鉴权结果(StartTransaction.conf 中返回)
|
||||||
|
* OCPP 1.6-J Section 7.14 AuthorizationStatus
|
||||||
|
*/
|
||||||
|
idTagStatus: varchar('id_tag_status', {
|
||||||
|
enum: ['Accepted', 'Blocked', 'Expired', 'Invalid', 'ConcurrentTx'],
|
||||||
|
}),
|
||||||
|
/**
|
||||||
|
* 充电开始时间(充电桩本地时间,UTC)
|
||||||
|
* StartTransaction.req.timestamp
|
||||||
|
*/
|
||||||
|
startTimestamp: timestamp('start_timestamp', {
|
||||||
|
withTimezone: true,
|
||||||
|
}).notNull(),
|
||||||
|
/**
|
||||||
|
* 开始时的电表读数(Wh)
|
||||||
|
* StartTransaction.req.meterStart
|
||||||
|
*/
|
||||||
|
startMeterValue: integer('start_meter_value').notNull(),
|
||||||
|
/**
|
||||||
|
* 停止充电的 idTag(可能与 idTag 不同,如工作人员强制停止)
|
||||||
|
* StopTransaction.req.idTag(optional)
|
||||||
|
*/
|
||||||
|
stopIdTag: varchar('stop_id_tag', { length: 20 }),
|
||||||
|
/**
|
||||||
|
* 充电结束时间(UTC)
|
||||||
|
* StopTransaction.req.timestamp
|
||||||
|
*/
|
||||||
|
stopTimestamp: timestamp('stop_timestamp', { withTimezone: true }),
|
||||||
|
/**
|
||||||
|
* 结束时的电表读数(Wh)
|
||||||
|
* StopTransaction.req.meterStop
|
||||||
|
*/
|
||||||
|
stopMeterValue: integer('stop_meter_value'),
|
||||||
|
/**
|
||||||
|
* 停止原因 — OCPP 1.6-J Section 7.20 Reason
|
||||||
|
* EmergencyStop / EVDisconnected / HardReset / Local / Other /
|
||||||
|
* PowerLoss / Reboot / Remote / SoftReset / UnlockCommand / DeAuthorized
|
||||||
|
*/
|
||||||
|
stopReason: varchar('stop_reason', {
|
||||||
|
enum: [
|
||||||
|
'EmergencyStop',
|
||||||
|
'EVDisconnected',
|
||||||
|
'HardReset',
|
||||||
|
'Local',
|
||||||
|
'Other',
|
||||||
|
'PowerLoss',
|
||||||
|
'Reboot',
|
||||||
|
'Remote',
|
||||||
|
'SoftReset',
|
||||||
|
'UnlockCommand',
|
||||||
|
'DeAuthorized',
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
/**
|
||||||
|
* 关联的预约 ID(若本次充电由预约触发)
|
||||||
|
* StartTransaction.req.reservationId(optional)
|
||||||
|
*/
|
||||||
|
reservationId: integer('reservation_id'),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
updatedAt: timestamp('updated_at', { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow()
|
||||||
|
.$onUpdate(() => new Date()),
|
||||||
|
},
|
||||||
|
(table) => ({
|
||||||
|
chargePointIdIdx: index('idx_transaction_charge_point_id').on(
|
||||||
|
table.chargePointId
|
||||||
|
),
|
||||||
|
connectorIdIdx: index('idx_transaction_connector_id').on(
|
||||||
|
table.connectorId
|
||||||
|
),
|
||||||
|
idTagIdx: index('idx_transaction_id_tag').on(table.idTag),
|
||||||
|
startTimestampIdx: index('idx_transaction_start_timestamp').on(
|
||||||
|
table.startTimestamp
|
||||||
|
),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 计量值 / Meter Value
|
||||||
|
// OCPP 1.6-J Section 4.7 MeterValues;也内嵌于 StartTransaction / StopTransaction
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/** SampledValue 类型定义(对应 OCPP 1.6-J Section 7.17) */
|
||||||
|
export type SampledValue = {
|
||||||
|
/** 测量值(字符串形式) */
|
||||||
|
value: string
|
||||||
|
/**
|
||||||
|
* 读数上下文 — ReadingContext
|
||||||
|
* Interruption.Begin / Interruption.End / Sample.Clock /
|
||||||
|
* Sample.Periodic / Transaction.Begin / Transaction.End / Trigger / Other
|
||||||
|
*/
|
||||||
|
context?:
|
||||||
|
| 'Interruption.Begin'
|
||||||
|
| 'Interruption.End'
|
||||||
|
| 'Sample.Clock'
|
||||||
|
| 'Sample.Periodic'
|
||||||
|
| 'Transaction.Begin'
|
||||||
|
| 'Transaction.End'
|
||||||
|
| 'Trigger'
|
||||||
|
| 'Other'
|
||||||
|
/** 数据格式:Raw(原始数值)/ SignedData(签名数据) */
|
||||||
|
format?: 'Raw' | 'SignedData'
|
||||||
|
/**
|
||||||
|
* 测量量 — Measurand(常用值)
|
||||||
|
* Energy.Active.Import.Register / Power.Active.Import /
|
||||||
|
* Current.Import / Voltage / SoC / Temperature 等
|
||||||
|
*/
|
||||||
|
measurand?: string
|
||||||
|
/** 相位信息(三相系统):L1 / L2 / L3 / N / L1-N / L2-N / L3-N / L1-L2 / L2-L3 / L3-L1 */
|
||||||
|
phase?: string
|
||||||
|
/** 测量位置:Cable / EV / Inlet / Outlet / Body */
|
||||||
|
location?: string
|
||||||
|
/** 单位:Wh / kWh / varh / kvarh / W / kW / VA / kVA / var / kvar / A / V / K / Celcius / Fahrenheit / Percent */
|
||||||
|
unit?: string
|
||||||
|
}
|
||||||
|
|
||||||
|
export const meterValue = pgTable(
|
||||||
|
'meter_value',
|
||||||
|
{
|
||||||
|
id: varchar('id').primaryKey(),
|
||||||
|
/**
|
||||||
|
* 关联的充电事务(可 null,如充电桩空闲时上报的周期性计量值)
|
||||||
|
* MeterValues.req.transactionId(optional)
|
||||||
|
*/
|
||||||
|
transactionId: integer('transaction_id').references(() => transaction.id, {
|
||||||
|
onDelete: 'set null',
|
||||||
|
}),
|
||||||
|
connectorId: varchar('connector_id')
|
||||||
|
.notNull()
|
||||||
|
.references(() => connector.id, { onDelete: 'cascade' }),
|
||||||
|
chargePointId: varchar('charge_point_id')
|
||||||
|
.notNull()
|
||||||
|
.references(() => chargePoint.id, { onDelete: 'cascade' }),
|
||||||
|
/** OCPP connectorId(冗余存储) */
|
||||||
|
connectorNumber: integer('connector_number').notNull(),
|
||||||
|
/**
|
||||||
|
* 充电桩上报的计量时间戳(UTC)
|
||||||
|
* MeterValues.req.meterValue[].timestamp
|
||||||
|
*/
|
||||||
|
timestamp: timestamp('timestamp', { withTimezone: true }).notNull(),
|
||||||
|
/**
|
||||||
|
* 采样值数组(JSONB)
|
||||||
|
* MeterValues.req.meterValue[].sampledValue[]
|
||||||
|
* 保持 JSONB 格式以支持 measurand 类型不固定的场景
|
||||||
|
*/
|
||||||
|
sampledValues: jsonb('sampled_values')
|
||||||
|
.notNull()
|
||||||
|
.$type<SampledValue[]>(),
|
||||||
|
/** CSMS 收到消息的时间 */
|
||||||
|
receivedAt: timestamp('received_at', { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => ({
|
||||||
|
transactionIdIdx: index('idx_meter_value_transaction_id').on(
|
||||||
|
table.transactionId
|
||||||
|
),
|
||||||
|
connectorIdIdx: index('idx_meter_value_connector_id').on(
|
||||||
|
table.connectorId
|
||||||
|
),
|
||||||
|
timestampIdx: index('idx_meter_value_timestamp').on(table.timestamp),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 预约 / Reservation
|
||||||
|
// OCPP 1.6-J Section 3.11 ReserveNow / Section 3.2 CancelReservation
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
export const reservation = pgTable(
|
||||||
|
'reservation',
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* OCPP reservationId(整型,由 CSMS 分配)
|
||||||
|
* ReserveNow.req.reservationId
|
||||||
|
*/
|
||||||
|
id: integer('id').primaryKey(),
|
||||||
|
chargePointId: varchar('charge_point_id')
|
||||||
|
.notNull()
|
||||||
|
.references(() => chargePoint.id, { onDelete: 'cascade' }),
|
||||||
|
/**
|
||||||
|
* 关联的内部连接器记录(可 null:connectorId=0 表示任意可用插口)
|
||||||
|
*/
|
||||||
|
connectorId: varchar('connector_id').references(() => connector.id, {
|
||||||
|
onDelete: 'set null',
|
||||||
|
}),
|
||||||
|
/**
|
||||||
|
* OCPP connectorId(0 = 整桩任意插口,≥1 = 指定插口)
|
||||||
|
* ReserveNow.req.connectorId
|
||||||
|
*/
|
||||||
|
connectorNumber: integer('connector_number').notNull(),
|
||||||
|
/**
|
||||||
|
* 预约到期时间(UTC)
|
||||||
|
* ReserveNow.req.expiryDate
|
||||||
|
*/
|
||||||
|
expiryDate: timestamp('expiry_date', { withTimezone: true }).notNull(),
|
||||||
|
/**
|
||||||
|
* 预约使用的 idTag,CiString20Type
|
||||||
|
* ReserveNow.req.idTag
|
||||||
|
*/
|
||||||
|
idTag: varchar('id_tag', { length: 20 }).notNull(),
|
||||||
|
/**
|
||||||
|
* 可选的父标签(用于允许同组任意 idTag 使用本预约)
|
||||||
|
* ReserveNow.req.parentIdTag
|
||||||
|
*/
|
||||||
|
parentIdTag: varchar('parent_id_tag', { length: 20 }),
|
||||||
|
/**
|
||||||
|
* 预约状态(扩展字段,非 OCPP 原生)
|
||||||
|
* Active = 有效中,Cancelled = 已取消,Expired = 已过期,Used = 已使用
|
||||||
|
*/
|
||||||
|
status: varchar('status', {
|
||||||
|
enum: ['Active', 'Cancelled', 'Expired', 'Used'],
|
||||||
|
})
|
||||||
|
.notNull()
|
||||||
|
.default('Active'),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
updatedAt: timestamp('updated_at', { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow()
|
||||||
|
.$onUpdate(() => new Date()),
|
||||||
|
},
|
||||||
|
(table) => ({
|
||||||
|
chargePointIdIdx: index('idx_reservation_charge_point_id').on(
|
||||||
|
table.chargePointId
|
||||||
|
),
|
||||||
|
statusIdx: index('idx_reservation_status').on(table.status),
|
||||||
|
expiryDateIdx: index('idx_reservation_expiry_date').on(table.expiryDate),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 本地授权列表 / Local Auth List
|
||||||
|
// OCPP 1.6-J Section 3.9 SendLocalList / Section 3.8 GetLocalListVersion
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 充电桩本地授权列表缓存
|
||||||
|
*
|
||||||
|
* 充电桩断网时依赖本地列表进行离线授权。CSMS 通过 SendLocalList 将列表
|
||||||
|
* 推送至充电桩,每次推送携带 listVersion(单调递增整数)。
|
||||||
|
* CSMS 侧同步维护此表,以便在需要时重新推送或审计。
|
||||||
|
*/
|
||||||
|
export const localAuthList = pgTable(
|
||||||
|
'local_auth_list',
|
||||||
|
{
|
||||||
|
id: varchar('id').primaryKey(),
|
||||||
|
chargePointId: varchar('charge_point_id')
|
||||||
|
.notNull()
|
||||||
|
.references(() => chargePoint.id, { onDelete: 'cascade' }),
|
||||||
|
/**
|
||||||
|
* 列表版本号(单调递增)
|
||||||
|
* SendLocalList.req.listVersion
|
||||||
|
*/
|
||||||
|
listVersion: integer('list_version').notNull(),
|
||||||
|
/** idTag,CiString20Type */
|
||||||
|
idTag: varchar('id_tag', { length: 20 }).notNull(),
|
||||||
|
/** 可选父标签 */
|
||||||
|
parentIdTag: varchar('parent_id_tag', { length: 20 }),
|
||||||
|
/** 本地授权状态 — AuthorizationStatus */
|
||||||
|
idTagStatus: varchar('id_tag_status', {
|
||||||
|
enum: ['Accepted', 'Blocked', 'Expired', 'Invalid', 'ConcurrentTx'],
|
||||||
|
}).notNull(),
|
||||||
|
/** 过期时间(UTC,可选) */
|
||||||
|
expiryDate: timestamp('expiry_date', { withTimezone: true }),
|
||||||
|
updatedAt: timestamp('updated_at', { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow()
|
||||||
|
.$onUpdate(() => new Date()),
|
||||||
|
},
|
||||||
|
(table) => ({
|
||||||
|
/** 同一充电桩内同一 idTag 唯一 */
|
||||||
|
chargePointIdTagUniq: uniqueIndex(
|
||||||
|
'idx_local_auth_list_charge_point_id_tag'
|
||||||
|
).on(table.chargePointId, table.idTag),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// 充电配置文件 / Charging Profile
|
||||||
|
// OCPP 1.6-J Section 3.12 SetChargingProfile(Smart Charging Profile)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ChargingSchedulePeriod 类型(对应 OCPP 1.6-J Section 7.8)
|
||||||
|
* 描述某一时间段内的充电限制
|
||||||
|
*/
|
||||||
|
export type ChargingSchedulePeriod = {
|
||||||
|
/** 距 chargingSchedule.startSchedule 的偏移秒数 */
|
||||||
|
startPeriod: number
|
||||||
|
/** 最大充电限制(单位由 chargingRateUnit 决定:W 或 A) */
|
||||||
|
limit: number
|
||||||
|
/** 可选:允许使用的相数(1 或 3) */
|
||||||
|
numberPhases?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* ChargingSchedule 类型(对应 OCPP 1.6-J Section 7.9)
|
||||||
|
*/
|
||||||
|
export type ChargingSchedule = {
|
||||||
|
/** 总时长(秒,可选)*/
|
||||||
|
duration?: number
|
||||||
|
/** 计划开始时间(UTC ISO 8601,可选,Absolute 类型时使用) */
|
||||||
|
startSchedule?: string
|
||||||
|
/** 限制单位:W(瓦特)或 A(安培) */
|
||||||
|
chargingRateUnit: 'W' | 'A'
|
||||||
|
/** 各时间段的限制列表(按 startPeriod 升序排列) */
|
||||||
|
chargingSchedulePeriod: ChargingSchedulePeriod[]
|
||||||
|
/** 最小充电速率(W / A,可选) */
|
||||||
|
minChargingRate?: number
|
||||||
|
}
|
||||||
|
|
||||||
|
export const chargingProfile = pgTable(
|
||||||
|
'charging_profile',
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* OCPP chargingProfileId(整型,由 CSMS 分配)
|
||||||
|
* SetChargingProfile.req.csChargingProfiles.chargingProfileId
|
||||||
|
*/
|
||||||
|
id: integer('id').primaryKey(),
|
||||||
|
chargePointId: varchar('charge_point_id')
|
||||||
|
.notNull()
|
||||||
|
.references(() => chargePoint.id, { onDelete: 'cascade' }),
|
||||||
|
/**
|
||||||
|
* 关联的内部连接器(0 表示整桩级别的配置文件,对应 connectorId=0)
|
||||||
|
*/
|
||||||
|
connectorId: varchar('connector_id').references(() => connector.id, {
|
||||||
|
onDelete: 'cascade',
|
||||||
|
}),
|
||||||
|
/** OCPP connectorId(0 = 充电桩级别,≥1 = 指定插口) */
|
||||||
|
connectorNumber: integer('connector_number').notNull(),
|
||||||
|
/**
|
||||||
|
* 关联的事务 ID(仅 TxProfile 类型时有效)
|
||||||
|
* SetChargingProfile.req.csChargingProfiles.transactionId
|
||||||
|
*/
|
||||||
|
transactionId: integer('transaction_id').references(() => transaction.id, {
|
||||||
|
onDelete: 'set null',
|
||||||
|
}),
|
||||||
|
/**
|
||||||
|
* 优先级堆叠层级(数值越高,优先级越高)
|
||||||
|
* SetChargingProfile.req.csChargingProfiles.stackLevel
|
||||||
|
*/
|
||||||
|
stackLevel: integer('stack_level').notNull(),
|
||||||
|
/**
|
||||||
|
* 配置文件用途 — ChargingProfilePurposeType
|
||||||
|
* ChargePointMaxProfile:限制整桩最大功率
|
||||||
|
* TxDefaultProfile:默认事务充电功率
|
||||||
|
* TxProfile:绑定到特定事务的充电功率
|
||||||
|
*/
|
||||||
|
chargingProfilePurpose: varchar('charging_profile_purpose', {
|
||||||
|
enum: ['ChargePointMaxProfile', 'TxDefaultProfile', 'TxProfile'],
|
||||||
|
}).notNull(),
|
||||||
|
/**
|
||||||
|
* 配置文件类型 — ChargingProfileKindType
|
||||||
|
* Absolute:从指定时间点开始
|
||||||
|
* Recurring:周期性重复(Daily / Weekly)
|
||||||
|
* Relative:相对于事务开始时间
|
||||||
|
*/
|
||||||
|
chargingProfileKind: varchar('charging_profile_kind', {
|
||||||
|
enum: ['Absolute', 'Recurring', 'Relative'],
|
||||||
|
}).notNull(),
|
||||||
|
/**
|
||||||
|
* 周期类型(仅 Recurring 类型时有效)
|
||||||
|
* Daily / Weekly
|
||||||
|
*/
|
||||||
|
recurrencyKind: varchar('recurrency_kind', {
|
||||||
|
enum: ['Daily', 'Weekly'],
|
||||||
|
}),
|
||||||
|
/** 配置文件生效时间(UTC,可选) */
|
||||||
|
validFrom: timestamp('valid_from', { withTimezone: true }),
|
||||||
|
/** 配置文件失效时间(UTC,可选) */
|
||||||
|
validTo: timestamp('valid_to', { withTimezone: true }),
|
||||||
|
/**
|
||||||
|
* 充电计划(JSONB)
|
||||||
|
* SetChargingProfile.req.csChargingProfiles.chargingSchedule
|
||||||
|
*/
|
||||||
|
chargingSchedule: jsonb('charging_schedule')
|
||||||
|
.notNull()
|
||||||
|
.$type<ChargingSchedule>(),
|
||||||
|
createdAt: timestamp('created_at', { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
updatedAt: timestamp('updated_at', { withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow()
|
||||||
|
.$onUpdate(() => new Date()),
|
||||||
|
},
|
||||||
|
(table) => ({
|
||||||
|
chargePointIdIdx: index('idx_charging_profile_charge_point_id').on(
|
||||||
|
table.chargePointId
|
||||||
|
),
|
||||||
|
connectorIdIdx: index('idx_charging_profile_connector_id').on(
|
||||||
|
table.connectorId
|
||||||
|
),
|
||||||
|
purposeStackIdx: index('idx_charging_profile_purpose_stack').on(
|
||||||
|
table.connectorNumber,
|
||||||
|
table.chargingProfilePurpose,
|
||||||
|
table.stackLevel
|
||||||
|
),
|
||||||
|
})
|
||||||
|
)
|
||||||
|
|||||||
@@ -7,11 +7,7 @@ import { cors } from 'hono/cors'
|
|||||||
import { logger } from 'hono/logger'
|
import { logger } from 'hono/logger'
|
||||||
import { showRoutes } from 'hono/dev'
|
import { showRoutes } from 'hono/dev'
|
||||||
import { auth } from './lib/auth.ts'
|
import { auth } from './lib/auth.ts'
|
||||||
import {
|
import { createOcppHandler } from './ocpp/handler.ts'
|
||||||
isSupportedOCPP,
|
|
||||||
SUPPORTED_OCPP_VERSIONS,
|
|
||||||
type SupportedOCPPVersion,
|
|
||||||
} from './constants.ts'
|
|
||||||
|
|
||||||
const app = new Hono<{
|
const app = new Hono<{
|
||||||
Variables: {
|
Variables: {
|
||||||
@@ -74,28 +70,8 @@ app.get(
|
|||||||
'/ocpp/:chargePointId',
|
'/ocpp/:chargePointId',
|
||||||
upgradeWebSocket((c) => {
|
upgradeWebSocket((c) => {
|
||||||
const chargePointId = c.req.param('chargePointId')
|
const chargePointId = c.req.param('chargePointId')
|
||||||
|
|
||||||
return {
|
|
||||||
onOpen(evt, ws) {
|
|
||||||
const subProtocol = ws.protocol || 'unknown'
|
|
||||||
if (!isSupportedOCPP(subProtocol)) {
|
|
||||||
ws.close(1002, 'Unsupported subprotocol')
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
const connInfo = getConnInfo(c)
|
const connInfo = getConnInfo(c)
|
||||||
console.log(
|
return createOcppHandler(chargePointId, connInfo.remote.address)
|
||||||
`New connection from ${connInfo.remote.address}:${connInfo.remote.port} for station ${chargePointId}`,
|
|
||||||
)
|
|
||||||
},
|
|
||||||
onMessage(evt, ws) {
|
|
||||||
console.log(`Received message: ${evt.data}`)
|
|
||||||
ws.send(`Echo: ${evt.data}`)
|
|
||||||
},
|
|
||||||
onClose(evt, ws) {
|
|
||||||
console.log('Connection closed: ', evt.code, evt.reason)
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}),
|
}),
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
61
apps/csms/src/ocpp/actions/boot-notification.ts
Normal file
61
apps/csms/src/ocpp/actions/boot-notification.ts
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
import { useDrizzle } from '@/lib/db.js'
|
||||||
|
import { chargePoint } from '@/db/schema.js'
|
||||||
|
import type {
|
||||||
|
BootNotificationRequest,
|
||||||
|
BootNotificationResponse,
|
||||||
|
OcppConnectionContext,
|
||||||
|
} from '../types.ts'
|
||||||
|
|
||||||
|
const DEFAULT_HEARTBEAT_INTERVAL = 60
|
||||||
|
|
||||||
|
export async function handleBootNotification(
|
||||||
|
payload: BootNotificationRequest,
|
||||||
|
ctx: OcppConnectionContext,
|
||||||
|
): Promise<BootNotificationResponse> {
|
||||||
|
const db = useDrizzle()
|
||||||
|
|
||||||
|
await db
|
||||||
|
.insert(chargePoint)
|
||||||
|
.values({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
chargePointIdentifier: ctx.chargePointIdentifier,
|
||||||
|
chargePointVendor: payload.chargePointVendor,
|
||||||
|
chargePointModel: payload.chargePointModel,
|
||||||
|
chargePointSerialNumber: payload.chargePointSerialNumber ?? null,
|
||||||
|
firmwareVersion: payload.firmwareVersion ?? null,
|
||||||
|
iccid: payload.iccid ?? null,
|
||||||
|
imsi: payload.imsi ?? null,
|
||||||
|
meterType: payload.meterType ?? null,
|
||||||
|
meterSerialNumber: payload.meterSerialNumber ?? null,
|
||||||
|
registrationStatus: 'Accepted',
|
||||||
|
heartbeatInterval: DEFAULT_HEARTBEAT_INTERVAL,
|
||||||
|
lastBootNotificationAt: new Date(),
|
||||||
|
})
|
||||||
|
.onConflictDoUpdate({
|
||||||
|
target: chargePoint.chargePointIdentifier,
|
||||||
|
set: {
|
||||||
|
chargePointVendor: payload.chargePointVendor,
|
||||||
|
chargePointModel: payload.chargePointModel,
|
||||||
|
chargePointSerialNumber: payload.chargePointSerialNumber ?? null,
|
||||||
|
firmwareVersion: payload.firmwareVersion ?? null,
|
||||||
|
iccid: payload.iccid ?? null,
|
||||||
|
imsi: payload.imsi ?? null,
|
||||||
|
meterType: payload.meterType ?? null,
|
||||||
|
meterSerialNumber: payload.meterSerialNumber ?? null,
|
||||||
|
registrationStatus: 'Accepted',
|
||||||
|
heartbeatInterval: DEFAULT_HEARTBEAT_INTERVAL,
|
||||||
|
lastBootNotificationAt: new Date(),
|
||||||
|
updatedAt: new Date(),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
ctx.isRegistered = true
|
||||||
|
|
||||||
|
console.log(`[OCPP] BootNotification accepted: ${ctx.chargePointIdentifier}`)
|
||||||
|
|
||||||
|
return {
|
||||||
|
currentTime: new Date().toISOString(),
|
||||||
|
interval: DEFAULT_HEARTBEAT_INTERVAL,
|
||||||
|
status: 'Accepted',
|
||||||
|
}
|
||||||
|
}
|
||||||
24
apps/csms/src/ocpp/actions/heartbeat.ts
Normal file
24
apps/csms/src/ocpp/actions/heartbeat.ts
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
import { eq } from 'drizzle-orm'
|
||||||
|
import { useDrizzle } from '@/lib/db.js'
|
||||||
|
import { chargePoint } from '@/db/schema.js'
|
||||||
|
import type {
|
||||||
|
HeartbeatRequest,
|
||||||
|
HeartbeatResponse,
|
||||||
|
OcppConnectionContext,
|
||||||
|
} from '../types.ts'
|
||||||
|
|
||||||
|
export async function handleHeartbeat(
|
||||||
|
_payload: HeartbeatRequest,
|
||||||
|
ctx: OcppConnectionContext,
|
||||||
|
): Promise<HeartbeatResponse> {
|
||||||
|
const db = useDrizzle()
|
||||||
|
|
||||||
|
await db
|
||||||
|
.update(chargePoint)
|
||||||
|
.set({ lastHeartbeatAt: new Date() })
|
||||||
|
.where(eq(chargePoint.chargePointIdentifier, ctx.chargePointIdentifier))
|
||||||
|
|
||||||
|
return {
|
||||||
|
currentTime: new Date().toISOString(),
|
||||||
|
}
|
||||||
|
}
|
||||||
104
apps/csms/src/ocpp/actions/status-notification.ts
Normal file
104
apps/csms/src/ocpp/actions/status-notification.ts
Normal file
@@ -0,0 +1,104 @@
|
|||||||
|
import { eq, and } from 'drizzle-orm'
|
||||||
|
import { useDrizzle } from '@/lib/db.js'
|
||||||
|
import { chargePoint, connector, connectorStatusHistory } from '@/db/schema.js'
|
||||||
|
import type {
|
||||||
|
StatusNotificationRequest,
|
||||||
|
StatusNotificationResponse,
|
||||||
|
OcppConnectionContext,
|
||||||
|
} from '../types.ts'
|
||||||
|
|
||||||
|
// Mirror the enum values defined in ocpp-schema.ts for type safety
|
||||||
|
type ConnectorStatus =
|
||||||
|
| 'Available'
|
||||||
|
| 'Preparing'
|
||||||
|
| 'Charging'
|
||||||
|
| 'SuspendedEVSE'
|
||||||
|
| 'SuspendedEV'
|
||||||
|
| 'Finishing'
|
||||||
|
| 'Reserved'
|
||||||
|
| 'Unavailable'
|
||||||
|
| 'Faulted'
|
||||||
|
|
||||||
|
type ConnectorErrorCode =
|
||||||
|
| 'NoError'
|
||||||
|
| 'ConnectorLockFailure'
|
||||||
|
| 'EVCommunicationError'
|
||||||
|
| 'GroundFailure'
|
||||||
|
| 'HighTemperature'
|
||||||
|
| 'InternalError'
|
||||||
|
| 'LocalListConflict'
|
||||||
|
| 'OtherError'
|
||||||
|
| 'OverCurrentFailure'
|
||||||
|
| 'OverVoltage'
|
||||||
|
| 'PowerMeterFailure'
|
||||||
|
| 'PowerSwitchFailure'
|
||||||
|
| 'ReaderFailure'
|
||||||
|
| 'ResetFailure'
|
||||||
|
| 'UnderVoltage'
|
||||||
|
| 'WeakSignal'
|
||||||
|
|
||||||
|
export async function handleStatusNotification(
|
||||||
|
payload: StatusNotificationRequest,
|
||||||
|
ctx: OcppConnectionContext,
|
||||||
|
): Promise<StatusNotificationResponse> {
|
||||||
|
const db = useDrizzle()
|
||||||
|
|
||||||
|
// Retrieve the internal charge point id
|
||||||
|
const [cp] = await db
|
||||||
|
.select({ id: chargePoint.id })
|
||||||
|
.from(chargePoint)
|
||||||
|
.where(eq(chargePoint.chargePointIdentifier, ctx.chargePointIdentifier))
|
||||||
|
.limit(1)
|
||||||
|
|
||||||
|
if (!cp) {
|
||||||
|
throw new Error(`ChargePoint not found: ${ctx.chargePointIdentifier}`)
|
||||||
|
}
|
||||||
|
|
||||||
|
const statusTimestamp = payload.timestamp ? new Date(payload.timestamp) : new Date()
|
||||||
|
const connStatus = payload.status as ConnectorStatus
|
||||||
|
const connErrorCode = payload.errorCode as ConnectorErrorCode
|
||||||
|
|
||||||
|
// Upsert connector and return the internal id for history insertion
|
||||||
|
const [upsertedConnector] = await db
|
||||||
|
.insert(connector)
|
||||||
|
.values({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
chargePointId: cp.id,
|
||||||
|
connectorId: payload.connectorId,
|
||||||
|
status: connStatus,
|
||||||
|
errorCode: connErrorCode,
|
||||||
|
info: payload.info ?? null,
|
||||||
|
vendorId: payload.vendorId ?? null,
|
||||||
|
vendorErrorCode: payload.vendorErrorCode ?? null,
|
||||||
|
lastStatusAt: statusTimestamp,
|
||||||
|
})
|
||||||
|
.onConflictDoUpdate({
|
||||||
|
target: [connector.chargePointId, connector.connectorId],
|
||||||
|
set: {
|
||||||
|
status: connStatus,
|
||||||
|
errorCode: connErrorCode,
|
||||||
|
info: payload.info ?? null,
|
||||||
|
vendorId: payload.vendorId ?? null,
|
||||||
|
vendorErrorCode: payload.vendorErrorCode ?? null,
|
||||||
|
lastStatusAt: statusTimestamp,
|
||||||
|
updatedAt: new Date(),
|
||||||
|
},
|
||||||
|
})
|
||||||
|
.returning({ id: connector.id })
|
||||||
|
|
||||||
|
if (upsertedConnector) {
|
||||||
|
await db.insert(connectorStatusHistory).values({
|
||||||
|
id: crypto.randomUUID(),
|
||||||
|
connectorId: upsertedConnector.id,
|
||||||
|
connectorNumber: payload.connectorId,
|
||||||
|
status: connStatus,
|
||||||
|
errorCode: connErrorCode,
|
||||||
|
info: payload.info ?? null,
|
||||||
|
vendorId: payload.vendorId ?? null,
|
||||||
|
vendorErrorCode: payload.vendorErrorCode ?? null,
|
||||||
|
statusTimestamp,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return {}
|
||||||
|
}
|
||||||
142
apps/csms/src/ocpp/handler.ts
Normal file
142
apps/csms/src/ocpp/handler.ts
Normal file
@@ -0,0 +1,142 @@
|
|||||||
|
import type { WSContext } from 'hono/ws'
|
||||||
|
import { isSupportedOCPP } from '@/constants.js'
|
||||||
|
import {
|
||||||
|
OCPP_MESSAGE_TYPE,
|
||||||
|
type OcppCall,
|
||||||
|
type OcppErrorCode,
|
||||||
|
type OcppMessage,
|
||||||
|
type OcppConnectionContext,
|
||||||
|
type BootNotificationRequest,
|
||||||
|
type BootNotificationResponse,
|
||||||
|
type HeartbeatRequest,
|
||||||
|
type HeartbeatResponse,
|
||||||
|
type StatusNotificationRequest,
|
||||||
|
type StatusNotificationResponse,
|
||||||
|
} from './types.ts'
|
||||||
|
import { handleBootNotification } from './actions/boot-notification.ts'
|
||||||
|
import { handleHeartbeat } from './actions/heartbeat.ts'
|
||||||
|
import { handleStatusNotification } from './actions/status-notification.ts'
|
||||||
|
|
||||||
|
// Typed dispatch map — only registered actions are accepted
|
||||||
|
type ActionHandlerMap = {
|
||||||
|
BootNotification: (
|
||||||
|
payload: BootNotificationRequest,
|
||||||
|
ctx: OcppConnectionContext,
|
||||||
|
) => Promise<BootNotificationResponse>
|
||||||
|
Heartbeat: (
|
||||||
|
payload: HeartbeatRequest,
|
||||||
|
ctx: OcppConnectionContext,
|
||||||
|
) => Promise<HeartbeatResponse>
|
||||||
|
StatusNotification: (
|
||||||
|
payload: StatusNotificationRequest,
|
||||||
|
ctx: OcppConnectionContext,
|
||||||
|
) => Promise<StatusNotificationResponse>
|
||||||
|
}
|
||||||
|
|
||||||
|
const actionHandlers: ActionHandlerMap = {
|
||||||
|
BootNotification: handleBootNotification,
|
||||||
|
Heartbeat: handleHeartbeat,
|
||||||
|
StatusNotification: handleStatusNotification,
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendCallResult(ws: WSContext, uniqueId: string, payload: unknown): void {
|
||||||
|
ws.send(JSON.stringify([OCPP_MESSAGE_TYPE.CALLRESULT, uniqueId, payload]))
|
||||||
|
}
|
||||||
|
|
||||||
|
function sendCallError(
|
||||||
|
ws: WSContext,
|
||||||
|
uniqueId: string,
|
||||||
|
errorCode: OcppErrorCode,
|
||||||
|
errorDescription: string,
|
||||||
|
): void {
|
||||||
|
ws.send(
|
||||||
|
JSON.stringify([OCPP_MESSAGE_TYPE.CALLERROR, uniqueId, errorCode, errorDescription, {}]),
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Factory that produces a hono-ws event handler object for a single
|
||||||
|
* OCPP WebSocket connection.
|
||||||
|
*
|
||||||
|
* Usage in route:
|
||||||
|
* upgradeWebSocket((c) => createOcppHandler(c.req.param('chargePointId'), remoteAddr))
|
||||||
|
*/
|
||||||
|
export function createOcppHandler(chargePointIdentifier: string, remoteAddr?: string) {
|
||||||
|
const ctx: OcppConnectionContext = {
|
||||||
|
chargePointIdentifier,
|
||||||
|
isRegistered: false,
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
onOpen(_evt: Event, ws: WSContext) {
|
||||||
|
const subProtocol = ws.protocol ?? 'unknown'
|
||||||
|
if (!isSupportedOCPP(subProtocol)) {
|
||||||
|
ws.close(1002, 'Unsupported subprotocol')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
console.log(
|
||||||
|
`[OCPP] ${chargePointIdentifier} connected` +
|
||||||
|
(remoteAddr ? ` from ${remoteAddr}` : ''),
|
||||||
|
)
|
||||||
|
},
|
||||||
|
|
||||||
|
async onMessage(evt: MessageEvent, ws: WSContext) {
|
||||||
|
let uniqueId = '(unknown)'
|
||||||
|
try {
|
||||||
|
const raw = evt.data
|
||||||
|
if (typeof raw !== 'string') return
|
||||||
|
|
||||||
|
let message: OcppMessage
|
||||||
|
try {
|
||||||
|
message = JSON.parse(raw) as OcppMessage
|
||||||
|
} catch {
|
||||||
|
sendCallError(ws, uniqueId, 'FormationViolation', 'Invalid JSON')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Array.isArray(message) || message.length < 3) {
|
||||||
|
sendCallError(ws, uniqueId, 'FormationViolation', 'Message must be a JSON array')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const [messageType, msgUniqueId] = message
|
||||||
|
uniqueId = String(msgUniqueId)
|
||||||
|
|
||||||
|
// CSMS only handles CALL messages from the charge point
|
||||||
|
if (messageType !== OCPP_MESSAGE_TYPE.CALL) return
|
||||||
|
|
||||||
|
const [, , action, payload] = message as OcppCall
|
||||||
|
|
||||||
|
// Enforce BootNotification before any other action
|
||||||
|
if (!ctx.isRegistered && action !== 'BootNotification') {
|
||||||
|
sendCallError(
|
||||||
|
ws,
|
||||||
|
uniqueId,
|
||||||
|
'SecurityError',
|
||||||
|
'Charge point must send BootNotification first',
|
||||||
|
)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const handler = actionHandlers[action as keyof ActionHandlerMap]
|
||||||
|
if (!handler) {
|
||||||
|
sendCallError(ws, uniqueId, 'NotImplemented', `Action '${action}' is not implemented`)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
const response = await (
|
||||||
|
handler as (payload: unknown, ctx: OcppConnectionContext) => Promise<unknown>
|
||||||
|
)(payload, ctx)
|
||||||
|
|
||||||
|
sendCallResult(ws, uniqueId, response)
|
||||||
|
} catch (err) {
|
||||||
|
console.error(`[OCPP] Error handling message from ${chargePointIdentifier} (uniqueId=${uniqueId}):`, err)
|
||||||
|
sendCallError(ws, uniqueId, 'InternalError', 'Internal server error')
|
||||||
|
}
|
||||||
|
},
|
||||||
|
|
||||||
|
onClose(evt: CloseEvent, _ws: WSContext) {
|
||||||
|
console.log(`[OCPP] ${chargePointIdentifier} disconnected (code=${evt.code})`)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
91
apps/csms/src/ocpp/types.ts
Normal file
91
apps/csms/src/ocpp/types.ts
Normal file
@@ -0,0 +1,91 @@
|
|||||||
|
// OCPP 1.6-J over WebSocket protocol types
|
||||||
|
|
||||||
|
export const OCPP_MESSAGE_TYPE = {
|
||||||
|
CALL: 2,
|
||||||
|
CALLRESULT: 3,
|
||||||
|
CALLERROR: 4,
|
||||||
|
} as const
|
||||||
|
|
||||||
|
// [MessageTypeId, UniqueId, Action, Payload]
|
||||||
|
export type OcppCall = [2, string, string, Record<string, unknown>]
|
||||||
|
// [MessageTypeId, UniqueId, Payload]
|
||||||
|
export type OcppCallResult = [3, string, Record<string, unknown>]
|
||||||
|
// [MessageTypeId, UniqueId, ErrorCode, ErrorDescription, ErrorDetails]
|
||||||
|
export type OcppCallError = [4, string, OcppErrorCode, string, Record<string, unknown>]
|
||||||
|
|
||||||
|
export type OcppMessage = OcppCall | OcppCallResult | OcppCallError
|
||||||
|
|
||||||
|
// OCPP 1.6-J Section 7.3.2 ErrorCode
|
||||||
|
export type OcppErrorCode =
|
||||||
|
| 'NotImplemented'
|
||||||
|
| 'NotSupported'
|
||||||
|
| 'InternalError'
|
||||||
|
| 'ProtocolError'
|
||||||
|
| 'SecurityError'
|
||||||
|
| 'FormationViolation'
|
||||||
|
| 'PropertyConstraintViolation'
|
||||||
|
| 'OccurenceConstraintViolation'
|
||||||
|
| 'TypeConstraintViolation'
|
||||||
|
| 'GenericError'
|
||||||
|
|
||||||
|
/** Per-connection mutable state shared across all action handlers */
|
||||||
|
export type OcppConnectionContext = {
|
||||||
|
chargePointIdentifier: string
|
||||||
|
isRegistered: boolean
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Action payload types (OCPP 1.6-J Section 4.x)
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
// Section 4.2 BootNotification
|
||||||
|
export type BootNotificationRequest = {
|
||||||
|
chargePointVendor: string // CiString20Type, required
|
||||||
|
chargePointModel: string // CiString20Type, required
|
||||||
|
chargePointSerialNumber?: string // CiString25Type
|
||||||
|
chargeBoxSerialNumber?: string // CiString25Type
|
||||||
|
firmwareVersion?: string // CiString50Type
|
||||||
|
iccid?: string // CiString20Type
|
||||||
|
imsi?: string // CiString20Type
|
||||||
|
meterType?: string // CiString25Type
|
||||||
|
meterSerialNumber?: string // CiString25Type
|
||||||
|
}
|
||||||
|
|
||||||
|
export type BootNotificationResponse = {
|
||||||
|
currentTime: string // UTC ISO 8601
|
||||||
|
interval: number // heartbeat interval in seconds
|
||||||
|
status: 'Accepted' | 'Pending' | 'Rejected'
|
||||||
|
}
|
||||||
|
|
||||||
|
// Section 4.8 Heartbeat
|
||||||
|
export type HeartbeatRequest = Record<string, never>
|
||||||
|
|
||||||
|
export type HeartbeatResponse = {
|
||||||
|
currentTime: string
|
||||||
|
}
|
||||||
|
|
||||||
|
// Section 4.6 StatusNotification
|
||||||
|
export type StatusNotificationRequest = {
|
||||||
|
connectorId: number // 0 = whole charge point / main controller
|
||||||
|
errorCode: string // ChargePointErrorCode
|
||||||
|
status: string // ChargePointStatus
|
||||||
|
timestamp?: string // optional, UTC ISO 8601
|
||||||
|
info?: string // CiString50Type
|
||||||
|
vendorId?: string // CiString255Type
|
||||||
|
vendorErrorCode?: string // CiString50Type
|
||||||
|
}
|
||||||
|
|
||||||
|
export type StatusNotificationResponse = Record<string, never>
|
||||||
|
|
||||||
|
// Section 4.1 Authorize
|
||||||
|
export type AuthorizeRequest = {
|
||||||
|
idTag: string // CiString20Type
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AuthorizeResponse = {
|
||||||
|
idTagInfo: {
|
||||||
|
status: 'Accepted' | 'Blocked' | 'Expired' | 'Invalid' | 'ConcurrentTx'
|
||||||
|
expiryDate?: string
|
||||||
|
parentIdTag?: string
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,4 +1,7 @@
|
|||||||
#define CFG_WIFI_MAXIMUM_RETRY 5
|
#define CFG_WIFI_MAXIMUM_RETRY 5
|
||||||
|
// OCPP 1.6-J: MOcppMongooseClient will append "/<CFG_CP_IDENTIFIER>" to this URL.
|
||||||
|
// For local dev: ws://<host>:3001/ocpp
|
||||||
|
// For production: ws://csms.helios.bh8.ga:8180/steve/websocket/CentralSystemService
|
||||||
#define CFG_OCPP_BACKEND "ws://csms.helios.bh8.ga:8180/steve/websocket/CentralSystemService"
|
#define CFG_OCPP_BACKEND "ws://csms.helios.bh8.ga:8180/steve/websocket/CentralSystemService"
|
||||||
#define CFG_CP_IDENTIFIER "CQWU_HHB_0001"
|
#define CFG_CP_IDENTIFIER "CQWU_HHB_0001"
|
||||||
#define CFG_CB_SERIAL "REDAone_prototype00"
|
#define CFG_CB_SERIAL "REDAone_prototype00"
|
||||||
|
|||||||
Reference in New Issue
Block a user