用python实现homekit附件协议

HAP-python的Python项目详细描述


PyPI versionBuild StatuscodecovDocumentation StatusDownloads

hap python

在python 3中实现homekit附件协议。 通过此项目,您可以集成自己的智能设备并将其添加到 iOS家庭应用程序。由于Siri已与家庭应用程序集成,您可以启动语音控制 配件马上。

主要功能:

  • camera-hap python支持2.3.0版的相机附件!
  • 异步支持-您可以在事件循环中运行各种任务或附件。
  • 对苹果定义的服务的开箱即用支持-请参见the resources folder
  • 扫描二维码即可确保配对安全。
  • 与家庭自动化框架集成。

这个项目是为一个覆盆子pi开发的,但是它应该可以在其他平台上工作。开始做一些事情, 你可以打开main.pybusy_home.py,在那里你会发现一些假的配件。 只需运行其中一个,例如python3 busy_home.py,就可以将其添加到 家庭应用程序(请确保位于同一网络中)。 按ctrl+c可停止此操作。

有示例附件以及与真实产品的集成 在the accessories folder中。查看如何在中配置相机 camera_main.py

目录

  1. API
  2. Installation
  3. Setting up a camera
  4. Run at boot (and a Switch to shutdown your device)
  5. Notice

安装

As of version 2.0.0, HAP-python no longer supports python older than 3.5, because we are moving to asyncio. If your platform does not have a compatible python out of the box, you can install it manually or just use an older version of HAP-python.

As a prerequisite, you will need Avahi/Bonjour installed (due to zeroconf package). On a Raspberry Pi, you can get it with:

^{pr 1}$

^{} may also fit the bill. Then, you can install with ^{} (you will need ^{} or ^{} for the install):

^{pr 2}$

This will install HAP-python in your python packages, so that you can import it as ^{}. To uninstall, just do:

^{pr 3}$

API

A typical flow for using HAP-python starts with implementing an Accessory. This is done by subclassing Accessory并放置一些细节 (见下文)。之后,您将附件交给AccessoryDriver管理。这个 将负责在本地网络上发布广告,设置HAP服务器和 运行附件。看看main.py就可以快速开始了。

frompyhap.accessoryimportAccessory,Categoryimportpyhap.loaderasloaderclassTemperatureSensor(Accessory):"""Implementation of a mock temperature sensor accessory."""category=Category.SENSOR# This is for the icon in the iOS Home app.def__init__(self,*args,**kwargs):"""Here, we just store a reference to the current temperature characteristic and        add a method that will be executed every time its value changes.        """# If overriding this method, be sure to call the super's implementation first.super().__init__(*args,**kwargs)# Add the services that this Accessory will support with add_preload_service heretemp_service=self.add_preload_service('TemperatureSensor')self.temp_char=temp_service.get_characteristic('CurrentTemperature')# Having a callback is optional, but you can use it to add functionality.self.temp_char.setter_callback=self.temperature_changeddeftemperature_changed(self,value):"""This will be called every time the value of the CurrentTemperature        is changed. Use setter_callbacks to react to user actions, e.g. setting the        lights On could fire some GPIO code to turn on a LED (see pyhap/accessories/LightBulb.py).        """print('Temperature changed to: ',value)@Acessory.run_at_interval(3)# Run this method every 3 seconds# The `run` method can be `async` as welldefrun(self):"""We override this method to implement what the accessory will do when it is        started.        We set the current temperature to a random number. The decorator runs this method        every 3 seconds.        """self.temp_char.set_value(random.randint(18,26))# The `stop` method can be `async` as welldefstop(self):"""We override this method to clean up any resources or perform final actions, as        this is called by the AccessoryDriver when the Accessory is being stopped.        """print('Stopping accessory.')

设置相机

The Camera accessory实现用于协商流设置的HomeKit协议, 如图片的宽度和高度,音频通道的数量等。 启动视频和/或音频流是非常特定于平台的。因为这个, 你需要弄清楚你的相机支持哪些视频和音频设置并设置它们 在传递给Camera附件的options参数中。参考 用于需要指定的设置的Camera控件的文档。

