mirror of
https://github.com/alexhopeoconnor/arduino-home-assistant.git
synced 2026-10-04 02:48:13 +10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
56d74df55a | ||
|
|
84cc0037b1 | ||
|
|
29ca5b2a29 | ||
|
|
5296fb1831 | ||
|
|
96c5aa6e78 | ||
|
|
9d3eaa61f7 | ||
|
|
3ac7fc98be | ||
|
|
d03766ffbc | ||
|
|
b9f4fd7f4b | ||
|
|
8ba5482892 | ||
|
|
c9e6eef5b2 | ||
|
|
40b98a38ee | ||
|
|
7c419cb99e | ||
|
|
25fc356a0a | ||
|
|
7d5d70d525 | ||
|
|
7894f0c621 | ||
|
|
d954543236 | ||
|
|
2ebdcf302b | ||
|
|
1d333ab229 | ||
|
|
2a00dcd65f | ||
|
|
105e96197b | ||
|
|
a838dac9c0 | ||
|
|
77a356bb37 | ||
|
|
9e17dda50b | ||
|
|
5c7acd7e39 | ||
|
|
87b7e03fe6 | ||
|
|
ae059aecc1 | ||
|
|
6cf4f11580 | ||
|
|
fdc60b57c3 | ||
|
|
80ae7ae592 | ||
|
|
ab46939903 | ||
|
|
e054e53eea | ||
|
|
9ec42d667d | ||
|
|
b1eeec0856 | ||
|
|
cd706969de | ||
|
|
8e3aad90c4 | ||
|
|
b0bc9b4ea7 | ||
|
|
8d76532e41 | ||
|
|
252f0ab6b1 | ||
|
|
b86495f492 | ||
|
|
884d8254bf | ||
|
|
0fc32a5bad | ||
|
|
a4e50b7d04 |
@@ -0,0 +1 @@
|
||||
github: dawidchyrzynski
|
||||
@@ -0,0 +1,45 @@
|
||||
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 }}
|
||||
@@ -0,0 +1,36 @@
|
||||
name: Home Assistant MQTT contract
|
||||
|
||||
on:
|
||||
workflow_dispatch:
|
||||
schedule:
|
||||
- cron: "17 3 * * 1"
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
contract:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
home_assistant: ["2024.11.3", stable, dev]
|
||||
env:
|
||||
HA_VERSION: ${{ matrix.home_assistant }}
|
||||
COMPOSE_FILE: tests/ha-contract/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 CONTRACT_MODE=retained-restart tests
|
||||
- name: Collect Home Assistant logs on failure
|
||||
if: failure()
|
||||
run: docker compose logs --no-color homeassistant mqtt
|
||||
- name: Remove contract volumes
|
||||
if: always()
|
||||
run: docker compose down -v
|
||||
@@ -0,0 +1,55 @@
|
||||
name: Publish release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
ha-contract:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
home_assistant: ["2024.11.3", stable, dev]
|
||||
env:
|
||||
HA_VERSION: ${{ matrix.home_assistant }}
|
||||
COMPOSE_FILE: tests/ha-contract/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 CONTRACT_MODE=retained-restart tests
|
||||
- name: Collect Home Assistant logs on failure
|
||||
if: failure()
|
||||
run: docker compose logs --no-color homeassistant mqtt
|
||||
- name: Remove contract volumes
|
||||
if: always()
|
||||
run: docker compose down -v
|
||||
|
||||
publish:
|
||||
needs: ha-contract
|
||||
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: ./scripts/test.sh compile --platform esp8266
|
||||
- run: pio test -e native --filter test_native_core
|
||||
- run: ./scripts/test.sh compile --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
@@ -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/
|
||||
+141
-4
@@ -1,13 +1,150 @@
|
||||
# Changelog
|
||||
|
||||
## 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 in `examples/sensor/sensor.ino`
|
||||
* 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`)
|
||||
* 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
|
||||
@@ -15,9 +152,9 @@
|
||||
* 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 `examples/advanced-availability/advanced-availability.ino`)
|
||||
* Added support for MQTT LWT (see [Advanced Availability example](examples/advanced-availability/advanced-availability.ino))
|
||||
|
||||
**Updates:**
|
||||
**Improvements:**
|
||||
* Optimized codebase and logic in all devices types
|
||||
* Updated all examples
|
||||
* Fixed compilation warnings in all classes
|
||||
|
||||
@@ -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/>.
|
||||
@@ -1,74 +1,80 @@
|
||||
# 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://github.com/alexhopeoconnor/arduino-home-assistant/releases)
|
||||
[](docs/README.md)
|
||||
|
||||
## Features
|
||||
ArduinoHA is the maintained MQTT-discovery library behind compact Arduino, ESP8266, and ESP32 integrations with Home Assistant. It uses Arduino's standard network `Client` API and is continuously compile-tested on ESP8266 and ESP32. Device discovery requires Home Assistant 2024.11.0 or newer; single-component discovery remains supported.
|
||||
|
||||
* MQTT discovery (device is added to the Home Assistant panel automatically)
|
||||
* MQTT Last Will and Testament
|
||||
* Auto reconnect with MQTT broker
|
||||
## Why use it
|
||||
|
||||
## Examples
|
||||
- **Home Assistant discovery:** entities appear automatically from retained MQTT discovery payloads.
|
||||
- **Two-way entities:** report local state and receive Home Assistant commands with a small, explicit API.
|
||||
- **One physical device:** group multiple entities, metadata, shared availability, and MQTT Last Will under `HADevice`.
|
||||
- **Control the footprint:** compile out entity implementations a firmware does not use.
|
||||
- **Two discovery shapes:** start with one payload per entity or opt into a single device-discovery payload.
|
||||
|
||||
* [Binary Sensor](examples/binary-sensor/binary-sensor.ino)
|
||||
* [Fan](examples/fan/fan.ino)
|
||||
* [LED switch](examples/led-switch/led-switch.ino)
|
||||
* [Multi-state button](examples/multi-state-button/multi-state-button.ino)
|
||||
* [Sensor (temperature, humidity, etc.)](examples/sensor/sensor.ino)
|
||||
* [HVAC](examples/hvac/hvac.ino)
|
||||
* [NodeMCU Wi-Fi](examples/nodemcu/nodemcu.ino)
|
||||
* [Arduino Nano 33 IoT Wi-Fi (SAMD)](examples/nano33iot/nano33iot.ino)
|
||||
* [Availability feature](examples/availability)
|
||||
* [Advanced availability (MQTT LWT)](examples/advanced-availability/advanced-availability.ino)
|
||||
* [MQTT with credentials](examples/mqtt-with-credentials/mqtt-with-credentials.ino)
|
||||
* [MQTT events](examples/mqtt-events/mqtt-events.ino)
|
||||
## Start with a sensor
|
||||
|
||||
## Tested boards
|
||||
```cpp
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ArduinoHA.h>
|
||||
|
||||
* 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)
|
||||
WiFiClient client;
|
||||
HADevice device;
|
||||
HAMqtt mqtt(client, device);
|
||||
HASensorNumber temperature("temperature");
|
||||
|
||||
## Tested Arduino Shields
|
||||
void setup() {
|
||||
byte mac[WL_MAC_ADDR_LENGTH];
|
||||
WiFi.macAddress(mac);
|
||||
device.setUniqueId(mac, sizeof(mac));
|
||||
|
||||
* Arduino Ethernet Shield (WizNet W5100)
|
||||
WiFi.begin("SSID", "password");
|
||||
while (WiFi.status() != WL_CONNECTED) delay(500);
|
||||
|
||||
## Supported HA types
|
||||
temperature.setName("Temperature");
|
||||
temperature.setUnitOfMeasurement("°C");
|
||||
mqtt.begin("mqtt.local", "mqtt_user", "mqtt_password");
|
||||
}
|
||||
|
||||
* Binary sensors
|
||||
* Fans
|
||||
* Device triggers
|
||||
* Switches
|
||||
* Sensors
|
||||
* Tag scanner
|
||||
* HVACs *(side note: HVACs requires more flash size than other HA types. It's not suitable for Arduino Nano/Uno)*
|
||||
void loop() {
|
||||
mqtt.loop();
|
||||
// Call temperature.setValue(...) when your reading changes.
|
||||
}
|
||||
```
|
||||
|
||||
## Roadmap
|
||||
Read [Getting started](docs/getting-started.md) before copying this into production: it explains object lifetime, MQTT lifecycle, ESP32 includes, and install routes.
|
||||
|
||||
* FAQ + Home Assistant setup instructions
|
||||
* Documentation of the library
|
||||
* Unit tests
|
||||
* Reduce flash memory usage
|
||||
* Add support for HA covers
|
||||
* Add support for HA lights
|
||||
## Install
|
||||
|
||||
## Unsupported features
|
||||
```ini
|
||||
lib_deps =
|
||||
home-assistant-integration=https://github.com/alexhopeoconnor/arduino-home-assistant.git#v3.1.0
|
||||
```
|
||||
|
||||
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.
|
||||
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); see [Getting started](docs/getting-started.md#install-the-library).
|
||||
|
||||
# License
|
||||
## Documentation
|
||||
|
||||
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.
|
||||
The [documentation map](docs/README.md) is the starting point:
|
||||
|
||||
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.
|
||||
- [Getting started](docs/getting-started.md): connection lifecycle and minimal sketches.
|
||||
- [Device and discovery](docs/device-and-discovery.md): device metadata, discovery modes, and runtime refresh.
|
||||
- [MQTT usage](docs/mqtt-usage.md): callbacks, availability, custom MQTT, logging, and footprint flags.
|
||||
- [Entity guide](docs/entities.md): supported entity types and the best matching example.
|
||||
- [Examples](examples/README.md): curated entry points and the full example index.
|
||||
|
||||
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
|
||||
## Development and releases
|
||||
|
||||
```bash
|
||||
./scripts/bump-version.sh vMAJOR.MINOR.PATCH
|
||||
# Replace the generated CHANGELOG TODO with the release summary.
|
||||
./scripts/test.sh compile --platform esp8266
|
||||
./scripts/test.sh compile --platform esp32
|
||||
./scripts/check-docs.sh
|
||||
./scripts/prepare-release.sh vMAJOR.MINOR.PATCH --tag
|
||||
```
|
||||
|
||||
The release preflight validates both package manifests and the matching changelog section. A pushed tag repeats the board-free compile checks and creates a GitHub Release from that section; it does not publish to the PlatformIO Registry or deploy firmware.
|
||||
|
||||
See the [changelog](CHANGELOG.md) and [licence](LICENSE).
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
# Documentation
|
||||
|
||||
User-facing notes for this library. API details live in the headers under [`src/`](../src/).
|
||||
|
||||
| Topic | What it covers |
|
||||
| ----- | ---------------- |
|
||||
| [Getting started](getting-started.md) | Prerequisites, installing the library, minimal sketches |
|
||||
| [Device & discovery](device-and-discovery.md) | `HADevice`, MQTT connection, discovery prefixes, entity IDs |
|
||||
| [MQTT usage](mqtt-usage.md) | Callbacks, custom topics, availability, compiler flags |
|
||||
| [Entities](entities.md) | Supported Home Assistant entity classes and example selection |
|
||||
| [Examples](../examples/README.md) | Curated paths through the standalone sketches |
|
||||
|
||||
Class-level API details live in headers under [`src/`](../src/). Return to the [project overview](../README.md).
|
||||
| [Compatibility baseline](compatibility.md) | Audited upstream/HA targets and deliberate exclusions |
|
||||
@@ -0,0 +1,41 @@
|
||||
# Compatibility baseline
|
||||
|
||||
This maintenance line begins from fork commit `84cc0037b1c0` (release `v3.0.2`).
|
||||
It intentionally tracks Home Assistant's MQTT discovery contract 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` |
|
||||
| Contract 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.
|
||||
|
||||
## 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 contract gates before publishing a new release.
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
# 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
|
||||
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.
|
||||
|
||||
### 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 deliberately 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
|
||||
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)).
|
||||
@@ -0,0 +1,33 @@
|
||||
# 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. Those are deliberate unsupported surfaces, not configuration switches.
|
||||
|
||||
## 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).
|
||||
@@ -0,0 +1,100 @@
|
||||
# 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.1.0
|
||||
```
|
||||
|
||||
**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);
|
||||
mqtt.begin("192.168.1.50", "mqtt_user", "mqtt_password");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
Ethernet.maintain();
|
||||
mqtt.loop();
|
||||
}
|
||||
```
|
||||
|
||||
### ESP8266 / ESP32 (example)
|
||||
|
||||
```cpp
|
||||
#include <ESP8266WiFi.h>
|
||||
#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");
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
delay(500);
|
||||
}
|
||||
|
||||
mqtt.begin("192.168.1.50", "mqtt_user", "mqtt_password");
|
||||
}
|
||||
|
||||
void loop() {
|
||||
mqtt.loop();
|
||||
}
|
||||
```
|
||||
|
||||
## `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.
|
||||
@@ -0,0 +1,149 @@
|
||||
# MQTT usage
|
||||
|
||||
## Callbacks and tuning
|
||||
|
||||
`HAMqtt` supports optional callbacks and PubSubClient tuning:
|
||||
|
||||
```cpp
|
||||
void onMessage(const char* topic, const uint8_t* payload, uint16_t length) { /* ... */ }
|
||||
void onConnected() { /* ... */ }
|
||||
void onDisconnected() { /* ... */ }
|
||||
void onStateChanged(HAMqtt::ConnectionState state) { /* ... */ }
|
||||
|
||||
void setup() {
|
||||
mqtt.onMessage(onMessage);
|
||||
mqtt.onConnected(onConnected);
|
||||
mqtt.onDisconnected(onDisconnected);
|
||||
mqtt.onStateChanged(onStateChanged);
|
||||
mqtt.setBufferSize(512); // default 256
|
||||
mqtt.setKeepAlive(60); // seconds, default 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.subscribe("my/custom/topic");
|
||||
}
|
||||
```
|
||||
|
||||
Handle payloads in `onMessage`.
|
||||
|
||||
## Publishing arbitrary payloads
|
||||
|
||||
```cpp
|
||||
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
|
||||
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
|
||||
sensor.setPayloadAvailable("ready");
|
||||
sensor.setPayloadNotAvailable("lost");
|
||||
```
|
||||
|
||||
For multi-topic availability discovery, add full MQTT topics and a mode:
|
||||
|
||||
```cpp
|
||||
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.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.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
|
||||
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:
|
||||
|
||||
```cpp
|
||||
arduinoHASetLogEnabled(true);
|
||||
arduinoHASetLogLevel(ArduinoHALogLevel::Trace);
|
||||
|
||||
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);
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
`arduinoHALog(...)` and `arduinoHALogf(...)` support subsystem-tagged messages such as `mqtt`, `discovery`, `availability`, `serializer`, `entity`, and `device`. `DeviceFramework` installs a structured sink so ArduinoHA messages follow the same main log stream as the rest of the firmware.
|
||||
|
||||
Optional transport context for diagnostics (registered automatically by **DeviceFramework**): **`arduinoHASetNetworkStatusFn`** (for example returning `WiFi.status()` so publish failure lines can include `wifi=`).
|
||||
|
||||
**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`
|
||||
@@ -0,0 +1,39 @@
|
||||
# ArduinoHA examples
|
||||
|
||||
Each directory is an Arduino sketch. Start with the network example matching your board, then pick an entity example from the table. Copy credentials into your local development configuration; do not commit them in a sketch.
|
||||
|
||||
| Starting point | Use it for |
|
||||
| --- | --- |
|
||||
| [nodemcu](nodemcu/nodemcu.ino) | Basic ESP8266 Wi-Fi and MQTT connection |
|
||||
| [nano33iot](nano33iot/nano33iot.ino) | Basic Arduino Nano 33 IoT connection |
|
||||
| [mqtt-with-credentials](mqtt-with-credentials/mqtt-with-credentials.ino) | MQTT authentication |
|
||||
| [mqtt-advanced](mqtt-advanced/mqtt-advanced.ino) | Custom MQTT subscriptions and publishing |
|
||||
| [availability](availability/availability.ino) | Per-entity availability |
|
||||
| [advanced-availability](advanced-availability/advanced-availability.ino) | Shared availability and MQTT Last Will |
|
||||
|
||||
## Entity examples
|
||||
|
||||
| Example | 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 |
|
||||
|
||||
The examples are intentionally small, not production firmware frameworks. For reusable Wi-Fi configuration, MQTT wiring, profiles, OTA, and migrations, use [DeviceFramework](https://github.com/alexhopeoconnor/DeviceFramework) in a consuming firmware.
|
||||
|
||||
See the [entity guide](../docs/entities.md) and [project overview](../README.md).
|
||||
@@ -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);
|
||||
// "myInput" is unique ID of the sensor. You should define you own ID.
|
||||
HABinarySensor sensor("myInput");
|
||||
|
||||
void setup() {
|
||||
pinMode(INPUT_PIN, INPUT_PULLUP);
|
||||
@@ -31,6 +29,19 @@ void setup() {
|
||||
// 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
|
||||
@@ -53,12 +64,12 @@ 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();
|
||||
}
|
||||
|
||||
if ((millis() - lastAvailabilityToggleAt) > 5000) {
|
||||
device.setAvailability(!device.isOnline());
|
||||
device.setAvailability(!device.isAvailable());
|
||||
lastAvailabilityToggleAt = millis();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,33 +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
|
||||
* HVACs
|
||||
* Fans
|
||||
|
||||
## 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.
|
||||
@@ -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);
|
||||
// "myInput" is unique ID of the sensor. You should define you own ID.
|
||||
HABinarySensor sensor("myInput");
|
||||
|
||||
void setup() {
|
||||
pinMode(INPUT_PIN, INPUT_PULLUP);
|
||||
@@ -36,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);
|
||||
}
|
||||
|
||||
@@ -46,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();
|
||||
}
|
||||
|
||||
|
||||
@@ -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);
|
||||
// "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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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
@@ -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
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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,
|
||||
|
+26
-17
@@ -11,27 +11,26 @@ 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 onStateChanged(bool state) {
|
||||
void onStateCommand(bool state, HAFan* sender) {
|
||||
Serial.print("State: ");
|
||||
Serial.println(state);
|
||||
|
||||
sender->setState(state); // report state back to the Home Assistant
|
||||
}
|
||||
|
||||
void onSpeedChanged(HAFan::Speed speed) {
|
||||
void onSpeedCommand(uint16_t speed, HAFan* sender) {
|
||||
Serial.print("Speed: ");
|
||||
if (speed == HAFan::OffSpeed) {
|
||||
Serial.print("off");
|
||||
} else if (speed == HAFan::LowSpeed) {
|
||||
Serial.print("low");
|
||||
} else if (speed == HAFan::MediumSpeed) {
|
||||
Serial.print("medium");
|
||||
} else if (speed == HAFan::HighSpeed) {
|
||||
Serial.print("high");
|
||||
}
|
||||
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);
|
||||
|
||||
@@ -40,14 +39,20 @@ void setup() {
|
||||
device.setSoftwareVersion("1.0.0");
|
||||
|
||||
// configure fan (optional)
|
||||
// default speeds are: Off | Low | Medium | High
|
||||
fan.setSpeeds(HAFan::OffSpeed | HAFan::LowSpeed | HAFan::HighSpeed);
|
||||
fan.setName("Bathroom");
|
||||
fan.setRetain(true);
|
||||
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.onStateChanged(onStateChanged);
|
||||
fan.onSpeedChanged(onSpeedChanged);
|
||||
fan.onStateCommand(onStateCommand);
|
||||
fan.onSpeedCommand(onSpeedCommand);
|
||||
|
||||
mqtt.begin(BROKER_ADDR);
|
||||
}
|
||||
@@ -55,4 +60,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 fan using a button connected to the device.
|
||||
// fan.setState(true); // true (ON) or false (OFF)
|
||||
}
|
||||
+33
-26
@@ -9,33 +9,35 @@ WiFiClient client;
|
||||
HADevice device;
|
||||
HAMqtt mqtt(client, device);
|
||||
|
||||
// see src/device-types/HAHVAC.h header for more details
|
||||
HAHVAC hvac("my_name", HAHVAC::AuxHeatingFeature | HAHVAC::AwayModeFeature | HAHVAC::HoldFeature);
|
||||
// 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;
|
||||
double lastTemp = 0;
|
||||
float lastTemp = 0;
|
||||
|
||||
void onAuxHeatingStateChanged(bool state) {
|
||||
Serial.print("Aux heating: ");
|
||||
Serial.println(state);
|
||||
}
|
||||
void onTargetTemperatureCommand(HANumeric temperature, HAHVAC* sender) {
|
||||
float temperatureFloat = temperature.toFloat();
|
||||
|
||||
void onAwayStateChanged(bool state) {
|
||||
Serial.print("Away state: ");
|
||||
Serial.println(state);
|
||||
}
|
||||
|
||||
void onHoldStateChanged(bool state) {
|
||||
Serial.print("Hold state: ");
|
||||
Serial.println(state);
|
||||
}
|
||||
|
||||
void onTargetTemperatureChanged(double temp) {
|
||||
Serial.print("Target temperature: ");
|
||||
Serial.println(temp);
|
||||
Serial.println(temperatureFloat);
|
||||
|
||||
sender->setTargetTemperature(temperature); // report target temperature back to the HA panel
|
||||
}
|
||||
|
||||
void onModeChanged(HAHVAC::Mode mode) {
|
||||
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");
|
||||
@@ -50,6 +52,8 @@ void onModeChanged(HAHVAC::Mode mode) {
|
||||
} else if (mode == HAHVAC::FanOnlyMode) {
|
||||
Serial.println("fan only");
|
||||
}
|
||||
|
||||
sender->setMode(mode); // report mode back to the HA panel
|
||||
}
|
||||
|
||||
void setup() {
|
||||
@@ -75,18 +79,21 @@ void setup() {
|
||||
device.setSoftwareVersion("1.0.0");
|
||||
|
||||
// assign callbacks (optional)
|
||||
hvac.onAuxHeatingStateChanged(onAuxHeatingStateChanged);
|
||||
hvac.onAwayStateChanged(onAwayStateChanged);
|
||||
hvac.onHoldStateChanged(onHoldStateChanged);
|
||||
hvac.onTargetTemperatureChanged(onTargetTemperatureChanged);
|
||||
hvac.onModeChanged(onModeChanged);
|
||||
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);
|
||||
hvac.setRetain(true);
|
||||
|
||||
// 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);
|
||||
}
|
||||
|
||||
@@ -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); // 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() {
|
||||
@@ -29,9 +32,15 @@ void setup() {
|
||||
|
||||
// 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);
|
||||
}
|
||||
@@ -39,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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
#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 (memcmp(topic, "myCustomTopic") == 0) { ... }
|
||||
|
||||
Serial.print("New message on topic: ");
|
||||
Serial.println(topic);
|
||||
Serial.print("Data: ");
|
||||
Serial.println((const char*)payload);
|
||||
|
||||
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();
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
#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 onMqttConnected() {
|
||||
Serial.println("Connected to the broker!");
|
||||
}
|
||||
|
||||
void onMqttConnectionFailed() {
|
||||
Serial.println("Failed to connect to the broker!");
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
Ethernet.begin(mac);
|
||||
|
||||
mqtt.onConnected(onMqttConnected);
|
||||
mqtt.onConnectionFailed(onMqttConnectionFailed);
|
||||
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); // 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;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -9,11 +9,14 @@
|
||||
WiFiClient client;
|
||||
HADevice device;
|
||||
HAMqtt mqtt(client, device);
|
||||
HASwitch led("led", false); // 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
|
||||
}
|
||||
|
||||
@@ -9,11 +9,14 @@
|
||||
WiFiClient client;
|
||||
HADevice device;
|
||||
HAMqtt mqtt(client, device);
|
||||
HASwitch led("led", false); // 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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
+15
-17
@@ -4,13 +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);
|
||||
HASensor temp("temp");
|
||||
|
||||
// "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
|
||||
@@ -21,9 +21,12 @@ void setup() {
|
||||
device.setSoftwareVersion("1.0.0");
|
||||
|
||||
// configure sensor (optional)
|
||||
temp.setUnitOfMeasurement("°C");
|
||||
temp.setDeviceClass("temperature");
|
||||
temp.setIcon("mdi:home");
|
||||
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);
|
||||
}
|
||||
@@ -32,16 +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");
|
||||
|
||||
// Supported data types:
|
||||
// uint32_t (uint16_t, uint8_t)
|
||||
// int32_t (int16_t, int8_t)
|
||||
// double
|
||||
// float
|
||||
// const char*
|
||||
}
|
||||
// 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.
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
{
|
||||
"name": "home-assistant-integration",
|
||||
"version": "3.1.0",
|
||||
"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
@@ -1,10 +1,10 @@
|
||||
name=home-assistant-integration
|
||||
version=1.2.0
|
||||
author=Dawid Chyrzynski <dawid.chyrzynski@gmail.com>
|
||||
maintainer=Dawid Chyrzynski <dawid.chyrzynski@gmail.com>
|
||||
version=3.1.0
|
||||
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
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
; PlatformIO — Unity tests for home-assistant-integration (ArduinoHA)
|
||||
;
|
||||
; Full suite:
|
||||
; pio test -e esp8266
|
||||
; pio test -e 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
|
||||
|
||||
[env:esp32]
|
||||
extends = common
|
||||
test_ignore = test_native_core
|
||||
platform = https://github.com/pioarduino/platform-espressif32/releases/download/51.03.05/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>
|
||||
Executable
+54
@@ -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."
|
||||
Executable
+27
@@ -0,0 +1,27 @@
|
||||
#!/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
|
||||
)
|
||||
|
||||
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 -name '*.md' -type f -print0)
|
||||
|
||||
echo "Documentation links and required files passed"
|
||||
Executable
+78
@@ -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
|
||||
Executable
+30
@@ -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"
|
||||
Executable
+18
@@ -0,0 +1,18 @@
|
||||
#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
|
||||
usage() {
|
||||
echo "Usage: $0 compile --platform esp8266|esp32" >&2
|
||||
exit 2
|
||||
}
|
||||
|
||||
[[ "${1:-}" == "compile" && "${2:-}" == "--platform" && $# -eq 3 ]] || usage
|
||||
|
||||
case "${3:-}" in
|
||||
esp8266|esp32) environment="${3}" ;;
|
||||
*) usage ;;
|
||||
esac
|
||||
|
||||
root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
|
||||
pio test -d "$root" -e "$environment" --without-uploading --without-testing
|
||||
echo "ArduinoHA compile check passed for ${3}"
|
||||
+22
-2
@@ -1,15 +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/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
|
||||
|
||||
+60
-10
@@ -1,13 +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
|
||||
|
||||
// You can reduce Flash size of the compiled library by commenting unused components below
|
||||
#define ARDUINOHA_BINARY_SENSOR
|
||||
#define ARDUINOHA_FAN
|
||||
#define ARDUINOHA_HVAC
|
||||
#define ARDUINOHA_SENSOR
|
||||
#define ARDUINOHA_SWITCH
|
||||
#define ARDUINOHA_TAG_SCANNER
|
||||
#define ARDUINOHA_TRIGGERS
|
||||
#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.1.0"
|
||||
|
||||
#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)
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
@@ -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
|
||||
@@ -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
|
||||
+401
-136
@@ -1,19 +1,150 @@
|
||||
#include <Arduino.h>
|
||||
|
||||
#include "ArduinoHADefines.h"
|
||||
#include "HADevice.h"
|
||||
#include "HAUtils.h"
|
||||
#include "HAMqtt.h"
|
||||
#include "device-types/DeviceTypeSerializer.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), \
|
||||
_sharedAvailability(false), \
|
||||
_ownsUniqueId(false), \
|
||||
_serializer(new HASerializer(nullptr, 16)), \
|
||||
_availabilityTopic(nullptr), \
|
||||
_available(true) // device will be available by default
|
||||
_sharedAvailability(false), \
|
||||
_available(true), \
|
||||
_extendedUniqueIds(false), \
|
||||
_payloadAvailable(nullptr), \
|
||||
_payloadNotAvailable(nullptr), \
|
||||
_connectionsJson(), \
|
||||
_hasConnections(false), \
|
||||
_connectionsPropertyRegistered(false)
|
||||
|
||||
HADevice::HADevice() :
|
||||
_uniqueId(nullptr),
|
||||
@@ -26,14 +157,219 @@ 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);
|
||||
}
|
||||
|
||||
HADevice::~HADevice()
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
void HADevice::setManufacturer(const char* manufacturer)
|
||||
{
|
||||
_serializer->set(AHATOFSTR(HADeviceManufacturerProperty), manufacturer);
|
||||
}
|
||||
|
||||
void HADevice::setModel(const char* model)
|
||||
{
|
||||
_serializer->set(AHATOFSTR(HADeviceModelProperty), model);
|
||||
}
|
||||
|
||||
void HADevice::setName(const char* name)
|
||||
{
|
||||
_serializer->set(AHATOFSTR(HANameProperty), name);
|
||||
}
|
||||
|
||||
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 (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;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
void HADevice::setPayloadNotAvailable(const char* payload)
|
||||
{
|
||||
_payloadNotAvailable = payload;
|
||||
}
|
||||
|
||||
void HADevice::setAvailability(bool online)
|
||||
@@ -45,154 +381,83 @@ void HADevice::setAvailability(bool online)
|
||||
bool HADevice::enableSharedAvailability()
|
||||
{
|
||||
if (_sharedAvailability) {
|
||||
return false;
|
||||
return true; // already enabled
|
||||
}
|
||||
|
||||
#if defined(ARDUINOHA_DEBUG)
|
||||
Serial.println(F("Enabling shared availability in the device"));
|
||||
#endif
|
||||
|
||||
const uint16_t& topicSize = DeviceTypeSerializer::calculateTopicLength(
|
||||
const uint16_t topicLength = HASerializer::calculateDataTopicLength(
|
||||
nullptr,
|
||||
nullptr,
|
||||
DeviceTypeSerializer::AvailabilityTopic
|
||||
AHATOFSTR(HAAvailabilityTopic)
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
if (topicLength == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
_availabilityTopic = (char*)malloc(topicSize);
|
||||
_sharedAvailability = true;
|
||||
_availabilityTopic = new char[topicLength];
|
||||
|
||||
DeviceTypeSerializer::generateTopic(
|
||||
if (HASerializer::generateDataTopic(
|
||||
_availabilityTopic,
|
||||
nullptr,
|
||||
nullptr,
|
||||
DeviceTypeSerializer::AvailabilityTopic
|
||||
);
|
||||
return true;
|
||||
AHATOFSTR(HAAvailabilityTopic)
|
||||
) > 0) {
|
||||
_sharedAvailability = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool HADevice::enableLastWill()
|
||||
void HADevice::enableLastWill()
|
||||
{
|
||||
HAMqtt* mqtt = HAMqtt::instance();
|
||||
if (mqtt == nullptr || _availabilityTopic == nullptr) {
|
||||
return false;
|
||||
if (!mqtt || !_availabilityTopic) {
|
||||
return;
|
||||
}
|
||||
|
||||
const char* lw = (_payloadNotAvailable && _payloadNotAvailable[0] != '\0')
|
||||
? _payloadNotAvailable
|
||||
: "offline";
|
||||
|
||||
mqtt->setLastWill(
|
||||
_availabilityTopic,
|
||||
DeviceTypeSerializer::Offline,
|
||||
false
|
||||
);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool HADevice::setUniqueId(const byte* uniqueId, const uint16_t& length)
|
||||
{
|
||||
if (_uniqueId != nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
_uniqueId = HAUtils::byteArrayToStr(uniqueId, length);
|
||||
return true;
|
||||
}
|
||||
|
||||
void HADevice::publishAvailability()
|
||||
{
|
||||
if (!_sharedAvailability) {
|
||||
return;
|
||||
}
|
||||
|
||||
HAMqtt* mqtt = HAMqtt::instance();
|
||||
if (mqtt == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
mqtt->publish(
|
||||
_availabilityTopic,
|
||||
(
|
||||
_available ?
|
||||
DeviceTypeSerializer::Online :
|
||||
DeviceTypeSerializer::Offline
|
||||
),
|
||||
lw,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
uint16_t HADevice::calculateSerializedLength() const
|
||||
void HADevice::publishAvailability() const
|
||||
{
|
||||
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
|
||||
HAMqtt* mqtt = HAMqtt::instance();
|
||||
if (!_availabilityTopic || !mqtt) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (_model != nullptr) {
|
||||
size += strlen(_model) + 9; // 9 - length of the JSON data for this field
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
uint16_t HADevice::serialize(char* dst) const
|
||||
{
|
||||
static const char QuotationSign[] PROGMEM = {"\""};
|
||||
|
||||
{
|
||||
static const char DataBefore[] PROGMEM = {"{\"ids\":\""};
|
||||
|
||||
strcpy_P(dst, DataBefore);
|
||||
strcat(dst, _uniqueId);
|
||||
strcat_P(dst, QuotationSign);
|
||||
}
|
||||
|
||||
if (_manufacturer != nullptr) {
|
||||
static const char DataBefore[] PROGMEM = {",\"mf\":\""};
|
||||
|
||||
strcat_P(dst, DataBefore);
|
||||
strcat(dst, _manufacturer);
|
||||
strcat_P(dst, QuotationSign);
|
||||
}
|
||||
|
||||
if (_model != nullptr) {
|
||||
static const char DataBefore[] PROGMEM = {",\"mdl\":\""};
|
||||
|
||||
strcat_P(dst, DataBefore);
|
||||
strcat(dst, _model);
|
||||
strcat_P(dst, QuotationSign);
|
||||
}
|
||||
|
||||
if (_name != nullptr) {
|
||||
static const char DataBefore[] PROGMEM = {",\"name\":\""};
|
||||
|
||||
strcat_P(dst, DataBefore);
|
||||
strcat(dst, _name);
|
||||
strcat_P(dst, QuotationSign);
|
||||
}
|
||||
|
||||
if (_softwareVersion != nullptr) {
|
||||
static const char DataBefore[] PROGMEM = {",\"sw\":\""};
|
||||
|
||||
strcat_P(dst, DataBefore);
|
||||
strcat(dst, _softwareVersion);
|
||||
strcat_P(dst, QuotationSign);
|
||||
}
|
||||
|
||||
{
|
||||
static const char Data[] PROGMEM = {"}"};
|
||||
strcat_P(dst, Data);
|
||||
}
|
||||
|
||||
return strlen(dst) + 1; // size with null terminator
|
||||
}
|
||||
|
||||
+201
-24
@@ -3,51 +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; }
|
||||
|
||||
inline void setModel(const char* model)
|
||||
{ _model = model; }
|
||||
|
||||
inline void setName(const char* name)
|
||||
{ _name = name; }
|
||||
|
||||
inline void setSoftwareVersion(const char* softwareVersion)
|
||||
{ _softwareVersion = softwareVersion; }
|
||||
/**
|
||||
* 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; }
|
||||
|
||||
/**
|
||||
* Returns true if the shared availability is enabled for the device.
|
||||
*/
|
||||
inline bool isSharedAvailabilityEnabled() const
|
||||
{ return _sharedAvailability; }
|
||||
|
||||
inline bool isOnline() const
|
||||
/**
|
||||
* Returns true if the extended unique IDs feature is enabled for the device.
|
||||
*/
|
||||
inline bool isExtendedUniqueIdsEnabled() const
|
||||
{ return _extendedUniqueIds; }
|
||||
|
||||
/**
|
||||
* 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; }
|
||||
|
||||
/**
|
||||
* 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();
|
||||
bool enableLastWill();
|
||||
bool setUniqueId(const byte* uniqueId, const uint16_t& length);
|
||||
void publishAvailability();
|
||||
uint16_t calculateSerializedLength() const;
|
||||
uint16_t serialize(char* dst) const;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
bool _sharedAvailability;
|
||||
|
||||
/// 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
|
||||
|
||||
+1329
-140
File diff suppressed because it is too large
Load Diff
+633
-56
@@ -1,144 +1,508 @@
|
||||
#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
|
||||
|
||||
class PubSubClient;
|
||||
class HADevice;
|
||||
class BaseDeviceType;
|
||||
#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 HADevice;
|
||||
class HABaseDeviceType;
|
||||
|
||||
#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,
|
||||
};
|
||||
|
||||
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
|
||||
};
|
||||
|
||||
/**
|
||||
* 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; }
|
||||
|
||||
HAMqtt(Client& netClient, HADevice& device);
|
||||
#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
|
||||
|
||||
/**
|
||||
* Sets prefix for Home Assistant discovery.
|
||||
* It needs to match prefix set in the HA admin panel.
|
||||
* 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; }
|
||||
|
||||
/**
|
||||
* 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 void setDataPrefix(const char* prefix)
|
||||
{ _dataPrefix = prefix; }
|
||||
|
||||
/**
|
||||
* 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; }
|
||||
|
||||
/**
|
||||
* Given callback will be called each time the connection with broker is acquired.
|
||||
* 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
|
||||
* @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; }
|
||||
|
||||
/**
|
||||
* Given callback will be called each time the library fails to connect to the broker.
|
||||
* Registers a new callback method that will be called each time the connection to the MQTT broker is lost.
|
||||
*
|
||||
* @param callback
|
||||
* @param callback Callback method.
|
||||
*/
|
||||
inline void onConnectionFailed(HAMQTT_CALLBACK(callback))
|
||||
{ _connectionFailedCallback = callback; }
|
||||
inline void onDisconnected(HAMQTT_CALLBACK(callback))
|
||||
{ _disconnectedCallback = callback; }
|
||||
|
||||
/**
|
||||
* Sets parameters of the connection to the MQTT broker.
|
||||
* 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 = HAMQTT_DEFAULT_PORT,
|
||||
const IPAddress serverIp,
|
||||
const uint16_t serverPort = HAMQTT_DEFAULT_PORT,
|
||||
const char* username = nullptr,
|
||||
const char* password = nullptr
|
||||
);
|
||||
|
||||
/**
|
||||
* 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 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
|
||||
);
|
||||
|
||||
/**
|
||||
* Connects to the MQTT broker using hostname.
|
||||
* 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 hostname Hostname of the MQTT broker.
|
||||
* @param serverHostname Hostname 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 char* hostname,
|
||||
const uint16_t& serverPort = HAMQTT_DEFAULT_PORT,
|
||||
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* hostname,
|
||||
const char* serverHostname,
|
||||
const char* username,
|
||||
const char* password
|
||||
);
|
||||
|
||||
/**
|
||||
* Closes connection with the MQTT broker.
|
||||
*
|
||||
* @param sendLastWill Set to true if you want to publish device unavailability before closing the connection.
|
||||
* Closes the MQTT connection.
|
||||
*/
|
||||
bool disconnect(bool sendLastWill = true);
|
||||
bool disconnect();
|
||||
|
||||
/**
|
||||
* ArduinoHA's ticker.
|
||||
* 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();
|
||||
|
||||
/**
|
||||
@@ -149,18 +513,18 @@ 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 last will message that will be produced when device disconnects from the broker.
|
||||
* 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 in the HADevice object instead.
|
||||
* please use enableLastWill() method from the HADevice class instead.
|
||||
*
|
||||
* @param lastWillTopic
|
||||
* @param lastWillMessage
|
||||
* @param lastWillRetain
|
||||
* @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,
|
||||
@@ -175,13 +539,61 @@ public:
|
||||
/**
|
||||
* 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;
|
||||
|
||||
/**
|
||||
@@ -195,21 +607,186 @@ private:
|
||||
*/
|
||||
void onConnectedLogic();
|
||||
|
||||
Client& _netClient;
|
||||
HADevice& _device;
|
||||
HAMQTT_CALLBACK(_connectedCallback);
|
||||
HAMQTT_CALLBACK(_connectionFailedCallback);
|
||||
bool _initialized;
|
||||
const char* _discoveryPrefix;
|
||||
bool publishDeviceDiscoveryPayload(HABaseDeviceType* removalType = nullptr);
|
||||
|
||||
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;
|
||||
|
||||
#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;
|
||||
#endif
|
||||
|
||||
/// 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
|
||||
|
||||
@@ -1,67 +0,0 @@
|
||||
#ifdef ARDUINO_ARCH_SAMD
|
||||
#include <avr/dtostrf.h>
|
||||
#endif
|
||||
|
||||
#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;
|
||||
}
|
||||
|
||||
void HAUtils::tempToStr(
|
||||
char* dst,
|
||||
const double& temp
|
||||
)
|
||||
{
|
||||
memset(dst, 0, sizeof(AHA_SERIALIZED_TEMP_SIZE));
|
||||
dtostrf(temp, 0, 2, dst);
|
||||
}
|
||||
|
||||
double HAUtils::strToTemp(
|
||||
const char* src
|
||||
)
|
||||
{
|
||||
return atof(src);
|
||||
}
|
||||
@@ -1,33 +0,0 @@
|
||||
#ifndef AHA_HAUTILS_H
|
||||
#define AHA_HAUTILS_H
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
#define AHA_SERIALIZED_TEMP_SIZE 8
|
||||
|
||||
class HAUtils
|
||||
{
|
||||
public:
|
||||
static bool endsWith(
|
||||
const char* str,
|
||||
const char* suffix
|
||||
);
|
||||
static void byteArrayToStr(
|
||||
char* dst,
|
||||
const byte* src,
|
||||
const uint16_t& length
|
||||
);
|
||||
static char* byteArrayToStr(
|
||||
const byte* src,
|
||||
const uint16_t& length
|
||||
);
|
||||
static void tempToStr(
|
||||
char* dst,
|
||||
const double& temp
|
||||
);
|
||||
static double strToTemp(
|
||||
const char* src
|
||||
);
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,159 +0,0 @@
|
||||
#include "BaseDeviceType.h"
|
||||
#include "../HAMqtt.h"
|
||||
#include "../HADevice.h"
|
||||
#include "../HAUtils.h"
|
||||
|
||||
BaseDeviceType::BaseDeviceType(
|
||||
const char* componentName,
|
||||
const char* name
|
||||
) :
|
||||
_componentName(componentName),
|
||||
_name(name),
|
||||
_availability(AvailabilityDefault)
|
||||
{
|
||||
mqtt()->addDeviceType(this);
|
||||
}
|
||||
|
||||
BaseDeviceType::~BaseDeviceType()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void BaseDeviceType::setAvailability(bool online)
|
||||
{
|
||||
_availability = (online ? AvailabilityOnline : AvailabilityOffline);
|
||||
publishAvailability();
|
||||
}
|
||||
|
||||
HAMqtt* BaseDeviceType::mqtt() const
|
||||
{
|
||||
return HAMqtt::instance();
|
||||
}
|
||||
|
||||
void BaseDeviceType::onMqttMessage(
|
||||
const char* topic,
|
||||
const uint8_t* payload,
|
||||
const uint16_t& length
|
||||
)
|
||||
{
|
||||
(void)topic;
|
||||
(void)payload;
|
||||
(void)length;
|
||||
}
|
||||
|
||||
void BaseDeviceType::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(
|
||||
componentName(),
|
||||
name(),
|
||||
DeviceTypeSerializer::ConfigTopic
|
||||
);
|
||||
const uint16_t& dataLength = calculateSerializedLength(serializedDevice);
|
||||
|
||||
if (topicLength == 0 || dataLength == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
char topic[topicLength];
|
||||
DeviceTypeSerializer::generateTopic(
|
||||
topic,
|
||||
componentName(),
|
||||
name(),
|
||||
DeviceTypeSerializer::ConfigTopic
|
||||
);
|
||||
|
||||
if (strlen(topic) == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (mqtt()->beginPublish(topic, dataLength, true)) {
|
||||
writeSerializedData(serializedDevice);
|
||||
mqtt()->endPublish();
|
||||
}
|
||||
}
|
||||
|
||||
void BaseDeviceType::publishAvailability()
|
||||
{
|
||||
const HADevice* device = HAMqtt::instance()->getDevice();
|
||||
if (device == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (_availability == AvailabilityDefault ||
|
||||
!mqtt()->isConnected() ||
|
||||
strlen(_name) == 0 ||
|
||||
strlen(_componentName) == 0 ||
|
||||
device->isSharedAvailabilityEnabled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const uint16_t& topicSize = DeviceTypeSerializer::calculateTopicLength(
|
||||
_componentName,
|
||||
_name,
|
||||
DeviceTypeSerializer::AvailabilityTopic
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
char topic[topicSize];
|
||||
DeviceTypeSerializer::generateTopic(
|
||||
topic,
|
||||
_componentName,
|
||||
_name,
|
||||
DeviceTypeSerializer::AvailabilityTopic
|
||||
);
|
||||
|
||||
if (strlen(topic) == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
mqtt()->publish(
|
||||
topic,
|
||||
(
|
||||
_availability == AvailabilityOnline ?
|
||||
DeviceTypeSerializer::Online :
|
||||
DeviceTypeSerializer::Offline
|
||||
),
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
bool BaseDeviceType::isMyTopic(const char* topic, const char* expectedTopic)
|
||||
{
|
||||
if (topic == nullptr || expectedTopic == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (strlen(name()) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
static const char Slash[] PROGMEM = {"/"};
|
||||
|
||||
// name + cmd topic + two slashes + null terminator
|
||||
uint8_t suffixLength = strlen(name()) + strlen(expectedTopic) + 3;
|
||||
char suffix[suffixLength];
|
||||
|
||||
strcpy_P(suffix, Slash);
|
||||
strcat(suffix, name());
|
||||
strcat_P(suffix, Slash);
|
||||
strcat(suffix, expectedTopic);
|
||||
|
||||
return HAUtils::endsWith(topic, suffix);
|
||||
}
|
||||
@@ -1,65 +0,0 @@
|
||||
#ifndef AHA_BASEDEVICETYPE_H
|
||||
#define AHA_BASEDEVICETYPE_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
#include "../ArduinoHADefines.h"
|
||||
#include "DeviceTypeSerializer.h"
|
||||
|
||||
class HAMqtt;
|
||||
|
||||
class BaseDeviceType
|
||||
{
|
||||
public:
|
||||
BaseDeviceType(
|
||||
const char* componentName,
|
||||
const char* name
|
||||
);
|
||||
virtual ~BaseDeviceType();
|
||||
|
||||
inline const char* name() const
|
||||
{ return _name; }
|
||||
|
||||
inline const char* componentName() const
|
||||
{ return _componentName; }
|
||||
|
||||
inline bool isAvailabilityConfigured() const
|
||||
{ return (_availability != AvailabilityDefault); }
|
||||
|
||||
inline bool isOnline() const
|
||||
{ return (_availability == AvailabilityOnline); }
|
||||
|
||||
virtual void setAvailability(bool online);
|
||||
|
||||
protected:
|
||||
HAMqtt* mqtt() const;
|
||||
|
||||
virtual void onMqttConnected() = 0;
|
||||
virtual void onMqttMessage(
|
||||
const char* topic,
|
||||
const uint8_t* payload,
|
||||
const uint16_t& length
|
||||
);
|
||||
|
||||
virtual void publishConfig();
|
||||
virtual void publishAvailability();
|
||||
virtual bool isMyTopic(const char* topic, const char* expectedTopic);
|
||||
virtual uint16_t calculateSerializedLength(const char* serializedDevice) const = 0;
|
||||
virtual bool writeSerializedData(const char* serializedDevice) const = 0;
|
||||
|
||||
const char* const _componentName;
|
||||
const char* const _name;
|
||||
|
||||
private:
|
||||
enum Availability {
|
||||
AvailabilityDefault = 0,
|
||||
AvailabilityOnline,
|
||||
AvailabilityOffline
|
||||
};
|
||||
|
||||
Availability _availability;
|
||||
|
||||
friend class HAMqtt;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,407 +0,0 @@
|
||||
#include <Arduino.h>
|
||||
|
||||
#include "DeviceTypeSerializer.h"
|
||||
#include "BaseDeviceType.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 char* component,
|
||||
const char* objectId,
|
||||
const char* suffix,
|
||||
bool includeNullTerminator
|
||||
)
|
||||
{
|
||||
const char* prefix = HAMqtt::instance()->getDiscoveryPrefix();
|
||||
if (prefix == nullptr) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint16_t size =
|
||||
strlen(prefix) + 1 + // prefix with slash
|
||||
strlen(suffix);
|
||||
|
||||
if (component != nullptr) {
|
||||
size += strlen(component) + 1; // component with slash
|
||||
}
|
||||
|
||||
if (HAMqtt::instance()->getDevice() != nullptr) {
|
||||
size += strlen(HAMqtt::instance()->getDevice()->getUniqueId()) + 1; // device ID with slash
|
||||
}
|
||||
|
||||
if (objectId != nullptr) {
|
||||
size += strlen(objectId) + 1; // with slash
|
||||
}
|
||||
|
||||
if (includeNullTerminator) {
|
||||
size += 1;
|
||||
}
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
uint16_t DeviceTypeSerializer::generateTopic(
|
||||
char* output,
|
||||
const char* component,
|
||||
const char* objectId,
|
||||
const char* suffix
|
||||
)
|
||||
{
|
||||
const char* prefix = HAMqtt::instance()->getDiscoveryPrefix();
|
||||
if (prefix == nullptr) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
strcpy(output, prefix);
|
||||
strcat_P(output, CharSlash);
|
||||
|
||||
if (component != nullptr) {
|
||||
strcat(output, component);
|
||||
strcat_P(output, CharSlash);
|
||||
}
|
||||
|
||||
if (HAMqtt::instance()->getDevice() != nullptr) {
|
||||
strcat(output, HAMqtt::instance()->getDevice()->getUniqueId());
|
||||
strcat_P(output, CharSlash);
|
||||
}
|
||||
|
||||
if (objectId != nullptr) {
|
||||
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 char* name
|
||||
)
|
||||
{
|
||||
HADevice const* device = HAMqtt::instance()->getDevice();
|
||||
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 BaseDeviceType* const dt
|
||||
)
|
||||
{
|
||||
const HADevice* device = HAMqtt::instance()->getDevice();
|
||||
if (device == nullptr) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const bool& sharedAvailability = device->isSharedAvailabilityEnabled();
|
||||
if (!sharedAvailability && !dt->isAvailabilityConfigured()) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const uint16_t& availabilityTopicLength = calculateTopicLength(
|
||||
(sharedAvailability ? nullptr : dt->componentName()),
|
||||
(sharedAvailability ? nullptr : dt->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::calculateRetainFieldSize(bool retain)
|
||||
{
|
||||
if (!retain) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Field format: ,"ret":true
|
||||
return 11;
|
||||
}
|
||||
|
||||
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()
|
||||
{
|
||||
static const char Data[] PROGMEM = {"{"};
|
||||
HAMqtt::instance()->writePayload_P(Data);
|
||||
}
|
||||
|
||||
void DeviceTypeSerializer::mqttWriteEndJson()
|
||||
{
|
||||
static const char Data[] PROGMEM = {"}"};
|
||||
HAMqtt::instance()->writePayload_P(Data);
|
||||
}
|
||||
|
||||
void DeviceTypeSerializer::mqttWriteConstCharField(
|
||||
const char* prefix,
|
||||
const char* value,
|
||||
bool quoteSuffix
|
||||
)
|
||||
{
|
||||
if (prefix == nullptr || value == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
HAMqtt::instance()->writePayload_P(prefix);
|
||||
HAMqtt::instance()->writePayload(value, strlen(value));
|
||||
|
||||
if (quoteSuffix) {
|
||||
HAMqtt::instance()->writePayload_P(CharQuotation);
|
||||
}
|
||||
}
|
||||
|
||||
void DeviceTypeSerializer::mqttWriteNameField(const char* name)
|
||||
{
|
||||
if (name == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
static const char Prefix[] PROGMEM = {",\"name\":\""};
|
||||
mqttWriteConstCharField(Prefix, name);
|
||||
}
|
||||
|
||||
void DeviceTypeSerializer::mqttWriteUniqueIdField(
|
||||
const char* name
|
||||
)
|
||||
{
|
||||
if (name == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
HADevice const* device = HAMqtt::instance()->getDevice();
|
||||
if (device == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
static const char Prefix[] PROGMEM = {",\"uniq_id\":\""};
|
||||
|
||||
uint8_t uniqueIdLength = strlen(name) + strlen(device->getUniqueId()) + 2; // underscore and null temrinator
|
||||
char uniqueId[uniqueIdLength];
|
||||
strcpy(uniqueId, name);
|
||||
strcat_P(uniqueId, CharUnderscore);
|
||||
strcat(uniqueId, device->getUniqueId());
|
||||
|
||||
mqttWriteConstCharField(Prefix, uniqueId);
|
||||
}
|
||||
|
||||
void DeviceTypeSerializer::mqttWriteAvailabilityField(
|
||||
const BaseDeviceType* const dt
|
||||
)
|
||||
{
|
||||
const HADevice* device = HAMqtt::instance()->getDevice();
|
||||
if (device == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
const bool& sharedAvailability = device->isSharedAvailabilityEnabled();
|
||||
if (!sharedAvailability && !dt->isAvailabilityConfigured()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const uint16_t& topicSize = calculateTopicLength(
|
||||
(sharedAvailability ? nullptr : dt->componentName()),
|
||||
(sharedAvailability ? nullptr : dt->name()),
|
||||
AvailabilityTopic
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
char availabilityTopic[topicSize];
|
||||
generateTopic(
|
||||
availabilityTopic,
|
||||
(sharedAvailability ? nullptr : dt->componentName()),
|
||||
(sharedAvailability ? nullptr : dt->name()),
|
||||
AvailabilityTopic
|
||||
);
|
||||
|
||||
if (strlen(availabilityTopic) == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
static const char Prefix[] PROGMEM = {",\"avty_t\":\""};
|
||||
mqttWriteConstCharField(Prefix, availabilityTopic);
|
||||
}
|
||||
|
||||
void DeviceTypeSerializer::mqttWriteRetainField(
|
||||
bool retain
|
||||
)
|
||||
{
|
||||
if (!retain) {
|
||||
return;
|
||||
}
|
||||
|
||||
static const char Prefix[] PROGMEM = {",\"ret\":"};
|
||||
mqttWriteConstCharField(
|
||||
Prefix,
|
||||
"true",
|
||||
false
|
||||
);
|
||||
}
|
||||
|
||||
void DeviceTypeSerializer::mqttWriteDeviceField(
|
||||
const char* serializedDevice
|
||||
)
|
||||
{
|
||||
if (serializedDevice == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
static const char Data[] PROGMEM = {",\"dev\":"};
|
||||
|
||||
HAMqtt::instance()->writePayload_P(Data);
|
||||
HAMqtt::instance()->writePayload(serializedDevice, strlen(serializedDevice));
|
||||
}
|
||||
|
||||
bool DeviceTypeSerializer::mqttWriteTopicField(
|
||||
const BaseDeviceType* const dt,
|
||||
const char* jsonPrefix,
|
||||
const char* topicSuffix
|
||||
)
|
||||
{
|
||||
if (jsonPrefix == nullptr || topicSuffix == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint16_t& topicSize = DeviceTypeSerializer::calculateTopicLength(
|
||||
dt->componentName(),
|
||||
dt->name() ,
|
||||
topicSuffix
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char topic[topicSize];
|
||||
DeviceTypeSerializer::generateTopic(
|
||||
topic,
|
||||
dt->componentName(),
|
||||
dt->name(),
|
||||
topicSuffix
|
||||
);
|
||||
|
||||
if (strlen(topic) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
DeviceTypeSerializer::mqttWriteConstCharField(jsonPrefix, topic);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool DeviceTypeSerializer::mqttPublishMessage(
|
||||
const BaseDeviceType* const dt,
|
||||
const char* topicSuffix,
|
||||
const char* data
|
||||
)
|
||||
{
|
||||
if (topicSuffix == nullptr || data == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint16_t& topicSize = calculateTopicLength(
|
||||
dt->componentName(),
|
||||
dt->name(),
|
||||
topicSuffix
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char topic[topicSize];
|
||||
generateTopic(
|
||||
topic,
|
||||
dt->componentName(),
|
||||
dt->name(),
|
||||
topicSuffix
|
||||
);
|
||||
|
||||
if (strlen(topic) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return HAMqtt::instance()->publish(
|
||||
topic,
|
||||
data,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
bool DeviceTypeSerializer::mqttSubscribeTopic(
|
||||
const BaseDeviceType* const dt,
|
||||
const char* topicSuffix
|
||||
)
|
||||
{
|
||||
const uint16_t& topicSize = calculateTopicLength(
|
||||
dt->componentName(),
|
||||
dt->name(),
|
||||
topicSuffix
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char topic[topicSize];
|
||||
generateTopic(
|
||||
topic,
|
||||
dt->componentName(),
|
||||
dt->name(),
|
||||
topicSuffix
|
||||
);
|
||||
|
||||
if (strlen(topic) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return HAMqtt::instance()->subscribe(topic);
|
||||
}
|
||||
@@ -1,111 +0,0 @@
|
||||
#ifndef AHA_DEVICETYPESERIALIZER_H
|
||||
#define AHA_DEVICETYPESERIALIZER_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
class HADevice;
|
||||
class BaseDeviceType;
|
||||
|
||||
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]/[deviceId]/[objectId]/[suffix]
|
||||
*
|
||||
* @param component
|
||||
* @param objectId
|
||||
* @param suffix
|
||||
* @param includeNullTerminator
|
||||
*/
|
||||
static uint16_t calculateTopicLength(
|
||||
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]/[deviceId]/[objectId]/[suffix]
|
||||
*
|
||||
* @param output
|
||||
* @param component
|
||||
* @param objectId
|
||||
* @param suffix
|
||||
* @param includeNullTerminator
|
||||
*/
|
||||
static uint16_t generateTopic(
|
||||
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 char* name
|
||||
);
|
||||
static uint16_t calculateAvailabilityFieldSize(
|
||||
const BaseDeviceType* const dt
|
||||
);
|
||||
static uint16_t calculateRetainFieldSize(
|
||||
bool retain
|
||||
);
|
||||
static uint16_t calculateDeviceFieldSize(
|
||||
const char* serializedDevice
|
||||
);
|
||||
|
||||
static void mqttWriteBeginningJson();
|
||||
static void mqttWriteEndJson();
|
||||
static void mqttWriteConstCharField(
|
||||
const char* prefix,
|
||||
const char* value,
|
||||
bool quoteSuffix = true
|
||||
);
|
||||
static void mqttWriteNameField(
|
||||
const char* name
|
||||
);
|
||||
static void mqttWriteUniqueIdField(
|
||||
const char* name
|
||||
);
|
||||
static void mqttWriteAvailabilityField(
|
||||
const BaseDeviceType* const dt
|
||||
);
|
||||
static void mqttWriteRetainField(
|
||||
bool retain
|
||||
);
|
||||
static void mqttWriteDeviceField(
|
||||
const char* serializedDevice
|
||||
);
|
||||
static bool mqttWriteTopicField(
|
||||
const BaseDeviceType* const dt,
|
||||
const char* jsonPrefix,
|
||||
const char* topicSuffix
|
||||
);
|
||||
static bool mqttPublishMessage(
|
||||
const BaseDeviceType* const dt,
|
||||
const char* topicSuffix,
|
||||
const char* data
|
||||
);
|
||||
static bool mqttSubscribeTopic(
|
||||
const BaseDeviceType* const dt,
|
||||
const char* topicSuffix
|
||||
);
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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
|
||||
+188
-158
@@ -1,194 +1,224 @@
|
||||
#include "HABinarySensor.h"
|
||||
#ifdef ARDUINOHA_BINARY_SENSOR
|
||||
#ifndef EX_ARDUINOHA_BINARY_SENSOR
|
||||
|
||||
#include "../ArduinoHADefines.h"
|
||||
#include "../HAMqtt.h"
|
||||
#include "../HADevice.h"
|
||||
#include "../utils/HADictionary.h"
|
||||
#include "../utils/HASerializer.h"
|
||||
|
||||
HABinarySensor::HABinarySensor(
|
||||
const char* name,
|
||||
bool initialState
|
||||
) :
|
||||
BaseDeviceType("binary_sensor", name),
|
||||
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,
|
||||
bool initialState,
|
||||
HAMqtt& mqtt
|
||||
) :
|
||||
HABinarySensor(name, initialState)
|
||||
bool HABinarySensor::setState(const bool state, const bool force)
|
||||
{
|
||||
(void)mqtt;
|
||||
if (!force && state == _currentState) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool published = publishState(state);
|
||||
_currentState = state;
|
||||
return published;
|
||||
}
|
||||
|
||||
HABinarySensor::HABinarySensor(
|
||||
const char* name,
|
||||
const char* deviceClass,
|
||||
bool initialState
|
||||
) :
|
||||
BaseDeviceType("binary_sensor", name),
|
||||
_class(deviceClass),
|
||||
_currentState(initialState)
|
||||
void HABinarySensor::setExpireAfter(uint16_t expireAfter)
|
||||
{
|
||||
|
||||
if (expireAfter > 0) {
|
||||
_expireAfter.setBaseValue(expireAfter);
|
||||
} else {
|
||||
_expireAfter.reset();
|
||||
}
|
||||
}
|
||||
|
||||
HABinarySensor::HABinarySensor(
|
||||
const char* name,
|
||||
const char* deviceClass,
|
||||
bool initialState,
|
||||
HAMqtt& mqtt
|
||||
) :
|
||||
HABinarySensor(name, deviceClass, initialState)
|
||||
void HABinarySensor::setOffDelay(uint16_t seconds)
|
||||
{
|
||||
(void)mqtt;
|
||||
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 (publishState(state)) {
|
||||
_currentState = state;
|
||||
return true;
|
||||
if (nonEmptyString(_payloadOff)) {
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
_payloadOff,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool HABinarySensor::publishState(bool state)
|
||||
{
|
||||
if (strlen(name()) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint16_t& topicSize = DeviceTypeSerializer::calculateTopicLength(
|
||||
componentName(),
|
||||
name(),
|
||||
DeviceTypeSerializer::StateTopic
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char topic[topicSize];
|
||||
DeviceTypeSerializer::generateTopic(
|
||||
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(name());
|
||||
size += DeviceTypeSerializer::calculateDeviceFieldSize(serializedDevice);
|
||||
size += DeviceTypeSerializer::calculateAvailabilityFieldSize(this);
|
||||
|
||||
// state topic
|
||||
{
|
||||
const uint16_t& topicLength = DeviceTypeSerializer::calculateTopicLength(
|
||||
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();
|
||||
|
||||
// state topic
|
||||
{
|
||||
static const char Prefix[] PROGMEM = {"\"stat_t\":\""};
|
||||
DeviceTypeSerializer::mqttWriteTopicField(
|
||||
this,
|
||||
Prefix,
|
||||
DeviceTypeSerializer::StateTopic
|
||||
);
|
||||
}
|
||||
|
||||
// device class
|
||||
if (_class != nullptr) {
|
||||
static const char Prefix[] PROGMEM = {",\"dev_cla\":\""};
|
||||
DeviceTypeSerializer::mqttWriteConstCharField(Prefix, _class);
|
||||
}
|
||||
|
||||
DeviceTypeSerializer::mqttWriteNameField(name());
|
||||
DeviceTypeSerializer::mqttWriteUniqueIdField(name());
|
||||
DeviceTypeSerializer::mqttWriteAvailabilityField(this);
|
||||
DeviceTypeSerializer::mqttWriteDeviceField(serializedDevice);
|
||||
DeviceTypeSerializer::mqttWriteEndJson();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,80 +1,125 @@
|
||||
#ifndef AHA_HABINARYSENSOR_H
|
||||
#define AHA_HABINARYSENSOR_H
|
||||
|
||||
#include "BaseDeviceType.h"
|
||||
#include "HABaseDeviceType.h"
|
||||
#include "../utils/HANumeric.h"
|
||||
|
||||
#ifdef ARDUINOHA_BINARY_SENSOR
|
||||
#ifndef EX_ARDUINOHA_BINARY_SENSOR
|
||||
|
||||
class HABinarySensor : public BaseDeviceType
|
||||
/**
|
||||
* 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. Recommended 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
|
||||
);
|
||||
HABinarySensor(
|
||||
const char* name,
|
||||
bool initialState,
|
||||
HAMqtt& mqtt
|
||||
); // legacy constructor
|
||||
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
|
||||
);
|
||||
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:
|
||||
bool publishState(bool state);
|
||||
uint16_t calculateSerializedLength(const char* serializedDevice) const override;
|
||||
bool writeSerializedData(const char* serializedDevice) const override;
|
||||
/**
|
||||
* 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
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
+241
-368
@@ -1,418 +1,291 @@
|
||||
#include "HAFan.h"
|
||||
#ifdef ARDUINOHA_FAN
|
||||
#ifndef EX_ARDUINOHA_FAN
|
||||
|
||||
#include "../HAMqtt.h"
|
||||
#include "../HADevice.h"
|
||||
#include "../utils/HAUtils.h"
|
||||
#include "../utils/HASerializer.h"
|
||||
|
||||
const char* HAFan::SpeedCommandTopic = {"sct"};
|
||||
const char* HAFan::SpeedStateTopic = {"sst"};
|
||||
|
||||
static const char OffStr[] PROGMEM = {"off"};
|
||||
static const char LowStr[] PROGMEM = {"low"};
|
||||
static const char MediumStr[] PROGMEM = {"medium"};
|
||||
static const char HighStr[] PROGMEM = {"high"};
|
||||
|
||||
HAFan::HAFan(const char* uniqueId, uint8_t features) :
|
||||
BaseDeviceType("fan", uniqueId),
|
||||
HAFan::HAFan(const char* uniqueId, const uint8_t features) :
|
||||
HABaseDeviceType(AHATOFSTR(HAComponentFan), uniqueId),
|
||||
_features(features),
|
||||
_speeds(OffSpeed | LowSpeed | MediumSpeed | HighSpeed),
|
||||
_icon(nullptr),
|
||||
_retain(false),
|
||||
_optimistic(false),
|
||||
_speedRangeMax(),
|
||||
_speedRangeMin(),
|
||||
_currentState(false),
|
||||
_currentSpeed(0),
|
||||
_stateCallback(nullptr),
|
||||
_currentSpeed(OffSpeed),
|
||||
_speedCallback(nullptr),
|
||||
_label(nullptr),
|
||||
_retain(false)
|
||||
_speedCallback(nullptr)
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
, _stateStdCallback(),
|
||||
_speedStdCallback()
|
||||
#endif
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
HAFan::HAFan(const char* uniqueId, uint8_t features, HAMqtt& mqtt) :
|
||||
HAFan(uniqueId, features)
|
||||
bool HAFan::setState(const bool state, const bool force)
|
||||
{
|
||||
(void)mqtt;
|
||||
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 (strlen(name()) == 0) {
|
||||
if (!uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
publishConfig();
|
||||
publishAvailability();
|
||||
|
||||
DeviceTypeSerializer::mqttSubscribeTopic(
|
||||
this,
|
||||
DeviceTypeSerializer::CommandTopic
|
||||
);
|
||||
|
||||
if (_features & SpeedsFeature) {
|
||||
DeviceTypeSerializer::mqttSubscribeTopic(
|
||||
this,
|
||||
SpeedCommandTopic
|
||||
);
|
||||
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
|
||||
const uint16_t length
|
||||
)
|
||||
{
|
||||
(void)payload;
|
||||
|
||||
if (isMyTopic(topic, DeviceTypeSerializer::CommandTopic)) {
|
||||
bool state = (length == strlen(DeviceTypeSerializer::StateOn));
|
||||
setState(state, true);
|
||||
} else if (isMyTopic(topic, SpeedCommandTopic)) {
|
||||
char speed[length + 1];
|
||||
memset(speed, 0, sizeof(speed));
|
||||
memcpy(speed, payload, length);
|
||||
|
||||
setSpeedFromStr(speed);
|
||||
if (HASerializer::compareDataTopics(
|
||||
topic,
|
||||
uniqueId(),
|
||||
AHATOFSTR(HACommandTopic)
|
||||
)) {
|
||||
handleStateCommand(payload, length);
|
||||
} else if (HASerializer::compareDataTopics(
|
||||
topic,
|
||||
uniqueId(),
|
||||
AHATOFSTR(HAPercentageCommandTopic)
|
||||
)) {
|
||||
handleSpeedCommand(payload, length);
|
||||
}
|
||||
}
|
||||
|
||||
bool HAFan::setState(bool state, bool force)
|
||||
bool HAFan::publishState(const bool state)
|
||||
{
|
||||
if (!force && _currentState == state) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (publishState(state)) {
|
||||
_currentState = state;
|
||||
|
||||
if (_stateCallback) {
|
||||
_stateCallback(state);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
AHATOFSTR(state ? HAStateOn : HAStateOff),
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
bool HAFan::setSpeed(Speed speed)
|
||||
bool HAFan::publishSpeed(const uint16_t speed)
|
||||
{
|
||||
if (speed == UnknownSpeed) {
|
||||
if (!(_features & SpeedsFeature)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (publishSpeed(speed)) {
|
||||
_currentSpeed = speed;
|
||||
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(_currentSpeed);
|
||||
_speedCallback(speed, this);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool HAFan::setSpeedFromStr(const char* speed)
|
||||
{
|
||||
if (strcmp_P(speed, OffStr) == 0) {
|
||||
return setSpeed(OffSpeed);
|
||||
} else if (strcmp_P(speed, LowStr) == 0) {
|
||||
return setSpeed(LowSpeed);
|
||||
} else if (strcmp_P(speed, MediumStr) == 0) {
|
||||
return setSpeed(MediumSpeed);
|
||||
} else if (strcmp_P(speed, HighStr) == 0) {
|
||||
return setSpeed(HighSpeed);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool HAFan::publishState(bool state)
|
||||
{
|
||||
if (strlen(name()) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return DeviceTypeSerializer::mqttPublishMessage(
|
||||
this,
|
||||
DeviceTypeSerializer::StateTopic,
|
||||
(
|
||||
state ?
|
||||
DeviceTypeSerializer::StateOn :
|
||||
DeviceTypeSerializer::StateOff
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
bool HAFan::publishSpeed(Speed speed)
|
||||
{
|
||||
if (strlen(name()) == 0 || speed == UnknownSpeed) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char speedStr[7];
|
||||
switch (speed) {
|
||||
case OffSpeed:
|
||||
strcpy_P(speedStr, OffStr);
|
||||
break;
|
||||
|
||||
case LowSpeed:
|
||||
strcpy_P(speedStr, LowStr);
|
||||
break;
|
||||
|
||||
case MediumSpeed:
|
||||
strcpy_P(speedStr, MediumStr);
|
||||
break;
|
||||
|
||||
case HighSpeed:
|
||||
strcpy_P(speedStr, HighStr);
|
||||
break;
|
||||
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
|
||||
return DeviceTypeSerializer::mqttPublishMessage(
|
||||
this,
|
||||
SpeedStateTopic,
|
||||
speedStr
|
||||
);
|
||||
}
|
||||
|
||||
uint16_t HAFan::calculateSerializedLength(const char* serializedDevice) const
|
||||
{
|
||||
if (serializedDevice == nullptr) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint16_t size = 0;
|
||||
size += DeviceTypeSerializer::calculateBaseJsonDataSize();
|
||||
size += DeviceTypeSerializer::calculateUniqueIdFieldSize(name());
|
||||
size += DeviceTypeSerializer::calculateDeviceFieldSize(serializedDevice);
|
||||
size += DeviceTypeSerializer::calculateAvailabilityFieldSize(this);
|
||||
size += DeviceTypeSerializer::calculateNameFieldSize(_label);
|
||||
size += DeviceTypeSerializer::calculateRetainFieldSize(_retain);
|
||||
|
||||
// command topic
|
||||
{
|
||||
const uint16_t& topicLength = DeviceTypeSerializer::calculateTopicLength(
|
||||
componentName(),
|
||||
name(),
|
||||
DeviceTypeSerializer::CommandTopic,
|
||||
false
|
||||
);
|
||||
|
||||
if (topicLength == 0) {
|
||||
return 0;
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
if (_speedStdCallback) {
|
||||
_speedStdCallback(speed, this);
|
||||
}
|
||||
|
||||
// Field format: "cmd_t":"[TOPIC]"
|
||||
size += topicLength + 10; // 10 - length of the JSON decorators for this field
|
||||
#endif
|
||||
}
|
||||
|
||||
// state topic
|
||||
{
|
||||
const uint16_t& topicLength = DeviceTypeSerializer::calculateTopicLength(
|
||||
componentName(),
|
||||
name(),
|
||||
DeviceTypeSerializer::StateTopic,
|
||||
false
|
||||
);
|
||||
|
||||
if (topicLength == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Field format: ,"stat_t":"[TOPIC]"
|
||||
size += topicLength + 12; // 12 - length of the JSON decorators for this field
|
||||
}
|
||||
|
||||
// speeds
|
||||
if (_features & SpeedsFeature) {
|
||||
// command topic
|
||||
{
|
||||
const uint16_t& topicLength = DeviceTypeSerializer::calculateTopicLength(
|
||||
componentName(),
|
||||
name(),
|
||||
SpeedCommandTopic,
|
||||
false
|
||||
);
|
||||
|
||||
if (topicLength == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Field format: ,"spd_cmd_t":"[TOPIC]"
|
||||
size += topicLength + 15; // 15 - length of the JSON decorators for this field
|
||||
}
|
||||
|
||||
// state topic
|
||||
{
|
||||
const uint16_t& topicLength = DeviceTypeSerializer::calculateTopicLength(
|
||||
componentName(),
|
||||
name(),
|
||||
SpeedStateTopic,
|
||||
false
|
||||
);
|
||||
|
||||
if (topicLength == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Field format: ,"spd_stat_t":"[TOPIC]"
|
||||
size += topicLength + 16; // 16 - length of the JSON decorators for this field
|
||||
}
|
||||
|
||||
// speeds list
|
||||
// Format: ,"spds":[SPEEDS]
|
||||
size += calculateSpeedsLength() + 8; // 8 - length of the JSON decorators for this field
|
||||
}
|
||||
|
||||
return size; // exludes null terminator
|
||||
}
|
||||
|
||||
uint16_t HAFan::calculateSpeedsLength() const
|
||||
{
|
||||
uint16_t length = 2; // opening and closing bracket
|
||||
|
||||
if (_speeds & OffSpeed) {
|
||||
// escape + comma
|
||||
length += 3 + strlen_P(OffStr);
|
||||
}
|
||||
|
||||
if (_speeds & LowSpeed) {
|
||||
// escape + comma
|
||||
length += 3 + strlen_P(LowStr);
|
||||
}
|
||||
|
||||
if (_speeds & MediumSpeed) {
|
||||
// escape + comma
|
||||
length += 3 + strlen_P(MediumStr);
|
||||
}
|
||||
|
||||
if (_speeds & HighSpeed) {
|
||||
// escape + comma
|
||||
length += 3 + strlen_P(HighStr);
|
||||
}
|
||||
|
||||
if (length > 2) {
|
||||
length--; // remove trailing comma
|
||||
}
|
||||
|
||||
return length; // excludes null terminator
|
||||
}
|
||||
|
||||
bool HAFan::writeSerializedData(const char* serializedDevice) const
|
||||
{
|
||||
if (serializedDevice == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
DeviceTypeSerializer::mqttWriteBeginningJson();
|
||||
|
||||
// command topic
|
||||
{
|
||||
static const char Prefix[] PROGMEM = {"\"cmd_t\":\""};
|
||||
DeviceTypeSerializer::mqttWriteTopicField(
|
||||
this,
|
||||
Prefix,
|
||||
DeviceTypeSerializer::CommandTopic
|
||||
);
|
||||
}
|
||||
|
||||
// state topic
|
||||
{
|
||||
static const char Prefix[] PROGMEM = {",\"stat_t\":\""};
|
||||
DeviceTypeSerializer::mqttWriteTopicField(
|
||||
this,
|
||||
Prefix,
|
||||
DeviceTypeSerializer::StateTopic
|
||||
);
|
||||
}
|
||||
|
||||
// speeds
|
||||
if (_features & SpeedsFeature) {
|
||||
// command topic
|
||||
{
|
||||
static const char Prefix[] PROGMEM = {",\"spd_cmd_t\":\""};
|
||||
DeviceTypeSerializer::mqttWriteTopicField(
|
||||
this,
|
||||
Prefix,
|
||||
SpeedCommandTopic
|
||||
);
|
||||
}
|
||||
|
||||
// state topic
|
||||
{
|
||||
static const char Prefix[] PROGMEM = {",\"spd_stat_t\":\""};
|
||||
DeviceTypeSerializer::mqttWriteTopicField(
|
||||
this,
|
||||
Prefix,
|
||||
SpeedStateTopic
|
||||
);
|
||||
}
|
||||
|
||||
// supported speeds
|
||||
{
|
||||
static const char CharQuotation[] PROGMEM = {"\""};
|
||||
static const char CharQuotationComma[] PROGMEM = {"\","};
|
||||
static const char Prefix[] PROGMEM = {",\"spds\":"};
|
||||
|
||||
char speedStr[calculateSpeedsLength() + 1]; // plus null terminator
|
||||
memset(speedStr, 0, sizeof(speedStr));
|
||||
strcpy(speedStr, "[");
|
||||
|
||||
if (_speeds != 0) {
|
||||
if (_speeds & OffSpeed) {
|
||||
strcat_P(speedStr, CharQuotation);
|
||||
strcat_P(speedStr, OffStr);
|
||||
strcat_P(speedStr, CharQuotationComma);
|
||||
}
|
||||
|
||||
if (_speeds & LowSpeed) {
|
||||
strcat_P(speedStr, CharQuotation);
|
||||
strcat_P(speedStr, LowStr);
|
||||
strcat_P(speedStr, CharQuotationComma);
|
||||
}
|
||||
|
||||
if (_speeds & MediumSpeed) {
|
||||
strcat_P(speedStr, CharQuotation);
|
||||
strcat_P(speedStr, MediumStr);
|
||||
strcat_P(speedStr, CharQuotationComma);
|
||||
}
|
||||
|
||||
if (_speeds & HighSpeed) {
|
||||
strcat_P(speedStr, CharQuotation);
|
||||
strcat_P(speedStr, HighStr);
|
||||
strcat_P(speedStr, CharQuotationComma);
|
||||
}
|
||||
|
||||
speedStr[strlen(speedStr) - 1] = ']';
|
||||
} else {
|
||||
strcat(speedStr, "]");
|
||||
}
|
||||
|
||||
DeviceTypeSerializer::mqttWriteConstCharField(
|
||||
Prefix,
|
||||
speedStr,
|
||||
false
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
DeviceTypeSerializer::mqttWriteRetainField(_retain);
|
||||
DeviceTypeSerializer::mqttWriteNameField(_label);
|
||||
DeviceTypeSerializer::mqttWriteUniqueIdField(name());
|
||||
DeviceTypeSerializer::mqttWriteAvailabilityField(this);
|
||||
DeviceTypeSerializer::mqttWriteDeviceField(serializedDevice);
|
||||
DeviceTypeSerializer::mqttWriteEndJson();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
+237
-92
@@ -1,150 +1,295 @@
|
||||
#ifndef AHA_FAN_H
|
||||
#define AHA_FAN_H
|
||||
#ifndef AHA_HAFAN_H
|
||||
#define AHA_HAFAN_H
|
||||
|
||||
#include "BaseDeviceType.h"
|
||||
#include "HABaseDeviceType.h"
|
||||
#include "../utils/HANumeric.h"
|
||||
|
||||
#ifdef ARDUINOHA_FAN
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
#include <functional>
|
||||
#endif
|
||||
|
||||
#define HAFAN_STATE_CALLBACK_BOOL(name) void (*name)(bool)
|
||||
#define HAFAN_STATE_CALLBACK_SPEED(name) void (*name)(Speed)
|
||||
#ifndef EX_ARDUINOHA_FAN
|
||||
|
||||
class HAFan : public BaseDeviceType
|
||||
#define HAFAN_STATE_CALLBACK(name) void (*name)(bool state, HAFan* sender)
|
||||
#define HAFAN_SPEED_CALLBACK(name) void (*name)(uint16_t speed, HAFan* sender)
|
||||
|
||||
/**
|
||||
* HAFan allows adding a controllable fan in the Home Assistant panel.
|
||||
* The library supports only the state and speed of the fan.
|
||||
* If you want more features please open a new GitHub issue.
|
||||
*
|
||||
* @note
|
||||
* You can find more information about this entity in the Home Assistant documentation:
|
||||
* https://www.home-assistant.io/integrations/fan.mqtt/
|
||||
*/
|
||||
class HAFan : public HABaseDeviceType
|
||||
{
|
||||
public:
|
||||
static const char* SpeedCommandTopic;
|
||||
static const char* SpeedStateTopic;
|
||||
|
||||
enum Features {
|
||||
DefaultFeatures = 0,
|
||||
SpeedsFeature = 1
|
||||
};
|
||||
|
||||
enum Speed {
|
||||
UnknownSpeed = 0,
|
||||
OffSpeed = 1,
|
||||
LowSpeed = 2,
|
||||
MediumSpeed = 4,
|
||||
HighSpeed = 8
|
||||
};
|
||||
|
||||
HAFan(const char* uniqueId, uint8_t features = DefaultFeatures);
|
||||
HAFan(const char* uniqueId, uint8_t features, HAMqtt& mqtt); // legacy constructor
|
||||
|
||||
virtual void onMqttConnected() override;
|
||||
virtual void onMqttMessage(
|
||||
const char* topic,
|
||||
const uint8_t* payload,
|
||||
const uint16_t& length
|
||||
) override;
|
||||
/**
|
||||
* @param uniqueId The unique ID of the fan. It needs to be unique in a scope of your device.
|
||||
* @param features Features that should be enabled for the fan.
|
||||
*/
|
||||
HAFan(const char* uniqueId, const uint8_t features = DefaultFeatures);
|
||||
|
||||
/**
|
||||
* Changes state of the fan 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 fan (on - true, off - false).
|
||||
* @param state New state of the fan.
|
||||
* @param force Forces to update state without comparing it to previous known state.
|
||||
* @returns Returns true if MQTT message has been published successfully.
|
||||
* @returns Returns `true` if MQTT message has been published successfully.
|
||||
*/
|
||||
bool setState(bool state, bool force = false);
|
||||
bool setState(const bool state, const bool force = false);
|
||||
|
||||
/**
|
||||
* Alias for setState(true).
|
||||
* Changes the speed of the fan 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 speed The new speed of the fan. It should be in range of min and max value.
|
||||
* @param force Forces to update the value without comparing it to a previous known value.
|
||||
* @returns Returns `true` if MQTT message has been published successfully.
|
||||
*/
|
||||
bool setSpeed(const uint16_t speed, const bool force = false);
|
||||
|
||||
/**
|
||||
* Alias for `setState(true)`.
|
||||
*/
|
||||
inline bool turnOn()
|
||||
{ return setState(true); }
|
||||
|
||||
/**
|
||||
* Alias for setState(false).
|
||||
* Alias for `setState(false)`.
|
||||
*/
|
||||
inline bool turnOff()
|
||||
{ return setState(false); }
|
||||
|
||||
/**
|
||||
* Returns last known state of the fan.
|
||||
* If setState method wasn't called the initial value will be returned.
|
||||
* Sets current state of the fan without publishing it to Home Assistant.
|
||||
* This method may be useful if you want to change state before connection
|
||||
* with MQTT broker is acquired.
|
||||
*
|
||||
* @param state New state of the fan.
|
||||
*/
|
||||
inline bool getState() const
|
||||
inline void setCurrentState(const bool state)
|
||||
{ _currentState = state; }
|
||||
|
||||
/**
|
||||
* Returns last known state of the fan.
|
||||
* By default it's `false`.
|
||||
*/
|
||||
inline bool getCurrentState() const
|
||||
{ return _currentState; }
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the state of the fan changes.
|
||||
* Please note that it's not possible to register multiple callbacks for the same fan.
|
||||
* Sets the current speed of the fan without pushing the value to Home Assistant.
|
||||
* This method may be useful if you want to change the speed before the connection
|
||||
* with the MQTT broker is acquired.
|
||||
*
|
||||
* @param callback
|
||||
* @param speed The new speed of the fan. It should be in range of min and max value.
|
||||
*/
|
||||
inline void onStateChanged(HAFAN_STATE_CALLBACK_BOOL(callback))
|
||||
{ _stateCallback = callback; }
|
||||
inline void setCurrentSpeed(const uint16_t speed)
|
||||
{ _currentSpeed = speed; }
|
||||
|
||||
/**
|
||||
* Sets the list of supported fan's speeds.
|
||||
*
|
||||
* @param speeds
|
||||
* Returns the last known speed of the fan.
|
||||
* By default speed is set to `0`.
|
||||
*/
|
||||
inline void setSpeeds(uint8_t speeds)
|
||||
{ _speeds = speeds; }
|
||||
|
||||
/**
|
||||
* Sets speed of the fan.
|
||||
*
|
||||
* @param speed
|
||||
*/
|
||||
bool setSpeed(Speed speed);
|
||||
|
||||
/**
|
||||
* Sets speed of the fan based on the name of the mode.
|
||||
*
|
||||
* @param speed
|
||||
*/
|
||||
bool setSpeedFromStr(const char* speed);
|
||||
|
||||
/**
|
||||
* Returns current speed of the fan.
|
||||
*/
|
||||
inline Speed getSpeed() const
|
||||
inline uint16_t getCurrentSpeed() const
|
||||
{ return _currentSpeed; }
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the speed of the fan changes.
|
||||
* Please note that it's not possible to register multiple callbacks for the same fan.
|
||||
* Sets icon of the fan.
|
||||
* Any icon from MaterialDesignIcons.com (for example: `mdi:home`).
|
||||
*
|
||||
* @param callback
|
||||
* @param icon The icon name.
|
||||
*/
|
||||
inline void onSpeedChanged(HAFAN_STATE_CALLBACK_SPEED(callback))
|
||||
{ _speedCallback = callback; }
|
||||
inline void setIcon(const char* icon)
|
||||
{ _icon = icon; }
|
||||
|
||||
/**
|
||||
* Sets name that wil be displayed in the Home Assistant panel.
|
||||
*
|
||||
* @param name
|
||||
*/
|
||||
inline void setName(const char* name)
|
||||
{ _label = name; } // it needs to be called "label" as "_name" is already in use
|
||||
|
||||
/**
|
||||
* Sets `retain` flag for commands published by Home Assistant.
|
||||
* By default it's set to false.
|
||||
* Sets retain flag for the fan's command.
|
||||
* If set to `true` the command produced by Home Assistant will be retained.
|
||||
*
|
||||
* @param retain
|
||||
*/
|
||||
inline void setRetain(bool retain)
|
||||
inline void setRetain(const bool retain)
|
||||
{ _retain = retain; }
|
||||
|
||||
protected:
|
||||
bool publishState(bool state);
|
||||
bool publishSpeed(Speed speed);
|
||||
uint16_t calculateSerializedLength(const char* serializedDevice) const override;
|
||||
uint16_t calculateSpeedsLength() const;
|
||||
bool writeSerializedData(const char* serializedDevice) const override;
|
||||
/**
|
||||
* Sets optimistic flag for the fan state.
|
||||
* In this mode the fan 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; }
|
||||
|
||||
/**
|
||||
* Sets the maximum of numeric output range (representing 100%).
|
||||
* The number of speeds within the speed_range / 100 will determine the percentage step.
|
||||
* By default the maximum range is `100`.
|
||||
*
|
||||
* @param max The maximum of numeric output range.
|
||||
*/
|
||||
inline void setSpeedRangeMax(const uint16_t max)
|
||||
{ _speedRangeMax.setBaseValue(max); }
|
||||
|
||||
/**
|
||||
* Sets the minimum of numeric output range (off is not included, so speed_range_min - 1 represents 0 %).
|
||||
* The number of speeds within the speed_range / 100 will determine the percentage step.
|
||||
* By default the minimum range is `1`.
|
||||
*
|
||||
* @param min The minimum of numeric output range.
|
||||
*/
|
||||
inline void setSpeedRangeMin(const uint16_t min)
|
||||
{ _speedRangeMin.setBaseValue(min); }
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the state command from HA is received.
|
||||
* Please note that it's not possible to register multiple callbacks for the same fan.
|
||||
*
|
||||
* @param callback
|
||||
* @note In non-optimistic mode, the state must be reported back to HA using the HAFan::setState method.
|
||||
*/
|
||||
inline void onStateCommand(HAFAN_STATE_CALLBACK(callback))
|
||||
{
|
||||
_stateCallback = callback;
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
_stateStdCallback = nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the speed command from HA is received.
|
||||
* Please note that it's not possible to register multiple callbacks for the same fan.
|
||||
*
|
||||
* @param callback
|
||||
* @note In non-optimistic mode, the speed must be reported back to HA using the HAFan::setSpeed method.
|
||||
*/
|
||||
inline void onSpeedCommand(HAFAN_SPEED_CALLBACK(callback))
|
||||
{
|
||||
_speedCallback = callback;
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
_speedStdCallback = nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
/**
|
||||
* Registers state callback using std::function.
|
||||
* It allows passing capturing lambdas and std::bind expressions.
|
||||
*
|
||||
* @param callback
|
||||
*/
|
||||
inline void onStateCommand(const std::function<void(bool, HAFan*)>& callback)
|
||||
{
|
||||
_stateCallback = nullptr;
|
||||
_stateStdCallback = callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers speed callback using std::function.
|
||||
* It allows passing capturing lambdas and std::bind expressions.
|
||||
*
|
||||
* @param callback
|
||||
*/
|
||||
inline void onSpeedCommand(const std::function<void(uint16_t, HAFan*)>& callback)
|
||||
{
|
||||
_speedCallback = nullptr;
|
||||
_speedStdCallback = 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 bool state);
|
||||
|
||||
/**
|
||||
* Publishes the MQTT message with the given speed.
|
||||
*
|
||||
* @param speed The speed to publish. It should be in range of min and max value.
|
||||
* @returns Returns `true` if the MQTT message has been published successfully.
|
||||
*/
|
||||
bool publishSpeed(const uint16_t speed);
|
||||
|
||||
/**
|
||||
* Parses the given state command and executes the callback with proper value.
|
||||
*
|
||||
* @param cmd The data of the command.
|
||||
* @param length Length of the command.
|
||||
*/
|
||||
void handleStateCommand(const uint8_t* cmd, const uint16_t length);
|
||||
|
||||
/**
|
||||
* Parses the given speed command and executes the callback with proper value.
|
||||
*
|
||||
* @param cmd The data of the command.
|
||||
* @param length Length of the command.
|
||||
*/
|
||||
void handleSpeedCommand(const uint8_t* cmd, const uint16_t length);
|
||||
|
||||
/// Features enabled for the fan.
|
||||
const uint8_t _features;
|
||||
uint8_t _speeds;
|
||||
bool _currentState;
|
||||
HAFAN_STATE_CALLBACK_BOOL(_stateCallback);
|
||||
Speed _currentSpeed;
|
||||
HAFAN_STATE_CALLBACK_SPEED(_speedCallback);
|
||||
const char* _label;
|
||||
|
||||
/// 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 fan (`true` - enabled, `false` - disabled).
|
||||
bool _optimistic;
|
||||
|
||||
/// The maximum of numeric output range.
|
||||
HANumeric _speedRangeMax;
|
||||
|
||||
/// The minimum of numeric output range.
|
||||
HANumeric _speedRangeMin;
|
||||
|
||||
/// The current state of the fan. By default it's `false`.
|
||||
bool _currentState;
|
||||
|
||||
/// The current speed of the fan. By default it's `0`.
|
||||
uint16_t _currentSpeed;
|
||||
|
||||
/// The callback that will be called when the state command is received from the HA.
|
||||
HAFAN_STATE_CALLBACK(_stateCallback);
|
||||
|
||||
/// The callback that will be called when the speed command is received from the HA.
|
||||
HAFAN_SPEED_CALLBACK(_speedCallback);
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
/// The std::function callback that will be called when the state command is received from the HA.
|
||||
std::function<void(bool, HAFan*)> _stateStdCallback;
|
||||
|
||||
/// The std::function callback that will be called when the speed command is received from the HA.
|
||||
std::function<void(uint16_t, HAFan*)> _speedStdCallback;
|
||||
#endif
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
+962
-990
File diff suppressed because it is too large
Load Diff
+713
-235
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,521 @@
|
||||
#include "HALight.h"
|
||||
#ifndef EX_ARDUINOHA_LIGHT
|
||||
|
||||
#include "../HAMqtt.h"
|
||||
#include "../utils/HASerializer.h"
|
||||
|
||||
const uint8_t HALight::RGBStringMaxLength = 3*4; // 4 characters per color
|
||||
|
||||
void HALight::RGBColor::fromBuffer(const uint8_t* data, const uint16_t length)
|
||||
{
|
||||
if (length > RGBStringMaxLength) {
|
||||
return;
|
||||
}
|
||||
|
||||
uint8_t firstCommaPos = 0;
|
||||
uint8_t secondCommaPos = 0;
|
||||
|
||||
for (uint8_t i = 0; i < length; i++) {
|
||||
if (data[i] == ',') {
|
||||
if (firstCommaPos == 0) {
|
||||
firstCommaPos = i;
|
||||
} else if (secondCommaPos == 0) {
|
||||
secondCommaPos = i;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (firstCommaPos == 0 || secondCommaPos == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const uint8_t redLen = firstCommaPos;
|
||||
const uint8_t greenLen = secondCommaPos - firstCommaPos - 1; // minus comma
|
||||
const uint8_t blueLen = length - redLen - greenLen - 2; // minus two commas
|
||||
|
||||
const HANumeric& r = HANumeric::fromStr(data, redLen);
|
||||
const HANumeric& g = HANumeric::fromStr(&data[redLen + 1], greenLen);
|
||||
const HANumeric& b = HANumeric::fromStr(&data[redLen + greenLen + 2], blueLen);
|
||||
|
||||
if (r.isUInt8() && g.isUInt8() && b.isUInt8()) {
|
||||
red = r.toUInt8();
|
||||
green = g.toUInt8();
|
||||
blue = b.toUInt8();
|
||||
isSet = true;
|
||||
}
|
||||
}
|
||||
|
||||
HALight::HALight(const char* uniqueId, const uint8_t features) :
|
||||
HABaseDeviceType(AHATOFSTR(HAComponentLight), uniqueId),
|
||||
_features(features),
|
||||
_icon(nullptr),
|
||||
_retain(false),
|
||||
_optimistic(false),
|
||||
_brightnessScale(),
|
||||
_currentState(false),
|
||||
_currentBrightness(0),
|
||||
_minMireds(),
|
||||
_maxMireds(),
|
||||
_currentColorTemperature(0),
|
||||
_currentRGBColor(),
|
||||
_stateCallback(nullptr),
|
||||
_brightnessCallback(nullptr),
|
||||
_colorTemperatureCallback(nullptr),
|
||||
_rgbColorCallback(nullptr)
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
, _stateStdCallback(),
|
||||
_brightnessStdCallback(),
|
||||
_colorTemperatureStdCallback(),
|
||||
_rgbColorStdCallback()
|
||||
#endif
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
bool HALight::setState(const bool state, const bool force)
|
||||
{
|
||||
if (!force && state == _currentState) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool published = publishState(state);
|
||||
_currentState = state;
|
||||
return published;
|
||||
}
|
||||
|
||||
bool HALight::setBrightness(const uint8_t brightness, const bool force)
|
||||
{
|
||||
if (!force && brightness == _currentBrightness) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!(_features & BrightnessFeature)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool published = publishBrightness(brightness);
|
||||
_currentBrightness = brightness;
|
||||
return published;
|
||||
}
|
||||
|
||||
bool HALight::setColorTemperature(const uint16_t temperature, const bool force)
|
||||
{
|
||||
if (!force && temperature == _currentColorTemperature) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!(_features & ColorTemperatureFeature)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool published = publishColorTemperature(temperature);
|
||||
_currentColorTemperature = temperature;
|
||||
return published;
|
||||
}
|
||||
|
||||
bool HALight::setRGBColor(const RGBColor& color, const bool force)
|
||||
{
|
||||
if (!force && color == _currentRGBColor) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!(_features & RGBFeature) || !color.isSet) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool published = publishRGBColor(color);
|
||||
_currentRGBColor = color;
|
||||
return published;
|
||||
}
|
||||
|
||||
void HALight::buildSerializer()
|
||||
{
|
||||
if (_serializer || !uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
_serializer = new HASerializer(this, 30);
|
||||
_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 & BrightnessFeature) {
|
||||
_serializer->topic(AHATOFSTR(HABrightnessStateTopic));
|
||||
_serializer->topic(AHATOFSTR(HABrightnessCommandTopic));
|
||||
|
||||
if (_brightnessScale.isSet()) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HABrightnessScaleProperty),
|
||||
&_brightnessScale,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (_features & ColorTemperatureFeature) {
|
||||
_serializer->topic(AHATOFSTR(HAColorTemperatureStateTopic));
|
||||
_serializer->topic(AHATOFSTR(HAColorTemperatureCommandTopic));
|
||||
|
||||
if (_minMireds.isSet()) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAMinMiredsProperty),
|
||||
&_minMireds,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_maxMireds.isSet()) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAMaxMiredsProperty),
|
||||
&_maxMireds,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (_features & RGBFeature) {
|
||||
_serializer->topic(AHATOFSTR(HARGBCommandTopic));
|
||||
_serializer->topic(AHATOFSTR(HARGBStateTopic));
|
||||
}
|
||||
|
||||
_serializer->set(HASerializer::WithDevice);
|
||||
_serializer->set(HASerializer::WithAvailability);
|
||||
_serializer->topic(AHATOFSTR(HAStateTopic));
|
||||
_serializer->topic(AHATOFSTR(HACommandTopic));
|
||||
}
|
||||
|
||||
HASerializer* HALight::buildDeviceDiscoverySerializer()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
HASerializer* serializer = new HASerializer(this, 30);
|
||||
serializer->set(
|
||||
AHATOFSTR(HAPlatformProperty),
|
||||
AHATOFSTR(HAComponentLight),
|
||||
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 & BrightnessFeature) {
|
||||
serializer->topic(AHATOFSTR(HABrightnessStateTopic));
|
||||
serializer->topic(AHATOFSTR(HABrightnessCommandTopic));
|
||||
|
||||
if (_brightnessScale.isSet()) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HABrightnessScaleProperty),
|
||||
&_brightnessScale,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (_features & ColorTemperatureFeature) {
|
||||
serializer->topic(AHATOFSTR(HAColorTemperatureStateTopic));
|
||||
serializer->topic(AHATOFSTR(HAColorTemperatureCommandTopic));
|
||||
|
||||
if (_minMireds.isSet()) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HAMinMiredsProperty),
|
||||
&_minMireds,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_maxMireds.isSet()) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HAMaxMiredsProperty),
|
||||
&_maxMireds,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (_features & RGBFeature) {
|
||||
serializer->topic(AHATOFSTR(HARGBCommandTopic));
|
||||
serializer->topic(AHATOFSTR(HARGBStateTopic));
|
||||
}
|
||||
|
||||
serializer->set(HASerializer::WithAvailability);
|
||||
serializer->topic(AHATOFSTR(HAStateTopic));
|
||||
serializer->topic(AHATOFSTR(HACommandTopic));
|
||||
return serializer;
|
||||
}
|
||||
|
||||
void HALight::onMqttConnected()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (shouldPublishSingleComponentConfig()) {
|
||||
publishConfig();
|
||||
}
|
||||
publishAvailability();
|
||||
|
||||
if (!_retain) {
|
||||
publishState(_currentState);
|
||||
publishBrightness(_currentBrightness);
|
||||
publishColorTemperature(_currentColorTemperature);
|
||||
publishRGBColor(_currentRGBColor);
|
||||
}
|
||||
|
||||
subscribeTopic(uniqueId(), AHATOFSTR(HACommandTopic));
|
||||
|
||||
if (_features & BrightnessFeature) {
|
||||
subscribeTopic(uniqueId(), AHATOFSTR(HABrightnessCommandTopic));
|
||||
}
|
||||
|
||||
if (_features & ColorTemperatureFeature) {
|
||||
subscribeTopic(uniqueId(), AHATOFSTR(HAColorTemperatureCommandTopic));
|
||||
}
|
||||
|
||||
if (_features & RGBFeature) {
|
||||
subscribeTopic(uniqueId(), AHATOFSTR(HARGBCommandTopic));
|
||||
}
|
||||
}
|
||||
|
||||
void HALight::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(HABrightnessCommandTopic)
|
||||
)) {
|
||||
handleBrightnessCommand(payload, length);
|
||||
} else if (HASerializer::compareDataTopics(
|
||||
topic,
|
||||
uniqueId(),
|
||||
AHATOFSTR(HAColorTemperatureCommandTopic)
|
||||
)) {
|
||||
handleColorTemperatureCommand(payload, length);
|
||||
} else if (
|
||||
HASerializer::compareDataTopics(
|
||||
topic,
|
||||
uniqueId(),
|
||||
AHATOFSTR(HARGBCommandTopic)
|
||||
)
|
||||
) {
|
||||
handleRGBCommand(payload, length);
|
||||
}
|
||||
}
|
||||
|
||||
bool HALight::publishState(const bool state)
|
||||
{
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
AHATOFSTR(state ? HAStateOn : HAStateOff),
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
bool HALight::publishBrightness(const uint8_t brightness)
|
||||
{
|
||||
if (!(_features & BrightnessFeature)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char str[3 + 1] = {0}; // uint8_t digits with null terminator
|
||||
HANumeric(brightness, 0).toStr(str);
|
||||
|
||||
return publishOnDataTopic(AHATOFSTR(HABrightnessStateTopic), str, true);
|
||||
}
|
||||
|
||||
bool HALight::publishColorTemperature(const uint16_t temperature)
|
||||
{
|
||||
if (!(_features & ColorTemperatureFeature)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char str[5 + 1] = {0}; // uint16_t digits with null terminator
|
||||
HANumeric(temperature, 0).toStr(str);
|
||||
|
||||
return publishOnDataTopic(AHATOFSTR(HAColorTemperatureStateTopic), str, true);
|
||||
}
|
||||
|
||||
bool HALight::publishRGBColor(const RGBColor& color)
|
||||
{
|
||||
if (!(_features & RGBFeature) || !color.isSet) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char str[RGBStringMaxLength] = {0};
|
||||
uint16_t len = 0;
|
||||
|
||||
// append red color with comma
|
||||
len += HANumeric(color.red, 0).toStr(&str[0]);
|
||||
str[len++] = ',';
|
||||
|
||||
// append green color with comma
|
||||
len += HANumeric(color.green, 0).toStr(&str[len]);
|
||||
str[len++] = ',';
|
||||
|
||||
// append blue color
|
||||
HANumeric(color.blue, 0).toStr(&str[len]);
|
||||
|
||||
return publishOnDataTopic(AHATOFSTR(HARGBStateTopic), str, true);
|
||||
}
|
||||
|
||||
void HALight::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 HALight::handleBrightnessCommand(const uint8_t* cmd, const uint16_t length)
|
||||
{
|
||||
const bool hasBrightnessCallback =
|
||||
_brightnessCallback
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
|| static_cast<bool>(_brightnessStdCallback)
|
||||
#endif
|
||||
;
|
||||
|
||||
if (!hasBrightnessCallback) {
|
||||
return;
|
||||
}
|
||||
|
||||
const HANumeric& number = HANumeric::fromStr(cmd, length);
|
||||
if (number.isUInt8()) {
|
||||
const uint8_t brightness = number.toUInt8();
|
||||
if (_brightnessCallback) {
|
||||
_brightnessCallback(brightness, this);
|
||||
}
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
if (_brightnessStdCallback) {
|
||||
_brightnessStdCallback(brightness, this);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
void HALight::handleColorTemperatureCommand(
|
||||
const uint8_t* cmd,
|
||||
const uint16_t length
|
||||
)
|
||||
{
|
||||
const bool hasColorTemperatureCallback =
|
||||
_colorTemperatureCallback
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
|| static_cast<bool>(_colorTemperatureStdCallback)
|
||||
#endif
|
||||
;
|
||||
|
||||
if (!hasColorTemperatureCallback) {
|
||||
return;
|
||||
}
|
||||
|
||||
const HANumeric& number = HANumeric::fromStr(cmd, length);
|
||||
if (number.isUInt16()) {
|
||||
const uint16_t temperature = number.toUInt16();
|
||||
if (_colorTemperatureCallback) {
|
||||
_colorTemperatureCallback(temperature, this);
|
||||
}
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
if (_colorTemperatureStdCallback) {
|
||||
_colorTemperatureStdCallback(temperature, this);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
void HALight::handleRGBCommand(const uint8_t* cmd, const uint16_t length)
|
||||
{
|
||||
const bool hasRgbCallback =
|
||||
_rgbColorCallback
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
|| static_cast<bool>(_rgbColorStdCallback)
|
||||
#endif
|
||||
;
|
||||
|
||||
if (!hasRgbCallback) {
|
||||
return;
|
||||
}
|
||||
|
||||
RGBColor color;
|
||||
color.fromBuffer(cmd, length);
|
||||
|
||||
if (color.isSet) {
|
||||
if (_rgbColorCallback) {
|
||||
_rgbColorCallback(color, this);
|
||||
}
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
if (_rgbColorStdCallback) {
|
||||
_rgbColorStdCallback(color, this);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,512 @@
|
||||
#ifndef AHA_HALIGHT_H
|
||||
#define AHA_HALIGHT_H
|
||||
|
||||
#include "HABaseDeviceType.h"
|
||||
#include "../utils/HANumeric.h"
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
#include <functional>
|
||||
#endif
|
||||
|
||||
#ifndef EX_ARDUINOHA_LIGHT
|
||||
|
||||
#define HALIGHT_STATE_CALLBACK(name) void (*name)(bool state, HALight* sender)
|
||||
#define HALIGHT_BRIGHTNESS_CALLBACK(name) void (*name)(uint8_t brightness, HALight* sender)
|
||||
#define HALIGHT_COLOR_TEMP_CALLBACK(name) void (*name)(uint16_t temperature, HALight* sender)
|
||||
#define HALIGHT_RGB_COLOR_CALLBACK(name) void (*name)(HALight::RGBColor color, HALight* sender)
|
||||
|
||||
/**
|
||||
* HALight allows adding a controllable light in the Home Assistant panel.
|
||||
* The library supports only the state, brightness, color temperature and RGB color.
|
||||
* If you need more features please open a new GitHub issue.
|
||||
*
|
||||
* @note
|
||||
* You can find more information about this entity in the Home Assistant documentation:
|
||||
* https://www.home-assistant.io/integrations/light.mqtt/
|
||||
*/
|
||||
class HALight : public HABaseDeviceType
|
||||
{
|
||||
public:
|
||||
static const uint8_t RGBStringMaxLength;
|
||||
|
||||
enum Features {
|
||||
DefaultFeatures = 0,
|
||||
BrightnessFeature = 1,
|
||||
ColorTemperatureFeature = 2,
|
||||
RGBFeature = 4
|
||||
};
|
||||
|
||||
struct RGBColor {
|
||||
uint8_t red;
|
||||
uint8_t green;
|
||||
uint8_t blue;
|
||||
bool isSet;
|
||||
|
||||
RGBColor() :
|
||||
red(0), green(0), blue(0), isSet(false) { }
|
||||
|
||||
RGBColor(uint8_t r, uint8_t g, uint8_t b) :
|
||||
red(r), green(g), blue(b), isSet(true) { }
|
||||
|
||||
void operator= (const RGBColor& a) {
|
||||
red = a.red;
|
||||
green = a.green;
|
||||
blue = a.blue;
|
||||
isSet = a.isSet;
|
||||
}
|
||||
|
||||
bool operator== (const RGBColor& a) const {
|
||||
return (
|
||||
red == a.red &&
|
||||
green == a.green &&
|
||||
blue == a.blue
|
||||
);
|
||||
}
|
||||
|
||||
bool operator!= (const RGBColor& a) const {
|
||||
return (
|
||||
red != a.red ||
|
||||
green != a.green ||
|
||||
blue != a.blue
|
||||
);
|
||||
}
|
||||
|
||||
void fromBuffer(const uint8_t* data, const uint16_t length);
|
||||
};
|
||||
|
||||
/**
|
||||
* @param uniqueId The unique ID of the light. It needs to be unique in a scope of your device.
|
||||
* @param features Features that should be enabled for the light.
|
||||
* You can enable multiple features by using OR bitwise operator, for example:
|
||||
* `HALight::BrightnessFeature | HALight::ColorTemperatureFeature`
|
||||
*/
|
||||
HALight(const char* uniqueId, const uint8_t features = DefaultFeatures);
|
||||
|
||||
/**
|
||||
* Changes state of the light 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 light.
|
||||
* @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 bool state, const bool force = false);
|
||||
|
||||
/**
|
||||
* Changes the brightness of the light 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 brightness The new brightness of the light.
|
||||
* @param force Forces to update the value without comparing it to a previous known value.
|
||||
* @returns Returns `true` if MQTT message has been published successfully.
|
||||
*/
|
||||
bool setBrightness(const uint8_t brightness, const bool force = false);
|
||||
|
||||
/**
|
||||
* Changes the color temperature of the light 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 temperature The new color temperature of the light.
|
||||
* @param force Forces to update the value without comparing it to a previous known value.
|
||||
* @returns Returns `true` if MQTT message has been published successfully.
|
||||
*/
|
||||
bool setColorTemperature(const uint16_t temperature, const bool force = false);
|
||||
|
||||
/**
|
||||
* Changes the RGB color of the light and publishes MQTT message.
|
||||
* Please note that if a new color is the same as previous one,
|
||||
* the MQTT message won't be published.
|
||||
*
|
||||
* @param color The new RGB color of the light.
|
||||
* @param force Forces to update the value without comparing it to a previous known value.
|
||||
* @returns Returns `true` if MQTT message has been published successfully.
|
||||
*/
|
||||
bool setRGBColor(const RGBColor& color, const bool force = false);
|
||||
|
||||
/**
|
||||
* Alias for `setState(true)`.
|
||||
*/
|
||||
inline bool turnOn()
|
||||
{ return setState(true); }
|
||||
|
||||
/**
|
||||
* Alias for `setState(false)`.
|
||||
*/
|
||||
inline bool turnOff()
|
||||
{ return setState(false); }
|
||||
|
||||
/**
|
||||
* Sets current state of the light without publishing it to Home Assistant.
|
||||
* This method may be useful if you want to change state before connection
|
||||
* with MQTT broker is acquired.
|
||||
*
|
||||
* @param state New state of the light.
|
||||
*/
|
||||
inline void setCurrentState(const bool state)
|
||||
{ _currentState = state; }
|
||||
|
||||
/**
|
||||
* Returns last known state of the light.
|
||||
* By default it's `false`.
|
||||
*/
|
||||
inline bool getCurrentState() const
|
||||
{ return _currentState; }
|
||||
|
||||
/**
|
||||
* Sets the current brightness of the light without pushing the value to Home Assistant.
|
||||
* This method may be useful if you want to change the brightness before the connection
|
||||
* with the MQTT broker is acquired.
|
||||
*
|
||||
* @param brightness The new brightness of the light.
|
||||
*/
|
||||
inline void setCurrentBrightness(const uint8_t brightness)
|
||||
{ _currentBrightness = brightness; }
|
||||
|
||||
/**
|
||||
* Returns the last known brightness of the light.
|
||||
* By default brightness is set to `0`.
|
||||
*/
|
||||
inline uint8_t getCurrentBrightness() const
|
||||
{ return _currentBrightness; }
|
||||
|
||||
/**
|
||||
* Sets the current color temperature of the light without pushing the value to Home Assistant.
|
||||
* This method may be useful if you want to change the color temperature before the connection
|
||||
* with the MQTT broker is acquired.
|
||||
*
|
||||
* @param colorTemp The new color temperature (mireds).
|
||||
*/
|
||||
inline void setCurrentColorTemperature(const uint16_t temperature)
|
||||
{ _currentColorTemperature = temperature; }
|
||||
|
||||
/**
|
||||
* Returns the last known color temperature of the light.
|
||||
* By default temperature is set to `0`.
|
||||
*/
|
||||
inline uint16_t getCurrentColorTemperature() const
|
||||
{ return _currentColorTemperature; }
|
||||
|
||||
/**
|
||||
* Sets the current RGB color of the light without pushing the value to Home Assistant.
|
||||
* This method may be useful if you want to change the color before the connection
|
||||
* with the MQTT broker is acquired.
|
||||
*
|
||||
* @param color The new RGB color.
|
||||
*/
|
||||
inline void setCurrentRGBColor(const RGBColor& color)
|
||||
{ _currentRGBColor = color; }
|
||||
|
||||
/**
|
||||
* Returns the last known RGB color of the light.
|
||||
* By default the RGB color is set to `0,0,0`.
|
||||
*/
|
||||
inline const RGBColor& getCurrentRGBColor() const
|
||||
{ return _currentRGBColor; }
|
||||
|
||||
/**
|
||||
* Sets icon of the light.
|
||||
* 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 light'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 light state.
|
||||
* In this mode the light 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; }
|
||||
|
||||
/**
|
||||
* Sets the maximum brightness value that can be set via HA panel.
|
||||
* By default it's `255`.
|
||||
*
|
||||
* @param scale The maximum value of the brightness.
|
||||
*/
|
||||
inline void setBrightnessScale(const uint8_t scale)
|
||||
{ _brightnessScale.setBaseValue(scale); }
|
||||
|
||||
/**
|
||||
* Sets the minimum color temperature (mireds) value that can be set via HA panel.
|
||||
* By default it's `153`.
|
||||
*
|
||||
* @param mireds The minimum value of the brightness.
|
||||
*/
|
||||
inline void setMinMireds(const uint16_t mireds)
|
||||
{ _minMireds.setBaseValue(mireds); }
|
||||
|
||||
/**
|
||||
* Sets the maximum color temperature (mireds) value that can be set via HA panel.
|
||||
* By default it's `500`.
|
||||
*
|
||||
* @param mireds The maximum value of the brightness.
|
||||
*/
|
||||
inline void setMaxMireds(const uint16_t mireds)
|
||||
{ _maxMireds.setBaseValue(mireds); }
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the state command from HA is received.
|
||||
* Please note that it's not possible to register multiple callbacks for the same light.
|
||||
*
|
||||
* @param callback
|
||||
* @note In non-optimistic mode, the state must be reported back to HA using the HALight::setState method.
|
||||
*/
|
||||
inline void onStateCommand(HALIGHT_STATE_CALLBACK(callback))
|
||||
{
|
||||
_stateCallback = callback;
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
_stateStdCallback = nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the brightness command from HA is received.
|
||||
* Please note that it's not possible to register multiple callbacks for the same light.
|
||||
*
|
||||
* @param callback
|
||||
* @note In non-optimistic mode, the brightness must be reported back to HA using the HALight::setBrightness method.
|
||||
*/
|
||||
inline void onBrightnessCommand(HALIGHT_BRIGHTNESS_CALLBACK(callback))
|
||||
{
|
||||
_brightnessCallback = callback;
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
_brightnessStdCallback = nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the color temperature command from HA is received.
|
||||
* Please note that it's not possible to register multiple callbacks for the same light.
|
||||
*
|
||||
* @param callback
|
||||
* @note In non-optimistic mode, the color temperature must be reported back to HA using the HALight::setColorTemperature method.
|
||||
*/
|
||||
inline void onColorTemperatureCommand(HALIGHT_COLOR_TEMP_CALLBACK(callback))
|
||||
{
|
||||
_colorTemperatureCallback = callback;
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
_colorTemperatureStdCallback = nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the RGB color command from HA is received.
|
||||
* Please note that it's not possible to register multiple callbacks for the same light.
|
||||
*
|
||||
* @param callback
|
||||
* @note In non-optimistic mode, the color must be reported back to HA using the HALight::setRGBColor method.
|
||||
*/
|
||||
inline void onRGBColorCommand(HALIGHT_RGB_COLOR_CALLBACK(callback))
|
||||
{
|
||||
_rgbColorCallback = callback;
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
_rgbColorStdCallback = nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
/**
|
||||
* Registers state callback using std::function.
|
||||
* It allows passing capturing lambdas and std::bind expressions.
|
||||
*
|
||||
* @param callback
|
||||
*/
|
||||
inline void onStateCommand(const std::function<void(bool, HALight*)>& callback)
|
||||
{
|
||||
_stateCallback = nullptr;
|
||||
_stateStdCallback = callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers brightness callback using std::function.
|
||||
* It allows passing capturing lambdas and std::bind expressions.
|
||||
*
|
||||
* @param callback
|
||||
*/
|
||||
inline void onBrightnessCommand(const std::function<void(uint8_t, HALight*)>& callback)
|
||||
{
|
||||
_brightnessCallback = nullptr;
|
||||
_brightnessStdCallback = callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers color temperature callback using std::function.
|
||||
* It allows passing capturing lambdas and std::bind expressions.
|
||||
*
|
||||
* @param callback
|
||||
*/
|
||||
inline void onColorTemperatureCommand(const std::function<void(uint16_t, HALight*)>& callback)
|
||||
{
|
||||
_colorTemperatureCallback = nullptr;
|
||||
_colorTemperatureStdCallback = callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers RGB color callback using std::function.
|
||||
* It allows passing capturing lambdas and std::bind expressions.
|
||||
*
|
||||
* @param callback
|
||||
*/
|
||||
inline void onRGBColorCommand(const std::function<void(HALight::RGBColor, HALight*)>& callback)
|
||||
{
|
||||
_rgbColorCallback = nullptr;
|
||||
_rgbColorStdCallback = 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 bool state);
|
||||
|
||||
/**
|
||||
* Publishes the MQTT message with the given brightness.
|
||||
*
|
||||
* @param brightness The brightness to publish.
|
||||
* @returns Returns `true` if the MQTT message has been published successfully.
|
||||
*/
|
||||
bool publishBrightness(const uint8_t brightness);
|
||||
|
||||
/**
|
||||
* Publishes the MQTT message with the given color temperature (mireds).
|
||||
*
|
||||
* @param temperature The color temperature to publish.
|
||||
* @returns Returns `true` if the MQTT message has been published successfully.
|
||||
*/
|
||||
bool publishColorTemperature(const uint16_t temperature);
|
||||
|
||||
/**
|
||||
* Publishes the MQTT message with the given RGB color.
|
||||
*
|
||||
* @param color The color to publish.
|
||||
* @returns Returns `true` if the MQTT message has been published successfully.
|
||||
*/
|
||||
bool publishRGBColor(const RGBColor& color);
|
||||
|
||||
/**
|
||||
* Parses the given state command and executes the callback with proper value.
|
||||
*
|
||||
* @param cmd The data of the command.
|
||||
* @param length Length of the command.
|
||||
*/
|
||||
void handleStateCommand(const uint8_t* cmd, const uint16_t length);
|
||||
|
||||
/**
|
||||
* Parses the given brightness command and executes the callback with proper value.
|
||||
*
|
||||
* @param cmd The data of the command.
|
||||
* @param length Length of the command.
|
||||
*/
|
||||
void handleBrightnessCommand(const uint8_t* cmd, const uint16_t length);
|
||||
|
||||
/**
|
||||
* Parses the given color temperature command and executes the callback with proper value.
|
||||
*
|
||||
* @param cmd The data of the command.
|
||||
* @param length Length of the command.
|
||||
*/
|
||||
void handleColorTemperatureCommand(const uint8_t* cmd, const uint16_t length);
|
||||
|
||||
/**
|
||||
* Parses the given RGB color command and executes the callback with proper value.
|
||||
*
|
||||
* @param cmd The data of the command.
|
||||
* @param length Length of the command.
|
||||
*/
|
||||
void handleRGBCommand(const uint8_t* cmd, const uint16_t length);
|
||||
|
||||
/// Features enabled for the light.
|
||||
const uint8_t _features;
|
||||
|
||||
/// 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 light (`true` - enabled, `false` - disabled).
|
||||
bool _optimistic;
|
||||
|
||||
/// The maximum value of the brightness. By default it's 255.
|
||||
HANumeric _brightnessScale;
|
||||
|
||||
/// The current state of the light. By default it's `false`.
|
||||
bool _currentState;
|
||||
|
||||
/// The current brightness of the light. By default it's `0`.
|
||||
uint8_t _currentBrightness;
|
||||
|
||||
/// The minimum color temperature (mireds). By default the value is not set.
|
||||
HANumeric _minMireds;
|
||||
|
||||
/// The maximum color temperature (mireds). By default the value is not set.
|
||||
HANumeric _maxMireds;
|
||||
|
||||
/// The current color temperature (mireds). By default the value is not set.
|
||||
uint16_t _currentColorTemperature;
|
||||
|
||||
/// The current RBB color. By default the value is not set.
|
||||
RGBColor _currentRGBColor;
|
||||
|
||||
/// The callback that will be called when the state command is received from the HA.
|
||||
HALIGHT_STATE_CALLBACK(_stateCallback);
|
||||
|
||||
/// The callback that will be called when the brightness command is received from the HA.
|
||||
HALIGHT_BRIGHTNESS_CALLBACK(_brightnessCallback);
|
||||
|
||||
/// The callback that will be called when the color temperature command is received from the HA.
|
||||
HALIGHT_COLOR_TEMP_CALLBACK(_colorTemperatureCallback);
|
||||
|
||||
/// The callback that will be called when the RGB command is received from the HA.
|
||||
HALIGHT_RGB_COLOR_CALLBACK(_rgbColorCallback);
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
/// The std::function callback that will be called when the state command is received from the HA.
|
||||
std::function<void(bool, HALight*)> _stateStdCallback;
|
||||
|
||||
/// The std::function callback that will be called when the brightness command is received from the HA.
|
||||
std::function<void(uint8_t, HALight*)> _brightnessStdCallback;
|
||||
|
||||
/// The std::function callback that will be called when the color temperature command is received from the HA.
|
||||
std::function<void(uint16_t, HALight*)> _colorTemperatureStdCallback;
|
||||
|
||||
/// The std::function callback that will be called when the RGB command is received from the HA.
|
||||
std::function<void(HALight::RGBColor, HALight*)> _rgbColorStdCallback;
|
||||
#endif
|
||||
};
|
||||
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,199 @@
|
||||
#include "HALock.h"
|
||||
#ifndef EX_ARDUINOHA_LOCK
|
||||
|
||||
#include "../HAMqtt.h"
|
||||
#include "../utils/HASerializer.h"
|
||||
|
||||
HALock::HALock(const char* uniqueId) :
|
||||
HABaseDeviceType(AHATOFSTR(HAComponentLock), uniqueId),
|
||||
_icon(nullptr),
|
||||
_retain(false),
|
||||
_optimistic(false),
|
||||
_currentState(StateUnknown),
|
||||
_commandCallback(nullptr)
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
, _commandStdCallback()
|
||||
#endif
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
bool HALock::setState(const LockState 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 HALock::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(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));
|
||||
}
|
||||
|
||||
HASerializer* HALock::buildDeviceDiscoverySerializer()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
HASerializer* serializer = new HASerializer(this, 20);
|
||||
serializer->set(
|
||||
AHATOFSTR(HAPlatformProperty),
|
||||
AHATOFSTR(HAComponentLock),
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
serializer->set(HASerializer::WithAvailability);
|
||||
serializer->topic(AHATOFSTR(HAStateTopic));
|
||||
serializer->topic(AHATOFSTR(HACommandTopic));
|
||||
return serializer;
|
||||
}
|
||||
|
||||
void HALock::onMqttConnected()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (shouldPublishSingleComponentConfig()) {
|
||||
publishConfig();
|
||||
}
|
||||
publishAvailability();
|
||||
|
||||
if (!_retain) {
|
||||
publishState(_currentState);
|
||||
}
|
||||
|
||||
subscribeTopic(uniqueId(), AHATOFSTR(HACommandTopic));
|
||||
}
|
||||
|
||||
void HALock::onMqttMessage(
|
||||
const char* topic,
|
||||
const uint8_t* payload,
|
||||
const uint16_t length
|
||||
)
|
||||
{
|
||||
if (HASerializer::compareDataTopics(
|
||||
topic,
|
||||
uniqueId(),
|
||||
AHATOFSTR(HACommandTopic)
|
||||
)) {
|
||||
handleCommand(payload, length);
|
||||
}
|
||||
}
|
||||
|
||||
bool HALock::publishState(const LockState state)
|
||||
{
|
||||
if (state == StateUnknown) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
AHATOFSTR(state == StateLocked ? HAStateLocked : HAStateUnlocked),
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
void HALock::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;
|
||||
}
|
||||
|
||||
LockCommand command;
|
||||
bool handled = false;
|
||||
if (memcmp_P(cmd, HALockCommand, length) == 0) {
|
||||
command = CommandLock;
|
||||
handled = true;
|
||||
} else if (memcmp_P(cmd, HAUnlockCommand, length) == 0) {
|
||||
command = CommandUnlock;
|
||||
handled = true;
|
||||
} else if (memcmp_P(cmd, HAOpenCommand, length) == 0) {
|
||||
command = CommandOpen;
|
||||
handled = true;
|
||||
}
|
||||
|
||||
if (!handled) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (_commandCallback) {
|
||||
_commandCallback(command, this);
|
||||
}
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
if (_commandStdCallback) {
|
||||
_commandStdCallback(command, this);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,179 @@
|
||||
#ifndef AHA_HALOCK_H
|
||||
#define AHA_HALOCK_H
|
||||
|
||||
#include "HABaseDeviceType.h"
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
#include <functional>
|
||||
#endif
|
||||
|
||||
#ifndef EX_ARDUINOHA_LOCK
|
||||
|
||||
#define HALOCK_CALLBACK(name) void (*name)(LockCommand command, HALock* sender)
|
||||
|
||||
/**
|
||||
* HALock allows to implement a custom lock (for example: door lock)
|
||||
* that can be controlled from the Home Assistant panel.
|
||||
*
|
||||
* @note
|
||||
* You can find more information about this entity in the Home Assistant documentation:
|
||||
* https://www.home-assistant.io/integrations/lock.mqtt/
|
||||
*/
|
||||
class HALock : public HABaseDeviceType
|
||||
{
|
||||
public:
|
||||
/// Available states of the lock that can be reported to the HA panel.
|
||||
enum LockState {
|
||||
StateUnknown = 0,
|
||||
StateLocked,
|
||||
StateUnlocked
|
||||
};
|
||||
|
||||
/// Commands that will be produced by the HA panel.
|
||||
enum LockCommand {
|
||||
CommandLock = 1,
|
||||
CommandUnlock,
|
||||
CommandOpen
|
||||
};
|
||||
|
||||
/**
|
||||
* @param uniqueId The unique ID of the lock. It needs to be unique in a scope of your device.
|
||||
*/
|
||||
HALock(const char* uniqueId);
|
||||
|
||||
/**
|
||||
* Changes state of the lock 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 lock.
|
||||
* @param force Forces to update state without comparing it to a previous known state.
|
||||
* @returns Returns `true` if MQTT message has been published successfully.
|
||||
*/
|
||||
bool setState(const LockState state, const bool force = false);
|
||||
|
||||
/**
|
||||
* Sets current state of the lock without publishing it to Home Assistant.
|
||||
* This method may be useful if you want to change state before connection
|
||||
* with MQTT broker is acquired.
|
||||
*
|
||||
* @param state New state of the lock.
|
||||
*/
|
||||
inline void setCurrentState(const LockState state)
|
||||
{ _currentState = state; }
|
||||
|
||||
/**
|
||||
* Returns last known state of the lock.
|
||||
* If setState method wasn't called the initial value will be returned.
|
||||
*/
|
||||
inline LockState getCurrentState() const
|
||||
{ return _currentState; }
|
||||
|
||||
/**
|
||||
* Sets icon of the lock.
|
||||
* 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 lock'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 lock state.
|
||||
* In this mode the lock 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 lock/unlock/open command from the HA is received.
|
||||
* Please note that it's not possible to register multiple callbacks for the same lock.
|
||||
*
|
||||
* @param callback
|
||||
*/
|
||||
inline void onCommand(HALOCK_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(LockCommand, HALock*)>& 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 LockState state);
|
||||
|
||||
/**
|
||||
* Parses the given command and executes the lock'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);
|
||||
|
||||
/// The icon of the lock. It can be nullptr.
|
||||
const char* _icon;
|
||||
|
||||
/// The retain flag for the HA commands.
|
||||
bool _retain;
|
||||
|
||||
/// The optimistic mode of the lock (`true` - enabled, `false` - disabled).
|
||||
bool _optimistic;
|
||||
|
||||
/// The current state of the lock. By default it's `HALock::StateUnknown`.
|
||||
LockState _currentState;
|
||||
|
||||
/// The callback that will be called when lock/unlock/open command is received from the HA.
|
||||
HALOCK_CALLBACK(_commandCallback);
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
/// The std::function callback that will be called when lock/unlock/open command is received from the HA.
|
||||
std::function<void(LockCommand, HALock*)> _commandStdCallback;
|
||||
#endif
|
||||
};
|
||||
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,390 @@
|
||||
#include "HANumber.h"
|
||||
#ifndef EX_ARDUINOHA_NUMBER
|
||||
|
||||
#include "../HAMqtt.h"
|
||||
#include "../utils/HADictionary.h"
|
||||
#include "../utils/HASerializer.h"
|
||||
#include <string.h>
|
||||
|
||||
HANumber::HANumber(const char* uniqueId, const NumberPrecision precision) :
|
||||
HABaseDeviceType(AHATOFSTR(HAComponentNumber), uniqueId),
|
||||
_precision(precision),
|
||||
_class(nullptr),
|
||||
_icon(nullptr),
|
||||
_retain(false),
|
||||
_optimistic(false),
|
||||
_mode(ModeAuto),
|
||||
_unitOfMeasurement(nullptr),
|
||||
_minValue(),
|
||||
_maxValue(),
|
||||
_step(),
|
||||
_currentState(),
|
||||
_commandCallback(nullptr),
|
||||
_commandTemplate(nullptr),
|
||||
_valueTemplate(nullptr),
|
||||
_payloadReset(nullptr)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void HANumber::setValueTemplate(const char* valueTemplate)
|
||||
{
|
||||
_valueTemplate = valueTemplate;
|
||||
}
|
||||
|
||||
void HANumber::setCommandTemplate(const char* commandTemplate)
|
||||
{
|
||||
_commandTemplate = commandTemplate;
|
||||
}
|
||||
|
||||
void HANumber::setPayloadReset(const char* payloadReset)
|
||||
{
|
||||
_payloadReset = payloadReset;
|
||||
}
|
||||
|
||||
bool HANumber::setState(const HANumeric& state, const bool force)
|
||||
{
|
||||
if (!force && state == _currentState) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool published = publishState(state);
|
||||
_currentState = state;
|
||||
return published;
|
||||
}
|
||||
|
||||
void HANumber::updateMinMaxStep(const float min, const float max, const float step)
|
||||
{
|
||||
_minValue = HANumeric(min, _precision);
|
||||
_maxValue = HANumeric(max, _precision);
|
||||
_step = HANumeric(step, _precision);
|
||||
republishDiscovery();
|
||||
}
|
||||
|
||||
void HANumber::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(HADeviceClassProperty), _class);
|
||||
_serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
|
||||
_serializer->set(AHATOFSTR(HAIconProperty), _icon);
|
||||
_serializer->set(AHATOFSTR(HAUnitOfMeasurementProperty), nonEmptyString(_unitOfMeasurement));
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAModeProperty),
|
||||
getModeProperty(),
|
||||
HASerializer::ProgmemPropertyValue
|
||||
);
|
||||
|
||||
if (nonEmptyString(_valueTemplate)) {
|
||||
_serializer->set(AHATOFSTR(HAValueTemplateProperty), _valueTemplate);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_payloadReset)) {
|
||||
_serializer->set(AHATOFSTR(HAPayloadResetProperty), _payloadReset);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_commandTemplate)) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HACommandTemplateProperty),
|
||||
_commandTemplate
|
||||
);
|
||||
} else if (getBuiltInCommandTemplate()) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HACommandTemplateProperty),
|
||||
getBuiltInCommandTemplate(),
|
||||
HASerializer::ProgmemPropertyValue
|
||||
);
|
||||
}
|
||||
|
||||
if (_minValue.isSet()) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAMinProperty),
|
||||
&_minValue,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_maxValue.isSet()) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAMaxProperty),
|
||||
&_maxValue,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_step.isSet()) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAStepProperty),
|
||||
&_step,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
HASerializer* HANumber::buildDeviceDiscoverySerializer()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
HASerializer* serializer = new HASerializer(this, 24);
|
||||
serializer->set(
|
||||
AHATOFSTR(HAPlatformProperty),
|
||||
AHATOFSTR(HAComponentNumber),
|
||||
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);
|
||||
serializer->set(AHATOFSTR(HAUnitOfMeasurementProperty), nonEmptyString(_unitOfMeasurement));
|
||||
serializer->set(
|
||||
AHATOFSTR(HAModeProperty),
|
||||
getModeProperty(),
|
||||
HASerializer::ProgmemPropertyValue
|
||||
);
|
||||
|
||||
if (nonEmptyString(_valueTemplate)) {
|
||||
serializer->set(AHATOFSTR(HAValueTemplateProperty), _valueTemplate);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_payloadReset)) {
|
||||
serializer->set(AHATOFSTR(HAPayloadResetProperty), _payloadReset);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_commandTemplate)) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HACommandTemplateProperty),
|
||||
_commandTemplate
|
||||
);
|
||||
} else if (getBuiltInCommandTemplate()) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HACommandTemplateProperty),
|
||||
getBuiltInCommandTemplate(),
|
||||
HASerializer::ProgmemPropertyValue
|
||||
);
|
||||
}
|
||||
|
||||
if (_minValue.isSet()) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HAMinProperty),
|
||||
&_minValue,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_maxValue.isSet()) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HAMaxProperty),
|
||||
&_maxValue,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_step.isSet()) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HAStepProperty),
|
||||
&_step,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
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));
|
||||
return serializer;
|
||||
}
|
||||
|
||||
void HANumber::onMqttConnected()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (shouldPublishSingleComponentConfig()) {
|
||||
publishConfig();
|
||||
}
|
||||
publishAvailability();
|
||||
|
||||
if (!_retain) {
|
||||
publishState(_currentState);
|
||||
}
|
||||
|
||||
subscribeTopic(uniqueId(), AHATOFSTR(HACommandTopic));
|
||||
}
|
||||
|
||||
void HANumber::onMqttMessage(
|
||||
const char* topic,
|
||||
const uint8_t* payload,
|
||||
const uint16_t length
|
||||
)
|
||||
{
|
||||
if (HASerializer::compareDataTopics(
|
||||
topic,
|
||||
uniqueId(),
|
||||
AHATOFSTR(HACommandTopic)
|
||||
)) {
|
||||
handleCommand(payload, length);
|
||||
}
|
||||
}
|
||||
|
||||
bool HANumber::publishState(const HANumeric& state)
|
||||
{
|
||||
if (!state.isSet()) {
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
AHATOFSTR(HAStateNone),
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
const uint8_t size = state.calculateSize();
|
||||
if (size == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char str[size + 1]; // with null terminator
|
||||
str[size] = 0;
|
||||
state.toStr(str);
|
||||
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
str,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
void HANumber::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;
|
||||
}
|
||||
|
||||
if (
|
||||
_payloadReset
|
||||
&& _payloadReset[0] != '\0'
|
||||
&& length == strlen(_payloadReset)
|
||||
&& memcmp(cmd, _payloadReset, length) == 0
|
||||
) {
|
||||
if (_commandCallback) {
|
||||
_commandCallback(HANumeric(), this);
|
||||
}
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
if (_commandStdCallback) {
|
||||
_commandStdCallback(HANumeric(), this);
|
||||
}
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
|
||||
if (memcmp_P(cmd, HAStateNone, length) == 0) {
|
||||
if (_commandCallback) {
|
||||
_commandCallback(HANumeric(), this);
|
||||
}
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
if (_commandStdCallback) {
|
||||
_commandStdCallback(HANumeric(), this);
|
||||
}
|
||||
#endif
|
||||
} else {
|
||||
HANumeric number = HANumeric::fromStr(cmd, length);
|
||||
if (number.isSet()) {
|
||||
number.setPrecision(_precision);
|
||||
if (_commandCallback) {
|
||||
_commandCallback(number, this);
|
||||
}
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
if (_commandStdCallback) {
|
||||
_commandStdCallback(number, this);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const __FlashStringHelper* HANumber::getModeProperty() const
|
||||
{
|
||||
switch (_mode) {
|
||||
case ModeBox:
|
||||
return AHATOFSTR(HAModeBox);
|
||||
|
||||
case ModeSlider:
|
||||
return AHATOFSTR(HAModeSlider);
|
||||
|
||||
default:
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
const __FlashStringHelper* HANumber::getBuiltInCommandTemplate() const
|
||||
{
|
||||
switch (_precision) {
|
||||
case PrecisionP1:
|
||||
return AHATOFSTR(HAValueTemplateFloatP1);
|
||||
|
||||
case PrecisionP2:
|
||||
return AHATOFSTR(HAValueTemplateFloatP2);
|
||||
|
||||
case PrecisionP3:
|
||||
return AHATOFSTR(HAValueTemplateFloatP3);
|
||||
|
||||
default:
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,312 @@
|
||||
#ifndef AHA_HANUMBER_H
|
||||
#define AHA_HANUMBER_H
|
||||
|
||||
#include "HABaseDeviceType.h"
|
||||
#include "../utils/HANumeric.h"
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
#include <functional>
|
||||
#endif
|
||||
|
||||
#ifndef EX_ARDUINOHA_NUMBER
|
||||
|
||||
#define _SET_STATE_OVERLOAD(type) \
|
||||
/** @overload */ \
|
||||
inline bool setState(const type state, const bool force = false) \
|
||||
{ return setState(HANumeric(state, _precision), force); }
|
||||
|
||||
#define _SET_CURRENT_STATE_OVERLOAD(type) \
|
||||
/** @overload */ \
|
||||
inline void setCurrentState(const type state) \
|
||||
{ setCurrentState(HANumeric(state, _precision)); }
|
||||
|
||||
#define HANUMBER_CALLBACK(name) void (*name)(HANumeric number, HANumber* sender)
|
||||
|
||||
/**
|
||||
* HANumber adds a slider or a box in the Home Assistant panel
|
||||
* that controls the numeric value stored on your device.
|
||||
*
|
||||
* @note
|
||||
* You can find more information about this entity in the Home Assistant documentation:
|
||||
* https://www.home-assistant.io/integrations/number.mqtt/
|
||||
*/
|
||||
class HANumber : public HABaseDeviceType
|
||||
{
|
||||
public:
|
||||
/// Represents mode of the number.
|
||||
enum Mode {
|
||||
ModeAuto = 0,
|
||||
ModeBox,
|
||||
ModeSlider
|
||||
};
|
||||
|
||||
/**
|
||||
* Creates instance of the HANumber entity with the given numbers precision.
|
||||
* The given precision applies to the state, min, max and step values.
|
||||
*
|
||||
* @param uniqueId The unique ID of the number. It needs to be unique in a scope of your device.
|
||||
* @param precision Precision of the floating point number that will be displayed in the HA panel.
|
||||
*/
|
||||
HANumber(const char* uniqueId, const NumberPrecision precision = PrecisionP0);
|
||||
|
||||
/**
|
||||
* Changes state of the number 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 number.
|
||||
* @param force Forces to update state without comparing it to a previous known state.
|
||||
* @returns Returns `true` if MQTT message has been published successfully.
|
||||
*/
|
||||
bool setState(const HANumeric& state, const bool force = false);
|
||||
|
||||
_SET_STATE_OVERLOAD(int8_t)
|
||||
_SET_STATE_OVERLOAD(int16_t)
|
||||
_SET_STATE_OVERLOAD(int32_t)
|
||||
_SET_STATE_OVERLOAD(uint8_t)
|
||||
_SET_STATE_OVERLOAD(uint16_t)
|
||||
_SET_STATE_OVERLOAD(uint32_t)
|
||||
_SET_STATE_OVERLOAD(float)
|
||||
|
||||
#ifdef ARDUINOHA_INT_OVERLOAD
|
||||
_SET_STATE_OVERLOAD(int)
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Sets current state of the number without publishing it to Home Assistant.
|
||||
* This method may be useful if you want to change state before connection
|
||||
* with MQTT broker is acquired.
|
||||
*
|
||||
* @param state New state of the number.
|
||||
*/
|
||||
inline void setCurrentState(const HANumeric& state)
|
||||
{ if (state.getPrecision() == _precision) { _currentState = state; } }
|
||||
|
||||
_SET_CURRENT_STATE_OVERLOAD(int8_t)
|
||||
_SET_CURRENT_STATE_OVERLOAD(int16_t)
|
||||
_SET_CURRENT_STATE_OVERLOAD(int32_t)
|
||||
_SET_CURRENT_STATE_OVERLOAD(uint8_t)
|
||||
_SET_CURRENT_STATE_OVERLOAD(uint16_t)
|
||||
_SET_CURRENT_STATE_OVERLOAD(uint32_t)
|
||||
_SET_CURRENT_STATE_OVERLOAD(float)
|
||||
|
||||
#ifdef ARDUINOHA_INT_OVERLOAD
|
||||
_SET_CURRENT_STATE_OVERLOAD(int)
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Returns last known state of the number.
|
||||
* If setState method wasn't called the initial value will be returned.
|
||||
*/
|
||||
inline const HANumeric& getCurrentState() const
|
||||
{ return _currentState; }
|
||||
|
||||
/**
|
||||
* Sets class of the device.
|
||||
* You can find list of available values here: https://www.home-assistant.io/integrations/number/#device-class
|
||||
*
|
||||
* @param deviceClass The class name.
|
||||
*/
|
||||
inline void setDeviceClass(const char* deviceClass)
|
||||
{ _class = deviceClass; }
|
||||
|
||||
/**
|
||||
* Sets icon of the number.
|
||||
* 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 number'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 number state.
|
||||
* In this mode the number 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; }
|
||||
|
||||
/**
|
||||
* Sets mode of the number.
|
||||
* It controls how the number should be displayed in the UI.
|
||||
* By default it's `HANumber::ModeAuto`.
|
||||
*
|
||||
* @param mode Mode to set.
|
||||
*/
|
||||
inline void setMode(const Mode mode)
|
||||
{ _mode = mode; }
|
||||
|
||||
/**
|
||||
* Defines the units of measurement of the number, if any.
|
||||
*
|
||||
* @param units For example: °C, %
|
||||
*/
|
||||
inline void setUnitOfMeasurement(const char* unitOfMeasurement)
|
||||
{ _unitOfMeasurement = unitOfMeasurement; }
|
||||
|
||||
/**
|
||||
* Sets the minimum value that can be set from the Home Assistant panel.
|
||||
*
|
||||
* @param min The minimal value. By default the value is not set.
|
||||
*/
|
||||
inline void setMin(const float min)
|
||||
{ _minValue = HANumeric(min, _precision); }
|
||||
|
||||
/**
|
||||
* Sets the maximum value that can be set from the Home Assistant panel.
|
||||
*
|
||||
* @param min The maximum value. By default the value is not set.
|
||||
*/
|
||||
inline void setMax(const float max)
|
||||
{ _maxValue = HANumeric(max, _precision); }
|
||||
|
||||
/**
|
||||
* Sets step of the slider's movement in the Home Assistant panel.
|
||||
*
|
||||
* @param step The step value. Smallest value `0.001`. By default the value is not set.
|
||||
*/
|
||||
inline void setStep(const float step)
|
||||
{ _step = HANumeric(step, _precision); }
|
||||
|
||||
/**
|
||||
* Updates min/max/step and republishes discovery config.
|
||||
* This can be used when limits need to change at runtime.
|
||||
*
|
||||
* @param min The minimal value.
|
||||
* @param max The maximal value.
|
||||
* @param step The slider step value.
|
||||
*/
|
||||
void updateMinMaxStep(const float min, const float max, const float step);
|
||||
|
||||
void setValueTemplate(const char* valueTemplate);
|
||||
void setCommandTemplate(const char* commandTemplate);
|
||||
void setPayloadReset(const char* payloadReset);
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the number is changed in the HA panel.
|
||||
* Please note that it's not possible to register multiple callbacks for the same number.
|
||||
*
|
||||
* @param callback
|
||||
* @note In non-optimistic mode, the number must be reported back to HA using the HANumber::setState method.
|
||||
*/
|
||||
inline void onCommand(HANUMBER_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(HANumeric, HANumber*)>& 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 HANumeric& state);
|
||||
|
||||
/**
|
||||
* Parses the given command and executes the number's callback with proper value.
|
||||
*
|
||||
* @param cmd The data of the command.
|
||||
* @param length Length of the command.
|
||||
*/
|
||||
void handleCommand(const uint8_t* cmd, const uint16_t length);
|
||||
|
||||
/**
|
||||
* Returns progmem string representing mode of the number
|
||||
*/
|
||||
const __FlashStringHelper* getModeProperty() const;
|
||||
|
||||
/**
|
||||
* Built-in command template used for float precision (when no custom template is set).
|
||||
*/
|
||||
const __FlashStringHelper* getBuiltInCommandTemplate() const;
|
||||
|
||||
/// The precision of the number. By default it's `HANumber::PrecisionP0`.
|
||||
const NumberPrecision _precision;
|
||||
|
||||
/// The device class. It can be nullptr.
|
||||
const char* _class;
|
||||
|
||||
/// The icon of the number. It can be nullptr.
|
||||
const char* _icon;
|
||||
|
||||
/// The retain flag for the HA commands.
|
||||
bool _retain;
|
||||
|
||||
/// The optimistic mode of the number (`true` - enabled, `false` - disabled).
|
||||
bool _optimistic;
|
||||
|
||||
/// Controls how the number should be displayed in the UI. By default it's `HANumber::ModeAuto`.
|
||||
Mode _mode;
|
||||
|
||||
/// The unit of measurement for the sensor. It can be nullptr.
|
||||
const char* _unitOfMeasurement;
|
||||
|
||||
/// The minimal value that can be set from the HA panel.
|
||||
HANumeric _minValue;
|
||||
|
||||
/// The maximum value that can be set from the HA panel.
|
||||
HANumeric _maxValue;
|
||||
|
||||
/// The step of the slider's movement.
|
||||
HANumeric _step;
|
||||
|
||||
/// The current state of the number. By default the value is not set.
|
||||
HANumeric _currentState;
|
||||
|
||||
/// The callback that will be called when the command is received from the HA.
|
||||
HANUMBER_CALLBACK(_commandCallback);
|
||||
|
||||
const char* _commandTemplate;
|
||||
const char* _valueTemplate;
|
||||
const char* _payloadReset;
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
/// The std::function callback that will be called when the command is received from the HA.
|
||||
std::function<void(HANumeric, HANumber*)> _commandStdCallback;
|
||||
#endif
|
||||
};
|
||||
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,135 @@
|
||||
#include "HAScene.h"
|
||||
#ifndef EX_ARDUINOHA_SCENE
|
||||
|
||||
#include "../HAMqtt.h"
|
||||
#include "../utils/HASerializer.h"
|
||||
|
||||
HAScene::HAScene(const char* uniqueId) :
|
||||
HABaseDeviceType(AHATOFSTR(HAComponentScene), uniqueId),
|
||||
_icon(nullptr),
|
||||
_retain(false),
|
||||
_commandCallback(nullptr)
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
, _commandStdCallback()
|
||||
#endif
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void HAScene::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);
|
||||
|
||||
// optional property
|
||||
if (_retain) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HARetainProperty),
|
||||
&_retain,
|
||||
HASerializer::BoolPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
// HA 2022.10 throws an exception if this property is not set
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAPayloadOnProperty),
|
||||
AHATOFSTR(HAStateOn),
|
||||
HASerializer::ProgmemPropertyValue
|
||||
);
|
||||
|
||||
_serializer->set(HASerializer::WithAvailability);
|
||||
_serializer->topic(AHATOFSTR(HACommandTopic));
|
||||
}
|
||||
|
||||
HASerializer* HAScene::buildDeviceDiscoverySerializer()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
HASerializer* serializer = new HASerializer(this, 18);
|
||||
serializer->set(
|
||||
AHATOFSTR(HAPlatformProperty),
|
||||
AHATOFSTR(HAComponentScene),
|
||||
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
|
||||
);
|
||||
}
|
||||
|
||||
serializer->set(
|
||||
AHATOFSTR(HAPayloadOnProperty),
|
||||
AHATOFSTR(HAStateOn),
|
||||
HASerializer::ProgmemPropertyValue
|
||||
);
|
||||
serializer->set(HASerializer::WithAvailability);
|
||||
serializer->topic(AHATOFSTR(HACommandTopic));
|
||||
return serializer;
|
||||
}
|
||||
|
||||
void HAScene::onMqttConnected()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (shouldPublishSingleComponentConfig()) {
|
||||
publishConfig();
|
||||
}
|
||||
publishAvailability();
|
||||
subscribeTopic(uniqueId(), AHATOFSTR(HACommandTopic));
|
||||
}
|
||||
|
||||
void HAScene::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 (_commandCallback) {
|
||||
_commandCallback(this);
|
||||
}
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
if (_commandStdCallback) {
|
||||
_commandStdCallback(this);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,104 @@
|
||||
#ifndef AHA_HASCENE_H
|
||||
#define AHA_HASCENE_H
|
||||
|
||||
#include "HABaseDeviceType.h"
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
#include <functional>
|
||||
#endif
|
||||
|
||||
#ifndef EX_ARDUINOHA_SCENE
|
||||
|
||||
#define HASCENE_CALLBACK(name) void (*name)(HAScene* sender)
|
||||
|
||||
/**
|
||||
* HAScene adds a new scene to the Home Assistant that triggers your callback once activated.
|
||||
*
|
||||
* @note
|
||||
* You can find more information about this entity in the Home Assistant documentation:
|
||||
* https://www.home-assistant.io/integrations/scene.mqtt/
|
||||
*/
|
||||
class HAScene : public HABaseDeviceType
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @param uniqueId The unique ID of the scene. It needs to be unique in a scope of your device.
|
||||
*/
|
||||
HAScene(const char* uniqueId);
|
||||
|
||||
/**
|
||||
* Sets icon of the scene.
|
||||
* 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 scene'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; }
|
||||
|
||||
/**
|
||||
* Registers callback that will be called when the scene is activated in the HA panel.
|
||||
* Please note that it's not possible to register multiple callbacks for the same scene.
|
||||
*
|
||||
* @param callback
|
||||
*/
|
||||
inline void onCommand(HASCENE_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(HAScene*)>& 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 icon of the scene. It can be nullptr.
|
||||
const char* _icon;
|
||||
|
||||
/// The retain flag for the HA commands.
|
||||
bool _retain;
|
||||
|
||||
/// The command callback that will be called when scene is activated from the HA panel.
|
||||
HASCENE_CALLBACK(_commandCallback);
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
/// The std::function callback that will be called when scene is activated from the HA panel.
|
||||
std::function<void(HAScene*)> _commandStdCallback;
|
||||
#endif
|
||||
};
|
||||
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,295 @@
|
||||
#include "HASelect.h"
|
||||
#ifndef EX_ARDUINOHA_SELECT
|
||||
|
||||
#include "../HAMqtt.h"
|
||||
#include "../utils/HAUtils.h"
|
||||
#include "../utils/HADictionary.h"
|
||||
#include "../utils/HASerializer.h"
|
||||
|
||||
HASelect::HASelect(const char* uniqueId) :
|
||||
HABaseDeviceType(AHATOFSTR(HAComponentSelect), uniqueId),
|
||||
_options(nullptr),
|
||||
_currentState(-1),
|
||||
_icon(nullptr),
|
||||
_retain(false),
|
||||
_optimistic(false),
|
||||
_valueTemplate(nullptr),
|
||||
_commandTemplate(nullptr),
|
||||
_commandCallback(nullptr)
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
, _commandStdCallback()
|
||||
#endif
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
HASelect::~HASelect()
|
||||
{
|
||||
if (_options) {
|
||||
const uint8_t optionsNb = _options->getItemsNb();
|
||||
const HASerializerArray::ItemType* options = _options->getItems();
|
||||
|
||||
if (optionsNb > 1) {
|
||||
for (uint8_t i = 0; i < optionsNb; i++) {
|
||||
delete[] options[i];
|
||||
}
|
||||
}
|
||||
|
||||
delete _options;
|
||||
}
|
||||
}
|
||||
|
||||
void HASelect::setValueTemplate(const char* valueTemplate)
|
||||
{
|
||||
_valueTemplate = valueTemplate;
|
||||
}
|
||||
|
||||
void HASelect::setCommandTemplate(const char* commandTemplate)
|
||||
{
|
||||
_commandTemplate = commandTemplate;
|
||||
}
|
||||
|
||||
void HASelect::setOptions(const char* options)
|
||||
{
|
||||
if (!options || _options) { // options can be set only once
|
||||
return;
|
||||
}
|
||||
|
||||
const uint16_t optionsNb = HAUtils::countSemicolonSeparatedOptions(options);
|
||||
if (optionsNb == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const uint16_t optionsLen = strlen(options) + 1; // include null terminator
|
||||
_options = new HASerializerArray(optionsNb, false);
|
||||
|
||||
if (optionsNb == 1) {
|
||||
_options->add(options);
|
||||
return;
|
||||
}
|
||||
|
||||
uint16_t optionLen = 0;
|
||||
for (uint16_t i = 0; i < optionsLen; i++) {
|
||||
if (options[i] == ';' || options[i] == 0) {
|
||||
if (optionLen == 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
char* option = new char[optionLen + 1]; // including null terminator
|
||||
option[optionLen] = 0;
|
||||
memcpy(option, &options[i - optionLen], optionLen);
|
||||
|
||||
if (!_options->add(option)) {
|
||||
delete[] option;
|
||||
break;
|
||||
}
|
||||
optionLen = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
optionLen++;
|
||||
}
|
||||
}
|
||||
|
||||
bool HASelect::setState(const int8_t state, const bool force)
|
||||
{
|
||||
if (!force && _currentState == state) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!_options || state >= _options->getItemsNb()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool published = publishState(state);
|
||||
_currentState = state;
|
||||
return published;
|
||||
}
|
||||
|
||||
const char* HASelect::getCurrentOption() const
|
||||
{
|
||||
return _options->getItem(getCurrentState());
|
||||
}
|
||||
|
||||
void HASelect::buildSerializer()
|
||||
{
|
||||
if (_serializer || !uniqueId() || !_options) {
|
||||
return;
|
||||
}
|
||||
|
||||
_serializer = new HASerializer(this, 20);
|
||||
_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(HAOptionsProperty),
|
||||
_options,
|
||||
HASerializer::ArrayPropertyType
|
||||
);
|
||||
|
||||
if (nonEmptyString(_valueTemplate)) {
|
||||
_serializer->set(AHATOFSTR(HAValueTemplateProperty), _valueTemplate);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_commandTemplate)) {
|
||||
_serializer->set(AHATOFSTR(HACommandTemplateProperty), _commandTemplate);
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
||||
HASerializer* HASelect::buildDeviceDiscoverySerializer()
|
||||
{
|
||||
if (!uniqueId() || !_options) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
HASerializer* serializer = new HASerializer(this, 20);
|
||||
serializer->set(
|
||||
AHATOFSTR(HAPlatformProperty),
|
||||
AHATOFSTR(HAComponentSelect),
|
||||
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(HAOptionsProperty),
|
||||
_options,
|
||||
HASerializer::ArrayPropertyType
|
||||
);
|
||||
|
||||
if (nonEmptyString(_valueTemplate)) {
|
||||
serializer->set(AHATOFSTR(HAValueTemplateProperty), _valueTemplate);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_commandTemplate)) {
|
||||
serializer->set(AHATOFSTR(HACommandTemplateProperty), _commandTemplate);
|
||||
}
|
||||
|
||||
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));
|
||||
return serializer;
|
||||
}
|
||||
|
||||
void HASelect::onMqttConnected()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (shouldPublishSingleComponentConfig()) {
|
||||
publishConfig();
|
||||
}
|
||||
publishAvailability();
|
||||
|
||||
if (!_retain) {
|
||||
publishState(_currentState);
|
||||
}
|
||||
|
||||
subscribeTopic(uniqueId(), AHATOFSTR(HACommandTopic));
|
||||
}
|
||||
|
||||
void HASelect::onMqttMessage(
|
||||
const char* topic,
|
||||
const uint8_t* payload,
|
||||
const uint16_t length
|
||||
)
|
||||
{
|
||||
const bool hasCommandCallback =
|
||||
_commandCallback
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
|| static_cast<bool>(_commandStdCallback)
|
||||
#endif
|
||||
;
|
||||
|
||||
if (hasCommandCallback && HASerializer::compareDataTopics(
|
||||
topic,
|
||||
uniqueId(),
|
||||
AHATOFSTR(HACommandTopic)
|
||||
)) {
|
||||
const uint8_t optionsNb = _options->getItemsNb();
|
||||
const HASerializerArray::ItemType* options = _options->getItems();
|
||||
|
||||
for (uint8_t i = 0; i < optionsNb; i++) {
|
||||
if (memcmp(payload, options[i], length) == 0) {
|
||||
if (_commandCallback) {
|
||||
_commandCallback(i, this);
|
||||
}
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
if (_commandStdCallback) {
|
||||
_commandStdCallback(i, this);
|
||||
}
|
||||
#endif
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool HASelect::publishState(const int8_t state)
|
||||
{
|
||||
if (!_options || state >= _options->getItemsNb()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (state < 0) {
|
||||
return publishOnDataTopic(AHATOFSTR(HAStateTopic), AHATOFSTR(HAStateNone), true);
|
||||
}
|
||||
|
||||
const char* item = _options->getItems()[state];
|
||||
if (!item) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return publishOnDataTopic(AHATOFSTR(HAStateTopic), item, true);
|
||||
}
|
||||
|
||||
uint8_t HASelect::countOptionsInString(const char* options) const
|
||||
{
|
||||
return HAUtils::countSemicolonSeparatedOptions(options);
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,199 @@
|
||||
#ifndef AHA_HASELECT_H
|
||||
#define AHA_HASELECT_H
|
||||
|
||||
#include "HABaseDeviceType.h"
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
#include <functional>
|
||||
#endif
|
||||
|
||||
#ifndef EX_ARDUINOHA_SELECT
|
||||
|
||||
class HASerializerArray;
|
||||
|
||||
#define HASELECT_CALLBACK(name) void (*name)(int8_t index, HASelect* sender)
|
||||
|
||||
/**
|
||||
* HASelect adds a dropdown with options in the Home Assistant panel.
|
||||
*
|
||||
* @note
|
||||
* You can find more information about this entity in the Home Assistant documentation:
|
||||
* https://www.home-assistant.io/integrations/button.mqtt/
|
||||
*/
|
||||
class HASelect : public HABaseDeviceType
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @param uniqueId The unique ID of the select. It needs to be unique in a scope of your device.
|
||||
*/
|
||||
HASelect(const char* uniqueId);
|
||||
~HASelect();
|
||||
|
||||
/**
|
||||
* Sets the list of available options that will be listed in the dropdown.
|
||||
* The input string should contain options separated using semicolons.
|
||||
* For example: `setOptions("Option A;Option B;Option C");
|
||||
*
|
||||
* @param options The list of options that are separated by semicolons.
|
||||
* @note The options list can be set only once.
|
||||
*/
|
||||
void setOptions(const char* options);
|
||||
|
||||
/**
|
||||
* Changes state of the select and publishes MQTT message.
|
||||
* State represents the index of the option that was set using the setOptions method.
|
||||
* 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 select. You can set `-1` to reset the select.
|
||||
* @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 int8_t state, const bool force = false);
|
||||
|
||||
/**
|
||||
* Returns the selected option based on the most recent state of the select.
|
||||
* You can utilize this method to get the string representation of the option (e.g. for printing).
|
||||
* If no option is selected, null is returned.
|
||||
*/
|
||||
const char* getCurrentOption() const;
|
||||
|
||||
/**
|
||||
* Sets the current state of the select without publishing it to Home Assistant.
|
||||
* State represents the index of the option that was set using the setOptions method.
|
||||
* 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 int8_t state)
|
||||
{ _currentState = state; }
|
||||
|
||||
/**
|
||||
* Returns last known state of the select.
|
||||
* State represents the index of the option that was set using the setOptions method.
|
||||
* By default the state is set to `-1`.
|
||||
*/
|
||||
inline int8_t getCurrentState() const
|
||||
{ return _currentState; }
|
||||
|
||||
/**
|
||||
* Sets icon of the select.
|
||||
* 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 select'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 select state.
|
||||
* In this mode the select 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; }
|
||||
|
||||
void setValueTemplate(const char* valueTemplate);
|
||||
void setCommandTemplate(const char* commandTemplate);
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the option is changed from the HA panel.
|
||||
* Please note that it's not possible to register multiple callbacks for the same select.
|
||||
*
|
||||
* @param callback
|
||||
* @note In non-optimistic mode, the selected option must be reported back to HA using the HASelect::setState method.
|
||||
*/
|
||||
inline void onCommand(HASELECT_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(int8_t, HASelect*)>& callback)
|
||||
{
|
||||
_commandCallback = nullptr;
|
||||
_commandStdCallback = callback;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef ARDUINOHA_TEST
|
||||
inline HASerializerArray* getOptions() const
|
||||
{ return _options; }
|
||||
#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 int8_t state);
|
||||
|
||||
/**
|
||||
* Counts the amount of options in the given string.
|
||||
*/
|
||||
uint8_t countOptionsInString(const char* options) const;
|
||||
|
||||
/// Array of options for the serializer.
|
||||
HASerializerArray* _options;
|
||||
|
||||
/// Stores the current state (the current option's index). By default it's `-1`.
|
||||
int8_t _currentState;
|
||||
|
||||
/// The icon of the select. It can be nullptr.
|
||||
const char* _icon;
|
||||
|
||||
/// The retain flag for the HA commands.
|
||||
bool _retain;
|
||||
|
||||
/// The optimistic mode of the select (`true` - enabled, `false` - disabled).
|
||||
bool _optimistic;
|
||||
|
||||
const char* _valueTemplate;
|
||||
const char* _commandTemplate;
|
||||
|
||||
/// The command callback that will be called when option is changed via the HA panel.
|
||||
HASELECT_CALLBACK(_commandCallback);
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
/// The std::function callback that will be called when option is changed via the HA panel.
|
||||
std::function<void(int8_t, HASelect*)> _commandStdCallback;
|
||||
#endif
|
||||
};
|
||||
|
||||
#endif
|
||||
#endif
|
||||
+252
-168
@@ -1,218 +1,302 @@
|
||||
#ifdef ARDUINO_ARCH_SAMD
|
||||
#include <avr/dtostrf.h>
|
||||
#endif
|
||||
|
||||
#include "HASensor.h"
|
||||
#ifdef ARDUINOHA_SENSOR
|
||||
#ifndef EX_ARDUINOHA_SENSOR
|
||||
|
||||
#include "../HAMqtt.h"
|
||||
#include "../HADevice.h"
|
||||
#include "../utils/HAUtils.h"
|
||||
#include "../utils/HADictionary.h"
|
||||
#include "../utils/HASerializer.h"
|
||||
#include "../utils/HASerializerArray.h"
|
||||
#include <string.h>
|
||||
|
||||
HASensor::HASensor(const char* name) :
|
||||
BaseDeviceType("sensor", name),
|
||||
_class(nullptr),
|
||||
_units(nullptr),
|
||||
_icon(nullptr)
|
||||
HASensor::HASensor(const char* uniqueId, const uint16_t features) :
|
||||
HABaseDeviceType(AHATOFSTR(HAComponentSensor), uniqueId),
|
||||
_features(features),
|
||||
_deviceClass(nullptr),
|
||||
_stateClass(nullptr),
|
||||
_forceUpdate(false),
|
||||
_icon(nullptr),
|
||||
_unitOfMeasurement(nullptr),
|
||||
_expireAfter(),
|
||||
_options(nullptr),
|
||||
_suggestedDisplayPrecision(),
|
||||
_valueTemplate(nullptr),
|
||||
_jsonAttributesTemplate(nullptr),
|
||||
_lastResetValueTemplate(nullptr)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
HASensor::HASensor(const char* name, HAMqtt& mqtt) :
|
||||
HASensor(name)
|
||||
HASensor::~HASensor()
|
||||
{
|
||||
(void)mqtt;
|
||||
if (_options) {
|
||||
const uint8_t optionsNb = _options->getItemsNb();
|
||||
const HASerializerArray::ItemType* options = _options->getItems();
|
||||
|
||||
if (optionsNb > 1) {
|
||||
for (uint8_t i = 0; i < optionsNb; i++) {
|
||||
delete[] options[i];
|
||||
}
|
||||
}
|
||||
|
||||
delete _options;
|
||||
}
|
||||
}
|
||||
|
||||
void HASensor::onMqttConnected()
|
||||
void HASensor::setSuggestedDisplayPrecision(uint8_t precision)
|
||||
{
|
||||
if (strlen(name()) == 0) {
|
||||
_suggestedDisplayPrecision = HANumeric(static_cast<uint8_t>(precision), 0);
|
||||
}
|
||||
|
||||
void HASensor::clearSuggestedDisplayPrecision()
|
||||
{
|
||||
_suggestedDisplayPrecision.reset();
|
||||
}
|
||||
|
||||
void HASensor::setOptions(const char* options)
|
||||
{
|
||||
if (!options || _options) {
|
||||
return;
|
||||
}
|
||||
|
||||
publishConfig();
|
||||
publishAvailability();
|
||||
const uint16_t optionsNb = HAUtils::countSemicolonSeparatedOptions(options);
|
||||
if (optionsNb == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const uint16_t optionsLen = strlen(options) + 1;
|
||||
_options = new HASerializerArray(optionsNb, false);
|
||||
|
||||
if (optionsNb == 1) {
|
||||
_options->add(options);
|
||||
return;
|
||||
}
|
||||
|
||||
uint16_t optionLen = 0;
|
||||
for (uint16_t i = 0; i < optionsLen; i++) {
|
||||
if (options[i] == ';' || options[i] == 0) {
|
||||
if (optionLen == 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
char* option = new char[optionLen + 1];
|
||||
option[optionLen] = 0;
|
||||
memcpy(option, &options[i - optionLen], optionLen);
|
||||
|
||||
if (!_options->add(option)) {
|
||||
delete[] option;
|
||||
break;
|
||||
}
|
||||
optionLen = 0;
|
||||
continue;
|
||||
}
|
||||
|
||||
optionLen++;
|
||||
}
|
||||
}
|
||||
|
||||
void HASensor::setValueTemplate(const char* valueTemplate)
|
||||
{
|
||||
_valueTemplate = valueTemplate;
|
||||
}
|
||||
|
||||
void HASensor::setJsonAttributesTemplate(const char* jsonAttributesTemplate)
|
||||
{
|
||||
_jsonAttributesTemplate = jsonAttributesTemplate;
|
||||
}
|
||||
|
||||
void HASensor::setLastResetValueTemplate(const char* lastResetValueTemplate)
|
||||
{
|
||||
_lastResetValueTemplate = lastResetValueTemplate;
|
||||
}
|
||||
|
||||
bool HASensor::setValue(const char* value)
|
||||
{
|
||||
return publishValue(value);
|
||||
}
|
||||
|
||||
bool HASensor::setValue(uint32_t value)
|
||||
{
|
||||
uint8_t digitsNb = floor(log10(value)) + 1;
|
||||
char str[digitsNb + 1]; // + null terminator
|
||||
memset(str, 0, sizeof(str));
|
||||
itoa(value, str, 10);
|
||||
|
||||
return publishValue(str);
|
||||
}
|
||||
|
||||
bool HASensor::setValue(int32_t value)
|
||||
{
|
||||
uint8_t digitsNb = floor(log10(value)) + 1;
|
||||
char str[digitsNb + 2]; // + null terminator and minus sign
|
||||
memset(str, 0, sizeof(str));
|
||||
itoa(value, str, 10);
|
||||
|
||||
return publishValue(str);
|
||||
}
|
||||
|
||||
bool HASensor::setValue(double value, uint8_t precision)
|
||||
{
|
||||
uint8_t digitsNb = floor(log10(floor(value))) + 1;
|
||||
char str[digitsNb + 3 + precision]; // null terminator, dot, minus sign
|
||||
dtostrf(value, 0, precision, str);
|
||||
|
||||
return publishValue(str);
|
||||
}
|
||||
|
||||
bool HASensor::setValue(float value, uint8_t precision)
|
||||
{
|
||||
uint8_t digitsNb = floor(log10(floor(value))) + 1;
|
||||
char str[digitsNb + 3 + precision]; // null terminator, dot, minus sign
|
||||
dtostrf(value, 0, precision, str);
|
||||
|
||||
return publishValue(str);
|
||||
}
|
||||
|
||||
bool HASensor::publishValue(const char* value)
|
||||
{
|
||||
if (strlen(name()) == 0 || value == nullptr) {
|
||||
return false;
|
||||
if (!value) {
|
||||
return publishOnDataTopic(AHATOFSTR(HAStateTopic), AHATOFSTR(HAStateNone), true);
|
||||
}
|
||||
|
||||
if (!mqtt()->isConnected()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint16_t& topicSize = DeviceTypeSerializer::calculateTopicLength(
|
||||
componentName(),
|
||||
name(),
|
||||
DeviceTypeSerializer::StateTopic
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char topic[topicSize];
|
||||
DeviceTypeSerializer::generateTopic(
|
||||
topic,
|
||||
componentName(),
|
||||
name(),
|
||||
DeviceTypeSerializer::StateTopic
|
||||
);
|
||||
|
||||
if (strlen(topic) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return mqtt()->publish(topic, value, true);
|
||||
return publishOnDataTopic(AHATOFSTR(HAStateTopic), value, true);
|
||||
}
|
||||
|
||||
uint16_t HASensor::calculateSerializedLength(
|
||||
const char* serializedDevice
|
||||
) const
|
||||
bool HASensor::setJsonAttributes(const char* json)
|
||||
{
|
||||
if (serializedDevice == nullptr) {
|
||||
return 0;
|
||||
return publishOnDataTopic(AHATOFSTR(HAJsonAttributesTopic), json, true);
|
||||
}
|
||||
|
||||
void HASensor::setExpireAfter(uint16_t expireAfter)
|
||||
{
|
||||
if (expireAfter > 0) {
|
||||
_expireAfter.setBaseValue(expireAfter);
|
||||
} else {
|
||||
_expireAfter.reset();
|
||||
}
|
||||
}
|
||||
|
||||
void HASensor::buildSerializer()
|
||||
{
|
||||
if (_serializer || !uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const HADevice* device = mqtt()->getDevice();
|
||||
if (device == nullptr) {
|
||||
return 0;
|
||||
}
|
||||
_serializer = new HASerializer(this, 24);
|
||||
_serializer->set(AHATOFSTR(HANameProperty), _name);
|
||||
setEntityIdProperty(_serializer);
|
||||
_serializer->set(HASerializer::WithUniqueId);
|
||||
applyCommonEntityProperties(_serializer);
|
||||
_serializer->set(AHATOFSTR(HADeviceClassProperty), _deviceClass);
|
||||
_serializer->set(AHATOFSTR(HAStateClassProperty), _stateClass);
|
||||
_serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
|
||||
_serializer->set(AHATOFSTR(HAIconProperty), _icon);
|
||||
_serializer->set(AHATOFSTR(HAUnitOfMeasurementProperty), nonEmptyString(_unitOfMeasurement));
|
||||
|
||||
uint16_t size = 0;
|
||||
size += DeviceTypeSerializer::calculateBaseJsonDataSize();
|
||||
size += DeviceTypeSerializer::calculateNameFieldSize(name());
|
||||
size += DeviceTypeSerializer::calculateUniqueIdFieldSize(name());
|
||||
size += DeviceTypeSerializer::calculateDeviceFieldSize(serializedDevice);
|
||||
size += DeviceTypeSerializer::calculateAvailabilityFieldSize(this);
|
||||
|
||||
{
|
||||
const uint16_t& topicSize = DeviceTypeSerializer::calculateTopicLength(
|
||||
componentName(),
|
||||
name(),
|
||||
DeviceTypeSerializer::StateTopic,
|
||||
false
|
||||
if (_suggestedDisplayPrecision.isSet()) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HASuggestedDisplayPrecisionProperty),
|
||||
&_suggestedDisplayPrecision,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (topicSize == 0) {
|
||||
return 0;
|
||||
if (nonEmptyString(_valueTemplate)) {
|
||||
_serializer->set(AHATOFSTR(HAValueTemplateProperty), _valueTemplate);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_lastResetValueTemplate)) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HALastResetValueTemplateProperty),
|
||||
_lastResetValueTemplate
|
||||
);
|
||||
}
|
||||
|
||||
if (_options) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HASensorOptionsProperty),
|
||||
_options,
|
||||
HASerializer::ArrayPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_forceUpdate) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAForceUpdateProperty),
|
||||
&_forceUpdate,
|
||||
HASerializer::BoolPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_expireAfter.isSet()) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAExpireAfterProperty),
|
||||
&_expireAfter,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_features & JsonAttributesFeature) {
|
||||
_serializer->topic(AHATOFSTR(HAJsonAttributesTopic));
|
||||
if (nonEmptyString(_jsonAttributesTemplate)) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAJsonAttributesTemplateProperty),
|
||||
_jsonAttributesTemplate
|
||||
);
|
||||
}
|
||||
|
||||
// Format: "stat_t":"[TOPIC]"
|
||||
size += topicSize + 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
|
||||
}
|
||||
|
||||
// units of measurement
|
||||
if (_units != nullptr) {
|
||||
// Format: ,"unit_of_meas":"[UNITS]"
|
||||
size += strlen(_units) + 18; // 18 - length of the JSON decorators for this field
|
||||
}
|
||||
|
||||
// icon
|
||||
if (_icon != nullptr) {
|
||||
// Field format: ,"ic":"[ICON]"
|
||||
size += strlen(_icon) + 8; // 8 - length of the JSON decorators for this field
|
||||
}
|
||||
|
||||
return size; // exludes null terminator
|
||||
_serializer->set(HASerializer::WithDevice);
|
||||
_serializer->set(HASerializer::WithAvailability);
|
||||
_serializer->topic(AHATOFSTR(HAStateTopic));
|
||||
}
|
||||
|
||||
bool HASensor::writeSerializedData(const char* serializedDevice) const
|
||||
HASerializer* HASensor::buildDeviceDiscoverySerializer()
|
||||
{
|
||||
if (serializedDevice == nullptr) {
|
||||
return false;
|
||||
if (!uniqueId()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
DeviceTypeSerializer::mqttWriteBeginningJson();
|
||||
HASerializer* serializer = new HASerializer(this, 24);
|
||||
serializer->set(
|
||||
AHATOFSTR(HAPlatformProperty),
|
||||
AHATOFSTR(HAComponentSensor),
|
||||
HASerializer::ProgmemPropertyValue
|
||||
);
|
||||
serializer->set(AHATOFSTR(HANameProperty), _name);
|
||||
setEntityIdProperty(serializer);
|
||||
serializer->set(HASerializer::WithUniqueId);
|
||||
applyCommonEntityProperties(serializer);
|
||||
serializer->set(AHATOFSTR(HADeviceClassProperty), _deviceClass);
|
||||
serializer->set(AHATOFSTR(HAStateClassProperty), _stateClass);
|
||||
serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
|
||||
serializer->set(AHATOFSTR(HAIconProperty), _icon);
|
||||
serializer->set(AHATOFSTR(HAUnitOfMeasurementProperty), nonEmptyString(_unitOfMeasurement));
|
||||
|
||||
// state topic
|
||||
{
|
||||
static const char Prefix[] PROGMEM = {"\"stat_t\":\""};
|
||||
DeviceTypeSerializer::mqttWriteTopicField(
|
||||
this,
|
||||
Prefix,
|
||||
DeviceTypeSerializer::StateTopic
|
||||
if (_suggestedDisplayPrecision.isSet()) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HASuggestedDisplayPrecisionProperty),
|
||||
&_suggestedDisplayPrecision,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
// device class
|
||||
if (_class != nullptr) {
|
||||
static const char Prefix[] PROGMEM = {",\"dev_cla\":\""};
|
||||
DeviceTypeSerializer::mqttWriteConstCharField(Prefix, _class);
|
||||
if (nonEmptyString(_valueTemplate)) {
|
||||
serializer->set(AHATOFSTR(HAValueTemplateProperty), _valueTemplate);
|
||||
}
|
||||
|
||||
// units of measurement
|
||||
if (_units != nullptr) {
|
||||
static const char Prefix[] PROGMEM = {",\"unit_of_meas\":\""};
|
||||
DeviceTypeSerializer::mqttWriteConstCharField(Prefix, _units);
|
||||
}
|
||||
|
||||
// icon
|
||||
if (_icon != nullptr) {
|
||||
static const char Prefix[] PROGMEM = {",\"ic\":\""};
|
||||
DeviceTypeSerializer::mqttWriteConstCharField(
|
||||
Prefix,
|
||||
_icon
|
||||
if (nonEmptyString(_lastResetValueTemplate)) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HALastResetValueTemplateProperty),
|
||||
_lastResetValueTemplate
|
||||
);
|
||||
}
|
||||
|
||||
DeviceTypeSerializer::mqttWriteNameField(name());
|
||||
DeviceTypeSerializer::mqttWriteUniqueIdField(name());
|
||||
DeviceTypeSerializer::mqttWriteAvailabilityField(this);
|
||||
DeviceTypeSerializer::mqttWriteDeviceField(serializedDevice);
|
||||
DeviceTypeSerializer::mqttWriteEndJson();
|
||||
if (_options) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HASensorOptionsProperty),
|
||||
_options,
|
||||
HASerializer::ArrayPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
if (_forceUpdate) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HAForceUpdateProperty),
|
||||
&_forceUpdate,
|
||||
HASerializer::BoolPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_expireAfter.isSet()) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HAExpireAfterProperty),
|
||||
&_expireAfter,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_features & JsonAttributesFeature) {
|
||||
serializer->topic(AHATOFSTR(HAJsonAttributesTopic));
|
||||
if (nonEmptyString(_jsonAttributesTemplate)) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HAJsonAttributesTemplateProperty),
|
||||
_jsonAttributesTemplate
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
serializer->set(HASerializer::WithAvailability);
|
||||
serializer->topic(AHATOFSTR(HAStateTopic));
|
||||
return serializer;
|
||||
}
|
||||
|
||||
void HASensor::onMqttConnected()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (shouldPublishSingleComponentConfig()) {
|
||||
publishConfig();
|
||||
}
|
||||
publishAvailability();
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
+119
-54
@@ -1,89 +1,154 @@
|
||||
#ifndef AHA_HASENSOR_H
|
||||
#define AHA_HASENSOR_H
|
||||
|
||||
#include "BaseDeviceType.h"
|
||||
#include "HABaseDeviceType.h"
|
||||
#include "../utils/HANumeric.h"
|
||||
|
||||
#ifdef ARDUINOHA_SENSOR
|
||||
class HASerializerArray;
|
||||
|
||||
class HASensor : public BaseDeviceType
|
||||
#ifndef EX_ARDUINOHA_SENSOR
|
||||
|
||||
/**
|
||||
* HASensor allows to publish textual sensor values that will be displayed in the HA panel.
|
||||
* If you need to publish numbers then HASensorNumber is what you're looking for.
|
||||
*
|
||||
* @note It's not possible to define a sensor that publishes mixed values (e.g. string + integer values).
|
||||
* @note
|
||||
* You can find more information about this entity in the Home Assistant documentation:
|
||||
* https://www.home-assistant.io/integrations/sensor.mqtt/
|
||||
*/
|
||||
class HASensor : public HABaseDeviceType
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* Initializes binary sensor.
|
||||
*
|
||||
* @param name Name of the sensor. Recommendes characters: [a-z0-9\-_]
|
||||
*/
|
||||
HASensor(
|
||||
const char* name
|
||||
);
|
||||
HASensor(
|
||||
const char* name,
|
||||
HAMqtt& mqtt
|
||||
); // legacy constructor
|
||||
enum Features {
|
||||
DefaultFeatures = 0,
|
||||
JsonAttributesFeature = 1
|
||||
};
|
||||
|
||||
/**
|
||||
* Publishes configuration of the sensor to the MQTT.
|
||||
* @param uniqueId The unique ID of the sensor. It needs to be unique in a scope of your device.
|
||||
* @param features Features that should be enabled for the sensor.
|
||||
*/
|
||||
virtual void onMqttConnected() override;
|
||||
HASensor(const char* uniqueId, const uint16_t features = DefaultFeatures);
|
||||
|
||||
virtual ~HASensor();
|
||||
|
||||
/**
|
||||
* Publishes new value of the sensor.
|
||||
* Please note that connection to MQTT broker must be acquired.
|
||||
* Otherwise method will return false.
|
||||
* Publishes the MQTT message with the given value.
|
||||
* 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.
|
||||
*
|
||||
* @param state Value to publish.
|
||||
* @returns Returns true if MQTT message has been published successfully.
|
||||
* @param value String representation of the sensor's value.
|
||||
* @returns Returns `true` if MQTT message has been published successfully.
|
||||
*/
|
||||
bool setValue(const char* value);
|
||||
bool setValue(uint32_t value);
|
||||
bool setValue(int32_t value);
|
||||
bool setValue(double value, uint8_t precision = 2);
|
||||
bool setValue(float value, uint8_t precision = 2);
|
||||
|
||||
inline bool setValue(uint8_t value)
|
||||
{ return setValue(static_cast<uint32_t>(value)); }
|
||||
|
||||
inline bool setValue(uint16_t value)
|
||||
{ return setValue(static_cast<uint32_t>(value)); }
|
||||
|
||||
inline bool setValue(int8_t value)
|
||||
{ return setValue(static_cast<int32_t>(value)); }
|
||||
|
||||
inline bool setValue(int16_t value)
|
||||
{ return setValue(static_cast<int32_t>(value)); }
|
||||
|
||||
/**
|
||||
* The type/class of the sensor to set the icon in the frontend.
|
||||
* Publishes the given JSON data on the JSON attributes topic.
|
||||
* The `JsonAttributesFeature` has to be enabled prior to setting the value.
|
||||
*
|
||||
* @param className https://www.home-assistant.io/integrations/sensor/#device-class
|
||||
* @param json JSON attributes.
|
||||
*/
|
||||
inline void setDeviceClass(const char* className)
|
||||
{ _class = className; }
|
||||
bool setJsonAttributes(const char* json);
|
||||
|
||||
/**
|
||||
* Sets the number of seconds after the sensor’s state expires, if it’s not updated.
|
||||
* By default the sensors state never expires.
|
||||
*
|
||||
* @param expireAfter The number of seconds.
|
||||
*/
|
||||
void setExpireAfter(uint16_t expireAfter);
|
||||
|
||||
/**
|
||||
* Sets class of the device.
|
||||
* You can find list of available values here: https://www.home-assistant.io/integrations/sensor/#device-class
|
||||
*
|
||||
* @param deviceClass The class name.
|
||||
*/
|
||||
inline void setDeviceClass(const char* deviceClass)
|
||||
{ _deviceClass = deviceClass; }
|
||||
|
||||
/**
|
||||
* Sets class of the state for the long term stats.
|
||||
* See: https://developers.home-assistant.io/docs/core/entity/sensor/#long-term-statistics
|
||||
*
|
||||
* @param stateClass The class name.
|
||||
*/
|
||||
inline void setStateClass(const char* stateClass)
|
||||
{ _stateClass = stateClass; }
|
||||
|
||||
/**
|
||||
* Forces HA panel to process each incoming value (MQTT message).
|
||||
* It's useful if you want to have meaningful value graphs in history.
|
||||
*
|
||||
* @param forceUpdate
|
||||
*/
|
||||
inline void setForceUpdate(bool forceUpdate)
|
||||
{ _forceUpdate = forceUpdate; }
|
||||
|
||||
/**
|
||||
* Sets icon of the sensor.
|
||||
* Any icon from MaterialDesignIcons.com (for example: `mdi:home`).
|
||||
*
|
||||
* @param class The icon name.
|
||||
*/
|
||||
inline void setIcon(const char* icon)
|
||||
{ _icon = icon; }
|
||||
|
||||
/**
|
||||
* Defines the units of measurement of the sensor, if any.
|
||||
*
|
||||
* @param units For example: °C, %
|
||||
*/
|
||||
inline void setUnitOfMeasurement(const char* units)
|
||||
{ _units = units; }
|
||||
inline void setUnitOfMeasurement(const char* unitOfMeasurement)
|
||||
{ _unitOfMeasurement = unitOfMeasurement; }
|
||||
|
||||
void setSuggestedDisplayPrecision(uint8_t precision);
|
||||
void clearSuggestedDisplayPrecision();
|
||||
|
||||
/**
|
||||
* Sets icon of the sensor, e.g. `mdi:home`.
|
||||
*
|
||||
* @param icon Material Design Icon name with mdi: prefix.
|
||||
* Semicolon-separated options for device_class `enum`. Set only once.
|
||||
*/
|
||||
inline void setIcon(const char* icon)
|
||||
{ _icon = icon; }
|
||||
void setOptions(const char* options);
|
||||
|
||||
void setValueTemplate(const char* valueTemplate);
|
||||
void setJsonAttributesTemplate(const char* jsonAttributesTemplate);
|
||||
void setLastResetValueTemplate(const char* lastResetValueTemplate);
|
||||
|
||||
protected:
|
||||
virtual void buildSerializer() override final;
|
||||
virtual HASerializer* buildDeviceDiscoverySerializer() override;
|
||||
virtual bool supportsDeviceDiscovery() const override
|
||||
{ return true; }
|
||||
virtual void onMqttConnected() override;
|
||||
|
||||
private:
|
||||
bool publishValue(const char* value);
|
||||
uint16_t calculateSerializedLength(const char* serializedDevice) const override;
|
||||
bool writeSerializedData(const char* serializedDevice) const override;
|
||||
/// Features enabled for the sensor.
|
||||
const uint16_t _features;
|
||||
|
||||
const char* _class;
|
||||
const char* _units;
|
||||
/// The device class. It can be nullptr.
|
||||
const char* _deviceClass;
|
||||
|
||||
/// The state class for the long term stats. It can be nullptr. See: https://developers.home-assistant.io/docs/core/entity/sensor/#long-term-statistics
|
||||
const char* _stateClass;
|
||||
|
||||
/// The force update flag for the HA panel.
|
||||
bool _forceUpdate;
|
||||
|
||||
/// The icon of the sensor. It can be nullptr.
|
||||
const char* _icon;
|
||||
|
||||
/// The unit of measurement for the sensor. It can be nullptr.
|
||||
const char* _unitOfMeasurement;
|
||||
|
||||
/// 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;
|
||||
|
||||
HASerializerArray* _options;
|
||||
HANumeric _suggestedDisplayPrecision;
|
||||
const char* _valueTemplate;
|
||||
const char* _jsonAttributesTemplate;
|
||||
const char* _lastResetValueTemplate;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
#include "HASensorNumber.h"
|
||||
#ifndef EX_ARDUINOHA_SENSOR
|
||||
|
||||
#include "../utils/HASerializer.h"
|
||||
|
||||
HASensorNumber::HASensorNumber(
|
||||
const char* uniqueId,
|
||||
const NumberPrecision precision,
|
||||
const uint16_t features
|
||||
) :
|
||||
HASensor(uniqueId, features),
|
||||
_precision(precision),
|
||||
_currentValue()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
bool HASensorNumber::setValue(const HANumeric& value, const bool force)
|
||||
{
|
||||
if (value.getPrecision() != _precision) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!force && value == _currentValue) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool published = publishValue(value);
|
||||
_currentValue = value;
|
||||
return published;
|
||||
}
|
||||
|
||||
void HASensorNumber::onMqttConnected()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
HASensor::onMqttConnected();
|
||||
publishValue(_currentValue);
|
||||
}
|
||||
|
||||
bool HASensorNumber::publishValue(const HANumeric& value)
|
||||
{
|
||||
if (!value.isSet()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
uint8_t size = value.calculateSize();
|
||||
if (size == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char str[size + 1]; // with null terminator
|
||||
str[size] = 0;
|
||||
value.toStr(str);
|
||||
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
str,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
#endif
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user