iOS/Sources/Shared/ControlEntityProvider.swift
Bruno Pantaleão Gonçalves 13ac4e4a87
Making API connection optional given activeURL is now optional as well (#3169)
<!-- Thank you for submitting a Pull Request and helping to improve Home
Assistant. Please complete the following sections to help the processing
and review of your changes. Please do not delete anything from this
template. -->

## Summary
<!-- Provide a brief summary of the changes you have made and most
importantly what they aim to achieve -->

## Screenshots
<!-- If this is a user-facing change not in the frontend, please include
screenshots in light and dark mode. -->

## Link to pull request in Documentation repository
<!-- Pull requests that add, change or remove functionality must have a
corresponding pull request in the Companion App Documentation repository
(https://github.com/home-assistant/companion.home-assistant). Please add
the number of this pull request after the "#" -->
Documentation: home-assistant/companion.home-assistant#

## Any other notes
<!-- If there is any other information of note, like if this Pull
Request is part of a bigger change, please include it here. -->
2024-11-18 15:07:18 +01:00

67 lines
2.4 KiB
Swift

import Foundation
import GRDB
public final class ControlEntityProvider {
public enum States: String {
case open
case opening
case close
case closing
case on
case off
}
public let domain: Domain
public init(domain: Domain) {
self.domain = domain
}
public func currentState(serverId: String, entityId: String) async throws -> String? {
guard let server = Current.servers.all.first(where: { $0.identifier.rawValue == serverId }),
let connection = Current.api(for: server)?.connection else {
return nil
}
let state: String? = await withCheckedContinuation { continuation in
connection.send(.init(
type: .rest(.get, "states/\(entityId)")
)) { result in
switch result {
case let .success(data):
let state: String? = data.decode("state", fallback: nil)
continuation.resume(returning: state)
case let .failure(error):
Current.Log.error("Failed to get \(entityId) state for ControlEntityProvider: \(error)")
continuation.resume(returning: nil)
}
}
}
return state
}
public func getEntities(matching string: String? = nil) -> [(Server, [HAAppEntity])] {
var entitiesPerServer: [(Server, [HAAppEntity])] = []
for server in Current.servers.all.sorted(by: { $0.info.name < $1.info.name }) {
do {
var entities: [HAAppEntity] = try Current.database.read { db in
try HAAppEntity
.filter(Column(DatabaseTables.AppEntity.serverId.rawValue) == server.identifier.rawValue)
.filter(Column(DatabaseTables.AppEntity.domain.rawValue) == domain.rawValue)
.fetchAll(db)
}
if let string {
entities = entities.filter({ entity in
entity.name.lowercased().contains(string.lowercased())
})
}
entitiesPerServer.append((server, entities))
} catch {
Current.Log.error("Failed to load entities from database: \(error.localizedDescription)")
}
}
return entitiesPerServer
}
}