默认情况下,hap python将使用协商的参数执行ffmpeg命令 当流应该启动时,并且当 应停止流(请参阅默认值:Camera.FFMPEG_CMD)。 如果您的平台不支持或格式不正确的默认命令, 流可能会失败。

对于这些情况,hap python有钩子,这样您就可以插入自己的命令或实现 启动或停止流的逻辑。有两个选项:

  1. 传递您自己的命令,该命令将在流启动时执行。

    将命令作为值传递给options参数中的键start_stream_cmd 附件的结构。命令的格式使用 协商流配置参数。例如,如果协商的宽度 是640,并且您传递foo start -width {width},命令将格式化为 foo start -width 640

    协商流配置参数的完整列表可以在 Camera.start方法的文档。

  2. 实现自己的逻辑来启动、停止和重新配置流。

    如果在管理流中需要更大的灵活性,可以直接实现 Camera方法startstopreconfigure。当 应分别启动、停止或重新配置流。开始和 重新配置方法给出了协商流配置参数。

    查看这些方法的文档以获取更多信息。

最后,如果可以从相机中拍摄快照,则可能需要实现 Camera.snapshot方法。默认情况下,这是一张普通照片。

启动时运行

This is a quick way to get ^{} to run at boot on a Raspberry Pi. It is recommended to turn on "Wait for network" in ^{}. If this turns to be unreliable, see this

/etc/systemd/system/HAP-python.service中复制下面的内容(需要sudo)。

[Unit]
Description = HAP-python daemon
Wants = pigpiod.service  # Remove this if you don't depend on pigpiod
After = local-fs.target network-online.target pigpiod.service

[Service]
User = lesserdaemon  # It's a good idea to use some unprivileged system user
# Script starting HAP-python, e.g. main.py
# Be careful to set any paths you use, e.g. for persisting the state.
ExecStart = /usr/bin/python3 /home/lesserdaemon/.hap-python/hap-python.py

[Install]
WantedBy = multi-user.target

通过做来检验一切都好:

> sudo systemctl start HAP-python
> systemctl status HAP-python
> sudo journalctl -u HAP-python  # to see the output of the start up script.
> sudo systemctl stop HAP-python

要在启动时启用或禁用,请执行以下操作:

> sudo systemctl enable HAP-python
> sudo systemctl disable HAP-python

停机开关

如果在覆盆子pi上运行HAP-python,则可能需要添加 Shutdown Switch去你家。这是一个 开关附件,当被触发时,执行sudo shutdown -h now,即。 它关闭并停止PI。这样你就可以安全地拔掉插头。

要使上述操作生效,您需要启用无密码/sbin/shutdown,以 用户正在运行HAP-python。例如,do:

$ sudo visudo # and add the line: "<hap-user> ALL=NOPASSWD: /sbin/shutdown".

注意

Some HAP know-how was taken from HAP-NodeJS by KhaosT

我不知道有什么错误,但我对这样的存在深信不疑。如果你找到了, 请报告,我会设法解决他们。

建议总是受欢迎的。

玩得开心!

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
java web爬虫:使用selenium+webdriver遍历页面链接时出现两种异常   java JPA和SYS_REFCURSOR-like OUT参数   非空参数的java方法引用?   xml中的java子节点名称   java为什么GC不在同一个方法中运行   java如何检查可执行JAR是否已在另一个JVM中完成   将外观更改为Nimbus后出现jtable Java错误   用户界面Java Swing架构问题?   java导入自定义字体时我做错了什么?   java如何用API制作可伸缩的游戏策划   java玩家和方块的碰撞和交集   java增强的for循环   java propertiesmavenplugin不适用于目标writeprojectproperties   java循环返回代码的开头   java使用分号执行apachecommonsexec多个命令   Wicket应用程序中的java全局可访问资源   java在eclipse中设置参数时可以使用类名而不是id吗?   eternal和maxElementsInMemory在ehcache中的java角色?   java ClassCastException在同一个ear中从两个不同的WAR加载同一个类时,由于类装入器不同