From 4fce1c6bdde6300e50a37744a5acfa17d20581dd Mon Sep 17 00:00:00 2001 From: Timothy Yin Date: Tue, 10 Mar 2026 10:42:20 +0800 Subject: [PATCH] feat(ocpp): implement BootNotification, Heartbeat, and StatusNotification actions with database integration --- apps/csms/drizzle/0002_melodic_moondragon.sql | 172 ++ apps/csms/drizzle/meta/0002_snapshot.json | 1660 +++++++++++++++++ apps/csms/drizzle/meta/_journal.json | 7 + apps/csms/src/db/ocpp-schema.ts | 679 +++++-- apps/csms/src/index.ts | 30 +- .../src/ocpp/actions/boot-notification.ts | 61 + apps/csms/src/ocpp/actions/heartbeat.ts | 24 + .../src/ocpp/actions/status-notification.ts | 104 ++ apps/csms/src/ocpp/handler.ts | 142 ++ apps/csms/src/ocpp/types.ts | 91 + hardware/firmware/src/config.h | 3 + 11 files changed, 2837 insertions(+), 136 deletions(-) create mode 100644 apps/csms/drizzle/0002_melodic_moondragon.sql create mode 100644 apps/csms/drizzle/meta/0002_snapshot.json create mode 100644 apps/csms/src/ocpp/actions/boot-notification.ts create mode 100644 apps/csms/src/ocpp/actions/heartbeat.ts create mode 100644 apps/csms/src/ocpp/actions/status-notification.ts create mode 100644 apps/csms/src/ocpp/handler.ts create mode 100644 apps/csms/src/ocpp/types.ts diff --git a/apps/csms/drizzle/0002_melodic_moondragon.sql b/apps/csms/drizzle/0002_melodic_moondragon.sql new file mode 100644 index 0000000..602f386 --- /dev/null +++ b/apps/csms/drizzle/0002_melodic_moondragon.sql @@ -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"); \ No newline at end of file diff --git a/apps/csms/drizzle/meta/0002_snapshot.json b/apps/csms/drizzle/meta/0002_snapshot.json new file mode 100644 index 0000000..8d56949 --- /dev/null +++ b/apps/csms/drizzle/meta/0002_snapshot.json @@ -0,0 +1,1660 @@ +{ + "id": "19bd6e2d-1648-4da6-a8db-4f66712febde", + "prevId": "0f080c45-a0f2-44c8-ad7b-9587335710d8", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.account": { + "name": "account", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.jwks": { + "name": "jwks", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "public_key": { + "name": "public_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "private_key": { + "name": "private_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.session": { + "name": "session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "impersonated_by": { + "name": "impersonated_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "session_token_unique": { + "name": "session_token_unique", + "nullsNotDistinct": false, + "columns": [ + "token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user": { + "name": "user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "banned": { + "name": "banned", + "type": "boolean", + "primaryKey": false, + "notNull": false, + "default": false + }, + "ban_reason": { + "name": "ban_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "ban_expires": { + "name": "ban_expires", + "type": "timestamp", + "primaryKey": false, + "notNull": false + }, + "username": { + "name": "username", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "display_username": { + "name": "display_username", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_email_unique": { + "name": "user_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + }, + "user_username_unique": { + "name": "user_username_unique", + "nullsNotDistinct": false, + "columns": [ + "username" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.charge_point": { + "name": "charge_point", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "varchar", + "primaryKey": true, + "notNull": true + }, + "charge_point_identifier": { + "name": "charge_point_identifier", + "type": "varchar(255)", + "primaryKey": false, + "notNull": true + }, + "charge_point_serial_number": { + "name": "charge_point_serial_number", + "type": "varchar(25)", + "primaryKey": false, + "notNull": false + }, + "charge_point_model": { + "name": "charge_point_model", + "type": "varchar(20)", + "primaryKey": false, + "notNull": true + }, + "charge_point_vendor": { + "name": "charge_point_vendor", + "type": "varchar(20)", + "primaryKey": false, + "notNull": true + }, + "firmware_version": { + "name": "firmware_version", + "type": "varchar(50)", + "primaryKey": false, + "notNull": false + }, + "iccid": { + "name": "iccid", + "type": "varchar(20)", + "primaryKey": false, + "notNull": false + }, + "imsi": { + "name": "imsi", + "type": "varchar(20)", + "primaryKey": false, + "notNull": false + }, + "meter_serial_number": { + "name": "meter_serial_number", + "type": "varchar(25)", + "primaryKey": false, + "notNull": false + }, + "meter_type": { + "name": "meter_type", + "type": "varchar(25)", + "primaryKey": false, + "notNull": false + }, + "registration_status": { + "name": "registration_status", + "type": "varchar", + "primaryKey": false, + "notNull": true, + "default": "'Pending'" + }, + "heartbeat_interval": { + "name": "heartbeat_interval", + "type": "integer", + "primaryKey": false, + "notNull": false, + "default": 60 + }, + "last_heartbeat_at": { + "name": "last_heartbeat_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "last_boot_notification_at": { + "name": "last_boot_notification_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "charge_point_charge_point_identifier_unique": { + "name": "charge_point_charge_point_identifier_unique", + "nullsNotDistinct": false, + "columns": [ + "charge_point_identifier" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.charging_profile": { + "name": "charging_profile", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "charge_point_id": { + "name": "charge_point_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "connector_number": { + "name": "connector_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "transaction_id": { + "name": "transaction_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "stack_level": { + "name": "stack_level", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "charging_profile_purpose": { + "name": "charging_profile_purpose", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "charging_profile_kind": { + "name": "charging_profile_kind", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "recurrency_kind": { + "name": "recurrency_kind", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "valid_from": { + "name": "valid_from", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "valid_to": { + "name": "valid_to", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "charging_schedule": { + "name": "charging_schedule", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_charging_profile_charge_point_id": { + "name": "idx_charging_profile_charge_point_id", + "columns": [ + { + "expression": "charge_point_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_charging_profile_connector_id": { + "name": "idx_charging_profile_connector_id", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_charging_profile_purpose_stack": { + "name": "idx_charging_profile_purpose_stack", + "columns": [ + { + "expression": "connector_number", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "charging_profile_purpose", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "stack_level", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "charging_profile_charge_point_id_charge_point_id_fk": { + "name": "charging_profile_charge_point_id_charge_point_id_fk", + "tableFrom": "charging_profile", + "tableTo": "charge_point", + "columnsFrom": [ + "charge_point_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "charging_profile_connector_id_connector_id_fk": { + "name": "charging_profile_connector_id_connector_id_fk", + "tableFrom": "charging_profile", + "tableTo": "connector", + "columnsFrom": [ + "connector_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "charging_profile_transaction_id_transaction_id_fk": { + "name": "charging_profile_transaction_id_transaction_id_fk", + "tableFrom": "charging_profile", + "tableTo": "transaction", + "columnsFrom": [ + "transaction_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.connector": { + "name": "connector", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "varchar", + "primaryKey": true, + "notNull": true + }, + "charge_point_id": { + "name": "charge_point_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "varchar", + "primaryKey": false, + "notNull": true, + "default": "'Unavailable'" + }, + "error_code": { + "name": "error_code", + "type": "varchar", + "primaryKey": false, + "notNull": true, + "default": "'NoError'" + }, + "info": { + "name": "info", + "type": "varchar(50)", + "primaryKey": false, + "notNull": false + }, + "vendor_id": { + "name": "vendor_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "vendor_error_code": { + "name": "vendor_error_code", + "type": "varchar(50)", + "primaryKey": false, + "notNull": false + }, + "last_status_at": { + "name": "last_status_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_connector_charge_point_id": { + "name": "idx_connector_charge_point_id", + "columns": [ + { + "expression": "charge_point_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_connector_charge_point_connector": { + "name": "idx_connector_charge_point_connector", + "columns": [ + { + "expression": "charge_point_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "connector_charge_point_id_charge_point_id_fk": { + "name": "connector_charge_point_id_charge_point_id_fk", + "tableFrom": "connector", + "tableTo": "charge_point", + "columnsFrom": [ + "charge_point_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.connector_status_history": { + "name": "connector_status_history", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "varchar", + "primaryKey": true, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "connector_number": { + "name": "connector_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "error_code": { + "name": "error_code", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "info": { + "name": "info", + "type": "varchar(50)", + "primaryKey": false, + "notNull": false + }, + "vendor_id": { + "name": "vendor_id", + "type": "varchar(255)", + "primaryKey": false, + "notNull": false + }, + "vendor_error_code": { + "name": "vendor_error_code", + "type": "varchar(50)", + "primaryKey": false, + "notNull": false + }, + "status_timestamp": { + "name": "status_timestamp", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "received_at": { + "name": "received_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_status_history_connector_id": { + "name": "idx_status_history_connector_id", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_status_history_timestamp": { + "name": "idx_status_history_timestamp", + "columns": [ + { + "expression": "status_timestamp", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_status_history_received_at": { + "name": "idx_status_history_received_at", + "columns": [ + { + "expression": "received_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "connector_status_history_connector_id_connector_id_fk": { + "name": "connector_status_history_connector_id_connector_id_fk", + "tableFrom": "connector_status_history", + "tableTo": "connector", + "columnsFrom": [ + "connector_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.id_tag": { + "name": "id_tag", + "schema": "", + "columns": { + "id_tag": { + "name": "id_tag", + "type": "varchar(20)", + "primaryKey": true, + "notNull": true + }, + "parent_id_tag": { + "name": "parent_id_tag", + "type": "varchar(20)", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "varchar", + "primaryKey": false, + "notNull": true, + "default": "'Accepted'" + }, + "expiry_date": { + "name": "expiry_date", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "id_tag_user_id_user_id_fk": { + "name": "id_tag_user_id_user_id_fk", + "tableFrom": "id_tag", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.local_auth_list": { + "name": "local_auth_list", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "varchar", + "primaryKey": true, + "notNull": true + }, + "charge_point_id": { + "name": "charge_point_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "list_version": { + "name": "list_version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "id_tag": { + "name": "id_tag", + "type": "varchar(20)", + "primaryKey": false, + "notNull": true + }, + "parent_id_tag": { + "name": "parent_id_tag", + "type": "varchar(20)", + "primaryKey": false, + "notNull": false + }, + "id_tag_status": { + "name": "id_tag_status", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "expiry_date": { + "name": "expiry_date", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_local_auth_list_charge_point_id_tag": { + "name": "idx_local_auth_list_charge_point_id_tag", + "columns": [ + { + "expression": "charge_point_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id_tag", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "local_auth_list_charge_point_id_charge_point_id_fk": { + "name": "local_auth_list_charge_point_id_charge_point_id_fk", + "tableFrom": "local_auth_list", + "tableTo": "charge_point", + "columnsFrom": [ + "charge_point_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.meter_value": { + "name": "meter_value", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "varchar", + "primaryKey": true, + "notNull": true + }, + "transaction_id": { + "name": "transaction_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "connector_id": { + "name": "connector_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "charge_point_id": { + "name": "charge_point_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "connector_number": { + "name": "connector_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "timestamp": { + "name": "timestamp", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "sampled_values": { + "name": "sampled_values", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "received_at": { + "name": "received_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_meter_value_transaction_id": { + "name": "idx_meter_value_transaction_id", + "columns": [ + { + "expression": "transaction_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_meter_value_connector_id": { + "name": "idx_meter_value_connector_id", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_meter_value_timestamp": { + "name": "idx_meter_value_timestamp", + "columns": [ + { + "expression": "timestamp", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "meter_value_transaction_id_transaction_id_fk": { + "name": "meter_value_transaction_id_transaction_id_fk", + "tableFrom": "meter_value", + "tableTo": "transaction", + "columnsFrom": [ + "transaction_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + }, + "meter_value_connector_id_connector_id_fk": { + "name": "meter_value_connector_id_connector_id_fk", + "tableFrom": "meter_value", + "tableTo": "connector", + "columnsFrom": [ + "connector_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "meter_value_charge_point_id_charge_point_id_fk": { + "name": "meter_value_charge_point_id_charge_point_id_fk", + "tableFrom": "meter_value", + "tableTo": "charge_point", + "columnsFrom": [ + "charge_point_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.reservation": { + "name": "reservation", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "charge_point_id": { + "name": "charge_point_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "connector_number": { + "name": "connector_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "expiry_date": { + "name": "expiry_date", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "id_tag": { + "name": "id_tag", + "type": "varchar(20)", + "primaryKey": false, + "notNull": true + }, + "parent_id_tag": { + "name": "parent_id_tag", + "type": "varchar(20)", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "varchar", + "primaryKey": false, + "notNull": true, + "default": "'Active'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_reservation_charge_point_id": { + "name": "idx_reservation_charge_point_id", + "columns": [ + { + "expression": "charge_point_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_reservation_status": { + "name": "idx_reservation_status", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_reservation_expiry_date": { + "name": "idx_reservation_expiry_date", + "columns": [ + { + "expression": "expiry_date", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "reservation_charge_point_id_charge_point_id_fk": { + "name": "reservation_charge_point_id_charge_point_id_fk", + "tableFrom": "reservation", + "tableTo": "charge_point", + "columnsFrom": [ + "charge_point_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "reservation_connector_id_connector_id_fk": { + "name": "reservation_connector_id_connector_id_fk", + "tableFrom": "reservation", + "tableTo": "connector", + "columnsFrom": [ + "connector_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.transaction": { + "name": "transaction", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "charge_point_id": { + "name": "charge_point_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "connector_id": { + "name": "connector_id", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "connector_number": { + "name": "connector_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "id_tag": { + "name": "id_tag", + "type": "varchar(20)", + "primaryKey": false, + "notNull": true + }, + "id_tag_status": { + "name": "id_tag_status", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "start_timestamp": { + "name": "start_timestamp", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "start_meter_value": { + "name": "start_meter_value", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "stop_id_tag": { + "name": "stop_id_tag", + "type": "varchar(20)", + "primaryKey": false, + "notNull": false + }, + "stop_timestamp": { + "name": "stop_timestamp", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "stop_meter_value": { + "name": "stop_meter_value", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "stop_reason": { + "name": "stop_reason", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "reservation_id": { + "name": "reservation_id", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "idx_transaction_charge_point_id": { + "name": "idx_transaction_charge_point_id", + "columns": [ + { + "expression": "charge_point_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_transaction_connector_id": { + "name": "idx_transaction_connector_id", + "columns": [ + { + "expression": "connector_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_transaction_id_tag": { + "name": "idx_transaction_id_tag", + "columns": [ + { + "expression": "id_tag", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "idx_transaction_start_timestamp": { + "name": "idx_transaction_start_timestamp", + "columns": [ + { + "expression": "start_timestamp", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "transaction_charge_point_id_charge_point_id_fk": { + "name": "transaction_charge_point_id_charge_point_id_fk", + "tableFrom": "transaction", + "tableTo": "charge_point", + "columnsFrom": [ + "charge_point_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "transaction_connector_id_connector_id_fk": { + "name": "transaction_connector_id_connector_id_fk", + "tableFrom": "transaction", + "tableTo": "connector", + "columnsFrom": [ + "connector_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/apps/csms/drizzle/meta/_journal.json b/apps/csms/drizzle/meta/_journal.json index e6b2089..1a4c849 100644 --- a/apps/csms/drizzle/meta/_journal.json +++ b/apps/csms/drizzle/meta/_journal.json @@ -15,6 +15,13 @@ "when": 1763319683557, "tag": "0001_gorgeous_invisible_woman", "breakpoints": true + }, + { + "idx": 2, + "version": "7", + "when": 1773109529038, + "tag": "0002_melodic_moondragon", + "breakpoints": true } ] } \ No newline at end of file diff --git a/apps/csms/src/db/ocpp-schema.ts b/apps/csms/src/db/ocpp-schema.ts index b6c70eb..cb4f89c 100644 --- a/apps/csms/src/db/ocpp-schema.ts +++ b/apps/csms/src/db/ocpp-schema.ts @@ -5,48 +5,85 @@ import { integer, text, index, + serial, + jsonb, + uniqueIndex, } 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', { + /** 内部 UUID 主键 */ id: varchar('id').primaryKey(), + /** + * 充电桩唯一标识符(chargeBoxIdentity) + * TLS/WebSocket 连接路径中的最后一段,CiString255Type + */ chargePointIdentifier: varchar('charge_point_identifier', { - length: 100, + length: 255, }) .unique() .notNull(), + /** BootNotification.req: chargePointSerialNumber, CiString25Type */ chargePointSerialNumber: varchar('charge_point_serial_number', { length: 25, }), + /** BootNotification.req: chargePointModel, CiString20Type (required) */ chargePointModel: varchar('charge_point_model', { length: 20 }).notNull(), + /** BootNotification.req: chargePointVendor, CiString20Type (required) */ chargePointVendor: varchar('charge_point_vendor', { length: 20 }).notNull(), + /** BootNotification.req: firmwareVersion, CiString50Type */ firmwareVersion: varchar('firmware_version', { length: 50 }), + /** BootNotification.req: iccid (SIM card), CiString20Type */ iccid: varchar('iccid', { length: 20 }), + /** BootNotification.req: imsi, CiString20Type */ imsi: varchar('imsi', { length: 20 }), + /** BootNotification.req: meterSerialNumber, CiString25Type */ meterSerialNumber: varchar('meter_serial_number', { length: 25 }), + /** BootNotification.req: meterType, CiString25Type */ 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() .defaultNow() .$onUpdate(() => new Date()), }) +// --------------------------------------------------------------------------- +// 连接器 / Connector +// OCPP 1.6-J Section 4.6 StatusNotification +// --------------------------------------------------------------------------- + /** - * 连接器表 - * OCPP 1.6-J 2.2术语定义: - * "Connector" 指充电桩上可独立操作和管理的电气插座。通常对应单个物理连接器, - * 但某些情况下一个插座可能有多个物理插座类型和/或拴住的电缆/连接器安排 - * 以适应不同的车辆类型(如四轮电动汽车和电动滑板车)。 - * - * 连接器ID规范: - * - 第一个连接器的ID必须是1 - * - 额外的连接器必须按顺序编号(不能跳过) - * - 连接器ID不能超过充电桩的总连接器数 - * - ID为0保留用于主控制器(在报告时)或整个充电桩(在中央系统的操作时) + * 连接器 ID 规范(OCPP 1.6-J Section 2.2): + * - connectorId = 0:主控制器(StatusNotification 中用于报告整桩状态) + * - connectorId ≥ 1:实际插口,从 1 开始按顺序编号,不能跳号 */ export const connector = pgTable( 'connector', @@ -55,26 +92,12 @@ export const connector = pgTable( chargePointId: varchar('charge_point_id') .notNull() .references(() => chargePoint.id, { onDelete: 'cascade' }), - /** - * 连接器编号(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 表示主控制器 - */ + /** OCPP connectorId(0 = 主控制器,≥1 = 实际插口) */ connectorId: integer('connector_id').notNull(), /** - * 当前状态(status字段) - * OCPP 1.6-J 7.7 ChargePointStatus: - * - Available: 连接器可用于新用户 - * - Preparing: 用户提示卡、插入电缆或车辆占用停泊位时 - * - Charging: 接触器闭合,允许车辆充电 - * - SuspendedEVSE: EV连接但EVSE不提供能量 - * - SuspendedEV: EVSE提供能量但EV不取用 - * - Finishing: 交易已停止但连接器未准备好新用户 - * - Reserved: 连接器因ReserveNow命令被保留 - * - Unavailable: 因ChangeAvailability命令不可用(非运行态) - * - Faulted: 充电桩或连接器报告错误且不可用(非运行态) + * 当前状态 — OCPP 1.6-J Section 7.7 ChargePointStatus + * Available / Preparing / Charging / SuspendedEVSE / SuspendedEV / + * Finishing / Reserved / Unavailable / Faulted */ status: varchar('status', { enum: [ @@ -88,11 +111,10 @@ export const connector = pgTable( 'Unavailable', 'Faulted', ], - }).notNull(), - /** - * 错误代码(errorCode字段) - * OCPP 1.6-J 7.6 ChargePointErrorCode - */ + }) + .notNull() + .default('Unavailable'), + /** 错误码 — OCPP 1.6-J Section 7.6 ChargePointErrorCode */ errorCode: varchar('error_code', { enum: [ 'NoError', @@ -115,32 +137,20 @@ export const connector = pgTable( }) .notNull() .default('NoError'), - /** - * 供应商标识(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个字符 - */ + /** StatusNotification.req: info, CiString50Type */ info: varchar('info', { length: 50 }), - /** - * 最后一次状态更新时间 - * OCPP 1.6-J 6.47: "The time for which the status is reported. - * If absent time of receipt of the message will be assumed." - */ - lastStatusUpdate: timestamp('last_status_update').notNull().defaultNow(), - createdAt: timestamp('created_at').notNull().defaultNow(), - updatedAt: timestamp('updated_at') + /** StatusNotification.req: vendorId, CiString255Type */ + vendorId: varchar('vendor_id', { length: 255 }), + /** StatusNotification.req: vendorErrorCode, CiString50Type */ + vendorErrorCode: varchar('vendor_error_code', { length: 50 }), + /** StatusNotification.req: timestamp(充电桩报告的状态时间,UTC) */ + lastStatusAt: timestamp('last_status_at', { withTimezone: true }) + .notNull() + .defaultNow(), + createdAt: timestamp('created_at', { withTimezone: true }) + .notNull() + .defaultNow(), + updatedAt: timestamp('updated_at', { withTimezone: true }) .notNull() .defaultNow() .$onUpdate(() => new Date()), @@ -149,18 +159,18 @@ export const connector = pgTable( chargePointIdIdx: index('idx_connector_charge_point_id').on( table.chargePointId ), - connectorIdIdx: index('idx_connector_connector_id').on( - table.chargePointId, - table.connectorId - ), + /** 同一充电桩内 connectorId 唯一 */ + chargePointConnectorUniq: uniqueIndex( + 'idx_connector_charge_point_connector' + ).on(table.chargePointId, table.connectorId), }) ) -/** - * 连接器状态历史表 - * 记录StatusNotification.req的完整消息内容,用于审计和历史查询 - * 对应 OCPP 1.6-J 6.47 StatusNotification.req 消息 - */ +// --------------------------------------------------------------------------- +// 连接器状态历史 / Connector Status History +// 完整记录每条 StatusNotification.req,用于审计与历史回溯 +// --------------------------------------------------------------------------- + export const connectorStatusHistory = pgTable( 'connector_status_history', { @@ -168,15 +178,8 @@ export const connectorStatusHistory = pgTable( connectorId: varchar('connector_id') .notNull() .references(() => connector.id, { onDelete: 'cascade' }), - /** - * 连接器编号(connectorId) - * OCPP 1.6-J 6.47: connectorId >= 0 - */ + /** OCPP connectorId(冗余存储,方便直接查询) */ connectorNumber: integer('connector_number').notNull(), - /** - * 状态值 - * OCPP 1.6-J 7.7 ChargePointStatus - */ status: varchar('status', { enum: [ 'Available', @@ -190,10 +193,6 @@ export const connectorStatusHistory = pgTable( 'Faulted', ], }).notNull(), - /** - * 错误代码 - * OCPP 1.6-J 7.6 ChargePointErrorCode - */ errorCode: varchar('error_code', { enum: [ 'NoError', @@ -214,31 +213,15 @@ export const connectorStatusHistory = pgTable( 'WeakSignal', ], }).notNull(), - /** - * 附加信息 - * OCPP 1.6-J 6.47: "Additional free format information related to the error." - */ info: varchar('info', { length: 50 }), - /** - * 供应商标识 - * OCPP 1.6-J 6.47: "This identifies the vendor-specific implementation." - */ 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 }), - /** - * 状态报告时间戳 - * OCPP 1.6-J 6.47: "The time for which the status is reported. - * If absent time of receipt of the message will be assumed." - */ - statusTimestamp: timestamp('status_timestamp'), - /** - * 消息接收时间 - */ - receivedAt: timestamp('received_at').notNull().defaultNow(), + /** StatusNotification.req: timestamp(充电桩上报的状态时间) */ + statusTimestamp: timestamp('status_timestamp', { withTimezone: true }), + /** CSMS 收到消息的时间 */ + receivedAt: timestamp('received_at', { withTimezone: true }) + .notNull() + .defaultNow(), }, (table) => ({ 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(), + /** 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(), + 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 + ), + }) +) diff --git a/apps/csms/src/index.ts b/apps/csms/src/index.ts index a6f7c17..fdf83f1 100644 --- a/apps/csms/src/index.ts +++ b/apps/csms/src/index.ts @@ -7,11 +7,7 @@ import { cors } from 'hono/cors' import { logger } from 'hono/logger' import { showRoutes } from 'hono/dev' import { auth } from './lib/auth.ts' -import { - isSupportedOCPP, - SUPPORTED_OCPP_VERSIONS, - type SupportedOCPPVersion, -} from './constants.ts' +import { createOcppHandler } from './ocpp/handler.ts' const app = new Hono<{ Variables: { @@ -74,28 +70,8 @@ app.get( '/ocpp/:chargePointId', upgradeWebSocket((c) => { 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) - console.log( - `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) - }, - } + const connInfo = getConnInfo(c) + return createOcppHandler(chargePointId, connInfo.remote.address) }), ) diff --git a/apps/csms/src/ocpp/actions/boot-notification.ts b/apps/csms/src/ocpp/actions/boot-notification.ts new file mode 100644 index 0000000..afcf54a --- /dev/null +++ b/apps/csms/src/ocpp/actions/boot-notification.ts @@ -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 { + 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', + } +} diff --git a/apps/csms/src/ocpp/actions/heartbeat.ts b/apps/csms/src/ocpp/actions/heartbeat.ts new file mode 100644 index 0000000..acdc1f9 --- /dev/null +++ b/apps/csms/src/ocpp/actions/heartbeat.ts @@ -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 { + const db = useDrizzle() + + await db + .update(chargePoint) + .set({ lastHeartbeatAt: new Date() }) + .where(eq(chargePoint.chargePointIdentifier, ctx.chargePointIdentifier)) + + return { + currentTime: new Date().toISOString(), + } +} diff --git a/apps/csms/src/ocpp/actions/status-notification.ts b/apps/csms/src/ocpp/actions/status-notification.ts new file mode 100644 index 0000000..523afaf --- /dev/null +++ b/apps/csms/src/ocpp/actions/status-notification.ts @@ -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 { + 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 {} +} diff --git a/apps/csms/src/ocpp/handler.ts b/apps/csms/src/ocpp/handler.ts new file mode 100644 index 0000000..8786f51 --- /dev/null +++ b/apps/csms/src/ocpp/handler.ts @@ -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 + Heartbeat: ( + payload: HeartbeatRequest, + ctx: OcppConnectionContext, + ) => Promise + StatusNotification: ( + payload: StatusNotificationRequest, + ctx: OcppConnectionContext, + ) => Promise +} + +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 + )(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})`) + }, + } +} diff --git a/apps/csms/src/ocpp/types.ts b/apps/csms/src/ocpp/types.ts new file mode 100644 index 0000000..27f96c9 --- /dev/null +++ b/apps/csms/src/ocpp/types.ts @@ -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] +// [MessageTypeId, UniqueId, Payload] +export type OcppCallResult = [3, string, Record] +// [MessageTypeId, UniqueId, ErrorCode, ErrorDescription, ErrorDetails] +export type OcppCallError = [4, string, OcppErrorCode, string, Record] + +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 + +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 + +// Section 4.1 Authorize +export type AuthorizeRequest = { + idTag: string // CiString20Type +} + +export type AuthorizeResponse = { + idTagInfo: { + status: 'Accepted' | 'Blocked' | 'Expired' | 'Invalid' | 'ConcurrentTx' + expiryDate?: string + parentIdTag?: string + } +} diff --git a/hardware/firmware/src/config.h b/hardware/firmware/src/config.h index 2267313..4aaa786 100644 --- a/hardware/firmware/src/config.h +++ b/hardware/firmware/src/config.h @@ -1,4 +1,7 @@ #define CFG_WIFI_MAXIMUM_RETRY 5 +// OCPP 1.6-J: MOcppMongooseClient will append "/" to this URL. +// For local dev: ws://: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_CP_IDENTIFIER "CQWU_HHB_0001" #define CFG_CB_SERIAL "REDAone_prototype00"