forked from Sevenstax/FreeV2G
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Whitebeet.py
2127 lines (1846 loc) · 103 KB
/
Whitebeet.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
from distutils.command.config import config
from encodings import utf_8
from multiprocessing import Value
import time
import struct
from Logger import *
from FramingInterface import *
class Whitebeet():
def __init__(self, iftype, iface, mac):
self.logger = Logger()
self.connectionError = False
self.payloadBytes = bytes()
self.payloadBytesRead = 0
self.payloadBytesLen = 0
# System sub IDs
self.sys_mod_id = 0x10
self.sys_sub_get_firmware_version = 0x41
# Network configuration IDs
self.netconf_sub_id = 0x05
self.netconf_set_port_mirror_state = 0x55
# SLAC module IDs
self.slac_mod_id = 0x28
self.slac_sub_start = 0x42
self.slac_sub_stop = 0x43
self.slac_sub_match = 0x44
self.slac_sub_start_match = 0x44
self.slac_sub_set_validation_configuration = 0x4B
self.slac_sub_join = 0x4D
self.slac_sub_success = 0x80
self.slac_sub_failed = 0x81
self.slac_sub_join_status = 0x84
# CP module IDs
self.cp_mod_id = 0x29
self.cp_sub_set_mode = 0x40
self.cp_sub_get_mode = 0x41
self.cp_sub_start = 0x42
self.cp_sub_stop = 0x43
self.cp_sub_set_dc = 0x44
self.cp_sub_get_dc = 0x45
self.cp_sub_set_res = 0x46
self.cp_sub_get_res = 0x47
self.cp_sub_get_state = 0x48
self.cp_sub_nc_state = 0x81
# V2G module IDs
self.v2g_mod_id = 0x27
self.v2g_sub_set_mode = 0x40
self.v2g_sub_get_mode = 0x41
self.v2g_sub_start = 0x42
self.v2g_sub_stop = 0x43
# EV sub IDs
self.v2g_sub_ev_set_configuration = 0xA0
self.v2g_sub_ev_get_configuration = 0xA1
self.v2g_sub_ev_set_dc_charging_parameters = 0xA2
self.v2g_sub_ev_update_dc_charging_parameters = 0xA3
self.v2g_sub_ev_get_dc_charging_parameters = 0xA4
self.v2g_sub_ev_set_ac_charging_parameters = 0xA5
self.v2g_sub_ev_update_ac_charging_parameters = 0xA6
self.v2g_sub_ev_get_ac_charging_parameters = 0xA7
self.v2g_sub_ev_set_charging_profile = 0xA8
self.v2g_sub_ev_start_session = 0xA9
self.v2g_sub_ev_start_cable_check = 0xAA
self.v2g_sub_ev_start_pre_charging = 0xAB
self.v2g_sub_ev_start_charging = 0xAC
self.v2g_sub_ev_stop_charging = 0xAD
self.v2g_sub_ev_stop_session = 0xAE
# EVSE sub IDs
self.v2g_sub_evse_set_configuration = 0x60
self.v2g_sub_evse_get_configuration = 0x61
self.v2g_sub_evse_set_dc_charging_parameters = 0x62
self.v2g_sub_evse_update_dc_charging_parameters = 0x63
self.v2g_sub_evse_get_dc_charging_parameters = 0x64
self.v2g_sub_evse_set_ac_charging_parameters = 0x65
self.v2g_sub_evse_update_ac_charging_parameters = 0x66
self.v2g_sub_evse_get_ac_charging_parameters = 0x67
self.v2g_sub_evse_set_sdp_config = 0x68
self.v2g_sub_evse_get_sdp_config = 0x69
self.v2g_sub_evse_start_listen = 0x6A
self.v2g_sub_evse_set_authorization_status = 0x6B
self.v2g_sub_evse_set_schedules = 0x6C
self.v2g_sub_evse_set_cable_check_finished = 0x6D
self.v2g_sub_evse_start_charging = 0x6E
self.v2g_sub_evse_stop_charging = 0x6F
self.v2g_sub_evse_stop_listen = 0x70
self.v2g_sub_evse_set_cable_certificate_installation_and_update_response = 0x73
self.v2g_sub_evse_set_meter_receipt = 0x74
self.v2g_sub_evse_send_notification = 0x75
self.v2g_sub_evse_set_session_parameter_timeout = 0x76
# Initialization of the framing interface
self.framing = FramingInterface()
iftype = iftype.upper()
try:
if iftype == 'ETH':
self.framing.initialize_framing(iftype, iface, mac)
log("iface: {}, name: {}, mac: {}".format(iftype, iface, mac))
else:
self.framing.initialize_framing(iftype, iface, None)
log("iface: {}, name: {}".format(iftype, iface))
self.framing.clear_backlog()
self.version = self.systemGetVersion()
self.slacStop()
self.controlPilotStop()
if self.v2gGetMode() == 1:
self.v2gEvseStopListen()
except:
self.connectionError = True
raise ConnectionError("Failed to initialize the framing interface on \"{}\"".format(self.framing.sut_interface))
def __enter__(self):
return self
def __exit__(self, exc_type, exc_value, traceback):
self._shutdown()
def __del__(self):
self._shutdown()
def _shutdown(self):
if self.framing.isInitialized() == True:
if self.connectionError == False:
if self.v2gGetMode() == 1:
self.v2gEvseStopListen()
self.slacStop()
self.controlPilotStop()
self.framing.shut_down_interface()
def _valueToExponential(self, value):
retValue = b""
if isinstance(value, int):
base = value
exponent = 0
while(not (base == 0) and (base % 10) == 0 and exponent < 3):
exponent += 1
base = base // 10
retValue += base.to_bytes(2, "big")
retValue += exponent.to_bytes(1, "big")
else:
retValue += value[0].to_bytes(2, "big")
retValue += value[1].to_bytes(1, "big")
return retValue
def _sendReceive(self, mod_id, sub_id, payload):
"""
Sends a message and receives the response. When the whitebeet returns busy the message will
be repeated until it is accepted to the timeout runs out.
"""
try:
time_now = time.time()
time_start = time_now
time_end = time_start + 5
loop = True
response = None
while loop == True:
req_id = self.framing.build_and_send_frame(mod_id, sub_id, payload)
response = self.framing.receive_next_frame(filter_mod=[mod_id, 0xFF], filter_sub={ mod_id: sub_id }, filter_req_id=req_id, timeout=time_end - time_start)
if response is None:
self.connectionError = True
raise ConnectionError("Problem with send/receive - Please check your connection!")
elif response.mod_id == 0xFF:
raise Warning("Framing protocol error: {:02X}".format(response.sub_id))
elif response.sub_id != sub_id:
raise Warning("Response from mod ID {:02X} with unexpected sub ID {:02X} received".format(response.mod_id, response.sub_id))
elif response.payload_len == 1 and response.payload[0] == 1:
loop = True
else:
loop = False
return response
except:
self.connectionError = True
raise ConnectionError("Problem with send/receive - Please check your connection!")
def _sendReceiveAck(self, mod_id, sub_id, payload):
"""
Sends a message and expects and ACK as response. Additional payload is returned.
"""
response = self._sendReceive(mod_id, sub_id, payload)
if response.payload_len == 0:
raise Warning("Module did not accept command with no return code")
elif response.payload[0] != 0:
raise Warning("Module did not accept command {:x}:{:x}, return code: {}".format(mod_id, sub_id, response.payload[0]))
else:
return response
def _receive(self, mod_id, sub_id, req_id, timeout):
"""
Try to receive a message with the given parameters until the timeout is reached.
"""
try:
response = self.framing.receive_next_frame(filter_mod=mod_id, filter_sub=sub_id, filter_req_id=req_id, timeout=timeout)
if response == None:
raise TimeoutError("We did not receive a frame before the timeout of {}s".format(timeout))
else:
return response
except AssertionError as error:
raise TimeoutError("We did not receive a frame before the timeout of {}s".format(timeout))
def _receiveSilent(self, mod_id, sub_id, req_id, timeout):
"""
Try to receive a message with the given parameters until the timeout is reached.
Does not raise an assertion if no frame is received within timeout.
"""
response = self.framing.receive_next_frame(filter_mod=mod_id, filter_sub=sub_id, filter_req_id=req_id, noisy_timeout=False, timeout=timeout)
return response
def _printPayload(self, payload):
print("Length of payload: " + str(len(payload)))
print("Payload:")
print(" ".join(hex(n) for n in payload))
def stop(self):
self.__exit__()
def payloadReaderInitialize(self, data, length):
"""
Helper function for parsing payload. Need to be called before payloadReaderReadInt and
payloadReaderReadBytes.
"""
self.payloadBytesRead = 0
self.payloadBytes = data
self.payloadBytesLen = length
def payloadReaderReadInt(self, num):
"""
Helper function for parsing payload. Reads an integer from the payload.
"""
value = 0
if self.payloadBytesRead + num <= self.payloadBytesLen:
i = self.payloadBytesRead
if num == 1:
value = self.payloadBytes[i]
else:
value = int.from_bytes(self.payloadBytes[i:i+num], 'big')
self.payloadBytesRead = self.payloadBytesRead + num
else:
raise Warning("Less payload than expected!")
return value
def payloadReaderReadExponential(self):
"""
Helper function for parsing payload. Reads an exponential from the payload.
"""
value = 0
if self.payloadBytesRead + 3 <= self.payloadBytesLen:
i = self.payloadBytesRead
number, exp = struct.unpack("!hb", self.payloadBytes[i: i+3])
value = number * 10 ** exp
self.payloadBytesRead = self.payloadBytesRead + 3
else:
raise Warning("Less payload than expected!")
return value
def payloadReaderReadIntSigned(self, num):
"""
Helper function for parsing payload. Reads an signed integer from the payload.
"""
value = 0
if self.payloadBytesRead + num <= self.payloadBytesLen:
i = self.payloadBytesRead
value = int.from_bytes(self.payloadBytes[i:i+num], 'big', signed=True)
self.payloadBytesRead = self.payloadBytesRead + num
else:
raise Warning("Less payload than expected!")
return value
def payloadReaderReadBytes(self, num):
"""
Helper function for parsing payload. Reads a number of bytes from the payload.
"""
bytes = None
if self.payloadBytesRead + num <= self.payloadBytesLen:
i = self.payloadBytesRead
if num == 1:
bytes = bytearray(self.payloadBytes[i])
else:
bytes = self.payloadBytes[i:i+num]
self.payloadBytesRead = self.payloadBytesRead + num
else:
raise Warning("Less payload than expected!")
return bytes
def payloadReaderFinalize(self):
"""
Helper function for parsing payload. Finalizes the reading. Checks if payload was read
completely. Raises a ValueError otherwise.
"""
if self.payloadBytesRead != self.payloadBytesLen:
raise Warning("More payload than expected! (read: {}, length: {})".format(self.payloadBytesRead, self.payloadBytesLen))
def systemGetVersion(self):
"""
Retrives the firmware version in the form x.x.x
"""
response = self._sendReceiveAck(self.sys_mod_id, self.sys_sub_get_firmware_version, None)
self.payloadReaderInitialize(response.payload, response.payload_len)
version_length = self.payloadReaderReadInt(2)
return self.payloadReaderReadBytes(version_length).decode("utf-8")
def controlPilotSetMode(self, mode):
"""
Sets the mode of the control pilot service.
0: EV, 1: EVSE
"""
if isinstance(mode, int) == False:
raise ValueError("CP mode needs to be from type int")
elif mode != 0 and mode != 1:
raise ValueError("CP mode can be either 0 or 1")
else:
self._sendReceiveAck(self.cp_mod_id, self.cp_sub_set_mode, mode.to_bytes(1, "big"))
def networkConfigSetPortMirrorState(self, value):
if not isinstance(value, int) or value not in [0,1]:
raise ValueError("Value needs to be of type int with value 0 or 1")
else:
self._sendReceiveAck(self.netconf_sub_id, self.netconf_set_port_mirror_state, value.to_bytes(1, "big"))
def controlPilotGetMode(self):
"""
Sets the mode of the control pilot service.
Returns: 0: EV, 1: EVSE, 255: Mode was not yet set
"""
response = self._sendReceiveAck(self.cp_mod_id, self.cp_sub_get_mode, None)
if response.payload_len != 2:
raise Warning("Module returned malformed message with length {}".format(response.payload_len))
elif response.payload[1] not in [0, 1, 255]:
raise Warning("Module returned invalid mode {}".format(response.payload[1]))
else:
return response.payload[1]
def controlPilotStart(self):
"""
Starts the control pilot service.
"""
self._sendReceiveAck(self.cp_mod_id, self.cp_sub_start, None)
def controlPilotStop(self):
"""
Stops the control pilot service.
"""
response = self._sendReceive(self.cp_mod_id, self.cp_sub_stop, None)
if response.payload[0] not in [0, 5]:
raise Warning("CP module did not accept our stop command")
def controlPilotSetDutyCycle(self, duty_cycle_in):
if not isinstance(duty_cycle_in, int) and not isinstance(duty_cycle_in, float):
raise ValueError("Duty cycle parameter needs to be int or float")
elif duty_cycle_in < 0 or duty_cycle_in > 100:
raise ValueError("Duty cycle parameter needs to be between 0 and 100")
else:
duty_cycle_permill = int(duty_cycle_in * 10)
# Convert given duty cycle to permill
payload = duty_cycle_permill.to_bytes(2, "big")
self._sendReceiveAck(self.cp_mod_id, self.cp_sub_set_dc, payload)
def controlPilotGetDutyCycle(self):
"""
Returns the currently configured duty cycle
"""
response = self._sendReceiveAck(self.cp_mod_id, self.cp_sub_get_dc, None)
if response.payload_len != 3:
raise Warning("Module returned malformed message with length {}".format(response.payload_len))
else:
duty_cycle = int.from_bytes(response.payload[1:3], 'big') / 10
if duty_cycle < 0 or duty_cycle > 100:
raise Warning("Module returned invalid duty cycle {}".format(duty_cycle))
else:
return duty_cycle
def controlPilotGetResistorValue(self):
"""
Returns the state of the resistor value
"""
response = self._sendReceiveAck(self.cp_mod_id, self.cp_sub_get_res, None)
if response.payload_len != 1:
raise Warning("Module returned malformed message with length {}".format(response.payload_len))
elif response.payload[0] not in range(0, 5):
raise Warning("Module returned invalid state {}".format(response.payload[1]))
else:
return response.payload[0]
def controlPilotSetResistorValue(self, value):
"""
Returns the state of the resistor value
"""
if not isinstance(value, int) or value not in range(0, 2):
print("Resistor value needs to be of type int with range 0..2")
return None
response = self._sendReceiveAck(self.cp_mod_id, self.cp_sub_set_res, value.to_bytes(1, "big"))
if response.payload_len != 1:
raise Warning("Module returned malformed message with length {}".format(response.payload_len))
elif response.payload[0] not in range(0, 5):
raise Warning("Module returned invalid state {}".format(response.payload[1]))
else:
return response.payload[0]
def controlPilotGetState(self):
"""
Returns the state on the CP
0: state A, 1: state B, 2: state C, 3: state D, 4: state E, 5: state F, 6: Unknown
"""
response = self._sendReceiveAck(self.cp_mod_id, self.cp_sub_get_state, None)
if response.payload_len != 2:
raise Warning("Module returned malformed message with length {}".format(response.payload_len))
elif response.payload[1] not in range(0, 7):
raise Warning("Module returned invalid state {}".format(response.payload[1]))
else:
return response.payload[1]
def slacStart(self, mode_in):
"""
Starts the SLAC service.
"""
if not isinstance(mode_in, int):
raise ValueError("Mode parameter needs to be int")
elif mode_in not in [0, 1]:
raise ValueError("Mode parameter needs to be 0 (EV) or 1 (EVSE)")
else:
self._sendReceiveAck(self.slac_mod_id, self.slac_sub_start, mode_in.to_bytes(1, "big"))
def slacStop(self):
"""
Stops the SLAC service.
"""
response = self._sendReceive(self.slac_mod_id, self.slac_sub_stop, None)
if response.payload[0] not in [0, 0x10]:
raise Warning("SLAC module did not accept our stop command")
def slacStartMatching(self):
"""
Starts the SLAC matching process on EV side
"""
self._sendReceiveAck(self.slac_mod_id, self.slac_sub_match, None)
def slacMatched(self):
"""
Waits for SLAC success or failed message for matching process
"""
time_start = time.time()
response = self._receive(self.slac_mod_id, [self.slac_sub_success, self.slac_sub_failed], 0xFF, 60)
if response.payload_len != 0:
raise Warning("Module returned malformed message with length {}".format(response.payload_len))
elif response.sub_id == self.slac_sub_success:
return True
else:
if time.time() - time_start > 49:
raise TimeoutError("SLAC matching timed out")
return False
def slacJoinNetwork(self, nid, nmk):
"""
Joins a network
"""
if not isinstance(nid, bytearray):
raise ValueError("NID parameter needs to be bytes")
elif len(nid) != 7:
raise ValueError("NID parameter needs to be of length 7 (is {})".format(len(nid)))
elif not isinstance(nmk, bytearray):
raise ValueError("NMK parameter needs to be bytes")
elif len(nmk) != 16:
raise ValueError("NMK parameter needs to be of length 16 (is {})".format(len(nmk)))
else:
self._sendReceiveAck(self.slac_mod_id, self.slac_sub_join, nid + nmk)
def slacJoined(self):
"""
Waits for SLAC success or failed message for joining process
"""
response = self._receive(self.slac_mod_id, self.slac_sub_join_status, 0xFF, 30)
if response.payload_len != 1:
raise Warning("Module sent malformed message with length {}".format(response.payload_len))
elif response.payload[0] not in [0, 1]:
raise Warning("Module sent invalid status {}".format(response.payload[0]))
elif response.payload[0] == 0:
return False
else:
return True
def slacSetValidationConfiguration(self, configuration):
"""
Enables or disables validation
"""
if not isinstance(configuration, int) or configuration not in [0,1]:
print("Parameter configuration needs to be of type int with value 0 or 1")
else:
self._sendReceiveAck(self.slac_mod_id, self.slac_sub_set_validation_configuration, configuration.to_bytes(1, "big"))
def v2gSetMode(self, mode):
"""
Sets the mode of the V2G service.
0: EV, 1: EVSE
"""
if isinstance(mode, int) == False:
raise ValueError("V2G mode needs to be from type int")
elif mode not in [0, 1]:
raise ValueError("V2G mode can be either 0 or 1")
else:
self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_set_mode, mode.to_bytes(1, "big"))
def v2gGetMode(self):
"""
Returns the mode of the V2G service.
Returns: 0: EV, 1: EVSE, 2: Mode was not yet set
"""
response = self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_get_mode, None)
if response.payload_len != 2:
raise Warning("Module returned malformed message with length {}".format(response.payload_len))
elif response.payload[1] not in [0, 1, 2]:
raise Warning("Module returned invalid mode {}".format(response.payload[1]))
else:
return response.payload[1]
def v2gStart(self):
"""
Starts the v2g service.
"""
self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_start, None)
def v2gStop(self):
"""
Stops the v2g service.
"""
self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_stop, None)
# EV
def v2gEvSetConfiguration(self, config):
"""
Sets the configuration for EV mode
"""
if not ({"evid", "protocol_count", "protocols", "payment_method_count", "payment_method", "energy_transfer_mode_count", "energy_transfer_mode", "battery_capacity", "battery_capacity"} <= set(config)):
raise ValueError("Missing keys in config dict")
if config["evid"] is not None and (not isinstance(config["evid"], bytes) or len(config["evid"]) != 6):
raise ValueError("evid needs to be of type byte with length 6")
elif not isinstance(config["protocol_count"], int) or not (1 <= config["protocol_count"] <= 2):
raise ValueError("protocol_count needs to be of type int with value 1 or 2")
elif config["protocols"] is not None and (not isinstance(config["protocols"], list) or len(config["protocols"]) != config["protocol_count"]):
raise ValueError("protocol needs to be of type int with value 0 or 1")
elif not isinstance(config["payment_method_count"], int):
raise ValueError("payment_method_count needs to be of type int")
elif not isinstance(config["payment_method"], list):
raise ValueError("payment_method needs to be of type list")
elif not isinstance(config["energy_transfer_mode_count"], int) or not (1 <= config["energy_transfer_mode_count"] <= 6):
raise ValueError("energy_transfer_mode_count needs to be of type int with value between 1 and 6")
elif config["energy_transfer_mode"] is not None and (not isinstance(config["energy_transfer_mode"], list) or len(config["energy_transfer_mode"]) != config["energy_transfer_mode_count"]):
raise ValueError("energy_transfer_mode needs to be of type list with length of energy_transfer_mode_count")
elif not isinstance(config["battery_capacity"], int) and not (isinstance(config["battery_capacity"], tuple) and len(config["battery_capacity"]) == 2):
raise ValueError("config battery_capacity needs to be of type int or tuple with length 2")
else:
payload = b""
payload += config["evid"]
payload += config["protocol_count"].to_bytes(1, "big")
for protocol in config["protocols"]:
payload += protocol.to_bytes(1, "big")
payload += config["payment_method_count"].to_bytes(1, "big")
for method in config["payment_method"]:
payload += method.to_bytes(1, "big")
payload += config["energy_transfer_mode_count"].to_bytes(1, "big")
for mode in config["energy_transfer_mode"]:
if mode not in range(0, 6):
raise ValueError("values of energy_transfer_mode out of range")
else:
payload += mode.to_bytes(1, "big")
payload += self._valueToExponential(config["battery_capacity"])
self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_ev_set_configuration, payload)
def v2gEvGetConfiguration(self):
"""
Get the configuration of EV mdoe
Returns dictionary
"""
ret = {}
response = self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_ev_get_configuration, None)
self.payloadReaderInitialize(response.payload, response.payload_len)
self.payloadReaderReadInt(1)
ret["evid"] = self.payloadReaderReadBytes(6)
ret["protocol_count"] = self.payloadReaderReadInt(1)
prot_list = []
for i in range(ret["protocol_count"]):
prot_list.append(self.payloadReaderReadInt(1))
ret["protocol"] = prot_list
ret["payment_method_count"] = self.payloadReaderReadInt(1)
met_list = []
for i in range(ret["payment_method_count"]):
met_list.append(self.payloadReaderReadInt(1))
ret["payment_method"] = met_list
ret["energy_transfer_mode_count"] = self.payloadReaderReadInt(1)
met_list = []
for i in range(ret["energy_transfer_mode_count"]):
met_list.append(self.payloadReaderReadInt(1))
ret["energy_transfer_mode"] = met_list
#TODO: wrong battery capacity
ret["battery_capacity"] = self.payloadReaderReadExponential()
#TODO: payload to short
#ret["departure_time"] = self.payloadReaderReadInt(4)
self.payloadReaderFinalize()
return ret
def v2gSetDCChargingParameters(self, parameter):
"""
Sets the DC charging parameters of the EV
"""
if not ({"min_current", "min_voltage", "min_power", "min_voltage", "min_current", "min_power", "status", "energy_request", "departure_time", "max_voltage", "max_current", "max_power", "soc", "target_voltage", "target_current", "full_soc", "bulk_soc"} <= set(parameter)):
raise ValueError("Missing keys in parameter dict")
elif not isinstance(parameter["min_voltage"], int) and not (isinstance(parameter["min_voltage"], tuple) and len(parameter["min_voltage"]) == 2):
raise ValueError("Parameter min_voltage needs to be of type int or tuple with length 2")
elif not isinstance(parameter["min_current"], int) and not (isinstance(parameter["min_current"], tuple) and len(parameter["min_current"]) == 2):
raise ValueError("Parameter min_current needs to be of type int or tuple with length 2")
elif not isinstance(parameter["min_power"], int) and not (isinstance(parameter["min_power"], tuple) and len(parameter["min_power"]) == 2):
raise ValueError("Parameter min_power needs to be of type int or tuple with length 2")
elif not isinstance(parameter["max_voltage"], int) and not (isinstance(parameter["max_voltage"], tuple) and len(parameter["max_voltage"]) == 2):
raise ValueError("Parameter max_voltage needs to be of type int or tuple with length 2")
elif not isinstance(parameter["max_current"], int) and not (isinstance(parameter["max_current"], tuple) and len(parameter["max_current"]) == 2):
raise ValueError("Parameter max_current needs to be of type int or tuple with length 2")
elif not isinstance(parameter["max_power"], int) and not (isinstance(parameter["max_power"], tuple) and len(parameter["max_power"]) == 2):
raise ValueError("Parameter max_power needs to be of type int or tuple with length 2")
elif not isinstance(parameter["soc"], int) or parameter["soc"] not in range(0, 101):
raise ValueError("Parameter soc needs to be of type int with a vlaue range from 0 to 100")
elif not isinstance(parameter["status"], int) or parameter["status"] not in range(0, 8):
raise ValueError("Parameter status needs to be of type int with a vlaue range from 0 to 7")
elif not isinstance(parameter["target_voltage"], int) and not (isinstance(parameter["target_voltage"], tuple) and len(parameter["target_voltage"]) == 2):
raise ValueError("Parameter target_voltage needs to be of type int or tuple with length 2")
elif not isinstance(parameter["target_current"], int) and not (isinstance(parameter["target_current"], tuple) and len(parameter["target_current"]) == 2):
raise ValueError("Parameter target_current needs to be of type int or tuple with length 2")
elif not isinstance(parameter["full_soc"], int) or parameter["full_soc"] not in range(0, 101):
raise ValueError("Parameter full_soc needs to be of type int with a value range from 0 to 100")
elif not isinstance(parameter["bulk_soc"], int) or parameter["bulk_soc"] not in range(0, 101):
raise ValueError("Parameter bulk_soc needs to be of type int with a value range from 0 to 100")
elif not isinstance(parameter["energy_request"], int) and not (isinstance(parameter["energy_request"], tuple) and len(parameter["energy_request"]) == 2):
raise ValueError("Parameter energy_request needs to be of type int or tuple with length 2")
elif not isinstance(parameter["departure_time"], int) or parameter["departure_time"] not in range(0, 2**32 + 1):
raise ValueError("Parameter departure_time needs to be of type int with a value range from 0 to 2**32")
else:
payload = b""
payload += self._valueToExponential(parameter["min_voltage"])
payload += self._valueToExponential(parameter["min_current"])
payload += self._valueToExponential(parameter["min_power"])
payload += self._valueToExponential(parameter["max_voltage"])
payload += self._valueToExponential(parameter["max_current"])
payload += self._valueToExponential(parameter["max_power"])
payload += parameter["soc"].to_bytes(1, "big")
payload += parameter["status"].to_bytes(1, "big")
payload += self._valueToExponential(parameter["target_voltage"])
payload += self._valueToExponential(parameter["target_current"])
payload += parameter["full_soc"].to_bytes(1, "big")
payload += parameter["bulk_soc"].to_bytes(1, "big")
payload += self._valueToExponential(parameter["energy_request"])
payload += parameter["departure_time"].to_bytes(4, "big")
self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_ev_set_dc_charging_parameters, payload)
def v2gUpdateDCChargingParameters(self, parameter):
"""
Updates the DC charging parameters of the EV
"""
if not ({"min_current", "min_voltage", "min_power", "min_voltage", "min_current", "min_power", "status","max_voltage", "max_current", "max_power", "soc", "target_voltage", "target_current"} <= set(parameter)):
raise ValueError("Missing keys in parameter dict")
elif not isinstance(parameter["min_voltage"], int) and not (isinstance(parameter["min_voltage"], tuple) and len(parameter["min_voltage"]) == 2):
raise ValueError("Parameter min_voltage needs to be of type int or tuple with length 2")
elif not isinstance(parameter["min_current"], int) and not (isinstance(parameter["min_current"], tuple) and len(parameter["min_current"]) == 2):
raise ValueError("Parameter min_current needs to be of type int or tuple with length 2")
elif not isinstance(parameter["min_power"], int) and not (isinstance(parameter["min_power"], tuple) and len(parameter["min_power"]) == 2):
raise ValueError("Parameter min_power needs to be of type int or tuple with length 2")
elif not isinstance(parameter["max_voltage"], int) and not (isinstance(parameter["max_voltage"], tuple) and len(parameter["max_voltage"]) == 2):
raise ValueError("Parameter max_voltage needs to be of type int or tuple with length 2")
elif not isinstance(parameter["max_current"], int) and not (isinstance(parameter["max_current"], tuple) and len(parameter["max_current"]) == 2):
raise ValueError("Parameter max_current needs to be of type int or tuple with length 2")
elif not isinstance(parameter["max_power"], int) and not (isinstance(parameter["max_power"], tuple) and len(parameter["max_power"]) == 2):
raise ValueError("Parameter max_power needs to be of type int or tuple with length 2")
elif not isinstance(parameter["soc"], int) or parameter["soc"] not in range(0, 101):
raise ValueError("Parameter soc needs to be of type int with a vlaue range from 0 to 100")
elif not isinstance(parameter["status"], int) or parameter["status"] not in range(0, 8):
raise ValueError("Parameter status needs to be of type int with a vlaue range from 0 to 7")
elif not isinstance(parameter["target_voltage"], int) and not (isinstance(parameter["target_voltage"], tuple) and len(parameter["target_voltage"]) == 2):
raise ValueError("Parameter target_voltage needs to be of type int or tuple with length 2")
elif not isinstance(parameter["target_current"], int) and not (isinstance(parameter["target_current"], tuple) and len(parameter["target_current"]) == 2):
raise ValueError("Parameter target_current needs to be of type int or tuple with length 2")
else:
payload = b""
payload += self._valueToExponential(parameter["min_voltage"])
payload += self._valueToExponential(parameter["min_current"])
payload += self._valueToExponential(parameter["min_power"])
payload += self._valueToExponential(parameter["max_voltage"])
payload += self._valueToExponential(parameter["max_current"])
payload += self._valueToExponential(parameter["max_power"])
payload += parameter["soc"].to_bytes(1, "big")
payload += parameter["status"].to_bytes(1, "big")
payload += self._valueToExponential(parameter["target_voltage"])
payload += self._valueToExponential(parameter["target_current"])
self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_ev_update_dc_charging_parameters, payload)
def v2gGetDCChargingParameters(self, data):
"""
Gets the DC charging parameters
Returns dictionary
"""
ret = {}
response = self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_ev_get_dc_charging_parameters, None)
self.payloadReaderInitialize(response.payload, response.payload_len)
self.payloadReaderReadInt(1)
ret["min_voltage"] = self.payloadReaderReadBytes(3)
ret["min_current"] = self.payloadReaderReadBytes(3)
ret["min_power"] = self.payloadReaderReadBytes(3)
ret["max_voltage"] = self.payloadReaderReadBytes(3)
ret["max_current"] = self.payloadReaderReadBytes(3)
ret["max_power"] = self.payloadReaderReadBytes(3)
ret["soc"] = self.payloadReaderReadInt(1)
ret["status"] = self.payloadReaderReadInt(1)
ret["full_soc"] = self.payloadReaderReadInt(1)
ret["bulk_soc"] = self.payloadReaderReadInt(1)
ret["energy_request"] = self.payloadReaderReadBytes(3)
ret["departure_time"] = self.payloadReaderReadInt(4)
self.payloadReaderFinalize()
return ret
def v2gSetACChargingParameters(self, parameter):
"""
Sets the AC charging parameters of the EV
"""
if not ({"min_current", "min_voltage", "min_power", "min_voltage", "min_current", "min_power", "energy_request", "departure_time", "max_voltage", "max_current", "max_power"} <= set(parameter)):
raise ValueError("Missing keys in parameter dict")
elif not isinstance(parameter["min_voltage"], int) and not (isinstance(parameter["min_voltage"], tuple) and len(parameter["min_voltage"]) == 2):
raise ValueError("Parameter min_voltage needs to be of type int or tuple with length 2")
elif not isinstance(parameter["min_current"], int) and not (isinstance(parameter["min_current"], tuple) and len(parameter["min_current"]) == 2):
raise ValueError("Parameter min_current needs to be of type int or tuple with length 2")
elif not isinstance(parameter["min_power"], int) and not (isinstance(parameter["min_power"], tuple) and len(parameter["min_power"]) == 2):
raise ValueError("Parameter min_power needs to be of type int or tuple with length 2")
elif not isinstance(parameter["max_voltage"], int) and not (isinstance(parameter["max_voltage"], tuple) and len(parameter["max_voltage"]) == 2):
raise ValueError("Parameter max_voltage needs to be of type int or tuple with length 2")
elif not isinstance(parameter["max_current"], int) and not (isinstance(parameter["max_current"], tuple) and len(parameter["max_current"]) == 2):
raise ValueError("Parameter max_current needs to be of type int or tuple with length 2")
elif not isinstance(parameter["max_power"], int) and not (isinstance(parameter["max_power"], tuple) and len(parameter["max_power"]) == 2):
raise ValueError("Parameter max_power needs to be of type int or tuple with length 2")
elif not isinstance(parameter["energy_request"], int) and not (isinstance(parameter["energy_request"], tuple) and len(parameter["energy_request"]) == 2):
raise ValueError("Parameter energy_request needs to be of type int or tuple with length 2")
elif not isinstance(parameter["departure_time"], int) or parameter["departure_time"] not in range(0, 2**32 + 1):
raise ValueError("Parameter departure_time needs to be of type int with a value range from 0 to 2**32")
else:
payload = b""
payload += self._valueToExponential(parameter["min_voltage"])
payload += self._valueToExponential(parameter["min_current"])
payload += self._valueToExponential(parameter["min_power"])
payload += self._valueToExponential(parameter["max_voltage"])
payload += self._valueToExponential(parameter["max_current"])
payload += self._valueToExponential(parameter["max_power"])
payload += self._valueToExponential(parameter["energy_request"])
payload += parameter["departure_time"].to_bytes(4, "big")
self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_ev_set_ac_charging_parameters, payload)
def v2gUpdateACChargingParameters(self, parameter):
"""
Updates the AC charging parameters of the EV
"""
if not ({"min_current", "min_voltage", "min_power", "min_voltage", "min_current", "min_power", "energy_request", "departure_time", "max_voltage", "max_current", "max_power", "soc"} <= set(parameter)):
raise ValueError("Missing keys in parameter dict")
elif not isinstance(parameter["min_voltage"], int) and not (isinstance(parameter["min_voltage"], tuple) and len(parameter["min_voltage"]) == 2):
raise ValueError("Parameter min_voltage needs to be of type int or tuple with length 2")
elif not isinstance(parameter["min_current"], int) and not (isinstance(parameter["min_current"], tuple) and len(parameter["min_current"]) == 2):
raise ValueError("Parameter min_current needs to be of type int or tuple with length 2")
elif not isinstance(parameter["min_power"], int) and not (isinstance(parameter["min_power"], tuple) and len(parameter["min_power"]) == 2):
raise ValueError("Parameter min_power needs to be of type int or tuple with length 2")
elif not isinstance(parameter["max_voltage"], int) and not (isinstance(parameter["max_voltage"], tuple) and len(parameter["max_voltage"]) == 2):
raise ValueError("Parameter max_voltage needs to be of type int or tuple with length 2")
elif not isinstance(parameter["max_current"], int) and not (isinstance(parameter["max_current"], tuple) and len(parameter["max_current"]) == 2):
raise ValueError("Parameter max_current needs to be of type int or tuple with length 2")
elif not isinstance(parameter["max_power"], int) and not (isinstance(parameter["max_power"], tuple) and len(parameter["max_power"]) == 2):
raise ValueError("Parameter max_power needs to be of type int or tuple with length 2")
else:
payload = b""
payload += self._valueToExponential(parameter["min_voltage"])
payload += self._valueToExponential(parameter["min_current"])
payload += self._valueToExponential(parameter["min_power"])
payload += self._valueToExponential(parameter["max_voltage"])
payload += self._valueToExponential(parameter["max_current"])
payload += self._valueToExponential(parameter["max_power"])
self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_ev_update_dc_charging_parameters, payload)
def v2gACGetChargingParameters(self, data):
"""
Gets the AC charging parameters
Returns dictionary
"""
ret = {}
response = self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_ev_get_dc_charging_parameters, None)
self.payloadReaderInitialize(response.payload, response.payload_len)
self.payloadReaderReadInt(1)
ret["min_voltage"] = self.payloadReaderReadBytes(3)
ret["min_current"] = self.payloadReaderReadBytes(3)
ret["min_power"] = self.payloadReaderReadBytes(3)
ret["max_voltage"] = self.payloadReaderReadBytes(3)
ret["max_current"] = self.payloadReaderReadBytes(3)
ret["max_power"] = self.payloadReaderReadBytes(3)
ret["energy_request"] = self.payloadReaderReadBytes(3)
ret["departure_time"] = self.payloadReaderReadInt(4)
self.payloadReaderFinalize()
return ret
def v2gSetChargingProfile(self, schedule):
"""
Sets the charging profile
"""
if not isinstance(schedule['schedule_tuple_id'], int) or schedule['schedule_tuple_id'] not in range(2**16):
raise ValueError("Parameter schedule_tuple_id needs to be of type int with range 0 - 65536")
if not isinstance(schedule['charging_profile_entries_count'], int) or schedule['charging_profile_entries_count'] not in range(1, 24):
raise ValueError("Parameter chargin_profile_entries_count needs to be of type int with range 1 - 24")
if schedule['start'] is not None and (not isinstance(schedule['start'], list)):
raise ValueError("Parameter start needs to be of type list")
if schedule['interval'] is not None and (not isinstance(schedule['interval'], list)):
raise ValueError("Parameter interval needs to be of type list")
elif schedule['power'] is not None and (not isinstance(schedule['power'], list)):
raise ValueError("Parameter power needs to be of type list")
else:
payload = b""
payload += schedule['schedule_tuple_id'].to_bytes(2, "big")
payload += schedule['charging_profile_entries_count'].to_bytes(1, "big")
for i in range(schedule['charging_profile_entries_count']):
payload += int(schedule['start'][i]).to_bytes(4, "big")
payload += int(schedule['interval'][i]).to_bytes(4, "big")
payload += int(schedule['power'][i]).to_bytes(2, "big")
payload += b"\x00"
print(schedule)
self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_ev_set_charging_profile, payload)
def v2gStartSession(self):
"""
Starts a new charging session
"""
self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_ev_start_session, None)
def v2gStartCableCheck(self):
"""
Starts the cable check after notification Cable Check Ready has been reveived
"""
self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_ev_start_cable_check, None)
def v2gStartPreCharging(self):
"""
Starts the pre charging after notification Pre Charging Ready has been reveived
"""
self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_ev_start_pre_charging, None)
def v2gStartCharging(self):
"""
Starts the charging after notification Charging Ready has been reveived
"""
self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_ev_start_charging, None)
def v2gStopCharging(self, renegotiation):
"""
Stops the charging
"""
if not isinstance(renegotiation, bool):
raise ValueError("Parameter renegotiation has to be of type bool")
else:
payload = b""
payload += renegotiation.to_bytes(1, "big")
self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_ev_stop_charging, payload)
def v2gStopSession(self):
"""
Stops the currently active charging session after the notification Post Charging Ready has been received.
When Charging in AC mode the session is stopped auotamically because no post charging needs to be performed.
"""
self._sendReceiveAck(self.v2g_mod_id, self.v2g_sub_ev_stop_session, None)
def v2gEvParseSessionStarted(self, data):
"""
Parse a session started message.
Will return a dictionary with the following keys:
keys protocol int
session_id bytes
evse_id bytes
payment_method int
energy_transfer_method int
"""
message = {}
self.payloadReaderInitialize(data, len(data))
message['protocol'] = self.payloadReaderReadInt(1)
message['session_id'] = self.payloadReaderReadBytes(8)
message['evse_id'] = self.payloadReaderReadBytes(self.payloadReaderReadInt(1))
message['payment_method'] = self.payloadReaderReadInt(1)
message['energy_transfer_mode'] = self.payloadReaderReadInt(1)
self.payloadReaderFinalize()
return message
def v2gEvParseDCChargeParametersChanged(self, data):
"""
Parse a DC charge parameters changed message.
Will return a dictionary with the following keys:
keys evse_min_voltage int or float
evse_min_current int or float
evse_min_power int or float
evse_max_voltage int or float
evse_max_current int or float
evse_max_power int or float
evse_present_voltage int or float
evse_present_current int or float
evse_status int
"""
message = {}
self.payloadReaderInitialize(data, len(data))
message['evse_min_voltage'] = self.payloadReaderReadExponential()
message['evse_min_current'] = self.payloadReaderReadExponential()
message['evse_min_power'] = self.payloadReaderReadExponential()
message['evse_max_voltage'] = self.payloadReaderReadExponential()
message['evse_max_current'] = self.payloadReaderReadExponential()
message['evse_max_power'] = self.payloadReaderReadExponential()
message['evse_present_voltage'] = self.payloadReaderReadExponential()
message['evse_present_current'] = self.payloadReaderReadExponential()
message['evse_status'] = self.payloadReaderReadInt(1)
if self.payloadReaderReadInt(1) != 0:
message['evse_isolation_status'] = self.payloadReaderReadInt(1)
message['evse_voltage_limit_achieved'] = self.payloadReaderReadInt(1)
message['evse_current_limit_achieved'] = self.payloadReaderReadInt(1)
message['evse_power_limit_achieved'] = self.payloadReaderReadInt(1)
message['evse_peak_current_ripple'] = self.payloadReaderReadExponential()
if self.payloadReaderReadInt(1) != 0:
message['evse_current_regulation_tolerance'] = self.payloadReaderReadExponential()
if self.payloadReaderReadInt(1) != 0:
message['evse_energy_to_be_delivered'] = self.payloadReaderReadExponential()
self.payloadReaderFinalize()
return message
def v2gEvParseACChargeParametersChanged(self, data):
"""
Parse a AC charge parameters changed message.
Will return a dictionary with the following keys:
keys nominal_voltage int or float
max_current int or float
rcd boolean
"""
message = {}
self.payloadReaderInitialize(data, len(data))
message['nominal_voltage'] = self.payloadReaderReadExponential()
message['max_current'] = self.payloadReaderReadExponential()
message['rcd'] = True if self.payloadReaderReadInt(1) == 1 else False
self.payloadReaderFinalize()
return message
def v2gEvParseScheduleReceived(self, data):
"""
Parse a schedule received message.
Will return a dictionary with the following keys:
keys tuple_count int
tuple_id int
entries_count int
entries list of dict
The list elements of entries have the following keys:
start int
interval int
power int or float
"""
message = {}
self.payloadReaderInitialize(data, len(data))
message['tuple_count'] = self.payloadReaderReadInt(1)
message['tuple_id'] = self.payloadReaderReadInt(2)