iphone siriをテストする。windows 編(HAP-python)

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/475577e0-082a-5dcd-20b9-8cd06319cde4.png)

# Windows 10でLinuxを走るようにする。
###WSL(Windows Subsystem for Linux)のインストール。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/3afe9c3b-cd2f-88fb-d581-572a55f3c1f2.png)
Windows Subsystem for Linuxにチェックを入れる。
windows storeからUbuntuをインストールする。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/6b3c0ead-52dc-4af9-07ae-2c4f00e5b97f.png)
windows commandの準備
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/31ac2ddc-2472-e89a-009b-c9bbcfd63c22.png)
従来のコンソールを使うのチェックを外す。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/8e0dd43d-be94-68a4-28ce-ba1449df1f77.png)
コマンドプロンプトでubuntuを入力する。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/fdfe0d03-83ae-1719-0aa1-42b68d92e59b.png)

``` 
 apt-get update
 apt-get upgrade
 sudo apt-get install libavahi-compat-libdnssd-dev
 mkdir src
 cd src
 clone git://github.com/ikalchev/HAP-python.git
 git clone git://github.com/ikalchev/HAP-python.git
 cd HAP-python
 pip install HAP-python[QRCode]
 pip install -e .[QRCode]

```
windowsのファイアーウォールのport 51826を開ける。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/1303da46-effa-5c92-acf4-2740257873d9.png)

```
root@MainCom:~/src/HAP-python# python3 main.py
```
#実行するとテストプログラムが走ります。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/3ca11687-1df3-34f4-5334-d0de8403f093.png)
##iphoneのホームのアプリケーションを立ち上げQRCODEを読み込みます。
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/cf539b94-f8ed-7d8c-ee32-766a0addae19.png)

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/f138ad31-76f7-5934-4aea-7139ec518e0a.png)
黒下線のように温度が現れれば正常動作

```main.py
"""An example of how to setup and start an Accessory.

This is:
1. Create the Accessory object you want.
2. Add it to an AccessoryDriver, which will advertise it on the local network,
    setup a server to answer client queries, etc.
"""
import logging
import signal
import random

from pyhap.accessory import Accessory, Bridge
from pyhap.accessory_driver import AccessoryDriver
import pyhap.loader as loader
from pyhap import camera
from pyhap.const import CATEGORY_SENSOR

logging.basicConfig(level=logging.INFO, format="[%(module)s] %(message)s")


class TemperatureSensor(Accessory):
    """Fake Temperature sensor, measuring every 3 seconds."""

    category = CATEGORY_SENSOR

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        serv_temp = self.add_preload_service('TemperatureSensor')
        self.char_temp = serv_temp.configure_char('CurrentTemperature')

    @Accessory.run_at_interval(3) #温度を表示している値の更新
    async def run(self):
        self.char_temp.set_value(random.randint(18, 26)) # 18℃から26℃


def get_bridge(driver):
    """Call this method to get a Bridge instead of a standalone accessory."""
    bridge = Bridge(driver, 'Bridge')
    temp_sensor = TemperatureSensor(driver, 'Sensor 2')
    temp_sensor2 = TemperatureSensor(driver, 'Sensor 1')
    bridge.add_accessory(temp_sensor)
    bridge.add_accessory(temp_sensor2)

    return bridge


def get_accessory(driver):
    """Call this method to get a standalone Accessory."""
    return TemperatureSensor(driver, 'MyTempSensor')


# Start the accessory on port 51826
driver = AccessoryDriver(port=51826)

# Change `get_accessory` to `get_bridge` if you want to run a Bridge.
driver.add_accessory(accessory=get_accessory(driver))

# We want SIGTERM (terminate) to be handled by the driver itself,
# so that it can gracefully stop the accessory, server and advertising.
signal.signal(signal.SIGTERM, driver.signal_handler)

# Start it!
driver.start()
```

servicesは、下記のように定義されている。

```/root/src/HAP-python/pyhap/resources/services.json
   "TemperatureSensor": {
      "OptionalCharacteristics": [
         "StatusActive",
         "StatusFault",
         "StatusLowBattery",
         "StatusTampered",
         "Name"
      ],
      "RequiredCharacteristics": [
         "CurrentTemperature"
      ],
      "UUID": "0000008A-0000-1000-8000-0026BB765291"
   },
```
characteristicsは、下記のように定義されている。

```/root/src/HAP-python/pyhap/resources/characteristics.json
   "CurrentTemperature": {
      "Format": "float",
      "Permissions": [
         "pr",
         "ev"
      ],
      "UUID": "00000011-0000-1000-8000-0026BB765291",
      "maxValue": 1000,
      "minStep": 0.1,
      "minValue": -273.1,
      "unit": "celsius"
   }
```
iphoneのSiriに「MyTempSensor」と話しかけると
![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/1228b45b-beac-a51c-53a1-b497dfb535f1.png)
<blockquote class="twitter-tweet"><p lang="ja" dir="ltr">iphone Homekit制作中 <a href="https://t.co/Xi40UKEKPk">pic.twitter.com/Xi40UKEKPk</a></p>&mdash; utaca.rich (@RichUtaka) <a href="https://twitter.com/RichUtaka/status/1140125187024646146?ref_src=twsrc%5Etfw">June 16, 2019</a></blockquote> <script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>
# では、スウィッチをOn/Offするサンプルを作ってみよう。
```home.py
#!/usr/bin/python3
'''
simple switch sample rich.hirata
'''
import logging,signal
from pyhap.accessory import Accessory, Bridge
from pyhap.accessory_driver import AccessoryDriver
from pyhap.const import (CATEGORY_SWITCH)
logging.basicConfig(level=logging.INFO, format="[%(module)s] %(message)s")
class SW(Accessory):
     category = CATEGORY_SWITCH
     def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        serv_tv = self.add_preload_service('Switch')
        self.char_on = serv_tv.configure_char('On', setter_callback=self.sw)
     def sw(self,value):
        logging.info("スウィッチ: %s", value)
def get_bridge(driver):
    bridge = Bridge(driver, 'Bridge')
    bridge.add_accessory(SW(driver, 'スウィッチ'))
    return bridge
driver = AccessoryDriver(port=51826, persist_file='home.state')
driver.add_accessory(accessory=get_bridge(driver))
signal.signal(signal.SIGTERM, driver.signal_handler)
driver.start()

```
#「スイッチオン」いうと
```
[home] スウィッチ: True
[hap_server] 192.168.1.104 - "PUT /characteristics HTTP/1.1" 204 -
```
「スイッチオフ」いうと

```
[home] スウィッチ: False
[hap_server] 192.168.1.104 - "PUT /characteristics HTTP/1.1" 204 -
```

# class SW の def swを書き直すと実際の応用となる。

![image.png](https://qiita-image-store.s3.ap-northeast-1.amazonaws.com/0/274715/4237da9e-1ac0-4999-9844-c65b61f1d962.png)

# デバックするとき再度登録をし直す場合、home.pyのディレクトリにあるhome.stateを削除するとQRCODEの再読み込みから行われる。

# 次回Raspberry PI編をお楽しみに!
# 「いいね」してね!

#[Souce program  https://github.com/yutakahirata/HAP-python.git](https://github.com/yutakahirata/HAP-python.git)