Compare commits

...
57 Commits
Author SHA1 Message Date
alex 72e80f236e build: share maintained ESP32 cache 2026-09-20 19:43:52 +10:00
alex 3892ce1ca9 build: standardize ESP32 3.3.11 test baseline 2026-09-18 02:41:49 +10:00
alex ea6f1cf353 ci: add current ESP32 validation lane 2026-09-17 12:10:59 +10:00
alex e3c9388ffc docs: correct MQTT example and ESP8266 guidance 2026-09-17 09:11:58 +10:00
alex e6dee4727d docs: clarify ArduinoHA discovery guidance 2026-09-08 09:52:56 +10:00
alex ea3f41b3f9 release: prepare ArduinoHA v3.2.0 2026-09-07 20:46:00 +10:00
alex 0dbf0ecb75 test: rename HA MQTT test harness 2026-09-07 19:29:21 +10:00
alex 50cf1c36f0 test: update MQTT contract support dependencies 2026-09-07 08:12:18 +10:00
alex bf18695c13 test: extract reusable HA MQTT contract testkit 2026-09-06 20:02:03 +10:00
alex e11fc4ace1 Merge pull request #1 from alexhopeoconnor/maintenance/ha-mqtt-compatibility
feat: merge Home Assistant MQTT compatibility release
2026-09-06 08:50:38 +10:00
alex ac08bf8431 style: remove trailing blank lines 2026-09-06 08:46:07 +10:00
alex 35b375b497 feat: improve MQTT discovery publishing and examples 2026-09-04 09:52:20 +10:00
alex 7f28604887 Stabilize Home Assistant contract CI 2026-09-02 07:48:48 +10:00
alex 56d74df55a Release ArduinoHA v3.1.0 2026-09-02 07:14:20 +10:00
alex 84cc0037b1 Improve release preparation tooling 2026-09-01 17:29:54 +10:00
alex 29ca5b2a29 Release v3.0.2 2026-09-01 11:39:46 +10:00
alex 5296fb1831 Release v3.0.1 2026-09-01 10:57:59 +10:00
alex 96c5aa6e78 feat: prepare ArduinoHA 3.0.0 2026-08-27 14:25:38 +10:00
alex 9d3eaa61f7 docs: clarify maintained fork installation 2026-08-25 09:01:06 +10:00
alex 3ac7fc98be Release home-assistant-integration 3.0.0 2026-08-24 22:08:19 +10:00
alex d03766ffbc Refactor ArduinoHA logging and add MQTT diagnostics.
Move ArduinoHA to a structured, runtime-configurable log model and instrument HAMqtt with disconnect and publish failure telemetry so ESP8266 MQTT failures can be diagnosed without patching PubSubClient first.
2026-05-05 22:29:48 +10:00
alex b9f4fd7f4b Per-entity availability, deferred discovery publish, suggested precision
- Add HAAvailabilityConfig for per-entity availability_topic and payloads
- Defer discovery until MQTT connected; publish availability after discovery
- HASensor/HANumber: optional suggested_display_precision in discovery
- HASerializer/HADictionary: extend for new keys; update device types and mocks
- Docs and examples reflect availability and precision usage
- Tests updated for discovery and availability behavior
- Ignore .cursor/ in repo root
2026-05-05 17:47:55 +10:00
alex 8ba5482892 test: add MQTT callback publish regressions and mock callback tracking
PubSubClientMock flags inbound callback context and counts publish attempts
from callbacks. Entity and core tests assert unsafe callback publishes are
rejected by the mock (baseline before HAMqtt deferred publish).
2026-05-05 13:52:00 +10:00
alex c9e6eef5b2 Add ArduinoHALog helpers, extend ArduinoHADefines, update mqtt usage doc 2026-04-22 12:09:12 +10:00
alex 40b98a38ee Migrate unit tests to PlatformIO Unity
Replace the legacy tests/ tree (AUnit, EpoxyDuino, Make, AUniter) with
PlatformIO Unity suites under test/, shared helpers, and platformio.ini.
Remove AUnitHelpers and drop the AUnit include from ArduinoHA test builds.
Refresh docs to Markdown-only and document the test workflow in CHANGELOG.
2026-04-19 23:24:28 +10:00
alex 7c419cb99e Add PlatformIO library.json and README note
Declare PubSubClient dependency; document lib_deps for PIO consumers.
2026-04-19 21:17:11 +10:00
alex 25fc356a0a Update fork metadata references.
Align the public package metadata and README badge with the maintained alexhopeoconnor fork while preserving upstream authorship credit.
2026-04-18 01:23:26 +10:00
alex 7d5d70d525 Modernize MQTT discovery compatibility and runtime refreshes.
Align ArduinoHA with current Home Assistant MQTT discovery expectations by adding default entity IDs, device discovery support, safer runtime discovery refresh behavior, expanded entity category coverage, and the tests/docs needed to support the migration away from legacy object_id payloads.
2026-04-16 19:49:50 +10:00
alex 7894f0c621 Fix MQTT client ownership and base device cleanup.
Store the production PubSubClient instance directly on HAMqtt and release base device serializers on destruction to avoid invalid deletes and leaked serializer allocations.
2026-04-16 17:39:42 +10:00
alex d954543236 Fix HASelect long-options parsing and add dynamic HANumber config updates.
This prevents overflow-related crashes when select options exceed 255 characters, adds runtime min/max/step updates that republish discovery config, and includes related HAText compilation fixes with test coverage.
2026-04-16 16:44:44 +10:00
alex 2ebdcf302b Add fork-driven MQTT and entity feature upgrades.
This integrates configurable MQTT reconnect behavior, the new Text entity, default lambda callback support across command-capable entities, and entity_category support for button/sensor/number families with test coverage.
2026-04-16 15:38:26 +10:00
Dawid Chyrzyński 1d333ab229 ArduinoHA 2.1.0 2024-02-10 00:48:58 +01:00
Dawid Chyrzynski 2a00dcd65f fix compiler warnings 2024-02-10 00:40:42 +01:00
Dawid Chyrzyński 105e96197b Add support for Arduino Due (#228)
* added support for Arduino Due

* update tests

* update changelog and docs

* fix tests
2024-02-09 22:16:54 +01:00
Dawid Chyrzyński a838dac9c0 fix tests (#227) 2024-02-09 20:31:15 +01:00
Dawid Chyrzyński 77a356bb37 HAMqtt improvements (#224)
* added setBufferSize method to the HAMqtt class

* added getState method to the HAMqtt class

* update docs

* update changelog

* changelog

* update mocks

* change data type in the PubSubClientMock

* update docs and changelog

* add more callbacks to the HAMqtt class

* improve handling of the disconnected state

* minor fixes in state handling
2024-02-09 19:27:10 +01:00
Dawid Chyrzyński 9e17dda50b Added support for object_id in all device types (#223)
* added support for the object_id property in all device types

* added tests
2024-02-07 00:03:30 +01:00
Dawid Chyrzynski 5c7acd7e39 update readme badges 2024-02-06 17:24:22 +01:00
Dawid Chyrzyński 87b7e03fe6 HASensor improvements (#222)
* added support for setting None value in the HASensor

* added support for the expire_after property in the HASensor

* update readme and docs

* added expire_after property in the HABinarySensor

* increase default device types limit to 24 on non ATMega328/168 processors

* added support for the JSON attributes in the HASensor
2024-02-06 17:01:46 +01:00
camnewnham ae059aecc1 Doc: add comment regarding position feature usage (#111)
* add comment regarding position feature usage

* add doc link
2024-02-06 13:58:27 +01:00
Dawid Chyrzyński 6cf4f11580 HASelect improvements (#221)
* added getCurrentOption method to the HASelect

* final fixes, tests

* added support for publishing None state in the HASelect

* update select.ino

* update docs
2024-02-05 20:44:29 +01:00
Dawid Chyrzyński fdc60b57c3 Added support for the configuration_url parameter in the HADevice (#220)
* added support for the configuration_url parameter in the HADevice

* update docs
2024-02-05 17:21:36 +01:00
Dawid Chyrzyński 80ae7ae592 Add support for extended unique IDs (#217)
* implement unique ID serialization as flag

* finished extended unique IDs feature

* add tests

* update docs

* add funding.yml
2024-02-05 16:20:40 +01:00
Dawid Chyrzynski ab46939903 docs 2024-02-05 16:17:33 +01:00
Dawid Chyrzynski e054e53eea update changelog 2024-01-31 09:11:32 +01:00
Dawid Chyrzynski 9ec42d667d update tests, change state_class to stat_cla 2024-01-31 09:11:25 +01:00
Mateusz Starzec b1eeec0856 Support for statistics from sensors in HA (#179)
* Fix statistics from sensors

* Test for state class setter in HASensor
2024-01-31 09:03:01 +01:00
Dawid Chyrzynski cd706969de update changelog 2024-01-31 09:00:44 +01:00
allenb2800andAllen Benter 8e3aad90c4 setKeepAlive function added issue #153 (#170)
Co-authored-by: Allen Benter <allen.benter@dpi.nsw.gov.au>
2024-01-31 08:54:12 +01:00
Dawid Chyrzynski b0bc9b4ea7 bump up version 2024-01-31 00:05:02 +01:00
Dawid Chyrzynski 8d76532e41 update changelog and tests 2024-01-31 00:04:31 +01:00
Kostiantyn Synytsia 252f0ab6b1 Bugfix/maximum number of device types (#190) (#191)
* added test for maximum device types

* fix max device types check
2024-01-30 23:59:54 +01:00
Dawid Chyrzynski b86495f492 update changelog 2024-01-30 23:31:53 +01:00
Eric Shtivelberg 884d8254bf fix: warning: class 'HANumeric' is implicitly friends with itself (#197) 2024-01-30 23:29:17 +01:00
Dawid ChyrzyńskiandDawid Chyrzynski 0fc32a5bad ArduinoHA 2.0.0 🔥 (#81)
* added tests for HADeviceTracker

* added support for progmem property value in the HASerializer

* codebase update

* add support for source type in HADeviceTracker

* added support for HACamera

* added support for HALock

* rename HABinarySensor::getState to getCurrentState

* standardize sender name in all callback headers

* remove duplicate serializer field protection (reduce flash usage)

* optimize HAUtils

* minor improvements

* optimize writing progmem payload

* optimize HAUtils:numberToStr

* remove relloc from HASerializer

* optimize HASerializerArray

* remove includeNullTerminator arg from the topics size generators

* optimize HASerializer

* replace dtostrf with custom implementation

* optimize BaseDeviceType

* removed relloc from the HAMqtt

* removed support for floats

* removed vtable for HADevice, HAMqtt, HASerializer and HASerializerArray

* implemented HASwitch with tests

* implemented basic HADeviceTrigger

* added support for built-in triggers

* finished HADeviceTrigger

* update changelog

* implemented base HASensor

* implemented HASensorInteger

* finished HASensorFloat

* override onMqttConnected in HASensorInteger and HASensorFloat

* add more tests for HASensorInteger and HASensorFloat

* optimize HASensorFloat

* update changelog

* standardize constructor of the HABinarySensor

* update readme

* readme

* readme

* standardize HADeviceTracker API

* standardize HASwitch API

* update docs README

* move Sphinx files to docsrc directory

* type in HASwitch

* test docs

* add .nojekyll to the docs directory

* update makefile of the docs

* wip: docs

* docs: fix html title

* docs: update styling and sidebar

* docs: add "Basics" section

* docs: device configuration

* docs: availability

* docs: MQTT discovery

* docs: MQTT security

* docs: MQTT advanced features

* rename BaseDeviceType to HABaseDeviceType

* update gitignore

* add API reference

* update gitignore

* HADevice doxygen

* doxygen css

* HADevice doxygen typos

* docs: update links

* docs: HAUtils doxygen

* HAMqtt and HADevice doxygen

* docs: device types

* docs: HABaseDeviceType

* reduced flash usage by 190 bytes

* fix tests

* move HAUtils class to the utils directory

* make HADevice const in HAMqtt

* HABinarySensor docs

* doxygen

* HADeviceTrigger doxygen

* HALock doxygen

* HASensor doxygen

* HASensor doxygen

* HASwitch doxygen

* HATagScanner doxygen

* HASerializer doxygen

* fix SAMD compile error

* add HAMqtt::publish method

* update examples

* add HAButton example

* update changelog

* added support for the optimistic property in the HACover

* do not set optimistic property in the HASwitch if it's set to default value

* update examples list

* update HASensor example

* update MQTT docs

* fix device trigger example link

* fix search form style on the search result page

* added support for the optimistic property in the HALock

* update readme

* change readme icon

* added HALock example

* MDNS example

* added HASensorFloat and HASensorInteger examples

* update readme

* update examples

* fix crash in the HABaseDeviceType

* add support for storing RAM elements in the HASerializerArray

* update tests cases in the CoverTest

* finished tests for HASelect

* added support for HASelect

* update README, CHANGELOG and examples list

* DeviceTest typos

* add more tests to SelectTest

* optimize HASelect command's handler

* improve CoverTest

* optimize HACover command's handler

* optimize HALock command's handler

* update SerializerTest

* remove HAMqtt::writePayload_P method

* remove FlagInternalType from the HASerializer

* added support for __FlashStringHelper in the topics related functions

* migrated serializer to use __FlashStringHelper

* add __FlashStringHelper to the HABaseDeviceType::publishOnDataTopic method

* move component name to flash memory

* update docs

* fix debug logs

* fix memory leaks

* monitor memory leaks in all test cases

* optimize tests (RAM)

* fix HALock states

* fix bug in the HASensor (invalid serialization of the value template property)

* fix memory leak in the HASelect

* fix crash in HASelect

* fix memory leak in the HADeviceTrigger

* fix memory leak in the HADevice

* tests: add support for ESP8266 and ESP32 envs

* update docs

* add multi-switch example

* update docs structure

* update MQTT advanced example in the docs

* HADevice: fix _uniqueId memory release

* wip: HANumber

* add HANumber to defines

* refactor HASensor implementation for numbers (again)

* update docs

* wip: HANumber

* wip: add support for number's precision in the HASerializer

* add support for float numbers in the HASerializer

* optimize vtables in the HASensor

* wip: HANumber

* fix crash in the float serialization

* handle another edge case in the float serialization

* replace int32_t with HAUtils::Number type

* HANumber fixes

* tests for HANumber

* change HAUtils::Number type to int64_t

* implemented HAUtils::strToNumber

* finished HANumber command handler

* finished HANumber

* update docs

* add number example

* added support for HAScene

* add scene example, update docs

* update doxygen

* remove memset from the codebase

* micro optimizations

* fix commands handlers

* update HACover code

* codebase cleanup

* finished HAFan implementation

* update docs, added fan example

* make json readable in all tests

* make position configurable in the HACover

* docs

* added support for HALight

* implement default values as static HAFan members

* update docs, added light example

* added support for color temperature in the HALight

* update light example

* update docs

* wip: HVAC

* improve all tests with callbacks

* update logs

* add HVAC to the docs

* optimize HANumber

* add current temperature to the HVAC

* started work on HVAC tests

* added action feature to the HVAC

* add temperature unit to the HVAC

* add more tests to UtilsTest

* fix fake MQTT messages mock - message shouldn't include null terminator

* fix HAUtils::strToNumber

* optimize HAFan, HACover and HALight

* add min/max temp to the HVAC

* added temp step property to the HVAC

* rename HASensorNumber::getCurrentValueAsFloat to getCurrentValueFloat

* update docs

* added support for aux heating in the HVAC

* added power command to the HVAC

* add subscriptions to the HVAC

* added fan mode to the HVAC

* update examples

* update command handlers in all device types

* added swing mode to the HVAC

* finished HVAC

* update docs

* fix memory leak in the HVAC

* added support for the target temperature in the HVAC

* add HVAC example

* update docs

* remove unnecessary checks from some device types

* added support for RGB in the HALight

* update docs

* standardize HAHVAC code

* rename HAButton::onPress method to onCommand

* rename HAScene::onActivate method to onCommand

* fix seg fault in the HAUtils

* HASensorNumber: do not publish default value on connect

* add return uint16_t to the HAUtils::numberToStr method

* simplify logic in the HALight::publishRGBColor

* optimize numbers serialization in the HASerializer

* update README, added LICENSE.md

* rename license file

* added tag-scanner example

* update publishOnDataTopic methods

* added esp32-cam example

* update docs

* add examples to the README.md

* update examples

* update HAMqtt.h for latest SAMD core, update aunier

* update README, fix auniter settings for esp32

* update README

* added documentation link to the README

* final tweaks in the HACover

* fix logic of the speed feature in the HAFan

* fix mdns example

* fix bug in the DeviceTrigger (invalid serialization of the progmem type/subtype)

* implemented HANumeric

* update HASensorNumber

* update HANumber

* update HALight

* update HAHVAC

* update HAFan

* update HACover

* update examples

* update tests

* update docs

* fix HANumeric constructor bug

* update HANumeric for SAMD

* update readme and docs

* add payload_on to the scene config (HA throws an exception if this property is missing)

* update sensor-analog example

* update sensor-integer example

* HVAC fixes

* update docs

Co-authored-by: Dawid Chyrzynski <dawid.chyrzynski@gmail.com>
2022-10-14 19:10:38 +02:00
Dawid Chyrzyński a4e50b7d04 Release 1.3.0 (#36)
* Add support for HVAC (#15)

* remove HASwitch::triggerCallback method

* fix typo in docs

* HASwitch: simplify callback #define

* work in progress: HVAC

* replace local mqtt instances with singleton

* device types optimization

* cleanup

* finished aux heating and away mode

* wip: HVAC

* finished HVAC implementation

* HVAC implementation

* add ifdefs for all HA components

* wip: optimization

* update readme

* update examples

* remove unused constructor from HAMqtt

* update HAUtils

* remove mqtt from constructors, fix compilation warnings

* finished HVAC

* add HVAC example, add changelog

* update changelog, add documentation

* Add support for icons in HASwitch and HASensor (#16)

* add support for icon in HASwitch

* add support for icon in HASensor

* update changelog

* add support for setting retain flag in HASwitch

* Add support for text payload in HASensor (#17)

* refactored HASensor

* update changelog

* fix sensor example

* Add support for fans (HAFan) (#18)

* finished basic implementation of the HAFan

* add retain method to DeviceTypeSerializer

* finished HAFan implementation

* update HAHVAC

* device types cleanup

* add HAFan example

* update changelog

* update readme

* update fan example

* optimization, add support for ActionFeature in HVAC

* Add support for MQTT LWT (#19)

* add support for hostname in HAMqtt

* add support for LWT and shared availability

* minor fixes

* added advanced availability example

* update examples

* update changelog

* cleanup & bug fix

* bump up version

* minor improvements and fixes

* update readme

* add HAMqtt::onMessage method

* Add support for covers (#28)

* add HACovers

* add cover example, update implementation

* disable debug

* update mqtt-events example

* Add support for setting different prefix for non-discovery topics (#29)

* add support for data prefix

* cleanup

* update comments and logs

* update multi-state-button example

* rename rexample from mqtt-events to mqtt-advanced

* update changelog

* update links in changelog

* Home Assistant 2021.4.5 - MQTT upgrade (#33)

* updae HAFan implementation

* change lib version

* update changelog

* fix setSpeed method

* update HAFan example

* Separate uniqueId from name (#34)

* rename name to uniqueId

* remove legacy labels

* update examples

* rename isMyTopic to compareTopics

* update changelog, rename name to uniqueId

* Implement onBeforeStateChanged callback in HASwitch (#35)

* add low latency mode to HASwitch

* add onBeforeStateChanged callback to HASwitch

* update readme

* rename DEPRECATED macro

* update advanced MQTT example
2021-04-17 20:03:32 +02:00
Dawid Chyrzyński 15562fa74c Release 1.2.0 (#21) 2021-03-23 13:23:56 +01:00
200 changed files with 39682 additions and 2555 deletions
+1
View File
@@ -0,0 +1 @@
github: dawidchyrzynski
+46
View File
@@ -0,0 +1,46 @@
name: Build
on:
push:
branches: [main]
tags: ["v*"]
pull_request:
concurrency:
group: build-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
permissions:
contents: read
jobs:
documentation:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: bash -n scripts/*.sh
- run: ./scripts/check-docs.sh
native-core-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- run: python -m pip install --upgrade platformio==6.1.19
- run: pio test -e native --filter test_native_core
compile-tests:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
platform: [esp8266, esp32]
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- run: python -m pip install --upgrade platformio==6.1.19
- run: ./scripts/test.sh compile --platform ${{ matrix.platform }}
- run: ./scripts/test.sh examples --platform ${{ matrix.platform }}
+43
View File
@@ -0,0 +1,43 @@
name: Home Assistant MQTT test harness
on:
workflow_dispatch:
schedule:
- cron: "17 3 * * 1"
permissions:
contents: read
jobs:
test_harness:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- home_assistant: "2024.11.3"
expect_disabled_cleanup: "0"
- home_assistant: stable
expect_disabled_cleanup: "0"
- home_assistant: dev
expect_disabled_cleanup: "1"
env:
HA_VERSION: ${{ matrix.home_assistant }}
TEST_HARNESS_EXPECT_DISABLED_CLEANUP: ${{ matrix.expect_disabled_cleanup }}
COMPOSE_FILE: tests/ha-test-harness/compose.yaml
steps:
- uses: actions/checkout@v4
- name: Start broker and Home Assistant
run: docker compose up -d mqtt homeassistant
- name: Check single-to-device migration
run: docker compose run --rm tests
- name: Restart Home Assistant from retained data
run: docker compose restart homeassistant
- name: Check retained discovery after restart
run: docker compose run --rm -e TEST_HARNESS_MODE=retained-restart tests
- name: Collect Home Assistant logs on failure
if: failure()
run: docker compose logs --no-color homeassistant mqtt
- name: Remove test harness volumes
if: always()
run: docker compose down -v
+59
View File
@@ -0,0 +1,59 @@
name: Publish release
on:
push:
tags:
- 'v*'
permissions:
contents: write
jobs:
test_harness:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
include:
- home_assistant: "2024.11.3"
- home_assistant: stable
env:
HA_VERSION: ${{ matrix.home_assistant }}
TEST_HARNESS_EXPECT_DISABLED_CLEANUP: "0"
COMPOSE_FILE: tests/ha-test-harness/compose.yaml
steps:
- uses: actions/checkout@v4
- name: Start broker and Home Assistant
run: docker compose up -d mqtt homeassistant
- name: Check single-to-device migration
run: docker compose run --rm tests
- name: Restart Home Assistant from retained data
run: docker compose restart homeassistant
- name: Check retained discovery after restart
run: docker compose run --rm -e TEST_HARNESS_MODE=retained-restart tests
- name: Collect Home Assistant logs on failure
if: failure()
run: docker compose logs --no-color homeassistant mqtt
- name: Remove test harness volumes
if: always()
run: docker compose down -v
publish:
runs-on: ubuntu-latest
needs: test_harness
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with:
python-version: '3.11'
- run: python -m pip install --upgrade platformio==6.1.19
- run: ./scripts/test.sh compile --platform esp8266
- run: ./scripts/test.sh examples --platform esp8266
- run: pio test -e native --filter test_native_core
- run: ./scripts/test.sh compile --platform esp32
- run: ./scripts/test.sh examples --platform esp32
- run: ./scripts/check-docs.sh
- run: ./scripts/prepare-release.sh "$GITHUB_REF_NAME"
- run: ./scripts/release-notes.sh "$GITHUB_REF_NAME" > "$RUNNER_TEMP/release-notes.md"
- run: gh release create "$GITHUB_REF_NAME" --title "ArduinoHA $GITHUB_REF_NAME" --notes-file "$RUNNER_TEMP/release-notes.md"
env:
GH_TOKEN: ${{ github.token }}
+15
View File
@@ -0,0 +1,15 @@
.DS_Store
tmp/
# Python test tooling
__pycache__/
*.py[cod]
# PlatformIO build output
.pio/
# Sphinx inventory (legacy); we ship Markdown-only under docs/
docs/*.inv
# Cursor IDE (local rules, not part of the library)
.cursor/
+180
View File
@@ -0,0 +1,180 @@
# Changelog
## 3.2.1
- Clarify discovery migration and entity documentation, including the choices
for new devices, existing installations, and no-device-discovery projects.
- Refresh the canonical PlatformIO and Arduino IDE package metadata.
## 3.2.0
**Discovery publication and resilience:**
- Batch direct MQTT discovery writes into bounded 128-byte chunks, avoiding hundreds of tiny TCP writes while preserving streaming payload generation.
- Treat allocation or streaming failure as a failed discovery publication, discard the unfinished payload, and reconnect before the next retained update.
- Allocate device-discovery component serializers only for sizing and emission, reducing peak heap use; make serializer allocation failure safe.
**Compatibility, tests, and documentation:**
- Add the reusable, Docker-based HA/MQTT testkit and run ArduinoHA migration and retained-restart checks against Home Assistant 2024.11.3, stable, and dev.
- Make the fixed baseline and current stable test-harness lanes release gates; keep the rolling dev lane scheduled/manual.
- Add maintained, credential-free PlatformIO ESP8266/ESP32 example projects and compile them in CI.
## 3.1.0
**Home Assistant MQTT compatibility:**
- Add an explicit, retry-safe single-component to device-discovery migration sequence: retained `migrate_discovery` markers, device config, then legacy-topic cleanup.
- Match Home Assistant device-component removal semantics with a platform-only tombstone followed by a compacted payload; `republishDiscovery()` re-adds a removed component.
- Stop serializing removed `obj_id`; keep `setObjectId()` source-compatible and use `setDefaultEntityId()` for new entities.
**Reliability and maintenance:**
- Reject invalid discovery topic tokens, escape dynamic JSON values, and fail discovery publication on partial writes or missing device IDs.
- Register entities safely regardless of whether they are constructed before or after `HAMqtt`, diagnose entity-limit drops, and make explicit disconnect callbacks observable.
- Make `HAText` own its current state and bounded command copy; align device-discovery origin version with the package version.
- Add native AddressSanitizer/UndefinedBehaviorSanitizer core regression coverage and release-script version consistency checks.
## 3.0.2
- Align the Arduino IDE `library.properties` version with `library.json` so both package formats identify the same release.
## 3.0.1
- Build and test against the Arduino 3-compatible pioarduino ESP32 platform.
- Enable the integer overload expected by Arduino-ESP32 3 while preserving the
existing ArduinoHA public API.
## 3.0.0
- Establish this maintained fork as the canonical ArduinoHA dependency for DeviceFramework.
- Prevent discovery serialization from writing past its entry allocation.
- Correct array deallocation in affected entity types.
**New features:**
* Added support for the `default_entity_id` (`def_ent_id`) discovery property across device types. New code should prefer `setDefaultEntityId()` over `setObjectId()`.
* Added opt-in MQTT device discovery payload support through `HAMqtt::enableDeviceDiscovery()`, while keeping single-component discovery as the default behavior.
* Added `HABaseDeviceType::removeFromDiscovery()` and `HABaseDeviceType::republishDiscovery()` helpers for explicit discovery lifecycle management.
* Added support for the `entity_category` property across the exposed MQTT device types.
**Fixes:**
* Fixed discovery refresh behavior for runtime config updates so device discovery mode clears stale retained per-entity configs before republishing device payloads.
* Fixed `HANumber::updateMinMaxStep()` so discovery updates follow the active discovery mode instead of always writing a retained per-entity config.
* Ignore empty `unit_of_measurement` values in discovery payloads.
* Allow `HANumber` configurations where `min` is equal to `max`.
**Migration notes:**
* Unit tests now live under `test/` as PlatformIO Unity suites (`pio test`). The legacy `tests/` tree (AUnit, EpoxyDuino, Make, AUniter) has been removed.
* Home Assistant deprecated MQTT `object_id` in favor of `default_entity_id`, and newer Home Assistant versions may warn on or remove `object_id` handling in discovery payloads.
* `setObjectId()` remains source-compatible but no longer serializes the removed `obj_id` discovery property; new projects should use `setDefaultEntityId()`.
* Existing single-component devices must use the staged migration API before device discovery; use `republishDiscovery()` when a runtime config change needs to refresh discovery state.
## 2.1.0
**New features:**
* Added support for setting MQTT's keep alive [#153](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/153) by [@allenb2800](https://github.com/allenb2800)
* Added support for the `state_class` property in the `HASensor` [#179](https://github.com/dawidchyrzynski/arduino-home-assistant/pull/179)
* Implemented extended unique ID support for all device types. This allows you to prefix each device type's unique ID with the device ID, ensuring smooth deployment of identical code on multiple devices without encountering unique ID conflicts [#212](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/212)
* Added support for the `configuration_url` property in the `HADevice` [#182](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/182)
* Added `getCurrentOption` method to the `HASelect` device type [#163](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/163)
* Added support for publishing the `None` state in the `HASelect` device type [#146](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/146)
* Added support for publishing the `None` state in the `HASensor` device type [#175](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/175)
* Added support for the `expire_after` property in the `HASensor` [#171](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/171)
* Added support for the `expire_after` property in the `HABinarySensor` [#159](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/159)
* Added support for the JSON attributes in the `HASensor`
* Added support for the `object_id` property in all device types
* Added `setBufferSize` method to the `HAMqtt` class [#202](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/202)
* Added `getState` method to the `HAMqtt` class
* Added `onDisconnected` callback method to the `HAMqtt` class
* Added `onStateChanged` callback method to the `HAMqtt` class
* Added support for Arduino Due [#137](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/137)
**Fixes:**
* Fixed a bug with the maximum number of device types [#190](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/190) by [@martaisty](https://github.com/martaisty)
* Fixed compiler warning: `class 'HANumeric' is implicitly friends with itself` [#197](https://github.com/dawidchyrzynski/arduino-home-assistant/pull/197) by [@shedokan](https://github.com/shedokan)
* The default limit for device types has been raised to 24 on processors other than ATMega328/ATMega168. The previous default limit of 6 led to confusion for many users.
## 2.0.0
**New features:**
* Added support for the `icon` property in the `HABinarySensor` (you can set the icon using `HABinarySensor::setIcon("iconName")`)
* Added support for changing the current state of the `HABinarySensor` using `HABinarySensor::setCurrentState` method
* Added support for forcing `setState` in `HABinarySensor` using a second argument as follows `HABinarySensor::setState(true, true)`
* Added support for the `device_class` property in the `HACover` (you can set the class using `HACover::setDeviceClass("className")`
* Added support for the `icon` property in the `HACover` (you can set the icon using `HACover::setIcon("iconName")`)
* Added pointer of the sender to the `HACover` callback function
* Added support for `optimistic` property in the `HACover` (you can change the mode using `HACover::setOptimistic(true)`)
* Added support for forcing `setPosition` in `HACover` using a second argument as follows `HACover::setPosition(100, true)`
* Added support for the `device_class` property in the `HASwitch` (you can set the class using `HASwitch::setDeviceClass("className")`
* Added support for the `optimistic` property in the `HASwitch` (you can change the mode using `HASwitch::setOptimistic(true)`)
* Added support for the `force_update` property in the `HASensor` (you can set the mode using `HASensor::setForceUpdate(true)`)
* Added support for the `HAButton` device type
* Added support for the `HADeviceTracker` device type
* Added support for the `HACamera` device type
* Added support for the `HALock` device type
* Added support for the `HASelect` device type
* Added support for the `HANumber` device type
* Added support for the `HAScene` device type
* Added support for the `HALight` device type
**Fixes:**
* Last Will Message is now retained (#70)
* Compilation error on SAMD family (#82)
**New examples:**
* [Button](examples/button/button.ino) - adding simple buttons to the Home Assistant panel.
**Breaking changes:**
* Changed structure of all MQTT topics used in the library.
* Changed constructor of the `HABinarySensor` class (removed `deviceClass` and `initialState` arguments)
* Renamed `HABinarySensor::getState()` method to `HABinarySensor::getCurrentState()`
* Replaced `HATriggers` with `HADeviceTrigger` - the new implementation is not backward compatible. Please check the updated example of the `multi-state-button`.
* Renamed `HADevice::isOnline()` method to `HADevice::isAvailable()`
* Renamed `HASwitch::onStateChanged` method to `HASwitch::onCommand`.
* Renamed `HAFan::onStateChanged` method to `HAFan::onStateCommand`.
* Renamed `HAFan::onSpeedChanged` method to `HAFan::onSpeedCommand`.
* Changed logic of the `HASwitch` callback. Please check the `led-switch` example.
* Refactored `HASensor` logic. It's now divided into two different classes: `HASensor` and `HASensorNumber`.
* Removed all legacy constructors with `HAMqtt` argument
* Removed `onConnectionFailed` callback from the `HAMqtt` class
* The position in the `HACover` is now available as configurable feature. It's disabled by default.
* Refactored `HAHVAC` class to support more features of the MQTT discovery. Please check the update example.
## 1.3.0
**New features:**
* Added `onMessage()` method to HAMqtt class
* Added support for HA Covers
* Added support for setting different prefix for non-discovery topics (see [Advanced MQTT example](examples/mqtt-advanced/mqtt-advanced.ino))
* Added `setName` method to HASensor
* Added `setName` method to HASwitch
* Added `onBeforeStateChanged` callback to HASwitch
**Improvements:**
* Removed legacy properties from HAFan (Home Assistant 2021.4.4). Deprecated methods will be removed after a quarter (2021.7)
* Separated `uniqueID` field from `name` in all devices types
## 1.2.0
**Breaking changes:**
* Refactored HASensor implementation. Please take a look at [updated example](examples/sensor/sensor.ino)
**New features:**
* Added support for HVAC
* Added support for excluding devices types from the compilation using defines (see [src/ArduinoHADefines.h](src/ArduinoHADefines.h))
* Added support for setting icon in HASwitch and HASensor
* Added support for setting retain flag in HASwitch
* Added support for text (const char*) payload in HASensor
* Added support for fans (HAFan)
* Added support for connecting to the MQTT broker using hostname
* Added `onConnected()` method in the HAMqtt
* Added `onConnectionFailed()` method in the HAMqtt
* Added support for MQTT LWT (see [Advanced Availability example](examples/advanced-availability/advanced-availability.ino))
**Improvements:**
* Optimized codebase and logic in all devices types
* Updated all examples
* Fixed compilation warnings in all classes
+661
View File
@@ -0,0 +1,661 @@
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.
+51 -40
View File
@@ -1,58 +1,69 @@
# Arduino Home Assistant integration
ArduinoHA allows to integrate an Arduino/ESP based device with Home Assistant using MQTT.
The library is designed to use as little resources (RAM/flash) as possible.
Initially it was optimized to work on Arduino Uno with Ethernet Shield,
but I successfully use it on ESP8266/ESP8255 boards in my projects.
[![](https://img.shields.io/github/v/release/alexhopeoconnor/arduino-home-assistant?label=Version)](https://github.com/alexhopeoconnor/arduino-home-assistant/releases)
[![](https://img.shields.io/badge/Documentation-40BC13)](docs/README.md)
## Features
ArduinoHA lets an Arduino, ESP8266, or ESP32 application publish MQTT discovery data that Home Assistant understands. Give it a connected Arduino `Client`, declare entities, and Home Assistant creates the controls and telemetry automatically.
* MQTT discovery (device is added to the Home Assistant panel automatically)
* Auto reconnect with MQTT broker
## Start with a sensor
## Examples
```cpp
#if defined(ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#endif
#include <ArduinoHA.h>
* [Binary Sensor](examples/binary-sensor/binary-sensor.ino)
* [LED switch](examples/led-switch/led-switch.ino)
* [MQTT with credentials](examples/mqtt-with-credentials/mqtt-with-credentials.ino)
* [Multi-state button](examples/multi-state-button/multi-state-button.ino)
* [Sensor (temperature, humidity, etc.)](examples/sensor/sensor.ino)
* [NodeMCU Wi-Fi](examples/nodemcu/nodemcu.ino)
* [Arduino Nano 33 IoT Wi-Fi (SAMD)](examples/nano33iot/nano33iot.ino)
* [Availability feature](examples/availability)
WiFiClient client;
HADevice device;
HAMqtt mqtt(client, device);
HASensorNumber temperature("temperature");
## Tested boards
void setup() {
byte mac[WL_MAC_ADDR_LENGTH];
WiFi.macAddress(mac);
device.setUniqueId(mac, sizeof(mac));
* Arduino Uno
* Arduino Mega
* Controllino Maxi (standard/pure/automation/power)
* Controllino Mega (standard/pure)
* NodeMCU
* ESP-01
* Generic ESP8266/ESP8255
* Arduino Nano 33 IoT (SAMD)
// Your application connects Wi-Fi before MQTT begins.
temperature.setName("Temperature");
temperature.setUnitOfMeasurement("°C");
mqtt.begin("mqtt.local", "mqtt_user", "mqtt_password"); // Connection work begins in mqtt.loop().
}
## Tested Arduino Shields
void loop() {
mqtt.loop(); // Maintains MQTT and publishes discovery after connecting.
// Call temperature.setValue(...) when your reading changes.
}
```
* Arduino Ethernet Shield (WizNet W5100)
Build [ESP Sensor](examples/01-esp-sensor/) for a complete ESP8266/ESP32 project. It clearly marks the network and broker values you must provide without committing credentials.
## Supported HA types
## What you can build
* Binary sensors
* Device triggers
* Switches
* Sensors
* Tag scanner
- **Automatic Home Assistant discovery:** retained MQTT discovery messages create entities without hand-written Home Assistant YAML.
- **Two-way controls:** sensors publish state while switches, lights, covers, and other writable entities receive explicit callbacks.
- **One physical device:** `HADevice` groups metadata, multiple entities, shared availability, and MQTT Last Will.
- **Device discovery:** publish one compact discovery document for a new multi-entity device, or keep traditional per-entity discovery.
- **Small footprint:** exclude entity implementations your firmware does not use.
## Unsupported features
## Choose an example
The library doesn't support all features of the MQTT integration.
If you need support for a new feature please open a new issue in the repository.
| Example | Learn how to… |
| --- | --- |
| [ESP Sensor](examples/01-esp-sensor/) | connect an ESP application and publish changing numeric telemetry |
| [Switch Callback](examples/02-switch-callback/) | reflect Home Assistant commands in a physical output and report state back |
| [Multi-entity Device](examples/03-multi-entity-device/) | group controls and telemetry with shared availability and Last Will |
| [Device Discovery](examples/04-device-discovery/) | publish one Home Assistant device-discovery document for a new device |
| [Entity recipes](examples/README.md#entity-recipes) | find the existing focused Arduino sketches for each supported entity |
# License
## Install
This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License v3.0 as published by the Free Software Foundation.
```ini
lib_deps =
home-assistant-integration=https://github.com/alexhopeoconnor/arduino-home-assistant.git#v3.2.1
```
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
PlatformIO clones the Git repository and checks out the ref after `#`; that ref is a release tag, not a GitHub Release asset. Arduino IDE is supported through the included [`library.properties`](library.properties).
You should have received a copy of the GNU General Public License along with this program. If not, see https://www.gnu.org/licenses/gpl.html
See [getting started](docs/getting-started.md), the [documentation map](docs/README.md), [examples](examples/README.md), [release history](CHANGELOG.md), and [licence](LICENSE).
+32
View File
@@ -0,0 +1,32 @@
# ESP8266 Postmortem linker workaround
The ESP8266 Arduino framework pin used by the DeviceFramework, WiFiManager,
DFTE, and ArduinoHA maintained builds is intentional:
```ini
platform_packages =
platformio/framework-arduinoespressif8266 @ https://github.com/esp8266/Arduino.git#521ae60a89e64bb0d1eb7a0b7addf620ced5cad3
```
That upstream commit fixes Postmortem's large-jump failure,
[`dangerous relocation: j: cannot encode`](https://github.com/esp8266/Arduino/commit/521ae60a89e64bb0d1eb7a0b7addf620ced5cad3).
It changes the restart wrapper to use a relaxed jump and adds an EPC1 address
check. The failure is a framework linker/runtime-support issue, not an ArduinoHA
or application-source error.
ArduinoHA's root `pio test -e esp8266` environment and every guided ESP8266
PlatformIO example now use this same snapshot. There is no root-test exception
that can hide a linker regression from the example test harness.
Keep this exact framework snapshot in ESP8266 environments that need the
maintained test harness. It is unrelated to ESP32, whose pioarduino platform
selects its framework and compiler as a unit. Do not replace the SHA with a
version range: remove or advance the pin only after an upstream release includes
the fix and the affected large firmware has compiled successfully. In
particular, changing the ESP32 validation lane does not justify changing this
ESP8266 pin.
The corresponding ESP32 Core 3.3.11 pin is documented in
[DeviceFramework's toolchain guide](https://github.com/alexhopeoconnor/DeviceFramework/blob/main/docs/TOOLCHAINS.md).
Back to the [documentation map](README.md).
+13
View File
@@ -0,0 +1,13 @@
# ArduinoHA documentation
| Topic | What it covers |
| ----- | ---------------- |
| [Getting started](getting-started.md) | Connecting a `Client`, installing the library, and the first MQTT lifecycle |
| [Device & discovery](device-and-discovery.md) | `HADevice`, discovery modes, metadata, identifiers, and migration |
| [MQTT usage](mqtt-usage.md) | Callbacks, custom topics, availability, logging, and footprint flags |
| [Entities](entities.md) | Supported Home Assistant entity classes and the best matching example |
| [ESP8266 linker workaround](ESP8266-LINKER-WORKAROUND.md) | Exact framework pin for the Postmortem large-jump fix |
| [Examples](../examples/README.md) | Guided PlatformIO projects and focused entity recipes |
| [Compatibility baseline](compatibility.md) | Supported Home Assistant capabilities and fork-specific compatibility notes |
Class-level API details live in headers under [`src/`](../src/). Return to the [project overview](../README.md).
+79
View File
@@ -0,0 +1,79 @@
# Compatibility baseline
This maintenance line begins from fork commit `84cc0037b1c0` (release `v3.0.2`).
It intentionally tracks Home Assistant's MQTT discovery test harness without merging
upstream development wholesale.
| Reference | Audited revision / target |
| --- | --- |
| Fork baseline | `84cc0037b1c0` (`v3.0.2`) |
| Upstream main | `1d333ab229b2` (`v2.1.0`) |
| Upstream develop | `a7039fad810b` (unreleased WIP 2.2.0) |
| Device discovery minimum | Home Assistant `2024.11.0` |
| Test harness matrix | `2024.11.3`, current `stable`, current `dev` |
The only imported upstream code fix is the four missing-device-ID guards from
upstream commit `9c9d074`. Device discovery migration, JSON validation,
lifecycle handling, and tests are fork-native changes.
## Arduino framework validation lanes
ArduinoHA compiles its embedded test suites and guided PlatformIO examples in
two maintained lanes:
| Selector | Target | Pinned stack | Role |
| --- | --- | --- | --- |
| `esp8266` | ESP8266 D1 mini | Arduino-ESP8266 commit `521ae60` | Maintained Postmortem linker-fix test-harness lane |
| `esp32` | ESP32 Dev Module | pioarduino `55.03.311` / Arduino-ESP32 3.3.11 / ESP-IDF 5.5.5 | Maintained baseline |
Every lane pins its complete framework stack. The ESP32 runner keeps its
maintained pioarduino graph in the persistent cache shared by these maintained
framework repositories, so stale global metadata cannot select an uploader or
compiler by accident without redownloading matching inputs for every repository.
The ESP8266 framework pin is independent of the ESP32 baseline; see the [linker
workaround](ESP8266-LINKER-WORKAROUND.md).
Run the current ESP32 lane locally with:
```bash
./scripts/test.sh compile --platform esp32
./scripts/test.sh examples --platform esp32
```
The script keeps that lane in the persistent PlatformIO Core/cache shared by
the maintained framework repositories by default
(`${XDG_CACHE_HOME:-$HOME/.cache}/arduino-framework-platformio/core-3.3.11`).
This prevents stale global `tool-esptoolpy` metadata from shadowing the current
pioarduino package-form uploader while avoiding duplicate Core 3.3.11
downloads. Set `ARDUINOHA_PLATFORMIO_CORE_DIR`,
`ARDUINOHA_PLATFORMIO_PACKAGES_DIR`, and
`ARDUINOHA_PLATFORMIO_CACHE_DIR` for a dedicated disk. The script never clears
that cache or repairs it by overriding one compiler package.
The embedded multi-suite compile path also defaults
`PLATFORMIO_RUN_JOBS=1`. A caller may explicitly set another value, but the
serial default avoids a reproducible PlatformIO archive missing-object race
seen in the Core 3.3.11 lane. Example builds remain parallel.
## Deliberate exclusions
- No merge or wholesale cherry-pick of upstream `develop` / WIP 2.2.0.
- No `obj_id` serialization: Home Assistant removed that discovery field. Use
`setDefaultEntityId()` for new code.
- No binary-sensor `state_class`: it is not valid in the current HA MQTT binary
sensor schema.
- No upstream IMqttClient abstraction or unreviewed entity-type feature PRs.
## Ongoing audit routine
The `upstream` remote has no usable push URL. Fetch and compare explicitly:
```bash
git fetch --prune upstream
git log --oneline main..upstream/develop
git diff --stat main...upstream/develop
```
Port only independently reviewed changes with regression tests; treat open
upstream pull requests as proposals, not release inputs. Run the native,
board-compile, and HA test harness gates before publishing a new release.
+152
View File
@@ -0,0 +1,152 @@
# Device & discovery
## `HADevice`
Represents the physical board in Home Assistant: one device can expose multiple entities (sensors, switches, lights, …).
**Unique ID** (required): must be unique in your Home Assistant instance. Common choices:
- MAC address as bytes: `HADevice device(mac, sizeof(mac));`
- String: `HADevice device("myId");` — keep it short and alphanumeric.
- Or default-construct and call `setUniqueId(bytes, length)` in `setup()`.
**Optional metadata** (each costs some RAM/flash; skip on tiny MCUs unless needed):
- `setName`, `setSoftwareVersion`, `setManufacturer`, `setModel`, `setConfigurationUrl`
- `setModelId`, `setHardwareVersion`, `setSerialNumber`, `setSuggestedArea`, `setViaDevice`
- `addConnection("mac", "aa:bb:cc:dd:ee:ff")` or `setConnectionsJson("[[\"mac\",\"aa:bb:cc:dd:ee:ff\"]]")`
String setters take **pointers whose contents are not copied** — use literals or storage that outlives the call.
## Discovery
When MQTT connects, the library publishes Home Assistant **MQTT discovery** payloads so entities appear automatically.
Entities can be constructed either before or after `HAMqtt`. Entities which already
exist when `HAMqtt` is constructed are registered then; entities constructed later
register immediately. Both the device, MQTT object, and entities must have a lifetime
that outlasts `mqtt.loop()`.
`HAMqtt` has a configurable entity limit (24 by default). Check
`getRegisteredDeviceTypeCount()`, `getDeviceTypeLimit()`, and `getDeviceTypeRegistrationFailures()` in firmware diagnostics: registrations above the limit are rejected and logged rather than silently disappearing from discovery.
### Topic prefixes
Defaults:
- Discovery prefix: `homeassistant`
- Data prefix (states, commands): `aha`
Override before `begin()` if needed:
```cpp
void configureTopicPrefixes() {
// Set both before mqtt.begin(...) publishes any discovery data.
mqtt.setDiscoveryPrefix("myHaPrefix");
mqtt.setDataPrefix("myDataPrefix");
}
```
### Single-component vs device discovery
- **Default:** one retained discovery topic per entity (single-component discovery).
- **Device discovery:** `HAMqtt::enableDeviceDiscovery()` publishes one retained device payload with components under `cmps`.
Both formats remain supported by Home Assistant. Device discovery requires Home Assistant **2024.11.0 or newer**. Use `enableDeviceDiscovery()` only for a new device which has never published this library's single-component discovery topics.
Choose the mode before connecting a device:
- **New device:** call `enableDeviceDiscovery()` before connecting.
- **Existing device using single-component discovery:** follow the migration
procedure below.
- **No need for device discovery:** keep the default behavior.
### Migrating an existing device to device discovery
Do not switch an existing device by calling `enableDeviceDiscovery()` alone.
Home Assistant derives an entity's discovery identity from the topic, and a
direct switch causes retained-topic conflicts. The migration publishes, in
order:
1. `{"migrate_discovery":true}` to every old retained component config topic;
2. the retained `/device/<deviceId>/config` payload; and only then
3. an empty retained payload to every old component config topic.
Keep the device ID and each entity ID unchanged. They preserve the mapping from the old `<component>/<deviceId>/<entityId>/config` topic to `cmps[entityId]` in the new device payload.
Start migration once during setup, then advance *one stage per loop iteration* after the MQTT connection is available. Each method is retry-safe: do not advance if it returns `false`.
```cpp
bool migrationStarted = false;
void setup() {
// Create device, mqtt, and entities; keep their IDs unchanged.
migrationStarted = mqtt.beginDeviceDiscoveryMigration();
mqtt.begin("192.168.1.50", "user", "password");
}
void loop() {
mqtt.loop();
switch (mqtt.getDeviceDiscoveryMigrationState()) {
case HAMqtt::DeviceDiscoveryMigrationMarkersPending:
mqtt.publishDeviceDiscoveryMigrationMarkers();
break;
case HAMqtt::DeviceDiscoveryMigrationMarkersPublished:
mqtt.publishDeviceDiscoveryMigrationConfig();
break;
case HAMqtt::DeviceDiscoveryMigrationDevicePublished:
mqtt.completeDeviceDiscoveryMigration();
break;
default:
break;
}
}
```
The migration stage is held in RAM. If the board reboots before completion, start the same migration again; the retained marker/config/cleanup publishes are idempotent. If you must abandon a started migration while connected, call `rollbackDeviceDiscoveryMigration()`. Once a device config has been published, it first writes `{"migrate_discovery":true}` to the device discovery topic, restores the legacy configs, then clears the device config and returns to single-component mode. A failed rollback remains pending and suppresses automatic device-bundle publication until retried successfully. Run all publishing stages from `loop()`, not inside an inbound MQTT callback.
Device discovery can also publish richer origin/device metadata, for example:
```cpp
void configureDeviceDiscovery() {
// These strings are borrowed, so keep literals or other long-lived storage.
device.setModelId("esp32-s3-devkit");
device.setHardwareVersion("rev-b");
device.setSerialNumber("SN-00042");
device.setSuggestedArea("Garage");
device.setViaDevice("main_gateway");
device.addConnection("mac", "AA:BB:CC:DD:EE:FF");
mqtt.setOriginSupportUrl("https://example.com/device-help");
}
```
For entity identifiers in Home Assistant, prefer **`setDefaultEntityId()`** over legacy **`setObjectId()`**.
`setObjectId()` remains source-compatible but no longer serializes the removed MQTT `obj_id` property. `setDefaultEntityId()` influences Home Assistant's entity ID only when it first creates the entity; existing users can retain a customized entity ID in the entity registry.
Common entity discovery metadata can be configured on most entity types via:
- `setEnabledByDefault(bool)`
- `setEntityPicture(const char*)`
- `setQos(uint8_t)`
- `setEncoding(const char*)`
- `setEntityCategory(const char*)`
### Runtime discovery changes
After changing discovery-related settings at runtime:
- `HABaseDeviceType::republishDiscovery()` to refresh discovery.
- `HABaseDeviceType::removeFromDiscovery()` to remove one entity from discovery.
In single-component mode, removal clears that entity's retained config topic. In device discovery mode, Home Assistant requires a platform-only component marker (`{"p":"sensor"}`, for example), followed by a compacted device bundle that omits the component. ArduinoHA performs both publishes. Call `republishDiscovery()` on that entity to add it back.
## Identifier and lifetime checklist
- Give `HADevice` a stable, non-empty unique ID and each entity a stable, topic-safe ID (`A-Z`, `a-z`, `0-9`, `_`, `-`).
- Use `enableExtendedUniqueIds()` when multiple devices could otherwise reuse the same entity IDs.
- Metadata setters store pointers; retain their backing strings. `HAText` copies the current state and command text it receives, so its state does not borrow a transient MQTT buffer.
## Trimming flash (optional)
You can exclude unused entity implementations with macros (see [MQTT usage](mqtt-usage.md#compiler-macros)).
+35
View File
@@ -0,0 +1,35 @@
# Entities
ArduinoHA supports these Home Assistant MQTT discovery entity classes. Choose the focused example where possible; it shows the entity's update or command callback pattern in a runnable sketch.
| Entity | Example |
| --- | --- |
| Binary sensor | [binary-sensor](../examples/binary-sensor/binary-sensor.ino) |
| Button | [button](../examples/button/button.ino) |
| Camera | [esp32-cam](../examples/esp32-cam/esp32-cam.ino) |
| Cover | [cover](../examples/cover/cover.ino) |
| Device tracker | Use the API header; no dedicated sketch yet |
| Device trigger | [multi-state-button](../examples/multi-state-button/multi-state-button.ino) |
| Fan | [fan](../examples/fan/fan.ino) |
| HVAC | [hvac](../examples/hvac/hvac.ino) |
| Light | [light](../examples/light/light.ino) |
| Lock | [lock](../examples/lock/lock.ino) |
| Number | [number](../examples/number/number.ino) |
| Scene | [scene](../examples/scene/scene.ino) |
| Select | [select](../examples/select/select.ino) |
| Sensor | [sensor](../examples/sensor/sensor.ino), [sensor-analog](../examples/sensor-analog/sensor-analog.ino), or [sensor-integer](../examples/sensor-integer/sensor-integer.ino) |
| Switch | [led-switch](../examples/led-switch/led-switch.ino) or [multi-switch](../examples/multi-switch/multi-switch.ino) |
| Tag scanner | [tag-scanner](../examples/tag-scanner/tag-scanner.ino) |
| Text | Use the API header; no dedicated sketch yet |
The library does not currently implement alarm control panels, events,
humidifiers, images, lawn mowers, sirens, updates, vacuums, valves, or water
heaters. They cannot be enabled through configuration.
## Common lifecycle
Create long-lived `HADevice`, `HAMqtt`, and entity objects, then call `mqtt.begin(...)` once and `mqtt.loop()` regularly. Entities may be constructed before or after `HAMqtt`; both orders register safely. Read [Getting started](getting-started.md) for the connection flow and [device discovery](device-and-discovery.md) for discovery settings.
For shared online/offline state, use `device.enableSharedAvailability()` and `device.enableLastWill()` before connecting. The [availability examples](../examples/availability/) show the simplest setup, while [advanced availability](../examples/advanced-availability/) covers custom payloads and Last Will behaviour.
Back to the [documentation map](README.md).
+107
View File
@@ -0,0 +1,107 @@
# Getting started
## Prerequisites
ArduinoHA talks to Home Assistant over **MQTT** (TCP). You need an MQTT broker reachable from your board. On Home Assistant OS, the [Mosquitto add-on](https://github.com/home-assistant/addons/blob/master/mosquitto/DOCS.md) is a common choice.
## Install the library
**PlatformIO (recommended):** add the maintained release tag in
`platformio.ini`. Its [`library.json`](../library.json) resolves PubSubClient:
```ini
lib_deps =
home-assistant-integration=https://github.com/alexhopeoconnor/arduino-home-assistant.git#v3.2.1
```
**Arduino IDE:** this fork is not indexed by Library Manager. Download the
source archive for a release, extract it, move the extracted library directory
to `<sketchbook>/libraries/home-assistant-integration`, and restart the IDE.
You also need a network `Client` (Ethernet or Wi-Fi) compatible with the
Arduino networking API.
## Minimal layout
1. Create **`HADevice`** and **`HAMqtt`** once (global or inside a long-lived object).
2. Call **`HAMqtt::begin(...)`** once, at the **end** of `setup()` — it only stores broker settings; the actual connection runs during **`HAMqtt::loop()`**.
3. Call **`mqtt.loop()`** regularly in `loop()` (not necessarily every iteration).
4. Construct **entity classes** (sensors, switches, …) before or after `HAMqtt`; ArduinoHA registers both orders. Keep all objects alive for the whole MQTT lifetime and configure discovery before the first connection.
### Ethernet (example)
```cpp
#include <Ethernet.h>
#include <ArduinoHA.h>
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
void setup() {
Ethernet.begin(mac); // Bring up the network Client before MQTT can connect.
mqtt.begin("192.168.1.50", "mqtt_user", "mqtt_password"); // Connection begins in mqtt.loop().
}
void loop() {
Ethernet.maintain(); // Renews DHCP leases where the Ethernet library requires it.
mqtt.loop(); // Services MQTT connection, discovery, and entity traffic.
}
```
### ESP8266 / ESP32 (example)
```cpp
#if defined(ESP8266)
#include <ESP8266WiFi.h>
#elif defined(ESP32)
#include <WiFi.h>
#endif
#include <ArduinoHA.h>
WiFiClient client;
HADevice device;
HAMqtt mqtt(client, device);
void setup() {
byte mac[WL_MAC_ADDR_LENGTH];
WiFi.macAddress(mac);
device.setUniqueId(mac, sizeof(mac));
WiFi.begin("SSID", "password");
// Keep this blocking wait only in a minimal sketch. Production firmware
// should retry, time out, or hand control to its provisioning flow.
while (WiFi.status() != WL_CONNECTED) {
delay(500);
}
// begin() stores broker settings; mqtt.loop() performs connection and recovery.
mqtt.begin("192.168.1.50", "mqtt_user", "mqtt_password");
}
void loop() {
mqtt.loop(); // Service reconnects, subscriptions, and discovery publishing.
}
```
## `begin()` variants
All are valid; pick one. Hostnames work instead of IP addresses.
- `mqtt.begin("192.168.1.50")` — anonymous, port 1883
- `mqtt.begin("192.168.1.50", 8888)` — anonymous, custom port
- `mqtt.begin("192.168.1.50", "user", "pass")` — credentials, port 1883
- `mqtt.begin("192.168.1.50", 8888, "user", "pass")` — credentials + custom port
`begin()` is intentionally a one-time configuration call. Reconnects are owned by `mqtt.loop()`, which uses the configured reconnect interval. Do not call `begin()` in a reconnect timer. `mqtt.disconnect()` now also produces the registered disconnected and state-change callbacks, making an explicit shutdown observable in the same way as a transport loss.
Use Home Assistant **2024.11.0 or newer** when opting into device discovery. See [Device & discovery](device-and-discovery.md) for the required staged migration from an existing single-component device.
## Security note
Credentials go over **plain TCP** unless you use a TLS-capable stack and broker setup. On a trusted LAN this is often acceptable; treat untrusted networks accordingly.
## Examples
See [`examples/`](../examples/) — start with `nodemcu` / `nano33iot` or an entity example matching what you need.
+185
View File
@@ -0,0 +1,185 @@
# MQTT usage
## Callbacks and tuning
The following snippets extend a sketch that already owns long-lived `HADevice`, `HAMqtt`, and entity objects. Configure callbacks, discovery metadata, and availability before `mqtt.begin(...)`; call the publishing snippets later from normal application logic.
`HAMqtt` supports optional callbacks and PubSubClient tuning:
```cpp
// These callbacks are registered before mqtt.begin(...).
void onMessage(const char* topic, const uint8_t* payload, uint16_t length) { /* ... */ }
void onConnected() { /* ... */ }
void onDisconnected() { /* ... */ }
void onStateChanged(HAMqtt::ConnectionState state) { /* ... */ }
void setup() {
// A successful reconnect creates a new MQTT session, so onConnected runs again.
mqtt.onMessage(onMessage);
mqtt.onConnected(onConnected);
mqtt.onDisconnected(onDisconnected);
mqtt.onStateChanged(onStateChanged);
mqtt.setBufferSize(512); // Increase only when a larger MQTT packet is required.
mqtt.setKeepAlive(60); // Seconds; the default is 15.
mqtt.begin("192.168.1.50", "user", "pass");
}
```
## Custom subscriptions
Subscribe after each successful connection (for example in `onConnected`), because subscriptions are tied to the MQTT session:
```cpp
void onConnected() {
// MQTT subscriptions belong to this session and must be restored after reconnecting.
mqtt.subscribe("my/custom/topic");
}
```
Handle payloads in `onMessage`.
## Publishing arbitrary payloads
```cpp
// Call after mqtt.begin(...); retain controls whether the broker keeps this value.
void publishApplicationState() {
mqtt.publish("customTopic", "payload", false); // Not retained.
mqtt.publish("customTopic", "payload", true); // Retained.
}
```
## Availability
**Shared availability (recommended):** one availability topic for the whole device — works well with **Last Will** (LWT):
```cpp
// Configure device-wide availability before mqtt.begin(...).
void configureSharedAvailability() {
device.enableSharedAvailability();
device.setPayloadAvailable("up");
device.setPayloadNotAvailable("down");
device.enableLastWill(); // Broker publishes offline when TCP drops.
// device.setAvailability(false); // Optional: start as offline.
}
```
**Per-entity availability:** call `someEntity.setAvailability(true/false)` on each type. Does not use LWT the same way as shared mode; see examples under `examples/availability/`.
Custom per-entity payloads are supported:
```cpp
// Configure the relevant entity before mqtt.begin(...).
void configureSensorAvailability() {
sensor.setPayloadAvailable("ready");
sensor.setPayloadNotAvailable("lost");
}
```
For multi-topic availability discovery, add full MQTT topics and a mode:
```cpp
// `sensor` is the entity whose availability depends on these external topics.
void configureExternalAvailability() {
sensor.setAvailabilityMode("all");
sensor.addAvailabilityEntry("bridge/status");
sensor.addAvailabilityEntry("sensor/status", "{{ value_json.state }}");
}
```
## Discovery helpers by entity
Common entity discovery metadata is available on most entity classes:
```cpp
// `entity` is an entity type that supports these common discovery fields.
void configureCommonDiscovery(HABaseDeviceType& entity) {
entity.setEnabledByDefault(false);
entity.setEntityPicture("https://example.com/entity.png");
entity.setQos(1);
entity.setEncoding("utf-8");
entity.setEntityCategory("diagnostic");
}
```
Read-only sensor presentation/template helpers:
```cpp
// `sensor` is a read-only HASensor instance.
void configureSensorPresentation(HASensor& sensor) {
sensor.setSuggestedDisplayPrecision(2);
sensor.setValueTemplate("{{ value_json.temperature }}");
sensor.setJsonAttributesTemplate("{{ value_json.attrs | tojson }}");
sensor.setLastResetValueTemplate("{{ value_json.last_reset }}");
sensor.setDeviceClass("enum");
sensor.setOptions("idle;charging;discharging;fault");
}
```
Writable entity template/payload helpers:
```cpp
// These names refer to the matching writable entity instances in the application.
void configureWritableEntities(HASwitch& mySwitch,
HANumber& myNumber,
HASelect& mySelect,
HAText& myText,
HAButton& myButton) {
mySwitch.setPayloadOn("ENABLE");
mySwitch.setPayloadOff("DISABLE");
mySwitch.setStateOn("running");
mySwitch.setStateOff("stopped");
mySwitch.setValueTemplate("{{ value_json.state }}");
mySwitch.setCommandTemplate("{{ value_json.command }}");
myNumber.setPayloadReset("RESET");
myNumber.setCommandTemplate("{{ value | float | round(1) }}");
mySelect.setCommandTemplate("{{ value_json.choice }}");
myText.setCommandTemplate("{{ value_json.text }}");
myButton.setPayloadPress("PRESS");
}
```
## Compiler macros
Defined in `ArduinoHADefines.h` or via build flags.
- **`ARDUINOHA_DISABLE_STDFUNCTION`** — disables the default capturing-lambda and
`std::bind` overloads on entity command APIs. Use it on targets without a complete
`std::function` implementation or where code size/RAM matters (constrained AVR
builds are the usual case). ESP8266/ESP32 support the overloads. `HAMqtt`
lifecycle callbacks remain ordinary function pointers.
- **`ARDUINOHA_DEBUG`** — enables ArduinoHA logging by default and sets the initial maximum verbosity to `Debug`. Without this flag, structured logs are compiled in but remain disabled until you call `arduinoHASetLogEnabled(true)`.
Structured logging is available through a long-lived sink:
```cpp
class MyLogSink : public ArduinoHALogSink {
public:
void log(const ArduinoHALogMessage& msg) override {
Serial.print("[");
Serial.print(arduinoHALogLevelTag(msg.level));
Serial.print("][aha.");
Serial.print(msg.subsystem);
Serial.print("] ");
Serial.println(msg.text);
}
};
MyLogSink logSink; // The installed sink must outlive ArduinoHA logging.
void setup() {
Serial.begin(115200);
arduinoHASetLogSink(&logSink);
arduinoHASetLogEnabled(true);
arduinoHASetLogLevel(ArduinoHALogLevel::Trace);
}
```
`arduinoHALog(...)` and `arduinoHALogf(...)` support subsystem-tagged messages such as `mqtt`, `discovery`, `availability`, `serializer`, `entity`, and `device`. Install a sink when you want those messages to join your application’s normal serial or structured log stream.
Applications that use Wi-Fi can register **`arduinoHASetNetworkStatusFn`** with a callback returning `WiFi.status()`. Publish failure diagnostics can then include the current Wi-Fi status without coupling ArduinoHA to a particular network library.
**Exclude unused device types** (saves flash from vtables), e.g.:
`EX_ARDUINOHA_BINARY_SENSOR`, `EX_ARDUINOHA_BUTTON`, `EX_ARDUINOHA_CAMERA`, `EX_ARDUINOHA_COVER`, `EX_ARDUINOHA_DEVICE_TRACKER`, `EX_ARDUINOHA_DEVICE_TRIGGER`, `EX_ARDUINOHA_FAN`, `EX_ARDUINOHA_HVAC`, `EX_ARDUINOHA_LIGHT`, `EX_ARDUINOHA_LOCK`, `EX_ARDUINOHA_NUMBER`, `EX_ARDUINOHA_SCENE`, `EX_ARDUINOHA_SELECT`, `EX_ARDUINOHA_SENSOR`, `EX_ARDUINOHA_SWITCH`, `EX_ARDUINOHA_TAG_SCANNER`
+9
View File
@@ -0,0 +1,9 @@
# ESP Sensor
This is the first complete ArduinoHA project for an ESP8266 D1 mini or ESP32 development board. It connects Wi-Fi, derives a stable device ID from the board MAC address, and publishes a changing **Uptime** sensor to Home Assistant.
Before uploading, replace the `EXAMPLE_*` values in `include/ExampleNetwork.h`, or provide them as PlatformIO build flags. The header contains safe placeholders and must not contain real credentials when committed.
After MQTT connects, Home Assistant discovers **ArduinoHA sensor example** and its Uptime entity. Rebooting the board keeps the same Home Assistant identity because its MAC address is stable.
See [getting started](../../docs/getting-started.md) and the shared [examples guide](../README.md).
@@ -0,0 +1,37 @@
#pragma once
#if defined(ESP32)
#include <Network.h>
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif
#ifndef EXAMPLE_WIFI_SSID
#define EXAMPLE_WIFI_SSID "replace-with-wifi-name"
#endif
#ifndef EXAMPLE_WIFI_PASSWORD
#define EXAMPLE_WIFI_PASSWORD "replace-with-wifi-password"
#endif
#ifndef EXAMPLE_MQTT_HOST
#define EXAMPLE_MQTT_HOST "replace-with-mqtt-host"
#endif
#ifndef EXAMPLE_MQTT_USER
#define EXAMPLE_MQTT_USER ""
#endif
#ifndef EXAMPLE_MQTT_PASSWORD
#define EXAMPLE_MQTT_PASSWORD ""
#endif
inline void connectExampleWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(EXAMPLE_WIFI_SSID, EXAMPLE_WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(250);
}
}
inline void setExampleUniqueId(HADevice& device) {
uint8_t mac[6];
WiFi.macAddress(mac);
device.setUniqueId(mac, sizeof(mac));
}
+24
View File
@@ -0,0 +1,24 @@
[platformio]
default_envs = esp8266
[common]
framework = arduino
lib_ldf_mode = deep+
lib_deps =
home-assistant-integration=symlink://../..
[env:esp8266]
extends = common
platform = espressif8266
board = d1_mini
platform_packages =
platformio/framework-arduinoespressif8266 @ https://github.com/esp8266/Arduino.git#521ae60a89e64bb0d1eb7a0b7addf620ced5cad3
[env:esp32]
extends = common
platform = https://github.com/pioarduino/platform-espressif32/releases/download/55.03.311/platform-espressif32.zip
board = esp32dev
build_unflags = -std=gnu++11
build_flags =
-std=gnu++14
-I${platformio.packages_dir}/framework-arduinoespressif32/libraries/Network/src
+30
View File
@@ -0,0 +1,30 @@
#include <Arduino.h>
#include <ArduinoHA.h>
#include "ExampleNetwork.h"
WiFiClient client;
HADevice device;
HAMqtt mqtt(client, device);
HASensorNumber uptime("uptime");
void setup() {
Serial.begin(115200);
connectExampleWiFi();
setExampleUniqueId(device);
device.setName("ArduinoHA sensor example");
device.setSoftwareVersion("1.0.0");
uptime.setName("Uptime");
uptime.setUnitOfMeasurement("s");
mqtt.begin(EXAMPLE_MQTT_HOST, EXAMPLE_MQTT_USER, EXAMPLE_MQTT_PASSWORD);
}
void loop() {
mqtt.loop();
static unsigned long lastUpdate = 0;
if (millis() - lastUpdate >= 1000) {
uptime.setValue(static_cast<uint32_t>(millis() / 1000));
lastUpdate = millis();
}
}
+9
View File
@@ -0,0 +1,9 @@
# Switch Callback
This example creates one writable Home Assistant switch. When Home Assistant sends a command, `onOutputCommand()` changes the local output and immediately reports the resulting state back through the supplied `HASwitch`.
The ESP8266 build uses `LED_BUILTIN`; the ESP32 build uses GPIO 2. Confirm your board’s LED polarity before treating that output as a real load.
Set the Wi-Fi and MQTT placeholders in `include/ExampleNetwork.h`, flash the board, then toggle **Example output** in Home Assistant.
See [MQTT usage](../../docs/mqtt-usage.md) and the shared [examples guide](../README.md).
@@ -0,0 +1,37 @@
#pragma once
#if defined(ESP32)
#include <Network.h>
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif
#ifndef EXAMPLE_WIFI_SSID
#define EXAMPLE_WIFI_SSID "replace-with-wifi-name"
#endif
#ifndef EXAMPLE_WIFI_PASSWORD
#define EXAMPLE_WIFI_PASSWORD "replace-with-wifi-password"
#endif
#ifndef EXAMPLE_MQTT_HOST
#define EXAMPLE_MQTT_HOST "replace-with-mqtt-host"
#endif
#ifndef EXAMPLE_MQTT_USER
#define EXAMPLE_MQTT_USER ""
#endif
#ifndef EXAMPLE_MQTT_PASSWORD
#define EXAMPLE_MQTT_PASSWORD ""
#endif
inline void connectExampleWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(EXAMPLE_WIFI_SSID, EXAMPLE_WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(250);
}
}
inline void setExampleUniqueId(HADevice& device) {
uint8_t mac[6];
WiFi.macAddress(mac);
device.setUniqueId(mac, sizeof(mac));
}
@@ -0,0 +1,24 @@
[platformio]
default_envs = esp8266
[common]
framework = arduino
lib_ldf_mode = deep+
lib_deps =
home-assistant-integration=symlink://../..
[env:esp8266]
extends = common
platform = espressif8266
board = d1_mini
platform_packages =
platformio/framework-arduinoespressif8266 @ https://github.com/esp8266/Arduino.git#521ae60a89e64bb0d1eb7a0b7addf620ced5cad3
[env:esp32]
extends = common
platform = https://github.com/pioarduino/platform-espressif32/releases/download/55.03.311/platform-espressif32.zip
board = esp32dev
build_unflags = -std=gnu++11
build_flags =
-std=gnu++14
-I${platformio.packages_dir}/framework-arduinoespressif32/libraries/Network/src
+36
View File
@@ -0,0 +1,36 @@
#include <Arduino.h>
#include <ArduinoHA.h>
#include "ExampleNetwork.h"
#if defined(ESP32)
constexpr uint8_t kOutputPin = 2;
#else
constexpr uint8_t kOutputPin = LED_BUILTIN;
#endif
WiFiClient client;
HADevice device;
HAMqtt mqtt(client, device);
HASwitch output("output");
void onOutputCommand(bool state, HASwitch* sender) {
digitalWrite(kOutputPin, state ? HIGH : LOW);
sender->setState(state);
}
void setup() {
Serial.begin(115200);
pinMode(kOutputPin, OUTPUT);
digitalWrite(kOutputPin, LOW);
connectExampleWiFi();
setExampleUniqueId(device);
device.setName("ArduinoHA switch example");
output.setName("Example output");
output.onCommand(onOutputCommand);
mqtt.begin(EXAMPLE_MQTT_HOST, EXAMPLE_MQTT_USER, EXAMPLE_MQTT_PASSWORD);
}
void loop() {
mqtt.loop();
}
@@ -0,0 +1,9 @@
# Multi-entity Device
This example groups an Uptime sensor and writable output under one `HADevice`. It adds common metadata, one shared availability topic, and MQTT Last Will so Home Assistant marks the complete device unavailable if its network connection disappears.
Configure `include/ExampleNetwork.h`, flash the selected target, and inspect the device page in Home Assistant. Both entities belong to **ArduinoHA multi-entity example** and share its availability state.
Use this shape when one physical board exposes several related controls or sensors.
See [device and discovery](../../docs/device-and-discovery.md) and [MQTT usage](../../docs/mqtt-usage.md).
@@ -0,0 +1,37 @@
#pragma once
#if defined(ESP32)
#include <Network.h>
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif
#ifndef EXAMPLE_WIFI_SSID
#define EXAMPLE_WIFI_SSID "replace-with-wifi-name"
#endif
#ifndef EXAMPLE_WIFI_PASSWORD
#define EXAMPLE_WIFI_PASSWORD "replace-with-wifi-password"
#endif
#ifndef EXAMPLE_MQTT_HOST
#define EXAMPLE_MQTT_HOST "replace-with-mqtt-host"
#endif
#ifndef EXAMPLE_MQTT_USER
#define EXAMPLE_MQTT_USER ""
#endif
#ifndef EXAMPLE_MQTT_PASSWORD
#define EXAMPLE_MQTT_PASSWORD ""
#endif
inline void connectExampleWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(EXAMPLE_WIFI_SSID, EXAMPLE_WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(250);
}
}
inline void setExampleUniqueId(HADevice& device) {
uint8_t mac[6];
WiFi.macAddress(mac);
device.setUniqueId(mac, sizeof(mac));
}
@@ -0,0 +1,24 @@
[platformio]
default_envs = esp8266
[common]
framework = arduino
lib_ldf_mode = deep+
lib_deps =
home-assistant-integration=symlink://../..
[env:esp8266]
extends = common
platform = espressif8266
board = d1_mini
platform_packages =
platformio/framework-arduinoespressif8266 @ https://github.com/esp8266/Arduino.git#521ae60a89e64bb0d1eb7a0b7addf620ced5cad3
[env:esp32]
extends = common
platform = https://github.com/pioarduino/platform-espressif32/releases/download/55.03.311/platform-espressif32.zip
board = esp32dev
build_unflags = -std=gnu++11
build_flags =
-std=gnu++14
-I${platformio.packages_dir}/framework-arduinoespressif32/libraries/Network/src
@@ -0,0 +1,48 @@
#include <Arduino.h>
#include <ArduinoHA.h>
#include "ExampleNetwork.h"
#if defined(ESP32)
constexpr uint8_t kOutputPin = 2;
#else
constexpr uint8_t kOutputPin = LED_BUILTIN;
#endif
WiFiClient client;
HADevice device;
HAMqtt mqtt(client, device);
HASensorNumber uptime("uptime");
HASwitch output("output");
void onOutputCommand(bool state, HASwitch* sender) {
digitalWrite(kOutputPin, state ? HIGH : LOW);
sender->setState(state);
}
void setup() {
Serial.begin(115200);
pinMode(kOutputPin, OUTPUT);
connectExampleWiFi();
setExampleUniqueId(device);
device.setName("ArduinoHA multi-entity example");
device.setManufacturer("Example Devices");
device.setSoftwareVersion("1.0.0");
device.enableSharedAvailability();
device.enableLastWill();
uptime.setName("Uptime");
uptime.setUnitOfMeasurement("s");
output.setName("Example output");
output.onCommand(onOutputCommand);
mqtt.begin(EXAMPLE_MQTT_HOST, EXAMPLE_MQTT_USER, EXAMPLE_MQTT_PASSWORD);
}
void loop() {
mqtt.loop();
static unsigned long lastUpdate = 0;
if (millis() - lastUpdate >= 1000) {
uptime.setValue(static_cast<uint32_t>(millis() / 1000));
lastUpdate = millis();
}
}
+9
View File
@@ -0,0 +1,9 @@
# Device Discovery
This example opts into Home Assistant MQTT device discovery. Instead of one retained discovery document per entity, ArduinoHA publishes one device document containing the component definitions and richer board metadata.
Use device discovery for a **new** device on Home Assistant 2024.11.0 or newer. Do not enable it on a device that has already published traditional single-component discovery without following the documented migration procedure.
After configuring `include/ExampleNetwork.h` and flashing the board, Home Assistant discovers **ArduinoHA device discovery example** and its Uptime sensor.
See [device discovery](../../docs/device-and-discovery.md#single-component-vs-device-discovery) and the shared [examples guide](../README.md).
@@ -0,0 +1,37 @@
#pragma once
#if defined(ESP32)
#include <Network.h>
#include <WiFi.h>
#else
#include <ESP8266WiFi.h>
#endif
#ifndef EXAMPLE_WIFI_SSID
#define EXAMPLE_WIFI_SSID "replace-with-wifi-name"
#endif
#ifndef EXAMPLE_WIFI_PASSWORD
#define EXAMPLE_WIFI_PASSWORD "replace-with-wifi-password"
#endif
#ifndef EXAMPLE_MQTT_HOST
#define EXAMPLE_MQTT_HOST "replace-with-mqtt-host"
#endif
#ifndef EXAMPLE_MQTT_USER
#define EXAMPLE_MQTT_USER ""
#endif
#ifndef EXAMPLE_MQTT_PASSWORD
#define EXAMPLE_MQTT_PASSWORD ""
#endif
inline void connectExampleWiFi() {
WiFi.mode(WIFI_STA);
WiFi.begin(EXAMPLE_WIFI_SSID, EXAMPLE_WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
delay(250);
}
}
inline void setExampleUniqueId(HADevice& device) {
uint8_t mac[6];
WiFi.macAddress(mac);
device.setUniqueId(mac, sizeof(mac));
}
@@ -0,0 +1,24 @@
[platformio]
default_envs = esp8266
[common]
framework = arduino
lib_ldf_mode = deep+
lib_deps =
home-assistant-integration=symlink://../..
[env:esp8266]
extends = common
platform = espressif8266
board = d1_mini
platform_packages =
platformio/framework-arduinoespressif8266 @ https://github.com/esp8266/Arduino.git#521ae60a89e64bb0d1eb7a0b7addf620ced5cad3
[env:esp32]
extends = common
platform = https://github.com/pioarduino/platform-espressif32/releases/download/55.03.311/platform-espressif32.zip
board = esp32dev
build_unflags = -std=gnu++11
build_flags =
-std=gnu++14
-I${platformio.packages_dir}/framework-arduinoespressif32/libraries/Network/src
+33
View File
@@ -0,0 +1,33 @@
#include <Arduino.h>
#include <ArduinoHA.h>
#include "ExampleNetwork.h"
WiFiClient client;
HADevice device;
HAMqtt mqtt(client, device);
HASensorNumber uptime("uptime");
void setup() {
Serial.begin(115200);
connectExampleWiFi();
setExampleUniqueId(device);
device.setName("ArduinoHA device discovery example");
device.setManufacturer("Example Devices");
device.setModel("ESP example");
device.setSoftwareVersion("1.0.0");
uptime.setName("Uptime");
uptime.setUnitOfMeasurement("s");
mqtt.enableDeviceDiscovery();
mqtt.begin(EXAMPLE_MQTT_HOST, EXAMPLE_MQTT_USER, EXAMPLE_MQTT_PASSWORD);
}
void loop() {
mqtt.loop();
static unsigned long lastUpdate = 0;
if (millis() - lastUpdate >= 1000) {
uptime.setValue(static_cast<uint32_t>(millis() / 1000));
lastUpdate = millis();
}
}
+45
View File
@@ -0,0 +1,45 @@
# ArduinoHA examples
Start with a guided PlatformIO project when you are new to the library. Each one builds for ESP8266 and ESP32, contains safe placeholder credentials, and explains the Home Assistant result you should see.
```bash
pio run -d examples/01-esp-sensor -e esp8266
pio run -d examples/01-esp-sensor -e esp8266 -t upload
```
The checked-in `esp32` environment uses Arduino-ESP32 3.3.11. A consuming
application should choose and pin its complete PlatformIO platform stack.
| Guided example | What it demonstrates |
| --- | --- |
| [ESP Sensor](01-esp-sensor/) | Wi-Fi application wiring, a unique device ID, and changing numeric telemetry |
| [Switch Callback](02-switch-callback/) | A Home Assistant command callback and local state acknowledgement |
| [Multi-entity Device](03-multi-entity-device/) | Multiple entities, shared availability, and MQTT Last Will |
| [Device Discovery](04-device-discovery/) | One device-discovery document for a newly deployed device |
## Entity recipes
The original focused sketches remain useful as short API recipes. They are intentionally transport-specific Arduino sketches, rather than full product firmware.
| Recipe | Home Assistant behaviour |
| --- | --- |
| [binary-sensor](binary-sensor/binary-sensor.ino) | Door/contact-style binary state |
| [button](button/button.ino) | Press action |
| [cover](cover/cover.ino) | Open, close, and stop commands |
| [esp32-cam](esp32-cam/esp32-cam.ino) | ESP32 camera preview |
| [fan](fan/fan.ino) | State and speed commands |
| [hvac](hvac/hvac.ino) | Modes, power, and target temperature |
| [led-switch](led-switch/led-switch.ino) | Basic writable switch |
| [light](light/light.ino) | Brightness, colour temperature, and RGB |
| [lock](lock/lock.ino) | Writable lock state |
| [multi-state-button](multi-state-button/multi-state-button.ino) | Device triggers from a wall switch |
| [multi-switch](multi-switch/multi-switch.ino) | Multiple writable switches |
| [number](number/number.ino) | Writable numeric value |
| [scene](scene/scene.ino) | Scene trigger |
| [select](select/select.ino) | Writable option list |
| [sensor](sensor/sensor.ino) | String state sensor |
| [sensor-analog](sensor-analog/sensor-analog.ino) | Analog voltage measurement |
| [sensor-integer](sensor-integer/sensor-integer.ino) | Integer uptime measurement |
| [tag-scanner](tag-scanner/tag-scanner.ino) | RFID tag reporting |
See the [entity guide](../docs/entities.md) and [project overview](../README.md).
@@ -0,0 +1,75 @@
#include <Ethernet.h>
#include <ArduinoHA.h>
#define INPUT_PIN 9
#define BROKER_ADDR IPAddress(192,168,0,17)
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
unsigned long lastReadAt = millis();
unsigned long lastAvailabilityToggleAt = millis();
bool lastInputState = false;
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
// "myInput" is unique ID of the sensor. You should define you own ID.
HABinarySensor sensor("myInput");
void setup() {
pinMode(INPUT_PIN, INPUT_PULLUP);
lastInputState = digitalRead(INPUT_PIN);
// you don't need to verify return status
Ethernet.begin(mac);
lastReadAt = millis();
lastAvailabilityToggleAt = millis();
// set device's details (optional)
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");
mqtt.setOriginSupportUrl("https://example.com/device-help");
sensor.setCurrentState(lastInputState); // optional
sensor.setName("Door sensor"); // optional
sensor.setDeviceClass("door"); // optional
sensor.setPayloadAvailable("ready");
sensor.setPayloadNotAvailable("lost");
// Optional multi-topic discovery metadata for external health sources.
// Runtime availability publishing still uses sensor.setAvailability(...).
// sensor.setAvailabilityMode("all");
// sensor.addAvailabilityEntry("bridge/status");
// sensor.addAvailabilityEntry("sensor/health", "{{ value_json.state }}");
// This method enables availability for all device types registered on the device.
// For example, if you have 5 sensors on the same device, you can enable
// shared availability and change availability state of all sensors using
// single method call "device.setAvailability(false|true)"
device.enableSharedAvailability();
// Optionally, you can enable MQTT LWT feature. If device will lose connection
// to the broker, all device types related to it will be marked as offline in
// the Home Assistant Panel.
device.enableLastWill();
mqtt.begin(BROKER_ADDR);
}
void loop() {
Ethernet.maintain();
mqtt.loop();
if ((millis() - lastReadAt) > 30) { // read in 30ms interval
// library produces MQTT message if a new state is different than the previous one
sensor.setState(digitalRead(INPUT_PIN));
lastInputState = sensor.getCurrentState();
lastReadAt = millis();
}
if ((millis() - lastAvailabilityToggleAt) > 5000) {
device.setAvailability(!device.isAvailable());
lastAvailabilityToggleAt = millis();
}
}
-31
View File
@@ -1,31 +0,0 @@
# Home Assistant availability example
This example shows how to use "availability" feature of the Home Assistant.
It's supported only by following device types:
* Binary sensor
* Sensor
* Switch
## Initialization and usage
Availability feature is turned off by default. In order to turn it on for the specific
sensor/switch you need to set initial state of the unit by calling `setAvailability` method.
Example:
```cpp
...
HABinarySensor sensor("input", "door", true, mqtt);
void setup() {
// ...
// method must be called before `mqtt.begin(...)`
sensor.setAvailability(false); // offline
mqtt.begin(BROKER_ADDR);
}
...
```
After availability is set for the very first time you can call `setAvailability` in any time.
Each time the method is called, the device will publish MQTT message to the broker.
+8 -5
View File
@@ -13,10 +13,8 @@ EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
// "input" may be anything you want to be displayed in HA panel
// "door" is device class (based on the class HA displays different icons in the panel)
// "true" is initial state of the sensor. In this example it's "true" as we use pullup resistor
HABinarySensor sensor("input", "door", true, mqtt);
// "myInput" is unique ID of the sensor. You should define you own ID.
HABinarySensor sensor("myInput");
void setup() {
pinMode(INPUT_PIN, INPUT_PULLUP);
@@ -26,6 +24,7 @@ void setup() {
Ethernet.begin(mac);
// turn on "availability" feature
// this method also sets initial availability so you can use "true" or "false"
sensor.setAvailability(false);
lastReadAt = millis();
@@ -35,6 +34,10 @@ void setup() {
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");
sensor.setCurrentState(lastInputState); // optional
sensor.setName("Door sensor"); // optional
sensor.setDeviceClass("door"); // optional
mqtt.begin(BROKER_ADDR);
}
@@ -45,7 +48,7 @@ void loop() {
if ((millis() - lastReadAt) > 30) { // read in 30ms interval
// library produces MQTT message if a new state is different than the previous one
sensor.setState(digitalRead(INPUT_PIN));
lastInputState = sensor.getState();
lastInputState = sensor.getCurrentState();
lastReadAt = millis();
}
+11 -6
View File
@@ -12,10 +12,8 @@ EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
// "input" may be anything you want to be displayed in HA panel
// "door" is device class (based on the class HA displays different icons in the panel)
// "true" is initial state of the sensor. In this example it's "true" as we use pullup resistor
HABinarySensor sensor("input", "door", true, mqtt);
// "myInput" is unique ID of the sensor. You should define you own ID.
HABinarySensor sensor("myInput");
void setup() {
pinMode(INPUT_PIN, INPUT_PULLUP);
@@ -24,10 +22,16 @@ void setup() {
// you don't need to verify return status
Ethernet.begin(mac);
// set device's details (optional)
// optional device's details
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");
// optional properties
sensor.setCurrentState(lastInputState);
sensor.setName("Door sensor");
sensor.setDeviceClass("door");
sensor.setIcon("mdi:fire");
mqtt.begin(BROKER_ADDR);
}
@@ -35,10 +39,11 @@ void loop() {
Ethernet.maintain();
mqtt.loop();
// reading the digital input of the Arduino device
if ((millis() - lastReadAt) > 30) { // read in 30ms interval
// library produces MQTT message if a new state is different than the previous one
sensor.setState(digitalRead(INPUT_PIN));
lastInputState = sensor.getState();
lastInputState = sensor.getCurrentState();
lastReadAt = millis();
}
}
+51
View File
@@ -0,0 +1,51 @@
#include <Ethernet.h>
#include <ArduinoHA.h>
#define BROKER_ADDR IPAddress(192,168,0,17)
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
// "myButtonA" and "myButtonB" are unique IDs of buttons. You should define you own ID.
HAButton buttonA("myButtonA");
HAButton buttonB("myButtonB");
void onButtonCommand(HAButton* sender)
{
if (sender == &buttonA) {
// button A was clicked, do your logic here
} else if (sender == &buttonB) {
// button B was clicked, do your logic here
}
}
void setup() {
// you don't need to verify return status
Ethernet.begin(mac);
// optional device's details
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");
// optional properties
buttonA.setIcon("mdi:fire");
buttonA.setName("Click me A");
// buttonA.setPayloadPress("PRESS_A");
// buttonA.setCommandTemplate("{{ value_json.command }}");
buttonB.setIcon("mdi:home");
buttonB.setName("Click me B");
// press callbacks
buttonA.onCommand(onButtonCommand);
buttonB.onCommand(onButtonCommand);
mqtt.begin(BROKER_ADDR);
}
void loop() {
Ethernet.maintain();
mqtt.loop();
}
+70
View File
@@ -0,0 +1,70 @@
#include <Ethernet.h>
#include <ArduinoHA.h>
#define BROKER_ADDR IPAddress(192,168,0,17)
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
// "myCover" is unique ID of the cover. You should define your own ID.
HACover cover("myCover", HACover::PositionFeature);
// PositionFeature is optional, however required to be in a "stopped" state other than open or closed.
// If ommitted, a CommandStop will result in HA treating the cover as either Open or Closed immediately after the command.
// See https://www.home-assistant.io/integrations/cover.mqtt/
// Added in https://github.com/dawidchyrzynski/arduino-home-assistant/pull/111
void onCoverCommand(HACover::CoverCommand cmd, HACover* sender) {
if (cmd == HACover::CommandOpen) {
Serial.println("Command: Open");
sender->setState(HACover::StateOpening); // report state back to the HA
} else if (cmd == HACover::CommandClose) {
Serial.println("Command: Close");
sender->setState(HACover::StateClosing); // report state back to the HA
} else if (cmd == HACover::CommandStop) {
Serial.println("Command: Stop");
sender->setState(HACover::StateStopped); // report state back to the HA
}
// Available states:
// HACover::StateClosed
// HACover::StateClosing
// HACover::StateOpen
// HACover::StateOpening
// HACover::StateStopped
// You can also report position using setPosition() method
}
void setup() {
Serial.begin(9600);
Ethernet.begin(mac);
// optional device's details
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");
cover.onCommand(onCoverCommand);
cover.setName("My cover"); // optional
// Optionally you can set retain flag for the HA commands
// cover.setRetain(true);
// Optionally you can enable optimistic mode for the HACover.
// In this mode you won't need to report state back to the HA when commands are executed.
// cover.setOptimistic(true);
mqtt.begin(BROKER_ADDR);
}
void loop() {
Ethernet.maintain();
mqtt.loop();
// You can also change the state at runtime as shown below.
// This kind of logic can be used if you want to control your cover using a button connected to the device.
// cover.setState(HACover::StateOpening); // use any state you want
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+273
View File
@@ -0,0 +1,273 @@
#if defined(CAMERA_MODEL_WROVER_KIT)
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 21
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 19
#define Y4_GPIO_NUM 18
#define Y3_GPIO_NUM 5
#define Y2_GPIO_NUM 4
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22
#elif defined(CAMERA_MODEL_ESP_EYE)
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 4
#define SIOD_GPIO_NUM 18
#define SIOC_GPIO_NUM 23
#define Y9_GPIO_NUM 36
#define Y8_GPIO_NUM 37
#define Y7_GPIO_NUM 38
#define Y6_GPIO_NUM 39
#define Y5_GPIO_NUM 35
#define Y4_GPIO_NUM 14
#define Y3_GPIO_NUM 13
#define Y2_GPIO_NUM 34
#define VSYNC_GPIO_NUM 5
#define HREF_GPIO_NUM 27
#define PCLK_GPIO_NUM 25
#elif defined(CAMERA_MODEL_M5STACK_PSRAM)
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM 15
#define XCLK_GPIO_NUM 27
#define SIOD_GPIO_NUM 25
#define SIOC_GPIO_NUM 23
#define Y9_GPIO_NUM 19
#define Y8_GPIO_NUM 36
#define Y7_GPIO_NUM 18
#define Y6_GPIO_NUM 39
#define Y5_GPIO_NUM 5
#define Y4_GPIO_NUM 34
#define Y3_GPIO_NUM 35
#define Y2_GPIO_NUM 32
#define VSYNC_GPIO_NUM 22
#define HREF_GPIO_NUM 26
#define PCLK_GPIO_NUM 21
#elif defined(CAMERA_MODEL_M5STACK_V2_PSRAM)
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM 15
#define XCLK_GPIO_NUM 27
#define SIOD_GPIO_NUM 22
#define SIOC_GPIO_NUM 23
#define Y9_GPIO_NUM 19
#define Y8_GPIO_NUM 36
#define Y7_GPIO_NUM 18
#define Y6_GPIO_NUM 39
#define Y5_GPIO_NUM 5
#define Y4_GPIO_NUM 34
#define Y3_GPIO_NUM 35
#define Y2_GPIO_NUM 32
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 26
#define PCLK_GPIO_NUM 21
#elif defined(CAMERA_MODEL_M5STACK_WIDE)
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM 15
#define XCLK_GPIO_NUM 27
#define SIOD_GPIO_NUM 22
#define SIOC_GPIO_NUM 23
#define Y9_GPIO_NUM 19
#define Y8_GPIO_NUM 36
#define Y7_GPIO_NUM 18
#define Y6_GPIO_NUM 39
#define Y5_GPIO_NUM 5
#define Y4_GPIO_NUM 34
#define Y3_GPIO_NUM 35
#define Y2_GPIO_NUM 32
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 26
#define PCLK_GPIO_NUM 21
#elif defined(CAMERA_MODEL_M5STACK_ESP32CAM)
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM 15
#define XCLK_GPIO_NUM 27
#define SIOD_GPIO_NUM 25
#define SIOC_GPIO_NUM 23
#define Y9_GPIO_NUM 19
#define Y8_GPIO_NUM 36
#define Y7_GPIO_NUM 18
#define Y6_GPIO_NUM 39
#define Y5_GPIO_NUM 5
#define Y4_GPIO_NUM 34
#define Y3_GPIO_NUM 35
#define Y2_GPIO_NUM 17
#define VSYNC_GPIO_NUM 22
#define HREF_GPIO_NUM 26
#define PCLK_GPIO_NUM 21
#elif defined(CAMERA_MODEL_M5STACK_UNITCAM)
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM 15
#define XCLK_GPIO_NUM 27
#define SIOD_GPIO_NUM 25
#define SIOC_GPIO_NUM 23
#define Y9_GPIO_NUM 19
#define Y8_GPIO_NUM 36
#define Y7_GPIO_NUM 18
#define Y6_GPIO_NUM 39
#define Y5_GPIO_NUM 5
#define Y4_GPIO_NUM 34
#define Y3_GPIO_NUM 35
#define Y2_GPIO_NUM 32
#define VSYNC_GPIO_NUM 22
#define HREF_GPIO_NUM 26
#define PCLK_GPIO_NUM 21
#elif defined(CAMERA_MODEL_AI_THINKER)
#define PWDN_GPIO_NUM 32
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 0
#define SIOD_GPIO_NUM 26
#define SIOC_GPIO_NUM 27
#define Y9_GPIO_NUM 35
#define Y8_GPIO_NUM 34
#define Y7_GPIO_NUM 39
#define Y6_GPIO_NUM 36
#define Y5_GPIO_NUM 21
#define Y4_GPIO_NUM 19
#define Y3_GPIO_NUM 18
#define Y2_GPIO_NUM 5
#define VSYNC_GPIO_NUM 25
#define HREF_GPIO_NUM 23
#define PCLK_GPIO_NUM 22
#elif defined(CAMERA_MODEL_TTGO_T_JOURNAL)
#define PWDN_GPIO_NUM 0
#define RESET_GPIO_NUM 15
#define XCLK_GPIO_NUM 27
#define SIOD_GPIO_NUM 25
#define SIOC_GPIO_NUM 23
#define Y9_GPIO_NUM 19
#define Y8_GPIO_NUM 36
#define Y7_GPIO_NUM 18
#define Y6_GPIO_NUM 39
#define Y5_GPIO_NUM 5
#define Y4_GPIO_NUM 34
#define Y3_GPIO_NUM 35
#define Y2_GPIO_NUM 17
#define VSYNC_GPIO_NUM 22
#define HREF_GPIO_NUM 26
#define PCLK_GPIO_NUM 21
#elif defined(CAMERA_MODEL_ESP32_CAM_BOARD)
// The 18 pin header on the board has Y5 and Y3 swapped
#define USE_BOARD_HEADER 0
#define PWDN_GPIO_NUM 32
#define RESET_GPIO_NUM 33
#define XCLK_GPIO_NUM 4
#define SIOD_GPIO_NUM 18
#define SIOC_GPIO_NUM 23
#define Y9_GPIO_NUM 36
#define Y8_GPIO_NUM 19
#define Y7_GPIO_NUM 21
#define Y6_GPIO_NUM 39
#if USE_BOARD_HEADER
#define Y5_GPIO_NUM 13
#else
#define Y5_GPIO_NUM 35
#endif
#define Y4_GPIO_NUM 14
#if USE_BOARD_HEADER
#define Y3_GPIO_NUM 35
#else
#define Y3_GPIO_NUM 13
#endif
#define Y2_GPIO_NUM 34
#define VSYNC_GPIO_NUM 5
#define HREF_GPIO_NUM 27
#define PCLK_GPIO_NUM 25
#elif defined(CAMERA_MODEL_ESP32S3_CAM_LCD)
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 40
#define SIOD_GPIO_NUM 17
#define SIOC_GPIO_NUM 18
#define Y9_GPIO_NUM 39
#define Y8_GPIO_NUM 41
#define Y7_GPIO_NUM 42
#define Y6_GPIO_NUM 12
#define Y5_GPIO_NUM 3
#define Y4_GPIO_NUM 14
#define Y3_GPIO_NUM 47
#define Y2_GPIO_NUM 13
#define VSYNC_GPIO_NUM 21
#define HREF_GPIO_NUM 38
#define PCLK_GPIO_NUM 11
#elif defined(CAMERA_MODEL_ESP32S2_CAM_BOARD)
// The 18 pin header on the board has Y5 and Y3 swapped
#define USE_BOARD_HEADER 0
#define PWDN_GPIO_NUM 1
#define RESET_GPIO_NUM 2
#define XCLK_GPIO_NUM 42
#define SIOD_GPIO_NUM 41
#define SIOC_GPIO_NUM 18
#define Y9_GPIO_NUM 16
#define Y8_GPIO_NUM 39
#define Y7_GPIO_NUM 40
#define Y6_GPIO_NUM 15
#if USE_BOARD_HEADER
#define Y5_GPIO_NUM 12
#else
#define Y5_GPIO_NUM 13
#endif
#define Y4_GPIO_NUM 5
#if USE_BOARD_HEADER
#define Y3_GPIO_NUM 13
#else
#define Y3_GPIO_NUM 12
#endif
#define Y2_GPIO_NUM 14
#define VSYNC_GPIO_NUM 38
#define HREF_GPIO_NUM 4
#define PCLK_GPIO_NUM 3
#elif defined(CAMERA_MODEL_ESP32S3_EYE)
#define PWDN_GPIO_NUM -1
#define RESET_GPIO_NUM -1
#define XCLK_GPIO_NUM 15
#define SIOD_GPIO_NUM 4
#define SIOC_GPIO_NUM 5
#define Y2_GPIO_NUM 11
#define Y3_GPIO_NUM 9
#define Y4_GPIO_NUM 8
#define Y5_GPIO_NUM 10
#define Y6_GPIO_NUM 12
#define Y7_GPIO_NUM 18
#define Y8_GPIO_NUM 17
#define Y9_GPIO_NUM 16
#define VSYNC_GPIO_NUM 6
#define HREF_GPIO_NUM 7
#define PCLK_GPIO_NUM 13
#else
#error "Camera model not selected"
#endif
+185
View File
@@ -0,0 +1,185 @@
#include <WiFi.h>
#include <ArduinoHA.h>
#include "esp_camera.h"
#define BROKER_ADDR IPAddress(192,168,0,17)
#define WIFI_SSID "MyNetwork"
#define WIFI_PASSWORD "MyPassword"
#define PUBLISH_INTERVAL 10000 // how often image should be published to HA (milliseconds)
WiFiClient client;
HADevice device;
HAMqtt mqtt(client, device);
HACamera haCamera("myCamera");
unsigned long lastPublishAt = 0;
// ===================
// Select camera model
// ===================
//#define CAMERA_MODEL_WROVER_KIT // Has PSRAM
//#define CAMERA_MODEL_ESP_EYE // Has PSRAM
//#define CAMERA_MODEL_ESP32S3_EYE // Has PSRAM
//#define CAMERA_MODEL_M5STACK_PSRAM // Has PSRAM
//#define CAMERA_MODEL_M5STACK_V2_PSRAM // M5Camera version B Has PSRAM
//#define CAMERA_MODEL_M5STACK_WIDE // Has PSRAM
//#define CAMERA_MODEL_M5STACK_ESP32CAM // No PSRAM
//#define CAMERA_MODEL_M5STACK_UNITCAM // No PSRAM
#define CAMERA_MODEL_AI_THINKER // Has PSRAM
//#define CAMERA_MODEL_TTGO_T_JOURNAL // No PSRAM
// ** Espressif Internal Boards **
//#define CAMERA_MODEL_ESP32_CAM_BOARD
//#define CAMERA_MODEL_ESP32S2_CAM_BOARD
//#define CAMERA_MODEL_ESP32S3_CAM_LCD
#include "camera_pins.h"
bool setupCamera();
void startCameraServer();
void publishCameraImage();
void setup() {
// Unique ID must be set!
byte mac[6];
WiFi.macAddress(mac);
device.setUniqueId(mac, sizeof(mac));
Serial.begin(115200);
Serial.setDebugOutput(true);
Serial.println();
if (!setupCamera()) {
return;
}
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
WiFi.setSleep(false);
while (WiFi.status() != WL_CONNECTED) {
delay(500);
Serial.print(".");
}
Serial.println("");
Serial.println("WiFi connected");
startCameraServer();
Serial.print("Camera Ready! Use 'http://");
Serial.print(WiFi.localIP());
Serial.println("' to connect");
// set device's details (optional)
device.setName("ESP32-CAM");
device.setSoftwareVersion("1.0.0");
haCamera.setIcon("mdi:home");
haCamera.setName("Garden camera");
mqtt.begin(BROKER_ADDR);
}
void loop() {
mqtt.loop();
if (millis() - lastPublishAt > PUBLISH_INTERVAL) {
Serial.println("Publishing image");
publishCameraImage();
}
}
bool setupCamera() {
camera_config_t config;
config.ledc_channel = LEDC_CHANNEL_0;
config.ledc_timer = LEDC_TIMER_0;
config.pin_d0 = Y2_GPIO_NUM;
config.pin_d1 = Y3_GPIO_NUM;
config.pin_d2 = Y4_GPIO_NUM;
config.pin_d3 = Y5_GPIO_NUM;
config.pin_d4 = Y6_GPIO_NUM;
config.pin_d5 = Y7_GPIO_NUM;
config.pin_d6 = Y8_GPIO_NUM;
config.pin_d7 = Y9_GPIO_NUM;
config.pin_xclk = XCLK_GPIO_NUM;
config.pin_pclk = PCLK_GPIO_NUM;
config.pin_vsync = VSYNC_GPIO_NUM;
config.pin_href = HREF_GPIO_NUM;
config.pin_sscb_sda = SIOD_GPIO_NUM;
config.pin_sscb_scl = SIOC_GPIO_NUM;
config.pin_pwdn = PWDN_GPIO_NUM;
config.pin_reset = RESET_GPIO_NUM;
config.xclk_freq_hz = 20000000;
config.frame_size = FRAMESIZE_UXGA;
config.pixel_format = PIXFORMAT_JPEG; // for streaming
//config.pixel_format = PIXFORMAT_RGB565; // for face detection/recognition
config.grab_mode = CAMERA_GRAB_WHEN_EMPTY;
config.fb_location = CAMERA_FB_IN_PSRAM;
config.jpeg_quality = 12;
config.fb_count = 1;
// if PSRAM IC present, init with UXGA resolution and higher JPEG quality
// for larger pre-allocated frame buffer.
if(config.pixel_format == PIXFORMAT_JPEG){
if(psramFound()){
config.jpeg_quality = 10;
config.fb_count = 2;
config.grab_mode = CAMERA_GRAB_LATEST;
} else {
// Limit the frame size when PSRAM is not available
config.frame_size = FRAMESIZE_SVGA;
config.fb_location = CAMERA_FB_IN_DRAM;
}
} else {
// Best option for face detection/recognition
config.frame_size = FRAMESIZE_240X240;
#if CONFIG_IDF_TARGET_ESP32S3
config.fb_count = 2;
#endif
}
#if defined(CAMERA_MODEL_ESP_EYE)
pinMode(13, INPUT_PULLUP);
pinMode(14, INPUT_PULLUP);
#endif
// camera init
esp_err_t err = esp_camera_init(&config);
if (err != ESP_OK) {
Serial.printf("Camera init failed with error 0x%x", err);
return false;
}
sensor_t * s = esp_camera_sensor_get();
// initial sensors are flipped vertically and colors are a bit saturated
if (s->id.PID == OV3660_PID) {
s->set_vflip(s, 1); // flip it back
s->set_brightness(s, 1); // up the brightness just a bit
s->set_saturation(s, -2); // lower the saturation
}
// drop down frame size for higher initial frame rate
if(config.pixel_format == PIXFORMAT_JPEG){
s->set_framesize(s, FRAMESIZE_QVGA);
}
#if defined(CAMERA_MODEL_M5STACK_WIDE) || defined(CAMERA_MODEL_M5STACK_ESP32CAM)
s->set_vflip(s, 1);
s->set_hmirror(s, 1);
#endif
#if defined(CAMERA_MODEL_ESP32S3_EYE)
s->set_vflip(s, 1);
#endif
return true;
}
void publishCameraImage() {
camera_fb_t* fb = esp_camera_fb_get();
if (!fb) {
return;
}
Serial.printf("Image size: %db\n", fb->len);
haCamera.publishImage(fb->buf, fb->len);
esp_camera_fb_return(fb);
lastPublishAt = millis();
}
+5
View File
@@ -0,0 +1,5 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, 0x9000, 0x5000,
otadata, data, ota, 0xe000, 0x2000,
app0, app, ota_0, 0x10000, 0x3d0000,
fr, data, , 0x3e0000, 0x20000,
1 # Name Type SubType Offset Size Flags
2 nvs data nvs 0x9000 0x5000
3 otadata data ota 0xe000 0x2000
4 app0 app ota_0 0x10000 0x3d0000
5 fr data 0x3e0000 0x20000
+67
View File
@@ -0,0 +1,67 @@
#include <Ethernet.h>
#include <ArduinoHA.h>
#define BROKER_ADDR IPAddress(192,168,0,17)
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
// HAFan::SpeedsFeature enables support for setting different speeds of fan.
// You can skip this argument if you don't need speed management.
// "ventilation" is unique ID of the fan. You should define your own ID.
HAFan fan("ventilation", HAFan::SpeedsFeature);
void onStateCommand(bool state, HAFan* sender) {
Serial.print("State: ");
Serial.println(state);
sender->setState(state); // report state back to the Home Assistant
}
void onSpeedCommand(uint16_t speed, HAFan* sender) {
Serial.print("Speed: ");
Serial.println(speed);
sender->setSpeed(speed); // report speed back to the Home Assistant
}
void setup() {
Serial.begin(9600);
// you don't need to verify return status
Ethernet.begin(mac);
// set device's details (optional)
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");
// configure fan (optional)
fan.setName("Bathroom");
fan.setSpeedRangeMin(1);
fan.setSpeedRangeMax(100);
// Optionally you can set retain flag for the HA commands
// fan.setRetain(true);
// Optionally you can enable optimistic mode for the HAFan.
// In this mode you won't need to report state back to the HA when commands are executed.
// fan.setOptimistic(true);
// handle fan states
fan.onStateCommand(onStateCommand);
fan.onSpeedCommand(onSpeedCommand);
mqtt.begin(BROKER_ADDR);
}
void loop() {
Ethernet.maintain();
mqtt.loop();
// You can also change the state at runtime as shown below.
// This kind of logic can be used if you want to control your fan using a button connected to the device.
// fan.setState(true); // true (ON) or false (OFF)
}
+109
View File
@@ -0,0 +1,109 @@
#include <ESP8266WiFi.h>
#include <ArduinoHA.h>
#define BROKER_ADDR IPAddress(192,168,0,17)
#define WIFI_SSID "MyNetwork"
#define WIFI_PASSWORD "MyPassword"
WiFiClient client;
HADevice device;
HAMqtt mqtt(client, device);
// By default HAHVAC supports only reporting of the temperature.
// You can enable feature you need using the second argument of the constructor.
// Please check the documentation of the HAHVAC class.
HAHVAC hvac(
"my_name",
HAHVAC::TargetTemperatureFeature | HAHVAC::PowerFeature | HAHVAC::ModesFeature
);
unsigned long lastTempPublishAt = 0;
float lastTemp = 0;
void onTargetTemperatureCommand(HANumeric temperature, HAHVAC* sender) {
float temperatureFloat = temperature.toFloat();
Serial.print("Target temperature: ");
Serial.println(temperatureFloat);
sender->setTargetTemperature(temperature); // report target temperature back to the HA panel
}
void onPowerCommand(bool state, HAHVAC* sender) {
if (state) {
Serial.println("Power on");
} else {
Serial.println("Power off");
}
}
void onModeCommand(HAHVAC::Mode mode, HAHVAC* sender) {
Serial.print("Mode: ");
if (mode == HAHVAC::OffMode) {
Serial.println("off");
} else if (mode == HAHVAC::AutoMode) {
Serial.println("auto");
} else if (mode == HAHVAC::CoolMode) {
Serial.println("cool");
} else if (mode == HAHVAC::HeatMode) {
Serial.println("heat");
} else if (mode == HAHVAC::DryMode) {
Serial.println("dry");
} else if (mode == HAHVAC::FanOnlyMode) {
Serial.println("fan only");
}
sender->setMode(mode); // report mode back to the HA panel
}
void setup() {
Serial.begin(9600);
Serial.println("Starting...");
// Unique ID must be set!
byte mac[WL_MAC_ADDR_LENGTH];
WiFi.macAddress(mac);
device.setUniqueId(mac, sizeof(mac));
// connect to wifi
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500); // waiting for the connection
}
Serial.println();
Serial.println("Connected to the network");
// set device's details (optional)
device.setName("NodeMCU");
device.setSoftwareVersion("1.0.0");
// assign callbacks (optional)
hvac.onTargetTemperatureCommand(onTargetTemperatureCommand);
hvac.onPowerCommand(onPowerCommand);
hvac.onModeCommand(onModeCommand);
// configure HVAC (optional)
hvac.setName("My HVAC");
hvac.setMinTemp(10);
hvac.setMaxTemp(30);
hvac.setTempStep(0.5);
// You can set retain flag for the HA commands
// hvac.setRetain(true);
// You can choose which modes should be available in the HA panel
// hvac.setModes(HAHVAC::OffMode | HAHVAC::CoolMode);
mqtt.begin(BROKER_ADDR);
}
void loop() {
mqtt.loop();
if ((millis() - lastTempPublishAt) > 3000) {
hvac.setCurrentTemperature(lastTemp);
lastTempPublishAt = millis();
lastTemp += 0.5;
}
}
+19 -3
View File
@@ -9,11 +9,14 @@ byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
HASwitch led("led", false, mqtt); // you can use custom name in place of "led"
void onSwitchStateChanged(bool state, HASwitch* s)
// "led" is unique ID of the switch. You should define your own ID.
HASwitch led("led");
void onSwitchCommand(bool state, HASwitch* sender)
{
digitalWrite(LED_PIN, (state ? HIGH : LOW));
sender->setState(state); // report state back to the Home Assistant
}
void setup() {
@@ -27,8 +30,17 @@ void setup() {
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");
// set icon (optional)
led.setIcon("mdi:lightbulb");
led.setName("My LED");
// led.setPayloadOn("ENABLE");
// led.setPayloadOff("DISABLE");
// led.setStateOn("running");
// led.setStateOff("stopped");
// led.setCommandTemplate("{{ value_json.command }}");
// handle switch state
led.onStateChanged(onSwitchStateChanged);
led.onCommand(onSwitchCommand);
mqtt.begin(BROKER_ADDR);
}
@@ -36,4 +48,8 @@ void setup() {
void loop() {
Ethernet.maintain();
mqtt.loop();
// You can also change the state at runtime as shown below.
// This kind of logic can be used if you want to control your switch using a button connected to the device.
// led.setState(true); // use any state you want
}
+93
View File
@@ -0,0 +1,93 @@
#include <Ethernet.h>
#include <ArduinoHA.h>
#define BROKER_ADDR IPAddress(192,168,0,17)
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
// HALight::BrightnessFeature enables support for setting brightness of the light.
// HALight::ColorTemperatureFeature enables support for setting color temperature of the light.
// Both features are optional and you can remove them if they're not needed.
// "prettyLight" is unique ID of the light. You should define your own ID.
HALight light("prettyLight", HALight::BrightnessFeature | HALight::ColorTemperatureFeature | HALight::RGBFeature);
void onStateCommand(bool state, HALight* sender) {
Serial.print("State: ");
Serial.println(state);
sender->setState(state); // report state back to the Home Assistant
}
void onBrightnessCommand(uint8_t brightness, HALight* sender) {
Serial.print("Brightness: ");
Serial.println(brightness);
sender->setBrightness(brightness); // report brightness back to the Home Assistant
}
void onColorTemperatureCommand(uint16_t temperature, HALight* sender) {
Serial.print("Color temperature: ");
Serial.println(temperature);
sender->setColorTemperature(temperature); // report color temperature back to the Home Assistant
}
void onRGBColorCommand(HALight::RGBColor color, HALight* sender) {
Serial.print("Red: ");
Serial.println(color.red);
Serial.print("Green: ");
Serial.println(color.green);
Serial.print("Blue: ");
Serial.println(color.blue);
sender->setRGBColor(color); // report color back to the Home Assistant
}
void setup() {
Serial.begin(9600);
// you don't need to verify return status
Ethernet.begin(mac);
// set device's details (optional)
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");
// configure light (optional)
light.setName("Bathroom");
// Optionally you can set retain flag for the HA commands
// light.setRetain(true);
// Maximum brightness level can be changed as follows:
// light.setBrightnessScale(50);
// Optionally you can enable optimistic mode for the HALight.
// In this mode you won't need to report state back to the HA when commands are executed.
// light.setOptimistic(true);
// Color temperature range (optional)
// light.setMinMireds(50);
// light.setMaxMireds(200);
// handle light states
light.onStateCommand(onStateCommand);
light.onBrightnessCommand(onBrightnessCommand); // optional
light.onColorTemperatureCommand(onColorTemperatureCommand); // optional
light.onRGBColorCommand(onRGBColorCommand); // optional
mqtt.begin(BROKER_ADDR);
}
void loop() {
Ethernet.maintain();
mqtt.loop();
// You can also change the state at runtime as shown below.
// This kind of logic can be used if you want to control your light using a button connected to the device.
// light.setState(true); // use any state you want
}
+56
View File
@@ -0,0 +1,56 @@
#include <Ethernet.h>
#include <ArduinoHA.h>
#define BROKER_ADDR IPAddress(192,168,0,17)
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
// "myLock" is unique ID of the lock. You should define your own ID.
HALock lock("myLock");
void onLockCommand(HALock::LockCommand cmd, HALock* sender) {
if (cmd == HALock::CommandLock) {
Serial.println("Command: Lock");
sender->setState(HALock::StateLocked); // report state back to the HA
} else if (cmd == HALock::CommandUnlock) {
Serial.println("Command: Unlock");
sender->setState(HALock::StateUnlocked); // report state back to the HA
} else if (cmd == HALock::CommandOpen) {
if (sender->getCurrentState() != HALock::StateUnlocked) {
return; // optionally you can verify if the lock is unlocked before opening
}
Serial.println("Command: Open");
}
}
void setup() {
Serial.begin(9600);
Ethernet.begin(mac);
lock.onCommand(onLockCommand);
lock.setName("My door lock"); // optional
lock.setIcon("mdi:home"); // optional
// Optionally you can set retain flag for the HA commands
// lock.setRetain(true);
// Optionally you can enable optimistic mode for the HALock.
// In this mode you won't need to report state back to the HA when commands are executed.
// lock.setOptimistic(true);
mqtt.begin(BROKER_ADDR);
}
void loop() {
Ethernet.maintain();
mqtt.loop();
// You can also change the state at runtime as shown below.
// This kind of logic can be used if you want to control your lock using a button connected to the device.
// lock.setState(HALock::StateLocked); // use any state you want
}
+70
View File
@@ -0,0 +1,70 @@
#include <ESP8266WiFi.h>
#include <ESP8266mDNS.h>
#include <ArduinoHA.h>
#define LED_PIN D0
#define BROKER_ADDR IPAddress(192,168,0,17)
#define WIFI_SSID "MyNetwork"
#define WIFI_PASSWORD "MyPassword"
WiFiClient client;
HADevice device;
HAMqtt mqtt(client, device);
// "led" is unique ID of the switch. You should define your own ID.
HASwitch led("led");
void onSwitchCommand(bool state, HASwitch* sender)
{
digitalWrite(LED_PIN, (state ? HIGH : LOW));
sender->setState(state); // report state back to the Home Assistant
}
void setup() {
Serial.begin(9600);
Serial.println("Starting...");
// Unique ID must be set!
byte mac[WL_MAC_ADDR_LENGTH];
WiFi.macAddress(mac);
device.setUniqueId(mac, sizeof(mac));
pinMode(LED_PIN, OUTPUT);
digitalWrite(LED_PIN, LOW);
// connect to wifi
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
while (WiFi.status() != WL_CONNECTED) {
Serial.print(".");
delay(500); // waiting for the connection
}
Serial.println();
Serial.println("Connected to the network");
if (MDNS.begin("arduinoha")) {
// at this stage your device will be available using the domain name "arduinoha.local"
Serial.println("MDNS initialized - arduinoha.local");
} else {
Serial.println("Failed to initialize MDNS");
return;
}
// set device's details (optional)
device.setName("NodeMCU MDNS");
device.setSoftwareVersion("1.0.0");
// handle switch state
led.onCommand(onSwitchCommand);
led.setName("My LED"); // optional
mqtt.begin(BROKER_ADDR);
}
void loop() {
mqtt.loop();
MDNS.update();
// You can also change the state at runtime as shown below.
// This kind of logic can be used if you want to control your switch using a button connected to the device.
// led.setState(true); // use any state you want
}
+67
View File
@@ -0,0 +1,67 @@
#include <Ethernet.h>
#include <ArduinoHA.h>
#define BROKER_ADDR IPAddress(192,168,0,17)
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
void onMqttMessage(const char* topic, const uint8_t* payload, uint16_t length) {
// This callback is called when message from MQTT broker is received.
// Please note that you should always verify if the message's topic is the one you expect.
// For example: if (strcmp(topic, "myCustomTopic") == 0) { ... }
Serial.print("New message on topic: ");
Serial.println(topic);
Serial.print("Data: ");
// MQTT payloads are length-delimited; they are not guaranteed to end in NUL.
Serial.write(payload, length);
Serial.println();
mqtt.publish("myPublishTopic", "hello");
}
void onMqttConnected() {
Serial.println("Connected to the broker!");
// You can subscribe to custom topic if you need
mqtt.subscribe("myCustomTopic");
}
void onMqttDisconnected() {
Serial.println("Disconnected from the broker!");
}
void onMqttStateChanged(HAMqtt::ConnectionState state) {
Serial.print("MQTT state changed to: ");
Serial.println(static_cast<int8_t>(state));
}
void setup() {
Serial.begin(9600);
Ethernet.begin(mac);
mqtt.onMessage(onMqttMessage);
mqtt.onConnected(onMqttConnected);
mqtt.onDisconnected(onMqttDisconnected);
mqtt.onStateChanged(onMqttStateChanged);
// If you use custom discovery prefix you can change it as following:
// mqtt.setDiscoveryPrefix("customPrefix");
// If you want to change prefix only for non-discovery prefix:
// mqtt.setDataPrefix("data");
// Obtaining state of the MQTT connection:
// mqtt.getState();
mqtt.begin(BROKER_ADDR);
}
void loop() {
Ethernet.maintain();
mqtt.loop();
}
@@ -11,11 +11,14 @@ byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
HASwitch led("led", false, mqtt); // you can use custom name in place of "led"
void onSwitchStateChanged(bool state, HASwitch* s)
// "led" is unique ID of the switch. You should define your own ID.
HASwitch led("led");
void onSwitchCommand(bool state, HASwitch* sender)
{
digitalWrite(LED_PIN, (state ? HIGH : LOW));
sender->setState(state); // report state back to the Home Assistant
}
void setup() {
@@ -30,7 +33,8 @@ void setup() {
device.setSoftwareVersion("1.0.0");
// handle switch state
led.onStateChanged(onSwitchStateChanged);
led.onCommand(onSwitchCommand);
led.setName("My LED"); // optional
mqtt.begin(BROKER_ADDR, BROKER_USERNAME, BROKER_PASSWORD);
}
@@ -14,7 +14,9 @@ byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
HATriggers triggers(mqtt);
HADeviceTrigger shortPressTrigger(HADeviceTrigger::ButtonShortPressType, BUTTON_NAME);
HADeviceTrigger longPressTrigger(HADeviceTrigger::ButtonLongPressType, BUTTON_NAME);
Button btn(BUTTON_PIN);
bool holdingBtn = false;
@@ -22,15 +24,11 @@ void setup() {
// you don't need to verify return status
Ethernet.begin(mac);
Serial.println(Ethernet.localIP());
// set device's details (optional)
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");
// setup triggers
triggers.add("button_short_press", BUTTON_NAME);
triggers.add("button_long_press", BUTTON_NAME);
// setup JC button
btn.begin();
mqtt.begin(BROKER_ADDR);
@@ -42,13 +40,13 @@ void loop() {
btn.read();
if (btn.pressedFor(3000) && !holdingBtn) {
triggers.trigger("button_long_press", BUTTON_NAME);
longPressTrigger.trigger();
holdingBtn = true;
} else if (btn.wasReleased()) {
if (holdingBtn) {
holdingBtn = false;
} else {
triggers.trigger("button_short_press", BUTTON_NAME);
shortPressTrigger.trigger();
}
}
}
+47
View File
@@ -0,0 +1,47 @@
#include <Ethernet.h>
#include <ArduinoHA.h>
#define BROKER_ADDR IPAddress(192,168,0,17)
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
// devices types go here
HASwitch switch1("mySwitch1");
HASwitch switch2("mySwitch2");
void onSwitchCommand(bool state, HASwitch* sender)
{
if (sender == &switch1) {
// the switch1 has been toggled
// state == true means ON state
} else if (sender == &switch2) {
// the switch2 has been toggled
// state == true means ON state
}
sender->setState(state); // report state back to the Home Assistant
}
void setup() {
// you don't need to verify return status
Ethernet.begin(mac);
switch1.setName("Pretty label 1");
switch1.setIcon("mdi:lightbulb");
switch1.onCommand(onSwitchCommand);
switch2.setName("Pretty label 2");
switch2.setIcon("mdi:lightbulb");
switch2.onCommand(onSwitchCommand);
mqtt.begin(BROKER_ADDR);
}
void loop() {
Ethernet.maintain();
mqtt.loop();
}
+11 -3
View File
@@ -9,11 +9,14 @@
WiFiClient client;
HADevice device;
HAMqtt mqtt(client, device);
HASwitch led("led", false, mqtt); // you can use custom name in place of "led"
void onSwitchStateChanged(bool state, HASwitch* s)
// "led" is unique ID of the switch. You should define your own ID.
HASwitch led("led");
void onSwitchCommand(bool state, HASwitch* sender)
{
digitalWrite(LED_PIN, (state ? HIGH : LOW));
sender->setState(state); // report state back to the Home Assistant
}
void setup() {
@@ -42,11 +45,16 @@ void setup() {
device.setSoftwareVersion("1.0.0");
// handle switch state
led.onStateChanged(onSwitchStateChanged);
led.onCommand(onSwitchCommand);
led.setName("My LED"); // optional
mqtt.begin(BROKER_ADDR);
}
void loop() {
mqtt.loop();
// You can also change the state at runtime as shown below.
// This kind of logic can be used if you want to control your switch using a button connected to the device.
// led.setState(true); // use any state you want
}
+11 -3
View File
@@ -9,11 +9,14 @@
WiFiClient client;
HADevice device;
HAMqtt mqtt(client, device);
HASwitch led("led", false, mqtt); // you can use custom name in place of "led"
void onSwitchStateChanged(bool state, HASwitch* s)
// "led" is unique ID of the switch. You should define your own ID.
HASwitch led("led");
void onSwitchCommand(bool state, HASwitch* sender)
{
digitalWrite(LED_PIN, (state ? HIGH : LOW));
sender->setState(state); // report state back to the Home Assistant
}
void setup() {
@@ -42,11 +45,16 @@ void setup() {
device.setSoftwareVersion("1.0.0");
// handle switch state
led.onStateChanged(onSwitchStateChanged);
led.onCommand(onSwitchCommand);
led.setName("My LED"); // optional
mqtt.begin(BROKER_ADDR);
}
void loop() {
mqtt.loop();
// You can also change the state at runtime as shown below.
// This kind of logic can be used if you want to control your switch using a button connected to the device.
// led.setState(true); // use any state you want
}
+76
View File
@@ -0,0 +1,76 @@
#include <Ethernet.h>
#include <ArduinoHA.h>
#define BROKER_ADDR IPAddress(192,168,0,17)
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
HANumber number("myNumber");
// You can also specify the precision of the number by providing the second argument to the constructor as follows:
// HANumber number("myNumber", HANumber::PrecisionP1);
// HANumber number("myNumber", HANumber::PrecisionP2);
// HANumber number("myNumber", HANumber::PrecisionP3);
void onNumberCommand(HANumeric number, HANumber* sender)
{
if (!number.isSet()) {
// the reset command was send by Home Assistant
} else {
// you can do whatever you want with the number as follows:
int8_t numberInt8 = number.toInt8();
int16_t numberInt16 = number.toInt16();
int32_t numberInt32 = number.toInt32();
uint8_t numberUInt8 = number.toUInt8();
uint16_t numberUInt16 = number.toUInt16();
uint32_t numberUInt32 = number.toUInt32();
float numberFloat = number.toFloat();
}
sender->setState(number); // report the selected option back to the HA panel
}
void setup() {
// you don't need to verify return status
Ethernet.begin(mac);
// set device's details (optional)
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");
// handle command from the HA panel
number.onCommand(onNumberCommand);
// Optional configuration
number.setIcon("mdi:home");
number.setName("My number");
// number.setMin(1); // can be float if precision is set via the constructor
// number.setMax(100); // can be float if precision is set via the constructor
// number.setStep(0.5f); // minimum step: 0.001f
// number.setMode(HANumber::ModeBox);
// number.setMode(HANumber::ModeSlider);
// number.setValueTemplate("{{ value_json.level }}");
// number.setPayloadReset("RESET");
// number.setCommandTemplate("{{ value | float | round(1) }}");
// You can set retain flag for the HA commands
// number.setRetain(true);
// You can also enable optimistic mode for the HASelect.
// In this mode you won't need to report state back to the HA when commands are executed.
// number.setOptimistic(true);
mqtt.begin(BROKER_ADDR);
}
void loop() {
Ethernet.maintain();
mqtt.loop();
// You can also report the state to the HA panel at runtime as shown below.
// number.setState(1);
// number.setState(25.25f); // remember to change precision before using floats
}
+43
View File
@@ -0,0 +1,43 @@
#include <Ethernet.h>
#include <ArduinoHA.h>
#define BROKER_ADDR IPAddress(192,168,0,17)
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
// "myScene" is unique IDs of buttons. You should define you own ID.
HAScene scene("myScene");
void onSceneCommand(HAScene* sender)
{
if (sender == &scene) {
// scene was activated via Home Assistant panel
}
}
void setup() {
// you don't need to verify return status
Ethernet.begin(mac);
// optional device's details
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");
// optional properties
scene.setIcon("mdi:fire");
scene.setName("Pretty Scene");
// press callbacks
scene.onCommand(onSceneCommand);
mqtt.begin(BROKER_ADDR);
}
void loop() {
Ethernet.maintain();
mqtt.loop();
}
+77
View File
@@ -0,0 +1,77 @@
#include <Ethernet.h>
#include <ArduinoHA.h>
#define BROKER_ADDR IPAddress(192,168,0,17)
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
HASelect mySelect("mySelect");
void onSelectCommand(int8_t index, HASelect* sender)
{
switch (index) {
case 0:
// Option "Low" was selected
break;
case 1:
// Option "Medium" was selected
break;
case 2:
// Option "High" was selected
break;
default:
// unknown option
return;
}
sender->setState(index); // report the selected option back to the HA panel
// it may return null
if (sender->getCurrentOption()) {
Serial.print("Current option: ");
Serial.println(sender->getCurrentOption());
}
}
void setup() {
// you don't need to verify return status
Ethernet.begin(mac);
// set device's details (optional)
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");
// set available options
mySelect.setOptions("Low;Medium;High"); // use semicolons as separator of options
mySelect.onCommand(onSelectCommand);
mySelect.setIcon("mdi:home"); // optional
mySelect.setName("My dropdown"); // optional
// Optionally you can set retain flag for the HA commands
// mySelect.setRetain(true);
// Optionally you can enable optimistic mode for the HASelect.
// In this mode you won't need to report state back to the HA when commands are executed.
// mySelect.setOptimistic(true);
mqtt.begin(BROKER_ADDR);
}
void loop() {
Ethernet.maintain();
mqtt.loop();
// You can also report the state to the HA panel at runtime as shown below.
// The integer corresponds to the option's index.
// mySelect.setState(1);
// You can also reset the select as follows:
// mySelect.setState(-1);
}
+53
View File
@@ -0,0 +1,53 @@
#include <Ethernet.h>
#include <ArduinoHA.h>
#define ANALOG_PIN A0
#define BROKER_ADDR IPAddress(192,168,0,17)
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
unsigned long lastUpdateAt = 0;
// "myAnalogInput" is unique ID of the sensor. You should define your own ID.
HASensorNumber analogSensor("myAnalogInput", HASensorNumber::PrecisionP1);
// You can also specify the precision of the sensor by providing the second argument to the constructor as follows:
// HASensorNumber analogSensor("myAnalogInput", HASensorNumber::PrecisionP2);
// HASensorNumber analogSensor("myAnalogInput", HASensorNumber::PrecisionP3);
void setup() {
// you don't need to verify return status
Ethernet.begin(mac);
// set device's details (optional)
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");
// configure sensor (optional)
analogSensor.setIcon("mdi:home");
analogSensor.setName("Analog voltage");
analogSensor.setUnitOfMeasurement("V");
analogSensor.setSuggestedDisplayPrecision(2);
// analogSensor.setValueTemplate("{{ value_json.voltage }}");
mqtt.begin(BROKER_ADDR);
}
void loop() {
Ethernet.maintain();
mqtt.loop();
if ((millis() - lastUpdateAt) > 1000) { // 1000ms debounce time
uint16_t reading = analogRead(ANALOG_PIN);
float voltage = reading * 5.f / 1023.f; // 0.0V - 5.0V
analogSensor.setValue(voltage);
lastUpdateAt = millis();
// you can reset the sensor as follows:
// analogSensor.setValue(nullptr);
}
}
@@ -0,0 +1,44 @@
#include <Ethernet.h>
#include <ArduinoHA.h>
#define BROKER_ADDR IPAddress(192,168,0,17)
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
unsigned long lastUpdateAt = 0;
// "myUptime" is unique ID of the sensor. You should define your own ID.
HASensorNumber uptimeSensor("myUptime");
void setup() {
// you don't need to verify return status
Ethernet.begin(mac);
// set device's details (optional)
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");
// configure sensor (optional)
uptimeSensor.setIcon("mdi:home");
uptimeSensor.setName("Uptime");
uptimeSensor.setUnitOfMeasurement("s");
mqtt.begin(BROKER_ADDR);
}
void loop() {
Ethernet.maintain();
mqtt.loop();
if ((millis() - lastUpdateAt) > 2000) { // update in 2s interval
unsigned long uptimeValue = millis() / 1000;
uptimeSensor.setValue(uptimeValue);
lastUpdateAt = millis();
// you can reset the sensor as follows:
// analogSensor.setValue(nullptr);
}
}
+16 -23
View File
@@ -4,27 +4,13 @@
#define BROKER_ADDR IPAddress(192,168,0,17)
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
unsigned long lastSentAt = millis();
double lastValue = 0;
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
/**
* Supported data types:
* - uint8_t
* - uint16_t
* - uint32_t
* - int8_t
* - int16_t
* - int32_t
* - double
* - float
*/
// you can use custom name in place of "temp"
// "0" is initial value of the sensor
HASensor<double> temp("temp", 0, mqtt);
// "myValve" is unique ID of the sensor. You should define your own ID.
HASensor valve("myValve");
void setup() {
// you don't need to verify return status
@@ -34,8 +20,13 @@ void setup() {
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");
// you can set custom units for the sensor (optional)
temp.setUnitOfMeasurement("°C");
// configure sensor (optional)
valve.setIcon("mdi:home");
valve.setName("Water valve");
// valve.setValueTemplate("{{ value_json.state }}");
// valve.setDeviceClass("enum");
// valve.setOptions("open;opening;closed");
// valve.setDefaultEntityId("sensor.water_valve");
mqtt.begin(BROKER_ADDR);
}
@@ -44,9 +35,11 @@ void loop() {
Ethernet.maintain();
mqtt.loop();
if ((millis() - lastSentAt) >= 5000) {
lastSentAt = millis();
lastValue = lastValue + 0.5;
temp.setValue(lastValue);
}
// you can report different states as follows:
// valve.setValue("open");
// valve.setValue("opening");
// valve.setValue("close");
// Unlike the other device types, the HASensor doesn't store the previous value that was set.
// It means that the MQTT message is produced each time the setValue method is called.
}
+79
View File
@@ -0,0 +1,79 @@
/**
* This example uses MFRC522 library: https://github.com/miguelbalboa/rfid
*
* Typical pin layout used:
* -----------------------------------------------------------------------------------------
* MFRC522 Arduino Arduino Arduino Arduino Arduino
* Reader/PCD Uno/101 Mega Nano v3 Leonardo/Micro Pro Micro
* Signal Pin Pin Pin Pin Pin Pin
* -----------------------------------------------------------------------------------------
* RST/Reset RST 9 5 D9 RESET/ICSP-5 RST
* SPI SS SDA(SS) 10 53 D10 10 10
* SPI MOSI MOSI 11 / ICSP-4 51 D11 ICSP-4 16
* SPI MISO MISO 12 / ICSP-1 50 D12 ICSP-1 14
* SPI SCK SCK 13 / ICSP-3 52 D13 ICSP-3 15
*/
#include <Ethernet.h>
#include <ArduinoHA.h>
#include <SPI.h>
#include <MFRC522.h>
#define SS_PIN 53 // Arduino Mega
#define RST_PIN 5 // Arduino Mega
#define BROKER_ADDR IPAddress(192,168,0,17)
#define SCAN_INTERVAL 5000
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
MFRC522 rfid(SS_PIN, RST_PIN);
EthernetClient client;
HADevice device(mac, sizeof(mac));
HAMqtt mqtt(client, device);
HATagScanner scanner("myScanner");
unsigned long lastTagScannedAt = 0;
void scan() {
if (!rfid.PICC_IsNewCardPresent() || !rfid.PICC_ReadCardSerial()) {
return;
}
if (millis() - lastTagScannedAt < SCAN_INTERVAL) {
return; // prevents spamming the HA. You can implement your own logic for debouncing the scans.
}
// the tag UID needs to be converted into string
char tag[rfid.uid.size*2+1] = {0};
HAUtils::byteArrayToStr(tag, rfid.uid.uidByte, rfid.uid.size);
Serial.print("Card scanned: ");
Serial.println(tag);
scanner.tagScanned(tag); // let the HA know about the scanned tag
lastTagScannedAt = millis();
}
void setup() {
Serial.begin(9600);
Serial.println("Starting...");
// you don't need to verify return status
Ethernet.begin(mac);
SPI.begin(); // Init SPI bus
rfid.PCD_Init();
rfid.PCD_DumpVersionToSerial();
// set device's details (optional)
device.setName("Arduino");
device.setSoftwareVersion("1.0.0");
mqtt.begin(BROKER_ADDR);
}
void loop() {
Ethernet.maintain();
mqtt.loop();
scan();
}
+48
View File
@@ -0,0 +1,48 @@
{
"name": "home-assistant-integration",
"version": "3.2.1",
"description": "Maintained Home Assistant MQTT discovery and entity integration for Arduino and ESP devices.",
"keywords": [
"mqtt",
"home-assistant",
"homeassistant",
"arduino",
"esp8266",
"esp32",
"communication",
"smarthome"
],
"authors": [
{
"name": "Dawid Chyrzynski",
"email": "dev@chyrzynski.pl"
},
{
"name": "Alex Hope-O'Connor",
"email": "alex.hope.oconnor@pomonaqld.au",
"maintainer": true
}
],
"license": "AGPL-3.0",
"homepage": "https://github.com/alexhopeoconnor/arduino-home-assistant",
"repository": {
"type": "git",
"url": "https://github.com/alexhopeoconnor/arduino-home-assistant.git"
},
"frameworks": "arduino",
"dependencies": {
"knolleary/PubSubClient": "2.8.0"
},
"export": {
"include": [
"src",
"examples",
"library.properties",
"library.json",
"README.md",
"LICENSE",
"CHANGELOG.md"
]
},
"$schema": "https://raw.githubusercontent.com/platformio/platformio-core/develop/platformio/assets/schema/library.json"
}
+4 -4
View File
@@ -1,10 +1,10 @@
name=home-assistant-integration
version=1.1.1
author=Dawid Chyrzynski <dawid.chyrzynski@gmail.com>
maintainer=Dawid Chyrzynski <dawid.chyrzynski@gmail.com>
version=3.2.1
author=Dawid Chyrzynski <dev@chyrzynski.pl>, Alex Hope-O'Connor <alex.hope.oconnor@pomonaqld.au>
maintainer=Alex Hope-O'Connor <alex.hope.oconnor@pomonaqld.au>
sentence=Home Assistant MQTT integration for Arduino
paragraph=Lightweight library that provides easy to use API for integrating your Arduino/ESP based device with Home Assistant.
category=Communication
url=https://github.com/dawidchyrzynski/arduino-home-assistant
url=https://github.com/alexhopeoconnor/arduino-home-assistant
architectures=*
depends=PubSubClient
+74
View File
@@ -0,0 +1,74 @@
; PlatformIO — Unity tests for home-assistant-integration (ArduinoHA)
;
; Full suite:
; pio test -e esp8266
; pio test -e esp32
; ./scripts/test.sh compile --platform esp32
;
; Single suite (examples):
; pio test -e esp8266 --filter test_utils_serializers
; pio test -e esp8266 --filter test_mqtt_core
; pio test -e esp8266 --filter test_entities_basic
; pio test -e esp8266 --filter test_entities_numeric
; pio test -e esp8266 --filter test_entities_extended
; pio test -e esp8266 --filter test_entities_misc
;
; See: https://docs.platformio.org/en/latest/advanced/unit-testing/structure/hierarchy.html
[platformio]
default_envs = esp8266
[common]
framework = arduino
test_framework = unity
test_build_src = yes
monitor_speed = 115200
build_flags = -DARDUINOHA_TEST
lib_deps = knolleary/PubSubClient@2.8.0
[env:esp8266]
extends = common
test_ignore = test_native_core
platform = espressif8266
board = d1_mini
; Keep root Unity coverage on the same Postmortem relocation-fix snapshot as
; the maintained ESP8266 examples. See docs/ESP8266-LINKER-WORKAROUND.md.
platform_packages =
platformio/framework-arduinoespressif8266 @ https://github.com/esp8266/Arduino.git#521ae60a89e64bb0d1eb7a0b7addf620ced5cad3
[env:esp32]
extends = common
test_ignore = test_native_core
platform = https://github.com/pioarduino/platform-espressif32/releases/download/55.03.311/platform-espressif32.zip
board = esp32dev
build_unflags = -std=gnu++11
build_flags = ${common.build_flags} -std=gnu++14
; Host-only regression checks for serialization, topic validation, and the
; PubSubClient mock path. The Arduino compatibility files live exclusively
; under test/native and are never included in firmware environments.
[env:native]
platform = native
test_framework = unity
test_build_src = yes
lib_deps = throwtheswitch/Unity@^2.6.1
build_flags =
-DARDUINOHA_TEST
-Itest/native/include
-fsanitize=address,undefined
-fno-omit-frame-pointer
build_src_filter =
-<*>
+<ArduinoHALog.cpp>
+<HADevice.cpp>
+<HAMqtt.cpp>
+<device-types/HABaseDeviceType.cpp>
+<device-types/HAText.cpp>
+<mocks/PubSubClientMock.cpp>
+<utils/HAAvailabilityConfig.cpp>
+<utils/HADictionary.cpp>
+<utils/HAJson.cpp>
+<utils/HANumeric.cpp>
+<utils/HASerializer.cpp>
+<utils/HASerializerArray.cpp>
+<utils/HAUtils.cpp>
+54
View File
@@ -0,0 +1,54 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
echo "Usage: $0 vMAJOR.MINOR.PATCH" >&2
exit 2
}
tag="${1:-}"
[[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || usage
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
version="${tag#v}"
repo_url="https://github.com/alexhopeoconnor/arduino-home-assistant.git"
reference_files=(README.md docs/getting-started.md)
defines_file="$root/src/ArduinoHADefines.h"
current_version="$(sed -n 's/.*"version": "\([^"]*\)".*/\1/p' "$root/library.json" | head -n 1)"
[[ "$current_version" != "$version" ]] || {
echo "library.json already declares $version; choose a new version." >&2
exit 1
}
version_macro_count="$(grep -Ec '^#define ARDUINOHA_LIBRARY_VERSION "[0-9]+\.[0-9]+\.[0-9]+"$' "$defines_file" || true)"
[[ "$version_macro_count" -eq 1 ]] || {
echo "src/ArduinoHADefines.h must contain exactly one ARDUINOHA_LIBRARY_VERSION macro." >&2
exit 1
}
grep -q "^## $version$" "$root/CHANGELOG.md" && {
echo "CHANGELOG.md already has a $version section; choose a new version." >&2
exit 1
}
sed -i -E '0,/"version": "[0-9]+\.[0-9]+\.[0-9]+"/s//"version": "'"$version"'"/' "$root/library.json"
sed -i -E "s/^version=[0-9]+\.[0-9]+\.[0-9]+$/version=$version/" "$root/library.properties"
sed -i -E "s/^#define ARDUINOHA_LIBRARY_VERSION \"[0-9]+\.[0-9]+\.[0-9]+\"$/#define ARDUINOHA_LIBRARY_VERSION \"$version\"/" "$defines_file"
for file in "${reference_files[@]}"; do
sed -i -E "s|${repo_url}#v[0-9]+\.[0-9]+\.[0-9]+|${repo_url}#v${version}|g" "$root/$file"
done
temp_file="$(mktemp)"
trap 'rm -f "$temp_file"' EXIT
{
IFS= read -r changelog_heading < "$root/CHANGELOG.md"
[[ "$changelog_heading" == "# Changelog" ]] || {
echo "CHANGELOG.md must begin with # Changelog" >&2
exit 1
}
printf '%s\n\n## %s\n\n- TODO: Describe this release.\n' "$changelog_heading" "$version"
tail -n +2 "$root/CHANGELOG.md"
} > "$temp_file"
mv "$temp_file" "$root/CHANGELOG.md"
echo "Updated ArduinoHA declarations and canonical install references to $tag."
echo "Replace the generated changelog TODO with the release summary, then run scripts/check-docs.sh and scripts/prepare-release.sh $tag."
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env bash
set -euo pipefail
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
required=(
README.md CHANGELOG.md
docs/README.md docs/getting-started.md docs/device-and-discovery.md docs/mqtt-usage.md docs/entities.md
examples/README.md
)
check_cpp_fence_scope() {
local markdown="$1"
awk '
function brace_delta(line, copy) {
copy = line
return gsub(/\{/, "{", copy) - gsub(/\}/, "}", copy)
}
/^```cpp[[:space:]]*$/ { in_cpp = 1; depth = 0; next }
in_cpp && /^```[[:space:]]*$/ { in_cpp = 0; next }
in_cpp {
line = $0
sub(/^[[:space:]]+/, "", line)
if (depth == 0 &&
(line ~ /^(if|for|while|switch)[[:space:]]*\(/ ||
line ~ /^[A-Za-z_][A-Za-z0-9_:]*::[A-Za-z0-9_]+[[:space:]]*\(/ ||
line ~ /^[A-Za-z_][A-Za-z0-9_]*\./ ||
line ~ /^[A-Za-z_][A-Za-z0-9_]*[[:space:]]*\(/)) {
printf "%s:%d: C++ expression appears at namespace scope; wrap it in a function.\n", FILENAME, FNR > "/dev/stderr"
failed = 1
}
depth += brace_delta($0)
}
END { exit failed }
' "$markdown"
}
for path in "${required[@]}"; do
[[ -f "$root/$path" ]] || { echo "Missing required documentation: $path" >&2; exit 1; }
done
while IFS= read -r -d '' markdown; do
while IFS= read -r target; do
[[ -z "$target" || "$target" == \#* || "$target" == http://* || "$target" == https://* || "$target" == mailto:* ]] && continue
target="${target%%#*}"
case "$target" in
/*) candidate="$root/${target#/}" ;;
*) candidate="$(dirname "$markdown")/$target" ;;
esac
[[ -e "$candidate" ]] || { echo "Broken relative link in ${markdown#$root/}: $target" >&2; exit 1; }
done < <(sed -nE 's/.*\]\(([^ )]+)( "[^"]*")?\).*/\1/p' "$markdown")
done < <(find "$root" -path "$root/.git" -prune -o -path '*/.pio' -prune -o -name '*.md' -type f -print0)
while IFS= read -r example; do
for required in README.md platformio.ini; do
[[ -f "$example/$required" ]] || { echo "Incomplete guided example: ${example#$root/} is missing $required" >&2; exit 1; }
done
find "$example" -maxdepth 2 -type f \( -name '*.ino' -o -name '*.cpp' \) -print -quit | grep -q . || {
echo "Incomplete guided example: ${example#$root/} has no sketch source" >&2
exit 1
}
done < <(find "$root/examples" -mindepth 1 -maxdepth 1 -type d -name '[0-9][0-9]-*' -print | sort)
while IFS= read -r markdown; do
check_cpp_fence_scope "$markdown"
done < <(find "$root" -path "$root/.git" -prune -o -path '*/.pio' -prune -o -name '*.md' -type f -print)
echo "Documentation links and required files passed"
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
echo "Usage: $0 vMAJOR.MINOR.PATCH [--tag]"
exit 2
}
tag="${1:-}"
[[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || usage
[[ "${2:-}" == "" || "${2:-}" == "--tag" ]] || usage
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
version="${tag#v}"
manifest_version="$(sed -n 's/.*"version": "\([^"]*\)".*/\1/p' "$root/library.json" | head -n 1)"
if [[ "$manifest_version" != "$version" ]]; then
echo "library.json is $manifest_version; expected $version for $tag" >&2
exit 1
fi
defines_file="$root/src/ArduinoHADefines.h"
version_macro_count="$(grep -Ec '^#define ARDUINOHA_LIBRARY_VERSION "[0-9]+\.[0-9]+\.[0-9]+"$' "$defines_file" || true)"
if [[ "$version_macro_count" -ne 1 ]]; then
echo "src/ArduinoHADefines.h must contain exactly one ARDUINOHA_LIBRARY_VERSION macro." >&2
exit 1
fi
defines_version="$(sed -n 's/^#define ARDUINOHA_LIBRARY_VERSION "\([^"]*\)"$/\1/p' "$defines_file")"
if [[ "$defines_version" != "$version" ]]; then
echo "src/ArduinoHADefines.h is $defines_version; expected $version for $tag" >&2
exit 1
fi
if [[ -f "$root/library.properties" ]]; then
properties_version="$(sed -n 's/^version=//p' "$root/library.properties" | head -n 1)"
if [[ "$properties_version" != "$version" ]]; then
echo "library.properties is $properties_version; expected $version for $tag" >&2
exit 1
fi
fi
if ! grep -q "^## ${version}$" "$root/CHANGELOG.md"; then
echo "CHANGELOG.md is missing a ## ${version} section" >&2
exit 1
fi
if awk -v heading="## $version" '
$0 == heading { found = 1; next }
found && /^## / { exit }
found { print }
' "$root/CHANGELOG.md" | grep -Fq 'TODO: Describe this release.'; then
echo "CHANGELOG.md still has the generated TODO for $version" >&2
exit 1
fi
repo_url="https://github.com/alexhopeoconnor/arduino-home-assistant.git"
validate_reference() {
local file="$1"
local reference_count
reference_count="$(grep -F "$repo_url#v" "$root/$file" | wc -l)"
[[ "$reference_count" -eq 1 ]] || { echo "$file must contain exactly one canonical release reference" >&2; exit 1; }
grep -Fq "$repo_url#$tag" "$root/$file" || { echo "$file does not reference $tag" >&2; exit 1; }
}
validate_reference README.md
validate_reference docs/getting-started.md
git -C "$root" diff --check
package_dir="$(mktemp -d)"
trap 'rm -rf "$package_dir"' EXIT
pio pkg pack "$root" --output "$package_dir/package.tar.gz" >/dev/null
echo "Validated release metadata and PlatformIO package for $tag"
if [[ "${2:-}" == "--tag" ]]; then
git -C "$root" diff --quiet
git -C "$root" diff --cached --quiet
git -C "$root" tag -a "$tag" -m "Release $tag"
echo "Created $tag. Push the branch and tag; GitHub Actions will publish the release."
fi
+30
View File
@@ -0,0 +1,30 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
echo "Usage: $0 vMAJOR.MINOR.PATCH" >&2
exit 2
}
tag="${1:-}"
[[ "$tag" =~ ^v[0-9]+\.[0-9]+\.[0-9]+$ ]] || usage
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
version="${tag#v}"
changelog="$root/CHANGELOG.md"
output="$(mktemp)"
trap 'rm -f "$output"' EXIT
awk -v version="$version" '
$0 == "## " version { capture = 1; next }
capture && /^## / { exit }
capture { print }
' "$changelog" > "$output"
if [[ ! -s "$output" ]]; then
echo "No release notes found for $tag in CHANGELOG.md" >&2
exit 1
fi
printf '%s\n\n' "# ArduinoHA $tag"
cat "$output"
+57
View File
@@ -0,0 +1,57 @@
#!/usr/bin/env bash
set -euo pipefail
usage() {
echo "Usage: $0 compile|examples --platform esp8266|esp32" >&2
exit 2
}
[[ $# -eq 3 && ( "${1:-}" == "compile" || "${1:-}" == "examples" ) && "${2:-}" == "--platform" ]] || usage
case "${3:-}" in
esp8266|esp32) environment="${3}" ;;
*) usage ;;
esac
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
pio_for_platform() {
if [[ "$environment" != "esp32" ]]; then
pio "$@"
return
fi
# Keep Core 3.3.11's package-form esptool and generated pioarduino
# environment in the persistent cache shared by the maintained framework
# repositories. It is never cleared by this script, and isolates this
# tested graph from stale global metadata without duplicate downloads.
local core_dir packages_dir cache_dir
core_dir="${ARDUINOHA_PLATFORMIO_CORE_DIR:-${XDG_CACHE_HOME:-$HOME/.cache}/arduino-framework-platformio/core-3.3.11}"
packages_dir="${ARDUINOHA_PLATFORMIO_PACKAGES_DIR:-$core_dir/packages}"
cache_dir="${ARDUINOHA_PLATFORMIO_CACHE_DIR:-$core_dir/cache}"
install -d -m 700 "$core_dir" "$packages_dir" "$cache_dir"
PLATFORMIO_CORE_DIR="$core_dir" PLATFORMIO_PACKAGES_DIR="$packages_dir" \
PLATFORMIO_CACHE_DIR="$cache_dir" pio "$@"
}
case "$1" in
compile)
# PlatformIO's test command starts many archive jobs by default. This
# multi-suite project has a reproducible missing-object race on Core
# 3.3.11 at high parallelism, so use a deterministic default while
# preserving an explicit caller override.
export PLATFORMIO_RUN_JOBS="${PLATFORMIO_RUN_JOBS:-1}"
pio_for_platform test -d "$root" -e "$environment" --without-uploading --without-testing
echo "ArduinoHA compile check passed for $environment"
;;
examples)
mapfile -t examples < <(find "$root/examples" -mindepth 1 -maxdepth 1 -type d -name '[0-9][0-9]-*' -print | sort)
if (( ${#examples[@]} == 0 )); then
echo "No example projects found" >&2
exit 1
fi
for example in "${examples[@]}"; do
pio_for_platform run -d "$example" -e "$environment" </dev/null
done
echo "ArduinoHA examples compile check passed for $environment"
;;
esac
+24 -3
View File
@@ -1,14 +1,35 @@
#ifndef AHA_ARDUINOHA_H
#define AHA_ARDUINOHA_H
#include "ArduinoHALog.h"
#include "ArduinoHALogTemplates.h"
#include "HADevice.h"
#include "HAMqtt.h"
#include "HAUtils.h"
#include "device-types/HABinarySensor.h"
#include "device-types/HAButton.h"
#include "device-types/HACamera.h"
#include "device-types/HACover.h"
#include "device-types/HADeviceTracker.h"
#include "device-types/HADeviceTrigger.h"
#include "device-types/HAFan.h"
#include "device-types/HAHVAC.h"
#include "device-types/HALight.h"
#include "device-types/HALock.h"
#include "device-types/HANumber.h"
#include "device-types/HAScene.h"
#include "device-types/HASelect.h"
#include "device-types/HASensor.h"
#include "device-types/HASensor.cpp"
#include "device-types/HASensorNumber.h"
#include "device-types/HASwitch.h"
#include "device-types/HATagScanner.h"
#include "device-types/HATriggers.h"
#include "device-types/HAText.h"
#include "utils/HAUtils.h"
#include "utils/HANumeric.h"
#ifdef ARDUINOHA_TEST
#include "mocks/PubSubClientMock.h"
#include "utils/HADictionary.h"
#include "utils/HASerializer.h"
#endif
#endif
+61 -2
View File
@@ -1,4 +1,63 @@
// Turns on debug information of the ArduinoHA core.
// Please note that you need to initialize serial interface manually
// by calling Serial.begin([baudRate]) before initializing ArduinoHA.
// Without a log sink (arduinoHASetLogSink), initialize Serial (e.g. Serial.begin(115200)) before ArduinoHA.
// With a sink installed, the host is responsible for transport setup.
// #define ARDUINOHA_DEBUG
#include "ArduinoHALog.h"
// These macros allow to exclude some parts of the library to save more resources.
// #define EX_ARDUINOHA_BINARY_SENSOR
// #define EX_ARDUINOHA_BUTTON
// #define EX_ARDUINOHA_CAMERA
// #define EX_ARDUINOHA_COVER
// #define EX_ARDUINOHA_DEVICE_TRACKER
// #define EX_ARDUINOHA_DEVICE_TRIGGER
// #define EX_ARDUINOHA_FAN
// #define EX_ARDUINOHA_HVAC
// #define EX_ARDUINOHA_LIGHT
// #define EX_ARDUINOHA_LOCK
// #define EX_ARDUINOHA_NUMBER
// #define EX_ARDUINOHA_SCENE
// #define EX_ARDUINOHA_SELECT
// #define EX_ARDUINOHA_SENSOR
// #define EX_ARDUINOHA_SWITCH
// #define EX_ARDUINOHA_TAG_SCANNER
// #define EX_ARDUINOHA_TEXT
// Enables std::function overloads for entity callbacks.
// Useful for capturing lambdas, but may increase binary size on constrained boards.
// Define ARDUINOHA_DISABLE_STDFUNCTION to opt out.
#if !defined(ARDUINOHA_DISABLE_STDFUNCTION)
#define ARDUINOHA_ENABLE_STDFUNCTION
#endif
// Current library version used in discovery origin metadata.
#define ARDUINOHA_LIBRARY_VERSION "3.2.1"
#if defined(ARDUINOHA_DEBUG)
#include <Arduino.h>
#define ARDUINOHA_DEBUG_INIT() do { \
if (!arduinoHAGetLogSink()) { Serial.begin(115200); } \
arduinoHASetLogEnabled(true); \
arduinoHASetLogLevel(ArduinoHALogLevel::Debug); \
} while(0)
/** @deprecated Prefer arduinoHALog / arduinoHALogf; each macro emits one structured line. */
#define ARDUINOHA_DEBUG_PRINTLN(x) \
arduinoHALog(ArduinoHALogLevel::Debug, "aha", String(x))
/** @deprecated Prefer arduinoHALog / arduinoHALogf; each macro emits one structured line. */
#define ARDUINOHA_DEBUG_PRINT(x) \
arduinoHALog(ArduinoHALogLevel::Debug, "aha", String(x))
#else
#define ARDUINOHA_DEBUG_INIT()
#define ARDUINOHA_DEBUG_PRINTLN(x)
#define ARDUINOHA_DEBUG_PRINT(x)
#endif
#if defined(__SAMD21G18A__) or defined(__SAM3X8E__) or (defined(ESP32) and defined(ESP_ARDUINO_VERSION_MAJOR) and ESP_ARDUINO_VERSION_MAJOR >= 3)
#define ARDUINOHA_INT_OVERLOAD
#endif
#define AHATOFSTR(x) reinterpret_cast<const __FlashStringHelper*>(x)
#define AHAFROMFSTR(x) reinterpret_cast<const char*>(x)
+97
View File
@@ -0,0 +1,97 @@
#include "ArduinoHALog.h"
static ArduinoHALogSink* g_arduinoHALogSink = nullptr;
static ArduinoHANetworkStatusFn g_networkStatusFn = nullptr;
#ifdef ARDUINOHA_DEBUG
static bool g_logEnabled = true;
static ArduinoHALogLevel g_logLevelMax = ArduinoHALogLevel::Debug;
#else
static bool g_logEnabled = false;
static ArduinoHALogLevel g_logLevelMax = ArduinoHALogLevel::Info;
#endif
void arduinoHASetLogSink(ArduinoHALogSink* sink) {
g_arduinoHALogSink = sink;
}
ArduinoHALogSink* arduinoHAGetLogSink() {
return g_arduinoHALogSink;
}
void arduinoHASetLogEnabled(bool enabled) {
g_logEnabled = enabled;
}
bool arduinoHAIsLogEnabled() {
return g_logEnabled;
}
void arduinoHASetLogLevel(ArduinoHALogLevel level) {
g_logLevelMax = level;
}
ArduinoHALogLevel arduinoHAGetLogLevel() {
return g_logLevelMax;
}
void arduinoHASetNetworkStatusFn(ArduinoHANetworkStatusFn fn) {
g_networkStatusFn = fn;
}
int arduinoHANetworkStatusOptional(void) {
if (!g_networkStatusFn) {
return -1;
}
return g_networkStatusFn();
}
const char* arduinoHALogLevelTag(ArduinoHALogLevel level) {
switch (level) {
case ArduinoHALogLevel::Error:
return "ERROR";
case ArduinoHALogLevel::Warn:
return "WARN";
case ArduinoHALogLevel::Info:
return "INFO";
case ArduinoHALogLevel::Debug:
return "DEBUG";
case ArduinoHALogLevel::Trace:
return "TRACE";
default:
return "?";
}
}
void arduinoHALog(
ArduinoHALogLevel level,
const char* subsystem,
const String& text
) {
if (!g_logEnabled) {
return;
}
if (static_cast<uint8_t>(level) > static_cast<uint8_t>(g_logLevelMax)) {
return;
}
const char* sub = (subsystem && subsystem[0] != '\0') ? subsystem : "aha";
ArduinoHALogMessage msg;
msg.level = level;
msg.subsystem = sub;
msg.text = text;
if (g_arduinoHALogSink) {
g_arduinoHALogSink->log(msg);
return;
}
Serial.print(F("["));
Serial.print(arduinoHALogLevelTag(level));
Serial.print(F("][aha."));
Serial.print(sub);
Serial.print(F("] "));
Serial.println(text);
}
+65
View File
@@ -0,0 +1,65 @@
#ifndef ARDUINOHA_LOG_H
#define ARDUINOHA_LOG_H
#include <Arduino.h>
/**
* Log severity for ArduinoHA. Numeric order is used for filtering: only messages with
* level <= the configured maximum (see arduinoHASetLogLevel) are emitted.
*/
enum class ArduinoHALogLevel : uint8_t {
Error = 1,
Warn,
Info,
Debug,
Trace,
};
struct ArduinoHALogMessage {
ArduinoHALogLevel level;
const char* subsystem;
String text;
};
/**
* Structured log sink (mirrors WiFiManager-style log callbacks).
* Install with arduinoHASetLogSink; when null, arduinoHALog writes to Serial if enabled.
*/
class ArduinoHALogSink {
public:
virtual void log(const ArduinoHALogMessage& msg) = 0;
virtual ~ArduinoHALogSink() = default;
};
void arduinoHASetLogSink(ArduinoHALogSink* sink);
ArduinoHALogSink* arduinoHAGetLogSink();
void arduinoHASetLogEnabled(bool enabled);
bool arduinoHAIsLogEnabled();
/**
* Maximum verbosity to print: Error..Trace. Messages with level <= this value are shown.
*/
void arduinoHASetLogLevel(ArduinoHALogLevel level);
ArduinoHALogLevel arduinoHAGetLogLevel();
void arduinoHALog(
ArduinoHALogLevel level,
const char* subsystem,
const String& text
);
const char* arduinoHALogLevelTag(ArduinoHALogLevel level);
/**
* Optional hook for transport diagnostics (e.g. return WiFi.status()).
* When unset, publish failure logs omit network fields.
*/
typedef int (*ArduinoHANetworkStatusFn)(void);
void arduinoHASetNetworkStatusFn(ArduinoHANetworkStatusFn fn);
/** Returns -1 when no hook is installed. */
int arduinoHANetworkStatusOptional(void);
#endif
+58
View File
@@ -0,0 +1,58 @@
#ifndef ARDUINOHA_LOG_TEMPLATES_H
#define ARDUINOHA_LOG_TEMPLATES_H
#include "ArduinoHALog.h"
#include <IPAddress.h>
inline String ahaLogStringifyArg(const __FlashStringHelper* v) {
return String(v);
}
inline String ahaLogStringifyArg(const IPAddress& v) {
return v.toString();
}
template<typename T>
inline String ahaLogStringifyArg(const T& v) {
return String(v);
}
template<typename T>
inline void arduinoHALogf(
ArduinoHALogLevel level,
const char* subsystem,
T&& text
) {
arduinoHALog(level, subsystem, ahaLogStringifyArg(text));
}
template<typename T, typename U>
inline void arduinoHALogf(
ArduinoHALogLevel level,
const char* subsystem,
T&& a,
U&& b
) {
arduinoHALog(
level,
subsystem,
ahaLogStringifyArg(a) + ahaLogStringifyArg(b)
);
}
template<typename T, typename U, typename V>
inline void arduinoHALogf(
ArduinoHALogLevel level,
const char* subsystem,
T&& a,
U&& b,
V&& c
) {
arduinoHALog(
level,
subsystem,
ahaLogStringifyArg(a) + ahaLogStringifyArg(b) + ahaLogStringifyArg(c)
);
}
#endif
+411 -66
View File
@@ -1,13 +1,150 @@
#include <Arduino.h>
#include "ArduinoHADefines.h"
#include "HADevice.h"
#include "HAUtils.h"
#include "HAMqtt.h"
#include "utils/HAUtils.h"
#include "utils/HADictionary.h"
#include "utils/HAJson.h"
#include "utils/HASerializer.h"
#include <string.h>
static bool appendEscapedJsonString(char*& cursor, char* end, const char* value)
{
return HAJson::appendEscapedString(cursor, end, value);
}
namespace {
void skipJsonWhitespace(const char*& cursor)
{
while (*cursor == ' ' || *cursor == '\t' || *cursor == '\n' || *cursor == '\r') {
cursor++;
}
}
bool isHexDigit(const char value)
{
return (value >= '0' && value <= '9') ||
(value >= 'a' && value <= 'f') ||
(value >= 'A' && value <= 'F');
}
bool parseJsonString(const char*& cursor)
{
if (*cursor != '"') {
return false;
}
cursor++;
while (*cursor != '\0') {
const unsigned char value = static_cast<unsigned char>(*cursor++);
if (value == '"') {
return true;
}
if (value < 0x20) {
return false;
}
if (value != '\\') {
continue;
}
const char escape = *cursor++;
if (escape == '\0') {
return false;
}
if (escape == '"' || escape == '\\' || escape == '/' ||
escape == 'b' || escape == 'f' || escape == 'n' ||
escape == 'r' || escape == 't') {
continue;
}
if (escape != 'u') {
return false;
}
for (uint8_t i = 0; i < 4; i++) {
if (!isHexDigit(*cursor++)) {
return false;
}
}
}
return false;
}
bool isValidConnectionsJson(const char* value, const size_t maxLength)
{
if (!value || value[0] == '\0' || strlen(value) >= maxLength) {
return false;
}
const char* cursor = value;
skipJsonWhitespace(cursor);
if (*cursor++ != '[') {
return false;
}
skipJsonWhitespace(cursor);
if (*cursor == ']') {
cursor++;
skipJsonWhitespace(cursor);
return *cursor == '\0';
}
while (true) {
if (*cursor++ != '[') {
return false;
}
skipJsonWhitespace(cursor);
if (!parseJsonString(cursor)) {
return false;
}
skipJsonWhitespace(cursor);
if (*cursor++ != ',') {
return false;
}
skipJsonWhitespace(cursor);
if (!parseJsonString(cursor)) {
return false;
}
skipJsonWhitespace(cursor);
if (*cursor++ != ']') {
return false;
}
skipJsonWhitespace(cursor);
if (*cursor == ']') {
cursor++;
skipJsonWhitespace(cursor);
return *cursor == '\0';
}
if (*cursor++ != ',') {
return false;
}
skipJsonWhitespace(cursor);
}
}
} // namespace
#define HADEVICE_INIT \
_manufacturer(nullptr), \
_model(nullptr), \
_name(nullptr), \
_softwareVersion(nullptr)
_ownsUniqueId(false), \
_serializer(new HASerializer(nullptr, 16)), \
_availabilityTopic(nullptr), \
_sharedAvailability(false), \
_available(true), \
_extendedUniqueIds(false), \
_payloadAvailable(nullptr), \
_payloadNotAvailable(nullptr), \
_connectionsJson(), \
_hasConnections(false), \
_connectionsPropertyRegistered(false)
HADevice::HADevice() :
_uniqueId(nullptr),
@@ -20,99 +157,307 @@ HADevice::HADevice(const char* uniqueId) :
_uniqueId(uniqueId),
HADEVICE_INIT
{
_serializer->set(AHATOFSTR(HADeviceIdentifiersProperty), _uniqueId);
}
HADevice::HADevice(const byte* uniqueId, const uint16_t& length) :
HADevice::HADevice(const byte* uniqueId, const uint16_t length) :
_uniqueId(HAUtils::byteArrayToStr(uniqueId, length)),
HADEVICE_INIT
{
_ownsUniqueId = true;
_serializer->set(AHATOFSTR(HADeviceIdentifiersProperty), _uniqueId);
}
bool HADevice::setUniqueId(const byte* uniqueId, const uint16_t& length)
HADevice::~HADevice()
{
if (_uniqueId != nullptr) {
return false;
delete _serializer;
if (_availabilityTopic) {
delete[] _availabilityTopic;
}
if (_ownsUniqueId) {
delete[] _uniqueId;
}
}
bool HADevice::setUniqueId(const byte* uniqueId, const uint16_t length)
{
if (_uniqueId) {
return false; // unique ID cannot be changed at runtime once it's set
}
_uniqueId = HAUtils::byteArrayToStr(uniqueId, length);
_ownsUniqueId = true;
_serializer->set(AHATOFSTR(HADeviceIdentifiersProperty), _uniqueId);
return true;
}
uint16_t HADevice::calculateSerializedLength() const
void HADevice::setManufacturer(const char* manufacturer)
{
uint16_t size =
3 + // opening and closing bracket + null terminator
strlen(_uniqueId) + 8; // 8 - length of the JSON data for this field
if (_manufacturer != nullptr) {
size += strlen(_manufacturer) + 8; // 8 - length of the JSON data for this field
}
if (_model != nullptr) {
size += strlen(_model) + 9; // 9 - length of the JSON data for this field
}
if (_name != nullptr) {
size += strlen(_name) + 10; // 10 - length of the JSON data for this field
}
if (_softwareVersion != nullptr) {
size += strlen(_softwareVersion) + 8; // 8 - length of the JSON data for this field
}
return size;
_serializer->set(AHATOFSTR(HADeviceManufacturerProperty), manufacturer);
}
uint16_t HADevice::serialize(char* dst) const
void HADevice::setModel(const char* model)
{
static const char QuotationSign[] PROGMEM = {"\""};
_serializer->set(AHATOFSTR(HADeviceModelProperty), model);
}
{
static const char DataBefore[] PROGMEM = {"{\"ids\":\""};
void HADevice::setName(const char* name)
{
_serializer->set(AHATOFSTR(HANameProperty), name);
}
strcpy_P(dst, DataBefore);
strcat(dst, _uniqueId);
strcat_P(dst, QuotationSign);
void HADevice::setSoftwareVersion(const char* softwareVersion)
{
_serializer->set(
AHATOFSTR(HADeviceSoftwareVersionProperty),
softwareVersion
);
}
void HADevice::setConfigurationUrl(const char* url)
{
_serializer->set(
AHATOFSTR(HADeviceConfigurationUrlProperty),
url
);
}
void HADevice::setModelId(const char* modelId)
{
if (!modelId) {
return;
}
_serializer->set(AHATOFSTR(HADeviceModelIdProperty), modelId);
}
void HADevice::setHardwareVersion(const char* hardwareVersion)
{
if (!hardwareVersion) {
return;
}
_serializer->set(AHATOFSTR(HADeviceHwVersionProperty), hardwareVersion);
}
void HADevice::setSerialNumber(const char* serialNumber)
{
if (!serialNumber) {
return;
}
_serializer->set(AHATOFSTR(HADeviceSerialNumberProperty), serialNumber);
}
void HADevice::setSuggestedArea(const char* suggestedArea)
{
if (!suggestedArea) {
return;
}
_serializer->set(AHATOFSTR(HADeviceSuggestedAreaProperty), suggestedArea);
}
void HADevice::setViaDevice(const char* viaDevice)
{
if (!viaDevice) {
return;
}
_serializer->set(AHATOFSTR(HADeviceViaDeviceProperty), viaDevice);
}
bool HADevice::addConnection(const char* type, const char* value)
{
if (!type || !value || type[0] == '\0' || value[0] == '\0') {
return false;
}
char next[MaxConnectionsJsonLength];
if (_hasConnections) {
strncpy(next, _connectionsJson, MaxConnectionsJsonLength - 1);
next[MaxConnectionsJsonLength - 1] = 0;
} else {
strcpy(next, "[]");
}
const size_t len = strlen(next);
if (len < 2 || next[len - 1] != ']') {
return false;
}
char* cursor = next + len - 1;
char* end = next + MaxConnectionsJsonLength - 1;
if (cursor > next + 1) {
if (cursor + 1 >= end) {
return false;
}
*cursor++ = ',';
}
if (_manufacturer != nullptr) {
static const char DataBefore[] PROGMEM = {",\"mf\":\""};
if (cursor + 1 >= end) {
return false;
}
*cursor++ = '[';
*cursor = 0;
if (!appendEscapedJsonString(cursor, end, type)) {
return false;
}
if (cursor + 1 >= end) {
return false;
}
*cursor++ = ',';
*cursor = 0;
if (!appendEscapedJsonString(cursor, end, value)) {
return false;
}
if (cursor + 2 >= end) {
return false;
}
*cursor++ = ']';
*cursor++ = ']';
*cursor = 0;
strncpy(_connectionsJson, next, MaxConnectionsJsonLength - 1);
_connectionsJson[MaxConnectionsJsonLength - 1] = 0;
_hasConnections = true;
if (!_connectionsPropertyRegistered) {
_serializer->set(
AHATOFSTR(HADeviceConnectionsProperty),
_connectionsJson,
HASerializer::JsonLiteralPropertyValue
);
_connectionsPropertyRegistered = true;
}
strcat_P(dst, DataBefore);
strcat(dst, _manufacturer);
strcat_P(dst, QuotationSign);
return true;
}
bool HADevice::setConnectionsJson(const char* connectionsJson)
{
if (!isValidConnectionsJson(connectionsJson, MaxConnectionsJsonLength)) {
return false;
}
strcpy(_connectionsJson, connectionsJson);
_hasConnections = true;
if (!_connectionsPropertyRegistered) {
_serializer->set(
AHATOFSTR(HADeviceConnectionsProperty),
_connectionsJson,
HASerializer::JsonLiteralPropertyValue
);
_connectionsPropertyRegistered = true;
}
return true;
}
void HADevice::setPayloadAvailable(const char* payload)
{
_payloadAvailable = payload;
}
if (_model != nullptr) {
static const char DataBefore[] PROGMEM = {",\"mdl\":\""};
void HADevice::setPayloadNotAvailable(const char* payload)
{
_payloadNotAvailable = payload;
}
strcat_P(dst, DataBefore);
strcat(dst, _model);
strcat_P(dst, QuotationSign);
void HADevice::setAvailability(bool online)
{
_available = online;
publishAvailability();
}
bool HADevice::enableSharedAvailability()
{
if (_sharedAvailability) {
return true; // already enabled
}
const uint16_t topicLength = HASerializer::calculateDataTopicLength(
nullptr,
AHATOFSTR(HAAvailabilityTopic)
);
if (topicLength == 0) {
return false;
}
if (_name != nullptr) {
static const char DataBefore[] PROGMEM = {",\"name\":\""};
_availabilityTopic = new char[topicLength];
strcat_P(dst, DataBefore);
strcat(dst, _name);
strcat_P(dst, QuotationSign);
if (HASerializer::generateDataTopic(
_availabilityTopic,
nullptr,
AHATOFSTR(HAAvailabilityTopic)
) > 0) {
_sharedAvailability = true;
return true;
}
if (_softwareVersion != nullptr) {
static const char DataBefore[] PROGMEM = {",\"sw\":\""};
return false;
}
strcat_P(dst, DataBefore);
strcat(dst, _softwareVersion);
strcat_P(dst, QuotationSign);
void HADevice::enableLastWill()
{
HAMqtt* mqtt = HAMqtt::instance();
if (!mqtt || !_availabilityTopic) {
return;
}
{
static const char Data[] PROGMEM = {"}"};
strcat_P(dst, Data);
const char* lw = (_payloadNotAvailable && _payloadNotAvailable[0] != '\0')
? _payloadNotAvailable
: "offline";
mqtt->setLastWill(
_availabilityTopic,
lw,
true
);
}
void HADevice::publishAvailability() const
{
HAMqtt* mqtt = HAMqtt::instance();
if (!_availabilityTopic || !mqtt) {
return;
}
return strlen(dst) + 1; // size with null terminator
if (_available) {
if (_payloadAvailable && _payloadAvailable[0] != '\0') {
const uint16_t len = strlen(_payloadAvailable);
if (mqtt->beginPublish(_availabilityTopic, len, true)) {
mqtt->writePayload(_payloadAvailable, len);
mqtt->endPublish();
}
} else {
const uint16_t len = strlen_P(HAOnline);
if (mqtt->beginPublish(_availabilityTopic, len, true)) {
mqtt->writePayload(AHATOFSTR(HAOnline));
mqtt->endPublish();
}
}
} else {
if (_payloadNotAvailable && _payloadNotAvailable[0] != '\0') {
const uint16_t len = strlen(_payloadNotAvailable);
if (mqtt->beginPublish(_availabilityTopic, len, true)) {
mqtt->writePayload(_payloadNotAvailable, len);
mqtt->endPublish();
}
} else {
const uint16_t len = strlen_P(HAOffline);
if (mqtt->beginPublish(_availabilityTopic, len, true)) {
mqtt->writePayload(AHATOFSTR(HAOffline));
mqtt->endPublish();
}
}
}
}
+207 -17
View File
@@ -3,38 +3,228 @@
#include <Arduino.h>
class HASerializer;
/**
* This class represents your device that's going to be registered in the Home Assistant devices registry.
* Each entity (HABinarySensor, HASensor, etc.) that you use will be owned by this device.
*/
class HADevice
{
public:
/**
* Constructs HADevice without the unique ID.
*
* @note You will need to set the ID using HADevice::setUniqueId method. Otherwise none of the entities will work.
*/
HADevice();
HADevice(const char* uniqueId);
HADevice(const byte* uniqueId, const uint16_t& length);
/**
* Constructs HADevice with the given unique ID (string).
* Keep the unique ID short to save the memory.
*
* @param uniqueId String with the null terminator.
*/
HADevice(const char* uniqueId);
/**
* Constructs HADevice using the given byte array as the unique ID.
* It works in the same way as HADevice::setUniqueId method.
*
* @param uniqueId Bytes array that's going to be converted into the string.
* @param length Number of bytes in the array.
*/
HADevice(const byte* uniqueId, const uint16_t length);
/**
* Deletes HASerializer and the availability topic if the shared availability was enabled.
*/
~HADevice();
HADevice(const HADevice&) = delete;
HADevice& operator=(const HADevice&) = delete;
HADevice(HADevice&&) = delete;
HADevice& operator=(HADevice&&) = delete;
/**
* Returns pointer to the unique ID. It can be nullptr if the device has no ID assigned.
*/
inline const char* getUniqueId() const
{ return _uniqueId; }
inline void setManufacturer(const char* manufacturer)
{ _manufacturer = manufacturer; }
/**
* Returns the instance of the HASerializer used by the device.
* This method is used by all entities to serialize device's representation.
*/
inline const HASerializer* getSerializer() const
{ return _serializer; }
inline void setModel(const char* model)
{ _model = model; }
/**
* Returns true if the shared availability is enabled for the device.
*/
inline bool isSharedAvailabilityEnabled() const
{ return _sharedAvailability; }
inline void setName(const char* name)
{ _name = name; }
/**
* Returns true if the extended unique IDs feature is enabled for the device.
*/
inline bool isExtendedUniqueIdsEnabled() const
{ return _extendedUniqueIds; }
inline void setSoftwareVersion(const char* softwareVersion)
{ _softwareVersion = softwareVersion; }
/**
* Returns availability topic generated by the HADevice::enableSharedAvailability method.
* It can be nullptr if the shared availability is not enabled.
*/
inline const char* getAvailabilityTopic() const
{ return _availabilityTopic; }
bool setUniqueId(const byte* uniqueId, const uint16_t& length);
uint16_t calculateSerializedLength() const;
uint16_t serialize(char* dst) const;
/**
* Returns online/offline state of the device.
*/
inline bool isAvailable() const
{ return _available; }
/**
* Enables the use of extended unique IDs for all registered device types.
* The unique ID of each device type will be prefixed with the device's ID once enabled.
*/
inline void enableExtendedUniqueIds()
{ _extendedUniqueIds = true; }
/**
* Sets unique ID of the device based on the given byte array.
* Each byte is converted into a hex string representation, so the final length of the unique ID will be twice as given.
*
* @param uniqueId Bytes array that's going to be converted into the string.
* @param length Number of bytes in the array.
* @note The unique ID can be set only once (via constructor or using this method).
*/
bool setUniqueId(const byte* uniqueId, const uint16_t length);
/**
* Sets the "manufacturer" property that's going to be displayed in the Home Assistant.
*
* @param manufacturer Any string. Keep it short to save the memory.
*/
void setManufacturer(const char* manufacturer);
/**
* Sets the "model" property that's going to be displayed in the Home Assistant.
*
* @param model Any string. Keep it short to save the memory.
*/
void setModel(const char* model);
/**
* Sets the "name" property that's going to be displayed in the Home Assistant.
*
* @param name Any string. Keep it short to save the memory.
*/
void setName(const char* name);
/**
* Sets the "software version" property that's going to be displayed in the Home Assistant.
*
* @param softwareVersion Any string. Keep it short to save the memory.
*/
void setSoftwareVersion(const char* softwareVersion);
/**
* Sets the "configuration URL" property that's going to be used by the Home Assistant.
*
* @param url Configuration URL to publish.
*/
void setConfigurationUrl(const char* url);
void setModelId(const char* modelId);
void setHardwareVersion(const char* hardwareVersion);
void setSerialNumber(const char* serialNumber);
void setSuggestedArea(const char* suggestedArea);
void setViaDevice(const char* viaDevice);
/**
* Adds one MQTT device connection entry (e.g. `("mac", "aa:bb:cc:dd:ee:ff")`).
* Connections are serialized as JSON arrays inside the discovery `dev` object.
*
* @returns Returns `false` when the internal JSON buffer would overflow.
*/
bool addConnection(const char* type, const char* value);
/**
* Sets the `connections` array as raw JSON (e.g. [[\"mac\",\"aa:bb:cc:dd:ee:ff\"]]).
*
* This legacy escape hatch accepts only a complete JSON array of two-string
* connection tuples and rejects an oversized or malformed value rather than
* truncating a retained discovery document. Prefer addConnection().
*
* @returns false when the value is malformed or does not fit in the
* internal discovery buffer.
*/
bool setConnectionsJson(const char* connectionsJson);
void setPayloadAvailable(const char* payload);
void setPayloadNotAvailable(const char* payload);
inline const char* getPayloadAvailable() const
{ return _payloadAvailable; }
inline const char* getPayloadNotAvailable() const
{ return _payloadNotAvailable; }
/**
* Sets device's availability and publishes MQTT message on the availability topic.
* If the device is not connected to an MQTT broker or the shared availability is not enabled then nothing happens.
*
* @param online Set to true if the device should be displayed as available in the HA panel.
*/
void setAvailability(bool online);
/**
* Enables the shared availability feature.
*/
bool enableSharedAvailability();
/**
* Enables MQTT LWT feature.
* Please note that the shared availability needs to be enabled first.
*/
void enableLastWill();
/**
* Publishes current availability of the device on the availability topic.
* If the device is not connected to an MQTT broker or the shared availability is not enabled then nothing happens.
* This method is called by the HAMqtt when the connection to an MQTT broker is acquired.
*/
void publishAvailability() const;
private:
/// The unique ID of the device. It can be a memory allocated by HADevice::setUniqueId method.
const char* _uniqueId;
const char* _manufacturer;
const char* _model;
const char* _name;
const char* _softwareVersion;
/// Specifies whether HADevice class owns the _uniqueId pointer.
bool _ownsUniqueId;
/// JSON serializer of the HADevice class. It's allocated in the constructor.
HASerializer* _serializer;
/// The availability topic allocated by HADevice::enableSharedAvailability method.
char* _availabilityTopic;
/// Specifies whether the shared availability is enabled.
bool _sharedAvailability;
/// Specifies whether the device is available (online / offline).
bool _available;
/// Specifies whether extended unique IDs feature is enabled.
bool _extendedUniqueIds;
const char* _payloadAvailable;
const char* _payloadNotAvailable;
static const uint16_t MaxConnectionsJsonLength = 192;
char _connectionsJson[MaxConnectionsJsonLength];
bool _hasConnections;
bool _connectionsPropertyRegistered;
};
#endif
+1445 -113
View File
File diff suppressed because it is too large Load Diff
+699 -43
View File
@@ -1,107 +1,509 @@
#ifndef AHA_HAMQTT_H
#define AHA_HAMQTT_H
#include <Arduino.h>
#include <Client.h>
#include <IPAddress.h>
#include "ArduinoHADefines.h"
#define HAMQTT_CALLBACK(name) void (*name)()
#define HAMQTT_STATE_CALLBACK(name) void (*name)(ConnectionState state)
#define HAMQTT_MESSAGE_CALLBACK(name) void (*name)(const char* topic, const uint8_t* payload, uint16_t length)
#define HAMQTT_DEFAULT_PORT 1883
#ifdef ARDUINOHA_TEST
class PubSubClientMock;
#else
#include <PubSubClient.h>
#endif
#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
#define HAMQTT_DEFAULT_DEVICES_LIMIT 6
#else
#define HAMQTT_DEFAULT_DEVICES_LIMIT 24
#endif
class PubSubClient;
class HADevice;
class BaseDeviceType;
class HABaseDeviceType;
class HASerializer;
#if defined(ARDUINO_API_VERSION)
using namespace arduino;
#endif
/**
* This class is a wrapper for the PubSub API.
* It's a central point of the library where instances of all device types are stored.
*/
class HAMqtt
{
public:
static const uint16_t ReconnectInterval = 5000; // ms
/**
* Best-effort classification of the last disconnect or transport failure
* (for diagnostics; not an MQTT DISCONNECT reason code).
*/
enum class DiagnosticDisconnectReason : uint8_t {
None = 0,
LoopReturnedFalse,
DeferredBeginPublishFailed,
DeferredEndPublishFailed,
NotConnectedDuringDeferredFlush,
UnderlyingPubSubStateChanged,
ExplicitDisconnect,
};
HAMqtt(Client& netClient, HADevice& device);
HAMqtt(const char* clientId, Client& netClient, HADevice& device);
static const char* diagnosticDisconnectReasonText(DiagnosticDisconnectReason reason);
enum ConnectionState {
StateConnecting = -5,
StateConnectionTimeout = -4,
StateConnectionLost = -3,
StateConnectionFailed = -2,
StateDisconnected = -1,
StateConnected = 0,
StateBadProtocol = 1,
StateBadClientId = 2,
StateUnavailable = 3,
StateBadCredentials = 4,
StateUnauthorized = 5
};
/**
* Sets prefix for Home Assistant discovery.
* It needs to match prefix set in the HA admin panel.
* Explicit stages for safely migrating retained single-component discovery
* to Home Assistant device discovery.
*/
enum DeviceDiscoveryMigrationState : uint8_t {
DeviceDiscoveryMigrationIdle = 0,
DeviceDiscoveryMigrationMarkersPending,
DeviceDiscoveryMigrationMarkersPublished,
DeviceDiscoveryMigrationDevicePublished,
DeviceDiscoveryMigrationCompleted,
DeviceDiscoveryMigrationRollbackPending
};
/**
* Returns existing instance (singleton) of the HAMqtt class.
* It may be a null pointer if the HAMqtt object was never constructed or it was destroyed.
*/
inline static HAMqtt* instance()
{ return _instance; }
#ifdef ARDUINOHA_TEST
explicit HAMqtt(
PubSubClientMock* pubSub,
HADevice& device,
const uint8_t maxDevicesTypesNb = HAMQTT_DEFAULT_DEVICES_LIMIT
);
#else
/**
* Creates a new instance of the HAMqtt class.
* Please note that only one instance of the class can be initialized at the same time.
*
* @param netClient The EthernetClient or WiFiClient that's going to be used for the network communication.
* @param device An instance of the HADevice class representing your device.
* @param maxDevicesTypesNb The maximum number of device types (sensors, switches, etc.) that you're going to implement.
*/
explicit HAMqtt(
Client& netClient,
HADevice& device,
const uint8_t maxDevicesTypesNb = HAMQTT_DEFAULT_DEVICES_LIMIT
);
#endif
/**
* Removes singleton of the HAMqtt class.
*/
~HAMqtt();
HAMqtt(const HAMqtt&) = delete;
HAMqtt& operator=(const HAMqtt&) = delete;
HAMqtt(HAMqtt&&) = delete;
HAMqtt& operator=(HAMqtt&&) = delete;
/**
* Sets the prefix of the Home Assistant discovery topics.
* It needs to match the prefix set in the HA admin panel.
* The default prefix is "homeassistant".
*
* @param prefix The discovery topics' prefix.
*/
inline void setDiscoveryPrefix(const char* prefix)
{ _discoveryPrefix = prefix; }
/**
* Returns discovery prefix.
* Returns the discovery topics' prefix.
*/
inline const char* getDiscoveryPrefix() const
{ return _discoveryPrefix; }
/**
* Returns instance of the device assigned to the HAMqtt class.
* Sets prefix of the data topics.
* It may be useful if you want to pass MQTT traffic through a bridge.
* The default prefix is "aha".
*
* @param prefix The data topics' prefix.
*/
inline HADevice const* getDevice() const
{ return (_hasDevice ? &_device : nullptr); }
inline void setDataPrefix(const char* prefix)
{ _dataPrefix = prefix; }
/**
* Sets parameters of the connection to the MQTT broker.
* Returns the data topics' prefix.
*/
inline const char* getDataPrefix() const
{ return _dataPrefix; }
/**
* Enables MQTT device discovery payloads.
* Single-component discovery remains the default when this is not enabled.
*/
inline void enableDeviceDiscovery()
{ _deviceDiscoveryEnabled = true; }
/**
* Returns true when MQTT device discovery payloads are enabled.
*/
inline bool isDeviceDiscoveryEnabled() const
{ return _deviceDiscoveryEnabled; }
/**
* Starts an explicit Home Assistant-safe migration from retained
* single-component discovery to device discovery.
*
* This method enables device discovery but does not publish anything. Call
* the subsequent migration methods after MQTT is connected, in order.
*/
bool beginDeviceDiscoveryMigration();
/**
* Publishes retained migration markers to each legacy component config
* topic. The state advances only when every marker is published.
*/
bool publishDeviceDiscoveryMigrationMarkers();
/**
* Publishes the retained device discovery config after all legacy markers
* have been published.
*/
bool publishDeviceDiscoveryMigrationConfig();
/**
* Clears the retained legacy component config topics after the device
* config was published. The state advances only when every cleanup
* publish succeeds.
*/
bool completeDeviceDiscoveryMigration();
/**
* Reverses a staged device discovery migration. A migration marker is
* published to the device discovery topic before legacy retained configs
* are restored and the device config is cleared.
* The method never runs automatically and returns to single-component
* discovery only after every required retained publish succeeds.
*/
bool rollbackDeviceDiscoveryMigration();
/**
* Returns the current in-memory device discovery migration stage.
*/
inline DeviceDiscoveryMigrationState getDeviceDiscoveryMigrationState() const
{ return _deviceDiscoveryMigrationState; }
/**
* Returns true while an explicit device discovery migration awaits a
* marker, device config, or legacy-topic cleanup step.
*/
inline bool isDeviceDiscoveryMigrationInProgress() const
{
return _deviceDiscoveryMigrationState != DeviceDiscoveryMigrationIdle &&
_deviceDiscoveryMigrationState != DeviceDiscoveryMigrationCompleted;
}
/**
* Republishes the current MQTT device discovery payload when device
* discovery is enabled.
*/
bool publishDeviceDiscovery();
/**
* Sets optional `support_url` in the discovery `origin` object (must remain valid).
*/
inline void setOriginSupportUrl(const char* url)
{ _originSupportUrl = url; }
inline const char* getOriginSupportUrl() const
{ return _originSupportUrl; }
/**
* Returns instance of the device assigned to the HAMqtt class.
* It's the same object (pointer) that was passed to the HAMqtt constructor.
*/
inline HADevice const* getDevice() const
{ return &_device; }
/**
* Registers a new callback method that will be called when the device receives an MQTT message.
* Please note that the callback is also fired by internal MQTT messages used by the library.
* You should always verify the topic of the received message.
*
* @param callback Callback method.
*/
inline void onMessage(HAMQTT_MESSAGE_CALLBACK(callback))
{ _messageCallback = callback; }
/**
* Registers a new callback method that will be called each time a connection to the MQTT broker is acquired.
* The callback is also fired after reconnecting to the broker.
* You can use this method to register topics' subscriptions.
*
* @param callback Callback method.
*/
inline void onConnected(HAMQTT_CALLBACK(callback))
{ _connectedCallback = callback; }
/**
* Registers a new callback method that will be called each time the connection to the MQTT broker is lost.
*
* @param callback Callback method.
*/
inline void onDisconnected(HAMQTT_CALLBACK(callback))
{ _disconnectedCallback = callback; }
/**
* Registers a new callback method that will be called each time the connection state changes.
*
* @param callback Callback method.
*/
inline void onStateChanged(HAMQTT_STATE_CALLBACK(callback))
{ _stateChangedCallback = callback; }
/**
* Returns the current state of the MQTT connection.
*/
inline ConnectionState getState() const
{ return _currentState; }
inline uint8_t getDeferredQueueCount() const
{ return _deferredCount; }
inline uint32_t getLastLoopOkAt() const
{ return _lastLoopOkAt; }
inline uint32_t getLastMessageAt() const
{ return _lastMessageAt; }
inline uint32_t getLastPublishAt() const
{ return _lastPublishAt; }
inline uint32_t getLastDisconnectAt() const
{ return _lastDisconnectAt; }
inline DiagnosticDisconnectReason getLastDisconnectReason() const
{ return _lastDisconnectReason; }
int getPubSubState() const;
/**
* Sets parameters of the MQTT connection using the IP address and port.
* The library will try to connect to the broker in first loop cycle.
* Please note that the library automatically reconnects to the broker if connection is lost.
*
* @param serverIp IP address of the MQTT broker.
* @param serverPort Port of the MQTT broker.
* @param username Username for authentication.
* @param password Password for authentication.
* @param username Username for authentication. It can be nullptr if the anonymous connection needs to be performed.
* @param password Password for authentication. It can be nullptr if the anonymous connection needs to be performed.
*/
bool begin(
const IPAddress& serverIp,
const uint16_t& serverPort = 1883,
const IPAddress serverIp,
const uint16_t serverPort = HAMQTT_DEFAULT_PORT,
const char* username = nullptr,
const char* password = nullptr
);
/**
* Sets parameters of the connection to the MQTT broker on default port.
* Sets parameters of the MQTT connection using the IP address and the default port (1883).
* The library will try to connect to the broker in first loop cycle.
* Please note that the library automatically reconnects to the broker if connection is lost.
*
* @param serverIp IP address of the MQTT broker.
* @param serverPort Port of the MQTT broker.
* @param username Username for authentication.
* @param password Password for authentication.
* @param username Username for authentication. It can be nullptr if the anonymous connection needs to be performed.
* @param password Password for authentication. It can be nullptr if the anonymous connection needs to be performed.
*/
bool begin(
const IPAddress& serverIp,
const IPAddress serverIp,
const char* username,
const char* password
);
/**
* ArduinoHA's ticker.
* Sets parameters of the MQTT connection using the hostname and port.
* The library will try to connect to the broker in first loop cycle.
* Please note that the library automatically reconnects to the broker if connection is lost.
*
* @param serverHostname Hostname of the MQTT broker.
* @param serverPort Port of the MQTT broker.
* @param username Username for authentication. It can be nullptr if the anonymous connection needs to be performed.
* @param password Password for authentication. It can be nullptr if the anonymous connection needs to be performed.
*/
bool begin(
const char* serverHostname,
const uint16_t serverPort = HAMQTT_DEFAULT_PORT,
const char* username = nullptr,
const char* password = nullptr
);
/**
* Sets parameters of the MQTT connection using the hostname and the default port (1883).
* The library will try to connect to the broker in first loop cycle.
* Please note that the library automatically reconnects to the broker if connection is lost.
*
* @param serverHostname Hostname of the MQTT broker.
* @param username Username for authentication. It can be nullptr if the anonymous connection needs to be performed.
* @param password Password for authentication. It can be nullptr if the anonymous connection needs to be performed.
*/
bool begin(
const char* serverHostname,
const char* username,
const char* password
);
/**
* Closes the MQTT connection.
*/
bool disconnect();
/**
* This method should be called periodically inside the main loop of the firmware.
* It's safe to call this method in some interval (like 5ms).
*/
void loop();
/**
* Returns true if connection to the MQTT broker is established.
*/
bool isConnected();
bool isConnected() const;
/**
* Sets keep alive for the MQTT connection.
* By default it's 15 seconds.
*
* @param keepAlive Number of seconds to keep connection alive.
*/
void setKeepAlive(uint16_t keepAlive);
/**
* Sets the buffer size for the MQTT connection.
* By default it's 256 bytes.
*
* @param size Size of the buffer.
*/
bool setBufferSize(uint16_t size);
/**
* Sets minimal interval between MQTT reconnect attempts.
* By default it's 10000 milliseconds.
*
* @param interval Interval in milliseconds. Zero is ignored.
*/
void setReconnectInterval(uint16_t interval);
/**
* Returns minimal interval between MQTT reconnect attempts.
*/
inline uint16_t getReconnectInterval() const
{ return _reconnectInterval; }
/**
* Adds a new device's type to the MQTT.
* Each time the connection with MQTT broker is acquired, the HAMqtt class
* calls "onMqttConnected" method in all devices' types instances.
*
* @param deviceType Instance of the device's type (eg. HATriggers).
* @note The HAMqtt class doesn't take ownership of the given pointer.
* @param deviceType Instance of the device's type (HASwitch, HABinarySensor, etc.).
*/
void addDeviceType(BaseDeviceType* deviceType);
bool addDeviceType(HABaseDeviceType* deviceType);
/**
* Publishes MQTT message with given topic and payload.
* Message won't be published if connection with MQTT broker is not established.
* Removes a destroyed entity from the connection registry.
* The MQTT instance does not own entity lifetimes.
*/
bool removeDeviceType(HABaseDeviceType* deviceType);
/**
* Number of entities currently registered for connection callbacks.
*/
inline uint8_t getRegisteredDeviceTypeCount() const
{ return _devicesTypesNb; }
/**
* Maximum number of entities that can be registered in this HAMqtt instance.
*/
inline uint8_t getDeviceTypeLimit() const
{ return _maxDevicesTypesNb; }
/**
* Number of registrations dropped because the configured entity limit was reached.
*/
inline uint16_t getDeviceTypeRegistrationFailures() const
{ return _deviceTypeRegistrationFailures; }
/**
* Publishes the MQTT message with given topic and payload.
* Message won't be published if the connection with the MQTT broker is not established.
* In this case method returns false.
*
* @param topic Topic to publish.
* @param payload Payload to publish (it may be empty const char).
* @param retained Determines whether message should be retained.
* While handling an inbound MQTT message (see isProcessingMessage()), a successful
* return means the message was queued for send after dispatch completes, not that it
* was already transmitted. Outside that context, behavior is unchanged.
*
* @param topic The topic to publish.
* @param payload The payload to publish (it may be empty const char).
* @param retained Specifies whether message should be retained.
*/
bool publish(const char* topic, const char* payload, bool retained = false);
/**
* Begins publishing of a message with the given properties.
* When this method returns true the payload can be written using HAMqtt::writePayload method.
*
* @param topic Topic of the published message.
* @param payloadLength Length of the payload (bytes) that's going to be published.
* @param retained Specifies whether the published message should be retained.
*/
bool beginPublish(const char* topic, uint16_t payloadLength, bool retained = false);
bool writePayload(const char* data, uint16_t length);
bool writePayload_P(const char* src);
/**
* Writes given string to the TCP stream.
* Please note that before writing any data the HAMqtt::beginPublish method
* needs to be called.
*
* @param data The string to publish.
* @param length Length of the data (bytes).
*/
bool writePayload(const char* data, const uint16_t length);
/**
* Writes given data to the TCP stream.
* Please note that before writing any data the HAMqtt::beginPublish method
* needs to be called.
*
* @param data The data to publish.
* @param length Length of the data (bytes).
*/
bool writePayload(const uint8_t* data, const uint16_t length);
/**
* Writes given progmem data to the TCP stream.
* Please note that before writing any data the HAMqtt::beginPublish method
* needs to be called.
*
* @param data Progmem data to publish.
*/
bool writePayload(const __FlashStringHelper* data);
/**
* Finishes publishing of a message.
* After calling this method the message will be processed by the broker.
*/
bool endPublish();
/**
@@ -112,20 +514,89 @@ public:
* Please note that you need to subscribe topic each time the connection
* with the broker is acquired.
*
* @param topic Topic to subscribe
* @param topic Topic to subscribe.
*/
bool subscribe(const char* topic);
/**
* Enables the last will message that will be produced when the device disconnects from the broker.
* If you want to change availability of the device in Home Assistant panel
* please use enableLastWill() method from the HADevice class instead.
*
* @param lastWillTopic The topic to publish.
* @param lastWillMessage The message (payload) to publish.
* @param lastWillRetain Specifies whether the published message should be retained.
*/
inline void setLastWill(
const char* lastWillTopic,
const char* lastWillMessage,
bool lastWillRetain
) {
_lastWillTopic = lastWillTopic;
_lastWillMessage = lastWillMessage;
_lastWillRetain = lastWillRetain;
}
/**
* Processes MQTT message received from the broker (subscription).
*
* @note Do not use this method on your own. It's only for the internal purpose.
* @param topic Topic of the message.
* @param payload Content of the message.
* @param length Length of the message.
*/
void processMessage(char* topic, uint8_t* payload, uint16_t length);
void processMessage(const char* topic, const uint8_t* payload, uint16_t length);
/**
* True while handling an inbound MQTT message (user onMessage and device onMqttMessage).
* Publish attempts in this window are queued and flushed when dispatch completes.
*/
inline bool isProcessingMessage() const
{ return _messageDispatchDepth > 0; }
#ifdef ARDUINOHA_TEST
inline uint8_t getDevicesTypesNb() const
{ return _devicesTypesNb; }
inline HABaseDeviceType** getDevicesTypes() const
{ return _devicesTypes; }
inline uint16_t getDeferredPublishEnqueueCountForTest() const
{ return _deferredPublishEnqueueCountForTest; }
inline void resetDeferredPublishTestCounters()
{
_deferredPublishEnqueueCountForTest = 0;
_deferredFlushFailedForTest = false;
_lastDeferredFlushErrorForTest = 0;
}
inline uint8_t getPendingDeferredPublishesForTest() const
{ return _deferredCount; }
inline bool hasDeferredFlushFailureForTest() const
{ return _deferredFlushFailedForTest; }
inline uint8_t getLastDeferredFlushErrorForTest() const
{ return _lastDeferredFlushErrorForTest; }
inline bool didDeferredFlushFailDueToDisconnectForTest() const
{ return _lastDeferredFlushErrorForTest == 1; }
inline bool didDeferredFlushFailAtBeginPublishForTest() const
{ return _lastDeferredFlushErrorForTest == 2; }
inline bool didDeferredFlushFailAtEndPublishForTest() const
{ return _lastDeferredFlushErrorForTest == 3; }
#endif
private:
/// Default interval between MQTT reconnect attempts (milliseconds).
static const uint16_t DefaultReconnectInterval = 10000;
/// Living instance of the HAMqtt class. It can be nullptr.
static HAMqtt* _instance;
/**
* Attempts to connect to the MQTT broker.
* The method uses properties passed to the "begin" method.
@@ -135,21 +606,206 @@ private:
/**
* This method is called each time the connection with MQTT broker is acquired.
*/
void onConnected();
void onConnectedLogic();
Client& _netClient;
HADevice& _device;
bool _hasDevice;
bool _initialized;
const char* _discoveryPrefix;
bool publishDeviceDiscoveryPayload(HABaseDeviceType* removalType = nullptr);
HASerializer* buildDeviceDiscoveryComponentSerializer(
HABaseDeviceType* deviceType,
HABaseDeviceType* removalType
);
bool clearDeviceDiscoveryConfig();
bool publishDeviceDiscoveryMigrationMarker(HABaseDeviceType* deviceType);
/**
* Marks the retained device discovery config for Home Assistant's reverse
* migration protocol before restoring legacy component configs.
*/
bool publishDeviceDiscoveryMigrationMarker();
/**
* Removes a component from a device discovery payload using Home
* Assistant's required platform-only marker, followed by a compacted
* bundle when another component remains.
*/
bool removeDeviceDiscoveryComponent(HABaseDeviceType* deviceType);
/**
* Re-adds (or refreshes) a component in the current device discovery
* payload.
*/
bool republishDeviceDiscoveryComponent(HABaseDeviceType* deviceType);
/**
* Sets the state of the MQTT connection.
*/
void setState(ConnectionState state);
struct DeferredPublishMessage {
char* topic;
uint8_t* payload;
uint16_t length;
bool retained;
};
struct DeferredPublishBuilder {
bool active;
bool valid;
char* topic;
uint8_t* payload;
uint16_t expectedLength;
uint16_t writtenLength;
bool retained;
};
enum DeferredFlushError {
DeferredFlushErrorNone = 0,
DeferredFlushErrorNotConnected,
DeferredFlushErrorBeginPublish,
DeferredFlushErrorEndPublish
};
static const uint8_t DeferredQueueCapacity = 8;
bool enqueueDeferredPublish(
const char* topic,
const uint8_t* payload,
uint16_t length,
bool retained
);
void clearDeferredMessage(DeferredPublishMessage& msg);
void clearDeferredQueue();
void clearDeferredBuilder();
/**
* Sends queued publishes in order. On transport failure, stops and leaves the
* remaining queue intact for a later retry (e.g. from loop()).
*/
bool flushDeferredPublishes();
/**
* PubSubClient snapshot when a direct publish step fails (header or endPublish).
*/
String formatDirectPublishFailureDiagnostics(bool hamqttConnectedBefore, int pubsubStateBefore) const;
// Buffer direct MQTT streaming writes so serializers do not issue hundreds
// of tiny TCP writes while a PubSubClient publish is open.
static const uint16_t DirectPublishBufferSize = 128;
bool flushDirectPublishBuffer();
bool appendDirectPublishPayload(const uint8_t* data, uint16_t length);
bool appendDirectPublishProgmemPayload(const __FlashStringHelper* src);
void clearDirectPublishBuffer();
void abortDirectPublish();
#ifdef ARDUINOHA_TEST
PubSubClientMock* _mqtt;
#else
/// Storage for the PubSubClient instance used in production builds.
PubSubClient _mqttStorage;
/// Pointer to the active MQTT client implementation.
PubSubClient* _mqtt;
IPAddress* _serverIp;
uint16_t _serverPort;
#endif
uint8_t _directPublishBuffer[DirectPublishBufferSize];
uint16_t _directPublishBufferLength;
bool _directPublishActive;
/// Instance of the HADevice passed to the constructor.
const HADevice& _device;
/// The callback method that will be called when an MQTT message is received.
HAMQTT_MESSAGE_CALLBACK(_messageCallback);
/// The callback method that will be called when the MQTT connection is acquired.
HAMQTT_CALLBACK(_connectedCallback);
/// The callback method that will be called when the MQTT connection is lost.
HAMQTT_CALLBACK(_disconnectedCallback);
/// The callback method that will be called when the MQTT connection state changes.
HAMQTT_STATE_CALLBACK(_stateChangedCallback);
/// Specifies whether the HAMqtt::begin method was ever called.
bool _initialized;
/// Teh discovery prefix that's used for the configuration messages.
const char* _discoveryPrefix;
/// The data prefix that's used for publishing data messages.
const char* _dataPrefix;
/// Enables MQTT device discovery mode when set to true.
bool _deviceDiscoveryEnabled;
/// Current in-memory stage of an explicit device discovery migration.
DeviceDiscoveryMigrationState _deviceDiscoveryMigrationState;
const char* _originSupportUrl;
/// The username used for the authentication. It's set in the HAMqtt::begin method.
const char* _username;
/// The password used for the authentication. It's set in the HAMqtt::begin method.
const char* _password;
/// Time of the last connection attemps (milliseconds since boot).
uint32_t _lastConnectionAttemptAt;
/// Interval between MQTT reconnect attempts (milliseconds).
uint16_t _reconnectInterval;
/// The amount of registered devices types.
uint8_t _devicesTypesNb;
BaseDeviceType** _devicesTypes;
/// The maximum amount of devices types that can be registered.
uint8_t _maxDevicesTypesNb;
/// Pointers of all registered devices types (array of pointers).
HABaseDeviceType** _devicesTypes;
/// The last will topic set by HAMqtt::setLastWill
const char* _lastWillTopic;
/// Count of entity registrations rejected because the configured cap was full.
uint16_t _deviceTypeRegistrationFailures;
/// The last will message set by HAMqtt::setLastWill
const char* _lastWillMessage;
/// The last will retain set by HAMqtt::setLastWill
bool _lastWillRetain;
/// The last known state of the MQTT connection.
ConnectionState _currentState;
uint32_t _lastLoopOkAt;
uint32_t _lastMessageAt;
uint32_t _lastPublishAt;
uint32_t _lastDisconnectAt;
DiagnosticDisconnectReason _lastDisconnectReason;
/// Nesting depth for inbound message dispatch (processMessage).
uint8_t _messageDispatchDepth;
DeferredPublishMessage _deferredQueue[DeferredQueueCapacity];
uint8_t _deferredHead;
uint8_t _deferredCount;
DeferredPublishBuilder _deferredBuilder;
#ifdef ARDUINOHA_TEST
uint16_t _deferredPublishEnqueueCountForTest = 0;
bool _deferredFlushFailedForTest = false;
uint8_t _lastDeferredFlushErrorForTest = 0;
#endif
friend class HABaseDeviceType;
};
#endif
-79
View File
@@ -1,79 +0,0 @@
#include <Arduino.h>
#include "HAUtils.h"
bool HAUtils::endsWith(const char* str, const char* suffix)
{
if (str == nullptr || suffix == nullptr) {
return false;
}
const uint16_t& lenstr = strlen(str);
const uint16_t& lensuffix = strlen(suffix);
if (lensuffix > lenstr) {
return false;
}
return (strncmp(str + lenstr - lensuffix, suffix, lensuffix) == 0);
}
void HAUtils::byteArrayToStr(
char* dst,
const byte* src,
const uint16_t& length
)
{
const uint16_t& finalLength = (length * 2);
static const char map[] PROGMEM = {"0123456789abcdef"};
for (uint8_t i = 0; i < length; i++) {
dst[i*2] = pgm_read_byte(&map[((char)src[i] & 0XF0) >> 4]);
dst[i*2+1] = pgm_read_byte(&map[((char)src[i] & 0x0F)]);
}
dst[finalLength] = '\0';
}
char* HAUtils::byteArrayToStr(
const byte* src,
const uint16_t& length
)
{
char* dst = (char*)malloc((length * 2) + 1); // include null terminator
byteArrayToStr(dst, src, length);
return dst;
}
uint8_t HAUtils::getValueTypeLength(const ValueType& type)
{
switch(type) {
case ValueTypeUint8:
return sizeof(uint8_t);
case ValueTypeUint16:
return sizeof(uint16_t);
case ValueTypeUint32:
return sizeof(uint32_t);
case ValueTypeInt8:
return sizeof(int8_t);
case ValueTypeInt16:
return sizeof(int16_t);
case ValueTypeInt32:
return sizeof(int32_t);
case ValueTypeDouble:
return sizeof(double);
case ValueTypeFloat:
return sizeof(float);
default:
return 0;
}
}
-58
View File
@@ -1,58 +0,0 @@
#ifndef AHA_HAUTILS_H
#define AHA_HAUTILS_H
#include <Arduino.h>
class HAUtils
{
public:
enum ValueType {
ValueTypeUnknown = -1,
ValueTypeUint8,
ValueTypeUint16,
ValueTypeUint32,
ValueTypeInt8,
ValueTypeInt16,
ValueTypeInt32,
ValueTypeDouble,
ValueTypeFloat
};
static bool endsWith(
const char* str,
const char* suffi
);
static void byteArrayToStr(
char* dst,
const byte* src,
const uint16_t& length
);
static char* byteArrayToStr(
const byte* src,
const uint16_t& length
);
template <typename A, typename B >
static bool compareType(A a, B b) { return false; }
template <typename A, typename B >
static bool compareType(A a, A b) { return true; }
template <typename T>
static ValueType determineValueType() {
if (compareType<T, uint8_t>(0, (uint8_t)0)) return ValueTypeUint8;
else if (compareType<T, uint16_t>(0, (uint16_t)0)) return ValueTypeUint16;
else if (compareType<T, uint32_t>(0, (uint32_t)0)) return ValueTypeUint32;
else if (compareType<T, int8_t>(0, (int8_t)0)) return ValueTypeInt8;
else if (compareType<T, int16_t>(0, (int16_t)0)) return ValueTypeInt16;
else if (compareType<T, int32_t>(0, (int32_t)0)) return ValueTypeInt32;
else if (compareType<T, double>(0, (double)0)) return ValueTypeDouble;
else if (compareType<T, float>(0, (float)0)) return ValueTypeFloat;
return ValueTypeUnknown;
}
static uint8_t getValueTypeLength(const ValueType& type);
};
#endif
-70
View File
@@ -1,70 +0,0 @@
#include "BaseDeviceType.h"
#include "../HAMqtt.h"
#include "../HADevice.h"
BaseDeviceType::BaseDeviceType(
HAMqtt& mqtt,
const char* componentName,
const char* name
) :
_mqtt(mqtt),
_componentName(componentName),
_name(name),
_availability(AvailabilityDefault)
{
_mqtt.addDeviceType(this);
}
BaseDeviceType::~BaseDeviceType()
{
}
void BaseDeviceType::setAvailability(bool online)
{
_availability = (online ? AvailabilityOnline : AvailabilityOffline);
publishAvailability();
}
void BaseDeviceType::publishAvailability()
{
if (_availability == AvailabilityDefault ||
!_mqtt.isConnected() ||
strlen(_name) == 0 ||
strlen(_componentName) == 0) {
return;
}
const uint16_t& topicSize = DeviceTypeSerializer::calculateTopicLength(
mqtt(),
_componentName,
_name,
DeviceTypeSerializer::AvailabilityTopic
);
if (topicSize == 0) {
return;
}
char topic[topicSize];
DeviceTypeSerializer::generateTopic(
mqtt(),
topic,
_componentName,
_name,
DeviceTypeSerializer::AvailabilityTopic
);
if (strlen(topic) == 0) {
return;
}
mqtt()->publish(
topic,
(
_availability == AvailabilityOnline ?
DeviceTypeSerializer::Online :
DeviceTypeSerializer::Offline
),
true
);
}
-63
View File
@@ -1,63 +0,0 @@
#ifndef AHA_BASEDEVICETYPE_H
#define AHA_BASEDEVICETYPE_H
#include <stdint.h>
#include "DeviceTypeSerializer.h"
class HAMqtt;
class BaseDeviceType
{
public:
BaseDeviceType(
HAMqtt& mqtt,
const char* componentName,
const char* name
);
virtual ~BaseDeviceType();
inline bool isOnline() const
{ return (_availability == AvailabilityOnline); }
virtual void setAvailability(bool online);
protected:
inline HAMqtt* mqtt() const
{ return &_mqtt; }
inline const char* name() const
{ return _name; }
inline const char* componentName() const
{ return _componentName; }
inline bool isAvailabilityConfigured() const
{ return (_availability != AvailabilityDefault); }
virtual void onMqttConnected() = 0;
virtual void onMqttMessage(
const char* topic,
const uint8_t* payload,
const uint16_t& length
) { };
virtual void publishAvailability();
const char* const _componentName;
const char* const _name;
private:
enum Availability {
AvailabilityDefault = 0,
AvailabilityOnline,
AvailabilityOffline
};
HAMqtt& _mqtt;
Availability _availability;
friend class HAMqtt;
};
#endif
-266
View File
@@ -1,266 +0,0 @@
#include <Arduino.h>
#include "DeviceTypeSerializer.h"
#include "../HAMqtt.h"
#include "../HADevice.h"
static const char CharSlash[] PROGMEM = {"/"};
static const char CharUnderscore[] PROGMEM = {"_"};
static const char CharQuotation[] PROGMEM = {"\""};
const char* DeviceTypeSerializer::ConfigTopic = "config";
const char* DeviceTypeSerializer::EventTopic = "event";
const char* DeviceTypeSerializer::AvailabilityTopic = "avail";
const char* DeviceTypeSerializer::StateTopic = "state";
const char* DeviceTypeSerializer::CommandTopic = "cmd";
const char* DeviceTypeSerializer::Online = "online";
const char* DeviceTypeSerializer::Offline = "offline";
const char* DeviceTypeSerializer::StateOn = "ON";
const char* DeviceTypeSerializer::StateOff = "OFF";
uint16_t DeviceTypeSerializer::calculateTopicLength(
const HAMqtt* mqtt,
const char* component,
const char* objectId,
const char* suffix,
bool includeNullTerminator
)
{
const char* prefix = mqtt->getDiscoveryPrefix();
if (prefix == nullptr) {
return 0;
}
uint16_t size =
strlen(prefix) + 1 + // with slash
strlen(component) + 1 + // with slash
strlen(suffix);
if (objectId != nullptr) {
size += strlen(objectId) + 1; // with slash
} else {
size += 1; // slash
}
if (mqtt->getDevice() != nullptr) {
size += strlen(mqtt->getDevice()->getUniqueId()) + 1; // with slash
}
if (includeNullTerminator) {
size += 1;
}
return size;
}
uint16_t DeviceTypeSerializer::generateTopic(
const HAMqtt* mqtt,
char* output,
const char* component,
const char* objectId,
const char* suffix
)
{
const char* prefix = mqtt->getDiscoveryPrefix();
strcpy(output, prefix);
strcat_P(output, CharSlash);
strcat(output, component);
strcat_P(output, CharSlash);
if (mqtt->getDevice() != nullptr) {
strcat(output, mqtt->getDevice()->getUniqueId());
strcat_P(output, CharSlash);
}
strcat(output, objectId);
strcat_P(output, CharSlash);
strcat(output, suffix);
return strlen(output) + 1; // size with null terminator
}
uint16_t DeviceTypeSerializer::calculateBaseJsonDataSize()
{
return 2; // opening and closing brackets of the JSON data
}
uint16_t DeviceTypeSerializer::calculateNameFieldSize(const char* name)
{
if (name == nullptr) {
return 0;
}
// Field format: ,"name":"[NAME]"
return strlen(name) + 10; // 10 - length of the JSON decorators for this field
}
uint16_t DeviceTypeSerializer::calculateUniqueIdFieldSize(
const HADevice* device,
const char* name
)
{
if (device == nullptr || name == nullptr) {
return 0;
}
// Field format: ,"uniq_id":"[DEVICE ID]_[NAME]"
return (
strlen(device->getUniqueId()) +
strlen(name) +
14 // 14 - length of the JSON decorators for this field
);
}
uint16_t DeviceTypeSerializer::calculateAvailabilityFieldSize(
const HAMqtt* mqtt,
const char* componentName,
const char* name
)
{
if (mqtt == nullptr || componentName == nullptr || name == nullptr) {
return 0;
}
const uint16_t& availabilityTopicLength = calculateTopicLength(
mqtt,
componentName,
name,
AvailabilityTopic,
false
);
if (availabilityTopicLength == 0) {
return 0;
}
// Field format: ,"avty_t":"[TOPIC]"
return availabilityTopicLength + 12; // 12 - length of the JSON decorators for this field
}
uint16_t DeviceTypeSerializer::calculateDeviceFieldSize(
const char* serializedDevice
)
{
if (serializedDevice == nullptr) {
return 0;
}
// Field format: ,"dev":[DEVICE]
return strlen(serializedDevice) + 7; // 7 - length of the JSON decorators for this field
}
void DeviceTypeSerializer::mqttWriteBeginningJson(HAMqtt* mqtt)
{
if (mqtt == nullptr) {
return;
}
static const char Data[] PROGMEM = {"{"};
mqtt->writePayload_P(Data);
}
void DeviceTypeSerializer::mqttWriteEndJson(HAMqtt* mqtt)
{
if (mqtt == nullptr) {
return;
}
static const char Data[] PROGMEM = {"}"};
mqtt->writePayload_P(Data);
}
void DeviceTypeSerializer::mqttWriteConstCharField(
HAMqtt* mqtt,
const char* prefix,
const char* value
)
{
if (mqtt == nullptr || prefix == nullptr || value == nullptr) {
return;
}
mqtt->writePayload_P(prefix);
mqtt->writePayload(value, strlen(value));
mqtt->writePayload_P(CharQuotation);
}
void DeviceTypeSerializer::mqttWriteNameField(HAMqtt* mqtt, const char* name)
{
if (mqtt == nullptr || name == nullptr) {
return;
}
static const char Prefix[] PROGMEM = {",\"name\":\""};
mqttWriteConstCharField(mqtt, Prefix, name);
}
void DeviceTypeSerializer::mqttWriteUniqueIdField(
HAMqtt* mqtt,
const char* name
)
{
if (mqtt == nullptr || name == nullptr) {
return;
}
static const char Prefix[] PROGMEM = {",\"uniq_id\":\""};
uint8_t uniqueIdLength = strlen(name) + strlen(mqtt->getDevice()->getUniqueId()) + 2; // underscore and null temrinator
char uniqueId[uniqueIdLength];
strcpy(uniqueId, name);
strcat_P(uniqueId, CharUnderscore);
strcat(uniqueId, mqtt->getDevice()->getUniqueId());
mqttWriteConstCharField(mqtt, Prefix, uniqueId);
}
void DeviceTypeSerializer::mqttWriteAvailabilityField(
HAMqtt* mqtt,
const char* componentName,
const char* name
)
{
if (mqtt == nullptr || componentName == nullptr || name == nullptr) {
return;
}
const uint16_t& topicSize = calculateTopicLength(
mqtt,
componentName,
name,
AvailabilityTopic
);
if (topicSize == 0) {
return;
}
char availabilityTopic[topicSize];
generateTopic(
mqtt,
availabilityTopic,
componentName,
name,
AvailabilityTopic
);
if (strlen(availabilityTopic) == 0) {
return;
}
static const char Prefix[] PROGMEM = {",\"avty_t\":\""};
mqttWriteConstCharField(mqtt, Prefix, availabilityTopic);
}
void DeviceTypeSerializer::mqttWriteDeviceField(
HAMqtt* mqtt,
const char* serializedDevice
)
{
if (mqtt == nullptr || serializedDevice == nullptr) {
return;
}
static const char Data[] PROGMEM = {",\"dev\":"};
mqtt->writePayload_P(Data);
mqtt->writePayload(serializedDevice, strlen(serializedDevice));
}
-98
View File
@@ -1,98 +0,0 @@
#ifndef AHA_DEVICETYPESERIALIZER_H
#define AHA_DEVICETYPESERIALIZER_H
#include <stdint.h>
class HAMqtt;
class HADevice;
class DeviceTypeSerializer
{
public:
static const char* ConfigTopic;
static const char* EventTopic;
static const char* AvailabilityTopic;
static const char* StateTopic;
static const char* CommandTopic;
static const char* Online;
static const char* Offline;
static const char* StateOn;
static const char* StateOff;
/**
* Calculates length of the topic with given parameters.
* Topic format: [discovery prefix]/[component]/[objectId]/[suffix]
*
* @param component
* @param objectId
* @param suffix
* @param includeNullTerminator
*/
static uint16_t calculateTopicLength(
const HAMqtt* mqtt,
const char* component,
const char* objectId,
const char* suffix,
bool includeNullTerminator = true
);
/**
* Generates topic and saves it to the given buffer.
* Please note that size of the buffer must be calculated by `calculateTopicLength` method first.
* Topic format: [discovery prefix]/[component]/[objectId]/[suffix]
*
* @param output
* @param component
* @param objectId
* @param suffix
* @param includeNullTerminator
*/
static uint16_t generateTopic(
const HAMqtt* mqtt,
char* output,
const char* component,
const char* objectId,
const char* suffix
);
static uint16_t calculateBaseJsonDataSize();
static uint16_t calculateNameFieldSize(
const char* name
);
static uint16_t calculateUniqueIdFieldSize(
const HADevice* device,
const char* name
);
static uint16_t calculateAvailabilityFieldSize(
const HAMqtt* mqtt,
const char* componentName,
const char* name
);
static uint16_t calculateDeviceFieldSize(
const char* serializedDevice
);
static void mqttWriteBeginningJson(HAMqtt* mqtt);
static void mqttWriteEndJson(HAMqtt* mqtt);
static void mqttWriteConstCharField(
HAMqtt* mqtt,
const char* prefix,
const char* value
);
static void mqttWriteNameField(HAMqtt* mqtt, const char* name);
static void mqttWriteUniqueIdField(
HAMqtt* mqtt,
const char* name
);
static void mqttWriteAvailabilityField(
HAMqtt* mqtt,
const char* componentName,
const char* name
);
static void mqttWriteDeviceField(
HAMqtt* mqtt,
const char* serializedDevice
);
};
#endif
+667
View File
@@ -0,0 +1,667 @@
#include "HABaseDeviceType.h"
#include "../HAMqtt.h"
#include "../HADevice.h"
#include "../utils/HAUtils.h"
#include "../utils/HADictionary.h"
#include "../utils/HASerializer.h"
#include <string.h>
HABaseDeviceType* HABaseDeviceType::_firstInstance = nullptr;
void HABaseDeviceType::registerAllWith(HAMqtt& mqttInstance)
{
for (HABaseDeviceType* entity = _firstInstance; entity; entity = entity->_nextInstance) {
mqttInstance.addDeviceType(entity);
}
}
HABaseDeviceType::HABaseDeviceType(
const __FlashStringHelper* componentName,
const char* uniqueId
) :
_componentName(componentName),
_uniqueId(uniqueId),
_name(nullptr),
_objectId(nullptr),
_defaultEntityId(nullptr),
_entityCategory(nullptr),
_serializer(nullptr),
_hasEnabledByDefault(false),
_enabledByDefault(true),
_entityPicture(nullptr),
_hasQos(false),
_qosNumeric(),
_encoding(nullptr),
_payloadAvailable(nullptr),
_payloadNotAvailable(nullptr),
_availabilityMode(nullptr),
_availabilityList(),
_deviceDiscoveryRemoved(false),
_availability(AvailabilityDefault),
_nextInstance(_firstInstance)
{
_firstInstance = this;
if (HAMqtt* mqttInstance = mqtt()) {
mqttInstance->addDeviceType(this);
}
}
HABaseDeviceType::~HABaseDeviceType()
{
if (_firstInstance == this) {
_firstInstance = _nextInstance;
} else {
HABaseDeviceType* previous = _firstInstance;
while (previous && previous->_nextInstance != this) {
previous = previous->_nextInstance;
}
if (previous) {
previous->_nextInstance = _nextInstance;
}
}
if (HAMqtt* mqttInstance = mqtt()) {
mqttInstance->removeDeviceType(this);
}
destroySerializer();
}
void HABaseDeviceType::setAvailability(bool online)
{
_availability = (online ? AvailabilityOnline : AvailabilityOffline);
publishAvailability();
}
bool HABaseDeviceType::removeFromDiscovery()
{
HAMqtt* mqttInstance = mqtt();
if (!mqttInstance) {
return false;
}
if (mqttInstance->isDeviceDiscoveryEnabled() && supportsDeviceDiscovery()) {
return mqttInstance->removeDeviceDiscoveryComponent(this);
}
return removeSingleComponentDiscovery();
}
bool HABaseDeviceType::removeSingleComponentDiscovery()
{
HAMqtt* mqttInstance = mqtt();
if (!mqttInstance) {
return false;
}
const uint16_t topicLength = HASerializer::calculateConfigTopicLength(
componentName(),
uniqueId()
);
if (topicLength == 0) {
return false;
}
char topic[topicLength];
if (!HASerializer::generateConfigTopic(topic, componentName(), uniqueId())) {
return false;
}
destroySerializer();
if (!mqttInstance->beginPublish(topic, 0, true)) {
return false;
}
return mqttInstance->endPublish();
}
bool HABaseDeviceType::republishDiscovery()
{
HAMqtt* mqttInstance = mqtt();
if (!mqttInstance) {
return false;
}
if (shouldPublishSingleComponentConfig()) {
return publishConfig();
}
return mqttInstance->republishDeviceDiscoveryComponent(this);
}
HAMqtt* HABaseDeviceType::mqtt()
{
return HAMqtt::instance();
}
void HABaseDeviceType::subscribeTopic(
const char* uniqueId,
const __FlashStringHelper* topic
)
{
const uint16_t topicLength = HASerializer::calculateDataTopicLength(
uniqueId,
topic
);
if (topicLength == 0) {
return;
}
char fullTopic[topicLength];
if (!HASerializer::generateDataTopic(
fullTopic,
uniqueId,
topic
)) {
return;
}
HAMqtt::instance()->subscribe(fullTopic);
}
void HABaseDeviceType::onMqttMessage(
const char* topic,
const uint8_t* payload,
const uint16_t length
)
{
(void)topic;
(void)payload;
(void)length;
}
void HABaseDeviceType::destroySerializer()
{
if (_serializer) {
delete _serializer;
_serializer = nullptr;
}
}
bool HABaseDeviceType::publishConfig()
{
HAMqtt* mqttInstance = mqtt();
if (!mqttInstance) {
return false;
}
buildSerializer();
if (_serializer == nullptr) {
return false;
}
const uint16_t topicLength = HASerializer::calculateConfigTopicLength(
componentName(),
uniqueId()
);
const uint16_t dataLength = _serializer->calculateSize();
bool published = false;
if (topicLength > 0 && dataLength > 0) {
char topic[topicLength];
if (!HASerializer::generateConfigTopic(
topic,
componentName(),
uniqueId()
)) {
destroySerializer();
return false;
}
if (mqttInstance->beginPublish(topic, dataLength, true)) {
const bool flushed = _serializer->flush();
const bool ended = mqttInstance->endPublish();
published = flushed && ended;
}
}
destroySerializer();
return published;
}
void HABaseDeviceType::publishAvailability()
{
HAMqtt* mqttInstance = mqtt();
if (!mqttInstance) {
return;
}
const HADevice* device = mqttInstance->getDevice();
if (
!device ||
device->isSharedAvailabilityEnabled() ||
!isAvailabilityConfigured()
) {
return;
}
const bool online = (_availability == AvailabilityOnline);
if (_availabilityList.count() > 0) {
char defaultBuf[12];
const __FlashStringHelper* flashPayload = online
? AHATOFSTR(HAOnline)
: AHATOFSTR(HAOffline);
for (uint8_t i = 0; i < _availabilityList.count(); i++) {
const HAAvailabilityConfig::Entry& e = _availabilityList.getEntry(i);
const char* payload = nullptr;
if (online) {
if (e.payloadAvailable && e.payloadAvailable[0] != '\0') {
payload = e.payloadAvailable;
} else if (_payloadAvailable && _payloadAvailable[0] != '\0') {
payload = _payloadAvailable;
} else {
strncpy_P(
defaultBuf,
reinterpret_cast<PGM_P>(AHAFROMFSTR(flashPayload)),
sizeof(defaultBuf) - 1
);
defaultBuf[sizeof(defaultBuf) - 1] = 0;
payload = defaultBuf;
}
} else {
if (e.payloadNotAvailable && e.payloadNotAvailable[0] != '\0') {
payload = e.payloadNotAvailable;
} else if (_payloadNotAvailable && _payloadNotAvailable[0] != '\0') {
payload = _payloadNotAvailable;
} else {
strncpy_P(
defaultBuf,
reinterpret_cast<PGM_P>(AHAFROMFSTR(flashPayload)),
sizeof(defaultBuf) - 1
);
defaultBuf[sizeof(defaultBuf) - 1] = 0;
payload = defaultBuf;
}
}
publishAbsolute(e.topic, payload, true);
}
return;
}
const char* ramPayload = online
? effectivePayloadAvailable()
: effectivePayloadNotAvailable();
if (ramPayload) {
publishOnDataTopic(AHATOFSTR(HAAvailabilityTopic), ramPayload, true);
} else {
publishOnDataTopic(
AHATOFSTR(HAAvailabilityTopic),
online ? AHATOFSTR(HAOnline) : AHATOFSTR(HAOffline),
true
);
}
}
bool HABaseDeviceType::publishAbsolute(
const char* fullTopic,
const char* payload,
bool retained
)
{
if (!fullTopic || !payload || !mqtt()) {
return false;
}
HAMqtt* mqttInstance = mqtt();
const uint16_t len = strlen(payload);
if (!mqttInstance->beginPublish(fullTopic, len, retained)) {
return false;
}
const bool written = mqttInstance->writePayload(payload, len);
const bool ended = mqttInstance->endPublish();
return written && ended;
}
bool HABaseDeviceType::publishOnDataTopic(
const __FlashStringHelper* topic,
const __FlashStringHelper* payload,
bool retained
)
{
if (!payload) {
return false;
}
return publishOnDataTopic(
topic,
reinterpret_cast<const uint8_t*>(payload),
strlen_P(AHAFROMFSTR(payload)),
retained,
true
);
}
bool HABaseDeviceType::publishOnDataTopic(
const __FlashStringHelper* topic,
const char* payload,
bool retained
)
{
if (!payload) {
return false;
}
return publishOnDataTopic(
topic,
reinterpret_cast<const uint8_t*>(payload),
strlen(payload),
retained
);
}
bool HABaseDeviceType::publishOnDataTopic(
const __FlashStringHelper* topic,
const uint8_t* payload,
const uint16_t length,
bool retained,
bool isProgmemData
)
{
HAMqtt* mqttInstance = mqtt();
if (!payload || !mqttInstance) {
return false;
}
if (!topic) {
return false;
}
const uint16_t topicLength = HASerializer::calculateDataTopicLength(
uniqueId(),
topic
);
if (topicLength == 0) {
return false;
}
char fullTopic[topicLength];
if (!HASerializer::generateDataTopic(
fullTopic,
uniqueId(),
topic
)) {
return false;
}
if (mqttInstance->beginPublish(fullTopic, length, retained)) {
bool written = false;
if (isProgmemData) {
written = mqttInstance->writePayload(AHATOFSTR(payload));
} else {
written = mqttInstance->writePayload(payload, length);
}
const bool ended = mqttInstance->endPublish();
return written && ended;
}
return false;
}
bool HABaseDeviceType::shouldPublishSingleComponentConfig() const
{
return !mqtt() || !mqtt()->isDeviceDiscoveryEnabled() || !supportsDeviceDiscovery();
}
void HABaseDeviceType::setEntityIdProperty(HASerializer* serializer) const
{
if (!serializer) {
return;
}
const char* defaultEntityId = nonEmptyString(_defaultEntityId);
if (defaultEntityId) {
serializer->set(AHATOFSTR(HADefaultEntityIdProperty), defaultEntityId);
}
}
const char* HABaseDeviceType::nonEmptyString(const char* value)
{
return (value && value[0] != '\0') ? value : nullptr;
}
HASerializer* HABaseDeviceType::buildDeviceDiscoverySerializer()
{
return nullptr;
}
bool HABaseDeviceType::supportsDeviceDiscovery() const
{
return false;
}
void HABaseDeviceType::setEnabledByDefault(bool enabled)
{
_enabledByDefault = enabled;
_hasEnabledByDefault = true;
}
void HABaseDeviceType::clearEnabledByDefault()
{
_hasEnabledByDefault = false;
}
void HABaseDeviceType::setEntityPicture(const char* url)
{
_entityPicture = url;
}
void HABaseDeviceType::clearEntityPicture()
{
_entityPicture = nullptr;
}
void HABaseDeviceType::setQos(uint8_t qos)
{
if (qos > 2) {
qos = 2;
}
_qosNumeric = HANumeric(static_cast<uint8_t>(qos), 0);
_hasQos = true;
}
void HABaseDeviceType::clearQos()
{
_hasQos = false;
_qosNumeric.reset();
}
void HABaseDeviceType::setEncoding(const char* encoding)
{
_encoding = encoding;
}
void HABaseDeviceType::clearEncoding()
{
_encoding = nullptr;
}
void HABaseDeviceType::setPayloadAvailable(const char* payload)
{
_payloadAvailable = payload;
}
void HABaseDeviceType::setPayloadNotAvailable(const char* payload)
{
_payloadNotAvailable = payload;
}
void HABaseDeviceType::setAvailabilityMode(const char* mode)
{
_availabilityMode = mode;
}
bool HABaseDeviceType::addAvailabilityEntry(
const char* topic,
const char* valueTemplate,
const char* payloadAvailable,
const char* payloadNotAvailable
)
{
return _availabilityList.add(
topic,
valueTemplate,
payloadAvailable,
payloadNotAvailable
);
}
void HABaseDeviceType::clearAvailabilityEntries()
{
_availabilityList.clear();
}
void HABaseDeviceType::applyCommonEntityProperties(
HASerializer* serializer,
bool includeEncoding
) const
{
if (!serializer) {
return;
}
if (_hasEnabledByDefault) {
serializer->set(
AHATOFSTR(HAEnabledByDefaultProperty),
&_enabledByDefault,
HASerializer::BoolPropertyType
);
}
if (nonEmptyString(_entityPicture)) {
serializer->set(AHATOFSTR(HAEntityPictureProperty), _entityPicture);
}
if (_hasQos) {
serializer->set(
AHATOFSTR(HAQosProperty),
&_qosNumeric,
HASerializer::NumberPropertyType
);
}
if (includeEncoding && nonEmptyString(_encoding)) {
serializer->set(AHATOFSTR(HAEncodingProperty), _encoding);
}
}
const char* HABaseDeviceType::effectivePayloadAvailable() const
{
if (_payloadAvailable && _payloadAvailable[0] != '\0') {
return _payloadAvailable;
}
HAMqtt* m = mqtt();
if (!m) {
return nullptr;
}
const HADevice* d = m->getDevice();
if (d && d->isSharedAvailabilityEnabled()) {
return d->getPayloadAvailable();
}
return nullptr;
}
const char* HABaseDeviceType::effectivePayloadNotAvailable() const
{
if (_payloadNotAvailable && _payloadNotAvailable[0] != '\0') {
return _payloadNotAvailable;
}
HAMqtt* m = mqtt();
if (!m) {
return nullptr;
}
const HADevice* d = m->getDevice();
if (d && d->isSharedAvailabilityEnabled()) {
return d->getPayloadNotAvailable();
}
return nullptr;
}
void HABaseDeviceType::configureAvailabilityEntries(HASerializer* serializer) const
{
if (!serializer || !mqtt()) {
return;
}
const HADevice* device = mqtt()->getDevice();
if (!device) {
return;
}
const bool isSharedAvailability = device->isSharedAvailabilityEnabled();
const bool availabilityActive = isAvailabilityConfigured();
if (!isSharedAvailability && !availabilityActive) {
return;
}
const char* pa = effectivePayloadAvailable();
if (nonEmptyString(pa)) {
serializer->set(
AHATOFSTR(HAPayloadAvailableProperty),
pa,
HASerializer::ConstCharPropertyValue
);
}
const char* pn = effectivePayloadNotAvailable();
if (nonEmptyString(pn)) {
serializer->set(
AHATOFSTR(HAPayloadNotAvailableProperty),
pn,
HASerializer::ConstCharPropertyValue
);
}
if (nonEmptyString(_availabilityMode)) {
serializer->set(
AHATOFSTR(HAAvailabilityModeProperty),
_availabilityMode,
HASerializer::ConstCharPropertyValue
);
}
const bool useList =
!isSharedAvailability
&& availabilityActive
&& _availabilityList.count() > 0;
if (useList) {
auto* entry = serializer->addEntry();
if (!entry) {
return;
}
entry->type = HASerializer::AvailabilityArrayEntryType;
entry->subtype = 0;
entry->property = AHATOFSTR(HAAvailabilityListProperty);
entry->value = const_cast<HAAvailabilityConfig*>(&_availabilityList);
return;
}
auto* e = serializer->addEntry();
if (!e) {
return;
}
e->type = HASerializer::TopicEntryType;
e->subtype = 0;
e->property = AHATOFSTR(HAAvailabilityTopic);
e->value = isSharedAvailability
? const_cast<char*>(device->getAvailabilityTopic())
: nullptr;
}
+423
View File
@@ -0,0 +1,423 @@
#ifndef AHA_HABASEDEVICETYPE_H
#define AHA_HABASEDEVICETYPE_H
#include <Arduino.h>
#include "../ArduinoHADefines.h"
#include "../utils/HAAvailabilityConfig.h"
#include "../utils/HANumeric.h"
class HAMqtt;
class HASerializer;
class HABaseDeviceType
{
public:
enum NumberPrecision {
/// No digits after the decimal point.
PrecisionP0 = 0,
/// One digit after the decimal point.
PrecisionP1,
/// Two digits after the decimal point.
PrecisionP2,
/// Three digits after the decimal point.
PrecisionP3
};
/**
* Creates a new device type instance and registers it in the HAMqtt class.
*
* @param componentName The name of the Home Assistant component (e.g. `binary_sensor`).
* You can find all available component names in the Home Assistant documentation.
* The component name needs to be stored in the flash memory.
* @param uniqueId The unique ID of the device type. It needs to be unique in a scope of the HADevice.
*/
HABaseDeviceType(
const __FlashStringHelper* componentName,
const char* uniqueId
);
virtual ~HABaseDeviceType();
HABaseDeviceType(const HABaseDeviceType&) = delete;
HABaseDeviceType& operator=(const HABaseDeviceType&) = delete;
HABaseDeviceType(HABaseDeviceType&&) = delete;
HABaseDeviceType& operator=(HABaseDeviceType&&) = delete;
/**
* Returns unique ID of the device type.
*/
inline const char* uniqueId() const
{ return _uniqueId; }
/**
* Returns component name defined by the device type.
* It's used for the MQTT discovery topic.
*/
inline const __FlashStringHelper* componentName() const
{ return _componentName; }
/**
* Returns `true` if the availability was configured for this device type.
*/
inline bool isAvailabilityConfigured() const
{ return (_availability != AvailabilityDefault); }
/**
* Returns online state of the device type.
*/
inline bool isOnline() const
{ return (_availability == AvailabilityOnline); }
/**
* Sets name of the device type that will be used as a label in the HA panel.
* Keep the name short to save the resources.
*
* @param name The device type name.
*/
inline void setName(const char* name)
{ _name = name; }
/**
* Returns name of the deviced type that was assigned via setName method.
* It can be nullptr if there is no name assigned.
*/
inline const char* getName() const
{ return _name; }
/**
* Sets the default entity ID that Home Assistant should use when creating
* the entity for the first time.
* Keep the ID short to save the resources.
*
* @param entityId The default entity ID.
*/
inline void setDefaultEntityId(const char* entityId)
{ _defaultEntityId = entityId; }
/**
* Returns the default entity ID that was assigned via setDefaultEntityId.
* It can be nullptr if there is no ID assigned.
*/
inline const char* getDefaultEntityId() const
{ return _defaultEntityId; }
/**
* Legacy compatibility setter. Home Assistant no longer supports the MQTT
* discovery `obj_id` payload property, so this value is retained only for
* source compatibility and is not published.
*
* Use setDefaultEntityId("domain.entity_id") to suggest an entity ID on
* first discovery. It does not rename existing entities.
*
* @param objectId The object ID.
*/
inline void setObjectId(const char* objectId)
{ _objectId = objectId; }
/**
* Returns the object ID that was set by setObjectId method.
* It can be nullptr if there is no ID assigned.
*/
inline const char* getObjectId() const
{ return _objectId; }
/**
* Sets the entity category for this entity.
*
* @param entityCategory The category name.
*/
inline void setEntityCategory(const char* entityCategory)
{ _entityCategory = entityCategory; }
/**
* Returns the entity category for this entity.
*/
inline const char* getEntityCategory() const
{ return _entityCategory; }
void setEnabledByDefault(bool enabled);
void clearEnabledByDefault();
void setEntityPicture(const char* url);
void clearEntityPicture();
void setQos(uint8_t qos);
void clearQos();
void setEncoding(const char* encoding);
void clearEncoding();
void setPayloadAvailable(const char* payload);
void setPayloadNotAvailable(const char* payload);
void setAvailabilityMode(const char* mode);
/**
* Adds a full-topic availability entry for discovery (`avty` list) and publishing.
* Only used when this entity does not use shared device availability.
*/
bool addAvailabilityEntry(
const char* topic,
const char* valueTemplate = nullptr,
const char* payloadAvailable = nullptr,
const char* payloadNotAvailable = nullptr
);
void clearAvailabilityEntries();
/**
* Sets availability of the device type.
* Setting the initial availability enables availability reporting for this device type.
* Please note that not all device types support this feature.
* Follow HA documentation of a specific device type to get more information.
*
* @param online Specifies whether the device type is online.
*/
virtual void setAvailability(bool online);
/**
* Removes this entity from MQTT discovery by publishing an empty retained
* payload on its config topic in single-component mode. In device
* discovery mode, publishes Home Assistant's required component-removal
* marker and updates the retained device config.
*/
bool removeFromDiscovery();
/**
* Returns true after this entity was removed from the retained device
* discovery payload and before it is republished.
*/
inline bool isRemovedFromDeviceDiscovery() const
{ return _deviceDiscoveryRemoved; }
/**
* Republishes MQTT discovery config for this entity.
* In device discovery mode, this also re-adds an entity previously removed
* from the retained device payload.
*/
bool republishDiscovery();
#ifdef ARDUINOHA_TEST
inline HASerializer* getSerializer() const
{ return _serializer; }
inline void buildSerializerTest()
{ buildSerializer(); }
#endif
protected:
/**
* Returns instance of the HAMqtt class.
*/
static HAMqtt* mqtt();
/**
* Subscribes to the given data topic.
*
* @param uniqueId THe unique ID of the device type assigned via the constructor.
* @param topic Topic to subscribe (progmem string).
*/
static void subscribeTopic(
const char* uniqueId,
const __FlashStringHelper* topic
);
/**
* Returns true if this entity should publish the single-component
* discovery config on connect.
*/
bool shouldPublishSingleComponentConfig() const;
/**
* This method should build serializer that will be used for publishing the configuration.
* The serializer is built each time the MQTT connection is acquired.
* Follow implementation of the existing device types to get better understanding of the logic.
*/
virtual void buildSerializer() { };
/**
* Writes shared MQTT discovery fields (enabled_by_default, entity_picture, qos, encoding).
*/
void applyCommonEntityProperties(
HASerializer* serializer,
bool includeEncoding = true
) const;
/**
* Populates availability-related discovery entries. Called from HASerializer::WithAvailability.
*/
void configureAvailabilityEntries(HASerializer* serializer) const;
/**
* This method is called each time the MQTT connection is acquired.
* Each device type should publish its configuration and availability.
* It can be also used for subscribing to MQTT topics.
*/
virtual void onMqttConnected() = 0;
/**
* This method is called each time the device receives a MQTT message.
* It can be any MQTT message so the method should always verify the topic.
*
* @param topic The topic on which the message was produced.
* @param payload The payload of the message. It can be nullptr.
* @param length The length of the payload.
*/
virtual void onMqttMessage(
const char* topic,
const uint8_t* payload,
const uint16_t length
);
/**
* Destroys the existing serializer.
*/
void destroySerializer();
/**
* Publishes configuration of this device type on the HA discovery topic.
*/
bool publishConfig();
/**
* Publishes current availability of the device type.
* The message is only produced if the availability is configured for this device type.
*/
void publishAvailability();
/**
* Publishes the given flash string on the data topic.
*
* @param topic The topic to publish on (progmem string).
* @param payload The message's payload (progmem string).
* @param retained Specifies whether the message should be retained.
*/
bool publishOnDataTopic(
const __FlashStringHelper* topic,
const __FlashStringHelper* payload,
bool retained = false
);
/**
* Publishes the given string on the data topic.
*
* @param topic The topic to publish on (progmem string).
* @param payload The message's payload.
* @param retained Specifies whether the message should be retained.
*/
bool publishOnDataTopic(
const __FlashStringHelper* topic,
const char* payload,
bool retained = false
);
/**
* Publishes the given data on the data topic.
*
* @param topic The topic to publish on (progmem string).
* @param payload The message's payload.
* @param length The length of the payload.
* @param retained Specifies whether the message should be retained.
* @param isProgmemData Specifies whether the given data is stored in the flash memory.
*/
bool publishOnDataTopic(
const __FlashStringHelper* topic,
const uint8_t* payload,
const uint16_t length,
bool retained = false,
bool isProgmemData = false
);
/**
* Publishes a RAM payload on an already fully-qualified MQTT topic.
*/
bool publishAbsolute(const char* fullTopic, const char* payload, bool retained = false);
/**
* Adds the preferred entity ID property to the serializer.
* Only `default_entity_id` is emitted. The legacy `obj_id` field is not
* supported by current Home Assistant MQTT discovery schemas.
*/
void setEntityIdProperty(HASerializer* serializer) const;
/**
* Returns a string pointer if it is non-empty, otherwise nullptr.
*/
static const char* nonEmptyString(const char* value);
/**
* Builds a serializer used as a device discovery component payload.
* Unsupported entities return nullptr.
*/
virtual HASerializer* buildDeviceDiscoverySerializer();
/**
* Returns true when the entity can be included in MQTT device discovery.
*/
virtual bool supportsDeviceDiscovery() const;
/// The component name that was assigned via the constructor.
const __FlashStringHelper* const _componentName;
/// The unique ID that was assigned via the constructor.
const char* _uniqueId;
/// The name that was set using setName method. It can be nullptr.
const char* _name;
/// The object ID that was set using setObjectId method. It can be nullptr.
const char* _objectId;
/// The default entity ID used by Home Assistant on first discovery.
const char* _defaultEntityId;
/// The entity category for the entity. It can be nullptr.
const char* _entityCategory;
/// HASerializer that belongs to this device type. It can be nullptr.
HASerializer* _serializer;
bool _hasEnabledByDefault;
bool _enabledByDefault;
const char* _entityPicture;
bool _hasQos;
HANumeric _qosNumeric;
const char* _encoding;
const char* _payloadAvailable;
const char* _payloadNotAvailable;
const char* _availabilityMode;
HAAvailabilityConfig _availabilityList;
/// Tracks an entity removed from the retained device discovery payload.
bool _deviceDiscoveryRemoved;
static void registerAllWith(HAMqtt& mqtt);
static HABaseDeviceType* _firstInstance;
private:
enum Availability {
AvailabilityDefault = 0,
AvailabilityOnline,
AvailabilityOffline
};
/// The current availability of this device type. AvailabilityDefault means that the initial availability was never set.
Availability _availability;
const char* effectivePayloadAvailable() const;
/// Intrusive list entry used to register entities created before HAMqtt.
HABaseDeviceType* _nextInstance;
const char* effectivePayloadNotAvailable() const;
bool removeSingleComponentDiscovery();
friend class HAMqtt;
friend class HASerializer;
};
#endif
+196 -233
View File
@@ -1,261 +1,224 @@
#include "HABinarySensor.h"
#include "../ArduinoHADefines.h"
#include "../HAMqtt.h"
#include "../HADevice.h"
#include "../HAUtils.h"
#ifndef EX_ARDUINOHA_BINARY_SENSOR
HABinarySensor::HABinarySensor(
const char* name,
bool initialState,
HAMqtt& mqtt
) :
BaseDeviceType(mqtt, "binary_sensor", name),
#include "../HAMqtt.h"
#include "../utils/HADictionary.h"
#include "../utils/HASerializer.h"
HABinarySensor::HABinarySensor(const char* uniqueId) :
HABaseDeviceType(AHATOFSTR(HAComponentBinarySensor), uniqueId),
_class(nullptr),
_currentState(initialState)
_icon(nullptr),
_payloadOn(nullptr),
_payloadOff(nullptr),
_forceUpdate(false),
_offDelay(),
_valueTemplate(nullptr),
_currentState(false)
{
}
HABinarySensor::HABinarySensor(
const char* name,
const char* deviceClass,
bool initialState,
HAMqtt& mqtt
) :
BaseDeviceType(mqtt, "binary_sensor", name),
_class(deviceClass),
_currentState(initialState)
bool HABinarySensor::setState(const bool state, const bool force)
{
if (!force && state == _currentState) {
return true;
}
const bool published = publishState(state);
_currentState = state;
return published;
}
void HABinarySensor::setExpireAfter(uint16_t expireAfter)
{
if (expireAfter > 0) {
_expireAfter.setBaseValue(expireAfter);
} else {
_expireAfter.reset();
}
}
void HABinarySensor::setOffDelay(uint16_t seconds)
{
if (seconds > 0) {
_offDelay.setBaseValue(seconds);
} else {
_offDelay.reset();
}
}
void HABinarySensor::clearOffDelay()
{
_offDelay.reset();
}
void HABinarySensor::setValueTemplate(const char* valueTemplate)
{
_valueTemplate = valueTemplate;
}
void HABinarySensor::buildSerializer()
{
if (_serializer || !uniqueId()) {
return;
}
_serializer = new HASerializer(this, 20);
_serializer->set(AHATOFSTR(HANameProperty), _name);
setEntityIdProperty(_serializer);
_serializer->set(HASerializer::WithUniqueId);
applyCommonEntityProperties(_serializer);
_serializer->set(AHATOFSTR(HADeviceClassProperty), _class);
_serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
_serializer->set(AHATOFSTR(HAIconProperty), _icon);
if (nonEmptyString(_payloadOn)) {
_serializer->set(AHATOFSTR(HAPayloadOnProperty), _payloadOn);
}
if (nonEmptyString(_payloadOff)) {
_serializer->set(AHATOFSTR(HAPayloadOffProperty), _payloadOff);
}
if (_forceUpdate) {
_serializer->set(
AHATOFSTR(HAForceUpdateProperty),
&_forceUpdate,
HASerializer::BoolPropertyType
);
}
if (_offDelay.isSet()) {
_serializer->set(
AHATOFSTR(HAOffDelayProperty),
&_offDelay,
HASerializer::NumberPropertyType
);
}
if (nonEmptyString(_valueTemplate)) {
_serializer->set(AHATOFSTR(HAValueTemplateProperty), _valueTemplate);
}
if (_expireAfter.isSet()) {
_serializer->set(
AHATOFSTR(HAExpireAfterProperty),
&_expireAfter,
HASerializer::NumberPropertyType
);
}
_serializer->set(HASerializer::WithDevice);
_serializer->set(HASerializer::WithAvailability);
_serializer->topic(AHATOFSTR(HAStateTopic));
}
HASerializer* HABinarySensor::buildDeviceDiscoverySerializer()
{
if (!uniqueId()) {
return nullptr;
}
HASerializer* serializer = new HASerializer(this, 20);
serializer->set(
AHATOFSTR(HAPlatformProperty),
AHATOFSTR(HAComponentBinarySensor),
HASerializer::ProgmemPropertyValue
);
serializer->set(AHATOFSTR(HANameProperty), _name);
setEntityIdProperty(serializer);
serializer->set(HASerializer::WithUniqueId);
applyCommonEntityProperties(serializer);
serializer->set(AHATOFSTR(HADeviceClassProperty), _class);
serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
serializer->set(AHATOFSTR(HAIconProperty), _icon);
if (nonEmptyString(_payloadOn)) {
serializer->set(AHATOFSTR(HAPayloadOnProperty), _payloadOn);
}
if (nonEmptyString(_payloadOff)) {
serializer->set(AHATOFSTR(HAPayloadOffProperty), _payloadOff);
}
if (_forceUpdate) {
serializer->set(
AHATOFSTR(HAForceUpdateProperty),
&_forceUpdate,
HASerializer::BoolPropertyType
);
}
if (_offDelay.isSet()) {
serializer->set(
AHATOFSTR(HAOffDelayProperty),
&_offDelay,
HASerializer::NumberPropertyType
);
}
if (nonEmptyString(_valueTemplate)) {
serializer->set(AHATOFSTR(HAValueTemplateProperty), _valueTemplate);
}
if (_expireAfter.isSet()) {
serializer->set(
AHATOFSTR(HAExpireAfterProperty),
&_expireAfter,
HASerializer::NumberPropertyType
);
}
serializer->set(HASerializer::WithAvailability);
serializer->topic(AHATOFSTR(HAStateTopic));
return serializer;
}
void HABinarySensor::onMqttConnected()
{
if (strlen(name()) == 0) {
if (!uniqueId()) {
return;
}
publishConfig();
publishState(_currentState);
if (shouldPublishSingleComponentConfig()) {
publishConfig();
}
publishAvailability();
publishState(_currentState);
}
bool HABinarySensor::setState(bool state)
bool HABinarySensor::publishState(const bool state)
{
if (state == _currentState) {
return true;
if (state) {
if (nonEmptyString(_payloadOn)) {
return publishOnDataTopic(
AHATOFSTR(HAStateTopic),
_payloadOn,
true
);
}
return publishOnDataTopic(
AHATOFSTR(HAStateTopic),
AHATOFSTR(HAStateOn),
true
);
}
if (strlen(name()) == 0) {
return false;
if (nonEmptyString(_payloadOff)) {
return publishOnDataTopic(
AHATOFSTR(HAStateTopic),
_payloadOff,
true
);
}
if (publishState(state)) {
_currentState = state;
return true;
}
return false;
}
void HABinarySensor::publishConfig()
{
const HADevice* device = mqtt()->getDevice();
if (device == nullptr) {
return;
}
const uint16_t& deviceLength = device->calculateSerializedLength();
if (deviceLength == 0) {
return;
}
char serializedDevice[deviceLength];
if (device->serialize(serializedDevice) == 0) {
return;
}
const uint16_t& topicLength = DeviceTypeSerializer::calculateTopicLength(
mqtt(),
componentName(),
name(),
DeviceTypeSerializer::ConfigTopic
);
const uint16_t& dataLength = calculateSerializedLength(serializedDevice);
if (topicLength == 0 || dataLength == 0) {
return;
}
char topic[topicLength];
DeviceTypeSerializer::generateTopic(
mqtt(),
topic,
componentName(),
name(),
DeviceTypeSerializer::ConfigTopic
);
if (strlen(topic) == 0) {
return;
}
if (mqtt()->beginPublish(topic, dataLength, true)) {
writeSerializedData(serializedDevice);
mqtt()->endPublish();
}
}
bool HABinarySensor::publishState(bool state)
{
if (strlen(name()) == 0) {
return false;
}
const uint16_t& topicSize = DeviceTypeSerializer::calculateTopicLength(
mqtt(),
componentName(),
name(),
DeviceTypeSerializer::StateTopic
);
if (topicSize == 0) {
return false;
}
char topic[topicSize];
DeviceTypeSerializer::generateTopic(
mqtt(),
topic,
componentName(),
name(),
DeviceTypeSerializer::StateTopic
);
if (strlen(topic) == 0) {
return false;
}
return mqtt()->publish(
topic,
(
state ?
DeviceTypeSerializer::StateOn :
DeviceTypeSerializer::StateOff
),
return publishOnDataTopic(
AHATOFSTR(HAStateTopic),
AHATOFSTR(HAStateOff),
true
);
}
uint16_t HABinarySensor::calculateSerializedLength(
const char* serializedDevice
) const
{
if (serializedDevice == nullptr) {
return 0;
}
const HADevice* device = mqtt()->getDevice();
if (device == nullptr) {
return 0;
}
uint16_t size = 0;
size += DeviceTypeSerializer::calculateBaseJsonDataSize();
size += DeviceTypeSerializer::calculateNameFieldSize(name());
size += DeviceTypeSerializer::calculateUniqueIdFieldSize(device, name());
size += DeviceTypeSerializer::calculateDeviceFieldSize(serializedDevice);
if (isAvailabilityConfigured()) {
size += DeviceTypeSerializer::calculateAvailabilityFieldSize(
mqtt(),
componentName(),
name()
);
}
// state topic
{
const uint16_t& topicLength = DeviceTypeSerializer::calculateTopicLength(
mqtt(),
componentName(),
name(),
DeviceTypeSerializer::StateTopic,
false
);
if (topicLength == 0) {
return 0;
}
// Field format: "stat_t":"[TOPIC]"
size += topicLength + 11; // 11 - length of the JSON decorators for this field
}
// device class
if (_class != nullptr) {
// Field format: ,"dev_cla":"[CLASS]"
size += strlen(_class) + 13; // 13 - length of the JSON decorators for this field
}
return size; // exludes null terminator
}
bool HABinarySensor::writeSerializedData(const char* serializedDevice) const
{
if (serializedDevice == nullptr) {
return false;
}
DeviceTypeSerializer::mqttWriteBeginningJson(mqtt());
// state topic
{
const uint16_t& topicSize = DeviceTypeSerializer::calculateTopicLength(
mqtt(),
componentName(),
name(),
DeviceTypeSerializer::StateTopic
);
if (topicSize == 0) {
return false;
}
char topic[topicSize];
DeviceTypeSerializer::generateTopic(
mqtt(),
topic,
componentName(),
name(),
DeviceTypeSerializer::StateTopic
);
if (strlen(topic) == 0) {
return false;
}
static const char Prefix[] PROGMEM = {"\"stat_t\":\""};
DeviceTypeSerializer::mqttWriteConstCharField(mqtt(), Prefix, topic);
}
// device class
if (_class != nullptr) {
static const char Prefix[] PROGMEM = {",\"dev_cla\":\""};
DeviceTypeSerializer::mqttWriteConstCharField(mqtt(), Prefix, _class);
}
DeviceTypeSerializer::mqttWriteNameField(mqtt(), name());
DeviceTypeSerializer::mqttWriteUniqueIdField(mqtt(), name());
if (isAvailabilityConfigured()) {
DeviceTypeSerializer::mqttWriteAvailabilityField(
mqtt(),
componentName(),
name()
);
}
DeviceTypeSerializer::mqttWriteDeviceField(mqtt(), serializedDevice);
DeviceTypeSerializer::mqttWriteEndJson(mqtt());
return true;
}
#endif
+97 -41
View File
@@ -1,70 +1,126 @@
#ifndef AHA_HABINARYSENSOR_H
#define AHA_HABINARYSENSOR_H
#include "BaseDeviceType.h"
#include "HABaseDeviceType.h"
#include "../utils/HANumeric.h"
class HABinarySensor : public BaseDeviceType
#ifndef EX_ARDUINOHA_BINARY_SENSOR
/**
* HABinarySensor represents a binary sensor that allows publishing on/off state to the Home Assistant panel.
*
* @note
* You can find more information about this entity in the Home Assistant documentation:
* https://www.home-assistant.io/integrations/binary_sensor.mqtt/
*/
class HABinarySensor : public HABaseDeviceType
{
public:
/**
* Initializes binary sensor.
* @param uniqueId The unique ID of the button. It needs to be unique in a scope of your device.
*/
HABinarySensor(const char* uniqueId);
/**
* Changes state of the sensor and publish MQTT message.
* Please note that if a new value is the same as the previous one the MQTT message won't be published.
*
* @param name Name of the sensor. Recommendes characters: [a-z0-9\-_]
* @param initialState Initial state of the sensor.
It will be published right after "config" message in order to update HA state.
* @param state New state of the sensor (`true` - on, `false` - off).
* @param force Forces to update the state without comparing it to a previous known state.
* @returns Returns `true` if the MQTT message has been published successfully.
*/
HABinarySensor(
const char* name,
bool initialState,
HAMqtt& mqtt
);
bool setState(const bool state, const bool force = false);
/**
* Initializes binary sensor with the specified class.
* You can find list of available values here: https://www.home-assistant.io/integrations/binary_sensor/#device-class
* Sets the number of seconds after the sensor’s state expires, if it’s not updated.
* By default the sensors state never expires.
*
* @param name Name of the sensor. Recommendes characters: [a-z0-9\-_]
* @param deviceClass Name of the class (lower case).
* @param initialState Initial state of the sensor.
It will be published right after "config" message in order to update HA state.
* @param expireAfter The number of seconds.
*/
HABinarySensor(
const char* name,
const char* deviceClass,
bool initialState,
HAMqtt& mqtt
);
void setExpireAfter(uint16_t expireAfter);
/**
* Publishes configuration of the sensor to the MQTT.
*/
virtual void onMqttConnected() override;
/**
* Changes state of the sensor and publishes MQTT message.
* Please note that if a new value is the same as previous one,
* the MQTT message won't be published.
* Sets the current state of the sensor without publishing it to Home Assistant.
* This method may be useful if you want to change the state before the connection with the MQTT broker is acquired.
*
* @param state New state of the sensor.
* @returns Returns true if MQTT message has been published successfully.
*/
bool setState(bool state);
inline void setCurrentState(const bool state)
{ _currentState = state; }
/**
* Returns last known state of the sensor.
* If setState method wasn't called the initial value will be returned.
* Returns the last known state of the sensor.
*/
inline bool getState() const
inline bool getCurrentState() const
{ return _currentState; }
private:
void publishConfig();
bool publishState(bool state);
uint16_t calculateSerializedLength(const char* serializedDevice) const;
bool writeSerializedData(const char* serializedDevice) const;
/**
* Sets class of the device.
* You can find list of available values here: https://www.home-assistant.io/integrations/binary_sensor/#device-class
*
* @param deviceClass The class name.
*/
inline void setDeviceClass(const char* deviceClass)
{ _class = deviceClass; }
/**
* Sets icon of the sensor.
* Any icon from MaterialDesignIcons.com (for example: `mdi:home`).
*
* @param icon The icon name.
*/
inline void setIcon(const char* icon)
{ _icon = icon; }
inline void setPayloadOn(const char* payload)
{ _payloadOn = payload; }
inline void setPayloadOff(const char* payload)
{ _payloadOff = payload; }
inline void setForceUpdate(bool forceUpdate)
{ _forceUpdate = forceUpdate; }
void setOffDelay(uint16_t seconds);
void clearOffDelay();
void setValueTemplate(const char* valueTemplate);
protected:
virtual void buildSerializer() override;
virtual HASerializer* buildDeviceDiscoverySerializer() override;
virtual bool supportsDeviceDiscovery() const override
{ return true; }
virtual void onMqttConnected() override;
private:
/**
* Publishes the MQTT message with the given state.
*
* @param state The state to publish.
* @returns Returns `true` if the MQTT message has been published successfully.
*/
bool publishState(bool state);
/// The device class. It can be nullptr.
const char* _class;
/// The icon of the sensor. It can be nullptr.
const char* _icon;
/// It defines the number of seconds after the sensor’s state expires, if it’s not updated. By default the sensors state never expires.
HANumeric _expireAfter;
const char* _payloadOn;
const char* _payloadOff;
bool _forceUpdate;
HANumeric _offDelay;
const char* _valueTemplate;
/// Current state of the sensor. By default it's false.
bool _currentState;
};
#endif
#endif
+164
View File
@@ -0,0 +1,164 @@
#include "HAButton.h"
#ifndef EX_ARDUINOHA_BUTTON
#include "../HAMqtt.h"
#include "../utils/HADictionary.h"
#include "../utils/HASerializer.h"
#include <string.h>
HAButton::HAButton(const char* uniqueId) :
HABaseDeviceType(AHATOFSTR(HAComponentButton), uniqueId),
_class(nullptr),
_icon(nullptr),
_retain(false),
_payloadPress(nullptr),
_commandTemplate(nullptr),
_commandCallback(nullptr)
{
}
void HAButton::setPayloadPress(const char* payload)
{
_payloadPress = payload;
}
void HAButton::setCommandTemplate(const char* commandTemplate)
{
_commandTemplate = commandTemplate;
}
void HAButton::buildSerializer()
{
if (_serializer || !uniqueId()) {
return;
}
_serializer = new HASerializer(this, 18);
_serializer->set(AHATOFSTR(HANameProperty), _name);
setEntityIdProperty(_serializer);
_serializer->set(HASerializer::WithUniqueId);
applyCommonEntityProperties(_serializer);
_serializer->set(AHATOFSTR(HADeviceClassProperty), _class);
_serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
_serializer->set(AHATOFSTR(HAIconProperty), _icon);
if (nonEmptyString(_payloadPress)) {
_serializer->set(AHATOFSTR(HAPayloadPressProperty), _payloadPress);
}
if (nonEmptyString(_commandTemplate)) {
_serializer->set(AHATOFSTR(HACommandTemplateProperty), _commandTemplate);
}
// optional property
if (_retain) {
_serializer->set(
AHATOFSTR(HARetainProperty),
&_retain,
HASerializer::BoolPropertyType
);
}
_serializer->set(HASerializer::WithDevice);
_serializer->set(HASerializer::WithAvailability);
_serializer->topic(AHATOFSTR(HACommandTopic));
}
HASerializer* HAButton::buildDeviceDiscoverySerializer()
{
if (!uniqueId()) {
return nullptr;
}
HASerializer* serializer = new HASerializer(this, 18);
serializer->set(
AHATOFSTR(HAPlatformProperty),
AHATOFSTR(HAComponentButton),
HASerializer::ProgmemPropertyValue
);
serializer->set(AHATOFSTR(HANameProperty), _name);
setEntityIdProperty(serializer);
serializer->set(HASerializer::WithUniqueId);
applyCommonEntityProperties(serializer);
serializer->set(AHATOFSTR(HADeviceClassProperty), _class);
serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
serializer->set(AHATOFSTR(HAIconProperty), _icon);
if (nonEmptyString(_payloadPress)) {
serializer->set(AHATOFSTR(HAPayloadPressProperty), _payloadPress);
}
if (nonEmptyString(_commandTemplate)) {
serializer->set(AHATOFSTR(HACommandTemplateProperty), _commandTemplate);
}
if (_retain) {
serializer->set(
AHATOFSTR(HARetainProperty),
&_retain,
HASerializer::BoolPropertyType
);
}
serializer->set(HASerializer::WithAvailability);
serializer->topic(AHATOFSTR(HACommandTopic));
return serializer;
}
void HAButton::onMqttConnected()
{
if (!uniqueId()) {
return;
}
if (shouldPublishSingleComponentConfig()) {
publishConfig();
}
publishAvailability();
subscribeTopic(uniqueId(), AHATOFSTR(HACommandTopic));
}
void HAButton::onMqttMessage(
const char* topic,
const uint8_t* payload,
const uint16_t length
)
{
(void)payload;
(void)length;
const bool hasCommandCallback =
_commandCallback
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|| static_cast<bool>(_commandStdCallback)
#endif
;
if (hasCommandCallback && HASerializer::compareDataTopics(
topic,
uniqueId(),
AHATOFSTR(HACommandTopic)
)) {
if (
nonEmptyString(_payloadPress)
&& (
length != strlen(_payloadPress)
|| memcmp(payload, _payloadPress, length) != 0
)
) {
return;
}
if (_commandCallback) {
_commandCallback(this);
}
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
if (_commandStdCallback) {
_commandStdCallback(this);
}
#endif
}
}
#endif
+123
View File
@@ -0,0 +1,123 @@
#ifndef AHA_HABUTTON_H
#define AHA_HABUTTON_H
#include "HABaseDeviceType.h"
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
#include <functional>
#endif
#ifndef EX_ARDUINOHA_BUTTON
#define HABUTTON_CALLBACK(name) void (*name)(HAButton* sender)
/**
* HAButton represents a button that's displayed in the Home Assistant panel and
* triggers some logic on your Arduino/ESP device once clicked.
*
* @note
* You can find more information about this entity in the Home Assistant documentation:
* https://www.home-assistant.io/integrations/button.mqtt/
*/
class HAButton : public HABaseDeviceType
{
public:
/**
* @param uniqueId The unique ID of the button. It needs to be unique in a scope of your device.
*/
HAButton(const char* uniqueId);
/**
* Sets class of the device.
* You can find list of available values here: https://www.home-assistant.io/integrations/button/#device-class
*
* @param deviceClass The class name.
*/
inline void setDeviceClass(const char* deviceClass)
{ _class = deviceClass; }
/**
* Sets icon of the button.
* Any icon from MaterialDesignIcons.com (for example: `mdi:home`).
*
* @param icon The icon name.
*/
inline void setIcon(const char* icon)
{ _icon = icon; }
/**
* Sets retain flag for the button's command.
* If set to `true` the command produced by Home Assistant will be retained.
*
* @param retain
*/
inline void setRetain(const bool retain)
{ _retain = retain; }
void setPayloadPress(const char* payload);
void setCommandTemplate(const char* commandTemplate);
/**
* Registers callback that will be called each time the press command from HA is received.
* Please note that it's not possible to register multiple callbacks for the same button.
*
* @param callback
*/
inline void onCommand(HABUTTON_CALLBACK(callback))
{
_commandCallback = callback;
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
_commandStdCallback = nullptr;
#endif
}
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
/**
* Registers callback using std::function.
* It allows passing capturing lambdas and std::bind expressions.
*
* @param callback
*/
inline void onCommand(const std::function<void(HAButton*)>& callback)
{
_commandCallback = nullptr;
_commandStdCallback = callback;
}
#endif
protected:
virtual void buildSerializer() override;
virtual HASerializer* buildDeviceDiscoverySerializer() override;
virtual bool supportsDeviceDiscovery() const override
{ return true; }
virtual void onMqttConnected() override;
virtual void onMqttMessage(
const char* topic,
const uint8_t* payload,
const uint16_t length
) override;
private:
/// The device class. It can be nullptr.
const char* _class;
/// The icon of the button. It can be nullptr.
const char* _icon;
/// The retain flag for the HA commands.
bool _retain;
const char* _payloadPress;
const char* _commandTemplate;
/// The command callback that will be called once clicking the button in HA panel.
HABUTTON_CALLBACK(_commandCallback);
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
/// The std::function command callback.
std::function<void(HAButton*)> _commandStdCallback;
#endif
};
#endif
#endif
+98
View File
@@ -0,0 +1,98 @@
#include "HACamera.h"
#ifndef EX_ARDUINOHA_CAMERA
#include "../HAMqtt.h"
#include "../utils/HASerializer.h"
HACamera::HACamera(const char* uniqueId) :
HABaseDeviceType(AHATOFSTR(HAComponentCamera), uniqueId),
_encoding(EncodingBinary),
_icon(nullptr)
{
}
bool HACamera::publishImage(const uint8_t* data, const uint16_t length)
{
if (!data) {
return false;
}
return publishOnDataTopic(AHATOFSTR(HATopic), data, length, true);
}
void HACamera::buildSerializer()
{
if (_serializer || !uniqueId()) {
return;
}
_serializer = new HASerializer(this, 18);
_serializer->set(AHATOFSTR(HANameProperty), _name);
setEntityIdProperty(_serializer);
_serializer->set(HASerializer::WithUniqueId);
applyCommonEntityProperties(_serializer, false);
_serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
_serializer->set(AHATOFSTR(HAIconProperty), _icon);
_serializer->set(
AHATOFSTR(HAEncodingProperty),
getEncodingProperty(),
HASerializer::ProgmemPropertyValue
);
_serializer->set(HASerializer::WithDevice);
_serializer->set(HASerializer::WithAvailability);
_serializer->topic(AHATOFSTR(HATopic));
}
HASerializer* HACamera::buildDeviceDiscoverySerializer()
{
if (!uniqueId()) {
return nullptr;
}
HASerializer* serializer = new HASerializer(this, 18);
serializer->set(
AHATOFSTR(HAPlatformProperty),
AHATOFSTR(HAComponentCamera),
HASerializer::ProgmemPropertyValue
);
serializer->set(AHATOFSTR(HANameProperty), _name);
setEntityIdProperty(serializer);
serializer->set(HASerializer::WithUniqueId);
applyCommonEntityProperties(serializer, false);
serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
serializer->set(AHATOFSTR(HAIconProperty), _icon);
serializer->set(
AHATOFSTR(HAEncodingProperty),
getEncodingProperty(),
HASerializer::ProgmemPropertyValue
);
serializer->set(HASerializer::WithAvailability);
serializer->topic(AHATOFSTR(HATopic));
return serializer;
}
void HACamera::onMqttConnected()
{
if (!uniqueId()) {
return;
}
if (shouldPublishSingleComponentConfig()) {
publishConfig();
}
publishAvailability();
}
const __FlashStringHelper* HACamera::getEncodingProperty() const
{
switch (_encoding) {
case EncodingBase64:
return AHATOFSTR(HAEncodingBase64);
default:
return nullptr;
}
}
#endif
+80
View File
@@ -0,0 +1,80 @@
#ifndef AHA_HACAMERA_H
#define AHA_HACAMERA_H
#include "HABaseDeviceType.h"
#ifndef EX_ARDUINOHA_CAMERA
/**
* HACamera allows to display an image in the Home Assistant panel.
* It can be used for publishing an image from the ESP32-Cam module or any other
* module that's equipped with a camera.
*
* @note
* You can find more information about this entity in the Home Assistant documentation:
* https://www.home-assistant.io/integrations/camera.mqtt/
*/
class HACamera : public HABaseDeviceType
{
public:
enum ImageEncoding {
EncodingBinary = 1,
EncodingBase64
};
/**
* @param uniqueId The unique ID of the camera. It needs to be unique in a scope of your device.
*/
HACamera(const char* uniqueId);
/**
* Publishes MQTT message with the given image data as a message content.
* It updates image displayed in the Home Assistant panel.
*
* @param data Image data (raw binary data or base64)
* @param length The length of the data.
* @returns Returns `true` if MQTT message has been published successfully.
*/
bool publishImage(const uint8_t* data, const uint16_t length);
/**
* Sets encoding of the image content.
* Bu default Home Assistant expects raw binary data (e.g. JPEG binary data).
*
* @param encoding The image's data encoding.
*/
inline void setEncoding(const ImageEncoding encoding)
{ _encoding = encoding; }
/**
* Sets icon of the camera.
* Any icon from MaterialDesignIcons.com (for example: `mdi:home`).
*
* @param icon The icon name.
*/
inline void setIcon(const char* icon)
{ _icon = icon; }
protected:
virtual void buildSerializer() override;
virtual HASerializer* buildDeviceDiscoverySerializer() override;
virtual bool supportsDeviceDiscovery() const override
{ return true; }
virtual void onMqttConnected() override;
private:
/**
* Returns progmem string representing the encoding property.
*/
const __FlashStringHelper* getEncodingProperty() const;
/// The encoding of the image's data. By default it's `HACamera::EncodingBinary`.
ImageEncoding _encoding;
/// The icon of the camera. It can be nullptr.
const char* _icon;
};
#endif
#endif
+265
View File
@@ -0,0 +1,265 @@
#include "HACover.h"
#ifndef EX_ARDUINOHA_COVER
#include "../HAMqtt.h"
#include "../utils/HAUtils.h"
#include "../utils/HANumeric.h"
#include "../utils/HASerializer.h"
HACover::HACover(const char* uniqueId, const Features features) :
HABaseDeviceType(AHATOFSTR(HAComponentCover), uniqueId),
_features(features),
_currentState(StateUnknown),
_currentPosition(DefaultPosition),
_class(nullptr),
_icon(nullptr),
_retain(false),
_optimistic(false),
_commandCallback(nullptr)
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
, _commandStdCallback()
#endif
{
}
bool HACover::setState(const CoverState state, const bool force)
{
if (!force && _currentState == state) {
return true;
}
if (state == StateUnknown) {
return false;
}
const bool published = publishState(state);
_currentState = state;
return published;
}
bool HACover::setPosition(const int16_t position, const bool force)
{
if (!force && _currentPosition == position) {
return true;
}
if (position == DefaultPosition || !(_features & PositionFeature)) {
return false;
}
const bool published = publishPosition(position);
_currentPosition = position;
return published;
}
void HACover::buildSerializer()
{
if (_serializer || !uniqueId()) {
return;
}
_serializer = new HASerializer(this, 22);
_serializer->set(AHATOFSTR(HANameProperty), _name);
setEntityIdProperty(_serializer);
_serializer->set(HASerializer::WithUniqueId);
applyCommonEntityProperties(_serializer);
_serializer->set(AHATOFSTR(HADeviceClassProperty), _class);
_serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
_serializer->set(AHATOFSTR(HAIconProperty), _icon);
if (_retain) {
_serializer->set(
AHATOFSTR(HARetainProperty),
&_retain,
HASerializer::BoolPropertyType
);
}
if (_optimistic) {
_serializer->set(
AHATOFSTR(HAOptimisticProperty),
&_optimistic,
HASerializer::BoolPropertyType
);
}
_serializer->set(HASerializer::WithDevice);
_serializer->set(HASerializer::WithAvailability);
_serializer->topic(AHATOFSTR(HAStateTopic));
_serializer->topic(AHATOFSTR(HACommandTopic));
if (_features & PositionFeature) {
_serializer->topic(AHATOFSTR(HAPositionTopic));
}
}
HASerializer* HACover::buildDeviceDiscoverySerializer()
{
if (!uniqueId()) {
return nullptr;
}
HASerializer* serializer = new HASerializer(this, 22);
serializer->set(
AHATOFSTR(HAPlatformProperty),
AHATOFSTR(HAComponentCover),
HASerializer::ProgmemPropertyValue
);
serializer->set(AHATOFSTR(HANameProperty), _name);
setEntityIdProperty(serializer);
serializer->set(HASerializer::WithUniqueId);
applyCommonEntityProperties(serializer);
serializer->set(AHATOFSTR(HADeviceClassProperty), _class);
serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
serializer->set(AHATOFSTR(HAIconProperty), _icon);
if (_retain) {
serializer->set(
AHATOFSTR(HARetainProperty),
&_retain,
HASerializer::BoolPropertyType
);
}
if (_optimistic) {
serializer->set(
AHATOFSTR(HAOptimisticProperty),
&_optimistic,
HASerializer::BoolPropertyType
);
}
serializer->set(HASerializer::WithAvailability);
serializer->topic(AHATOFSTR(HAStateTopic));
serializer->topic(AHATOFSTR(HACommandTopic));
if (_features & PositionFeature) {
serializer->topic(AHATOFSTR(HAPositionTopic));
}
return serializer;
}
void HACover::onMqttConnected()
{
if (!uniqueId()) {
return;
}
if (shouldPublishSingleComponentConfig()) {
publishConfig();
}
publishAvailability();
if (!_retain) {
publishState(_currentState);
publishPosition(_currentPosition);
}
subscribeTopic(uniqueId(), AHATOFSTR(HACommandTopic));
}
void HACover::onMqttMessage(
const char* topic,
const uint8_t* payload,
const uint16_t length
)
{
if (HASerializer::compareDataTopics(
topic,
uniqueId(),
AHATOFSTR(HACommandTopic)
)) {
handleCommand(payload, length);
}
}
bool HACover::publishState(CoverState state)
{
if (state == StateUnknown) {
return false;
}
const __FlashStringHelper *stateStr = nullptr;
switch (state) {
case StateClosed:
stateStr = AHATOFSTR(HAClosedState);
break;
case StateClosing:
stateStr = AHATOFSTR(HAClosingState);
break;
case StateOpen:
stateStr = AHATOFSTR(HAOpenState);
break;
case StateOpening:
stateStr = AHATOFSTR(HAOpeningState);
break;
case StateStopped:
stateStr = AHATOFSTR(HAStoppedState);
break;
default:
return false;
}
return publishOnDataTopic(AHATOFSTR(HAStateTopic), stateStr, true);
}
bool HACover::publishPosition(int16_t position)
{
if (position == DefaultPosition || !(_features & PositionFeature)) {
return false;
}
char str[6 + 1] = {0}; // int16_t digits with null terminator
HANumeric(position, 0).toStr(str);
return publishOnDataTopic(AHATOFSTR(HAPositionTopic), str, true);
}
void HACover::handleCommand(const uint8_t* cmd, const uint16_t length)
{
const bool hasCommandCallback =
_commandCallback
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|| static_cast<bool>(_commandStdCallback)
#endif
;
if (!hasCommandCallback) {
return;
}
CoverCommand command;
bool handled = false;
if (memcmp_P(cmd, HACloseCommand, length) == 0) {
command = CommandClose;
handled = true;
} else if (memcmp_P(cmd, HAOpenCommand, length) == 0) {
command = CommandOpen;
handled = true;
} else if (memcmp_P(cmd, HAStopCommand, length) == 0) {
command = CommandStop;
handled = true;
}
if (!handled) {
return;
}
if (_commandCallback) {
_commandCallback(command, this);
}
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
if (_commandStdCallback) {
_commandStdCallback(command, this);
}
#endif
}
#endif
+241
View File
@@ -0,0 +1,241 @@
#ifndef AHA_HACOVER_H
#define AHA_HACOVER_H
#include "HABaseDeviceType.h"
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
#include <functional>
#endif
#ifndef EX_ARDUINOHA_COVER
#define HACOVER_CALLBACK(name) void (*name)(CoverCommand cmd, HACover* sender)
/**
* HACover allows to control a cover (such as blinds, a roller shutter or a garage door).
*
* @note
* You can find more information about this entity in the Home Assistant documentation:
* https://www.home-assistant.io/integrations/cover.mqtt/
*/
class HACover : public HABaseDeviceType
{
public:
static const int16_t DefaultPosition = -32768;
enum CoverState {
StateUnknown = 0,
StateClosed,
StateClosing,
StateOpen,
StateOpening,
StateStopped
};
enum CoverCommand {
CommandOpen,
CommandClose,
CommandStop
};
enum Features {
DefaultFeatures = 0,
PositionFeature = 1
};
/**
* @param uniqueId The unique ID of the cover. It needs to be unique in a scope of your device.
* @param features Features that should be enabled for the fan.
*/
HACover(const char* uniqueId, const Features features = DefaultFeatures);
/**
* Changes state of the cover and publishes MQTT message.
* Please note that if a new value is the same as previous one,
* the MQTT message won't be published.
*
* @param state New state of the cover.
* @param force Forces to update state without comparing it to previous known state.
* @returns Returns true if MQTT message has been published successfully.
*/
bool setState(const CoverState state, const bool force = false);
/**
* Changes the position of the cover and publishes MQTT message.
* Please note that if a new value is the same as previous one,
* the MQTT message won't be published.
*
* @param position The new position of the cover (0-100).
* @param force Forces to update the state without comparing it to a previous known state.
* @returns Returns `true` if MQTT message has been published successfully.
*/
bool setPosition(const int16_t position, const bool force = false);
/**
* Sets the current state of the cover without publishing it to Home Assistant.
* This method may be useful if you want to change the state before the connection
* with the MQTT broker is acquired.
*
* @param state The new state of the cover.
*/
inline void setCurrentState(const CoverState state)
{ _currentState = state; }
/**
* Returns last known state of the cover.
* By default the state is set to CoverState::StateUnknown
*/
inline CoverState getCurrentState() const
{ return _currentState; }
/**
* Sets the current position of the cover without pushing the value to Home Assistant.
* This method may be useful if you want to change the position before the connection
* with the MQTT broker is acquired.
*
* @param position The new position of the cover (0-100).
*/
inline void setCurrentPosition(const int16_t position)
{ _currentPosition = position; }
/**
* Returns the last known position of the cover.
* By default position is set to HACover::DefaultPosition
*/
inline int16_t getCurrentPosition() const
{ return _currentPosition; }
/**
* Sets class of the device.
* You can find list of available values here: https://www.home-assistant.io/integrations/cover/
*
* @param deviceClass The class name.
*/
inline void setDeviceClass(const char* deviceClass)
{ _class = deviceClass; }
/**
* Sets icon of the cover.
* Any icon from MaterialDesignIcons.com (for example: `mdi:home`).
*
* @param icon The icon name.
*/
inline void setIcon(const char* icon)
{ _icon = icon; }
/**
* Sets retain flag for the cover's command.
* If set to `true` the command produced by Home Assistant will be retained.
*
* @param retain
*/
inline void setRetain(const bool retain)
{ _retain = retain; }
/**
* Sets optimistic flag for the cover state.
* In this mode the cover state doesn't need to be reported back to the HA panel when a command is received.
* By default the optimistic mode is disabled.
*
* @param optimistic The optimistic mode (`true` - enabled, `false` - disabled).
*/
inline void setOptimistic(const bool optimistic)
{ _optimistic = optimistic; }
/**
* Registers callback that will be called each time the command from HA is received.
* Please note that it's not possible to register multiple callbacks for the same cover.
*
* @param callback
*/
inline void onCommand(HACOVER_CALLBACK(callback))
{
_commandCallback = callback;
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
_commandStdCallback = nullptr;
#endif
}
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
/**
* Registers callback using std::function.
* It allows passing capturing lambdas and std::bind expressions.
*
* @param callback
*/
inline void onCommand(const std::function<void(CoverCommand, HACover*)>& callback)
{
_commandCallback = nullptr;
_commandStdCallback = callback;
}
#endif
protected:
virtual void buildSerializer() override;
virtual HASerializer* buildDeviceDiscoverySerializer() override;
virtual bool supportsDeviceDiscovery() const override
{ return true; }
virtual void onMqttConnected() override;
virtual void onMqttMessage(
const char* topic,
const uint8_t* payload,
const uint16_t length
) override;
private:
/**
* Publishes the MQTT message with the given state.
*
* @param state The state to publish.
* @returns Returns `true` if the MQTT message has been published successfully.
*/
bool publishState(const CoverState state);
/**
* Publishes the MQTT message with the given position.
*
* @param position The position to publish.
* @returns Returns `true` if the MQTT message has been published successfully.
*/
bool publishPosition(const int16_t position);
/**
* Parses the given command and executes the cover's callback with proper enum's property.
*
* @param cmd The data of the command.
* @param length Length of the command.
*/
void handleCommand(const uint8_t* cmd, const uint16_t length);
/// Features enabled for the cover.
const uint8_t _features;
/// The current state of the cover. By default it's `HACover::StateUnknown`.
CoverState _currentState;
/// The current position of the cover. By default it's `HACover::DefaultPosition`.
int16_t _currentPosition;
/// The device class. It can be nullptr.
const char* _class;
/// The icon of the button. It can be nullptr.
const char* _icon;
/// The retain flag for the HA commands.
bool _retain;
/// The optimistic mode of the cover (`true` - enabled, `false` - disabled).
bool _optimistic;
/// The command callback that will be called when clicking the cover's button in the HA panel.
HACOVER_CALLBACK(_commandCallback);
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
/// The std::function callback that will be called when clicking the cover's button in the HA panel.
std::function<void(CoverCommand, HACover*)> _commandStdCallback;
#endif
};
#endif
#endif
+138
View File
@@ -0,0 +1,138 @@
#include "HADeviceTracker.h"
#ifndef EX_ARDUINOHA_DEVICE_TRACKER
#include "../HAMqtt.h"
#include "../utils/HASerializer.h"
HADeviceTracker::HADeviceTracker(const char* uniqueId) :
HABaseDeviceType(AHATOFSTR(HAComponentDeviceTracker), uniqueId),
_icon(nullptr),
_sourceType(SourceTypeUnknown),
_currentState(StateUnknown)
{
}
bool HADeviceTracker::setState(const TrackerState state, const bool force)
{
if (!force && state == _currentState) {
return true;
}
if (state == StateUnknown) {
return false;
}
const bool published = publishState(state);
_currentState = state;
return published;
}
void HADeviceTracker::buildSerializer()
{
if (_serializer || !uniqueId()) {
return;
}
_serializer = new HASerializer(this, 18);
_serializer->set(AHATOFSTR(HANameProperty), _name);
setEntityIdProperty(_serializer);
_serializer->set(HASerializer::WithUniqueId);
applyCommonEntityProperties(_serializer);
_serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
_serializer->set(AHATOFSTR(HAIconProperty), _icon);
_serializer->set(
AHATOFSTR(HASourceTypeProperty),
getSourceTypeProperty(),
HASerializer::ProgmemPropertyValue
);
_serializer->set(HASerializer::WithDevice);
_serializer->set(HASerializer::WithAvailability);
_serializer->topic(AHATOFSTR(HAStateTopic));
}
HASerializer* HADeviceTracker::buildDeviceDiscoverySerializer()
{
if (!uniqueId()) {
return nullptr;
}
HASerializer* serializer = new HASerializer(this, 18);
serializer->set(
AHATOFSTR(HAPlatformProperty),
AHATOFSTR(HAComponentDeviceTracker),
HASerializer::ProgmemPropertyValue
);
serializer->set(AHATOFSTR(HANameProperty), _name);
setEntityIdProperty(serializer);
serializer->set(HASerializer::WithUniqueId);
applyCommonEntityProperties(serializer);
serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
serializer->set(AHATOFSTR(HAIconProperty), _icon);
serializer->set(
AHATOFSTR(HASourceTypeProperty),
getSourceTypeProperty(),
HASerializer::ProgmemPropertyValue
);
serializer->set(HASerializer::WithAvailability);
serializer->topic(AHATOFSTR(HAStateTopic));
return serializer;
}
void HADeviceTracker::onMqttConnected()
{
if (!uniqueId()) {
return;
}
if (shouldPublishSingleComponentConfig()) {
publishConfig();
}
publishAvailability();
publishState(_currentState);
}
bool HADeviceTracker::publishState(const TrackerState state)
{
const __FlashStringHelper *stateStr = nullptr;
switch (state) {
case StateHome:
stateStr = AHATOFSTR(HAHome);
break;
case StateNotHome:
stateStr = AHATOFSTR(HANotHome);
break;
case StateNotAvailable:
stateStr = AHATOFSTR(HAOffline);
break;
default:
return false;
}
return publishOnDataTopic(AHATOFSTR(HAStateTopic), stateStr, true);
}
const __FlashStringHelper* HADeviceTracker::getSourceTypeProperty() const
{
switch (_sourceType) {
case SourceTypeGPS:
return AHATOFSTR(HAGPSType);
case SourceTypeRouter:
return AHATOFSTR(HARouterType);
case SourceTypeBluetooth:
return AHATOFSTR(HABluetoothType);
case SourceTypeBluetoothLE:
return AHATOFSTR(HABluetoothLEType);
default:
return nullptr;
}
}
#endif
+117
View File
@@ -0,0 +1,117 @@
#ifndef AHA_HADEVICETRACKER_H
#define AHA_HADEVICETRACKER_H
#include "HABaseDeviceType.h"
#ifndef EX_ARDUINOHA_DEVICE_TRACKER
/**
* HADeviceTracker allows to implement a custom device's tracker.
*
* @note
* You can find more information about this entity in the Home Assistant documentation:
* https://www.home-assistant.io/integrations/device_tracker.mqtt/
*/
class HADeviceTracker : public HABaseDeviceType
{
public:
/// Available source types of the tracker.
enum SourceType {
SourceTypeUnknown = 0,
SourceTypeGPS,
SourceTypeRouter,
SourceTypeBluetooth,
SourceTypeBluetoothLE
};
/// Available states that can be reported to the HA panel.
enum TrackerState {
StateUnknown = 0,
StateHome,
StateNotHome,
StateNotAvailable
};
/**
* @param uniqueId The unique ID of the tracker. It needs to be unique in a scope of your device.
*/
HADeviceTracker(const char* uniqueId);
/**
* Changes the state of the tracker and publishes MQTT message.
* Please note that if a new value is the same as previous one,
* the MQTT message won't be published.
*
* @param state The new state of the tracker.
* @param force Forces to update the state without comparing it to a previous known state.
* @returns Returns `true` if MQTT message has been published successfully.
*/
bool setState(const TrackerState state, const bool force = false);
/**
* Sets the current state of the tracker without publishing it to Home Assistant.
* This method may be useful if you want to change the state before connection
* with MQTT broker is acquired.
*
* @param state The new state of the tracker.
*/
inline void setCurrentState(const TrackerState state)
{ _currentState = state; }
/**
* Returns the last known state of the tracker.
* If setState method wasn't called the initial value will be returned.
*/
inline TrackerState getState() const
{ return _currentState; }
/**
* Sets icon of the tracker.
* Any icon from MaterialDesignIcons.com (for example: `mdi:home`).
*
* @param icon The icon name.
*/
inline void setIcon(const char* icon)
{ _icon = icon; }
/**
* Sets the source type of the tracker.
*
* @param type The source type (gps, router, bluetooth, bluetooth LE).
*/
inline void setSourceType(const SourceType type)
{ _sourceType = type; }
protected:
virtual void buildSerializer() override;
virtual HASerializer* buildDeviceDiscoverySerializer() override;
virtual bool supportsDeviceDiscovery() const override
{ return true; }
virtual void onMqttConnected() override;
private:
/**
* Publishes the MQTT message with the given state.
*
* @param state The state to publish.
* @returns Returns `true` if the MQTT message has been published successfully.
*/
bool publishState(TrackerState state);
/**
* Returns progmem string representing source type of the tracker.
*/
const __FlashStringHelper* getSourceTypeProperty() const;
/// The icon of the tracker. It can be nullptr.
const char* _icon;
/// The source type of the tracker. By default it's `HADeviceTracker::SourceTypeUnknown`.
SourceType _sourceType;
/// The current state of the device's tracker. By default its `HADeviceTracker::StateUnknown`.
TrackerState _currentState;
};
#endif
#endif
+246
View File
@@ -0,0 +1,246 @@
#include "HADeviceTrigger.h"
#ifndef EX_ARDUINOHA_DEVICE_TRIGGER
#include "../HAMqtt.h"
#include "../utils/HASerializer.h"
HADeviceTrigger::HADeviceTrigger(const char* type, const char* subtype) :
HABaseDeviceType(AHATOFSTR(HAComponentDeviceAutomation), nullptr),
_type(type),
_subtype(subtype),
_isProgmemType(false),
_isProgmemSubtype(false)
{
buildUniqueId();
}
HADeviceTrigger::HADeviceTrigger(TriggerType type, const char* subtype) :
HABaseDeviceType(AHATOFSTR(HAComponentDeviceAutomation), nullptr),
_type(determineProgmemType(type)),
_subtype(subtype),
_isProgmemType(true),
_isProgmemSubtype(false)
{
buildUniqueId();
}
HADeviceTrigger::HADeviceTrigger(const char* type, TriggerSubtype subtype) :
HABaseDeviceType(AHATOFSTR(HAComponentDeviceAutomation), nullptr),
_type(type),
_subtype(determineProgmemSubtype(subtype)),
_isProgmemType(false),
_isProgmemSubtype(true)
{
buildUniqueId();
}
HADeviceTrigger::HADeviceTrigger(TriggerType type, TriggerSubtype subtype) :
HABaseDeviceType(AHATOFSTR(HAComponentDeviceAutomation), nullptr),
_type(determineProgmemType(type)),
_subtype(determineProgmemSubtype(subtype)),
_isProgmemType(true),
_isProgmemSubtype(true)
{
buildUniqueId();
}
HADeviceTrigger::~HADeviceTrigger()
{
if (_uniqueId) {
delete[] _uniqueId;
}
}
bool HADeviceTrigger::trigger()
{
if (!_type || !_subtype) {
return false;
}
return publishOnDataTopic(AHATOFSTR(HATopic), "");
}
void HADeviceTrigger::buildSerializer()
{
if (_serializer || !uniqueId()) {
return;
}
_serializer = new HASerializer(this, 5); // 5 - max properties nb
_serializer->set(
AHATOFSTR(HAAutomationTypeProperty),
AHATOFSTR(HATrigger),
HASerializer::ProgmemPropertyValue
);
_serializer->set(
AHATOFSTR(HATypeProperty),
_type,
_isProgmemType
? HASerializer::ProgmemPropertyValue
: HASerializer::ConstCharPropertyValue
);
_serializer->set(
AHATOFSTR(HASubtypeProperty),
_subtype,
_isProgmemSubtype
? HASerializer::ProgmemPropertyValue
: HASerializer::ConstCharPropertyValue
);
_serializer->set(HASerializer::WithDevice);
_serializer->topic(AHATOFSTR(HATopic));
}
HASerializer* HADeviceTrigger::buildDeviceDiscoverySerializer()
{
if (!uniqueId()) {
return nullptr;
}
HASerializer* serializer = new HASerializer(this, 6);
serializer->set(
AHATOFSTR(HAPlatformProperty),
AHATOFSTR(HAComponentDeviceAutomation),
HASerializer::ProgmemPropertyValue
);
serializer->set(
AHATOFSTR(HAAutomationTypeProperty),
AHATOFSTR(HATrigger),
HASerializer::ProgmemPropertyValue
);
serializer->set(
AHATOFSTR(HATypeProperty),
_type,
_isProgmemType
? HASerializer::ProgmemPropertyValue
: HASerializer::ConstCharPropertyValue
);
serializer->set(
AHATOFSTR(HASubtypeProperty),
_subtype,
_isProgmemSubtype
? HASerializer::ProgmemPropertyValue
: HASerializer::ConstCharPropertyValue
);
serializer->topic(AHATOFSTR(HATopic));
return serializer;
}
void HADeviceTrigger::onMqttConnected()
{
if (!uniqueId()) {
return;
}
if (shouldPublishSingleComponentConfig()) {
publishConfig();
}
}
uint16_t HADeviceTrigger::calculateIdSize() const
{
if (!_type || !_subtype) {
return 0;
}
const uint16_t typeSize = _isProgmemType ? strlen_P(_type) : strlen(_type);
const uint16_t subtypeSize = _isProgmemSubtype
? strlen_P(_subtype)
: strlen(_subtype);
// plus underscore separator and null terminator
return typeSize + subtypeSize + 2;
}
void HADeviceTrigger::buildUniqueId()
{
const uint16_t idSize = calculateIdSize();
if (idSize == 0) {
return;
}
char* id = new char[idSize];
if (_isProgmemType) {
strcpy_P(id, _type);
} else {
strcpy(id, _type);
}
strcat_P(id, HASerializerUnderscore);
if (_isProgmemSubtype) {
strcat_P(id, _subtype);
} else {
strcat(id, _subtype);
}
_uniqueId = id;
}
const char* HADeviceTrigger::determineProgmemType(TriggerType type) const
{
switch (type) {
case ButtonShortPressType:
return HAButtonShortPressType;
case ButtonShortReleaseType:
return HAButtonShortReleaseType;
case ButtonLongPressType:
return HAButtonLongPressType;
case ButtonLongReleaseType:
return HAButtonLongReleaseType;
case ButtonDoublePressType:
return HAButtonDoublePressType;
case ButtonTriplePressType:
return HAButtonTriplePressType;
case ButtonQuadruplePressType:
return HAButtonQuadruplePressType;
case ButtonQuintuplePressType:
return HAButtonQuintuplePressType;
default:
return nullptr;
}
}
const char* HADeviceTrigger::determineProgmemSubtype(
TriggerSubtype subtype
) const
{
switch (subtype) {
case TurnOnSubtype:
return HATurnOnSubtype;
case TurnOffSubtype:
return HATurnOffSubtype;
case Button1Subtype:
return HAButton1Subtype;
case Button2Subtype:
return HAButton2Subtype;
case Button3Subtype:
return HAButton3Subtype;
case Button4Subtype:
return HAButton4Subtype;
case Button5Subtype:
return HAButton5Subtype;
case Button6Subtype:
return HAButton6Subtype;
default:
return nullptr;
}
}
#endif
+179
View File
@@ -0,0 +1,179 @@
#ifndef AHA_HADEVICETRIGGER_H
#define AHA_HADEVICETRIGGER_H
#include "HABaseDeviceType.h"
#ifndef EX_ARDUINOHA_DEVICE_TRIGGER
/**
* HADeviceTrigger allows to a custom trigger that can be used in the Home Assistant automation.
* For example, it can be a wall switch that produces `press` and `long_press` actions.
*
* @note
* You can find more information about this entity in the Home Assistant documentation:
* https://www.home-assistant.io/integrations/device_trigger.mqtt/
*/
class HADeviceTrigger : public HABaseDeviceType
{
public:
/// Built-in types of the trigger.
enum TriggerType {
ButtonShortPressType = 1,
ButtonShortReleaseType,
ButtonLongPressType,
ButtonLongReleaseType,
ButtonDoublePressType,
ButtonTriplePressType,
ButtonQuadruplePressType,
ButtonQuintuplePressType
};
/// Built-in subtypes of the trigger.
enum TriggerSubtype {
TurnOnSubtype = 1,
TurnOffSubtype,
Button1Subtype,
Button2Subtype,
Button3Subtype,
Button4Subtype,
Button5Subtype,
Button6Subtype
};
/**
* Creates the device trigger with a custom type and subtype.
* For example, it can be `click` as the type and `btn0` as the subtype.
* Please note that combination of the type and subtype needs to be unique in a scope of your device.
*
* @param type String representation of the type.
* @param subtype String representation of the subtype.
*/
HADeviceTrigger(const char* type, const char* subtype);
/**
* Creates the device trigger with a built-in type and a custom subtype.
* For example, it can be `HADeviceTrigger::ButtonShortPressType` as the type and `btn0` as the subtype.
* Please note that combination of the type and subtype needs to be unique in a scope of your device.
*
* @param type Built-in type of the trigger.
* @param subtype String representation of the subtype.
*/
HADeviceTrigger(TriggerType type, const char* subtype);
/**
* Creates the device trigger with a custom type and a built-in subtype.
* For example, it can be `click` as the type and `HADeviceTrigger::Button1Subtype` as the subtype.
* Please note that combination of the type and subtype needs to be unique in a scope of your device.
*
* @param type String representation of the subtype.
* @param subtype Built-in subtype of the trigger.
*/
HADeviceTrigger(const char* type, TriggerSubtype subtype);
/**
* Creates the device trigger with a built-in type and built-in subtype.
* For example, it can be `HADeviceTrigger::ButtonShortPressType` as the type and `HADeviceTrigger::Button1Subtype` as the subtype.
* Please note that combination of the type and subtype needs to be unique in a scope of your device.
*
* @param type Built-in type of the trigger.
* @param subtype Built-in subtype of the trigger.
*/
HADeviceTrigger(TriggerType type, TriggerSubtype subtype);
/**
* Frees memory allocated by the class.
*/
~HADeviceTrigger();
/**
* Publishes MQTT message with the trigger event.
* The published message is not retained.
*
* @returns Returns `true` if MQTT message has been published successfully.
*/
bool trigger();
/**
* Returns the type of the trigger.
* If the built-in type is used the returned value points to the flash memory.
* Use `HADeviceTrigger::isProgmemType` to verify if the returned value is the progmem pointer.
*
* @returns Pointer to the type.
*/
inline const char* getType() const
{ return _type; }
/**
* Returns `true` if the built-in type was assigned to the trigger.
*/
inline bool isProgmemType() const
{ return _isProgmemType; }
/**
* Returns the subtype of the trigger.
* If the built-in subtype is used the returned value points to the flash memory.
* Use `HADeviceTrigger::isProgmemSubtype` to verify if the returned value is the progmem pointer.
*
* @returns Pointer to the subtype.
*/
inline const char* getSubtype() const
{ return _subtype; }
/**
* Returns `true` if the built-in subtype was assigned to the trigger.
*/
inline bool isProgmemSubtype() const
{ return _isProgmemSubtype; }
protected:
virtual void buildSerializer() override;
virtual HASerializer* buildDeviceDiscoverySerializer() override;
virtual bool supportsDeviceDiscovery() const override
{ return true; }
virtual void onMqttConnected() override;
private:
/**
* Calculates desired size of the unique ID based on the type and subtype that were passed to the constructor.
*/
uint16_t calculateIdSize() const;
/**
* Builds the unique ID of the device's type based on the type and subtype that were passed to the constructor.
*/
void buildUniqueId();
/**
* Returns pointer to the flash memory that represents the given type.
*
* @param subtype Built-in type enum's value.
* @returns Pointer to the flash memory if the given type is supported.
* For the unsupported type the nullptr is returned.
*/
const char* determineProgmemType(TriggerType type) const;
/**
* Returns pointer to the flash memory that represents the given subtype.
*
* @param subtype Built-in subtype enum's value.
* @returns Pointer to the flash memory if the given subtype is supported.
* For the unsupported subtype the nullptr is returned.
*/
const char* determineProgmemSubtype(TriggerSubtype subtype) const;
private:
/// Pointer to the trigger's type. It can be pointer to the flash memory.
const char* _type;
/// Pointer to the trigger's subtype. It can be pointer to the flash memory.
const char* _subtype;
/// Specifies whether the type points to the flash memory.
bool _isProgmemType;
/// Specifies whether the subtype points to the flash memory.
bool _isProgmemSubtype;
};
#endif
#endif
+291
View File
@@ -0,0 +1,291 @@
#include "HAFan.h"
#ifndef EX_ARDUINOHA_FAN
#include "../HAMqtt.h"
#include "../utils/HAUtils.h"
#include "../utils/HASerializer.h"
HAFan::HAFan(const char* uniqueId, const uint8_t features) :
HABaseDeviceType(AHATOFSTR(HAComponentFan), uniqueId),
_features(features),
_icon(nullptr),
_retain(false),
_optimistic(false),
_speedRangeMax(),
_speedRangeMin(),
_currentState(false),
_currentSpeed(0),
_stateCallback(nullptr),
_speedCallback(nullptr)
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
, _stateStdCallback(),
_speedStdCallback()
#endif
{
}
bool HAFan::setState(const bool state, const bool force)
{
if (!force && state == _currentState) {
return true;
}
const bool published = publishState(state);
_currentState = state;
return published;
}
bool HAFan::setSpeed(const uint16_t speed, const bool force)
{
if (!force && speed == _currentSpeed) {
return true;
}
if (!(_features & SpeedsFeature)) {
return false;
}
const bool published = publishSpeed(speed);
_currentSpeed = speed;
return published;
}
void HAFan::buildSerializer()
{
if (_serializer || !uniqueId()) {
return;
}
_serializer = new HASerializer(this, 24);
_serializer->set(AHATOFSTR(HANameProperty), _name);
setEntityIdProperty(_serializer);
_serializer->set(HASerializer::WithUniqueId);
applyCommonEntityProperties(_serializer);
_serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
_serializer->set(AHATOFSTR(HAIconProperty), _icon);
if (_retain) {
_serializer->set(
AHATOFSTR(HARetainProperty),
&_retain,
HASerializer::BoolPropertyType
);
}
if (_optimistic) {
_serializer->set(
AHATOFSTR(HAOptimisticProperty),
&_optimistic,
HASerializer::BoolPropertyType
);
}
if (_features & SpeedsFeature) {
_serializer->topic(AHATOFSTR(HAPercentageStateTopic));
_serializer->topic(AHATOFSTR(HAPercentageCommandTopic));
if (_speedRangeMax.isSet()) {
_serializer->set(
AHATOFSTR(HASpeedRangeMaxProperty),
&_speedRangeMax,
HASerializer::NumberPropertyType
);
}
if (_speedRangeMin.isSet()) {
_serializer->set(
AHATOFSTR(HASpeedRangeMinProperty),
&_speedRangeMin,
HASerializer::NumberPropertyType
);
}
}
_serializer->set(HASerializer::WithDevice);
_serializer->set(HASerializer::WithAvailability);
_serializer->topic(AHATOFSTR(HAStateTopic));
_serializer->topic(AHATOFSTR(HACommandTopic));
}
HASerializer* HAFan::buildDeviceDiscoverySerializer()
{
if (!uniqueId()) {
return nullptr;
}
HASerializer* serializer = new HASerializer(this, 24);
serializer->set(
AHATOFSTR(HAPlatformProperty),
AHATOFSTR(HAComponentFan),
HASerializer::ProgmemPropertyValue
);
serializer->set(AHATOFSTR(HANameProperty), _name);
setEntityIdProperty(serializer);
serializer->set(HASerializer::WithUniqueId);
applyCommonEntityProperties(serializer);
serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
serializer->set(AHATOFSTR(HAIconProperty), _icon);
if (_retain) {
serializer->set(
AHATOFSTR(HARetainProperty),
&_retain,
HASerializer::BoolPropertyType
);
}
if (_optimistic) {
serializer->set(
AHATOFSTR(HAOptimisticProperty),
&_optimistic,
HASerializer::BoolPropertyType
);
}
if (_features & SpeedsFeature) {
serializer->topic(AHATOFSTR(HAPercentageStateTopic));
serializer->topic(AHATOFSTR(HAPercentageCommandTopic));
if (_speedRangeMax.isSet()) {
serializer->set(
AHATOFSTR(HASpeedRangeMaxProperty),
&_speedRangeMax,
HASerializer::NumberPropertyType
);
}
if (_speedRangeMin.isSet()) {
serializer->set(
AHATOFSTR(HASpeedRangeMinProperty),
&_speedRangeMin,
HASerializer::NumberPropertyType
);
}
}
serializer->set(HASerializer::WithAvailability);
serializer->topic(AHATOFSTR(HAStateTopic));
serializer->topic(AHATOFSTR(HACommandTopic));
return serializer;
}
void HAFan::onMqttConnected()
{
if (!uniqueId()) {
return;
}
if (shouldPublishSingleComponentConfig()) {
publishConfig();
}
publishAvailability();
if (!_retain) {
publishState(_currentState);
publishSpeed(_currentSpeed);
}
subscribeTopic(uniqueId(), AHATOFSTR(HACommandTopic));
if (_features & SpeedsFeature) {
subscribeTopic(uniqueId(), AHATOFSTR(HAPercentageCommandTopic));
}
}
void HAFan::onMqttMessage(
const char* topic,
const uint8_t* payload,
const uint16_t length
)
{
if (HASerializer::compareDataTopics(
topic,
uniqueId(),
AHATOFSTR(HACommandTopic)
)) {
handleStateCommand(payload, length);
} else if (HASerializer::compareDataTopics(
topic,
uniqueId(),
AHATOFSTR(HAPercentageCommandTopic)
)) {
handleSpeedCommand(payload, length);
}
}
bool HAFan::publishState(const bool state)
{
return publishOnDataTopic(
AHATOFSTR(HAStateTopic),
AHATOFSTR(state ? HAStateOn : HAStateOff),
true
);
}
bool HAFan::publishSpeed(const uint16_t speed)
{
if (!(_features & SpeedsFeature)) {
return false;
}
char str[5 + 1] = {0}; // uint16_t digits with null terminator
HANumeric(speed, 0).toStr(str);
return publishOnDataTopic(AHATOFSTR(HAPercentageStateTopic), str, true);
}
void HAFan::handleStateCommand(const uint8_t* cmd, const uint16_t length)
{
(void)cmd;
const bool hasStateCallback =
_stateCallback
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|| static_cast<bool>(_stateStdCallback)
#endif
;
if (!hasStateCallback) {
return;
}
bool state = length == strlen_P(HAStateOn);
if (_stateCallback) {
_stateCallback(state, this);
}
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
if (_stateStdCallback) {
_stateStdCallback(state, this);
}
#endif
}
void HAFan::handleSpeedCommand(const uint8_t* cmd, const uint16_t length)
{
const bool hasSpeedCallback =
_speedCallback
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|| static_cast<bool>(_speedStdCallback)
#endif
;
if (!hasSpeedCallback) {
return;
}
const HANumeric& number = HANumeric::fromStr(cmd, length);
if (number.isUInt16()) {
const uint16_t speed = number.toUInt16();
if (_speedCallback) {
_speedCallback(speed, this);
}
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
if (_speedStdCallback) {
_speedStdCallback(speed, this);
}
#endif
}
}
#endif

Some files were not shown because too many files have changed in this diff Show More