-
Notifications
You must be signed in to change notification settings - Fork 57
/
Copy pathinit_device_model_db.cpp
1627 lines (1373 loc) · 71 KB
/
init_device_model_db.cpp
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
// SPDX-License-Identifier: Apache-2.0
// Copyright Pionix GmbH and Contributors to EVerest
#include <ocpp/v201/init_device_model_db.hpp>
#include <cstdint>
#include <fstream>
#include <map>
#include <string>
#include <everest/logging.hpp>
#include <ocpp/v201/enums.hpp>
const static std::string STANDARDIZED_COMPONENT_CONFIG_DIR = "standardized";
const static std::string CUSTOM_COMPONENT_CONFIG_DIR = "custom";
namespace ocpp::v201 {
// Forward declarations.
static void check_integrity(const std::map<ComponentKey, std::vector<DeviceModelVariable>>& component_configs);
static std::optional<std::string> check_integrity_required_value(const DeviceModelVariable& variable);
static std::vector<std::string> check_integrity_value_type(const DeviceModelVariable& variable);
static bool value_is_of_type(const std::string& value, const DataEnum& type);
static bool is_same_component_key(const ComponentKey& component_key1, const ComponentKey& component_key2);
static bool is_same_attribute_type(const VariableAttribute attribute1, const VariableAttribute& attribute2);
static bool is_attribute_different(const VariableAttribute& attribute1, const VariableAttribute& attribute2);
static bool variable_has_same_attributes(const std::vector<DbVariableAttribute>& attributes1,
const std::vector<DbVariableAttribute>& attributes2);
static bool variable_has_same_monitors(const std::vector<VariableMonitoringMeta>& monitors1,
const std::vector<VariableMonitoringMeta>& monitors2);
static bool is_characteristics_different(const VariableCharacteristics& c1, const VariableCharacteristics& c2);
static bool is_same_variable(const DeviceModelVariable& v1, const DeviceModelVariable& v2);
static bool is_variable_different(const DeviceModelVariable& v1, const DeviceModelVariable& v2);
static bool is_monitor_different(const VariableMonitoringMeta& meta1, const VariableMonitoringMeta& meta2);
// Spec based monitor duplicate detection
static bool is_monitor_duplicate(const VariableMonitoringMeta& meta1, const VariableMonitoringMeta& meta2);
static bool has_attribute_actual_value(const VariableAttribute& attribute,
const std::optional<std::string>& default_actual_value);
static std::string get_string_value_from_json(const json& value);
static std::string get_component_name_for_logging(const ComponentKey& component);
static std::string get_variable_name_for_logging(const DeviceModelVariable& variable);
InitDeviceModelDb::InitDeviceModelDb(const std::filesystem::path& database_path,
const std::filesystem::path& migration_files_path) :
common::DatabaseHandlerCommon(std::make_unique<common::DatabaseConnection>(database_path), migration_files_path,
MIGRATION_DEVICE_MODEL_FILE_VERSION_V201),
database_path(database_path),
database_exists(std::filesystem::exists(database_path)) {
}
InitDeviceModelDb::~InitDeviceModelDb() {
close_connection();
}
void InitDeviceModelDb::initialize_database(const std::filesystem::path& config_path, bool delete_db_if_exists = true) {
execute_init_sql(delete_db_if_exists);
// Get existing components from the database.
std::map<ComponentKey, std::vector<DeviceModelVariable>> existing_components;
DeviceModelMap device_model;
if (this->database_exists) {
existing_components = get_all_components_from_db();
}
// Get component config files from the filesystem.
std::map<ComponentKey, std::vector<DeviceModelVariable>> component_configs = get_all_component_configs(config_path);
// Check if the config is consistent (fe has a value when required).
check_integrity(component_configs);
// Remove components from db if they do not exist in the component config
if (this->database_exists) {
remove_not_existing_components_from_db(component_configs, existing_components);
}
// Starting a transaction makes this a lot faster (inserting all components takes a few seconds without it and a
// few milliseconds if it is done inside a transaction).
std::unique_ptr<common::DatabaseTransactionInterface> transaction = database->begin_transaction();
insert_components(component_configs, existing_components);
transaction->commit();
}
void InitDeviceModelDb::execute_init_sql(const bool delete_db_if_exists) {
if (delete_db_if_exists) {
if (std::filesystem::exists(database_path)) {
if (!std::filesystem::remove(database_path)) {
EVLOG_AND_THROW(InitDeviceModelDbError("Could not remove database " + database_path.u8string()));
}
database_exists = false;
}
}
if (database_exists) {
// Check if this is an old database version.
try {
this->database->open_connection();
if (this->database->get_user_version() == 0) {
EVLOG_AND_THROW(
InitDeviceModelDbError("Database does not support migrations yet, please update the database."));
}
} catch (const std::runtime_error& /* e*/) {
EVLOG_AND_THROW(
InitDeviceModelDbError("Database does not support migrations yet, please update the database."));
}
}
// Connect to the database. This will automatically do the migrations (including the initial sql file).
open_connection();
}
std::vector<std::filesystem::path>
InitDeviceModelDb::get_component_config_from_directory(const std::filesystem::path& directory) {
std::vector<std::filesystem::path> component_config_files;
for (const auto& p : std::filesystem::directory_iterator(directory)) {
if (p.path().extension() == ".json") {
component_config_files.push_back(p.path());
}
}
return component_config_files;
}
std::map<ComponentKey, std::vector<DeviceModelVariable>>
InitDeviceModelDb::get_all_component_configs(const std::filesystem::path& directory) {
const std::vector<std::filesystem::path> standardized_component_config_files =
get_component_config_from_directory(directory / STANDARDIZED_COMPONENT_CONFIG_DIR);
const std::vector<std::filesystem::path> custom_component_config_files =
get_component_config_from_directory(directory / CUSTOM_COMPONENT_CONFIG_DIR);
std::map<ComponentKey, std::vector<DeviceModelVariable>> standardized_components_map =
read_component_config(standardized_component_config_files);
std::map<ComponentKey, std::vector<DeviceModelVariable>> components =
read_component_config(custom_component_config_files);
// Merge the two maps so they can be used for the insert_component function with a single iterator. This will use
// the custom components map as base and add not existing standardized components to the components map. So if the
// component exists in both, the custom component will be used.
components.merge(standardized_components_map);
return components;
}
void InitDeviceModelDb::insert_components(
const std::map<ComponentKey, std::vector<DeviceModelVariable>>& components,
const std::map<ComponentKey, std::vector<DeviceModelVariable>>& existing_components) {
for (auto& component : components) {
// Check if component already exists in the database.
std::optional<std::pair<ComponentKey, std::vector<DeviceModelVariable>>> component_db;
if (this->database_exists &&
(component_db = component_exists_in_db(existing_components, component.first)).has_value()) {
// Component exists in the database, update component if necessary.
update_component_variables(component_db.value(), component.second);
} else {
// Database is new or component does not exist. Insert component.
insert_component(component.first, component.second);
}
}
}
void InitDeviceModelDb::insert_component(const ComponentKey& component_key,
const std::vector<DeviceModelVariable>& component_variables) {
EVLOG_debug << "Inserting component " << component_key.name;
static const std::string statement = "INSERT OR REPLACE INTO COMPONENT (NAME, INSTANCE, EVSE_ID, CONNECTOR_ID) "
"VALUES (@name, @instance, @evse_id, @connector_id)";
std::unique_ptr<common::SQLiteStatementInterface> insert_component_statement;
try {
insert_component_statement = this->database->new_statement(statement);
} catch (const common::QueryExecutionException&) {
throw InitDeviceModelDbError("Could not create statement " + statement);
}
insert_component_statement->bind_text("@name", component_key.name, ocpp::common::SQLiteString::Transient);
if (component_key.connector_id.has_value()) {
insert_component_statement->bind_int("@connector_id", component_key.connector_id.value());
} else {
insert_component_statement->bind_null("@connector_id");
}
if (component_key.evse_id.has_value()) {
insert_component_statement->bind_int("@evse_id", component_key.evse_id.value());
} else {
insert_component_statement->bind_null("@evse_id");
}
if (component_key.instance.has_value() && !component_key.instance.value().empty()) {
insert_component_statement->bind_text("@instance", component_key.instance.value(),
ocpp::common::SQLiteString::Transient);
} else {
insert_component_statement->bind_null("@instance");
}
if (insert_component_statement->step() != SQLITE_DONE) {
throw InitDeviceModelDbError("Could not insert component " + component_key.name + ": " +
std::string(this->database->get_error_message()));
}
const int64_t component_id = this->database->get_last_inserted_rowid();
// Loop over the properties of this component.
for (const auto& variable : component_variables) {
EVLOG_debug << "-- Inserting variable " << variable.name;
// Add variable
insert_variable(variable, static_cast<uint64_t>(component_id));
}
}
std::map<ComponentKey, std::vector<DeviceModelVariable>>
InitDeviceModelDb::read_component_config(const std::vector<std::filesystem::path>& components_config_path) {
std::map<ComponentKey, std::vector<DeviceModelVariable>> components;
for (const auto& path : components_config_path) {
std::ifstream config_file(path);
try {
json data = json::parse(config_file);
ComponentKey p = data;
if (data.contains("properties")) {
std::vector<DeviceModelVariable> variables =
get_all_component_properties(data.at("properties"), p.required);
components.insert({p, variables});
} else {
EVLOG_warning << "Component " << data.at("name") << " does not contain any properties";
continue;
}
} catch (const json::parse_error& e) {
EVLOG_error << "Error while parsing config file: " << path;
throw;
}
}
return components;
}
std::vector<DeviceModelVariable>
InitDeviceModelDb::get_all_component_properties(const json& component_properties,
std::vector<std::string> required_properties) {
std::vector<DeviceModelVariable> variables;
for (const auto& variable : component_properties.items()) {
DeviceModelVariable v = variable.value();
const std::string variable_key_name = variable.key();
// Check if this is a required variable and if it is, add that to the variable struct.
if (std::find(required_properties.begin(), required_properties.end(), variable_key_name) !=
required_properties.end()) {
v.required = true;
}
variables.push_back(v);
}
return variables;
}
void InitDeviceModelDb::insert_variable_characteristics(const VariableCharacteristics& characteristics,
const int64_t& variable_id) {
static const std::string statement = "INSERT OR REPLACE INTO VARIABLE_CHARACTERISTICS (DATATYPE_ID, VARIABLE_ID, "
"MAX_LIMIT, MIN_LIMIT, SUPPORTS_MONITORING, "
"UNIT, VALUES_LIST) VALUES (@datatype_id, @variable_id, @max_limit, "
"@min_limit, @supports_monitoring, @unit, @values_list)";
std::unique_ptr<common::SQLiteStatementInterface> insert_characteristics_statement;
try {
insert_characteristics_statement = this->database->new_statement(statement);
} catch (const common::QueryExecutionException&) {
throw InitDeviceModelDbError("Could not create statement " + statement);
}
insert_characteristics_statement->bind_int("@datatype_id", static_cast<int>(characteristics.dataType));
insert_characteristics_statement->bind_int("@variable_id", static_cast<int>(variable_id));
const uint8_t supports_monitoring = (characteristics.supportsMonitoring ? 1 : 0);
insert_characteristics_statement->bind_int("@supports_monitoring", supports_monitoring);
if (characteristics.unit.has_value()) {
insert_characteristics_statement->bind_text("@unit", characteristics.unit.value(),
ocpp::common::SQLiteString::Transient);
} else {
insert_characteristics_statement->bind_null("@unit");
}
if (characteristics.valuesList.has_value()) {
insert_characteristics_statement->bind_text("@values_list", characteristics.valuesList.value(),
ocpp::common::SQLiteString::Transient);
} else {
insert_characteristics_statement->bind_null("@values_list");
}
if (characteristics.maxLimit.has_value()) {
insert_characteristics_statement->bind_double("@max_limit",
static_cast<double>(characteristics.maxLimit.value()));
} else {
insert_characteristics_statement->bind_null("@max_limit");
}
if (characteristics.minLimit.has_value()) {
insert_characteristics_statement->bind_double("@min_limit",
static_cast<double>(characteristics.minLimit.value()));
} else {
insert_characteristics_statement->bind_null("@min_limit");
}
if (insert_characteristics_statement->step() != SQLITE_DONE) {
throw InitDeviceModelDbError(this->database->get_error_message());
}
}
void InitDeviceModelDb::update_variable_characteristics(const VariableCharacteristics& characteristics,
const int64_t& characteristics_id, const int64_t& variable_id) {
static const std::string update_characteristics_statement =
"UPDATE VARIABLE_CHARACTERISTICS SET DATATYPE_ID=@datatype_id, VARIABLE_ID=@variable_id, MAX_LIMIT=@max_limit, "
"MIN_LIMIT=@min_limit, SUPPORTS_MONITORING=@supports_monitoring, UNIT=@unit, VALUES_LIST=@values_list WHERE "
"ID=@characteristics_id";
std::unique_ptr<common::SQLiteStatementInterface> update_statement;
try {
update_statement = this->database->new_statement(update_characteristics_statement);
} catch (const common::QueryExecutionException&) {
throw InitDeviceModelDbError("Could not create statement " + update_characteristics_statement);
}
update_statement->bind_int("@datatype_id", static_cast<int>(characteristics.dataType));
update_statement->bind_int("@characteristics_id", static_cast<int>(characteristics_id));
update_statement->bind_int("@variable_id", static_cast<int>(variable_id));
const uint8_t supports_monitoring = (characteristics.supportsMonitoring ? 1 : 0);
update_statement->bind_int("@supports_monitoring", supports_monitoring);
if (characteristics.unit.has_value()) {
update_statement->bind_text("@unit", characteristics.unit.value(), ocpp::common::SQLiteString::Transient);
} else {
update_statement->bind_null("@unit");
}
if (characteristics.valuesList.has_value()) {
update_statement->bind_text("@values_list", characteristics.valuesList.value(),
ocpp::common::SQLiteString::Transient);
} else {
update_statement->bind_null("@values_list");
}
if (characteristics.maxLimit.has_value()) {
update_statement->bind_double("@max_limit", static_cast<double>(characteristics.maxLimit.value()));
} else {
update_statement->bind_null("@max_limit");
}
if (characteristics.minLimit.has_value()) {
update_statement->bind_double("@min_limit", static_cast<double>(characteristics.minLimit.value()));
} else {
update_statement->bind_null("@min_limit");
}
if (update_statement->step() != SQLITE_DONE) {
throw InitDeviceModelDbError("Could not update variable characteristics: " +
std::string(this->database->get_error_message()));
}
}
void InitDeviceModelDb::insert_variable(const DeviceModelVariable& variable, const uint64_t& component_id) {
static const std::string statement =
"INSERT OR REPLACE INTO VARIABLE (NAME, INSTANCE, COMPONENT_ID, REQUIRED) VALUES "
"(@name, @instance, @component_id, @required)";
std::unique_ptr<common::SQLiteStatementInterface> insert_variable_statement;
try {
insert_variable_statement = this->database->new_statement(statement);
} catch (const common::QueryExecutionException&) {
throw InitDeviceModelDbError("Could not create statement " + statement);
}
insert_variable_statement->bind_text("@name", variable.name, ocpp::common::SQLiteString::Transient);
insert_variable_statement->bind_int("@component_id", static_cast<int>(component_id));
if (variable.instance.has_value() && !variable.instance.value().empty()) {
insert_variable_statement->bind_text("@instance", variable.instance.value(),
ocpp::common::SQLiteString::Transient);
} else {
insert_variable_statement->bind_null("@instance");
}
const uint8_t required_int = (variable.required ? 1 : 0);
insert_variable_statement->bind_int("@required", required_int);
if (insert_variable_statement->step() != SQLITE_DONE) {
throw InitDeviceModelDbError("Variable " + variable.name +
" could not be inserted: " + std::string(this->database->get_error_message()));
}
const int64_t variable_id = this->database->get_last_inserted_rowid();
insert_variable_characteristics(variable.characteristics, variable_id);
insert_attributes(variable.attributes, static_cast<uint64_t>(variable_id), variable.default_actual_value);
insert_variable_monitors(variable.monitors, variable_id);
}
void InitDeviceModelDb::update_variable(const DeviceModelVariable& variable, const DeviceModelVariable& db_variable,
const uint64_t component_id) {
if (!db_variable.db_id.has_value()) {
EVLOG_error << "Can not update variable " << variable.name << ": database id unknown";
return;
}
static const std::string update_variable_statement =
"UPDATE VARIABLE SET NAME=@name, INSTANCE=@instance, COMPONENT_ID=@component_id, REQUIRED=@required WHERE "
"ID=@variable_id";
std::unique_ptr<common::SQLiteStatementInterface> update_statement;
try {
update_statement = this->database->new_statement(update_variable_statement);
} catch (const common::QueryExecutionException&) {
throw InitDeviceModelDbError("Could not create statement " + update_variable_statement);
}
update_statement->bind_int("@variable_id", static_cast<int>(db_variable.db_id.value()));
update_statement->bind_text("@name", variable.name, ocpp::common::SQLiteString::Transient);
update_statement->bind_int("@component_id", static_cast<int>(component_id));
if (variable.instance.has_value() && !variable.instance.value().empty()) {
update_statement->bind_text("@instance", variable.instance.value(), ocpp::common::SQLiteString::Transient);
} else {
update_statement->bind_null("@instance");
}
const uint8_t required_int = (variable.required ? 1 : 0);
update_statement->bind_int("@required", required_int);
if (update_statement->step() != SQLITE_DONE) {
throw InitDeviceModelDbError("Could not update variable " + variable.name + ": " +
std::string(this->database->get_error_message()));
}
if (db_variable.variable_characteristics_db_id.has_value() &&
is_characteristics_different(variable.characteristics, db_variable.characteristics)) {
update_variable_characteristics(variable.characteristics,
static_cast<int64_t>(db_variable.variable_characteristics_db_id.value()),
static_cast<int64_t>(db_variable.db_id.value()));
}
if (!variable_has_same_attributes(variable.attributes, db_variable.attributes)) {
update_attributes(variable.attributes, db_variable.attributes, db_variable.db_id.value(),
variable.default_actual_value);
}
if (!variable_has_same_monitors(variable.monitors, db_variable.monitors)) {
update_variable_monitors(variable.monitors, db_variable.monitors, db_variable.db_id.value());
}
}
void InitDeviceModelDb::delete_variable(const DeviceModelVariable& variable) {
if (!variable.db_id.has_value()) {
EVLOG_error << "Can not remove variable " << variable.name << " from db: id unknown";
return;
}
static const std::string delete_variable_statement = "DELETE FROM VARIABLE WHERE ID=@variable_id";
std::unique_ptr<common::SQLiteStatementInterface> delete_statement;
try {
delete_statement = this->database->new_statement(delete_variable_statement);
} catch (const common::QueryExecutionException&) {
throw InitDeviceModelDbError("Could not create statement " + delete_variable_statement);
}
delete_statement->bind_int("@variable_id", static_cast<int>(variable.db_id.value()));
if (delete_statement->step() != SQLITE_DONE) {
EVLOG_error << "Can not remove variable " << variable.name
<< " from db: " << this->database->get_error_message();
throw InitDeviceModelDbError("Could not delete variable " + variable.name + ": " +
std::string(this->database->get_error_message()));
}
}
void InitDeviceModelDb::insert_attribute(const VariableAttribute& attribute, const uint64_t& variable_id,
const std::optional<std::string>& default_actual_value) {
static const std::string statement =
"INSERT OR REPLACE INTO VARIABLE_ATTRIBUTE (VARIABLE_ID, MUTABILITY_ID, PERSISTENT, CONSTANT, TYPE_ID) "
"VALUES(@variable_id, @mutability_id, @persistent, @constant, @type_id)";
std::unique_ptr<common::SQLiteStatementInterface> insert_attributes_statement;
try {
insert_attributes_statement = this->database->new_statement(statement);
} catch (const common::QueryExecutionException&) {
throw InitDeviceModelDbError("Could not create statement " + statement);
}
insert_attributes_statement->bind_int("@variable_id", static_cast<int>(variable_id));
insert_attributes_statement->bind_int("@persistent", 1);
insert_attributes_statement->bind_int("@constant", 0);
if (attribute.mutability.has_value()) {
insert_attributes_statement->bind_int("@mutability_id", static_cast<int>(attribute.mutability.value()));
} else {
insert_attributes_statement->bind_null("@mutability_id");
}
if (attribute.type.has_value()) {
insert_attributes_statement->bind_int("@type_id", static_cast<int>(attribute.type.value()));
}
if (insert_attributes_statement->step() != SQLITE_DONE) {
throw InitDeviceModelDbError("Could not insert attribute: " + std::string(this->database->get_error_message()));
}
const int64_t attribute_id = this->database->get_last_inserted_rowid();
if (has_attribute_actual_value(attribute, default_actual_value)) {
insert_variable_attribute_value(
attribute_id, (attribute.value.has_value() ? attribute.value.value().get() : default_actual_value.value()),
true);
}
}
void InitDeviceModelDb::insert_attributes(const std::vector<DbVariableAttribute>& attributes,
const uint64_t& variable_id,
const std::optional<std::string>& default_actual_value) {
for (const auto& attribute : attributes) {
insert_attribute(attribute.variable_attribute, variable_id, default_actual_value);
}
}
void InitDeviceModelDb::update_attributes(const std::vector<DbVariableAttribute>& new_attributes,
const std::vector<DbVariableAttribute>& db_attributes,
const uint64_t& variable_id,
const std::optional<std::string>& default_actual_value) {
// First check if there are attributes in the database that are not in the config. They should be removed.
for (const auto& db_attribute : db_attributes) {
const auto& it = std::find_if(
new_attributes.begin(), new_attributes.end(), [&db_attribute](const DbVariableAttribute& new_attribute) {
return is_same_attribute_type(db_attribute.variable_attribute, new_attribute.variable_attribute);
});
if (it == new_attributes.end()) {
// Attribute not found in config, remove from db.
delete_attribute(db_attribute);
}
}
// Check if the variable attributes in the config match the ones from the database. If not, add or update.
for (const auto& new_attribute : new_attributes) {
const auto& it = std::find_if(
db_attributes.begin(), db_attributes.end(), [&new_attribute](const DbVariableAttribute& db_attribute) {
return is_same_attribute_type(new_attribute.variable_attribute, db_attribute.variable_attribute);
});
if (it == db_attributes.end()) {
// Variable attribute does not exist in the db, add to db.
insert_attribute(new_attribute.variable_attribute, variable_id, default_actual_value);
} else {
if (is_attribute_different(new_attribute.variable_attribute, it->variable_attribute)) {
update_attribute(new_attribute.variable_attribute, *it, default_actual_value);
}
}
}
}
void InitDeviceModelDb::update_attribute(const VariableAttribute& attribute, const DbVariableAttribute& db_attribute,
const std::optional<std::string>& default_actual_value) {
if (!db_attribute.db_id.has_value()) {
EVLOG_error << "Can not update attribute: id not found";
return;
}
static const std::string update_attribute_statement =
"UPDATE VARIABLE_ATTRIBUTE SET MUTABILITY_ID=@mutability_id, PERSISTENT=@persistent, CONSTANT=@constant, "
"TYPE_ID=@type_id WHERE ID=@id";
std::unique_ptr<common::SQLiteStatementInterface> update_statement;
try {
update_statement = this->database->new_statement(update_attribute_statement);
} catch (const common::QueryExecutionException&) {
throw InitDeviceModelDbError("Could not create statement " + update_attribute_statement);
}
update_statement->bind_int("@id", static_cast<int>(db_attribute.db_id.value()));
if (attribute.mutability.has_value()) {
update_statement->bind_int("@mutability_id", static_cast<int>(attribute.mutability.value()));
} else {
update_statement->bind_null("@mutability_id");
}
if (attribute.persistent.has_value()) {
update_statement->bind_int("@persistent", (attribute.persistent.value() ? 1 : 0));
} else if (db_attribute.variable_attribute.persistent.has_value()) {
update_statement->bind_int("@persistent", (db_attribute.variable_attribute.persistent.value() ? 1 : 0));
} else {
// Set default value.
update_statement->bind_int("@persistent", 1);
}
if (attribute.constant.has_value()) {
update_statement->bind_int("@constant", (attribute.constant.value() ? 1 : 0));
} else if (db_attribute.variable_attribute.constant.has_value()) {
update_statement->bind_int("@constant", (db_attribute.variable_attribute.constant.value() ? 1 : 0));
} else {
// Set default value.
update_statement->bind_int("@constant", 0);
}
if (attribute.type.has_value()) {
update_statement->bind_int("@type_id", static_cast<int>(attribute.type.value()));
} else {
update_statement->bind_null("@type_id");
}
if (update_statement->step() != SQLITE_DONE) {
EVLOG_error << "Could not update variable attribute: " << this->database->get_error_message();
throw InitDeviceModelDbError("Could not update attribute: " + std::string(this->database->get_error_message()));
}
if (has_attribute_actual_value(attribute, default_actual_value)) {
if (!insert_variable_attribute_value(
static_cast<int64_t>(db_attribute.db_id.value()),
(attribute.value.has_value() ? attribute.value.value().get() : default_actual_value.value()), false)) {
EVLOG_error << "Can not update variable attribute (" << db_attribute.db_id.value()
<< ") value: " << attribute.value.value();
}
}
}
void InitDeviceModelDb::delete_attribute(const DbVariableAttribute& attribute) {
if (!attribute.db_id.has_value()) {
EVLOG_error << "Could not remove attribute, because id is unknown.";
return;
}
static const std::string delete_attribute_statement = "DELETE FROM VARIABLE_ATTRIBUTE WHERE ID=@attribute_id";
std::unique_ptr<common::SQLiteStatementInterface> delete_statement;
try {
delete_statement = this->database->new_statement(delete_attribute_statement);
} catch (const common::QueryExecutionException&) {
throw InitDeviceModelDbError("Could not create statement " + delete_attribute_statement);
}
delete_statement->bind_int("@attribute_id", static_cast<int>(attribute.db_id.value()));
if (delete_statement->step() != SQLITE_DONE) {
throw InitDeviceModelDbError("Can not remove attribute: " + std::string(this->database->get_error_message()));
}
}
bool InitDeviceModelDb::insert_variable_attribute_value(const int64_t& variable_attribute_id,
const std::string& variable_attribute_value,
const bool warn_source_not_default) {
// Insert variable statement.
// Use 'IS' when value can also be NULL
// Only update when VALUE_SOURCE is 'default', because otherwise it is already updated by the csms or the user and
// we don't overwrite that.
static const std::string statement = "UPDATE VARIABLE_ATTRIBUTE "
"SET VALUE = @value, VALUE_SOURCE = 'default' "
"WHERE ID = @variable_attribute_id "
"AND (VALUE_SOURCE = 'default' OR VALUE_SOURCE = '' OR VALUE_SOURCE IS NULL)";
std::unique_ptr<common::SQLiteStatementInterface> insert_variable_attribute_statement;
try {
insert_variable_attribute_statement = this->database->new_statement(statement);
} catch (const common::QueryExecutionException&) {
throw InitDeviceModelDbError("Could not create statement " + statement);
}
insert_variable_attribute_statement->bind_int("@variable_attribute_id",
static_cast<int32_t>(variable_attribute_id));
insert_variable_attribute_statement->bind_text("@value", variable_attribute_value,
ocpp::common::SQLiteString::Transient);
if (insert_variable_attribute_statement->step() != SQLITE_DONE) {
throw InitDeviceModelDbError("Could not set value '" + variable_attribute_value +
"' of variable attribute id " + std::to_string(variable_attribute_id) + ": " +
std::string(this->database->get_error_message()));
} else if ((insert_variable_attribute_statement->changes() < 1) && warn_source_not_default) {
EVLOG_debug << "Could not set value '" + variable_attribute_value + "' of variable attribute id " +
std::to_string(variable_attribute_id) + ": value has already changed by other source";
}
return true;
}
void InitDeviceModelDb::insert_variable_monitor(const VariableMonitoringMeta& monitor, const int64_t& variable_id) {
std::string insert_statement =
"INSERT OR REPLACE INTO VARIABLE_MONITORING (VARIABLE_ID, SEVERITY, 'TRANSACTION', TYPE_ID, "
"CONFIG_TYPE_ID, VALUE, REFERENCE_VALUE) "
"VALUES (?, ?, ?, ?, ?, ?, ?)";
auto insert_stmt = this->database->new_statement(insert_statement);
insert_stmt->bind_int(1, variable_id);
insert_stmt->bind_int(2, monitor.monitor.severity);
insert_stmt->bind_int(3, monitor.monitor.transaction);
insert_stmt->bind_int(4, static_cast<int>(monitor.monitor.type));
insert_stmt->bind_int(5, static_cast<int>(monitor.type));
insert_stmt->bind_double(6, monitor.monitor.value);
if (monitor.monitor.type == MonitorEnum::Delta && !monitor.reference_value.has_value()) {
throw InitDeviceModelDbError("Delta monitors must have a reference value set:" + variable_id);
}
if (monitor.reference_value.has_value()) {
insert_stmt->bind_text(7, monitor.reference_value.value(), ocpp::common::SQLiteString::Transient);
} else {
insert_stmt->bind_null(7);
}
if (insert_stmt->step() != SQLITE_DONE) {
throw InitDeviceModelDbError("Can not insert monitor for variable id:" + variable_id);
}
}
void InitDeviceModelDb::insert_variable_monitors(const std::vector<VariableMonitoringMeta>& monitors,
const int64_t& variable_id) {
for (const VariableMonitoringMeta& monitor : monitors) {
insert_variable_monitor(monitor, variable_id);
}
}
void InitDeviceModelDb::update_variable_monitor(const VariableMonitoringMeta& new_monitor,
const VariableMonitoringMeta& db_monitor, const int64_t& variable_id) {
/* clang-format off */
static const std::string update_monitor = "UPDATE VARIABLE_MONITORING "
"SET SEVERITY=?, 'TRANSACTION'=?, TYPE_ID=?, CONFIG_TYPE_ID=?, VALUE=?, REFERENCE_VALUE=? "
"WHERE ID=?";
/* clang-format on */
auto update_stmt = this->database->new_statement(update_monitor);
update_stmt->bind_int(1, new_monitor.monitor.severity);
update_stmt->bind_int(2, new_monitor.monitor.transaction);
update_stmt->bind_int(3, static_cast<int>(new_monitor.monitor.type));
update_stmt->bind_int(4, static_cast<int>(new_monitor.type));
update_stmt->bind_double(5, new_monitor.monitor.value);
if (new_monitor.reference_value.has_value()) {
update_stmt->bind_text(6, new_monitor.reference_value.value(), ocpp::common::SQLiteString::Transient);
} else {
update_stmt->bind_null(6);
}
// Bind existing-database ID, from the existing DB monitor
update_stmt->bind_int(7, db_monitor.monitor.id);
if (update_stmt->step() != SQLITE_DONE) {
throw InitDeviceModelDbError("Can not update monitor for variable id:" + variable_id);
}
}
void InitDeviceModelDb::update_variable_monitors(const std::vector<VariableMonitoringMeta>& new_monitors,
const std::vector<VariableMonitoringMeta>& db_monitors,
const int64_t& variable_id) {
// Remove monitors that are present in the database but not in the config
for (const VariableMonitoringMeta& db_monitor : db_monitors) {
const auto& it = std::find_if(std::begin(new_monitors), std::end(new_monitors),
[&db_monitor](const VariableMonitoringMeta& new_monitor) {
return is_monitor_duplicate(db_monitor, new_monitor);
});
// Monitor duplicate not found in config, remove from db.
if (it == std::end(new_monitors)) {
delete_variable_monitor(db_monitor, variable_id);
}
}
// Check if the variable monitors in the config match the ones from the database. If not, add or update.
for (const VariableMonitoringMeta& new_monitor : new_monitors) {
const auto& it = std::find_if(
// Search for the config monitors in the database
std::begin(db_monitors), std::end(db_monitors), [&new_monitor](const VariableMonitoringMeta& db_monitor) {
// Two monitors are equivalent when they have the same type and severity (3.77 - Duplicate)
return is_monitor_duplicate(new_monitor, db_monitor);
});
if (it == std::end(db_monitors)) {
// Variable monitor does not exist in the db, add to db.
insert_variable_monitor(new_monitor, variable_id);
} else {
// On how monitors are identified see section 3.77
if (is_monitor_different(new_monitor, *it)) {
update_variable_monitor(new_monitor, *it, variable_id);
}
}
}
}
void InitDeviceModelDb::delete_variable_monitor(const VariableMonitoringMeta& monitor, const int64_t& variable_id) {
try {
std::string delete_query = "DELETE FROM VARIABLE_MONITORING WHERE ID = ?";
auto delete_stmt = this->database->new_statement(delete_query);
delete_stmt->bind_int(1, monitor.monitor.id);
if (delete_stmt->step() != SQLITE_DONE) {
throw InitDeviceModelDbError("Can not delete monitor: " + std::string(this->database->get_error_message()));
}
} catch (const common::QueryExecutionException& e) {
throw InitDeviceModelDbError("Delete monitor error: " + std::string(e.what()));
}
}
std::map<ComponentKey, std::vector<DeviceModelVariable>> InitDeviceModelDb::get_all_components_from_db() {
/* clang-format off */
const std::string statement =
"SELECT "
"c.ID, c.NAME, c.INSTANCE, c.EVSE_ID, c.CONNECTOR_ID, "
"v.ID, v.NAME, v.INSTANCE, v.REQUIRED, "
"vc.ID, vc.DATATYPE_ID, vc.MAX_LIMIT, vc.MIN_LIMIT, vc.SUPPORTS_MONITORING, vc.UNIT, vc.VALUES_LIST, "
"va.ID, va.MUTABILITY_ID, va.PERSISTENT, va.CONSTANT, va.TYPE_ID, va.VALUE, va.VALUE_SOURCE "
"FROM "
"COMPONENT c "
"JOIN VARIABLE v ON v.COMPONENT_ID = c.ID "
"JOIN VARIABLE_CHARACTERISTICS vc ON vc.VARIABLE_ID = v.ID "
"JOIN VARIABLE_ATTRIBUTE va ON va.VARIABLE_ID = v.ID";
/* clang-format on */
std::unique_ptr<common::SQLiteStatementInterface> select_statement;
try {
select_statement = this->database->new_statement(statement);
} catch (const common::QueryExecutionException&) {
throw InitDeviceModelDbError("Could not create statement " + statement);
}
std::map<ComponentKey, std::vector<DeviceModelVariable>> components;
int status;
while ((status = select_statement->step()) == SQLITE_ROW) {
ComponentKey component_key;
component_key.db_id = select_statement->column_int(0);
component_key.name = select_statement->column_text(1);
component_key.instance = select_statement->column_text_nullable(2);
if (select_statement->column_type(3) != SQLITE_NULL) {
component_key.evse_id = select_statement->column_int(3);
}
if (select_statement->column_type(4) != SQLITE_NULL) {
component_key.connector_id = select_statement->column_int(4);
}
bool variable_exists = false;
DeviceModelVariable new_variable;
new_variable.db_id = select_statement->column_int(5);
new_variable.name = select_statement->column_text(6);
new_variable.instance = select_statement->column_text_nullable(7);
DeviceModelVariable* variable = nullptr;
// Check if the variable is already added to the component. If it is, the attribute should be added to the
// vector of attributes, otherwise the whole variable must be added to the variable vector of the component.
const auto& it = components.find(component_key);
if (it != components.end()) {
// Component found. Now search for variables.
std::vector<DeviceModelVariable>& variables = it->second;
for (DeviceModelVariable& v : variables) {
if (is_same_variable(v, new_variable)) {
// Variable found as well. Set variable pointer to the found variable.
variable = &v;
variable_exists = true;
}
}
}
if (!variable_exists) {
// Variable does not exist, add extra information from database.
if (select_statement->column_type(8) != SQLITE_NULL) {
new_variable.required = (select_statement->column_int(8) == 1 ? true : false);
}
new_variable.variable_characteristics_db_id = select_statement->column_int(9);
new_variable.characteristics.dataType = static_cast<DataEnum>(select_statement->column_int(10));
if (select_statement->column_type(11) != SQLITE_NULL) {
new_variable.characteristics.maxLimit = select_statement->column_double(11);
}
if (select_statement->column_type(12) != SQLITE_NULL) {
new_variable.characteristics.minLimit = select_statement->column_double(12);
}
new_variable.characteristics.supportsMonitoring = (select_statement->column_int(13) == 1 ? true : false);
new_variable.characteristics.unit = select_statement->column_text_nullable(14);
new_variable.characteristics.valuesList = select_statement->column_text_nullable(15);
// Variable is new, set variable pointer to this new variable.
variable = &new_variable;
}
DbVariableAttribute attribute;
attribute.db_id = select_statement->column_int(16);
if (select_statement->column_type(17) != SQLITE_NULL) {
attribute.variable_attribute.mutability = static_cast<MutabilityEnum>(select_statement->column_int(17));
}
if (select_statement->column_type(18) != SQLITE_NULL) {
attribute.variable_attribute.persistent = (select_statement->column_int(18) == 1 ? true : false);
}
if (select_statement->column_type(19) != SQLITE_NULL) {
attribute.variable_attribute.constant = (select_statement->column_int(19) == 1 ? true : false);
}
if (select_statement->column_type(20) != SQLITE_NULL) {
attribute.variable_attribute.type = static_cast<AttributeEnum>(select_statement->column_int(20));
}
attribute.variable_attribute.value = select_statement->column_text_nullable(21);
attribute.value_source = select_statement->column_text_nullable(22);
variable->attributes.push_back(attribute);
// Query all monitors
if (variable->db_id.has_value()) {
auto monitors = get_variable_monitors_from_db(variable->db_id.value());
for (auto& monitor_meta : monitors) {
// If monitor is not already contained in the list
bool contained = std::find_if(std::begin(variable->monitors), std::end(variable->monitors),
[&monitor_meta](const auto& contained_monitor) {
return (contained_monitor.monitor.id == monitor_meta.monitor.id);
}) != std::end(variable->monitors);
if (!contained) {
variable->monitors.push_back(std::move(monitor_meta));
}
}
}
if (!variable_exists) {
components[component_key].push_back(*variable);
}
}
if (status != SQLITE_DONE) {
throw InitDeviceModelDbError("Could not get all components from the database: " +
std::string(this->database->get_error_message()));
}
return components;
}
std::optional<std::pair<ComponentKey, std::vector<DeviceModelVariable>>>
InitDeviceModelDb::component_exists_in_db(const std::map<ComponentKey, std::vector<DeviceModelVariable>>& db_components,
const ComponentKey& component) {
for (const auto& db_component : db_components) {
if (is_same_component_key(db_component.first, component)) {
return db_component;
}
}
return std::nullopt;
}
bool InitDeviceModelDb::component_exists_in_config(
const std::map<ComponentKey, std::vector<DeviceModelVariable>>& component_config, const ComponentKey& component) {
for (const auto& component_in_config : component_config) {
if (is_same_component_key(component, component_in_config.first)) {
return true;
}
}
return false;
}
void InitDeviceModelDb::remove_not_existing_components_from_db(
const std::map<ComponentKey, std::vector<DeviceModelVariable>>& component_config,
const std::map<ComponentKey, std::vector<DeviceModelVariable>>& db_components) {
for (const auto& component : db_components) {
if (!component_exists_in_config(component_config, component.first)) {
remove_component_from_db(component.first);
}
}
}
bool InitDeviceModelDb::remove_component_from_db(const ComponentKey& component) {
const std::string& delete_component_statement = "DELETE FROM COMPONENT WHERE ID = @component_id";
std::unique_ptr<common::SQLiteStatementInterface> delete_statement;
try {
delete_statement = this->database->new_statement(delete_component_statement);
} catch (const common::QueryExecutionException&) {
throw InitDeviceModelDbError("Could not create statement " + delete_component_statement);
}
if (!component.db_id.has_value()) {
EVLOG_error << "Can not delete component " << component.name << ": no id given";
return false;
}
delete_statement->bind_int("@component_id", static_cast<int>(component.db_id.value()));
if (delete_statement->step() != SQLITE_DONE) {
throw InitDeviceModelDbError(this->database->get_error_message());
}
return true;
}
void InitDeviceModelDb::update_component_variables(
const std::pair<ComponentKey, std::vector<DeviceModelVariable>>& db_component_variables,
const std::vector<DeviceModelVariable>& variables) {
const std::vector<DeviceModelVariable>& db_variables = db_component_variables.second;
const ComponentKey& db_component = db_component_variables.first;
if (!db_component.db_id.has_value()) {
EVLOG_error << "Can not update component " << db_component.name << ", because database id is unknown.";
return;
}
// Check for variables that do exist in the database but do not exist in the config. They should be removed.
for (const auto& db_variable : db_variables) {
auto it = std::find_if(variables.begin(), variables.end(), [&db_variable](const DeviceModelVariable& variable) {