HAKit 0.3

HAKit 0.3

Zachary West 维护。



HAKit 0.3

  • Home Assistant

HAKit

这仍然处于早期开发阶段。

Documentation codecov License Apache 2.0

这个库允许您连接到 Home Assistant WebSocket API 以发出命令并订阅事件。未来的计划包括提供最基本的支持REST API,主要围绕身份验证。

API 参考

您可以在 完整的文档集 中查看。最重要的方法集合在 HAConnection 协议中。这个协议是连接到 Home Assistant 实例的主入口点。

创建和连接

创建连接需要两个信息:服务器 URL 和访问令牌。这两者在尝试连接时获取。由于 Home Assistant 实例的连通性可能因当前网络而异,这些值将在每次尝试连接时重新查询。

您可以使用公开的初始化器获取连接实例

let connection = HAConnection.api(configuration: .init(
  connectionInfo: {
    // Connection is required to be returned synchronously.
    .init(url: URL(string: "http://homeassistant.local:8123")!)
  },
  fetchAuthToken: { completion in
    // Access tokens are retrieved asynchronously, but be aware that Home Assistant
    // has a timeout of 10 seconds for sending your access token.
    completion(.success("API_Token_Here"))
  }
))

您可以进一步配置此连接的其他属性,例如 callbackQueue(您的处理程序在其中调用)以及触发手动连接尝试。有关更多信息,请参阅协议。

一旦调用 .connection() 并直到调用 .disconnect(),连接将尝试保持连接状态,在网络状态改变时尝试重新连接,并在断开连接后的重试期间尝试重新连接。

发送和订阅

请求分为两种类型:具有即时结果的请求和触发事件直到取消的请求。这些操作分别是“发送”和“订阅”。例如,你可以发送服务调用,但订阅模板的渲染。

发出的请求将在重新连接期间继续重试,直到执行一次,订阅在必要时将自动重新注册,直到取消。每次 sendsubscribe 都返回一个 HACancellable 令牌,您可以取消它,每个订阅处理程序也包含一个令牌。

例如,检索当前用户,就像其他在 HATypedRequestHATypedSubscription 中的调用一样,有辅助方法提供强类型值。例如,您可以以两种方式之一编写它

// with the CurrentUser convenience helper
connection.send(.currentUser()) { result in
  switch result {
  case let .success(user):
    // e.g. user.id or user.name are available on the result object
  case let .failure(error):
    // an error occurred with the request
  }
}

// or issued directly, and getting the raw response
connection.send(.init(type: .currentUser, data: [:])) { result in
  switch result {
  case let .success(data):
    // data is an `HAData` which wraps possible responses and provides decoding
  case let .failure(error):
    // an error occurred with the request
  }
}

类似地,可以使用便利辅助程序或直接订阅事件。

// with the RenderTemplate convenience helper
connection.subscribe(
  to: .renderTemplate("{{ states('sun.sun') }} {{ states.device_tracker | count }}"),
  initiated: { result in
    // when the initiated method is provided, this is the result of the subscription
  },
  handler: { [textView] cancelToken, response in
    // the overall response is parsed for type, but native template rendering means
    // the rendered type will be a Dictionary, Array, etc.
    textView.text = String(describing: response.result)
    // you could call `cancelToken.cancel()` to end the subscription here if desired
  }
)

// or issued directly, and getting the raw response
connection.subscribe(
  to: .init(type: .renderTemplate, data: [
    "template": "{{ states('sun.sun') }} {{ states.device_tracker | count }}"
  ]),
  initiated: { result in
    // when the initiated method is provided, this is the result of the subscription
  },
  handler: { [textView] cancelToken, data in
    // data is an `HAData` which wraps possible responses and provides decoding
    // the decode methods infer which type you're asking for and attempt to convert
    textView.text = try? data.decode("result")
    // you could call `cancelToken.cancel()` to end the subscription here if desired
  }
)  

您也可以调用任何请求或订阅,即使是那些不带便利访问器名称的请求或订阅。事件名称和请求类型符合 ExpressibleByStringLiteral 或您可以使用原始值初始化它们。

解码

当不使用便利包装器时,许多方法会将结果作为 HAData 返回。它替代了底层字典或数组响应,并具有解码字典中的键为特定类型的便利方法。这类似于 Decodable,但不相同——许多 Home Assistant 调用将返回必须保留为 Any 的结果,而 Swift 的 JSON 编码没有很好地处理这种情况。

请参阅 HADataDecodable 了解可用方法。

安装

Swift 包管理器

要安装库,请将其添加为 Package.swift 中的依赖项:

.Package(url: "https://github.com/home-assistant/HAKit.git", majorVersion: 0)

要将它添加到 Xcode 项目中,您可以通过添加 URL 来完成,方法是转到文件 > Swift 包 > 添加包依赖项。

cocoaPods

将以下行添加到您的 Podfile

pod "HAKit", "~> 0.1"

贡献

请参阅 CONTRIBUTING.md 以获取有关如何构建和修改此库的更多信息。

许可证

此库受 Apache 2.0 许可证保护,它还依赖于 Starscream 来实现旧版本的 iOS 上的 WebSocket 连接。Starscream 也受 Apache 2.0 许可证保护。