mirror of
https://github.com/alexhopeoconnor/arduino-home-assistant.git
synced 2026-10-04 02:48:13 +10:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
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 | ||
|
|
15562fa74c | ||
|
|
70ccd26c75 | ||
|
|
4135d0991f |
@@ -0,0 +1 @@
|
||||
github: dawidchyrzynski
|
||||
@@ -0,0 +1,34 @@
|
||||
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: ./scripts/check-docs.sh
|
||||
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,27 @@
|
||||
name: Publish release
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
- 'v*'
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
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: ./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 }}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
.DS_Store
|
||||
tmp/
|
||||
|
||||
# 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/
|
||||
+144
@@ -0,0 +1,144 @@
|
||||
# Changelog
|
||||
|
||||
## 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.
|
||||
* Existing code using `setObjectId()` remains supported as a legacy fallback, but new projects should migrate to `setDefaultEntityId()`.
|
||||
* If you enable device discovery mode, avoid publishing per-entity discovery topics manually. Use `republishDiscovery()` when a runtime config change needs to refresh discovery state.
|
||||
|
||||
## 2.1.0
|
||||
|
||||
**New features:**
|
||||
* Added support for setting MQTT's keep alive [#153](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/153) by [@allenb2800](https://github.com/allenb2800)
|
||||
* Added support for the `state_class` property in the `HASensor` [#179](https://github.com/dawidchyrzynski/arduino-home-assistant/pull/179)
|
||||
* Implemented extended unique ID support for all device types. This allows you to prefix each device type's unique ID with the device ID, ensuring smooth deployment of identical code on multiple devices without encountering unique ID conflicts [#212](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/212)
|
||||
* Added support for the `configuration_url` property in the `HADevice` [#182](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/182)
|
||||
* Added `getCurrentOption` method to the `HASelect` device type [#163](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/163)
|
||||
* Added support for publishing the `None` state in the `HASelect` device type [#146](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/146)
|
||||
* Added support for publishing the `None` state in the `HASensor` device type [#175](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/175)
|
||||
* Added support for the `expire_after` property in the `HASensor` [#171](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/171)
|
||||
* Added support for the `expire_after` property in the `HABinarySensor` [#159](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/159)
|
||||
* Added support for the JSON attributes in the `HASensor`
|
||||
* Added support for the `object_id` property in all device types
|
||||
* Added `setBufferSize` method to the `HAMqtt` class [#202](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/202)
|
||||
* Added `getState` method to the `HAMqtt` class
|
||||
* Added `onDisconnected` callback method to the `HAMqtt` class
|
||||
* Added `onStateChanged` callback method to the `HAMqtt` class
|
||||
* Added support for Arduino Due [#137](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/137)
|
||||
|
||||
**Fixes:**
|
||||
* Fixed a bug with the maximum number of device types [#190](https://github.com/dawidchyrzynski/arduino-home-assistant/issues/190) by [@martaisty](https://github.com/martaisty)
|
||||
* Fixed compiler warning: `class 'HANumeric' is implicitly friends with itself` [#197](https://github.com/dawidchyrzynski/arduino-home-assistant/pull/197) by [@shedokan](https://github.com/shedokan)
|
||||
* The default limit for device types has been raised to 24 on processors other than ATMega328/ATMega168. The previous default limit of 6 led to confusion for many users.
|
||||
|
||||
## 2.0.0
|
||||
|
||||
**New features:**
|
||||
|
||||
* Added support for the `icon` property in the `HABinarySensor` (you can set the icon using `HABinarySensor::setIcon("iconName")`)
|
||||
* Added support for changing the current state of the `HABinarySensor` using `HABinarySensor::setCurrentState` method
|
||||
* Added support for forcing `setState` in `HABinarySensor` using a second argument as follows `HABinarySensor::setState(true, true)`
|
||||
* Added support for the `device_class` property in the `HACover` (you can set the class using `HACover::setDeviceClass("className")`
|
||||
* Added support for the `icon` property in the `HACover` (you can set the icon using `HACover::setIcon("iconName")`)
|
||||
* Added pointer of the sender to the `HACover` callback function
|
||||
* Added support for `optimistic` property in the `HACover` (you can change the mode using `HACover::setOptimistic(true)`)
|
||||
* Added support for forcing `setPosition` in `HACover` using a second argument as follows `HACover::setPosition(100, true)`
|
||||
* Added support for the `device_class` property in the `HASwitch` (you can set the class using `HASwitch::setDeviceClass("className")`
|
||||
* Added support for the `optimistic` property in the `HASwitch` (you can change the mode using `HASwitch::setOptimistic(true)`)
|
||||
* Added support for the `force_update` property in the `HASensor` (you can set the mode using `HASensor::setForceUpdate(true)`)
|
||||
* Added support for the `HAButton` device type
|
||||
* Added support for the `HADeviceTracker` device type
|
||||
* Added support for the `HACamera` device type
|
||||
* Added support for the `HALock` device type
|
||||
* Added support for the `HASelect` device type
|
||||
* Added support for the `HANumber` device type
|
||||
* Added support for the `HAScene` device type
|
||||
* Added support for the `HALight` device type
|
||||
|
||||
**Fixes:**
|
||||
* Last Will Message is now retained (#70)
|
||||
* Compilation error on SAMD family (#82)
|
||||
|
||||
**New examples:**
|
||||
* [Button](examples/button/button.ino) - adding simple buttons to the Home Assistant panel.
|
||||
|
||||
**Breaking changes:**
|
||||
|
||||
* Changed structure of all MQTT topics used in the library.
|
||||
* Changed constructor of the `HABinarySensor` class (removed `deviceClass` and `initialState` arguments)
|
||||
* Renamed `HABinarySensor::getState()` method to `HABinarySensor::getCurrentState()`
|
||||
* Replaced `HATriggers` with `HADeviceTrigger` - the new implementation is not backward compatible. Please check the updated example of the `multi-state-button`.
|
||||
* Renamed `HADevice::isOnline()` method to `HADevice::isAvailable()`
|
||||
* Renamed `HASwitch::onStateChanged` method to `HASwitch::onCommand`.
|
||||
* Renamed `HAFan::onStateChanged` method to `HAFan::onStateCommand`.
|
||||
* Renamed `HAFan::onSpeedChanged` method to `HAFan::onSpeedCommand`.
|
||||
* Changed logic of the `HASwitch` callback. Please check the `led-switch` example.
|
||||
* Refactored `HASensor` logic. It's now divided into two different classes: `HASensor` and `HASensorNumber`.
|
||||
* Removed all legacy constructors with `HAMqtt` argument
|
||||
* Removed `onConnectionFailed` callback from the `HAMqtt` class
|
||||
* The position in the `HACover` is now available as configurable feature. It's disabled by default.
|
||||
* Refactored `HAHVAC` class to support more features of the MQTT discovery. Please check the update example.
|
||||
|
||||
## 1.3.0
|
||||
|
||||
**New features:**
|
||||
* Added `onMessage()` method to HAMqtt class
|
||||
* Added support for HA Covers
|
||||
* Added support for setting different prefix for non-discovery topics (see [Advanced MQTT example](examples/mqtt-advanced/mqtt-advanced.ino))
|
||||
* Added `setName` method to HASensor
|
||||
* Added `setName` method to HASwitch
|
||||
* Added `onBeforeStateChanged` callback to HASwitch
|
||||
|
||||
**Improvements:**
|
||||
* Removed legacy properties from HAFan (Home Assistant 2021.4.4). Deprecated methods will be removed after a quarter (2021.7)
|
||||
* Separated `uniqueID` field from `name` in all devices types
|
||||
|
||||
## 1.2.0
|
||||
|
||||
**Breaking changes:**
|
||||
* Refactored HASensor implementation. Please take a look at [updated example](examples/sensor/sensor.ino)
|
||||
|
||||
**New features:**
|
||||
* Added support for HVAC
|
||||
* Added support for excluding devices types from the compilation using defines (see [src/ArduinoHADefines.h](src/ArduinoHADefines.h))
|
||||
* Added support for setting icon in HASwitch and HASensor
|
||||
* Added support for setting retain flag in HASwitch
|
||||
* Added support for text (const char*) payload in HASensor
|
||||
* Added support for fans (HAFan)
|
||||
* Added support for connecting to the MQTT broker using hostname
|
||||
* Added `onConnected()` method in the HAMqtt
|
||||
* Added `onConnectionFailed()` method in the HAMqtt
|
||||
* Added support for MQTT LWT (see [Advanced Availability example](examples/advanced-availability/advanced-availability.ino))
|
||||
|
||||
**Improvements:**
|
||||
* Optimized codebase and logic in all devices types
|
||||
* Updated all examples
|
||||
* Fixed compilation warnings in all classes
|
||||
@@ -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,55 +1,78 @@
|
||||
# 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.
|
||||
|
||||
* MQTT discovery (device is added to the Home Assistant panel automatically)
|
||||
* 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)
|
||||
* [LED switch](examples/led-switch/led-switch.ino)
|
||||
* [MQTT with credentials](examples/mqtt-with-credentials/mqtt-with-credentials.ino)
|
||||
* [Multi-state button](examples/multi-state-button/multi-state-button.ino)
|
||||
* [Sensor (temperature, humidity, etc.)](examples/sensor/sensor.ino)
|
||||
* [NodeMCU Wi-Fi](examples/nodemcu/nodemcu.ino)
|
||||
## 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
|
||||
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
|
||||
* Device triggers
|
||||
* Switches
|
||||
* Sensors
|
||||
* Tag scanner
|
||||
void loop() {
|
||||
mqtt.loop();
|
||||
// Call temperature.setValue(...) when your reading changes.
|
||||
}
|
||||
```
|
||||
|
||||
## Unsupported features
|
||||
Read [Getting started](docs/getting-started.md) before copying this into production: it explains object lifetime, MQTT lifecycle, ESP32 includes, and install routes.
|
||||
|
||||
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.
|
||||
## Install
|
||||
|
||||
# License
|
||||
```ini
|
||||
lib_deps =
|
||||
home-assistant-integration=https://github.com/alexhopeoconnor/arduino-home-assistant.git#v3.0.2
|
||||
```
|
||||
|
||||
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.
|
||||
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).
|
||||
|
||||
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.
|
||||
## Documentation
|
||||
|
||||
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
|
||||
The [documentation map](docs/README.md) is the starting point:
|
||||
|
||||
- [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.
|
||||
|
||||
## Development and releases
|
||||
|
||||
```bash
|
||||
./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,13 @@
|
||||
# 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).
|
||||
@@ -0,0 +1,79 @@
|
||||
# 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.
|
||||
|
||||
**Rule:** construct entity objects **after** `HAMqtt` so they can register with it.
|
||||
|
||||
### 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).
|
||||
- **Optional:** call `HAMqtt::enableDeviceDiscovery()` to publish a single **device** discovery payload with components under `cmps` (see project README for migration notes).
|
||||
|
||||
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()`**.
|
||||
|
||||
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 clear retained discovery for one entity.
|
||||
|
||||
If device discovery mode is enabled, the library clears stale per-entity configs when refreshing.
|
||||
|
||||
## 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 `HADevice`, `HAMqtt`, then entities in that order; create them before `mqtt.begin(...)`. Call `mqtt.loop()` regularly. 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,96 @@
|
||||
# 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.0.2
|
||||
```
|
||||
|
||||
**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, …) **after** `HAMqtt`, and register them before `begin()` where the API requires it.
|
||||
|
||||
### 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
|
||||
|
||||
## 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,144 @@
|
||||
# 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_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).
|
||||
@@ -0,0 +1,75 @@
|
||||
#include <Ethernet.h>
|
||||
#include <ArduinoHA.h>
|
||||
|
||||
#define INPUT_PIN 9
|
||||
#define BROKER_ADDR IPAddress(192,168,0,17)
|
||||
|
||||
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
|
||||
unsigned long lastReadAt = millis();
|
||||
unsigned long lastAvailabilityToggleAt = millis();
|
||||
bool lastInputState = false;
|
||||
|
||||
EthernetClient client;
|
||||
HADevice device(mac, sizeof(mac));
|
||||
HAMqtt mqtt(client, device);
|
||||
|
||||
// "myInput" is unique ID of the sensor. You should define you own ID.
|
||||
HABinarySensor sensor("myInput");
|
||||
|
||||
void setup() {
|
||||
pinMode(INPUT_PIN, INPUT_PULLUP);
|
||||
lastInputState = digitalRead(INPUT_PIN);
|
||||
|
||||
// you don't need to verify return status
|
||||
Ethernet.begin(mac);
|
||||
|
||||
lastReadAt = millis();
|
||||
lastAvailabilityToggleAt = millis();
|
||||
|
||||
// set device's details (optional)
|
||||
device.setName("Arduino");
|
||||
device.setSoftwareVersion("1.0.0");
|
||||
mqtt.setOriginSupportUrl("https://example.com/device-help");
|
||||
|
||||
sensor.setCurrentState(lastInputState); // optional
|
||||
sensor.setName("Door sensor"); // optional
|
||||
sensor.setDeviceClass("door"); // optional
|
||||
sensor.setPayloadAvailable("ready");
|
||||
sensor.setPayloadNotAvailable("lost");
|
||||
|
||||
// Optional multi-topic discovery metadata for external health sources.
|
||||
// Runtime availability publishing still uses sensor.setAvailability(...).
|
||||
// sensor.setAvailabilityMode("all");
|
||||
// sensor.addAvailabilityEntry("bridge/status");
|
||||
// sensor.addAvailabilityEntry("sensor/health", "{{ value_json.state }}");
|
||||
|
||||
// This method enables availability for all device types registered on the device.
|
||||
// For example, if you have 5 sensors on the same device, you can enable
|
||||
// shared availability and change availability state of all sensors using
|
||||
// single method call "device.setAvailability(false|true)"
|
||||
device.enableSharedAvailability();
|
||||
|
||||
// Optionally, you can enable MQTT LWT feature. If device will lose connection
|
||||
// to the broker, all device types related to it will be marked as offline in
|
||||
// the Home Assistant Panel.
|
||||
device.enableLastWill();
|
||||
|
||||
mqtt.begin(BROKER_ADDR);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
Ethernet.maintain();
|
||||
mqtt.loop();
|
||||
|
||||
if ((millis() - lastReadAt) > 30) { // read in 30ms interval
|
||||
// library produces MQTT message if a new state is different than the previous one
|
||||
sensor.setState(digitalRead(INPUT_PIN));
|
||||
lastInputState = sensor.getCurrentState();
|
||||
lastReadAt = millis();
|
||||
}
|
||||
|
||||
if ((millis() - lastAvailabilityToggleAt) > 5000) {
|
||||
device.setAvailability(!device.isAvailable());
|
||||
lastAvailabilityToggleAt = millis();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
#include <Ethernet.h>
|
||||
#include <ArduinoHA.h>
|
||||
|
||||
#define INPUT_PIN 9
|
||||
#define BROKER_ADDR IPAddress(192,168,0,17)
|
||||
|
||||
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
|
||||
unsigned long lastReadAt = millis();
|
||||
unsigned long lastAvailabilityToggleAt = millis();
|
||||
bool lastInputState = false;
|
||||
|
||||
EthernetClient client;
|
||||
HADevice device(mac, sizeof(mac));
|
||||
HAMqtt mqtt(client, device);
|
||||
|
||||
// "myInput" is unique ID of the sensor. You should define you own ID.
|
||||
HABinarySensor sensor("myInput");
|
||||
|
||||
void setup() {
|
||||
pinMode(INPUT_PIN, INPUT_PULLUP);
|
||||
lastInputState = digitalRead(INPUT_PIN);
|
||||
|
||||
// you don't need to verify return status
|
||||
Ethernet.begin(mac);
|
||||
|
||||
// turn on "availability" feature
|
||||
// this method also sets initial availability so you can use "true" or "false"
|
||||
sensor.setAvailability(false);
|
||||
|
||||
lastReadAt = millis();
|
||||
lastAvailabilityToggleAt = millis();
|
||||
|
||||
// set device's details (optional)
|
||||
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);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
Ethernet.maintain();
|
||||
mqtt.loop();
|
||||
|
||||
if ((millis() - lastReadAt) > 30) { // read in 30ms interval
|
||||
// library produces MQTT message if a new state is different than the previous one
|
||||
sensor.setState(digitalRead(INPUT_PIN));
|
||||
lastInputState = sensor.getCurrentState();
|
||||
lastReadAt = millis();
|
||||
}
|
||||
|
||||
if ((millis() - lastAvailabilityToggleAt) > 5000) {
|
||||
sensor.setAvailability(!sensor.isOnline());
|
||||
lastAvailabilityToggleAt = millis();
|
||||
}
|
||||
}
|
||||
@@ -12,9 +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)
|
||||
HABinarySensor sensor("input", "door", false, mqtt);
|
||||
// "myInput" is unique ID of the sensor. You should define you own ID.
|
||||
HABinarySensor sensor("myInput");
|
||||
|
||||
void setup() {
|
||||
pinMode(INPUT_PIN, INPUT_PULLUP);
|
||||
@@ -23,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);
|
||||
}
|
||||
|
||||
@@ -34,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,
|
||||
|
@@ -0,0 +1,67 @@
|
||||
#include <Ethernet.h>
|
||||
#include <ArduinoHA.h>
|
||||
|
||||
#define BROKER_ADDR IPAddress(192,168,0,17)
|
||||
|
||||
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
|
||||
|
||||
EthernetClient client;
|
||||
HADevice device(mac, sizeof(mac));
|
||||
HAMqtt mqtt(client, device);
|
||||
|
||||
// HAFan::SpeedsFeature enables support for setting different speeds of fan.
|
||||
// You can skip this argument if you don't need speed management.
|
||||
// "ventilation" is unique ID of the fan. You should define your own ID.
|
||||
HAFan fan("ventilation", HAFan::SpeedsFeature);
|
||||
|
||||
void onStateCommand(bool state, HAFan* sender) {
|
||||
Serial.print("State: ");
|
||||
Serial.println(state);
|
||||
|
||||
sender->setState(state); // report state back to the Home Assistant
|
||||
}
|
||||
|
||||
void onSpeedCommand(uint16_t speed, HAFan* sender) {
|
||||
Serial.print("Speed: ");
|
||||
Serial.println(speed);
|
||||
|
||||
sender->setSpeed(speed); // report speed back to the Home Assistant
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
|
||||
// you don't need to verify return status
|
||||
Ethernet.begin(mac);
|
||||
|
||||
// set device's details (optional)
|
||||
device.setName("Arduino");
|
||||
device.setSoftwareVersion("1.0.0");
|
||||
|
||||
// configure fan (optional)
|
||||
fan.setName("Bathroom");
|
||||
fan.setSpeedRangeMin(1);
|
||||
fan.setSpeedRangeMax(100);
|
||||
|
||||
// Optionally you can set retain flag for the HA commands
|
||||
// fan.setRetain(true);
|
||||
|
||||
// Optionally you can enable optimistic mode for the HAFan.
|
||||
// In this mode you won't need to report state back to the HA when commands are executed.
|
||||
// fan.setOptimistic(true);
|
||||
|
||||
// handle fan states
|
||||
fan.onStateCommand(onStateCommand);
|
||||
fan.onSpeedCommand(onSpeedCommand);
|
||||
|
||||
mqtt.begin(BROKER_ADDR);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
Ethernet.maintain();
|
||||
mqtt.loop();
|
||||
|
||||
// You can also change the state at runtime as shown below.
|
||||
// This kind of logic can be used if you want to control your fan using a button connected to the device.
|
||||
// fan.setState(true); // true (ON) or false (OFF)
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
#include <ESP8266WiFi.h>
|
||||
#include <ArduinoHA.h>
|
||||
|
||||
#define BROKER_ADDR IPAddress(192,168,0,17)
|
||||
#define WIFI_SSID "MyNetwork"
|
||||
#define WIFI_PASSWORD "MyPassword"
|
||||
|
||||
WiFiClient client;
|
||||
HADevice device;
|
||||
HAMqtt mqtt(client, device);
|
||||
|
||||
// By default HAHVAC supports only reporting of the temperature.
|
||||
// You can enable feature you need using the second argument of the constructor.
|
||||
// Please check the documentation of the HAHVAC class.
|
||||
HAHVAC hvac(
|
||||
"my_name",
|
||||
HAHVAC::TargetTemperatureFeature | HAHVAC::PowerFeature | HAHVAC::ModesFeature
|
||||
);
|
||||
|
||||
unsigned long lastTempPublishAt = 0;
|
||||
float lastTemp = 0;
|
||||
|
||||
void onTargetTemperatureCommand(HANumeric temperature, HAHVAC* sender) {
|
||||
float temperatureFloat = temperature.toFloat();
|
||||
|
||||
Serial.print("Target temperature: ");
|
||||
Serial.println(temperatureFloat);
|
||||
|
||||
sender->setTargetTemperature(temperature); // report target temperature back to the HA panel
|
||||
}
|
||||
|
||||
void onPowerCommand(bool state, HAHVAC* sender) {
|
||||
if (state) {
|
||||
Serial.println("Power on");
|
||||
} else {
|
||||
Serial.println("Power off");
|
||||
}
|
||||
}
|
||||
|
||||
void onModeCommand(HAHVAC::Mode mode, HAHVAC* sender) {
|
||||
Serial.print("Mode: ");
|
||||
if (mode == HAHVAC::OffMode) {
|
||||
Serial.println("off");
|
||||
} else if (mode == HAHVAC::AutoMode) {
|
||||
Serial.println("auto");
|
||||
} else if (mode == HAHVAC::CoolMode) {
|
||||
Serial.println("cool");
|
||||
} else if (mode == HAHVAC::HeatMode) {
|
||||
Serial.println("heat");
|
||||
} else if (mode == HAHVAC::DryMode) {
|
||||
Serial.println("dry");
|
||||
} else if (mode == HAHVAC::FanOnlyMode) {
|
||||
Serial.println("fan only");
|
||||
}
|
||||
|
||||
sender->setMode(mode); // report mode back to the HA panel
|
||||
}
|
||||
|
||||
void setup() {
|
||||
Serial.begin(9600);
|
||||
Serial.println("Starting...");
|
||||
|
||||
// Unique ID must be set!
|
||||
byte mac[WL_MAC_ADDR_LENGTH];
|
||||
WiFi.macAddress(mac);
|
||||
device.setUniqueId(mac, sizeof(mac));
|
||||
|
||||
// connect to wifi
|
||||
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
|
||||
while (WiFi.status() != WL_CONNECTED) {
|
||||
Serial.print(".");
|
||||
delay(500); // waiting for the connection
|
||||
}
|
||||
Serial.println();
|
||||
Serial.println("Connected to the network");
|
||||
|
||||
// set device's details (optional)
|
||||
device.setName("NodeMCU");
|
||||
device.setSoftwareVersion("1.0.0");
|
||||
|
||||
// assign callbacks (optional)
|
||||
hvac.onTargetTemperatureCommand(onTargetTemperatureCommand);
|
||||
hvac.onPowerCommand(onPowerCommand);
|
||||
hvac.onModeCommand(onModeCommand);
|
||||
|
||||
// configure HVAC (optional)
|
||||
hvac.setName("My HVAC");
|
||||
hvac.setMinTemp(10);
|
||||
hvac.setMaxTemp(30);
|
||||
hvac.setTempStep(0.5);
|
||||
|
||||
// You can set retain flag for the HA commands
|
||||
// hvac.setRetain(true);
|
||||
|
||||
// You can choose which modes should be available in the HA panel
|
||||
// hvac.setModes(HAHVAC::OffMode | HAHVAC::CoolMode);
|
||||
|
||||
mqtt.begin(BROKER_ADDR);
|
||||
}
|
||||
|
||||
void loop() {
|
||||
mqtt.loop();
|
||||
|
||||
if ((millis() - lastTempPublishAt) > 3000) {
|
||||
hvac.setCurrentTemperature(lastTemp);
|
||||
lastTempPublishAt = millis();
|
||||
lastTemp += 0.5;
|
||||
}
|
||||
}
|
||||
@@ -9,11 +9,14 @@ byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
|
||||
EthernetClient client;
|
||||
HADevice device(mac, sizeof(mac));
|
||||
HAMqtt mqtt(client, device);
|
||||
HASwitch led("led", false, mqtt); // you can use custom name in place of "led"
|
||||
|
||||
void onSwitchStateChanged(bool state, HASwitch* s)
|
||||
// "led" is unique ID of the switch. You should define your own ID.
|
||||
HASwitch led("led");
|
||||
|
||||
void onSwitchCommand(bool state, HASwitch* sender)
|
||||
{
|
||||
digitalWrite(LED_PIN, (state ? HIGH : LOW));
|
||||
sender->setState(state); // report state back to the Home Assistant
|
||||
}
|
||||
|
||||
void setup() {
|
||||
@@ -27,8 +30,17 @@ void setup() {
|
||||
device.setName("Arduino");
|
||||
device.setSoftwareVersion("1.0.0");
|
||||
|
||||
// set icon (optional)
|
||||
led.setIcon("mdi:lightbulb");
|
||||
led.setName("My LED");
|
||||
// led.setPayloadOn("ENABLE");
|
||||
// led.setPayloadOff("DISABLE");
|
||||
// led.setStateOn("running");
|
||||
// led.setStateOff("stopped");
|
||||
// led.setCommandTemplate("{{ value_json.command }}");
|
||||
|
||||
// handle switch state
|
||||
led.onStateChanged(onSwitchStateChanged);
|
||||
led.onCommand(onSwitchCommand);
|
||||
|
||||
mqtt.begin(BROKER_ADDR);
|
||||
}
|
||||
@@ -36,4 +48,8 @@ void setup() {
|
||||
void loop() {
|
||||
Ethernet.maintain();
|
||||
mqtt.loop();
|
||||
|
||||
// You can also change the state at runtime as shown below.
|
||||
// This kind of logic can be used if you want to control your switch using a button connected to the device.
|
||||
// led.setState(true); // use any state you want
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -11,11 +11,14 @@ byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
|
||||
EthernetClient client;
|
||||
HADevice device(mac, sizeof(mac));
|
||||
HAMqtt mqtt(client, device);
|
||||
HASwitch led("led", false, mqtt); // you can use custom name in place of "led"
|
||||
|
||||
void onSwitchStateChanged(bool state, HASwitch* s)
|
||||
// "led" is unique ID of the switch. You should define your own ID.
|
||||
HASwitch led("led");
|
||||
|
||||
void onSwitchCommand(bool state, HASwitch* sender)
|
||||
{
|
||||
digitalWrite(LED_PIN, (state ? HIGH : LOW));
|
||||
sender->setState(state); // report state back to the Home Assistant
|
||||
}
|
||||
|
||||
void setup() {
|
||||
@@ -30,7 +33,8 @@ void setup() {
|
||||
device.setSoftwareVersion("1.0.0");
|
||||
|
||||
// handle switch state
|
||||
led.onStateChanged(onSwitchStateChanged);
|
||||
led.onCommand(onSwitchCommand);
|
||||
led.setName("My LED"); // optional
|
||||
|
||||
mqtt.begin(BROKER_ADDR, BROKER_USERNAME, BROKER_PASSWORD);
|
||||
}
|
||||
|
||||
@@ -14,7 +14,9 @@ byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
|
||||
EthernetClient client;
|
||||
HADevice device(mac, sizeof(mac));
|
||||
HAMqtt mqtt(client, device);
|
||||
HATriggers triggers(mqtt);
|
||||
|
||||
HADeviceTrigger shortPressTrigger(HADeviceTrigger::ButtonShortPressType, BUTTON_NAME);
|
||||
HADeviceTrigger longPressTrigger(HADeviceTrigger::ButtonLongPressType, BUTTON_NAME);
|
||||
Button btn(BUTTON_PIN);
|
||||
bool holdingBtn = false;
|
||||
|
||||
@@ -22,15 +24,11 @@ void setup() {
|
||||
// you don't need to verify return status
|
||||
Ethernet.begin(mac);
|
||||
|
||||
Serial.println(Ethernet.localIP());
|
||||
|
||||
// set device's details (optional)
|
||||
device.setName("Arduino");
|
||||
device.setSoftwareVersion("1.0.0");
|
||||
|
||||
// setup triggers
|
||||
triggers.add("button_short_press", BUTTON_NAME);
|
||||
triggers.add("button_long_press", BUTTON_NAME);
|
||||
// setup JC button
|
||||
btn.begin();
|
||||
|
||||
mqtt.begin(BROKER_ADDR);
|
||||
@@ -42,13 +40,13 @@ void loop() {
|
||||
btn.read();
|
||||
|
||||
if (btn.pressedFor(3000) && !holdingBtn) {
|
||||
triggers.trigger("button_long_press", BUTTON_NAME);
|
||||
longPressTrigger.trigger();
|
||||
holdingBtn = true;
|
||||
} else if (btn.wasReleased()) {
|
||||
if (holdingBtn) {
|
||||
holdingBtn = false;
|
||||
} else {
|
||||
triggers.trigger("button_short_press", BUTTON_NAME);
|
||||
shortPressTrigger.trigger();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
#include <WiFiNINA.h>
|
||||
#include <ArduinoHA.h>
|
||||
|
||||
#define LED_PIN 9
|
||||
#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");
|
||||
|
||||
// set device's details (optional)
|
||||
device.setName("Nano 33 IoT");
|
||||
device.setSoftwareVersion("1.0.0");
|
||||
|
||||
// handle switch state
|
||||
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
|
||||
}
|
||||
@@ -6,22 +6,28 @@
|
||||
#define WIFI_SSID "MyNetwork"
|
||||
#define WIFI_PASSWORD "MyPassword"
|
||||
|
||||
byte mac[6];
|
||||
WiFiClient client;
|
||||
HADevice device(mac, sizeof(mac));
|
||||
HADevice device;
|
||||
HAMqtt mqtt(client, device);
|
||||
HASwitch led("led", false, mqtt); // you can use custom name in place of "led"
|
||||
|
||||
void onSwitchStateChanged(bool state, HASwitch* s)
|
||||
// "led" is unique ID of the switch. You should define your own ID.
|
||||
HASwitch led("led");
|
||||
|
||||
void onSwitchCommand(bool state, HASwitch* sender)
|
||||
{
|
||||
digitalWrite(LED_PIN, (state ? HIGH : LOW));
|
||||
sender->setState(state); // report state back to the Home Assistant
|
||||
}
|
||||
|
||||
void setup() {
|
||||
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);
|
||||
|
||||
@@ -39,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);
|
||||
}
|
||||
}
|
||||
+16
-21
@@ -4,25 +4,13 @@
|
||||
#define BROKER_ADDR IPAddress(192,168,0,17)
|
||||
|
||||
byte mac[] = {0x00, 0x10, 0xFA, 0x6E, 0x38, 0x4A};
|
||||
unsigned long lastSentAt = millis();
|
||||
double lastValue = 0;
|
||||
|
||||
EthernetClient client;
|
||||
HADevice device(mac, sizeof(mac));
|
||||
HAMqtt mqtt(client, device);
|
||||
|
||||
/**
|
||||
* Supported data types:
|
||||
* - uint8_t
|
||||
* - uint16_t (unsigned int)
|
||||
* - uint32_t (unsigned long)
|
||||
* - int8_t
|
||||
* - int16_t (int)
|
||||
* - int32_t (long)
|
||||
* - double
|
||||
* - float
|
||||
*/
|
||||
HASensor<double> temp("temp", 0, mqtt); // you can use custom name in place of "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
|
||||
@@ -32,8 +20,13 @@ void setup() {
|
||||
device.setName("Arduino");
|
||||
device.setSoftwareVersion("1.0.0");
|
||||
|
||||
// you can set custom units for the sensor (optional)
|
||||
temp.setUnitOfMeasurement("°C");
|
||||
// configure sensor (optional)
|
||||
valve.setIcon("mdi:home");
|
||||
valve.setName("Water valve");
|
||||
// valve.setValueTemplate("{{ value_json.state }}");
|
||||
// valve.setDeviceClass("enum");
|
||||
// valve.setOptions("open;opening;closed");
|
||||
// valve.setDefaultEntityId("sensor.water_valve");
|
||||
|
||||
mqtt.begin(BROKER_ADDR);
|
||||
}
|
||||
@@ -42,9 +35,11 @@ void loop() {
|
||||
Ethernet.maintain();
|
||||
mqtt.loop();
|
||||
|
||||
if ((millis() - lastSentAt) >= 5000) {
|
||||
lastSentAt = millis();
|
||||
lastValue = lastValue + 0.5;
|
||||
temp.setValue(lastValue);
|
||||
}
|
||||
// you can report different states as follows:
|
||||
// valve.setValue("open");
|
||||
// valve.setValue("opening");
|
||||
// valve.setValue("close");
|
||||
|
||||
// Unlike the other device types, the HASensor doesn't store the previous value that was set.
|
||||
// It means that the MQTT message is produced each time the setValue method is called.
|
||||
}
|
||||
|
||||
@@ -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.0.2",
|
||||
"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": "MIT",
|
||||
"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.0.1
|
||||
author=Dawid Chyrzynski <dawid.chyrzynski@gmail.com>
|
||||
maintainer=Dawid Chyrzynski <dawid.chyrzynski@gmail.com>
|
||||
version=3.0.2
|
||||
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,38 @@
|
||||
; 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
|
||||
platform = espressif8266
|
||||
board = d1_mini
|
||||
|
||||
[env:esp32]
|
||||
extends = common
|
||||
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
|
||||
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
+47
@@ -0,0 +1,47 @@
|
||||
#!/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
|
||||
|
||||
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
|
||||
|
||||
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 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}"
|
||||
+24
-3
@@ -1,14 +1,35 @@
|
||||
#ifndef AHA_ARDUINOHA_H
|
||||
#define AHA_ARDUINOHA_H
|
||||
|
||||
#include "ArduinoHALog.h"
|
||||
#include "ArduinoHALogTemplates.h"
|
||||
#include "HADevice.h"
|
||||
#include "HAMqtt.h"
|
||||
#include "HAUtils.h"
|
||||
#include "device-types/HABinarySensor.h"
|
||||
#include "device-types/HAButton.h"
|
||||
#include "device-types/HACamera.h"
|
||||
#include "device-types/HACover.h"
|
||||
#include "device-types/HADeviceTracker.h"
|
||||
#include "device-types/HADeviceTrigger.h"
|
||||
#include "device-types/HAFan.h"
|
||||
#include "device-types/HAHVAC.h"
|
||||
#include "device-types/HALight.h"
|
||||
#include "device-types/HALock.h"
|
||||
#include "device-types/HANumber.h"
|
||||
#include "device-types/HAScene.h"
|
||||
#include "device-types/HASelect.h"
|
||||
#include "device-types/HASensor.h"
|
||||
#include "device-types/HASensor.cpp"
|
||||
#include "device-types/HASensorNumber.h"
|
||||
#include "device-types/HASwitch.h"
|
||||
#include "device-types/HATagScanner.h"
|
||||
#include "device-types/HATriggers.h"
|
||||
#include "device-types/HAText.h"
|
||||
#include "utils/HAUtils.h"
|
||||
#include "utils/HANumeric.h"
|
||||
|
||||
#ifdef ARDUINOHA_TEST
|
||||
#include "mocks/PubSubClientMock.h"
|
||||
#include "utils/HADictionary.h"
|
||||
#include "utils/HASerializer.h"
|
||||
#endif
|
||||
|
||||
#endif
|
||||
|
||||
+61
-2
@@ -1,4 +1,63 @@
|
||||
// Turns on debug information of the ArduinoHA core.
|
||||
// Please note that you need to initialize serial interface manually
|
||||
// by calling Serial.begin([baudRate]) before initializing ArduinoHA.
|
||||
// Without a log sink (arduinoHASetLogSink), initialize Serial (e.g. Serial.begin(115200)) before ArduinoHA.
|
||||
// With a sink installed, the host is responsible for transport setup.
|
||||
// #define ARDUINOHA_DEBUG
|
||||
|
||||
#include "ArduinoHALog.h"
|
||||
|
||||
// These macros allow to exclude some parts of the library to save more resources.
|
||||
// #define EX_ARDUINOHA_BINARY_SENSOR
|
||||
// #define EX_ARDUINOHA_BUTTON
|
||||
// #define EX_ARDUINOHA_CAMERA
|
||||
// #define EX_ARDUINOHA_COVER
|
||||
// #define EX_ARDUINOHA_DEVICE_TRACKER
|
||||
// #define EX_ARDUINOHA_DEVICE_TRIGGER
|
||||
// #define EX_ARDUINOHA_FAN
|
||||
// #define EX_ARDUINOHA_HVAC
|
||||
// #define EX_ARDUINOHA_LIGHT
|
||||
// #define EX_ARDUINOHA_LOCK
|
||||
// #define EX_ARDUINOHA_NUMBER
|
||||
// #define EX_ARDUINOHA_SCENE
|
||||
// #define EX_ARDUINOHA_SELECT
|
||||
// #define EX_ARDUINOHA_SENSOR
|
||||
// #define EX_ARDUINOHA_SWITCH
|
||||
// #define EX_ARDUINOHA_TAG_SCANNER
|
||||
// #define EX_ARDUINOHA_TEXT
|
||||
|
||||
// Enables std::function overloads for entity callbacks.
|
||||
// Useful for capturing lambdas, but may increase binary size on constrained boards.
|
||||
// Define ARDUINOHA_DISABLE_STDFUNCTION to opt out.
|
||||
#if !defined(ARDUINOHA_DISABLE_STDFUNCTION)
|
||||
#define ARDUINOHA_ENABLE_STDFUNCTION
|
||||
#endif
|
||||
|
||||
// Current library version used in discovery origin metadata.
|
||||
#define ARDUINOHA_LIBRARY_VERSION "2.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
|
||||
+331
-61
@@ -1,101 +1,371 @@
|
||||
#include <Arduino.h>
|
||||
|
||||
#include "ArduinoHADefines.h"
|
||||
#include "HADevice.h"
|
||||
#include "HAUtils.h"
|
||||
#include "HAMqtt.h"
|
||||
#include "utils/HAUtils.h"
|
||||
#include "utils/HADictionary.h"
|
||||
#include "utils/HASerializer.h"
|
||||
#include <string.h>
|
||||
|
||||
static bool appendEscapedJsonString(char*& cursor, char* end, const char* value)
|
||||
{
|
||||
if (!cursor || !value || cursor >= end) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (cursor + 1 >= end) {
|
||||
return false;
|
||||
}
|
||||
|
||||
*cursor++ = '"';
|
||||
for (const char* p = value; *p != '\0'; p++) {
|
||||
if ((*p == '"' || *p == '\\') && cursor + 2 >= end) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (*p == '"' || *p == '\\') {
|
||||
*cursor++ = '\\';
|
||||
}
|
||||
|
||||
if (cursor + 1 >= end) {
|
||||
return false;
|
||||
}
|
||||
|
||||
*cursor++ = *p;
|
||||
}
|
||||
|
||||
if (cursor + 1 >= end) {
|
||||
return false;
|
||||
}
|
||||
|
||||
*cursor++ = '"';
|
||||
*cursor = 0;
|
||||
return true;
|
||||
}
|
||||
|
||||
#define HADEVICE_INIT \
|
||||
_manufacturer(nullptr), \
|
||||
_model(nullptr), \
|
||||
_name(nullptr), \
|
||||
_softwareVersion(nullptr)
|
||||
_ownsUniqueId(false), \
|
||||
_serializer(new HASerializer(nullptr, 16)), \
|
||||
_availabilityTopic(nullptr), \
|
||||
_sharedAvailability(false), \
|
||||
_available(true), \
|
||||
_extendedUniqueIds(false), \
|
||||
_payloadAvailable(nullptr), \
|
||||
_payloadNotAvailable(nullptr), \
|
||||
_connectionsJson(), \
|
||||
_hasConnections(false), \
|
||||
_connectionsPropertyRegistered(false)
|
||||
|
||||
HADevice::HADevice() :
|
||||
_uniqueId(nullptr),
|
||||
HADEVICE_INIT
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
|
||||
uint16_t HADevice::calculateSerializedLength() const
|
||||
HADevice::~HADevice()
|
||||
{
|
||||
uint16_t size =
|
||||
3 + // opening and closing bracket + null terminator
|
||||
strlen(_uniqueId) + 8; // 8 - length of the JSON data for this field
|
||||
delete _serializer;
|
||||
|
||||
if (_manufacturer != nullptr) {
|
||||
size += strlen(_manufacturer) + 8; // 8 - length of the JSON data for this field
|
||||
if (_availabilityTopic) {
|
||||
delete[] _availabilityTopic;
|
||||
}
|
||||
|
||||
if (_model != nullptr) {
|
||||
size += strlen(_model) + 9; // 9 - length of the JSON data for this field
|
||||
if (_ownsUniqueId) {
|
||||
delete[] _uniqueId;
|
||||
}
|
||||
|
||||
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
|
||||
bool HADevice::setUniqueId(const byte* uniqueId, const uint16_t length)
|
||||
{
|
||||
static const char QuotationSign[] PROGMEM = {"\""};
|
||||
|
||||
{
|
||||
static const char DataBefore[] PROGMEM = {"{\"ids\":\""};
|
||||
|
||||
strcpy_P(dst, DataBefore);
|
||||
strcat(dst, _uniqueId);
|
||||
strcat_P(dst, QuotationSign);
|
||||
if (_uniqueId) {
|
||||
return false; // unique ID cannot be changed at runtime once it's set
|
||||
}
|
||||
|
||||
if (_manufacturer != nullptr) {
|
||||
static const char DataBefore[] PROGMEM = {",\"mf\":\""};
|
||||
_uniqueId = HAUtils::byteArrayToStr(uniqueId, length);
|
||||
_ownsUniqueId = true;
|
||||
_serializer->set(AHATOFSTR(HADeviceIdentifiersProperty), _uniqueId);
|
||||
return true;
|
||||
}
|
||||
|
||||
strcat_P(dst, DataBefore);
|
||||
strcat(dst, _manufacturer);
|
||||
strcat_P(dst, QuotationSign);
|
||||
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;
|
||||
}
|
||||
|
||||
if (_model != nullptr) {
|
||||
static const char DataBefore[] PROGMEM = {",\"mdl\":\""};
|
||||
_serializer->set(AHATOFSTR(HADeviceSerialNumberProperty), serialNumber);
|
||||
}
|
||||
|
||||
strcat_P(dst, DataBefore);
|
||||
strcat(dst, _model);
|
||||
strcat_P(dst, QuotationSign);
|
||||
void HADevice::setSuggestedArea(const char* suggestedArea)
|
||||
{
|
||||
if (!suggestedArea) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (_name != nullptr) {
|
||||
static const char DataBefore[] PROGMEM = {",\"name\":\""};
|
||||
_serializer->set(AHATOFSTR(HADeviceSuggestedAreaProperty), suggestedArea);
|
||||
}
|
||||
|
||||
strcat_P(dst, DataBefore);
|
||||
strcat(dst, _name);
|
||||
strcat_P(dst, QuotationSign);
|
||||
void HADevice::setViaDevice(const char* viaDevice)
|
||||
{
|
||||
if (!viaDevice) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (_softwareVersion != nullptr) {
|
||||
static const char DataBefore[] PROGMEM = {",\"sw\":\""};
|
||||
_serializer->set(AHATOFSTR(HADeviceViaDeviceProperty), viaDevice);
|
||||
}
|
||||
|
||||
strcat_P(dst, DataBefore);
|
||||
strcat(dst, _softwareVersion);
|
||||
strcat_P(dst, QuotationSign);
|
||||
bool HADevice::addConnection(const char* type, const char* value)
|
||||
{
|
||||
if (!type || !value || type[0] == '\0' || value[0] == '\0') {
|
||||
return false;
|
||||
}
|
||||
|
||||
{
|
||||
static const char Data[] PROGMEM = {"}"};
|
||||
strcat_P(dst, Data);
|
||||
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;
|
||||
|
||||
return strlen(dst) + 1; // size with null terminator
|
||||
if (!_connectionsPropertyRegistered) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HADeviceConnectionsProperty),
|
||||
_connectionsJson,
|
||||
HASerializer::JsonLiteralPropertyValue
|
||||
);
|
||||
_connectionsPropertyRegistered = true;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void HADevice::setConnectionsJson(const char* connectionsJson)
|
||||
{
|
||||
if (!connectionsJson || connectionsJson[0] == '\0') {
|
||||
return;
|
||||
}
|
||||
|
||||
strncpy(_connectionsJson, connectionsJson, MaxConnectionsJsonLength - 1);
|
||||
_connectionsJson[MaxConnectionsJsonLength - 1] = 0;
|
||||
_hasConnections = true;
|
||||
|
||||
if (!_connectionsPropertyRegistered) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HADeviceConnectionsProperty),
|
||||
_connectionsJson,
|
||||
HASerializer::JsonLiteralPropertyValue
|
||||
);
|
||||
_connectionsPropertyRegistered = true;
|
||||
}
|
||||
}
|
||||
|
||||
void HADevice::setPayloadAvailable(const char* payload)
|
||||
{
|
||||
_payloadAvailable = payload;
|
||||
}
|
||||
|
||||
void HADevice::setPayloadNotAvailable(const char* payload)
|
||||
{
|
||||
_payloadNotAvailable = payload;
|
||||
}
|
||||
|
||||
void HADevice::setAvailability(bool online)
|
||||
{
|
||||
_available = online;
|
||||
publishAvailability();
|
||||
}
|
||||
|
||||
bool HADevice::enableSharedAvailability()
|
||||
{
|
||||
if (_sharedAvailability) {
|
||||
return true; // already enabled
|
||||
}
|
||||
|
||||
const uint16_t topicLength = HASerializer::calculateDataTopicLength(
|
||||
nullptr,
|
||||
AHATOFSTR(HAAvailabilityTopic)
|
||||
);
|
||||
if (topicLength == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
_availabilityTopic = new char[topicLength];
|
||||
|
||||
if (HASerializer::generateDataTopic(
|
||||
_availabilityTopic,
|
||||
nullptr,
|
||||
AHATOFSTR(HAAvailabilityTopic)
|
||||
) > 0) {
|
||||
_sharedAvailability = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void HADevice::enableLastWill()
|
||||
{
|
||||
HAMqtt* mqtt = HAMqtt::instance();
|
||||
if (!mqtt || !_availabilityTopic) {
|
||||
return;
|
||||
}
|
||||
|
||||
const char* lw = (_payloadNotAvailable && _payloadNotAvailable[0] != '\0')
|
||||
? _payloadNotAvailable
|
||||
: "offline";
|
||||
|
||||
mqtt->setLastWill(
|
||||
_availabilityTopic,
|
||||
lw,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
void HADevice::publishAvailability() const
|
||||
{
|
||||
HAMqtt* mqtt = HAMqtt::instance();
|
||||
if (!_availabilityTopic || !mqtt) {
|
||||
return;
|
||||
}
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+197
-16
@@ -3,36 +3,217 @@
|
||||
|
||||
#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:
|
||||
HADevice(const char* uniqueId);
|
||||
HADevice(const byte* uniqueId, const uint16_t& length);
|
||||
/**
|
||||
* 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();
|
||||
|
||||
/**
|
||||
* 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();
|
||||
|
||||
/**
|
||||
* Returns pointer to the unique ID. It can be nullptr if the device has no ID assigned.
|
||||
*/
|
||||
inline const char* getUniqueId() const
|
||||
{ return _uniqueId; }
|
||||
|
||||
inline void setManufacturer(const char* manufacturer)
|
||||
{ _manufacturer = manufacturer; }
|
||||
/**
|
||||
* Returns the instance of the HASerializer used by the device.
|
||||
* This method is used by all entities to serialize device's representation.
|
||||
*/
|
||||
inline const HASerializer* getSerializer() const
|
||||
{ return _serializer; }
|
||||
|
||||
inline void setModel(const char* model)
|
||||
{ _model = model; }
|
||||
/**
|
||||
* Returns true if the shared availability is enabled for the device.
|
||||
*/
|
||||
inline bool isSharedAvailabilityEnabled() const
|
||||
{ return _sharedAvailability; }
|
||||
|
||||
inline void setName(const char* name)
|
||||
{ _name = name; }
|
||||
/**
|
||||
* Returns true if the extended unique IDs feature is enabled for the device.
|
||||
*/
|
||||
inline bool isExtendedUniqueIdsEnabled() const
|
||||
{ return _extendedUniqueIds; }
|
||||
|
||||
inline void setSoftwareVersion(const char* softwareVersion)
|
||||
{ _softwareVersion = softwareVersion; }
|
||||
/**
|
||||
* Returns availability topic generated by the HADevice::enableSharedAvailability method.
|
||||
* It can be nullptr if the shared availability is not enabled.
|
||||
*/
|
||||
inline const char* getAvailabilityTopic() const
|
||||
{ return _availabilityTopic; }
|
||||
|
||||
uint16_t calculateSerializedLength() const;
|
||||
uint16_t serialize(char* dst) const;
|
||||
/**
|
||||
* Returns online/offline state of the device.
|
||||
*/
|
||||
inline bool isAvailable() const
|
||||
{ return _available; }
|
||||
|
||||
/**
|
||||
* Enables the use of extended unique IDs for all registered device types.
|
||||
* The unique ID of each device type will be prefixed with the device's ID once enabled.
|
||||
*/
|
||||
inline void enableExtendedUniqueIds()
|
||||
{ _extendedUniqueIds = true; }
|
||||
|
||||
/**
|
||||
* Sets unique ID of the device based on the given byte array.
|
||||
* Each byte is converted into a hex string representation, so the final length of the unique ID will be twice as given.
|
||||
*
|
||||
* @param uniqueId Bytes array that's going to be converted into the string.
|
||||
* @param length Number of bytes in the array.
|
||||
* @note The unique ID can be set only once (via constructor or using this method).
|
||||
*/
|
||||
bool setUniqueId(const byte* uniqueId, const uint16_t length);
|
||||
|
||||
/**
|
||||
* Sets the "manufacturer" property that's going to be displayed in the Home Assistant.
|
||||
*
|
||||
* @param manufacturer Any string. Keep it short to save the memory.
|
||||
*/
|
||||
void setManufacturer(const char* manufacturer);
|
||||
|
||||
/**
|
||||
* Sets the "model" property that's going to be displayed in the Home Assistant.
|
||||
*
|
||||
* @param model Any string. Keep it short to save the memory.
|
||||
*/
|
||||
void setModel(const char* model);
|
||||
|
||||
/**
|
||||
* Sets the "name" property that's going to be displayed in the Home Assistant.
|
||||
*
|
||||
* @param name Any string. Keep it short to save the memory.
|
||||
*/
|
||||
void setName(const char* name);
|
||||
|
||||
/**
|
||||
* Sets the "software version" property that's going to be displayed in the Home Assistant.
|
||||
*
|
||||
* @param softwareVersion Any string. Keep it short to save the memory.
|
||||
*/
|
||||
void setSoftwareVersion(const char* softwareVersion);
|
||||
|
||||
/**
|
||||
* Sets the "configuration URL" property that's going to be used by the Home Assistant.
|
||||
*
|
||||
* @param url Configuration URL to publish.
|
||||
*/
|
||||
void setConfigurationUrl(const char* url);
|
||||
|
||||
void setModelId(const char* modelId);
|
||||
void setHardwareVersion(const char* hardwareVersion);
|
||||
void setSerialNumber(const char* serialNumber);
|
||||
void setSuggestedArea(const char* suggestedArea);
|
||||
void setViaDevice(const char* viaDevice);
|
||||
|
||||
/**
|
||||
* Adds one MQTT device connection entry (e.g. `("mac", "aa:bb:cc:dd:ee:ff")`).
|
||||
* Connections are serialized as JSON arrays inside the discovery `dev` object.
|
||||
*
|
||||
* @returns Returns `false` when the internal JSON buffer would overflow.
|
||||
*/
|
||||
bool addConnection(const char* type, const char* value);
|
||||
|
||||
/**
|
||||
* Sets the `connections` array as raw JSON (e.g. [[\"mac\",\"aa:bb:cc:dd:ee:ff\"]]).
|
||||
* The payload is copied into an internal buffer.
|
||||
*/
|
||||
void setConnectionsJson(const char* connectionsJson);
|
||||
|
||||
void setPayloadAvailable(const char* payload);
|
||||
void setPayloadNotAvailable(const char* payload);
|
||||
|
||||
inline const char* getPayloadAvailable() const
|
||||
{ return _payloadAvailable; }
|
||||
|
||||
inline const char* getPayloadNotAvailable() const
|
||||
{ return _payloadNotAvailable; }
|
||||
|
||||
/**
|
||||
* Sets device's availability and publishes MQTT message on the availability topic.
|
||||
* If the device is not connected to an MQTT broker or the shared availability is not enabled then nothing happens.
|
||||
*
|
||||
* @param online Set to true if the device should be displayed as available in the HA panel.
|
||||
*/
|
||||
void setAvailability(bool online);
|
||||
|
||||
/**
|
||||
* Enables the shared availability feature.
|
||||
*/
|
||||
bool enableSharedAvailability();
|
||||
|
||||
/**
|
||||
* Enables MQTT LWT feature.
|
||||
* Please note that the shared availability needs to be enabled first.
|
||||
*/
|
||||
void enableLastWill();
|
||||
|
||||
/**
|
||||
* Publishes current availability of the device on the availability topic.
|
||||
* If the device is not connected to an MQTT broker or the shared availability is not enabled then nothing happens.
|
||||
* This method is called by the HAMqtt when the connection to an MQTT broker is acquired.
|
||||
*/
|
||||
void publishAvailability() const;
|
||||
|
||||
private:
|
||||
/// The unique ID of the device. It can be a memory allocated by HADevice::setUniqueId method.
|
||||
const char* _uniqueId;
|
||||
const char* _manufacturer;
|
||||
const char* _model;
|
||||
const char* _name;
|
||||
const char* _softwareVersion;
|
||||
|
||||
/// Specifies whether HADevice class owns the _uniqueId pointer.
|
||||
bool _ownsUniqueId;
|
||||
|
||||
/// JSON serializer of the HADevice class. It's allocated in the constructor.
|
||||
HASerializer* _serializer;
|
||||
|
||||
/// The availability topic allocated by HADevice::enableSharedAvailability method.
|
||||
char* _availabilityTopic;
|
||||
|
||||
/// Specifies whether the shared availability is enabled.
|
||||
bool _sharedAvailability;
|
||||
|
||||
/// Specifies whether the device is available (online / offline).
|
||||
bool _available;
|
||||
|
||||
/// Specifies whether extended unique IDs feature is enabled.
|
||||
bool _extendedUniqueIds;
|
||||
|
||||
const char* _payloadAvailable;
|
||||
const char* _payloadNotAvailable;
|
||||
static const uint16_t MaxConnectionsJsonLength = 192;
|
||||
char _connectionsJson[MaxConnectionsJsonLength];
|
||||
bool _hasConnections;
|
||||
bool _connectionsPropertyRegistered;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
+886
-114
File diff suppressed because it is too large
Load Diff
+559
-42
@@ -2,97 +2,412 @@
|
||||
#define AHA_HAMQTT_H
|
||||
|
||||
#include <Arduino.h>
|
||||
#include <Client.h>
|
||||
#include <IPAddress.h>
|
||||
#include "ArduinoHADefines.h"
|
||||
|
||||
#define HAMQTT_CALLBACK(name) void (*name)()
|
||||
#define HAMQTT_STATE_CALLBACK(name) void (*name)(ConnectionState state)
|
||||
#define HAMQTT_MESSAGE_CALLBACK(name) void (*name)(const char* topic, const uint8_t* payload, uint16_t length)
|
||||
#define HAMQTT_DEFAULT_PORT 1883
|
||||
|
||||
#ifdef ARDUINOHA_TEST
|
||||
class PubSubClientMock;
|
||||
#else
|
||||
#include <PubSubClient.h>
|
||||
#endif
|
||||
|
||||
#if defined(__AVR_ATmega328P__) || defined(__AVR_ATmega168__)
|
||||
#define HAMQTT_DEFAULT_DEVICES_LIMIT 6
|
||||
#else
|
||||
#define HAMQTT_DEFAULT_DEVICES_LIMIT 24
|
||||
#endif
|
||||
|
||||
class IPAddress;
|
||||
class Client;
|
||||
class PubSubClient;
|
||||
class HADevice;
|
||||
class BaseDeviceType;
|
||||
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,
|
||||
};
|
||||
|
||||
HAMqtt(Client& netClient, HADevice& device);
|
||||
HAMqtt(const char* clientId, Client& netClient, HADevice& device);
|
||||
static const char* diagnosticDisconnectReasonText(DiagnosticDisconnectReason reason);
|
||||
|
||||
enum ConnectionState {
|
||||
StateConnecting = -5,
|
||||
StateConnectionTimeout = -4,
|
||||
StateConnectionLost = -3,
|
||||
StateConnectionFailed = -2,
|
||||
StateDisconnected = -1,
|
||||
StateConnected = 0,
|
||||
StateBadProtocol = 1,
|
||||
StateBadClientId = 2,
|
||||
StateUnavailable = 3,
|
||||
StateBadCredentials = 4,
|
||||
StateUnauthorized = 5
|
||||
};
|
||||
|
||||
/**
|
||||
* Sets prefix for Home Assistant discovery.
|
||||
* It needs to match prefix set in the HA admin panel.
|
||||
* Returns existing instance (singleton) of the HAMqtt class.
|
||||
* It may be a null pointer if the HAMqtt object was never constructed or it was destroyed.
|
||||
*/
|
||||
inline static HAMqtt* instance()
|
||||
{ return _instance; }
|
||||
|
||||
#ifdef ARDUINOHA_TEST
|
||||
explicit HAMqtt(
|
||||
PubSubClientMock* pubSub,
|
||||
HADevice& device,
|
||||
const uint8_t maxDevicesTypesNb = HAMQTT_DEFAULT_DEVICES_LIMIT
|
||||
);
|
||||
#else
|
||||
/**
|
||||
* Creates a new instance of the HAMqtt class.
|
||||
* Please note that only one instance of the class can be initialized at the same time.
|
||||
*
|
||||
* @param netClient The EthernetClient or WiFiClient that's going to be used for the network communication.
|
||||
* @param device An instance of the HADevice class representing your device.
|
||||
* @param maxDevicesTypesNb The maximum number of device types (sensors, switches, etc.) that you're going to implement.
|
||||
*/
|
||||
explicit HAMqtt(
|
||||
Client& netClient,
|
||||
HADevice& device,
|
||||
const uint8_t maxDevicesTypesNb = HAMQTT_DEFAULT_DEVICES_LIMIT
|
||||
);
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Removes singleton of the HAMqtt class.
|
||||
*/
|
||||
~HAMqtt();
|
||||
|
||||
/**
|
||||
* Sets the prefix of the Home Assistant discovery topics.
|
||||
* It needs to match the prefix set in the HA admin panel.
|
||||
* The default prefix is "homeassistant".
|
||||
*
|
||||
* @param prefix The discovery topics' prefix.
|
||||
*/
|
||||
inline void setDiscoveryPrefix(const char* prefix)
|
||||
{ _discoveryPrefix = prefix; }
|
||||
|
||||
/**
|
||||
* Returns discovery prefix.
|
||||
* Returns the discovery topics' prefix.
|
||||
*/
|
||||
inline const char* getDiscoveryPrefix() const
|
||||
{ return _discoveryPrefix; }
|
||||
|
||||
/**
|
||||
* Returns instance of the device assigned to the HAMqtt class.
|
||||
* Sets prefix of the data topics.
|
||||
* It may be useful if you want to pass MQTT traffic through a bridge.
|
||||
* The default prefix is "aha".
|
||||
*
|
||||
* @param prefix The data topics' prefix.
|
||||
*/
|
||||
inline HADevice const* getDevice() const
|
||||
{ return (_hasDevice ? &_device : nullptr); }
|
||||
inline void setDataPrefix(const char* prefix)
|
||||
{ _dataPrefix = prefix; }
|
||||
|
||||
/**
|
||||
* Sets parameters of the connection to the MQTT broker.
|
||||
* Returns the data topics' prefix.
|
||||
*/
|
||||
inline const char* getDataPrefix() const
|
||||
{ return _dataPrefix; }
|
||||
|
||||
/**
|
||||
* Enables MQTT device discovery payloads.
|
||||
* Single-component discovery remains the default when this is not enabled.
|
||||
*/
|
||||
inline void enableDeviceDiscovery()
|
||||
{ _deviceDiscoveryEnabled = true; }
|
||||
|
||||
/**
|
||||
* Returns true when MQTT device discovery payloads are enabled.
|
||||
*/
|
||||
inline bool isDeviceDiscoveryEnabled() const
|
||||
{ return _deviceDiscoveryEnabled; }
|
||||
|
||||
/**
|
||||
* Republishes the current MQTT device discovery payload when device
|
||||
* discovery is enabled.
|
||||
*/
|
||||
bool publishDeviceDiscovery();
|
||||
|
||||
/**
|
||||
* Sets optional `support_url` in the discovery `origin` object (must remain valid).
|
||||
*/
|
||||
inline void setOriginSupportUrl(const char* url)
|
||||
{ _originSupportUrl = url; }
|
||||
|
||||
inline const char* getOriginSupportUrl() const
|
||||
{ return _originSupportUrl; }
|
||||
|
||||
/**
|
||||
* Returns instance of the device assigned to the HAMqtt class.
|
||||
* It's the same object (pointer) that was passed to the HAMqtt constructor.
|
||||
*/
|
||||
inline HADevice const* getDevice() const
|
||||
{ return &_device; }
|
||||
|
||||
/**
|
||||
* Registers a new callback method that will be called when the device receives an MQTT message.
|
||||
* Please note that the callback is also fired by internal MQTT messages used by the library.
|
||||
* You should always verify the topic of the received message.
|
||||
*
|
||||
* @param callback Callback method.
|
||||
*/
|
||||
inline void onMessage(HAMQTT_MESSAGE_CALLBACK(callback))
|
||||
{ _messageCallback = callback; }
|
||||
|
||||
/**
|
||||
* Registers a new callback method that will be called each time a connection to the MQTT broker is acquired.
|
||||
* The callback is also fired after reconnecting to the broker.
|
||||
* You can use this method to register topics' subscriptions.
|
||||
*
|
||||
* @param callback Callback method.
|
||||
*/
|
||||
inline void onConnected(HAMQTT_CALLBACK(callback))
|
||||
{ _connectedCallback = callback; }
|
||||
|
||||
/**
|
||||
* Registers a new callback method that will be called each time the connection to the MQTT broker is lost.
|
||||
*
|
||||
* @param callback Callback method.
|
||||
*/
|
||||
inline void onDisconnected(HAMQTT_CALLBACK(callback))
|
||||
{ _disconnectedCallback = callback; }
|
||||
|
||||
/**
|
||||
* Registers a new callback method that will be called each time the connection state changes.
|
||||
*
|
||||
* @param callback Callback method.
|
||||
*/
|
||||
inline void onStateChanged(HAMQTT_STATE_CALLBACK(callback))
|
||||
{ _stateChangedCallback = callback; }
|
||||
|
||||
/**
|
||||
* Returns the current state of the MQTT connection.
|
||||
*/
|
||||
inline ConnectionState getState() const
|
||||
{ return _currentState; }
|
||||
|
||||
inline uint8_t getDeferredQueueCount() const
|
||||
{ return _deferredCount; }
|
||||
|
||||
inline uint32_t getLastLoopOkAt() const
|
||||
{ return _lastLoopOkAt; }
|
||||
|
||||
inline uint32_t getLastMessageAt() const
|
||||
{ return _lastMessageAt; }
|
||||
|
||||
inline uint32_t getLastPublishAt() const
|
||||
{ return _lastPublishAt; }
|
||||
|
||||
inline uint32_t getLastDisconnectAt() const
|
||||
{ return _lastDisconnectAt; }
|
||||
|
||||
inline DiagnosticDisconnectReason getLastDisconnectReason() const
|
||||
{ return _lastDisconnectReason; }
|
||||
|
||||
int getPubSubState() const;
|
||||
|
||||
/**
|
||||
* Sets parameters of the MQTT connection using the IP address and port.
|
||||
* The library will try to connect to the broker in first loop cycle.
|
||||
* Please note that the library automatically reconnects to the broker if connection is lost.
|
||||
*
|
||||
* @param serverIp IP address of the MQTT broker.
|
||||
* @param serverPort Port of the MQTT broker.
|
||||
* @param username Username for authentication.
|
||||
* @param password Password for authentication.
|
||||
* @param username Username for authentication. It can be nullptr if the anonymous connection needs to be performed.
|
||||
* @param password Password for authentication. It can be nullptr if the anonymous connection needs to be performed.
|
||||
*/
|
||||
bool begin(
|
||||
const IPAddress& serverIp,
|
||||
const uint16_t& serverPort = 1883,
|
||||
const IPAddress serverIp,
|
||||
const uint16_t serverPort = HAMQTT_DEFAULT_PORT,
|
||||
const char* username = nullptr,
|
||||
const char* password = nullptr
|
||||
);
|
||||
|
||||
/**
|
||||
* Sets parameters of the 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
|
||||
);
|
||||
|
||||
/**
|
||||
* ArduinoHA's ticker.
|
||||
* Sets parameters of the MQTT connection using the hostname and port.
|
||||
* The library will try to connect to the broker in first loop cycle.
|
||||
* Please note that the library automatically reconnects to the broker if connection is lost.
|
||||
*
|
||||
* @param serverHostname Hostname of the MQTT broker.
|
||||
* @param serverPort Port of the MQTT broker.
|
||||
* @param username Username for authentication. It can be nullptr if the anonymous connection needs to be performed.
|
||||
* @param password Password for authentication. It can be nullptr if the anonymous connection needs to be performed.
|
||||
*/
|
||||
bool begin(
|
||||
const char* serverHostname,
|
||||
const uint16_t serverPort = HAMQTT_DEFAULT_PORT,
|
||||
const char* username = nullptr,
|
||||
const char* password = nullptr
|
||||
);
|
||||
|
||||
/**
|
||||
* Sets parameters of the MQTT connection using the hostname and the default port (1883).
|
||||
* The library will try to connect to the broker in first loop cycle.
|
||||
* Please note that the library automatically reconnects to the broker if connection is lost.
|
||||
*
|
||||
* @param serverHostname Hostname of the MQTT broker.
|
||||
* @param username Username for authentication. It can be nullptr if the anonymous connection needs to be performed.
|
||||
* @param password Password for authentication. It can be nullptr if the anonymous connection needs to be performed.
|
||||
*/
|
||||
bool begin(
|
||||
const char* serverHostname,
|
||||
const char* username,
|
||||
const char* password
|
||||
);
|
||||
|
||||
/**
|
||||
* Closes the MQTT connection.
|
||||
*/
|
||||
bool disconnect();
|
||||
|
||||
/**
|
||||
* This method should be called periodically inside the main loop of the firmware.
|
||||
* It's safe to call this method in some interval (like 5ms).
|
||||
*/
|
||||
void loop();
|
||||
|
||||
/**
|
||||
* Returns true if connection to the MQTT broker is established.
|
||||
*/
|
||||
bool isConnected();
|
||||
bool isConnected() const;
|
||||
|
||||
/**
|
||||
* Sets keep alive for the MQTT connection.
|
||||
* By default it's 15 seconds.
|
||||
*
|
||||
* @param keepAlive Number of seconds to keep connection alive.
|
||||
*/
|
||||
void setKeepAlive(uint16_t keepAlive);
|
||||
|
||||
/**
|
||||
* Sets the buffer size for the MQTT connection.
|
||||
* By default it's 256 bytes.
|
||||
*
|
||||
* @param size Size of the buffer.
|
||||
*/
|
||||
bool setBufferSize(uint16_t size);
|
||||
|
||||
/**
|
||||
* Sets minimal interval between MQTT reconnect attempts.
|
||||
* By default it's 10000 milliseconds.
|
||||
*
|
||||
* @param interval Interval in milliseconds. Zero is ignored.
|
||||
*/
|
||||
void setReconnectInterval(uint16_t interval);
|
||||
|
||||
/**
|
||||
* Returns minimal interval between MQTT reconnect attempts.
|
||||
*/
|
||||
inline uint16_t getReconnectInterval() const
|
||||
{ return _reconnectInterval; }
|
||||
|
||||
/**
|
||||
* Adds a new device's type to the MQTT.
|
||||
* Each time the connection with MQTT broker is acquired, the HAMqtt class
|
||||
* calls "onMqttConnected" method in all devices' types instances.
|
||||
*
|
||||
* @param deviceType Instance of the device's type (eg. HATriggers).
|
||||
* @note The HAMqtt class doesn't take ownership of the given pointer.
|
||||
* @param deviceType Instance of the device's type (HASwitch, HABinarySensor, etc.).
|
||||
*/
|
||||
void addDeviceType(BaseDeviceType* deviceType);
|
||||
void addDeviceType(HABaseDeviceType* deviceType);
|
||||
|
||||
/**
|
||||
* Publishes MQTT message with given topic and payload.
|
||||
* Message won't be published if connection with MQTT broker is not established.
|
||||
* 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).
|
||||
*/
|
||||
void 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).
|
||||
*/
|
||||
void 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.
|
||||
*/
|
||||
void writePayload(const __FlashStringHelper* data);
|
||||
|
||||
/**
|
||||
* Finishes publishing of a message.
|
||||
* After calling this method the message will be processed by the broker.
|
||||
*/
|
||||
bool endPublish();
|
||||
|
||||
/**
|
||||
@@ -103,20 +418,89 @@ public:
|
||||
* Please note that you need to subscribe topic each time the connection
|
||||
* with the broker is acquired.
|
||||
*
|
||||
* @param topic Topic to subscribe
|
||||
* @param topic Topic to subscribe.
|
||||
*/
|
||||
bool subscribe(const char* topic);
|
||||
|
||||
/**
|
||||
* Enables the last will message that will be produced when the device disconnects from the broker.
|
||||
* If you want to change availability of the device in Home Assistant panel
|
||||
* please use enableLastWill() method from the HADevice class instead.
|
||||
*
|
||||
* @param lastWillTopic The topic to publish.
|
||||
* @param lastWillMessage The message (payload) to publish.
|
||||
* @param lastWillRetain Specifies whether the published message should be retained.
|
||||
*/
|
||||
inline void setLastWill(
|
||||
const char* lastWillTopic,
|
||||
const char* lastWillMessage,
|
||||
bool lastWillRetain
|
||||
) {
|
||||
_lastWillTopic = lastWillTopic;
|
||||
_lastWillMessage = lastWillMessage;
|
||||
_lastWillRetain = lastWillRetain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Processes MQTT message received from the broker (subscription).
|
||||
*
|
||||
* @note Do not use this method on your own. It's only for the internal purpose.
|
||||
* @param topic Topic of the message.
|
||||
* @param payload Content of the message.
|
||||
* @param length Length of the message.
|
||||
*/
|
||||
void processMessage(char* topic, uint8_t* payload, uint16_t length);
|
||||
void processMessage(const char* topic, const uint8_t* payload, uint16_t length);
|
||||
|
||||
/**
|
||||
* True while handling an inbound MQTT message (user onMessage and device onMqttMessage).
|
||||
* Publish attempts in this window are queued and flushed when dispatch completes.
|
||||
*/
|
||||
inline bool isProcessingMessage() const
|
||||
{ return _messageDispatchDepth > 0; }
|
||||
|
||||
#ifdef ARDUINOHA_TEST
|
||||
inline uint8_t getDevicesTypesNb() const
|
||||
{ return _devicesTypesNb; }
|
||||
|
||||
inline HABaseDeviceType** getDevicesTypes() const
|
||||
{ return _devicesTypes; }
|
||||
|
||||
inline uint16_t getDeferredPublishEnqueueCountForTest() const
|
||||
{ return _deferredPublishEnqueueCountForTest; }
|
||||
|
||||
inline void resetDeferredPublishTestCounters()
|
||||
{
|
||||
_deferredPublishEnqueueCountForTest = 0;
|
||||
_deferredFlushFailedForTest = false;
|
||||
_lastDeferredFlushErrorForTest = 0;
|
||||
}
|
||||
|
||||
inline uint8_t getPendingDeferredPublishesForTest() const
|
||||
{ return _deferredCount; }
|
||||
|
||||
inline bool hasDeferredFlushFailureForTest() const
|
||||
{ return _deferredFlushFailedForTest; }
|
||||
|
||||
inline uint8_t getLastDeferredFlushErrorForTest() const
|
||||
{ return _lastDeferredFlushErrorForTest; }
|
||||
|
||||
inline bool didDeferredFlushFailDueToDisconnectForTest() const
|
||||
{ return _lastDeferredFlushErrorForTest == 1; }
|
||||
|
||||
inline bool didDeferredFlushFailAtBeginPublishForTest() const
|
||||
{ return _lastDeferredFlushErrorForTest == 2; }
|
||||
|
||||
inline bool didDeferredFlushFailAtEndPublishForTest() const
|
||||
{ return _lastDeferredFlushErrorForTest == 3; }
|
||||
#endif
|
||||
|
||||
private:
|
||||
/// Default interval between MQTT reconnect attempts (milliseconds).
|
||||
static const uint16_t DefaultReconnectInterval = 10000;
|
||||
|
||||
/// Living instance of the HAMqtt class. It can be nullptr.
|
||||
static HAMqtt* _instance;
|
||||
|
||||
/**
|
||||
* Attempts to connect to the MQTT broker.
|
||||
* The method uses properties passed to the "begin" method.
|
||||
@@ -126,22 +510,155 @@ private:
|
||||
/**
|
||||
* This method is called each time the connection with MQTT broker is acquired.
|
||||
*/
|
||||
void onConnected();
|
||||
void onConnectedLogic();
|
||||
|
||||
const char* _clientId;
|
||||
Client& _netClient;
|
||||
HADevice& _device;
|
||||
bool _hasDevice;
|
||||
bool _initialized;
|
||||
const char* _discoveryPrefix;
|
||||
/**
|
||||
* 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;
|
||||
IPAddress* _serverIp;
|
||||
uint16_t _serverPort;
|
||||
#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;
|
||||
|
||||
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;
|
||||
|
||||
/// 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
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
#include <Arduino.h>
|
||||
|
||||
#include "HAUtils.h"
|
||||
|
||||
bool HAUtils::endsWith(const char* str, const char* suffix)
|
||||
{
|
||||
if (str == nullptr || suffix == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint16_t& lenstr = strlen(str);
|
||||
const uint16_t& lensuffix = strlen(suffix);
|
||||
|
||||
if (lensuffix > lenstr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return (strncmp(str + lenstr - lensuffix, suffix, lensuffix) == 0);
|
||||
}
|
||||
|
||||
void HAUtils::byteArrayToStr(
|
||||
char* dst,
|
||||
const byte* src,
|
||||
const uint16_t& length
|
||||
)
|
||||
{
|
||||
const uint16_t& finalLength = (length * 2);
|
||||
static const char map[] PROGMEM = {"0123456789abcdef"};
|
||||
|
||||
for (uint8_t i = 0; i < length; i++) {
|
||||
dst[i*2] = pgm_read_byte(&map[((char)src[i] & 0XF0) >> 4]);
|
||||
dst[i*2+1] = pgm_read_byte(&map[((char)src[i] & 0x0F)]);
|
||||
}
|
||||
|
||||
dst[finalLength] = '\0';
|
||||
}
|
||||
|
||||
char* HAUtils::byteArrayToStr(
|
||||
const byte* src,
|
||||
const uint16_t& length
|
||||
)
|
||||
{
|
||||
char* dst = (char*)malloc((length * 2) + 1); // include null terminator
|
||||
byteArrayToStr(dst, src, length);
|
||||
|
||||
return dst;
|
||||
}
|
||||
|
||||
uint8_t HAUtils::getValueTypeLength(const ValueType& type)
|
||||
{
|
||||
switch(type) {
|
||||
case ValueTypeUint8:
|
||||
return sizeof(uint8_t);
|
||||
|
||||
case ValueTypeUint16:
|
||||
return sizeof(uint16_t);
|
||||
|
||||
case ValueTypeUint32:
|
||||
return sizeof(uint32_t);
|
||||
|
||||
case ValueTypeInt8:
|
||||
return sizeof(int8_t);
|
||||
|
||||
case ValueTypeInt16:
|
||||
return sizeof(int16_t);
|
||||
|
||||
case ValueTypeInt32:
|
||||
return sizeof(int32_t);
|
||||
|
||||
case ValueTypeDouble:
|
||||
return sizeof(double);
|
||||
|
||||
case ValueTypeFloat:
|
||||
return sizeof(float);
|
||||
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
@@ -1,58 +0,0 @@
|
||||
#ifndef AHA_HAUTILS_H
|
||||
#define AHA_HAUTILS_H
|
||||
|
||||
#include <Arduino.h>
|
||||
|
||||
class HAUtils
|
||||
{
|
||||
public:
|
||||
enum ValueType {
|
||||
ValueTypeUnknown = -1,
|
||||
ValueTypeUint8,
|
||||
ValueTypeUint16,
|
||||
ValueTypeUint32,
|
||||
ValueTypeInt8,
|
||||
ValueTypeInt16,
|
||||
ValueTypeInt32,
|
||||
ValueTypeDouble,
|
||||
ValueTypeFloat
|
||||
};
|
||||
|
||||
static bool endsWith(
|
||||
const char* str,
|
||||
const char* suffi
|
||||
);
|
||||
static void byteArrayToStr(
|
||||
char* dst,
|
||||
const byte* src,
|
||||
const uint16_t& length
|
||||
);
|
||||
static char* byteArrayToStr(
|
||||
const byte* src,
|
||||
const uint16_t& length
|
||||
);
|
||||
|
||||
template <typename A, typename B >
|
||||
static bool compareType(A a, B b) { return false; }
|
||||
|
||||
template <typename A, typename B >
|
||||
static bool compareType(A a, A b) { return true; }
|
||||
|
||||
template <typename T>
|
||||
static ValueType determineValueType() {
|
||||
if (compareType<T, uint8_t>(0, (uint8_t)0)) return ValueTypeUint8;
|
||||
else if (compareType<T, uint16_t>(0, (uint16_t)0)) return ValueTypeUint16;
|
||||
else if (compareType<T, uint32_t>(0, (uint32_t)0)) return ValueTypeUint32;
|
||||
else if (compareType<T, int8_t>(0, (int8_t)0)) return ValueTypeInt8;
|
||||
else if (compareType<T, int16_t>(0, (int16_t)0)) return ValueTypeInt16;
|
||||
else if (compareType<T, int32_t>(0, (int32_t)0)) return ValueTypeInt32;
|
||||
else if (compareType<T, double>(0, (double)0)) return ValueTypeDouble;
|
||||
else if (compareType<T, float>(0, (float)0)) return ValueTypeFloat;
|
||||
|
||||
return ValueTypeUnknown;
|
||||
}
|
||||
|
||||
static uint8_t getValueTypeLength(const ValueType& type);
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -1,78 +0,0 @@
|
||||
#include "BaseDeviceType.h"
|
||||
#include "../HAMqtt.h"
|
||||
#include "../HADevice.h"
|
||||
|
||||
const char* BaseDeviceType::ConfigTopic = "config"; // todo: move to progmem
|
||||
const char* BaseDeviceType::EventTopic = "event";
|
||||
|
||||
BaseDeviceType::BaseDeviceType(HAMqtt& mqtt) :
|
||||
_mqtt(mqtt)
|
||||
{
|
||||
_mqtt.addDeviceType(this);
|
||||
}
|
||||
|
||||
BaseDeviceType::~BaseDeviceType()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
uint16_t BaseDeviceType::calculateTopicLength(
|
||||
const char* component,
|
||||
const char* objectId,
|
||||
const char* suffix,
|
||||
bool includeNullTerminator
|
||||
) const
|
||||
{
|
||||
// [discovery prefix]/[namespace]/[device id - optional]/subtype_type/[suffix]
|
||||
const char* prefix = _mqtt.getDiscoveryPrefix();
|
||||
if (prefix == nullptr) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint16_t size =
|
||||
strlen(prefix) + 1 + // with slash
|
||||
strlen(component) + 1 + // with slash
|
||||
strlen(suffix); // with null terminator
|
||||
|
||||
if (objectId != nullptr) {
|
||||
size += strlen(objectId) + 1; // with slash
|
||||
} else {
|
||||
size += 1; // slash
|
||||
}
|
||||
|
||||
if (_mqtt.getDevice() != nullptr) {
|
||||
size += strlen(_mqtt.getDevice()->getUniqueId()) + 1; // with slash
|
||||
}
|
||||
|
||||
if (includeNullTerminator) {
|
||||
size += 1;
|
||||
}
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
uint16_t BaseDeviceType::generateTopic(
|
||||
char* output,
|
||||
const char* component,
|
||||
const char* objectId,
|
||||
const char* suffix
|
||||
) const
|
||||
{
|
||||
static const char Slash[] PROGMEM = {"/"};
|
||||
|
||||
const char* prefix = _mqtt.getDiscoveryPrefix();
|
||||
strcpy(output, prefix);
|
||||
strcat_P(output, Slash);
|
||||
strcat(output, component);
|
||||
strcat_P(output, Slash);
|
||||
|
||||
if (_mqtt.getDevice() != nullptr) {
|
||||
strcat(output, _mqtt.getDevice()->getUniqueId());
|
||||
strcat_P(output, Slash);
|
||||
}
|
||||
|
||||
strcat(output, objectId);
|
||||
strcat_P(output, Slash);
|
||||
strcat(output, suffix);
|
||||
return strlen(output) + 1; // size with null terminator
|
||||
}
|
||||
@@ -1,46 +0,0 @@
|
||||
#ifndef AHA_BASEDEVICETYPE_H
|
||||
#define AHA_BASEDEVICETYPE_H
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
class HAMqtt;
|
||||
|
||||
class BaseDeviceType
|
||||
{
|
||||
public:
|
||||
static const char* ConfigTopic;
|
||||
static const char* EventTopic;
|
||||
|
||||
BaseDeviceType(HAMqtt& mqtt);
|
||||
virtual ~BaseDeviceType();
|
||||
|
||||
virtual void onMqttConnected() = 0;
|
||||
virtual void onMqttMessage(
|
||||
const char* topic,
|
||||
const uint8_t* payload,
|
||||
const uint16_t& length
|
||||
) { };
|
||||
|
||||
protected:
|
||||
inline HAMqtt* mqtt() const
|
||||
{ return &_mqtt; }
|
||||
|
||||
virtual uint16_t calculateTopicLength(
|
||||
const char* component,
|
||||
const char* objectId,
|
||||
const char* suffix,
|
||||
bool includeNullTerminator = true
|
||||
) const final;
|
||||
|
||||
virtual uint16_t generateTopic(
|
||||
char* output,
|
||||
const char* component,
|
||||
const char* objectId,
|
||||
const char* suffix
|
||||
) const final;
|
||||
|
||||
private:
|
||||
HAMqtt& _mqtt;
|
||||
};
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,607 @@
|
||||
#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(
|
||||
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(),
|
||||
_availability(AvailabilityDefault)
|
||||
{
|
||||
if (mqtt()) {
|
||||
mqtt()->addDeviceType(this);
|
||||
}
|
||||
}
|
||||
|
||||
HABaseDeviceType::~HABaseDeviceType()
|
||||
{
|
||||
destroySerializer();
|
||||
}
|
||||
|
||||
void HABaseDeviceType::setAvailability(bool online)
|
||||
{
|
||||
_availability = (online ? AvailabilityOnline : AvailabilityOffline);
|
||||
publishAvailability();
|
||||
}
|
||||
|
||||
bool HABaseDeviceType::removeFromDiscovery()
|
||||
{
|
||||
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 (!mqtt()->beginPublish(topic, 0, true)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return mqtt()->endPublish();
|
||||
}
|
||||
|
||||
bool HABaseDeviceType::republishDiscovery()
|
||||
{
|
||||
HAMqtt* mqttInstance = mqtt();
|
||||
if (!mqttInstance) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (shouldPublishSingleComponentConfig()) {
|
||||
return publishConfig();
|
||||
}
|
||||
|
||||
// Clear any stale per-entity retained config so device discovery remains
|
||||
// the single source of truth for supported entities.
|
||||
removeFromDiscovery();
|
||||
return mqttInstance->publishDeviceDiscovery();
|
||||
}
|
||||
|
||||
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()
|
||||
{
|
||||
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];
|
||||
HASerializer::generateConfigTopic(
|
||||
topic,
|
||||
componentName(),
|
||||
uniqueId()
|
||||
);
|
||||
|
||||
if (mqtt()->beginPublish(topic, dataLength, true)) {
|
||||
_serializer->flush();
|
||||
published = mqtt()->endPublish();
|
||||
}
|
||||
}
|
||||
|
||||
destroySerializer();
|
||||
return published;
|
||||
}
|
||||
|
||||
void HABaseDeviceType::publishAvailability()
|
||||
{
|
||||
const HADevice* device = mqtt()->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;
|
||||
}
|
||||
|
||||
const uint16_t len = strlen(payload);
|
||||
if (!mqtt()->beginPublish(fullTopic, len, retained)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
mqtt()->writePayload(payload, len);
|
||||
return mqtt()->endPublish();
|
||||
}
|
||||
|
||||
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
|
||||
)
|
||||
{
|
||||
if (!payload) {
|
||||
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 (mqtt()->beginPublish(fullTopic, length, retained)) {
|
||||
if (isProgmemData) {
|
||||
mqtt()->writePayload(AHATOFSTR(payload));
|
||||
} else {
|
||||
mqtt()->writePayload(payload, length);
|
||||
}
|
||||
|
||||
return mqtt()->endPublish();
|
||||
}
|
||||
|
||||
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);
|
||||
return;
|
||||
}
|
||||
|
||||
const char* objectId = nonEmptyString(_objectId);
|
||||
if (objectId) {
|
||||
serializer->set(AHATOFSTR(HAObjectIdProperty), objectId);
|
||||
}
|
||||
}
|
||||
|
||||
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,391 @@
|
||||
#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();
|
||||
|
||||
/**
|
||||
* 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 alias for the MQTT `object_id` discovery property.
|
||||
* Prefer setDefaultEntityId() for new code.
|
||||
*
|
||||
* @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.
|
||||
*/
|
||||
bool removeFromDiscovery();
|
||||
|
||||
/**
|
||||
* Republishes MQTT discovery config for this entity.
|
||||
*/
|
||||
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.
|
||||
* `default_entity_id` takes precedence and the legacy `object_id` is only
|
||||
* emitted when no default entity ID was configured.
|
||||
*/
|
||||
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;
|
||||
|
||||
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;
|
||||
const char* effectivePayloadNotAvailable() const;
|
||||
|
||||
friend class HAMqtt;
|
||||
friend class HASerializer;
|
||||
};
|
||||
|
||||
#endif
|
||||
+191
-233
@@ -1,266 +1,224 @@
|
||||
#include "HABinarySensor.h"
|
||||
#include "../ArduinoHADefines.h"
|
||||
#ifndef EX_ARDUINOHA_BINARY_SENSOR
|
||||
|
||||
#include "../HAMqtt.h"
|
||||
#include "../HADevice.h"
|
||||
#include "../HAUtils.h"
|
||||
#include "../utils/HADictionary.h"
|
||||
#include "../utils/HASerializer.h"
|
||||
|
||||
// todo: move all variables to progmem
|
||||
static const char* HAComponentName = "binary_sensor";
|
||||
static const char* StateTopic = "state";
|
||||
static const char* StateOn = "ON";
|
||||
static const char* StateOff = "OFF";
|
||||
|
||||
HABinarySensor::HABinarySensor(
|
||||
const char* name,
|
||||
bool initialState,
|
||||
HAMqtt& mqtt
|
||||
) :
|
||||
BaseDeviceType(mqtt),
|
||||
_name(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,
|
||||
const char* deviceClass,
|
||||
bool initialState,
|
||||
HAMqtt& mqtt
|
||||
) :
|
||||
BaseDeviceType(mqtt),
|
||||
_name(name),
|
||||
_class(deviceClass),
|
||||
_currentState(initialState)
|
||||
bool HABinarySensor::setState(const bool state, const bool force)
|
||||
{
|
||||
if (!force && state == _currentState) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool published = publishState(state);
|
||||
_currentState = state;
|
||||
return published;
|
||||
}
|
||||
|
||||
HABinarySensor::~HABinarySensor()
|
||||
void HABinarySensor::setExpireAfter(uint16_t expireAfter)
|
||||
{
|
||||
if (expireAfter > 0) {
|
||||
_expireAfter.setBaseValue(expireAfter);
|
||||
} else {
|
||||
_expireAfter.reset();
|
||||
}
|
||||
}
|
||||
|
||||
void HABinarySensor::setOffDelay(uint16_t seconds)
|
||||
{
|
||||
if (seconds > 0) {
|
||||
_offDelay.setBaseValue(seconds);
|
||||
} else {
|
||||
_offDelay.reset();
|
||||
}
|
||||
}
|
||||
|
||||
void HABinarySensor::clearOffDelay()
|
||||
{
|
||||
_offDelay.reset();
|
||||
}
|
||||
|
||||
void HABinarySensor::setValueTemplate(const char* valueTemplate)
|
||||
{
|
||||
_valueTemplate = valueTemplate;
|
||||
}
|
||||
|
||||
void HABinarySensor::buildSerializer()
|
||||
{
|
||||
if (_serializer || !uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
_serializer = new HASerializer(this, 20);
|
||||
_serializer->set(AHATOFSTR(HANameProperty), _name);
|
||||
setEntityIdProperty(_serializer);
|
||||
_serializer->set(HASerializer::WithUniqueId);
|
||||
applyCommonEntityProperties(_serializer);
|
||||
_serializer->set(AHATOFSTR(HADeviceClassProperty), _class);
|
||||
_serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
|
||||
_serializer->set(AHATOFSTR(HAIconProperty), _icon);
|
||||
|
||||
if (nonEmptyString(_payloadOn)) {
|
||||
_serializer->set(AHATOFSTR(HAPayloadOnProperty), _payloadOn);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_payloadOff)) {
|
||||
_serializer->set(AHATOFSTR(HAPayloadOffProperty), _payloadOff);
|
||||
}
|
||||
|
||||
if (_forceUpdate) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAForceUpdateProperty),
|
||||
&_forceUpdate,
|
||||
HASerializer::BoolPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_offDelay.isSet()) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAOffDelayProperty),
|
||||
&_offDelay,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_valueTemplate)) {
|
||||
_serializer->set(AHATOFSTR(HAValueTemplateProperty), _valueTemplate);
|
||||
}
|
||||
|
||||
if (_expireAfter.isSet()) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAExpireAfterProperty),
|
||||
&_expireAfter,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
_serializer->set(HASerializer::WithDevice);
|
||||
_serializer->set(HASerializer::WithAvailability);
|
||||
_serializer->topic(AHATOFSTR(HAStateTopic));
|
||||
}
|
||||
|
||||
HASerializer* HABinarySensor::buildDeviceDiscoverySerializer()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
HASerializer* serializer = new HASerializer(this, 20);
|
||||
serializer->set(
|
||||
AHATOFSTR(HAPlatformProperty),
|
||||
AHATOFSTR(HAComponentBinarySensor),
|
||||
HASerializer::ProgmemPropertyValue
|
||||
);
|
||||
serializer->set(AHATOFSTR(HANameProperty), _name);
|
||||
setEntityIdProperty(serializer);
|
||||
serializer->set(HASerializer::WithUniqueId);
|
||||
applyCommonEntityProperties(serializer);
|
||||
serializer->set(AHATOFSTR(HADeviceClassProperty), _class);
|
||||
serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
|
||||
serializer->set(AHATOFSTR(HAIconProperty), _icon);
|
||||
|
||||
if (nonEmptyString(_payloadOn)) {
|
||||
serializer->set(AHATOFSTR(HAPayloadOnProperty), _payloadOn);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_payloadOff)) {
|
||||
serializer->set(AHATOFSTR(HAPayloadOffProperty), _payloadOff);
|
||||
}
|
||||
|
||||
if (_forceUpdate) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HAForceUpdateProperty),
|
||||
&_forceUpdate,
|
||||
HASerializer::BoolPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_offDelay.isSet()) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HAOffDelayProperty),
|
||||
&_offDelay,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_valueTemplate)) {
|
||||
serializer->set(AHATOFSTR(HAValueTemplateProperty), _valueTemplate);
|
||||
}
|
||||
|
||||
if (_expireAfter.isSet()) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HAExpireAfterProperty),
|
||||
&_expireAfter,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
serializer->set(HASerializer::WithAvailability);
|
||||
serializer->topic(AHATOFSTR(HAStateTopic));
|
||||
return serializer;
|
||||
}
|
||||
|
||||
void HABinarySensor::onMqttConnected()
|
||||
{
|
||||
if (strlen(_name) == 0) {
|
||||
if (!uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
publishConfig();
|
||||
if (shouldPublishSingleComponentConfig()) {
|
||||
publishConfig();
|
||||
}
|
||||
publishAvailability();
|
||||
publishState(_currentState);
|
||||
}
|
||||
|
||||
bool HABinarySensor::setState(bool state)
|
||||
bool HABinarySensor::publishState(const bool state)
|
||||
{
|
||||
if (state == _currentState) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strlen(_name) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (publishState(state)) {
|
||||
_currentState = state;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void HABinarySensor::publishConfig()
|
||||
{
|
||||
const HADevice* device = mqtt()->getDevice();
|
||||
if (device == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
const uint16_t& deviceLength = device->calculateSerializedLength();
|
||||
if (deviceLength == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
char serializedDevice[deviceLength];
|
||||
if (device->serialize(serializedDevice) == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const uint16_t& topicLength = calculateTopicLength(HAComponentName, _name, ConfigTopic);
|
||||
const uint16_t& dataLength = calculateSerializedLength(serializedDevice);
|
||||
|
||||
if (topicLength == 0 || dataLength == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
char topic[topicLength];
|
||||
generateTopic(topic, HAComponentName, _name, ConfigTopic);
|
||||
|
||||
if (strlen(topic) == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (mqtt()->beginPublish(topic, dataLength, true)) {
|
||||
writeSerializedTrigger(serializedDevice);
|
||||
mqtt()->endPublish();
|
||||
}
|
||||
}
|
||||
|
||||
bool HABinarySensor::publishState(bool state)
|
||||
{
|
||||
if (strlen(_name) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint16_t& topicSize = calculateTopicLength(
|
||||
HAComponentName,
|
||||
_name,
|
||||
StateTopic
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char topic[topicSize];
|
||||
generateTopic(
|
||||
topic,
|
||||
HAComponentName,
|
||||
_name,
|
||||
StateTopic
|
||||
);
|
||||
|
||||
if (strlen(topic) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return mqtt()->publish(topic, (state ? StateOn : StateOff), true);
|
||||
}
|
||||
|
||||
uint16_t HABinarySensor::calculateSerializedLength(
|
||||
const char* serializedDevice
|
||||
) const
|
||||
{
|
||||
if (serializedDevice == nullptr) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const uint16_t& stateTopicLength = calculateTopicLength(
|
||||
HAComponentName,
|
||||
_name,
|
||||
StateTopic,
|
||||
false
|
||||
);
|
||||
|
||||
if (stateTopicLength == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint16_t size =
|
||||
2 + // opening and closing bracket (without null terminator)
|
||||
stateTopicLength + 11 + // 11 - length of the JSON data for this field
|
||||
strlen(_name) + 10; // 10 - length of the JSON data for this field
|
||||
|
||||
// unique ID
|
||||
size += strlen(mqtt()->getDevice()->getUniqueId());
|
||||
size += strlen(_name) + 14; // 14 - length of the JSON data for this field
|
||||
|
||||
// device class
|
||||
if (_class != nullptr) {
|
||||
size += strlen(_class) + 13; // 13 - length of the JSON data for this field
|
||||
}
|
||||
|
||||
// device
|
||||
size += strlen(serializedDevice) + 7; // 7 - length of the JSON data for this field
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
bool HABinarySensor::writeSerializedTrigger(const char* serializedDevice) const
|
||||
{
|
||||
if (serializedDevice == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
static const char QuotationSign[] PROGMEM = {"\""};
|
||||
|
||||
// state topic
|
||||
{
|
||||
const uint16_t& topicSize = calculateTopicLength(
|
||||
HAComponentName,
|
||||
_name,
|
||||
StateTopic
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
return false;
|
||||
if (state) {
|
||||
if (nonEmptyString(_payloadOn)) {
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
_payloadOn,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
char stateTopic[topicSize];
|
||||
generateTopic(
|
||||
stateTopic,
|
||||
HAComponentName,
|
||||
_name,
|
||||
StateTopic
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
AHATOFSTR(HAStateOn),
|
||||
true
|
||||
);
|
||||
|
||||
if (strlen(stateTopic) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
static const char DataBefore[] PROGMEM = {"{\"stat_t\":\""};
|
||||
|
||||
mqtt()->writePayload_P(DataBefore);
|
||||
mqtt()->writePayload(stateTopic, strlen(stateTopic));
|
||||
mqtt()->writePayload_P(QuotationSign);
|
||||
}
|
||||
|
||||
// name
|
||||
{
|
||||
static const char DataBefore[] PROGMEM = {",\"name\":\""};
|
||||
|
||||
mqtt()->writePayload_P(DataBefore);
|
||||
mqtt()->writePayload(_name, strlen(_name));
|
||||
mqtt()->writePayload_P(QuotationSign);
|
||||
if (nonEmptyString(_payloadOff)) {
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
_payloadOff,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
// unique ID
|
||||
{
|
||||
static const char Underscore[] PROGMEM = {"_"};
|
||||
static const char DataBefore[] PROGMEM = {",\"uniq_id\":\""};
|
||||
|
||||
const HADevice* device = mqtt()->getDevice();
|
||||
uint8_t uniqueIdLength = strlen(_name) + strlen(device->getUniqueId()) + 2; // underscore and null temrinator
|
||||
char uniqueId[uniqueIdLength];
|
||||
strcpy(uniqueId, _name);
|
||||
strcat_P(uniqueId, Underscore);
|
||||
strcat(uniqueId, device->getUniqueId());
|
||||
|
||||
mqtt()->writePayload_P(DataBefore);
|
||||
mqtt()->writePayload(uniqueId, strlen(uniqueId));
|
||||
mqtt()->writePayload_P(QuotationSign);
|
||||
}
|
||||
|
||||
// device
|
||||
{
|
||||
static const char Data[] PROGMEM = {",\"dev\":"};
|
||||
|
||||
mqtt()->writePayload_P(Data);
|
||||
mqtt()->writePayload(serializedDevice, strlen(serializedDevice));
|
||||
}
|
||||
|
||||
// device class
|
||||
if (_class != nullptr) {
|
||||
static const char DataBefore[] PROGMEM = {",\"dev_cla\":\""};
|
||||
|
||||
mqtt()->writePayload_P(DataBefore);
|
||||
mqtt()->writePayload(_class, strlen(_class));
|
||||
mqtt()->writePayload_P(QuotationSign);
|
||||
}
|
||||
|
||||
{
|
||||
static const char Data[] PROGMEM = {"}"};
|
||||
mqtt()->writePayload_P(Data);
|
||||
}
|
||||
|
||||
return true;
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
AHATOFSTR(HAStateOff),
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,73 +1,126 @@
|
||||
#ifndef AHA_HABINARYSENSOR_H
|
||||
#define AHA_HABINARYSENSOR_H
|
||||
|
||||
#include "BaseDeviceType.h"
|
||||
#include "HABaseDeviceType.h"
|
||||
#include "../utils/HANumeric.h"
|
||||
|
||||
class HABinarySensor : public BaseDeviceType
|
||||
#ifndef EX_ARDUINOHA_BINARY_SENSOR
|
||||
|
||||
/**
|
||||
* HABinarySensor represents a binary sensor that allows publishing on/off state to the Home Assistant panel.
|
||||
*
|
||||
* @note
|
||||
* You can find more information about this entity in the Home Assistant documentation:
|
||||
* https://www.home-assistant.io/integrations/binary_sensor.mqtt/
|
||||
*/
|
||||
class HABinarySensor : public HABaseDeviceType
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* Initializes binary sensor.
|
||||
* @param uniqueId The unique ID of the button. It needs to be unique in a scope of your device.
|
||||
*/
|
||||
HABinarySensor(const char* uniqueId);
|
||||
|
||||
/**
|
||||
* Changes state of the sensor and publish MQTT message.
|
||||
* Please note that if a new value is the same as the previous one the MQTT message won't be published.
|
||||
*
|
||||
* @param name Name of the sensor. Recommendes characters: [a-z0-9\-_]
|
||||
* @param initialState Initial state of the sensor.
|
||||
It will be published right after "config" message in order to update HA state.
|
||||
* @param state New state of the sensor (`true` - on, `false` - off).
|
||||
* @param force Forces to update the state without comparing it to a previous known state.
|
||||
* @returns Returns `true` if the MQTT message has been published successfully.
|
||||
*/
|
||||
HABinarySensor(
|
||||
const char* name,
|
||||
bool initialState,
|
||||
HAMqtt& mqtt
|
||||
);
|
||||
bool setState(const bool state, const bool force = false);
|
||||
|
||||
/**
|
||||
* Initializes binary sensor with the specified class.
|
||||
* You can find list of available values here: https://www.home-assistant.io/integrations/binary_sensor/#device-class
|
||||
* Sets the number of seconds after the sensor’s state expires, if it’s not updated.
|
||||
* By default the sensors state never expires.
|
||||
*
|
||||
* @param name Name of the sensor. Recommendes characters: [a-z0-9\-_]
|
||||
* @param deviceClass Name of the class (lower case).
|
||||
* @param initialState Initial state of the sensor.
|
||||
It will be published right after "config" message in order to update HA state.
|
||||
* @param expireAfter The number of seconds.
|
||||
*/
|
||||
HABinarySensor(
|
||||
const char* name,
|
||||
const char* deviceClass,
|
||||
bool initialState,
|
||||
HAMqtt& mqtt
|
||||
);
|
||||
|
||||
virtual ~HABinarySensor();
|
||||
void setExpireAfter(uint16_t expireAfter);
|
||||
|
||||
/**
|
||||
* Publishes configuration of the sensor to the MQTT.
|
||||
*/
|
||||
virtual void onMqttConnected() override;
|
||||
|
||||
/**
|
||||
* Changes state of the sensor and publishes MQTT message.
|
||||
* Please note that if a new value is the same as previous one,
|
||||
* the MQTT message won't be published.
|
||||
* Sets the current state of the sensor without publishing it to Home Assistant.
|
||||
* This method may be useful if you want to change the state before the connection with the MQTT broker is acquired.
|
||||
*
|
||||
* @param state New state of the sensor.
|
||||
* @returns Returns true if MQTT message has been published successfully.
|
||||
*/
|
||||
bool setState(bool state);
|
||||
inline void setCurrentState(const bool state)
|
||||
{ _currentState = state; }
|
||||
|
||||
/**
|
||||
* Returns last known state of the sensor.
|
||||
* If setState method wasn't called the initial value will be returned.
|
||||
* Returns the last known state of the sensor.
|
||||
*/
|
||||
inline bool getState() const
|
||||
inline bool getCurrentState() const
|
||||
{ return _currentState; }
|
||||
|
||||
private:
|
||||
void publishConfig();
|
||||
bool publishState(bool state);
|
||||
uint16_t calculateSerializedLength(const char* serializedDevice) const;
|
||||
bool writeSerializedTrigger(const char* serializedDevice) const;
|
||||
/**
|
||||
* Sets class of the device.
|
||||
* You can find list of available values here: https://www.home-assistant.io/integrations/binary_sensor/#device-class
|
||||
*
|
||||
* @param deviceClass The class name.
|
||||
*/
|
||||
inline void setDeviceClass(const char* deviceClass)
|
||||
{ _class = deviceClass; }
|
||||
|
||||
const char* _name;
|
||||
/**
|
||||
* Sets icon of the sensor.
|
||||
* Any icon from MaterialDesignIcons.com (for example: `mdi:home`).
|
||||
*
|
||||
* @param icon The icon name.
|
||||
*/
|
||||
inline void setIcon(const char* icon)
|
||||
{ _icon = icon; }
|
||||
|
||||
inline void setPayloadOn(const char* payload)
|
||||
{ _payloadOn = payload; }
|
||||
|
||||
inline void setPayloadOff(const char* payload)
|
||||
{ _payloadOff = payload; }
|
||||
|
||||
inline void setForceUpdate(bool forceUpdate)
|
||||
{ _forceUpdate = forceUpdate; }
|
||||
|
||||
void setOffDelay(uint16_t seconds);
|
||||
void clearOffDelay();
|
||||
|
||||
void setValueTemplate(const char* valueTemplate);
|
||||
|
||||
protected:
|
||||
virtual void buildSerializer() override;
|
||||
virtual HASerializer* buildDeviceDiscoverySerializer() override;
|
||||
virtual bool supportsDeviceDiscovery() const override
|
||||
{ return true; }
|
||||
virtual void onMqttConnected() override;
|
||||
|
||||
private:
|
||||
/**
|
||||
* Publishes the MQTT message with the given state.
|
||||
*
|
||||
* @param state The state to publish.
|
||||
* @returns Returns `true` if the MQTT message has been published successfully.
|
||||
*/
|
||||
bool publishState(bool state);
|
||||
|
||||
/// The device class. It can be nullptr.
|
||||
const char* _class;
|
||||
|
||||
/// The icon of the sensor. It can be nullptr.
|
||||
const char* _icon;
|
||||
|
||||
/// It defines the number of seconds after the sensor’s state expires, if it’s not updated. By default the sensors state never expires.
|
||||
HANumeric _expireAfter;
|
||||
|
||||
const char* _payloadOn;
|
||||
const char* _payloadOff;
|
||||
bool _forceUpdate;
|
||||
HANumeric _offDelay;
|
||||
const char* _valueTemplate;
|
||||
|
||||
/// Current state of the sensor. By default it's false.
|
||||
bool _currentState;
|
||||
|
||||
};
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -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
|
||||
@@ -0,0 +1,291 @@
|
||||
#include "HAFan.h"
|
||||
#ifndef EX_ARDUINOHA_FAN
|
||||
|
||||
#include "../HAMqtt.h"
|
||||
#include "../utils/HAUtils.h"
|
||||
#include "../utils/HASerializer.h"
|
||||
|
||||
HAFan::HAFan(const char* uniqueId, const uint8_t features) :
|
||||
HABaseDeviceType(AHATOFSTR(HAComponentFan), uniqueId),
|
||||
_features(features),
|
||||
_icon(nullptr),
|
||||
_retain(false),
|
||||
_optimistic(false),
|
||||
_speedRangeMax(),
|
||||
_speedRangeMin(),
|
||||
_currentState(false),
|
||||
_currentSpeed(0),
|
||||
_stateCallback(nullptr),
|
||||
_speedCallback(nullptr)
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
, _stateStdCallback(),
|
||||
_speedStdCallback()
|
||||
#endif
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
bool HAFan::setState(const bool state, const bool force)
|
||||
{
|
||||
if (!force && state == _currentState) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool published = publishState(state);
|
||||
_currentState = state;
|
||||
return published;
|
||||
}
|
||||
|
||||
bool HAFan::setSpeed(const uint16_t speed, const bool force)
|
||||
{
|
||||
if (!force && speed == _currentSpeed) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!(_features & SpeedsFeature)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const bool published = publishSpeed(speed);
|
||||
_currentSpeed = speed;
|
||||
return published;
|
||||
}
|
||||
|
||||
void HAFan::buildSerializer()
|
||||
{
|
||||
if (_serializer || !uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
_serializer = new HASerializer(this, 24);
|
||||
_serializer->set(AHATOFSTR(HANameProperty), _name);
|
||||
setEntityIdProperty(_serializer);
|
||||
_serializer->set(HASerializer::WithUniqueId);
|
||||
applyCommonEntityProperties(_serializer);
|
||||
_serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
|
||||
_serializer->set(AHATOFSTR(HAIconProperty), _icon);
|
||||
|
||||
if (_retain) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HARetainProperty),
|
||||
&_retain,
|
||||
HASerializer::BoolPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_optimistic) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAOptimisticProperty),
|
||||
&_optimistic,
|
||||
HASerializer::BoolPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_features & SpeedsFeature) {
|
||||
_serializer->topic(AHATOFSTR(HAPercentageStateTopic));
|
||||
_serializer->topic(AHATOFSTR(HAPercentageCommandTopic));
|
||||
|
||||
if (_speedRangeMax.isSet()) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HASpeedRangeMaxProperty),
|
||||
&_speedRangeMax,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_speedRangeMin.isSet()) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HASpeedRangeMinProperty),
|
||||
&_speedRangeMin,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
_serializer->set(HASerializer::WithDevice);
|
||||
_serializer->set(HASerializer::WithAvailability);
|
||||
_serializer->topic(AHATOFSTR(HAStateTopic));
|
||||
_serializer->topic(AHATOFSTR(HACommandTopic));
|
||||
}
|
||||
|
||||
HASerializer* HAFan::buildDeviceDiscoverySerializer()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
HASerializer* serializer = new HASerializer(this, 24);
|
||||
serializer->set(
|
||||
AHATOFSTR(HAPlatformProperty),
|
||||
AHATOFSTR(HAComponentFan),
|
||||
HASerializer::ProgmemPropertyValue
|
||||
);
|
||||
serializer->set(AHATOFSTR(HANameProperty), _name);
|
||||
setEntityIdProperty(serializer);
|
||||
serializer->set(HASerializer::WithUniqueId);
|
||||
applyCommonEntityProperties(serializer);
|
||||
serializer->set(AHATOFSTR(HAStateEntityCategory), nonEmptyString(_entityCategory));
|
||||
serializer->set(AHATOFSTR(HAIconProperty), _icon);
|
||||
|
||||
if (_retain) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HARetainProperty),
|
||||
&_retain,
|
||||
HASerializer::BoolPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_optimistic) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HAOptimisticProperty),
|
||||
&_optimistic,
|
||||
HASerializer::BoolPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_features & SpeedsFeature) {
|
||||
serializer->topic(AHATOFSTR(HAPercentageStateTopic));
|
||||
serializer->topic(AHATOFSTR(HAPercentageCommandTopic));
|
||||
|
||||
if (_speedRangeMax.isSet()) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HASpeedRangeMaxProperty),
|
||||
&_speedRangeMax,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_speedRangeMin.isSet()) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HASpeedRangeMinProperty),
|
||||
&_speedRangeMin,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
serializer->set(HASerializer::WithAvailability);
|
||||
serializer->topic(AHATOFSTR(HAStateTopic));
|
||||
serializer->topic(AHATOFSTR(HACommandTopic));
|
||||
return serializer;
|
||||
}
|
||||
|
||||
void HAFan::onMqttConnected()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (shouldPublishSingleComponentConfig()) {
|
||||
publishConfig();
|
||||
}
|
||||
publishAvailability();
|
||||
|
||||
if (!_retain) {
|
||||
publishState(_currentState);
|
||||
publishSpeed(_currentSpeed);
|
||||
}
|
||||
|
||||
subscribeTopic(uniqueId(), AHATOFSTR(HACommandTopic));
|
||||
|
||||
if (_features & SpeedsFeature) {
|
||||
subscribeTopic(uniqueId(), AHATOFSTR(HAPercentageCommandTopic));
|
||||
}
|
||||
}
|
||||
|
||||
void HAFan::onMqttMessage(
|
||||
const char* topic,
|
||||
const uint8_t* payload,
|
||||
const uint16_t length
|
||||
)
|
||||
{
|
||||
if (HASerializer::compareDataTopics(
|
||||
topic,
|
||||
uniqueId(),
|
||||
AHATOFSTR(HACommandTopic)
|
||||
)) {
|
||||
handleStateCommand(payload, length);
|
||||
} else if (HASerializer::compareDataTopics(
|
||||
topic,
|
||||
uniqueId(),
|
||||
AHATOFSTR(HAPercentageCommandTopic)
|
||||
)) {
|
||||
handleSpeedCommand(payload, length);
|
||||
}
|
||||
}
|
||||
|
||||
bool HAFan::publishState(const bool state)
|
||||
{
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
AHATOFSTR(state ? HAStateOn : HAStateOff),
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
bool HAFan::publishSpeed(const uint16_t speed)
|
||||
{
|
||||
if (!(_features & SpeedsFeature)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char str[5 + 1] = {0}; // uint16_t digits with null terminator
|
||||
HANumeric(speed, 0).toStr(str);
|
||||
|
||||
return publishOnDataTopic(AHATOFSTR(HAPercentageStateTopic), str, true);
|
||||
}
|
||||
|
||||
void HAFan::handleStateCommand(const uint8_t* cmd, const uint16_t length)
|
||||
{
|
||||
(void)cmd;
|
||||
|
||||
const bool hasStateCallback =
|
||||
_stateCallback
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
|| static_cast<bool>(_stateStdCallback)
|
||||
#endif
|
||||
;
|
||||
|
||||
if (!hasStateCallback) {
|
||||
return;
|
||||
}
|
||||
|
||||
bool state = length == strlen_P(HAStateOn);
|
||||
if (_stateCallback) {
|
||||
_stateCallback(state, this);
|
||||
}
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
if (_stateStdCallback) {
|
||||
_stateStdCallback(state, this);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
void HAFan::handleSpeedCommand(const uint8_t* cmd, const uint16_t length)
|
||||
{
|
||||
const bool hasSpeedCallback =
|
||||
_speedCallback
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
|| static_cast<bool>(_speedStdCallback)
|
||||
#endif
|
||||
;
|
||||
|
||||
if (!hasSpeedCallback) {
|
||||
return;
|
||||
}
|
||||
|
||||
const HANumeric& number = HANumeric::fromStr(cmd, length);
|
||||
if (number.isUInt16()) {
|
||||
const uint16_t speed = number.toUInt16();
|
||||
if (_speedCallback) {
|
||||
_speedCallback(speed, this);
|
||||
}
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
if (_speedStdCallback) {
|
||||
_speedStdCallback(speed, this);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,296 @@
|
||||
#ifndef AHA_HAFAN_H
|
||||
#define AHA_HAFAN_H
|
||||
|
||||
#include "HABaseDeviceType.h"
|
||||
#include "../utils/HANumeric.h"
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
#include <functional>
|
||||
#endif
|
||||
|
||||
#ifndef EX_ARDUINOHA_FAN
|
||||
|
||||
#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:
|
||||
enum Features {
|
||||
DefaultFeatures = 0,
|
||||
SpeedsFeature = 1
|
||||
};
|
||||
|
||||
/**
|
||||
* @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.
|
||||
* @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 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)`.
|
||||
*/
|
||||
inline bool turnOff()
|
||||
{ return setState(false); }
|
||||
|
||||
/**
|
||||
* 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 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; }
|
||||
|
||||
/**
|
||||
* 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 speed The new speed of the fan. It should be in range of min and max value.
|
||||
*/
|
||||
inline void setCurrentSpeed(const uint16_t speed)
|
||||
{ _currentSpeed = speed; }
|
||||
|
||||
/**
|
||||
* Returns the last known speed of the fan.
|
||||
* By default speed is set to `0`.
|
||||
*/
|
||||
inline uint16_t getCurrentSpeed() const
|
||||
{ return _currentSpeed; }
|
||||
|
||||
/**
|
||||
* Sets icon of the fan.
|
||||
* 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 fan'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 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;
|
||||
|
||||
/// 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
|
||||
#endif
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,823 @@
|
||||
#ifndef AHA_HAHVAC_H
|
||||
#define AHA_HAHVAC_H
|
||||
|
||||
#include "HABaseDeviceType.h"
|
||||
#include "../utils/HANumeric.h"
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
#include <functional>
|
||||
#endif
|
||||
|
||||
#ifndef EX_ARDUINOHA_HVAC
|
||||
|
||||
#define _SET_CURRENT_TEMPERATURE_OVERLOAD(type) \
|
||||
/** @overload */ \
|
||||
inline bool setCurrentTemperature(const type temperature, const bool force = false) \
|
||||
{ return setCurrentTemperature(HANumeric(temperature, _precision), force); }
|
||||
|
||||
#define _SET_CURRENT_CURRENT_TEMPERATURE_OVERLOAD(type) \
|
||||
/** @overload */ \
|
||||
inline void setCurrentCurrentTemperature(const type temperature) \
|
||||
{ setCurrentCurrentTemperature(HANumeric(temperature, _precision)); }
|
||||
|
||||
#define _SET_TARGET_TEMPERATURE_OVERLOAD(type) \
|
||||
/** @overload */ \
|
||||
inline bool setTargetTemperature(const type temperature, const bool force = false) \
|
||||
{ return setTargetTemperature(HANumeric(temperature, _precision), force); }
|
||||
|
||||
#define _SET_CURRENT_TARGET_TEMPERATURE_OVERLOAD(type) \
|
||||
/** @overload */ \
|
||||
inline void setCurrentTargetTemperature(const type temperature) \
|
||||
{ setCurrentTargetTemperature(HANumeric(temperature, _precision)); }
|
||||
|
||||
#define HAHVAC_CALLBACK_BOOL(name) void (*name)(bool state, HAHVAC* sender)
|
||||
#define HAHVAC_CALLBACK_TARGET_TEMP(name) void (*name)(HANumeric temperature, HAHVAC* sender)
|
||||
#define HAHVAC_CALLBACK_FAN_MODE(name) void (*name)(FanMode mode, HAHVAC* sender)
|
||||
#define HAHVAC_CALLBACK_SWING_MODE(name) void (*name)(SwingMode mode, HAHVAC* sender)
|
||||
#define HAHVAC_CALLBACK_MODE(name) void (*name)(Mode mode, HAHVAC* sender)
|
||||
|
||||
class HASerializerArray;
|
||||
|
||||
/**
|
||||
* HAHVAC lets you control your HVAC devices.
|
||||
*
|
||||
* @note
|
||||
* You can find more information about this entity in the Home Assistant documentation:
|
||||
* https://www.home-assistant.io/integrations/climate.mqtt/
|
||||
*/
|
||||
class HAHVAC : public HABaseDeviceType
|
||||
{
|
||||
public:
|
||||
static const uint8_t DefaultFanModes;
|
||||
static const uint8_t DefaultSwingModes;
|
||||
static const uint8_t DefaultModes;
|
||||
|
||||
/// The list of features available in the HVAC. They're used in the constructor.
|
||||
enum Features {
|
||||
DefaultFeatures = 0,
|
||||
ActionFeature = 1,
|
||||
AuxHeatingFeature = 2,
|
||||
PowerFeature = 4,
|
||||
FanFeature = 8,
|
||||
SwingFeature = 16,
|
||||
ModesFeature = 32,
|
||||
TargetTemperatureFeature = 64
|
||||
};
|
||||
|
||||
/// The list of available actions of the HVAC.
|
||||
enum Action {
|
||||
UnknownAction = 0,
|
||||
OffAction,
|
||||
HeatingAction,
|
||||
CoolingAction,
|
||||
DryingAction,
|
||||
IdleAction,
|
||||
FanAction
|
||||
};
|
||||
|
||||
/// The list of available fan modes.
|
||||
enum FanMode {
|
||||
UnknownFanMode = 0,
|
||||
AutoFanMode = 1,
|
||||
LowFanMode = 2,
|
||||
MediumFanMode = 4,
|
||||
HighFanMode = 8
|
||||
};
|
||||
|
||||
/// The list of available swing modes.
|
||||
enum SwingMode {
|
||||
UnknownSwingMode = 0,
|
||||
OnSwingMode = 1,
|
||||
OffSwingMode = 2
|
||||
};
|
||||
|
||||
/// The list of available HVAC's modes.
|
||||
enum Mode {
|
||||
UnknownMode = 0,
|
||||
AutoMode = 1,
|
||||
OffMode = 2,
|
||||
CoolMode = 4,
|
||||
HeatMode = 8,
|
||||
DryMode = 16,
|
||||
FanOnlyMode = 32
|
||||
};
|
||||
|
||||
/// Temperature units available in the HVAC.
|
||||
enum TemperatureUnit {
|
||||
DefaultUnit = 1,
|
||||
CelsiusUnit,
|
||||
FahrenheitUnit
|
||||
};
|
||||
|
||||
/**
|
||||
* @param uniqueId The unique ID of the HVAC. It needs to be unique in a scope of your device.
|
||||
* @param features Features that should be enabled for the HVAC.
|
||||
* @param precision The precision of temperatures reported by the HVAC.
|
||||
*/
|
||||
HAHVAC(
|
||||
const char* uniqueId,
|
||||
const uint16_t features = DefaultFeatures,
|
||||
const NumberPrecision precision = PrecisionP1
|
||||
);
|
||||
|
||||
/**
|
||||
* Frees memory allocated for the arrays serialization.
|
||||
*/
|
||||
~HAHVAC();
|
||||
|
||||
/**
|
||||
* Changes current temperature of the HVAC 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 New current temperature.
|
||||
* @param force Forces to update the temperature without comparing it to a previous known value.
|
||||
* @returns Returns `true` if MQTT message has been published successfully.
|
||||
*/
|
||||
bool setCurrentTemperature(const HANumeric& temperature, const bool force = false);
|
||||
|
||||
_SET_CURRENT_TEMPERATURE_OVERLOAD(int8_t)
|
||||
_SET_CURRENT_TEMPERATURE_OVERLOAD(int16_t)
|
||||
_SET_CURRENT_TEMPERATURE_OVERLOAD(int32_t)
|
||||
_SET_CURRENT_TEMPERATURE_OVERLOAD(uint8_t)
|
||||
_SET_CURRENT_TEMPERATURE_OVERLOAD(uint16_t)
|
||||
_SET_CURRENT_TEMPERATURE_OVERLOAD(uint32_t)
|
||||
_SET_CURRENT_TEMPERATURE_OVERLOAD(float)
|
||||
|
||||
#ifdef ARDUINOHA_INT_OVERLOAD
|
||||
_SET_CURRENT_TEMPERATURE_OVERLOAD(int)
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Changes action of the HVAC 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 action New action.
|
||||
* @param force Forces to update the action without comparing it to a previous known value.
|
||||
* @returns Returns `true` if MQTT message has been published successfully.
|
||||
*/
|
||||
bool setAction(const Action action, const bool force = false);
|
||||
|
||||
/**
|
||||
* Changes state of the aux heating 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.
|
||||
* @param force Forces to update the state without comparing it to a previous known value.
|
||||
* @returns Returns `true` if MQTT message has been published successfully.
|
||||
*/
|
||||
bool setAuxState(const bool state, const bool force = false);
|
||||
|
||||
/**
|
||||
* Changes mode of the fan of the HVAC 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 mode New fan's mode.
|
||||
* @param force Forces to update the mode without comparing it to a previous known value.
|
||||
* @returns Returns `true` if MQTT message has been published successfully.
|
||||
*/
|
||||
bool setFanMode(const FanMode mode, const bool force = false);
|
||||
|
||||
/**
|
||||
* Changes swing mode of the HVAC 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 mode New swing mode.
|
||||
* @param force Forces to update the mode without comparing it to a previous known value.
|
||||
* @returns Returns `true` if MQTT message has been published successfully.
|
||||
*/
|
||||
bool setSwingMode(const SwingMode mode, const bool force = false);
|
||||
|
||||
/**
|
||||
* Changes mode of the HVAC 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 mode New HVAC's mode.
|
||||
* @param force Forces to update the mode without comparing it to a previous known value.
|
||||
* @returns Returns `true` if MQTT message has been published successfully.
|
||||
*/
|
||||
bool setMode(const Mode mode, const bool force = false);
|
||||
|
||||
/**
|
||||
* Changes target temperature of the HVAC 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 Target temperature to set.
|
||||
* @param force Forces to update the mode without comparing it to a previous known value.
|
||||
* @returns Returns `true` if MQTT message has been published successfully.
|
||||
*/
|
||||
bool setTargetTemperature(const HANumeric& temperature, const bool force = false);
|
||||
|
||||
_SET_TARGET_TEMPERATURE_OVERLOAD(int8_t)
|
||||
_SET_TARGET_TEMPERATURE_OVERLOAD(int16_t)
|
||||
_SET_TARGET_TEMPERATURE_OVERLOAD(int32_t)
|
||||
_SET_TARGET_TEMPERATURE_OVERLOAD(uint8_t)
|
||||
_SET_TARGET_TEMPERATURE_OVERLOAD(uint16_t)
|
||||
_SET_TARGET_TEMPERATURE_OVERLOAD(uint32_t)
|
||||
_SET_TARGET_TEMPERATURE_OVERLOAD(float)
|
||||
|
||||
#ifdef ARDUINOHA_INT_OVERLOAD
|
||||
_SET_TARGET_TEMPERATURE_OVERLOAD(int)
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Sets current temperature of the HVAC without publishing it to Home Assistant.
|
||||
* This method may be useful if you want to change temperature before connection
|
||||
* with MQTT broker is acquired.
|
||||
*
|
||||
* @param temperature New current temperature.
|
||||
*/
|
||||
inline void setCurrentCurrentTemperature(const HANumeric& temperature)
|
||||
{ if (temperature.getPrecision() == _precision) { _currentTemperature = temperature; } }
|
||||
|
||||
_SET_CURRENT_CURRENT_TEMPERATURE_OVERLOAD(int8_t)
|
||||
_SET_CURRENT_CURRENT_TEMPERATURE_OVERLOAD(int16_t)
|
||||
_SET_CURRENT_CURRENT_TEMPERATURE_OVERLOAD(int32_t)
|
||||
_SET_CURRENT_CURRENT_TEMPERATURE_OVERLOAD(uint8_t)
|
||||
_SET_CURRENT_CURRENT_TEMPERATURE_OVERLOAD(uint16_t)
|
||||
_SET_CURRENT_CURRENT_TEMPERATURE_OVERLOAD(uint32_t)
|
||||
_SET_CURRENT_CURRENT_TEMPERATURE_OVERLOAD(float)
|
||||
|
||||
#ifdef ARDUINOHA_INT_OVERLOAD
|
||||
_SET_CURRENT_CURRENT_TEMPERATURE_OVERLOAD(int)
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Returns last known current temperature of the HVAC.
|
||||
* If setCurrentTemperature method wasn't called the initial value will be returned.
|
||||
*/
|
||||
inline const HANumeric& getCurrentTemperature() const
|
||||
{ return _currentTemperature; }
|
||||
|
||||
/**
|
||||
* Sets action of the HVAC without publishing it to Home Assistant.
|
||||
* This method may be useful if you want to change the action before connection
|
||||
* with MQTT broker is acquired.
|
||||
*
|
||||
* @param action New action.
|
||||
*/
|
||||
inline void setCurrentAction(const Action action)
|
||||
{ _action = action; }
|
||||
|
||||
/**
|
||||
* Returns last known action of the HVAC.
|
||||
* If setAction method wasn't called the initial value will be returned.
|
||||
*/
|
||||
inline Action getCurrentAction() const
|
||||
{ return _action; }
|
||||
|
||||
/**
|
||||
* Sets aux heating state 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.
|
||||
*/
|
||||
inline void setCurrentAuxState(const bool state)
|
||||
{ _auxState = state; }
|
||||
|
||||
/**
|
||||
* Returns last known state of the aux heating.
|
||||
* If setAuxState method wasn't called the initial value will be returned.
|
||||
*/
|
||||
inline bool getCurrentAuxState() const
|
||||
{ return _auxState; }
|
||||
|
||||
/**
|
||||
* Sets fan's mode of the HVAC without publishing it to Home Assistant.
|
||||
* This method may be useful if you want to change the mode before connection
|
||||
* with MQTT broker is acquired.
|
||||
*
|
||||
* @param mode New fan's mode.
|
||||
*/
|
||||
inline void setCurrentFanMode(const FanMode mode)
|
||||
{ _fanMode = mode; }
|
||||
|
||||
/**
|
||||
* Returns last known fan's mode of the HVAC.
|
||||
* If setFanMode method wasn't called the initial value will be returned.
|
||||
*/
|
||||
inline FanMode getCurrentFanMode() const
|
||||
{ return _fanMode; }
|
||||
|
||||
/**
|
||||
* Sets available fan modes.
|
||||
*
|
||||
* @param modes The modes to set (for example: `HAHVAC::AutoFanMode | HAHVAC::HighFanMode`).
|
||||
*/
|
||||
inline void setFanModes(const uint8_t modes)
|
||||
{ _fanModes = modes; }
|
||||
|
||||
/**
|
||||
* Sets swing mode of the HVAC without publishing it to Home Assistant.
|
||||
* This method may be useful if you want to change the mode before connection
|
||||
* with MQTT broker is acquired.
|
||||
*
|
||||
* @param mode New swing mode.
|
||||
*/
|
||||
inline void setCurrentSwingMode(const SwingMode mode)
|
||||
{ _swingMode = mode; }
|
||||
|
||||
/**
|
||||
* Returns last known swing mode of the HVAC.
|
||||
* If setSwingMode method wasn't called the initial value will be returned.
|
||||
*/
|
||||
inline SwingMode getCurrentSwingMode() const
|
||||
{ return _swingMode; }
|
||||
|
||||
/**
|
||||
* Sets available swing modes.
|
||||
*
|
||||
* @param modes The modes to set (for example: `HAHVAC::OnSwingMode`).
|
||||
*/
|
||||
inline void setSwingModes(const uint8_t modes)
|
||||
{ _swingModes = modes; }
|
||||
|
||||
/**
|
||||
* Sets mode of the HVAC without publishing it to Home Assistant.
|
||||
* This method may be useful if you want to change the mode before connection
|
||||
* with MQTT broker is acquired.
|
||||
*
|
||||
* @param mode New HVAC's mode.
|
||||
*/
|
||||
inline void setCurrentMode(const Mode mode)
|
||||
{ _mode = mode; }
|
||||
|
||||
/**
|
||||
* Returns last known mode of the HVAC.
|
||||
* If setMode method wasn't called the initial value will be returned.
|
||||
*/
|
||||
inline Mode getCurrentMode() const
|
||||
{ return _mode; }
|
||||
|
||||
/**
|
||||
* Sets available HVAC's modes.
|
||||
*
|
||||
* @param modes The modes to set (for example: `HAHVAC::CoolMode | HAHVAC::HeatMode`).
|
||||
*/
|
||||
inline void setModes(const uint8_t modes)
|
||||
{ _modes = modes; }
|
||||
|
||||
/**
|
||||
* Sets target temperature of the HVAC without publishing it to Home Assistant.
|
||||
* This method may be useful if you want to change the target before connection
|
||||
* with MQTT broker is acquired.
|
||||
*
|
||||
* @param temperature Target temperature to set.
|
||||
*/
|
||||
inline void setCurrentTargetTemperature(const HANumeric& temperature)
|
||||
{ if (temperature.getPrecision() == _precision) { _targetTemperature = temperature; } }
|
||||
|
||||
_SET_CURRENT_TARGET_TEMPERATURE_OVERLOAD(int8_t)
|
||||
_SET_CURRENT_TARGET_TEMPERATURE_OVERLOAD(int16_t)
|
||||
_SET_CURRENT_TARGET_TEMPERATURE_OVERLOAD(int32_t)
|
||||
_SET_CURRENT_TARGET_TEMPERATURE_OVERLOAD(uint8_t)
|
||||
_SET_CURRENT_TARGET_TEMPERATURE_OVERLOAD(uint16_t)
|
||||
_SET_CURRENT_TARGET_TEMPERATURE_OVERLOAD(uint32_t)
|
||||
_SET_CURRENT_TARGET_TEMPERATURE_OVERLOAD(float)
|
||||
|
||||
#ifdef ARDUINOHA_INT_OVERLOAD
|
||||
_SET_CURRENT_TARGET_TEMPERATURE_OVERLOAD(int)
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Returns last known target temperature of the HVAC.
|
||||
* If setTargetTemperature method wasn't called the initial value will be returned.
|
||||
*/
|
||||
inline const HANumeric& getCurrentTargetTemperature() const
|
||||
{ return _targetTemperature; }
|
||||
|
||||
/**
|
||||
* Sets icon of the HVAC.
|
||||
* 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 HVAC'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; }
|
||||
|
||||
/**
|
||||
* Changes the temperature unit.
|
||||
*
|
||||
* @param unit See the TemperatureUnit enum above.
|
||||
*/
|
||||
inline void setTemperatureUnit(TemperatureUnit unit)
|
||||
{ _temperatureUnit = unit; }
|
||||
|
||||
/**
|
||||
* Sets the minimum temperature that can be set from the Home Assistant panel.
|
||||
*
|
||||
* @param min The minimum value.
|
||||
*/
|
||||
inline void setMinTemp(const float min)
|
||||
{ _minTemp = HANumeric(min, _precision); }
|
||||
|
||||
/**
|
||||
* Sets the maximum temperature that can be set from the Home Assistant panel.
|
||||
*
|
||||
* @param min The maximum value.
|
||||
*/
|
||||
inline void setMaxTemp(const float max)
|
||||
{ _maxTemp = HANumeric(max, _precision); }
|
||||
|
||||
/**
|
||||
* Sets the step of the temperature that can be set from the Home Assistant panel.
|
||||
*
|
||||
* @param step The setp value. By default it's `1`.
|
||||
*/
|
||||
inline void setTempStep(const float step)
|
||||
{ _tempStep = HANumeric(step, _precision); }
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the aux state command from HA is received.
|
||||
* Please note that it's not possible to register multiple callbacks for the same HVAC.
|
||||
*
|
||||
* @param callback
|
||||
* @note The aux state must be reported back to HA using the HAHVAC::setAuxState method.
|
||||
*/
|
||||
inline void onAuxStateCommand(HAHVAC_CALLBACK_BOOL(callback))
|
||||
{
|
||||
_auxCallback = callback;
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
_auxStdCallback = nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the power command from HA is received.
|
||||
* Please note that it's not possible to register multiple callbacks for the same HVAC.
|
||||
*
|
||||
* @param callback
|
||||
*/
|
||||
inline void onPowerCommand(HAHVAC_CALLBACK_BOOL(callback))
|
||||
{
|
||||
_powerCallback = callback;
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
_powerStdCallback = nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the fan mode command from HA is received.
|
||||
* Please note that it's not possible to register multiple callbacks for the same HVAC.
|
||||
*
|
||||
* @param callback
|
||||
* @note The fan mode must be reported back to HA using the HAHVAC::setFanMode method.
|
||||
*/
|
||||
inline void onFanModeCommand(HAHVAC_CALLBACK_FAN_MODE(callback))
|
||||
{
|
||||
_fanModeCallback = callback;
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
_fanModeStdCallback = nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the swing mode command from HA is received.
|
||||
* Please note that it's not possible to register multiple callbacks for the same HVAC.
|
||||
*
|
||||
* @param callback
|
||||
* @note The swing mode must be reported back to HA using the HAHVAC::setSwingMode method.
|
||||
*/
|
||||
inline void onSwingModeCommand(HAHVAC_CALLBACK_SWING_MODE(callback))
|
||||
{
|
||||
_swingModeCallback = callback;
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
_swingModeStdCallback = nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the HVAC mode command from HA is received.
|
||||
* Please note that it's not possible to register multiple callbacks for the same HVAC.
|
||||
*
|
||||
* @param callback
|
||||
* @note The mode must be reported back to HA using the HAHVAC::setMode method.
|
||||
*/
|
||||
inline void onModeCommand(HAHVAC_CALLBACK_MODE(callback))
|
||||
{
|
||||
_modeCallback = callback;
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
_modeStdCallback = nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the target temperature is set via HA panel.
|
||||
* Please note that it's not possible to register multiple callbacks for the same HVAC.
|
||||
*
|
||||
* @param callback
|
||||
* @note The target temperature must be reported back to HA using the HAHVAC::setTargetTemperature method.
|
||||
*/
|
||||
inline void onTargetTemperatureCommand(HAHVAC_CALLBACK_TARGET_TEMP(callback))
|
||||
{
|
||||
_targetTemperatureCallback = callback;
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
_targetTemperatureStdCallback = nullptr;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
/**
|
||||
* Registers aux state callback using std::function.
|
||||
* It allows passing capturing lambdas and std::bind expressions.
|
||||
*/
|
||||
inline void onAuxStateCommand(const std::function<void(bool, HAHVAC*)>& callback)
|
||||
{
|
||||
_auxCallback = nullptr;
|
||||
_auxStdCallback = callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers power callback using std::function.
|
||||
* It allows passing capturing lambdas and std::bind expressions.
|
||||
*/
|
||||
inline void onPowerCommand(const std::function<void(bool, HAHVAC*)>& callback)
|
||||
{
|
||||
_powerCallback = nullptr;
|
||||
_powerStdCallback = callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers fan mode callback using std::function.
|
||||
* It allows passing capturing lambdas and std::bind expressions.
|
||||
*/
|
||||
inline void onFanModeCommand(const std::function<void(FanMode, HAHVAC*)>& callback)
|
||||
{
|
||||
_fanModeCallback = nullptr;
|
||||
_fanModeStdCallback = callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers swing mode callback using std::function.
|
||||
* It allows passing capturing lambdas and std::bind expressions.
|
||||
*/
|
||||
inline void onSwingModeCommand(const std::function<void(SwingMode, HAHVAC*)>& callback)
|
||||
{
|
||||
_swingModeCallback = nullptr;
|
||||
_swingModeStdCallback = callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers HVAC mode callback using std::function.
|
||||
* It allows passing capturing lambdas and std::bind expressions.
|
||||
*/
|
||||
inline void onModeCommand(const std::function<void(Mode, HAHVAC*)>& callback)
|
||||
{
|
||||
_modeCallback = nullptr;
|
||||
_modeStdCallback = callback;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers target temperature callback using std::function.
|
||||
* It allows passing capturing lambdas and std::bind expressions.
|
||||
*/
|
||||
inline void onTargetTemperatureCommand(const std::function<void(HANumeric, HAHVAC*)>& callback)
|
||||
{
|
||||
_targetTemperatureCallback = nullptr;
|
||||
_targetTemperatureStdCallback = 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 current temperature.
|
||||
*
|
||||
* @param temperature The temperature to publish.
|
||||
* @returns Returns `true` if the MQTT message has been published successfully.
|
||||
*/
|
||||
bool publishCurrentTemperature(const HANumeric& temperature);
|
||||
|
||||
/**
|
||||
* Publishes the MQTT message with the given action.
|
||||
*
|
||||
* @param action The action to publish.
|
||||
* @returns Returns `true` if the MQTT message has been published successfully.
|
||||
*/
|
||||
bool publishAction(const Action action);
|
||||
|
||||
/**
|
||||
* Publishes the MQTT message with the given aux heating state.
|
||||
*
|
||||
* @param state The state to publish.
|
||||
* @returns Returns `true` if the MQTT message has been published successfully.
|
||||
*/
|
||||
bool publishAuxState(const bool state);
|
||||
|
||||
/**
|
||||
* Publishes the MQTT message with the given fan mode.
|
||||
*
|
||||
* @param mode The mode to publish.
|
||||
* @returns Returns `true` if the MQTT message has been published successfully.
|
||||
*/
|
||||
bool publishFanMode(const FanMode mode);
|
||||
|
||||
/**
|
||||
* Publishes the MQTT message with the given swing mode.
|
||||
*
|
||||
* @param mode The mode to publish.
|
||||
* @returns Returns `true` if the MQTT message has been published successfully.
|
||||
*/
|
||||
bool publishSwingMode(const SwingMode mode);
|
||||
|
||||
/**
|
||||
* Publishes the MQTT message with the given mode.
|
||||
*
|
||||
* @param mode The mode to publish.
|
||||
* @returns Returns `true` if the MQTT message has been published successfully.
|
||||
*/
|
||||
bool publishMode(const Mode mode);
|
||||
|
||||
/**
|
||||
* Publishes the MQTT message with the given target temperature.
|
||||
*
|
||||
* @param temperature The temperature to publish.
|
||||
* @returns Returns `true` if the MQTT message has been published successfully.
|
||||
*/
|
||||
bool publishTargetTemperature(const HANumeric& temperature);
|
||||
|
||||
/**
|
||||
* Parses the given aux state command and executes the callback with proper value.
|
||||
*
|
||||
* @param cmd The data of the command.
|
||||
* @param length Length of the command.
|
||||
*/
|
||||
void handleAuxStateCommand(const uint8_t* cmd, const uint16_t length);
|
||||
|
||||
/**
|
||||
* Parses the given power command and executes the callback with proper value.
|
||||
*
|
||||
* @param cmd The data of the command.
|
||||
* @param length Length of the command.
|
||||
*/
|
||||
void handlePowerCommand(const uint8_t* cmd, const uint16_t length);
|
||||
|
||||
/**
|
||||
* Parses the given fan mode command and executes the callback with proper value.
|
||||
*
|
||||
* @param cmd The data of the command.
|
||||
* @param length Length of the command.
|
||||
*/
|
||||
void handleFanModeCommand(const uint8_t* cmd, const uint16_t length);
|
||||
|
||||
/**
|
||||
* Parses the given swing mode command and executes the callback with proper value.
|
||||
*
|
||||
* @param cmd The data of the command.
|
||||
* @param length Length of the command.
|
||||
*/
|
||||
void handleSwingModeCommand(const uint8_t* cmd, const uint16_t length);
|
||||
|
||||
/**
|
||||
* Parses the given HVAC's mode command and executes the callback with proper value.
|
||||
*
|
||||
* @param cmd The data of the command.
|
||||
* @param length Length of the command.
|
||||
*/
|
||||
void handleModeCommand(const uint8_t* cmd, const uint16_t length);
|
||||
|
||||
/**
|
||||
* Parses the given HVAC's target temperature command and executes the callback with proper value.
|
||||
*
|
||||
* @param cmd The data of the command.
|
||||
* @param length Length of the command.
|
||||
*/
|
||||
void handleTargetTemperatureCommand(const uint8_t* cmd, const uint16_t length);
|
||||
|
||||
/**
|
||||
* Returns progmem string representing value template for the command
|
||||
* that contains floating point numbers.
|
||||
*/
|
||||
const __FlashStringHelper* getCommandWithFloatTemplate();
|
||||
|
||||
/// Features enabled for the HVAC.
|
||||
const uint16_t _features;
|
||||
|
||||
/// The precision of temperatures. By default it's `HANumber::PrecisionP1`.
|
||||
const NumberPrecision _precision;
|
||||
|
||||
/// The icon of the button. It can be nullptr.
|
||||
const char* _icon;
|
||||
|
||||
/// The retain flag for the HA commands.
|
||||
bool _retain;
|
||||
|
||||
/// The current temperature of the HVAC. By default it's not set.
|
||||
HANumeric _currentTemperature;
|
||||
|
||||
/// The current action of the HVAC. By default it's `HAHVAC::UnknownAction`.
|
||||
Action _action;
|
||||
|
||||
/// The temperature unit for the HVAC. By default it's `HAHVAC::DefaultUnit`.
|
||||
TemperatureUnit _temperatureUnit;
|
||||
|
||||
/// The minimum temperature that can be set.
|
||||
HANumeric _minTemp;
|
||||
|
||||
/// The maximum temperature that can be set.
|
||||
HANumeric _maxTemp;
|
||||
|
||||
/// The step of the temperature that can be set.
|
||||
HANumeric _tempStep;
|
||||
|
||||
/// Callback that will be called when the aux state command is received from the HA.
|
||||
HAHVAC_CALLBACK_BOOL(_auxCallback);
|
||||
|
||||
/// The state of the aux heating. By default it's `false`.
|
||||
bool _auxState;
|
||||
|
||||
/// Callback that will be called when the power command is received from the HA.
|
||||
HAHVAC_CALLBACK_BOOL(_powerCallback);
|
||||
|
||||
/// The current mode of the fan. By default it's `HAHVAC::UnknownFanMode`.
|
||||
FanMode _fanMode;
|
||||
|
||||
/// The supported fan modes. By default it's `HAHVAC::DefaultFanModes`.
|
||||
uint8_t _fanModes;
|
||||
|
||||
/// The serializer for the fan modes. It's `nullptr` if the fan feature is disabled.
|
||||
HASerializerArray* _fanModesSerializer;
|
||||
|
||||
/// Callback that will be called when the fan mode command is received from the HA.
|
||||
HAHVAC_CALLBACK_FAN_MODE(_fanModeCallback);
|
||||
|
||||
/// The current swing mode. By default it's `HAHVAC::UnknownSwingMode`.
|
||||
SwingMode _swingMode;
|
||||
|
||||
/// The supported swing modes. By default it's `HAHVAC::DefaultSwingModes`.
|
||||
uint8_t _swingModes;
|
||||
|
||||
/// The serializer for the swing modes. It's `nullptr` if the swing feature is disabled.
|
||||
HASerializerArray* _swingModesSerializer;
|
||||
|
||||
/// Callback that will be called when the swing mode command is received from the HA.
|
||||
HAHVAC_CALLBACK_SWING_MODE(_swingModeCallback);
|
||||
|
||||
/// The current mode. By default it's `HAHVAC::UnknownMode`.
|
||||
Mode _mode;
|
||||
|
||||
/// The supported modes. By default it's `HAHVAC::DefaultModes`.
|
||||
uint8_t _modes;
|
||||
|
||||
/// The serializer for the modes. It's `nullptr` if the modes feature is disabled.
|
||||
HASerializerArray* _modesSerializer;
|
||||
|
||||
/// Callback that will be called when the mode command is received from the HA.
|
||||
HAHVAC_CALLBACK_MODE(_modeCallback);
|
||||
|
||||
/// The target temperature of the HVAC. By default it's not set.
|
||||
HANumeric _targetTemperature;
|
||||
|
||||
/// Callback that will be called when the target temperature is changed via the HA panel.
|
||||
HAHVAC_CALLBACK_TARGET_TEMP(_targetTemperatureCallback);
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
/// The std::function callback that will be called when the aux state command is received from the HA.
|
||||
std::function<void(bool, HAHVAC*)> _auxStdCallback;
|
||||
|
||||
/// The std::function callback that will be called when the power command is received from the HA.
|
||||
std::function<void(bool, HAHVAC*)> _powerStdCallback;
|
||||
|
||||
/// The std::function callback that will be called when the fan mode command is received from the HA.
|
||||
std::function<void(FanMode, HAHVAC*)> _fanModeStdCallback;
|
||||
|
||||
/// The std::function callback that will be called when the swing mode command is received from the HA.
|
||||
std::function<void(SwingMode, HAHVAC*)> _swingModeStdCallback;
|
||||
|
||||
/// The std::function callback that will be called when the mode command is received from the HA.
|
||||
std::function<void(Mode, HAHVAC*)> _modeStdCallback;
|
||||
|
||||
/// The std::function callback that will be called when the target temperature is changed via the HA panel.
|
||||
std::function<void(HANumeric, HAHVAC*)> _targetTemperatureStdCallback;
|
||||
#endif
|
||||
};
|
||||
|
||||
#endif
|
||||
#endif
|
||||
@@ -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
|
||||
+280
-356
@@ -1,378 +1,302 @@
|
||||
#include "HASensor.h"
|
||||
#include "../ArduinoHADefines.h"
|
||||
#ifndef EX_ARDUINOHA_SENSOR
|
||||
|
||||
#include "../HAMqtt.h"
|
||||
#include "../HADevice.h"
|
||||
#include "../HAUtils.h"
|
||||
#include "../utils/HAUtils.h"
|
||||
#include "../utils/HADictionary.h"
|
||||
#include "../utils/HASerializer.h"
|
||||
#include "../utils/HASerializerArray.h"
|
||||
#include <string.h>
|
||||
|
||||
// todo: move all variables to progmem
|
||||
static const char* HAComponentName = "sensor";
|
||||
static const char* ValueTopic = "value";
|
||||
|
||||
template <typename T>
|
||||
HASensor<T>::HASensor(
|
||||
const char* name,
|
||||
T initialValue,
|
||||
HAMqtt& mqtt
|
||||
) :
|
||||
BaseDeviceType(mqtt),
|
||||
_name(name),
|
||||
_class(nullptr),
|
||||
_units(nullptr),
|
||||
_valueType(HAUtils::determineValueType<T>()),
|
||||
_currentValue(initialValue)
|
||||
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)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
HASensor<T>::HASensor(
|
||||
const char* name,
|
||||
const char* deviceClass,
|
||||
T initialValue,
|
||||
HAMqtt& mqtt
|
||||
) :
|
||||
BaseDeviceType(mqtt),
|
||||
_name(name),
|
||||
_class(deviceClass),
|
||||
_units(nullptr),
|
||||
_valueType(HAUtils::determineValueType<T>()),
|
||||
_currentValue(initialValue)
|
||||
HASensor::~HASensor()
|
||||
{
|
||||
if (_options) {
|
||||
const uint8_t optionsNb = _options->getItemsNb();
|
||||
const HASerializerArray::ItemType* options = _options->getItems();
|
||||
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
HASensor<T>::~HASensor()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void HASensor<T>::onMqttConnected()
|
||||
{
|
||||
if (strlen(_name) == 0 || _valueType == HAUtils::ValueTypeUnknown) {
|
||||
return;
|
||||
}
|
||||
|
||||
publishConfig();
|
||||
publishValue(_currentValue);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool HASensor<T>::setValue(T value)
|
||||
{
|
||||
if (strlen(_name) == 0 ||
|
||||
_valueType == HAUtils::ValueTypeUnknown) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (_currentValue == value) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (publishValue(value)) {
|
||||
_currentValue = value;
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void HASensor<T>::publishConfig()
|
||||
{
|
||||
if (_valueType == HAUtils::ValueTypeUnknown) {
|
||||
return;
|
||||
}
|
||||
|
||||
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 = calculateTopicLength(HAComponentName, _name, ConfigTopic);
|
||||
const uint16_t& dataLength = calculateSerializedLength(serializedDevice);
|
||||
|
||||
if (topicLength == 0 || dataLength == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
char topic[topicLength];
|
||||
generateTopic(topic, HAComponentName, _name, ConfigTopic);
|
||||
|
||||
if (strlen(topic) == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (mqtt()->beginPublish(topic, dataLength, true)) {
|
||||
writeSerializedTrigger(serializedDevice);
|
||||
mqtt()->endPublish();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool HASensor<T>::publishValue(T value)
|
||||
{
|
||||
if (strlen(_name) == 0 ||
|
||||
_valueType == HAUtils::ValueTypeUnknown) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint16_t& topicSize = calculateTopicLength(
|
||||
HAComponentName,
|
||||
_name,
|
||||
ValueTopic
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char topic[topicSize];
|
||||
generateTopic(
|
||||
topic,
|
||||
HAComponentName,
|
||||
_name,
|
||||
ValueTopic
|
||||
);
|
||||
|
||||
if (strlen(topic) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint16_t& valueLength = calculateValueLength();
|
||||
if (valueLength == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char valueStr[valueLength];
|
||||
if (!valueToStr(valueStr, value)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return mqtt()->publish(topic, valueStr, true);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
uint16_t HASensor<T>::calculateSerializedLength(
|
||||
const char* serializedDevice
|
||||
) const
|
||||
{
|
||||
if (serializedDevice == nullptr ||
|
||||
_valueType == HAUtils::ValueTypeUnknown) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const uint16_t& valueTopicLength = calculateTopicLength(
|
||||
HAComponentName,
|
||||
_name,
|
||||
ValueTopic,
|
||||
false
|
||||
);
|
||||
|
||||
if (valueTopicLength == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint16_t size =
|
||||
2 + // opening and closing bracket (without null terminator)
|
||||
valueTopicLength + 11 + // 11 - length of the JSON data for this field
|
||||
strlen(_name) + 10; // 10 - length of the JSON data for this field
|
||||
|
||||
// unique ID
|
||||
size += strlen(mqtt()->getDevice()->getUniqueId());
|
||||
size += strlen(_name) + 14; // 14 - length of the JSON data for this field
|
||||
|
||||
// device class
|
||||
if (_class != nullptr) {
|
||||
size += strlen(_class) + 13; // 13 - length of the JSON data for this field
|
||||
}
|
||||
|
||||
// units of measurement
|
||||
if (_units != nullptr) {
|
||||
size += strlen(_units) + 18;
|
||||
}
|
||||
|
||||
// device
|
||||
size += strlen(serializedDevice) + 7; // 7 - length of the JSON data for this field
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool HASensor<T>::writeSerializedTrigger(const char* serializedDevice) const
|
||||
{
|
||||
if (serializedDevice == nullptr ||
|
||||
_valueType == HAUtils::ValueTypeUnknown) {
|
||||
return false;
|
||||
}
|
||||
|
||||
static const char QuotationSign[] PROGMEM = {"\""};
|
||||
|
||||
// state topic
|
||||
{
|
||||
const uint16_t& topicSize = calculateTopicLength(
|
||||
HAComponentName,
|
||||
_name,
|
||||
ValueTopic
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
return false;
|
||||
if (optionsNb > 1) {
|
||||
for (uint8_t i = 0; i < optionsNb; i++) {
|
||||
delete[] options[i];
|
||||
}
|
||||
}
|
||||
|
||||
char stateTopic[topicSize];
|
||||
generateTopic(
|
||||
stateTopic,
|
||||
HAComponentName,
|
||||
_name,
|
||||
ValueTopic
|
||||
);
|
||||
delete _options;
|
||||
}
|
||||
}
|
||||
|
||||
if (strlen(stateTopic) == 0) {
|
||||
return false;
|
||||
void HASensor::setSuggestedDisplayPrecision(uint8_t precision)
|
||||
{
|
||||
_suggestedDisplayPrecision = HANumeric(static_cast<uint8_t>(precision), 0);
|
||||
}
|
||||
|
||||
void HASensor::clearSuggestedDisplayPrecision()
|
||||
{
|
||||
_suggestedDisplayPrecision.reset();
|
||||
}
|
||||
|
||||
void HASensor::setOptions(const char* options)
|
||||
{
|
||||
if (!options || _options) {
|
||||
return;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
static const char DataBefore[] PROGMEM = {"{\"stat_t\":\""};
|
||||
|
||||
mqtt()->writePayload_P(DataBefore);
|
||||
mqtt()->writePayload(stateTopic, strlen(stateTopic));
|
||||
mqtt()->writePayload_P(QuotationSign);
|
||||
optionLen++;
|
||||
}
|
||||
|
||||
// name
|
||||
{
|
||||
static const char DataBefore[] PROGMEM = {",\"name\":\""};
|
||||
|
||||
mqtt()->writePayload_P(DataBefore);
|
||||
mqtt()->writePayload(_name, strlen(_name));
|
||||
mqtt()->writePayload_P(QuotationSign);
|
||||
}
|
||||
|
||||
// unique ID
|
||||
{
|
||||
static const char Underscore[] PROGMEM = {"_"};
|
||||
static const char DataBefore[] PROGMEM = {",\"uniq_id\":\""};
|
||||
|
||||
const HADevice* device = mqtt()->getDevice();
|
||||
uint8_t uniqueIdLength = strlen(_name) + strlen(device->getUniqueId()) + 2; // underscore and null temrinator
|
||||
char uniqueId[uniqueIdLength];
|
||||
strcpy(uniqueId, _name);
|
||||
strcat_P(uniqueId, Underscore);
|
||||
strcat(uniqueId, device->getUniqueId());
|
||||
|
||||
mqtt()->writePayload_P(DataBefore);
|
||||
mqtt()->writePayload(uniqueId, strlen(uniqueId));
|
||||
mqtt()->writePayload_P(QuotationSign);
|
||||
}
|
||||
|
||||
// device
|
||||
{
|
||||
static const char Data[] PROGMEM = {",\"dev\":"};
|
||||
|
||||
mqtt()->writePayload_P(Data);
|
||||
mqtt()->writePayload(serializedDevice, strlen(serializedDevice));
|
||||
}
|
||||
|
||||
// device class
|
||||
if (_class != nullptr) {
|
||||
static const char DataBefore[] PROGMEM = {",\"dev_cla\":\""};
|
||||
|
||||
mqtt()->writePayload_P(DataBefore);
|
||||
mqtt()->writePayload(_class, strlen(_class));
|
||||
mqtt()->writePayload_P(QuotationSign);
|
||||
}
|
||||
|
||||
// units of measurement
|
||||
if (_units != nullptr) {
|
||||
static const char DataBefore[] PROGMEM = {",\"unit_of_meas\":\""};
|
||||
|
||||
mqtt()->writePayload_P(DataBefore);
|
||||
mqtt()->writePayload(_units, strlen(_units));
|
||||
mqtt()->writePayload_P(QuotationSign);
|
||||
}
|
||||
|
||||
{
|
||||
static const char Data[] PROGMEM = {"}"};
|
||||
mqtt()->writePayload_P(Data);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
uint16_t HASensor<T>::calculateValueLength() const
|
||||
void HASensor::setValueTemplate(const char* valueTemplate)
|
||||
{
|
||||
if (_valueType == HAUtils::ValueTypeUnknown) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint16_t size = 0;
|
||||
|
||||
switch (_valueType) {
|
||||
case HAUtils::ValueTypeUint8:
|
||||
size = 3; // from 0 to 255
|
||||
break;
|
||||
|
||||
case HAUtils::ValueTypeUint16:
|
||||
size = 5; // from 0 to 65535
|
||||
break;
|
||||
|
||||
case HAUtils::ValueTypeUint32:
|
||||
size = 10; // from 0 to 4294967295
|
||||
break;
|
||||
|
||||
case HAUtils::ValueTypeInt8:
|
||||
size = 4; // from -128 to 127
|
||||
break;
|
||||
|
||||
case HAUtils::ValueTypeInt16:
|
||||
size = 6; // from -32768 to 32767
|
||||
break;
|
||||
|
||||
case HAUtils::ValueTypeInt32:
|
||||
size = 11; // from -2147483648 to 2147483647
|
||||
break;
|
||||
|
||||
case HAUtils::ValueTypeDouble:
|
||||
case HAUtils::ValueTypeFloat:
|
||||
// 3 digits per byte + dot separator + 2 precision digits
|
||||
return (HAUtils::getValueTypeLength(_valueType) * 3) + 3;
|
||||
}
|
||||
|
||||
return (size > 0 ? (size + 1) : 0);
|
||||
_valueTemplate = valueTemplate;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool HASensor<T>::valueToStr(char* dst, T value) const
|
||||
void HASensor::setJsonAttributesTemplate(const char* jsonAttributesTemplate)
|
||||
{
|
||||
if (_valueType == HAUtils::ValueTypeUnknown) {
|
||||
return false;
|
||||
}
|
||||
|
||||
switch (_valueType) {
|
||||
case HAUtils::ValueTypeUint8:
|
||||
case HAUtils::ValueTypeUint16:
|
||||
case HAUtils::ValueTypeUint32:
|
||||
case HAUtils::ValueTypeInt8:
|
||||
case HAUtils::ValueTypeInt16:
|
||||
case HAUtils::ValueTypeInt32:
|
||||
itoa(value, dst, 10);
|
||||
break;
|
||||
|
||||
case HAUtils::ValueTypeDouble:
|
||||
case HAUtils::ValueTypeFloat:
|
||||
dtostrf(value, 0, 2, dst);
|
||||
break;
|
||||
}
|
||||
|
||||
return true;
|
||||
_jsonAttributesTemplate = jsonAttributesTemplate;
|
||||
}
|
||||
|
||||
void HASensor::setLastResetValueTemplate(const char* lastResetValueTemplate)
|
||||
{
|
||||
_lastResetValueTemplate = lastResetValueTemplate;
|
||||
}
|
||||
|
||||
bool HASensor::setValue(const char* value)
|
||||
{
|
||||
if (!value) {
|
||||
return publishOnDataTopic(AHATOFSTR(HAStateTopic), AHATOFSTR(HAStateNone), true);
|
||||
}
|
||||
|
||||
return publishOnDataTopic(AHATOFSTR(HAStateTopic), value, true);
|
||||
}
|
||||
|
||||
bool HASensor::setJsonAttributes(const char* json)
|
||||
{
|
||||
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;
|
||||
}
|
||||
|
||||
_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));
|
||||
|
||||
if (_suggestedDisplayPrecision.isSet()) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HASuggestedDisplayPrecisionProperty),
|
||||
&_suggestedDisplayPrecision,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
_serializer->set(HASerializer::WithDevice);
|
||||
_serializer->set(HASerializer::WithAvailability);
|
||||
_serializer->topic(AHATOFSTR(HAStateTopic));
|
||||
}
|
||||
|
||||
HASerializer* HASensor::buildDeviceDiscoverySerializer()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
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));
|
||||
|
||||
if (_suggestedDisplayPrecision.isSet()) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HASuggestedDisplayPrecisionProperty),
|
||||
&_suggestedDisplayPrecision,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
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
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
serializer->set(HASerializer::WithAvailability);
|
||||
serializer->topic(AHATOFSTR(HAStateTopic));
|
||||
return serializer;
|
||||
}
|
||||
|
||||
void HASensor::onMqttConnected()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (shouldPublishSingleComponentConfig()) {
|
||||
publishConfig();
|
||||
}
|
||||
publishAvailability();
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
+125
-57
@@ -1,87 +1,155 @@
|
||||
#ifndef AHA_HASENSOR_H
|
||||
#define AHA_HASENSOR_H
|
||||
|
||||
#include "BaseDeviceType.h"
|
||||
#include "../HAUtils.h"
|
||||
#include "HABaseDeviceType.h"
|
||||
#include "../utils/HANumeric.h"
|
||||
|
||||
template <typename T>
|
||||
class HASensor : public BaseDeviceType
|
||||
class HASerializerArray;
|
||||
|
||||
#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\-_]
|
||||
* @param initialValue Initial value of the sensor.
|
||||
It will be published right after "config" message in order to update HA state.
|
||||
*/
|
||||
HASensor(
|
||||
const char* name,
|
||||
T initialValue,
|
||||
HAMqtt& mqtt
|
||||
);
|
||||
enum Features {
|
||||
DefaultFeatures = 0,
|
||||
JsonAttributesFeature = 1
|
||||
};
|
||||
|
||||
/**
|
||||
* 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
|
||||
*
|
||||
* @param name Name of the sensor. Recommendes characters: [a-z0-9\-_]
|
||||
* @param deviceClass Name of the class (lower case).
|
||||
* @param initialValue Initial value of the sensor.
|
||||
It will be published right after "config" message in order to update HA state.
|
||||
* @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.
|
||||
*/
|
||||
HASensor(
|
||||
const char* name,
|
||||
const char* deviceClass,
|
||||
T initialValue,
|
||||
HAMqtt& mqtt
|
||||
);
|
||||
HASensor(const char* uniqueId, const uint16_t features = DefaultFeatures);
|
||||
|
||||
virtual ~HASensor();
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* 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 New state of the sensor.
|
||||
* @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(T value);
|
||||
bool setValue(const char* value);
|
||||
|
||||
/**
|
||||
* Returns last known state of the sensor.
|
||||
* If setState method wasn't called the initial value will be returned.
|
||||
* Publishes the given JSON data on the JSON attributes topic.
|
||||
* The `JsonAttributesFeature` has to be enabled prior to setting the value.
|
||||
*
|
||||
* @param json JSON attributes.
|
||||
*/
|
||||
inline T getValue() const
|
||||
{ return _currentValue; }
|
||||
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();
|
||||
|
||||
/**
|
||||
* Semicolon-separated options for device_class `enum`. Set only once.
|
||||
*/
|
||||
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:
|
||||
void publishConfig();
|
||||
bool publishValue(T value);
|
||||
uint16_t calculateSerializedLength(const char* serializedDevice) const;
|
||||
bool writeSerializedTrigger(const char* serializedDevice) const;
|
||||
uint16_t calculateValueLength() const;
|
||||
bool valueToStr(char* dst, T value) const;
|
||||
/// Features enabled for the sensor.
|
||||
const uint16_t _features;
|
||||
|
||||
const char* _name;
|
||||
const char* _class;
|
||||
const char* _units;
|
||||
HAUtils::ValueType _valueType;
|
||||
T _currentValue;
|
||||
/// 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
|
||||
#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
|
||||
@@ -0,0 +1,107 @@
|
||||
#ifndef AHA_HASENSORNUMBER_H
|
||||
#define AHA_HASENSORNUMBER_H
|
||||
|
||||
#include "HASensor.h"
|
||||
|
||||
#ifndef EX_ARDUINOHA_SENSOR
|
||||
|
||||
#define _SET_VALUE_OVERLOAD(type) \
|
||||
/** @overload */ \
|
||||
inline bool setValue(const type value, const bool force = false) \
|
||||
{ return setValue(HANumeric(value, _precision), force); }
|
||||
|
||||
#define _SET_CURRENT_VALUE_OVERLOAD(type) \
|
||||
/** @overload */ \
|
||||
inline void setCurrentValue(const type value) \
|
||||
{ setCurrentValue(HANumeric(value, _precision)); }
|
||||
|
||||
/**
|
||||
* HASensorInteger allows to publish numeric values of a sensor that will be displayed in the HA panel.
|
||||
*
|
||||
* @note You can find more information about this class in HASensor documentation.
|
||||
*/
|
||||
class HASensorNumber : public HASensor
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* @param uniqueId The unique ID of the sensor. 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.
|
||||
* @param features Features that should be enabled for the sensor.
|
||||
*/
|
||||
HASensorNumber(
|
||||
const char* uniqueId,
|
||||
const NumberPrecision precision = PrecisionP0,
|
||||
const uint16_t features = DefaultFeatures
|
||||
);
|
||||
|
||||
/**
|
||||
* Changes value 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 value New value of the sensor. THe precision of the value needs to match precision of the sensor.
|
||||
* @param force Forces to update the value without comparing it to a previous known value.
|
||||
* @returns Returns `true` if the MQTT message has been published successfully.
|
||||
*/
|
||||
bool setValue(const HANumeric& value, const bool force = false);
|
||||
|
||||
_SET_VALUE_OVERLOAD(int8_t)
|
||||
_SET_VALUE_OVERLOAD(int16_t)
|
||||
_SET_VALUE_OVERLOAD(int32_t)
|
||||
_SET_VALUE_OVERLOAD(uint8_t)
|
||||
_SET_VALUE_OVERLOAD(uint16_t)
|
||||
_SET_VALUE_OVERLOAD(uint32_t)
|
||||
_SET_VALUE_OVERLOAD(float)
|
||||
|
||||
#ifdef ARDUINOHA_INT_OVERLOAD
|
||||
_SET_VALUE_OVERLOAD(int)
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Sets the current value of the sensor without publishing it to Home Assistant.
|
||||
* This method may be useful if you want to change the value before the connection with the MQTT broker is acquired.
|
||||
*
|
||||
* @param value New value of the sensor.
|
||||
*/
|
||||
inline void setCurrentValue(const HANumeric& value)
|
||||
{ if (value.getPrecision() == _precision) { _currentValue = value; } }
|
||||
|
||||
_SET_CURRENT_VALUE_OVERLOAD(int8_t)
|
||||
_SET_CURRENT_VALUE_OVERLOAD(int16_t)
|
||||
_SET_CURRENT_VALUE_OVERLOAD(int32_t)
|
||||
_SET_CURRENT_VALUE_OVERLOAD(uint8_t)
|
||||
_SET_CURRENT_VALUE_OVERLOAD(uint16_t)
|
||||
_SET_CURRENT_VALUE_OVERLOAD(uint32_t)
|
||||
_SET_CURRENT_VALUE_OVERLOAD(float)
|
||||
|
||||
#ifdef ARDUINOHA_INT_OVERLOAD
|
||||
_SET_CURRENT_VALUE_OVERLOAD(int)
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Returns the last known value of the sensor.
|
||||
* By default the value is not set.
|
||||
*/
|
||||
inline const HANumeric& getCurrentValue() const
|
||||
{ return _currentValue; }
|
||||
|
||||
protected:
|
||||
virtual void onMqttConnected() override;
|
||||
|
||||
private:
|
||||
/**
|
||||
* Publishes the MQTT message with the given value.
|
||||
*
|
||||
* @param state The value to publish.
|
||||
* @returns Returns `true` if the MQTT message has been published successfully.
|
||||
*/
|
||||
bool publishValue(const HANumeric& value);
|
||||
|
||||
/// The precision of the sensor. By default it's `HASensorNumber::PrecisionP0`.
|
||||
const NumberPrecision _precision;
|
||||
|
||||
/// The current value of the sensor. By default the value is not set.
|
||||
HANumeric _currentValue;
|
||||
};
|
||||
|
||||
#endif
|
||||
#endif
|
||||
+253
-300
@@ -1,337 +1,290 @@
|
||||
#include "HASwitch.h"
|
||||
#include "../ArduinoHADefines.h"
|
||||
#ifndef EX_ARDUINOHA_SWITCH
|
||||
|
||||
#include "../HAMqtt.h"
|
||||
#include "../HADevice.h"
|
||||
#include "../HAUtils.h"
|
||||
#include "../utils/HADictionary.h"
|
||||
#include "../utils/HASerializer.h"
|
||||
#include <string.h>
|
||||
|
||||
// todo: move all variables to progmem
|
||||
static const char* HAComponentName = "switch";
|
||||
static const char* CommandTopic = "cmd";
|
||||
static const char* StateTopic = "state";
|
||||
static const char* StateOn = "ON";
|
||||
static const char* StateOff = "OFF";
|
||||
static bool payloadEquals(
|
||||
const uint8_t* data,
|
||||
const uint16_t length,
|
||||
const char* ram,
|
||||
const __FlashStringHelper* flash
|
||||
)
|
||||
{
|
||||
if (ram) {
|
||||
const size_t n = strlen(ram);
|
||||
return (length == n) && (memcmp(data, ram, length) == 0);
|
||||
}
|
||||
|
||||
HASwitch::HASwitch(const char* name, bool initialState, HAMqtt& mqtt) :
|
||||
BaseDeviceType(mqtt),
|
||||
_name(name),
|
||||
_stateCallback(nullptr),
|
||||
_currentState(initialState)
|
||||
const size_t n = strlen_P(AHAFROMFSTR(flash));
|
||||
return (length == n) && (memcmp_P(data, AHAFROMFSTR(flash), n) == 0);
|
||||
}
|
||||
|
||||
HASwitch::HASwitch(const char* uniqueId) :
|
||||
HABaseDeviceType(AHATOFSTR(HAComponentSwitch), uniqueId),
|
||||
_class(nullptr),
|
||||
_icon(nullptr),
|
||||
_retain(false),
|
||||
_optimistic(false),
|
||||
_currentState(false),
|
||||
_payloadOn(nullptr),
|
||||
_payloadOff(nullptr),
|
||||
_stateOn(nullptr),
|
||||
_stateOff(nullptr),
|
||||
_valueTemplate(nullptr),
|
||||
_commandTemplate(nullptr),
|
||||
_commandCallback(nullptr)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
HASwitch::~HASwitch()
|
||||
void HASwitch::setValueTemplate(const char* valueTemplate)
|
||||
{
|
||||
_valueTemplate = valueTemplate;
|
||||
}
|
||||
|
||||
void HASwitch::setCommandTemplate(const char* commandTemplate)
|
||||
{
|
||||
_commandTemplate = commandTemplate;
|
||||
}
|
||||
|
||||
bool HASwitch::setState(const bool state, const bool force)
|
||||
{
|
||||
if (!force && state == _currentState) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool published = publishState(state);
|
||||
_currentState = state;
|
||||
return published;
|
||||
}
|
||||
|
||||
void HASwitch::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);
|
||||
|
||||
if (nonEmptyString(_payloadOn)) {
|
||||
_serializer->set(AHATOFSTR(HAPayloadOnProperty), _payloadOn);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_payloadOff)) {
|
||||
_serializer->set(AHATOFSTR(HAPayloadOffProperty), _payloadOff);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_stateOn)) {
|
||||
_serializer->set(AHATOFSTR(HAStateOnDiscoveryProperty), _stateOn);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_stateOff)) {
|
||||
_serializer->set(AHATOFSTR(HAStateOffDiscoveryProperty), _stateOff);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_valueTemplate)) {
|
||||
_serializer->set(AHATOFSTR(HAValueTemplateProperty), _valueTemplate);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_commandTemplate)) {
|
||||
_serializer->set(AHATOFSTR(HACommandTemplateProperty), _commandTemplate);
|
||||
}
|
||||
|
||||
// optional property
|
||||
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* HASwitch::buildDeviceDiscoverySerializer()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
HASerializer* serializer = new HASerializer(this, 24);
|
||||
serializer->set(
|
||||
AHATOFSTR(HAPlatformProperty),
|
||||
AHATOFSTR(HAComponentSwitch),
|
||||
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 (nonEmptyString(_stateOn)) {
|
||||
serializer->set(AHATOFSTR(HAStateOnDiscoveryProperty), _stateOn);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_stateOff)) {
|
||||
serializer->set(AHATOFSTR(HAStateOffDiscoveryProperty), _stateOff);
|
||||
}
|
||||
|
||||
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 HASwitch::onMqttConnected()
|
||||
{
|
||||
if (strlen(_name) == 0) {
|
||||
if (!uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
publishConfig();
|
||||
publishState(_currentState);
|
||||
subscribeCommandTopic();
|
||||
if (shouldPublishSingleComponentConfig()) {
|
||||
publishConfig();
|
||||
}
|
||||
publishAvailability();
|
||||
|
||||
if (!_retain) {
|
||||
publishState(_currentState);
|
||||
}
|
||||
|
||||
subscribeTopic(uniqueId(), AHATOFSTR(HACommandTopic));
|
||||
}
|
||||
|
||||
void HASwitch::onMqttMessage(
|
||||
const char* topic,
|
||||
const uint8_t* payload,
|
||||
const uint16_t& length
|
||||
const uint16_t length
|
||||
)
|
||||
{
|
||||
if (strlen(_name) == 0) {
|
||||
return;
|
||||
}
|
||||
const bool hasCommandCallback =
|
||||
_commandCallback
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
|| static_cast<bool>(_commandStdCallback)
|
||||
#endif
|
||||
;
|
||||
|
||||
static const char Slash[] PROGMEM = {"/"};
|
||||
uint8_t suffixLength = strlen(_name) + strlen(CommandTopic) + 3; // two slashes + null terminator
|
||||
char suffix[suffixLength];
|
||||
|
||||
strcpy_P(suffix, Slash);
|
||||
strcat(suffix, _name);
|
||||
strcat_P(suffix, Slash);
|
||||
strcat(suffix, CommandTopic);
|
||||
|
||||
if (HAUtils::endsWith(topic, suffix)) {
|
||||
bool onState = (length == strlen(StateOn));
|
||||
setState(onState);
|
||||
}
|
||||
}
|
||||
|
||||
bool HASwitch::setState(bool state)
|
||||
{
|
||||
if (_currentState == state) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (strlen(_name) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (publishState(state)) {
|
||||
_currentState = state;
|
||||
triggerCallback(_currentState);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void HASwitch::onStateChanged(HASWITCH_CALLBACK)
|
||||
{
|
||||
_stateCallback = callback;
|
||||
}
|
||||
|
||||
void HASwitch::triggerCallback(bool state)
|
||||
{
|
||||
if (_stateCallback == nullptr) {
|
||||
return;
|
||||
}
|
||||
|
||||
_stateCallback(state, this);
|
||||
}
|
||||
|
||||
void HASwitch::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 = calculateTopicLength(HAComponentName, _name, ConfigTopic);
|
||||
const uint16_t& dataLength = calculateSerializedLength(serializedDevice);
|
||||
|
||||
if (topicLength == 0 || dataLength == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
char topic[topicLength];
|
||||
generateTopic(topic, HAComponentName, _name, ConfigTopic);
|
||||
|
||||
if (strlen(topic) == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (mqtt()->beginPublish(topic, dataLength, true)) {
|
||||
writeSerializedTrigger(serializedDevice);
|
||||
mqtt()->endPublish();
|
||||
}
|
||||
}
|
||||
|
||||
bool HASwitch::publishState(bool state)
|
||||
{
|
||||
if (strlen(_name) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint16_t& topicSize = calculateTopicLength(
|
||||
HAComponentName,
|
||||
_name,
|
||||
StateTopic
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char topic[topicSize];
|
||||
generateTopic(
|
||||
if (hasCommandCallback && HASerializer::compareDataTopics(
|
||||
topic,
|
||||
HAComponentName,
|
||||
_name,
|
||||
StateTopic
|
||||
);
|
||||
uniqueId(),
|
||||
AHATOFSTR(HACommandTopic)
|
||||
)) {
|
||||
const bool isOn = payloadEquals(
|
||||
payload,
|
||||
length,
|
||||
_payloadOn,
|
||||
AHATOFSTR(HAStateOn)
|
||||
);
|
||||
const bool isOff = payloadEquals(
|
||||
payload,
|
||||
length,
|
||||
_payloadOff,
|
||||
AHATOFSTR(HAStateOff)
|
||||
);
|
||||
|
||||
if (strlen(topic) == 0) {
|
||||
return false;
|
||||
if (!isOn && !isOff) {
|
||||
return;
|
||||
}
|
||||
|
||||
const bool state = isOn;
|
||||
if (_commandCallback) {
|
||||
_commandCallback(state, this);
|
||||
}
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
if (_commandStdCallback) {
|
||||
_commandStdCallback(state, this);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
return mqtt()->publish(topic, (state ? StateOn : StateOff), true);
|
||||
}
|
||||
|
||||
void HASwitch::subscribeCommandTopic()
|
||||
bool HASwitch::publishState(const bool state)
|
||||
{
|
||||
const uint16_t& topicSize = calculateTopicLength(
|
||||
HAComponentName,
|
||||
_name,
|
||||
CommandTopic
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
return;
|
||||
if (state) {
|
||||
if (nonEmptyString(_stateOn)) {
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
_stateOn,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
AHATOFSTR(HAStateOn),
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
char topic[topicSize];
|
||||
generateTopic(
|
||||
topic,
|
||||
HAComponentName,
|
||||
_name,
|
||||
CommandTopic
|
||||
);
|
||||
|
||||
if (strlen(topic) == 0) {
|
||||
return;
|
||||
if (nonEmptyString(_stateOff)) {
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
_stateOff,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
mqtt()->subscribe(topic);
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
AHATOFSTR(HAStateOff),
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
uint16_t HASwitch::calculateSerializedLength(const char* serializedDevice) const
|
||||
{
|
||||
if (serializedDevice == nullptr) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
const uint16_t& cmdTopicLength = calculateTopicLength(
|
||||
HAComponentName,
|
||||
_name,
|
||||
CommandTopic,
|
||||
false
|
||||
);
|
||||
const uint16_t& stateTopicLength = calculateTopicLength(
|
||||
HAComponentName,
|
||||
_name,
|
||||
StateTopic,
|
||||
false
|
||||
);
|
||||
|
||||
if (cmdTopicLength == 0 || stateTopicLength == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
uint16_t size =
|
||||
2 + // opening and closing bracket (without null terminator)
|
||||
cmdTopicLength + 10 + // 10 - length of the JSON data for this field
|
||||
stateTopicLength + 12 + // 12 - length of the JSON data for this field
|
||||
strlen(_name) + 10; // 10 - length of the JSON data for this field
|
||||
|
||||
// unique ID
|
||||
size += strlen(mqtt()->getDevice()->getUniqueId());
|
||||
size += strlen(_name) + 14; // 14 - length of the JSON data for this field
|
||||
|
||||
// device
|
||||
size += strlen(serializedDevice) + 7; // 7 - length of the JSON data for this field
|
||||
|
||||
return size;
|
||||
}
|
||||
|
||||
bool HASwitch::writeSerializedTrigger(const char* serializedDevice) const
|
||||
{
|
||||
if (serializedDevice == nullptr) {
|
||||
return false;
|
||||
}
|
||||
|
||||
static const char QuotationSign[] PROGMEM = {"\""};
|
||||
|
||||
// command topic
|
||||
{
|
||||
const uint16_t& topicSize = calculateTopicLength(
|
||||
HAComponentName,
|
||||
_name,
|
||||
CommandTopic
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char cmdTopic[topicSize];
|
||||
generateTopic(
|
||||
cmdTopic,
|
||||
HAComponentName,
|
||||
_name,
|
||||
CommandTopic
|
||||
);
|
||||
|
||||
if (strlen(cmdTopic) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
static const char DataBefore[] PROGMEM = {"{\"cmd_t\":\""};
|
||||
|
||||
mqtt()->writePayload_P(DataBefore);
|
||||
mqtt()->writePayload(cmdTopic, strlen(cmdTopic));
|
||||
mqtt()->writePayload_P(QuotationSign);
|
||||
}
|
||||
|
||||
// state topic
|
||||
{
|
||||
const uint16_t& topicSize = calculateTopicLength(
|
||||
HAComponentName,
|
||||
_name,
|
||||
StateTopic
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char stateTopic[topicSize];
|
||||
generateTopic(
|
||||
stateTopic,
|
||||
HAComponentName,
|
||||
_name,
|
||||
StateTopic
|
||||
);
|
||||
|
||||
if (strlen(stateTopic) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
static const char DataBefore[] PROGMEM = {",\"stat_t\":\""};
|
||||
|
||||
mqtt()->writePayload_P(DataBefore);
|
||||
mqtt()->writePayload(stateTopic, strlen(stateTopic));
|
||||
mqtt()->writePayload_P(QuotationSign);
|
||||
}
|
||||
|
||||
// name
|
||||
{
|
||||
static const char DataBefore[] PROGMEM = {",\"name\":\""};
|
||||
|
||||
mqtt()->writePayload_P(DataBefore);
|
||||
mqtt()->writePayload(_name, strlen(_name));
|
||||
mqtt()->writePayload_P(QuotationSign);
|
||||
}
|
||||
|
||||
// unique ID
|
||||
{
|
||||
static const char Underscore[] PROGMEM = {"_"};
|
||||
static const char DataBefore[] PROGMEM = {",\"uniq_id\":\""};
|
||||
|
||||
const HADevice* device = mqtt()->getDevice();
|
||||
uint8_t uniqueIdLength = strlen(_name) + strlen(device->getUniqueId()) + 2; // underscore and null temrinator
|
||||
char uniqueId[uniqueIdLength];
|
||||
strcpy(uniqueId, _name);
|
||||
strcat_P(uniqueId, Underscore);
|
||||
strcat(uniqueId, device->getUniqueId());
|
||||
|
||||
mqtt()->writePayload_P(DataBefore);
|
||||
mqtt()->writePayload(uniqueId, strlen(uniqueId));
|
||||
mqtt()->writePayload_P(QuotationSign);
|
||||
}
|
||||
|
||||
// device
|
||||
{
|
||||
static const char Data[] PROGMEM = {",\"dev\":"};
|
||||
|
||||
mqtt()->writePayload_P(Data);
|
||||
mqtt()->writePayload(serializedDevice, strlen(serializedDevice));
|
||||
}
|
||||
|
||||
{
|
||||
static const char Data[] PROGMEM = {"}"};
|
||||
mqtt()->writePayload_P(Data);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
+159
-52
@@ -1,47 +1,30 @@
|
||||
#ifndef AHA_HASWITCH_H
|
||||
#define AHA_HASWITCH_H
|
||||
|
||||
#include "BaseDeviceType.h"
|
||||
#include "HABaseDeviceType.h"
|
||||
|
||||
#define HASWITCH_CALLBACK void (*callback)(bool, HASwitch*)
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
#include <functional>
|
||||
#endif
|
||||
|
||||
class HASwitch : public BaseDeviceType
|
||||
#ifndef EX_ARDUINOHA_SWITCH
|
||||
|
||||
#define HASWITCH_CALLBACK(name) void (*name)(bool state, HASwitch* sender)
|
||||
|
||||
/**
|
||||
* HASwitch allows to display on/off switch in the HA panel and receive commands on your device.
|
||||
*
|
||||
* @note
|
||||
* You can find more information about this entity in the Home Assistant documentation:
|
||||
* https://www.home-assistant.io/integrations/switch.mqtt/
|
||||
*/
|
||||
class HASwitch : public HABaseDeviceType
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* Initializes switch.
|
||||
*
|
||||
* @param name Name of the switch. Recommendes characters: [a-z0-9\-_]
|
||||
* @param initialState Initial state of the switch.
|
||||
It will be published right after "config" message in order to update HA state.
|
||||
* @param uniqueId The unique ID of the sensor. It needs to be unique in a scope of your device.
|
||||
*/
|
||||
HASwitch(
|
||||
const char* name,
|
||||
bool initialState,
|
||||
HAMqtt& mqtt
|
||||
);
|
||||
virtual ~HASwitch();
|
||||
|
||||
/**
|
||||
* Publishes configuration of the sensor to the MQTT.
|
||||
*/
|
||||
virtual void onMqttConnected() override;
|
||||
|
||||
/**
|
||||
* Processes message received from the MQTT broker.
|
||||
* The method updates state of the switch (if message matches switch'es topic).
|
||||
*/
|
||||
virtual void onMqttMessage(
|
||||
const char* topic,
|
||||
const uint8_t* payload,
|
||||
const uint16_t& length
|
||||
) override;
|
||||
|
||||
/**
|
||||
* Returns name of the switch assigned via constructor.
|
||||
*/
|
||||
inline const char* getName() const
|
||||
{ return _name; }
|
||||
HASwitch(const char* uniqueId);
|
||||
|
||||
/**
|
||||
* Changes state of the switch and publishes MQTT message.
|
||||
@@ -49,48 +32,172 @@ public:
|
||||
* the MQTT message won't be published.
|
||||
*
|
||||
* @param state New state of the switch.
|
||||
* @returns Returns true if MQTT message has been published successfully.
|
||||
* @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(bool state);
|
||||
bool setState(const bool state, const bool force = false);
|
||||
|
||||
/**
|
||||
* Alias for setState(true).
|
||||
* 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 switch.
|
||||
* If setState method wasn't called the initial value will be returned.
|
||||
* Sets current state of the switch 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 switch.
|
||||
*/
|
||||
inline bool getState() const
|
||||
inline void setCurrentState(const bool state)
|
||||
{ _currentState = state; }
|
||||
|
||||
/**
|
||||
* Returns last known state of the switch.
|
||||
* By default it's `false`.
|
||||
*/
|
||||
inline bool getCurrentState() const
|
||||
{ return _currentState; }
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the value of the switch changes.
|
||||
* Sets class of the device.
|
||||
* You can find list of available values here: https://www.home-assistant.io/integrations/switch/#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; }
|
||||
|
||||
/**
|
||||
* Sets retain flag for the switch 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 switch state.
|
||||
* In this mode the switch 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; }
|
||||
|
||||
inline void setPayloadOn(const char* payload)
|
||||
{ _payloadOn = payload; }
|
||||
|
||||
inline void setPayloadOff(const char* payload)
|
||||
{ _payloadOff = payload; }
|
||||
|
||||
inline void setStateOn(const char* state)
|
||||
{ _stateOn = state; }
|
||||
|
||||
inline void setStateOff(const char* state)
|
||||
{ _stateOff = state; }
|
||||
|
||||
void setValueTemplate(const char* valueTemplate);
|
||||
void setCommandTemplate(const char* commandTemplate);
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time the on/off command from HA is received.
|
||||
* Please note that it's not possible to register multiple callbacks for the same switch.
|
||||
*
|
||||
* @param callback
|
||||
* @note In non-optimistic mode, the state must be reported back to HA using the HASwitch::setState method.
|
||||
*/
|
||||
void onStateChanged(HASWITCH_CALLBACK);
|
||||
inline void onCommand(HASWITCH_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(bool, HASwitch*)>& 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:
|
||||
void triggerCallback(bool state);
|
||||
void publishConfig();
|
||||
bool publishState(bool state);
|
||||
void subscribeCommandTopic();
|
||||
uint16_t calculateSerializedLength(const char* serializedDevice) const;
|
||||
bool writeSerializedTrigger(const char* serializedDevice) const;
|
||||
/**
|
||||
* 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);
|
||||
|
||||
const char* _name;
|
||||
void (*_stateCallback)(bool, HASwitch*);
|
||||
/// 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 switch (`true` - enabled, `false` - disabled).
|
||||
bool _optimistic;
|
||||
|
||||
/// The current state of the switch. By default it's `false`.
|
||||
bool _currentState;
|
||||
|
||||
const char* _payloadOn;
|
||||
const char* _payloadOff;
|
||||
const char* _stateOn;
|
||||
const char* _stateOff;
|
||||
const char* _valueTemplate;
|
||||
const char* _commandTemplate;
|
||||
|
||||
/// The callback that will be called when switch command is received from the HA.
|
||||
HASWITCH_CALLBACK(_commandCallback);
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
/// The std::function callback that will be called when switch command is received from the HA.
|
||||
std::function<void(bool, HASwitch*)> _commandStdCallback;
|
||||
#endif
|
||||
};
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -1,165 +1,60 @@
|
||||
#include "HATagScanner.h"
|
||||
#include "../ArduinoHADefines.h"
|
||||
#ifndef EX_ARDUINOHA_TAG_SCANNER
|
||||
|
||||
#include "../HAMqtt.h"
|
||||
#include "../HADevice.h"
|
||||
#include "../HAUtils.h"
|
||||
#include "../utils/HASerializer.h"
|
||||
|
||||
// todo: move to progmem
|
||||
static const char* HAComponentName = "tag";
|
||||
|
||||
HATagScanner::HATagScanner(const char* name, HAMqtt& mqtt) :
|
||||
BaseDeviceType(mqtt),
|
||||
_name(name)
|
||||
HATagScanner::HATagScanner(const char* uniqueId) :
|
||||
HABaseDeviceType(AHATOFSTR(HAComponentTag), uniqueId)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
HATagScanner::~HATagScanner()
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void HATagScanner::onMqttConnected()
|
||||
{
|
||||
if (strlen(_name) == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
publishConfig();
|
||||
}
|
||||
|
||||
bool HATagScanner::tagScanned(const char* tag)
|
||||
{
|
||||
if (tag == nullptr || strlen(tag) == 0) {
|
||||
if (!tag || strlen(tag) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const uint16_t& topicSize = calculateTopicLength(
|
||||
HAComponentName,
|
||||
_name,
|
||||
EventTopic
|
||||
);
|
||||
if (topicSize == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
char topic[topicSize];
|
||||
generateTopic(
|
||||
topic,
|
||||
HAComponentName,
|
||||
_name,
|
||||
EventTopic
|
||||
);
|
||||
|
||||
if (strlen(topic) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return mqtt()->publish(topic, tag);
|
||||
return publishOnDataTopic(AHATOFSTR(HATopic), tag);
|
||||
}
|
||||
|
||||
void HATagScanner::publishConfig()
|
||||
void HATagScanner::buildSerializer()
|
||||
{
|
||||
const HADevice* device = mqtt()->getDevice();
|
||||
if (device == nullptr) {
|
||||
if (_serializer || !uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const uint16_t& deviceLength = device->calculateSerializedLength();
|
||||
if (deviceLength == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
char serializedDevice[deviceLength];
|
||||
if (device->serialize(serializedDevice) == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
const uint16_t& topicLength = calculateTopicLength(HAComponentName, _name, ConfigTopic);
|
||||
const uint16_t& dataLength = calculateSerializedLength(serializedDevice);
|
||||
|
||||
if (topicLength == 0 || dataLength == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
char topic[topicLength];
|
||||
generateTopic(topic, HAComponentName, _name, ConfigTopic);
|
||||
|
||||
if (strlen(topic) == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (mqtt()->beginPublish(topic, dataLength, true)) {
|
||||
writeSerializedTrigger(serializedDevice);
|
||||
mqtt()->endPublish();
|
||||
}
|
||||
_serializer = new HASerializer(this, 2); // 2 - max properties nb
|
||||
_serializer->set(HASerializer::WithDevice);
|
||||
_serializer->topic(AHATOFSTR(HATopic));
|
||||
}
|
||||
|
||||
uint16_t HATagScanner::calculateSerializedLength(
|
||||
const char* serializedDevice
|
||||
) const
|
||||
HASerializer* HATagScanner::buildDeviceDiscoverySerializer()
|
||||
{
|
||||
if (serializedDevice == nullptr) {
|
||||
return 0;
|
||||
if (!uniqueId()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
const uint16_t& eventTopicLength = calculateTopicLength(
|
||||
HAComponentName,
|
||||
_name,
|
||||
EventTopic,
|
||||
false
|
||||
HASerializer* serializer = new HASerializer(this, 2);
|
||||
serializer->set(
|
||||
AHATOFSTR(HAPlatformProperty),
|
||||
AHATOFSTR(HAComponentTag),
|
||||
HASerializer::ProgmemPropertyValue
|
||||
);
|
||||
|
||||
uint16_t size =
|
||||
2 + // opening and closing bracket (without null terminator)
|
||||
eventTopicLength + 6 + // 6 - length of the JSON data for this field
|
||||
strlen(serializedDevice) + 7; // 7 - length of the JSON data for this field
|
||||
|
||||
return size;
|
||||
serializer->topic(AHATOFSTR(HATopic));
|
||||
return serializer;
|
||||
}
|
||||
|
||||
bool HATagScanner::writeSerializedTrigger(const char* serializedDevice) const
|
||||
void HATagScanner::onMqttConnected()
|
||||
{
|
||||
if (serializedDevice == nullptr) {
|
||||
return false;
|
||||
if (!uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
static const char QuotationSign[] PROGMEM = {"\""};
|
||||
|
||||
// topic
|
||||
{
|
||||
const uint16_t& topicSize = calculateTopicLength(
|
||||
HAComponentName,
|
||||
_name,
|
||||
EventTopic
|
||||
);
|
||||
char topic[topicSize];
|
||||
generateTopic(
|
||||
topic,
|
||||
HAComponentName,
|
||||
_name,
|
||||
EventTopic
|
||||
);
|
||||
|
||||
static const char DataBefore[] PROGMEM = {"{\"t\":\""};
|
||||
|
||||
mqtt()->writePayload_P(DataBefore);
|
||||
mqtt()->writePayload(topic, strlen(topic));
|
||||
mqtt()->writePayload_P(QuotationSign);
|
||||
if (shouldPublishSingleComponentConfig()) {
|
||||
publishConfig();
|
||||
}
|
||||
|
||||
// device
|
||||
{
|
||||
static const char Data[] PROGMEM = {",\"dev\":"};
|
||||
|
||||
mqtt()->writePayload_P(Data);
|
||||
mqtt()->writePayload(serializedDevice, strlen(serializedDevice));
|
||||
}
|
||||
|
||||
{
|
||||
static const char Data[] PROGMEM = {"}"};
|
||||
mqtt()->writePayload_P(Data);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,38 +1,41 @@
|
||||
#ifndef AHA_HATAGSCANNER_H
|
||||
#define AHA_HATAGSCANNER_H
|
||||
|
||||
#include "BaseDeviceType.h"
|
||||
#include "HABaseDeviceType.h"
|
||||
|
||||
class HATagScanner : public BaseDeviceType
|
||||
#ifndef EX_ARDUINOHA_TAG_SCANNER
|
||||
|
||||
/**
|
||||
* HATagScanner allow to produce scan events that can be used in the HA automation.
|
||||
*
|
||||
* @note
|
||||
* You can find more information about this entity in the Home Assistant documentation:
|
||||
* https://www.home-assistant.io/integrations/tag.mqtt/
|
||||
*/
|
||||
class HATagScanner : public HABaseDeviceType
|
||||
{
|
||||
public:
|
||||
/**
|
||||
* Initializes tag scanner with the given name.
|
||||
*
|
||||
* @param name Name of the scanner. Recommendes characters: [a-z0-9\-_]
|
||||
* @param uniqueId The unique ID of the scanner. It needs to be unique in a scope of your device.
|
||||
*/
|
||||
HATagScanner(const char* name, HAMqtt& mqtt);
|
||||
virtual ~HATagScanner();
|
||||
|
||||
/**
|
||||
* Publishes configuration of the sensor to the MQTT.
|
||||
*/
|
||||
virtual void onMqttConnected() override;
|
||||
HATagScanner(const char* uniqueId);
|
||||
|
||||
/**
|
||||
* Sends "tag scanned" event to the MQTT (Home Assistant).
|
||||
* Based on this event HA may perform user-defined automation.
|
||||
*
|
||||
* @param tag Value of the scanned tag.
|
||||
* @returns Returns `true` if MQTT message has been published successfully.
|
||||
*/
|
||||
bool tagScanned(const char* tag);
|
||||
|
||||
private:
|
||||
void publishConfig();
|
||||
uint16_t calculateSerializedLength(const char* serializedDevice) const;
|
||||
bool writeSerializedTrigger(const char* serializedDevice) const;
|
||||
|
||||
const char* _name;
|
||||
protected:
|
||||
virtual void buildSerializer() override;
|
||||
virtual HASerializer* buildDeviceDiscoverySerializer() override;
|
||||
virtual bool supportsDeviceDiscovery() const override
|
||||
{ return true; }
|
||||
virtual void onMqttConnected() override;
|
||||
};
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,260 @@
|
||||
#include "HAText.h"
|
||||
#ifndef EX_ARDUINOHA_TEXT
|
||||
|
||||
#include "../HAMqtt.h"
|
||||
#include "../utils/HADictionary.h"
|
||||
#include "../utils/HASerializer.h"
|
||||
|
||||
HAText::HAText(const char* uniqueId) :
|
||||
HABaseDeviceType(AHATOFSTR(HAComponentText), uniqueId),
|
||||
_icon(nullptr),
|
||||
_retain(false),
|
||||
_optimistic(false),
|
||||
_mode(ModeText),
|
||||
_minValue(),
|
||||
_maxValue(),
|
||||
_pattern(nullptr),
|
||||
_valueTemplate(nullptr),
|
||||
_commandTemplate(nullptr),
|
||||
_currentState(nullptr),
|
||||
_commandCallback(nullptr)
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
, _commandStdCallback()
|
||||
#endif
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
void HAText::setValueTemplate(const char* valueTemplate)
|
||||
{
|
||||
_valueTemplate = valueTemplate;
|
||||
}
|
||||
|
||||
void HAText::setCommandTemplate(const char* commandTemplate)
|
||||
{
|
||||
_commandTemplate = commandTemplate;
|
||||
}
|
||||
|
||||
bool HAText::setState(const char* state, const bool force)
|
||||
{
|
||||
if (!state) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (
|
||||
!force &&
|
||||
_currentState &&
|
||||
strcmp(state, _currentState) == 0
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const bool published = publishState(state);
|
||||
_currentState = state;
|
||||
return published;
|
||||
}
|
||||
|
||||
void HAText::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(HAStateEntityCategory), nonEmptyString(_entityCategory));
|
||||
_serializer->set(AHATOFSTR(HAIconProperty), _icon);
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAModeProperty),
|
||||
getModeProperty(),
|
||||
HASerializer::ProgmemPropertyValue
|
||||
);
|
||||
_serializer->set(AHATOFSTR(HAPatternProperty), _pattern);
|
||||
|
||||
if (nonEmptyString(_valueTemplate)) {
|
||||
_serializer->set(AHATOFSTR(HAValueTemplateProperty), _valueTemplate);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_commandTemplate)) {
|
||||
_serializer->set(AHATOFSTR(HACommandTemplateProperty), _commandTemplate);
|
||||
}
|
||||
|
||||
if (_minValue.isSet()) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAMinProperty),
|
||||
&_minValue,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_maxValue.isSet()) {
|
||||
_serializer->set(
|
||||
AHATOFSTR(HAMaxProperty),
|
||||
&_maxValue,
|
||||
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* HAText::buildDeviceDiscoverySerializer()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
HASerializer* serializer = new HASerializer(this, 22);
|
||||
serializer->set(
|
||||
AHATOFSTR(HAPlatformProperty),
|
||||
AHATOFSTR(HAComponentText),
|
||||
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(HAModeProperty),
|
||||
getModeProperty(),
|
||||
HASerializer::ProgmemPropertyValue
|
||||
);
|
||||
serializer->set(AHATOFSTR(HAPatternProperty), _pattern);
|
||||
|
||||
if (nonEmptyString(_valueTemplate)) {
|
||||
serializer->set(AHATOFSTR(HAValueTemplateProperty), _valueTemplate);
|
||||
}
|
||||
|
||||
if (nonEmptyString(_commandTemplate)) {
|
||||
serializer->set(AHATOFSTR(HACommandTemplateProperty), _commandTemplate);
|
||||
}
|
||||
|
||||
if (_minValue.isSet()) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HAMinProperty),
|
||||
&_minValue,
|
||||
HASerializer::NumberPropertyType
|
||||
);
|
||||
}
|
||||
|
||||
if (_maxValue.isSet()) {
|
||||
serializer->set(
|
||||
AHATOFSTR(HAMaxProperty),
|
||||
&_maxValue,
|
||||
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 HAText::onMqttConnected()
|
||||
{
|
||||
if (!uniqueId()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (shouldPublishSingleComponentConfig()) {
|
||||
publishConfig();
|
||||
}
|
||||
publishAvailability();
|
||||
|
||||
if (!_retain && _currentState) {
|
||||
publishState(_currentState);
|
||||
}
|
||||
|
||||
subscribeTopic(uniqueId(), AHATOFSTR(HACommandTopic));
|
||||
}
|
||||
|
||||
void HAText::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)
|
||||
)) {
|
||||
char value[length + 1];
|
||||
value[length] = 0;
|
||||
memcpy(value, payload, length);
|
||||
if (_commandCallback) {
|
||||
_commandCallback(value, this);
|
||||
}
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
if (_commandStdCallback) {
|
||||
_commandStdCallback(value, this);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
bool HAText::publishState(const char* state)
|
||||
{
|
||||
return publishOnDataTopic(
|
||||
AHATOFSTR(HAStateTopic),
|
||||
state,
|
||||
true
|
||||
);
|
||||
}
|
||||
|
||||
const __FlashStringHelper* HAText::getModeProperty() const
|
||||
{
|
||||
return _mode == ModePassword
|
||||
? AHATOFSTR(HAModePassword)
|
||||
: nullptr;
|
||||
}
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,219 @@
|
||||
#ifndef AHA_HATEXT_H
|
||||
#define AHA_HATEXT_H
|
||||
|
||||
#include "HABaseDeviceType.h"
|
||||
#include "../utils/HANumeric.h"
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
#include <functional>
|
||||
#endif
|
||||
|
||||
#ifndef EX_ARDUINOHA_TEXT
|
||||
|
||||
#define HATEXT_CALLBACK(name) void (*name)(const char* value, HAText* sender)
|
||||
|
||||
/**
|
||||
* HAText adds a text input 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/text.mqtt/
|
||||
*/
|
||||
class HAText : public HABaseDeviceType
|
||||
{
|
||||
public:
|
||||
/// Represents mode of the text input.
|
||||
enum Mode {
|
||||
ModeText = 0,
|
||||
ModePassword
|
||||
};
|
||||
|
||||
/**
|
||||
* @param uniqueId The unique ID of the text entity. It needs to be unique in a scope of your device.
|
||||
*/
|
||||
HAText(const char* uniqueId);
|
||||
|
||||
/**
|
||||
* Changes state of the text 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 text.
|
||||
* @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 char* state, const bool force = false);
|
||||
|
||||
/**
|
||||
* Sets current state of the text 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 text.
|
||||
*/
|
||||
inline void setCurrentState(const char* state)
|
||||
{ _currentState = state; }
|
||||
|
||||
/**
|
||||
* Returns last known state of the text.
|
||||
*/
|
||||
inline const char* getCurrentState() const
|
||||
{ return _currentState; }
|
||||
|
||||
/**
|
||||
* Sets icon of the text.
|
||||
* 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 text 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 text state.
|
||||
* In this mode the text 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 text input.
|
||||
* By default it's `HAText::ModeText`.
|
||||
*
|
||||
* @param mode Mode to set.
|
||||
*/
|
||||
inline void setMode(const Mode mode)
|
||||
{ _mode = mode; }
|
||||
|
||||
/**
|
||||
* Sets minimum accepted length of the command payload.
|
||||
*
|
||||
* @param min Minimum number of characters.
|
||||
*/
|
||||
inline void setMin(const uint16_t min)
|
||||
{ _minValue = HANumeric(min, PrecisionP0); }
|
||||
|
||||
/**
|
||||
* Sets maximum accepted length of the command payload.
|
||||
*
|
||||
* @param max Maximum number of characters.
|
||||
*/
|
||||
inline void setMax(const uint16_t max)
|
||||
{ _maxValue = HANumeric(max, PrecisionP0); }
|
||||
|
||||
/**
|
||||
* Sets regex pattern for command payload validation in Home Assistant.
|
||||
*
|
||||
* @param pattern Regex pattern.
|
||||
*/
|
||||
inline void setPattern(const char* pattern)
|
||||
{ _pattern = pattern; }
|
||||
|
||||
void setValueTemplate(const char* valueTemplate);
|
||||
void setCommandTemplate(const char* commandTemplate);
|
||||
|
||||
/**
|
||||
* Registers callback that will be called each time text command from HA is received.
|
||||
* Please note that it's not possible to register multiple callbacks for the same text entity.
|
||||
*
|
||||
* @param callback
|
||||
* @note In non-optimistic mode, the state should be reported back to HA using HAText::setState.
|
||||
*/
|
||||
inline void onCommand(HATEXT_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(const char*, HAText*)>& 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 char* state);
|
||||
|
||||
/**
|
||||
* Returns progmem string representing mode of the text.
|
||||
*/
|
||||
const __FlashStringHelper* getModeProperty() const;
|
||||
|
||||
/// The icon of the text. It can be nullptr.
|
||||
const char* _icon;
|
||||
|
||||
/// The retain flag for the HA commands.
|
||||
bool _retain;
|
||||
|
||||
/// The optimistic mode of the text (`true` - enabled, `false` - disabled).
|
||||
bool _optimistic;
|
||||
|
||||
/// Controls how the text should be displayed in the UI.
|
||||
Mode _mode;
|
||||
|
||||
/// The minimal number of characters accepted by Home Assistant.
|
||||
HANumeric _minValue;
|
||||
|
||||
/// The maximum number of characters accepted by Home Assistant.
|
||||
HANumeric _maxValue;
|
||||
|
||||
/// Regular expression pattern accepted by Home Assistant. It can be nullptr.
|
||||
const char* _pattern;
|
||||
|
||||
const char* _valueTemplate;
|
||||
const char* _commandTemplate;
|
||||
|
||||
/// The current state of the text. It can be nullptr if state wasn't set.
|
||||
const char* _currentState;
|
||||
|
||||
/// The callback that will be called when command is received from the HA.
|
||||
HATEXT_CALLBACK(_commandCallback);
|
||||
|
||||
#if defined(ARDUINOHA_ENABLE_STDFUNCTION)
|
||||
/// The std::function callback that will be called when command is received from the HA.
|
||||
std::function<void(const char*, HAText*)> _commandStdCallback;
|
||||
#endif
|
||||
};
|
||||
|
||||
#endif
|
||||
#endif
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user