-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcsms.py
More file actions
5172 lines (4513 loc) · 212 KB
/
Copy pathcsms.py
File metadata and controls
5172 lines (4513 loc) · 212 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
CSMS (Charging Station Management System) implementation for OCPP 2.0.1 test suite.
Note: This implementation is intended solely for testing, debugging, and stepping through
the tzi-octt test suite. It is NOT designed to be used in production.
it was written entirely by Anthropic Claude and OpenAI Codex.
Runs two servers:
- WS on port 9000 (Security Profile 1: Basic Auth, no TLS)
- WSS on port 8082 (Security Profile 2: TLS + Basic Auth, Profile 3: mTLS)
Usage:
python csms.py [test_mode]
Examples:
python csms.py # Auto-detect mode (handles all A tests)
python csms.py password_update # TC_A_09, A_10
python csms.py clear_cache # TC_C_37, C_38
python csms.py send_local_list_full # TC_D_01
Test mode configuration (three options, can be combined):
1. CLI argument (first positional arg):
python csms.py <test_mode>
2. Global mode via CSMS_TEST_MODE env var (applies to all CPs):
CSMS_TEST_MODE=password_update python csms.py
3. Per-CP mode via CSMS_CP_ACTIONS env var (JSON mapping, takes precedence):
CSMS_CP_ACTIONS='{"CP001": "password_update"}' python csms.py
Priority: Per-CP actions > CLI arg / env var.
When no test mode is set, the CSMS uses auto-detection:
- Waits briefly after connection to see if CP sends BootNotification
- If boot is received: no proactive action (quiet connection)
- If no boot: determines action based on security profile and
connection sequence (password_update, cert_renewal, profile_upgrade)
Available test modes:
"" Auto-detect / reactive
"password_update" SetVariables(BasicAuthPassword) (TC_A_09, A_10)
"cert_renewal_cs" TriggerMessage(SignCSCertificate) (TC_A_11, A_14)
"cert_renewal_v2g" TriggerMessage(SignV2GCertificate) (TC_A_12)
"cert_renewal_combined" TriggerMessage(SignCombinedCertificate) (TC_A_13)
"profile_upgrade" SetNetworkProfile + SetVariables + Reset(TC_A_19)
"clear_cache" ClearCacheRequest (TC_C_37, C_38)
"get_local_list_version" GetLocalListVersionRequest (TC_D_08, D_09)
"send_local_list_full" SendLocalList(Full, with entries) (TC_D_01)
"send_local_list_diff_update" SendLocalList(Differential, add) (TC_D_02)
"send_local_list_diff_remove" SendLocalList(Differential, remove) (TC_D_03)
"send_local_list_full_empty" SendLocalList(Full, empty) (TC_D_04)
Reactive handlers (always active, no test mode needed):
- BootNotification, StatusNotification, NotifyEvent, Heartbeat
- SignCertificate -> CertificateSigned
- SecurityEventNotification
- Authorize (token lookup from TOKEN_DATABASE)
- TransactionEvent (token lookup if id_token present)
- MeterValues, LogStatusNotification, FirmwareStatusNotification
Token database:
Hardcoded token entries used by Authorize/TransactionEvent handlers.
Override group via VALID_TOKEN_GROUP / MASTERPASS_GROUP_ID env vars.
Actions fire only once per CP (except profile_upgrade which uses a state machine).
"""
import asyncio
import json
import logging
import re
import sys
import websockets
import ssl
import base64
import http
import os
import urllib.request
import urllib.error
from copy import deepcopy
from pathlib import Path
from datetime import datetime, timedelta, timezone
from ocpp.routing import on
from ocpp.v201 import ChargePoint, call, call_result
from ocpp.v201.enums import (
Action,
DataTransferStatusEnumType,
GenericStatusEnumType,
RegistrationStatusEnumType,
InstallCertificateUseEnumType,
GetCertificateIdUseEnumType,
GetCertificateStatusEnumType,
Iso15118EVCertificateStatusEnumType,
MonitoringCriterionEnumType,
MonitorBaseEnumType,
MonitorEnumType,
LogEnumType,
MessagePriorityEnumType,
MessageFormatEnumType,
MessageStateEnumType,
)
from ocpp.v201.datatypes import IdTokenInfoType, IdTokenType
from websockets import ConnectionClosedOK
try:
from ocpp.exceptions import SecurityError as OCPPSecurityError
except ImportError:
from ocpp.exceptions import OCPPError
class OCPPSecurityError(OCPPError):
code = 'SecurityError'
default_description = 'Not authorized'
# Keep local imports stable after project restructuring.
_MODULE_DIR = Path(__file__).resolve().parent
_PROJECT_ROOT = _MODULE_DIR.parent
for _path in (str(_MODULE_DIR), str(_PROJECT_ROOT)):
if _path not in sys.path:
sys.path.insert(0, _path)
from utils import now_iso
logging.basicConfig(level=logging.INFO)
# ─── Configuration ───────────────────────────────────────────────────────────
REQUIRED_CONFIG_KEYS = (
'BASIC_AUTH_CP_PASSWORD',
'NEW_BASIC_AUTH_PASSWORD',
'CSMS_WS_PORT',
'CSMS_WSS_PORT',
'CSMS_TEST_MODE',
'CSMS_CP_ACTIONS',
'CSMS_SERVER_CERT',
'CSMS_SERVER_KEY',
'CSMS_SERVER_RSA_CERT',
'CSMS_SERVER_RSA_KEY',
'CSMS_CA_CERT',
'CSMS_CA_KEY',
'CSMS_WSS_URL',
'CSMS_MESSAGE_TIMEOUT',
'CSMS_OCPP_INTERFACE',
'CONFIGURED_EVSE_ID',
'CONFIGURED_CONNECTOR_ID',
'CONFIGURED_CONFIGURATION_SLOT',
'CONFIGURED_SECURITY_PROFILE',
'CONFIGURED_OCPP_CSMS_URL',
'CONFIGURED_OCPP_INTERFACE',
'CONFIGURED_MESSAGE_TIMEOUT',
'VALID_ID_TOKEN',
'VALID_ID_TOKEN_TYPE',
'BASIC_AUTH_CP_F',
'BASIC_AUTH_CP',
'CONFIGURED_NUMBER_OF_EVSES',
'CONFIGURED_CONNECTOR_TYPE',
'CONFIGURED_VENDOR_ID',
'CONFIGURED_MESSAGE_ID',
'CONFIGURED_NUMBER_PHASES',
'CONFIGURED_STACK_LEVEL',
'CONFIGURED_CHARGING_RATE_UNIT',
'CONFIGURED_CHARGING_SCHEDULE_DURATION',
'TRANSACTION_DURATION',
'COST_PER_KWH',
'LOCAL_LIST_VERSION',
'GROUP_ID',
'MASTERPASS_GROUP_ID',
'ISO15118_REVOKED_CERT_HASH_DATA_FILE',
)
def _load_config():
config_path = Path(__file__).resolve().with_name('config.json')
if not config_path.exists():
raise FileNotFoundError(f"Required config file not found: {config_path}")
with open(config_path) as f:
loaded = json.load(f)
if not isinstance(loaded, dict):
raise ValueError('config.json root must be an object')
missing = [key for key in REQUIRED_CONFIG_KEYS if key not in loaded]
if missing:
raise KeyError(
"config.json is missing required key(s): " + ", ".join(sorted(missing))
)
return loaded
CONFIG = _load_config()
def _cfg_str(key):
value = CONFIG[key]
return '' if value is None else str(value)
def _cfg_int(key):
value = CONFIG[key]
try:
return int(value)
except (TypeError, ValueError):
raise ValueError(f"Invalid int for '{key}' in config.json: {value!r}")
def _cfg_float(key):
value = CONFIG[key]
try:
return float(value)
except (TypeError, ValueError):
raise ValueError(f"Invalid float for '{key}' in config.json: {value!r}")
def _cfg_dict(key):
value = CONFIG[key]
if isinstance(value, dict):
return value
raise ValueError(f"Invalid object for '{key}' in config.json: {value!r}")
def _cfg_path(key):
raw_value = _cfg_str(key)
if not raw_value:
return raw_value
raw_path = Path(raw_value)
if raw_path.is_absolute():
return str(raw_path)
config_dir = Path(__file__).resolve().parent
candidates = (
config_dir / raw_path,
config_dir.parent / raw_path,
Path.cwd() / raw_path,
)
for candidate in candidates:
if candidate.exists():
return str(candidate.resolve())
return str((config_dir / raw_path).resolve())
BASIC_AUTH_CP_PASSWORD = _cfg_str('BASIC_AUTH_CP_PASSWORD')
NEW_BASIC_AUTH_PASSWORD = _cfg_str('NEW_BASIC_AUTH_PASSWORD')
WS_PORT = _cfg_int('CSMS_WS_PORT')
WSS_PORT = _cfg_int('CSMS_WSS_PORT')
TEST_MODE = sys.argv[1] if len(sys.argv) > 1 else _cfg_str('CSMS_TEST_MODE')
CP_ACTIONS = _cfg_dict('CSMS_CP_ACTIONS')
# TLS paths (server-side)
SERVER_CERT = _cfg_path('CSMS_SERVER_CERT')
SERVER_KEY = _cfg_path('CSMS_SERVER_KEY')
SERVER_RSA_CERT = _cfg_path('CSMS_SERVER_RSA_CERT')
SERVER_RSA_KEY = _cfg_path('CSMS_SERVER_RSA_KEY')
CA_CERT = _cfg_path('CSMS_CA_CERT')
CA_KEY_PATH = _cfg_path('CSMS_CA_KEY')
# Profile upgrade configuration
CSMS_WSS_URL = _cfg_str('CSMS_WSS_URL')
MESSAGE_TIMEOUT = _cfg_int('CSMS_MESSAGE_TIMEOUT')
OCPP_INTERFACE = _cfg_str('CSMS_OCPP_INTERFACE')
# Provisioning configuration (B tests)
CONFIGURED_EVSE_ID = _cfg_int('CONFIGURED_EVSE_ID')
CONFIGURED_CONNECTOR_ID = _cfg_int('CONFIGURED_CONNECTOR_ID')
CONFIGURED_CONFIGURATION_SLOT = _cfg_int('CONFIGURED_CONFIGURATION_SLOT')
CONFIGURED_SECURITY_PROFILE = _cfg_int('CONFIGURED_SECURITY_PROFILE')
CONFIGURED_OCPP_CSMS_URL = _cfg_str('CONFIGURED_OCPP_CSMS_URL')
CONFIGURED_OCPP_INTERFACE = _cfg_str('CONFIGURED_OCPP_INTERFACE')
CONFIGURED_MESSAGE_TIMEOUT_B = _cfg_int('CONFIGURED_MESSAGE_TIMEOUT')
# F/H-test configuration
VALID_ID_TOKEN = _cfg_str('VALID_ID_TOKEN')
VALID_ID_TOKEN_TYPE = _cfg_str('VALID_ID_TOKEN_TYPE')
BASIC_AUTH_CP_F = _cfg_str('BASIC_AUTH_CP_F')
BASIC_AUTH_CP = _cfg_str('BASIC_AUTH_CP')
CONFIGURED_NUMBER_OF_EVSES = _cfg_int('CONFIGURED_NUMBER_OF_EVSES')
CONFIGURED_CONNECTOR_TYPE = _cfg_str('CONFIGURED_CONNECTOR_TYPE')
CONFIGURED_VENDOR_ID = _cfg_str('CONFIGURED_VENDOR_ID')
CONFIGURED_MESSAGE_ID = _cfg_str('CONFIGURED_MESSAGE_ID')
CONFIGURED_NUMBER_PHASES = _cfg_int('CONFIGURED_NUMBER_PHASES')
CONFIGURED_STACK_LEVEL = _cfg_int('CONFIGURED_STACK_LEVEL')
CONFIGURED_CHARGING_SCHEDULE_DURATION = _cfg_int('CONFIGURED_CHARGING_SCHEDULE_DURATION')
CONFIGURED_CHARGING_RATE_UNIT = (_cfg_str('CONFIGURED_CHARGING_RATE_UNIT') or 'A').upper()
TRANSACTION_DURATION = _cfg_int('TRANSACTION_DURATION')
COST_PER_KWH = _cfg_float('COST_PER_KWH')
LOCAL_LIST_VERSION = _cfg_int('LOCAL_LIST_VERSION')
TRIGGER_PORT = _cfg_int('CSMS_TRIGGER_PORT') if 'CSMS_TRIGGER_PORT' in CONFIG else 5001
# ─── Token Database ──────────────────────────────────────────────────────────
VALID_TOKEN_GROUP = _cfg_str('GROUP_ID')
MASTERPASS_GROUP_ID = _cfg_str('MASTERPASS_GROUP_ID')
TOKEN_DATABASE = {
'100000C01': {'status': 'Accepted', 'group': VALID_TOKEN_GROUP},
'100000C39B': {'status': 'Accepted', 'group': VALID_TOKEN_GROUP},
'TAG-001': {'status': 'Accepted', 'group': VALID_TOKEN_GROUP},
'100000C02': {'status': 'Invalid'},
'100000C06': {'status': 'Blocked'},
'100000C07': {'status': 'Expired'},
'MASTERC47': {'status': 'Accepted', 'group': MASTERPASS_GROUP_ID},
'D001001': {'status': 'Accepted'},
'D001002': {'status': 'Accepted'},
'DE-TZI-C12345-A': {'status': 'Accepted'},
'EMAID001': {'status': 'Accepted'},
}
def lookup_token(token_value):
return TOKEN_DATABASE.get(token_value.upper(), {'status': 'Invalid'})
# ─── ISO 15118 Revoked Serials ──────────────────────────────────────────────
# Load serial numbers from the revoked cert hash data file so the Authorize
# handler can distinguish valid from revoked certificates without real OCSP.
_REVOKED_SERIALS = set()
_revoked_file = _cfg_path('ISO15118_REVOKED_CERT_HASH_DATA_FILE')
if _revoked_file and os.path.exists(_revoked_file):
try:
with open(_revoked_file) as _f:
for _entry in json.load(_f):
_REVOKED_SERIALS.add(_entry['serial_number'])
logging.info(f"Loaded {len(_REVOKED_SERIALS)} revoked serial(s) from {_revoked_file}")
except Exception as _e:
logging.warning(f"Failed to load revoked cert hash data: {_e}")
# ─── OCSP Helpers ────────────────────────────────────────────────────────────
def _parse_ocsp_response_status(der_data: bytes) -> str:
"""Parse DER-encoded OCSP response to extract cert status."""
def _read_tlv(data, offset):
tag = data[offset]; offset += 1
length = data[offset]; offset += 1
if length & 0x80:
n = length & 0x7F
length = int.from_bytes(data[offset:offset + n], 'big')
offset += n
return tag, length, offset
try:
# OCSPResponse SEQUENCE
_, _, pos = _read_tlv(der_data, 0)
# responseStatus ENUMERATED
_, elen, pos = _read_tlv(der_data, pos)
if der_data[pos] != 0:
return 'unknown'
pos += elen
# [0] EXPLICIT responseBytes
_, _, pos = _read_tlv(der_data, pos)
# ResponseBytes SEQUENCE
_, _, pos = _read_tlv(der_data, pos)
# responseType OID — skip
_, olen, pos = _read_tlv(der_data, pos)
pos += olen
# response OCTET STRING
_, _, pos = _read_tlv(der_data, pos)
# BasicOCSPResponse SEQUENCE
_, _, pos = _read_tlv(der_data, pos)
# tbsResponseData SEQUENCE
_, _, pos = _read_tlv(der_data, pos)
# responderID — skip
_, rlen, pos = _read_tlv(der_data, pos)
pos += rlen
# producedAt — skip
_, plen, pos = _read_tlv(der_data, pos)
pos += plen
# responses SEQUENCE OF
_, _, pos = _read_tlv(der_data, pos)
# SingleResponse SEQUENCE
_, _, pos = _read_tlv(der_data, pos)
# certID SEQUENCE — skip
_, clen, pos = _read_tlv(der_data, pos)
pos += clen
# certStatus tag
tag = der_data[pos]
if tag == 0x80:
return 'good'
elif tag & 0xE0 == 0xA0 and (tag & 0x1F) == 1:
return 'revoked'
else:
return 'unknown'
except (IndexError, ValueError):
return 'unknown'
def _query_ocsp_responder(responder_url: str) -> str:
"""Query an OCSP responder URL via HTTP POST, return 'good'/'revoked'/'unknown'."""
try:
req = urllib.request.Request(
responder_url,
data=b'\x30\x00',
headers={'Content-Type': 'application/ocsp-request'},
method='POST',
)
with urllib.request.urlopen(req, timeout=10) as resp:
return _parse_ocsp_response_status(resp.read())
except Exception as e:
logging.warning(f"OCSP query to {responder_url} failed: {e}")
return 'unknown'
def _extract_ocsp_url_from_cert(pem_cert: str):
"""Extract OCSP responder URL from certificate AIA extension."""
try:
from cryptography import x509 as cx509
from cryptography.x509.oid import ExtensionOID, AuthorityInformationAccessOID
cert = cx509.load_pem_x509_certificate(pem_cert.encode('utf-8'))
aia = cert.extensions.get_extension_for_oid(ExtensionOID.AUTHORITY_INFORMATION_ACCESS)
for desc in aia.value:
if desc.access_method == AuthorityInformationAccessOID.OCSP:
return desc.access_location.value
except Exception as e:
logging.warning(f"Failed to extract OCSP URL from certificate: {e}")
return None
# ─── Global State ────────────────────────────────────────────────────────────
cp_passwords = {} # cp_id -> current password
cp_min_security_profile = {} # cp_id -> minimum required security profile
# Pre-populate SP3 stations so the WSS handler knows to accept them without Basic Auth
for _sp3_id in CONFIG.get('CSMS_SP3_STATION_IDS', []):
cp_min_security_profile[_sp3_id] = 3
cp_test_state = {} # cp_id -> test flow state (profile_upgrade)
cp_action_fired = {} # cp_id -> set of action types already executed
# Auto-detect mode: per-(cp_id, security_profile) action counters
# Tracks how many "no-boot" connections have been handled per profile
_auto_action_counter = {}
# Auto-detect action sequences per security profile.
# These define which proactive action to perform for each successive
# "no-boot" connection (where the CP waits for CSMS-initiated action).
_AUTO_SP1_ACTIONS = ['password_update', 'password_update', 'profile_upgrade']
_AUTO_SP2_ACTIONS = ['cert_renewal_cs', 'profile_upgrade']
_AUTO_SP3_ACTIONS = [
'cert_renewal_cs', # TC_A_11
'cert_renewal_v2g', # TC_A_12
'cert_renewal_combined', # TC_A_13
'cert_renewal_cs', # TC_A_14
]
# ─── SP1 Provisioning Sequence ──────────────────────────────────────────────
# Defines the boot response and post-boot action for each successive
# BootNotification received on SP1 (WS) connections.
# Format: (boot_status, action_name_or_None)
_sp1_boot_counter = {} # cp_id -> boot count on SP1
_auto_detect_used = set() # CP IDs that have used auto-detect no-boot actions
# Reactive-mode detection: CP IDs that sent non-boot messages (C-test pattern).
# Subsequent "waiting" (silent) connections use C-specific actions (clear_cache)
# instead of A-test actions (password_update, profile_upgrade).
_reactive_mode_detected = set()
_auto_action_counter_c = {} # Separate counter for C-session SP1 actions
_AUTO_SP1_ACTIONS_C = ['clear_cache', 'clear_cache']
_SP1_PROVISIONING = [
# Boot/registration
('Accepted', None),
('Pending', None),
('Accepted', None),
# GetVariables
('Accepted', 'get_variables_single'),
('Accepted', 'get_variables_multiple'),
('Accepted', 'get_variables_split'),
# SetVariables
('Accepted', 'set_variables_single'),
('Accepted', 'set_variables_multiple'),
# GetBaseReport
('Accepted', 'get_base_report_config'),
('Accepted', 'get_base_report_full'),
('Accepted', 'get_base_report_summary'),
# GetReport with criteria
('Accepted', 'get_report_criteria'),
# Reset CS
('Accepted', 'reset_on_idle_cs'),
('Accepted', None),
('Accepted', 'reset_on_idle_cs'),
('Accepted', None),
('Accepted', 'reset_immediate_cs'),
('Accepted', None),
# Reset EVSE
('Accepted', 'reset_on_idle_evse'),
('Accepted', 'reset_on_idle_evse'),
('Accepted', 'reset_immediate_evse'),
# Pending/Rejected flows
('Pending', None),
('Pending', 'trigger_boot'),
('Accepted', None),
# Network profile
('Accepted', 'set_network_profile'),
('Accepted', 'set_network_profile'),
]
# E-test transaction tracking and provisioning
# E-mode is detected when a non-boot CP sends 3+ StatusNotification messages,
# distinguishing E tests (many connections with StatusNotification) from C tests
# (only 1-2 StatusNotification before their silent ClearCache tests).
_E_MODE_THRESHOLD = 3
_e_cp_status_count = {} # cp_id -> StatusNotification count (non-boot only)
_e_mode_active = set() # CP IDs detected as E-mode
_e_cp_transactions = {} # cp_id -> latest transaction_id
_e_action_index = {} # cp_id -> next E provisioning action index
_e_pending_action_task = {} # cp_id -> asyncio.Task for delayed actions
# E provisioning sequence: (trigger_type, action_name)
# 'after_charging' = fire after TransactionEvent Updated with Charging state + silence
# 'after_ended' = fire after TransactionEvent Ended with offline=True + silence
# 'silent' = fire on silent connection (no messages within auto-detect timeout)
_SP1_E_PROVISIONING = [
('after_charging', 'request_stop_transaction'), # E_21
('silent', 'get_transaction_status'), # E_29 reconnect
('after_charging', 'get_transaction_status'), # E_30
('after_ended', 'get_transaction_status'), # E_31 reconnect
('silent', 'get_transaction_status_no_id'), # E_33 reconnect
('silent', 'get_transaction_status_no_id'), # E_34
]
# F-test session detection and provisioning (remote control tests)
_f_mode_active = set() # CP IDs in F-test mode
_f_action_index = {} # cp_id -> next action index
_f_pending_action_task = {} # cp_id -> asyncio.Task for delayed action
_f_remote_start_id = 0 # Global counter for remote start IDs
_SP1_F_PROVISIONING = [
'request_start_transaction', # F_01
'request_start_transaction', # F_02
'request_start_transaction', # F_03
'request_start_transaction', # F_04
'unlock_connector', # F_06
'trigger_meter_values_evse', # F_11
'trigger_meter_values_all', # F_12
'trigger_transaction_event_evse', # F_13
'trigger_transaction_event_all', # F_14
'trigger_log_status', # F_15
'trigger_firmware_status', # F_18
'trigger_heartbeat', # F_20
'trigger_status_notification_evse', # F_23
'trigger_status_notification_evse', # F_24
'trigger_heartbeat', # F_27
]
# Post-provisioning mode: unified queue for CPs that don't match F session type.
# Contains D (local list) actions followed by G (availability) actions.
# A single global index advances each time any CP fires an action, so
# sequential test suites (D -> G) naturally consume the right actions.
_post_prov_mode_active = set() # CP IDs in post-provisioning mode
_post_prov_global_index = 0 # Global action index (shared across all CPs)
_post_prov_pending_task = {} # cp_id -> asyncio.Task for delayed action
_POST_PROVISIONING_ACTIONS = [
# Local list management (D tests)
'send_local_list_full',
'send_local_list_diff_update',
'send_local_list_diff_remove',
'send_local_list_full_empty',
'get_local_list_version',
'get_local_list_version',
# Availability management (G tests)
'change_availability_evse_inoperative',
'change_availability_evse_operative',
'change_availability_station_inoperative',
'change_availability_station_operative',
'change_availability_connector_inoperative',
'change_availability_connector_operative',
'change_availability_evse_inoperative',
'change_availability_station_inoperative',
'change_availability_connector_inoperative',
None,
]
# H-test reservation sequence (CP_1).
_h_reservation_id = 1000
_h_mode_active = set() # CP IDs in H reservation mode
_h_action_index = {} # cp_id -> next H action index
_h_pending_action_task = {} # cp_id -> asyncio.Task for delayed action
_SP1_H_PROVISIONING = [
'reserve_specific', # H_01
'reserve_specific_expiry', # H_07
'reserve_unspecified', # H_08
'reserve_unspecified_multi', # H_14
'reserve_connector_type', # H_15
'reserve_then_cancel', # H_17
'reserve_specific_group', # H_19
'reserve_specific', # H_20
'reserve_specific', # H_22
]
# K-test smart charging sequence (CP_1).
# Order matches the lexical test order in ./K when running the full K suite.
_k_mode_active = set() # CP IDs in K smart-charging mode
_k_action_index = {} # cp_id -> next K action index
_k_pending_action_task = {} # cp_id -> asyncio.Task for delayed K action
_k_request_start_id = 0 # RequestStartTransaction remote_start_id counter
_k_profile_id = 5000 # Charging profile id counter for K-mode profiles
_k_latest_transaction_id = {} # cp_id -> latest known transaction_id
_k_last_offered_schedule = {} # cp_id -> latest CSMS-offered schedule (for schedule validation)
_k_last_reported_profile_id = {} # cp_id -> last charging profile id from ReportChargingProfiles
_k_exclusive_mode = set() # cp_id -> K confirmed, suppress H-mode interference
_k_post_h_reset_done = set() # cp_id -> K sequence reset once after H suite completion
_active_cp_instance = {} # cp_id -> currently active ChargePointHandler instance
_trigger_session_active = set() # CP IDs controlled via HTTP trigger API (skip auto-detect)
_SP1_K_PROVISIONING = [
'set_tx_default_specific', # K_01
'set_tx_profile_no_tx', # K_02
'set_station_max_profile', # K_03
'set_replace_same_id', # K_04
'get_then_clear_by_id', # K_05
'clear_by_criteria', # K_06
'clear_by_criteria', # K_08
'set_tx_default_all', # K_10
'set_tx_default_specific', # K_15
'set_tx_default_recurring', # K_19
'get_profiles_evse0_purpose', # K_29
'get_profiles_evse_purpose', # K_30
'get_profiles_no_evse_purpose', # K_31
'get_profiles_by_id', # K_32
'get_profiles_evse_stack', # K_33
'get_profiles_evse_source', # K_34
'get_profiles_evse_purpose', # K_35
'get_profiles_evse_purpose_stack',# K_36
'request_start_tx_with_profile', # K_37
'get_composite_evse', # K_43
'get_composite_station', # K_44
None, # K_48 (CP -> CSMS notify only)
None, # K_50 (CP -> CSMS notify only)
None, # K_51 (CP -> CSMS notify only)
None, # K_52 (triggered by NotifyChargingLimit)
None, # K_53 (NotifyEVChargingNeeds-driven)
None, # K_55 (NotifyEVChargingNeeds-driven)
None, # K_57 (NotifyEVChargingNeeds-driven)
None, # K_58 (CSMS-initiated renegotiation after charging event)
None, # K_59 (CSMS-initiated + NotifyEVChargingNeeds-driven)
None, # K_60 (ongoing transaction-driven TxProfile)
None, # K_70 (ongoing transaction-driven multiple profiles)
]
# L-test firmware management sequence (CP_1).
# This models a CSMS firmware campaign plan that progresses per maintenance
# session and reacts to CP firmware status notifications.
_l_mode_active = set() # CP IDs in L firmware-management mode
_l_action_index = {} # cp_id -> next L action index (raw, no wrap)
_l_pending_action_task = {} # cp_id -> asyncio.Task for delayed L action
_SP1_L_PROVISIONING = [
{'op': 'update', 'variant': 'secure'}, # L_01
{'op': 'update', 'variant': 'install_scheduled'}, # L_02
{'op': 'update', 'variant': 'download_scheduled'}, # L_03
{'op': 'update', 'variant': 'secure'}, # L_04
{'op': 'update', 'variant': 'secure'}, # L_05
{'op': 'update', 'variant': 'secure'}, # L_06
{'op': 'update', 'variant': 'secure'}, # L_07
{'op': 'update', 'variant': 'secure'}, # L_08
{'op': 'update', 'variant': 'secure'}, # L_09
{'op': 'update', 'variant': 'replace_on_downloading'}, # L_10
{'op': 'update', 'variant': 'replace_on_downloading'}, # L_11
{'op': 'update', 'variant': 'secure'}, # L_13
{'op': 'publish', 'variant': 'standard'}, # L_17
{'op': 'publish', 'variant': 'standard'}, # L_19
{'op': 'publish', 'variant': 'standard'}, # L_20
{'op': 'unpublish', 'variant': 'standard'}, # L_21
{'op': 'unpublish', 'variant': 'standard'}, # L_22
{'op': 'unpublish', 'variant': 'standard'}, # L_23
{'op': 'publish', 'variant': 'standard'}, # L_24
]
# M-test certificate-management sequence (CP_1).
# This models a CSMS certificate campaign that includes certificate
# installation, retrieval, and deletion, followed by reactive-only
# certificate status and EV certificate exchange flows.
_m_mode_active = set() # CP IDs in M certificate-management mode
_m_action_index = {} # cp_id -> next M action index (raw, no wrap)
_m_pending_action_task = {} # cp_id -> asyncio.Task for delayed M action
_m_last_cert_hash_data = {} # cp_id -> last certificate hash data from GetInstalledCertificateIds
_SP1_M_PROVISIONING = [
{'op': 'install_certificate', 'install_type': InstallCertificateUseEnumType.csms_root_certificate}, # M_01
{'op': 'install_certificate', 'install_type': InstallCertificateUseEnumType.manufacturer_root_certificate}, # M_02
{'op': 'install_certificate', 'install_type': InstallCertificateUseEnumType.v2g_root_certificate}, # M_03
{'op': 'install_certificate', 'install_type': InstallCertificateUseEnumType.mo_root_certificate}, # M_04
{'op': 'install_certificate', 'install_type': InstallCertificateUseEnumType.csms_root_certificate}, # M_05
{'op': 'get_installed_ids', 'certificate_type': [GetCertificateIdUseEnumType.csms_root_certificate], 'repeat': 3}, # M_12
{'op': 'get_installed_ids', 'certificate_type': [GetCertificateIdUseEnumType.manufacturer_root_certificate]}, # M_13
{'op': 'get_installed_ids', 'certificate_type': [GetCertificateIdUseEnumType.v2g_root_certificate]}, # M_14
{'op': 'get_installed_ids', 'certificate_type': [GetCertificateIdUseEnumType.v2g_certificate_chain]}, # M_15
{'op': 'get_installed_ids', 'certificate_type': [GetCertificateIdUseEnumType.mo_root_certificate]}, # M_16
{
'op': 'get_installed_ids',
'certificate_type': [
GetCertificateIdUseEnumType.csms_root_certificate,
GetCertificateIdUseEnumType.manufacturer_root_certificate,
],
}, # M_17
{'op': 'get_installed_ids', 'certificate_type': None}, # M_18
{'op': 'get_installed_ids', 'certificate_type': [GetCertificateIdUseEnumType.manufacturer_root_certificate]}, # M_19
{'op': 'install_get_delete', 'install_type': InstallCertificateUseEnumType.csms_root_certificate, 'certificate_type': [GetCertificateIdUseEnumType.csms_root_certificate]}, # M_20 SHA256
{'op': 'install_get_delete', 'install_type': InstallCertificateUseEnumType.csms_root_certificate, 'certificate_type': [GetCertificateIdUseEnumType.csms_root_certificate]}, # M_20 SHA384
{'op': 'install_get_delete', 'install_type': InstallCertificateUseEnumType.csms_root_certificate, 'certificate_type': [GetCertificateIdUseEnumType.csms_root_certificate]}, # M_20 SHA512
{'op': 'install_get_delete', 'install_type': InstallCertificateUseEnumType.csms_root_certificate, 'certificate_type': [GetCertificateIdUseEnumType.csms_root_certificate]}, # M_21
None, # M_24 (CP initiated)
None, # M_26 (CP initiated)
None, # M_28 (CP initiated)
]
# N-test diagnostics/monitoring/customer-information sequence (CP_1).
# This models a CSMS monitoring and diagnostics campaign with proactive and
# reactive phases.
_n_mode_active = set() # CP IDs in N diagnostics/monitoring mode
_n_action_index = {} # cp_id -> next N action index (raw, no wrap)
_n_pending_action_task = {} # cp_id -> asyncio.Task for delayed N action
_N_LOG_REMOTE_LOCATION = 'https://logs.example.org/upload'
_N_CUSTOMER_CERTIFICATE_HASH = {
'hash_algorithm': 'SHA256',
'issuer_name_hash': 'aabbccdd' * 8,
'issuer_key_hash': 'eeff0011' * 8,
'serial_number': '01020304',
}
_SP1_N_PROVISIONING = [
{ # N_01
'op': 'get_monitoring_report_pair',
'first': {'monitoring_criteria': [MonitoringCriterionEnumType.delta_monitoring]},
'second': {'monitoring_criteria': [MonitoringCriterionEnumType.threshold_monitoring]},
},
{ # N_02
'op': 'get_monitoring_report_pair',
'first': {
'component_variable': [
{'component': {'name': 'ChargingStation'}, 'variable': {'name': 'Power'}},
],
},
'second': {
'component_variable': [
{'component': {'name': 'EVSE', 'evse': {'id': CONFIGURED_EVSE_ID}}, 'variable': {'name': 'AvailabilityState'}},
],
},
},
{ # N_03
'op': 'get_monitoring_report_pair',
'first': {
'monitoring_criteria': [MonitoringCriterionEnumType.delta_monitoring],
'component_variable': [
{'component': {'name': 'EVSE', 'evse': {'id': CONFIGURED_EVSE_ID}}, 'variable': {'name': 'AvailabilityState'}},
],
},
'second': {
'monitoring_criteria': [MonitoringCriterionEnumType.threshold_monitoring],
'component_variable': [
{'component': {'name': 'ChargingStation'}, 'variable': {'name': 'Power'}},
],
},
},
{ # N_05
'op': 'set_monitoring_base_sequence',
'bases': [
MonitorBaseEnumType.all,
MonitorBaseEnumType.factory_default,
MonitorBaseEnumType.hard_wired_only,
],
},
{ # N_08
'op': 'set_variable_monitoring',
'data': [
{
'value': 1,
'type': MonitorEnumType.delta,
'severity': 8,
'component': {'name': 'EVSE', 'evse': {'id': CONFIGURED_EVSE_ID}},
'variable': {'name': 'AvailabilityState'},
},
],
},
{ # N_09
'op': 'set_variable_monitoring',
'data': [
{
'value': 1,
'type': MonitorEnumType.delta,
'severity': 8,
'component': {'name': 'EVSE', 'evse': {'id': CONFIGURED_EVSE_ID}},
'variable': {'name': 'AvailabilityState'},
},
{
'value': 1,
'type': MonitorEnumType.delta,
'severity': 8,
'component': {'name': 'ChargingStation'},
'variable': {'name': 'AvailabilityState'},
},
],
},
{'op': 'set_monitoring_level', 'severity': 4}, # N_16
{'op': 'set_monitoring_level', 'severity': 4}, # N_17
{'op': 'clear_variable_monitoring_chunked', 'ids': [1, 2, 3, 4, 5]}, # N_18
None, # N_21 (CP initiated NotifyEvent)
None, # N_24 (CP initiated NotifyEvent)
{'op': 'get_log', 'log_type': LogEnumType.diagnostics_log}, # N_25
{'op': 'customer_information', 'report': True, 'clear': False, 'ref': 'id_token'}, # N_27
{'op': 'customer_information', 'report': True, 'clear': False, 'ref': 'id_token'}, # N_28
{'op': 'customer_information', 'report': True, 'clear': False, 'ref': 'id_token'}, # N_29
{'op': 'customer_information', 'report': True, 'clear': True, 'ref': 'id_token'}, # N_30
{'op': 'customer_information', 'report': True, 'clear': True, 'ref': 'id_token'}, # N_31
{'op': 'customer_information', 'report': False, 'clear': True, 'ref': 'id_token'}, # N_32
{'op': 'get_log', 'log_type': LogEnumType.diagnostics_log}, # N_34
{'op': 'get_log', 'log_type': LogEnumType.security_log}, # N_35
{'op': 'get_log_dual', 'log_type': LogEnumType.diagnostics_log}, # N_36
{'op': 'clear_variable_monitoring', 'ids': [1]}, # N_44
{'op': 'customer_information', 'report': True, 'clear': True, 'ref': 'id_token', 'send_local_list_on_notify': True}, # N_46
{'op': 'get_monitoring_report', 'monitoring_criteria': None, 'component_variable': None}, # N_47
None, # N_48 (CP initiated NotifyEvent)
None, # N_49 (CP initiated NotifyEvent)
None, # N_50 (CP initiated NotifyEvent)
{ # N_60
'op': 'get_monitoring_report_pair',
'first': {
'monitoring_criteria': [MonitoringCriterionEnumType.delta_monitoring],
'component_variable': [
{'component': {'name': 'ChargingStation'}, 'variable': {'name': 'AvailabilityState'}},
{'component': {'name': 'EVSE', 'evse': {'id': CONFIGURED_EVSE_ID}}, 'variable': {'name': 'AvailabilityState'}},
],
},
'second': {
'monitoring_criteria': [MonitoringCriterionEnumType.threshold_monitoring],
'component_variable': [
{'component': {'name': 'ChargingStation'}, 'variable': {'name': 'AvailabilityState'}},
{'component': {'name': 'EVSE', 'evse': {'id': CONFIGURED_EVSE_ID}}, 'variable': {'name': 'AvailabilityState'}},
],
},
},
{'op': 'customer_information', 'report': True, 'clear': True, 'ref': 'customer_identifier'}, # N_62
{'op': 'customer_information', 'report': True, 'clear': True, 'ref': 'customer_certificate'}, # N_63
]
# O-test display-message-management sequence (CP_1).
# This models a CSMS display-message campaign with message set/get/clear
# requests and reactive handling for NotifyDisplayMessages.
_o_mode_active = set() # CP IDs in O display-message mode
_o_action_index = {} # cp_id -> next O action index (raw, no wrap)
_o_pending_action_task = {} # cp_id -> asyncio.Task for delayed O action
_o_message_id = 9000 # message id counter for O-mode display messages
_SP1_O_PROVISIONING = [
{'op': 'set_display'}, # O_01
{'op': 'set_then_get', 'filter': 'all'}, # O_02
{'op': 'get_display', 'filter': 'all'}, # O_03
{'op': 'set_then_clear', 'clear_known': True}, # O_04
{'op': 'clear_display_unknown'}, # O_05
{'op': 'set_display', 'transaction_ref': 'active'}, # O_06
{'op': 'set_then_get', 'filter': 'id'}, # O_07
{'op': 'set_then_get', 'filter': 'priority'}, # O_08
{'op': 'set_then_get', 'filter': 'state'}, # O_09
{'op': 'set_display', 'transaction_ref': 'unknown'}, # O_10
{'op': 'set_then_get', 'filter': 'unknown_id'}, # O_11
{'op': 'set_replace_same_id'}, # O_12
{'op': 'set_display', 'start_offset_s': 60}, # O_13
{'op': 'set_display', 'end_offset_s': 120}, # O_14
{'op': 'set_display', 'priority': MessagePriorityEnumType.always_front}, # O_17
{'op': 'set_display', 'state': MessageStateEnumType.faulted}, # O_18
{'op': 'set_display', 'format': MessageFormatEnumType.html}, # O_19
{'op': 'set_display', 'state': MessageStateEnumType.charging}, # O_25
{'op': 'set_display', 'priority': MessagePriorityEnumType.normal_cycle}, # O_26
{ # O_27
'op': 'set_display',
'transaction_ref': 'active',
'include_state': False,
'start_offset_s': 60,
'include_end': False,
},
{ # O_28
'op': 'set_display',
'transaction_ref': 'active',
'include_state': False,
'include_start': False,
'end_offset_s': 120,
},
]
_L_UPDATE_LOCATION = 'https://downloads.example.org/firmware/ocpp-v201.bin'
_L_UPDATE_LOCATION_ALT = 'https://downloads.example.org/firmware/ocpp-v201-hotfix.bin'
_L_PUBLISH_LOCATION = 'https://cdn.example.org/firmware/publish.bin'
_L_PUBLISH_CHECKSUM = 'A1B2C3D4'
_L_UNPUBLISH_CHECKSUM = 'A1B2C3D4'
_L_SIGNING_CERT = (
"-----BEGIN CERTIFICATE-----\n"
"MIIBlTCCATugAwIBAgIUBtziLTestSigningCert1234567890wCgYIKoZIzj0EAwIw\n"
"GDEWMBQGA1UEAwwNT0NQUC1GaXJtd2FyZS1DQTAeFw0yNTAxMDEwMDAwMDBaFw0z\n"
"NTAxMDEwMDAwMDBaMBgxFjAUBgNVBAMMDU9DUFAtRmlybXdhcmUtQ0EwWTATBgcq\n"
"hkjOPQIBBggqhkjOPQMBBwNCAAQxL2vJ3I9+u8V6n8a+Pj8f1R+MdC5y2t3N2q1J\n"
"kL5rX9YyKqS8gLJ5v6s8n1Z4u8X9A3mQz4fL0p1gR0sN8a8Lo1MwUTAdBgNVHQ4E\n"
"FgQURRANDOMPLACEHOLDERFIRMWARECERT123wHwYDVR0jBBgwFoAURRANDOMPLACE\n"
"HOLDERFIRMWARECERT123MA8GA1UdEwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDSQAw\n"
"RgIhAJs6U2FMtR6eD4lJQz8J2kTq8n0A5Q9Jw3eV2D1sL0h7AiEAxqW+QWm3Q+vB\n"
"6w8A7nZ5o2o4C7N3d9mQ2nQxQ9rY5n8=\n"
"-----END CERTIFICATE-----"
)
_L_SIGNATURE = 'MEUCIQCfirmwareSignaturePlaceholder1234567890=='
_M_CERTIFICATE_PEM = (
"-----BEGIN CERTIFICATE-----\n"
"MIIBZjCCAQ2gAwIBAgIUY2VydGlmaWNhdGVUZXN0TTAxMDAwMDAwCgYIKoZIzj0E\n"
"AwIwGTEXMBUGA1UEAwwOTUNTVE1vY2tSb290Q0EwHhcNMjYwMTAxMDAwMDAwWhcN\n"
"MzYwMTAxMDAwMDAwWjAZMRcwFQYDVQQDDA5NQ1NUTW9ja1Jvb3RDQTBZMBMGByqG\n"
"SM49AgEGCCqGSM49AwEHA0IABFhE3V6g1uZs2M4m2V7g3X9q+P5c1w6s8A4zKz3I\n"
"qv9j5Y3w4k9y2fN6a8d2n0h1Q0xW8z8w8n6n2u9M0VdWq5CjUzBRMB0GA1UdDgQW\n"
"BBRtb2NrY2VydGlmaWNhdGVzaWduZXIwHwYDVR0jBBgwFoAUbW9ja2NlcnRpZmlj\n"
"YXRlc2lnbmVyMA8GA1UdEwEB/wQFMAMBAf8wCgYIKoZIzj0EAwIDSAAwRQIgQ0hB\n"
"UkdJTkdfU1RBVElPTl9URVNUX01PQ0tfQ0VSVC0wAiAQVklfVGVzdF9DZXJ0X0RhdGE=\n"
"-----END CERTIFICATE-----"
)
_M_OCSP_RESULT_B64 = base64.b64encode(b"\x30\x03\x0a\x01\x00").decode("ascii")
_M_EXI_RESPONSE_B64 = base64.b64encode(b"mock-iso15118-exi-response").decode("ascii")
# I/J transaction cost tracking: cp_id -> tx_id -> {'start': float, 'last': float}
_txn_cost_state = {}
def _enum_text(value):
return getattr(value, 'value', str(value))
def _normalize_data_transfer_key(value):
return str(value or '').strip().lower()
def _transaction_id_from_info(transaction_info):
if isinstance(transaction_info, dict):
return transaction_info.get('transaction_id') or transaction_info.get('transactionId')
return getattr(transaction_info, 'transaction_id', None) or getattr(transaction_info, 'transactionId', None)
def _charging_state_from_info(transaction_info):
if isinstance(transaction_info, dict):
return transaction_info.get('charging_state') or transaction_info.get('chargingState', '')
return getattr(transaction_info, 'charging_state', '') or getattr(transaction_info, 'chargingState', '')
def _extract_last_meter_value(meter_value):
"""Extract the last numeric sampled value from meter_value payload."""
if not meter_value:
return None
last_numeric = None
for mv in meter_value:
if isinstance(mv, dict):
sampled_values = mv.get('sampled_value') or mv.get('sampledValue') or []
else:
sampled_values = getattr(mv, 'sampled_value', []) or []
for sample in sampled_values:
if isinstance(sample, dict):
raw_value = sample.get('value')
else:
raw_value = getattr(sample, 'value', None)
if raw_value is None:
continue
try:
last_numeric = float(raw_value)
except (TypeError, ValueError):
continue
return last_numeric
def _update_transaction_cost_state(cp_id, transaction_id, meter_value):
meter_reading = _extract_last_meter_value(meter_value)
if transaction_id is None or meter_reading is None:
return
cp_map = _txn_cost_state.setdefault(cp_id, {})
tx_state = cp_map.setdefault(transaction_id, {'start': meter_reading, 'last': meter_reading})
tx_state['last'] = meter_reading
def _estimate_transaction_total_cost(cp_id, transaction_id):
tx_state = _txn_cost_state.get(cp_id, {}).get(transaction_id)
if not tx_state:
return 0.0
delta_wh = max(0.0, float(tx_state['last']) - float(tx_state['start']))
return round((delta_wh / 1000.0) * COST_PER_KWH, 2)
async def _send_cost_updated(cp, transaction_id):
total_cost = _estimate_transaction_total_cost(cp.id, transaction_id)
try:
logging.info(f"Sending CostUpdated to {cp.id}: txn={transaction_id}, total_cost={total_cost}")
await cp.call(call.CostUpdated(total_cost=total_cost, transaction_id=transaction_id))
except Exception as e:
logging.warning(f"CostUpdated call failed for {cp.id}: {e}")
# ─── K-Mode Smart Charging Helpers ───────────────────────────────────────────
def _k_next_request_start_id():
global _k_request_start_id
_k_request_start_id += 1
return _k_request_start_id