Repository: rednblkx/HAP-ESPHome Branch: main Commit: 018b356129ed Files: 51 Total size: 312.7 KB Directory structure: gitextract_ncf8nb64/ ├── .github/ │ ├── ISSUE_TEMPLATE/ │ │ ├── bug_report.md │ │ └── feature_request.md │ └── workflows/ │ └── main.yml ├── .gitignore ├── .python-version ├── .vscode/ │ ├── c_cpp_properties.json │ └── settings.json ├── README.md ├── components/ │ ├── homekit/ │ │ ├── HAPAccessory.cpp │ │ ├── HAPAccessory.h │ │ ├── LICENSE │ │ ├── __init__.py │ │ ├── automation.cpp │ │ ├── automation.h │ │ ├── climate.hpp │ │ ├── const.h │ │ ├── fan.hpp │ │ ├── hap_entity.h │ │ ├── light.hpp │ │ ├── lock.cpp │ │ ├── lock.h │ │ ├── sensor.hpp │ │ └── switch.hpp │ ├── homekit_base/ │ │ ├── HAPRootComponent.cpp │ │ ├── HAPRootComponent.h │ │ ├── LICENSE │ │ ├── __init__.py │ │ └── button/ │ │ ├── __init__.py │ │ ├── factory_reset.cpp │ │ └── factory_reset.h │ ├── pn532/ │ │ ├── LICENSE │ │ ├── __init__.py │ │ ├── binary_sensor.py │ │ ├── pn532.cpp │ │ ├── pn532.h │ │ ├── pn532_mifare_classic.cpp │ │ └── pn532_mifare_ultralight.cpp │ └── pn532_spi/ │ ├── LICENSE │ ├── __init__.py │ ├── pn532_spi.cpp │ └── pn532_spi.h ├── fan-c3.yaml ├── homekey-test-c3.yaml ├── homekey-test-c6.yaml ├── homekey-test-esp32.yaml ├── homekey-test-s3.yaml ├── lights-c3.yaml ├── pyproject.toml ├── sensor-c3.yaml ├── switch-c3.yaml └── test.yaml ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/ISSUE_TEMPLATE/bug_report.md ================================================ --- name: Bug report about: Create a report to help us improve title: '' labels: bug assignees: rednblkx --- **Describe the bug** A clear and concise description of what the bug is. **To Reproduce** Steps to reproduce the behavior: 1. Go to '...' 2. Click on '....' 3. Scroll down to '....' 4. See error **Expected behavior** A clear and concise description of what you expected to happen. **Screenshots** If applicable, add screenshots to help explain your problem. **Additional context** - Device: [e.g. iPhone 12] - iOS version: [e.g. iOS 17.5] Add any other context about the problem here. ================================================ FILE: .github/ISSUE_TEMPLATE/feature_request.md ================================================ --- name: Feature request about: Suggest an idea for this project title: '' labels: enhancement assignees: rednblkx --- **Is your feature request related to a problem? Please describe.** A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] **Describe the solution you'd like** A clear and concise description of what you want to happen. **Additional context** Add any other context or screenshots about the feature request here. ================================================ FILE: .github/workflows/main.yml ================================================ # This is a basic workflow to help you get started with Actions name: CI # Controls when the action will run. Triggers the workflow on push or pull request # events but only for the master branch on: push: branches: [ main, dev ] paths: - 'components/**' - '.github/workflows/main.yml' - '*.yaml' - '*.yml' pull_request: branches: [ main, dev ] jobs: build: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v4 with: fetch-depth: 0 fetch-tags: true - uses: actions/cache@v4 with: path: | ~/.cache/pip ~/.platformio/.cache key: ${{ runner.os }}-esphome - uses: actions/setup-python@v5 with: python-version: '3.11' - name: Install PlatformIO Core run: pip install --upgrade platformio - name: Install ESPHome run: pip install esphome - name: Create dummy secrets.yml run: | touch secrets.yaml echo 'wifi_ssid: "ssid"' >> secrets.yaml echo 'wifi_password: "password"' >> secrets.yaml openssl rand 32 | base64 | xargs printf 'api_key: "%s"\n' >> secrets.yaml openssl rand 32 | base64 | xargs printf 'ota_password: "%s"\n' >> secrets.yaml - name: Compile test configuration run: esphome compile test.yaml ================================================ FILE: .gitignore ================================================ # Gitignore settings for ESPHome # This is an example and may include too much for your use-case. # You can modify this file to suit your needs. /.esphome/ /secrets.yaml __pycache__ ================================================ FILE: .python-version ================================================ 3.12 ================================================ FILE: .vscode/c_cpp_properties.json ================================================ { "configurations": [ { "name": "PlatformIO", "includePath": [ "${workspaceFolder}/.esphome/build/custom_components_test/src", "${workspaceFolder}/.esphome/build/custom_components_test/src/esphome/core", "${workspaceFolder}/.esphome/build/custom_components_test/.piolibdeps/custom_components_test/ArduinoJson/src", "${workspaceFolder}/.esphome/build/custom_components_test/components/esp_hap_apple_profiles/include", "${workspaceFolder}/.esphome/build/custom_components_test/components/esp_hap_core/include", "${workspaceFolder}/.esphome/build/custom_components_test/components/jsoncons/include", "${workspaceFolder}/.esphome/build/custom_components_test/src", "${workspaceFolder}/.esphome/build/custom_components_test/.piolibdeps/custom_components_test/ArduinoJson/src", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/riscv/include", "${workspaceFolder}/.esphome/build/custom_components_test/.pioenvs/custom_components_test/config", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/newlib/platform_include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/freertos/FreeRTOS-Kernel/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/freertos/FreeRTOS-Kernel/portable/riscv/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/freertos/esp_additions/include/freertos", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/freertos/esp_additions/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/freertos/esp_additions/arch/riscv/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_hw_support/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_hw_support/include/soc", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_hw_support/include/soc/esp32c3", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_hw_support/port/esp32c3", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_hw_support/port/esp32c3/private_include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/heap/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/log/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/soc/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/soc/esp32c3", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/soc/esp32c3/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/hal/esp32c3/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/hal/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/hal/platform_port/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_rom/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_rom/include/esp32c3", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_rom/esp32c3", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_common/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_system/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_system/port/soc", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_system/port/include/riscv", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_system/port/include/private", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/lwip/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/lwip/include/apps", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/lwip/include/apps/sntp", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/lwip/lwip/src/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/lwip/port/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/lwip/port/freertos/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/lwip/port/esp32xx/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/lwip/port/esp32xx/include/arch", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_ringbuf/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/efuse/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/efuse/esp32c3/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_timer/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/deprecated", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/analog_comparator/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/dac/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/gpio/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/gptimer/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/i2c/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/i2s/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/ledc/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/mcpwm/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/parlio/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/pcnt/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/rmt/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/sdio_slave/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/sdmmc/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/sigma_delta/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/spi/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/temperature_sensor/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/touch_sensor/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/twai/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/uart/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/driver/usb_serial_jtag/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_pm/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/mbedtls/port/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/mbedtls/mbedtls/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/mbedtls/mbedtls/library", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/mbedtls/esp_crt_bundle/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/mbedtls/mbedtls/3rdparty/everest/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/mbedtls/mbedtls/3rdparty/p256-m", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/mbedtls/mbedtls/3rdparty/p256-m/p256-m", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_app_format/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/bootloader_support/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/bootloader_support/bootloader_flash/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_partition/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/app_update/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_mm/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/spi_flash/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/pthread/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/app_trace/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_event/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/nvs_flash/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_phy/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_phy/esp32c3/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/vfs/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_netif/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/wpa_supplicant/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/wpa_supplicant/port/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/wpa_supplicant/esp_supplicant/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_coex/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_wifi/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_wifi/wifi_apps/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/unity/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/unity/unity/src", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/cmock/CMock/src", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/console", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/http_parser", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp-tls", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp-tls/esp-tls-crypto", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_adc/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_adc/interface", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_adc/esp32c3/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_adc/deprecated/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_eth/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_gdbstub/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_hid/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/tcp_transport/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_http_client/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_http_server/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_https_ota/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_psram/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_lcd/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_lcd/interface", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/protobuf-c/protobuf-c", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/protocomm/include/common", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/protocomm/include/security", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/protocomm/include/transports", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/esp_local_ctrl/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/espcoredump/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/espcoredump/include/port/riscv", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/wear_levelling/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/sdmmc/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/fatfs/diskio", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/fatfs/vfs", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/fatfs/src", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/idf_test/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/idf_test/include/esp32c3", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/ieee802154/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/json/cJSON", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/mqtt/esp-mqtt/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/spiffs/include", "${HOME}/.platformio/packages/framework-espidf@3.50102.240122/components/wifi_provisioning/include", "${workspaceFolder}/.esphome/build/custom_components_test/components/libsodium/libsodium/src/libsodium/include", "${workspaceFolder}/.esphome/build/custom_components_test/components/libsodium/port_include", "${workspaceFolder}/.esphome/build/custom_components_test/components/hkdf-sha/include", "${workspaceFolder}/.esphome/build/custom_components_test/components/mu_srp", "${workspaceFolder}/.esphome/build/custom_components_test/components/json_generator/include", "${workspaceFolder}/.esphome/build/custom_components_test/components/jsmn/include", "${workspaceFolder}/.esphome/build/custom_components_test/components/json_parser/include", "${workspaceFolder}/.esphome/build/custom_components_test/components/mdns/include", "${workspaceFolder}/.esphome/build/custom_components_test/components/esp_hap_platform/include", "${workspaceFolder}/.esphome/build/custom_components_test/components/esp_hap_core/include", "${workspaceFolder}/.esphome/build/custom_components_test/components/esp_hap_apple_profiles/include", "${workspaceFolder}/.esphome/build/custom_components_test/components/esp_hap_extras/include", "${workspaceFolder}/.esphome/build/custom_components_test/components/HK-HomeKit-Lib/include", "${workspaceFolder}/.esphome/build/custom_components_test/components/HK-HomeKit-Lib/include", "${workspaceFolder}/.esphome/build/custom_components_test/managed_components/espressif__cbor/port/include" ], "browse": { "limitSymbolsToIncludedHeaders": false, "path": [ "${workspaceFolder}/.esphome/build/custom_components_test/src", "${workspaceFolder}/.esphome/build/custom_components_test/src/esphome", "${workspaceFolder}/.esphome/build/custom_components_test/src/esphome/core", "${HOME}/Desktop/esphome", "${workspaceFolder}/.esphome/build/custom_components_test/components", "${HOME}/.platformio/packages/framework-espidf/components", "${workspaceFolder}/.esphome/build/custom_components_test/.piolibdeps/custom_components_test" ] }, "cStandard": "gnu99", "cppStandard": "gnu++23", "compilerPath": "${HOME}/.platformio/packages/toolchain-riscv32-esp@12.2.0+20230208/bin/riscv32-esp-elf-gcc", "compilerArgs": [ "-Os", "-Wall", "-Werror=all", "-Wextra", "-Wno-enum-conversion", "-Wno-error=deprecated-declarations", "-Wno-error=unused-but-set-variable", "-Wno-error=unused-function", "-Wno-error=unused-variable", "-Wno-sign-compare", "-Wno-unused-parameter", "-fdata-sections", "-ffunction-sections", "-fmacro-prefix-map=${HOME}/.platformio/packages/framework-espidf@3.50102.240122=/IDF", "-fmacro-prefix-map=${workspaceFolder}/.esphome/build/custom_components_test=.", "-fno-exceptions", "-fno-jump-tables", "-fno-rtti", "-fno-tree-switch-conversion", "-freorder-blocks", "-fstrict-volatile-bitfields", "-gdwarf-4", "-ggdb", "-march=rv32imc_zicsr_zifencei", "-nostartfiles", "-std=gnu++2b", "-Wno-nonnull-compare", "-Wno-sign-compare", "-Wno-unused-but-set-variable", "-Wno-unused-variable", "-fno-exceptions" ] } ], "version": 4 } ================================================ FILE: .vscode/settings.json ================================================ { "esphome.dashboardUri": "localhost:6052", "clangd.arguments": [ "--enable-config" ], "clangd.fallbackFlags": [ "-I${workspaceFolder}/esphome", "--include-dir=${workspaceFolder}/esphome" ], "files.associations": { "*.js": "javascript", "functional": "cpp", "*.in": "c", "version.h": "c", "crypto_sign.h": "c", "*.tcc": "c", "crypto_hash_sha512.h": "c", "crypto_scalarmult_curve25519.h": "c", "random.h": "c", "array": "cpp", "string": "cpp", "string_view": "cpp", "config.h": "c", "atomic": "cpp", "bit": "cpp", "bitset": "cpp", "cctype": "cpp", "chrono": "cpp", "cinttypes": "cpp", "clocale": "cpp", "cmath": "cpp", "compare": "cpp", "concepts": "cpp", "condition_variable": "cpp", "cstdarg": "cpp", "cstddef": "cpp", "cstdint": "cpp", "cstdio": "cpp", "cstdlib": "cpp", "cstring": "cpp", "ctime": "cpp", "cwchar": "cpp", "cwctype": "cpp", "deque": "cpp", "forward_list": "cpp", "list": "cpp", "map": "cpp", "set": "cpp", "unordered_map": "cpp", "vector": "cpp", "exception": "cpp", "algorithm": "cpp", "iterator": "cpp", "memory": "cpp", "memory_resource": "cpp", "numeric": "cpp", "random": "cpp", "ratio": "cpp", "regex": "cpp", "system_error": "cpp", "tuple": "cpp", "type_traits": "cpp", "utility": "cpp", "initializer_list": "cpp", "iomanip": "cpp", "iosfwd": "cpp", "iostream": "cpp", "istream": "cpp", "limits": "cpp", "mutex": "cpp", "new": "cpp", "numbers": "cpp", "ostream": "cpp", "semaphore": "cpp", "sstream": "cpp", "stdexcept": "cpp", "stop_token": "cpp", "streambuf": "cpp", "thread": "cpp", "typeinfo": "cpp", "tlv8.h": "c", "bignum.h": "c", "sdkconfig.h": "c", "ranges": "cpp", "span": "cpp", "valarray": "cpp", "any": "cpp", "charconv": "cpp", "codecvt": "cpp", "optional": "cpp", "variant": "cpp", "crypto_auth_hmacsha512256.h": "c", "complex": "cpp", "netfwd": "cpp", "fstream": "cpp", "future": "cpp", "esp_hap_database.h": "c" } } ================================================ FILE: README.md ================================================ # HAP-ESPHome [![CI](https://github.com/rednblkx/HAP-ESPHome/actions/workflows/main.yml/badge.svg?branch=main)](https://github.com/rednblkx/HAP-ESPHome/actions/workflows/main.yml) [![C# Discord](https://badgen.net/discord/members/VWpZ5YyUcm?icon=discord)](https://discord.com/invite/VWpZ5YyUcm) HomeKit support for ESPHome-based ESP32 devices ## 1. Introduction This project aims to bring HomeKit support to ESP32 devices flashed with an ESPHome configuration that will enable you to directly control the device from the Apple Home app without anything else inbetween. Components can be imported like any other external compoents as follows: ```yaml external_components: source: github://rednblkx/HAP-ESPHome@main refresh: 0s ``` See [Components](#3-components) for documentation. > [!IMPORTANT] > Some components like Bluetooth for example, take up a lot of space in RAM and will result in error during compiling, something like `section '.iram0.text' will not fit in region 'iram0_0_seg'` will be present in the log. ### Supported entity types | Type | Attributes | Notes | |--------|-----------------------------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------| | Light | On/Off, Brightness, RGB, Color Temperature | | | Lock | Lock/Unlock | Homekey can be enabled but only the `pn532_spi` component is supported to be used with it | | Switch | On/Off | | | Sensor | Temperature, Humidity, Illuminance, Air Quality, CO2, CO, PM10, PM2.5 | `device_class` property has to be declared with the sensor type as per HASS [docs](https://www.home-assistant.io/integrations/sensor/#device-class) | | Fan | On/Off | | ## 2. Prerequisites The components were designed to be used with ESP-IDF version 5. See below required configuration that needs to be present in your yaml file. ```yaml esp32: board: framework: type: esp-idf sdkconfig_options: CONFIG_COMPILER_OPTIMIZATION_SIZE: y CONFIG_LWIP_MAX_SOCKETS: "16" CONFIG_MBEDTLS_HKDF_C: y ``` `CONFIG_COMPILER_OPTIMIZATION_SIZE` is not functionally required but assists with the size optimization since a full configuration will take a lot of space. ## 3. Components Project is divided into two different components, `homekit_base` which handles the bridge logic and `homekit` that handles the actual accessory logic (lights, switches, etc.). This repository also includes the `pn532` and `pn532_spi` components which are just slightly modified versions of the official ones from the ESPHome repository to suit HomeKey needs with no extra options added to them nor deleted, however, it's not guaranteed to be kept up to date with upstream changes. > [!TIP] > For configuration examples, you can see the `.yaml` files in this repository, e.g. [lights-c3.yaml](lights-c3.yaml) ### 3.1. `homekit_base` > [!NOTE] > The `homekit_base` component does not have to included in the configuration unless you are interested in one of the properties listed below as it is automatically loaded by the `homekit` component #### 3.1.1. Configuration variables: - **port** (Optional, int): The port HomeKit should listen to - **meta** (Optional): Bridge information - **name** (Optional, string): Name of the bridge accessory - **model** (Optional, string): Model name for the bridge accessory - **manufacturer** (Optional, string): Manufacturer name for the bridge accessory - **serial_number** (Optional, string): Serial number for the bridge accessory - **fw_rev** (Optional, string): Firmware revision for the bridge accessory - **setup_code** (Optional, string): The HomeKit setup code in the format `XXX-XX-XXX` - **Default:** `159-35-728` - **setup_id** (Optional, string): The Setup ID that can be used to generate a pairing QR Code - **Default:** `ES32` Configuration Example: ```yaml homekit_base: meta: name: "PRIMO" manufacturer: "AMICI&CO" model: "IMPERIUM" serial_number: "16161616" fw_rev: "0.16.2" setup_code: '159-35-728' setup_id: "ES32" ``` #### 3.1.2. Factory reset `homekit_base` can also be used as a platform component for the button component to reset the HomeKit pairings, see example below: ```yaml button: - platform: homekit_base factory_reset: name: "Reset HomeKit pairings" ``` This will function like any regular button in ESPHome and therefore will be visible in the Web Interface and HASS. ### 3.2. `homekit` This is what handles the accessory logic like syncing states between HomeKit and ESPHome and basic information (name, attributes, etc.). #### 3.2.1. Configuration variables: - **light** (Optional): Array of Light entities - **id** (Required, [Light](https://esphome.io/components/light/)) - Id of the light entity - **meta** (Optional): Accessory information - **name** (Optional, string): Name of the accessory, defaults to name of the entity - **model** (Optional, string): Model name for the accessory - **manufacturer** (Optional, string): Manufacturer name for the accessory - **serial_number** (Optional, string): Serial number for the accessory, defaults to internal object id - **fw_rev** (Optional, string): Firmware revision for the accessory Example: ```yaml homekit: light: - id: desk_light meta: name: "RGB Light" manufacturer: "AMICI&CO" model: "IGNIS" serial_number: "42424242" fw_rev: "0.16.2" ``` - **lock** (Optional): Array of Lock Entities - **id** (Required, [Lock](https://esphome.io/components/lock/)) - Id of the lock entity - **meta** (Optional): Accessory information - **name** (Optional, string): Name of the accessory, defaults to name of the entity - **model** (Optional, string): Model name for the accessory - **manufacturer** (Optional, string): Manufacturer name for the accessory - **serial_number** (Optional, string): Serial number for the accessory, defaults to internal object id - **fw_rev** (Optional, string): Firmware revision for the accessory - **nfc_id** (Optional, [PN532](https://esphome.io/components/binary_sensor/pn532.html#over-spi)): Id of the `pn532_spi` component, used for the HomeKey functionality - **on_hk_success** (Optional, [Action](https://esphome.io/automations/actions)): Action to be executed when Homekey is successfully authenticated - **on_hk_fail** (Optional, [Action](https://esphome.io/automations/actions)): Action to be executed when Homekey fails to authenticate - **hk_hw_finish**(Optional, string): Color of the Homekey card from the predefined `BLACK`, `SILVER`, `GOLD` and `TAN`, defaults to `BLACK` Example: ```yaml homekit: lock: - id: this_lock meta: manufacturer: "AMICI&CO" model: "IMPEDIO" serial_number: "42424242" fw_rev: "0.16.2" nfc_id: nfc_spi_module on_hk_success: lambda: |- ESP_LOGI("HEREHERE", "IssuerID: %s", x.c_str()); ESP_LOGI("HEREHERE", "EndpointID: %s", y.c_str()); id(test_light).toggle().perform(); on_hk_fail: lambda: |- ESP_LOGI("GSDGSGS", "IT FAILED :("); hk_hw_finish: "SILVER" ``` - **sensor** - **id** (Required, [Sensor](https://esphome.io/components/sensor/)): Id of the sensor entity - **meta** (Optional): Accessory information - **name** (Optional, string): Name of the accessory, defaults to name of the entity - **model** (Optional, string): Model name for the accessory - **manufacturer** (Optional, string): Manufacturer name for the accessory - **serial_number** (Optional, string): Serial number for the accessory, defaults to internal object id - **fw_rev** (Optional, string): Firmware revision for the accessory Example: ```yaml homekit: sensor: - id: my_sensor meta: manufacturer: "AMICI&CO" model: "VARIO" serial_number: "42424242" fw_rev: "0.16.2" ``` - **switch** - **id** (Required, [Switch](https://esphome.io/components/switch/)): Id of the switch entity - **meta** (Optional): Accessory information - **name** (Optional, string): Name of the accessory, defaults to name of the entity - **model** (Optional, string): Model name for the accessory - **manufacturer** (Optional, string): Manufacturer name for the accessory - **serial_number** (Optional, string): Serial number for the accessory, defaults to internal object id - **fw_rev** (Optional, string): Firmware revision for the accessory Example: ```yaml switch: - id: some_switch meta: manufacturer: "AMICI&CO" model: "TRANSMUTO" serial_number: "42424242" fw_rev: "0.16.2" ``` - **fan** (Optional): Array of Fan Entities - **id** (Required, [Fan](https://esphome.io/components/fan/)): Id of the fan entity - **meta** (Optional): Accessory information - **name** (Optional, string): Name of the accessory, defaults to name of the entity - **model** (Optional, string): Model name for the accessory - **manufacturer** (Optional, string): Manufacturer name for the accessory - **serial_number** (Optional, string): Serial number for the accessory, defaults to internal object id - **fw_rev** (Optional, string): Firmware revision for the accessory Example: ```yaml homekit: fan: - id: my_fan meta: name: "Living Room Fan" manufacturer: "AMICI&CO" model: "VENTUS" serial_number: "42424242" fw_rev: "0.16.2" ``` ## 4. HomeKey > [!NOTE] > If you notice an error in the logs that says `Can't decode message length.`, you can safely ignore it. The project is using a "hijacked" version of the official pn532 component and the message is part of the normal operation of it since it's meant to be used with "regular" NFC Tags. ### 4.1 Disclaimer > [!WARNING] > The functionality of Homekey is entirely based on reverse engineering since HomeKit specs stopped being available to hobbyists and therefore the entire functionality or parts of it might or might not break in the future and/or lack official features or any internal implementations. ### 4.2 Setup > [!IMPORTANT] > Only PN532 over SPI(`pn532_spi` component) is supported at the moment due to required modifications that haven't been ported to other protocols or chips > [!NOTE] > For quick reactions and to avoid issues, don't raise the `update_interval` over 500ms ```yaml spi: clk_pin: 4 miso_pin: 5 mosi_pin: 6 pn532_spi: id: nfc_spi_module cs_pin: 7 update_interval: 100ms homekit: lock: - id: nfc_id: nfc_spi_module ``` ## Support & Contributing If you wish to contribute with a feature or a fix, a PR will be most welcomed The best way to support the work that i do is to :star: the repository but you can also buy me a :coffee: if you wish by sponsoring me on [GitHub](https://github.com/sponsors/rednblkx). You can also choose to join the [Discord server](https://discord.com/invite/VWpZ5YyUcm) where you will find a helpful and lovely community. ## Credits [@kormax](https://github.com/kormax) - Homekey NFC protocol [research](https://github.com/kormax/apple-home-key), [ECP](https://github.com/kormax/apple-enhanced-contactless-polling) and [PoC](https://github.com/kormax/apple-home-key-reader) [@kupa22](https://github.com/kupa22) - [Documenting](https://github.com/kupa22/apple-homekey) the HAP part for the Homekey [ESPHome](https://github.com/esphome/esphome) - ESPHome and the PN532 module [Espressif](https://github.com/espressif) - [esp-homekit-sdk](https://github.com/espressif/esp-homekit-sdk) ## License This repository consists of multiple licenses since it contains some components([pn532](https://github.com/rednblkx/HAP-ESPHome/tree/main/components/pn532) and [pn532_spi](https://github.com/rednblkx/HAP-ESPHome/tree/main/components/pn532_spi)) originally from the [ESPHome](https://github.com/esphome/esphome) repository, please consult the LICENSE file in each folder in the [components](https://github.com/rednblkx/HAP-ESPHome/tree/main/components) folder. ================================================ FILE: components/homekit/HAPAccessory.cpp ================================================ #include "HAPAccessory.h" namespace esphome { namespace homekit { HAPAccessory::HAPAccessory() { } void HAPAccessory::setup() { #ifdef USE_LIGHT for (const auto v : lights) { v->setup(); } #endif #ifdef USE_LOCK for (const auto &v : locks) { #ifdef USE_HOMEKEY if (nfc) { v->set_hk_hw_finish(hkHwFinish); v->set_nfc_ctx(nfc); } #endif v->setup(); } #endif #ifdef USE_FAN for (const auto v : fans) { v->setup(); } #endif #ifdef USE_SWITCH for (const auto v : switches) { v->setup(); } #endif #ifdef USE_SENSOR for (const auto v : sensors) { v->setup(); } #endif #ifdef USE_CLIMATE for (const auto v : climates) { v->setup(); } #endif } void HAPAccessory::dump_config() { #ifdef USE_LOCK ESP_LOGCONFIG(TAG, "Lock HK Entities: %d", locks.size()); #endif #ifdef USE_LIGHT ESP_LOGCONFIG(TAG, "Light HK Entities: %d", lights.size()); #endif #ifdef USE_SENSOR ESP_LOGCONFIG(TAG, "Sensor HK Entities: %d", sensors.size()); #endif #ifdef USE_FAN ESP_LOGCONFIG(TAG, "Fan HK Entities: %d", fans.size()); #endif #ifdef USE_SWITCH ESP_LOGCONFIG(TAG, "Switch HK Entities: %d", switches.size()); #endif } #ifdef USE_LIGHT LightEntity* HAPAccessory::add_light(light::LightState* lightPtr) { lights.push_back(new LightEntity(lightPtr)); return lights.back(); } #endif #ifdef USE_LOCK LockEntity* HAPAccessory::add_lock(lock::Lock* lockPtr) { locks.push_back(new LockEntity(lockPtr)); return locks.back(); } #endif #ifdef USE_HOMEKEY void HAPAccessory::set_nfc_ctx(pn532::PN532* nfcCtx) { nfc = nfcCtx; } void HAPAccessory::set_hk_hw_finish(HKFinish color) { hkHwFinish = color; } #endif #ifdef USE_FAN FanEntity* HAPAccessory::add_fan(fan::Fan* fanPtr) { fans.push_back(new FanEntity(fanPtr)); return fans.back(); } #endif #ifdef USE_SWITCH SwitchEntity* HAPAccessory::add_switch(switch_::Switch* switchPtr) { switches.push_back(new SwitchEntity(switchPtr)); return switches.back(); } #endif #ifdef USE_SENSOR SensorEntity* HAPAccessory::add_sensor(sensor::Sensor* sensorPtr, TemperatureUnits units) { sensors.push_back(new SensorEntity(sensorPtr)); return sensors.back(); } #endif #ifdef USE_CLIMATE ClimateEntity* HAPAccessory::add_climate(climate::Climate* climatePtr) { climates.push_back(new ClimateEntity(climatePtr)); return climates.back(); } #endif } } ================================================ FILE: components/homekit/HAPAccessory.h ================================================ #pragma once #include #include #include #include #include "const.h" #ifdef USE_LIGHT #include "light.hpp" #endif #ifdef USE_LOCK #include "lock.h" #endif #ifdef USE_FAN #include "fan.hpp" #endif #ifdef USE_SWITCH #include "switch.hpp" #endif #ifdef USE_SENSOR #include "sensor.hpp" #endif #ifdef USE_CLIMATE #include "climate.hpp" #endif namespace esphome { namespace homekit { class HAPAccessory : public Component { public: const char* TAG = "HAPAccessory"; HAPAccessory(); float get_setup_priority() const override { return setup_priority::AFTER_WIFI + 1; } void setup() override; void dump_config() override; #ifdef USE_HOMEKEY pn532::PN532* nfc = nullptr; HKFinish hkHwFinish = SILVER; #endif #ifdef USE_LIGHT std::vector lights; LightEntity* add_light(light::LightState* lightPtr); #endif #ifdef USE_LOCK std::vector locks; LockEntity* add_lock(lock::Lock* lockPtr); #endif #ifdef USE_HOMEKEY void set_nfc_ctx(pn532::PN532* nfcCtx); void set_hk_hw_finish(HKFinish color); #endif #ifdef USE_FAN std::vector fans; FanEntity* add_fan(fan::Fan* fanPtr); #endif #ifdef USE_SWITCH std::vector switches; SwitchEntity* add_switch(switch_::Switch* switchPtr); #endif #ifdef USE_SENSOR std::vector sensors; SensorEntity* add_sensor(sensor::Sensor* sensorPtr, TemperatureUnits units); #endif #ifdef USE_CLIMATE std::vector climates; ClimateEntity* add_climate(climate::Climate* sensorPtr); #endif }; } } ================================================ FILE: components/homekit/LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: components/homekit/__init__.py ================================================ from esphome import automation import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import mdns, wifi, light, lock, sensor, switch, climate, pn532, fan from esphome.const import PLATFORM_ESP32, CONF_ID, CONF_TRIGGER_ID from esphome.core import ID, Lambda from esphome.components.esp32 import add_idf_component from .. import homekit_base AUTO_LOAD = ["homekit_base"] DEPENDENCIES = ['esp32', 'network', 'homekit_base'] CODEOWNERS = ["@rednblkx"] homekit_ns = homekit_base.homekit_ns HAPRootComponent = homekit_base.HAPRootComponent TemperatureUnits = homekit_ns.enum("TemperatureUnits") AInfo = homekit_ns.enum("AInfo") HKFinish = homekit_ns.enum("HKFinish") HAPAccessory = homekit_ns.class_('HAPAccessory', cg.Component) LightEntity = homekit_ns.class_('LightEntity') SensorEntity = homekit_ns.class_('SensorEntity') SwitchEntity = homekit_ns.class_('SwitchEntity') LockEntity = homekit_ns.class_('LockEntity') FanEntity = homekit_ns.class_('FanEntity') OnHkSuccessTrigger = homekit_ns.class_( "HKAuthTrigger", automation.Trigger.template(cg.std_string, cg.std_string) ) OnHkFailTrigger = homekit_ns.class_( "HKFailTrigger", automation.Trigger.template() ) CONF_IDENTIFY_LAMBDA = "identify_fn" TEMP_UNITS = { "CELSIUS": TemperatureUnits.CELSIUS, "FAHRENHEIT": TemperatureUnits.FAHRENHEIT } ACC_INFO = { "name": AInfo.NAME, "model": AInfo.MODEL, "manufacturer": AInfo.MANUFACTURER, "serial_number": AInfo.SN, "fw_rev": AInfo.FW_REV, } HK_HW_FINISH = { "TAN": HKFinish.TAN, "GOLD": HKFinish.GOLD, "SILVER": HKFinish.SILVER, "BLACK": HKFinish.BLACK } ACCESSORY_INFORMATION = { cv.Optional(i): cv.string for i in ACC_INFO } CONFIG_SCHEMA = cv.All(cv.Schema({ cv.GenerateID() : cv.declare_id(HAPAccessory), cv.Optional("light"): cv.ensure_list({cv.Required(CONF_ID): cv.use_id(light.LightState), cv.Optional("meta") : ACCESSORY_INFORMATION}), cv.Optional("lock"): cv.ensure_list({cv.Required(CONF_ID): cv.use_id(lock.Lock), cv.Optional("nfc_id") : cv.use_id(pn532.PN532), cv.Optional("on_hk_success"): automation.validate_automation( { cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(OnHkSuccessTrigger), } ), cv.Optional("on_hk_fail"): automation.validate_automation( { cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(OnHkFailTrigger), } ), cv.Optional("hk_hw_finish", default="BLACK") : cv.enum(HK_HW_FINISH), cv.Optional("meta") : ACCESSORY_INFORMATION }), cv.Optional("sensor"): cv.ensure_list({cv.Required(CONF_ID): cv.use_id(sensor.Sensor), cv.Optional("temp_units", default="CELSIUS") : cv.enum(TEMP_UNITS), cv.Optional("meta") : ACCESSORY_INFORMATION}), cv.Optional("fan"): cv.ensure_list({cv.Required(CONF_ID): cv.use_id(fan.Fan), cv.Optional("meta") : ACCESSORY_INFORMATION}), cv.Optional("switch"): cv.ensure_list({cv.Required(CONF_ID): cv.use_id(switch.Switch), cv.Optional("meta") : ACCESSORY_INFORMATION}), cv.Optional("climate"): cv.ensure_list({cv.Required(CONF_ID): cv.use_id(climate.Climate), cv.Optional("meta") : ACCESSORY_INFORMATION}), }).extend(cv.COMPONENT_SCHEMA), cv.only_on([PLATFORM_ESP32]), cv.only_with_esp_idf) async def to_code(config): var = cg.new_Pvariable(config[CONF_ID]) await cg.register_component(var, config) if 'light' in config: for l in config["light"]: light_entity = cg.Pvariable(ID(f"{l['id'].id}_hk_light_entity", type=LightEntity), var.add_light(await cg.get_variable(l['id']))) if "meta" in l: info_temp = [] for m in l["meta"]: info_temp.append([ACC_INFO[m], l["meta"][m]]) cg.add(light_entity.setInfo(info_temp)) if 'sensor' in config: for l in config["sensor"]: sensor_entity = cg.Pvariable(ID(f"{l['id'].id}_hk_sensor_entity", type=SensorEntity), var.add_sensor(await cg.get_variable(l['id']), l['temp_units'])) if "meta" in l: info_temp = [] for m in l["meta"]: info_temp.append([ACC_INFO[m], l["meta"][m]]) cg.add(sensor_entity.setInfo(info_temp)) if 'lock' in config: for l in config["lock"]: lock_entity = cg.Pvariable(ID(f"{l['id'].id}_hk_lock_entity", type=LockEntity), var.add_lock(await cg.get_variable(l['id']))) if "nfc_id" in l: nfc = await cg.get_variable(l["nfc_id"]) cg.add(var.set_nfc_ctx(nfc)) cg.add(var.set_hk_hw_finish(l["hk_hw_finish"])) cg.add_define("USE_HOMEKEY") add_idf_component( name="HK-HomeKit-Lib", repo="https://github.com/rednblkx/HK-HomeKit-Lib.git", ref="a4af730ec54536e1ba931413206fec89ce2b6c4f" ) for conf in l.get("on_hk_success", []): trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID]) cg.add(lock_entity.register_onhk_trigger(trigger)) await automation.build_automation(trigger, [(cg.std_string, "x"), (cg.std_string, "y")], conf) for conf in l.get("on_hk_fail", []): trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID]) cg.add(lock_entity.register_onhkfail_trigger(trigger)) await automation.build_automation(trigger, [], conf) if "meta" in l: info_temp = [] for m in l["meta"]: info_temp.append([ACC_INFO[m], l["meta"][m]]) cg.add(lock_entity.setInfo(info_temp)) if "fan" in config: for l in config["fan"]: fan_entity = cg.Pvariable(ID(f"{l['id'].id}_hk_fan_entity", type=FanEntity), var.add_fan(await cg.get_variable(l['id']))) if "meta" in l: info_temp = [] for m in l["meta"]: info_temp.append([ACC_INFO[m], l["meta"][m]]) cg.add(fan_entity.setInfo(info_temp)) if "switch" in config: for l in config["switch"]: switch_entity = cg.Pvariable(ID(f"{l['id'].id}_hk_switch_entity", type=SwitchEntity), var.add_switch(await cg.get_variable(l['id']))) if "meta" in l: info_temp = [] for m in l["meta"]: info_temp.append([ACC_INFO[m], l["meta"][m]]) cg.add(switch_entity.setInfo(info_temp)) if "climate" in config: for l in config["climate"]: climate_entity = cg.Pvariable(ID(f"{l['id'].id}_hk_climate_entity", type=ClimateEntity), var.add_climate(await cg.get_variable(l['id']))) if "meta" in l: info_temp = [] for m in l["meta"]: info_temp.append([ACC_INFO[m], l["meta"][m]]) cg.add(climate_entity.setInfo(info_temp)) ================================================ FILE: components/homekit/automation.cpp ================================================ #include "automation.h" namespace esphome { namespace homekit { void HKAuthTrigger::process(std::string issuerId, std::string endpointId) { this->trigger(issuerId, endpointId); } void HKFailTrigger::process() { this->trigger(); } } } ================================================ FILE: components/homekit/automation.h ================================================ #pragma once #include "esphome/core/component.h" #include "esphome/core/automation.h" namespace esphome { namespace homekit { class HKAuthTrigger : public Trigger { public: void process(std::string issuerId, std::string endpointId); }; class HKFailTrigger : public Trigger<> { public: void process(); }; } } ================================================ FILE: components/homekit/climate.hpp ================================================ #pragma once #include #ifdef USE_CLIMATE #include #include #include #include #include #include "const.h" #include "hap_entity.h" namespace esphome { namespace homekit { class ClimateEntity : public HAPEntity { private: static constexpr const char* TAG = "ClimateEntity"; climate::Climate* climatePtr; static void on_climate_update(climate::Climate& obj) { ESP_LOGI(TAG, "%s Mode: %d Action: %d CTemp: %.2f TTemp: %.2f CHum: %.2f THum: %.2f", obj.get_name().c_str(), obj.mode, obj.action, obj.current_temperature, obj.target_temperature, obj.current_humidity, obj.target_humidity); hap_acc_t* acc = hap_acc_get_by_aid(hap_get_unique_aid(std::to_string(obj.get_object_id_hash()).c_str())); if (acc) { hap_serv_t* hs = hap_acc_get_serv_by_uuid(acc, HAP_SERV_UUID_THERMOSTAT); hap_char_t* current_mode = hap_serv_get_char_by_uuid(hs, HAP_CHAR_UUID_CURRENT_HEATING_COOLING_STATE); hap_char_t* target_mode = hap_serv_get_char_by_uuid(hs, HAP_CHAR_UUID_TARGET_HEATING_COOLING_STATE); hap_char_t* current_temp = hap_serv_get_char_by_uuid(hs, HAP_CHAR_UUID_CURRENT_TEMPERATURE); hap_char_t* current_humidity = hap_serv_get_char_by_uuid(hs, HAP_CHAR_UUID_CURRENT_RELATIVE_HUMIDITY); hap_char_t* target_temp = hap_serv_get_char_by_uuid(hs, HAP_CHAR_UUID_TARGET_TEMPERATURE); hap_char_t* target_humidity = hap_serv_get_char_by_uuid(hs, HAP_CHAR_UUID_TARGET_RELATIVE_HUMIDITY); hap_val_t state; state.i = obj.action; hap_char_update_val(current_mode, &state); state.i = obj.mode; hap_char_update_val(target_mode, &state); state.f = obj.current_temperature; hap_char_update_val(current_temp, &state); state.f = obj.target_temperature; hap_char_update_val(target_temp, &state); state.f = obj.target_humidity; hap_char_update_val(target_humidity, &state); state.f = obj.current_humidity; hap_char_update_val(current_humidity, &state); } return; } static int climate_read(hap_char_t* hc, hap_status_t* status_code, void* serv_priv, void* read_priv) { std::string key((char*)serv_priv); ESP_LOGI(TAG, "Write called for Accessory %s", (char*)serv_priv); climate::Climate* obj = App.get_climate_by_key(static_cast(std::stoul(key))); int i, ret = HAP_SUCCESS; const char* type = hap_char_get_type_uuid(hc); if (!strcmp(type, HAP_CHAR_UUID_CURRENT_HEATING_COOLING_STATE)) { hap_val_t state; switch (obj->action) { case climate::CLIMATE_ACTION_OFF: state.i = 0; hap_char_update_val(hc, &state); break; case climate::CLIMATE_ACTION_HEATING: state.i = 1; hap_char_update_val(hc, &state); break; case climate::CLIMATE_ACTION_COOLING: state.i = 2; hap_char_update_val(hc, &state); break; default: state.i = 0; hap_char_update_val(hc, &state); break; } } else if (!strcmp(type, HAP_CHAR_UUID_CURRENT_TEMPERATURE)) { hap_val_t state; state.f = obj->current_temperature; hap_char_update_val(hc, &state); } else if (!strcmp(type, HAP_CHAR_UUID_CURRENT_RELATIVE_HUMIDITY)) { hap_val_t state; state.f = obj->current_humidity; hap_char_update_val(hc, &state); } return ret; } static int climate_write(hap_write_data_t write_data[], int count, void* serv_priv, void* write_priv) { std::string key((char*)serv_priv); ESP_LOGI(TAG, "Write called for Accessory %s", (char*)serv_priv); climate::Climate* obj = App.get_climate_by_key(static_cast(std::stoul(key))); int i, ret = HAP_SUCCESS; hap_write_data_t* write; for (i = 0; i < count; i++) { write = &write_data[i]; const char* type = hap_char_get_type_uuid(write->hc); if (!strcmp(type, HAP_CHAR_UUID_TARGET_HEATING_COOLING_STATE)) { switch (write->val.i) { case 0: obj->make_call().set_mode(climate::ClimateMode::CLIMATE_MODE_OFF).perform(); break; case 1: obj->make_call().set_mode(climate::ClimateMode::CLIMATE_MODE_HEAT).perform(); break; case 2: obj->make_call().set_mode(climate::ClimateMode::CLIMATE_MODE_COOL).perform(); break; case 3: obj->make_call().set_mode(climate::ClimateMode::CLIMATE_MODE_AUTO).perform(); break; default: break; } } else if (!strcmp(type, HAP_CHAR_UUID_TARGET_TEMPERATURE)) { obj->make_call().set_target_temperature(write->val.f).perform(); } else if (!strcmp(type, HAP_CHAR_UUID_TARGET_RELATIVE_HUMIDITY)) { obj->make_call().set_target_humidity(write->val.f).perform(); } } return ret; } static int acc_identify(hap_acc_t* ha) { ESP_LOGI(TAG, "Accessory identified"); return HAP_SUCCESS; } public: ClimateEntity(climate::Climate* climatePtr) : HAPEntity({{MODEL, "HAP-CLIMATE"}}), climatePtr(climatePtr) {} void setup(TemperatureUnits units = CELSIUS) { hap_acc_cfg_t acc_cfg = { .model = "ESP-CLIMATE", .manufacturer = "rednblkx", .fw_rev = "0.1.0", .hw_rev = NULL, .pv = "1.1.0", .cid = HAP_CID_BRIDGE, .identify_routine = acc_identify, }; hap_acc_t* accessory = nullptr; hap_serv_t* service = nullptr; hap_serv_t* service_fan = nullptr; std::string accessory_name = this->climatePtr->get_name(); acc_cfg.name = accessory_name.data(); acc_cfg.serial_num = std::to_string(this->climatePtr->get_object_id_hash()).data(); climate::ClimateTraits climateTraits = this->climatePtr->get_traits(); climate::ClimateMode climateMode = this->climatePtr->mode; climate::ClimateAction climateAction = this->climatePtr->action; uint8_t current_mode = 0; uint8_t target_mode = 0; switch (climateAction) { case climate::ClimateAction::CLIMATE_ACTION_OFF: current_mode = 0; break; case climate::ClimateAction::CLIMATE_ACTION_HEATING: current_mode = 1; break; case climate::ClimateAction::CLIMATE_ACTION_COOLING: current_mode = 2; break; default: current_mode = 0; break; } switch (climateMode) { case climate::ClimateMode::CLIMATE_MODE_OFF: target_mode = 0; break; case climate::ClimateMode::CLIMATE_MODE_HEAT: target_mode = 1; break; case climate::ClimateMode::CLIMATE_MODE_COOL: target_mode = 2; break; case climate::ClimateMode::CLIMATE_MODE_AUTO: target_mode = 3; break; default: break; } ESP_LOGI(TAG, "CTemp: %.2f TTemp: %.2f CHum: %.2f THum: %.2f", this->climatePtr->current_temperature, this->climatePtr->target_temperature, this->climatePtr->current_humidity, this->climatePtr->target_humidity); service = hap_serv_thermostat_create(current_mode, target_mode, this->climatePtr->current_temperature, this->climatePtr->target_temperature, units); if (climateTraits.get_supports_current_humidity()) { hap_serv_add_char(service, hap_char_current_relative_humidity_create(this->climatePtr->current_humidity)); } if (climateTraits.get_supports_target_humidity()) { hap_serv_add_char(service, hap_char_target_relative_humidity_create(this->climatePtr->target_humidity)); } // service_fan = hap_serv_fan_v2_create(!this->climatePtr->fan_mode ? 1 : 0); // hap_char_swing_mode_create(); // hap_serv_link_serv() if (service) { /* Create accessory object */ accessory = hap_acc_create(&acc_cfg); ESP_LOGI(TAG, "ID HASH: %lu", this->climatePtr->get_object_id_hash()); hap_serv_set_priv(service, strdup(std::to_string(this->climatePtr->get_object_id_hash()).c_str())); /* Set the write callback for the service */ hap_serv_set_write_cb(service, climate_write); hap_serv_set_read_cb(service, climate_read); /* Add the Lock Service to the Accessory Object */ hap_acc_add_serv(accessory, service); /* Add the Accessory to the HomeKit Database */ hap_add_bridged_accessory(accessory, hap_get_unique_aid(std::to_string(this->climatePtr->get_object_id_hash()).c_str())); } } }; } } #endif ================================================ FILE: components/homekit/const.h ================================================ #pragma once namespace esphome { namespace homekit { enum TemperatureUnits { CELSIUS, FAHRENHEIT }; enum HKFinish { TAN, GOLD, SILVER, BLACK }; enum AInfo { NAME, MODEL, SN, MANUFACTURER, FW_REV }; } } ================================================ FILE: components/homekit/fan.hpp ================================================ #pragma once #include #ifdef USE_FAN #include #include #include #include #include "hap_entity.h" namespace esphome { namespace homekit { class FanEntity : public HAPEntity { private: static constexpr const char* TAG = "FanEntity"; fan::Fan* fanPtr; static int fanwrite(hap_write_data_t write_data[], int count, void* serv_priv, void* write_priv) { fan::Fan* fanPtr = (fan::Fan*)serv_priv; ESP_LOGD(TAG, "Write called for Accessory %s (%s)", std::to_string(fanPtr->get_object_id_hash()).c_str(), fanPtr->get_name().c_str()); int i, ret = HAP_SUCCESS; hap_write_data_t* write; for (i = 0; i < count; i++) { write = &write_data[i]; if (!strcmp(hap_char_get_type_uuid(write->hc), HAP_CHAR_UUID_ON)) { ESP_LOGD(TAG, "Received Write for fan '%s' -> %s", fanPtr->get_name().c_str(), write->val.b ? "On" : "Off"); ESP_LOGD(TAG, "[STATE] CURRENT STATE: %d", fanPtr->state); fanPtr->make_call().set_state(write->val.b).perform(); hap_char_update_val(write->hc, &(write->val)); *(write->status) = HAP_STATUS_SUCCESS; } else { *(write->status) = HAP_STATUS_RES_ABSENT; } } return ret; } static void on_fanupdate(fan::Fan* obj) { ESP_LOGD(TAG, "%s state: %s", obj->get_name().c_str(), ONOFF(obj->state)); hap_acc_t* acc = hap_acc_get_by_aid(hap_get_unique_aid(std::to_string(obj->get_object_id_hash()).c_str())); if (acc) { hap_serv_t* hs = hap_acc_get_serv_by_uuid(acc, HAP_SERV_UUID_FAN); hap_char_t* on_char = hap_serv_get_char_by_uuid(hs, HAP_CHAR_UUID_ON); hap_val_t state; state.b = !!obj->state; hap_char_update_val(on_char, &state); } } static int acc_identify(hap_acc_t* ha) { ESP_LOGI(TAG, "Accessory identified"); return HAP_SUCCESS; } public: FanEntity(fan::Fan* fanPtr) : HAPEntity({{MODEL, "HAP-FAN"}}), fanPtr(fanPtr) {} void setup() { hap_acc_cfg_t acc_cfg = { .model = strdup(accessory_info[MODEL]), .manufacturer = strdup(accessory_info[MANUFACTURER]), .fw_rev = strdup(accessory_info[FW_REV]), .hw_rev = NULL, .pv = strdup("1.1.0"), .cid = HAP_CID_BRIDGE, .identify_routine = acc_identify, }; hap_acc_t* accessory = nullptr; hap_serv_t* service = nullptr; std::string accessory_name = fanPtr->get_name(); if (accessory_info[NAME] == NULL) { acc_cfg.name = strdup(accessory_name.c_str()); } else { acc_cfg.name = strdup(accessory_info[NAME]); } if (accessory_info[SN] == NULL) { acc_cfg.serial_num = strdup(std::to_string(fanPtr->get_object_id_hash()).c_str()); } else { acc_cfg.serial_num = strdup(accessory_info[SN]); } /* Create accessory object */ accessory = hap_acc_create(&acc_cfg); /* Create the fan Service. */ service = hap_serv_fan_create(fanPtr->state); ESP_LOGD(TAG, "ID HASH: %lu", fanPtr->get_object_id_hash()); hap_serv_set_priv(service, fanPtr); /* Set the write callback for the service */ hap_serv_set_write_cb(service, fanwrite); /* Add the Fan Service to the Accessory Object */ hap_acc_add_serv(accessory, service); /* Add the Accessory to the HomeKit Database */ hap_add_bridged_accessory(accessory, hap_get_unique_aid(std::to_string(fanPtr->get_object_id_hash()).c_str())); if (!fanPtr->is_internal()) fanPtr->add_on_state_callback([this]() { FanEntity::on_fanupdate(fanPtr); }); ESP_LOGI(TAG, "Fan '%s' linked to HomeKit", accessory_name.c_str()); } }; } } #endif ================================================ FILE: components/homekit/hap_entity.h ================================================ #pragma once #include "const.h" #include "esphome/core/entity_base.h" #include #include namespace esphome { namespace homekit { class HAPEntity { private: static constexpr const char* TAG = "HAPEntity"; protected: std::map accessory_info = { {NAME, NULL}, {MODEL, "HAP-GENERIC"}, {SN, NULL}, {MANUFACTURER, "rednblkx"}, {FW_REV, "0.1"} }; public: HAPEntity(){ } HAPEntity(std::map accessory_info) { setInfo(accessory_info); } void setInfo(std::map info) { for (const auto& pair : info) { if (this->accessory_info.find(pair.first) != this->accessory_info.end()) { this->accessory_info[pair.first] = pair.second; } } } void virtual setup() { ESP_LOGI(TAG, "Uninmplemented!"); } }; } } ================================================ FILE: components/homekit/light.hpp ================================================ #include #ifdef USE_LIGHT #pragma once #include #include #include #include #include "hap_entity.h" namespace esphome { namespace homekit { class LightEntity : public HAPEntity, public light::LightTargetStateReachedListener { private: static constexpr const char* TAG = "LightEntity"; light::LightState* lightPtr; static int light_write(hap_write_data_t write_data[], int count, void* serv_priv, void* write_priv) { light::LightState* lightPtr = (light::LightState*)serv_priv; ESP_LOGD(TAG, "Write called for Accessory %s (%s)", std::to_string(lightPtr->get_object_id_hash()).c_str(), lightPtr->get_name().c_str()); int i, ret = HAP_SUCCESS; hap_write_data_t* write; for (i = 0; i < count; i++) { write = &write_data[i]; if (!strcmp(hap_char_get_type_uuid(write->hc), HAP_CHAR_UUID_ON)) { ESP_LOGD(TAG, "Received Write for Light '%s' state: %s", lightPtr->get_name().c_str(), write->val.b ? "On" : "Off"); ESP_LOGD(TAG, "[STATE] CURRENT STATE: %d", (int)(lightPtr->current_values.get_state() * 100)); write->val.b ? lightPtr->turn_on().set_save(true).perform() : lightPtr->turn_off().set_save(true).perform(); hap_char_update_val(write->hc, &(write->val)); *(write->status) = HAP_STATUS_SUCCESS; } if (!strcmp(hap_char_get_type_uuid(write->hc), HAP_CHAR_UUID_BRIGHTNESS)) { ESP_LOGD(TAG, "Received Write for Light '%s' Level: %d", lightPtr->get_name().c_str(), write->val.i); ESP_LOGD(TAG, "[LEVEL] CURRENT BRIGHTNESS: %d", (int)(lightPtr->current_values.get_brightness() * 100)); ESP_LOGD(TAG, "TARGET BRIGHTNESS: %d", (int)write->val.i); lightPtr->make_call().set_save(true).set_brightness((float)(write->val.i) / 100).perform(); hap_char_update_val(write->hc, &(write->val)); *(write->status) = HAP_STATUS_SUCCESS; } if (!strcmp(hap_char_get_type_uuid(write->hc), HAP_CHAR_UUID_HUE)) { ESP_LOGD(TAG, "Received Write for Light '%s' Hue: %.2f", lightPtr->get_name().c_str(), write->val.f); int hue = 0; float saturation = 0; float colorValue = 0; rgb_to_hsv(lightPtr->remote_values.get_red(), lightPtr->remote_values.get_green(), lightPtr->remote_values.get_blue(), hue, saturation, colorValue); ESP_LOGD(TAG, "[HUE] CURRENT Hue: %d, Saturation: %.2f, Value: %.2f", hue, saturation, colorValue); ESP_LOGD(TAG, "TARGET HUE: %.2f", write->val.f); float tR = 0; float tG = 0; float tB = 0; hsv_to_rgb(write->val.f, saturation, colorValue, tR, tG, tB); ESP_LOGD(TAG, "TARGET RGB: %.2f %.2f %.2f", tR, tG, tB); lightPtr->make_call().set_rgb(tR, tG, tB).set_save(true).perform(); hap_char_update_val(write->hc, &(write->val)); *(write->status) = HAP_STATUS_SUCCESS; } if (!strcmp(hap_char_get_type_uuid(write->hc), HAP_CHAR_UUID_SATURATION)) { ESP_LOGD(TAG, "Received Write for Light '%s' Saturation: %.2f", lightPtr->get_name().c_str(), write->val.f); int hue = 0; float saturation = 0; float colorValue = 0; rgb_to_hsv(lightPtr->remote_values.get_red(), lightPtr->remote_values.get_green(), lightPtr->remote_values.get_blue(), hue, saturation, colorValue); ESP_LOGD(TAG, "[SATURATION] CURRENT Hue: %d, Saturation: %.2f, Value: %.2f", hue, saturation, colorValue); ESP_LOGD(TAG, "TARGET SATURATION: %.2f", write->val.f); float tR = 0; float tG = 0; float tB = 0; hsv_to_rgb(hue, write->val.f / 100, colorValue, tR, tG, tB); ESP_LOGD(TAG, "TARGET RGB: %.2f %.2f %.2f", tR, tG, tB); lightPtr->make_call().set_rgb(tR, tG, tB).set_save(true).perform(); hap_char_update_val(write->hc, &(write->val)); *(write->status) = HAP_STATUS_SUCCESS; } if (!strcmp(hap_char_get_type_uuid(write->hc), HAP_CHAR_UUID_COLOR_TEMPERATURE)) { ESP_LOGD(TAG, "Received Write for Light '%s' Level: %d", lightPtr->get_name().c_str(), write->val.i); ESP_LOGD(TAG, "[LEVEL] CURRENT COLOR TEMPERATURE(mired): %.2f", lightPtr->current_values.get_color_temperature()); ESP_LOGD(TAG, "TARGET COLOR TEMPERATURE(mired): %lu", write->val.u); lightPtr->make_call().set_color_temperature(write->val.u).set_save(true).perform(); hap_char_update_val(write->hc, &(write->val)); *(write->status) = HAP_STATUS_SUCCESS; } else { *(write->status) = HAP_STATUS_RES_ABSENT; } } return ret; } void on_light_target_state_reached() override { on_light_update(lightPtr); } static void on_light_update(light::LightState* obj) { bool rgb = obj->current_values.get_color_mode() & light::ColorCapability::RGB; bool level = obj->get_traits().supports_color_capability(light::ColorCapability::BRIGHTNESS); bool temperature = obj->current_values.get_color_mode() & (light::ColorCapability::COLOR_TEMPERATURE | light::ColorCapability::COLD_WARM_WHITE); if (rgb) { ESP_LOGD(TAG, "%s RED: %.2f, GREEN: %.2f, BLUE: %.2f", obj->get_name().c_str(), obj->current_values.get_red(), obj->current_values.get_green(), obj->current_values.get_blue()); } ESP_LOGD(TAG, "%s state: %d brightness: %d", obj->get_name().c_str(), (int)(obj->current_values.get_state() * 100), (int)(obj->current_values.get_brightness() * 100)); hap_acc_t* acc = hap_acc_get_by_aid(hap_get_unique_aid(std::to_string(obj->get_object_id_hash()).c_str())); if (acc) { hap_serv_t* hs = hap_acc_get_serv_by_uuid(acc, HAP_SERV_UUID_LIGHTBULB); hap_char_t* on_char = hap_serv_get_char_by_uuid(hs, HAP_CHAR_UUID_ON); hap_val_t state; state.b = obj->current_values.get_state(); hap_char_update_val(on_char, &state); if (level) { hap_char_t* level_char = hap_serv_get_char_by_uuid(hs, HAP_CHAR_UUID_BRIGHTNESS); hap_val_t level; level.i = (int)(obj->current_values.get_brightness() * 100); hap_char_update_val(level_char, &level); } if (rgb) { hap_char_t* hue_char = hap_serv_get_char_by_uuid(hs, HAP_CHAR_UUID_HUE); hap_char_t* saturation_char = hap_serv_get_char_by_uuid(hs, HAP_CHAR_UUID_SATURATION); hap_val_t hue; hap_val_t saturation; int cHue = 0; float cSaturation = 0; float colorValue = 0; rgb_to_hsv(obj->current_values.get_red(), obj->current_values.get_green(), obj->current_values.get_blue(), cHue, cSaturation, colorValue); hue.f = cHue; saturation.f = cSaturation * 100; hap_char_update_val(hue_char, &hue); hap_char_update_val(saturation_char, &saturation); } if (temperature) { hap_char_t* temp_char = hap_serv_get_char_by_uuid(hs, HAP_CHAR_UUID_COLOR_TEMPERATURE); hap_val_t temp; temp.u = obj->current_values.get_color_temperature(); hap_char_update_val(temp_char, &temp); } } } static int acc_identify(hap_acc_t* ha) { ESP_LOGI(TAG, "Accessory identified"); return HAP_SUCCESS; } public: LightEntity(light::LightState* lightPtr) : HAPEntity({{MODEL, "HAP-LIGHT"}}), lightPtr(lightPtr) {} void setup() { hap_acc_cfg_t acc_cfg = { .model = strdup(accessory_info[MODEL]), .manufacturer = strdup(accessory_info[MANUFACTURER]), .fw_rev = strdup(accessory_info[FW_REV]), .hw_rev = NULL, .pv = strdup("1.1.0"), .cid = HAP_CID_BRIDGE, .identify_routine = acc_identify, }; hap_acc_t* accessory = nullptr; hap_serv_t* service = nullptr; std::string accessory_name = lightPtr->get_name(); if (accessory_info[NAME] == NULL) { acc_cfg.name = strdup(accessory_name.c_str()); } else { acc_cfg.name = strdup(accessory_info[NAME]); } if (accessory_info[SN] == NULL) { acc_cfg.serial_num = strdup(std::to_string(lightPtr->get_object_id_hash()).c_str()); } else { acc_cfg.serial_num = strdup(accessory_info[SN]); } accessory = hap_acc_create(&acc_cfg); int hue = 0; float saturation = 0; float colorValue = 0; rgb_to_hsv(lightPtr->current_values.get_red(), lightPtr->current_values.get_green(), lightPtr->current_values.get_blue(), hue, saturation, colorValue); service = hap_serv_lightbulb_create(lightPtr->current_values.get_state()); hap_serv_add_char(service, hap_char_name_create(accessory_name.data())); if (lightPtr->get_traits().supports_color_capability(light::ColorCapability::BRIGHTNESS)) { hap_serv_add_char(service, hap_char_brightness_create(lightPtr->current_values.get_brightness() * 100)); } if (lightPtr->get_traits().supports_color_capability(light::ColorCapability::RGB)) { hap_serv_add_char(service, hap_char_hue_create(hue)); hap_serv_add_char(service, hap_char_saturation_create(saturation * 100)); } if (lightPtr->get_traits().supports_color_capability(light::ColorCapability::COLOR_TEMPERATURE) || lightPtr->get_traits().supports_color_capability(light::ColorCapability::COLD_WARM_WHITE)) { hap_serv_add_char(service, hap_char_color_temperature_create(lightPtr->current_values.get_color_temperature())); } ESP_LOGD(TAG, "ID HASH: %lu", lightPtr->get_object_id_hash()); hap_serv_set_priv(service, lightPtr); /* Set the write callback for the service */ hap_serv_set_write_cb(service, light_write); /* Add the Light Service to the Accessory Object */ hap_acc_add_serv(accessory, service); /* Add the Accessory to the HomeKit Database */ hap_add_bridged_accessory(accessory, hap_get_unique_aid(std::to_string(lightPtr->get_object_id_hash()).c_str())); if (!lightPtr->is_internal()) lightPtr->add_target_state_reached_listener(this); ESP_LOGI(TAG, "Light '%s' linked to HomeKit", accessory_name.c_str()); } }; } } #endif ================================================ FILE: components/homekit/lock.cpp ================================================ #include #ifdef USE_LOCK #include "lock.h" namespace esphome { namespace homekit { #ifdef USE_HOMEKEY readerData_t LockEntity::readerData; nvs_handle LockEntity::savedHKdata; pn532::PN532 *LockEntity::nfc_ctx; int LockEntity::nfcAccess_write(hap_write_data_t write_data[], int count, void *serv_priv, void *write_priv) { LockEntity *parent = (LockEntity *)serv_priv; LOG(I, "PROVISIONED READER KEY: %s", hk_utils::bufToHexString(parent->readerData.reader_sk.data(), parent->readerData.reader_sk.size(), true) .c_str()); LOG(I, "READER PUBLIC KEY: %s", hk_utils::bufToHexString(parent->readerData.reader_pk.data(), parent->readerData.reader_pk.size(), true) .c_str()); LOG(I, "READER GROUP IDENTIFIER: %s", hk_utils::bufToHexString(parent->readerData.reader_gid.data(), parent->readerData.reader_gid.size(), true) .c_str()); LOG(I, "READER UNIQUE IDENTIFIER: %s", hk_utils::bufToHexString(parent->readerData.reader_id.data(), parent->readerData.reader_id.size(), true) .c_str()); int i, ret = HAP_SUCCESS; hap_write_data_t *write; for (i = 0; i < count; i++) { write = &write_data[i]; /* Setting a default error value */ *(write->status) = HAP_STATUS_VAL_INVALID; if (!strcmp(hap_char_get_type_uuid(write->hc), HAP_CHAR_UUID_NFC_ACCESS_CONTROL_POINT)) { hap_tlv8_val_t buf = write->val.t; auto tlv_rx_data = std::vector(buf.buf, buf.buf + buf.buflen); ESP_LOGD( TAG, "TLV RX DATA: %s SIZE: %d", hk_utils::bufToHexString(tlv_rx_data.data(), tlv_rx_data.size(), true) .c_str(), tlv_rx_data.size()); HK_HomeKit ctx(parent->readerData, parent->savedHKdata, "READERDATA", tlv_rx_data); auto result = ctx.processResult(); memcpy(parent->tlv8_data, result.data(), result.size()); // if (strlen((const char*)readerData.reader_group_id) > 0) { // memcpy(ecpData + 8, readerData.reader_group_id, // sizeof(readerData.reader_group_id)); with_crc16(ecpData, 16, ecpData // + 16); // } hap_val_t new_val; new_val.t.buf = parent->tlv8_data; new_val.t.buflen = result.size(); hap_char_update_val(write->hc, &new_val); *(write->status) = HAP_STATUS_SUCCESS; } else { *(write->status) = HAP_STATUS_RES_ABSENT; } } return ret; } void LockEntity::hap_event_handler(hap_event_t event, void *data) { if (event == HAP_EVENT_CTRL_PAIRED) { char *ctrl_id = (char *)data; hap_ctrl_data_t *ctrl = hap_get_controller_data(ctrl_id); if (ctrl->valid) { std::vector id = hk_utils::getHashIdentifier(ctrl->info.ltpk, 32, true); ESP_LOG_BUFFER_HEX(TAG, ctrl->info.ltpk, 32); LOG(D, "Found allocated controller - Hash: %s", hk_utils::bufToHexString(id.data(), 8).c_str()); hkIssuer_t *foundIssuer = nullptr; for (auto &issuer : readerData.issuers) { if (!memcmp(issuer.issuer_id.data(), id.data(), 8)) { LOG(D, "Issuer %s already added, skipping", hk_utils::bufToHexString(issuer.issuer_id.data(), 8).c_str()); foundIssuer = &issuer; break; } } if (foundIssuer == nullptr) { LOG(D, "Adding new issuer - ID: %s", hk_utils::bufToHexString(id.data(), 8).c_str()); hkIssuer_t issuer; issuer.issuer_id = id; issuer.issuer_pk.insert(issuer.issuer_pk.begin(), ctrl->info.ltpk, ctrl->info.ltpk + 32); readerData.issuers.emplace_back(issuer); std::vector data = nlohmann::json::to_msgpack(readerData); esp_err_t set_nvs = nvs_set_blob(savedHKdata, "READERDATA", data.data(), data.size()); esp_err_t commit_nvs = nvs_commit(savedHKdata); LOG(I, "NVS SET STATUS: %s", esp_err_to_name(set_nvs)); LOG(I, "NVS COMMIT STATUS: %s", esp_err_to_name(commit_nvs)); } } } else if (event == HAP_EVENT_CTRL_UNPAIRED) { int ctrl_count = hap_get_paired_controller_count(); if (ctrl_count == 0) { readerData = {}; esp_err_t erase_nvs = nvs_erase_key(savedHKdata, "READERDATA"); esp_err_t commit_nvs = nvs_commit(savedHKdata); LOG(D, "*** NVS W STATUS"); LOG(D, "ERASE: %s", esp_err_to_name(erase_nvs)); LOG(D, "COMMIT: %s", esp_err_to_name(commit_nvs)); LOG(D, "*** NVS W STATUS"); } // else { // char* ctrl_id = (char*)data; // hap_ctrl_data_t* ctrl = hap_get_controller_data(ctrl_id); // if (ctrl->valid) { // // readerData.issuers.erase(std::remove_if(readerData.issuers.begin(), // readerData.issuers.end(), // // [ctrl](HomeKeyData_KeyIssuer x) { // // std::vector id = // hk_utils::getHashIdentifier(ctrl->info.ltpk, 32, true); // // LOG(D, "Found allocated controller - Hash: %s", // hk_utils::bufToHexString(id.data(), 8).c_str()); // // if (!memcmp(x.publicKey, id.data(), 8)) { // // return false; // // } // // LOG(D, "Issuer ID: %s - Associated controller was removed from // Home, erasing from reader data.", hk_utils::bufToHexString(x.issuerId, // 8).c_str()); // // return true; // // }), // // readerData.issuers.end()); // } // } } } #endif void LockEntity::on_lock_update(lock::Lock *obj) { ESP_LOGD("on_lock_update", "%s state: %s", obj->get_name().c_str(), lock_state_to_string(obj->state)); hap_acc_t *acc = hap_acc_get_by_aid( hap_get_unique_aid(std::to_string(obj->get_object_id_hash()).c_str())); hap_serv_t *hs = hap_acc_get_serv_by_uuid(acc, HAP_SERV_UUID_LOCK_MECHANISM); hap_char_t *current_state = hap_serv_get_char_by_uuid(hs, HAP_CHAR_UUID_LOCK_CURRENT_STATE); hap_char_t *target_state = hap_serv_get_char_by_uuid(hs, HAP_CHAR_UUID_LOCK_TARGET_STATE); hap_val_t c; hap_val_t t; if (obj->state == lock::LockState::LOCK_STATE_LOCKED || obj->state == lock::LockState::LOCK_STATE_UNLOCKED) { c.i = obj->state % 2; t.i = obj->state % 2; hap_char_update_val(current_state, &c); hap_char_update_val(target_state, &t); } else if (obj->state == lock::LockState::LOCK_STATE_LOCKING || obj->state == lock::LockState::LOCK_STATE_UNLOCKING) { t.i = (obj->state % 5) % 3; hap_char_update_val(target_state, &t); } else if (obj->state == lock::LockState::LOCK_STATE_JAMMED) { c.i = obj->state; hap_char_update_val(current_state, &c); } return; } int LockEntity::lock_write(hap_write_data_t write_data[], int count, void *serv_priv, void *write_priv) { lock::Lock *lockPtr = (lock::Lock *)serv_priv; ESP_LOGD("lock_write", "Write called for Accessory '%s'(%s)", lockPtr->get_name().c_str(), std::to_string(lockPtr->get_object_id_hash()).c_str()); int i, ret = HAP_SUCCESS; hap_write_data_t *write; for (i = 0; i < count; i++) { write = &write_data[i]; if (!strcmp(hap_char_get_type_uuid(write->hc), HAP_CHAR_UUID_LOCK_TARGET_STATE)) { ESP_LOGD("lock_write", "Target State req: %d", write->val.i); hap_char_update_val(write->hc, &(write->val)); hap_char_t *c = hap_serv_get_char_by_uuid( hap_char_get_parent(write->hc), HAP_CHAR_UUID_LOCK_CURRENT_STATE); ESP_LOGD("lock_write", "Current State: %d", hap_char_get_val(c)->i); hap_char_update_val(c, &(write->val)); write->val.i ? lockPtr->lock() : lockPtr->unlock(); *(write->status) = HAP_STATUS_SUCCESS; } else { *(write->status) = HAP_STATUS_RES_ABSENT; } } return ret; } int LockEntity::acc_identify(hap_acc_t *ha) { ESP_LOGI(TAG, "Accessory identified"); return HAP_SUCCESS; } // Function to calculate CRC16 void crc16a(unsigned char *data, unsigned int size, unsigned char *result) { unsigned short w_crc = 0x6363; for (unsigned int i = 0; i < size; ++i) { unsigned char byte = data[i]; byte = (byte ^ (w_crc & 0x00FF)); byte = ((byte ^ (byte << 4)) & 0xFF); w_crc = ((w_crc >> 8) ^ (byte << 8) ^ (byte << 3) ^ (byte >> 4)) & 0xFFFF; } result[0] = static_cast(w_crc & 0xFF); result[1] = static_cast((w_crc >> 8) & 0xFF); } // Function to append CRC16 to data void with_crc16(unsigned char *data, unsigned int size, unsigned char *result) { crc16a(data, size, result); } LockEntity::LockEntity(lock::Lock *lockPtr) : HAPEntity({{MODEL, "HAP-LOCK"}}), ptrToLock(lockPtr) { #ifdef USE_HOMEKEY ecpData.resize(18); auto t = nvs_open("HK_DATA", NVS_READWRITE, &savedHKdata); LOG(D, "NVS_OPEN: %s", esp_err_to_name(t)); size_t len = 0; if (!nvs_get_blob(savedHKdata, "READERDATA", NULL, &len)) { std::vector savedBuf(len); nvs_get_blob(savedHKdata, "READERDATA", savedBuf.data(), &len); LOG(D, "NVS DATA LENGTH: %d", len); ESP_LOG_BUFFER_HEX_LEVEL(TAG, savedBuf.data(), savedBuf.size(), ESP_LOG_VERBOSE); // try { nlohmann::json data = nlohmann::json::from_msgpack(savedBuf); data.get_to(readerData); // } // catch (const std::exception& e) { // std::cerr << e.what() << '\n'; // } } LOG(D, "PROVISIONED READER KEY: %s", hk_utils::bufToHexString(readerData.reader_sk.data(), readerData.reader_sk.size(), true) .c_str()); LOG(D, "READER PUBLIC KEY: %s", hk_utils::bufToHexString(readerData.reader_pk.data(), readerData.reader_pk.size(), true) .c_str()); LOG(D, "READER GROUP IDENTIFIER: %s", hk_utils::bufToHexString(readerData.reader_gid.data(), readerData.reader_gid.size(), true) .c_str()); LOG(D, "READER UNIQUE IDENTIFIER: %s", hk_utils::bufToHexString(readerData.reader_id.data(), readerData.reader_id.size(), true) .c_str()); LOG(D, "ISSUERS COUNT: %d", readerData.issuers.size()); memcpy(ecpData.data() + 8, readerData.reader_gid.data(), readerData.reader_gid.size()); with_crc16(ecpData.data(), 16, ecpData.data() + 16); #endif } std::string intToFinishString(HKFinish d) { switch (d) { case TAN: return "TAN"; break; case GOLD: return "GOLD"; break; case SILVER: return "SILVER"; break; case BLACK: return "BLACK"; break; default: return "UNKNOWN"; break; } } #ifdef USE_HOMEKEY std::string hex_representation(const std::vector &v) { std::string hex_tmp; for (auto x : v) { std::ostringstream oss; oss << std::hex << std::setw(2) << std::setfill('0') << (unsigned)x; hex_tmp += oss.str(); } return hex_tmp; } void LockEntity::register_onhk_trigger(HKAuthTrigger *trig) { triggers_onhk_.push_back(trig); } void LockEntity::register_onhkfail_trigger(HKFailTrigger *trig) { triggers_onhk_fail_.push_back(trig); } void LockEntity::set_hk_hw_finish(HKFinish color) { ESP_LOGI(TAG, "SELECTED HK FINISH: %s", intToFinishString(color).c_str()); hap_tlv8_val_t tlvData = {.buf = hk_color_vals[color].data(), .buflen = hk_color_vals[color].size()}; hkFinishTlvData = std::make_unique(tlvData); } void LockEntity::set_nfc_ctx(pn532::PN532 *ctx) { ctx->set_ecp_frame(ecpData); nfc_ctx = ctx; auto trigger = new nfc::NfcOnTagTrigger(); ctx->register_ontag_trigger(trigger); auto automation_id_3 = new Automation(trigger); auto lambdaaction_id_3 = new LambdaAction( [this, ctx](std::string x, nfc::NfcTag tag) -> void { std::function lambda = [=](uint8_t *send, uint8_t sendLen, uint8_t *res, uint16_t *resLen, bool ignoreLog) -> bool { auto data = ctx->inDataExchange(std::vector(send, send + sendLen)); data.erase(data.begin()); ESP_LOGD(TAG, "%s", format_hex_pretty(data).c_str()); memcpy(res, data.data(), data.size()); uint16_t t = data.size(); memcpy(resLen, &t, sizeof(uint16_t)); return true; }; auto versions = ctx->inDataExchange({0x00, 0xA4, 0x04, 0x00, 0x07, 0xA0, 0x00, 0x00, 0x08, 0x58, 0x01, 0x01, 0x0}); if (versions.size() > 0) { ESP_LOGD(TAG, "HK SUPPORTED VERSIONS: %s", format_hex_pretty(versions).c_str()); if (versions.data()[versions.size() - 2] == 0x90 && versions.data()[versions.size() - 1] == 0x0) { HKAuthenticationContext authCtx(lambda, readerData, savedHKdata); auto authResult = authCtx.authenticate(KeyFlow(kFlowFAST)); if (std::get<0>(authResult).size() > 0 && std::get<2>(authResult) != kFlowFailed) { for (auto &&t : triggers_onhk_) { t->process(hex_representation(std::get<0>(authResult)), hex_representation(std::get<1>(authResult))); } } else { for (auto &&t : triggers_onhk_fail_) { t->process(); } } } else { for (auto &&t : triggers_onhk_fail_) { t->process(); } ESP_LOGE(TAG, "Invalid response for HK"); } } else { ESP_LOGW(TAG, "Target probably not Homekey"); } }); automation_id_3->add_actions({lambdaaction_id_3}); } #endif void LockEntity::setup() { hap_acc_cfg_t acc_cfg = { .model = strdup(accessory_info[MODEL]), .manufacturer = strdup(accessory_info[MANUFACTURER]), .fw_rev = strdup(accessory_info[FW_REV]), .hw_rev = NULL, .pv = strdup("1.1.0"), .cid = HAP_CID_BRIDGE, .identify_routine = acc_identify, }; hap_acc_t *accessory = nullptr; hap_serv_t *lockMechanism = nullptr; std::string accessory_name = ptrToLock->get_name(); if (accessory_info[NAME] == NULL) { acc_cfg.name = strdup(accessory_name.c_str()); } else { acc_cfg.name = strdup(accessory_info[NAME]); } if (accessory_info[SN] == NULL) { acc_cfg.serial_num = strdup(std::to_string(ptrToLock->get_object_id_hash()).c_str()); } else { acc_cfg.serial_num = strdup(accessory_info[SN]); } #ifdef USE_HOMEKEY acc_cfg.hw_finish = hkFinishTlvData.get(); #endif accessory = hap_acc_create(&acc_cfg); lockMechanism = hap_serv_lock_mechanism_create(ptrToLock->state, ptrToLock->state); ESP_LOGD(TAG, "ID HASH: %lu", ptrToLock->get_object_id_hash()); hap_serv_set_priv(lockMechanism, ptrToLock); /* Set the write callback for the service */ hap_serv_set_write_cb(lockMechanism, lock_write); /* Add the Lock Service to the Accessory Object */ hap_acc_add_serv(accessory, lockMechanism); hap_acc_add_serv(accessory, hap_serv_lock_management_create(&management, strdup("1.0.0"))); #ifdef USE_HOMEKEY hap_register_event_handler(hap_event_handler); hap_serv_t *nfcAccess = nullptr; nfcAccess = hap_serv_nfc_access_create(0, &management, &nfcSupportedConf); hap_serv_set_priv(nfcAccess, this); hap_serv_set_write_cb(nfcAccess, nfcAccess_write); hap_acc_add_serv(accessory, nfcAccess); #endif /* Add the Accessory to the HomeKit Database */ hap_add_bridged_accessory( accessory, hap_get_unique_aid( std::to_string(ptrToLock->get_object_id_hash()).c_str())); if (!ptrToLock->is_internal()) #if ESPHOME_VERSION_CODE >= VERSION_CODE(2026, 4, 0) ptrToLock->add_on_state_callback([this](lock::LockState /* state */) { LockEntity::on_lock_update(ptrToLock); }); #else ptrToLock->add_on_state_callback( [this]() { LockEntity::on_lock_update(ptrToLock); }); #endif ESP_LOGI(TAG, "Lock '%s' linked to HomeKit", accessory_name.c_str()); } } // namespace homekit } // namespace esphome #endif ================================================ FILE: components/homekit/lock.h ================================================ #pragma once #include #ifdef USE_LOCK #include #include #include #include #include "hap_entity.h" #ifdef USE_HOMEKEY #include #include "const.h" #include #include #include #include #include "automation.h" #endif namespace esphome { namespace homekit { class LockEntity : public HAPEntity { private: static constexpr const char* TAG = "LockEntity"; lock::Lock* ptrToLock; hap_tlv8_val_t management = { .buf = 0, .buflen = 0 }; #ifdef USE_HOMEKEY static nvs_handle savedHKdata; static readerData_t readerData; uint8_t tlv8_data[128]; std::vector ecpData{ 0x6A, 0x2, 0xCB, 0x2, 0x6, 0x2, 0x11, 0x0 }; static pn532::PN532* nfc_ctx; std::vector nfcSupportedConfBuffer{ 0x01, 0x01, 0x10, 0x02, 0x01, 0x10 }; std::map> hk_color_vals = { {TAN, {0x01, 0x04, 0xce, 0xd5, 0xda, 0x00}}, {GOLD, {0x01, 0x04, 0xaa, 0xd6, 0xec, 0x00}}, {SILVER, {0x01, 0x04, 0xe3, 0xe3, 0xe3, 0x00}}, {BLACK, {0x01, 0x04, 0x00, 0x00, 0x00, 0x00}} }; std::unique_ptr hkFinishTlvData; hap_tlv8_val_t nfcSupportedConf = { .buf = nfcSupportedConfBuffer.data(), .buflen = nfcSupportedConfBuffer.size() }; std::vector triggers_onhk_; std::vector triggers_onhk_fail_; static int nfcAccess_write(hap_write_data_t write_data[], int count, void* serv_priv, void* write_priv); static void hap_event_handler(hap_event_t event, void* data); #endif static void on_lock_update(lock::Lock* obj); static int lock_write(hap_write_data_t write_data[], int count, void* serv_priv, void* write_priv); static int acc_identify(hap_acc_t* ha); public: LockEntity(lock::Lock* lockPtr); void setup(); #ifdef USE_HOMEKEY void set_nfc_ctx(pn532::PN532* ctx); void set_hk_hw_finish(HKFinish color); void register_onhk_trigger(HKAuthTrigger* trig); void register_onhkfail_trigger(HKFailTrigger* trig); #endif }; } } #endif ================================================ FILE: components/homekit/sensor.hpp ================================================ #pragma once #include #ifdef USE_SENSOR #include #include "const.h" #include #include #include #include #include "hap_entity.h" namespace esphome { namespace homekit { class SensorEntity : public HAPEntity { private: static constexpr const char* TAG = "SensorEntity"; sensor::Sensor* sensorPtr; static void on_sensor_update(sensor::Sensor* obj, float v) { ESP_LOGD(TAG, "%s value: %.2f", obj->get_name().c_str(), v); hap_acc_t* acc = hap_acc_get_by_aid(hap_get_unique_aid(std::to_string(obj->get_object_id_hash()).c_str())); if (acc) { hap_serv_t* hs = hap_serv_get_next(hap_acc_get_first_serv(acc)); if (hs) { hap_char_t* on_char = hap_serv_get_first_char(hs); ESP_LOGD(TAG, "HAP CURRENT VALUE - f:%.2f u:%lu", hap_char_get_val(on_char)->f, hap_char_get_val(on_char)->u); hap_val_t state; if (ceilf(v) == v) { state.u = v; } else { state.f = v; } hap_char_update_val(on_char, &state); } } return; } static int sensor_read(hap_char_t* hc, hap_status_t* status_code, void* serv_priv, void* read_priv) { if (serv_priv) { sensor::Sensor* sensorPtr = (sensor::Sensor*)serv_priv; ESP_LOGD(TAG, "Read called for Accessory %s (%s)", std::to_string(sensorPtr->get_object_id_hash()).c_str(), sensorPtr->get_name().c_str()); hap_val_t sensorValue; float v = sensorPtr->get_state(); if (ceilf(v) == v) { sensorValue.u = v; } else { sensorValue.f = v; } hap_char_update_val(hc, &sensorValue); return HAP_SUCCESS; } return HAP_FAIL; } static int acc_identify(hap_acc_t* ha) { ESP_LOGI(TAG, "Accessory identified"); return HAP_SUCCESS; } public: SensorEntity(sensor::Sensor* sensorPtr) : HAPEntity({{MODEL, "HAP-SENSOR"}}), sensorPtr(sensorPtr) {} void setup() { hap_serv_t* service = nullptr; std::string device_class = sensorPtr->get_device_class(); if (std::equal(device_class.begin(), device_class.end(), strdup("temperature"))) { service = hap_serv_temperature_sensor_create(sensorPtr->state); } else if (std::equal(device_class.begin(), device_class.end(), strdup("humidity"))) { service = hap_serv_humidity_sensor_create(sensorPtr->state); } else if (std::equal(device_class.begin(), device_class.end(), strdup("illuminance"))) { service = hap_serv_light_sensor_create(sensorPtr->state); } else if (std::equal(device_class.begin(), device_class.end(), strdup("aqi"))) { service = hap_serv_air_quality_sensor_create(sensorPtr->state); } else if (std::equal(device_class.begin(), device_class.end(), strdup("carbon_dioxide"))) { service = hap_serv_carbon_dioxide_sensor_create(false); } else if (std::equal(device_class.begin(), device_class.end(), strdup("carbon_monoxide"))) { service = hap_serv_carbon_monoxide_sensor_create(false); } else if (std::equal(device_class.begin(), device_class.end(), strdup("pm10"))) { service = hap_serv_create(HAP_SERV_UUID_AIR_QUALITY_SENSOR); hap_serv_add_char(service, hap_char_pm_10_density_create(sensorPtr->state)); } else if (std::equal(device_class.begin(), device_class.end(), strdup("pm25"))) { service = hap_serv_create(HAP_SERV_UUID_AIR_QUALITY_SENSOR); hap_serv_add_char(service, hap_char_pm_2_5_density_create(sensorPtr->state)); } if (service) { hap_acc_cfg_t acc_cfg = { .model = strdup(accessory_info[MODEL]), .manufacturer = strdup(accessory_info[MANUFACTURER]), .fw_rev = strdup(accessory_info[FW_REV]), .hw_rev = NULL, .pv = strdup("1.1.0"), .cid = HAP_CID_BRIDGE, .identify_routine = acc_identify, }; hap_acc_t* accessory = nullptr; std::string accessory_name = sensorPtr->get_name(); if (accessory_info[NAME] == NULL) { acc_cfg.name = strdup(accessory_name.c_str()); } else { acc_cfg.name = strdup(accessory_info[NAME]); } if (accessory_info[SN] == NULL) { acc_cfg.serial_num = strdup(std::to_string(sensorPtr->get_object_id_hash()).c_str()); } else { acc_cfg.serial_num = strdup(accessory_info[SN]); } accessory = hap_acc_create(&acc_cfg); ESP_LOGD(TAG, "ID HASH: %lu", sensorPtr->get_object_id_hash()); hap_serv_set_priv(service, sensorPtr); /* Set the read callback for the service */ hap_serv_set_read_cb(service, sensor_read); /* Add the Sensor Service to the Accessory Object */ hap_acc_add_serv(accessory, service); /* Add the Accessory to the HomeKit Database */ hap_add_bridged_accessory(accessory, hap_get_unique_aid(std::to_string(sensorPtr->get_object_id_hash()).c_str())); if (!sensorPtr->is_internal()) sensorPtr->add_on_state_callback([this](float v) { SensorEntity::on_sensor_update(sensorPtr, v); }); ESP_LOGI(TAG, "Sensor '%s' linked to HomeKit", accessory_name.c_str()); } } }; } } #endif ================================================ FILE: components/homekit/switch.hpp ================================================ #pragma once #include #ifdef USE_SWITCH #include #include #include #include #include "hap_entity.h" namespace esphome { namespace homekit { class SwitchEntity : public HAPEntity { private: static constexpr const char* TAG = "SwitchEntity"; switch_::Switch* switchPtr; static int switch_write(hap_write_data_t write_data[], int count, void* serv_priv, void* write_priv) { switch_::Switch* switchPtr = (switch_::Switch*)serv_priv; ESP_LOGD(TAG, "Write called for Accessory %s (%s)", std::to_string(switchPtr->get_object_id_hash()).c_str(), switchPtr->get_name().c_str()); int i, ret = HAP_SUCCESS; hap_write_data_t* write; for (i = 0; i < count; i++) { write = &write_data[i]; if (!strcmp(hap_char_get_type_uuid(write->hc), HAP_CHAR_UUID_ON)) { ESP_LOGD(TAG, "Received Write for switch '%s' -> %s", switchPtr->get_name().c_str(), write->val.b ? "On" : "Off"); ESP_LOGD(TAG, "[STATE] CURRENT STATE: %d", switchPtr->state); write->val.b ? switchPtr->turn_on() : switchPtr->turn_off(); hap_char_update_val(write->hc, &(write->val)); *(write->status) = HAP_STATUS_SUCCESS; } else { *(write->status) = HAP_STATUS_RES_ABSENT; } } return ret; } static void on_switch_update(switch_::Switch* obj, bool v) { ESP_LOGD(TAG, "%s state: %d", obj->get_name().c_str(), v); hap_acc_t* acc = hap_acc_get_by_aid(hap_get_unique_aid(std::to_string(obj->get_object_id_hash()).c_str())); if (acc) { hap_serv_t* hs = hap_acc_get_serv_by_uuid(acc, HAP_SERV_UUID_SWITCH); hap_char_t* on_char = hap_serv_get_char_by_uuid(hs, HAP_CHAR_UUID_ON); hap_val_t state; state.b = v; hap_char_update_val(on_char, &state); } } static int acc_identify(hap_acc_t* ha) { ESP_LOGI(TAG, "Accessory identified"); return HAP_SUCCESS; } public: SwitchEntity(switch_::Switch* switchPtr) : HAPEntity({{MODEL, "HAP-SWITCH"}}), switchPtr(switchPtr) {} void setup() { hap_acc_cfg_t acc_cfg = { .model = strdup(accessory_info[MODEL]), .manufacturer = strdup(accessory_info[MANUFACTURER]), .fw_rev = strdup(accessory_info[FW_REV]), .hw_rev = NULL, .pv = strdup("1.1.0"), .cid = HAP_CID_BRIDGE, .identify_routine = acc_identify, }; hap_acc_t* accessory = nullptr; hap_serv_t* service = nullptr; std::string accessory_name = switchPtr->get_name(); if (accessory_info[NAME] == NULL) { acc_cfg.name = strdup(accessory_name.c_str()); } else { acc_cfg.name = strdup(accessory_info[NAME]); } if (accessory_info[SN] == NULL) { acc_cfg.serial_num = strdup(std::to_string(switchPtr->get_object_id_hash()).c_str()); } else { acc_cfg.serial_num = strdup(accessory_info[SN]); } /* Create accessory object */ accessory = hap_acc_create(&acc_cfg); /* Create the switch Service. */ service = hap_serv_switch_create(switchPtr->state); ESP_LOGD(TAG, "ID HASH: %lu", switchPtr->get_object_id_hash()); hap_serv_set_priv(service, switchPtr); /* Set the write callback for the service */ hap_serv_set_write_cb(service, switch_write); /* Add the Switch Service to the Accessory Object */ hap_acc_add_serv(accessory, service); /* Add the Accessory to the HomeKit Database */ hap_add_bridged_accessory(accessory, hap_get_unique_aid(std::to_string(switchPtr->get_object_id_hash()).c_str())); if (!switchPtr->is_internal()) switchPtr->add_on_state_callback([this](bool v) { SwitchEntity::on_switch_update(switchPtr, v); }); ESP_LOGI(TAG, "Switch '%s' linked to HomeKit", accessory_name.c_str()); } }; } } #endif ================================================ FILE: components/homekit_base/HAPRootComponent.cpp ================================================ #include "HAPRootComponent.h" #include #include "sodium/randombytes.h" namespace esphome { namespace homekit { /* Mandatory identify routine for the accessory. * In a real accessory, something like LED blink should be implemented * got visual identification */ static int acc_identify(hap_acc_t *ha) { ESP_LOGI("HAP", "Accessory identified"); return HAP_SUCCESS; } void HAPRootComponent::factory_reset() { hap_reset_pairings(); } static const char *randombytes_esp32xx_implementation_name(void) { return CONFIG_IDF_TARGET; } HAPRootComponent::HAPRootComponent(const char* setup_code, const char* setup_id, std::map info) { const struct randombytes_implementation randombytes_esp32_implementation = { .implementation_name = randombytes_esp32xx_implementation_name, .random = esp_random, .stir = NULL, .uniform = NULL, .buf = esp_fill_random, .close = NULL, }; randombytes_set_implementation(&randombytes_esp32_implementation); ESP_LOGI(TAG, "[APP] Free memory: %" PRIu32 " bytes", esp_get_free_heap_size()); ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version()); ESP_LOGI(TAG, "%s", esp_err_to_name(nvs_flash_init())); std::map merged_info; merged_info.merge(info); merged_info.merge(this->accessory_info); this->accessory_info.swap(merged_info); hap_acc_t* accessory; /* Initialize the HAP core */ hap_init(HAP_TRANSPORT_WIFI); /* Initialise the mandatory parameters for Accessory which will be added as * the mandatory services internally */ hap_cfg_t hap_cfg; hap_get_config(&hap_cfg); hap_cfg.task_stack_size = 8192; hap_cfg.task_priority = 2; hap_set_config(&hap_cfg); hap_acc_cfg_t cfg = { .name = strdup(accessory_info[NAME]), .model = strdup(accessory_info[MODEL]), .manufacturer = strdup(accessory_info[MANUFACTURER]), .serial_num = strdup(accessory_info[SN]), .fw_rev = strdup(accessory_info[FW_REV]), .hw_rev = "1.0", .pv = "1.1.0", .cid = HAP_CID_BRIDGE, .identify_routine = acc_identify, }; /* Create accessory object */ accessory = hap_acc_create(&cfg); if (!accessory) { ESP_LOGE(TAG, "Failed to create accessory"); hap_acc_delete(accessory); vTaskDelete(NULL); } /* Add a dummy Product Data */ uint8_t product_data[] = {'E','S','P','3','2','H','A','P'}; hap_acc_add_product_data(accessory, product_data, sizeof(product_data)); /* Add Wi-Fi Transport service required for HAP Spec R16 */ hap_acc_add_wifi_transport_service(accessory, 0); /* Add the Accessory to the HomeKit Database */ hap_add_accessory(accessory); /* Unique Setup code of the format xxx-xx-xxx. Default: 111-22-333 */ hap_set_setup_code(setup_code); /* Unique four character Setup Id. Default: ES32 */ hap_set_setup_id(setup_id); } void HAPRootComponent::setup() { // hap_http_debug_enable(); // hap_set_debug_level(HAP_DEBUG_LEVEL_INFO); // esp_log_level_set("HAP", ESP_LOG_INFO); hap_start(); ESP_LOGI(TAG, "HAP Bridge started!"); } void HAPRootComponent::loop() { } void HAPRootComponent::dump_config() { } } // namespace homekit } // namespace esphome ================================================ FILE: components/homekit_base/HAPRootComponent.h ================================================ #pragma once #include "esphome/core/component.h" #include "esphome/core/log.h" #include "esphome/core/application.h" #include #include #include #include #include #include #include #include #include #include "esphome/components/homekit/const.h" #ifdef USE_BUTTON #include "esphome/components/button/button.h" #endif namespace esphome { namespace homekit { class HAPRootComponent : public Component { #ifdef USE_BUTTON SUB_BUTTON(reset) #endif private: static constexpr const char* TAG = "HAPRootComponent"; std::map accessory_info = {{NAME, "ESPH Bridge"}, {MODEL, "HAP-BRIDGE"}, {SN, "16161616"}, {MANUFACTURER, "rednblkx"}, {FW_REV, "0.1"}}; public: float get_setup_priority() const override { return setup_priority::LATE; } void factory_reset(); HAPRootComponent(const char* setup_code = "159-35-728", const char* setup_id = "ES32", std::map info = {{NAME, "ESPH Bridge"}, {MODEL, "HAP-BRIDGE"}, {SN, "16161616"}, {MANUFACTURER, "rednblkx"}, {FW_REV, "0.1"}}); void setup() override; void loop() override; void dump_config() override; }; } // namespace homekit } // namespace esphome ================================================ FILE: components/homekit_base/LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: components/homekit_base/__init__.py ================================================ import esphome.codegen as cg import esphome.config_validation as cv from esphome.const import CONF_PORT, PLATFORM_ESP32, CONF_ID from esphome.components.esp32 import add_idf_component, add_idf_sdkconfig_option import re DEPENDENCIES = ['esp32', 'network', 'mdns'] CODEOWNERS = ["@rednblkx"] MULTI_CONF = True homekit_ns = cg.esphome_ns.namespace('homekit') HAPRootComponent = homekit_ns.class_('HAPRootComponent', cg.Component) AInfo = homekit_ns.enum("AInfo") CONF_HAP_ID = "hap_id" def hk_setup_code(value): """Validate that a given config value is a valid icon.""" value = cv.string_strict(value) if not value: return value if re.match("^[\\d]{3}-[\\d]{2}-[\\d]{3}$", value): return value raise cv.Invalid( 'Setup code must match the format XXX-XX-XXX' ) ACC_INFO = { "name": AInfo.NAME, "model": AInfo.MODEL, "manufacturer": AInfo.MANUFACTURER, "serial_number": AInfo.SN, "fw_rev": AInfo.FW_REV, } ACCESSORY_INFORMATION = { cv.Optional(i): cv.string for i in ACC_INFO } CONFIG_SCHEMA = cv.All(cv.Schema({ cv.GenerateID(): cv.declare_id(HAPRootComponent), cv.Optional(CONF_PORT, default=32042): cv.port, cv.Optional("meta") : ACCESSORY_INFORMATION, cv.Optional("setup_code", default="159-35-728"): hk_setup_code, cv.Optional("setup_id", default="ES32"): cv.All(cv.string_strict,cv.Upper,cv.Length(min=4, max=4, msg="Setup ID has to be a 4 character long alpha numeric string (with capital letters)")) }).extend(cv.COMPONENT_SCHEMA), cv.only_on([PLATFORM_ESP32]), cv.only_with_esp_idf) async def to_code(config): add_idf_component( name="esp_hap_core", repo="https://github.com/rednblkx/esp-homekit-sdk", ref="esphome", path="components/homekit/esp_hap_core" ) add_idf_component( name="esp_hap_apple_profiles", repo="https://github.com/rednblkx/esp-homekit-sdk", ref="esphome", path="components/homekit/esp_hap_apple_profiles" ) add_idf_component( name="esp_hap_extras", repo="https://github.com/rednblkx/esp-homekit-sdk", ref="esphome", path="components/homekit/esp_hap_extras" ) add_idf_component( name="esp_hap_platform", repo="https://github.com/rednblkx/esp-homekit-sdk", ref="esphome", path="components/homekit/esp_hap_platform" ) add_idf_component( name="hkdf-sha", repo="https://github.com/rednblkx/esp-homekit-sdk", ref="esphome", path="components/homekit/hkdf-sha" ) add_idf_component( name="mu_srp", repo="https://github.com/rednblkx/esp-homekit-sdk", ref="esphome", path="components/homekit/mu_srp" ) info_temp = [] if "meta" in config: for m in config["meta"]: info_temp.append([ACC_INFO[m], config["meta"][m]]) var = cg.new_Pvariable(config[CONF_ID], config["setup_code"], config["setup_id"], info_temp) if CONF_PORT in config: add_idf_sdkconfig_option("CONFIG_HAP_HTTP_SERVER_PORT", config[CONF_PORT]) add_idf_sdkconfig_option("CONFIG_MBEDTLS_HKDF_C", True) add_idf_sdkconfig_option("CONFIG_LWIP_MAX_SOCKETS", 16) await cg.register_component(var, config) ================================================ FILE: components/homekit_base/button/__init__.py ================================================ import esphome.codegen as cg from esphome.components import button import esphome.config_validation as cv from esphome.const import ( CONF_FACTORY_RESET, DEVICE_CLASS_RESTART, ENTITY_CATEGORY_CONFIG, ICON_RESTART_ALERT, ) from .. import homekit_ns, HAPRootComponent, CONF_HAP_ID ResetButton = homekit_ns.class_("ResetButton", button.Button) CONFIG_SCHEMA = { cv.GenerateID(CONF_HAP_ID): cv.use_id(HAPRootComponent), cv.Optional(CONF_FACTORY_RESET): button.button_schema( ResetButton, device_class=DEVICE_CLASS_RESTART, entity_category=ENTITY_CATEGORY_CONFIG, icon=ICON_RESTART_ALERT, ), } async def to_code(config): hap_component = await cg.get_variable(config[CONF_HAP_ID]) if factory_reset_config := config.get(CONF_FACTORY_RESET): b = await button.new_button(factory_reset_config) await cg.register_parented(b, config[CONF_HAP_ID]) cg.add(hap_component.set_reset_button(b)) ================================================ FILE: components/homekit_base/button/factory_reset.cpp ================================================ #include "factory_reset.h" namespace esphome { namespace homekit { void ResetButton::press_action() { this->parent_->factory_reset(); } } // namespace homekit } // namespace esphome ================================================ FILE: components/homekit_base/button/factory_reset.h ================================================ #pragma once #include "esphome/components/button/button.h" #include "../HAPRootComponent.h" namespace esphome { namespace homekit { class ResetButton : public button::Button, public Parented { public: ResetButton() = default; protected: void press_action() override; }; } // namespace homekit } // namespace esphome ================================================ FILE: components/pn532/LICENSE ================================================ # ESPHome License Copyright (c) 2019 ESPHome The ESPHome License is made up of two base licenses: MIT and the GNU GENERAL PUBLIC LICENSE. The C++/runtime codebase of the ESPHome project (file extensions .c, .cpp, .h, .hpp, .tcc, .ino) are published under the GPLv3 license. The python codebase and all other parts of this codebase are published under the MIT license. Both MIT and GPLv3 licenses are attached to this document. ## MIT License Copyright (c) 2019 ESPHome Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## GPLv3 License GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: components/pn532/__init__.py ================================================ from esphome import automation import esphome.codegen as cg from esphome.components import nfc import esphome.config_validation as cv from esphome.const import ( CONF_ID, CONF_ON_FINISHED_WRITE, CONF_ON_TAG, CONF_ON_TAG_REMOVED, CONF_TRIGGER_ID, ) CODEOWNERS = ["@OttoWinter", "@jesserockz"] AUTO_LOAD = ["binary_sensor", "nfc"] MULTI_CONF = True CONF_PN532_ID = "pn532_id" pn532_ns = cg.esphome_ns.namespace("pn532") PN532 = pn532_ns.class_("PN532", cg.PollingComponent) PN532IsWritingCondition = pn532_ns.class_( "PN532IsWritingCondition", automation.Condition ) PN532_SCHEMA = cv.Schema( { cv.GenerateID(): cv.declare_id(PN532), cv.Optional(CONF_ON_TAG): automation.validate_automation( { cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(nfc.NfcOnTagTrigger), } ), cv.Optional(CONF_ON_FINISHED_WRITE): automation.validate_automation({}), cv.Optional(CONF_ON_TAG_REMOVED): automation.validate_automation( { cv.GenerateID(CONF_TRIGGER_ID): cv.declare_id(nfc.NfcOnTagTrigger), } ), } ).extend(cv.polling_component_schema("1s")) def CONFIG_SCHEMA(conf): if conf: raise cv.Invalid( "This component has been moved in 1.16, please see the docs for updated " "instructions. https://esphome.io/components/binary_sensor/pn532/" ) _CALLBACK_AUTOMATIONS = ( automation.CallbackAutomation( CONF_ON_FINISHED_WRITE, "add_on_finished_write_callback" ), ) async def setup_pn532(var, config): await cg.register_component(var, config) for conf in config.get(CONF_ON_TAG, []): trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID]) cg.add(var.register_ontag_trigger(trigger)) await automation.build_automation( trigger, [(cg.std_string, "x"), (nfc.NfcTag, "tag")], conf ) for conf in config.get(CONF_ON_TAG_REMOVED, []): trigger = cg.new_Pvariable(conf[CONF_TRIGGER_ID]) cg.add(var.register_ontagremoved_trigger(trigger)) await automation.build_automation( trigger, [(cg.std_string, "x"), (nfc.NfcTag, "tag")], conf ) await automation.build_callback_automations(var, config, _CALLBACK_AUTOMATIONS) @automation.register_condition( "pn532.is_writing", PN532IsWritingCondition, cv.Schema( { cv.GenerateID(): cv.use_id(PN532), } ), ) async def pn532_is_writing_to_code(config, condition_id, template_arg, args): var = cg.new_Pvariable(condition_id, template_arg) await cg.register_parented(var, config[CONF_ID]) return var ================================================ FILE: components/pn532/binary_sensor.py ================================================ import esphome.codegen as cg from esphome.components import binary_sensor import esphome.config_validation as cv from esphome.const import CONF_UID from esphome.core import HexInt from . import CONF_PN532_ID, PN532, pn532_ns DEPENDENCIES = ["pn532"] def validate_uid(value): value = cv.string_strict(value) for x in value.split("-"): if len(x) != 2: raise cv.Invalid( "Each part (separated by '-') of the UID must be two characters long." ) try: x = int(x, 16) except ValueError as err: raise cv.Invalid( "Valid characters for parts of a UID are 0123456789ABCDEF." ) from err if x < 0 or x > 255: raise cv.Invalid( "Valid values for UID parts (separated by '-') are 00 to FF" ) return value PN532BinarySensor = pn532_ns.class_("PN532BinarySensor", binary_sensor.BinarySensor) CONFIG_SCHEMA = binary_sensor.binary_sensor_schema(PN532BinarySensor).extend( { cv.GenerateID(CONF_PN532_ID): cv.use_id(PN532), cv.Required(CONF_UID): validate_uid, } ) async def to_code(config): var = await binary_sensor.new_binary_sensor(config) hub = await cg.get_variable(config[CONF_PN532_ID]) cg.add(hub.register_tag(var)) addr = [HexInt(int(x, 16)) for x in config[CONF_UID].split("-")] cg.add(var.set_uid(addr)) ================================================ FILE: components/pn532/pn532.cpp ================================================ #include "pn532.h" #include #include "esphome/core/log.h" #include "esphome/core/hal.h" // Based on: // - https://cdn-shop.adafruit.com/datasheets/PN532C106_Application+Note_v1.2.pdf // - https://www.nxp.com/docs/en/nxp/application-notes/AN133910.pdf // - https://www.nxp.com/docs/en/nxp/application-notes/153710.pdf namespace esphome { namespace pn532 { static const char *const TAG = "pn532"; void PN532::setup() { ESP_LOGCONFIG(TAG, "Running setup"); // Get version data if (!this->write_command_({PN532_COMMAND_VERSION_DATA})) { ESP_LOGW(TAG, "Error sending version command, trying again"); if (!this->write_command_({PN532_COMMAND_VERSION_DATA})) { ESP_LOGE(TAG, "Error sending version command"); this->mark_failed(); return; } } std::vector version_data; if (!this->read_response(PN532_COMMAND_VERSION_DATA, version_data)) { ESP_LOGE(TAG, "Error getting version"); this->mark_failed(); return; } ESP_LOGD(TAG, "Found chip PN5%02X, Firmware v%d.%d", version_data[0], version_data[1], version_data[2]); if (!this->write_command_({ PN532_COMMAND_SAMCONFIGURATION, 0x01, // normal mode 0x14, // zero timeout (not in virtual card mode) 0x01, })) { ESP_LOGE(TAG, "No wakeup ack"); this->mark_failed(); return; } std::vector wakeup_result; if (!this->read_response(PN532_COMMAND_SAMCONFIGURATION, wakeup_result)) { this->error_code_ = WAKEUP_FAILED; this->mark_failed(); return; } // Set up SAM (secure access module) uint8_t sam_timeout = std::min(255u, this->update_interval_ / 50); if (!this->write_command_({ PN532_COMMAND_SAMCONFIGURATION, 0x01, // normal mode sam_timeout, // timeout as multiple of 50ms (actually only for virtual card mode, but shouldn't matter) 0x01, // Enable IRQ })) { this->error_code_ = SAM_COMMAND_FAILED; this->mark_failed(); return; } std::vector sam_result; if (!this->read_response(PN532_COMMAND_SAMCONFIGURATION, sam_result)) { ESP_LOGV(TAG, "Invalid SAM result: (%u)", sam_result.size()); // NOLINT for (uint8_t dat : sam_result) { ESP_LOGV(TAG, " 0x%02X", dat); } this->error_code_ = SAM_COMMAND_FAILED; this->mark_failed(); return; } // Set up Passive Activation Tries to 0 if (!this->write_command_({ PN532_COMMAND_RFCONFIGURATION, 0x05, 0xFF, 0x01, 0x0 })) { this->error_code_ = WAKEUP_FAILED; this->mark_failed(); return; } std::vector rf_conf; if (!this->read_response(PN532_COMMAND_RFCONFIGURATION, rf_conf)) { ESP_LOGV(TAG, "Invalid RF CONF result: (%u)", rf_conf.size()); // NOLINT for (uint8_t dat : rf_conf) { ESP_LOGV(TAG, " 0x%02X", dat); } this->error_code_ = WAKEUP_FAILED; this->mark_failed(); return; } this->turn_off_rf_(); } bool PN532::powerdown() { updates_enabled_ = false; requested_read_ = false; ESP_LOGI(TAG, "Powering down PN532"); if (!this->write_command_({PN532_COMMAND_POWERDOWN, 0b10100000})) { // enable i2c,spi wakeup ESP_LOGE(TAG, "Error writing powerdown command to PN532"); return false; } std::vector response; if (!this->read_response(PN532_COMMAND_POWERDOWN, response)) { ESP_LOGE(TAG, "Error reading PN532 powerdown response"); return false; } if (response[0] != 0x00) { ESP_LOGE(TAG, "Error on PN532 powerdown: %02x", response[0]); return false; } ESP_LOGV(TAG, "Powerdown successful"); delay(1); return true; } void PN532::update() { if (!updates_enabled_) return; for (auto *obj : this->binary_sensors_) obj->on_scan_end(); // Enhanced Contactless Polling sequence if (this->ecp_frame.size() > 0) { if (this->next_flow_ == 0) { if (!this->write_command_({ PN532_COMMAND_WRITEREGISTER, (0x633d >> 8) & 0xFF, 0x633d & 0xFF, 0x0 })) { ESP_LOGW(TAG, "Setting 8bit TX failed!"); this->status_set_warning(); return; } this->status_clear_warning(); this->requested_ecp_ = true; return; } else if (this->next_flow_ == 1) { std::vector frame_send{ PN532_COMMAND_INCOMMUNICATETHRU }; frame_send.insert(frame_send.end(), ecp_frame.begin(), ecp_frame.end()); if (!this->write_command_(frame_send)) { ESP_LOGW(TAG, "Sending ECP Frame failed!"); this->status_set_warning(); return; } this->status_clear_warning(); this->requested_ecp_ = true; return; } } // End of ECP sequence if (!this->write_command_({ PN532_COMMAND_INLISTPASSIVETARGET, 0x01, // max 1 card 0x00, // baud rate ISO14443A (106 kbit/s) })) { ESP_LOGW(TAG, "Requesting tag read failed!"); this->status_set_warning(); return; } this->status_clear_warning(); this->requested_read_ = true; } void PN532::loop() { // Enhanced Contactless Polling sequence if (this->next_flow_ == 0 && this->requested_ecp_) { auto ready = this->read_ready_(false); if (ready == WOULDBLOCK) return; bool success = false; std::vector read; if (ready == READY) { success = this->read_response(PN532_COMMAND_WRITEREGISTER, read); ESP_LOGV(TAG, "ECP: %s", format_hex(read).c_str()); this->next_flow_ = 1; } else { this->send_ack_(); } this->requested_ecp_ = false; return; } else if (this->next_flow_ == 1 && this->requested_ecp_) { auto ready = this->read_ready_(false); if (ready == WOULDBLOCK) return; bool success = false; std::vector read; if (ready == READY) { success = this->read_response(PN532_COMMAND_INCOMMUNICATETHRU, read); ESP_LOGV(TAG, "ECP: %s", format_hex(read).c_str()); this->next_flow_ = 2; } else { this->send_ack_(); } this->requested_ecp_ = false; return; } // End of ECP sequence if (!this->requested_read_) return; auto ready = this->read_ready_(false); if (ready == WOULDBLOCK) return; bool success = false; std::vector read; if (ready == READY) { success = this->read_response(PN532_COMMAND_INLISTPASSIVETARGET, read); } else { this->send_ack_(); // abort still running InListPassiveTarget } this->requested_read_ = false; if (!success) { // Something failed if (!this->current_uid_.empty()) { auto tag = make_unique(this->current_uid_); for (auto *trigger : this->triggers_ontagremoved_) trigger->process(tag); } this->current_uid_ = {}; // this->turn_off_rf_(); this->next_flow_ = 0; return; } uint8_t num_targets = read[0]; if (num_targets != 1) { this->target_still_present = false; // no tags found or too many if (!this->current_uid_.empty()) { auto tag = make_unique(this->current_uid_); for (auto *trigger : this->triggers_ontagremoved_) trigger->process(tag); } this->current_uid_ = {}; // this->turn_off_rf_(); this->next_flow_ = 0; return; } else { if (this->target_still_present) { this->current_uid_ = {}; this->next_flow_ = 0; ESP_LOGD(TAG, "Tag still present"); return; } this->target_still_present = true; } uint8_t nfcid_length = read[5]; if (nfcid_length > nfc::NFC_UID_MAX_LENGTH || read.size() < 6U + nfcid_length) { // oops, pn532 returned invalid data return; } nfc::NfcTagUid nfcid(read.begin() + 6, read.begin() + 6 + nfcid_length); bool report = true; for (auto *bin_sens : this->binary_sensors_) { if (bin_sens->process(nfcid)) { report = false; } } if (nfcid.size() == this->current_uid_.size()) { bool same_uid = true; for (size_t i = 0; i < nfcid.size(); i++) same_uid &= nfcid[i] == this->current_uid_[i]; if (same_uid) return; } this->current_uid_ = nfcid; if (next_task_ == READ) { auto tag = this->read_tag_(nfcid); for (auto *trigger : this->triggers_ontag_) trigger->process(tag); if (report) { char uid_buf[nfc::FORMAT_UID_BUFFER_SIZE]; ESP_LOGD(TAG, "Found new tag '%s'", nfc::format_uid_to(uid_buf, nfcid)); if (tag->has_ndef_message()) { const auto &message = tag->get_ndef_message(); const auto &records = message->get_records(); ESP_LOGD(TAG, " NDEF formatted records:"); for (const auto &record : records) { ESP_LOGD(TAG, " %s - %s", record->get_type().c_str(), record->get_payload().c_str()); } } } } else if (next_task_ == CLEAN) { ESP_LOGD(TAG, " Tag cleaning"); if (!this->clean_tag_(nfcid)) { ESP_LOGE(TAG, " Tag was not fully cleaned successfully"); } ESP_LOGD(TAG, " Tag cleaned!"); } else if (next_task_ == FORMAT) { ESP_LOGD(TAG, " Tag formatting"); if (!this->format_tag_(nfcid)) { ESP_LOGE(TAG, "Error formatting tag as NDEF"); } ESP_LOGD(TAG, " Tag formatted!"); } else if (next_task_ == WRITE) { if (this->next_task_message_to_write_ != nullptr) { ESP_LOGD(TAG, " Tag writing"); ESP_LOGD(TAG, " Tag formatting"); if (!this->format_tag_(nfcid)) { ESP_LOGE(TAG, " Tag could not be formatted for writing"); } else { ESP_LOGD(TAG, " Writing NDEF data"); if (!this->write_tag_(nfcid, this->next_task_message_to_write_)) { ESP_LOGE(TAG, " Failed to write message to tag"); } ESP_LOGD(TAG, " Finished writing NDEF data"); delete this->next_task_message_to_write_; this->next_task_message_to_write_ = nullptr; this->on_finished_write_callback_.call(); } } } this->read_mode(); this->turn_off_rf_(); this->next_flow_ = 0; } std::vector PN532::inDataExchange(const std::vector& data) { std::vector dataToSend{ PN532_COMMAND_INDATAEXCHANGE, 0x01 }; dataToSend.insert(dataToSend.end(), data.begin(), data.end()); if (!this->write_command_(dataToSend)) { ESP_LOGW(TAG, "Error sending InDataExchange command, trying again..."); if (!this->write_command_(dataToSend)) { ESP_LOGE(TAG, "Error sending InDataExchange command"); // this->mark_failed(); return std::vector(); } } int timeout = 0; while (this->read_ready_(true) != pn532::PN532ReadReady::READY) { timeout++; delay(1); if (timeout > 250) break; } std::vector buffer(0); if (!this->read_response(PN532_COMMAND_INDATAEXCHANGE, buffer)) { ESP_LOGE(TAG, "Error getting response"); // this->mark_failed(); return std::vector(); } return buffer; } bool PN532::write_command_(const std::vector& data) { std::vector write_data; // Preamble write_data.push_back(0x00); // Start code write_data.push_back(0x00); write_data.push_back(0xFF); // Length of message, TFI + data bytes const uint8_t real_length = data.size() + 1; // LEN write_data.push_back(real_length); // LCS (Length checksum) write_data.push_back(~real_length + 1); // TFI (Frame Identifier, 0xD4 means to PN532, 0xD5 means from PN532) write_data.push_back(0xD4); // calculate checksum, TFI is part of checksum uint8_t checksum = 0xD4; // DATA for (uint8_t dat : data) { write_data.push_back(dat); checksum += dat; } // DCS (Data checksum) write_data.push_back(~checksum + 1); // Postamble write_data.push_back(0x00); this->write_data(write_data); return this->read_ack_(); } bool PN532::read_ack_() { ESP_LOGV(TAG, "Reading ACK"); std::vector data; if (!this->read_data(data, 6)) { return false; } bool matches = (data[1] == 0x00 && // preamble data[2] == 0x00 && // start of packet data[3] == 0xFF && data[4] == 0x00 && // ACK packet code data[5] == 0xFF && data[6] == 0x00); // postamble ESP_LOGV(TAG, "ACK valid: %s", YESNO(matches)); return matches; } void PN532::send_ack_() { ESP_LOGV(TAG, "Sending ACK for abort"); this->write_data({0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00}); delay(10); } void PN532::send_nack_() { ESP_LOGV(TAG, "Sending NACK for retransmit"); this->write_data({0x00, 0x00, 0xFF, 0xFF, 0x00, 0x00}); delay(10); } enum PN532ReadReady PN532::read_ready_(bool block) { if (this->rd_ready_ == READY) { if (block) { this->rd_start_time_.reset(); this->rd_ready_ = WOULDBLOCK; } return READY; } if (!this->rd_start_time_.has_value()) { this->rd_start_time_ = millis(); } while (true) { if (this->is_read_ready()) { this->rd_ready_ = READY; break; } if (millis() - *this->rd_start_time_ > 100) { ESP_LOGV(TAG, "Timed out waiting for readiness from PN532!"); this->rd_ready_ = TIMEOUT; break; } if (!block) { this->rd_ready_ = WOULDBLOCK; break; } yield(); } auto rdy = this->rd_ready_; if (block || rdy == TIMEOUT) { this->rd_start_time_.reset(); this->rd_ready_ = WOULDBLOCK; } return rdy; } void PN532::turn_off_rf_() { ESP_LOGV(TAG, "Turning RF field OFF"); this->write_command_({ PN532_COMMAND_RFCONFIGURATION, 0x01, // RF Field 0x00, // Off }); } std::unique_ptr PN532::read_tag_(nfc::NfcTagUid &uid) { uint8_t type = nfc::guess_tag_type(uid.size()); if (type == nfc::TAG_TYPE_MIFARE_CLASSIC) { ESP_LOGD(TAG, "Mifare classic"); return this->read_mifare_classic_tag_(uid); } else if (type == nfc::TAG_TYPE_2) { ESP_LOGD(TAG, "Mifare ultralight"); return this->read_mifare_ultralight_tag_(uid); } else if (type == nfc::TAG_TYPE_UNKNOWN) { ESP_LOGV(TAG, "Cannot determine tag type"); return make_unique(uid); } else { return make_unique(uid); } } void PN532::read_mode() { this->next_task_ = READ; ESP_LOGD(TAG, "Waiting to read next tag"); } void PN532::clean_mode() { this->next_task_ = CLEAN; ESP_LOGD(TAG, "Waiting to clean next tag"); } void PN532::format_mode() { this->next_task_ = FORMAT; ESP_LOGD(TAG, "Waiting to format next tag"); } void PN532::write_mode(nfc::NdefMessage *message) { this->next_task_ = WRITE; this->next_task_message_to_write_ = message; ESP_LOGD(TAG, "Waiting to write next tag"); } bool PN532::clean_tag_(nfc::NfcTagUid &uid) { uint8_t type = nfc::guess_tag_type(uid.size()); if (type == nfc::TAG_TYPE_MIFARE_CLASSIC) { return this->format_mifare_classic_mifare_(uid); } else if (type == nfc::TAG_TYPE_2) { return this->clean_mifare_ultralight_(); } ESP_LOGE(TAG, "Unsupported Tag for formatting"); return false; } bool PN532::format_tag_(nfc::NfcTagUid &uid) { uint8_t type = nfc::guess_tag_type(uid.size()); if (type == nfc::TAG_TYPE_MIFARE_CLASSIC) { return this->format_mifare_classic_ndef_(uid); } else if (type == nfc::TAG_TYPE_2) { return this->clean_mifare_ultralight_(); } ESP_LOGE(TAG, "Unsupported Tag for formatting"); return false; } bool PN532::write_tag_(nfc::NfcTagUid &uid, nfc::NdefMessage *message) { uint8_t type = nfc::guess_tag_type(uid.size()); if (type == nfc::TAG_TYPE_MIFARE_CLASSIC) { return this->write_mifare_classic_tag_(uid, message); } else if (type == nfc::TAG_TYPE_2) { return this->write_mifare_ultralight_tag_(uid, message); } ESP_LOGE(TAG, "Unsupported Tag for formatting"); return false; } void PN532::dump_config() { ESP_LOGCONFIG(TAG, "PN532:"); switch (this->error_code_) { case NONE: break; case WAKEUP_FAILED: ESP_LOGE(TAG, "Wake Up command failed!"); break; case SAM_COMMAND_FAILED: ESP_LOGE(TAG, "SAM command failed!"); break; } LOG_UPDATE_INTERVAL(this); for (auto *child : this->binary_sensors_) { LOG_BINARY_SENSOR(" ", "Tag", child); } } bool PN532BinarySensor::process(const nfc::NfcTagUid &data) { if (data.size() != this->uid_.size()) return false; for (size_t i = 0; i < data.size(); i++) { if (data[i] != this->uid_[i]) return false; } this->publish_state(true); this->found_ = true; return true; } } // namespace pn532 } // namespace esphome ================================================ FILE: components/pn532/pn532.h ================================================ #pragma once #include "esphome/core/component.h" #include "esphome/core/automation.h" #include "esphome/components/binary_sensor/binary_sensor.h" #include "esphome/components/nfc/nfc_tag.h" #include "esphome/components/nfc/nfc.h" #include "esphome/components/nfc/automation.h" #include #include namespace esphome { namespace pn532 { static const uint8_t PN532_COMMAND_VERSION_DATA = 0x02; static const uint8_t PN532_COMMAND_SAMCONFIGURATION = 0x14; static const uint8_t PN532_COMMAND_RFCONFIGURATION = 0x32; static const uint8_t PN532_COMMAND_INDATAEXCHANGE = 0x40; static const uint8_t PN532_COMMAND_INCOMMUNICATETHRU = 0x42; static const uint8_t PN532_COMMAND_WRITEREGISTER = 0x08; static const uint8_t PN532_COMMAND_INLISTPASSIVETARGET = 0x4A; static const uint8_t PN532_COMMAND_POWERDOWN = 0x16; enum PN532ReadReady { WOULDBLOCK = 0, TIMEOUT, READY, }; class PN532BinarySensor; class PN532 : public PollingComponent { public: void setup() override; void dump_config() override; void update() override; void loop() override; void on_powerdown() override { powerdown(); } void register_tag(PN532BinarySensor *tag) { this->binary_sensors_.push_back(tag); } void register_ontag_trigger(nfc::NfcOnTagTrigger *trig) { this->triggers_ontag_.push_back(trig); } void register_ontagremoved_trigger(nfc::NfcOnTagTrigger *trig) { this->triggers_ontagremoved_.push_back(trig); } template void add_on_finished_write_callback(F &&callback) { this->on_finished_write_callback_.add(std::forward(callback)); } bool is_writing() { return this->next_task_ != READ; }; std::vector inDataExchange(const std::vector& data); void set_ecp_frame(std::vector& frame) { ecp_frame = frame; }; void read_mode(); void clean_mode(); void format_mode(); void write_mode(nfc::NdefMessage *message); bool powerdown(); protected: void turn_off_rf_(); bool write_command_(const std::vector &data); bool read_ack_(); void send_ack_(); void send_nack_(); enum PN532ReadReady read_ready_(bool block); virtual bool is_read_ready() = 0; virtual bool write_data(const std::vector &data) = 0; virtual bool read_data(std::vector &data, uint8_t len) = 0; virtual bool read_response(uint8_t command, std::vector &data) = 0; std::unique_ptr read_tag_(nfc::NfcTagUid &uid); bool format_tag_(nfc::NfcTagUid &uid); bool clean_tag_(nfc::NfcTagUid &uid); bool write_tag_(nfc::NfcTagUid &uid, nfc::NdefMessage *message); std::unique_ptr read_mifare_classic_tag_(nfc::NfcTagUid &uid); bool read_mifare_classic_block_(uint8_t block_num, std::vector &data); bool write_mifare_classic_block_(uint8_t block_num, const uint8_t *data, size_t len); bool auth_mifare_classic_block_(nfc::NfcTagUid &uid, uint8_t block_num, uint8_t key_num, const uint8_t *key); bool format_mifare_classic_mifare_(nfc::NfcTagUid &uid); bool format_mifare_classic_ndef_(nfc::NfcTagUid &uid); bool write_mifare_classic_tag_(nfc::NfcTagUid &uid, nfc::NdefMessage *message); std::unique_ptr read_mifare_ultralight_tag_(nfc::NfcTagUid &uid); bool read_mifare_ultralight_bytes_(uint8_t start_page, uint16_t num_bytes, std::vector &data); bool is_mifare_ultralight_formatted_(const std::vector &page_3_to_6); uint16_t read_mifare_ultralight_capacity_(); bool find_mifare_ultralight_ndef_(const std::vector &page_3_to_6, uint8_t &message_length, uint8_t &message_start_index); bool write_mifare_ultralight_page_(uint8_t page_num, const uint8_t *write_data, size_t len); bool write_mifare_ultralight_tag_(nfc::NfcTagUid &uid, nfc::NdefMessage *message); bool clean_mifare_ultralight_(); std::vector ecp_frame; bool updates_enabled_{ true }; bool requested_read_{ false }; bool target_still_present{ false }; bool requested_ecp_{ false }; int next_flow_{ 0 }; std::vector binary_sensors_; std::vector triggers_ontag_; std::vector triggers_ontagremoved_; nfc::NfcTagUid current_uid_; nfc::NdefMessage *next_task_message_to_write_; optional rd_start_time_{}; enum PN532ReadReady rd_ready_ { WOULDBLOCK }; enum NfcTask { READ = 0, CLEAN, FORMAT, WRITE, } next_task_{READ}; enum PN532Error { NONE = 0, WAKEUP_FAILED, SAM_COMMAND_FAILED, } error_code_{NONE}; CallbackManager on_finished_write_callback_; }; class PN532BinarySensor : public binary_sensor::BinarySensor { public: void set_uid(const nfc::NfcTagUid &uid) { uid_ = uid; } bool process(const nfc::NfcTagUid &data); void on_scan_end() { if (!this->found_) { this->publish_state(false); } this->found_ = false; } protected: nfc::NfcTagUid uid_; bool found_{false}; }; template class PN532IsWritingCondition : public Condition, public Parented { public: bool check(const Ts &...x) override { return this->parent_->is_writing(); } }; } // namespace pn532 } // namespace esphome ================================================ FILE: components/pn532/pn532_mifare_classic.cpp ================================================ #include #include #include "pn532.h" #include "esphome/core/log.h" namespace esphome { namespace pn532 { static const char *const TAG = "pn532.mifare_classic"; std::unique_ptr PN532::read_mifare_classic_tag_(nfc::NfcTagUid &uid) { uint8_t current_block = 4; uint8_t message_start_index = 0; uint32_t message_length = 0; if (this->auth_mifare_classic_block_(uid, current_block, nfc::MIFARE_CMD_AUTH_A, nfc::NDEF_KEY)) { std::vector data; if (this->read_mifare_classic_block_(current_block, data)) { if (!nfc::decode_mifare_classic_tlv(data, message_length, message_start_index)) { return make_unique(uid, nfc::ERROR); } } else { ESP_LOGE(TAG, "Failed to read block %d", current_block); return make_unique(uid, nfc::MIFARE_CLASSIC); } } else { ESP_LOGV(TAG, "Tag is not NDEF formatted"); return make_unique(uid, nfc::MIFARE_CLASSIC); } uint32_t index = 0; uint32_t buffer_size = nfc::get_mifare_classic_buffer_size(message_length); std::vector buffer; while (index < buffer_size) { if (nfc::mifare_classic_is_first_block(current_block)) { if (!this->auth_mifare_classic_block_(uid, current_block, nfc::MIFARE_CMD_AUTH_A, nfc::NDEF_KEY)) { ESP_LOGE(TAG, "Error, Block authentication failed for %d", current_block); } } std::vector block_data; if (this->read_mifare_classic_block_(current_block, block_data)) { buffer.insert(buffer.end(), block_data.begin(), block_data.end()); } else { ESP_LOGE(TAG, "Error reading block %d", current_block); } index += nfc::MIFARE_CLASSIC_BLOCK_SIZE; current_block++; if (nfc::mifare_classic_is_trailer_block(current_block)) { current_block++; } } if (buffer.begin() + message_start_index < buffer.end()) { buffer.erase(buffer.begin(), buffer.begin() + message_start_index); } else { return make_unique(uid, nfc::MIFARE_CLASSIC); } return make_unique(uid, nfc::MIFARE_CLASSIC, buffer); } bool PN532::read_mifare_classic_block_(uint8_t block_num, std::vector &data) { if (!this->write_command_({ PN532_COMMAND_INDATAEXCHANGE, 0x01, // One card nfc::MIFARE_CMD_READ, block_num, })) { return false; } if (!this->read_response(PN532_COMMAND_INDATAEXCHANGE, data) || data[0] != 0x00) { return false; } data.erase(data.begin()); char data_buf[nfc::FORMAT_BYTES_BUFFER_SIZE]; ESP_LOGVV(TAG, " Block %d: %s", block_num, nfc::format_bytes_to(data_buf, data)); return true; } bool PN532::auth_mifare_classic_block_(nfc::NfcTagUid &uid, uint8_t block_num, uint8_t key_num, const uint8_t *key) { std::vector data({ PN532_COMMAND_INDATAEXCHANGE, 0x01, // One card key_num, // Mifare Key slot block_num, // Block number }); data.insert(data.end(), key, key + 6); data.insert(data.end(), uid.begin(), uid.end()); if (!this->write_command_(data)) { ESP_LOGE(TAG, "Authentication failed - Block %d", block_num); return false; } std::vector response; if (!this->read_response(PN532_COMMAND_INDATAEXCHANGE, response) || response[0] != 0x00) { ESP_LOGE(TAG, "Authentication failed - Block 0x%02x", block_num); return false; } return true; } bool PN532::format_mifare_classic_mifare_(nfc::NfcTagUid &uid) { static constexpr std::array BLANK_BUFFER = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static constexpr std::array TRAILER_BUFFER = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0x07, 0x80, 0x69, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; bool error = false; for (int block = 0; block < 64; block += 4) { if (!this->auth_mifare_classic_block_(uid, block + 3, nfc::MIFARE_CMD_AUTH_B, nfc::DEFAULT_KEY)) { continue; } if (block != 0) { if (!this->write_mifare_classic_block_(block, BLANK_BUFFER.data(), BLANK_BUFFER.size())) { ESP_LOGE(TAG, "Unable to write block %d", block); error = true; } } if (!this->write_mifare_classic_block_(block + 1, BLANK_BUFFER.data(), BLANK_BUFFER.size())) { ESP_LOGE(TAG, "Unable to write block %d", block + 1); error = true; } if (!this->write_mifare_classic_block_(block + 2, BLANK_BUFFER.data(), BLANK_BUFFER.size())) { ESP_LOGE(TAG, "Unable to write block %d", block + 2); error = true; } if (!this->write_mifare_classic_block_(block + 3, TRAILER_BUFFER.data(), TRAILER_BUFFER.size())) { ESP_LOGE(TAG, "Unable to write block %d", block + 3); error = true; } } return !error; } bool PN532::format_mifare_classic_ndef_(nfc::NfcTagUid &uid) { static constexpr std::array EMPTY_NDEF_MESSAGE = { 0x03, 0x03, 0xD0, 0x00, 0x00, 0xFE, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static constexpr std::array BLANK_BLOCK = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; static constexpr std::array BLOCK_1_DATA = { 0x14, 0x01, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1}; static constexpr std::array BLOCK_2_DATA = { 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1}; static constexpr std::array BLOCK_3_TRAILER = { 0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0x78, 0x77, 0x88, 0xC1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; static constexpr std::array NDEF_TRAILER = { 0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7, 0x7F, 0x07, 0x88, 0x40, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; if (!this->auth_mifare_classic_block_(uid, 0, nfc::MIFARE_CMD_AUTH_B, nfc::DEFAULT_KEY)) { ESP_LOGE(TAG, "Unable to authenticate block 0 for formatting!"); return false; } if (!this->write_mifare_classic_block_(1, BLOCK_1_DATA.data(), BLOCK_1_DATA.size())) return false; if (!this->write_mifare_classic_block_(2, BLOCK_2_DATA.data(), BLOCK_2_DATA.size())) return false; if (!this->write_mifare_classic_block_(3, BLOCK_3_TRAILER.data(), BLOCK_3_TRAILER.size())) return false; ESP_LOGD(TAG, "Sector 0 formatted to NDEF"); for (int block = 4; block < 64; block += 4) { if (!this->auth_mifare_classic_block_(uid, block + 3, nfc::MIFARE_CMD_AUTH_B, nfc::DEFAULT_KEY)) { return false; } if (block == 4) { if (!this->write_mifare_classic_block_(block, EMPTY_NDEF_MESSAGE.data(), EMPTY_NDEF_MESSAGE.size())) { ESP_LOGE(TAG, "Unable to write block %d", block); } } else { if (!this->write_mifare_classic_block_(block, BLANK_BLOCK.data(), BLANK_BLOCK.size())) { ESP_LOGE(TAG, "Unable to write block %d", block); } } if (!this->write_mifare_classic_block_(block + 1, BLANK_BLOCK.data(), BLANK_BLOCK.size())) { ESP_LOGE(TAG, "Unable to write block %d", block + 1); } if (!this->write_mifare_classic_block_(block + 2, BLANK_BLOCK.data(), BLANK_BLOCK.size())) { ESP_LOGE(TAG, "Unable to write block %d", block + 2); } if (!this->write_mifare_classic_block_(block + 3, NDEF_TRAILER.data(), NDEF_TRAILER.size())) { ESP_LOGE(TAG, "Unable to write trailer block %d", block + 3); } } return true; } bool PN532::write_mifare_classic_block_(uint8_t block_num, const uint8_t *data, size_t len) { std::vector cmd({ PN532_COMMAND_INDATAEXCHANGE, 0x01, // One card nfc::MIFARE_CMD_WRITE, block_num, }); cmd.insert(cmd.end(), data, data + len); if (!this->write_command_(cmd)) { ESP_LOGE(TAG, "Error writing block %d", block_num); return false; } std::vector response; if (!this->read_response(PN532_COMMAND_INDATAEXCHANGE, response)) { ESP_LOGE(TAG, "Error writing block %d", block_num); return false; } return true; } bool PN532::write_mifare_classic_tag_(nfc::NfcTagUid &uid, nfc::NdefMessage *message) { auto encoded = message->encode(); uint32_t message_length = encoded.size(); uint32_t buffer_length = nfc::get_mifare_classic_buffer_size(message_length); encoded.insert(encoded.begin(), 0x03); if (message_length < 255) { encoded.insert(encoded.begin() + 1, message_length); } else { encoded.insert(encoded.begin() + 1, 0xFF); encoded.insert(encoded.begin() + 2, (message_length >> 8) & 0xFF); encoded.insert(encoded.begin() + 3, message_length & 0xFF); } encoded.push_back(0xFE); encoded.resize(buffer_length, 0); uint32_t index = 0; uint8_t current_block = 4; while (index < buffer_length) { if (nfc::mifare_classic_is_first_block(current_block)) { if (!this->auth_mifare_classic_block_(uid, current_block, nfc::MIFARE_CMD_AUTH_A, nfc::NDEF_KEY)) { return false; } } if (!this->write_mifare_classic_block_(current_block, encoded.data() + index, nfc::MIFARE_CLASSIC_BLOCK_SIZE)) { return false; } index += nfc::MIFARE_CLASSIC_BLOCK_SIZE; current_block++; if (nfc::mifare_classic_is_trailer_block(current_block)) { // Skipping as cannot write to trailer current_block++; } } return true; } } // namespace pn532 } // namespace esphome ================================================ FILE: components/pn532/pn532_mifare_ultralight.cpp ================================================ #include #include #include "pn532.h" #include "esphome/core/log.h" namespace esphome { namespace pn532 { static const char *const TAG = "pn532.mifare_ultralight"; std::unique_ptr PN532::read_mifare_ultralight_tag_(nfc::NfcTagUid &uid) { std::vector data; // pages 3 to 6 contain various info we are interested in -- do one read to grab it all if (!this->read_mifare_ultralight_bytes_(3, nfc::MIFARE_ULTRALIGHT_PAGE_SIZE * nfc::MIFARE_ULTRALIGHT_READ_SIZE, data)) { return make_unique(uid, nfc::NFC_FORUM_TYPE_2); } if (!this->is_mifare_ultralight_formatted_(data)) { ESP_LOGW(TAG, "Not NDEF formatted"); return make_unique(uid, nfc::NFC_FORUM_TYPE_2); } uint8_t message_length; uint8_t message_start_index; if (!this->find_mifare_ultralight_ndef_(data, message_length, message_start_index)) { ESP_LOGW(TAG, "Couldn't find NDEF message"); return make_unique(uid, nfc::NFC_FORUM_TYPE_2); } ESP_LOGVV(TAG, "NDEF message length: %u, start: %u", message_length, message_start_index); if (message_length == 0) { return make_unique(uid, nfc::NFC_FORUM_TYPE_2); } // we already read pages 3-6 earlier -- pick up where we left off so we're not re-reading pages const uint8_t read_length = message_length + message_start_index > 12 ? message_length + message_start_index - 12 : 0; if (read_length) { if (!read_mifare_ultralight_bytes_(nfc::MIFARE_ULTRALIGHT_DATA_START_PAGE + 3, read_length, data)) { ESP_LOGE(TAG, "Error reading tag data"); return make_unique(uid, nfc::NFC_FORUM_TYPE_2); } } // we need to trim off page 3 as well as any bytes ahead of message_start_index data.erase(data.begin(), data.begin() + message_start_index + nfc::MIFARE_ULTRALIGHT_PAGE_SIZE); return make_unique(uid, nfc::NFC_FORUM_TYPE_2, data); } bool PN532::read_mifare_ultralight_bytes_(uint8_t start_page, uint16_t num_bytes, std::vector &data) { const uint8_t read_increment = nfc::MIFARE_ULTRALIGHT_READ_SIZE * nfc::MIFARE_ULTRALIGHT_PAGE_SIZE; std::vector response; for (uint8_t i = 0; i * read_increment < num_bytes; i++) { if (!this->write_command_({ PN532_COMMAND_INDATAEXCHANGE, 0x01, // One card nfc::MIFARE_CMD_READ, uint8_t(i * nfc::MIFARE_ULTRALIGHT_READ_SIZE + start_page), })) { return false; } if (!this->read_response(PN532_COMMAND_INDATAEXCHANGE, response) || response[0] != 0x00) { return false; } uint16_t bytes_offset = (i + 1) * read_increment; auto pages_in_end_itr = bytes_offset <= num_bytes ? response.end() : response.end() - (bytes_offset - num_bytes); if ((pages_in_end_itr > response.begin()) && (pages_in_end_itr <= response.end())) { data.insert(data.end(), response.begin() + 1, pages_in_end_itr); } } char data_buf[nfc::FORMAT_BYTES_BUFFER_SIZE]; ESP_LOGVV(TAG, "Data read: %s", nfc::format_bytes_to(data_buf, data)); return true; } bool PN532::is_mifare_ultralight_formatted_(const std::vector &page_3_to_6) { const uint8_t p4_offset = nfc::MIFARE_ULTRALIGHT_PAGE_SIZE; // page 4 will begin 4 bytes into the vector return (page_3_to_6.size() > p4_offset + 3) && !((page_3_to_6[p4_offset + 0] == 0xFF) && (page_3_to_6[p4_offset + 1] == 0xFF) && (page_3_to_6[p4_offset + 2] == 0xFF) && (page_3_to_6[p4_offset + 3] == 0xFF)); } uint16_t PN532::read_mifare_ultralight_capacity_() { std::vector data; if (this->read_mifare_ultralight_bytes_(3, nfc::MIFARE_ULTRALIGHT_PAGE_SIZE, data)) { ESP_LOGV(TAG, "Tag capacity is %u bytes", data[2] * 8U); return data[2] * 8U; } return 0; } bool PN532::find_mifare_ultralight_ndef_(const std::vector &page_3_to_6, uint8_t &message_length, uint8_t &message_start_index) { const uint8_t p4_offset = nfc::MIFARE_ULTRALIGHT_PAGE_SIZE; // page 4 will begin 4 bytes into the vector if (!(page_3_to_6.size() > p4_offset + 6)) { return false; } if (page_3_to_6[p4_offset + 0] == 0x03) { message_length = page_3_to_6[p4_offset + 1]; message_start_index = 2; return true; } else if (page_3_to_6[p4_offset + 5] == 0x03) { message_length = page_3_to_6[p4_offset + 6]; message_start_index = 7; return true; } return false; } bool PN532::write_mifare_ultralight_tag_(nfc::NfcTagUid &uid, nfc::NdefMessage *message) { uint32_t capacity = this->read_mifare_ultralight_capacity_(); auto encoded = message->encode(); uint32_t message_length = encoded.size(); uint32_t buffer_length = nfc::get_mifare_ultralight_buffer_size(message_length); if (buffer_length > capacity) { ESP_LOGE(TAG, "Message length exceeds tag capacity %" PRIu32 " > %" PRIu32, buffer_length, capacity); return false; } encoded.insert(encoded.begin(), 0x03); if (message_length < 255) { encoded.insert(encoded.begin() + 1, message_length); } else { encoded.insert(encoded.begin() + 1, 0xFF); encoded.insert(encoded.begin() + 2, (message_length >> 8) & 0xFF); encoded.insert(encoded.begin() + 3, message_length & 0xFF); } encoded.push_back(0xFE); encoded.resize(buffer_length, 0); uint32_t index = 0; uint8_t current_page = nfc::MIFARE_ULTRALIGHT_DATA_START_PAGE; while (index < buffer_length) { if (!this->write_mifare_ultralight_page_(current_page, encoded.data() + index, nfc::MIFARE_ULTRALIGHT_PAGE_SIZE)) { return false; } index += nfc::MIFARE_ULTRALIGHT_PAGE_SIZE; current_page++; } return true; } bool PN532::clean_mifare_ultralight_() { uint32_t capacity = this->read_mifare_ultralight_capacity_(); uint8_t pages = (capacity / nfc::MIFARE_ULTRALIGHT_PAGE_SIZE) + nfc::MIFARE_ULTRALIGHT_DATA_START_PAGE; static constexpr std::array BLANK_DATA = {0x00, 0x00, 0x00, 0x00}; for (int i = nfc::MIFARE_ULTRALIGHT_DATA_START_PAGE; i < pages; i++) { if (!this->write_mifare_ultralight_page_(i, BLANK_DATA.data(), BLANK_DATA.size())) { return false; } } return true; } bool PN532::write_mifare_ultralight_page_(uint8_t page_num, const uint8_t *write_data, size_t len) { std::vector cmd({ PN532_COMMAND_INDATAEXCHANGE, 0x01, // One card nfc::MIFARE_CMD_WRITE_ULTRALIGHT, page_num, }); cmd.insert(cmd.end(), write_data, write_data + len); if (!this->write_command_(cmd)) { ESP_LOGE(TAG, "Error writing page %u", page_num); return false; } std::vector response; if (!this->read_response(PN532_COMMAND_INDATAEXCHANGE, response)) { ESP_LOGE(TAG, "Error writing page %u", page_num); return false; } return true; } } // namespace pn532 } // namespace esphome ================================================ FILE: components/pn532_spi/LICENSE ================================================ # ESPHome License Copyright (c) 2019 ESPHome The ESPHome License is made up of two base licenses: MIT and the GNU GENERAL PUBLIC LICENSE. The C++/runtime codebase of the ESPHome project (file extensions .c, .cpp, .h, .hpp, .tcc, .ino) are published under the GPLv3 license. The python codebase and all other parts of this codebase are published under the MIT license. Both MIT and GPLv3 licenses are attached to this document. ## MIT License Copyright (c) 2019 ESPHome Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ## GPLv3 License GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: components/pn532_spi/__init__.py ================================================ import esphome.codegen as cg import esphome.config_validation as cv from esphome.components import spi, pn532 from esphome.const import CONF_ID AUTO_LOAD = ["pn532"] CODEOWNERS = ["@OttoWinter", "@jesserockz"] DEPENDENCIES = ["spi"] MULTI_CONF = True pn532_spi_ns = cg.esphome_ns.namespace("pn532_spi") PN532Spi = pn532_spi_ns.class_("PN532Spi", pn532.PN532, spi.SPIDevice) CONFIG_SCHEMA = cv.All( pn532.PN532_SCHEMA.extend( { cv.GenerateID(): cv.declare_id(PN532Spi), } ).extend(spi.spi_device_schema(cs_pin_required=True)) ) async def to_code(config): var = cg.new_Pvariable(config[CONF_ID]) await pn532.setup_pn532(var, config) await spi.register_spi_device(var, config) ================================================ FILE: components/pn532_spi/pn532_spi.cpp ================================================ #include "pn532_spi.h" #include "esphome/core/helpers.h" #include "esphome/core/log.h" // Based on: // - https://cdn-shop.adafruit.com/datasheets/PN532C106_Application+Note_v1.2.pdf // - https://www.nxp.com/docs/en/nxp/application-notes/AN133910.pdf // - https://www.nxp.com/docs/en/nxp/application-notes/153710.pdf namespace esphome { namespace pn532_spi { static const char *const TAG = "pn532_spi"; // Maximum bytes to log in verbose hex output static constexpr size_t PN532_MAX_LOG_BYTES = 64; void PN532Spi::setup() { this->spi_setup(); this->cs_->digital_write(false); delay(10); PN532::setup(); } bool PN532Spi::is_read_ready() { this->enable(); this->write_byte(0x02); bool ready = this->read_byte() == 0x01; this->disable(); return ready; } bool PN532Spi::write_data(const std::vector &data) { this->enable(); delay(2); // First byte, communication mode: Write data this->write_byte(0x01); #if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE char hex_buf[format_hex_pretty_size(PN532_MAX_LOG_BYTES)]; #endif ESP_LOGV(TAG, "Writing data: %s", format_hex_pretty_to(hex_buf, sizeof(hex_buf), data.data(), data.size())); this->write_array(data.data(), data.size()); this->disable(); return true; } bool PN532Spi::read_data(std::vector &data, uint8_t len) { if (this->read_ready_(true) != pn532::PN532ReadReady::READY) { return false; } // Read data (transmission from the PN532 to the host) this->enable(); delay(2); this->write_byte(0x03); ESP_LOGV(TAG, "Reading data"); data.resize(len); this->read_array(data.data(), len); this->disable(); data.insert(data.begin(), 0x01); #if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE char hex_buf[format_hex_pretty_size(PN532_MAX_LOG_BYTES)]; #endif ESP_LOGV(TAG, "Read data: %s", format_hex_pretty_to(hex_buf, sizeof(hex_buf), data.data(), data.size())); return true; } bool PN532Spi::read_response(uint8_t command, std::vector &data) { ESP_LOGV(TAG, "Reading response"); if (this->read_ready_(true) != pn532::PN532ReadReady::READY) { return false; } this->enable(); delay(2); this->write_byte(0x03); std::vector header(7); this->read_array(header.data(), 7); #if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE char hex_buf[format_hex_pretty_size(PN532_MAX_LOG_BYTES)]; #endif ESP_LOGV(TAG, "Header data: %s", format_hex_pretty_to(hex_buf, sizeof(hex_buf), header.data(), header.size())); if (header[0] != 0x00 || header[1] != 0x00 || header[2] != 0xFF) { // invalid packet ESP_LOGV(TAG, "read data invalid preamble!"); this->disable(); return false; } bool valid_header = (static_cast(header[3] + header[4]) == 0 && // LCS, len + lcs = 0 header[5] == 0xD5 && // TFI - frame from PN532 to system controller header[6] == command + 1); // Correct command response bool error_frame = (static_cast(header[3] + header[4]) == 0 && header[5] == 0x7F && header[6] == 0x81); bool extended_frame = (header[3] == 0xFF && header[4] == 0xFF); if (!valid_header && !error_frame && !extended_frame) { ESP_LOGV(TAG, "read data invalid header!"); this->disable(); return false; } // full length of message, including command response (minimum 2: TFI + command response) uint16_t full_len = header[3]; if (full_len < 2) { ESP_LOGV(TAG, "read data has no payload"); this->disable(); return false; } if (extended_frame) { ESP_LOGV(TAG, "Abnormal length and checksum, possible Extended Frame"); header.resize(10); this->read_array(header.data() + 7, 3); ESP_LOGV(TAG, "EF: Header data: %s", format_hex_pretty(header).c_str()); if ((uint8_t)(header[5] + header[6] + header[7]) != 0) { ESP_LOGV(TAG, "EF: read data invalid header!"); this->disable(); return false; } full_len = ((((uint16_t)header[5]) << 8) | header[6]); } // length of data, excluding command response uint16_t len = full_len - 1; ESP_LOGV(TAG, "Reading response of length %d", len); data.resize(len + 1); this->read_array(data.data(), len + 1); this->disable(); ESP_LOGV(TAG, "Response data: %s", format_hex_pretty_to(hex_buf, sizeof(hex_buf), data.data(), data.size())); uint8_t checksum = header[5] + header[6]; // TFI + Command response code if (extended_frame) { checksum = header[8] + header[9]; } for (int i = 0; i < len - 1; i++) { uint8_t dat = data[i]; checksum += dat; } checksum = ~checksum + 1; if (data[len - 1] != checksum) { ESP_LOGV(TAG, "read data invalid checksum! %02X != %02X", data[len - 1], checksum); return false; } if (data[len] != 0x00) { ESP_LOGV(TAG, "read data invalid postamble!"); return false; } data.erase(data.end() - 2, data.end()); // Remove checksum and postamble if (error_frame) { return false; } return true; } void PN532Spi::dump_config() { PN532::dump_config(); LOG_PIN(" CS Pin: ", this->cs_); } } // namespace pn532_spi } // namespace esphome ================================================ FILE: components/pn532_spi/pn532_spi.h ================================================ #pragma once #include "esphome/core/component.h" #include "esphome/components/pn532/pn532.h" #include "esphome/components/spi/spi.h" #include namespace esphome { namespace pn532_spi { class PN532Spi : public pn532::PN532, public spi::SPIDevice { public: void setup() override; void dump_config() override; protected: bool is_read_ready() override; bool write_data(const std::vector &data) override; bool read_data(std::vector &data, uint8_t len) override; bool read_response(uint8_t command, std::vector &data) override; }; } // namespace pn532_spi } // namespace esphome ================================================ FILE: fan-c3.yaml ================================================ esphome: name: fan_test esp32: board: esp32-c3-devkitm-1 flash_size: 4MB framework: type: esp-idf version: 5.2.1 platform_version: 6.7.0 sdkconfig_options: CONFIG_COMPILER_OPTIMIZATION_SIZE: y CONFIG_LWIP_MAX_SOCKETS: "16" CONFIG_MBEDTLS_HKDF_C: y external_components: source: github://rednblkx/HAP-ESPHome@main refresh: 0s homekit_base: setup_code: '159-35-728' homekit: fan: - id: fan_1 meta: name: "My Fan" fan: - platform: binary id: fan_1 name: "My Fan" output: fan_output output: - platform: gpio id: fan_output pin: number: GPIO8 inverted: true logger: level: DEBUG wifi: ssid: !secret wifi_ssid password: !secret wifi_password ================================================ FILE: homekey-test-c3.yaml ================================================ esphome: name: homekey-test platformio_options: board_build.flash_mode: dio wifi: ssid: !secret wifi_ssid password: !secret wifi_password api: encryption: key: !secret api_key ota: - platform: esphome password: !secret ota_password lock: - platform: template id: "this_lock" name: "Main Lock" optimistic: True on_lock: - logger.log: "Door Locked!" on_unlock: - logger.log: "Door Unlocked!" external_components: source: github://rednblkx/HAP-ESPHome@main spi: clk_pin: 4 miso_pin: 5 mosi_pin: 6 pn532_spi: id: nfc_spi_module cs_pin: 7 update_interval: 100ms esp32: board: esp32-c3-devkitm-1 flash_size: 4MB framework: type: esp-idf homekit_base: setup_code: '159-35-728' homekit: lock: - id: this_lock nfc_id: nfc_spi_module on_hk_success: lambda: |- ESP_LOGI("HEREHERE", "IssuerID: %s", x.c_str()); ESP_LOGI("HEREHERE", "EndpointID: %s", y.c_str()); if (id(this_lock).state == LOCK_STATE_LOCKED) { id(this_lock).unlock(); } else { id(this_lock).lock(); } on_hk_fail: lambda: |- ESP_LOGI("GSDGSGS", "IT FAILED :("); hk_hw_finish: "SILVER" logger: level: DEBUG ================================================ FILE: homekey-test-c6.yaml ================================================ esphome: name: homekey-test wifi: ssid: !secret wifi_ssid password: !secret wifi_password api: encryption: key: !secret api_key ota: - platform: esphome password: !secret ota_password lock: - platform: template id: "this_lock" name: "Main Lock" optimistic: True on_lock: - logger.log: "Door Locked!" on_unlock: - logger.log: "Door Unlocked!" external_components: source: github://rednblkx/HAP-ESPHome@main spi: clk_pin: 18 miso_pin: 19 mosi_pin: 20 pn532_spi: id: nfc_spi_module cs_pin: 21 update_interval: 100ms esp32: board: esp32-c6-devkitm-1 flash_size: 16MB framework: type: esp-idf homekit_base: setup_code: '159-35-728' homekit: lock: - id: this_lock nfc_id: nfc_spi_module on_hk_success: then: if: condition: lock.is_locked: this_lock then: lock.unlock: this_lock else: lock.lock: this_lock on_hk_fail: lambda: |- ESP_LOGI("HK", "IT FAILED :("); hk_hw_finish: "SILVER" logger: level: DEBUG ================================================ FILE: homekey-test-esp32.yaml ================================================ esphome: name: homekey-test wifi: ssid: !secret wifi_ssid password: !secret wifi_password lock: - platform: template id: "this_lock" name: "Main Lock" optimistic: True on_lock: - logger.log: "Door Locked!" on_unlock: - logger.log: "Door Unlocked!" api: encryption: key: !secret api_key ota: - platform: esphome password: !secret ota_password external_components: source: components spi: clk_pin: 18 miso_pin: 19 mosi_pin: 23 pn532_spi: id: nfc_spi_module cs_pin: 5 update_interval: 100ms esp32: board: esp32dev flash_size: 4MB framework: type: esp-idf homekit_base: setup_code: '159-35-728' homekit: lock: - id: this_lock nfc_id: nfc_spi_module on_hk_success: then: if: condition: lock.is_locked: this_lock then: lock.unlock: this_lock else: lock.lock: this_lock on_hk_fail: lambda: |- ESP_LOGI("GSDGSGS", "IT FAILED :("); hk_hw_finish: "SILVER" logger: level: DEBUG ================================================ FILE: homekey-test-s3.yaml ================================================ esphome: name: homekey-test platformio_options: board_build.flash_mode: dio wifi: ssid: !secret wifi_ssid password: !secret wifi_password api: encryption: key: !secret api_key ota: - platform: esphome password: !secret ota_password lock: - platform: template id: "this_lock" name: "Main Lock" optimistic: True on_lock: - logger.log: "Door Locked!" on_unlock: - logger.log: "Door Unlocked!" external_components: source: github://rednblkx/HAP-ESPHome@main spi: clk_pin: 12 miso_pin: 13 mosi_pin: 11 pn532_spi: id: nfc_spi_module cs_pin: 10 update_interval: 100ms esp32: board: lolin_s3 flash_size: 16MB framework: type: esp-idf homekit_base: setup_code: '159-35-728' homekit: lock: - id: this_lock nfc_id: nfc_spi_module on_hk_success: lambda: |- ESP_LOGI("HEREHERE", "IssuerID: %s", x.c_str()); ESP_LOGI("HEREHERE", "EndpointID: %s", y.c_str()); if (id(this_lock).state == LOCK_STATE_LOCKED) { id(this_lock).unlock(); } else { id(this_lock).lock(); } on_hk_fail: lambda: |- ESP_LOGI("GSDGSGS", "IT FAILED :("); hk_hw_finish: "SILVER" logger: level: DEBUG ================================================ FILE: lights-c3.yaml ================================================ esphome: name: lights_test platformio_options: board_build.flash_mode: dio wifi: ssid: !secret wifi_ssid password: !secret wifi_password output: - platform: gpio pin: GPIO3 id: simple_led external_components: source: github://rednblkx/HAP-ESPHome@main refresh: 0s esp32: board: esp32-c3-devkitm-1 flash_size: 4MB framework: type: esp-idf homekit_base: setup_code: '159-35-728' homekit: light: - id: test_light meta: manufacturer: "AMICI&CO" model: "IGNIS" serial_number: "42424242" fw_rev: "0.16.2" - id: desk_light light: - platform: esp32_rmt_led_strip id: test_light rgb_order: GRB pin: GPIO8 num_leds: 1 rmt_channel: 0 chipset: ws2812 name: "RGB Light" restore_mode: RESTORE_DEFAULT_OFF - platform: binary id: desk_light name: "Desk Lamp" output: simple_led restore_mode: RESTORE_DEFAULT_OFF logger: level: DEBUG hardware_uart: USB_SERIAL_JTAG ================================================ FILE: pyproject.toml ================================================ [project] name = "hap-esphome" version = "0.1.0" description = "ESPHome component providing HomeKit functionality" readme = "README.md" requires-python = ">=3.11" dependencies = [ "esphome>=2026.1.5", ] ================================================ FILE: sensor-c3.yaml ================================================ esphome: name: lights_test platformio_options: board_build.flash_mode: dio wifi: ssid: !secret wifi_ssid password: !secret wifi_password external_components: source: github://rednblkx/HAP-ESPHome@main refresh: 0s esp32: board: esp32-c3-devkitm-1 flash_size: 4MB framework: type: esp-idf version: 5.3.1 platform_version: 6.8.1 sdkconfig_options: CONFIG_COMPILER_OPTIMIZATION_SIZE: y CONFIG_LWIP_MAX_SOCKETS: "16" CONFIG_MBEDTLS_HKDF_C: y number: - platform: template name: "Sensor Value" min_value: 10 max_value: 30 step: 1 optimistic: True id: "number_sensor" sensor: - platform: template id: "temp_sensor" name: "Template Sensor" unit_of_measurement: "°C" icon: "mdi:water-percent" device_class: "temperature" state_class: "measurement" lambda: |- return id(number_sensor).state; update_interval: 10s - platform: template id: "humidity_sensor" name: "Template Humidity Sensor" icon: "mdi:water-percent" device_class: "humidity" state_class: "measurement" lambda: |- return id(number_sensor).state; update_interval: 10s homekit_base: setup_code: '159-35-728' homekit: sensor: - id: temp_sensor meta: manufacturer: "AMICI&CO" model: "VARIO" serial_number: "42424242" fw_rev: "0.16.2" - id: humidity_sensor logger: level: DEBUG ================================================ FILE: switch-c3.yaml ================================================ esphome: name: lights_test platformio_options: board_build.flash_mode: dio wifi: ssid: !secret wifi_ssid password: !secret wifi_password output: - platform: gpio pin: GPIO3 id: simple_led external_components: source: github://rednblkx/HAP-ESPHome@main refresh: 0s esp32: board: esp32-c3-devkitm-1 flash_size: 4MB framework: type: esp-idf homekit_base: setup_code: '159-35-728' homekit: switch: - id: some_switch meta: manufacturer: "AMICI&CO" model: "TRANSMUTO" serial_number: "42424242" fw_rev: "0.16.2" switch: - platform: template id: some_switch name: "Template Switch" restore_mode: RESTORE_DEFAULT_OFF lambda: |- if (id(desk_light).current_values.get_state()) { return true; } else { return false; } turn_on_action: - light.turn_on: desk_light turn_off_action: - light.turn_off: desk_light light: - platform: binary id: desk_light name: "Desk Lamp" output: simple_led restore_mode: RESTORE_DEFAULT_OFF logger: level: DEBUG ================================================ FILE: test.yaml ================================================ esphome: name: custom_components_test platformio_options: board_build.flash_mode: dio wifi: ssid: !secret wifi_ssid password: !secret wifi_password api: encryption: key: !secret api_key ota: - platform: esphome password: !secret ota_password web_server: port: 8080 output: - platform: gpio pin: GPIO3 id: simple_led lock: - platform: template id: "this_lock" name: "Main Lock" optimistic: True on_lock: - logger.log: "Door Locked!" on_unlock: - logger.log: "Door Unlocked!" sensor: - platform: template id: "my_sensor" name: "Template Sensor" unit_of_measurement: "°C" icon: "mdi:water-percent" device_class: "temperature" state_class: "measurement" lambda: |- return id(number_sensor).state; update_interval: 10s - platform: template id: "my_sensor_second" name: "Template Sensor 1" unit_of_measurement: "°C" icon: "mdi:water-percent" device_class: "temperature" state_class: "measurement" lambda: |- return id(number_sensor).state; update_interval: 10s number: - platform: template name: "Sensor Value" min_value: 10 max_value: 30 step: 1 optimistic: True id: "number_sensor" switch: - platform: template id: some_switch name: "Template Switch" restore_mode: RESTORE_DEFAULT_OFF lambda: |- if (id(test_light).current_values.get_state()) { return true; } else { return false; } turn_on_action: - light.turn_on: test_light turn_off_action: - light.turn_off: test_light external_components: source: github://rednblkx/HAP-ESPHome@main refresh: 0s spi: clk_pin: 4 miso_pin: 5 mosi_pin: 6 pn532_spi: id: nfc_spi_module cs_pin: 7 update_interval: 100ms esp32: board: esp32-c3-devkitm-1 flash_size: 4MB framework: type: esp-idf homekit_base: meta: name: "PRIMO" manufacturer: "AMICI&CO" model: "IMPERIUM" serial_number: "16161616" fw_rev: "0.16.2" setup_code: '159-35-728' homekit: lock: - id: this_lock meta: manufacturer: "AMICI&CO" model: "IMPEDIO" serial_number: "42424242" fw_rev: "0.16.2" nfc_id: nfc_spi_module on_hk_success: lambda: |- ESP_LOGI("HEREHERE", "IssuerID: %s", x.c_str()); ESP_LOGI("HEREHERE", "EndpointID: %s", y.c_str()); id(test_light).toggle().perform(); on_hk_fail: lambda: |- ESP_LOGI("GSDGSGS", "IT FAILED :("); hk_hw_finish: "SILVER" light: - id: test_light meta: name: "RGB Light" manufacturer: "AMICI&CO" model: "IGNIS" serial_number: "42424242" fw_rev: "0.16.2" - id: desk_light meta: manufacturer: "AMICI&CO" model: "IGNIS" serial_number: "42424242" fw_rev: "0.16.2" sensor: - id: my_sensor meta: manufacturer: "AMICI&CO" model: "VARIO" serial_number: "42424242" fw_rev: "0.16.2" - id: my_sensor_second meta: manufacturer: "AMICI&CO" model: "VARIO" serial_number: "42424242" fw_rev: "0.16.2" switch: - id: some_switch meta: manufacturer: "AMICI&CO" model: "TRANSMUTO" serial_number: "42424242" fw_rev: "0.16.2" button: - platform: homekit_base factory_reset: name: "Reset Homekit pairings" light: - platform: esp32_rmt_led_strip id: test_light rgb_order: GRB pin: GPIO8 num_leds: 1 # rmt_channel: 0 chipset: ws2812 name: "My Light" restore_mode: RESTORE_DEFAULT_OFF - platform: binary id: desk_light name: "Desk Lamp" output: simple_led restore_mode: RESTORE_DEFAULT_OFF logger: # hardware_uart: UART0 level: DEBUG