-
-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathtest_charge_point_v201.py
1263 lines (1164 loc) · 45.8 KB
/
test_charge_point_v201.py
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
"""Implement a test by a simulating an OCPP 2.0.1 chargepoint."""
import asyncio
from datetime import datetime, timedelta, UTC
from homeassistant.core import HomeAssistant, ServiceResponse
from homeassistant.exceptions import HomeAssistantError
from ocpp.v16.enums import Measurand
from custom_components.ocpp import CentralSystem
from custom_components.ocpp.enums import (
HAChargerDetails as cdet,
HAChargerServices as csvcs,
HAChargerSession as csess,
HAChargerStatuses as cstat,
Profiles,
)
from .charge_point_test import (
set_switch,
set_number,
press_button,
create_configuration,
run_charge_point_test,
remove_configuration,
wait_ready,
)
from .const import MOCK_CONFIG_DATA
from custom_components.ocpp.const import (
DEFAULT_METER_INTERVAL,
DOMAIN as OCPP_DOMAIN,
CONF_PORT,
CONF_MONITORED_VARIABLES,
MEASURANDS,
)
import pytest
from pytest_homeassistant_custom_component.common import MockConfigEntry
import ocpp
from ocpp.routing import on
import ocpp.exceptions
from ocpp.v201 import ChargePoint as cpclass, call, call_result
from ocpp.v201.datatypes import (
ComponentType,
EVSEType,
GetVariableResultType,
SetVariableResultType,
VariableType,
VariableAttributeType,
VariableCharacteristicsType,
ReportDataType,
)
from ocpp.v201.enums import (
Action,
AuthorizationStatusEnumType,
BootReasonEnumType,
ChangeAvailabilityStatusEnumType,
ChargingProfileKindEnumType,
ChargingProfilePurposeEnumType,
ChargingProfileStatusEnumType,
ChargingRateUnitEnumType,
ChargingStateEnumType,
ClearChargingProfileStatusEnumType,
ConnectorStatusEnumType,
DataEnumType,
FirmwareStatusEnumType,
GenericDeviceModelStatusEnumType,
GetVariableStatusEnumType,
IdTokenEnumType,
MeasurandEnumType,
MutabilityEnumType,
OperationalStatusEnumType,
PhaseEnumType,
ReadingContextEnumType,
RegistrationStatusEnumType,
ReportBaseEnumType,
RequestStartStopStatusEnumType,
ResetStatusEnumType,
ResetEnumType,
SetVariableStatusEnumType,
ReasonEnumType,
TransactionEventEnumType,
MessageTriggerEnumType,
TriggerMessageStatusEnumType,
TriggerReasonEnumType,
UpdateFirmwareStatusEnumType,
)
from ocpp.v16.enums import ChargePointStatus as ChargePointStatusv16
supported_measurands = [
measurand
for measurand in MEASURANDS
if (measurand != Measurand.rpm.value) and (measurand != Measurand.temperature.value)
]
class ChargePoint(cpclass):
"""Representation of real client Charge Point."""
remote_starts: list[call.RequestStartTransaction] = []
remote_stops: list[str] = []
task: asyncio.Task | None = None
remote_start_tx_id: str = "remotestart"
operative: bool | None = None
tx_updated_interval: int | None = None
tx_updated_measurands: list[str] | None = None
tx_start_time: datetime | None = None
component_instance_used: str | None = None
variable_instance_used: str | None = None
charge_profiles_set: list[call.SetChargingProfile] = []
charge_profiles_cleared: list[call.ClearChargingProfile] = []
accept_reset: bool = True
resets: list[call.Reset] = []
@on(Action.get_base_report)
def _on_base_report(self, request_id: int, report_base: str, **kwargs):
assert report_base == ReportBaseEnumType.full_inventory.value
self.task = asyncio.create_task(self._send_full_inventory(request_id))
return call_result.GetBaseReport(
GenericDeviceModelStatusEnumType.accepted.value
)
@on(Action.request_start_transaction)
def _on_remote_start(
self, id_token: dict, remote_start_id: int, **kwargs
) -> call_result.RequestStartTransaction:
self.remote_starts.append(
call.RequestStartTransaction(id_token, remote_start_id, *kwargs)
)
self.task = asyncio.create_task(
self._start_transaction_remote_start(id_token, remote_start_id)
)
return call_result.RequestStartTransaction(
RequestStartStopStatusEnumType.accepted.value
)
@on(Action.request_stop_transaction)
def _on_remote_stop(self, transaction_id: str, **kwargs):
assert transaction_id == self.remote_start_tx_id
self.remote_stops.append(transaction_id)
return call_result.RequestStopTransaction(
RequestStartStopStatusEnumType.accepted.value
)
@on(Action.set_variables)
def _on_set_variables(self, set_variable_data: list[dict], **kwargs):
result: list[SetVariableResultType] = []
for input in set_variable_data:
if (input["component"] == {"name": "SampledDataCtrlr"}) and (
input["variable"] == {"name": "TxUpdatedInterval"}
):
self.tx_updated_interval = int(input["attribute_value"])
if (input["component"] == {"name": "SampledDataCtrlr"}) and (
input["variable"] == {"name": "TxUpdatedMeasurands"}
):
self.tx_updated_measurands = input["attribute_value"].split(",")
attr_result: SetVariableStatusEnumType
if input["variable"] == {"name": "RebootRequired"}:
attr_result = SetVariableStatusEnumType.reboot_required
elif input["variable"] == {"name": "BadVariable"}:
attr_result = SetVariableStatusEnumType.unknown_variable
elif input["variable"] == {"name": "VeryBadVariable"}:
raise ocpp.exceptions.InternalError()
else:
attr_result = SetVariableStatusEnumType.accepted
self.component_instance_used = input["component"].get("instance", None)
self.variable_instance_used = input["variable"].get("instance", None)
result.append(
SetVariableResultType(
attr_result,
ComponentType(input["component"]["name"]),
VariableType(input["variable"]["name"]),
)
)
return call_result.SetVariables(result)
@on(Action.get_variables)
def _on_get_variables(self, get_variable_data: list[dict], **kwargs):
result: list[GetVariableResultType] = []
for input in get_variable_data:
value: str | None = None
if (input["component"] == {"name": "SampledDataCtrlr"}) and (
input["variable"] == {"name": "TxUpdatedInterval"}
):
value = str(self.tx_updated_interval)
elif input["variable"]["name"] == "TestInstance":
value = (
input["component"]["instance"] + "," + input["variable"]["instance"]
)
elif input["variable"] == {"name": "VeryBadVariable"}:
raise ocpp.exceptions.InternalError()
result.append(
GetVariableResultType(
GetVariableStatusEnumType.accepted
if value is not None
else GetVariableStatusEnumType.unknown_variable,
ComponentType(input["component"]["name"]),
VariableType(input["variable"]["name"]),
attribute_value=value,
)
)
return call_result.GetVariables(result)
@on(Action.change_availability)
def _on_change_availability(self, operational_status: str, **kwargs):
if operational_status == OperationalStatusEnumType.operative.value:
self.operative = True
elif operational_status == OperationalStatusEnumType.inoperative.value:
self.operative = False
else:
assert False
return call_result.ChangeAvailability(
ChangeAvailabilityStatusEnumType.accepted.value
)
@on(Action.set_charging_profile)
def _on_set_charging_profile(self, evse_id: int, charging_profile: dict, **kwargs):
self.charge_profiles_set.append(
call.SetChargingProfile(evse_id, charging_profile)
)
unit = charging_profile["charging_schedule"][0]["charging_rate_unit"]
limit = charging_profile["charging_schedule"][0]["charging_schedule_period"][0][
"limit"
]
if (unit == ChargingRateUnitEnumType.amps.value) and (limit < 6):
return call_result.SetChargingProfile(
ChargingProfileStatusEnumType.rejected.value
)
return call_result.SetChargingProfile(
ChargingProfileStatusEnumType.accepted.value
)
@on(Action.clear_charging_profile)
def _on_clear_charging_profile(self, **kwargs):
self.charge_profiles_cleared.append(
call.ClearChargingProfile(
kwargs.get("charging_profile_id", None),
kwargs.get("charging_profile_criteria", None),
)
)
return call_result.ClearChargingProfile(
ClearChargingProfileStatusEnumType.accepted.value
)
@on(Action.reset)
def _on_reset(self, type: str, **kwargs):
self.resets.append(call.Reset(type, kwargs.get("evse_id", None)))
return call_result.Reset(
ResetStatusEnumType.accepted.value
if self.accept_reset
else ResetStatusEnumType.rejected.value
)
async def _start_transaction_remote_start(
self, id_token: dict, remote_start_id: int
):
# As if AuthorizeRemoteStart is set
authorize_resp: call_result.Authorize = await self.call(
call.Authorize(id_token)
)
assert (
authorize_resp.id_token_info["status"]
== AuthorizationStatusEnumType.accepted.value
)
self.tx_start_time = datetime.now(tz=UTC)
request = call.TransactionEvent(
TransactionEventEnumType.started.value,
self.tx_start_time.isoformat(),
TriggerReasonEnumType.remote_start.value,
0,
transaction_info={
"transaction_id": self.remote_start_tx_id,
"remote_start_id": remote_start_id,
},
meter_value=[
{
"timestamp": self.tx_start_time.isoformat(),
"sampled_value": [
{
"value": 0,
"measurand": Measurand.power_active_import.value,
"unit_of_measure": {"unit": "W"},
},
],
},
],
id_token=id_token,
)
await self.call(request)
async def _send_full_inventory(self, request_id: int):
# Cannot send all at once because of a bug in python ocpp module
await self.call(
call.NotifyReport(
request_id,
datetime.now(tz=UTC).isoformat(),
0,
[
ReportDataType(
ComponentType("SmartChargingCtrlr"),
VariableType("Available"),
[
VariableAttributeType(
value="true", mutability=MutabilityEnumType.read_only
)
],
)
],
tbc=True,
)
)
await self.call(
call.NotifyReport(
request_id,
datetime.now(tz=UTC).isoformat(),
1,
[
ReportDataType(
ComponentType("ReservationCtrlr"),
VariableType("Available"),
[
VariableAttributeType(
value="true", mutability=MutabilityEnumType.read_only
)
],
),
],
tbc=True,
)
)
await self.call(
call.NotifyReport(
request_id,
datetime.now(tz=UTC).isoformat(),
2,
[
ReportDataType(
ComponentType("LocalAuthListCtrlr"),
VariableType("Available"),
[
VariableAttributeType(
value="true", mutability=MutabilityEnumType.read_only
)
],
),
],
tbc=True,
)
)
await self.call(
call.NotifyReport(
request_id,
datetime.now(tz=UTC).isoformat(),
3,
[
ReportDataType(
ComponentType("EVSE", evse=EVSEType(1)),
VariableType("Available"),
[
VariableAttributeType(
value="true", mutability=MutabilityEnumType.read_only
)
],
),
],
tbc=True,
)
)
await self.call(
call.NotifyReport(
request_id,
datetime.now(tz=UTC).isoformat(),
4,
[
ReportDataType(
ComponentType("Connector", evse=EVSEType(1, connector_id=1)),
VariableType("Available"),
[
VariableAttributeType(
value="true", mutability=MutabilityEnumType.read_only
)
],
),
],
tbc=True,
)
)
await self.call(
call.NotifyReport(
request_id,
datetime.now(tz=UTC).isoformat(),
5,
[
ReportDataType(
ComponentType("SampledDataCtrlr"),
VariableType("TxUpdatedMeasurands"),
[VariableAttributeType(value="", persistent=True)],
VariableCharacteristicsType(
DataEnumType.member_list,
False,
values_list=",".join(supported_measurands),
),
),
],
)
)
async def _test_transaction(hass: HomeAssistant, cs: CentralSystem, cp: ChargePoint):
cpid: str = cs.settings.cpid
await set_switch(hass, cs, "charge_control", True)
assert len(cp.remote_starts) == 1
assert cp.remote_starts[0].id_token == {
"id_token": cs.charge_points[cpid]._remote_id_tag,
"type": IdTokenEnumType.central.value,
}
while cs.get_metric(cpid, csess.transaction_id.value) is None:
await asyncio.sleep(0.1)
assert cs.get_metric(cpid, csess.transaction_id.value) == cp.remote_start_tx_id
tx_start_time = cp.tx_start_time
await cp.call(
call.StatusNotification(
tx_start_time.isoformat(), ConnectorStatusEnumType.occupied, 1, 1
)
)
assert (
cs.get_metric(cpid, cstat.status_connector.value)
== ChargePointStatusv16.preparing
)
await cp.call(
call.TransactionEvent(
TransactionEventEnumType.updated.value,
tx_start_time.isoformat(),
TriggerReasonEnumType.cable_plugged_in.value,
1,
transaction_info={
"transaction_id": cp.remote_start_tx_id,
},
)
)
await cp.call(
call.TransactionEvent(
TransactionEventEnumType.updated.value,
tx_start_time.isoformat(),
TriggerReasonEnumType.charging_state_changed.value,
2,
transaction_info={
"transaction_id": cp.remote_start_tx_id,
"charging_state": ChargingStateEnumType.charging.value,
},
meter_value=[
{
"timestamp": tx_start_time.isoformat(),
"sampled_value": [
{
"value": 0,
"measurand": Measurand.current_export.value,
"phase": PhaseEnumType.l1.value,
"unit_of_measure": {"unit": "A"},
},
{
"value": 0,
"measurand": Measurand.current_export.value,
"phase": PhaseEnumType.l2.value,
"unit_of_measure": {"unit": "A"},
},
{
"value": 0,
"measurand": Measurand.current_export.value,
"phase": PhaseEnumType.l3.value,
"unit_of_measure": {"unit": "A"},
},
{
"value": 1.1,
"measurand": Measurand.current_import.value,
"phase": PhaseEnumType.l1.value,
"unit_of_measure": {"unit": "A"},
},
{
"value": 2.2,
"measurand": Measurand.current_import.value,
"phase": PhaseEnumType.l2.value,
"unit_of_measure": {"unit": "A"},
},
{
"value": 3.3,
"measurand": Measurand.current_import.value,
"phase": PhaseEnumType.l3.value,
"unit_of_measure": {"unit": "A"},
},
{
"value": 12.1,
"measurand": Measurand.current_offered.value,
"phase": PhaseEnumType.l1.value,
"unit_of_measure": {"unit": "A"},
},
{
"value": 12.2,
"measurand": Measurand.current_offered.value,
"phase": PhaseEnumType.l2.value,
"unit_of_measure": {"unit": "A"},
},
{
"value": 12.3,
"measurand": Measurand.current_offered.value,
"phase": PhaseEnumType.l3.value,
"unit_of_measure": {"unit": "A"},
},
{
"value": 0,
"measurand": Measurand.energy_active_export_register.value,
"unit_of_measure": {"unit": "Wh"},
},
{
"value": 0.1,
"measurand": Measurand.energy_active_import_register.value,
"unit_of_measure": {"unit": "Wh", "multiplier": 3},
},
{
"value": 0,
"measurand": Measurand.energy_reactive_export_register.value,
"unit_of_measure": {"unit": "Wh"},
},
{
"value": 0,
"measurand": Measurand.energy_reactive_import_register.value,
"unit_of_measure": {"unit": "Wh"},
},
{
"value": 50,
"measurand": Measurand.frequency.value,
"unit_of_measure": {"unit": "Hz"},
},
{
"value": 0,
"measurand": Measurand.power_active_export.value,
"unit_of_measure": {"unit": "W"},
},
{
"value": 1518,
"measurand": Measurand.power_active_import.value,
"unit_of_measure": {"unit": "W"},
},
{
"value": 8418,
"measurand": Measurand.power_offered.value,
"unit_of_measure": {"unit": "W"},
},
{
"value": 1,
"measurand": Measurand.power_factor.value,
},
{
"value": 0,
"measurand": Measurand.power_reactive_export.value,
"unit_of_measure": {"unit": "W"},
},
{
"value": 0,
"measurand": Measurand.power_reactive_import.value,
"unit_of_measure": {"unit": "W"},
},
{
"value": 69,
"measurand": Measurand.soc.value,
"unit_of_measure": {"unit": "percent"},
},
{
"value": 229.9,
"measurand": Measurand.voltage.value,
"phase": PhaseEnumType.l1_n.value,
"unit_of_measure": {"unit": "V"},
},
{
"value": 230,
"measurand": Measurand.voltage.value,
"phase": PhaseEnumType.l2_n.value,
"unit_of_measure": {"unit": "V"},
},
{
"value": 230.4,
"measurand": Measurand.voltage.value,
"phase": PhaseEnumType.l3_n.value,
"unit_of_measure": {"unit": "V"},
},
{
# Not among enabled measurands, will be ignored
"value": 1111,
"measurand": MeasurandEnumType.energy_active_net.value,
"unit_of_measure": {"unit": "Wh"},
},
],
}
],
)
)
assert (
cs.get_metric(cpid, cstat.status_connector.value)
== ChargePointStatusv16.charging
)
assert cs.get_metric(cpid, Measurand.current_export.value) == 0
assert cs.get_metric(cpid, Measurand.current_import.value) == 6.6
assert cs.get_metric(cpid, Measurand.current_offered.value) == 36.6
assert cs.get_metric(cpid, Measurand.energy_active_export_register.value) == 0
assert cs.get_metric(cpid, Measurand.energy_active_import_register.value) == 0.1
assert cs.get_metric(cpid, Measurand.energy_reactive_export_register.value) == 0
assert cs.get_metric(cpid, Measurand.energy_reactive_import_register.value) == 0
assert cs.get_metric(cpid, Measurand.frequency.value) == 50
assert cs.get_metric(cpid, Measurand.power_active_export.value) == 0
assert cs.get_metric(cpid, Measurand.power_active_import.value) == 1.518
assert cs.get_metric(cpid, Measurand.power_offered.value) == 8.418
assert cs.get_metric(cpid, Measurand.power_reactive_export.value) == 0
assert cs.get_metric(cpid, Measurand.power_reactive_import.value) == 0
assert cs.get_metric(cpid, Measurand.soc.value) == 69
assert cs.get_metric(cpid, Measurand.voltage.value) == 230.1
assert cs.get_metric(cpid, csess.session_energy) == 0
assert cs.get_metric(cpid, csess.session_time) == 0
await cp.call(
call.TransactionEvent(
TransactionEventEnumType.updated.value,
(tx_start_time + timedelta(seconds=60)).isoformat(),
TriggerReasonEnumType.meter_value_periodic.value,
3,
transaction_info={
"transaction_id": cp.remote_start_tx_id,
"charging_state": ChargingStateEnumType.charging.value,
},
meter_value=[
{
"timestamp": (tx_start_time + timedelta(seconds=60)).isoformat(),
"sampled_value": [
{
"value": 256,
"measurand": Measurand.energy_active_import_register.value,
"unit_of_measure": {"unit": "Wh"},
},
],
}
],
)
)
assert cs.get_metric(cpid, csess.session_energy) == 0.156
assert cs.get_metric(cpid, csess.session_time) == 1
await set_switch(hass, cs, "charge_control", False)
assert len(cp.remote_stops) == 1
await cp.call(
call.TransactionEvent(
TransactionEventEnumType.ended.value,
(tx_start_time + timedelta(seconds=120)).isoformat(),
TriggerReasonEnumType.remote_stop.value,
4,
transaction_info={
"transaction_id": cp.remote_start_tx_id,
"charging_state": ChargingStateEnumType.ev_connected.value,
"stopped_reason": ReasonEnumType.remote.value,
},
meter_value=[
{
"timestamp": (tx_start_time + timedelta(seconds=120)).isoformat(),
"sampled_value": [
{
"value": 333,
"context": ReadingContextEnumType.transaction_end,
"measurand": Measurand.energy_active_import_register.value,
"unit_of_measure": {"unit": "Wh"},
},
],
}
],
)
)
assert cs.get_metric(cpid, Measurand.current_import.value) == 0
assert cs.get_metric(cpid, Measurand.current_offered.value) == 0
assert cs.get_metric(cpid, Measurand.energy_active_import_register.value) == 0.333
assert cs.get_metric(cpid, Measurand.frequency.value) == 0
assert cs.get_metric(cpid, Measurand.power_active_import.value) == 0
assert cs.get_metric(cpid, Measurand.power_offered.value) == 0
assert cs.get_metric(cpid, Measurand.power_reactive_import.value) == 0
assert cs.get_metric(cpid, Measurand.soc.value) == 0
assert cs.get_metric(cpid, Measurand.voltage.value) == 0
assert cs.get_metric(cpid, csess.session_energy) == 0.233
assert cs.get_metric(cpid, csess.session_time) == 2
# Now with energy reading in Started transaction event
await cp.call(
call.TransactionEvent(
TransactionEventEnumType.started.value,
tx_start_time.isoformat(),
TriggerReasonEnumType.cable_plugged_in.value,
0,
transaction_info={
"transaction_id": cp.remote_start_tx_id,
"charging_state": ChargingStateEnumType.ev_connected.value,
},
meter_value=[
{
"timestamp": tx_start_time.isoformat(),
"sampled_value": [
{
"value": 1000,
"measurand": Measurand.energy_active_import_register.value,
"unit_of_measure": {"unit": "kWh", "multiplier": -3},
},
],
},
],
)
)
assert (
cs.get_metric(cpid, cstat.status_connector.value)
== ChargePointStatusv16.preparing
)
await cp.call(
call.TransactionEvent(
TransactionEventEnumType.updated.value,
tx_start_time.isoformat(),
TriggerReasonEnumType.charging_state_changed.value,
1,
transaction_info={
"transaction_id": cp.remote_start_tx_id,
"charging_state": ChargingStateEnumType.charging.value,
},
meter_value=[
{
"timestamp": tx_start_time.isoformat(),
"sampled_value": [
{
"value": 1234,
"measurand": Measurand.energy_active_import_register.value,
"unit_of_measure": {"unit": "kWh", "multiplier": -3},
},
],
},
],
)
)
assert cs.get_metric(cpid, csess.session_energy) == 0.234
await cp.call(
call.TransactionEvent(
TransactionEventEnumType.updated.value,
tx_start_time.isoformat(),
TriggerReasonEnumType.charging_state_changed.value,
1,
transaction_info={
"transaction_id": cp.remote_start_tx_id,
"charging_state": ChargingStateEnumType.suspended_ev.value,
},
)
)
assert (
cs.get_metric(cpid, cstat.status_connector.value)
== ChargePointStatusv16.suspended_ev
)
await cp.call(
call.TransactionEvent(
TransactionEventEnumType.updated.value,
tx_start_time.isoformat(),
TriggerReasonEnumType.charging_state_changed.value,
1,
transaction_info={
"transaction_id": cp.remote_start_tx_id,
"charging_state": ChargingStateEnumType.suspended_evse.value,
},
)
)
assert (
cs.get_metric(cpid, cstat.status_connector.value)
== ChargePointStatusv16.suspended_evse
)
await cp.call(
call.TransactionEvent(
TransactionEventEnumType.ended.value,
tx_start_time.isoformat(),
TriggerReasonEnumType.ev_communication_lost.value,
2,
transaction_info={
"transaction_id": cp.remote_start_tx_id,
"charging_state": ChargingStateEnumType.idle.value,
"stopped_reason": ReasonEnumType.ev_disconnected.value,
},
)
)
assert (
cs.get_metric(cpid, cstat.status_connector.value)
== ChargePointStatusv16.available
)
async def _set_variable(
hass: HomeAssistant, cs: CentralSystem, cp: ChargePoint, key: str, value: str
) -> tuple[ServiceResponse, HomeAssistantError]:
response: ServiceResponse | None = None
error: HomeAssistantError | None = None
try:
response = await hass.services.async_call(
OCPP_DOMAIN,
csvcs.service_configure_v201,
service_data={"ocpp_key": key, "value": value},
blocking=True,
return_response=True,
)
except HomeAssistantError as e:
error = e
return response, error
async def _get_variable(
hass: HomeAssistant, cs: CentralSystem, cp: ChargePoint, key: str
) -> tuple[ServiceResponse, HomeAssistantError]:
response: ServiceResponse | None = None
error: HomeAssistantError | None = None
try:
response = await hass.services.async_call(
OCPP_DOMAIN,
csvcs.service_get_configuration_v201,
service_data={"ocpp_key": key},
blocking=True,
return_response=True,
)
except HomeAssistantError as e:
error = e
return response, error
async def _test_services(hass: HomeAssistant, cs: CentralSystem, cp: ChargePoint):
service_response: ServiceResponse
error: HomeAssistantError
service_response, error = await _set_variable(
hass, cs, cp, "SampledDataCtrlr/TxUpdatedInterval", "17"
)
assert service_response == {"reboot_required": False}
assert cp.tx_updated_interval == 17
service_response, error = await _set_variable(
hass, cs, cp, "SampledDataCtrlr/RebootRequired", "17"
)
assert service_response == {"reboot_required": True}
service_response, error = await _set_variable(
hass, cs, cp, "TestComponent(CompInstance)/TestVariable(VarInstance)", "17"
)
assert service_response == {"reboot_required": False}
assert cp.component_instance_used == "CompInstance"
assert cp.variable_instance_used == "VarInstance"
service_response, error = await _set_variable(
hass, cs, cp, "SampledDataCtrlr/BadVariable", "17"
)
assert error is not None
assert str(error).startswith("Failed to set variable")
service_response, error = await _set_variable(
hass, cs, cp, "SampledDataCtrlr/VeryBadVariable", "17"
)
assert error is not None
assert str(error).startswith("OCPP call failed: InternalError")
service_response, error = await _set_variable(
hass, cs, cp, "does not compute", "17"
)
assert error is not None
assert str(error) == "Invalid OCPP key"
service_response, error = await _get_variable(
hass, cs, cp, "SampledDataCtrlr/TxUpdatedInterval"
)
assert service_response == {"value": "17"}
service_response, error = await _get_variable(
hass, cs, cp, "TestComponent(CompInstance)/TestInstance(VarInstance)"
)
assert service_response == {"value": "CompInstance,VarInstance"}
service_response, error = await _get_variable(
hass, cs, cp, "SampledDataCtrlr/BadVariale"
)
assert error is not None
assert str(error).startswith("Failed to get variable")
service_response, error = await _get_variable(
hass, cs, cp, "SampledDataCtrlr/VeryBadVariable"
)
assert error is not None
assert str(error).startswith("OCPP call failed: InternalError")
async def _set_charge_rate_service(
hass: HomeAssistant, data: dict
) -> HomeAssistantError:
try:
await hass.services.async_call(
OCPP_DOMAIN,
csvcs.service_set_charge_rate,
service_data=data,
blocking=True,
)
except HomeAssistantError as e:
return e
return None
async def _test_charge_profiles(
hass: HomeAssistant, cs: CentralSystem, cp: ChargePoint
):
error: HomeAssistantError = await _set_charge_rate_service(
hass, {"limit_watts": 3000}
)
assert error is None
assert len(cp.charge_profiles_set) == 1
assert cp.charge_profiles_set[-1].evse_id == 0
assert cp.charge_profiles_set[-1].charging_profile == {
"id": 1,
"stack_level": 0,
"charging_profile_purpose": ChargingProfilePurposeEnumType.charging_station_max_profile,
"charging_profile_kind": ChargingProfileKindEnumType.relative.value,
"charging_schedule": [
{
"id": 1,
"charging_schedule_period": [{"start_period": 0, "limit": 3000}],
"charging_rate_unit": ChargingRateUnitEnumType.watts.value,
},
],
}
error = await _set_charge_rate_service(hass, {"limit_amps": 16})
assert error is None
assert len(cp.charge_profiles_set) == 2
assert cp.charge_profiles_set[-1].evse_id == 0
assert cp.charge_profiles_set[-1].charging_profile == {
"id": 1,
"stack_level": 0,
"charging_profile_purpose": ChargingProfilePurposeEnumType.charging_station_max_profile,
"charging_profile_kind": ChargingProfileKindEnumType.relative.value,
"charging_schedule": [
{
"id": 1,
"charging_schedule_period": [{"start_period": 0, "limit": 16}],
"charging_rate_unit": ChargingRateUnitEnumType.amps.value,
},
],
}
error = await _set_charge_rate_service(
hass,
{
"custom_profile": """{
'id': 2,
'stack_level': 1,
'charging_profile_purpose': 'TxProfile',
'charging_profile_kind': 'Relative',
'charging_schedule': [{
'id': 1,
'charging_rate_unit': 'A',
'charging_schedule_period': [{'start_period': 0, 'limit': 6}]
}]
}"""
},
)
assert error is None
assert len(cp.charge_profiles_set) == 3
assert cp.charge_profiles_set[-1].evse_id == 0
assert cp.charge_profiles_set[-1].charging_profile == {
"id": 2,
"stack_level": 1,
"charging_profile_purpose": ChargingProfilePurposeEnumType.tx_profile.value,
"charging_profile_kind": ChargingProfileKindEnumType.relative.value,
"charging_schedule": [
{
"id": 1,
"charging_schedule_period": [{"start_period": 0, "limit": 6}],
"charging_rate_unit": ChargingRateUnitEnumType.amps.value,
},
],
}
await set_number(hass, cs, "maximum_current", 12)
assert len(cp.charge_profiles_set) == 4
assert cp.charge_profiles_set[-1].evse_id == 0
assert cp.charge_profiles_set[-1].charging_profile == {
"id": 1,
"stack_level": 0,
"charging_profile_purpose": ChargingProfilePurposeEnumType.charging_station_max_profile.value,
"charging_profile_kind": ChargingProfileKindEnumType.relative.value,
"charging_schedule": [
{
"id": 1,
"charging_schedule_period": [{"start_period": 0, "limit": 12}],