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