forked from dresden-elektronik/deconz-rest-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
database.cpp
5654 lines (4919 loc) · 181 KB
/
database.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
/*
* Copyright (c) 2016-2020 dresden elektronik ingenieurtechnik gmbh.
* All rights reserved.
*
* The software in this package is published under the terms of the BSD
* style license a copy of which has been included with this distribution in
* the LICENSE.txt file.
*
*/
#include <QString>
#include <QStringBuilder>
#include <QElapsedTimer>
#include <unistd.h>
#include "de_web_plugin.h"
#include "de_web_plugin_private.h"
#include "deconz/dbg_trace.h"
#include "gateway.h"
#include "json.h"
static const char *pragmaUserVersion = "PRAGMA user_version";
static const char *pragmaPageCount = "PRAGMA page_count";
static const char *pragmaPageSize = "PRAGMA page_size";
static const char *pragmaFreeListCount = "PRAGMA freelist_count";
struct DB_Callback {
DeRestPluginPrivate *d = nullptr;
LightNode *lightNode = nullptr;
Sensor *sensorNode = nullptr;
};
/******************************************************************************
Local prototypes
******************************************************************************/
static int sqliteLoadAuthCallback(void *user, int ncols, char **colval , char **colname);
static int sqliteLoadConfigCallback(void *user, int ncols, char **colval , char **colname);
static int sqliteLoadUserparameterCallback(void *user, int ncols, char **colval , char **colname);
static int sqliteLoadLightNodeCallback(void *user, int ncols, char **colval , char **colname);
static int sqliteLoadAllGroupsCallback(void *user, int ncols, char **colval , char **colname);
static int sqliteLoadAllResourcelinksCallback(void *user, int ncols, char **colval , char **colname);
static int sqliteLoadGroupCallback(void *user, int ncols, char **colval , char **colname);
static int sqliteLoadAllScenesCallback(void *user, int ncols, char **colval , char **colname);
static int sqliteLoadSceneCallback(void *user, int ncols, char **colval , char **colname);
static int sqliteLoadAllRulesCallback(void *user, int ncols, char **colval , char **colname);
static int sqliteLoadAllSensorsCallback(void *user, int ncols, char **colval , char **colname);
static int sqliteGetAllLightIdsCallback(void *user, int ncols, char **colval , char **colname);
static int sqliteGetAllSensorIdsCallback(void *user, int ncols, char **colval , char **colname);
static int sqliteLoadAllGatewaysCallback(void *user, int ncols, char **colval , char **colname);
/******************************************************************************
Implementation
******************************************************************************/
/*! Inits the database and creates tables/columns if necessary.
*/
void DeRestPluginPrivate::initDb()
{
DBG_Assert(db != 0);
if (!db)
{
DBG_Printf(DBG_ERROR, "DB initDb() failed db not opened\n");
return;
}
DBG_Printf(DBG_INFO, "DB sqlite version %s\n", sqlite3_libversion());
int pageCount = getDbPragmaInteger(pragmaPageCount);
int pageSize = getDbPragmaInteger(pragmaPageSize);
int pageFreeListCount = getDbPragmaInteger(pragmaFreeListCount);
DBG_Printf(DBG_INFO, "DB file size %d bytes, free pages %d\n", pageCount * pageSize, pageFreeListCount);
checkDbUserVersion();
}
/*! Checks the sqlite 'user_version' in order to apply database schema updates.
Updates are applied in recursive manner to have sane upgrade paths from
certain versions in the field.
*/
void DeRestPluginPrivate::checkDbUserVersion()
{
bool updated = false;
int userVersion = getDbPragmaInteger(pragmaUserVersion); // sqlite default is 0
if (userVersion == 0) // initial and legacy databases
{
updated = upgradeDbToUserVersion1();
}
else if (userVersion == 1)
{
updated = upgradeDbToUserVersion2();
}
else if (userVersion >= 2 && userVersion <= 5 )
{
updated = upgradeDbToUserVersion6();
}
else if (userVersion == 6)
{
updated = upgradeDbToUserVersion7();
}
else if (userVersion == 7)
{
// latest version
}
else
{
DBG_Printf(DBG_INFO, "DB database file opened with a older deCONZ version\n");
}
// if something was upgraded
if (updated)
{
checkDbUserVersion();
}
else
{
cleanUpDb();
createTempViews();
}
}
/*! Cleanup tasks for database maintenance.
*/
void DeRestPluginPrivate::cleanUpDb()
{
int rc;
char *errmsg;
DBG_Printf(DBG_INFO, "DB cleanup\n");
/* Create SQL statement */
const char *sql[] = {
// cleanup invalid sensors created in version 2.05.30
"DELETE from sensors "
" WHERE modelid like 'RWL02%' "
" AND type = 'ZHAPresence'",
// cleanup invalid sensor resource for Centralite motion sensor
"DELETE FROM sensors WHERE modelid = 'Motion Sensor-A' AND uniqueid LIKE '%02-0406'",
// cleanup invalid ZHAAlarm resource for Xiaomi motion sensor
"DELETE from sensors WHERE type = 'ZHAAlarm' AND modelid LIKE 'lumi.sensor_motion%'",
// delete duplicates in device_descriptors
//"DELETE FROM device_descriptors WHERE rowid NOT IN"
//" (SELECT max(rowid) FROM device_descriptors GROUP BY device_id,type,endpoint)",
// change old default value of zcl data store, from 1 hour to disabled
"UPDATE config2 SET value = 0 WHERE key = 'zclvaluemaxage' AND value = 3600",
nullptr
};
for (int i = 0; sql[i] != nullptr; i++)
{
errmsg = nullptr;
/* Execute SQL statement */
rc = sqlite3_exec(db, sql[i], nullptr, nullptr, &errmsg);
if (rc != SQLITE_OK)
{
if (errmsg)
{
DBG_Printf(DBG_ERROR_L2, "SQL exec failed: %s, error: %s (%d)\n", sql[i], errmsg, rc);
sqlite3_free(errmsg);
}
}
}
}
/*! Creates temporary views only valid during this session.
*/
void DeRestPluginPrivate::createTempViews()
{
int rc;
char *errmsg;
DBG_Printf(DBG_INFO, "DB create temporary views\n");
/* Create SQL statement */
const char *sql[] = {
"CREATE TEMP VIEW sensor_device_view "
" AS SELECT a.sid, b.mac, b.id FROM sensors a, devices b "
" WHERE a.uniqueid like b.mac || '%'",
"CREATE TEMP VIEW sensor_device_value_view "
" AS SELECT a.sid AS sensor_id, b.cluster AS cluster_id, b.data AS data, b.timestamp AS timestamp "
" from sensor_device_view a, zcl_values b where a.id = b.device_id "
" ORDER BY timestamp ASC ",
"CREATE TEMP VIEW light_device_view "
" AS SELECT a.id as lid, b.mac, b.id FROM nodes a, devices b "
" WHERE a.mac like b.mac || '%'",
"CREATE TEMP VIEW light_device_value_view "
" AS SELECT a.lid AS light_id, b.cluster AS cluster_id, b.data AS data, b.timestamp AS timestamp "
" from light_device_view a, zcl_values b where a.id = b.device_id "
" ORDER BY timestamp ASC ",
nullptr
};
for (int i = 0; sql[i] != NULL; i++)
{
errmsg = NULL;
/* Execute SQL statement */
rc = sqlite3_exec(db, sql[i], NULL, NULL, &errmsg);
if (rc != SQLITE_OK)
{
if (errmsg)
{
DBG_Printf(DBG_ERROR_L2, "SQL exec failed: %s, error: %s (%d)\n", sql[i], errmsg, rc);
sqlite3_free(errmsg);
}
}
else
{
DBG_Printf(DBG_INFO_L2, "DB view [%d] created\n", i);
}
}
}
/*! Returns SQLite pragma parameters specified by \p sql.
*/
int DeRestPluginPrivate::getDbPragmaInteger(const char *sql)
{
int rc;
int val = -1;
sqlite3_stmt *res = NULL;
rc = sqlite3_prepare_v2(db, sql, -1, &res, 0);
DBG_Assert(rc == SQLITE_OK);
if (rc == SQLITE_OK) { rc = sqlite3_step(res); }
DBG_Assert(rc == SQLITE_ROW);
if (rc == SQLITE_ROW)
{
val = sqlite3_column_int(res, 0);
DBG_Printf(DBG_INFO, "DB %s: %d\n", sql, val);
}
DBG_Assert(res != NULL);
if (res)
{
rc = sqlite3_finalize(res);
DBG_Assert(rc == SQLITE_OK);
}
return val;
}
/*! Writes database user_version to \p userVersion. */
bool DeRestPluginPrivate::setDbUserVersion(int userVersion)
{
int rc;
char *errmsg;
DBG_Printf(DBG_INFO, "DB write sqlite user_version %d\n", userVersion);
const auto sql = QString("PRAGMA user_version = %1").arg(userVersion);
errmsg = NULL;
rc = sqlite3_exec(db, qPrintable(sql), NULL, NULL, &errmsg);
if (rc != SQLITE_OK)
{
if (errmsg)
{
DBG_Printf(DBG_ERROR_L2, "SQL exec failed: %s, error: %s (%d)\n", qPrintable(sql), errmsg, rc);
sqlite3_free(errmsg);
}
return false;
}
return true;
}
/*! Upgrades database to user_version 1. */
bool DeRestPluginPrivate::upgradeDbToUserVersion1()
{
int rc;
char *errmsg;
DBG_Printf(DBG_INFO, "DB upgrade to user_version 1\n");
// create tables
const char *sql[] = {
"CREATE TABLE IF NOT EXISTS auth (apikey TEXT PRIMARY KEY, devicetype TEXT)",
"CREATE TABLE IF NOT EXISTS userparameter (key TEXT PRIMARY KEY, value TEXT)",
"CREATE TABLE IF NOT EXISTS nodes (mac TEXT PRIMARY KEY, id TEXT, state TEXT, name TEXT, groups TEXT, endpoint TEXT, modelid TEXT, manufacturername TEXT, swbuildid TEXT)",
"CREATE TABLE IF NOT EXISTS config2 (key text PRIMARY KEY, value text)",
"ALTER TABLE nodes add column id TEXT",
"ALTER TABLE nodes add column state TEXT",
"ALTER TABLE nodes add column groups TEXT",
"ALTER TABLE nodes add column endpoint TEXT",
"ALTER TABLE nodes add column modelid TEXT",
"ALTER TABLE nodes add column manufacturername TEXT",
"ALTER TABLE nodes add column swbuildid TEXT",
"ALTER TABLE nodes add column ritems TEXT",
"ALTER TABLE auth add column createdate TEXT",
"ALTER TABLE auth add column lastusedate TEXT",
"ALTER TABLE auth add column useragent TEXT",
"CREATE TABLE IF NOT EXISTS groups (gid TEXT PRIMARY KEY, name TEXT, state TEXT, mids TEXT, devicemembership TEXT, lightsequence TEXT, hidden TEXT)",
"CREATE TABLE IF NOT EXISTS resourcelinks (id TEXT PRIMARY KEY, json TEXT)",
"CREATE TABLE IF NOT EXISTS rules (rid TEXT PRIMARY KEY, name TEXT, created TEXT, etag TEXT, lasttriggered TEXT, owner TEXT, status TEXT, timestriggered TEXT, actions TEXT, conditions TEXT, periodic TEXT)",
"CREATE TABLE IF NOT EXISTS sensors (sid TEXT PRIMARY KEY, name TEXT, type TEXT, modelid TEXT, manufacturername TEXT, uniqueid TEXT, swversion TEXT, state TEXT, config TEXT, fingerprint TEXT, deletedState TEXT, mode TEXT)",
"CREATE TABLE IF NOT EXISTS scenes (gsid TEXT PRIMARY KEY, gid TEXT, sid TEXT, name TEXT, transitiontime TEXT, lights TEXT)",
"CREATE TABLE IF NOT EXISTS schedules (id TEXT PRIMARY KEY, json TEXT)",
"CREATE TABLE IF NOT EXISTS gateways (uuid TEXT PRIMARY KEY, name TEXT, ip TEXT, port TEXT, pairing TEXT, apikey TEXT, cgroups TEXT)",
"ALTER TABLE sensors add column fingerprint TEXT",
"ALTER TABLE sensors add column deletedState TEXT",
"ALTER TABLE sensors add column mode TEXT",
"ALTER TABLE groups add column state TEXT",
"ALTER TABLE groups add column mids TEXT",
"ALTER TABLE groups add column devicemembership TEXT",
"ALTER TABLE groups add column lightsequence TEXT",
"ALTER TABLE groups add column hidden TEXT",
"ALTER TABLE groups add column type TEXT",
"ALTER TABLE groups add column class TEXT",
"ALTER TABLE groups add column uniqueid TEXT",
"ALTER TABLE scenes add column transitiontime TEXT",
"ALTER TABLE scenes add column lights TEXT",
"ALTER TABLE rules add column periodic TEXT",
"CREATE TABLE IF NOT EXISTS zbconf (conf TEXT)",
NULL
};
for (int i = 0; sql[i] != NULL; i++)
{
errmsg = NULL;
rc = sqlite3_exec(db, sql[i], NULL, NULL, &errmsg);
if (rc != SQLITE_OK)
{
if (errmsg)
{
DBG_Printf(DBG_ERROR_L2, "SQL exec failed: %s, error: %s (%d)\n", sql[i], errmsg, rc);
sqlite3_free(errmsg);
}
}
}
return setDbUserVersion(1);
}
/*! Upgrades database to user_version 2. */
bool DeRestPluginPrivate::upgradeDbToUserVersion2()
{
int rc;
char *errmsg;
DBG_Printf(DBG_INFO, "DB upgrade to user_version 2\n");
// create tables
const char *sql[] = {
"PRAGMA foreign_keys = 1",
"CREATE TABLE IF NOT EXISTS devices (id INTEGER PRIMARY KEY, mac TEXT UNIQUE, timestamp INTEGER NOT NULL)",
// zcl_values: table for logging various data
// zcl_values.data: This field can hold anything (text,integer,blob) since sqlite supports dynamic types on per value level.
"CREATE TABLE IF NOT EXISTS zcl_values (id INTEGER PRIMARY KEY, device_id INTEGER REFERENCES devices(id) ON DELETE CASCADE, endpoint INTEGER NOT NULL, cluster INTEGER NOT NULL, attribute INTEGER NOT NULL, data INTEGER NOT NULL, timestamp INTEGER NOT NULL)",
NULL
};
for (int i = 0; sql[i] != NULL; i++)
{
errmsg = NULL;
rc = sqlite3_exec(db, sql[i], NULL, NULL, &errmsg);
if (rc != SQLITE_OK)
{
if (errmsg)
{
DBG_Printf(DBG_ERROR_L2, "SQL exec failed: %s, error: %s (%d)\n", sql[i], errmsg, rc);
sqlite3_free(errmsg);
}
return false;
}
}
return setDbUserVersion(2);
}
/*! Upgrades database to user_version 6. */
bool DeRestPluginPrivate::upgradeDbToUserVersion6()
{
DBG_Printf(DBG_INFO, "DB upgrade to user_version 6\n");
// create tables
const char *sql[] = {
"DROP TABLE IF EXISTS device_gui", // development version
"ALTER TABLE devices ADD COLUMN nwk INTEGER",
// device_descriptors: cache for queried descriptors
// device_descriptors.data: This field holds the raw descriptor as blob.
"CREATE TABLE IF NOT EXISTS device_descriptors ("
" id INTEGER PRIMARY KEY,"
" device_id INTEGER REFERENCES devices(id) ON DELETE CASCADE,"
" flags INTEGER NOT NULL DEFAULT 0,"
" endpoint INTEGER NOT NULL,"
" type INTEGER NOT NULL," // ZDP cluster id which was used to query the descriptor
" data BLOB NOT NULL,"
" timestamp INTEGER NOT NULL)",
"CREATE TABLE if NOT EXISTS device_gui ("
" id INTEGER PRIMARY KEY,"
" device_id INTEGER UNIQUE,"
" flags INTEGER NOT NULL DEFAULT 0,"
" scene_x REAL NOT NULL,"
" scene_y REAL NOT NULL,"
" FOREIGN KEY(device_id) REFERENCES devices(id) ON DELETE CASCADE)",
nullptr
};
for (int i = 0; sql[i] != nullptr; i++)
{
char *errmsg = nullptr;
int rc = sqlite3_exec(db, sql[i], nullptr, nullptr, &errmsg);
if (rc != SQLITE_OK)
{
bool fatalError = true;
if (errmsg)
{
if (strstr(errmsg, "duplicate column name")) // harmless
{
fatalError = false;
}
else
{
DBG_Printf(DBG_ERROR_L2, "SQL exec failed: %s, error: %s (%d)\n", sql[i], errmsg, rc);
}
sqlite3_free(errmsg);
}
if (fatalError)
{
return false;
}
}
}
return setDbUserVersion(6);
}
/*! Upgrades database to user_version 7. */
bool DeRestPluginPrivate::upgradeDbToUserVersion7()
{
DBG_Printf(DBG_INFO, "DB upgrade to user_version 7\n");
/*
The 'source_routes' table references 'devices' so that entries are
automatically deleted if the destination node is removed.
Inserting an entry with an existing uuid will automatically replace the old row.
The 'source_route_hops' table also references 'devices' so that
entries for a hop get deleted when the respective node is removed.
In this case the source route entry still exists but the source_routes.hops
count won't match the number of source_route_hops entries anymore.
*/
// create tables
const char *sql[] = {
"CREATE TABLE IF NOT EXISTS source_routes ("
" uuid TEXT PRIMARY KEY ON CONFLICT REPLACE,"
" dest_device_id INTEGER REFERENCES devices(id) ON DELETE CASCADE,"
" route_order INTEGER NOT NULL,"
" hops INTEGER NOT NULL," // to track number of entries which should be in 'source_route_relays'
" timestamp INTEGER NOT NULL)",
"CREATE TABLE if NOT EXISTS source_route_hops ("
" source_route_uuid TEXT REFERENCES source_routes(uuid) ON DELETE CASCADE,"
" hop_device_id INTEGER REFERENCES devices(id) ON DELETE CASCADE,"
" hop INTEGER NOT NULL)",
nullptr
};
for (int i = 0; sql[i] != nullptr; i++)
{
char *errmsg = nullptr;
int rc = sqlite3_exec(db, sql[i], nullptr, nullptr, &errmsg);
if (rc != SQLITE_OK)
{
if (errmsg)
{
DBG_Printf(DBG_ERROR_L2, "SQL exec failed: %s, error: %s (%d), line: %d\n", sql[i], errmsg, rc, __LINE__);
sqlite3_free(errmsg);
}
return false;
}
}
return setDbUserVersion(7);
}
#if DECONZ_LIB_VERSION >= 0x010E00
/*! Stores a source route.
Any existing source route with the same uuid will be replaced automatically.
*/
void DeRestPluginPrivate::storeSourceRoute(const deCONZ::SourceRoute &sourceRoute)
{
DBG_Assert(sourceRoute.hops().size() > 1);
if (sourceRoute.hops().size() <= 1)
{
return; // at least two hops (incl. destination)
}
openDb();
DBG_Assert(db);
if (!db)
{
return;
}
QString sql = QString("INSERT INTO source_routes (uuid,dest_device_id,route_order,hops,timestamp)"
" SELECT '%1', (SELECT id FROM devices WHERE mac = '%2'), %3, %4, strftime('%s','now');")
.arg(sourceRoute.uuid())
.arg(generateUniqueId(sourceRoute.hops().back().ext(), 0, 0))
.arg(sourceRoute.order())
.arg(sourceRoute.hops().size());
for (size_t i = 0; i < sourceRoute.hops().size(); i++)
{
sql += QString("INSERT INTO source_route_hops (source_route_uuid, hop_device_id, hop)"
" SELECT '%1', (SELECT id FROM devices WHERE mac = '%2'), %3;")
.arg(sourceRoute.uuid())
.arg(generateUniqueId(sourceRoute.hops().at(i).ext(), 0, 0))
.arg(i);
}
char *errmsg = nullptr;
int rc = sqlite3_exec(db, sql.toUtf8().constData(), NULL, NULL, &errmsg);
if (rc != SQLITE_OK)
{
if (errmsg)
{
DBG_Printf(DBG_ERROR, "DB sqlite3_exec failed: %s, error: %s, line: %d\n", qPrintable(sql), errmsg, __LINE__);
sqlite3_free(errmsg);
}
}
closeDb();
}
/*! Deletes the source route with \p uuid. */
void DeRestPluginPrivate::deleteSourceRoute(const QString &uuid)
{
DBG_Assert(!uuid.isEmpty());
openDb();
DBG_Assert(db);
if (!db)
{
return;
}
char *errmsg = nullptr;
const auto sql = QString("DELETE FROM source_routes WHERE uuid = '%1'").arg(uuid);
int rc = sqlite3_exec(db, sql.toUtf8().constData(), NULL, NULL, &errmsg);
if (rc != SQLITE_OK)
{
if (errmsg)
{
DBG_Printf(DBG_ERROR, "DB sqlite3_exec failed: %s, error: %s, line: %d\n", qPrintable(sql), errmsg, __LINE__);
sqlite3_free(errmsg);
}
}
closeDb();
}
/*! Restores and activates all source routes in core. */
void DeRestPluginPrivate::restoreSourceRoutes()
{
openDb();
DBG_Assert(db);
if (!db)
{
return;
}
const auto loadSourceRoutesCallback = [](void *user, int ncols, char **colval , char **) -> int
{
auto *sourceRoutes = static_cast<std::vector<deCONZ::SourceRoute>*>(user);
DBG_Assert(sourceRoutes);
DBG_Assert(ncols == 3);
// TODO verify number of hops in colval[2]
sourceRoutes->push_back(deCONZ::SourceRoute(colval[0], QString(colval[1]).toInt(), {}));
return 0;
};
char *errmsg = nullptr;
std::vector<deCONZ::SourceRoute> sourceRoutes;
const char *sql = "SELECT uuid, route_order, hops FROM source_routes";
int rc = sqlite3_exec(db, sql, loadSourceRoutesCallback, &sourceRoutes, &errmsg);
if (rc != SQLITE_OK)
{
if (errmsg)
{
DBG_Printf(DBG_ERROR, "sqlite3_exec %s, error: %s, line: %d\n", qPrintable(sql), errmsg, __LINE__);
sqlite3_free(errmsg);
errmsg = nullptr;
}
}
const auto loadHopsCallback = [](void *user, int ncols, char **colval , char **) -> int
{
auto *hops = static_cast<std::vector<deCONZ::Address>*>(user);
DBG_Assert(hops);
DBG_Assert(ncols == 2);
const auto mac = QString("0x%1").arg(colval[0]).remove(':');
// TODO make use of 'hop' in colval[1]
bool ok = false;
deCONZ::Address addr;
addr.setExt(static_cast<uint64_t>(mac.toULongLong(&ok, 16)));
if (ok)
{
hops->push_back(addr);
}
return 0;
};
for (auto &sr : sourceRoutes)
{
std::vector<deCONZ::Address> hops;
const auto sql = QString("SELECT mac, hop FROM source_route_hops INNER JOIN devices WHERE hop_device_id = devices.id AND source_route_uuid = '%1';").arg(sr.uuid());
rc = sqlite3_exec(db, qPrintable(sql), loadHopsCallback, &hops, &errmsg);
if (rc != SQLITE_OK)
{
if (errmsg)
{
DBG_Printf(DBG_ERROR, "sqlite3_exec %s, error: %s, line: %d\n", qPrintable(sql), errmsg, __LINE__);
sqlite3_free(errmsg);
errmsg = nullptr;
}
}
else if (apsCtrl && hops.size() > 1) // at least two items
{
apsCtrl->activateSourceRoute(deCONZ::SourceRoute(sr.uuid(), sr.order(), hops));
}
}
closeDb();
}
#endif // DECONZ_LIB_VERSION >= 0x010E00
/*! Puts a new top level device entry in the db (mac address) or refreshes nwk address.
*/
void DeRestPluginPrivate::refreshDeviceDb(const deCONZ::Address &addr)
{
if (!addr.hasExt() || !addr.hasNwk())
{
return;
}
QString sql = QString(QLatin1String(
"UPDATE devices SET nwk = %2 WHERE mac = '%1';"
"INSERT INTO devices (mac,nwk,timestamp) SELECT '%1', %2, strftime('%s','now') WHERE (SELECT changes() = 0);"))
.arg(generateUniqueId(addr.ext(), 0, 0)).arg(addr.nwk());
dbQueryQueue.push_back(sql);
queSaveDb(DB_QUERY_QUEUE, DB_SHORT_SAVE_DELAY);
}
/*! Push/update a zdp descriptor in the database to cache node data.
*/
void DeRestPluginPrivate::pushZdpDescriptorDb(quint64 extAddress, quint8 endpoint, quint16 type, const QByteArray &data)
{
DBG_Printf(DBG_INFO_L2, "DB pushZdpDescriptorDb()\n");
openDb();
DBG_Assert(db);
if (!db)
{
return;
}
// store now to make sure 'devices' table is populated
if (!dbQueryQueue.empty())
{
saveDb();
}
qint64 now = QDateTime::currentMSecsSinceEpoch() / 1000;
const QString uniqueid = generateUniqueId(extAddress, 0, 0);
char mac[23 + 1];
strncpy(mac, qPrintable(uniqueid), uniqueid.size());
mac[23] = '\0';
// 0) check if exists
int rc;
sqlite3_stmt *res = nullptr;
const char * sql = "SELECT COUNT(*) FROM device_descriptors"
" WHERE device_id = (SELECT id FROM devices WHERE mac = ?1)"
" AND endpoint = ?2"
" AND type = ?3"
" AND data = ?4";
rc = sqlite3_prepare_v2(db, sql, -1, &res, nullptr);
DBG_Assert(res);
DBG_Assert(rc == SQLITE_OK);
if (rc == SQLITE_OK)
{
rc = sqlite3_bind_text(res, 1, mac, -1, SQLITE_STATIC);
DBG_Assert(rc == SQLITE_OK);
}
if (rc == SQLITE_OK)
{
rc = sqlite3_bind_int(res, 2, endpoint);
DBG_Assert(rc == SQLITE_OK);
}
if (rc == SQLITE_OK)
{
rc = sqlite3_bind_int(res, 3, type);
DBG_Assert(rc == SQLITE_OK);
}
if (rc == SQLITE_OK)
{
rc = sqlite3_bind_blob(res, 4, data.constData(), data.size(), SQLITE_STATIC);
DBG_Assert(rc == SQLITE_OK);
}
int rows = -1;
if (rc == SQLITE_OK)
{
rc = sqlite3_step(res);
DBG_Assert(rc == SQLITE_ROW);
if (rc == SQLITE_ROW)
{
rows = sqlite3_column_int(res, 0);
}
}
rc = sqlite3_finalize(res);
DBG_Assert(rc == SQLITE_OK);
if (rows != 0) // error or already existing
{
return;
}
// 1) if exist, try to update existing entry
sql = "UPDATE device_descriptors SET data = ?1, timestamp = ?2"
" WHERE device_id = (SELECT id FROM devices WHERE mac = ?3)"
" AND endpoint = ?4"
" AND type = ?5";
rc = sqlite3_prepare_v2(db, sql, -1, &res, nullptr);
DBG_Assert(res);
DBG_Assert(rc == SQLITE_OK);
if (rc == SQLITE_OK)
{
rc = sqlite3_bind_blob(res, 1, data.constData(), data.size(), SQLITE_STATIC);
DBG_Assert(rc == SQLITE_OK);
}
if (rc == SQLITE_OK)
{
rc = sqlite3_bind_int64(res, 2, now);
DBG_Assert(rc == SQLITE_OK);
}
if (rc == SQLITE_OK)
{
rc = sqlite3_bind_text(res, 3, mac, -1, SQLITE_STATIC);
DBG_Assert(rc == SQLITE_OK);
}
if (rc == SQLITE_OK)
{
rc = sqlite3_bind_int(res, 4, endpoint);
DBG_Assert(rc == SQLITE_OK);
}
if (rc == SQLITE_OK)
{
rc = sqlite3_bind_int(res, 5, type);
DBG_Assert(rc == SQLITE_OK);
}
if (rc != SQLITE_OK)
{
DBG_Printf(DBG_INFO, "DB failed %s\n", sqlite3_errmsg(db));
if (res)
{
rc = sqlite3_finalize(res);
DBG_Assert(rc == SQLITE_OK);
}
return;
}
#if SQLITE_VERSION_NUMBER > 3014000
auto exp = sqlite3_expanded_sql(res);
if (exp)
{
DBG_Printf(DBG_INFO, "DB %s\n", exp);
sqlite3_free(exp);
}
#endif
int changes = -1;
rc = sqlite3_step(res);
if (rc == SQLITE_DONE)
{
changes = sqlite3_changes(db);
}
DBG_Assert(rc == SQLITE_DONE);
rc = sqlite3_finalize(res);
DBG_Assert(rc == SQLITE_OK);
if (rc != SQLITE_OK)
{
return;
}
if (changes == 1)
{
return; // done updating already existing entry
}
// 2) no existing entry, insert new entry
res = nullptr;
sql = "INSERT INTO device_descriptors (device_id, endpoint, type, data, timestamp)"
" SELECT id, ?1, ?2, ?3, ?4"
" FROM devices WHERE mac = ?5";
rc = sqlite3_prepare_v2(db, sql, -1, &res, nullptr);
DBG_Assert(res);
DBG_Assert(rc == SQLITE_OK);
if (rc == SQLITE_OK)
{
rc = sqlite3_bind_int(res, 1, endpoint);
DBG_Assert(rc == SQLITE_OK);
}
if (rc == SQLITE_OK)
{
rc = sqlite3_bind_int(res, 2, type);
DBG_Assert(rc == SQLITE_OK);
}
if (rc == SQLITE_OK)
{
rc = sqlite3_bind_blob(res, 3, data.constData(), data.size(), SQLITE_STATIC);
DBG_Assert(rc == SQLITE_OK);
}
if (rc == SQLITE_OK)
{
rc = sqlite3_bind_int64(res, 4, now);
DBG_Assert(rc == SQLITE_OK);
}
if (rc == SQLITE_OK)
{
rc = sqlite3_bind_text(res, 5, mac, -1, SQLITE_STATIC);
DBG_Assert(rc == SQLITE_OK);
}
if (rc != SQLITE_OK)
{
DBG_Printf(DBG_INFO, "DB failed %s\n", sqlite3_errmsg(db));
if (res)
{
rc = sqlite3_finalize(res);
DBG_Assert(rc == SQLITE_OK);
}
return;
}
#if SQLITE_VERSION_NUMBER > 3014000
exp = sqlite3_expanded_sql(res);
if (exp)
{
DBG_Printf(DBG_INFO, "DB %s\n", exp);
sqlite3_free(exp);
}
#endif
rc = sqlite3_step(res);
if (rc == SQLITE_DONE)
{
changes = sqlite3_changes(db);
DBG_Assert(changes == 1);
}
rc = sqlite3_finalize(res);
DBG_Assert(rc == SQLITE_OK);
closeDb();
}
/*! Push a zcl value sample in the database to keep track of value history.
The data might be a sensor reading or light state or any ZCL value.
*/
void DeRestPluginPrivate::pushZclValueDb(quint64 extAddress, quint8 endpoint, quint16 clusterId, quint16 attributeId, qint64 data)
{
if (dbZclValueMaxAge <= 0)
{
return; // zcl value datastore disabled
}
/*
select mac, printf('0x%04X', cluster), data, datetime(zcl_values.timestamp,'unixepoch','localtime')
from zcl_values inner join devices ON zcl_values.device_id = devices.id
where zcl_values.timestamp > strftime('%s','now') - 300;
*/
qint64 now = QDateTime::currentMSecsSinceEpoch() / 1000;
QString sql = QString(QLatin1String(
"INSERT INTO zcl_values (device_id,endpoint,cluster,attribute,data,timestamp) "
"SELECT id, %2, %3, %4, %5, %6 "
"FROM devices WHERE mac = '%1'"))
.arg(generateUniqueId(extAddress, 0, 0))
.arg(endpoint)
.arg(clusterId)
.arg(attributeId)
.arg(data)
.arg(now);
dbQueryQueue.push_back(sql);
queSaveDb(DB_QUERY_QUEUE, (dbQueryQueue.size() > 30) ? DB_SHORT_SAVE_DELAY : DB_LONG_SAVE_DELAY);
// add a cleanup command if not already queued
for (const QString &q : dbQueryQueue)
{
if (q.startsWith(QLatin1String("DELETE FROM zcl_values")))
{
return; // already queued
}
}
sql = QString(QLatin1String("DELETE FROM zcl_values WHERE timestamp < %1")).arg(now - dbZclValueMaxAge);
dbQueryQueue.push_back(sql);
}
/*! Opens/creates sqlite database.
*/
void DeRestPluginPrivate::openDb()
{
//DBG_Assert(db == 0);
if (db)
{
ttlDataBaseConnection = idleTotalCounter + DB_CONNECTION_TTL;
return;
}
int rc = sqlite3_open(qPrintable(sqliteDatabaseName), &db);
if (rc != SQLITE_OK) {
// failed
DBG_Printf(DBG_ERROR, "Can't open database: %s\n", sqlite3_errmsg(db));
db = 0;
return;
}
const char *sql = "PRAGMA foreign_keys = ON"; // must be enabled at runtime for each connection
rc = sqlite3_exec(db, sql, nullptr, nullptr, nullptr);
DBG_Assert(rc == SQLITE_OK);
ttlDataBaseConnection = idleTotalCounter + DB_CONNECTION_TTL;
}
/*! Reads all data sets from sqlite database.
*/
void DeRestPluginPrivate::readDb()
{
DBG_Assert(db != 0);
if (!db)
{
return;
}
loadAuthFromDb();
loadConfigFromDb();
loadUserparameterFromDb();
loadAllGroupsFromDb();
loadAllResourcelinksFromDb();
loadAllScenesFromDb();
loadAllRulesFromDb();
loadAllSchedulesFromDb();
loadAllSensorsFromDb();