홈어시스턴트용 커스텀 컴포넌트 작성

21031 단어 python

This is a dummy component which integrates with binary sensor, lock, sensor and switch platforms for demonstrating the development of custom components used in Home Assistant.



개발


  • 다음 URL에 설명된 대로 개발 환경을 설정합니다.
  • https://developers.home-assistant.io/docs/development_environment/
  • 다음 명령을 실행하여 통합을 위한 스켈레톤 코드를 생성합니다.
  • python3 -m script.scaffold integration
    대화식 Q&A 세션이 시작됩니다. 완료되면 스켈레톤 코드를 생성합니다.

       What is the domain?
       > dummy_garage
    
       What is the name of your integration?
       > Dummy Garage
    
       What is your GitHub handle?
       > @adafycheng
    
       What PyPI package and version do you depend on? Leave blank for none.
       >
    
       How will your integration gather data?
    
       Valid values are assumed_state, calculated, cloud_polling, cloud_push, local_polling, local_push
    
       More info @ https://developers.home-assistant.io/docs/creating_integration_manifest#iot-class
    
       > local_polling
    
       Does Home Assistant need the user to authenticate to control the device/service? (yes/no) [yes]
       > no
    
       Is the device/service discoverable on the local network? (yes/no) [no]
       > no
    
       Is this a helper integration? (yes/no) [no]
       > yes
    
       Can the user authenticate the device using OAuth2? (yes/no) [no]
       > no
    
       Scaffolding integration for the dummy_garage integration...
       Writing tests/components/dummy_garage/__init__.py
       Writing homeassistant/components/dummy_garage/const.py
       Writing homeassistant/components/dummy_garage/manifest.json
       Writing homeassistant/components/dummy_garage/__init__.py
       Updating dummy_garage manifest: {'codeowners': ['@adafycheng'], 'iot_class': 'local_polling'}
    
       Scaffolding config_flow_helper for the dummy_garage integration...
       Writing homeassistant/components/dummy_garage/const.py
       Writing homeassistant/components/dummy_garage/__init__.py
       Writing homeassistant/components/dummy_garage/sensor.py
       Writing homeassistant/components/dummy_garage/config_flow.py
       Writing tests/components/dummy_garage/test_config_flow.py
       Writing tests/components/dummy_garage/test_init.py
       Updating dummy_garage manifest: {'config_flow': True}
       Updating dummy_garage strings: ['config', 'options']
    
       Running hassfest to pick up new information.
    
       Running gen_requirements_all to pick up new information.
    
       Running script/translations_develop to pick up new translation strings.
    
       **************************
    
       Integration code has been generated
    
       Added the following files:
       - homeassistant/components/dummy_garage/config_flow.py
       - homeassistant/components/dummy_garage/manifest.json
       - homeassistant/components/dummy_garage/const.py
       - homeassistant/components/dummy_garage/sensor.py
       - homeassistant/components/dummy_garage/__init__.py
    
       Added the following tests:
       - tests/components/dummy_garage/test_init.py
       - tests/components/dummy_garage/test_config_flow.py
    
       The next step is to look at the files and deal with all areas marked as TODO.
    


  • 이 통합에서는 구성별로 엔티티를 생성하므로 대부분의 코드in __init__.py를 지웁니다.
  • 각 플랫폼에 대해,

  • 나. configuration.yaml에서 입력을 가져오기 위해 PLATFORM_SCHEMA(필수 및 데이터 유형)를 정의합니다.

       import voluptuous as vol
    
       from homeassistant.components.sensor import (
           PLATFORM_SCHEMA,
           SensorDeviceClass,
           SensorEntity,
           SensorStateClass,
       )
    
       DEFAULT_NAME = "Dummy Garage - Sensor"
    
       PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
       {
           vol.Required(CONF_MAC): cv.string,
           vol.Optional(CONF_NAME, default=DEFAULT_NAME): cv.string,
       }
       )
    
    


    ii. 플랫폼이 설정될 때 호출되는 함수async_setup_platform를 추가합니다. 이 기능에서 엔터티가 생성되어 홈어시스턴트에 추가됩니다.

       async def async_setup_platform(
           hass: HomeAssistant,
           config: ConfigType,
           add_entities: AddEntitiesCallback,
           discovery_info: DiscoveryInfoType | None = None,
       ) -> None:
           """Set up the sensor platform."""
           name = config[CONF_NAME]
           mac_addr = config[CONF_MAC]
    
           add_entities([DummyGarageSensor(mac_addr, name)], True)
    


    iii. 플랫폼에 해당하는 Entity 클래스를 입력 매개변수로 사용하여 클래스를 생성합니다.
  • __init__ 함수는 클래스의 생성자입니다.
  • name 함수는 홈어시스턴트 웹 애플리케이션에 표시된 엔티티의 이름으로 반환됩니다.
  • unique_id 함수는 엔티티의 고유 ID로 반환됩니다. 입력된 MAC 주소를 고유 ID로 변환합니다.

  •    class DummyGarageSensor(SensorEntity):
           """Representation of a Sensor."""
    
           def __init__(self, mac, name) -> None:
               super().__init__()
               self._mac = mac
               self._name = name
               self._attr_name = name
               self._attr_native_unit_of_measurement = TEMP_CELSIUS
               self._attr_device_class = SensorDeviceClass.TEMPERATURE
               self._attr_state_class = SensorStateClass.MEASUREMENT
    
           @property
           def name(self) -> str:
               """Return the name of the switch."""
               return self._name
    
           @property
           def unique_id(self) -> str:
               """Return a unique, Home Assistant friendly identifier for this entity."""
               return self._mac.replace(":", "")
    
           def update(self) -> None:
               """Fetch new state data for the sensor.
    
               This is the only method that should fetch new data for Home Assistant.
               """
               self._attr_native_value = 23
    


    전개


  • homeassistant/components/dummy_garage/디렉토리를 Home Assistant Core/homeassistant/components/에 복사합니다.
  • config/configuration.yaml 파일에서 원하는 엔티티에 대한 구성을 추가합니다.

  •    binary_sensor:
       - platform: dummy_garage
         name: "Dummy Car Presence"
         mac: "12:34:12:34:12:34"
         device_class: "presence"
    
       lock:
       - platform: dummy_garage
         name: "Dummy Garage Lock"
         mac: "EF:EF:EF:EF:EF:EF"
    
       switch:
       - platform: dummy_garage
         name: "Dummy Garage Switch"
         mac: "AB:AB:AB:CD:CD:CD"
    
       sensor:
       - platform: dummy_garage
         name: "Dummy Temperature"
         mac: "56:34:12:90:78:56"
    



  • 테스트 목적으로 config/automations.yaml 파일에 차고 문을 열고 닫는 자동화를 추가하십시오. 이 예와 다른 경우 entity_id의 값을 변경해야 합니다.

    - id: open_garage
      alias: "Open Garage Door"
      trigger:
        - platform: time_pattern
          minutes: 5
        - platform: time_pattern
         minutes: 15
        - platform: time_pattern
          minutes: 25
        - platform: time_pattern
          minutes: 35
        - platform: time_pattern
          minutes: 45
        - platform: time_pattern
          minutes: 55
      action:
        - service: lock.unlock
          target:
            entity_id: lock.dummy_garage_lock
        - delay: 00:00:10
        - service: switch.turn_on
          target:
            entity_id: switch.dummy_garage_switch
    
    - id: close_garage
      alias: "Close Garage Door"
      trigger:
        - platform: time_pattern
          minutes: 10
        - platform: time_pattern
          minutes: 20
        - platform: time_pattern
          minutes: 30
        - platform: time_pattern
          minutes: 40
        - platform: time_pattern
          minutes: 50
        - platform: time_pattern
          minutes: 0
      action:
        - service: switch.turn_off
          target:
            entity_id: switch.dummy_garage_switch
        - delay: 00:00:10
        - service: lock.lock
          target:
            entity_id: lock.dummy_garage_lock
    

  • 홈어시스턴트 코어 시작:
  • hass -c config

    확인


  • 홈어시스턴트 웹 애플리케이션에 로그인합니다.


  • 엔티티가 생성되었는지 확인하십시오.


  • 개요 탭에서 엔티티를 추가합니다.
  • Garage Door 열기 작업을 트리거하고 도어 잠금 및 스위치 상태를 관찰합니다.


  • 차고 문 닫기 작업을 트리거하고 도어 잠금 및 스위치 상태를 관찰합니다.



  • 감사의 말



  • Set up Development Environment for Home Assistant .

  • Home Assistant Entities .

  • GitHub Source Code .
  • 좋은 웹페이지 즐겨찾기