-
-
Notifications
You must be signed in to change notification settings - Fork 134
Expand file tree
/
Copy pathSitemapPageViewModel.swift
More file actions
1206 lines (1057 loc) · 44.5 KB
/
SitemapPageViewModel.swift
File metadata and controls
1206 lines (1057 loc) · 44.5 KB
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) 2010-2026 Contributors to the openHAB project
//
// See the NOTICE file(s) distributed with this work for additional
// information.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0
//
// SPDX-License-Identifier: EPL-2.0
@preconcurrency import Combine
import OpenHABCore
import os.log
import SwiftUI
import UIKit
private let logger = Logger(subsystem: Bundle.main.bundleIdentifier ?? "org.openhab.app", category: "SitemapPageViewModel")
enum SitemapPageError: LocalizedError {
case noActiveConnection
case serviceUnavailable
case noData
var errorDescription: String? {
switch self {
case .noActiveConnection:
"No active connection available."
case .serviceUnavailable:
"Service unavailable."
case .noData:
"No page data received."
}
}
}
enum CommandLifecycleSummary: Equatable {
case idle
case sending(count: Int)
case failed(count: Int)
}
enum SitemapInteractionSummary: Equatable {
case onlineIdle
case connecting
case offline
case queued(count: Int)
case sending(count: Int)
case failed(count: Int)
}
enum RowInteractionState: Equatable {
case idle
case offline
case queued
case sending
case failed
}
@MainActor
class SitemapPageViewModel: ObservableObject {
@Published var currentPage: OpenHABPage?
@Published var searchText = "" {
didSet {
rebuildRowInputs()
}
}
@Published var error: (any LocalizedError)?
@Published var isLoading = true
@Published var isUpdating = false
@Published var openHABRootUrl: String?
@Published var showSearchField = false
@Published private(set) var commandStates: [String: WidgetCommandLifecycleState] = [:]
@Published private(set) var trackerStatus: NetworkStatus = .stopped
@Published private(set) var widgetUpdateVersions: [String: Int] = [:]
@Published private(set) var rowInputs: [SitemapRowInput] = []
let networkTracker = MainActorNetworkTracker.shared
private var openAPIService: OpenAPIService?
private var activeConnectionInfo: ConnectionInfo?
private var pageHandlingTask: Task<Void, Never>?
private var foregroundRefreshTask: Task<Void, Never>?
private var connectionObserverTask: Task<Void, Never>?
private var networkStatusObserverTask: Task<Void, Never>?
private let commandDispatcher = WidgetCommandDispatcher()
private var defaultSitemap = ""
private var defaultSitemapLabel = ""
private var fallbackTitle = ""
@Published var pageId = ""
private var isLinkedPage = false
private var pageNetworkStatus: NetworkStatus?
private var pageNetworkStatusAvailable = false
private var activePageHandlingKey: String?
private var activePageHandlingID: UUID?
private var commandStateResetTasks: [String: Task<Void, Never>] = [:]
private var commandStateVersions: [String: Int] = [:]
private var queuedCommands: [String: QueuedCommand] = [:]
private var rowWidgetIndex: [RowID: OpenHABWidget] = [:]
private var sliderValueOverrides: [String: Double] = [:]
private var sliderOverrideResetTasks: [String: Task<Void, Never>] = [:]
private var lastForegroundRefreshAt: Date = .distantPast
var relevantWidgets: [OpenHABWidget] {
let widgets = currentPage?.widgets ?? []
guard !searchText.isEmpty else { return widgets }
return widgets.filter {
$0.label.lowercased().contains(searchText.lowercased()) && $0.type != .frame
}
}
var pageTitle: String {
// Strip bracket content from title (e.g., "Living Room[2]" becomes "Living Room")
let title = currentPage?.title.components(separatedBy: "[")[0].trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
if !title.isEmpty {
return title
} else if !fallbackTitle.isEmpty {
return fallbackTitle
} else if !defaultSitemapLabel.isEmpty {
return defaultSitemapLabel
} else {
// Return empty — SitemapPageView shows a redacted placeholder title when loading
return ""
}
}
var isLinked: Bool {
isLinkedPage
}
var commandLifecycleSummary: CommandLifecycleSummary {
let failedCount = commandStates.values.reduce(into: 0) { result, state in
if case .failed = state {
result += 1
}
}
if failedCount > 0 {
return .failed(count: failedCount)
}
let sendingCount = commandStates.values.reduce(into: 0) { result, state in
if case .sending = state {
result += 1
}
}
if sendingCount > 0 {
return .sending(count: sendingCount)
}
return .idle
}
var sitemapInteractionSummary: SitemapInteractionSummary {
if case let .failed(count) = commandLifecycleSummary {
return .failed(count: count)
}
let queuedCount = commandStates.values.reduce(into: 0) { result, state in
if case .queued = state {
result += 1
}
}
if queuedCount > 0 {
return .queued(count: queuedCount)
}
switch trackerStatus {
case .connected:
if case let .sending(count) = commandLifecycleSummary {
return .sending(count: count)
}
return .onlineIdle
case .started, .connecting:
return .connecting
case .stopped:
return .offline
}
}
init() {
loadSettings()
startObservers()
}
init(pageUrl: String, title: String, pageId: String = "") {
loadSettings()
startObservers()
isLinkedPage = true
fallbackTitle = title
defaultSitemapLabel = title
// Set openHABRootUrl from current active connection for charts/images
openHABRootUrl = networkTracker.activeConnection?.configuration.url
// Extract pageId from URL if not provided
if pageId.isEmpty {
if let urlComponents = URLComponents(string: pageUrl),
let extractedPageId = urlComponents.queryItems?.first(where: { $0.name == "sitemap" })?.value {
self.pageId = extractedPageId
} else if let lastPathComponent = URL(string: pageUrl)?.lastPathComponent {
self.pageId = lastPathComponent
}
} else {
self.pageId = pageId
}
}
/// Initializes the view model with a fixed set of widgets, without loading or polling
init(pageUrl: String = "", title: String = "Preview Page", pageId: String = "", widgets: [OpenHABWidget]) {
isLinkedPage = !pageUrl.isEmpty
fallbackTitle = title
self.pageId = pageId
currentPage = OpenHABPage(
pageId: pageId.isEmpty ? UUID().uuidString : pageId,
title: title,
link: pageUrl,
leaf: false,
widgets: widgets,
icon: ""
)
rebuildRowInputs()
}
func rowInteractionState(for itemname: String?) -> RowInteractionState {
guard let itemname, !itemname.isEmpty else { return .idle }
if let lifecycleState = commandStates[itemname] {
switch lifecycleState {
case .queued:
return .queued
case .sending:
return .sending
case .failed:
return .failed
case .idle:
break
}
}
return trackerStatus == .connected ? .idle : .offline
}
private func startObservers() {
trackerStatus = networkTracker.status
// Observe connection changes (skip initial value) — initial load is triggered by .task in the view.
connectionObserverTask = Task { [weak self] in
guard let tracker = self?.networkTracker else { return }
for await connection in tracker.$activeConnection.values.dropFirst() {
await MainActor.run { [weak self] in
self?.handleActiveConnectionChange(connection)
}
}
}
networkStatusObserverTask = Task { [weak self] in
guard let tracker = self?.networkTracker else { return }
for await status in tracker.$status.values {
await MainActor.run { [weak self] in
self?.trackerStatus = status
if status == .connected {
self?.flushQueuedCommands()
}
}
}
}
}
func rebuildRowInputs() {
let pageKey = "\(defaultSitemap)|\(pageId)"
let widgets = relevantWidgets
let inputs = SitemapRowInputMapper.map(pageKey: pageKey, widgets: widgets)
rowWidgetIndex = buildWidgetIndex(pageKey: pageKey, widgets: widgets)
if inputs != rowInputs {
rowInputs = inputs
}
}
private func buildWidgetIndex(pageKey: String, widgets: [OpenHABWidget]) -> [RowID: OpenHABWidget] {
var occurrenceByWidgetID: [String: Int] = [:]
var index: [RowID: OpenHABWidget] = [:]
index.reserveCapacity(widgets.count)
for widget in widgets {
let identityWidgetID = SitemapRowInputMapper.rowIdentityWidgetID(for: widget)
occurrenceByWidgetID[identityWidgetID, default: 0] += 1
let occurrence = occurrenceByWidgetID[identityWidgetID]!
let rowID = RowID(pageKey: pageKey, widgetId: identityWidgetID, occurrence: occurrence)
index[rowID] = widget
}
return index
}
/// Increments `widgetUpdateVersions` for each row whose content differs between `oldInputs`
/// and `newInputs`, keyed by full row identity.
func bumpWidgetVersions(from oldInputs: [SitemapRowInput], to newInputs: [SitemapRowInput]) {
if newInputs.count == oldInputs.count {
for (new, old) in zip(newInputs, oldInputs) where new != old {
widgetUpdateVersions[new.rowID.rawValue, default: 0] += 1
}
} else {
for input in newInputs {
widgetUpdateVersions[input.rowID.rawValue, default: 0] += 1
}
}
}
func widget(for rowID: RowID) -> OpenHABWidget? {
rowWidgetIndex[rowID]
}
func widgetUpdateVersion(for rowID: RowID) -> Int {
widgetUpdateVersions[rowID.rawValue] ?? 0
}
func sliderOverrideValue(for itemname: String?) -> Double? {
guard let itemname, !itemname.isEmpty else { return nil }
return sliderValueOverrides[itemname]
}
func setSliderOverrideValue(_ value: Double, for itemname: String?) {
guard let itemname, !itemname.isEmpty else { return }
sliderOverrideResetTasks[itemname]?.cancel()
sliderOverrideResetTasks[itemname] = nil
objectWillChange.send()
sliderValueOverrides[itemname] = value
}
@discardableResult
func syncSliderOverridesWithServerState(for widgets: [OpenHABWidget]) -> Int {
clearSyncedSliderOverrides(using: widgets)
}
deinit {
connectionObserverTask?.cancel()
networkStatusObserverTask?.cancel()
pageHandlingTask?.cancel()
foregroundRefreshTask?.cancel()
commandStateResetTasks.values.forEach { $0.cancel() }
commandStateResetTasks.removeAll()
sliderOverrideResetTasks.values.forEach { $0.cancel() }
sliderOverrideResetTasks.removeAll()
}
}
@MainActor
extension SitemapPageViewModel {
func loadSettings() {
defaultSitemap = Preferences.shared.currentHomePreferences.defaultSitemap
showSearchField = Preferences.shared.applicationPreferences.showSearchField
}
func stopPageHandling() {
pageHandlingTask?.cancel()
pageHandlingTask = nil
foregroundRefreshTask?.cancel()
foregroundRefreshTask = nil
activePageHandlingKey = nil
activePageHandlingID = nil
}
func refreshOnForeground() {
// Coalesce repeated .active transitions from scene/system churn.
let now = Date()
guard now.timeIntervalSince(lastForegroundRefreshAt) > 0.75 else { return }
lastForegroundRefreshAt = now
guard foregroundRefreshTask == nil else { return }
logger.info("FG refresh: scheduled")
foregroundRefreshTask = Task { [weak self] in
self?.startPageHandling(
forceRestart: true,
reason: "scene-became-active",
preserveCurrentContent: true,
recreateService: true
)
await MainActor.run {
self?.foregroundRefreshTask = nil
}
}
}
func startPageHandling(forceRestart: Bool = false,
reason: String = "manual",
preserveCurrentContent: Bool = false,
recreateService: Bool = false) {
let pipelineStart = Date()
let requestedKey = "\(defaultSitemap)|\(pageId)"
if !forceRestart,
let activeTask = pageHandlingTask,
!activeTask.isCancelled,
activePageHandlingKey == requestedKey {
logger.info("Skipping duplicate page handling start for \(requestedKey, privacy: .public), reason: \(reason, privacy: .public)")
return
}
pageHandlingTask?.cancel()
error = nil // Clear any previous errors when starting a new page handling session
if preserveCurrentContent, currentPage != nil {
isLoading = false
isUpdating = true
} else {
isLoading = true // Show redacted view immediately
isUpdating = false
}
let runID = UUID()
activePageHandlingID = runID
activePageHandlingKey = requestedKey
logger.info("🚀 Starting page load and long polling flow (reason: \(reason, privacy: .public), run: \(runID.uuidString, privacy: .public), key: \(requestedKey, privacy: .public))")
pageHandlingTask = Task {
await runPageHandling(
runID: runID,
recreateService: recreateService,
pipelineStart: pipelineStart
)
}
}
private func runPageHandling(
runID: UUID,
recreateService: Bool,
pipelineStart: Date
) async {
defer {
if activePageHandlingID == runID {
pageHandlingTask = nil
activePageHandlingID = nil
}
}
do {
guard await ensureSitemapAvailableForHandling() else { return }
guard let activeConnection = await waitForConnectionForHandling() else { return }
try setupServiceIfNeeded(activeConnection: activeConnection, forceRecreate: recreateService)
if defaultSitemapLabel.isEmpty {
await fetchSitemapLabel()
}
try await loadInitialPageForHandling(runID: runID)
isLoading = false
isUpdating = false
let totalDurationMs = Date().timeIntervalSince(pipelineStart) * 1000
logger.info("Sitemap pipeline ready in \(Int(totalDurationMs.rounded()), privacy: .public)ms")
try await runLongPollingLoop(runID: runID)
} catch {
handlePageHandlingError(error)
}
}
private func ensureSitemapAvailableForHandling() async -> Bool {
if defaultSitemap.isEmpty {
await discoverAndSelectSitemap()
}
guard !defaultSitemap.isEmpty else {
logger.error("startPageHandling: Cannot run with empty sitemap after discovery")
isLoading = false
isUpdating = false
return false
}
return true
}
private func waitForConnectionForHandling() async -> ConnectionInfo? {
if let activeConnection = networkTracker.activeConnection {
activeConnectionInfo = activeConnection
openHABRootUrl = activeConnection.configuration.url
return activeConnection
}
activeConnectionInfo = nil
guard let activeConnection = await NetworkTracker.shared.waitForActiveConnection() else {
logger.error("Failed to establish connection within timeout")
isLoading = false
isUpdating = false
return nil
}
activeConnectionInfo = activeConnection
openHABRootUrl = activeConnection.configuration.url
return activeConnection
}
private func setupServiceIfNeeded(activeConnection: ConnectionInfo, forceRecreate: Bool = false) throws {
if forceRecreate || openAPIService == nil {
openAPIService = try makeSitemapService(for: activeConnection)
if forceRecreate {
logger.info("Recreated OpenAPIService for fresh sitemap polling")
}
}
}
private func loadInitialPageForHandling(runID: UUID) async throws {
let initialPage = try await openAPIService?.pollDataForPage(
sitemapname: defaultSitemap,
pageId: pageId,
longPolling: false
)
try Task.checkCancellation()
guard activePageHandlingID == runID else {
logger.info("Ignoring stale initial page result for run \(runID.uuidString, privacy: .public)")
return
}
if let page = initialPage {
updateUI(with: page, origin: .initialPoll)
} else {
logger.info("Initial sitemap poll returned no page data")
}
}
private func runLongPollingLoop(runID: UUID) async throws {
while !Task.isCancelled {
do {
let page = try await openAPIService?.pollDataForPage(
sitemapname: defaultSitemap,
pageId: pageId,
longPolling: true
)
try Task.checkCancellation()
guard activePageHandlingID == runID else {
logger.info("Ignoring stale long-poll result for run \(runID.uuidString, privacy: .public)")
return
}
if let page {
updateUI(with: page, origin: .longPolling)
}
} catch {
try Task.checkCancellation()
guard shouldRetryLongPolling(after: error) else {
throw error
}
logger.info("Transient long-polling error, retrying: \(error.localizedDescription, privacy: .public)")
try? await Task.sleep(nanoseconds: 500_000_000)
}
}
}
@MainActor
private func updateUI(with page: OpenHABPage, origin: PageUpdateOrigin) {
logger.debug("Incoming sitemap update origin=\(origin.rawValue, privacy: .public), widgets=\(page.widgets.count)")
let pageKey = "\(defaultSitemap)|\(pageId)"
// Snapshot what the list would render from the new data — before any widget mutation.
let incomingFiltered: [OpenHABWidget]
if searchText.isEmpty {
incomingFiltered = page.widgets
} else {
incomingFiltered = page.widgets.filter {
$0.label.lowercased().contains(searchText.lowercased()) && $0.type != .frame
}
}
let previewInputs = SitemapRowInputMapper.map(pageKey: pageKey, widgets: incomingFiltered)
let titleChanged = currentPage == nil || currentPage?.title != page.title
let canSkipReconciliation = searchText.isEmpty && previewInputs == rowInputs && !titleChanged
guard !canSkipReconciliation else {
_ = clearSyncedSliderOverrides(using: page.widgets)
return
}
// Something changed — reconcile widget objects and update stored state.
let currentWidgets = currentPage?.widgets ?? []
let structureChanged = currentWidgets.count != page.widgets.count
|| !zip(currentWidgets, page.widgets).allSatisfy { $0.widgetId == $1.widgetId }
let reconciledWidgets = reconcileWidgets(page.widgets, with: currentWidgets)
injectSendCommand(for: reconciledWidgets)
if structureChanged || titleChanged {
page.widgets = reconciledWidgets
currentPage = page
} else {
currentPage?.widgets = reconciledWidgets
}
_ = clearSyncedSliderOverrides(using: reconciledWidgets)
// Rebuild command-dispatch index from the now-current reconciled widgets.
rowWidgetIndex = buildWidgetIndex(pageKey: pageKey, widgets: relevantWidgets)
// Bump widget versions only for rows whose content actually changed.
bumpWidgetVersions(from: rowInputs, to: previewInputs)
// Publish new row inputs — guaranteed to differ from current (checked above).
rowInputs = previewInputs
}
private func clearSyncedSliderOverrides(using widgets: [OpenHABWidget]) -> Int {
guard !sliderValueOverrides.isEmpty else { return 0 }
var cleared = 0
for widget in widgets {
guard let item = widget.item else {
cleared += clearSyncedSliderOverrides(using: widget.widgets)
continue
}
let itemname = item.name
guard let overrideValue = sliderValueOverrides[itemname] else {
cleared += clearSyncedSliderOverrides(using: widget.widgets)
continue
}
let serverValue = item.state?.parseAsNumber(format: item.stateDescription?.numberPattern).value ?? .nan
guard serverValue.isFinite else {
cleared += clearSyncedSliderOverrides(using: widget.widgets)
continue
}
let threshold = max(widget.step, 0.001)
if abs(serverValue - overrideValue) <= threshold {
clearSliderOverride(for: itemname)
cleared += 1
logger.debug("Cleared slider override for \(itemname, privacy: .public) (server=\(serverValue), override=\(overrideValue))")
}
cleared += clearSyncedSliderOverrides(using: widget.widgets)
}
return cleared
}
func reload() async {
do {
isLoading = true
try await setupConnection()
// Fetch sitemap label if we don't have it yet
if defaultSitemapLabel.isEmpty {
await fetchSitemapLabel()
}
try await loadCurrentPage()
} catch {
self.error = error as? any LocalizedError
}
isLoading = false
}
private func setupConnection() async throws {
guard let activeConnection = await NetworkTracker.shared.waitForActiveConnection() else {
throw SitemapPageError.noActiveConnection
}
activeConnectionInfo = activeConnection
openAPIService = try makeSitemapService(for: activeConnection)
}
private func loadCurrentPage() async throws {
guard let service = openAPIService else { throw SitemapPageError.serviceUnavailable }
guard let page = try await service.pollDataForPage(
sitemapname: defaultSitemap,
pageId: pageId,
longPolling: false
) else {
throw SitemapPageError.noData
}
injectSendCommand(for: page.widgets)
currentPage = page
rebuildRowInputs()
}
private func reconcileWidgets(_ newWidgets: [OpenHABWidget], with currentWidgets: [OpenHABWidget]) -> [OpenHABWidget] {
var buckets: [String: [OpenHABWidget]] = [:]
for widget in currentWidgets {
buckets[widget.widgetId, default: []].append(widget)
}
var reconciled: [OpenHABWidget] = []
reconciled.reserveCapacity(newWidgets.count)
for newWidget in newWidgets {
if var candidates = buckets[newWidget.widgetId], !candidates.isEmpty {
let existing = candidates.removeFirst()
buckets[newWidget.widgetId] = candidates
// Always copy server properties to avoid missing updates when
// non-keyed fields change (for example group summary/state rows).
let previousChildren = existing.widgets
copyWidgetProperties(from: newWidget, to: existing)
existing.widgets = reconcileWidgets(newWidget.widgets, with: previousChildren)
reconciled.append(existing)
} else {
reconciled.append(newWidget)
}
}
return reconciled
}
private func copyWidgetProperties(from source: OpenHABWidget, to target: OpenHABWidget) {
target.label = source.label
target.icon = source.icon
target.state = source.state
target.type = source.type
target.isLeaf = source.isLeaf
target.item = source.item
target.iconColor = source.iconColor
target.labelcolor = source.labelcolor
target.valuecolor = source.valuecolor
target.url = source.url
target.period = source.period
target.service = source.service
target.legend = source.legend
target.refresh = source.refresh
target.height = source.height
target.forceAsItem = source.forceAsItem
target.minValue = source.minValue
target.maxValue = source.maxValue
target.step = source.step
target.pattern = source.pattern
target.unit = source.unit
target.switchSupport = source.switchSupport
target.mappings = source.mappings
target.linkedPage = source.linkedPage
target.visibility = source.visibility
target.staticIcon = source.staticIcon
target.text = source.text
target.inputHint = source.inputHint
target.encoding = source.encoding
target.labelSource = source.labelSource
target.releaseOnly = source.releaseOnly
target.row = source.row
target.column = source.column
target.releaseCommand = source.releaseCommand
target.command = source.command
target.stateless = source.stateless
target.yAxisDecimalPattern = source.yAxisDecimalPattern
}
private func shouldRetryLongPolling(after error: any Error) -> Bool {
if let urlError = OpenAPIErrorInspector.underlyingURLError(from: error) {
switch urlError.code {
case .timedOut, .networkConnectionLost, .cannotConnectToHost, .notConnectedToInternet, .cannotFindHost:
return true
default:
break
}
}
if let openAPIError = error as? OpenAPIServiceError {
switch openAPIError {
case let .undocumented(statusCode, _):
return statusCode == 408 || statusCode == 499 || statusCode == 502 || statusCode == 503 || statusCode == 504
case .badRequest, .notFound, .noRootURL, .unAuthorized:
break
}
}
return false
}
private func injectSendCommand(for widgets: [OpenHABWidget]) {
for widget in widgets {
widget.sendCommand = { [weak self] item, command in
self?.sendCommand(item, commandToSend: command)
}
// If widget has nested children (e.g., frames/groups), inject recursively
injectSendCommand(for: widget.widgets)
}
}
@MainActor
func pushSitemap(name: String, path: String?) async {
defaultSitemap = name
defaultSitemapLabel = "" // Clear old label so it gets fetched for the new sitemap
pageId = path ?? ""
error = nil // Clear any previous errors when switching sitemaps
startPageHandling(forceRestart: true, reason: "push-sitemap")
}
private func fetchSitemapLabel() async {
guard let service = openAPIService else {
logger.error("OpenAPI service not available for fetching sitemap label")
return
}
do {
let sitemaps = try await service.openHABSitemaps()
// Find the sitemap matching our defaultSitemap name and get its label
if let sitemap = sitemaps.first(where: { $0.name == defaultSitemap }) {
defaultSitemapLabel = sitemap.label
// swiftformat:disable:next redundantSelf
logger.info("Found label '\(self.defaultSitemapLabel)' for sitemap '\(self.defaultSitemap)'")
} else {
// swiftformat:disable:next redundantSelf
logger.warning("Could not find sitemap '\(self.defaultSitemap)' in available sitemaps")
}
} catch {
logger.warning("Failed to fetch sitemap label: \(error)")
// Don't set error here as this is not critical - we can continue without the label
}
}
private func discoverAndSelectSitemap() async {
do {
try await setupConnection()
guard let service = openAPIService else {
logger.error("Could not setup service for sitemap discovery")
return
}
let sitemaps = try await service.openHABSitemaps()
// Filter out _default sitemap if there are multiple sitemaps available
let filteredSitemaps = sitemaps.count > 1 ? sitemaps.filter { $0.name != "_default" } : sitemaps
switch filteredSitemaps.count {
case 1:
// Auto-select the only available sitemap
defaultSitemap = filteredSitemaps[0].name
defaultSitemapLabel = filteredSitemaps[0].label
// swiftformat:disable:next redundantSelf
logger.info("Auto-selected single sitemap: \(self.defaultSitemap)")
// Save as default for future launches
Preferences.shared.modifyActiveHome { homePreferences in
homePreferences.defaultSitemap = defaultSitemap
}
case 2...:
// Multiple sitemaps available - select the first one
defaultSitemap = filteredSitemaps[0].name
defaultSitemapLabel = filteredSitemaps[0].label
// swiftformat:disable:next redundantSelf
logger.info("Auto-selected first sitemap from \(filteredSitemaps.count) available: \(self.defaultSitemap)")
// Save as default for future launches
Preferences.shared.modifyActiveHome { homePreferences in
homePreferences.defaultSitemap = defaultSitemap
}
default:
logger.error("No sitemaps available")
error = SitemapPageError.serviceUnavailable
}
} catch {
logger.error("Failed to discover sitemaps: \(error)")
self.error = error as? any LocalizedError ?? SitemapPageError.serviceUnavailable
}
}
func handleActiveConnectionChange(_ activeConnection: ConnectionInfo?) {
guard let activeConnection else { return }
logger.info("SitemapPageViewModel tracker URL \(activeConnection.configuration.url)")
// Skip if already connected to this URL — avoids restarting long-polling
// when the NetworkTracker re-evaluates to the same connection
let connectionDidChange = openHABRootUrl != activeConnection.configuration.url
let hasRunningPageTask = pageHandlingTask != nil && pageHandlingTask?.isCancelled == false
let networkStatusDidChange = pageNetworkStatusChanged()
guard connectionDidChange || (networkStatusDidChange && !hasRunningPageTask) else {
return
}
Task {
await handleActiveConnection(activeConnection)
}
}
@discardableResult
private func pageNetworkStatusChanged() -> Bool {
logger.info("SitemapPageViewModel pageNetworkStatusChange")
let currentStatus = MainActorNetworkTracker.shared.status
// First run
if !pageNetworkStatusAvailable {
pageNetworkStatus = currentStatus
pageNetworkStatusAvailable = true
return false
}
if pageNetworkStatus == currentStatus {
return false
} else {
pageNetworkStatus = currentStatus
return true
}
}
private func handleActiveConnection(_ connection: ConnectionInfo) async {
let previousURL = activeConnectionInfo?.configuration.url
let newURL = connection.configuration.url
let connectionDidChange = previousURL != newURL
// Save the active connection information
activeConnectionInfo = connection
openHABRootUrl = newURL
do {
// Setup the OpenAPI service based on the new connection
openAPIService = try makeSitemapService(for: connection)
// Restart when connection changed, or when polling is currently inactive.
let shouldRestart = connectionDidChange
|| pageHandlingTask == nil
|| pageHandlingTask?.isCancelled == true
if shouldRestart {
startPageHandling(forceRestart: true, reason: connectionDidChange ? "connection-changed" : "connection-recovered")
}
} catch {
self.error = error as? any LocalizedError
}
}
func selectSitemap() async {
startPageHandling(forceRestart: true, reason: "select-sitemap")
}
private func makeSitemapService(for connection: ConnectionInfo) throws -> OpenAPIService {
// Keep sitemap polling fresh after foreground transitions or long inactivity.
// Long-term config disables URL cache and aligns with watchOS behavior.
try OpenAPIService(
connectionConfiguration: connection.configuration,
serviceConfiguration: .longTerm
)
}
// MARK: - Command Sending
func sendCommand(_ command: String?,
for widget: OpenHABWidget,
policy: WidgetCommandPolicy = .immediate,
phase: WidgetCommandPhase = .change,
key: String? = nil,
fallbackItem: OpenHABItem? = nil) {
commandDispatcher.send(
command,
for: widget,
policy: policy,
phase: phase,
key: key,
fallbackItem: fallbackItem
)
}
func cancelPendingCommand(for widget: OpenHABWidget, key: String? = nil) {
commandDispatcher.cancelPending(for: widget, key: key)
}
func cancelPendingCommand(for item: OpenHABItem, key: String? = nil) {
commandDispatcher.cancelPending(for: item, key: key)
}
func cancelPendingCommand(for itemname: String, key: String? = nil) {
commandDispatcher.cancelPending(for: itemname, key: key)
if key == nil {
queuedCommands.removeValue(forKey: itemname)
clearSliderOverride(for: itemname)
if case .queued = commandStates[itemname] {
setCommandState(.idle, for: itemname)
}
}
}
func sendCommand(_ command: String?,
for itemname: String,
policy: WidgetCommandPolicy = .immediate,
phase: WidgetCommandPhase = .change,
key: String? = nil) {
commandDispatcher.send(
command,
for: itemname,
policy: policy,
phase: phase,
key: key
) { [weak self] itemname, command in
self?.sendCommand(itemname: itemname, command: command, origin: .command)
}
}
func sendCommand(_ item: OpenHABItem?, commandToSend command: String?) {
commandDispatcher.send(command, for: item, policy: .immediate, phase: .change) { [weak self] itemname, command in
self?.sendCommand(itemname: itemname, command: command, origin: .command)
}
}
func sendCommand(itemname: String, command: String) {
sendCommand(itemname: itemname, command: command, origin: .command)
}
private func sendCommand(itemname: String, command: String, origin: CommandSendOrigin) {
logger.debug("Dispatching command origin=\(origin.rawValue, privacy: .public), item=\(itemname, privacy: .public), command=\(command, privacy: .private(mask: .hash))")
let version = nextCommandVersion(for: itemname)
if trackerStatus != .connected {
queuedCommands[itemname] = QueuedCommand(command: command, version: version)
setCommandState(.queued, for: itemname)
return
}
sendCommandNow(itemname: itemname, command: command, version: version)
}