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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
//! Background worker for BLE sensor operations.
//!
//! This module contains the [`SensorWorker`] which handles all Bluetooth Low Energy
//! operations in a background task, keeping the UI thread responsive. The worker
//! communicates with the UI thread via channels:
//!
//! - Receives [`Command`]s from the UI to perform operations
//! - Sends [`SensorEvent`]s back to report results and status updates
//!
//! # Architecture
//!
//! The worker runs in a separate Tokio task and uses `tokio::select!` to handle:
//! - Incoming commands from the UI
//! - Periodic auto-refresh of sensor readings (when enabled)
//!
//! All BLE operations are performed here to avoid blocking the UI rendering loop.
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::Arc;
use std::time::Duration;
/// Disconnect from a device, logging any errors at debug level.
async fn disconnect_quietly(device: &aranet_core::Device) {
if let Err(e) = device.disconnect().await {
tracing::debug!("Failed to disconnect device: {e}");
}
}
use aranet_core::device::{ConnectionConfig, SignalQuality};
use aranet_core::messages::{ErrorContext, ServiceDeviceStats};
use aranet_core::service_client::ServiceClient;
use aranet_core::settings::{DeviceSettings, MeasurementInterval};
use aranet_core::{
BluetoothRange, Device, RetryConfig, ScanOptions, scan::scan_with_options, with_retry,
};
use aranet_store::Store;
use aranet_types::{CurrentReading, DeviceType};
use tokio::sync::{RwLock, mpsc};
use tokio::time::interval;
use tokio_util::sync::CancellationToken;
use tracing::{debug, error, info, warn};
use super::messages::{CachedDevice, Command, SensorEvent};
/// Background worker that handles BLE operations.
///
/// The worker receives commands from the UI thread and performs
/// Bluetooth operations asynchronously, sending events back to
/// update the UI state.
///
/// Note: The Store is not held directly because rusqlite's Connection
/// is not Send+Sync. Instead, we store the path and open the store
/// when needed.
pub struct SensorWorker {
/// Receiver for commands from the UI thread.
command_rx: mpsc::Receiver<Command>,
/// Sender for events back to the UI thread.
event_tx: mpsc::Sender<SensorEvent>,
/// Path to persistent storage.
store_path: PathBuf,
/// Service client for aranet-service communication.
service_client: Option<ServiceClient>,
/// Connection configuration (platform-optimized timeouts).
connection_config: ConnectionConfig,
/// Background polling tasks indexed by device_id.
/// Each entry holds a cancel token that can be used to stop the polling task.
background_polling: Arc<RwLock<HashMap<String, tokio::sync::watch::Sender<bool>>>>,
/// Last known signal quality per device (for adaptive behavior).
signal_quality_cache: Arc<RwLock<HashMap<String, SignalQuality>>>,
/// Cancellation token for long-running operations.
/// Used to cancel scans, connections, and history syncs.
cancel_token: CancellationToken,
}
/// Default URL for the aranet-service.
const DEFAULT_SERVICE_URL: &str = "http://localhost:8080";
impl SensorWorker {
/// Create a new sensor worker.
///
/// # Arguments
///
/// * `command_rx` - Channel receiver for commands from the UI
/// * `event_tx` - Channel sender for events to the UI
/// * `store_path` - Path to persistent storage
pub fn new(
command_rx: mpsc::Receiver<Command>,
event_tx: mpsc::Sender<SensorEvent>,
store_path: PathBuf,
) -> Self {
Self::with_service_config(command_rx, event_tx, store_path, DEFAULT_SERVICE_URL, None)
}
/// Create a new sensor worker with custom service authentication settings.
pub fn with_service_config(
command_rx: mpsc::Receiver<Command>,
event_tx: mpsc::Sender<SensorEvent>,
store_path: PathBuf,
service_url: &str,
service_api_key: Option<String>,
) -> Self {
// Try to create service client with default URL
let service_client = ServiceClient::new_with_api_key(service_url, service_api_key).ok();
// Use platform-optimized connection configuration
let connection_config = ConnectionConfig::for_current_platform();
info!(
?connection_config,
"Using platform-optimized connection config"
);
Self {
command_rx,
event_tx,
store_path,
service_client,
connection_config,
background_polling: Arc::new(RwLock::new(HashMap::new())),
signal_quality_cache: Arc::new(RwLock::new(HashMap::new())),
cancel_token: CancellationToken::new(),
}
}
/// Open the store, logging a warning on failure.
///
/// This helper centralizes store access and error handling.
fn open_store(&self) -> Option<Store> {
match Store::open(&self.store_path) {
Ok(store) => Some(store),
Err(e) => {
warn!(error = %e, "Failed to open store");
None
}
}
}
/// Run the worker's main loop.
///
/// This method consumes the worker and runs until a [`Command::Shutdown`]
/// is received or the command channel is closed.
pub async fn run(mut self) {
info!("SensorWorker started");
loop {
tokio::select! {
// Handle incoming commands
cmd = self.command_rx.recv() => {
match cmd {
Some(Command::Shutdown) => {
info!("SensorWorker received shutdown command");
break;
}
Some(cmd) => {
self.handle_command(cmd).await;
}
None => {
info!("Command channel closed, shutting down worker");
break;
}
}
}
}
}
info!("SensorWorker stopped");
}
/// Handle a single command from the UI.
async fn handle_command(&mut self, cmd: Command) {
info!(?cmd, "Handling command");
match cmd {
Command::LoadCachedData => {
self.handle_load_cached_data().await;
}
Command::Scan { duration } => {
self.handle_scan(duration).await;
}
Command::Connect { device_id } => {
self.handle_connect(&device_id).await;
}
Command::Disconnect { device_id } => {
self.handle_disconnect(&device_id).await;
}
Command::RefreshReading { device_id } => {
self.handle_refresh_reading(&device_id).await;
}
Command::RefreshAll => {
self.handle_refresh_all().await;
}
Command::SyncHistory { device_id } => {
self.handle_sync_history(&device_id).await;
}
Command::SetInterval {
device_id,
interval_secs,
} => {
self.handle_set_interval(&device_id, interval_secs).await;
}
Command::SetBluetoothRange {
device_id,
extended,
} => {
self.handle_set_bluetooth_range(&device_id, extended).await;
}
Command::SetSmartHome { device_id, enabled } => {
self.handle_set_smart_home(&device_id, enabled).await;
}
Command::RefreshServiceStatus => {
self.handle_refresh_service_status().await;
}
Command::StartServiceCollector => {
self.handle_start_service_collector().await;
}
Command::StopServiceCollector => {
self.handle_stop_service_collector().await;
}
Command::SetAlias { device_id, alias } => {
self.handle_set_alias(&device_id, alias).await;
}
Command::ForgetDevice { device_id } => {
self.handle_forget_device(&device_id).await;
}
Command::CancelOperation => {
self.handle_cancel_operation().await;
}
Command::StartBackgroundPolling {
device_id,
interval_secs,
} => {
self.handle_start_background_polling(&device_id, interval_secs)
.await;
}
Command::StopBackgroundPolling { device_id } => {
self.handle_stop_background_polling(&device_id).await;
}
Command::Shutdown => {
// Handled in run() loop
}
// System service commands not supported in TUI
Command::InstallSystemService { .. }
| Command::UninstallSystemService { .. }
| Command::StartSystemService { .. }
| Command::StopSystemService { .. }
| Command::CheckSystemServiceStatus { .. }
| Command::FetchServiceConfig
| Command::AddServiceDevice { .. }
| Command::UpdateServiceDevice { .. }
| Command::RemoveServiceDevice { .. } => {
info!("System service commands not supported in TUI");
}
}
}
/// Load cached devices and readings from the store.
async fn handle_load_cached_data(&self) {
info!("Loading cached data from store");
let Some(store) = self.open_store() else {
// Send empty cached data
let _ = self
.event_tx
.send(SensorEvent::CachedDataLoaded { devices: vec![] })
.await;
return;
};
// Load all known devices
let stored_devices = match store.list_devices() {
Ok(devices) => devices,
Err(e) => {
warn!("Failed to list devices: {}", e);
let _ = self
.event_tx
.send(SensorEvent::CachedDataLoaded { devices: vec![] })
.await;
return;
}
};
// Load latest reading for each device
let mut cached_devices = Vec::new();
for stored in stored_devices {
let reading = match store.get_latest_reading(&stored.id) {
Ok(Some(stored_reading)) => Some(stored_reading.to_reading()),
Ok(None) => None,
Err(e) => {
debug!("Failed to get latest reading for {}: {}", stored.id, e);
None
}
};
// Get sync state for last sync time
let last_sync = match store.get_sync_state(&stored.id) {
Ok(Some(state)) => state.last_sync_at,
Ok(None) => None,
Err(e) => {
debug!("Failed to get sync state for {}: {}", stored.id, e);
None
}
};
cached_devices.push(CachedDevice {
id: stored.id,
name: stored.name,
device_type: stored.device_type,
reading,
last_sync,
});
}
info!(count = cached_devices.len(), "Loaded cached devices");
// Collect device IDs before sending (we need them for history loading)
let device_ids: Vec<String> = cached_devices.iter().map(|d| d.id.clone()).collect();
if let Err(e) = self
.event_tx
.send(SensorEvent::CachedDataLoaded {
devices: cached_devices,
})
.await
{
error!("Failed to send CachedDataLoaded event: {}", e);
}
// Load history for each cached device (for sparklines on startup)
for device_id in device_ids {
self.load_and_send_history(&device_id).await;
}
}
/// Handle a scan command.
async fn handle_scan(&self, duration: Duration) {
info!(?duration, "Starting device scan");
// Notify UI that scan has started
if let Err(e) = self.event_tx.send(SensorEvent::ScanStarted).await {
error!("Failed to send ScanStarted event: {}", e);
return;
}
// Clone the cancel token for this operation
let cancel_token = self.cancel_token.clone();
// Perform the scan with cancellation support
let options = ScanOptions::default().duration(duration);
let scan_result = tokio::select! {
result = scan_with_options(options) => result,
_ = cancel_token.cancelled() => {
info!("Scan cancelled by user");
let _ = self
.event_tx
.send(SensorEvent::OperationCancelled {
operation: "Device scan".to_string(),
})
.await;
return;
}
};
match scan_result {
Ok(devices) => {
info!(count = devices.len(), "Scan complete");
// Save discovered devices to store
self.save_discovered_devices(&devices);
if let Err(e) = self
.event_tx
.send(SensorEvent::ScanComplete { devices })
.await
{
error!("Failed to send ScanComplete event: {}", e);
}
}
Err(e) => {
error!("Scan failed: {}", e);
if let Err(send_err) = self
.event_tx
.send(SensorEvent::ScanError {
error: e.to_string(),
})
.await
{
error!("Failed to send ScanError event: {}", send_err);
}
}
}
}
/// Handle a connect command with retry logic and error context.
async fn handle_connect(&self, device_id: &str) {
info!(device_id, "Connecting to device");
// Notify UI that we're connecting
if let Err(e) = self
.event_tx
.send(SensorEvent::DeviceConnecting {
device_id: device_id.to_string(),
})
.await
{
error!("Failed to send DeviceConnecting event: {}", e);
return;
}
// Clone the cancel token for this operation
let cancel_token = self.cancel_token.clone();
// Use retry logic for connection (connection can fail due to timing, signal, etc.)
let retry_config = RetryConfig::for_connect();
let device_id_owned = device_id.to_string();
let config = self.connection_config.clone();
let connect_future = with_retry(&retry_config, "connect_and_read", || {
let device_id = device_id_owned.clone();
let config = config.clone();
async move { Self::connect_and_read_with_config(&device_id, config).await }
});
// Wrap in select for cancellation support
let result = tokio::select! {
result = connect_future => result,
_ = cancel_token.cancelled() => {
info!(device_id, "Connection cancelled by user");
let _ = self
.event_tx
.send(SensorEvent::OperationCancelled {
operation: format!("Connect to {}", device_id),
})
.await;
return;
}
};
match result {
Ok((name, device_type, reading, settings, rssi, signal_quality)) => {
info!(
device_id,
?name,
?device_type,
?rssi,
?signal_quality,
"Device connected"
);
// Cache signal quality for adaptive behavior
if let Some(quality) = signal_quality {
self.signal_quality_cache
.write()
.await
.insert(device_id.to_string(), quality);
// Send signal strength update
if let Some(rssi_val) = rssi {
let _ = self
.event_tx
.send(SensorEvent::SignalStrengthUpdate {
device_id: device_id.to_string(),
rssi: rssi_val,
quality: aranet_core::messages::SignalQuality::from_rssi(rssi_val),
})
.await;
}
// Warn about poor signal quality
if quality == SignalQuality::Poor {
warn!(
device_id,
"Poor signal quality - connection may be unstable"
);
}
}
// Update device metadata in store
self.update_device_metadata(device_id, name.as_deref(), device_type);
// Send connected event
if let Err(e) = self
.event_tx
.send(SensorEvent::DeviceConnected {
device_id: device_id.to_string(),
name,
device_type,
rssi,
})
.await
{
error!("Failed to send DeviceConnected event: {}", e);
}
// Send settings if we got them
if let Some(settings) = settings
&& let Err(e) = self
.event_tx
.send(SensorEvent::SettingsLoaded {
device_id: device_id.to_string(),
settings,
})
.await
{
error!("Failed to send SettingsLoaded event: {}", e);
}
// Send reading if we got one and save to store
if let Some(reading) = reading {
// Save to store
self.save_reading(device_id, &reading);
if let Err(e) = self
.event_tx
.send(SensorEvent::ReadingUpdated {
device_id: device_id.to_string(),
reading,
})
.await
{
error!("Failed to send ReadingUpdated event: {}", e);
}
}
// Load history for sparklines
self.load_and_send_history(device_id).await;
}
Err(e) => {
error!(device_id, error = %e, "Failed to connect to device after retries");
// Populate error context with user-friendly information
let context = ErrorContext::from_error(&e);
if let Err(send_err) = self
.event_tx
.send(SensorEvent::ConnectionError {
device_id: device_id.to_string(),
error: e.to_string(),
context: Some(context),
})
.await
{
error!("Failed to send ConnectionError event: {}", send_err);
}
}
}
}
/// Handle a disconnect command.
///
/// For TUI purposes, disconnection mostly means updating UI state since
/// we don't maintain persistent connections (we connect, read, and disconnect).
/// This sends a DeviceDisconnected event to update the UI.
async fn handle_disconnect(&self, device_id: &str) {
info!(device_id, "Disconnecting device");
// Send disconnected event to update UI state
if let Err(e) = self
.event_tx
.send(SensorEvent::DeviceDisconnected {
device_id: device_id.to_string(),
})
.await
{
error!("Failed to send DeviceDisconnected event: {}", e);
}
}
/// Handle a refresh reading command with retry logic and adaptive timing.
async fn handle_refresh_reading(&self, device_id: &str) {
info!(device_id, "Refreshing reading for device");
// Get cached signal quality for adaptive retry configuration
let signal_quality = self
.signal_quality_cache
.read()
.await
.get(device_id)
.copied();
// Use more aggressive retries for devices with known poor signal
let retry_config = match signal_quality {
Some(SignalQuality::Poor) | Some(SignalQuality::Fair) => {
debug!(
device_id,
?signal_quality,
"Using aggressive retry config for weak signal"
);
RetryConfig::aggressive()
}
_ => RetryConfig::for_read(),
};
let device_id_owned = device_id.to_string();
let config = self.connection_config.clone();
let result = with_retry(&retry_config, "refresh_reading", || {
let device_id = device_id_owned.clone();
let config = config.clone();
async move { Self::connect_and_read_with_config(&device_id, config).await }
})
.await;
match result {
Ok((_, _, reading, settings, rssi, new_signal_quality)) => {
// Update cached signal quality
if let Some(quality) = new_signal_quality {
self.signal_quality_cache
.write()
.await
.insert(device_id.to_string(), quality);
}
// Send signal strength update if available
if let Some(rssi_val) = rssi {
let _ = self
.event_tx
.send(SensorEvent::SignalStrengthUpdate {
device_id: device_id.to_string(),
rssi: rssi_val,
quality: aranet_core::messages::SignalQuality::from_rssi(rssi_val),
})
.await;
}
// Send settings if we got them
if let Some(settings) = settings
&& let Err(e) = self
.event_tx
.send(SensorEvent::SettingsLoaded {
device_id: device_id.to_string(),
settings,
})
.await
{
error!("Failed to send SettingsLoaded event: {}", e);
}
if let Some(reading) = reading {
info!(device_id, "Reading refreshed successfully");
// Save to store
self.save_reading(device_id, &reading);
if let Err(e) = self
.event_tx
.send(SensorEvent::ReadingUpdated {
device_id: device_id.to_string(),
reading,
})
.await
{
error!("Failed to send ReadingUpdated event: {}", e);
}
} else {
warn!(device_id, "Connected but failed to read current values");
let context = ErrorContext::transient(
"Failed to read current values",
"Device connected but returned no data. Try again.",
);
if let Err(e) = self
.event_tx
.send(SensorEvent::ReadingError {
device_id: device_id.to_string(),
error: "Failed to read current values".to_string(),
context: Some(context),
})
.await
{
error!("Failed to send ReadingError event: {}", e);
}
}
}
Err(e) => {
error!(device_id, error = %e, "Failed to refresh reading after retries");
let context = ErrorContext::from_error(&e);
if let Err(send_err) = self
.event_tx
.send(SensorEvent::ReadingError {
device_id: device_id.to_string(),
error: e.to_string(),
context: Some(context),
})
.await
{
error!("Failed to send ReadingError event: {}", send_err);
}
}
}
}
/// Handle a refresh all command.
///
/// Refreshes readings from all known devices by iterating through
/// and calling handle_refresh_reading for each device.
async fn handle_refresh_all(&self) {
info!("Refreshing all devices");
// Open store to get list of known devices
let Some(store) = self.open_store() else {
return;
};
let devices = match store.list_devices() {
Ok(devices) => devices,
Err(e) => {
warn!("Failed to list devices for refresh all: {}", e);
return;
}
};
// Refresh each device
for device in devices {
self.handle_refresh_reading(&device.id).await;
}
info!("Completed refreshing all devices");
}
/// Handle a set interval command with retry logic and error context.
///
/// Connects to the device, sets the measurement interval, and sends
/// the appropriate event back to the UI.
async fn handle_set_interval(&self, device_id: &str, interval_secs: u16) {
info!(device_id, interval_secs, "Setting measurement interval");
// Validate and convert seconds to MeasurementInterval
let interval = match MeasurementInterval::from_seconds(interval_secs) {
Some(i) => i,
None => {
let error = format!(
"Invalid interval: {} seconds. Must be 60, 120, 300, or 600.",
interval_secs
);
error!(device_id, %error, "Invalid interval value");
let context = ErrorContext::permanent(&error);
let _ = self
.event_tx
.send(SensorEvent::IntervalError {
device_id: device_id.to_string(),
error,
context: Some(context),
})
.await;
return;
}
};
// Connect to the device with retry
let retry_config = RetryConfig::for_connect();
let device_id_owned = device_id.to_string();
let config = self.connection_config.clone();
let device = match with_retry(&retry_config, "connect_for_interval", || {
let device_id = device_id_owned.clone();
let config = config.clone();
async move { Device::connect_with_config(&device_id, config).await }
})
.await
{
Ok(d) => d,
Err(e) => {
error!(device_id, error = %e, "Failed to connect for set interval");
let context = ErrorContext::from_error(&e);
let _ = self
.event_tx
.send(SensorEvent::IntervalError {
device_id: device_id.to_string(),
error: e.to_string(),
context: Some(context),
})
.await;
return;
}
};
// Set the interval with retry
let retry_config = RetryConfig::for_write();
if let Err(e) = with_retry(&retry_config, "set_interval", || async {
device.set_interval(interval).await
})
.await
{
error!(device_id, error = %e, "Failed to set interval");
disconnect_quietly(&device).await;
let context = ErrorContext::from_error(&e);
let _ = self
.event_tx
.send(SensorEvent::IntervalError {
device_id: device_id.to_string(),
error: e.to_string(),
context: Some(context),
})
.await;
return;
}
// Disconnect from device
disconnect_quietly(&device).await;
info!(
device_id,
interval_secs, "Measurement interval set successfully"
);
// Send success event
if let Err(e) = self
.event_tx
.send(SensorEvent::IntervalChanged {
device_id: device_id.to_string(),
interval_secs,
})
.await
{
error!("Failed to send IntervalChanged event: {}", e);
}
}
/// Handle a set bluetooth range command with retry logic and error context.
async fn handle_set_bluetooth_range(&self, device_id: &str, extended: bool) {
let range_name = if extended { "Extended" } else { "Standard" };
info!(device_id, range_name, "Setting Bluetooth range");
// Connect to the device with retry
let retry_config = RetryConfig::for_connect();
let device_id_owned = device_id.to_string();
let config = self.connection_config.clone();
let device = match with_retry(&retry_config, "connect_for_bt_range", || {
let device_id = device_id_owned.clone();
let config = config.clone();
async move { Device::connect_with_config(&device_id, config).await }
})
.await
{
Ok(d) => d,
Err(e) => {
error!(device_id, error = %e, "Failed to connect for set Bluetooth range");
let context = ErrorContext::from_error(&e);
let _ = self
.event_tx
.send(SensorEvent::BluetoothRangeError {
device_id: device_id.to_string(),
error: e.to_string(),
context: Some(context),
})
.await;
return;
}
};
// Set the Bluetooth range
let range = if extended {
BluetoothRange::Extended
} else {
BluetoothRange::Standard
};
// Set range with retry
let retry_config = RetryConfig::for_write();
if let Err(e) = with_retry(&retry_config, "set_bt_range", || async {
device.set_bluetooth_range(range).await
})
.await
{
error!(device_id, error = %e, "Failed to set Bluetooth range");
disconnect_quietly(&device).await;
let context = ErrorContext::from_error(&e);
let _ = self
.event_tx
.send(SensorEvent::BluetoothRangeError {
device_id: device_id.to_string(),
error: e.to_string(),
context: Some(context),
})
.await;
return;
}
// Disconnect from device
disconnect_quietly(&device).await;
info!(device_id, range_name, "Bluetooth range set successfully");
// Send success event
if let Err(e) = self
.event_tx
.send(SensorEvent::BluetoothRangeChanged {
device_id: device_id.to_string(),
extended,
})
.await
{
error!("Failed to send BluetoothRangeChanged event: {}", e);
}
}
/// Handle a set smart home command with retry logic and error context.
async fn handle_set_smart_home(&self, device_id: &str, enabled: bool) {
let mode = if enabled { "enabled" } else { "disabled" };
info!(device_id, mode, "Setting Smart Home");
// Connect to the device with retry
let retry_config = RetryConfig::for_connect();
let device_id_owned = device_id.to_string();
let config = self.connection_config.clone();
let device = match with_retry(&retry_config, "connect_for_smart_home", || {
let device_id = device_id_owned.clone();
let config = config.clone();
async move { Device::connect_with_config(&device_id, config).await }
})
.await
{
Ok(d) => d,
Err(e) => {
error!(device_id, error = %e, "Failed to connect for set Smart Home");
let context = ErrorContext::from_error(&e);
let _ = self
.event_tx
.send(SensorEvent::SmartHomeError {
device_id: device_id.to_string(),
error: e.to_string(),
context: Some(context),
})
.await;
return;
}
};
// Set Smart Home mode with retry
let retry_config = RetryConfig::for_write();
if let Err(e) = with_retry(&retry_config, "set_smart_home", || async {
device.set_smart_home(enabled).await
})
.await
{
error!(device_id, error = %e, "Failed to set Smart Home");
disconnect_quietly(&device).await;
let context = ErrorContext::from_error(&e);
let _ = self
.event_tx
.send(SensorEvent::SmartHomeError {
device_id: device_id.to_string(),
error: e.to_string(),
context: Some(context),
})
.await;
return;
}
// Disconnect from device
disconnect_quietly(&device).await;
info!(device_id, mode, "Smart Home set successfully");
// Send success event
if let Err(e) = self
.event_tx
.send(SensorEvent::SmartHomeChanged {
device_id: device_id.to_string(),
enabled,
})
.await
{
error!("Failed to send SmartHomeChanged event: {}", e);
}
}
/// Connect to a device and read its current values with custom configuration.
///
/// This is a static method that doesn't require `&self`, making it suitable
/// for use with retry closures.
///
/// Returns the device name, type, current reading, settings, RSSI, and signal quality.
/// The device is disconnected after reading.
async fn connect_and_read_with_config(
device_id: &str,
config: ConnectionConfig,
) -> Result<
(
Option<String>,
Option<DeviceType>,
Option<CurrentReading>,
Option<DeviceSettings>,
Option<i16>,
Option<SignalQuality>,
),
aranet_core::Error,
> {
let device = Device::connect_with_config(device_id, config).await?;
// Validate connection is truly alive (especially important on macOS)
if !device.validate_connection().await {
warn!(
device_id,
"Connection validation failed - device may be out of range"
);
disconnect_quietly(&device).await;
return Err(aranet_core::Error::NotConnected);
}
debug!(device_id, "Connection validated successfully");
let name = device.name().map(String::from);
let device_type = device.device_type();
// Read RSSI and determine signal quality for adaptive behavior
let rssi = device.read_rssi().await.ok();
let signal_quality = rssi.map(SignalQuality::from_rssi);
if let Some(quality) = signal_quality {
debug!(device_id, ?quality, rssi = ?rssi, "Signal quality assessed");
}
// Add adaptive delay for weak signals before reading
if let Some(quality) = signal_quality {
let delay = quality.recommended_read_delay();
if delay > Duration::from_millis(50) {
debug!(device_id, ?delay, "Adding read delay for signal quality");
tokio::time::sleep(delay).await;
}
}
// Try to read current values
let reading = match device.read_current().await {
Ok(reading) => {
info!(device_id, "Read current values successfully");
Some(reading)
}
Err(e) => {
warn!(device_id, error = %e, "Failed to read current values");
None
}
};
// Try to read device settings
let settings = match device.get_settings().await {
Ok(settings) => {
info!(device_id, ?settings, "Read device settings successfully");
Some(settings)
}
Err(e) => {
warn!(device_id, error = %e, "Failed to read device settings");
None
}
};
// Disconnect from the device
disconnect_quietly(&device).await;
Ok((name, device_type, reading, settings, rssi, signal_quality))
}
/// Save a reading to the store.
fn save_reading(&self, device_id: &str, reading: &CurrentReading) {
let Some(store) = self.open_store() else {
return;
};
if let Err(e) = store.insert_reading(device_id, reading) {
warn!(device_id, error = %e, "Failed to save reading to store");
} else {
debug!(device_id, "Reading saved to store");
}
}
/// Save discovered devices to the store.
fn save_discovered_devices(&self, devices: &[aranet_core::DiscoveredDevice]) {
let Some(store) = self.open_store() else {
return;
};
for device in devices {
let device_id = device.id.to_string();
// Upsert the device with name
if let Err(e) = store.upsert_device(&device_id, device.name.as_deref()) {
warn!(device_id, error = %e, "Failed to upsert device");
continue;
}
// Update device type if known
if let Some(device_type) = device.device_type
&& let Err(e) = store.update_device_metadata(&device_id, None, Some(device_type))
{
warn!(device_id, error = %e, "Failed to update device metadata");
}
}
debug!(count = devices.len(), "Saved discovered devices to store");
}
/// Update device metadata in the store.
fn update_device_metadata(
&self,
device_id: &str,
name: Option<&str>,
device_type: Option<DeviceType>,
) {
let Some(store) = self.open_store() else {
return;
};
// Ensure device exists
if let Err(e) = store.upsert_device(device_id, name) {
warn!(device_id, error = %e, "Failed to upsert device");
return;
}
// Update metadata
if let Err(e) = store.update_device_metadata(device_id, name, device_type) {
warn!(device_id, error = %e, "Failed to update device metadata");
} else {
debug!(device_id, ?name, ?device_type, "Device metadata updated");
}
}
/// Load history from store and send to UI.
async fn load_and_send_history(&self, device_id: &str) {
let Some(store) = self.open_store() else {
return;
};
// Query all history for the device (no limit)
// The UI will filter by time range and resample for sparkline display
use aranet_store::HistoryQuery;
let query = HistoryQuery::new().device(device_id).oldest_first(); // Chronological order for sparkline (oldest to newest)
match store.query_history(&query) {
Ok(stored_records) => {
let records: Vec<aranet_types::HistoryRecord> =
stored_records.into_iter().map(|r| r.to_history()).collect();
info!(
device_id,
count = records.len(),
"Loaded history from store"
);
if let Err(e) = self
.event_tx
.send(SensorEvent::HistoryLoaded {
device_id: device_id.to_string(),
records,
})
.await
{
error!("Failed to send HistoryLoaded event: {}", e);
}
}
Err(e) => {
warn!(device_id, error = %e, "Failed to query history from store");
}
}
}
/// Sync history from device (download via BLE and save to store).
///
/// Uses incremental sync - only downloads new records since the last sync.
/// Includes retry logic and progress reporting.
async fn handle_sync_history(&self, device_id: &str) {
use aranet_core::history::HistoryOptions;
info!(device_id, "Syncing history from device");
// Open store first to check sync state
let Some(store) = self.open_store() else {
let context = ErrorContext::permanent("Failed to open local database");
let _ = self
.event_tx
.send(SensorEvent::HistorySyncError {
device_id: device_id.to_string(),
error: "Failed to open store".to_string(),
context: Some(context),
})
.await;
return;
};
// Connect to the device with retry logic
let retry_config = RetryConfig::for_connect();
let device_id_owned = device_id.to_string();
let config = self.connection_config.clone();
let device = match with_retry(&retry_config, "connect_for_history", || {
let device_id = device_id_owned.clone();
let config = config.clone();
async move { Device::connect_with_config(&device_id, config).await }
})
.await
{
Ok(d) => d,
Err(e) => {
error!(device_id, error = %e, "Failed to connect for history sync");
let context = ErrorContext::from_error(&e);
let _ = self
.event_tx
.send(SensorEvent::HistorySyncError {
device_id: device_id.to_string(),
error: e.to_string(),
context: Some(context),
})
.await;
return;
}
};
// Validate connection
if !device.validate_connection().await {
warn!(device_id, "Connection validation failed for history sync");
disconnect_quietly(&device).await;
let context = ErrorContext::transient(
"Connection validation failed",
"Device connected but is not responding. Try moving closer.",
);
let _ = self
.event_tx
.send(SensorEvent::HistorySyncError {
device_id: device_id.to_string(),
error: "Connection validation failed".to_string(),
context: Some(context),
})
.await;
return;
}
// Get history info to know how many records are on the device
let history_info = match device.get_history_info().await {
Ok(info) => info,
Err(e) => {
error!(device_id, error = %e, "Failed to get history info");
disconnect_quietly(&device).await;
let context = ErrorContext::from_error(&e);
let _ = self
.event_tx
.send(SensorEvent::HistorySyncError {
device_id: device_id.to_string(),
error: e.to_string(),
context: Some(context),
})
.await;
return;
}
};
let total_on_device = history_info.total_readings;
// Calculate start index for incremental sync
let start_index = match store.calculate_sync_start(device_id, total_on_device) {
Ok(idx) => idx,
Err(e) => {
warn!(device_id, error = %e, "Failed to calculate sync start, doing full sync");
1u16
}
};
// Check if already up to date
if start_index > total_on_device {
info!(device_id, "Already up to date, no new readings to sync");
disconnect_quietly(&device).await;
let _ = self
.event_tx
.send(SensorEvent::HistorySynced {
device_id: device_id.to_string(),
count: 0,
})
.await;
// Still load history from store to update UI
self.load_and_send_history(device_id).await;
return;
}
let records_to_download = total_on_device.saturating_sub(start_index) + 1;
info!(
device_id,
start_index,
total_on_device,
records_to_download,
"Downloading history (incremental sync)"
);
// Notify UI that sync is starting with total count
if let Err(e) = self
.event_tx
.send(SensorEvent::HistorySyncStarted {
device_id: device_id.to_string(),
total_records: Some(records_to_download),
})
.await
{
error!("Failed to send HistorySyncStarted event: {}", e);
}
// Download history with start_index for incremental sync
// Use adaptive read delay based on signal quality
let signal_quality = self
.signal_quality_cache
.read()
.await
.get(device_id)
.copied();
let read_delay = signal_quality
.map(|q| q.recommended_read_delay())
.unwrap_or(Duration::from_millis(50));
let history_options = HistoryOptions {
start_index: Some(start_index),
end_index: None, // Download to the end
read_delay,
use_adaptive_delay: true, // Use adaptive delay based on signal quality
..Default::default()
};
// Send periodic progress updates during download
let event_tx = self.event_tx.clone();
let device_id_for_progress = device_id.to_string();
let total = records_to_download as usize;
// Create a progress callback
let last_progress_update = std::sync::Arc::new(std::sync::atomic::AtomicUsize::new(0));
let last_progress_clone = last_progress_update.clone();
// Spawn a task to send progress updates every 10 records or 500ms
let progress_task = {
let event_tx = event_tx.clone();
let device_id = device_id_for_progress.clone();
tokio::spawn(async move {
let mut interval = interval(Duration::from_millis(500));
loop {
interval.tick().await;
let downloaded = last_progress_clone.load(std::sync::atomic::Ordering::Relaxed);
if downloaded > 0 && downloaded < total {
let _ = event_tx
.send(SensorEvent::HistorySyncProgress {
device_id: device_id.clone(),
downloaded,
total,
})
.await;
}
if downloaded >= total {
break;
}
}
})
};
// Clone the cancel token for this operation
let cancel_token = self.cancel_token.clone();
// Download with retry for the actual download operation
let retry_config = RetryConfig::for_history();
let download_future = with_retry(&retry_config, "download_history", || {
let options = history_options.clone();
let progress = last_progress_update.clone();
let device = &device;
async move {
let records = device.download_history_with_options(options).await?;
progress.store(records.len(), std::sync::atomic::Ordering::Relaxed);
Ok(records)
}
});
// Wrap download in select for cancellation support
let download_result = tokio::select! {
result = download_future => result,
_ = cancel_token.cancelled() => {
progress_task.abort();
info!(device_id, "History sync cancelled by user");
disconnect_quietly(&device).await;
let _ = self
.event_tx
.send(SensorEvent::OperationCancelled {
operation: format!("History sync for {}", device_id),
})
.await;
return;
}
};
let records = match download_result {
Ok(r) => {
progress_task.abort();
r
}
Err(e) => {
progress_task.abort();
error!(device_id, error = %e, "Failed to download history");
disconnect_quietly(&device).await;
let context = ErrorContext::from_error(&e);
let _ = self
.event_tx
.send(SensorEvent::HistorySyncError {
device_id: device_id.to_string(),
error: e.to_string(),
context: Some(context),
})
.await;
return;
}
};
let record_count = records.len();
info!(
device_id,
count = record_count,
"Downloaded history from device"
);
// Send final progress update
let _ = self
.event_tx
.send(SensorEvent::HistorySyncProgress {
device_id: device_id.to_string(),
downloaded: record_count,
total,
})
.await;
// Disconnect from device
disconnect_quietly(&device).await;
// Insert history to store (with deduplication)
// Only update sync state if insert succeeds to avoid data loss on next sync
match store.insert_history(device_id, &records) {
Ok(inserted) => {
debug!(
device_id,
downloaded = record_count,
inserted,
"History saved to store"
);
// Update sync state for next incremental sync
if let Err(e) = store.update_sync_state(device_id, total_on_device, total_on_device)
{
warn!(device_id, error = %e, "Failed to update sync state");
}
}
Err(e) => {
warn!(device_id, error = %e, "Failed to save history to store - sync state not updated");
}
}
// Notify UI that sync is complete
if let Err(e) = self
.event_tx
.send(SensorEvent::HistorySynced {
device_id: device_id.to_string(),
count: record_count,
})
.await
{
error!("Failed to send HistorySynced event: {}", e);
}
// Send history to UI for sparklines
self.load_and_send_history(device_id).await;
}
/// Handle refreshing the aranet-service status.
async fn handle_refresh_service_status(&self) {
info!("Refreshing service status");
let Some(ref client) = self.service_client else {
let _ = self
.event_tx
.send(SensorEvent::ServiceStatusError {
error: "Service client not available".to_string(),
})
.await;
return;
};
match client.status().await {
Ok(status) => {
// Convert device stats to our message type
let devices: Vec<ServiceDeviceStats> = status
.devices
.into_iter()
.map(|d| ServiceDeviceStats {
device_id: d.device_id,
alias: d.alias,
poll_interval: d.poll_interval,
polling: d.polling,
success_count: d.success_count,
failure_count: d.failure_count,
last_poll_at: d.last_poll_at,
last_error: d.last_error,
})
.collect();
let _ = self
.event_tx
.send(SensorEvent::ServiceStatusRefreshed {
reachable: true,
collector_running: status.collector.running,
uptime_seconds: status.collector.uptime_seconds,
devices,
})
.await;
}
Err(e) => match &e {
aranet_core::service_client::ServiceClientError::NotReachable { .. } => {
let _ = self
.event_tx
.send(SensorEvent::ServiceStatusRefreshed {
reachable: false,
collector_running: false,
uptime_seconds: None,
devices: vec![],
})
.await;
}
_ => {
let _ = self
.event_tx
.send(SensorEvent::ServiceStatusError {
error: Self::format_service_error(&e),
})
.await;
}
},
}
}
/// Handle starting the aranet-service collector.
async fn handle_start_service_collector(&self) {
info!("Starting service collector");
let Some(ref client) = self.service_client else {
let _ = self
.event_tx
.send(SensorEvent::ServiceCollectorError {
error: "Service client not available".to_string(),
})
.await;
return;
};
match client.start_collector().await {
Ok(_) => {
let _ = self
.event_tx
.send(SensorEvent::ServiceCollectorStarted)
.await;
// Refresh status to get updated state
self.handle_refresh_service_status().await;
}
Err(e) => {
let _ = self
.event_tx
.send(SensorEvent::ServiceCollectorError {
error: Self::format_service_error(&e),
})
.await;
}
}
}
/// Handle stopping the aranet-service collector.
async fn handle_stop_service_collector(&self) {
info!("Stopping service collector");
let Some(ref client) = self.service_client else {
let _ = self
.event_tx
.send(SensorEvent::ServiceCollectorError {
error: "Service client not available".to_string(),
})
.await;
return;
};
match client.stop_collector().await {
Ok(_) => {
let _ = self
.event_tx
.send(SensorEvent::ServiceCollectorStopped)
.await;
// Refresh status to get updated state
self.handle_refresh_service_status().await;
}
Err(e) => {
let _ = self
.event_tx
.send(SensorEvent::ServiceCollectorError {
error: Self::format_service_error(&e),
})
.await;
}
}
}
fn format_service_error(e: &aranet_core::service_client::ServiceClientError) -> String {
use aranet_core::service_client::ServiceClientError;
match e {
ServiceClientError::NotReachable { url, .. } => {
format!(
"Service not reachable at {}. Run 'aranet-service run' to start it.",
url
)
}
ServiceClientError::InvalidUrl(url) => {
format!("Invalid service URL: '{}'. Check your configuration.", url)
}
ServiceClientError::ApiError { status, message } => match *status {
401 => "Authentication required. Check your API key.".to_string(),
403 => "Access denied. Check your API key permissions.".to_string(),
404 => "Endpoint not found. The service may be an older version.".to_string(),
409 => message.clone(),
500..=599 => format!("Service error ({}): {}", status, message),
_ => format!("API error ({}): {}", status, message),
},
ServiceClientError::Request(req_err) => {
if req_err.is_timeout() {
"Request timed out. The service may be overloaded.".to_string()
} else if req_err.is_connect() {
"Connection failed. The service may not be running.".to_string()
} else {
format!("Request failed: {}", req_err)
}
}
}
}
async fn handle_set_alias(&self, device_id: &str, alias: Option<String>) {
info!("Setting alias for device {} to {:?}", device_id, alias);
let Some(store) = self.open_store() else {
let _ = self
.event_tx
.send(SensorEvent::AliasError {
device_id: device_id.to_string(),
error: "Could not open database".to_string(),
})
.await;
return;
};
match store.update_device_metadata(device_id, alias.as_deref(), None) {
Ok(()) => {
info!("Alias updated successfully for {}", device_id);
let _ = self
.event_tx
.send(SensorEvent::AliasChanged {
device_id: device_id.to_string(),
alias,
})
.await;
}
Err(e) => {
let _ = self
.event_tx
.send(SensorEvent::AliasError {
device_id: device_id.to_string(),
error: e.to_string(),
})
.await;
}
}
}
/// Start background polling for a device.
///
/// Spawns a background task that periodically reads from the device
/// and sends updates to the UI. The task can be cancelled by calling
/// `handle_stop_background_polling`.
async fn handle_start_background_polling(&self, device_id: &str, interval_secs: u64) {
info!(device_id, interval_secs, "Starting background polling");
// Check if already polling this device
{
let polling = self.background_polling.read().await;
if polling.contains_key(device_id) {
warn!(device_id, "Background polling already active for device");
return;
}
}
// Create a cancel channel
let (cancel_tx, mut cancel_rx) = tokio::sync::watch::channel(false);
// Store the cancel sender
{
let mut polling = self.background_polling.write().await;
polling.insert(device_id.to_string(), cancel_tx);
}
// Clone necessary data for the spawned task
let device_id_owned = device_id.to_string();
let event_tx = self.event_tx.clone();
let config = self.connection_config.clone();
let signal_quality_cache = self.signal_quality_cache.clone();
let store_path = self.store_path.clone();
let polling_interval = Duration::from_secs(interval_secs);
// Notify UI that polling has started
let _ = event_tx
.send(SensorEvent::BackgroundPollingStarted {
device_id: device_id.to_string(),
interval_secs,
})
.await;
// Spawn the polling task
tokio::spawn(async move {
let mut interval_timer = interval(polling_interval);
// Skip the first immediate tick
interval_timer.tick().await;
loop {
tokio::select! {
_ = cancel_rx.changed() => {
if *cancel_rx.borrow() {
info!(device_id = %device_id_owned, "Background polling cancelled");
break;
}
}
_ = interval_timer.tick() => {
debug!(device_id = %device_id_owned, "Background poll tick");
// Get cached signal quality for adaptive behavior
let signal_quality = signal_quality_cache.read().await.get(&device_id_owned).copied();
// Use more aggressive retries for devices with known poor signal
let retry_config = match signal_quality {
Some(SignalQuality::Poor) | Some(SignalQuality::Fair) => {
RetryConfig::aggressive()
}
_ => RetryConfig::for_read(),
};
// Attempt to read
match with_retry(&retry_config, "background_poll", || {
let device_id = device_id_owned.clone();
let config = config.clone();
async move {
Self::connect_and_read_with_config(&device_id, config).await
}
})
.await
{
Ok((_, _, reading, _, rssi, new_signal_quality)) => {
// Update cached signal quality
if let Some(quality) = new_signal_quality {
signal_quality_cache
.write()
.await
.insert(device_id_owned.clone(), quality);
}
// Send signal strength update if available
if let Some(rssi_val) = rssi {
let _ = event_tx
.send(SensorEvent::SignalStrengthUpdate {
device_id: device_id_owned.clone(),
rssi: rssi_val,
quality: aranet_core::messages::SignalQuality::from_rssi(rssi_val),
})
.await;
}
if let Some(reading) = reading {
debug!(device_id = %device_id_owned, "Background poll successful");
// Save to store
if let Ok(store) = Store::open(&store_path)
&& let Err(e) = store.insert_reading(&device_id_owned, &reading)
{
warn!(device_id = %device_id_owned, error = %e, "Failed to save background reading to store");
}
// Send reading update
let _ = event_tx
.send(SensorEvent::ReadingUpdated {
device_id: device_id_owned.clone(),
reading,
})
.await;
}
}
Err(e) => {
warn!(device_id = %device_id_owned, error = %e, "Background poll failed");
let context = ErrorContext::from_error(&e);
let _ = event_tx
.send(SensorEvent::ReadingError {
device_id: device_id_owned.clone(),
error: e.to_string(),
context: Some(context),
})
.await;
}
}
}
}
}
// Notify UI that polling has stopped
let _ = event_tx
.send(SensorEvent::BackgroundPollingStopped {
device_id: device_id_owned,
})
.await;
});
info!(device_id, "Background polling task spawned");
}
/// Cancel any currently running long-running operation (scan, connect, history sync).
///
/// This method cancels the current cancellation token and creates a new one
/// for future operations.
async fn handle_cancel_operation(&mut self) {
info!("Cancelling current operation");
// Cancel the current token
self.cancel_token.cancel();
// Create a new token for future operations
self.cancel_token = CancellationToken::new();
// Notify the UI that the operation was cancelled
let _ = self
.event_tx
.send(SensorEvent::OperationCancelled {
operation: "Current operation".to_string(),
})
.await;
}
/// Forget (remove) a device from the store and stop any associated polling.
async fn handle_forget_device(&self, device_id: &str) {
info!(device_id, "Forgetting device");
// Stop any background polling for this device
{
let mut polling = self.background_polling.write().await;
if let Some(cancel_tx) = polling.remove(device_id) {
let _ = cancel_tx.send(true);
info!(device_id, "Stopped background polling for forgotten device");
}
}
// Clear signal quality cache for this device
{
let mut cache = self.signal_quality_cache.write().await;
cache.remove(device_id);
}
// Try to delete from the store
let Some(store) = self.open_store() else {
let _ = self
.event_tx
.send(SensorEvent::ForgetDeviceError {
device_id: device_id.to_string(),
error: "Could not open database".to_string(),
})
.await;
return;
};
match store.delete_device(device_id) {
Ok(deleted) => {
if deleted {
info!(device_id, "Device forgotten (deleted from store)");
} else {
info!(
device_id,
"Device not found in store (removing from UI only)"
);
}
let _ = self
.event_tx
.send(SensorEvent::DeviceForgotten {
device_id: device_id.to_string(),
})
.await;
}
Err(e) => {
error!(device_id, error = %e, "Failed to forget device");
let _ = self
.event_tx
.send(SensorEvent::ForgetDeviceError {
device_id: device_id.to_string(),
error: e.to_string(),
})
.await;
}
}
}
/// Stop background polling for a device.
async fn handle_stop_background_polling(&self, device_id: &str) {
info!(device_id, "Stopping background polling");
let mut polling = self.background_polling.write().await;
if let Some(cancel_tx) = polling.remove(device_id) {
// Signal the task to stop
let _ = cancel_tx.send(true);
info!(device_id, "Background polling stop signal sent");
} else {
warn!(device_id, "No active background polling found for device");
}
}
}
#[cfg(test)]
mod tests {
use std::time::{SystemTime, UNIX_EPOCH};
use super::*;
fn test_store_path(label: &str) -> PathBuf {
let unique = SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_nanos();
std::env::temp_dir().join(format!(
"aranet-tui-worker-{label}-{}-{unique}.db",
std::process::id()
))
}
#[tokio::test]
async fn handle_cancel_operation_resets_token_and_emits_event() {
let (_command_tx, command_rx) = mpsc::channel(1);
let (event_tx, mut event_rx) = mpsc::channel(1);
let mut worker = SensorWorker::new(command_rx, event_tx, test_store_path("cancel"));
let original_token = worker.cancel_token.clone();
worker.handle_cancel_operation().await;
assert!(original_token.is_cancelled());
assert!(!worker.cancel_token.is_cancelled());
let event = event_rx.recv().await.unwrap();
match event {
SensorEvent::OperationCancelled { operation } => {
assert_eq!(operation, "Current operation");
}
other => panic!("unexpected event: {other:?}"),
}
}
#[tokio::test]
async fn handle_stop_background_polling_removes_cancel_sender() {
let (_command_tx, command_rx) = mpsc::channel(1);
let (event_tx, _event_rx) = mpsc::channel(1);
let worker = SensorWorker::new(command_rx, event_tx, test_store_path("polling"));
let (cancel_tx, cancel_rx) = tokio::sync::watch::channel(false);
let device_id = "aranet-test";
worker
.background_polling
.write()
.await
.insert(device_id.to_string(), cancel_tx);
worker.handle_stop_background_polling(device_id).await;
assert!(
!worker
.background_polling
.read()
.await
.contains_key(device_id)
);
assert!(*cancel_rx.borrow());
}
}