-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathmain.js
2520 lines (2324 loc) · 98.9 KB
/
main.js
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
'use strict';
/*
* Created with @iobroker/create-adapter v1.33.0
*/
// The adapter-core module gives you access to the core ioBroker functions
// you need to create an adapter
const utils = require('@iobroker/adapter-core');
// Load your modules here, e.g.:
const dgram = require('dgram');
const request = require('request');
/**
* The adapter instance
* @type {ioBroker.Adapter}
*/
let adapter;
const DEFAULT_UDP_PORT = 7090;
const BROADCAST_UDP_PORT = 7092;
let txSocket;
let rxSocketReports = null;
let rxSocketBroadcast = null;
let sendDelayTimer = null;
const states = {}; // contains all actual state values
const stateChangeListeners = {};
const currentStateValues = {}; // contains all actual state values
const sendQueue = [];
const MODEL_P20 = 1; // product ID is like KC-P20-ES240030-000-ST
const MODEL_P30 = 2;
const MODEL_BMW = 3; // product ID is like BMW-10-EC2405B2-E1R
const TYPE_A_SERIES = 1;
const TYPE_B_SERIES = 2;
const TYPE_C_SERIES = 3; // product ID for P30 is like KC-P30-EC240422-E00
const TYPE_E_SERIES = 4; // product ID for P30 is like KC-P30-EC240422-E00
const TYPE_X_SERIES = 5;
const TYPE_D_EDITION = 6; // product id (only P30) is KC-P30-EC220112-000-DE, there's no other
//var ioBroker_Settings
let ioBrokerLanguage = 'en';
const chargeTextAutomatic = {'en': 'PV automatic active', 'de': 'PV-optimierte Ladung'};
const chargeTextMax = {'en': 'max. charging power', 'de': 'volle Ladeleistung'};
let wallboxWarningSent = false; // Warning for inacurate regulation with Deutshcland Edition
let wallboxUnknownSent = false; // Warning wallbox not recognized
let isPassive = true; // no automatic power regulation?
let lastDeviceData = null; // time of last check for device information
const intervalDeviceDataUpdate = 24 * 60 * 60 * 1000; // check device data (e.g. firmware) every 24 hours => 'report 1'
let intervalPassiveUpdate = 10 * 60 * 1000; // check charging information every 10 minutes
let timerDataUpdate = null; // interval object for calculating timer
const intervalActiceUpdate = 15 * 1000; // check current power (and calculate PV-automatics/power limitation every 15 seconds (report 2+3))
let lastCalculating = null; // time of last check for charging information
const intervalCalculating = 25 * 1000; // calculate charging poser every 25(-30) seconds
let chargingToBeStarted = false; // tried to start charging session last time?
let loadChargingSessions = false;
let photovoltaicsActive = false; // is photovoltaics automatic active?
let useX1switchForAutomatic = true;
let maxPowerActive = false; // is limiter für maximum power active?
let wallboxIncluded = true; // amperage of wallbox include in energy meters 1, 2 or 3?
let amperageDelta = 500; // default for step of amperage
let underusage = 0; // maximum regard use to reach minimal charge power for vehicle
const minAmperageDefault = 6000; // default minimum amperage to start charging session
const maxCurrentEnWG = 6000; // maximum current allowed when limitation of §14a EnWg is active
let minAmperage = 5000; // minimum amperage to start charging session
let minChargeSeconds = 0; // minimum of charge time even when surplus is not sufficient
let minRegardSeconds = 0; // maximum time to accept regard when charging
let min1p3pSwSec = 0; // minimum time betwenn phase switching
let isMaxPowerCalculation = false; // switch to show if max power calculation is active
let valueFor1p3pOff = null; // value that will be assigned to 1p/3p state when vehicle is unplugged (unpower switch)
let valueFor1pCharging = null; // value that will be assigned to 1p/3p state to switch to 1 phase charging
let valueFor3pCharging = null; // value that will be assigned to 1p/3p state to switch to 3 phase charging
let stateFor1p3pCharging = null; // state for switching installation contactor
let stateFor1p3pAck = false; // Is state acknowledged?
let stepFor1p3pSwitching = 0; // 0 = nothing to switch, 1 = stop charging, 2 = switch phases, 3 = acknowledge switching, -1 = temporarily disabled
let retries1p3pSwitching = 0;
let valueFor1p3pSwitching = null; // value for switch
let batteryStrategy = 0; // default = don't care for a battery storage
let startWithState5Attempted = false; // switch, whether a start command was tried once even with state of 5
const voltage = 230; // calculate with european standard voltage of 230V
const firmwareUrl = 'https://www.keba.com/en/emobility/service-support/downloads/downloads';
const regexP30cSeries = /<h3 .*class="headline *tw-h3 ">(?:(?:\s|\n|\r)*?)Updates KeContact P30 a-\/b-\/c-\/e-series((?:.|\n|\r)*?)<h3/gi;
//const regexP30xSeries = /<h3 .*class="headline *tw-h3 ">(?:(?:\s|\n|\r)*?)Updates KeContact P30 x-series((?:.|\n|\r)*?)<h3/gi;
const regexFirmware = /<div class="mt-3">Firmware Update\s+((?:.)*?)<\/div>/gi;
const regexCurrFirmware = /P30 v\s+((?:.)*?)\s+\(/gi;
const stateWallboxEnabled = 'enableUser'; /*Enable User*/
const stateWallboxCurrent = 'currentUser'; /*Current User*/
const stateWallboxMaxCurrent = 'currentHardware'; /*Maximum Current Hardware*/
const stateWallboxCurrentWithTimer = 'currentTimer'; /*Current value for currTime */
const stateTimeForCurrentChange = 'timeoutCurrentTimer'; /*Timer value for currTime */
const stateWallboxPhase1 = 'i1'; /*Current 1*/
const stateWallboxPhase2 = 'i2'; /*Current 2*/
const stateWallboxPhase3 = 'i3'; /*Current 3*/
const stateWallboxPlug = 'plug'; /*Plug status */
const stateWallboxState = 'state'; /*State of charging session */
const stateWallboxPower = 'p'; /*Power*/
const stateWallboxChargeAmount = 'ePres'; /*ePres - amount of charged energy in Wh */
const stateWallboxDisplay = 'display';
const stateWallboxOutput = 'output';
const stateSetEnergy = 'setenergy';
const stateReport = 'report';
const stateStart = 'start';
const stateStop = 'stop';
const stateSetDateTime = 'setdatetime';
const stateUnlock = 'unlock';
const stateProduct = 'product';
const stateX1input = 'input';
const stateFirmware = 'firmware'; /*current running version of firmware*/
const stateFirmwareAvailable = 'statistics.availableFirmware';/*current version of firmware available at keba.com*/
const stateSurplus = 'statistics.surplus'; /*current surplus for PV automatics*/
const stateMaxPower = 'statistics.maxPower'; /*maximum power for wallbox*/
const stateChargingPhases = 'statistics.chargingPhases'; /*number of phases with which vehicle is currently charging*/
const statePlugTimestamp = 'statistics.plugTimestamp'; /*Timestamp when vehicled was plugged to wallbox*/
const stateChargeTimestamp = 'statistics.chargeTimestamp'; /*Timestamp when charging (re)started */
const stateRegardTimestamp = 'statistics.regardTimestamp'; /*Timestamp when charging session was continued with regard */
const state1p3pSwTimestamp = 'statistics.1p3pSwTimestamp'; /*Timestamp when 1p3pSw was changed */
const stateSessionId = 'statistics.sessionId'; /*id of current charging session */
const stateRfidTag = 'statistics.rfid_tag'; /*rfid tag of current charging session */
const stateRfidClass = 'statistics.rfid_class'; /*rfid class of current charging session */
const stateWallboxDisabled = 'automatic.pauseWallbox'; /*switch to generally disable charging of wallbox, e.g. because of night storage heater */
const statePvAutomatic = 'automatic.photovoltaics'; /*switch to charge vehicle in regard to surplus of photovoltaics (false= charge with max available power) */
const stateAddPower = 'automatic.addPower'; /*additional regard to run charging session*/
const stateLimitCurrent = 'automatic.limitCurrent'; /*maximum amperage for charging*/
const stateLimitCurrent1p = 'automatic.limitCurrent1p'; /*maximum amperage for charging when 1p 3p switch set to 1p */
const stateManualPhases = 'automatic.calcPhases'; /*count of phases to calculate with for KeContact Deutschland-Edition*/
const stateBatteryStrategy = 'automatic.batteryStorageStrategy'; /*strategy to use for battery storage dynamically*/
const stateMinimumSoCOfBatteryStorage = 'automatic.batterySoCForCharging'; /*SoC above which battery storage may be used for charging vehicle*/
const stateLastChargeStart = 'statistics.lastChargeStart'; /*Timestamp when *last* charging session was started*/
const stateLastChargeFinish = 'statistics.lastChargeFinish'; /*Timestamp when *last* charging session was finished*/
const stateLastChargeAmount = 'statistics.lastChargeAmount'; /*Energy charging in *last* session in kWh*/
const stateMsgFromOtherwallbox = 'internal.message'; /*Message passed on from other instance*/
const stateX2Source = 'x2phaseSource'; /*X2 switch source */
const stateX2Switch = 'x2phaseSwitch'; /*X2 switch */
/**
* Starts the adapter instance
* @param {Partial<utils.AdapterOptions>} [options]
*/
function startAdapter(options) {
// Create the adapter and define its methods
return adapter = utils.adapter(Object.assign({}, options, {
name: 'kecontact',
// The ready callback is called when databases are connected and adapter received configuration.
// start here!
ready: onAdapterReady, // Main method defined below for readability
// is called when adapter shuts down - callback has to be called under any circumstances!
unload: onAdapterUnload,
// If you need to react to object changes, uncomment the following method.
// You also need to subscribe to the objects with `adapter.subscribeObjects`, similar to `adapter.subscribeStates`.
// objectChange: (id, obj) => {
// if (obj) {
// // The object was changed
// adapter.log.info(`object ${id} changed: ${JSON.stringify(obj)}`);
// } else {
// // The object was deleted
// adapter.log.info(`object ${id} deleted`);
// }
// },
// is called if a subscribed state changes
stateChange: onAdapterStateChange,
// If you need to accept messages in your adapter, uncomment the following block.
// /**
// * Some message was sent to this instance over message box. Used by email, pushover, text2speech, ...
// * Using this method requires 'common.messagebox' property to be set to true in io-package.json
// */
// message: (obj) => {
// if (typeof obj === 'object' && obj.message) {
// if (obj.command === 'send') {
// // e.g. send email or pushover or whatever
// adapter.log.info('send command');
// // Send response in callback if required
// if (obj.callback) adapter.sendTo(obj.from, obj.command, 'Message received', obj.callback);
// }
// }
// },
}));
}
/**
* Function is called after the startup of the Adapter if its ready. It's the first function which is called.
*/
function onAdapterReady() {
if (! checkConfig()) {
adapter.log.error('start of adapter not possible due to config errors');
return;
}
if (loadChargingSessions) {
//History Datenpunkte anlegen
createHistory();
}
main();
}
/**
* Function is called if the adapter is unloaded.
*/
function onAdapterUnload(callback) {
try {
if (sendDelayTimer) {
clearInterval(sendDelayTimer);
}
disableChargingTimer();
if (txSocket) {
txSocket.close();
}
if (rxSocketReports) {
if (rxSocketBroadcast.active)
rxSocketReports.close();
}
if (rxSocketBroadcast) {
if (rxSocketBroadcast.active)
rxSocketBroadcast.close();
}
if (isForeignStateSpecified(adapter.config.stateRegard))
adapter.unsubscribeForeignStates(adapter.config.stateRegard);
if (isForeignStateSpecified(adapter.config.stateSurplus))
adapter.unsubscribeForeignStates(adapter.config.stateSurplus);
if (isForeignStateSpecified(adapter.config.stateBatteryCharging))
adapter.unsubscribeForeignStates(adapter.config.stateBatteryCharging);
if (isForeignStateSpecified(adapter.config.stateBatteryDischarging))
adapter.unsubscribeForeignStates(adapter.config.stateBatteryDischarging);
if (isForeignStateSpecified(adapter.config.stateBatterySoC))
adapter.unsubscribeForeignStates(adapter.config.stateBatterySoC);
if (isForeignStateSpecified(adapter.config.stateEnergyMeter1))
adapter.unsubscribeForeignStates(adapter.config.stateEnergyMeter1);
if (isForeignStateSpecified(adapter.config.stateEnergyMeter2))
adapter.unsubscribeForeignStates(adapter.config.stateEnergyMeter2);
if (isForeignStateSpecified(adapter.config.stateEnergyMeter3))
adapter.unsubscribeForeignStates(adapter.config.stateEnergyMeter3);
if (isForeignStateSpecified(adapter.config.stateEnWG))
adapter.unsubscribeForeignStates(adapter.config.stateEnWG);
} catch (e) {
if (adapter.log) // got an exception 'TypeError: Cannot read property 'warn' of undefined'
adapter.log.warn('Error while closing: ' + e);
}
callback();
}
/**
* Function is called if a subscribed state changes
* @param {string} id is the id of the state which changed
* @param state is the new value of the state which is changed
*/
function onAdapterStateChange (id, state) {
// Warning: state can be null if it was deleted!
if (!id || !state) {
return;
}
//adapter.log.silly('stateChange ' + id + ' ' + JSON.stringify(state));
// save state changes of foreign adapters - this is done even if value has not changed but acknowledged
const oldValue = getStateInternal(id);
let newValue = state.val;
setStateInternal(id, newValue);
// if vehicle is (un)plugged check if schedule has to be disabled/enabled
if (id == adapter.namespace + '.' + stateWallboxPlug) {
const wasVehiclePlugged = isVehiclePlugged(oldValue);
const isNowVehiclePlugged = isVehiclePlugged(newValue);
if (isNowVehiclePlugged && ! wasVehiclePlugged) {
adapter.log.info('vehicle plugged to wallbox');
if (stepFor1p3pSwitching < 0) {
reset1p3pSwitching();
}
if (! isPvAutomaticsActive()) {
set1p3pSwitching(valueFor3pCharging);
}
initChargingSession();
forceUpdateOfCalculation();
} else if (! isNowVehiclePlugged && wasVehiclePlugged) {
adapter.log.info('vehicle unplugged from wallbox');
finishChargingSession();
set1p3pSwitching(valueFor1p3pOff);
if (stepFor1p3pSwitching < 0) {
reset1p3pSwitching();
}
}
}
// if the Wallbox have been disabled or enabled.
if (id == adapter.namespace + '.' + stateWallboxDisabled) {
if (oldValue != newValue) {
adapter.log.info('change pause status of wallbox from ' + oldValue + ' to ' + newValue);
newValue = getBoolean(newValue);
forceUpdateOfCalculation();
}
}
// if PV Automatic has been disable or enabled.
if (id == adapter.namespace + '.' + statePvAutomatic) {
if (oldValue != newValue) {
adapter.log.info('change of photovoltaics automatic from ' + oldValue + ' to ' + newValue);
newValue = getBoolean(newValue);
displayChargeMode();
forceUpdateOfCalculation();
}
}
// if the state of the X1 Input has chaned.
if (id == adapter.namespace + '.' + stateX1input) {
if (useX1switchForAutomatic) {
if (oldValue != newValue) {
adapter.log.info('change of photovoltaics automatic via X1 from ' + oldValue + ' to ' + newValue);
displayChargeMode();
forceUpdateOfCalculation();
}
}
}
// if the value for AddPower was changes.
if (id == adapter.namespace + '.' + stateAddPower) {
if (oldValue != newValue)
adapter.log.info('change additional power from regard from ' + oldValue + ' to ' + newValue);
}
if (id == adapter.namespace + '.' + stateFirmware) {
checkFirmware();
}
if (id == stateFor1p3pCharging) {
stateFor1p3pAck = state.ack;
}
if (state.ack) {
return;
}
if (! id.startsWith(adapter.namespace)) {
// do not care for foreign states
return;
}
if (!Object.prototype.hasOwnProperty.call(stateChangeListeners, id)) {
adapter.log.error('Unsupported state change: ' + id);
return;
}
stateChangeListeners[id](oldValue, newValue);
setStateAck(id, newValue);
}
/**
* Function is called at the end of the function onAdapterReady
* It shows the full configuration of the adapter on the config window at start and created the upd socket.
*/
async function main() {
// Reset the connection indicator during startup
await adapter.setStateAsync('info.connection', false, true);
// The adapters config (in the instance object everything under the attribute 'native') is accessible via
// adapter.config:
adapter.log.info('config host: ' + adapter.config.host);
adapter.log.info('config passiveMode: ' + adapter.config.passiveMode);
adapter.log.info('config pollInterval: ' + adapter.config.pollInterval);
adapter.log.info('config loadChargingSessions: ' + adapter.config.loadChargingSessions);
adapter.log.info('config useX1forAutomatic: ' + adapter.config.useX1forAutomatic);
adapter.log.info('config stateRegard: ' + adapter.config.stateRegard);
adapter.log.info('config stateSurplus: ' + adapter.config.stateSurplus);
adapter.log.info('config stateBatteryCharging: ' + adapter.config.stateBatteryCharging);
adapter.log.info('config stateBatteryDischarging: ' + adapter.config.stateBatteryDischarging);
adapter.log.info('config stateBatterySoC: ' + adapter.config.stateBatterySoC);
adapter.log.info('config batteryPower: ' + adapter.config.batteryPower);
adapter.log.info('config batteryMinSoC: ' + adapter.config.batteryMinSoC);
adapter.log.info('config batteryStorageStrategy: ' + adapter.config.batteryStorageStrategy);
adapter.log.info('config statesIncludeWallbox: ' + adapter.config.statesIncludeWallbox);
adapter.log.info('config.state1p3pSwitch: ' + adapter.config.state1p3pSwitch);
adapter.log.info('config.1p3pViax2: ' + adapter.config['1p3pViaX2']);
adapter.log.info('config.1p3pSwitchIsNO: ' + adapter.config['1p3pSwitchIsNO'] +
', 1p = ' + valueFor1pCharging + ', 3p = ' + valueFor3pCharging + ', off = ' + valueFor1p3pOff);
adapter.log.info('config minAmperage: ' + adapter.config.minAmperage);
adapter.log.info('config addPower: ' + adapter.config.addPower);
adapter.log.info('config delta: ' + adapter.config.delta);
adapter.log.info('config underusage: ' + adapter.config.underusage);
adapter.log.info('config minTime: ' + adapter.config.minTime);
adapter.log.info('config regardTime: ' + adapter.config.regardTime);
adapter.log.info('config stateEnWG: ' + adapter.config.stateEnWG);
adapter.log.info('config dynamicEnWG: ' + adapter.config.dynamicEnWG);
adapter.log.info('config maxPower: ' + adapter.config.maxPower);
adapter.log.info('config stateEnergyMeter1: ' + adapter.config.stateEnergyMeter1);
adapter.log.info('config stateEnergyMeter2: ' + adapter.config.stateEnergyMeter2);
adapter.log.info('config stateEnergyMeter3: ' + adapter.config.stateEnergyMeter3);
adapter.log.info('config wallboxNotIncluded: ' + adapter.config.wallboxNotIncluded);
/*
For every state in the system there has to be also an object of type state
Here a simple template for a boolean variable named 'testVariable'
Because every adapter instance uses its own unique namespace variable names can't collide with other adapters variables
*/
// await adapter.setObjectNotExistsAsync('testVariable', {
// type: 'state',
// common: {
// name: 'testVariable',
// type: 'boolean',
// role: 'indicator',
// read: true,
// write: true,
// },
// native: {},
// });
// In order to get state updates, you need to subscribe to them. The following line adds a subscription for our variable we have created above.
// adapter.subscribeStates('testVariable');
// You can also add a subscription for multiple states. The following line watches all states starting with 'lights.'
// adapter.subscribeStates('lights.*');
// Or, if you really must, you can also watch all states. Don't do this if you don't need to. Otherwise this will cause a lot of unnecessary load on the system:
// adapter.subscribeStates('*');
/*
setState examples
you will notice that each setState will cause the stateChange event to fire (because of above subscribeStates cmd)
*/
// the variable testVariable is set to true as command (ack=false)
// await adapter.setStateAsync('testVariable', true);
// same thing, but the value is flagged 'ack'
// ack should be always set to true if the value is received from or acknowledged from the target system
// await adapter.setStateAsync('testVariable', { val: true, ack: true });
// same thing, but the state is deleted after 30s (getState will return null afterwards)
// await adapter.setStateAsync('testVariable', { val: true, ack: true, expire: 30 });
// examples for the checkPassword/checkGroup functions
// adapter.checkPassword('admin', 'iobroker', (res) => {
// adapter.log.info('check user admin pw iobroker: ' + res);
// });
// adapter.checkGroup('admin', 'admin', (res) => {
// adapter.log.info('check group user admin group admin: ' + res);
// });
txSocket = dgram.createSocket('udp4');
rxSocketReports = dgram.createSocket({ type: 'udp4', reuseAddr: true });
rxSocketReports.on('error', (err) => {
adapter.log.error('RxSocketReports error: ' + err.message + '\n' + err.stack);
rxSocketReports.close();
});
rxSocketReports.on('listening', function () {
rxSocketReports.setBroadcast(true);
const address = rxSocketReports.address();
adapter.log.debug('UDP server listening on ' + address.address + ':' + address.port);
});
rxSocketReports.on('message', handleWallboxMessage);
rxSocketReports.bind(DEFAULT_UDP_PORT, '0.0.0.0');
rxSocketBroadcast = dgram.createSocket({ type: 'udp4', reuseAddr: true });
rxSocketBroadcast.on('error', (err) => {
adapter.log.error('RxSocketBroadcast error: ' + err.message + '\n' + err.stack);
rxSocketBroadcast.close();
});
rxSocketBroadcast.on('listening', function () {
rxSocketBroadcast.setBroadcast(true);
rxSocketBroadcast.setMulticastLoopback(true);
const address = rxSocketBroadcast.address();
adapter.log.debug('UDP broadcast server listening on ' + address.address + ':' + address.port);
});
rxSocketBroadcast.on('message', handleWallboxBroadcast);
rxSocketBroadcast.bind(BROADCAST_UDP_PORT);
//await adapter.setStateAsync('info.connection', true, true); // too ealry to acknowledge ...
adapter.getForeignObject('system.config', function(err, ioBroker_Settings) {
if (err) {
adapter.log.error('Error while fetching system.config: ' + err);
return;
}
if (ioBroker_Settings && (ioBroker_Settings.common.language == 'de')) {
ioBrokerLanguage = 'de';
} else {
ioBrokerLanguage = 'en';
}
});
adapter.getStatesOf(function (err, data) {
if (data) {
for (let i = 0; i < data.length; i++) {
if (data[i].native && data[i].native.udpKey) {
states[data[i].native.udpKey] = data[i];
}
}
}
// save all state value into internal store
adapter.getStates('*', function (err, obj) {
if (err) {
adapter.log.error('error reading states: ' + err);
} else {
if (obj) {
for (const i in obj) {
if (! Object.prototype.hasOwnProperty.call(obj, i)) continue;
if (obj[i] !== null) {
if (typeof obj[i] == 'object') {
setStateInternal(i, obj[i].val);
} else {
adapter.log.error('unexpected state value: ' + obj[i]);
}
}
}
} else {
adapter.log.error('not states found');
}
}
});
start();
});
}
/**
* Function is called at the end of main function and will add the subscribed functions
* of all the states of the dapter.
*/
function start() {
adapter.subscribeStates('*');
stateChangeListeners[adapter.namespace + '.' + stateWallboxEnabled] = function (_oldValue, newValue) {
sendUdpDatagram('ena ' + (newValue ? 1 : 0), true);
};
stateChangeListeners[adapter.namespace + '.' + stateWallboxCurrent] = function (_oldValue, newValue) {
sendUdpDatagram('curr ' + parseInt(newValue), true);
};
stateChangeListeners[adapter.namespace + '.' + stateWallboxCurrentWithTimer] = function (_oldValue, newValue) {
sendUdpDatagram('currtime ' + parseInt(newValue) + ' ' + getStateDefault0(stateTimeForCurrentChange), true);
};
stateChangeListeners[adapter.namespace + '.' + stateTimeForCurrentChange] = function () {
// parameters (oldValue, newValue) can be ommited if not needed
// no real action to do
};
stateChangeListeners[adapter.namespace + '.' + stateWallboxOutput] = function (_oldValue, newValue) {
sendUdpDatagram('output ' + (newValue ? 1 : 0), true);
};
stateChangeListeners[adapter.namespace + '.' + stateWallboxDisplay] = function (_oldValue, newValue) {
if (newValue !== null) {
if (typeof newValue == 'string') {
sendUdpDatagram('display 0 0 0 0 ' + newValue.replace(/ /g, '$'), true);
} else {
adapter.log.error('invalid data to send to display: ' + newValue);
}
}
};
stateChangeListeners[adapter.namespace + '.' + stateWallboxDisabled] = function (_oldValue, newValue) {
adapter.log.debug('set ' + stateWallboxDisabled + ' to ' + newValue);
// no real action to do
};
stateChangeListeners[adapter.namespace + '.' + statePvAutomatic] = function (_oldValue, newValue) {
adapter.log.debug('set ' + statePvAutomatic + ' to ' + newValue);
// no real action to do
};
stateChangeListeners[adapter.namespace + '.' + stateSetEnergy] = function (_oldValue, newValue) {
sendUdpDatagram('setenergy ' + parseInt(newValue) * 10, true);
};
stateChangeListeners[adapter.namespace + '.' + stateReport] = function (_oldValue, newValue) {
sendUdpDatagram('report ' + newValue, true);
};
stateChangeListeners[adapter.namespace + '.' + stateStart] = function (_oldValue, newValue) {
sendUdpDatagram('start ' + newValue, true);
};
stateChangeListeners[adapter.namespace + '.' + stateStop] = function (_oldValue, newValue) {
sendUdpDatagram('stop ' + newValue, true);
};
stateChangeListeners[adapter.namespace + '.' + stateSetDateTime] = function (_oldValue, newValue) {
sendUdpDatagram('setdatetime ' + newValue, true);
};
stateChangeListeners[adapter.namespace + '.' + stateUnlock] = function () {
sendUdpDatagram('unlock', true);
};
stateChangeListeners[adapter.namespace + '.' + stateX2Source] = function (_oldValue, newValue) {
sendUdpDatagram('x2src ' + newValue, true);
};
stateChangeListeners[adapter.namespace + '.' + stateX2Switch] = function (_oldValue, newValue) {
sendUdpDatagram('x2 ' + newValue, true);
setStateAck(state1p3pSwTimestamp, new Date().toString());
};
stateChangeListeners[adapter.namespace + '.' + stateAddPower] = function (_oldValue, newValue) {
adapter.log.debug('set ' + stateAddPower + ' to ' + newValue);
// no real action to do
};
stateChangeListeners[adapter.namespace + '.' + stateManualPhases] = function (_oldValue, newValue) {
adapter.log.debug('set ' + stateManualPhases + ' to ' + newValue);
// no real action to do
};
stateChangeListeners[adapter.namespace + '.' + stateLimitCurrent] = function (_oldValue, newValue) {
adapter.log.debug('set ' + stateLimitCurrent + ' to ' + newValue);
// no real action to do
};
stateChangeListeners[adapter.namespace + '.' + stateLimitCurrent1p] = function (_oldValue, newValue) {
adapter.log.debug('set ' + stateLimitCurrent1p + ' to ' + newValue);
// no real action to do
};
stateChangeListeners[adapter.namespace + '.' + stateBatteryStrategy] = function (_oldValue, newValue) {
adapter.log.debug('set ' + stateBatteryStrategy + ' to ' + newValue);
// no real action to do
};
stateChangeListeners[adapter.namespace + '.' + stateMsgFromOtherwallbox] = function (_oldValue, newValue) {
handleWallboxExchange(newValue);
};
stateChangeListeners[adapter.namespace + '.' + stateMinimumSoCOfBatteryStorage] = function (_oldValue, newValue) {
adapter.log.debug('set ' + stateMinimumSoCOfBatteryStorage + ' to ' + newValue);
// no real action to do
};
//sendUdpDatagram('i'); only needed for discovery
requestReports();
enableChargingTimer((isPassive) ? intervalPassiveUpdate : intervalActiceUpdate);
}
/**
* Function which checks weahter the state given by the parameter is defined in the adapter.config page.
* @param {string} stateValue is a string with the value of the state.
* @returns {*} true if the state is specified.
*/
function isForeignStateSpecified(stateValue) {
return stateValue && stateValue !== null && typeof stateValue == 'string' && stateValue !== '' && stateValue !== '[object Object]';
}
/**
* Function calls addForeignState which subscribes a foreign state to write values
* in 'currentStateValues'
* @param {string} stateName is a string with the name of the state.
* @returns {boolean} returns true if the function addForeingnState was executed successful
*/
function addForeignStateFromConfig(stateName) {
if (isForeignStateSpecified(stateName)) {
if (addForeignState(stateName)) {
return true;
} else {
adapter.log.error('Error when adding foreign state "' + stateName + '"');
return false;
}
}
return true;
}
/**
* Function is called by onAdapterReady. Check if config data is fine for adapter start
* @returns {boolean} returns true if everything is fine
*/
function checkConfig() {
let everythingFine = true;
if (adapter.config.host == '0.0.0.0' || adapter.config.host == '127.0.0.1') {
adapter.log.warn('Can\'t start adapter for invalid IP address: ' + adapter.config.host);
everythingFine = false;
}
if (adapter.config.loadChargingSessions == true) {
loadChargingSessions = true;
}
isPassive = false;
if (adapter.config.passiveMode) {
isPassive = true;
if (everythingFine) {
adapter.log.info('starting charging station in passive mode');
}
if (adapter.config.pollInterval > 0) {
intervalPassiveUpdate = getNumber(adapter.config.pollInterval) * 1000;
}
} else {
if (everythingFine) {
adapter.log.info('starting charging station in active mode');
}
}
if (isForeignStateSpecified(adapter.config.stateRegard)) {
photovoltaicsActive = true;
everythingFine = addForeignStateFromConfig(adapter.config.stateRegard) && everythingFine;
}
if (isForeignStateSpecified(adapter.config.stateSurplus)) {
photovoltaicsActive = true;
everythingFine = addForeignStateFromConfig(adapter.config.stateSurplus) && everythingFine;
}
if (photovoltaicsActive) {
everythingFine = init1p3pSwitching(adapter.config.state1p3pSwitch) && everythingFine;
everythingFine = addForeignStateFromConfig(adapter.config.stateBatteryCharging) && everythingFine;
everythingFine = addForeignStateFromConfig(adapter.config.stateBatteryDischarging) && everythingFine;
everythingFine = addForeignStateFromConfig(adapter.config.stateBatterySoC) && everythingFine;
if ((isForeignStateSpecified(adapter.config.stateBatteryCharging) ||
isForeignStateSpecified(adapter.config.stateBatteryDischarging) ||
adapter.config.batteryPower > 0)) {
batteryStrategy = adapter.config.batteryStorageStrategy;
}
if (adapter.config.useX1forAutomatic) {
useX1switchForAutomatic = true;
} else {
useX1switchForAutomatic = false;
}
if (! adapter.config.delta || adapter.config.delta <= 50) {
adapter.log.info('amperage delta not speficied or too low, using default value of ' + amperageDelta);
} else {
amperageDelta = getNumber(adapter.config.delta);
}
if (! adapter.config.minAmperage || adapter.config.minAmperage == 0) {
adapter.log.info('using default minimum amperage of ' + minAmperageDefault);
minAmperage = minAmperageDefault;
} else if (adapter.config.minAmperage < minAmperage) {
adapter.log.info('minimum amperage not speficied or too low, using default value of ' + minAmperage);
} else {
minAmperage = getNumber(adapter.config.minAmperage);
}
if (adapter.config.addPower !== 0) {
setStateAck(stateAddPower, getNumber(adapter.config.addPower));
}
if (adapter.config.underusage !== 0) {
underusage = getNumber(adapter.config.underusage);
}
if (! adapter.config.minTime || adapter.config.minTime < 0) {
adapter.log.info('minimum charge time not speficied or too low, using default value of ' + minChargeSeconds);
} else {
minChargeSeconds = getNumber(adapter.config.minTime);
}
if (! adapter.config.regardTime || adapter.config.regardTime < 0) {
adapter.log.info('minimum regard time not speficied or too low, using default value of ' + minRegardSeconds);
} else {
minRegardSeconds = getNumber(adapter.config.regardTime);
}
}
if (isX2PhaseSwitch()) {
if (isForeignStateSpecified(adapter.config.state1p3pSwitch)) {
everythingFine = false;
adapter.log.error('both, state for 1p/3p switch and switching via X2, must not be specified together');
}
const valueOn = 1;
const valueOff = 0;
valueFor1p3pOff = valueOff;
if (adapter.config['1p3pSwitchIsNO'] === true) {
valueFor1pCharging = valueOff;
valueFor3pCharging = valueOn;
} else {
valueFor1pCharging = valueOn;
valueFor3pCharging = valueOff;
}
min1p3pSwSec = 305;
adapter.log.info('Using min time between phase switching of: ' +min1p3pSwSec);
}
if (isEnWGDefined()) {
everythingFine = addForeignStateFromConfig(adapter.config.stateEnWG) && everythingFine;
}
if (adapter.config.maxPower && (adapter.config.maxPower != 0)) {
maxPowerActive = true;
if (adapter.config.maxPower <= 0) {
adapter.log.warn('max. power negative or zero - power limitation deactivated');
maxPowerActive = false;
}
}
if (maxPowerActive) {
everythingFine = addForeignStateFromConfig(adapter.config.stateEnergyMeter1) && everythingFine;
everythingFine = addForeignStateFromConfig(adapter.config.stateEnergyMeter2) && everythingFine;
everythingFine = addForeignStateFromConfig(adapter.config.stateEnergyMeter3) && everythingFine;
if (adapter.config.wallboxNotIncluded) {
wallboxIncluded = false;
} else {
wallboxIncluded = true;
}
if (everythingFine) {
if (! (adapter.config.stateEnergyMeter1 || adapter.config.stateEnergyMeter2 || adapter.config.stateEnergyMeter1)) {
adapter.log.error('no energy meters defined - power limitation deactivated');
maxPowerActive = false;
}
}
}
return everythingFine;
}
function init1p3pSwitching(stateNameFor1p3p) {
if (! isForeignStateSpecified(stateNameFor1p3p)) {
return true;
}
if (! addForeignStateFromConfig(stateNameFor1p3p)) {
return false;
}
adapter.getForeignState(stateNameFor1p3p, function (err, obj) {
if (err) {
adapter.log.error('error reading state ' + stateNameFor1p3p + ': ' + err);
return;
} else {
if (obj) {
stateFor1p3pCharging = stateNameFor1p3p;
let valueOn;
let valueOff;
if (typeof obj.val == 'boolean') {
valueOn = true;
valueOff = false;
} else if (typeof obj.val == 'number') {
valueOn = 1;
valueOff = 0;
} else {
adapter.log.error('unhandled type ' + typeof obj.val + ' for state ' + stateNameFor1p3p);
return;
}
stateFor1p3pAck = obj.ack;
valueFor1p3pOff = valueOff;
if (adapter.config['1p3pSwitchIsNO'] === true) {
valueFor1pCharging = valueOff;
valueFor3pCharging = valueOn;
} else {
valueFor1pCharging = valueOn;
valueFor3pCharging = valueOff;
}
}
else {
adapter.log.error('state ' + stateNameFor1p3p + ' not found!');
}
}
});
return true;
}
// subscribe a foreign state to save values in 'currentStateValues'
function addForeignState(id) {
if (typeof id !== 'string')
return false;
if (id == '' || id == ' ')
return false;
adapter.getForeignState(id, function (err, obj) {
if (err) {
adapter.log.error('error subscribing ' + id + ': ' + err);
} else {
if (obj) {
adapter.log.debug('subscribe state ' + id + ' - current value: ' + obj.val);
setStateInternal(id, obj.val);
adapter.subscribeForeignStates(id); // there's no return value (success, ...)
//adapter.subscribeForeignStates({id: id, change: 'ne'}); // condition is not working
}
else {
adapter.log.error('state ' + id + ' not found!');
}
}
});
return true;
}
function isMessageFromWallboxOfThisInstance(remote) {
return (remote.address == adapter.config.host);
}
function sendMessageToOtherInstance(message, remote) {
// save message for other instances by setting value into state
const prefix = 'system.adapter.';
const adapterpart = adapter.name + '.';
const suffix = '.uptime';
adapter.getForeignObjects(prefix + adapterpart + '*' + suffix, function(err, objects) {
if (err) {
adapter.log.error('Error while fetching other instances: ' + err);
return;
}
if (objects) {
for (const item in objects) {
if (Object.prototype.hasOwnProperty.call(objects, item) && item.endsWith(suffix)) {
const namespace = item.slice(prefix.length, - suffix.length);
adapter.getForeignObject(prefix + namespace, function(err, object) {
if (err) {
adapter.log.error('Error while fetching other instances: ' + err);
return;
}
if (object) {
if (Object.prototype.hasOwnProperty.call(object, 'native')) {
if (Object.prototype.hasOwnProperty.call(object.native, 'host')) {
if (object.native.host == remote.address) {
adapter.setForeignState(namespace + '.' + stateMsgFromOtherwallbox, message.toString().trim());
adapter.log.debug('Message from ' + remote.address + ' send to ' + namespace);
}
}
}
}
});
}
}
}
});
}
// handle incomming message from wallbox
function handleWallboxMessage(message, remote) {
adapter.log.debug('UDP datagram from ' + remote.address + ':' + remote.port + ': "' + message + '"');
if (isMessageFromWallboxOfThisInstance(remote)) { // handle only message from wallbox linked to this instance, ignore other wallboxes sending broadcasts
// Mark that connection is established by incomming data
handleMessage(message, 'received');
} else {
sendMessageToOtherInstance(message, remote);
}
}
// handle incomming broadcast message from wallbox
function handleWallboxBroadcast(message, remote) {
adapter.log.debug('UDP broadcast datagram from ' + remote.address + ':' + remote.port + ': "' + message + '"');
if (isMessageFromWallboxOfThisInstance(remote)) { // handle only message from wallbox linked to this instance, ignore other wallboxes sending broadcasts
handleMessage(message, 'broadcast');
}
}
// handle incomming message from other instance for this wallbox
function handleWallboxExchange(message) {
adapter.log.debug('datagram from other instance: "' + message + '"');
handleMessage(message, 'instance');
}
function handleMessage(message, origin) {
// Mark that connection is established by incomming data
adapter.setState('info.connection', true, true);
let msg = '';
try {
msg = message.toString().trim();
if (msg.length === 0) {
return;
}
if (msg == 'started ...') {
adapter.log.info('Wallbox startup complete');
return;
}
if (msg == 'i') {
adapter.log.debug('Received: ' + message);
return;
}
if (msg.startsWith('TCH-OK')) {
adapter.log.debug('Received ' + message);
return;
}
if (msg.startsWith('TCH-ERR')) {
adapter.log.error('Error received from wallbox: ' + message);
return;
}
if (msg[0] == '"') {
msg = '{ ' + msg + ' }';
}
handleJsonMessage(JSON.parse(msg));
} catch (e) {
adapter.log.warn('Error handling ' + origin + ' message: ' + e + ' (' + msg + ')');
return;
}
}
async function handleJsonMessage(message) {
// message auf ID Kennung für Session History prüfen
if (message.ID >= 100 && message.ID <= 130) {
adapter.log.debug('History ID received: ' + message.ID.substr(1));
const sessionid = message.ID.substr(1);
if (loadChargingSessions) {
updateState(states[sessionid + '_json'], JSON.stringify([message]));
}
for (const key in message){
if (states[sessionid + '_' + key] || loadChargingSessions === false) {
try {
if (message.ID == 100) {
// process some values of current charging session
switch (key) {
case 'Session ID': setStateAck(stateSessionId, message[key]); break;
case 'RFID tag': setStateAck(stateRfidTag, message[key]); break;
case 'RFID class': setStateAck(stateRfidClass, message[key]); break;
}
}
if (loadChargingSessions) {
updateState(states[sessionid + '_' + key], message[key]);
}
} catch (e) {
adapter.log.warn('Couldn"t update state ' + 'Session_' + sessionid + '.' + key + ': ' + e);
}
} else if (key != 'ID'){
adapter.log.warn('Unknown Session value received: ' + key + '=' + message[key]);
}
}
} else {
for (const key in message) {
if (states[key]) {
try {
await updateState(states[key], message[key]);
if (key == 'X2 phaseSwitch source' && isX2PhaseSwitch()) {
const currentValue = getStateDefault0(states[key]._id);
if (currentValue !== 4) {
adapter.log.info('activating X2 source from ' + currentValue + ' to 4 for phase switching');
sendUdpDatagram('x2src 4', true);
}
}
} catch (e) {
adapter.log.warn('Couldn"t update state ' + key + ': ' + e);