Compare commits

..

179 Commits

Author SHA1 Message Date
HomeSpan d6fcc50a0b
Merge pull request #878 from HomeSpan/release-1.9.1
Release 1.9.1
2024-07-03 17:59:28 -04:00
HomeSpan c6e032b5af
Merge branch 'master' into release-1.9.1 2024-07-03 17:57:51 -04:00
HomeSpan 144559f6d6
Update library.properties 2024-07-03 16:55:36 -05:00
HomeSpan f3066ea9c6
Update README.md 2024-07-03 16:52:19 -05:00
HomeSpan 875c53f8fd
Update README.md 2024-06-30 20:54:29 -05:00
HomeSpan 7494e0bb22
Update PWM.md 2024-06-30 20:48:30 -05:00
Gregg e23247c39f Added NAN as allowed value for ServoPin::set()
Sets duty-cycle to 0, which allows an analog servo to freely rotate.  Use Servo::set() with an actual number in degrees to restore position.
2024-06-30 17:15:00 -05:00
Gregg 212370f57c Merge branch 'release-1.9.1' of https://github.com/HomeSpan/HomeSpan into release-1.9.1 2024-06-30 16:17:36 -05:00
Gregg 767a125a70 Update 22-TLV8_Characteristics.ino 2024-06-30 16:17:30 -05:00
HomeSpan 40e8dcbec2
Update TVServices.md 2024-06-30 16:16:45 -05:00
HomeSpan beee92f6ee
Update TVServices.md 2024-06-30 16:10:49 -05:00
HomeSpan aad5d26c5b
Update TVServices.md 2024-06-30 16:00:03 -05:00
HomeSpan e522e709c9
Update Reference.md 2024-06-30 15:31:15 -05:00
Gregg b6ed73aed1 Use typedefs for CREATE_CHAR() to ensure consistency 2024-06-30 12:35:37 -05:00
Gregg 8f133585f9 Update 22-TLV8_Characteristics.ino 2024-06-30 12:19:58 -05:00
Gregg e6b57b6723 Merge branch 'release-1.9.1' of https://github.com/HomeSpan/HomeSpan into release-1.9.1 2024-06-29 15:47:06 -05:00
Gregg 2a91ed645a updated ServiceList.md 2024-06-29 15:47:03 -05:00
HomeSpan a3891cd983
Update Reference.md 2024-06-29 15:36:04 -05:00
HomeSpan d9af8032a4
Update Reference.md 2024-06-29 15:14:52 -05:00
Gregg dbe07dad7e Merge branch 'release-1.9.1' of https://github.com/HomeSpan/HomeSpan into release-1.9.1 2024-06-29 10:03:10 -05:00
Gregg 3ed18b3f79 Added constructors for TLV8 and DATA Characteristics
Conformed all CUSTOM_CHAR macros to allow for these constructors
2024-06-29 10:03:07 -05:00
HomeSpan a223d3046a
Update TLV8.md 2024-06-27 07:10:19 -05:00
HomeSpan b8338cad71
Update TLV8.md 2024-06-27 06:59:32 -05:00
Gregg 1b93c7e75b Merge branch 'release-1.9.1' of https://github.com/HomeSpan/HomeSpan into release-1.9.1 2024-06-26 22:08:39 -05:00
Gregg d7dbb5fee5 Update HomeSpan.h 2024-06-26 22:08:36 -05:00
HomeSpan 970f4d7ce8
Update README.md 2024-06-26 21:14:23 -05:00
HomeSpan 9b791e2ac3
Update Reference.md 2024-06-26 21:00:52 -05:00
Gregg f73c779913 Added "constantness" to all aspects of TLV8 code, including Characteristic Constructors 2024-06-25 21:59:23 -05:00
Gregg 2d25c044ae Allow TLV8 Characteristics to accept an initial value when instantiated
Also simplified up form of SpanCharacteristic init() template
2024-06-25 20:50:40 -05:00
Gregg 7a13b99942 Added initial method to contract TLV8 Characteristic; Added UUID static char to Services; Added hapName filter to getLinks() 2024-06-23 10:19:32 -05:00
Gregg c3c32dbc07 Changed SpanServices::getLinks() to template function
Allows return of Linked Services to be cast into a pointer to any Service type.  Default template if not specified is <SpanService *>
2024-06-21 21:36:55 -05:00
Gregg 2279c30510 Update HAP.cpp 2024-06-19 13:02:11 -05:00
HomeSpan 7de8f1abb4
Update TVServices.md 2024-06-16 09:10:52 -05:00
HomeSpan 463bdd4cda
Update TVServices.md 2024-06-16 09:09:52 -05:00
HomeSpan 8e2304bacb
Update README.md 2024-06-15 22:07:27 -05:00
Gregg 9653224aca Allow homeSpan.begin() to take dynamic char * instead of just constant string 2024-06-12 21:18:44 -05:00
Gregg c1b2d49da1 Added version.h containing check for Arduino-ESP32 Version 2
Also includes HomeSpan version number
2024-06-10 21:11:50 -05:00
HomeSpan b4a32e82bb
Update Reference.md 2024-06-09 07:31:35 -05:00
HomeSpan c0d1a93c52
Update README.md 2024-06-09 07:21:17 -05:00
HomeSpan 901807e47a
Merge pull request #862 from HomeSpan/master
update dev with any changes in master documentation
2024-06-09 08:12:01 -04:00
HomeSpan f09499359b
Merge pull request #861 from HomeSpan/structural
Structural->Dev
2024-06-08 21:54:13 -04:00
Gregg e10025bd54 Update HomeSpan.cpp 2024-06-08 20:32:39 -05:00
Gregg 7ab8354ed7 Deleted setMaxConnections() and DEPRECATED reserveSocketConnections
setMaxConnections() was deprecated many version ago and is now deleted

reserveSocketConnections() is no longer needed since new HomeKit architecture does not require more than a few connections - this function has been deprecated and if used will not do anything
2024-06-08 18:03:37 -05:00
Gregg 892c2247a3 Finished testing new evList functionality 2024-06-08 17:46:49 -05:00
Gregg 983e159adf Created evList to store notifications
Also updated all code to use hapList and deleted all references to **hap
2024-06-08 16:45:46 -05:00
Gregg 153ab451fd Moved Controller Class definition back to HAP.h instead of HomeSpan.h
As long as `class Controller` is forward-declared in HomeSpan.h, the definition can live in HAP.h
2024-06-05 13:32:15 -05:00
Gregg 9d29b73dac Fixed memory leak [needed to free `body` in tlvRespond()]
This hopefully addresses memory leak that occurs when not using a Home Hub and connections constantly drop and re-establish.

To do: must add back logic for notifications using new hap linked-list structure, and then delete static hap array code.
2024-06-02 20:57:41 -05:00
HomeSpan cce2dc59b4
Update README.md 2024-05-31 08:56:27 -05:00
Gregg dbfad7d222 initial change of hap[i] to linked-list from fixed array 2024-05-12 07:17:21 -05:00
Gregg 3643506d89 Move temporary keys for pairing/verification into separate structure
Confirmed pairing and verification continue to works as expected.
2024-05-11 13:29:07 -05:00
Gregg e0ec162938 Added logic to check for hap[i] disconnect and issue stop() when found
This cures memory leakage when using HomeSpan without a Home Hub.  Sockets are now properly closed when the Home App abruptly disconnects.
2024-05-11 07:43:11 -05:00
Gregg 747b8c3244 initial change in hap[i] array to reserve space according to socket number 2024-05-08 06:45:57 -05:00
Gregg be4825dacb Move "internal" SpanCharacteristic methods from public to private
As well as additional clean-up of organization and format of SpanCharacteristic prototype declarations.
2024-05-04 08:31:34 -05:00
Gregg 214286f4de remove deprecated SpanRange structure
Has been deprecated many versions ago.
2024-05-04 08:07:03 -05:00
Gregg 80a8935828 Moved definitions of non-template SpanCharacteristic methods from HomeSpan.h to HomeSpan.cpp 2024-05-03 06:36:25 -05:00
Gregg 8775a2df85 Eliminated use of exceptions in PSRAM.h and added -fno-exceptions
Added build_opt.h which include -fno-exceptions compiler instructions.  Seems to save about 29K of flash in compiled code (compiling for ESP32)
2024-05-02 20:45:30 -05:00
HomeSpan 1863cc4309
Update README.md 2024-04-29 21:37:54 -05:00
HomeSpan d523a27124
Update Tutorials.md 2024-04-29 21:36:06 -05:00
HomeSpan 638285f48f
Update README.md 2024-04-29 21:31:56 -05:00
HomeSpan a52a2ad432
Update README.md 2024-04-29 21:24:17 -05:00
Gregg 4af2bdbbe3 Add displayOrder to ServiceList.md
Run shell-script 'tools/makeServiceList'
2024-04-29 21:22:37 -05:00
HomeSpan 0c22bfb752
Update README.md 2024-04-29 15:45:34 -05:00
HomeSpan 2bdafb534e
Update README.md 2024-04-29 07:57:46 -05:00
HomeSpan 7843ce49a5
Merge pull request #843 from HomeSpan/tlvwork
Tlvwork into Dev
2024-04-28 22:52:04 -04:00
HomeSpan bdf25cbaf9
Update Reference.md 2024-04-28 20:41:16 -05:00
HomeSpan 96a08ea84b
Update Reference.md 2024-04-28 13:23:54 -05:00
HomeSpan 1267603e71
Update Reference.md 2024-04-28 12:59:42 -05:00
HomeSpan a8883c911d
Update Reference.md 2024-04-28 11:13:53 -05:00
HomeSpan db80dab963
Update Reference.md 2024-04-28 11:03:57 -05:00
Gregg 74d27485d5 Added homeSpan.setControllerCallback()
Also adds: homeSpan.controllerListBegin(), homeSpan.controllerListEnd()
Also adds: Controller::isAdmin(), Controller::getID(), Controller::getLTPK()

To accomplish this, needed to move Controller definition from HAP.h to HomeSpan.h

Also, converted Controller from struct to class to ensure Controller data is protected from being modified now that it is exposed through condstant iterators.
2024-04-28 08:15:04 -05:00
HomeSpan ee2e850505
Update TLV8.md 2024-04-27 16:14:24 -05:00
HomeSpan 7a796bac2f
Update Tutorials.md 2024-04-27 16:13:22 -05:00
HomeSpan 012c778f15
Update Tutorials.md 2024-04-27 10:47:52 -05:00
HomeSpan 0eec3920f4
Update TLV8.md 2024-04-27 10:45:18 -05:00
HomeSpan d2d1b79c4d
Update TLV8.md 2024-04-27 10:44:30 -05:00
HomeSpan a92f73666a
Update TLV8.md 2024-04-27 10:40:34 -05:00
Gregg 3273f7f24d Completed Example 22-TLV8_Characteristics
Must update Television.md documentation as well as Television Example to reflect recent changes to the Characteristics Apple made - there seems to be less flexibility in what needs to be defined to use the input sources.

Also need to add DisplayOrder Characteristic to TV documentation.
2024-04-23 06:41:44 -05:00
Gregg a785c1f937 Merge branch 'tlvwork' of https://github.com/HomeSpan/HomeSpan into tlvwork 2024-04-22 22:49:58 -05:00
Gregg 3db4676b7d Created initial Example 22 - TLV8_Characteristics
Requires some debugging...
2024-04-22 22:49:55 -05:00
HomeSpan 20f74aa968
Update TLV8.md 2024-04-22 20:43:11 -05:00
HomeSpan c7f67225d6
Update TLV8.md 2024-04-21 22:08:04 -05:00
HomeSpan 0be3b0cd1b
Update Reference.md 2024-04-21 21:23:44 -05:00
HomeSpan 050a30f72c
Update Reference.md 2024-04-21 21:16:08 -05:00
Gregg 4e5d03f63f renamed CUSTOM_CHAR_TLV() macro to CUSTOM_CHAR_TLV8() macro 2024-04-21 15:18:22 -05:00
HomeSpan 04cb07a0fc
Update README.md 2024-04-21 12:45:27 -05:00
HomeSpan 059c58ca46
Update TLV8.md 2024-04-21 12:41:14 -05:00
HomeSpan 4334789d50
Update TLV8.md 2024-04-21 12:39:39 -05:00
HomeSpan fa25369ebb
Update TLV8.md 2024-04-21 12:37:51 -05:00
HomeSpan ccda8f04d9
Update TLV8.md 2024-04-21 10:31:10 -05:00
HomeSpan b995a75907
Update TLV8.md 2024-04-21 08:30:07 -05:00
HomeSpan 998bd873bc
Update TLV8.md 2024-04-21 08:27:00 -05:00
HomeSpan bfdf114ed3
Update TLV8.md 2024-04-21 07:46:01 -05:00
HomeSpan d51b74e1c1
Update TLV8.md 2024-04-21 07:06:36 -05:00
HomeSpan aa9d64cb58
Update TLV8.md 2024-04-20 20:17:02 -05:00
HomeSpan e83df601b2
Update TLV8.md 2024-04-20 20:08:53 -05:00
HomeSpan e0f593bc2e
Update TLV8.md 2024-04-20 19:50:46 -05:00
HomeSpan d9e9783dc1
Update TLV8.md 2024-04-20 19:01:50 -05:00
HomeSpan e6c7637825
Update TLV8.md 2024-04-20 18:35:29 -05:00
Gregg b4bfac54e7 small tweaks to the TLV8 library for ease of use 2024-04-20 10:14:31 -05:00
HomeSpan 173ba036f0
Update TLV8.md 2024-04-20 09:05:43 -05:00
HomeSpan 15a0396897
Update TLV8.md 2024-04-20 08:00:19 -05:00
HomeSpan cd3b525dbb
Update TLV8.md 2024-04-20 07:54:41 -05:00
HomeSpan f96721b948
Update TLV8.md 2024-04-20 07:23:18 -05:00
HomeSpan 520a4f3df0
Update TLV8.md 2024-04-19 22:05:02 -05:00
HomeSpan 9b0555d256
Update TLV8.md 2024-04-19 12:58:43 -05:00
HomeSpan b05be87a29
Update TLV8.md 2024-04-18 22:20:58 -05:00
HomeSpan dfec533212
Create TLV8.md 2024-04-18 21:06:47 -05:00
HomeSpan 04443d70dd
Update Reference.md 2024-04-18 20:59:55 -05:00
HomeSpan 2ecbed9f26
Update Reference.md 2024-04-18 18:21:02 -05:00
HomeSpan 6794a804f9
Update README.md 2024-04-18 17:59:31 -05:00
HomeSpan 64f67fbb8a
Update Reference.md 2024-04-18 07:04:13 -05:00
HomeSpan bb531184d7
Documents resetIID(), Service::getIID() and Characteristic::getIID() 2024-04-18 06:43:58 -05:00
Gregg d1dd565478 Converted IID from int to uint32_t everywhere 2024-04-17 07:24:08 -05:00
Gregg 723c343277 Added error checking to warn if non-bridge device defines more than 3 Accessories
It appears that HomeKit requires devices with more than 3 Accessories to be configured as a bridge.  If not, the Home App will ignore any functional Services in the first Accessory and treat it like a bridge regardless.  Device with 3 or less Accessories do not require a bridge configuration.
2024-04-16 22:17:00 -05:00
Gregg b9efa873dc Added error-checking for homeSpan.resetIID()
HomeSpan will throw a Warning when 'i' CLI command finds a duplicate IID within the same Accessory.
2024-04-16 21:56:07 -05:00
Gregg fe3269e9ef Added new validation check for homeSpan.resetIID()
New value must be equal to, or greater than, the last IID value used.  This prevents possible re-use.
2024-04-15 22:14:05 -05:00
Gregg 73561328e6 Changed TLV8:add() for *values* to ensure resulting size is always multiple of 2
Checked that this is correctly interpreted by HomeKit using adaptive light TLV.

TLV code is now ready for documentation and then transfer to dev branch.
2024-04-14 21:29:02 -05:00
Gregg a7d57699a0 Added homeSpan.resetIID()...
...as well as SpanService.getIID() and SpanCharacteristic.getIID().

This provides control of IIDs used for each Service and Characteristic.
By using this with adaptive lighting test, was able to verify that HomeKit can interpret TLV values of 1 byte, 2 bytes, and 4 bytes, but not 3 bytes.  Suggests that TLV values need to be multiples of 2 (i.e. uint8, uint16, uint32).  Will change TLV value-writing methodology so that padding zeros are used to round to 1, 2, 4, or 8 bytes.
2024-04-14 21:05:09 -05:00
Gregg e4df56293a Added TLV8:printAll()
Recursively prints an entire TLV and all embedded sub-TLVs based on a best-guess if the value of any TLV is a sub-TLV.
2024-04-14 13:37:04 -05:00
Gregg 48cab1f82b Changed tlv8_t from struct to class and made variables private
Add getLen() and getTag() method to get length and tag of tlv8_t.

Also overrode subscript operator [] so you can access any element of internal uint8_t array.

Given previous additions (such as getVal()) there is now no reason to need to access the underlying std::unique_ptr directly.
2024-04-13 22:59:37 -05:00
Gregg 28990d6ed6 Revert "Changed TLV:add() so it returns TLV8 instead of iterator."
This reverts commit 7a50479bac.
2024-04-13 22:00:37 -05:00
Gregg 7a50479bac Changed TLV:add() so it returns TLV8 instead of iterator.
Makes it easier to chain .add() functions as well as dynamically create sub TLVs.

Changing TLV8::add() in this fashion also required updating various use cases of TLV::add() in HAP.cpp where add() was used to reserve space for a blank TLV element.  All changes have been tested.
2024-04-13 19:12:26 -05:00
Gregg 5ded77d6d9 Replace TLV8 (*it)[0] with new TLV8 getVal() method in HAP.cpp 2024-04-08 21:52:51 -05:00
Gregg d40d709643 Add TLV8 add() methods for uint64_t and char*, as well as new getVal() template for returning an integer 2024-04-08 21:33:27 -05:00
Gregg acebaf6caa Add ability to unpack TLV8 by iterator
Also fixed bug using increment operator (++) by replacing with std::next()
2024-04-06 21:45:49 -05:00
Gregg 7e2625034c Added TLV8_it add(uint8_t tag, TLV8 &subTLV)
Allows easy-add of a sub TLV to an existing TLV8
2024-04-04 21:31:28 -05:00
Gregg 75cbf9715f added mechanism to strip unnecessary backslashes from Home App JSON
Apple "escapes" forward slashes in JSON output, replacing '/' with '\/', which destroys base64 strings.
2024-04-04 21:12:13 -05:00
Gregg 3d4b02e492 created getDataGeneric() and getStringGeneric()
Though this simplifies the code, the code size is still the same - compiler must have already optimized these functions.
2024-03-31 21:40:00 -05:00
Gregg 1892a0a5a2 created getTLVGeneric() and used as base for getTLV() and getNewTLV()
avoids unnecessary duplication of code where the only difference is whether you need the value or the newValue of a Characteristic.
2024-03-31 21:25:22 -05:00
Gregg f137b0bee5 Updated getTLV() so it uses a fixed buffer as intermediate step
This is much more memory efficient.  Instead of decoding entire STRING from base64 to a temporary buffer or potentially very large size and then unpacking into TLV object, we decode a maximum of 48 characters at a time and unpack the resulting 36 (max) bytes until entire STRING is consumed.

getTLV() returns pack_size of final TLV, unless there is a problem with conversion, in which cae TLV is wiped and return value=0
2024-03-31 21:13:17 -05:00
Gregg eb821f002f created getTLV(TLV8 &tlv)
Works, but is memory-inefficient since it decodes entire string before unpacking.  Need to add new functionality to TLV8 so that unpacking can be done in chunks similar to how pack() works.

Also need to create getNewTLV() OR make all get/getNew generic to reduce code size.
2024-03-31 09:23:23 -05:00
Gregg cbe26c7c41 update setString() to use setValCheck() and setValFinish() 2024-03-31 08:51:06 -05:00
Gregg 11bd605a03 updated setData and setTLV to use new common setValCheck() and setValFinish() 2024-03-30 22:13:52 -05:00
Gregg f6d4d37ff7 Initial creation of setTLV() 2024-03-30 17:51:37 -05:00
Gregg e8f9ca8ac1 Modified UUID check to allow for Custom short-form UUID
Also truncated string Characteristics printed via 'i' CLI Command to show only first 32 characters followed by "..." if there are more than 32.
2024-03-30 06:03:31 -05:00
Gregg 69fd86f2ef Testing TLV Characteristic using DisplayOrder (custom Characteristic) 2024-03-29 22:18:04 -05:00
Gregg 1b74564baf More TLV updates 2024-03-29 09:19:06 -05:00
Gregg a11eab4b37 Fixed return value in TLV8::add() 2024-03-27 20:41:29 -05:00
Gregg 9b0b18310e changed TLV8 from std::forward_list to std::list
Though this increases space requirement for TLV8 (just a little), using std::list allows adding elements directly to end, which ensure the order is maintained when packing and unpacking.  Will avoid potential confusion when TLV8 is used for Characteristics.
2024-03-24 22:03:23 -05:00
HomeSpan 7c5b01e967 Additional logic for TLV Characteristics 2024-03-24 09:37:27 -05:00
Gregg 6bc45cf884 Added enum and logic for TLV Characteristics 2024-03-17 19:54:48 -05:00
HomeSpan 41f755039f
Update Reference.md 2024-03-16 14:29:36 -05:00
Gregg faa99e0fbb Added checks for use of setVal()
Throws warning, but still performs change, if setVal() is used within update() to change the value of a Characteristic that is being updated by the Home App, UNLESS the Characteristics has requested a write-response (in which case setVal() is expected).

Throw warning, and DOES NOT perform change, if setVal() is used on a Characteristic without EV permission, UNLESS it has been used in update() in response to a write-response request.

Also added diagnostic to 'i' CLI command that indicates which connections have currently asked to EV Notifications for each Characteristic.  Only applies if EV permission is set for a Characteristic.
2024-03-16 13:56:04 -05:00
Gregg 8ce80157b3 Added native support for WR (write-response)
HAPClient::putCharacteristics() now parses for "r":true in JSON, which is the HAP request for a write-response.  When found, HomeSpan will return with a full write-response for all Characteristics updated using "207 Multi-Status", where "value" will be included only if "r":true was specified for a Characteristic.

HomeSpan processes "r":true for any Characteristic regardless if permissions includes WR.

To change the value of the Characteristic from within an update() method, use setVal() WITH OPTIONAL SECOND ARGUMENT AS FALSE to supress an EV broadcast (in the unlikely event that there was a notification subscriber).

To do: Consider generally disallowing the changing of any Characteristic value from within update() using setVal() unless the Characteristic has WR permission.  And if so, automatically surpress EV notification.
2024-03-15 17:35:04 -05:00
HomeSpan 181c5e99b2
Update Tutorials.md 2024-03-09 19:04:59 -06:00
Gregg cf2a98d1c2 Review and refresh comment in Tutorial Examples as needed.
Also introduced the use of Enumerated Constants in Example 13 - Target States
2024-03-09 19:00:05 -06:00
HomeSpan 2d1b567388
Update Tutorials.md 2024-03-09 17:26:05 -06:00
Gregg 7a58a20de1 Created Example 21 - AccessoryIdentifier 2024-03-09 15:07:31 -06:00
HomeSpan 04a10309c2
Sync on-line documentation (#802)
* Update NOW.md

* Update Solutions.md

* Update Solutions.md
2024-03-09 08:59:21 -06:00
HomeSpan aa6f3690a4
Update Solutions.md 2024-03-09 08:55:37 -06:00
HomeSpan 52e7bfef2b
Update Solutions.md 2024-03-09 07:17:40 -06:00
HomeSpan 16f3e9d146
Update NOW.md 2024-03-07 22:06:59 -06:00
HomeSpan 0f10d9354d
Merge pull request #799 from HomeSpan/master
Update Dev with Master
2024-03-05 06:03:22 -06:00
HomeSpan 1510718e65
Update Solutions.md 2024-03-05 05:58:15 -06:00
HomeSpan d441f81548
Update Solutions.md 2024-03-04 20:49:58 -06:00
Gregg be893b0968 Update DEV_Blinker.h 2024-03-04 06:04:13 -06:00
Gregg 38e0b1efea Bug-fix in SpanPoint that caused a crash when receiveSize=0
When printing SpanPoint configuration data to the Serial Monitor info using the 'i' CLI command, HomeSpan did NOT check to see if the receiveSize was zero, in which case there would be no queue, which caused a crash when trying to report the queue depth.   Since all existing SpanPoint examples were based on receiving data from remote devices, this bug was never encountered (since the receiveSize was always greater than zero).

Fix: check to see if receiveSize==0.  If it is, do not retrieve queue depth, but report zero instead.
2024-03-03 17:27:45 -06:00
Gregg e3e0b11717 Converted HKDF from struct to simple functions in HKDF namespace
Eliminated the need to instantiate a static HKDF structure within HAPClient since there is no storage within HKDF itself, just a single function call (create).
2024-03-02 16:02:16 -06:00
Gregg 24f36bbccb Moved all NVS Handles into Span
Also added Span constructor that call nvs_open for each nvs_handle upon start-up instead of waiting for homeSpan.begin() and HAP::init()
2024-03-02 15:49:06 -06:00
HomeSpan 3bb9df4818
Update README.md 2024-03-02 12:16:31 -06:00
HomeSpan 6011d09e8d
Update Reference.md 2024-03-02 12:02:58 -06:00
Gregg 0d404ccf1b Fixed bug in setPairingCode() and added second "internal" argument
homeSpan.setPairingCode() operates silently if called from within a sketch, but will report error to Serial Monitor and HALT sketch if code is invalid.

Otherwise, if called from 'S', or from AP, or as default during start-up, diagnostics are printed as usual and sketch will NOT halt if invalid code is provided
2024-03-02 11:57:40 -06:00
HomeSpan c17fabe326
Update Pixels.md 2024-02-29 18:36:58 -06:00
Gregg 959e3cbcde Update Pixel.cpp 2024-02-27 06:17:46 -06:00
HomeSpan b6c479eafc
Update Pixels.md 2024-02-26 06:50:09 -06:00
HomeSpan 8aec89c0fd
update dev (#787)
* Update README.md

* Update Solutions.md

* Update FAQ.md

* Update FAQ.md

* Update Solutions.md

* Update Solutions.md

* Update Solutions.md
2024-02-26 05:59:38 -06:00
Gregg e708d1d148 Update Pixel.ino 2024-02-25 22:19:35 -06:00
Gregg c16e0612be Added Pixel::isRGBW(), and added Other Example -> PixelTester sketch
Also flagged the original constructor, Pixel(int pin, boolean isRGBW), as being deprecated, though it will still work as expected.
2024-02-25 21:53:33 -06:00
Gregg a0bf2c8c8a Removed setColorMap and replaced as second parameter to Pixel constructor
Provides for full backwards compatibility with previous constructor.
2024-02-25 17:21:52 -06:00
Gregg 0cf12f3331 Completed Pixel::setColorMap() 2024-02-24 20:51:45 -06:00
Gregg 218e1f6611 added Pixel::setColorMap() 2024-02-24 18:15:52 -06:00
HomeSpan 42e174e3cd
Update Solutions.md 2024-02-19 11:54:25 -06:00
HomeSpan c6183ff20f
Update Solutions.md 2024-02-19 11:46:50 -06:00
HomeSpan b0fa52858f
Update Solutions.md 2024-02-19 11:46:04 -06:00
HomeSpan 51385874e4
Update FAQ.md 2024-02-19 08:26:24 -06:00
HomeSpan 13657d45b4
Update FAQ.md 2024-02-19 08:22:52 -06:00
HomeSpan 6bc1483dcb
Update Solutions.md 2024-02-18 10:21:28 -06:00
HomeSpan 694723b959
Update README.md 2024-02-18 09:32:53 -06:00
HomeSpan d10f73e3c7
Release 1.9.0 (#775)
* Converted various homeSpan.set() methods from void to Span& to enable chaining

* Update Reference.md

* Update Reference.md

* Update src.ino

* Update Pixel.ino

changed nPixels from uint8_t to int to allow for longer pixel strands (library is coded for int, so there is no need to limit to uint8_t in the example).

* Converted static HTTP Buffer to dynamic TempBuffer

Saved about 8K in RAM!

* Upgraded TempBuffer logic to use .get() to return pointer

Next up: update Network.cpp to use client.available() and reduce fixed memory usage.

* Update Network.cpp

* Replaced appropriate snprintf() with asprintf() and used *m in sscanf

Optimized use of heap memory instead of stack memory for temporary variables, and makes code easier to read, provided all heap usage is free() at end of each function.

Also removed char *hostName as a member variable of homeSpan.  It's never actually used since MDNS constructs its own copy of hostName as needed.

* Removed duplicate if(POST /pairings)

* modified HAP::receivedEncrypted() to use TempBuffer instead of fixed stack array

* Added HAPClient::listControllers()

Will be used for pairings list request

* Completed adding LIST to HAPClient::postPairingsURL()

HomeSpan now correctly responds to pairing list requests

* Refactored TLV

* Added support for zero-length TLV
* Added SEPARATOR as a formal kTLVType (and updated listControllers() to use)
* Added `uint8_t *buf(tagType tag, uint8_t *src, int len);` to load buffer needing external memcpy (and updated listControllers() to use)

* Simplified `uint8_t *TLV<tagType, maxTags>::buf(tagType tag, int len)`

Also updated HAP.cpp to use new `uint8_t *TLV<tagType, maxTags>::buf(tagType tag, uint8_t *src, int len)`

* Refactored Controller Structure and Add/Remove/List/Save Functions

Changed fixed-size array `struct Controller[MAX_CONTROLLERS]` to a dynamic linked-list of Controllers.  Re-coded all related functions.  MAX_CONTROLLERS no sets the size of any buffers but is only used to limit the ultimate size of the linked-list.

Saved about 1K of RAM since most of the time there are only 2 Controllers defined (as opposed to the 16 allowed).

* Support Non-English WiFi name

* Preventing possibility of buffer overwrite.

* Update README.md

* Update README.md

* Bumped release to 1.8.1

* Added homeSpan.setWebLogCallback(String (*f)())

Allows extension of initial table produced in WebLog, where f is a function that returns a String.  The returned String is copied into the WebLog HTML just before the </table> tag is printed in the initial table.

* Change webLogCallback() to pass String as reference

* Verbose WiFi Reconnect
Add the ability to turn off WiFi reconnect messages.

* Update Reference.md

* Update Logging.md

* Update README.md

* Added homeSpan.setWifiCallbackAll(int n)

Adds a second type of WiFi Callback that is called every time WiFi is established OR re-established after a disconnect.  Passes the number of times WiFi has been connected as an argument.

* Update README.md

* Update Reference.md

* Update README.md

* Made conforming changes to setVerboseWiFiReconnect

* Update Reference.md

* Update README.md

* Update Reference.md

* Update Logging.md

* Changed Accessory Limit from 41 to 150 and added Memory Warning

Low Memory Watermark is compared to DEFAULT_LOW_MEM_THRESHOLD (currently set at 80,000 bytes) after HAP initialization but before WIFI connection.  If Low Memory Watermark is below DEFAULT_LOW_MEM_THRESHOLD, a WARNING is issued.

Note: memory is based on heap with MALLOC_CAP_DEFAULT capabilities

* Update Reference.md

* Made vTaskDelay(5) in pollTask conditional of using autoPoll()

vTaskDelay(5) is only needed if polling is in its own task.  If calling poll() directly, there is no need for any delay.

* Update Logging.md

* Add hint for UTF8 usage in names

* Moved vTaskDelay(5) from pollTask() to homeSpan.autoPoll()

Adding the vTaskDelay(5) to the code that spawns the separate task is more consistent with how Arduino-ESP32 spawns the main loop() task.

* Update HomeSpan.h

Forgot braces in for-loop of autoPoll()

* Update 07-AccessoryNames.ino

fix typo

* Update Reference.md

* Add MAC Address output to RemoteDevice.ino

Prompts user with reminder of which MAC Address to use in Main Device.

* Added new homeSpan.rebootCallback() function

An optional callback used to track the number of times the device reboots, where a reboot is defined as any restart where the uptime was less than a specified number of milliseconds (default=5000)

* Update src.ino

* Update Reference.md

* Update src.ino

* Update README.md

* Update Reference.md

* Update README.md

* Update 07-AccessoryNames.ino

* Update HAPClient::sendEncrypted() to send individual frames to save memory

Rather than use a large temporary buffer to store all encrypted frames to transmit all at once, each encrypted frame is transmitted as soon as created, which means the temporary buffer only needs to be large enough to store a single encrypted frame.

For a device with a large number of Accessories, this can save 15-20 KB of temporary storage, allowing for more Accessories.

Note this change does not reduce the size of the unencrypted message that is initially produced and can also be quite large.  Potential for future project.

* Changed storage of required and optional Characteristics from unordered_set to vector

Significantly reduces memory usage - unordered_sets take up much more memory and using std::find from <algorithm> is as efficient as using find() method of an unordered_set.

To do: Remove all uses of unordered_set across HomeSpan wherever possible

* Changed unordered_set to vector when checking for duplicate AID

This eliminated the use of unordered_set everywhere in HomeSpan

* Added error checking for NVS storage

Also added NVS storage diagnostic to 'm' command.

* Fixing HTML syntax error in weblogs.

* PSRAM: Adds custom allocator and HS_MALLOC/HS_CALLOC macros

Forces all heap requests to be drawn from PSRAM, unless the device does not contain PSRAM.

To do:  Provide easy-to-use NEW() macro; add custom allocator to unordered sets; auto-shrink vectors after updateDatabase()

* Added ps_new() macro

A more generic version of `new(*ptr)` that allocates from PSRAM if present, otherwise is that same a normal `new`

* Added HS_REALLOC macro for generalized realloc() when using PSRAM

When using PSRAM, changing the number of Accessories no longer creates any change to heap usage on internal RAM.  The entire Accessory will be stored in PSRAM.

* Address WebLog size issue that limited number of entries

Added logic to sequentially transmit chunks of the HTML response String whenever it grows beyond 1024 bytes.  This ensures the number of WebLog entries does not create a very large HTML String that eats up all the free heap space.  WebLog entries are now only limited by storage of the entries themselves.  Tested successfully with 500 entries.

* Change NVS storage for Characteristics to always use nvs_set_u64()

Reduces NVS consumption by from 3 to only 1 records when storing numerical values.

Also:  Fixed memory problem in getCharacteristics by replacing dynamically-sized stack buffers with TempBuffer (must do this everywhere), which was causing stack probllem when combination number of Accessories and number of Characteristics got very large.

* Override new operator for SpanAccessory, SpanService, and SpanCharacteristic

New Operator now uses PSRAM if available, else uses Internal RAM.  Obviates the need for the ps_new() macro, though will keep definition since it may be useful for any class that does not already override malloc() to use PSRAM.

* Streamlined NVS recall for String values

Avoids need for intermediate variable

* Create MaxAccessories.ino

Demonstrates use of custom partition and shows how PSRAM is used in background when available

* Create partitions.csv

* Changed various static and dynamic stack-based buffers to TempBuffer

Also added casting overload to TempBuffer so that get() method is no longer needed

* Eliminated .get() from TempBuffer objects where possible

Stylistic only.  Cannot remove .get() when a TempBuffer is being re-cast.  Also can't remove .get() when cast can't be determined, such as when used in Serial.printf() [potential to do: explore if this can be addressed, though this is stylistic only and has no impact on code]

* Added Characteristic Constants

Added constants to Characteristics that describe states.

Example: Characteristic::SecuritySystemTargetState::ARM_STAY

* Correction to time server URL doc

* Addressed issue with new Characteristic enum constants

* Update MaxAccessories.ino

* Added ability to turn off SpanPoint encryption

New class-level method SpanPoint::setEncryption(boolean encrypt).  Default is to use encryption unless method is called with encrypt=false.

With encryption, 7 connections max; without encryption, 20 connections max.
 Serial Monitor provides warnings if connections are exceeded.

* Update NOW.md

* Update README.md

* Update README.md

* Update README.md

* Added new TLV8 class

To do: Refactor HAP.cpp to use new TLV8 class

* Starting to integrate new TLV8 into postPairVerify

* Completed re-factoring of postPairVerify using new TLV8

Next: re-factor postPairSetup

* Preparing for re-factoring postPairSetup

* Starting re-factoring of postPairSetup

* added TLV length function

Checks that iterator exists (i.e. does not equal end()) and returns length, else returns -1.  Can be used for checking for both the presence, and length, of a TLV record

* Completed initial re-factoring of postPairSetup - must test!

* Completed postPairSetup and fully tested - also changes TLV8 from vector to forward_list

Changed TLV8 from vector to forward_list to ensure iterators are always retained after adding new elements.

Nest: refactor postPairings

* Completed and fully tested refactoring of TLV8

Next up: remove old TLV code and clean up

* Removed all old TLV code

* Cleaning up postverify

* Added new initializer to TempBuffer

Allows TempBuffer to be initialized by concatenation of multiple existing buffers.

Constructor contains pairs of (T *buf), nElements, where last argument MUST BE NULL to signify end of variable argument list.

Will work with any type T, and nElements is in units of elements of type T.

* Start re-working SRP6A's use in Pair-Setup to make it local instead of global

* Initial integration of local SRP6A into Pair Setup

* Moved definitions of N3072 and other constants into SRP6A structure

* In process of updated Pair-Setup M3...

Cleaning up code by replacing calls to mbedTLS within Pair-Setup with arguments passed to/from SRP6A.  Much better and better encapsulates SRP6A

* Completed Pair-Setup M3 update

* Completed refactoring of SRP6A and integration into all steps of Pair-Setup

* Remove include HAP.h from SRP

SRP now only requires Utils (for TempBuffer).

Also, moved HS_ALLOC definitions into Utils so it can be re-used by others files

* Initial test of StreamBuffer added to WebLog

* Moved Streamer from Utils.h into separate Streamer.cpp

But declared Streamer inside HomeSpan.h instead of separate Streamer.h since it  should only be used when HomeSpan.h is used.

Also, changed class structure so that it is "final" by removing virtual tags and making all protected variables private.

* Begin integration of hapStream into HAP.ccp

* Moved StreamBuf parameter calls into HapOut

* Moved StreamBuf into HapOut as private nested class

* Added getSize() to HapOut and changed default behavior to NEVER output anything

Note: getSize() must be called before flush(), which resets byte counter

* Converted sprintfAttributes to printfAttributes and added encryption to HapOut

Success!

* Added SHA-384 hash computation to HapOut

Hashing of entire database is now done piecemeal within HapOut, preventing the need to load the entire database into a large buffer just to obtain a unique hash.

Modified updateDatabase() to use HapOut.getHash()

* Deleted sprintfAttributes for Span, SpanAccessory, and SpanService

These now use the new printfAttributes with HapOut

* Converted sprintfNotify and eventNotify to use HapOut

Successfully tested with MultiTest script

* Added back weblogCallback() functionality that uses hapOut

* Converted all remaining sprintfAttributes to printfAttributes

This removes last of large-sized JSON buffers - everything has now been converted to using hapOut.

Next up: Must add prettyPrint to hapOut to support 'd' command

* Moved prettyPrint into HapOut

This completes re-work of all JSON buffer memory management to use HAPOut.

Next up: Stress test with Max Accessories to see how many Accessories we can now handle.

* Changed HapOut delay from 1ms to 50ms for WiFi transmits.  Seems to be much more stable.

* Update MaxAccessories.ino

* fix for PSRAM with new hapOut

Force hapOut to use internal memory only.

Tested on ESP32-S2 with/without PSRAM.  However, crashes on ESP32-S3 when using PSRAM (?!)

* Changed hapOut delay back to 1ms - works fine

Identified issue with ESP32-S3 crashing when using PSRAM.  Problem was not the code, but that the sketch was using pins that are needed to run the Octal PSRAM that comes with the Espressif S3 DevKit.

* Fixed CSS in weblog

Missing conversion from String to c_str() when using hapOut.

* Added homeSpan.getWebLog()

* Update src.ino

* Update src.ino

* started work on TLV streaming with << operator

Goal - eliminate sendEncrypted() completely by using hapOut in tlvRepond().
Next up: use function call instead of << operator so logic can be moved into TLV.h

* moved tlv streaming into tlv class

* refactored tlvRespond() to use hapOut instead of sendEncrypted()

To do:

1) update putPrepareURL() to use hapOut instead of sendEncrypted()
2) remove sendEncrypted() since it is no longer needed
3) try moving MAllocator template into separate file (memory.h?) so it can be called from any other module
4) remove #include "HomeSpan.h" from TLV8

* Moved all PSRAM definitions into separate PSRAM.h file

Now allows #include "HomeSpan.h" to be removed from TLV dependencies

* updated putPrepareURL and deleted receiveEncrypted()

Must test with Door example, which uses putPrepare

* Modified range checks so that "NAN" gets picked up as error for FLOAT Characteristics

* Truncate all STRING-based Characteristics to 64 characters when adding to JSON

HAP default max length of STRING Characteristics is 64 characters

* Added homeSpan.getAutoPollTask() to return task handler of autoPoll

Returns NULL if autoPoll has not been used.

Also added low stack size for both main Arduino loop task and HomeSpan autoPoll task to 'm' command

* Added optional triggerType to homeSpan.setControlPin()

Default is SpanButton::TRIGGER_ON_LOW.  Follows same options as SpanButton, including the ability to provide your own triggerType function of form:

boolean f(int pin)

* Cleaned up some public/private permissioning inside PushButton and SpanButton

Ensure users can access constants like TRIGGER_ON_HIGH, TRIGGER_ON_LOW, etc. using any of these equivalent fully-qualified names:

* PushButton::TRIGGER_ON_HIGH
* SpanButton::TRIGGER_ON_HIGH
* SpanToggle::TRIGGER_ON_HIGH

* Update Reference.md

* Update Reference.md

* Added CustomNVSPartition Example

To do:  Add to list of Other Examples in documentation.

* Update CustomNVSPartition.ino

* Update Tutorials.md

* Create ExternalReference.ino

* Update Tutorials.md

* Update Logging.md

* Update Reference.md

* New Services and Characteristics List (#751)

* auto-generation of service list

* Update makeServiceList

* Update makeServiceList

* Update test.md

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* Update Span.h

* Update test.md

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* update

* Create ServiceListHead.md

* Update ServiceListHead.md

* Update ServiceListHead.md

* Update test.md

* update

* update

* Update ServiceList.md

* update

* Update ServiceList.md

* update

* removed bold font for Characteristic Constants in ServiceList.md

* fix heavy_check_mark

* add <span> to ServiceList to prevent linebreaks before checkmark

* fixed typo in ServiceLabelNameSpace description

* Create ServistList_Expanded.md

* Update ServistList_Expanded.md

* Update ServiceList.md

* added ServiceList_Expanded

* added code to create pre-expanded Services and Characteristics List

* Update Tutorials.md

* Update Tutorials.md

* Added ConfiguredName to Switch and Lightbulb

* Moved error/warning output to end of 'i' output

* Add configuredName() to all applicable Services and deprecated Name()

* reformat ServiceList to remove expandable details

Expandable details are not as practical to navigate for a page this size.  Easier to see everything laid out all at once.

* Re-organized Services List into Service Groups

* Update ServiceList.md

* converted Service Group names to upper case

* Added linebreak after each Service

* updated some descriptions

* Delete ServiceList_Expanded.md

* Revised Example 11 (Service Names) to use ConfiguredName Characteristic

Complete re-work of Example 11 - fully tested for iOS 17.2.1

* Documentation update (#765)

* Update Stepper.md

* Update README.md

* Update FAQ.md

* Update TVServices.md

* Get Arduino-ESP32 Version from <esp_arduino_version.h> instead of <core_version.h>

This works fine for all versions after 2.0.3, but returns 2.0.0 for versions 2.0.2 and 2.0.1, as well as 2.0.0.  Not an issue since current version is 2.0.14.

* Update Solutions.md

* Added Stepper_UNIPOLAR and Stepper_UNL2003

ALSO:  Re-arranged include files so that StepperControl.h is now part of HomeSpan.h.   No need to include anything except for HomeSpan.h to use any of the Stepper Motor classes.  Must update documentation accordingly.

NOTE: Always including StepperControl.h DOES NOT increase size of compile if no stepper motors are instantiated.

To do:  Consider doing the same for Pixel, PWM, and RMT as well.

* Removed #include "extras/PwmPin.h" from all Tutorial Examples

Since PwmPin.h is already included in HomeSpan.h, there is no reason to separately include it in user sketches.

* Removed all #include "extras/*.h" from "Other Examples"

Including any extras/*.h files in a HomeSpan sketch is no longer necessary since these are already included in HomeSpan.h.

* Update PWM.md

* Update RMT.md

* Update Pixels.md

* Update RMT.md

* Update Stepper.md

* Update 17-LinkedServices.ino

* Update Stepper.md

* Update Stepper_TB6612.md

* Update Stepper_A3967.md

* Update Stepper.md

* Update Stepper.md

* Update Stepper.md

* Update StepperControl.h

* Update Stepper_A3967.md

* Create Stepper_ULN2003A.md

* Update Stepper_ULN2003A.md

* Update Stepper_ULN2003A.md

* Update Stepper_TB6612.md

* Update Stepper_A3967.md

* Create Stepper_UNIPOLAR

* Create Stepper_UNIPOLAR.md

* Update Stepper_UNIPOLAR.md

* Delete Stepper_UNIPOLAR

* Update Stepper_UNIPOLAR.md

* Update Stepper_UNIPOLAR.md

* Update Stepper_UNIPOLAR.md

* Update Stepper_UNIPOLAR.md

* Added option to specify NULL for 4th parameter of homeSpan.enableWebLog()

If 4th parameter (the statusURL) is NULL, web logging will NOT be enabled BUT time server will still acquire time if server address and time zone were specified as 2nd and 3rd parameters.

Note that not having web logging enabled only impacts ability to acquire weblog from HTTP request.  It has no effect on the actual logging of WEBLOG() messages and thus homeSpan.getWebLog() works as expected.

* Allow user-defined data when receiving weblogs from callback (#770)

* Adding userData to getweblogs callback.
Allows user-specific data to be available in the callback that returns weblog HTML data.

* Adding userData to getweblogs callback.
Allows user-specific data to be available in the callback that returns weblog HTML data.

Return HTTP response code and content type only when no weblog callback defined

* Small clean-up and formatting of comments

* Bump version to 1.9.0

* Updated copyright dates to 2024

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update README.md

* Update Reference.md

* Update Logging.md

* Update README.md

* Update Logging.md

* Update README.md

* Update HomeSpan.h

* Update README.md

* Update FeatherPins.h

Changed F21 from pin 35 to pin 38 for ESP32-S3 to avoid conflicting with Octal PSRAM.

* Update README.md

* Update README.md

* Update Logging.md

* Update library.properties

---------

Co-authored-by: Yitao Jiang <jytscientist@hotmail.com>
Co-authored-by: Francois <franklamoureux@hotmail.com>
Co-authored-by: Michael Geramb <mail@michael-geramb.at>
Co-authored-by: frankonski <frankonski@users.noreply.github.com>
2024-02-17 17:11:17 -06:00
59 changed files with 2520 additions and 1203 deletions

154
README.md
View File

@ -4,10 +4,12 @@ Welcome to HomeSpan - a robust and extremely easy-to-use Arduino library for cre
HomeSpan provides a microcontroller-focused implementation of Apple's HomeKit Accessory Protocol Specification Release R2 (HAP-R2) designed specifically for the Espressif ESP32 microcontroller running within the Arduino IDE. HomeSpan pairs directly to HomeKit via your home WiFi network without the need for any external bridges or components. With HomeSpan you can use the full power of the ESP32's I/O functionality to create custom control software and/or hardware to automatically operate external devices from the Home App on your iPhone, iPad, or Mac, or with Siri.
HomeSpan requires version 2.0.0 or later of the [Arduino-ESP32 Board Manager](https://github.com/espressif/arduino-esp32), and has been tested up through version 2.0.14 (recommended). HomeSpan can be run on the original ESP32 as well as Espressif's ESP32-S2, ESP32-C3, and ESP32-S3 chips.
HomeSpan requires version 2 of the [Arduino-ESP32 Board Manager](https://github.com/espressif/arduino-esp32). HomeSpan can be run on the original ESP32 as well as Espressif's ESP32-S2, ESP32-C3, and ESP32-S3 chips.
HomeSpan is currently NOT compatible with version 3.X of the Arduino-ESP32 Board Manager, since version 3 contains many breaking changes and is not backwards-compatible with version 2.X of the Arduino-ESP32 Board Manager. At present, HomeSpan can only be compiled under version 2.X of the Board Manager.
> [!NOTE]
> Apple's new HomeKit architecture [requires the use of a Home Hub](https://support.apple.com/en-us/HT207057) (either a HomePod or Apple TV) for full and proper operation of any HomeKit device, include those based on HomeSpan. Without a Home Hub, HomeSpan cannot send notifications to the Home App - things like pushbuttons and temperature sensors will not be able to transmit updates to the Home App.
> Apple's new HomeKit architecture [requires the use of a Home Hub](https://support.apple.com/en-us/HT207057) (either a HomePod or Apple TV) for full and proper operation of any HomeKit device, including those based on HomeSpan. Without a Home Hub, HomeSpan cannot send notifications to the Home App - things like pushbuttons and temperature sensors will not be able to transmit updates to the Home App. Use of HomeSpan without a Home Hub is NOT recommended.
### HomeSpan Highlights
@ -15,7 +17,7 @@ HomeSpan requires version 2.0.0 or later of the [Arduino-ESP32 Board Manager](ht
* Utilizes a unique *Service-Centric* approach to creating HomeKit devices
* Takes full advantage of the widely-popular Arduino IDE
* 100% HAP-R2 compliance
* 38 integrated HomeKit Services
* Dozens of integrated HomeKit Services
* Operates in either Accessory or Bridge mode
* Supports pairing with Setup Codes or QR Codes
@ -52,81 +54,96 @@ HomeSpan requires version 2.0.0 or later of the [Arduino-ESP32 Board Manager](ht
* Launch the WiFi Access Point
* A standalone, detailed End-User Guide
## ❗Latest Update - HomeSpan 1.9.0 (2/17/2024)
## ❗Latest Update - HomeSpan 1.9.1 (07/03/2024)
* **HomeSpan has been optimized to use significantly less RAM!**
* **HomeSpan now supports *Tag-Length-Value ("TLV8")* Characteristics!**
* supports approximately **TWICE** the number of Accessories using the same amount of memory
* minimized memory use also means much more room for users to add non-HomeSpan features to their sketch without running out of memory, especially if the non-HomeSpan code consumes a lot of stack space
* HomeSpan now automatically detects the presence of **PSRAM** (SPIRAM) and will utilize that extra memory to the largest extent possible to keep internal RAM free for certain HomeSpan functions and ESP32 functions (e.g. WiFi) that require internal RAM. Also keeps internal RAM free for use by any non-HomeSpan code that does not (or cannot) use PSRAM
* increased HomeSpan's 41-Accessory limit to a 150-Accessory Limit (as specified by HAP) since it is now possible to create a device with many more than 41 Accessories without running out of memory, especially if PSRAM is used
* adds new, fully-integrated `TLV8()` class library for the creation and management of TLV8 objects
* includes methods to handle standard byte-stream VALUES as well as strings, numerical values, zero-length tags, and sub-TLVs
* utilizes standard C++ iterators for easy access to reading and writing TLV8 records
* adds new `Characteristic` methods `getTLV()`, `getNewTLV()`, and `setTLV()`
* adds new `CUSTOM_CHAR_TLV8()` that allows for easy creation of custom TLV8 Characteristics
* includes new [Tutorial Example 22 - TLV8 Characteristics](examples/22-TLV8_Characteristics) demonstrating use of the `TLV8()` class and TLV8 Characteristics
* see the new [TLV8 Characteristics](docs/TLV8.md) page for complete details and documentation
* **New *DisplayOrder* TLV8 Characteristic**
* utlizes HomeSpan's new `TLV8()` library
* allows you to specify the exact order in which the Input Sources for a Television Service are displayed in the Home App
* see [Tutorial Example 22 - TLV8 Characteristics](examples/22-TLV8_Characteristics) for details
* **New *AccessoryIdentifier* Tutorial**
* **HomeSpan has been optimized to use significantly less Non-Volatile Storage (NVS)**
* demonstrates how to trigger an Accessory's Identifier Characteristic, optionally used to help identify a device during initial pairing
* see [Tutorial Example 21 - AccessoryIdentifier](examples/21-AccessoryIdentifier)
* allows you to use NVS to save the values of a many more Characteristics
* see the newly-added [CustomNVSPartition](docs/Tutorials.md#customnvspartition) example that demonstrates how to create your own Partition Scheme to further expand the size of the NVS partition beyond the ESP32 default to support sketches with a large number of Accessories each configured to use NVS to save the values of many Characteristics
* **Added support for customizing Pixel chips**
* **New features and documentation for Services and Characteristics**
* created "enumerated constants" (e.g. *SWING_ENABLED*, *HUMIDIFYING*, etc.) for every applicable Characteristic that can be used instead of integers when reading and writing values
* very helpful since Apple is no longer publishing its non-commercial HAP document that provided a list and description of the states for each Characteristic
* example: `if(target.getNewVal()==target.ARM_STAY) {...}`
* added ability to properly name individual Services within a single Accessory using new **Characteristic::ConfiguredName()**
* see revised [Example 11 - ServiceNames](docs/Tutorials.md#example-11---servicenames) for details
* new [Services and Characteristics](docs/ServiceList.md) page now provides functional descriptions and detailed specifications for every Service and Characteristic supported by HomeSpan, including a list of the enumerated constants available for every Characteristic
* new constructor `Pixel(uint8_t pin, [pixelType_t pixelType])` allows your to set the order in which colors are transmitted to the pixel chip, where *pixelType* is one of the following:
* PixelType::RGB, PixelType::RBG, PixelType::BRG, PixelType::BGR, PixelType::GBR, PixelType::GRB
* PixelType::RGBW, PixelType::RBGW, PixelType::BRGW, PixelType::BGRW, PixelType::GBRW, PixelType::GRBW*
* deprecated previous constructor `Pixel(uint8_t pin, boolean isRGBW)`
* this constructor will continue to work, but you will receive a warning during compilation that it has been deprecated
* users should switch to the new constructor to avoid potential compatibility issues with future versions of HomeSpan
* added new method `boolean isRGBW()`
* returns *true* if Pixel was constructed as RGBW, else *false* if constructed as RGB only (i.e. no white LED)
* added new [PixelTester](examples/Other%20Examples/PixelTester) sketch (found under *Other Examples*) to aid in determining the *pixelType* for any LED Strip
* see the [Adressable RGB LEDs](docs/Pixels.md) page for details
* **New ability to read and set the IIDs of Services and Characteristics**
* adds new `SpanService` method `getIID()` that returns the IID of a Service
* adds new `SpanCharacteristic` method `getIID()` that returns the IID of a Characteristic
* adds new `homeSpan` method `resetIID(int newIID)` that resets the IID count for the current Accessory
* see the [API Reference](docs/Reference.md) for details
* **New ability to read Controller pairing data (for advanced use-cases only)**
* adds new `homeSpan` methods `controllerListBegin()` and `controllerListEnd()` that returns iterators to HomeSpan's internal linked-list of Controller data records
* adds new methods to read each Controller's pairing data:
* `getID()` - returns a pointer to the 36-byte Device ID of the controller
* `getLTPK()` - a pointer to the 32-byte Long-Term Public Key of the controller
* `isAdmin()` - returns true if the controller has admin permission, else returns false
* adds new `homeSpan` method `setControllerCallback()` to set optional callback function that HomeSpan calls whenever a controller is added, removed, or updated
* see the [API Reference](docs/Reference.md) for details
* **HomeSpan now supports the *write-response ("WR")* protocol**
* added automated handling of the HomeKits's *write-response ("WR")* protocol*
* not needed for any Characteristics that are currently supported by HomeSpan, but useful for experimentation and work with Custom Characteristics
* added extra checks when using `setVal()`
* a warning message is output on the Serial Monitor if `setVal()` is called to change the value of a Characteristic from within the `update()` method at the same time the Home App is sending an update request for that value
* does not apply if `setVal()` is called from within `update()` to change the value of a Characteristic in response to a *write-response* request from the Home App
* **New ability to use *Inverted Buttons* and *Touch Sensors* as a Control Button**
* adds *triggerType* as a second, optional argument to `Span& setControlPin(uint8_t pin, triggerType_t triggerType)`
* supports TRIGGER_ON_LOW, TRIGGER_ON_HIGH, TRIGGER_ON_TOUCH, or any user-defined function
* see [API Reference](docs/Reference.md) for details
* **New ability to "remotely" trigger user-defined actions by repeatedly power-cycling the device**
* adds new homeSpan method `Span& setRebootCallback(void (*func)(uint8_t count), uint32_t upTime=5000)`
* the parameter *count*, which is passed by HomeSpan to *func*, indicates the number of "short" reboots that have occurred prior to the current reboot, where a "short" reboot is any that occurs before *upTime* milliseconds have elapsed
* can be use to remotely restore a device that is not easily accessible to a pre-defined state
* see [API Reference](docs/Reference.md) for details
* **Added two new Stepper Motor Drivers**
* **Stepper_UNIPOLAR**: a generic driver for any 4-wire center-tapped unipolar motor
* **Stepper_ULN2003A**: support for the ULN2003A driver board
* see [Stepper Motor Control Stepper](docs/Stepper.md) for details
* **Additional Web Log functionality**
* adds new homeSpan method `Span& setWebLogCallback(void (*func)(String &))`
* allows users to include additional data and custom HTML in the Web Log
* adds new homeSpan method `getWebLog(void (*f)(const char *, void *), void *args)`
* allows users to retrieve the underlying Web Log HTML from within sketch
* modified `enableWebLog()` so that it can be used to set the time from an NTP server without actually serving Web Log pages
* see [Message Logging](docs/Logging.md) for details
* **Added ability to "chain" *homeSpan* methods**
* converted various *homeSpan* methods that previously returned *void* to now return *Span &*
* example: `homeSpan.setControlPin(21).setStatusPin(13);`
* see [API Reference](docs/Reference.md) for details
* **Added ability to disable SpanPoint encryption**
* without encryption increases the maximum number of allowed SpanPoint devices from 7 to 20
* see [SpanPoint](docs/NOW.md) for details
* **Converted the `getLinks()` SpanService method to a template function**
* allows user to automatically cast the elements of the returned vector into any specific Service type
* also adds an optional parameter to restrict the elements of the returned vector to match a specified HomeSpan Service
* see the [API Reference](docs/Reference.md) for details
* **Other new *homeSpan* methods included in this release:**
* **New ability to halt the pulse generation for a ServoPin**
* calling `set(NAN)` for a ServoPin halts the pulse generation, which (for most analog servos) allows the motor to be freely rotated
* calling `set(position)`, where *position* equal the desired number of degrees, restarts the pulse generation and sets the servo position accordingly
* **Refactored client/slot management to save memory and prepare for future integration of Ethernet support**
* fixed-array of Client/Socket connections replaced by dynamic linked-list
* serial interface now only shows active client connections (rather than a fixed list of client slots)
* **deprecated** `homeSpan.reserveSocketConnections()` since it is no longer needed
* **Fixed bug introduced in 1.9.0 that prevented `homeSpan.setPairingCode()` from saving (and subsequently using) the request Setup Pairing Code**
* this method now operates silently, unless an invalid pairing code is provided, in which case an error is reported to the Serial Monitor and *the sketch is halted*
* the process for setting the Pairing Code using the CLI 'S' command or via the Access Point are unchanged - confirmation messages are still output to the Serial Monitor and errors do *not* cause the sketch to halt
* `Span& setVerboseWifiReconnect()` - optionally suppresses "Trying to connect to..." messages
* `Span& setWifiCallbackAll()` - provides an optional callback every time WiFi is connected *or re-connected*
* `TaskHandle_t getAutoPollTask()` - returns the Task Handle for the HomeSpan Auto Poll Task
* **Fixed memory leak introduced in 1.9.0 that would fail to free a small temporary memory block created when verifying a new connection**
* had no practical impact when using a Home Hub since Home Kit only creates a few permanent connections
* had significant impact when not using a Home Hub in cases where the Home App repeatedly drops and re-establishes connections, resulting in slow erosion of heap memory and then out-of-memory failure of the device after a few days (note use of HomeSpan without a Home Hub is not formally supported)
* **Fixed latent bug in SpanPoint**
* HomeSpan would crash when printing **SpanPoint** configuration information to the Serial Monitor (the 'i' CLI command) if any of the instances of SpanPoint had *receiveSize=0*
* this bug never surfaced before since all the **SpanPoint examples** were based on receiving data and therefore had a non-zero *receiveSize*
* **Removed dependencies on various "extra" `#include` files**
* the following \#include files are now embedded in *HomeSpan.h* and **should not be specified in any sketch:**
* *extras/Pixel.h*
* *extras/RFControl.h*
* *extras/PwmPin.h*
* *extras/StepperControl.h*
* **Deleted `homeSpan.setMaxConnections()`, which had been *deprecated* many versions ago**
> [!IMPORTANT]
> At present it is okay to include the above `#include` files in your sketch (they have no effect on the compiled code), but they will be deleted at some point in the future so please remove them from your sketches now to ensure forward compatibility with subsequent releases.
* **Deleted stand-alone `SpanRange` structure, which had been *deprecated* many versions ago**
* this has no impact on standard use of the Characteristic method `setRange()`
See [Releases](https://github.com/HomeSpan/HomeSpan/releases) for details on all changes and bug fixes included in this update.
@ -151,6 +168,7 @@ HomeSpan includes the following documentation:
* [HomeSpan SpanPoint](docs/NOW.md) - facilitates point-to-point, bi-directional communication between ESP32 Devices using ESP-NOW
* [HomeSpan Television Services](docs/TVServices.md) - how to use HomeKit's undocumented Television Services and Characteristics
* [HomeSpan Message Logging](docs/Logging.md) - how to generate log messages for display on the Arduino Serial Monitor as well as optionally posted to an integrated Web Log page
* [HomeSpan TLV8 Characteristics](docs/TLV8.md) - classes and methods for creating TLV8 objects to use with TLV8-based Characteristics
* [HomeSpan Device Cloning](docs/Cloning.md) - seamlessly swap a broken device for a new one without needing to re-pair and lose HomeKit automations
* [HomeSpan Projects](https://github.com/topics/homespan) - real-world applications of the HomeSpan Library
* [HomeSpan FAQ](docs/FAQ.md) - answers to frequently-asked questions

View File

@ -20,7 +20,7 @@
#### Can you use more than one HomeSpan device on the same HomeKit network?
* Yes, multiple ESP32's, each running a separate copy of HomeSpan, can be used on the same HomeKit network, provided that each device has a unique *Device ID*, a unique *Host Name*, and a unique *Display Name*. Normally, the *Device ID* is randomly-generated by HomeSpan at start-up and will therefore automatically be unique across multiple devices. Also, unless you override the suffix of the default *Host Name*, it will also be unique across multiple devices since HomeSpan uses the *Device ID* as the suffix of the *Host Name*. The only thing you need to ensure is that you assign a different *Display Name* to each of your devices. See the [HomeSpan API Reference](https://github.com/HomeSpan/HomeSpan/blob/master/docs/Reference.md) for details on how to do this.
* Yes, multiple ESP32's, each running a separate copy of HomeSpan, can be used on the same HomeKit network, provided that each device has a unique *Device ID*, a unique *Host Name*, and a unique *Display Name*. Normally, the *Device ID* is randomly-generated by HomeSpan at start-up and will therefore automatically be unique across multiple devices. Also, unless you override the suffix of the default *Host Name*, it will also be unique across multiple devices since HomeSpan uses the *Device ID* as the suffix of the *Host Name*. The only thing you need to ensure is that you assign a different *Display Name* to each of your devices. See the [HomeSpan API Reference](Reference.md) for details on how to do this.
#### Does HomeSpan require the use of a HomeKit Hub, such as a HomePod or Apple TV?
@ -36,7 +36,7 @@
#### Will HomeSpan work on an ESP8266 device?
* No, HomeSpan is coded specifically for the ESP32 and will not operate on an ESP8266 device, though an ESP8266 can be used as a remote [SpanPoint ESP-NOW](../docs/NOW.md) Device.
* No, HomeSpan is coded specifically for the ESP32 and will not operate on an ESP8266 device, though an ESP8266 can be used as a remote [SpanPoint ESP-NOW](NOW.md) Device.
#### How can I read HomeSpan's MDNS broadcast mentioned in the [OTA](OTA.md) documentation?
@ -48,7 +48,7 @@
#### Does HomeSpan support Television Services?
* Yes. Though undocumented by Apple and not officially part of HAP-R2, HomeSpan supports HomeKit Television controls. See [Television Services](../docs/TVServices.md) for details.
* Yes. Though undocumented by Apple and not officially part of HAP-R2, HomeSpan supports HomeKit Television controls. See [Television Services](TVServices.md) for details.
#### Can you use HomeSpan via Bluetooth?
@ -68,7 +68,7 @@
#### Can you add *custom* Services and Characteristics to HomeSpan?
* Yes, HomeSpan includes two easy-to-use macros to define your own custom Services and custom Characteristics beyond those specified in HAP-R2. See the [HomeSpan API Reference](https://github.com/HomeSpan/HomeSpan/blob/master/docs/Reference.md) for details and examples demonstrating how to do this. Note that any new Characteristics you create will be *completely ignored* by the Home App. Similarly, any new Services you create will be shown in the Home App on a tile labeled "Not Supported". Apple ***does not*** provide any mechanism to extend the functionality of the Home App itself. However, the place where custom Services and Characteristics can be used is in third-party applications designed for these extra features. For example, the *Eve for HomeKit* App properly handles all the Services and Characteristics defined in HAP-R2, *plus* a variety of additional Services and Characteristics designed explictly for use with Eve products. If you know the UUID codes for these extra Services and Characteristics you can add them to HomeKit and use them within the Eve App just as if they were HAP-R2 Services and Characteristics.
* Yes, HomeSpan includes two easy-to-use macros to define your own custom Services and custom Characteristics beyond those specified in HAP-R2. See the [HomeSpan API Reference](Reference.md#custom-characteristics-and-custom-services-macros) for details and examples demonstrating how to do this. Note that any new Characteristics you create will be *completely ignored* by the Home App. Similarly, any new Services you create will be shown in the Home App on a tile labeled "Not Supported". Apple ***does not*** provide any mechanism to extend the functionality of the Home App itself. However, the place where custom Services and Characteristics can be used is in third-party applications designed for these extra features. For example, the *Eve for HomeKit* App properly handles all the Services and Characteristics defined in HAP-R2, *plus* a variety of additional Services and Characteristics designed explictly for use with Eve products. If you know the UUID codes for these extra Services and Characteristics you can add them to HomeKit and use them within the Eve App just as if they were HAP-R2 Services and Characteristics.
#### Can HomeSpan be used for commercial devices?
@ -76,7 +76,22 @@
#### Why does the Home App indicate the Doorbell Service is unsupported?
* Though not documented in HAP-R2, it appears that the Doorbell Service is designed to be used in conjunction with another service, such as the Lock Mechanism. If you add in a second service, the Home App will show the appropriate Tile (such as a Lock) with the Doorbell being the second service. However, you can still use the Doorbell Service on a standalone basis --- even though the Home App says it is unsupported, a button press on the device will properly trigger a chime on your Home Pods as expected.
* Though not documented in HAP-R2, it appears that the Doorbell Service is designed to be used in conjunction with another service, such as the Lock Mechanism. If you add in a second service, the Home App will show the appropriate Tile (such as a Lock) with the Doorbell being the second service. However, you can still use the Doorbell Service on a standalone basis --- even though the Home App says it is unsupported, a button press on the device will properly trigger a chime on your Home Pods as expected.
#### How can I read the current date and time from within my sketch?
* HomeSpan can automatically acquire the current date and time for your local timezone when you enable the HomeSpan Web Log using `homeSpan.enableWebLog()`. Note this command can be used to set the date and time even without enabling the Web Log itself (see the [HomeSpan API Reference](Reference.md) for details on how to do this). Once the date and time has been acquired, you can use the built-in Arduino-ESP32 `getLocalTime(struct tm *info)` command whenever needed to populate *info* with the current date and time. Note *info* is in [standard Unix](https://man7.org/linux/man-pages/man0/time.h.0p.html) `struct tm` format which is easily parsed as follows:
```C++
struct tm myTime; // create a tm structure
getLocalTime(&myTime); // populate the tm structure with current date and time
// print the individual elements of the tm structure (see standard Unix tm structure for details)
Serial.printf("Current Date = %02d/%02d/%04d\n", myTime.tm_mon+1, myTime.tm_mday, myTime.tm_year+1900);
Serial.printf("Current Time = %02d:%02d:%02d\n", myTime.tm_hour, myTime.tm_min, myTime.tm_sec);
```
---
[↩️](../README.md) Back to the Welcome page

View File

@ -91,6 +91,9 @@ Examples showing such a configuration can be found in the Arduino IDE under [*Fi
* *RemoteDevice.ino* - a lightweight sketch that simulates taking periodic temperature measurements, which are then transmitted to the Main Device via SpanPoint
* *RemoteTempSensor.ino* - a lightweight sketch that is similar to *RemoteDevice.ino*, except that instead of simulating a temperature sensor, it implements an actual Adafruit ADT7410 I2C-based temperature sensor. This sketch also uses some power-management techniques to extend battery life, such as lowering the CPU frequency and entering into deep-sleep after each measurement is taken
* *RemoteDevice8266.ino* - similar in function to *RemoteDevice.ino*, but implemented to run on an ESP8266 device using native ESP-NOW commands (since neither HomeSpan nor SpanPoint support the ESP8266). Note that the "complementary" SpanPoint object on the ESP32 that receives data from the ESP8266 must be configured to use the ESP32's *AP MAC Address* (instead of the *STA MAC Address*) by setting *useAPaddress* to *true* in the SpanPoint constructor
Please also see the [SpanPointLightSwitch Repository](https://github.com/HomeSpan/SpanPointLightSwitch/tree/main) for a detailed example that shows how to use SpanPoint for *bi-directional communication* between an ESP32 "Central Hub" device implementing two HomeKit Lighbulb Accessories, an remote ESP32 device controlling an LED, and a separate ESP8266 device controlling another LED.
---
[↩️](../README.md) Back to the Welcome page

View File

@ -71,7 +71,8 @@ The *minMicros* parameter must be less than the *maxMicros* parameter, but setti
* `void set(double position)`
* sets the position of the Servo Motor to *position* (in degrees). In order to protect the Servo Motor, values of *position* less than *minDegrees* are automatically reset to *minDegrees*, and values greater than *maxDegrees* are automatically reset to *maxDegrees*.
* sets the position of the Servo Motor to *position* (in degrees). In order to protect the Servo Motor, values of *position* less than *minDegrees* are automatically reset to *minDegrees*, and values greater than *maxDegrees* are automatically reset to *maxDegrees*
* if *position* is specified as *NAN* (i.e. the C++ "not-a-number" constant), the duty-cycle is set to zero, which effectively stops the pulse generation --- for most analog servos this means the motor can be freely rotated. Calling `set()` once again with *position* equal to an actual number of degrees restarts the pulse train and sets the servo position accordingly
* `int getPin()`

View File

@ -6,12 +6,22 @@ Both classes allow you to individually set each of the "pixels" in a multi-pixel
The methods for both classes are nearly identical, which allows you to readily interchange code written for single-wire devices to use with two-wire devices (and vice-versa) with only minor modifications.
## *Pixel(uint8_t pin, [boolean isRGBW])*
## *Pixel(uint8_t pin, [pixelType_t pixelType])*
Creating an instance of this **class** configures the specified *pin* to output a waveform signal suitable for controlling a single-wire, addressable RGB or RGBW LED device with an arbitrary number of pixels. Such devices typically contain SK6812 or WS2812 LEDs. Arguments, along with their defaults if left unspecified, are as follows:
* *pin* - the pin on which the RGB control signal will be output; normally connected to the "data" input of the addressable LED device
* *isRGBW* - set to *true* for RGBW devices that contain 4-color (red/green/blue/white) LEDs; set to *false* for the more typical 3-color RGB devices. Defaults to *false* if unspecified. Note you must set the *isRGBW* flag to *true* if you are using an RGBW device, even if you do not intend on utilizing the white LED
* *pixelType* - controls the order in which color data is transmitted, as well as whether the device contains 3-color (red/green/blue) or&nbsp;4&#8209;color (red/green/blue/white) LEDs. Pre-defined values for *pixelType* are provided in the **PixelType** namespace. Choose from one of the following twelve formats:
* *PixelType::RGB, PixelType::RBG, PixelType::BRG, PixelType::BGR, PixelType::GBR, PixelType::GRB*
* *PixelType::RGBW, PixelType::RBGW, PixelType::BRGW, PixelType::BGRW, PixelType::GBRW, PixelType::GRBW*
* Example: `Pixel myDevice(26, PixelType::BRGW);` creates a 4-color RGBW device attached to pin 26 where the colors are transmitted in the order blue, red, green, and then white
Note that *pixelType* is optional. If left unspecified, the default value is *PixelType::GRB*.
> [!TIP]
> Since it is often not obvious which type of LED your specific device may have, HomeSpan includes a sketch designed to help you determine the correct value of *pixelType*. See [*File → Examples → HomeSpan → Other Examples → PixelTester*](../examples/Other%20Examples/PixelTester) under the Arduino IDE for detailed instructions. Please use this tester sketch if you find the colors of your Pixel device are not matching what appears in the Home App.
The two main methods to set pixel colors are:
@ -47,19 +57,26 @@ The **Pixel** class also supports the following class-level methods as a conveni
* equivalent to `return(Color().HSV(h,s,v,w));`
* example: `Pixel::Color c[]={Pixel::HSV(120,100,100),Pixel::HSV(60,100,100),Pixel::HSV(0,100,100)};` to create a red-yellow-green traffic light pattern
Finally, the **Pixel** class supports these two additional, but rarely-needed, methods:
Finally, the **Pixel** class supports these additional methods:
* `int getPin()`
* returns the pin number, or -1 if the instantiation failed due to lack of resources
* `boolean isRGBW()`
* returns *true* if *pixelType* specified an RGBW LED, else *false* if just an RGB LED
* `void setTiming(float high0, float low0, float high1, float low1, uint32_t lowReset)`
* the default timing parameters used by the **Pixel** class to generate the "data" signal needed to set the colors of an RGB LED device should work with most commercial products based on SK6812 or WS2812 driver chips. Use this method **ONLY** if you need to override the class defaults and replace them with your own timing parameters, where
* *high0* and *low0* specify the duration (in microseconds) of the high phase and low phase for a pulse encoding a zero-bit;
* *high1* and *low1* specify the duration (in microseconds) of the high phase and low phase for a pulse encoding a one-bit; and
* *lowReset* specifies the delay (in microseconds) representing the end of a pulse stream
* for reference, the **Pixel** class uses the following defaults: *high0=0.32𝛍s, low0=0.88𝛍s, high1=0.64𝛍s, low1=0.56𝛍s, lowReset=80.0𝛍s*
* for reference, the **Pixel** class uses the following defaults: *high0=0.32𝛍s, low0=0.88𝛍s, high1=0.64𝛍s, low1=0.56𝛍s, lowReset=80.0𝛍s*
> [!TIP]
> If your LED colors are flickering, this is likely due to a mismatch in timing parameters. To solve, please search the web for a specifications document for the exact **chip** used by your specific device. These documents generally provide a table listing the durations of the HIGH and LOW periods required to transmit a binary 1 or binary 0. You can then use the `setTiming` method above to set the timing parameters accordingly.
### Resource Usage and Resource Conflicts

View File

@ -103,15 +103,6 @@ Methods with a return type of `Span&` return a reference to `homeSpan` itself an
* `int getLogLevel()`
* returns the current Log Level as set by `setLogLevel(level)`
* `Span& reserveSocketConnections(uint8_t nSockets)`
* reserves *nSockets* network sockets for uses **other than** by the HomeSpan HAP Server for HomeKit Controller Connections
* for sketches compiled under Arduino-ESP32 v2.0.1 or later, HomeSpan reserves 14 sockets for HAP Controller Connections
* each call to `reserveSocketConnections(nSockets)` reduces this number by *nSockets*
* use this method if you add code to a sketch that requires its own socket connections (e.g. a separate web service, an MQTT server, etc.)
* multiple calls to this method are allowed - the number of sockets reserved will be the sum of *nSockets* across all calls
* note you do not need to separately reserve sockets for built-in HomeSpan functionality
* for example, `enableOTA()` already contains an embedded call to `reserveSocketConnections(1)` since HomeSpan knows one socket must be reserved to support OTA
* `Span& setPortNum(uint16_t port)`
* sets the TCP port number used for communication between HomeKit and HomeSpan (default=80)
@ -181,7 +172,13 @@ The following **optional** `homeSpan` methods enable additional features and pro
* this one-time call to *func* is provided for users that would like to trigger additional actions when the device is first paired, or the device is later unpaired
* note this *func* is **not** called upon start-up and should not be used to simply check whether a device is paired or unpaired. It is only called when pairing status changes
* the function *func* must be of type *void* and accept one *boolean* argument
* `Span& setControllerCallback(void (*func)())`
* sets an optional user-defined callback function, *func*, to be called by HomeSpan every time a new controller is added, removed, or updated, even if the pairing status does not change
* note this method differs from `setPairCallback()`, which is only called if the device's pairing status changes, such as when the first controller is added during initial pairing, or the last controller is removed when unpairing
* the function *func* must be of type *void* and have no arguments
* see the `controllerListBegin()` and `controllerListEnd()` methods for details on how to read the pairing data for each paired controller (*only needed to support certain advanced use cases*)
* `Span& setStatusCallback(void (*func)(HS_STATUS status))`
* sets an optional user-defined callback function, *func*, to be called by HomeSpan whenever its running state (e.g. WiFi Connecting, Pairing Needed...) changes in way that would alter the blinking pattern of the (optional) Status LED
* if *func* is set, it will be called regardless of whether or not a Status LED has actually been defined
@ -196,7 +193,7 @@ The following **optional** `homeSpan` methods enable additional features and pro
* sets the Setup Pairing Code to *s*, which **must** be exactly eight numerical digits (no dashes)
* example: `homeSpan.setPairingCode("46637726");`
* a hashed version of the Pairing Code will be saved to the device's non-volatile storage, overwriting any currently-stored Pairing Code
* if *s* contains an invalid code, an error will be reported and the code will *not* be saved. Instead, the currently-stored Pairing Code (or the HomeSpan default Pairing Code if no code has been stored) will be used
* this method operated silently unless *s* contains an invalid code, in which case a fatal error will be reported to the Serial Monitor, the code will *not* be saved, and the sketch will be HALTED
* :warning: SECURTY WARNING: Hardcoding a device's Pairing Code into your sketch is considered a security risk and is **not** recommended. Instead, use one of the more secure methods provided by HomeSpan, such as typing 'S \<code\>' from the CLI, or launching HomeSpan's Access Point, to set your Pairing Code without hardcoding it into your sketch
* `Span& setSketchVersion(const char *sVer)`
@ -281,7 +278,7 @@ The following **optional** `homeSpan` methods provide additional run-time functi
* allows for dynamically changing the Accessory database during run-time (i.e. changing the configuration *after* the Arduino `setup()` has finished)
* deleting an Accessory automatically deletes all Services, Characteristics, and any other resources it contains
* outputs Level-1 Log Messages listing all deleted components
* note: though deletions take effect immediately, HomeKit Controllers, such as the Home App, will not be aware of these changes until the database configuration number is updated and rebroadcast - see updateDatabase() below
* note: though deletions take effect immediately, HomeKit Controllers, such as the Home App, will not be aware of these changes until the database configuration number is updated and rebroadcast - see `updateDatabase()` below
* `boolean updateDatabase()`
* recomputes the database configuration number and, if changed, rebroadcasts the new number via MDNS so all connected HomeKit Controllers, such as the Home App, can request a full refresh to accurately reflect the new configuration
@ -290,6 +287,43 @@ The following **optional** `homeSpan` methods provide additional run-time functi
* use anytime after dynamically adding one or more Accessories (with `new SpanAccessory(aid)`) or deleting one or more Accessories (with `homeSpan.deleteAccessory(aid)`)
* **important**: once you delete an Accessory, you cannot re-use the same *aid* when adding a new Accessory (on the same device) unless the new Accessory is configured with the exact same Services and Characteristics as the deleted Accessory
* note: this method is **not** needed if you have a static Accessory database that is fully defined in the Arduino `setup()` function of a sketch
* `Span& resetIID(uint32_t newIID)`
* resets the IID count for the current Accessory to *newIID*, which must be greater than 0
* throws an error and halts program if called before at least one Accessory is created
* example: `homeSpan.resetIID(100)` causes HomeSpan to set the IID to 100 for the very next Service or Characteristic defined within the current Accessory, and then increment the IID count going forward so that any Services or Characteristics subsequently defined (within the same Accessory) have IID=101, 102, etc.
* note: calling this function only affects the IID generation for the current Accessory (the count will be reset to IID=1 upon instantiation of a new Accessory)
* `const_iterator controllerListBegin()` and `const_iterator controllerListEnd()`
* returns a *constant iterator* pointing to either the *beginning*, or the *end*, of an opaque linked list that stores all controller data
* iterators should be defined using the `auto` keyword as follows: `auto myIt=homeSpan.controllerListBegin();`
* controller data can be read from a de-referenced iterator using the following methods:
* `const uint8_t *getID()` returns pointer to the 36-byte ID of the controller
* `const uint8_t *getLTPK()` returns pointer to the 32-byte Long Term Public Key of the controller
* `boolean isAdmin()` returns true if controller has admin permissions, else returns false
* <details><summary>click here for example code</summary><br>
```C++
// Extract and print the same data about each controller that HomeSpan prints to the Serial Monitor when using the 's' CLI command
Serial.printf("\nController Data\n");
for(auto it=homeSpan.controllerListBegin(); it!=homeSpan.controllerListEnd(); ++it){ // loop over each controller
Serial.printf("Admin=%d",it->isAdmin()); // indicate if controller has admin permissions
Serial.printf(" ID="); // print the 36-byte Device ID of the controller
for(int i=0;i<36;i++)
Serial.printf("%02X",it->getID()[i]);
Serial.printf(" LTPK="); // print the 32-byte Long-Term Public Key of the controller)
for(int i=0;i<32;i++)
Serial.printf("%02X",it->getLTPK()[i]);
Serial.printf("\n");
}
```
</details>
---
@ -352,11 +386,15 @@ The following methods are supported:
* note that Linked Services are only applicable for select HAP Services. See Apple's HAP-R2 documentation for full details
* example: `(new Service::Faucet)->addLink(new Service::Valve)->addLink(new Service::Valve);` (links two Valves to a Faucet)
* `vector<SpanService *> getLinks()`
* returns a vector of pointers to Services that were added using `addLink()`
* useful for creating loops that iterate over all linked Services
* note that the returned vector points to generic SpanServices, which should be re-cast as needed
* example: `for(auto myValve : faucet->getLinks()) { if((MyValve *)myValve)->active->getVal()) ... }` checks all Valves linked to a Faucet
* `vector<T> getLinks<T=SpanService *>(const char *serviceName=NULL)`
* template function that returns a vector of pointers to Services that were added using `addLink()`
* if template parameter, *T*, is left blank, the elements of the returned vector will be of type *SpanService \**
* if template parameter, *T*, is specified, the elements of the returned vector will be cast into type *T*
* if *serviceName* is specified, only those services matching *serviceName* will be included in the return vector
* *serviceName* must be one of HomeSpan's built-in Services (e.g. "Valve")
* if *serviceName* is left blank or set to NULL, all services will be included in the return vector
* this function is useful for creating loops that iterate over all linked Services
* example: from within a Faucet Service containing linked Valves defined in *MyValveService*, use `for(auto valve : getLinks<MyValveService *>()) { if(valve->active->getVal()) ... }` to check which Valves are active
* `virtual boolean update()`
* HomeSpan calls this method upon receiving a request from a HomeKit Controller to update one or more Characteristics associated with the Service. Users should override this method with code that implements that requested updates using one or more of the SpanCharacteristic methods below. Method **must** return *true* if update succeeds, or *false* if not.
@ -371,6 +409,9 @@ The following methods are supported:
* 0=single press (SpanButton::SINGLE)
* 1=double press (SpanButton::DOUBLE)
* 2=long press (SpanButton::LONG)
* `uint32_t getIID()`
* returns the IID of the Service
## *SpanCharacteristic(value [,boolean nvsStore])*
@ -378,13 +419,18 @@ This is a **base class** from which all HomeSpan Characteristics are derived, an
* instantiated Characteristics are added to the HomeSpan HAP Database and associated with the last Service instantiated
* instantiating a Characteristic without first instantiating a Service throws an error during initialization
* the first argument optionally allows you to set the initial *value* of the Characteristic at startup. If *value* is not specified, HomeSpan will supply a reasonable default for the Characteristic
* throws a runtime warning if *value* is outside of the min/max range for the Characteristic, where min/max is either the HAP default, or any new values set via a call to `setRange()`
* the first argument optionally allows you to set the initial *value* of the Characteristic at startup using the following formats:
* for NUMERIC Characteristics, *value* can be any integer or decimal numeric type, such as `boolean`, `int`, `uint64_t`, `double`, etc. HomeSpan will automatically cast *value* into a variable with the correct numerical precision for the Characteristic specified
* for STRING Characteristics, *value* must be either of the type `char *`, or a literal quote-enclosed UTF-8 string
* for TLV8 Characteristics, *value* must be of the type `TLV8`
* for DATA Characteristics, *value* must be a brace-enclosed *pair* of the form `{uint8_t *data, size_t len}`, where *len* specifies the length of the size of the byte-array *data*
* if *value* is not specified, HomeSpan will supply a reasonable default for the Characteristic
* for numerical Characteristics, throws a runtime warning if *value* is outside of the min/max range for the Characteristic, where min/max is either the HAP default, or any new values set via a call to `setRange()`
* the second optional argument, if set to `true`, instructs HomeSpan to save updates to this Characteristic's value in the device's non-volative storage (NVS) for restoration at startup if the device should lose power. If not specified, *nvsStore* will default to `false` (no storage)
* examples:
* `new Characteristic::Brightness();` Brightness initialized to default value
* `new Characteristic::Brightness(50);` Brightness initialized to 50
* `new Characteristic::Brightness(50,true);` Brightness initialized to 50; updates saved in NVS
* `new Characteristic::Brightness(50,true);` Brightness initialized to 50; updates to the value are saved to, and restored from, NVS
#### The following methods are supported for numerical-based Characteristics (e.g. *int*, *float*...):
@ -395,12 +441,16 @@ This is a **base class** from which all HomeSpan Characteristics are derived, an
* `type T getNewVal<T>()`
* a template method that returns the desired **new** value to which a HomeKit Controller has requested the Characteristic be updated. Same casting rules as for `getVal<>()`
* only applicable when called from within the `update()` loop of a **SpanService** (if called outside of the `update()` loop, the return value is that same as calling `getVal<>()`)
* `void setVal(value [,boolean notify])`
* sets the value of a numerical-based Characteristic to *value*, and, if *notify* is set to true, notifies all HomeKit Controllers of the change. The *notify* flag is optional and will be set to true if not specified. Setting the *notify* flag to false allows you to update a Characateristic without notifying any HomeKit Controllers, which is useful for Characteristics that HomeKit automatically adjusts (such as a countdown timer) but will be requested from the Accessory if the Home App closes and is then re-opened
* works with any integer, boolean, or floating-based numerical *value*, though HomeSpan will convert *value* into the appropriate type for each Characteristic (e.g. calling `setValue(5.5)` on an integer-based Characteristic results in *value*=5)
* throws a runtime warning if *value* is outside of the min/max range for the Characteristic, where min/max is either the HAP default, or any new min/max range set via a prior call to `setRange()`
* *value* is **not** restricted to being an increment of the step size; for example it is perfectly valid to call `setVal(43.5)` after calling `setRange(0,100,5)` on a floating-based Characteristic even though 43.5 does does not align with the step size specified. The Home App will properly retain the value as 43.5, though it will round to the nearest step size increment (in this case 45) when used in a slider graphic (such as setting the temperature of a thermostat)
* note that *value* is **not** restricted to being an increment of the step size; for example it is perfectly valid to call `setVal(43.5)` after calling `setRange(0,100,5)` on a floating-based Characteristic even though 43.5 does does not align with the step size specified. The Home App will properly retain the value as 43.5, though it will round to the nearest step size increment (in this case 45) when used in a slider graphic (such as setting the temperature of a thermostat)
* throws a runtime warning if called from within the `update()` routine of a **SpanService** *and* `isUpdated()` is *true* for the Characteristic (i.e. it is being updated at the same time via the Home App), *unless* you are changing the value of a Characteristic in response to a *write-response* request from HomeKit (typically used only for certain TLV-based Characteristics)
* note this method can be used to update the value of a Characteristic even if the Characteristic is not permissioned for event notifications (EV), in which case the value stored by HomeSpan will be updated but the Home App will *not* be notified of the change
* `SpanCharacteristic *setRange(min, max, step)`
* overrides the default HAP range for a Characteristic with the *min*, *max*, and *step* parameters specified
@ -427,10 +477,10 @@ This is a **base class** from which all HomeSpan Characteristics are derived, an
* `char *getNewString()`
* equivalent to `getNewVal()`, but used exclusively for string-characteristics (i.e. a null-terminated array of characters)
* `void setString(const char *value)`
* `void setString(const char *value [,boolean notify])`
* equivalent to `setVal(value)`, but used exclusively for string-characteristics (i.e. a null-terminated array of characters)
#### The following methods are supported for DATA (i.e. byte-array) Characteristics:
#### The following methods are supported for DATA (i.e. byte-array) Characteristics:
* `size_t getData(uint8_t *data, size_t len)`
* similar to `getVal()`, but exclusively used for byte-array Characteristics
@ -438,14 +488,38 @@ This is a **base class** from which all HomeSpan Characteristics are derived, an
* returns the total number of bytes encoded in the Characteristic
* if *len* is less than the total number of bytes encoded, no data is extracted (i.e. *data* is unmodified) and a warning message is thrown indicating that the size of the *data* array is insufficient to extract all the bytes encoded in the Characteristic
* setting *data* to NULL returns the total number of bytes encoded without extracting any data. This can be used to help create a *data* array of sufficient size in advance of extracting the data
* note: byte-array Characteristics are encoded and transmitted as base-64 strings. HomeSpan automatically peforms all encoding and decoding between this format and the specified byte arrays. But when output to the Serial Monitor using the 'i' CLI command, the value of byte-array Characteristics are displayed in their base-64 string format (only the first 32 characters are shown), since base-64 is the representation that is actually transmitted to and from HomeKit
* a warning message is thrown if the value stored in the Characteristic is not in base-64 format
* `size_t getNewData(uint8_t *data, size_t len)`
* similar to `getData()`, but fills byte array *data*, of specified size *len*, with bytes based on the desired **new** value to which a HomeKit Controller has requested the Characteristic be updated
* `void setData(uint8_t *data, size_t len)`
* `void setData(uint8_t *data, size_t len [,boolean notify])`
* similar to `setVal()`, but exclusively used for byte-array Characteristics
* updates the Characteristic by "filling" it with *len* bytes from bytes array *data*
* note: byte-array Characteristics are encoded and transmitted as base-64 strings. HomeSpan automatically peforms all encoding and decoding between this format and the specified byte arrays. But when output to the Serial Monitor, the value of byte-array Characteristics are displayed in their base-64 format (as opposed to being shown as a byte array), since base-64 is the representation that is actually transmitted to and from HomeKit
#### The following methods are supported for TLV8 (structured-data) Characteristics:
* `size_t getTLV(TLV8 &tlv)`
* similar to `getVal()`, but exclusively used for TLV8 Characteristics
* fills TLV8 structure *tlv* with TLV8 records from the current value of the Characteristic
* returns the total number of bytes encoded in the Characteristic
* if *tlv8* is not empty, TLV8 records from the Characteristic will be appended to any existing records
* similar to DATA Characteristics, TLV8 Characteristics are stored and transmitted as base-64 strings
* a warning message is thrown if the value stored in the Characteristic is not in base-64 format, or does not appear to contain TLV8 records
* `size_t getNewTLV(TLV8 &tlv)`
* similar to `getTLV()`, but fills TLV8 structure *tlv* with TLV8 records based on the desired **new** value to which a HomeKit Controller has requested the Characteristic be updated
* `void setTLV(TLV8 &tlv [,boolean notify])`
* similar to `setVal()`, but exclusively used for TLV8 Characteristics
* updates the Characteristic by packing the TLV8 structure *tlv* into a byte array and then encoding it in base-64 for storage as a string
* `NULL_TLV`
* this is not a method, but rather a static HomeSpan constant defined as an empty TLV8 object. It may used a placeholder wherever an empty TLV8 object is needed, such as when you want to instantiate a TLV8 Characteristic with *nvsStore=true*, but you don't yet want set the TLV8 value
* example: `new Characteristic::DisplayOrder(NULL_TLV,true);`
* see the [TLV8 Characteristics](TLV8.md) page for complete details on how to read/process/create TLV8 Objects using HomeSpan's TLV8 Library.
#### The following methods are supported for all Characteristics:
@ -481,6 +555,9 @@ This is a **base class** from which all HomeSpan Characteristics are derived, an
* returns a pointer to the Characteristic itself so that the method can be chained during instantiation
* example: `(new Characteristic::RotationSpeed())->setUnit("percentage");`
* `uint32_t getIID()`
* returns the IID of the Characteristic
### *SpanButton(int pin, uint16_t longTime, uint16_t singleTime, uint16_t doubleTime, boolean (\*triggerType)(int))*
Creating an instance of this **class** attaches a pushbutton handler to the ESP32 *pin* specified.
@ -591,17 +668,20 @@ To create more than one user-defined command, simply create multiple instances o
### *CUSTOM_CHAR(name,uuid,perms,format,defaultValue,minValue,maxValue,staticRange)*
### *CUSTOM_CHAR_STRING(name,uuid,perms,defaultValue)*
### *CUSTOM_CHAR_DATA(name,uuid,perms)*
### *CUSTOM_CHAR_TLV8(name,uuid,perms)*
Creates a custom Characteristic that can be added to any Service. Custom Characteristics are generally ignored by the Home App but may be used by other third-party applications (such as *Eve for HomeKit*). The first form should be used create numerical Characterstics (e.g., UINT8, BOOL...). The second form is used to STRING-based Characteristics. The third form is used for DATA-based (i.e. byte-array) Characteristics. Parameters are as follows (note that quotes should NOT be used in any of the macro parameters, except for *defaultValue* when applied to a STRING-based Characteristic):
Creates a custom Characteristic that can be added to any Service. Custom Characteristics are generally ignored by the Home App but may be used by other third-party applications (such as *Eve for HomeKit*). The first form should be used create numerical Characterstics (e.g., UINT8, BOOL...); the second form is used to STRING-based Characteristics; the third form is used for DATA-based (i.e. byte-array) Characteristics; and the fourth form is used for TLV8-based (i.e. *structured* byte-array) Characteristics Parameters are as follows (note that quotes should NOT be used in any of the macro parameters, except for *defaultValue* when applied to a STRING-based Characteristic):
* *name* - the name of the custom Characteristic. This will be added to the Characteristic namespace so that it is accessed the same as any HomeSpan Characteristic. Use UTF-8 coded string for non-ASCII characters.
* *uuid* - the UUID of the Characteristic as defined by the manufacturer. Must be *exactly* 36 characters in the form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, where *X* represent a valid hexidecimal digit. Leading zeros are required if needed as described more fully in HAP-R2 Section 6.6.1
* *perms* - additive list of permissions as described in HAP-R2 Table 6-4. Valid values are PR, PW, EV, AA, TW, HD, and WR
* *format* - specifies the format of the Characteristic value, as described in HAP-R2 Table 6-5. Valid value are BOOL, UINT8, UINT16, UNIT32, UINT64, INT, and FLOAT (note that the HomeSpan does not presently support the TLV8 formats). Not applicable for the STRING or DATA Characteristic macros
* *defaultValue* - specifies the default value of the Characteristic if not defined during instantiation. Not applicable for the DATA Characteristic macro.
* *minValue* - specifies the default minimum range for a valid value, which may be able to be overriden by a call to `setRange()`. Not applicable for the STRING or DATA Characteristic macros
* *minValue* - specifies the default minimum range for a valid value, which may be able to be overriden by a call to `setRange()`. Not applicable for the STRING or DATA Characteristic macros
* *staticRange* - set to *true* if *minValue* and *maxValue* are static and cannot be overridden with a call to `setRange()`. Set to *false* if calls to `setRange()` are allowed. Not applicable for the STRING or DATA Characteristic macros
* *uuid* - the UUID of the Characteristic as defined by the manufacturer. Must be either:
* *exactly* 36 characters of the form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX, where *X* represent a valid hexidecimal digit, or
* a single hexidecimal number of the form XXXXXXXX with *8 digits or less*, and no leading zeros
* *perms* - additive list of permissions. Valid values are PR, PW, EV, AA, TW, HD, and WR (e.g. PR+PW+EV)
* *format* - for numerical Characteristics, specifies the number format. Valid value are BOOL, UINT8, UINT16, UNIT32, UINT64, INT, and FLOAT. Not applicable for the STRING, DATA, or TLV8 Characteristic macros
* *defaultValue* - specifies the default value of the Characteristic when not defined during instantiation. Not applicable for the DATA or TLV7 Characteristic macros.
* *minValue* - specifies the default minimum range for a valid value, which may be able to be overriden by a call to `setRange()`. Not applicable for the STRING, DATA or TLV8 Characteristic macros
* *minValue* - specifies the default minimum range for a valid value, which may be able to be overriden by a call to `setRange()`. Not applicable for the STRING, DATA or TLV8 Characteristic macros
* *staticRange* - set to *true* if *minValue* and *maxValue* are static and cannot be overridden with a call to `setRange()`. Set to *false* if calls to `setRange()` are allowed. Not applicable for the STRING, DATA or TLV8 Characteristic macros
As an example, the first line below creates a custom Characteristic named "Voltage" with a UUID code that is recognized by the *Eve for HomeKit* app. The parameters show that the Characteristic is read-only (PR) and notifications are enabled (EV). The default range of allowed values is 0-240, with a default of 120. The range *can* be overridden by subsequent calls to `setRange()`. The second line below creates a custom read-only String-based Characteristic:

View File

@ -428,6 +428,7 @@ The pre-defined constant expressions for enumerated Characteristics are in names
<tr><th>Characteristic</th><th>Format</th><th>Perms</th><th>Min</th><th>Max</th><th>Constants/Defaults</th></tr>
<tr><td><b>Active (B0) :small_blue_diamond:</b><ul><li> indicates if the Service is active/on</li></ul></td><td align="center">uint8</td><td align="center">PW+PR+EV</td><td align="center">0</td><td align="center">1</td><td><ul><li><span>INACTIVE&nbsp(0)&nbsp;</span>:heavy_check_mark:</li><li><span>ACTIVE&nbsp(1)&nbsp;</span></li></ul></td></tr>
<tr><td><b>ActiveIdentifier (E7) </b><ul><li> numerical Identifier of the <b>InputSource</b> selected in the Home App.</li></ul></td><td align="center">uint32</td><td align="center">PW+PR+EV</td><td align="center">0</td><td align="center">255</td><td align="center">0</td></tr>
<tr><td><b>DisplayOrder (136) </b><ul><li> specifies the order in which the TV inputs are displayed for selection in the Home App</li></ul></td><td align="center">tlv8</td><td align="center">PR+EV</td><td align="center">-</td><td align="center">-</td><td align="center">NULL_TLV</td></tr>
<tr><td><b>RemoteKey (E1) </b><ul><li> triggers an update when the corresponding key is pressed in the Remote Control widget on an iPhone </li></ul></td><td align="center">uint8</td><td align="center">PW</td><td align="center">4</td><td align="center">15</td><td><ul><li><span>UP&nbsp(4)&nbsp;</span></li><li><span>DOWN&nbsp(5)&nbsp;</span></li><li><span>LEFT&nbsp(6)&nbsp;</span></li><li><span>RIGHT&nbsp(7)&nbsp;</span></li><li><span>CENTER&nbsp(8)&nbsp;</span></li><li><span>BACK&nbsp(9)&nbsp;</span></li><li><span>PLAY_PAUSE&nbsp(11)&nbsp;</span></li><li><span>INFO&nbsp(15)&nbsp;</span></li></ul></td></tr>
<tr><td><b>PowerModeSelection (DF) </b><ul><li> when defined, creates a "View TV Settings" button in the Home App that triggers an update to this Characteristic when pressed </li></ul></td><td align="center">uint8</td><td align="center">PW</td><td align="center">0</td><td align="center">0</td><td><ul><li><span>VIEW_SETTINGS&nbsp(0)&nbsp;</span></li></ul></td></tr>
<tr><td><b>ConfiguredName (E3) </b><ul><li> default display name of this Service</li></ul></td><td align="center">string</td><td align="center">PW+PR+EV</td><td align="center">-</td><td align="center">-</td><td align="center">"unnamed"</td></tr>

View File

@ -1,6 +1,18 @@
# Common Problems and Potential Solutions
#### *HomeSpan works correctly when my ESP32 is plugged into a computer or separately powered through the USB port, but it fails to work when powered directly through the ESP32 5V pin without any USB connection*
### *My HomeSpan device does not appear in the Home App when I try to pair it*
* There are a few reasons this may occur:
* **You have not yet entered your WiFi credentials**. HomeSpan can't connect to your WiFi network until you provide it with your WiFi&nbsp;SSID and password. If HomeSpan can't find these Credentials it outputs a warning message to the Serial Monitor during start-up. You can enter your WiFi Credentials into HomeSpan either directly from the Serial Monitor by using the 'W' CLI command, or via the HomeSpan Access Point Setup Page, or by hardcoding it into your sketch with the `homeSpan.setWifiCredentials()` function, though this last method is not recommended for security reasons.
* **You are out of range of your WiFi network, or entered the wrong WiFi Credentials**. When HomeSpan first boots, if you've previously entered your WiFi Credentials (see above) it will use them to connect to your WiFi network. Check the Serial Monitor for status on whether a connection has been successfully made. If not, make sure your device is in the range of your WiFi network, and re-enter your WiFi Credentials in case you entered them incorrectly the first time. To double-check that your HomeSpan device is indeed connected to your network after HomeSpan reports a successful connection, open up a terminal window on your computer and use the `ping` command to confirm you can reach the device.
* **Your iPhone and ESP32 device are not connected to the same WiFi network**. Make sure your HomeSpan device is connected to the same SSID as your iPhone and any HomeKit Hubs (e.g. HomePods or Apple TV). Some routers provide a separate SSID to use for IoT ("Internet of Things") devices. If you decide to use a separate SSID, make sure to configure your router so that message traffic flows unimpeded between your main SSID and your dedicated IoT SSID with absolutely no filtering of any messages. Also note that like most commercial HomeKit devices, ESP32 devices operate only on the 2.4 GHz WiFi band. Most iPhones can operate on either the 2.4 GHz or the 5.0 GHz WiFi bands, so if your router provides multi-band access, you need to make sure it is configured to allow unimpeded cross-traffic between the bands.
* **Your device thinks it is already paired (this is the most common reason)**. Check the Serial Monitor when HomeSpan first boots - it will let you know if the device is currently *paired* or *unpaired*. If its already *paired* you must unpair it before it can be paired again with the Home App. Normally you would unpair the device from the Home App itself, but if for whatever reason you can't (perhaps the device is no longer showing up in the Home App) you can force HomeSpan to forget all its pairing data and reset its state to *unpaired* by typing either the 'U' or 'H' CLI command into the Serial Monitor. The 'U' command instructs HomeSpan to simply erase all its *Controller* pairing data and reset its state to *unpaired*. The 'H' command instructs HomeSpan to erase all its *Controller* pairing data **and** its *HomeKit Device ID*, after which it reboots into the *unpaired* state and generates a new *HomeKit Device ID*. Typing 'H' is recommended to get the cleanest refresh. Note that your WiFi Credentials and Pairing Setup Code are not changed by either of these commands.
### *HomeSpan works correctly when my ESP32 is plugged into a computer or separately powered through the USB port, but it fails to work when powered directly through the ESP32 5V pin without any USB connection*
* On some ESP32 boards, the USB-UART chip only receives power if power is applied through the USB port, and thus remains unpowered if the ESP32 is powered solely through the ESP32 5V pin. As a result, the Serial RX pin associated with UART0 on the ESP32, which is normally driven by the USB-UART chip, is free to float at any voltage. If this pin floats low, the ESP32 thinks there is data to be read from the Serial Monitor, and HomeSpan falls into an infinite loop trying to read this non-existent data.
@ -12,8 +24,34 @@
* Note that adding this pull-up resistor should **not** interefere with normal serial operation of the board, such as using the Serial Monitor or uploading sketches.
* *As an alternative*, instead of adding a pull-up resistor, you can simply exclude (or comment out) the `Serial.begin()` line in your sketch. This prevents the problem of HomeSpan hanging when you power it through the 5V pin, but it unfortunately means the Serial Monitor will not function when you connect the board to your computer, and you will need to add back `Serial.begin()` whenever you want to use the Serial Monitor.
* *As an alternative*, instead of adding a pull-up resistor, you can simply exclude (or comment out) the `Serial.begin()` line in your sketch, or call `homeSpan.setSerialInputDisable(false)` to disable HomeSpan reading from the Serial port. This should prevent the problem of HomeSpan hanging when you power it through the 5V pin, but it unfortunately means the Serial Monitor will not function when you connect the board to your computer, and you will need to add back `Serial.begin()`, or remove `homeSpan.setSerialInputDisable(false)` whenever you want to use the Serial Monitor.
### *HomeSpan crashes when I enable PSRAM, but works fine if I disable PSRAM*
* If your ESP32 comes with Quad or Octal PSRAM, the chip will likely need to use one or more additional I/O pins so that it can access the PSRAM using an extended SPI bus, as required for these types of PSRAM. If you happen to use one of those pins for something else (e.g an input button, an LED, etc.) the ESP32 will likely crash whenever PSRAM is enabled.
* **Resolution:** Check the documentation for your board to see what pins are reserved for use when PSRAM is enabled, and *don't use those pins for anything else.*
### *The Serial Monitor is reporting* "gpio: gpio_set_level(226): GPIO output gpio_num error"
* This is an ESP32-generated error message and it occurs if you try to set the output of a pin that either does not exist on your chip, or does exist but it is input-only (i.e. it cannot be used as a output). This typically occurs when you try to compile code for one chip (such as an ESP32-S2) on another chip (such as an ESP32-C3). The code will compile fine, but may produce the above error during run-time.
* **Resolution:** Check the documentation for your board and *use only pins that exist for your chip, and are not reserved for internal functions, and are not input-only.*
### *My sketch is too large to be uploaded (error when trying to upload)*
* Though all ESP32 chips have a minimum of 4MB of flash memory, the amount that can be used to store a program depends on the *partition scheme* selected. By default, the ESP32 uses a parition scheme that reserves 1408 KB for a SPIFFS partition (SPI Flash File Storage) and splits the majority of the remaining flash into two equal OTA partitions of 1280 KB each for program storage. Most HomeSpan sketches come close to filling up an entire OTA partition, and if you add a lot of other libraries you will likely exceed 1280&nbsp;KB.
* **Resolution:** Select a different partition table that does not reserve so much flash memory for a SPIFFS partition since SPIFFS is not used at all by HomeSpan and *this partition is just wasting space.*
* From within the Arduino IDE, the easiest way to reduce the SPIFFS partition is to select the *Minimal SPIFFS* partition scheme from under the Tools menu, and then simply recompile and upload your sketch. This scheme reserves only 128 KB for the SPIFFS partition, which leaves a full 1920 KB of program storage for each OTA partition. This represents a 50% increase in program size, which should suffice for most applications.
* If for some reason you still need more space, and you only have 4MB of flash, you can try selecting the *Huge App* partition scheme, which reserves 896 KB for SPIFFS and leaves a *single* partition of 3072 KB for program storage. OTA will unfortunately *not* be available in this scheme.
* Note: if you are not using the Arduino IDE to compile and upload HomeSpan sketches, please consult the documentation for your IDE to learn how to change the partition scheme.
* Note: if none of the built-in partition schemes contain the right balance of partition sizes for your sketch, you can always create a custom partition scheme as demonstrated in HomeSpan's [CustomNVSParititon Example](../examples/Other%20Examples/CustomNVSPartition). This technique should work even if not using the Arduino IDE.
---
[↩️](../README.md) Back to the Welcome page

313
docs/TLV8.md Normal file
View File

@ -0,0 +1,313 @@
# TLV8 Characteristics
Most HomeKit Characteristics store a single numerical value or simple string. However, HomeKit supports two additional storage formats - a simple list of bytes (the **DATA** format) and a structured list of tags and values (the **TLV8** format). The DATA format is not used by any Apple-defined Characterstics but it is included in HomeSpan for use when creating Custom Characteristics for non-Apple applications.
In contrast, the TLV8 format is used extensively by HomeKit during the initial pairing process as well as whenever a new secure (verified) connection is established between HomeKit and a HomeSpan device. There are also a variety of Apple-defined Characteristics that use the TLV8 format to store and transmit multiple sets of values, each represented as byte-arrays of arbitrary length.
## Overview of TLV8 Format
The TLV8 format itself is quite simple. A TLV8 object comprises one or more TLV8 *records*, where the first byte in a record represents an identifying TAG (from 0-255), the second byte represents the LENGTH of the value, and the remaining LENGTH-bytes represent the VALUE itself, which is always in the form of a *byte-array* (i.e. an array of 0 or more *uint8_t* elements). Notable points about the TLV8 format are as follows:
* since the LENGTH is stored only as a single byte, VALUES requiring more than 255 bytes must be represented as sequential TLV8 records *with the same TAG*
* it is fine (and in fact common) for a TLV8 object to include multiple records with the same TAG, except that they must be *separated by a record with a different TAG*, otherwise the parser reading the data will concatenate the VALUES from sequential records having the same TAG into a single record (as per above)
* records representing a zero-LENGTH VALUE are allowed, and consist of only two bytes: a TAG and a zero (indicating a zero-length VALUE). TAGS with a zero-LENGTH VALUE are often used to separate multiple records having the same TAG
* if the VALUE's byte-array is supposed to represent an single, unsigned integer, it should be arranged in little endian format (i.e. least-significant byte first) and padded with trailing zeros as needed to bring the total LENGTH of the VALUE to either 1, 2, 4, or 8 bytes (representing uint8_t, uint16_t, uint32_t, and uint64_t values)
* if the VALUE's byte-array is supposed to represent a string, it should not include the terminating null since the LENGTH tells you have many characters are in the string
* the bytes that make up a VALUE can themselves represent a separate, complete TLV8 object. There is no limit on the number of "sub-TLVs" that can be recursively nested in a "parent" TLV8 object
* a parser reading TLV8 records should silently ignore any TAG it is not expecting. It may be an error to omit a TAG that the parser requires, but it will be not an error to include a TAG it does not recognize
* it is **not** possible to unambigously determine whether the VALUE byte-array in a TLV8 record is supposed to represent an unsigned integer, a string, an arbitrary series of bytes, a sub-TLV object, or something else entirely. The only identifying information for any given TLV8 record is its TAG number, which ranges from 0-255. There is no general schema or TLV8 protocol that maps TAG types to VALUE types. Rather, the TAG numbers are arbitrary and users must consult the documentation for each Characteristic to learn what TAG numbers are expected, and what their VALUEs are supposed to represent for that specific Characteristic
* since HomeKit data transmissions are often represented in JSON, and JSON is a text-only format, HomeKit requires that TLV8 records are first encoded in base-64 when transmitting JSON to and from Controllers to Accessories.
Fortunately, HomeSpan includes a dedicated TLV8 library (see below) that automatically takes care of many of the above points, which enables you to read, create, and process TLV8 data without worrying about parsing TLV8 records with more than 255 bytes, converting numerical values to little-endian, or encoding/decoding records into base-64.
## *TLV8()*
Creating an instance of HomeSpan's TLV8 **class** using the above constructor builds an empty TLV8 object into which you can add and process TLV8 records. TLV8 objects are instantiated as standard C++ linked-list containers derived from `std::list<tlv8_t>`, where *tlv8_t* is an opaque structure used to store individual TLV8 records.[^opaque]
Also, as shown below, many of the TLV8 methods utilize linked-list *constant* iterators. These are represented by the typedef *TLV8_itc*.[^iterators]
[^opaque]:The *tlv8_t* structure is opaque because in general you will not have to create or interact directly with the structure or its data. Note that in addition to the above TLV8-specific methods, you can use any `std::list` method with a TLV8 object if desired.
[^iterators]:You do not need expert knowledge of C++ containers and iterators in order to use the TLV8 library, but a basic understanding of containers and iterators will make the library much easier to learn and enjoyable to use.
The method for adding a generic TLV8 record to a TLV8 object is as follows:
* `TLV8_itc add(uint8_t tag, size_t len, const uint8_t *val)`
* where *tag* is the TAG identifier for the record to add and *val* is a pointer to a byte-array containing *len* elements
* example: `TLV8 myTLV; uint8_t v[]={0x01, 0x05, 0xE3, 0x4C}; tlv.add(1, sizeof(v), v);
* setting *val* to NULL reserves *len* bytes of space for the TLV8 record within the TLV8 object, but does not copy any data
* this method returns a TLV8 constant iterator to the resulting TLV8 record so you can reference the record at a later time if needed
In addition to the above generic method suitable for any type of data, the following methods make it easier to add TLV8 records with specific, frequently-used types of data:
* `TLV8_itc add(uint8_t tag, uintXX_t val)`
* adds a TLV8 record containing a single, unsigned numeric value, *val* (i.e. uint8_t, uint16_t, uint32_t, or uint64_t)
* `TLV8_itc add(uint8_t tag, const char *val)`
* adds a TLV8 record containing all the non-null bytes of a null-terminated character string, *val*
* `TLV8_itc add(uint8_t tag, TLV8 &subTLV)`
* adds a TLV8 record containing all the bytes of an entire TLV8 object, *subTLV*
* `TLV8_itc add(uint8_t tag)`
* adds a zero-length TLV8 record containing nothing but a TAG identifer
Note that if you *add* consecutive records with the same TAG identifier, the TLV8 library will concatenate their data and combine into a single record. For example, `myTLV.add(1,13); myTLV.add(1,300)` will be combined to produce a single 3-byte recording containing the data 0x0D2C01, where the first byte represents from the number 13 and the second two bytes represent the number 300. This may have been your desired outcome, but likely not what you wanted to happen.
Instead, to create two distinct records with the same tag value, simply interpose a zero-length record with a different TAG identifier between the two as a "separator" like this: `myTLV.add(1,13); myTLV.add(255); myTLV.add(1,300);` Here we used a TAG identifer of 255 to represent the separator, but that choice is arbitrary, unless that TAG happens to be used by the Characteristic for something else (TAG identifiers of 0 or 255 are commonly used as separators).
The method for finding a TLV8 record within a TLV8 object that contains a specific TAG identifer is as follows:
* `TLV8_itc find(uint8_t tag)`
* where *tag* is the TAG identifier you are seeking
* returns a TLV8 constant iterator to *first* record that matches; returns *end()* if no records match
To restrict the search range to a limited set of records, add optional starting and ending iterators *it1* and *it2*:
* `TLV8_itc find(uint8_t tag [, TLV8_itc it1 [, TLV8_itc it2]])`
* returns a TLV8 constant iterator to the *first* record within the range of constant iterators from *it1* to *it2* that matches the specified *tag*
* search range is inclusive of *it1* but exclusive of *it2*
* returns *it2* if no records match
* if *it2* is unspecified, default is *end()*; if *it1* is unspecified, default is *begin()*
* note `myTLV.find(tag)` is equivalent to `myTLV.find(tag, myTLV.begin(), myTLV.end())`
Use of the C++ `auto` keyword is generally the best way to save the TVL8_itc iterator that is returned from the `find()` and `add()` methods. For example, `auto myIT = myTLV.find(6)` sets *myIT* to a constant iterator pointing to the first TLV8 record in *myTLV* that has a TAG identifer of 6.
The method for finding the LENGTH of the data VALUE stored in a particular TLV8 record is as follows:
* `int len(TLV8_itc it)`
* where *it* is an constant iterator pointing to a specific TLV8 record
* returns the length of the data VALUE stored in the associated record, which may be zero for a zero-LENGTH record
* returns -1 if *it* points to the *end()* of the TLV8 object
A typical use of the `len()` method is to simultaneously check whether a TLV8 object contains a particular TAG identifier, and that the LENGTH of the TAG matches an expected value. For example, if a certain Characteristic requires a TLV8 record with a TAG identifer of 6 to contain a 32-byte registration number, you can perform the following check:
```C++
auto myIT = myTLV.find(6);
if(myTLV.len(myIT)!=32)
Serial.printf("Error: TAG 6 is either missing or of improper length\n");
else
Serial.printf("TAG 6 containing 32 bytes of data has been found\n");
```
The method for printing all of the records in a TLV8 object to the Serial Monitor is as follows:
* `void print()`
* prints all TLV8 records, one per line, to the Serial Monitor
* format of the output is: TAG(LENGTH) VALUE [NUMERIC], where
* TAG = the TAG identifer (0-255)
* LENGTH = length of the VALUE byte-array (may be zero)
* VALUE = a sequential list, in hexadecimal, of all the bytes in the VALUE byte-array (only displayed if LENGTH>0)
* NUMERIC = an unsigned-integer interpretation of the bytes in VALUE, assuming little-endian ordering
* this decimal value is only displayed if LENGTH<=8
* if LENGTH=0, the word "null" is displayed instead
To restrict the the printing range to a limited set of records, add optional starting and ending constant iterators *it1* and *it2*:
* `void print(TLV8_itc it1 [, TLV8_itc it2])`
* prints all TLV8 records between constant iterators *it1* and *it2*
* print range is inclusive of *it1* but exclusive of *it2*
* if *it2* is unspecified, prints only the record pointed to by *it1*
* note `myTLV.print()` is equivalent to `myTLV.print(myTLV.begin(), myTLV.end())`
The output generated by `print()` can contain some very long lines, especially if the VALUE of some of the TLV8 records represents other complete TLV8 objects (known as sub-TLVs or "nested" TLVs). To recursively print all sub-TLV objects, use the following method:
* `void printAll()`
* recursively prints all TLV8 records, one per line, to the Serial Monitor
* inspects each TLV8 record and tries to parse as if the record represented a sub-TLV object
* if parsing is successful, prints the record and then calls `printAll()` on the sub-TLV
* if not, prints the record and ends this branch of the recursion
* the format of each line is the same as that of `print()` except that TAG displays the full path of all TAGs through the branch
* note that the output can be very voluminous if your TLV8 object contains many levels of nested sub-TLVs
* warning: some care is required when interpretating the output[^subTLVs]
[^subTLVs]:The `printAll()` method assumes that any VALUE that is consistent with the format of a sub-TLV must be a sub-TLV, even if its just a simple numeric value. For example, `add(10,65536)` yields a record with a TAG identifer of 10 and a 4-byte VALUE of 0x00000100. The `printAll()` method will display this record along with NUMERIC=65536, but it will also then interpret (and thus display) this VALUE as a sub-TLV containing one zero-length record with TAG identifier=0 and another zero-length record with TAG identifer=1, since the VALUE can be successfully parsed as such.
TLV8 objects manage all of their internal memory requirements, and free up all resources and memory when they go out of scope or are otherwise deleted. However, if you need to "erase" all the contents of a TLV8 object but stil retain the object so you can re-fill with new data, use the following method:
* `void wipe()`
* erases all TLV8 records and frees all associated memory
* leaves an empty TLV8 object ready for re-use
## *TLV8_itc()*
Objects of type *TLV8_itc* are constant iterators that point to specific *tlv8_t* records in a TLV8 object (or to *end()*). TLV8 iterators are used to access, read from, and write to, the data elements in any given TLV8 record, and are thus a critical part of the TLV8 library. However, if you are using the TLV8 library correctly you should rarely, if ever, need to directly instantiate a *TLV8_itc* using its constructor. Instead, simply use the C++ `auto` keyword as noted above.
TLV8_itc iterators can be dereferenced to work with data in an individual TLV8 record using the follow methods:
* `uint8_t getTag()`
* returns the TAG identifier (0-255) of the TLV8 record
* example: `uint8_t tag = myIT->getTag()` or, equivalently, `uint8_t tag = (*myIT).getTag()`
* `size_t getLen()`
* returns the LENGTH of the VALUE byte-array of the TLV8 record
* example: `size_t len = myIT->getLen()` or, equivalently, `size_t len = (*myIT).getLen()`
* `uint8_t *get()`
* returns `uint8_t *` pointing to the first element of the VALUE byte-array of the TLV8 record
* for zero-LENGTH TLV8 records, the return value is NULL
* example: `uint8_t *v = myIT->get();` or, equivalently, `uint8_t *v = (*myIT).get();`
* the `(uint8_t *)` casting operator has been overloaded so you can also obtain this same `uint8_t *` pointer by simply dereferencing the iterator
* example: `auto myIT = myTLV.find(6); uint8_t *v = *myIT;`
* note this only works if the compiler can determine the need to auto-cast into a `uint8_t *` pointer based on the context of the code
* `uint8_t get()[i]`
* returns the *i<sup>th</sup>* element of the VALUE byte-array
* example: `uint8_t n = myIT->get()[i]` or, equivalently, `uint8_t n = (*myIT).get()[i]`
* the subscript operator has also been overloaded so you can obtain the *i<sup>th</sup>* element by simply dereferencing the iterator
* example: `uint8_t n = (*myIT)[i]`
* note there is no range-checking so make sure *i* does not try to reference an element beyond the end of the VALUE byte-array
* `T getVal<class T>()`
* this template function returns a single numeric value of type *T* on the assumption that the VALUE byte-array is storing an unsigned integer in little endian format
* *T* can be *uint8_t*, *uint16_t*, *uint32_t*, or *uint64_t* (if unspecified *T* defaults to *uint32_t*)
* example: `auto myIT = myTLV.add(50,60000); uint16_t n = myIT->getVal<uint16_t>();`
* this method returns the correct numeric value as long as sizeof(*T*) >= LENGTH of the byte-array. For example:
* setting *T=uint64_t* with a VALUE byte-array containing 2 bytes returns the *correct* numeric value
* setting *T=uint16_t* with a VALUE byte-array containing 4 bytes return an *incorrect* numeric value
* this function returns zero for all zero-LENGTH TLV8 records
### A detailed example using the above methods
The following code:
```C++
TLV8 myTLV; // instantiates an empty TLV8 object
myTLV.add(1,8700); // add a TLV8 record with TAG=1 and VALUE=8700
auto it_A = myTLV.add(2,180); // add a TLV8 record with TAG=2 and VALUE=180, and save the iterator that is returned
uint8_t v[32]; // create a 32-byte array, v, and fill it with some data
for(int i=0;i<32;i++)
v[i]=i;
myTLV.add(200,32,v); // add a TLV8 record with TAG=200 and copy all 32 bytes of array v into its VALUE
myTLV.add(50,60000); // add a TLV8 record with TAG=50 and VALUE=60000
myTLV.add(255); // add a zero-length TLV8 record with TAG=255 to act as separator
myTLV.add(50,120000); // add a TLV8 record with TAG=50 and VALUE=120000
myTLV.add(255); // add a zero-length TLV8 record with TAG=255 to act as separator
myTLV.add(50,180000); // add a TLV8 record with TAG=50 and VALUE=180000
myTLV.add(255); // add a zero-length TLV8 record with TAG=255 to act as separator
auto it_B = myTLV.add(50,240000); // add a TLV8 record with TAG=50 and VALUE=240000, and save the iterator that is returned
auto it_C = myTLV.find(50); // find an iterator to the first TLV8 record with TAG=50;
auto it_D = myTLV.find(50,std::next(it_C)); // find an iterator to the first TLV8 record with TAG=50 that occurs AFTER it_C;
auto it_E = myTLV.find(200); // find an iterator to first TLV8 record with TAG=200;
Serial.printf("results of myTLV.print():\n\n");
myTLV.print(); // print the contents of myTLV to the Serial Monitor
Serial.printf("\n");
// print content of it_A:
Serial.printf("it_A: TAG=%d, LENGTH=%d, Value=%d\n", it_A->getTag(), it_A->getLen(), it_A->getVal());
// print content of it_B using alternative syntax:
Serial.printf("it_B: TAG=%d, LENGTH=%d, Value=%d\n", (*it_B).getTag(), (*it_B).getLen(), (*it_B).getVal());
// print contents of it_C and it_D, based on previous find() above:
Serial.printf("it_C TAG=%d, LENGTH=%d, Value=%d\n", (*it_C).getTag(), (*it_C).getLen(), (*it_C).getVal());
Serial.printf("it_D TAG=%d, LENGTH=%d, Value=%d\n", (*it_D).getTag(), (*it_D).getLen(), (*it_D).getVal());
// you can also use the results of find() directly without saving as a separate iterator, though this is computationally inefficient:
if(myTLV.find(1)!=myTLV.end()) // check for match
Serial.printf("Found: TAG=%d, LENGTH=%d, Value=%d\n", myTLV.find(1)->getTag(), myTLV.find(1)->getLen(), myTLV.find(1)->getVal());
// sum up all the bytes in it_E:
int sum=0;
for(int i=0; i < it_E->getLen(); i++)
sum+= (*it_E)[i];
Serial.printf("it_E TAG=%d, LENGTH=%d, Sum of all bytes = %d\n", (*it_E).getTag(), (*it_E).getLen(), sum);
// create a "blank" TLV8 record with TAG=90 and space for 16 bytes:
auto it_F = myTLV.add(90,16,NULL);
// copy the first 16 bytes of it_E into it_F and print the record:
memcpy(*it_F,*it_E,16);
myTLV.print(it_F);
```
produces the following output:
```C++
results of myTLV.print():
1(2) FC21 [8700]
2(1) B4 [180]
200(32) 000102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F
50(2) 60EA [60000]
255(0) [null]
50(4) C0D40100 [120000]
255(0) [null]
50(4) 20BF0200 [180000]
255(0) [null]
50(4) 80A90300 [240000]
it_A: TAG=2, LENGTH=1, Value=180
it_B: TAG=50, LENGTH=4, Value=240000
it_C TAG=50, LENGTH=2, Value=60000
it_D TAG=50, LENGTH=4, Value=120000
Found: TAG=1, LENGTH=2, Value=8700
it_E TAG=200, LENGTH=32, Sum of all bytes = 496
90(16) 000102030405060708090A0B0C0D0E0F
```
## Reading and Writing TLV8 Characteristics
As fully documented in the [API Reference](Reference.md), the following *SpanCharacteristic* methods are used to read and write TLV8 objects to TLV8 Characteristics:
* `getTLV(TLV8 &tlv)`
* `getNewTLV(TLV8 &tlv)`
* `setTLV(TLV8 &tlv)`
These are analagous to the `getVal()`, `getNewVal()` and `setVal()` methods used for numerical-based Characteristics.
Note that using the above methods *do not* require you to create a separate byte-array that splits records into chunks of 255 bytes, nor does it require you to encode or decode anything into base-64. Rather, you directly read and write to and from the Characteristic into a TLV8 object.[^getString]
For a detailed example of how TLV8 Characteristics are used in practice, see [Tutorial Example 22 - TLV8_Characteristics](../examples/22-TLV8_Characteristics) demonstrating how the **DisplayOrder** TLV8 Charactersitic can be used to set the order in which Input Sources for a TV Service are displayed in the Home App.
[^getString]:Since TLV8 Characteristics are stored as base-64 encoded strings, you can always use `getString()` to read the base-64 text, or `getData()` to decode the string into the full byte-array that represents the entire TLV8 object, if you desire. Also, if you really don't want to use HomeSpan's TLV8 library to produce TLV8 objects, but instead prefer to use your own methods to create a TLV8-compliant byte-array, you can do so and then use `setData()` to save the byte-array you produced to the TLV8 Characteristic, which will perform the base-64 encoding for you. Or, if you want to additionally perform your own base-64 encoding (why?), you can do so and then simply use `setString()` to save the resulting encoded text to the TLV8 Characteristic.
### Write-Response Requests
For most Characteristics, when the Home App sends HomeSpan a request to update a value, it is instructing HomeSpan to perform some sort of action, such as "change the brightness of a lightbulb to 30%" or "change the target state of the door to open." The only feedback the Home App expects to receive in response to such requests is basically an "OK" or "NOT OKAY" message, which is the purpose of the boolean return value in the `update()` method for every Service.
However, sometimes the Home App sends HomeSpan a request for information, rather than a direct instruction to perform a task. In such instances, rather than sending back just an OK/NOT-OKAY message, the Home App expects the Accessory device to update the value of the Characteristic *not* with the new value that the Home App sent, but rather with the information it requested. It then expects this information to be transmitted back to the Home App at the conclusion of the update.
This procedure is known as a "Write-Response Request", and it is the primary purpose for having TLV8 Characteristics, since TLV8 objects are ideal for storing structured information.
Though the procedure is complex, HomeSpan handles all of the protocol details. You only need to focus on reading the TLV8 Characteristic and updating it with the required TLV8 response as follows:
* first, from within the `update()` loop of the applicable Service, check to see if the Home App has requested an update to the TLV8&nbsp;Characteristic;
* if so, create a new TLV8 object and use `getNewTLV()` to load the contents of the updated Characteristic into that TLV8 object;
* then, use the TLV8 library methods described above to read through the TAGS and VALUES in the TLV8 object to determine what data the Home App is conveying and what information it wants returned (based on the specs for the Characteristic);
* next, create a *second* TLV8 object and use the TLV8 library methods above to create the appropriate TAGS and VALUES needed to respond to the information request (again, based on the on the specs for the Characteristic);
* finally, use `setVal()` to update the TLV8 Characteristic with the second TLV8 object
HomeSpan will automatically send the new TLV8 data you placed in the TLV8 Characterstic back to the Home App in its response at the conclusion of the `update()` loop.
---
[↩️](../README.md) Back to the Welcome page

View File

@ -21,7 +21,7 @@ new Service::Television();
new Characteristic::Active(0); // set power to OFF at start-up
new Characteristic::ConfiguredName("Sony TV"); // optional Characteristic to set name of TV
```
More advanced control of a TV can enabled with two other optional Characteristics:
More advanced control of a TV can enabled with these *optional* Characteristics:
* `Characteristic::RemoteKey()` - this write-only numerical Characteristic enables HomeSpan to read button presses from the Remote Control widget on an iPhone that can be found under the Control Center. This widget is normally used to control Apple TVs, but it seems any Television Accessory created per above can also be operated from the Remote Control widget. The layout of the widget (which cannot be modified) includes 4 arrows, a central select button, a play/pause button, a large "back" button, and an "info" button. When a "key" is pressed, the Home App sends an update to `Characteristic::RemoteKey()` that can be read by HomeSpan using the usual `update()` method. Values are as follows:
@ -38,6 +38,23 @@ More advanced control of a TV can enabled with two other optional Characteristic
* `Characteristic::ActiveIdentifier()` - this numerical Characteristic is used to control the input source for the TV (e.g. HDMI-1, HDMI-2, Netflix, etc.). It is only used when input sources are defined and linked using `Service::InputSource()` (see below), in which case it is a *required* Characteristic
* `Characteristic::DisplayOrder()` - this TLV8 Characteristic is used to control the order in which linked Input Sources are displayed in the Home App
* absent specifying the order with this Characteristic, the Home App will display the Input Sources in a random order within the selection section (under the power button), and in numerical order on the settings page of the Accessory based on the numeric Identifier for each Input Source
* the format of the TLV8 object used by this Characteristic is a series of TLV8 "Identifier" records with TAG=1 and a VALUE set to the Identifer of a particular Input Source; the "Identifier" records should each be separated by an empty TLV8 record with TAG=0
* example, the following code snippet sets the display order for three input sources with Identifiers 10, 20, and 30 to be 20, 30, and then 10:
```C++
TLV8 orderTLV; // create an empty TLV8 object named "orderTLV"
orderTLV.add(1,20); // TAG=1, VALUE=20 (the Identifier of the first Input Source to be displayed)
orderTLV.add(0); // TAG=0 (empty record used as a separator)
orderTLV.add(1,30); // TAG=1, VALUE=30 (the Identifier of the second Input Source to be displayed)
orderTLV.add(0); // TAG=0 (empty record used as a separator)
orderTLV.add(1,10); // TAG=1, VALUE=10 (the Identifier of the third Input Source to be displayed)
new Characteristic::DisplayOrder(orderTLV); // instantiate the DisplayOrder Characteristic and set its value to the orderTLV object
```
### `Service::InputSource()`
Use `Service::InputSource()` to create a new input source selection for the TV, such as HDMI-1, HDMI-2, Netflix, etc. The use of `Service::InputSource()` is optional - it is perfectly okay to create a Television Service without the ability to select different Input Sources. However, if used, each Input Source Service added should be defined in the *same* Accessory as the Television Service to which it applies, and ***must*** be linked to that Television Service using `addLink()`. The Home App behaves unexpectedly if it finds any Input Source Services that are not linked to a Television Service.
@ -66,8 +83,10 @@ This Service allows you to change the volume of a television using the iPhone's
### Examples
Please see [*File → Examples → HomeSpan → Other Examples → Television*](../Other%20Examples/Television) for a complete worked example demonstrating the effects of using different combinations of the above Characteristics. Also, don't forget to check out the [HomeSpan Projects](https://github.com/topics/homespan) page for some real-world examples of TV sketches and controllers.
* Please see [*File → Examples → HomeSpan → Other Examples → Television*](../examples/Other%20Examples/Television) for a complete worked example demonstrating the effects of using different combinations of the above Characteristics
* For details on how to use TLV8 records with the DisplayOrder Characteristic, see [Tutorial Example 22 - TLV8 Characteristics](../examples/22-TLV8_Characteristics)
* For more advanced use case, see the Television Example on the [HomeSpan Reference Sketches](https://github.com/HomeSpan/HomeSpanReferenceSketches) page
* Also, don't forget to check out the [HomeSpan Projects](https://github.com/topics/homespan) page for some real-world examples of TV sketches and controllers.
### Credits

View File

@ -2,7 +2,8 @@
The HomeSpan library includes many tutorial sketches of increasing complexity that take you through all the functions and features of HomeSpan. The sketches are extensively annotated, and you'll even learn a lot about HomeKit itself by working through all the examples. If you've already loaded HomeSpan into your Arduino IDE, the tutorials will be found under *File → Examples → HomeSpan*. Each sketch is ready to be compiled and uploaded to your ESP32 device so you can see them in action. Alternatively, you can explore just the code within GitHub by clicking on any of titles below. Note: you may want to first read through the [HomeSpan API Overview](Overview.md) before exploring the tutorials. They will probably make a lot more sense if you do!
> :heavy_check_mark: Each example is designed to be operated after pairing your ESP32 to HomeKit so you can control HomeSpan from the Home App on your iPhone, iPad, or Mac. In principle, once you configure and pair your device to HomeKit, your Home App should automatically reflect all changes in your configuration whenever you upload a different tutorial. However, in practice this is not always the case as it seems HomeKit sometimes caches information about devices, which means what you see in your Home App may not be fully in sync with your sketch. If this occurs, unpairing and then re-pairing the ESP32 device usually fixes the issue. If not, you may have to reset the ID on the ESP32 device so that HomeKit thinks it is a new device and will not use any cached data. This is very easy to do - see the [HomeSpan Command-Line Interface (CLI)](CLI.md) page for details.
>[!TIP]
>Each example is designed to be operated after pairing your ESP32 to HomeKit so you can control HomeSpan from the Home App on your iPhone, iPad, or Mac. In principle, once you configure and pair your device to HomeKit, your Home App should automatically reflect all changes in your configuration whenever you upload a different tutorial. However, in practice this is not always the case as it seems HomeKit sometimes caches information about devices, which means what you see in your Home App may not be fully in sync with your sketch. If this occurs, unpairing and then re-pairing the ESP32 device usually fixes the issue. If not, you may have to reset the HomeKit Device ID on the ESP32 device so that HomeKit thinks it is a new device and will not use any cached data. This is very easy to do - see the [HomeSpan Command-Line Interface (CLI)](CLI.md) page for details.
### [Example 1 - SimpleLightBulb](../examples/01-SimpleLightBulb)
This first example introduces the HomeSpan library and demonstrates how to implement a simple on/off light control using a combination of HomeSpan Accessory, Service, and Characteristic objects. Once this sketch has been uploaded to your HomeSpan device and the device is paired to your home, a new "lightbulb" tile will appear in the Home App of your iPhone, iPad, or Mac. Though the tile will be fully operational (i.e. you can change the status of the lightbulb from "on" or "off"), we won't yet connect an actual light or LED to the HomeSpan device, so nothing real will light up. Instead, in this and the next few examples, we'll focus on learning about the different ways HomeKit controls can be configured. Starting in Example 5, we'll connect an LED to the device and introduce the methods that actually turn the LED on and off from your Home App. HomeSpan API topics covered in this example include:
@ -68,7 +69,9 @@ Example 12 introduces HomeKit *Event Notifications* to implement two new accesso
* setting the value of a Characteristic and triggering an Event Notification with the `setVal()` method
### [Example 13 - TargetStates](../examples/13-TargetStates)
Example 13 we demonstrate the simultaneous use of both the `update()` and `loop()` methods by implementing two new Services: a Garage Door Opener and a motorized Window Shade. Both examples showcase HomeKit's Target-State/Current-State framework.
Example 13 demonstrates the simultaneous use of both the `update()` and `loop()` methods by implementing two new Services: a Garage Door Opener and a motorized Window Shade. Both examples showcase HomeKit's Target-State/Current-State framework. New HomeSpan API topics covered in this example include:
* using Enumerated Constants to set the values of Characteristics that represent discrete states (e.g. "raising", "closing")
### [Example 14 - EmulatedPushButtons](../examples/14-EmulatedPushButtons)
Example 14 demonstrates how you can use the `setVal()` and `timeVal()` methods inside a Service's `loop()` method to create a tile in the Home App that emulates a pushbutton switch. In this example pressing the tile in the Home App will cause it to turn on, blink an LED 3 times, and then turn off (just like a real pushbutton might do).
@ -106,6 +109,16 @@ Example 20 illustrates a number of advanced techniques through the implementatio
* dynamically deleting Accessories with `homeSpan.deleteAccessory()`
* refreshing the Accessory database (which automatically updates the Home App) using `homeSpan.updateDatabase()`
* using `homeSpan.autoPoll()` to implement HomeSpan Polling in the background (and on the second core, if available)
### [Example 21 - AccessoryIdentifier](../examples/21-AccessoryIdentifier)
Example 21 shows how the Identifier Characteristic that is always present in each Accessory's required AccessoryInformation Service can be used to create a custom "identification routine" that can be triggered from within the Home App when pairing a device. This example does not use any new HomeSpan methods.
### [Example 22 - TLV8 Characteristics](../examples/22-TLV8_Characteristics)
Example 22 demonstrates how to create and utilize TLV8-based Characteristics through the implementation of the DisplayOrder Characteristic used to set the order in which input sources for a Television Service are presented in the Home App. New HomeSpan API topics covered in this example include:
* creating TLV8 objects using HomeSpan's TLV8 class
* updating TLV8 Characteristics using `setTLV()`
## Other Examples
@ -126,6 +139,9 @@ An example of HomeKit's *undocumented* Television Service showing how different
### [Pixel](../examples/Other%20Examples/Pixel)
Demonstrates how to use HomeSpan's *Pixel* and *Dot* classes to control one- and two-wire Addressable RGB and RGBW LEDs. See the [Addressable RGB LEDs](Pixels.md) page for full details
### [PixelTester](../examples/Other%20Examples/PixelTester)
A sketch to aid in determining the *pixelType* for any RGB(W) LED Strip. See the [Addressable RGB LEDs](Pixels.md) page for full details
### [CustomService](../examples/Other%20Examples/CustomService)
Demonstrates how to create Custom Services and Custom Characteristics in HomeSpan to implement an Atmospheric Pressure Sensor recognized by the *Eve for HomeKit* app. See [Custom Characteristics and Custom Services Macros](Reference.md#custom-characteristics-and-custom-services-macros) for full details

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*
@ -51,9 +51,6 @@
// NOTE: All HomeSpan examples are best understood when reviewed in conjunction with the documentation provided on the HomeSpan GitHub page.
// See https://github.com/HomeSpan/HomeSpan for details and references. In particular, you may want to review the HomeSpan API Overview
// page before proceeding.
// These examples also make frequent reference to Apple's HomeKit Accessory Protocol Specification, known as HAP. You can download this
// directly from Apple at https://developer.apple.com/support/homekit-accessory-protocol.
// LET'S GET STARTED...

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*
@ -30,12 +30,11 @@
// HomeSpan: A HomeKit implementation for the ESP32 //
// ------------------------------------------------ //
// //
// Example 5: Two working on/off LEDs based on the //
// Example 5: Two working on/off LEDs based on the //
// LightBulb Service //
// //
////////////////////////////////////////////////////////////
#include "HomeSpan.h"
#include "DEV_LED.h" // NEW! Include this new file, DEV_LED.h, which will be fully explained below

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*
@ -60,18 +60,19 @@ void setup() {
// guesses the actions a device is taking, and updates it tile's icon accordingly, by comparing the value of the target state
// Characteristic it sets, and the current state Characteristic it receives in the form of Event Notifications. When they are the same,
// HomeKit assumes the physical device has reached the required position. When they differ, HomeKit assumes something will be opening,
// closing, raising, lowering, etc. The details of this process for each Service is outlined in the HAP documentation, but beware
// the document is not always up to date with the lastest version of the HomeKit application. Sometimes a little experimenting and a lot
// of trial and error is required to fully understand how each Service responds to different combinations of Characteristic values.
// closing, raising, lowering, etc. Sometimes a little experimenting and a lot of trial and error is required to fully understand how
// each Service responds to different combinations of Characteristic values.
// As always, we won't be connecting our ESP32 to an actual garage door or window shade but will instead simulate their responses and
// actions for illustrative purposes. In some ways the code is more complicated because of the need to simulate values - it might be
// easier if we actually were connecting to a garage door or window shade!
// Fully commented code for both of our derived Services can be found in DEV_DoorsWindows.h. These examples do not introduce any new
// HomeSpan functions or features. Rather we are combining everything learned so far into two reasonably complex Services. You may
// want to reference the HAP documentation for these two parent Services to fully understand the meaning of the different value settings
// for each of the Services' Characteristics.
// HomeSpan functions, but you will see how to use HomeSpan's ENUMERATED CONSTANTS, instead of just plain integers, to set the values
// of Characteristics where the values represent discrete states (e.g. "lowering", "opening").
// Please see HomeSpan's Services and Characteristics page for a complete list of the enumerated constants available for Characteristics
// where they are applicable.
Serial.begin(115200);

View File

@ -3,17 +3,33 @@
// DEVICE-SPECIFIC LED SERVICES //
////////////////////////////////////
struct DEV_GarageDoor : Service::GarageDoorOpener { // A Garage Door Opener
struct DEV_GarageDoor : Service::GarageDoorOpener { // A Garage Door Opener
Characteristic::CurrentDoorState *current; // reference to the Current Door State Characteristic (specific to Garage Door Openers)
Characteristic::CurrentDoorState *current; // reference to the Current Door State Characteristic (specific to Garage Door Openers)
Characteristic::TargetDoorState *target; // reference to the Target Door State Characteristic (specific to Garage Door Openers)
SpanCharacteristic *obstruction; // reference to the Obstruction Detected Characteristic (specific to Garage Door Openers)
SpanCharacteristic *obstruction; // reference to the Obstruction Detected Characteristic (specific to Garage Door Openers)
DEV_GarageDoor() : Service::GarageDoorOpener(){ // constructor() method
DEV_GarageDoor() : Service::GarageDoorOpener(){ // constructor() method
// Below we use enumerated constants rather than integers to set the values of the Characteristics.
// Using enumerated constants means not having to remember the integer code for each state. You'll find
// a complete list of all available enumerated constants on HomeSpan's Services and Characteristics page.
// Note the use of enumerated constants is optional - you can always use the integer code representing
// each state instead.
current=new Characteristic::CurrentDoorState(1); // initial value of 1 means closed
target=new Characteristic::TargetDoorState(1); // initial value of 1 means closed
obstruction=new Characteristic::ObstructionDetected(false); // initial value of false means NO obstruction is detected
current=new Characteristic::CurrentDoorState(Characteristic::CurrentDoorState::CLOSED); // here we use the fully-qualified name of the constant "CLOSED"
target=new Characteristic::TargetDoorState(target->CLOSED); // here we use the name of the object instead of the fully-qualified name (much less typing)
// Below we must use the fully-qualified name of the enumerated constant and cannot use "obstruction->NOT_DETECTED".
// Why? Because above we declared "obstruction" to be a pointer to a generic SpanCharacteristic instead of a pointer to
// the more specific Characteristic::ObstructionDetected. Either is fine, and it's just a matter of programming preference
// (as you can see we use both conventions in this sketch). But the downside of using SpanCharacteristic to declare a
// Characteristic that contains enumerated constants is that the object itself does not know about these constants. This is
// because all enumerated constants are uniquely defined within their respective specific Characteristic classes, and not in the
// generic SpanCharacteristic class from which all specific Characterstics are derived.
obstruction=new Characteristic::ObstructionDetected(Characteristic::ObstructionDetected::NOT_DETECTED); // this works
// obstruction=new Characteristic::ObstructionDetected(obstruction->NOT_DETECTED); // this would produce a compiler error (try it and see)
Serial.print("Configuring Garage Door Opener"); // initialization message
Serial.print("\n");
@ -24,13 +40,13 @@ struct DEV_GarageDoor : Service::GarageDoorOpener { // A Garage Door Opener
// see HAP Documentation for details on what each value represents
if(target->getNewVal()==0){ // if the target-state value is set to 0, HomeKit is requesting the door to be in open position
if(target->getNewVal()==target->OPEN){ // HomeKit is requesting the door to be in OPEN position
LOG1("Opening Garage Door\n");
current->setVal(2); // set the current-state value to 2, which means "opening"
obstruction->setVal(false); // clear any prior obstruction detection
current->setVal(current->OPENING); // set the current-state value to OPENING
obstruction->setVal(false); // clear any prior obstruction detection - note we do not bother using an enumerated constant here
} else {
LOG1("Closing Garage Door\n"); // else the target-state value is set to 1, and HomeKit is requesting the door to be in the closed position
current->setVal(3); // set the current-state value to 3, which means "closing"
LOG1("Closing Garage Door\n"); // else HomeKit must be requesting the door to be in the CLOSED position
current->setVal(current->CLOSING); // set the current-state value to CLOSING
obstruction->setVal(false); // clear any prior obstruction detection
}
@ -43,13 +59,13 @@ struct DEV_GarageDoor : Service::GarageDoorOpener { // A Garage Door Opener
if(current->getVal()==target->getVal()) // if current-state matches target-state there is nothing do -- exit loop()
return;
if(current->getVal()==3 && random(100000)==0){ // here we simulate a random obstruction, but only if the door is closing (not opening)
current->setVal(4); // if our simulated obstruction is triggered, set the curent-state to 4, which means "stopped"
obstruction->setVal(true); // and set obstruction-detected to true
if(current->getVal()==current->CLOSING && random(100000)==0){ // here we simulate a random obstruction, but only if the door is closing (not opening)
current->setVal(current->STOPPED); // if our simulated obstruction is triggered, set the curent-state to STOPPED
obstruction->setVal(true); // and set obstruction-detected to true
LOG1("Garage Door Obstruction Detected!\n");
}
if(current->getVal()==4) // if the current-state is stopped, there is nothing more to do - exit loop()
if(current->getVal()==current->STOPPED) // if the current-state is stopped, there is nothing more to do - exit loop()
return;
// This last bit of code only gets called if the door is in a state that represents actively opening or actively closing.
@ -83,15 +99,6 @@ struct DEV_WindowShade : Service::WindowCovering { // A motorized Window Sha
boolean update(){ // update() method
// The logic below is based on how HomeKit appears to operate in practice, which is NOT consistent with
// HAP documentation. In that document HomeKit seems to support fully opening or fully closing a window shade, with
// an optional control to HOLD the window shade at a given in-between position while it is moving.
// In practice, HomeKit does not appear to implement any form of a HOLD control button, even if you instantiate that
// Characteristic. Instead, HomeKit provides a full slider control, similar to the brightness control for a lightbulb,
// that allows you to set the exact position of the window shade from 0-100%. This obviates the need to any sort of HOLD button.
// The resulting logic is also very simple:
if(target->getNewVal()>current->getVal()){ // if the target-position requested is greater than the current-position, simply log a "raise" message
LOG1("Raising Shade\n"); // ** there is nothing more to do - HomeKit keeps track of the current-position so knows raising is required
} else
@ -116,10 +123,7 @@ struct DEV_WindowShade : Service::WindowCovering { // A motorized Window Sha
// the user in the Home App. If it finds current and target positions are the same, it knows the shade is stopped. Otherwise
// it will report the shade is raising or lowering depending on whether the specified target state is greater or less than
// the current state.
// According to HAP, the Characteristic Position State is also required. However, this seems duplicative and is NOT needed
// at all given the way HomeKit uses current position.
} // loop
};

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*
@ -40,7 +40,7 @@
void setup() {
// Though HomeKit and the HomeKit Accessory Protocol (HAP) Specification provide a very flexible framework
// for creating iOS- and MacOS-controlled devices, they does not contain every possible desired feature.
// for creating iOS- and MacOS-controlled devices, they do not contain every possible desired feature.
//
// One very common Characteristic HomeKit does not seem to contain is a simple pushbutton, like the type you
// would find on a remote control. Unlike switches that can be "on" or "off", a pushbutton has no state.

View File

@ -87,10 +87,3 @@ struct DEV_Blinker : Service::LightBulb { // LED Blinker
};
//////////////////////////////////
// HomeKit Bug Note: There is an apparent bug in HomeKit uncovered during the development of this example.
// If you have an Accessory with three or more Services, and the Accessory receives a notification message
// from the device, AND the HomeKit interface is open to show the detailed control for this Service tile
// in the HomeKit app, then for some reason HomeKit sends an update() request back to the device asking to
// set the Characteristic to the value that it just received from an Event Notification. HomeKit is not supposed
// to send update requests in response to an Event Notification.

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*
@ -113,7 +113,7 @@ struct Shower : Service::Faucet { // this is our Shower structur
struct WaterValve : Service::Valve { // here we define our WaterValve structure as a child class of the HomeSpan Valve Service
SpanCharacteristic *active=new Characteristic::Active(1);; // the Active Characteristic is used to specify whether the Valve is Active (open) or Inactive (closed)
SpanCharacteristic *inUse=new Characteristic::InUse(); // the InUser Characteristic is used to specify whether water is actually flowing through value
SpanCharacteristic *inUse=new Characteristic::InUse(); // the InUse Characteristic is used to specify whether water is actually flowing through value
Shower *shower; // storage for the pointer to the "controlling" Shower Service
WaterValve(Shower *s){ // this is constructor for WaterValve. It takes a single argument that points to the "controlling" Shower Service

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2021-2022 Gregg E. Berman
* Copyright (c) 2021-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2022 Gregg E. Berman
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*

View File

@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2022 Gregg E. Berman
* Copyright (c) 2022-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*
@ -123,7 +123,7 @@ void addLight(int n){
char name[32];
sprintf(name,"Light-%d",n); // create the name of the device using the specified "ID"
char sNum[32];
sprintf(sNum,"%0.10d",n); // create serial number from the ID - this is helpful in case we rename the Light to something else using the Home App
sprintf(sNum,"%010d",n); // create serial number from the ID - this is helpful in case we rename the Light to something else using the Home App
Serial.printf("Adding Accessory: %s\n",name);

View File

@ -0,0 +1,173 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
********************************************************************************/
////////////////////////////////////////////////////////////
// //
// HomeSpan: A HomeKit implementation for the ESP32 //
// ------------------------------------------------ //
// //
// Example 21: Using the Identify Characteristic //
// //
// //
////////////////////////////////////////////////////////////
// This sketch is similar to Example 5, in which we implemented two simple Lightbulb Accessories,
// except now we will also add functionality for the Identify Characteristic (we will also configure
// the device as a Bridge Accessory, instead of two standalone Accessories).
// Recall that the Identify Characteristic has been instantiated in every example sketch since it
// is a required Characteristic of the AccessoryInformation Service, and that Service is itself
// required to be present for every Accessory. Thus, every Accessory (including the Bridge
// Accessory if used), has its own instant of the Identify Characteristic.
// Though not typically used during normal operation of an Accessory, the Identify Characteristic
// can be useful when first pairing your device to HomeKit. You may have noticed when pairing your
// device using the Home App that there is the word "Identify" at the bottom of each of the screens
// that ask you what you want to name each Accessory, what room the Accessory should be assigned to, etc.
// Clicking "Identify" on any of those screens causes HomeKit to send an update request to the
// Identify Characteristic associated with the corresponding Accessory. As with any Characteristic that
// is updated via the Home App, this will trigger a call to the update() method for the enclosing Service.
// The purpose of this is so that your device can run some sort of "identification routine" when requested,
// allowing you to visually confirm that you are indeed pairing the correct device. For example, if you
// have three separate devices wired to three different lights or appliances, you want to make sure that when
// you start pairing each of them to the Home App you are connected to the device you intend.
// The identification routine can be anything you choose. The only HAP requirement is that it should not take
// longer than 5 seconds to run. In the sketch below we have created an identification routine that logs a
// message to the Serial Monitor and blinks the LED associated with the Accessory 3 times whenever its
// Identify Characteristic is updated.
#include "HomeSpan.h"
//////////////////////////////////////
// Below is the same DEV_LED Lightbulb Service we've used in many of the previous examples
struct DEV_LED : Service::LightBulb {
int ledPin;
SpanCharacteristic *power;
DEV_LED(int ledPin) : Service::LightBulb(){
power=new Characteristic::On();
this->ledPin=ledPin;
pinMode(ledPin,OUTPUT);
}
boolean update(){
digitalWrite(ledPin,power->getNewVal());
LOG0("LED %d: Power %s\n",ledPin,power->getNewVal()?"ON":"OFF");
return(true);
}
};
//////////////////////////////////////
// NEW: Here we derive a new class, DEV_INFO, from the Accessory Information Service
// This structure takes a single argument (ledPin), creates a name from it, and assigns
// it to the Name Characteristic.
// It also instantiates the required Identify Characteristic, and implements an update() method
// that logs a message to the Serial Monitor and blinks the associated LED three times.
// Note that in the update() method we do not bother to check which Characteristic has been updated.
// This is because the only possibility is the Identify Characteristic.
// Also, we do not need to use getNewVal() to check the value. The Home App always sends a value of 1,
// since it is just trying to trigger the identification routine (the value itself is meaningless).
struct DEV_INFO : Service::AccessoryInformation {
int ledPin;
DEV_INFO(int ledPin) : Service::AccessoryInformation(){
new Characteristic::Identify();
char c[64];
sprintf(c,"LED-%d",ledPin);
new Characteristic::Name(c);
this->ledPin=ledPin;
pinMode(ledPin,OUTPUT);
}
boolean update(){
LOG0("Running Identification for LED %d\n",ledPin);
for(int i=0;i<3;i++){
digitalWrite(ledPin,HIGH);
delay(500);
digitalWrite(ledPin,LOW);
delay(500);
}
return(true);
}
};
//////////////////////////////////////
void setup() {
Serial.begin(115200);
homeSpan.setLogLevel(1);
homeSpan.begin(Category::Lighting,"HomeSpan LEDS");
// Here we replace the usual construct:
// new SpanAccessory();
// new Service::AccessoryInformation();
// new Characteristic::Identify();
// with this:
new SpanAccessory();
new DEV_INFO(13); // instantiate a new DEV_INFO structure that will run our custom identification routine to blink an LED on pin 13 three times
new SpanAccessory();
new DEV_INFO(16); // Note we instantiate a new DEV_INFO structure for each Accessory in this device
new DEV_LED(16); // Here we instantiate the usual DEV_LED structure that controls the LED during normal operation
new SpanAccessory(); // Here we add a second LED Accessory
new DEV_INFO(17);
new DEV_LED(17);
}
//////////////////////////////////////
void loop(){
homeSpan.poll();
}
//////////////////////////////////////
// NOTE: Once a device has been paired, it is no longer possible to trigger the Identify Characteristic from the Home App.
// Apple assumes that the identification routine is no longer needed since you can always identify the device by simply operating it.
// However, the Eve for HomeKit app DOES provide an "ID" button in the interface for each Accessory that can be used to trigger
// the identification routine for that Accessory at any time after the device has been paired.

View File

@ -0,0 +1,159 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
********************************************************************************/
////////////////////////////////////////////////////////////////
// //
// HomeSpan: A HomeKit implementation for the ESP32 //
// ------------------------------------------------ //
// //
// Example 22: Demonstrates the use of the TLV8 Library //
// by implementing DisplayOrder, an optional //
// TLV8 Characteristic used with the TV Service //
// to set the order in which TV Inputs are //
// displayed for selection in the Home App //
// //
////////////////////////////////////////////////////////////////
#include "HomeSpan.h"
// NOTE: Please see the "Other Examples -> Television" sketch for complete details on how to implement a Television Service. The focus
// of this sketch is solely to demonstrate how to use the TLV8 Library to create TLV8 data for use with the DisplayOrder Characteristic.
// First we define a simple Television Input Source Service
struct TVInput : Service::InputSource {
SpanCharacteristic *inputID;
SpanCharacteristic *inputName;
TVInput(uint32_t id, const char *name) : Service::InputSource() {
inputID = new Characteristic::Identifier(id);
inputName = new Characteristic::ConfiguredName(name);
new Characteristic::IsConfigured(Characteristic::IsConfigured::CONFIGURED);
new Characteristic::CurrentVisibilityState(Characteristic::CurrentVisibilityState::VISIBLE);
}
};
// Next we define a simple Television Service
struct HomeSpanTV : Service::Television {
SpanCharacteristic *active = new Characteristic::Active(0);
SpanCharacteristic *activeID = new Characteristic::ActiveIdentifier(10);
SpanCharacteristic *displayOrder; // Create a pointer to use for the new TLV8 DisplayOrder Characteristic, which will be instantiated below once we build the TLV8 record
HomeSpanTV() : Service::Television() {
// Before we instantiate displayOrder, we need to build a TLV8 object with the information required
// by the DisplayOrder Characteristic. The (undocumented by Apple!) TLV8 specifications for the
// DisplayOrder Characteristic are as follows:
// TAG NAME FORMAT DESCRIPTION
// ---- ------------- ------ --------------------------------------------
// 0x01 inputSourceID uint32 ID of the Input Source to be displayed first
// 0x00 separator none Empty element to separate the inputSourceIDs
// 0x01 inputSourceID uint32 ID of the Input Source to be displayed second
// 0x00 separator none Empty element to separate the inputSourceIDs
// 0x01 inputSourceID uint32 ID of the Input Source to be displayed third
// 0x00 separator none Empty element to separate the inputSourceIDs
// etc...
// To start, instantiate a new TLV8 object
TLV8 orderTLV; // creates an empty TLV8 object
// Next, fill it with TAGS and VALUES based on the above specification. The easiest, though
// not necessarily most elegant, way to do this is by simply adding each TAG/VALUE as follows:
orderTLV.add(1,10); // TAG=1, VALUE=ID of first Input Source to be displayed
orderTLV.add(0); // TAG=0 (no value)
orderTLV.add(1,20); // TAG=1, VALUE=ID of the second Input Source to be displayed
orderTLV.add(0); // TAG=0 (no value)
orderTLV.add(1,50); // TAG=1, VALUE=ID of the third Input Source to be displayed
orderTLV.add(0); // TAG=0 (no value)
orderTLV.add(1,30); // TAG=1, VALUE=ID of the fourth Input Source to be displayed
orderTLV.add(0); // TAG=0 (no value)
orderTLV.add(1,40); // TAG=1, VALUE=ID of the fifth Input Source to be displayed
// Based on the above structure, we expect the Home App to display our input sources based on their IDs
// in the following order: 10, 20, 50, 30, 40. These IDs must of course match the IDs you choose
// for your input sources when you create them at the end of this sketch in setup()
// Now we can instantiate displayOrder using the TLV8 object created above as its initial value
displayOrder = new Characteristic::DisplayOrder(orderTLV); // set the "value" of DisplayOrder to be the orderTLV object we just created
// That's it - you've created your first TLV8 Characteristic!
}
// Below we define the usual update() loop. There is nothing "TLV-specific" about this part of the code
boolean update() override {
if(active->updated()){
LOG0("Set TV Power to: %s\n",active->getNewVal()?"ON":"OFF");
}
if(activeID->updated()){
LOG0("Set Input Source to ID=%d\n",activeID->getNewVal());
}
return(true);
}
};
///////////////////////////////
void setup() {
Serial.begin(115200);
homeSpan.setLogLevel(2);
homeSpan.begin(Category::Television,"HomeSpan Television");
SPAN_ACCESSORY();
(new HomeSpanTV()) // Define a Television Service and link in the InputSources!
->addLink(new TVInput(10,"Xfinity"))
->addLink(new TVInput(20,"BlueRay Disc"))
->addLink(new TVInput(30,"Amazon Prime"))
->addLink(new TVInput(40,"Netflix"))
->addLink(new TVInput(50,"Hulu"))
;
}
//////////////////////////////////////
void loop(){
homeSpan.poll();
}
//////////////////////////////////////

View File

@ -76,7 +76,7 @@ struct NeoPixel_RGB : Service::LightBulb { // Addressable single-wire RGB L
NeoPixel_RGB(uint8_t pin, int nPixels) : Service::LightBulb(){
V.setRange(5,100,1); // sets the range of the Brightness to be from a min of 5%, to a max of 100%, in steps of 1%
pixel=new Pixel(pin); // creates Pixel LED on specified pin
pixel=new Pixel(pin); // creates Pixel RGB LED on specified pin
this->nPixels=nPixels; // save number of Pixels in this LED Strand
update(); // manually call update() to set pixel with restored initial values
}
@ -110,7 +110,7 @@ struct NeoPixel_RGBW : Service::LightBulb { // Addressable single-wire RGBW
NeoPixel_RGBW(uint8_t pin, int nPixels) : Service::LightBulb(){
V.setRange(5,100,1); // sets the range of the Brightness to be from a min of 5%, to a max of 100%, in steps of 1%
pixel=new Pixel(pin,true); // creates Pixel RGBW LED (second parameter set to true for RGBW) on specified pin
pixel=new Pixel(pin,PixelType::GRBW); // creates Pixel RGBW LED on specified pin (with order of colors chnanged to reflect this specific NeoPixel device)
this->nPixels=nPixels; // save number of Pixels in this LED Strand
update(); // manually call update() to set pixel with restored initial values
}

View File

@ -0,0 +1,131 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
********************************************************************************/
/////////////////////// PIXEL TESTER //////////////////////////
// This sketch is designed to help identify the proper settings to use for a NeoPixel, NeoPixel Strip,
// or any device containing one or more single-wire addressable RGB or RGBW LEDs (the "Pixel Device").
// Before compiling, set PIXEL_PIN to the ESP32 pin that is connected to your Pixel Device, and set NPIXELS to
// the numnber of Pixels in the Pixel Device. Note that for some strips a single chip controls more than one LED,
// in which case NPIXELS should be set to the number of controlling chips, NOT the number of LEDs.
// To start, the second argument of the Pixel constructor for the testPixel object below should remain
// set to PixelType::RGBW
// When run, the sketch will repeatedly cycle colors by setting ALL pixels in the device first to RED, then GREEN,
// followed by BLUE, and then finally WHITE. After a short pause, the cycle repeats.
// For each color the brightness will increase from 0 through MAX_BRIGHTNESS, and then back to 0. You can change
// MAX_BRIGHTNESS to something lower than 255 if you want to limit how bright the pixels get.
// For Pixel Devices with more than one pixel, diagnostics are as follows:
//
// * If all 4 colors repeatedly flash in the order expected, this means the base setting of PixelType::RGBW is correct!
//
// * If instead of each pixel being set to the same color, the pixels in the strip each light up with a different color
// (or no color at all), this means you have an RGB LED, not an RGBW LED. Change the second parameter of the constructor
// to PixelType::RGB and re-run the sketch.
//
// * If all of the pixels are being set to the same color, but the sequence is NOT in the order RED, GREEN, BLUE, change
// the second parameter of the constructor so that the order of the PixelType colors match the sequence of the colors
// that appear on the Pixel Device. For example, if your RGBW Pixel Device flashes GREEN, RED, BLUE, and than WHITE, use
// PixelType::GRBW.
// For Pixel Devices with only a single pixel, diagnostics are as follows:
// * If all 4 colors repeatedly flash in the order expected, this means the base setting of PixelType::RGBW is correct!
//
// * If the pixel does not light at all when set to WHITE this means you have an RGB LED, not an RGBW LED. Change the
// second parameter of the constructor to PixelType::RGB and re-run the sketch.
//
// * If all of the pixels are being set to the same color, but the sequence is NOT in the order RED, GREEN, BLUE, change
// the second parameter of the constructor so that the order of the PixelType colors match the sequence of the colors
// that appear on the Pixel Device. For example, if your RGB Pixel Device flashes GREEN, RED, and then BLUE, use
// PixelType::GRB.
//////////////////////////////////////
#include "HomeSpan.h"
//////////////////////////////////////
#define MAX_BRIGHTNESS 255 // maximum brightness when flashing RGBW [0-255]
#define PIXEL_PIN 26 // set this to whatever pin you are using - note pin cannot be "input only"
#define NPIXELS 8 // set to number of pixels in strip
Pixel testPixel(PIXEL_PIN, PixelType::RGBW); // change the second argument until device operates with correct colors
//////////////////////////////////////
void setup() {
Serial.begin(115200);
delay(1000);
Serial.printf("\n\nPixel Test on pin %d with %d pixels\n\n",PIXEL_PIN,NPIXELS);
}
//////////////////////////////////////
void flashColor(boolean r, boolean g, boolean b, boolean w){
for(int i=0;i<MAX_BRIGHTNESS;i++){
testPixel.set(Pixel::RGB(i*r,i*g,i*b,i*w),NPIXELS);
delay(4);
}
for(int i=MAX_BRIGHTNESS;i>=0;i--){
testPixel.set(Pixel::RGB(i*r,i*g,i*b,i*w),NPIXELS);
delay(4);
}
}
//////////////////////////////////////
void loop(){
Serial.printf("Red...");
flashColor(1,0,0,0);
Serial.printf("Green...");
flashColor(0,1,0,0);
Serial.printf("Blue...");
flashColor(0,0,1,0);
if(testPixel.isRGBW()){
Serial.printf("White...");
flashColor(0,0,0,1);
}
Serial.printf("Pausing.\n");
delay(1000);
}
//////////////////////////////////////

View File

@ -1,5 +1,5 @@
name=HomeSpan
version=1.9.0
version=1.9.1
author=Gregg <homespan@icloud.com>
maintainer=Gregg <homespan@icloud.com>
sentence=A robust and extremely easy-to-use HomeKit implementation for the Espressif ESP32 running on the Arduino IDE.

View File

@ -49,22 +49,12 @@ enum FORMAT { // HAP Table 6-5
INT=5,
FLOAT=6,
STRING=7,
DATA=8
DATA=8,
TLV_ENC=9
};
///////////////////////////////
typedef boolean BOOL_t;
typedef uint8_t UINT8_t;
typedef uint16_t UINT16_t;
typedef uint32_t UINT32_t;
typedef uint64_t UINT64_t;
typedef int32_t INT_t;
typedef double FLOAT_t;
typedef char * STRING_t;
///////////////////////////////
struct HapChar {
const char *type;
const char *hapName;
@ -113,6 +103,7 @@ struct HapCharacteristics {
HAPCHAR( CurrentTemperature, 11, PR+EV, FLOAT, false );
HAPCHAR( CurrentTiltAngle, C1, PR+EV, INT, false );
HAPCHAR( CurrentVisibilityState, 135, PR+EV, UINT8, true );
HAPCHAR( DisplayOrder, 136, PR+EV, TLV_ENC, true );
HAPCHAR( FilterLifeLevel, AB, PR+EV, FLOAT, false );
HAPCHAR( FilterChangeIndication, AC, PR+EV, UINT8, true );
HAPCHAR( FirmwareRevision, 52, PR+EV, STRING, true );

View File

@ -24,6 +24,8 @@
* SOFTWARE.
*
********************************************************************************/
#include "version.h"
#include <ESPmDNS.h>
#include <sodium.h>
@ -38,9 +40,6 @@ void HAPClient::init(){
size_t len; // not used but required to read blobs from NVS
nvs_open("SRP",NVS_READWRITE,&srpNVS); // open SRP data namespace in NVS
nvs_open("HAP",NVS_READWRITE,&hapNVS); // open HAP data namespace in NVS
if(strlen(homeSpan.spanOTA.otaPwd)==0){ // OTA password has not been specified in sketch
if(!nvs_get_str(homeSpan.otaNVS,"OTADATA",NULL,&len)){ // if found OTA data in NVS...
nvs_get_str(homeSpan.otaNVS,"OTADATA",homeSpan.spanOTA.otaPwd,&len); // ...retrieve data.
@ -49,19 +48,19 @@ void HAPClient::init(){
}
}
if(nvs_get_blob(srpNVS,"VERIFYDATA",NULL,&len)) // if Pair-Setup verification code data not found in NVS
homeSpan.setPairingCode(DEFAULT_SETUP_CODE); // create and save verification from using Pairing Setup Code
if(!strlen(homeSpan.qrID)){ // is Setup ID has not been specified in sketch
if(!nvs_get_str(hapNVS,"SETUPID",NULL,&len)){ // check for saved value
nvs_get_str(hapNVS,"SETUPID",homeSpan.qrID,&len); // retrieve data
if(!strlen(homeSpan.qrID)){ // if Setup ID has not been specified in sketch
if(!nvs_get_str(homeSpan.hapNVS,"SETUPID",NULL,&len)){ // check for saved value
nvs_get_str(homeSpan.hapNVS,"SETUPID",homeSpan.qrID,&len); // retrieve data
} else {
sprintf(homeSpan.qrID,"%s",DEFAULT_QR_ID); // use default
}
}
if(nvs_get_blob(homeSpan.srpNVS,"VERIFYDATA",NULL,&len)) // if Pair-Setup verification code data not found in NVS
homeSpan.setPairingCode(DEFAULT_SETUP_CODE,false); // create and save verification from default Pairing Setup Code
if(!nvs_get_blob(hapNVS,"ACCESSORY",NULL,&len)){ // if found long-term Accessory data in NVS
nvs_get_blob(hapNVS,"ACCESSORY",&accessory,&len); // retrieve data
if(!nvs_get_blob(homeSpan.hapNVS,"ACCESSORY",NULL,&len)){ // if found long-term Accessory data in NVS
nvs_get_blob(homeSpan.hapNVS,"ACCESSORY",&accessory,&len); // retrieve data
} else {
LOG0("Generating new random Accessory ID and Long-Term Ed25519 Signature Keys...\n\n");
uint8_t buf[6];
@ -74,13 +73,13 @@ void HAPClient::init(){
memcpy(accessory.ID,cBuf,17); // copy into Accessory ID for permanent storage
crypto_sign_keypair(accessory.LTPK,accessory.LTSK); // generate new random set of keys using libsodium public-key signature
nvs_set_blob(hapNVS,"ACCESSORY",&accessory,sizeof(accessory)); // update data
nvs_commit(hapNVS); // commit to NVS
nvs_set_blob(homeSpan.hapNVS,"ACCESSORY",&accessory,sizeof(accessory)); // update data
nvs_commit(homeSpan.hapNVS); // commit to NVS
}
if(!nvs_get_blob(hapNVS,"CONTROLLERS",NULL,&len)){ // if found long-term Controller Pairings data from NVS
if(!nvs_get_blob(homeSpan.hapNVS,"CONTROLLERS",NULL,&len)){ // if found long-term Controller Pairings data from NVS
TempBuffer<Controller> tBuf(len/sizeof(Controller));
nvs_get_blob(hapNVS,"CONTROLLERS",tBuf,&len); // retrieve data
nvs_get_blob(homeSpan.hapNVS,"CONTROLLERS",tBuf,&len); // retrieve data
for(int i=0;i<tBuf.size();i++){
if(tBuf[i].allocated)
controllerList.push_back(tBuf[i]);
@ -95,12 +94,12 @@ void HAPClient::init(){
printControllers();
if(!nvs_get_blob(hapNVS,"HAPHASH",NULL,&len)){ // if found HAP HASH structure
nvs_get_blob(hapNVS,"HAPHASH",&homeSpan.hapConfig,&len); // retrieve data
if(!nvs_get_blob(homeSpan.hapNVS,"HAPHASH",NULL,&len)){ // if found HAP HASH structure
nvs_get_blob(homeSpan.hapNVS,"HAPHASH",&homeSpan.hapConfig,&len); // retrieve data
} else {
LOG0("Resetting Database Hash...\n");
nvs_set_blob(hapNVS,"HAPHASH",&homeSpan.hapConfig,sizeof(homeSpan.hapConfig)); // save data (will default to all zero values, which will then be updated below)
nvs_commit(hapNVS); // commit to NVS
nvs_set_blob(homeSpan.hapNVS,"HAPHASH",&homeSpan.hapConfig,sizeof(homeSpan.hapConfig)); // save data (will default to all zero values, which will then be updated below)
nvs_commit(homeSpan.hapNVS); // commit to NVS
}
if(homeSpan.updateDatabase(false)){ // create Configuration Number and Loop vector
@ -316,6 +315,8 @@ int HAPClient::unauthorizedError(){
int HAPClient::postPairSetupURL(uint8_t *content, size_t len){
static SRP6A *srp=NULL; // must persist across multiple calls to postPairSetupURL
HAPTLV iosTLV;
HAPTLV responseTLV;
HAPTLV subTLV;
@ -325,7 +326,7 @@ int HAPClient::postPairSetupURL(uint8_t *content, size_t len){
iosTLV.print();
LOG2("------------ END TLVS! ------------\n");
LOG1("In Pair Setup #%d (%s)...",conNum,client.remoteIP().toString().c_str());
LOG1("In Pair Setup #%d (%s)...",clientNumber,client.remoteIP().toString().c_str());
auto itState=iosTLV.find(kTLVType_State);
@ -335,7 +336,7 @@ int HAPClient::postPairSetupURL(uint8_t *content, size_t len){
return(0);
}
int tlvState=(*itState)[0];
int tlvState=itState->getVal();
if(nAdminControllers()){ // error: Device already paired (i.e. there is at least one admin Controller). We should not be receiving any requests for Pair-Setup!
LOG0("\n*** ERROR: Device already paired!\n\n");
@ -345,7 +346,7 @@ int HAPClient::postPairSetupURL(uint8_t *content, size_t len){
return(0);
};
LOG2("Found <M%d>. Expected <M%d>.\n",tlvState,pairStatus);
LOG1("Found <M%d>. Expected <M%d>.\n",tlvState,pairStatus);
if(tlvState!=pairStatus){ // error: Device is not yet paired, but out-of-sequence pair-setup STATE was received
LOG0("\n*** ERROR: Out-of-Sequence Pair-Setup request!\n\n");
@ -364,7 +365,7 @@ int HAPClient::postPairSetupURL(uint8_t *content, size_t len){
auto itMethod=iosTLV.find(kTLVType_Method);
if(iosTLV.len(itMethod)!=1 || (*itMethod)[0]!=0){ // error: "Pair Setup" method must always be 0 to indicate setup without MiFi Authentification (HAP Table 5-3)
if(iosTLV.len(itMethod)!=1 || itMethod->getVal()!=0){ // error: "Pair Setup" method must always be 0 to indicate setup without MiFi Authentification (HAP Table 5-3)
LOG0("\n*** ERROR: Pair 'Method' missing or not set to 0\n\n");
responseTLV.add(kTLVType_Error,tagError_Unavailable); // set Error=Unavailable
tlvRespond(responseTLV); // send response to client
@ -378,7 +379,7 @@ int HAPClient::postPairSetupURL(uint8_t *content, size_t len){
TempBuffer<Verification> verifyData; // retrieve verification data (should already be stored in NVS)
size_t len=verifyData.len();
nvs_get_blob(srpNVS,"VERIFYDATA",verifyData,&len);
nvs_get_blob(homeSpan.srpNVS,"VERIFYDATA",verifyData,&len);
responseTLV.add(kTLVType_Salt,16,verifyData.get()->salt); // write Salt from verification data into TLV
@ -405,7 +406,7 @@ int HAPClient::postPairSetupURL(uint8_t *content, size_t len){
return(0);
};
srp->createSessionKey(*itPublicKey,(*itPublicKey).len); // create session key, K, from client Public Key, A
srp->createSessionKey(*itPublicKey,itPublicKey->getLen()); // create session key, K, from client Public Key, A
if(!srp->verifyClientProof(*itClientProof)){ // verify client Proof, M1
LOG0("\n*** ERROR: SRP Proof Verification Failed\n\n");
@ -448,16 +449,15 @@ int HAPClient::postPairSetupURL(uint8_t *content, size_t len){
// Note the SALT and INFO text fields used by HKDF to create this Session Key are NOT the same as those for creating iosDeviceX.
// The iosDeviceX HKDF calculations are separate and will be performed further below with the SALT and INFO as specified in the HAP docs.
TempBuffer<uint8_t> sessionKey(crypto_box_PUBLICKEYBYTES); // temporary space - used only in this block
hkdf.create(sessionKey,srp->K,64,"Pair-Setup-Encrypt-Salt","Pair-Setup-Encrypt-Info"); // create SessionKey
HKDF::create(temp.sessionKey,srp->K,64,"Pair-Setup-Encrypt-Salt","Pair-Setup-Encrypt-Info"); // create SessionKey
LOG2("------- DECRYPTING SUB-TLVS -------\n");
// use SessionKey to decrypt encryptedData TLV with padded nonce="PS-Msg05"
TempBuffer<uint8_t> decrypted((*itEncryptedData).len-crypto_aead_chacha20poly1305_IETF_ABYTES); // temporary storage for decrypted data
TempBuffer<uint8_t> decrypted(itEncryptedData->getLen()-crypto_aead_chacha20poly1305_IETF_ABYTES); // temporary storage for decrypted data
if(crypto_aead_chacha20poly1305_ietf_decrypt(decrypted, NULL, NULL, *itEncryptedData, (*itEncryptedData).len, NULL, 0, (unsigned char *)"\x00\x00\x00\x00PS-Msg05", sessionKey)==-1){
if(crypto_aead_chacha20poly1305_ietf_decrypt(decrypted, NULL, NULL, *itEncryptedData, itEncryptedData->getLen(), NULL, 0, (unsigned char *)"\x00\x00\x00\x00PS-Msg05", temp.sessionKey)==-1){
LOG0("\n*** ERROR: Exchange-Request Authentication Failed\n\n");
responseTLV.add(kTLVType_Error,tagError_Authentication); // set Error=Authentication
tlvRespond(responseTLV); // send response to client
@ -489,11 +489,11 @@ int HAPClient::postPairSetupURL(uint8_t *content, size_t len){
// Note that the SALT and INFO text fields now match those in HAP Section 5.6.6.1
TempBuffer<uint8_t> iosDeviceX(32);
hkdf.create(iosDeviceX,srp->K,64,"Pair-Setup-Controller-Sign-Salt","Pair-Setup-Controller-Sign-Info"); // derive iosDeviceX (32 bytes) from SRP Shared Secret using HKDF
HKDF::create(iosDeviceX,srp->K,64,"Pair-Setup-Controller-Sign-Salt","Pair-Setup-Controller-Sign-Info"); // derive iosDeviceX (32 bytes) from SRP Shared Secret using HKDF
// Concatenate iosDeviceX, IOS ID, and IOS PublicKey into iosDeviceInfo
TempBuffer<uint8_t> iosDeviceInfo(iosDeviceX,iosDeviceX.len(),(*itIdentifier).val.get(),(*itIdentifier).len,(*itPublicKey).val.get(),(*itPublicKey).len,NULL);
TempBuffer<uint8_t> iosDeviceInfo(iosDeviceX,iosDeviceX.len(),(uint8_t *)(*itIdentifier),itIdentifier->getLen(),(uint8_t *)(*itPublicKey),itPublicKey->getLen(),NULL);
if(crypto_sign_verify_detached(*itSignature, iosDeviceInfo, iosDeviceInfo.len(), *itPublicKey) != 0){ // verify signature of iosDeviceInfo using iosDeviceLTPK
LOG0("\n*** ERROR: LPTK Signature Verification Failed\n\n");
@ -508,7 +508,7 @@ int HAPClient::postPairSetupURL(uint8_t *content, size_t len){
// Now perform the above steps in reverse to securely transmit the AccessoryLTPK to the Controller (HAP Section 5.6.6.2)
TempBuffer<uint8_t> accessoryX(32);
hkdf.create(accessoryX,srp->K,64,"Pair-Setup-Accessory-Sign-Salt","Pair-Setup-Accessory-Sign-Info"); // derive accessoryX from SRP Shared Secret using HKDF
HKDF::create(accessoryX,srp->K,64,"Pair-Setup-Accessory-Sign-Salt","Pair-Setup-Accessory-Sign-Info"); // derive accessoryX from SRP Shared Secret using HKDF
// Concatenate accessoryX, Accessory ID, and Accessory PublicKey into accessoryInfo
@ -535,13 +535,14 @@ int HAPClient::postPairSetupURL(uint8_t *content, size_t len){
itEncryptedData=responseTLV.add(kTLVType_EncryptedData,subPack.len()+crypto_aead_chacha20poly1305_IETF_ABYTES,NULL); //create blank EncryptedData TLV with space for subTLV + Authentication Tag
crypto_aead_chacha20poly1305_ietf_encrypt(*itEncryptedData,NULL,subPack,subPack.len(),NULL,0,NULL,(unsigned char *)"\x00\x00\x00\x00PS-Msg06",sessionKey);
crypto_aead_chacha20poly1305_ietf_encrypt(*itEncryptedData,NULL,subPack,subPack.len(),NULL,0,NULL,(unsigned char *)"\x00\x00\x00\x00PS-Msg06",temp.sessionKey);
LOG2("---------- END SUB-TLVS! ----------\n");
tlvRespond(responseTLV); // send response to client
delete srp; // delete SRP - no longer needed once pairing is completed
srp=NULL; // reset to NULL
mdns_service_txt_item_set("_hap","_tcp","sf","0"); // broadcast new status
@ -575,7 +576,7 @@ int HAPClient::postPairVerifyURL(uint8_t *content, size_t len){
iosTLV.print();
LOG2("------------ END TLVS! ------------\n");
LOG1("In Pair Verify #%d (%s)...",conNum,client.remoteIP().toString().c_str());
LOG1("In Pair Verify #%d (%s)...",clientNumber,client.remoteIP().toString().c_str());
auto itState=iosTLV.find(kTLVType_State);
@ -585,7 +586,7 @@ int HAPClient::postPairVerifyURL(uint8_t *content, size_t len){
return(0);
}
int tlvState=(*itState)[0];
int tlvState=itState->getVal();
if(!nAdminControllers()){ // error: Device not yet paired - we should not be receiving any requests for Pair-Verify!
LOG0("\n*** ERROR: Device not yet paired!\n\n");
@ -595,7 +596,7 @@ int HAPClient::postPairVerifyURL(uint8_t *content, size_t len){
return(0);
};
LOG2("Found <M%d>\n",tlvState); // unlike pair-setup, out-of-sequencing can be handled gracefully for pair-verify (HAP requirement). No need to keep track of pairStatus
LOG1("Found <M%d>\n",tlvState); // unlike pair-setup, out-of-sequencing can be handled gracefully for pair-verify (HAP requirement). No need to keep track of pairStatus
switch(tlvState){ // Pair-Verify STATE received -- process request! (HAP Section 5.7)
@ -611,16 +612,14 @@ int HAPClient::postPairVerifyURL(uint8_t *content, size_t len){
return(0);
}
publicCurveKey=(uint8_t *)HS_MALLOC(crypto_box_PUBLICKEYBYTES); // temporary space - will be deleted at end of verification process
TempBuffer<uint8_t> secretCurveKey(crypto_box_SECRETKEYBYTES); // temporary space - used only in this block
crypto_box_keypair(publicCurveKey,secretCurveKey); // generate Accessory's random Curve25519 Public/Secret Key Pair
crypto_box_keypair(temp.publicCurveKey,secretCurveKey); // generate Accessory's random Curve25519 Public/Secret Key Pair
iosCurveKey=(uint8_t *)HS_MALLOC(crypto_box_PUBLICKEYBYTES); // temporary space - will be deleted at end of verification process
memcpy(iosCurveKey,*itPublicKey,crypto_box_PUBLICKEYBYTES); // save Controller's Curve25519 Public Key
memcpy(temp.iosCurveKey,*itPublicKey,crypto_box_PUBLICKEYBYTES); // save Controller's Curve25519 Public Key
// concatenate Accessory's Curve25519 Public Key, Accessory's Pairing ID, and Controller's Curve25519 Public Key into accessoryInfo
TempBuffer<uint8_t> accessoryInfo(publicCurveKey,crypto_box_PUBLICKEYBYTES,accessory.ID,hap_accessory_IDBYTES,iosCurveKey,crypto_box_PUBLICKEYBYTES,NULL);
TempBuffer<uint8_t> accessoryInfo(temp.publicCurveKey,crypto_box_PUBLICKEYBYTES,accessory.ID,hap_accessory_IDBYTES,temp.iosCurveKey,crypto_box_PUBLICKEYBYTES,NULL);
subTLV.add(kTLVType_Identifier,hap_accessory_IDBYTES,accessory.ID); // set Identifier subTLV record as Accessory's Pairing ID
auto itSignature=subTLV.add(kTLVType_Signature,crypto_sign_BYTES,NULL); // create blank Signature subTLV
@ -634,19 +633,17 @@ int HAPClient::postPairVerifyURL(uint8_t *content, size_t len){
TempBuffer<uint8_t> subPack(subTLV.pack_size()); // create sub-TLV by packing Identifier and Signature TLV records together
subTLV.pack(subPack);
sharedCurveKey=(uint8_t *)HS_MALLOC(crypto_box_PUBLICKEYBYTES); // temporary space - will be deleted at end of verification process
crypto_scalarmult_curve25519(sharedCurveKey,secretCurveKey,iosCurveKey); // generate Shared-Secret Curve25519 Key from Accessory's Curve25519 Secret Key and Controller's Curve25519 Public Key
crypto_scalarmult_curve25519(temp.sharedCurveKey,secretCurveKey,temp.iosCurveKey); // generate Shared-Secret Curve25519 Key from Accessory's Curve25519 Secret Key and Controller's Curve25519 Public Key
sessionKey=(uint8_t *)HS_MALLOC(crypto_box_PUBLICKEYBYTES); // temporary space - will be deleted at end of verification process
hkdf.create(sessionKey,sharedCurveKey,crypto_box_PUBLICKEYBYTES,"Pair-Verify-Encrypt-Salt","Pair-Verify-Encrypt-Info"); // create Session Curve25519 Key from Shared-Secret Curve25519 Key using HKDF-SHA-512
HKDF::create(temp.sessionKey,temp.sharedCurveKey,crypto_box_PUBLICKEYBYTES,"Pair-Verify-Encrypt-Salt","Pair-Verify-Encrypt-Info"); // create Session Curve25519 Key from Shared-Secret Curve25519 Key using HKDF-SHA-512
auto itEncryptedData=responseTLV.add(kTLVType_EncryptedData,subPack.len()+crypto_aead_chacha20poly1305_IETF_ABYTES,NULL); // create blank EncryptedData subTLV
crypto_aead_chacha20poly1305_ietf_encrypt(*itEncryptedData,NULL,subPack,subPack.len(),NULL,0,NULL,(unsigned char *)"\x00\x00\x00\x00PV-Msg02",sessionKey); // encrypt data with Session Curve25519 Key and padded nonce="PV-Msg02"
auto itEncryptedData=responseTLV.add(kTLVType_EncryptedData,subPack.len()+crypto_aead_chacha20poly1305_IETF_ABYTES,NULL); // create blank EncryptedData subTLV
crypto_aead_chacha20poly1305_ietf_encrypt(*itEncryptedData,NULL,subPack,subPack.len(),NULL,0,NULL,(unsigned char *)"\x00\x00\x00\x00PV-Msg02",temp.sessionKey); // encrypt data with Session Curve25519 Key and padded nonce="PV-Msg02"
LOG2("---------- END SUB-TLVS! ----------\n");
responseTLV.add(kTLVType_State,pairState_M2); // set State=<M2>
responseTLV.add(kTLVType_PublicKey,crypto_box_PUBLICKEYBYTES,publicCurveKey); // set PublicKey to Accessory's Curve25519 Public Key
responseTLV.add(kTLVType_PublicKey,crypto_box_PUBLICKEYBYTES,temp.publicCurveKey); // set PublicKey to Accessory's Curve25519 Public Key
tlvRespond(responseTLV); // send response to client
}
@ -668,9 +665,9 @@ int HAPClient::postPairVerifyURL(uint8_t *content, size_t len){
// use Session Curve25519 Key (from previous step) to decrypt encrypytedData TLV with padded nonce="PV-Msg03"
TempBuffer<uint8_t> decrypted((*itEncryptedData).len-crypto_aead_chacha20poly1305_IETF_ABYTES); // temporary storage for decrypted data
TempBuffer<uint8_t> decrypted((*itEncryptedData).getLen()-crypto_aead_chacha20poly1305_IETF_ABYTES); // temporary storage for decrypted data
if(crypto_aead_chacha20poly1305_ietf_decrypt(decrypted, NULL, NULL, *itEncryptedData, (*itEncryptedData).len, NULL, 0, (unsigned char *)"\x00\x00\x00\x00PV-Msg03", sessionKey)==-1){
if(crypto_aead_chacha20poly1305_ietf_decrypt(decrypted, NULL, NULL, *itEncryptedData, itEncryptedData->getLen(), NULL, 0, (unsigned char *)"\x00\x00\x00\x00PV-Msg03", temp.sessionKey)==-1){
LOG0("\n*** ERROR: Verify Authentication Failed\n\n");
responseTLV.add(kTLVType_State,pairState_M4); // set State=<M4>
responseTLV.add(kTLVType_Error,tagError_Authentication); // set Error=Authentication
@ -698,9 +695,9 @@ int HAPClient::postPairVerifyURL(uint8_t *content, size_t len){
Controller *tPair; // temporary pointer to Controller
if(!(tPair=findController(*itIdentifier))){
LOG0("\n*** ERROR: Unrecognized Controller ID: ");
charPrintRow(*itIdentifier,hap_controller_IDBYTES,2);
LOG0("\n\n");
LOG1("\n*** WARNING: Unrecognized Controller ID: ");
charPrintRow(*itIdentifier,hap_controller_IDBYTES,1);
LOG1("\n\n");
responseTLV.add(kTLVType_State,pairState_M4); // set State=<M4>
responseTLV.add(kTLVType_Error,tagError_Authentication); // set Error=Authentication
tlvRespond(responseTLV); // send response to client
@ -713,7 +710,7 @@ int HAPClient::postPairVerifyURL(uint8_t *content, size_t len){
// concatenate Controller's Curve25519 Public Key (from previous step), Controller's Pairing ID, and Accessory's Curve25519 Public Key (from previous step) into iosDeviceInfo
TempBuffer<uint8_t> iosDeviceInfo(iosCurveKey,crypto_box_PUBLICKEYBYTES,tPair->ID,hap_controller_IDBYTES,publicCurveKey,crypto_box_PUBLICKEYBYTES,NULL);
TempBuffer<uint8_t> iosDeviceInfo(temp.iosCurveKey,crypto_box_PUBLICKEYBYTES,tPair->ID,hap_controller_IDBYTES,temp.publicCurveKey,crypto_box_PUBLICKEYBYTES,NULL);
if(crypto_sign_verify_detached(*itSignature, iosDeviceInfo, iosDeviceInfo.len(), tPair->LTPK) != 0){ // verify signature of iosDeviceInfo using Controller's LTPK
LOG0("\n*** ERROR: LPTK Signature Verification Failed\n\n");
@ -728,17 +725,12 @@ int HAPClient::postPairVerifyURL(uint8_t *content, size_t len){
cPair=tPair; // save Controller for this connection slot - connection is now verified and should be encrypted going forward
hkdf.create(a2cKey,sharedCurveKey,32,"Control-Salt","Control-Read-Encryption-Key"); // create AccessoryToControllerKey from (previously-saved) Shared-Secret Curve25519 Key (HAP Section 6.5.2)
hkdf.create(c2aKey,sharedCurveKey,32,"Control-Salt","Control-Write-Encryption-Key"); // create ControllerToAccessoryKey from (previously-saved) Shared-Secret Curve25519 Key (HAP Section 6.5.2)
HKDF::create(a2cKey,temp.sharedCurveKey,32,"Control-Salt","Control-Read-Encryption-Key"); // create AccessoryToControllerKey from (previously-saved) Shared-Secret Curve25519 Key (HAP Section 6.5.2)
HKDF::create(c2aKey,temp.sharedCurveKey,32,"Control-Salt","Control-Write-Encryption-Key"); // create ControllerToAccessoryKey from (previously-saved) Shared-Secret Curve25519 Key (HAP Section 6.5.2)
a2cNonce.zero(); // reset Nonces for this session to zero
c2aNonce.zero();
free(publicCurveKey); // free storage of these temporary variables created in previous step
free(sharedCurveKey);
free(sessionKey);
free(iosCurveKey);
LOG2("\n*** SESSION VERIFICATION COMPLETE *** \n");
}
break;
@ -766,12 +758,12 @@ int HAPClient::postPairingsURL(uint8_t *content, size_t len){
iosTLV.print();
LOG2("------------ END TLVS! ------------\n");
LOG1("In Post Pairings #%d (%s)...",conNum,client.remoteIP().toString().c_str());
LOG1("In Post Pairings #%d (%s)...",clientNumber,client.remoteIP().toString().c_str());
auto itState=iosTLV.find(kTLVType_State);
auto itMethod=iosTLV.find(kTLVType_Method);
if(iosTLV.len(itState)!=1 || (*itState)[0]!=1){ // missing STATE TLV
if(iosTLV.len(itState)!=1 || itState->getVal()!=1){ // missing STATE TLV
LOG0("\n*** ERROR: Parirings 'State' is either missing or not set to <M1>\n\n");
badRequestError(); // return with 400 error, which closes connection
return(0);
@ -783,7 +775,7 @@ int HAPClient::postPairingsURL(uint8_t *content, size_t len){
return(0);
}
int tlvMethod=(*itMethod)[0];
int tlvMethod=itMethod->getVal();
responseTLV.add(kTLVType_State,pairState_M2); // all responses include State=M2
@ -810,7 +802,7 @@ int HAPClient::postPairingsURL(uint8_t *content, size_t len){
return(0);
}
tagError err=addController(*itIdentifier,*itPublicKey,(*itPermissions)[0]);
tagError err=addController(*itIdentifier,*itPublicKey,itPermissions->getVal());
if(err!=tagError_None)
responseTLV.add(kTLVType_Error,err);
@ -892,7 +884,7 @@ int HAPClient::getAccessoriesURL(){
return(0);
}
LOG1("In Get Accessories #%d (%s)...\n",conNum,client.remoteIP().toString().c_str());
LOG1("In Get Accessories #%d (%s)...\n",clientNumber,client.remoteIP().toString().c_str());
homeSpan.printfAttributes();
size_t nBytes=hapOut.getSize();
@ -920,7 +912,7 @@ int HAPClient::getCharacteristicsURL(char *urlBuf){
return(0);
}
LOG1("In Get Characteristics #%d (%s)...\n",conNum,client.remoteIP().toString().c_str());
LOG1("In Get Characteristics #%d (%s)...\n",clientNumber,client.remoteIP().toString().c_str());
int len=strlen(urlBuf); // determine number of IDs specified by counting commas in URL
int numIDs=1;
@ -988,7 +980,7 @@ int HAPClient::putCharacteristicsURL(char *json){
return(0);
}
LOG1("In Put Characteristics #%d (%s)...\n",conNum,client.remoteIP().toString().c_str());
LOG1("In Put Characteristics #%d (%s)...\n",clientNumber,client.remoteIP().toString().c_str());
int n=homeSpan.countCharacteristics(json); // count number of objects in JSON request
if(n==0) // if no objects found, return
@ -998,10 +990,10 @@ int HAPClient::putCharacteristicsURL(char *json){
if(!homeSpan.updateCharacteristics(json, pObj)) // perform update
return(0); // return if failed to update (error message will have been printed in update)
int multiCast=0; // check if all status is OK, or if multicast response is request
for(int i=0;i<n;i++)
if(pObj[i].status!=StatusCode::OK)
multiCast=1;
boolean multiCast=false;
for(int i=0;i<n && !multiCast;i++) // for each characterstic, check if any status is either NOT OKAY, or if WRITE-RESPONSE is requested
if(pObj[i].status!=StatusCode::OK || pObj[i].wr) // if so, to use multicast response
multiCast=true;
LOG2("\n>>>>>>>>>> %s >>>>>>>>>>\n",client.remoteIP().toString().c_str());
@ -1027,7 +1019,7 @@ int HAPClient::putCharacteristicsURL(char *json){
// Create and send Event Notifications if needed
eventNotify(pObj,n,HAPClient::conNum); // transmit EVENT Notification for "n" pObj objects, except DO NOT notify client making request
eventNotify(pObj,n,this); // transmit EVENT Notification for "n" pObj objects, except DO NOT notify client making request
return(1);
}
@ -1041,7 +1033,7 @@ int HAPClient::putPrepareURL(char *json){
return(0);
}
LOG1("In Put Prepare #%d (%s)...\n",conNum,client.remoteIP().toString().c_str());
LOG1("In Put Prepare #%d (%s)...\n",clientNumber,client.remoteIP().toString().c_str());
char ttlToken[]="\"ttl\":";
char pidToken[]="\"pid\":";
@ -1217,6 +1209,7 @@ void HAPClient::getStatusURL(HAPClient *hapClient, void (*callBack)(const char *
if(hapClient){
hapClient->client.stop();
delay(1);
LOG2("------------ SENT! --------------\n");
}
}
@ -1246,27 +1239,26 @@ void HAPClient::checkTimedWrites(){
else
tw++;
}
}
//////////////////////////////////////
void HAPClient::eventNotify(SpanBuf *pObj, int nObj, int ignoreClient){
for(int cNum=0;cNum<homeSpan.maxConnections;cNum++){ // loop over all connection slots
if(hap[cNum]->client && cNum!=ignoreClient){ // if there is a client connected to this slot and it is NOT flagged to be ignored (in cases where it is the client making a PUT request)
void HAPClient::eventNotify(SpanBuf *pObj, int nObj, HAPClient *ignore){
homeSpan.printfNotify(pObj,nObj,cNum); // create JSON (which may be of zero length if there are no applicable notifications for this cNum)
for(auto it=homeSpan.hapList.begin(); it!=homeSpan.hapList.end(); ++it){ // loop over all connection slots
if(&(*it)!=ignore){ // if NOT flagged to be ignored (in cases where it is the client making a PUT request)
homeSpan.printfNotify(pObj,nObj,&(*it)); // create JSON (which may be of zero length if there are no applicable notifications for this cNum)
size_t nBytes=hapOut.getSize();
hapOut.flush();
if(nBytes>0){ // if there ARE notifications to send to client cNum
LOG2("\n>>>>>>>>>> %s >>>>>>>>>>\n",hap[cNum]->client.remoteIP().toString().c_str());
LOG2("\n>>>>>>>>>> %s >>>>>>>>>>\n",it->client.remoteIP().toString().c_str());
hapOut.setLogLevel(2).setHapClient(hap[cNum]);
hapOut.setLogLevel(2).setHapClient(&(*it));
hapOut << "EVENT/1.0 200 OK\r\nContent-Type: application/hap+json\r\nContent-Length: " << nBytes << "\r\n\r\n";
homeSpan.printfNotify(pObj,nObj,cNum);
homeSpan.printfNotify(pObj,nObj,&(*it));
hapOut.flush();
LOG2("\n-------- SENT ENCRYPTED! --------\n");
@ -1301,6 +1293,8 @@ void HAPClient::tlvRespond(TLV8 &tlv8){
LOG2("------------ SENT! --------------\n");
else
LOG2("-------- SENT ENCRYPTED! --------\n");
free(body);
} // tlvRespond
@ -1345,7 +1339,7 @@ int HAPClient::receiveEncrypted(uint8_t *httpBuf, int messageSize){
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
void HAPClient::hexPrintColumn(uint8_t *buf, int n, int minLogLevel){
void HAPClient::hexPrintColumn(const uint8_t *buf, int n, int minLogLevel){
if(homeSpan.logLevel<minLogLevel)
return;
@ -1356,7 +1350,7 @@ void HAPClient::hexPrintColumn(uint8_t *buf, int n, int minLogLevel){
//////////////////////////////////////
void HAPClient::hexPrintRow(uint8_t *buf, int n, int minLogLevel){
void HAPClient::hexPrintRow(const uint8_t *buf, int n, int minLogLevel){
if(homeSpan.logLevel<minLogLevel)
return;
@ -1367,7 +1361,7 @@ void HAPClient::hexPrintRow(uint8_t *buf, int n, int minLogLevel){
//////////////////////////////////////
void HAPClient::charPrintRow(uint8_t *buf, int n, int minLogLevel){
void HAPClient::charPrintRow(const uint8_t *buf, int n, int minLogLevel){
if(homeSpan.logLevel<minLogLevel)
return;
@ -1469,11 +1463,11 @@ void HAPClient::removeController(uint8_t *id){
//////////////////////////////////////
void HAPClient::tearDown(uint8_t *id){
for(int i=0;i<homeSpan.maxConnections;i++){ // loop over all connection slots
if(hap[i]->client && (id==NULL || (hap[i]->cPair && !memcmp(id,hap[i]->cPair->ID,hap_controller_IDBYTES)))){
LOG1("*** Terminating Client #%d\n",i);
hap[i]->client.stop();
for(HAPClient &hc : homeSpan.hapList){
if(id==NULL || (hc.cPair && !memcmp(id,hc.cPair->ID,hap_controller_IDBYTES))){
LOG1("*** Terminating Client #%d\n",hc.clientNumber);
hc.client.stop();
}
}
}
@ -1503,16 +1497,19 @@ void HAPClient::printControllers(int minLogLevel){
void HAPClient::saveControllers(){
if(homeSpan.controllerCallback)
homeSpan.controllerCallback();
if(controllerList.empty()){
nvs_erase_key(hapNVS,"CONTROLLERS");
nvs_erase_key(homeSpan.hapNVS,"CONTROLLERS");
return;
}
TempBuffer<Controller> tBuf(controllerList.size()); // create temporary buffer to hold Controller data
std::copy(controllerList.begin(),controllerList.end(),tBuf.get()); // copy data from linked list to buffer
std::copy(controllerList.begin(),controllerList.end(),tBuf.get()); // copy data from linked list to buffer
nvs_set_blob(hapNVS,"CONTROLLERS",tBuf,tBuf.len()); // update data
nvs_commit(hapNVS); // commit to NVS
nvs_set_blob(homeSpan.hapNVS,"CONTROLLERS",tBuf,tBuf.len()); // update data
nvs_commit(homeSpan.hapNVS); // commit to NVS
}
@ -1566,9 +1563,12 @@ HapOut::HapStreamBuffer::HapStreamBuffer(){
//////////////////////////////////////
HapOut::HapStreamBuffer::~HapStreamBuffer(){
sync();
free(buffer);
free(encBuf);
free(hash);
free(ctx);
}
//////////////////////////////////////
@ -1690,12 +1690,7 @@ void HapOut::HapStreamBuffer::printFormatted(char *buf, size_t nChars, size_t ns
// instantiate all static HAP Client structures and data
nvs_handle HAPClient::hapNVS;
nvs_handle HAPClient::srpNVS;
HKDF HAPClient::hkdf;
pairState HAPClient::pairStatus;
Accessory HAPClient::accessory;
list<Controller, Mallocator<Controller>> HAPClient::controllerList;
SRP6A *HAPClient::srp=NULL;
int HAPClient::conNum;

View File

@ -34,7 +34,6 @@
#include "HAPConstants.h"
#include "HKDF.h"
#include "SRP.h"
#include "TLV8.h"
const TLV8_names HAP_Names[] = {
{kTLVType_Separator,"SEPARATOR"},
@ -64,26 +63,6 @@ struct Nonce {
void inc();
};
/////////////////////////////////////////////////
// Paired Controller Structure for Permanently-Stored Data
struct Controller {
boolean allocated=false; // DEPRECATED (but needed for backwards compatability with original NVS storage of Controller info)
boolean admin; // Controller has admin privileges
uint8_t ID[hap_controller_IDBYTES]; // Pairing ID
uint8_t LTPK[crypto_sign_PUBLICKEYBYTES]; // Long Term Ed2519 Public Key
Controller(){}
Controller(uint8_t *id, uint8_t *ltpk, boolean ad){
allocated=true;
admin=ad;
memcpy(ID,id,hap_controller_IDBYTES);
memcpy(LTPK,ltpk,crypto_sign_PUBLICKEYBYTES);
}
};
/////////////////////////////////////////////////
// Accessory Structure for Permanently-Stored Data
@ -93,6 +72,34 @@ struct Accessory {
uint8_t LTPK[crypto_sign_PUBLICKEYBYTES]; // Long Term Ed2519 Public Key
};
//////////////////////////////////////////////////////////
// Paired Controller Structure for Permanently-Stored Data
class Controller {
friend class HAPClient;
boolean allocated=false; // DEPRECATED (but needed for backwards compatability with original NVS storage of Controller info)
boolean admin; // Controller has admin privileges
uint8_t ID[36]; // Pairing ID
uint8_t LTPK[32]; // Long Term Ed2519 Public Key
public:
Controller(uint8_t *id, uint8_t *ltpk, boolean ad){
allocated=true;
admin=ad;
memcpy(ID,id,36);
memcpy(LTPK,ltpk,32);
}
Controller(){}
const uint8_t *getID() const {return(ID);}
const uint8_t *getLTPK() const {return(LTPK);}
boolean isAdmin() const {return(admin);}
};
/////////////////////////////////////////////////
// HAPClient Structure
// Reads and Writes from each HAP Client connection
@ -105,27 +112,25 @@ struct HAPClient {
static const int MAX_CONTROLLERS=16; // maximum number of paired controllers (HAP requires at least 16)
static const int MAX_ACCESSORIES=150; // maximum number of allowed Accessories (HAP limit=150)
static nvs_handle hapNVS; // handle for non-volatile-storage of HAP data
static nvs_handle srpNVS; // handle for non-volatile-storage of SRP data
static HKDF hkdf; // generates (and stores) HKDF-SHA-512 32-byte keys derived from an inputKey of arbitrary length, a salt string, and an info string
static pairState pairStatus; // tracks pair-setup status
static SRP6A *srp; // stores all SRP-6A keys used for Pair-Setup (must persist through multiple calls to Pair-Setup)
static Accessory accessory; // Accessory ID and Ed25519 public and secret keys- permanently stored
static Accessory accessory; // Accessory ID and Ed25519 public and secret keys - permanently stored
static list<Controller, Mallocator<Controller>> controllerList; // linked-list of Paired Controller IDs and ED25519 long-term public keys - permanently stored
static int conNum; // connection number - used to keep track of per-connection EV notifications
// individual structures and data defined for each Hap Client connection
WiFiClient client; // handle to client
int clientNumber; // client number
Controller *cPair=NULL; // pointer to info on current, session-verified Paired Controller (NULL=un-verified, and therefore un-encrypted, connection)
// These temporary Curve25519 keys are generated in the first call to pair-verify and used in the second call to pair-verify so must persist for a short period
uint8_t *publicCurveKey; // Accessory's Curve25519 Public Key
uint8_t *sharedCurveKey; // Shared-Secret Curve25519 Key derived from Accessory's Secret Key and Controller's Public Key
uint8_t *sessionKey; // Session Key Curve25519 (derived with various HKDF calls)
uint8_t *iosCurveKey; // Controller's Curve25519 Public Key
struct tempKeys_t {
uint8_t publicCurveKey[crypto_box_PUBLICKEYBYTES]; // Accessory's Curve25519 Public Key
uint8_t sharedCurveKey[crypto_box_PUBLICKEYBYTES]; // Shared-Secret Curve25519 Key derived from Accessory's Secret Key and Controller's Public Key
uint8_t sessionKey[crypto_box_PUBLICKEYBYTES]; // Session Key Curve25519 (derived with various HKDF calls)
uint8_t iosCurveKey[crypto_box_PUBLICKEYBYTES]; // Controller's Curve25519 Public Key
} temp;
// CurveKey and CurveKey Nonces are created once each new session is verified in /pair-verify. Keys persist for as long as connection is open
uint8_t a2cKey[32]; // AccessoryToControllerKey derived from HKDF-SHA-512 of sharedCurveKey (HAP Section 6.5.2)
@ -155,9 +160,9 @@ struct HAPClient {
static void init(); // initialize HAP after start-up
static void hexPrintColumn(uint8_t *buf, int n, int minLogLevel=0); // prints 'n' bytes of *buf as HEX, one byte per row, subject to specified minimum log level
static void hexPrintRow(uint8_t *buf, int n, int minLogLevel=0); // prints 'n' bytes of *buf as HEX, all on one row, subject to specified minimum log level
static void charPrintRow(uint8_t *buf, int n, int minLogLevel=0); // prints 'n' bytes of *buf as CHAR, all on one row, subject to specified minimum log level
static void hexPrintColumn(const uint8_t *buf, int n, int minLogLevel=0); // prints 'n' bytes of *buf as HEX, one byte per row, subject to specified minimum log level
static void hexPrintRow(const uint8_t *buf, int n, int minLogLevel=0); // prints 'n' bytes of *buf as HEX, all on one row, subject to specified minimum log level
static void charPrintRow(const uint8_t *buf, int n, int minLogLevel=0); // prints 'n' bytes of *buf as CHAR, all on one row, subject to specified minimum log level
static Controller *findController(uint8_t *id); // returns pointer to controller with matching ID (or NULL if no match)
static tagError addController(uint8_t *id, uint8_t *ltpk, boolean admin); // stores data for new Controller with specified data. Returns tagError (if any)
@ -168,7 +173,7 @@ struct HAPClient {
static void tearDown(uint8_t *id); // tears down connections using Controller with ID=id; tears down all connections if id=NULL
static void checkNotifications(); // checks for Event Notifications and reports to controllers as needed (HAP Section 6.8)
static void checkTimedWrites(); // checks for expired Timed Write PIDs, and clears any found (HAP Section 6.7.2.4)
static void eventNotify(SpanBuf *pObj, int nObj, int ignoreClient=-1); // transmits EVENT Notifications for nObj SpanBuf objects, pObj, with optional flag to ignore a specific client
static void eventNotify(SpanBuf *pObj, int nObj, HAPClient *ignore=NULL); // transmits EVENT Notifications for nObj SpanBuf objects, pObj, with optional flag to ignore a specific client
static void getStatusURL(HAPClient *, void (*)(const char *, void *), void *); // GET / status (an optional, non-HAP feature)
@ -231,5 +236,4 @@ class HapOut : public std::ostream {
/////////////////////////////////////////////////
// Extern Variables
extern HAPClient **hap;
extern HapOut hapOut;

View File

@ -38,6 +38,6 @@
// incorporated under hkdf.cpp, with a wrapper to always
// use SHA-512 with 32 bytes of output as required by HAP.
struct HKDF {
namespace HKDF{
int create(uint8_t *outputKey, uint8_t *inputKey, int inputLen, const char *salt, const char *info); // output of HKDF is always a 32-byte key derived from an input key, a salt string, and an info string
};

File diff suppressed because it is too large Load Diff

View File

@ -27,9 +27,7 @@
#pragma once
#ifndef ARDUINO_ARCH_ESP32
#error ERROR: HOMESPAN IS ONLY AVAILABLE FOR ESP32 MICROCONTROLLERS!
#endif
#include "version.h"
#pragma GCC diagnostic ignored "-Wpmf-conversions" // eliminates warning messages from use of pointers to member functions to detect whether update() and loop() are overridden by user
#pragma GCC diagnostic ignored "-Wunused-result" // eliminates warning message regarded unused result from call to crypto_scalarmult_curve25519()
@ -55,6 +53,7 @@
#include "HAPConstants.h"
#include "HapQR.h"
#include "Characteristics.h"
#include "TLV8.h"
using std::vector;
using std::unordered_map;
@ -72,6 +71,20 @@ enum {
GET_STATUS=256
};
typedef boolean BOOL_t;
typedef uint8_t UINT8_t;
typedef uint16_t UINT16_t;
typedef uint32_t UINT32_t;
typedef uint64_t UINT64_t;
typedef int32_t INT_t;
typedef double FLOAT_t;
typedef const char * STRING_t;
typedef const TLV8 & TLV_ENC_t;
typedef std::pair<const uint8_t *, size_t> DATA_t;
static DATA_t NULL_DATA={NULL,0};
static TLV8 NULL_TLV{};
///////////////////////////////
#define STATUS_UPDATE(LED_UPDATE,MESSAGE_UPDATE) {homeSpan.statusLED->LED_UPDATE;if(homeSpan.statusCallback)homeSpan.statusCallback(MESSAGE_UPDATE);}
@ -108,11 +121,13 @@ struct Span;
struct SpanAccessory;
struct SpanService;
struct SpanCharacteristic;
struct SpanRange;
struct SpanBuf;
struct SpanButton;
struct SpanUserCommand;
struct HAPClient;
class Controller;
extern Span homeSpan;
////////////////////////////////////////////////////////
@ -135,7 +150,8 @@ struct SpanConfig{
struct SpanBuf{ // temporary storage buffer for use with putCharacteristicsURL() and checkTimedResets()
uint32_t aid=0; // updated aid
int iid=0; // updated iid
uint32_t iid=0; // updated iid
boolean wr=false; // flag to indicate write-response has been requested
char *val=NULL; // updated value (optional, though either at least 'val' or 'ev' must be specified)
char *ev=NULL; // updated event notification flag (optional, though either at least 'val' or 'ev' must be specified)
StatusCode status; // return status (HAP Table 6-11)
@ -198,26 +214,22 @@ class Span{
friend class SpanCharacteristic;
friend class SpanUserCommand;
friend class SpanButton;
friend class SpanRange;
friend class SpanWebLog;
friend class SpanOTA;
friend class Network;
friend class HAPClient;
const char *displayName; // display name for this device - broadcast as part of Bonjour MDNS
const char *hostNameBase; // base of hostName of this device - full host name broadcast by Bonjour MDNS will have 6-byte accessoryID as well as '.local' automatically appended
const char *hostNameSuffix=NULL; // optional "suffix" of hostName of this device. If specified, will be used as the hostName suffix instead of the 6-byte accessoryID
char *displayName; // display name for this device - broadcast as part of Bonjour MDNS
char *hostNameBase; // base of hostName of this device - full host name broadcast by Bonjour MDNS will have 6-byte accessoryID as well as '.local' automatically appended
char *hostNameSuffix=NULL; // optional "suffix" of hostName of this device. If specified, will be used as the hostName suffix instead of the 6-byte accessoryID
char *hostName=NULL; // derived full hostname
const char *modelName; // model name of this device - broadcast as Bonjour field "md"
char *modelName; // model name of this device - broadcast as Bonjour field "md"
char category[3]=""; // category ID of primary accessory - broadcast as Bonjour field "ci" (HAP Section 13)
unsigned long snapTime; // current time (in millis) snapped before entering Service loops() or updates()
boolean isInitialized=false; // flag indicating HomeSpan has been initialized
boolean isBridge=true; // flag indicating whether device is configured as a bridge (i.e. first Accessory contains nothing but AccessoryInformation and HAPProtocolInformation)
HapQR qrCode; // optional QR Code to use for pairing
const char *sketchVersion="n/a"; // version of the sketch
nvs_handle charNVS; // handle for non-volatile-storage of Characteristics data
nvs_handle wifiNVS=0; // handle for non-volatile-storage of WiFi data
nvs_handle otaNVS; // handle for non-volatile storage of OTA data
char pairingCodeCommand[12]=""; // user-specified Pairing Code - only needed if Pairing Setup Code is specified in sketch using setPairingCode()
String lastClientIP="0.0.0.0"; // IP address of last client accessing device through encrypted channel
boolean newCode; // flag indicating new application code has been loaded (based on keeping track of app SHA256)
@ -225,6 +237,12 @@ class Span{
uint8_t rebootCount=0; // counts number of times device was rebooted (used in optional Reboot callback)
uint32_t rebootCallbackTime; // length of time to wait (in milliseconds) before calling optional Reboot callback
nvs_handle charNVS; // handle for non-volatile-storage of Characteristics data
nvs_handle wifiNVS=0; // handle for non-volatile-storage of WiFi data
nvs_handle otaNVS; // handle for non-volatile storage of OTA data
nvs_handle srpNVS; // handle for non-volatile storage of SRP data
nvs_handle hapNVS; // handle for non-volatile-storage of HAP data
int connected=0; // WiFi connection status (increments upon each connect and disconnect)
unsigned long waitTime=60000; // time to wait (in milliseconds) between WiFi connection attempts
unsigned long alarmConnect=0; // time after which WiFi connection attempt should be tried again
@ -232,8 +250,6 @@ class Span{
const char *defaultSetupCode=DEFAULT_SETUP_CODE; // Setup Code used for pairing
uint16_t autoOffLED=0; // automatic turn-off duration (in seconds) for Status LED
int logLevel=DEFAULT_LOG_LEVEL; // level for writing out log messages to serial monitor
uint8_t maxConnections=CONFIG_LWIP_MAX_SOCKETS-2; // maximum number of allowed simultaneous HAP connections
uint8_t requestedMaxCon=CONFIG_LWIP_MAX_SOCKETS-2; // requested maximum number of simultaneous HAP connections
unsigned long comModeLife=DEFAULT_COMMAND_TIMEOUT*1000; // length of time (in milliseconds) to keep Command Mode alive before resuming normal operations
uint16_t tcpPortNum=DEFAULT_TCP_PORT; // port for TCP communications between HomeKit and HomeSpan
char qrID[5]=""; // Setup ID used for pairing with QR Code
@ -245,6 +261,7 @@ class Span{
void (*apFunction)()=NULL; // optional function to invoke when starting Access Point
void (*statusCallback)(HS_STATUS status)=NULL; // optional callback when HomeSpan status changes
void (*rebootCallback)(uint8_t)=NULL; // optional callback when device reboots
void (*controllerCallback)()=NULL; // optional callback when Controller is added/removed/changed
WiFiServer *hapServer; // pointer to the HAP Server connection
Blinker *statusLED; // indicates HomeSpan status
@ -258,16 +275,17 @@ class Span{
SpanOTA spanOTA; // manages OTA process
SpanConfig hapConfig; // track configuration changes to the HAP Accessory database; used to increment the configuration number (c#) when changes found
vector<SpanAccessory *, Mallocator<SpanAccessory *>> Accessories; // vector of pointers to all Accessories
vector<SpanService *, Mallocator<SpanService *>> Loops; // vector of pointer to all Services that have over-ridden loop() methods
list<HAPClient, Mallocator<HAPClient>> hapList; // linked-list of HAPClient structures containing HTTP client connections, parsing routines, and state variables
list<HAPClient, Mallocator<HAPClient>>::iterator currentClient; // iterator to current client
vector<SpanAccessory *, Mallocator<SpanAccessory *>> Accessories; // vector of pointers to all Accessories
vector<SpanService *, Mallocator<SpanService *>> Loops; // vector of pointer to all Services that have over-ridden loop() methods
vector<SpanBuf, Mallocator<SpanBuf>> Notifications; // vector of SpanBuf objects that store info for Characteristics that are updated with setVal() and require a Notification Event
vector<SpanButton *, Mallocator<SpanButton *>> PushButtons; // vector of pointer to all PushButtons
unordered_map<uint64_t, uint32_t> TimedWrites; // map of timed-write PIDs and Alarm Times (based on TTLs)
unordered_map<char, SpanUserCommand *> UserCommands; // map of pointers to all UserCommands
vector<SpanButton *, Mallocator<SpanButton *>> PushButtons; // vector of pointer to all PushButtons
unordered_map<uint64_t, uint32_t> TimedWrites; // map of timed-write PIDs and Alarm Times (based on TTLs)
unordered_map<char, SpanUserCommand *> UserCommands; // map of pointers to all UserCommands
void pollTask(); // poll HAP Clients and process any new HAP requests
int getFreeSlot(); // returns free HAPClient slot number. HAPClients slot keep track of each active HAPClient connection
void checkConnect(); // check WiFi connection; connect if needed
void commandMode(); // allows user to control and reset HomeSpan settings with the control button
void resetStatus(); // resets statusLED and calls statusCallback based on current HomeSpan status
@ -275,22 +293,27 @@ class Span{
void printfAttributes(int flags=GET_VALUE|GET_META|GET_PERMS|GET_TYPE|GET_DESC); // writes Attributes JSON database to hapOut stream
SpanCharacteristic *find(uint32_t aid, int iid); // return Characteristic with matching aid and iid (else NULL if not found)
SpanCharacteristic *find(uint32_t aid, uint32_t iid); // return Characteristic with matching aid and iid (else NULL if not found)
int countCharacteristics(char *buf); // return number of characteristic objects referenced in PUT /characteristics JSON request
int updateCharacteristics(char *buf, SpanBuf *pObj); // parses PUT /characteristics JSON request 'buf into 'pObj' and updates referenced characteristics; returns 1 on success, 0 on fail
void printfAttributes(SpanBuf *pObj, int nObj); // writes SpanBuf objects to hapOut stream
boolean printfAttributes(char **ids, int numIDs, int flags); // writes accessory requested characteristic ids to hapOut stream - returns true if all characteristics are found and readable, else returns false
void clearNotify(int slotNum); // set ev notification flags for connection 'slotNum' to false across all characteristics
void printfNotify(SpanBuf *pObj, int nObj, int conNum); // writes notification JSON to hapOut stream based on SpanBuf objects and specified connection number
void clearNotify(HAPClient *hc); // clear all notifications related to specific client connection
void printfNotify(SpanBuf *pObj, int nObj, HAPClient *hc); // writes notification JSON to hapOut stream based on SpanBuf objects and specified connection
static boolean invalidUUID(const char *uuid, boolean isCustom){
static boolean invalidUUID(const char *uuid){
int x=0;
sscanf(uuid,"%*8[0-9a-fA-F]%n",&x); // check for short-form of UUID
if(strlen(uuid)==x && uuid[0]!='0')
return(false);
sscanf(uuid,"%*8[0-9a-fA-F]-%*4[0-9a-fA-F]-%*4[0-9a-fA-F]-%*4[0-9a-fA-F]-%*12[0-9a-fA-F]%n",&x);
return(isCustom && (strlen(uuid)!=36 || x!=36));
return(strlen(uuid)!=36 || x!=36);
}
public:
Span(); // constructor
void begin(Category catID=DEFAULT_CATEGORY,
const char *displayName=DEFAULT_DISPLAY_NAME,
const char *hostNameBase=DEFAULT_HOST_NAME,
@ -328,8 +351,6 @@ class Span{
int getLogLevel(){return(logLevel);} // get Log Level
Span& setSerialInputDisable(boolean val){serialInputDisabled=val;return(*this);} // sets whether serial input is disabled (true) or enabled (false)
boolean getSerialInputDisable(){return(serialInputDisabled);} // returns true if serial input is disabled, or false if serial input in enabled
Span& reserveSocketConnections(uint8_t n){maxConnections-=n;return(*this);} // reserves n socket connections *not* to be used for HAP
Span& setHostNameSuffix(const char *suffix){hostNameSuffix=suffix;return(*this);} // sets the hostName suffix to be used instead of the 6-byte AccessoryID
Span& setPortNum(uint16_t port){tcpPortNum=port;return(*this);} // sets the TCP port number to use for communications between HomeKit and HomeSpan
Span& setQRID(const char *id); // sets the Setup ID for optional pairing with a QR Code
Span& setSketchVersion(const char *sVer){sketchVersion=sVer;return(*this);} // set optional sketch version number
@ -342,8 +363,12 @@ class Span{
Span& setWifiCredentials(const char *ssid, const char *pwd); // sets WiFi Credentials
Span& setStatusCallback(void (*f)(HS_STATUS status)){statusCallback=f;return(*this);} // sets an optional user-defined function to call when HomeSpan status changes
const char* statusString(HS_STATUS s); // returns char string for HomeSpan status change messages
Span& setPairingCode(const char *s); // sets the Pairing Code - use is NOT recommended. Use 'S' from CLI instead
void deleteStoredValues(){processSerialCommand("V");} // deletes stored Characteristic values from NVS
Span& setPairingCode(const char *s, boolean progCall=true); // sets the Pairing Code - use is NOT recommended. Use 'S' from CLI instead
void deleteStoredValues(){processSerialCommand("V");} // deletes stored Characteristic values from NVS
Span& resetIID(uint32_t newIID); // resets the IID count for the current Accessory to start at newIID
Span& setControllerCallback(void (*f)()){controllerCallback=f;return(*this);} // sets an optional user-defined function to call whenever a Controller is added/removed/changed
Span& setHostNameSuffix(const char *suffix){asprintf(&hostNameSuffix,"%s",suffix);return(*this);} // sets the hostName suffix to be used instead of the 6-byte AccessoryID
int enableOTA(boolean auth=true, boolean safeLoad=true){return(spanOTA.init(auth, safeLoad, NULL));} // enables Over-the-Air updates, with (auth=true) or without (auth=false) authorization password
int enableOTA(const char *pwd, boolean safeLoad=true){return(spanOTA.init(true, safeLoad, pwd));} // enables Over-the-Air updates, with custom authorization password (overrides any password stored with the 'O' command)
@ -382,9 +407,13 @@ class Span{
TaskHandle_t getAutoPollTask(){return(pollTaskHandle);}
Span& setTimeServerTimeout(uint32_t tSec){webLog.waitTime=tSec*1000;return(*this);} // sets wait time (in seconds) for optional web log time server to connect
[[deprecated("Please use reserveSocketConnections(n) method instead.")]]
void setMaxConnections(uint8_t n){requestedMaxCon=n;} // sets maximum number of simultaneous HAP connections
list<Controller, Mallocator<Controller>>::const_iterator controllerListBegin();
list<Controller, Mallocator<Controller>>::const_iterator controllerListEnd();
[[deprecated("This function has been deprecated (it is not needed) and no longer does anything. Please remove from sketch to ensure backwards compatilibilty with future versions.")]]
Span& reserveSocketConnections(uint8_t n){return(*this);}
};
///////////////////////////////
@ -395,17 +424,16 @@ class SpanAccessory{
friend class SpanService;
friend class SpanCharacteristic;
friend class SpanButton;
friend class SpanRange;
uint32_t aid=0; // Accessory Instance ID (HAP Table 6-1)
int iidCount=0; // running count of iid to use for Services and Characteristics associated with this Accessory
vector<SpanService *, Mallocator<SpanService*>> Services; // vector of pointers to all Services in this Accessory
uint32_t aid=0; // Accessory Instance ID (HAP Table 6-1)
uint32_t iidCount=0; // running count of iid to use for Services and Characteristics associated with this Accessory
vector<SpanService *, Mallocator<SpanService*>> Services; // vector of pointers to all Services in this Accessory
void printfAttributes(int flags); // writes Accessory JSON to hapOut stream
void printfAttributes(int flags); // writes Accessory JSON to hapOut stream
protected:
~SpanAccessory(); // destructor
~SpanAccessory(); // destructor
public:
@ -420,34 +448,43 @@ class SpanService{
friend class Span;
friend class SpanAccessory;
friend class SpanCharacteristic;
friend class SpanRange;
int iid=0; // Instance ID (HAP Table 6-2)
const char *type; // Service Type
const char *hapName; // HAP Name
boolean hidden=false; // optional property indicating service is hidden
boolean primary=false; // optional property indicating service is primary
vector<SpanCharacteristic *, Mallocator<SpanCharacteristic*>> Characteristics; // vector of pointers to all Characteristics in this Service
vector<SpanService *, Mallocator<SpanService *>> linkedServices; // vector of pointers to any optional linked Services
boolean isCustom; // flag to indicate this is a Custom Service
SpanAccessory *accessory=NULL; // pointer to Accessory containing this Service
uint32_t iid=0; // Instance ID (HAP Table 6-2)
const char *type; // Service Type
const char *hapName; // HAP Name
boolean hidden=false; // optional property indicating service is hidden
boolean primary=false; // optional property indicating service is primary
vector<SpanCharacteristic *, Mallocator<SpanCharacteristic*>> Characteristics; // vector of pointers to all Characteristics in this Service
vector<SpanService *, Mallocator<SpanService *>> linkedServices; // vector of pointers to any optional linked Services
boolean isCustom; // flag to indicate this is a Custom Service
SpanAccessory *accessory=NULL; // pointer to Accessory containing this Service
void printfAttributes(int flags); // writes Service JSON to hapOut stream
void printfAttributes(int flags); // writes Service JSON to hapOut stream
protected:
virtual ~SpanService(); // destructor
vector<HapChar *, Mallocator<HapChar*>> req; // vector of pointers to all required HAP Characteristic Types for this Service
vector<HapChar *, Mallocator<HapChar*>> opt; // vector of pointers to all optional HAP Characteristic Types for this Service
virtual ~SpanService(); // destructor
vector<HapChar *, Mallocator<HapChar*>> req; // vector of pointers to all required HAP Characteristic Types for this Service
vector<HapChar *, Mallocator<HapChar*>> opt; // vector of pointers to all optional HAP Characteristic Types for this Service
public:
void *operator new(size_t size){return(HS_MALLOC(size));} // override new operator to use PSRAM when available
SpanService(const char *type, const char *hapName, boolean isCustom=false); // constructor
SpanService *setPrimary(); // sets the Service Type to be primary and returns pointer to self
SpanService *setHidden(); // sets the Service Type to be hidden and returns pointer to self
SpanService *addLink(SpanService *svc); // adds svc as a Linked Service and returns pointer to self
vector<SpanService *, Mallocator<SpanService *>> getLinks(){return(linkedServices);} // returns linkedServices vector for use as range in "for-each" loops
void *operator new(size_t size){return(HS_MALLOC(size));} // override new operator to use PSRAM when available
SpanService(const char *type, const char *hapName, boolean isCustom=false); // constructor
SpanService *setPrimary(); // sets the Service Type to be primary and returns pointer to self
SpanService *setHidden(); // sets the Service Type to be hidden and returns pointer to self
SpanService *addLink(SpanService *svc); // adds svc as a Linked Service and returns pointer to self
template <typename T=SpanService *> vector<T, Mallocator<T>> getLinks(const char *hapName=NULL){ // returns linkedServices vector, mapped to <T>, for use as range in "for-each" loops
vector<T, Mallocator<T>> v;
for(auto svc : linkedServices){
if(hapName==NULL || !strcmp(hapName,svc->hapName))
v.push_back(static_cast<T>(svc));
}
return(v);
}
uint32_t getIID(){return(iid);} // returns IID of Service
virtual boolean update() {return(true);} // placeholder for code that is called when a Service is updated via a Controller. Must return true/false depending on success of update
virtual void loop(){} // loops for each Service - called every cycle if over-ridden with user-defined code
@ -462,17 +499,24 @@ class SpanCharacteristic{
friend class SpanService;
union UVal {
BOOL_t BOOL;
UINT8_t UINT8;
UINT16_t UINT16;
UINT32_t UINT32;
UINT64_t UINT64;
INT_t INT;
FLOAT_t FLOAT;
STRING_t STRING = NULL;
boolean BOOL;
uint8_t UINT8;
uint16_t UINT16;
uint32_t UINT32;
uint64_t UINT64;
int32_t INT;
double FLOAT;
char * STRING = NULL;
};
int iid=0; // Instance ID (HAP Table 6-3)
class EVLIST : public vector<HAPClient *, Mallocator<HAPClient *>>{ // vector of current connections that have subscribed to EV notifications for this Characteristic
public:
boolean has(HAPClient *hc); // returns true if pointer to connection hc is subscribed, else returns false
void add(HAPClient *hc); // adds connection hc as new subscriber, IF not already a subscriber
void remove(HAPClient *hc); // removes connection hc as a subscriber; okay to remove even if hc was not already a subscriber
};
uint32_t iid=0; // Instance ID (HAP Table 6-3)
HapChar *hapChar; // pointer to HAP Characteristic structure
const char *type; // Characteristic Type
const char *hapName; // HAP Name
@ -487,61 +531,28 @@ class SpanCharacteristic{
boolean staticRange; // Flag that indicates whether Range is static and cannot be changed with setRange()
boolean customRange=false; // Flag for custom ranges
char *validValues=NULL; // Optional JSON array of valid values. Applicable only to uint8 Characteristics
boolean *ev; // Characteristic Event Notify Enable (per-connection)
char *nvsKey=NULL; // key for NVS storage of Characteristic value
boolean isCustom; // flag to indicate this is a Custom Characteristic
boolean setRangeError=false; // flag to indicate attempt to set Range on Characteristic that does not support changes to Range
boolean setValidValuesError=false; // flag to indicate attempt to set Valid Values on Characteristic that does not support changes to Valid Values
uint32_t aid=0; // Accessory ID - passed through from Service containing this Characteristic
boolean isUpdated=false; // set to true when new value has been requested by PUT /characteristic
uint8_t updateFlag=0; // set to either 1 (for normal write) or 2 (for write-response) inside update() when Characteristic is successfully updated via Home App
unsigned long updateTime=0; // last time value was updated (in millis) either by PUT /characteristic OR by setVal()
UVal newValue; // the updated value requested by PUT /characteristic
SpanService *service=NULL; // pointer to Service containing this Characteristic
void printfAttributes(int flags); // writes Characteristic JSON to hapOut stream
StatusCode loadUpdate(char *val, char *ev); // load updated val/ev from PUT /characteristic JSON request. Return intitial HAP status code (checks to see if characteristic is found, is writable, etc.)
EVLIST evList; // vector of current connections that have subscribed to EV notifications for this Characteristic
String uvPrint(UVal &u){
char c[67]; // space for 64 characters + surrounding quotes + terminating null
switch(format){
case FORMAT::BOOL:
return(String(u.BOOL));
case FORMAT::INT:
return(String(u.INT));
case FORMAT::UINT8:
return(String(u.UINT8));
case FORMAT::UINT16:
return(String(u.UINT16));
case FORMAT::UINT32:
return(String(u.UINT32));
case FORMAT::UINT64:
sprintf(c,"%llu",u.UINT64);
return(String(c));
case FORMAT::FLOAT:
sprintf(c,"%g",u.FLOAT);
return(String(c));
case FORMAT::STRING:
case FORMAT::DATA:
sprintf(c,"\"%.64s\"",u.STRING); // Truncating string to 64 chars
return(String(c));
} // switch
return(String()); // included to prevent compiler warnings
}
void printfAttributes(int flags); // writes Characteristic JSON to hapOut stream
StatusCode loadUpdate(char *val, char *ev, boolean wr); // load updated val/ev from PUT /characteristic JSON request. Return intitial HAP status code (checks to see if characteristic is found, is writable, etc.)
String uvPrint(UVal &u); // returns "printable" String for any type of Characteristic
void uvSet(UVal &dest, UVal &src); // copies UVal src into UVal dest
void uvSet(UVal &u, STRING_t val); // copies string val into UVal u
void uvSet(UVal &u, DATA_t data); // copies DATA data into UVal u (after transforming to a char *)
void uvSet(UVal &u, TLV_ENC_t tlv); // copies TLV8 tlv into UVal u (after transforming to a char *)
void uvSet(UVal &dest, UVal &src){
if(format==FORMAT::STRING || format==FORMAT::DATA)
uvSet(dest,(const char *)src.STRING);
else
dest=src;
}
void uvSet(UVal &u, const char *val){
u.STRING = (char *)HS_REALLOC(u.STRING, strlen(val) + 1);
strcpy(u.STRING, val);
}
template <typename T> void uvSet(UVal &u, T val){
template <typename T> void uvSet(UVal &u, T val){ // copies numeric val into UVal u
switch(format){
case FORMAT::BOOL:
u.BOOL=(boolean)val;
@ -564,13 +575,16 @@ class SpanCharacteristic{
case FORMAT::FLOAT:
u.FLOAT=(double)val;
break;
case FORMAT::STRING:
case FORMAT::DATA:
default:
break;
} // switch
}
template <class T> T uvGet(UVal &u){
char *getStringGeneric(UVal &val); // gets the specified UVal for string-based Characteristics
size_t getDataGeneric(uint8_t *data, size_t len, UVal &val); // gets the specified UVal for data-based Characteristics
size_t getTLVGeneric(TLV8 &tlv, UVal &val); // gets the specified UVal for tlv8-based Characteristics
template <class T> T uvGet(UVal &u){ // gets the specified UVal for numeric-based Characteristics
switch(format){
case FORMAT::BOOL:
@ -587,18 +601,20 @@ class SpanCharacteristic{
return((T) u.UINT64);
case FORMAT::FLOAT:
return((T) u.FLOAT);
case FORMAT::STRING:
case FORMAT::DATA:
default:
break;
}
return((T)0); // included to prevent compiler warnings
}
void setValCheck(); // initial check before setting value of any Characteristic
void setValFinish(boolean notify); // final processing after setting value of any Characteristic
protected:
~SpanCharacteristic(); // destructor
template <typename T, typename A=boolean, typename B=boolean> void init(T val, boolean nvsStore, A min=0, B max=1){
~SpanCharacteristic(); // destructor
template <typename T> void init(T val, boolean nvsStore, T min, T max){
uvSet(value,val);
@ -609,7 +625,7 @@ class SpanCharacteristic{
sprintf(nvsKey,"%04X%08X%03X",t,aid,iid&0xFFF);
size_t len;
if(format!=FORMAT::STRING && format!=FORMAT::DATA){
if(format<FORMAT::STRING){
if(nvs_get_u64(homeSpan.charNVS,nvsKey,&(value.UINT64))!=ESP_OK) {
nvs_set_u64(homeSpan.charNVS,nvsKey,value.UINT64); // store data as uint64_t regardless of actual type (it will be read correctly when access through uvGet())
nvs_commit(homeSpan.charNVS); // commit to NVS
@ -628,129 +644,37 @@ class SpanCharacteristic{
uvSet(newValue,value);
if(format!=FORMAT::STRING && format!=FORMAT::DATA) {
uvSet(minValue,min);
uvSet(maxValue,max);
uvSet(stepValue,0);
if(format<FORMAT::STRING){
uvSet(minValue,min);
uvSet(maxValue,max);
uvSet(stepValue,0);
}
} // init()
public:
void *operator new(size_t size){return(HS_MALLOC(size));} // override new operator to use PSRAM when available
SpanCharacteristic(HapChar *hapChar, boolean isCustom=false); // constructor
SpanCharacteristic(HapChar *hapChar, boolean isCustom=false); // SpanCharacteristic constructor
void *operator new(size_t size){return(HS_MALLOC(size));} // override new operator to use PSRAM when available
template <class T=int> T getVal(){
return(uvGet<T>(value));
}
template <class T=int> T getVal(){return(uvGet<T>(value));} // gets the value for numeric-based Characteristics
char *getString(){return(getStringGeneric(value));} // gets the value for string-based Characteristics
size_t getData(uint8_t *data, size_t len){return(getDataGeneric(data,len,value));} // gets the value for data-based Characteristics
size_t getTLV(TLV8 &tlv){return(getTLVGeneric(tlv,value));} // gets the value for tlv8-based Characteristics
template <class T=int> T getNewVal(){
return(uvGet<T>(newValue));
}
template <class T=int> T getNewVal(){return(uvGet<T>(newValue));} // gets the newValue for numeric-based Characteristics
char *getNewString(){return(getStringGeneric(newValue));} // gets the newValue for string-based Characteristics
size_t getNewData(uint8_t *data, size_t len){return(getDataGeneric(data,len,newValue));} // gets the newValue for data-based Characteristics
size_t getNewTLV(TLV8 &tlv){return(getTLVGeneric(tlv,newValue));} // gets the newValue for tlv8-based Characteristics
void setString(const char *val, boolean notify=true); // sets the value and newValue for string-based Characteristic
void setData(const uint8_t *data, size_t len, boolean notify=true); // sets the value and newValue for data-based Characteristic
void setTLV(const TLV8 &tlv, boolean notify=true); // sets the value and newValue for tlv8-based Characteristic
template <typename T> void setVal(T val, boolean notify=true){ // sets the value and newValue for numeric-based Characteristics
setValCheck();
char *getString(){
if(format == FORMAT::STRING)
return value.STRING;
return NULL;
}
char *getNewString(){
if(format == FORMAT::STRING)
return newValue.STRING;
return NULL;
}
void setString(const char *val){
if((perms & EV) == 0){
LOG0("\n*** WARNING: Attempt to update Characteristic::%s with setString() ignored. No NOTIFICATION permission on this characteristic\n\n",hapName);
return;
}
uvSet(value,val);
uvSet(newValue,value);
updateTime=homeSpan.snapTime;
SpanBuf sb; // create SpanBuf object
sb.characteristic=this; // set characteristic
sb.status=StatusCode::OK; // set status
char dummy[]="";
sb.val=dummy; // set dummy "val" so that printfNotify knows to consider this "update"
homeSpan.Notifications.push_back(sb); // store SpanBuf in Notifications vector
if(nvsKey){
nvs_set_str(homeSpan.charNVS,nvsKey,value.STRING); // store data
nvs_commit(homeSpan.charNVS);
}
} // setString()
size_t getData(uint8_t *data, size_t len){
if(format!=FORMAT::DATA)
return(0);
size_t olen;
int ret=mbedtls_base64_decode(data,len,&olen,(uint8_t *)value.STRING,strlen(value.STRING));
if(data==NULL)
return(olen);
if(ret==MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL)
LOG0("\n*** WARNING: Can't decode Characteristic::%s with getData(). Destination buffer is too small (%d out of %d bytes needed)\n\n",hapName,len,olen);
else if(ret==MBEDTLS_ERR_BASE64_INVALID_CHARACTER)
LOG0("\n*** WARNING: Can't decode Characteristic::%s with getData(). Data is not in base-64 format\n\n",hapName);
return(olen);
}
size_t getNewData(uint8_t *data, size_t len){
if(format!=FORMAT::DATA)
return(0);
size_t olen;
int ret=mbedtls_base64_decode(data,len,&olen,(uint8_t *)newValue.STRING,strlen(newValue.STRING));
if(data==NULL)
return(olen);
if(ret==MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL)
LOG0("\n*** WARNING: Can't decode Characteristic::%s with getData(). Destination buffer is too small (%d out of %d bytes needed)\n\n",hapName,len,olen);
else if(ret==MBEDTLS_ERR_BASE64_INVALID_CHARACTER)
LOG0("\n*** WARNING: Can't decode Characteristic::%s with getData(). Data is not in base-64 format\n\n",hapName);
return(olen);
}
void setData(uint8_t *data, size_t len){
if((perms & EV) == 0){
LOG0("\n*** WARNING: Attempt to update Characteristic::%s with setData() ignored. No NOTIFICATION permission on this characteristic\n\n",hapName);
return;
}
if(len<1){
LOG0("\n*** WARNING: Attempt to update Characteristic::%s with setData() ignored. Size of data buffer must be greater than zero\n\n",hapName);
return;
}
size_t olen;
mbedtls_base64_encode(NULL,0,&olen,data,len); // get length of string buffer needed (mbedtls includes the trailing null in this size)
TempBuffer<char> tBuf(olen); // create temporary string buffer, with room for trailing null
mbedtls_base64_encode((uint8_t*)tBuf.get(),olen,&olen,data,len ); // encode data into string buf
setString(tBuf); // call setString to continue processing as if characteristic was a string
}
template <typename T> void setVal(T val, boolean notify=true){
if((perms & EV) == 0){
LOG0("\n*** WARNING: Attempt to update Characteristic::%s with setVal() ignored. No NOTIFICATION permission on this characteristic\n\n",hapName);
return;
}
if(!((val >= uvGet<T>(minValue)) && (val <= uvGet<T>(maxValue)))){
LOG0("\n*** WARNING: Attempt to update Characteristic::%s with setVal(%g) is out of range [%g,%g]. This may cause device to become non-responsive!\n\n",
hapName,(double)val,uvGet<double>(minValue),uvGet<double>(maxValue));
@ -762,27 +686,35 @@ class SpanCharacteristic{
updateTime=homeSpan.snapTime;
if(notify){
SpanBuf sb; // create SpanBuf object
sb.characteristic=this; // set characteristic
sb.status=StatusCode::OK; // set status
char dummy[]="";
sb.val=dummy; // set dummy "val" so that printfNotify knows to consider this "update"
homeSpan.Notifications.push_back(sb); // store SpanBuf in Notifications vector
if(updateFlag!=2){ // do not broadcast EV if update is being done in context of write-response
SpanBuf sb; // create SpanBuf object
sb.characteristic=this; // set characteristic
sb.status=StatusCode::OK; // set status
char dummy[]="";
sb.val=dummy; // set dummy "val" so that printfNotify knows to consider this "update"
homeSpan.Notifications.push_back(sb); // store SpanBuf in Notifications vector
}
if(nvsKey){
nvs_set_u64(homeSpan.charNVS,nvsKey,value.UINT64); // store data as uint64_t regardless of actual type (it will be read correctly when access through uvGet())
nvs_commit(homeSpan.charNVS);
}
}
} // setVal()
} // setVal()
boolean updated(); // returns true within update() if Characteristic was updated by Home App
unsigned long timeVal(); // returns time elapsed (in millis) since value was last updated, either by Home App or by using setVal()
uint32_t getIID(); // returns IID of Characteristic
boolean updated(){return(isUpdated);} // returns isUpdated
unsigned long timeVal(); // returns time elapsed (in millis) since value was last updated
SpanCharacteristic *setValidValues(int n, ...); // sets a list of 'n' valid values allowed for a Characteristic and returns pointer to self. Only applicable if format=INT, UINT8, UINT16, or UINT32
SpanCharacteristic *setPerms(uint8_t perms); // sets permissions of a Characteristic
SpanCharacteristic *addPerms(uint8_t dPerms); // add permissions of a Characteristic
SpanCharacteristic *removePerms(uint8_t dPerms); // removes permissions of a Characteristic
SpanCharacteristic *setDescription(const char *c); // sets description of a Characteristic
SpanCharacteristic *setUnit(const char *c); // set unit of a Characteristic
SpanCharacteristic *setValidValues(int n, ...); // sets a list of 'n' valid values allowed for a Characteristic - only applicable if format=INT, UINT8, UINT16, or UINT32
template <typename A, typename B, typename S=int> SpanCharacteristic *setRange(A min, B max, S step=0){
template <typename A, typename B, typename S=int> SpanCharacteristic *setRange(A min, B max, S step=0){ // sets the allowed range of a Characteristic
if(!staticRange){
uvSet(minValue,min);
@ -795,40 +727,6 @@ class SpanCharacteristic{
return(this);
} // setRange()
SpanCharacteristic *setPerms(uint8_t perms){
perms&=0x7F;
if(perms>0)
this->perms=perms;
return(this);
}
SpanCharacteristic *addPerms(uint8_t dPerms){
return(setPerms(perms|dPerms));
}
SpanCharacteristic *removePerms(uint8_t dPerms){
return(setPerms(perms&(~dPerms)));
}
SpanCharacteristic *setDescription(const char *c){
desc = (char *)HS_REALLOC(desc, strlen(c) + 1);
strcpy(desc, c);
return(this);
}
SpanCharacteristic *setUnit(const char *c){
unit = (char *)HS_REALLOC(unit, strlen(c) + 1);
strcpy(unit, c);
return(this);
}
};
///////////////////////////////
struct [[deprecated("Please use Characteristic::setRange() method instead.")]] SpanRange{
SpanRange(int min, int max, int step);
};
///////////////////////////////

View File

@ -24,6 +24,8 @@
* SOFTWARE.
*
********************************************************************************/
#include "version.h"
#include <DNSServer.h>

View File

@ -45,11 +45,14 @@ template <class T>
struct Mallocator {
typedef T value_type;
Mallocator() = default;
template <class U> constexpr Mallocator(const Mallocator<U>&) noexcept {}
template <class U> constexpr Mallocator(const Mallocator<U>&) {}
[[nodiscard]] T* allocate(std::size_t n) {
if(n > std::size_t(-1) / sizeof(T)) throw std::bad_alloc();
if(auto p = static_cast<T*>(HS_MALLOC(n*sizeof(T)))) return p;
throw std::bad_alloc();
auto p = static_cast<T*>(HS_MALLOC(n*sizeof(T)));
if(p==NULL){
Serial.printf("\n\n*** FATAL ERROR: Requested allocation of %d bytes failed. Program Halting.\n\n",n*sizeof(T));
while(1);
}
return p;
}
void deallocate(T* p, std::size_t) noexcept { std::free(p); }
};

View File

@ -24,41 +24,9 @@
* SOFTWARE.
*
********************************************************************************/
// USER-DEFINED SETTINGS AND REFERENCE ENUMERATION CLASSES
#include <esp_arduino_version.h>
#pragma once
//////////////////////////////////////////////////////
// HomeSpan Version //
#define HS_MAJOR 1
#define HS_MINOR 9
#define HS_PATCH 0
#define STRINGIFY(x) _STR(x)
#define _STR(x) #x
#define HOMESPAN_VERSION STRINGIFY(HS_MAJOR) "." STRINGIFY(HS_MINOR) "." STRINGIFY(HS_PATCH)
#define VERSION(major,minor,patch) major*10000+minor*100+patch
#ifndef REQUIRED
#define REQUIRED 0
#endif
#if (REQUIRED>VERSION(HS_MAJOR,HS_MINOR,HS_PATCH))
#error THIS SKETCH REQUIRES A LATER VERSION OF THE HOMESPAN LIBRARY
#endif
#define ARDUINO_ESP_VERSION STRINGIFY(ESP_ARDUINO_VERSION_MAJOR) "." STRINGIFY(ESP_ARDUINO_VERSION_MINOR) "." STRINGIFY(ESP_ARDUINO_VERSION_PATCH)
#if ESP_ARDUINO_VERSION_MAJOR<2
#error HOMESPAN REQUIRES VERSION 2 OF THE ARDUINO ESP32 LIBRARY
#endif
//////////////////////////////////////////////////////
// DEFAULT SETTINGS //

View File

@ -29,17 +29,16 @@
// SPAN SERVICES (HAP Chapter 8) //
///////////////////////////////////
// Macros to define services, along with vectors of required and optional characteristics for each Span Service structure
// The names of the macros are picked up by external scripts to help generate documentation
// Note: These macros below are also parsed by an external awk script to auto-generate Services and Characteristics documentation.
// Macros to define Services, along with vectors of required and optional Characteristics for each Span Service structure.
//
// NOTE: these macros are parsed by an external awk script to auto-generate Services and Characteristics documentation.
//
// The CREATE_SERV_DEP() macro is the same as the CREATE_SERV() macro, except that it is used for deprecated Services that will not
// be included in documentation. The OPT_DEP() macro is that same as the OPT() macro, except that it is used for deprecated Characteristics
// that will not be included in documentation.
// be included in documentation. The REQ_DEP and OPT_DEP() macros are the same as the REQ() and OPT() macros, except that they are used
// for deprecated Characteristics that will not be included in documentation.
#define CREATE_SERV(NAME,UUID) struct NAME : SpanService { NAME() : SpanService{#UUID,#NAME}{
#define CREATE_SERV_DEP(NAME,UUID) struct NAME : SpanService { NAME() : SpanService{#UUID,#NAME}{
#define CREATE_SERV(NAME,_UUID) struct NAME : SpanService { static constexpr const char *UUID=#_UUID; NAME() : SpanService{#_UUID,#NAME}{
#define CREATE_SERV_DEP(NAME,_UUID) struct NAME : SpanService { static constexpr const char *UUID=#_UUID; NAME() : SpanService{#_UUID,#NAME}{
#define END_SERV }};
#define REQ(HAPCHAR) req.push_back(&hapChars.HAPCHAR)
@ -429,6 +428,7 @@ namespace Service {
CREATE_SERV(Television,D8) // Defines a TV. Optional Linked Services: <b>InputSource</b> and <b>TelevisionSpeaker</b>.
REQ(Active);
OPT(ActiveIdentifier);
OPT(DisplayOrder);
OPT(RemoteKey);
OPT(PowerModeSelection);
OPT(ConfiguredName);
@ -475,126 +475,127 @@ namespace Service {
// Macro to define Span Characteristic structures based on name of HAP Characteristic, default value, and min/max value (not applicable for STRING or BOOL which default to min=0, max=1)
#define CREATE_CHAR(TYPE,HAPCHAR,DEFVAL,MINVAL,MAXVAL,...) \
struct HAPCHAR : SpanCharacteristic { __VA_OPT__(enum{) __VA_ARGS__ __VA_OPT__(};) HAPCHAR(TYPE val=DEFVAL, boolean nvsStore=false) : SpanCharacteristic {&hapChars.HAPCHAR} { init(val,nvsStore,(TYPE)MINVAL,(TYPE)MAXVAL); } };
struct HAPCHAR : SpanCharacteristic { __VA_OPT__(enum{) __VA_ARGS__ __VA_OPT__(};) HAPCHAR(TYPE val=DEFVAL, boolean nvsStore=false) : SpanCharacteristic {&hapChars.HAPCHAR} { init<TYPE>(val,nvsStore,MINVAL,MAXVAL); } };
namespace Characteristic {
CREATE_CHAR(uint32_t,AccessoryFlags,1,1,1); // not applicable for HomeSpan
CREATE_CHAR(uint8_t,Active,0,0,1,INACTIVE,ACTIVE); // indicates if the Service is active/on
CREATE_CHAR(uint32_t,ActiveIdentifier,0,0,255); // numerical Identifier of the <b>InputSource</b> selected in the Home App.
CREATE_CHAR(uint8_t,AirQuality,0,0,5,UNKNOWN,EXCELLENT,GOOD,FAIR,INFERIOR,POOR); // a subjective description
CREATE_CHAR(uint8_t,BatteryLevel,100,0,100); // measured as a percentage
CREATE_CHAR(int,Brightness,0,0,100); // measured as a percentage
CREATE_CHAR(double,CarbonMonoxideLevel,0,0,100); // measured in parts per million (ppm)
CREATE_CHAR(double,CarbonMonoxidePeakLevel,0,0,100); // measured in parts per million (ppm)
CREATE_CHAR(uint8_t,CarbonMonoxideDetected,0,0,1,NORMAL,ABNORMAL); // indicates if abnormal level is detected
CREATE_CHAR(double,CarbonDioxideLevel,0,0,100000); // measured on parts per million (ppm)
CREATE_CHAR(double,CarbonDioxidePeakLevel,0,0,100000); // measured in parts per million (ppm)
CREATE_CHAR(uint8_t,CarbonDioxideDetected,0,0,1,NORMAL,ABNORMAL); // indicates if abnormal level is detected
CREATE_CHAR(uint8_t,ChargingState,0,0,2,NOT_CHARGING,CHARGING,NOT_CHARGEABLE); // indicates state of battery charging
CREATE_CHAR(uint8_t,ClosedCaptions,0,0,1); // unused by any Service
CREATE_CHAR(double,CoolingThresholdTemperature,10,10,35); // cooling turns on when temperature (in Celsius) rises above this threshold
CREATE_CHAR(uint32_t,ColorTemperature,200,140,500); // measured in inverse megaKelvin (= 1,000,000 / Kelvin)
CREATE_CHAR(uint8_t,ContactSensorState,1,0,1,DETECTED,NOT_DETECTED); // indictates if contact is detected (i.e. closed)
CREATE_CHAR(const char *,ConfiguredName,"unnamed",0,1); // default display name of this Service
CREATE_CHAR(double,CurrentAmbientLightLevel,1,0.0001,100000); // measured in Lux (lumens/m<sup>2</sup>
CREATE_CHAR(int,CurrentHorizontalTiltAngle,0,-90,90); // current angle (in degrees) of slats from fully up (-90) to fully open (0) to fully down (90)
CREATE_CHAR(uint8_t,CurrentAirPurifierState,0,0,2,INACTIVE,IDLE,PURIFYING); // indicates current state of air purification
CREATE_CHAR(uint8_t,CurrentSlatState,0,0,2,FIXED,JAMMED,SWINGING); // indicates current state of slats
CREATE_CHAR(uint8_t,CurrentPosition,0,0,100); // current position (as a percentage) from fully closed (0) to full open (100)
CREATE_CHAR(int,CurrentVerticalTiltAngle,0,-90,90); // current angle (in degrees) of slats from fully left (-90) to fully open (0) to fully right (90)
CREATE_CHAR(uint8_t,CurrentVisibilityState,0,0,1,VISIBLE,NOT_VISIBLE); // current visibility of the Service, as selectable on the Settings Page of the Home App
CREATE_CHAR(uint8_t,CurrentHumidifierDehumidifierState,1,0,3,INACTIVE,IDLE,HUMIDIFYING,DEHUMIDIFYING); // indicates current state of humidifier/dehumidifer
CREATE_CHAR(uint8_t,CurrentDoorState,1,0,4,OPEN,CLOSED,OPENING,CLOSING,STOPPED); // indicates current state of a door
CREATE_CHAR(uint8_t,CurrentFanState,1,0,2,INACTIVE,IDLE,BLOWING); // indicates current state of a fan
CREATE_CHAR(uint8_t,CurrentHeatingCoolingState,0,0,2,IDLE,HEATING,COOLING); // indicates whether appliance is currently heating, cooling, or just idle
CREATE_CHAR(uint8_t,CurrentHeaterCoolerState,1,0,3,INACTIVE,IDLE,HEATING,COOLING); // indicates whether appliance is currently heating, cooling, idle, or off
CREATE_CHAR(uint8_t,CurrentMediaState,0,0,5); // not used
CREATE_CHAR(double,CurrentRelativeHumidity,0,0,100); // current humidity measured as a percentage
CREATE_CHAR(double,CurrentTemperature,0,0,100); // current temperature measured in Celsius
CREATE_CHAR(int,CurrentTiltAngle,0,-90,90); // current angle (in degrees) of slats from fully up or left (-90) to fully open (0) to fully down or right (90)
CREATE_CHAR(double,FilterLifeLevel,100,0,100); // measured as a percentage of remaining life
CREATE_CHAR(uint8_t,FilterChangeIndication,0,0,1,NO_CHANGE_NEEDED,CHANGE_NEEDED); // indicates state of filter
CREATE_CHAR(const char *,FirmwareRevision,"1.0.0",0,1); // must be in form x[.y[.z]] - informational only
CREATE_CHAR(const char *,HardwareRevision,"1.0.0",0,1); // must be in form x[.y[.z]] - informational only
CREATE_CHAR(double,HeatingThresholdTemperature,16,0,25); // heating turns on when temperature (in Celsius) falls below this threshold
CREATE_CHAR(boolean,HoldPosition,false,0,1); // deprecated
CREATE_CHAR(double,Hue,0,0,360); // color (in degrees) from red (0) to green (120) to blue (240) and back to red (360)
CREATE_CHAR(boolean,Identify,1,1,1,RUN_ID=1); // triggers an update when HomeKit wants HomeSpan to run its identification routine for an Accessory
CREATE_CHAR(uint32_t,Identifier,0,0,255); // numerical Identifer of the <b>InputSource</b>.
CREATE_CHAR(uint8_t,InputDeviceType,0,0,6); // not used
CREATE_CHAR(uint8_t,InputSourceType,0,0,10); // not used
CREATE_CHAR(uint8_t,InUse,0,0,1,NOT_IN_USE,IN_USE); // if Service is set to active, this indictes whether it is currently in use
CREATE_CHAR(uint8_t,IsConfigured,0,0,1,NOT_CONFIGURED,CONFIGURED); // indicates if a predefined Service has been configured
CREATE_CHAR(uint8_t,LeakDetected,0,0,1,NOT_DETECTED,DETECTED); // indictates if a leak is detected
CREATE_CHAR(uint8_t,LockCurrentState,0,0,3,UNLOCKED,LOCKED,JAMMED,UNKNOWN); // indicates state of a lock
CREATE_CHAR(uint8_t,LockPhysicalControls,0,0,1,CONTROL_LOCK_DISABLED,CONTROL_LOCK_ENABLED); // indicates if local control lock is enabled
CREATE_CHAR(uint8_t,LockTargetState,0,0,1,UNLOCK,LOCK); // indicates desired state of lock
CREATE_CHAR(const char *,Manufacturer,"HomeSpan",0,1); // any string - informational only
CREATE_CHAR(const char *,Model,"HomeSpan-ESP32",0,1); // any string - informational only
CREATE_CHAR(boolean,MotionDetected,0,0,1,NOT_DETECTED,DETECTED); // indicates if motion is detected
CREATE_CHAR(boolean,Mute,0,0,1,OFF,ON); // not used
CREATE_CHAR(const char *,Name,"unnamed",0,1); // default display name of the Accessory
CREATE_CHAR(double,NitrogenDioxideDensity,0,0,1000); // measured in &micro;g/m<sup>3</sup>
CREATE_CHAR(boolean,ObstructionDetected,0,0,1,NOT_DETECTED,DETECTED); // indicates if obstruction is detected
CREATE_CHAR(double,PM25Density,0,0,1000); // 2.5-micron particulate density, measured in &micro;g/m<sup>3</sup>
CREATE_CHAR(uint8_t,OccupancyDetected,0,0,1,NOT_DETECTED,DETECTED); // indicates if occupanccy is detected
CREATE_CHAR(boolean,OutletInUse,0,0,1,NOT_IN_USE,IN_USE); // indicates if an appliance or light is plugged into the outlet, regardless of whether on or off
CREATE_CHAR(boolean,On,0,0,1,OFF,ON); // indicates if the Service is active/on
CREATE_CHAR(double,OzoneDensity,0,0,1000); // measured in &micro;g/m<sup>3</sup>
CREATE_CHAR(uint8_t,PictureMode,0,0,13); // not used
CREATE_CHAR(double,PM10Density,0,0,1000); // 10-micron particulate density, measured in &micro;g/m<sup>3</sup>
CREATE_CHAR(uint8_t,PositionState,2,0,2,GOING_TO_MINIMUM,GOING_TO_MAXIMUM,STOPPED); // deprecated
CREATE_CHAR(uint8_t,PowerModeSelection,0,0,0,VIEW_SETTINGS); // when defined, creates a "View TV Settings" button in the Home App that triggers an update to this Characteristic when pressed
CREATE_CHAR(uint8_t,ProgramMode,0,0,2,NONE,SCHEDULED,SCHEDULE_OVERRIDEN); // indicates if pre-scheduled program is running
CREATE_CHAR(uint8_t,ProgrammableSwitchEvent,0,0,2,SINGLE_PRESS,DOUBLE_PRESS,LONG_PRESS); // specifies type of button press
CREATE_CHAR(double,RelativeHumidityDehumidifierThreshold,50,0,100); // dehumidfier turns on when humidity rises above this threshold
CREATE_CHAR(double,RelativeHumidityHumidifierThreshold,50,0,100); // humidfier turns on when humidity falls below this threshold
CREATE_CHAR(uint32_t,RemainingDuration,60,0,3600); // duration (in seconds) remaining for Service to be active/on
CREATE_CHAR(uint8_t,RemoteKey,4,4,15,UP=4,DOWN,LEFT,RIGHT,CENTER,BACK,PLAY_PAUSE=11,INFO=15); // triggers an update when the corresponding key is pressed in the Remote Control widget on an iPhone
CREATE_CHAR(uint8_t,ResetFilterIndication,1,1,1,RESET_FILTER=1); // triggers an update when the user chooses to reset the <b>FilterChangeIndication</b> (only appears in Eve App, not Home App)
CREATE_CHAR(int,RotationDirection,0,0,1,CLOCKWISE,COUNTERCLOCKWISE); // indicates the rotation direction of a fan
CREATE_CHAR(double,RotationSpeed,0,0,100); // measured as a percentage
CREATE_CHAR(double,Saturation,0,0,100); // color saturation, measured as a percentage
CREATE_CHAR(uint8_t,SecuritySystemAlarmType,0,0,1,KNOWN,UNKNOWN); // indicates whether alarm was triggered for known reason
CREATE_CHAR(uint8_t,SecuritySystemCurrentState,3,0,4,ARMED_STAY,ARMED_AWAY,ARMED_NIGHT,DISARMED,ALARM_TRIGGERED); // indicates current state of the security system
CREATE_CHAR(uint8_t,SecuritySystemTargetState,3,0,3,ARM_STAY,ARM_AWAY,ARM_NIGHT,DISARM); // indicates desired state of the security system
CREATE_CHAR(const char *,SerialNumber,"HS-12345",0,1); // any string - informational only
CREATE_CHAR(uint8_t,ServiceLabelIndex,1,1,255); // numerical index used to distinguish multiple copies of the same Service within an Accessory
CREATE_CHAR(uint8_t,ServiceLabelNamespace,1,0,1,DOTS,NUMERALS); // indicates how un-named Services linked together with a <b>ServiceLabel</b> Service should be displayed in the Home App
CREATE_CHAR(uint8_t,SlatType,0,0,1,HORIZONTAL,VERTICAL); // indicates the direction of a slat or group of slats
CREATE_CHAR(uint8_t,SleepDiscoveryMode,0,0,1); // not used
CREATE_CHAR(uint8_t,SmokeDetected,0,0,1,NOT_DETECTED,DETECTED); // indicates if smoke is detected
CREATE_CHAR(boolean,StatusActive,1,0,1,NOT_FUNCTIONING,FUNCTIONING); // indicates whether the Service is properly functioning
CREATE_CHAR(uint8_t,StatusFault,0,0,1,NO_FAULT,FAULT); // indicates whether the Service has a fault (only appears in Eve App, not Home App)
CREATE_CHAR(uint8_t,StatusJammed,0,0,1,NOT_JAMMED,JAMMED); // indicates whether the Service has been "jammed"
CREATE_CHAR(uint8_t,StatusLowBattery,0,0,1,NOT_LOW_BATTERY,LOW_BATTERY); // indicates state of battery
CREATE_CHAR(uint8_t,StatusTampered,0,0,1,NOT_TAMPERED,TAMPERED); // indicates whether the Service has been tampered with
CREATE_CHAR(double,SulphurDioxideDensity,0,0,1000); // measured in &micro;g/m<sup>3</sup>
CREATE_CHAR(uint8_t,SwingMode,0,0,1,SWING_DISABLED,SWING_ENABLED); // indicates whether swing-mode is enabled
CREATE_CHAR(uint8_t,TargetAirPurifierState,1,0,1,MANUAL,AUTO); // indicates desired state of air purifier
CREATE_CHAR(uint8_t,TargetFanState,1,0,1,MANUAL,AUTO); // indicates desired state of fan
CREATE_CHAR(int,TargetTiltAngle,0,-90,90); // indicated desired angle (in degrees) of slats from fully up or left (-90) to fully open (0) to fully down or right (90)
CREATE_CHAR(uint8_t,TargetHeaterCoolerState,0,0,2,AUTO,HEAT,COOL); // indicates desired state of heater/cooler
CREATE_CHAR(uint32_t,SetDuration,60,0,3600); // specifies the duration (in seconds) for a Service to remain on once activated
CREATE_CHAR(int,TargetHorizontalTiltAngle,0,-90,90); // indicates desired angle (in degrees) of slats from fully up (-90) to fully open (0) to fully down (90)
CREATE_CHAR(uint8_t,TargetHumidifierDehumidifierState,0,0,2,AUTO,HUMIDIFY,DEHUMIDIFY); // indicates desired state of humidifier/dehumidifier
CREATE_CHAR(uint8_t,TargetPosition,0,0,100); // indicates target position (as a percentage) from fully closed (0) to full open (100)
CREATE_CHAR(uint8_t,TargetDoorState,1,0,1,OPEN,CLOSED); // indicates desired state of door
CREATE_CHAR(uint8_t,TargetHeatingCoolingState,0,0,3,OFF,HEAT,COOL,AUTO); // indicates desired state of appliance
CREATE_CHAR(uint8_t,TargetMediaState,0,0,2); // unused
CREATE_CHAR(double,TargetRelativeHumidity,0,0,100); // indicates desired humidity measured as a percentage
CREATE_CHAR(double,TargetTemperature,16,10,38); // indicates desired temperature measures in Celsius
CREATE_CHAR(uint8_t,TargetVisibilityState,0,0,1,VISIBLE,NOT_VISIBLE); // indicates desired visibility of the Service, as selectable on the Settings Page of the Home App
CREATE_CHAR(uint8_t,TemperatureDisplayUnits,0,0,1,CELSIUS,FAHRENHEIT); // indicates the desired units to display the temperature on the device itself (has no effect on Home App)
CREATE_CHAR(int,TargetVerticalTiltAngle,0,-90,90); // indicates desired angle (in degrees) of slats from fully left (-90) to fully open (0) to fully right (90)
CREATE_CHAR(uint8_t,ValveType,0,0,3,GENERIC,IRRIGATION,SHOWER_HEAD,FAUCET); // indicates the type of valve
CREATE_CHAR(const char *,Version,"1.0.0",0,1); // unused
CREATE_CHAR(double,VOCDensity,0,0,1000); // measured in &micro;g/m<sup>3</sup>
CREATE_CHAR(uint8_t,Volume,0,0,100); // unused
CREATE_CHAR(uint8_t,VolumeControlType,3,0,3,NONE,RELATIVE,RELATIVE_CURRENT,ABSOLUTE); // indicates the type of volume control
CREATE_CHAR(uint8_t,VolumeSelector,0,0,1,VOLUME_UP,VOLUME_DOWN); // triggered by presses to the iPhone's volume up/down buttons when TV is selected in the Remote Control widget
CREATE_CHAR(double,WaterLevel,0,0,100); // measured as a percentage
CREATE_CHAR(UINT32_t,AccessoryFlags,1,1,1); // not applicable for HomeSpan
CREATE_CHAR(UINT8_t,Active,0,0,1,INACTIVE,ACTIVE); // indicates if the Service is active/on
CREATE_CHAR(UINT32_t,ActiveIdentifier,0,0,255); // numerical Identifier of the <b>InputSource</b> selected in the Home App.
CREATE_CHAR(UINT8_t,AirQuality,0,0,5,UNKNOWN,EXCELLENT,GOOD,FAIR,INFERIOR,POOR); // a subjective description
CREATE_CHAR(UINT8_t,BatteryLevel,100,0,100); // measured as a percentage
CREATE_CHAR(INT_t,Brightness,0,0,100); // measured as a percentage
CREATE_CHAR(FLOAT_t,CarbonMonoxideLevel,0,0,100); // measured in parts per million (ppm)
CREATE_CHAR(FLOAT_t,CarbonMonoxidePeakLevel,0,0,100); // measured in parts per million (ppm)
CREATE_CHAR(UINT8_t,CarbonMonoxideDetected,0,0,1,NORMAL,ABNORMAL); // indicates if abnormal level is detected
CREATE_CHAR(FLOAT_t,CarbonDioxideLevel,0,0,100000); // measured on parts per million (ppm)
CREATE_CHAR(FLOAT_t,CarbonDioxidePeakLevel,0,0,100000); // measured in parts per million (ppm)
CREATE_CHAR(UINT8_t,CarbonDioxideDetected,0,0,1,NORMAL,ABNORMAL); // indicates if abnormal level is detected
CREATE_CHAR(UINT8_t,ChargingState,0,0,2,NOT_CHARGING,CHARGING,NOT_CHARGEABLE); // indicates state of battery charging
CREATE_CHAR(UINT8_t,ClosedCaptions,0,0,1); // unused by any Service
CREATE_CHAR(FLOAT_t,CoolingThresholdTemperature,10,10,35); // cooling turns on when temperature (in Celsius) rises above this threshold
CREATE_CHAR(UINT32_t,ColorTemperature,200,140,500); // measured in inverse megaKelvin (= 1,000,000 / Kelvin)
CREATE_CHAR(UINT8_t,ContactSensorState,1,0,1,DETECTED,NOT_DETECTED); // indictates if contact is detected (i.e. closed)
CREATE_CHAR(STRING_t,ConfiguredName,"unnamed",NULL,NULL); // default display name of this Service
CREATE_CHAR(FLOAT_t,CurrentAmbientLightLevel,1,0.0001,100000); // measured in Lux (lumens/m<sup>2</sup>
CREATE_CHAR(INT_t,CurrentHorizontalTiltAngle,0,-90,90); // current angle (in degrees) of slats from fully up (-90) to fully open (0) to fully down (90)
CREATE_CHAR(UINT8_t,CurrentAirPurifierState,0,0,2,INACTIVE,IDLE,PURIFYING); // indicates current state of air purification
CREATE_CHAR(UINT8_t,CurrentSlatState,0,0,2,FIXED,JAMMED,SWINGING); // indicates current state of slats
CREATE_CHAR(UINT8_t,CurrentPosition,0,0,100); // current position (as a percentage) from fully closed (0) to full open (100)
CREATE_CHAR(INT_t,CurrentVerticalTiltAngle,0,-90,90); // current angle (in degrees) of slats from fully left (-90) to fully open (0) to fully right (90)
CREATE_CHAR(UINT8_t,CurrentVisibilityState,0,0,1,VISIBLE,NOT_VISIBLE); // current visibility of the Service, as selectable on the Settings Page of the Home App
CREATE_CHAR(UINT8_t,CurrentHumidifierDehumidifierState,1,0,3,INACTIVE,IDLE,HUMIDIFYING,DEHUMIDIFYING); // indicates current state of humidifier/dehumidifer
CREATE_CHAR(UINT8_t,CurrentDoorState,1,0,4,OPEN,CLOSED,OPENING,CLOSING,STOPPED); // indicates current state of a door
CREATE_CHAR(UINT8_t,CurrentFanState,1,0,2,INACTIVE,IDLE,BLOWING); // indicates current state of a fan
CREATE_CHAR(UINT8_t,CurrentHeatingCoolingState,0,0,2,IDLE,HEATING,COOLING); // indicates whether appliance is currently heating, cooling, or just idle
CREATE_CHAR(UINT8_t,CurrentHeaterCoolerState,1,0,3,INACTIVE,IDLE,HEATING,COOLING); // indicates whether appliance is currently heating, cooling, idle, or off
CREATE_CHAR(UINT8_t,CurrentMediaState,0,0,5); // not used
CREATE_CHAR(FLOAT_t,CurrentRelativeHumidity,0,0,100); // current humidity measured as a percentage
CREATE_CHAR(FLOAT_t,CurrentTemperature,0,0,100); // current temperature measured in Celsius
CREATE_CHAR(INT_t,CurrentTiltAngle,0,-90,90); // current angle (in degrees) of slats from fully up or left (-90) to fully open (0) to fully down or right (90)
CREATE_CHAR(TLV_ENC_t,DisplayOrder,NULL_TLV,NULL_TLV,NULL_TLV); // specifies the order in which the TV inputs are displayed for selection in the Home App
CREATE_CHAR(FLOAT_t,FilterLifeLevel,100,0,100); // measured as a percentage of remaining life
CREATE_CHAR(UINT8_t,FilterChangeIndication,0,0,1,NO_CHANGE_NEEDED,CHANGE_NEEDED); // indicates state of filter
CREATE_CHAR(STRING_t,FirmwareRevision,"1.0.0",NULL,NULL); // must be in form x[.y[.z]] - informational only
CREATE_CHAR(STRING_t,HardwareRevision,"1.0.0",NULL,NULL); // must be in form x[.y[.z]] - informational only
CREATE_CHAR(FLOAT_t,HeatingThresholdTemperature,16,0,25); // heating turns on when temperature (in Celsius) falls below this threshold
CREATE_CHAR(BOOL_t,HoldPosition,false,0,1); // deprecated
CREATE_CHAR(FLOAT_t,Hue,0,0,360); // color (in degrees) from red (0) to green (120) to blue (240) and back to red (360)
CREATE_CHAR(BOOL_t,Identify,1,1,1,RUN_ID=1); // triggers an update when HomeKit wants HomeSpan to run its identification routine for an Accessory
CREATE_CHAR(UINT32_t,Identifier,0,0,255); // numerical Identifer of the <b>InputSource</b>.
CREATE_CHAR(UINT8_t,InputDeviceType,0,0,6); // not used
CREATE_CHAR(UINT8_t,InputSourceType,0,0,10); // not used
CREATE_CHAR(UINT8_t,InUse,0,0,1,NOT_IN_USE,IN_USE); // if Service is set to active, this indictes whether it is currently in use
CREATE_CHAR(UINT8_t,IsConfigured,0,0,1,NOT_CONFIGURED,CONFIGURED); // indicates if a predefined Service has been configured
CREATE_CHAR(UINT8_t,LeakDetected,0,0,1,NOT_DETECTED,DETECTED); // indictates if a leak is detected
CREATE_CHAR(UINT8_t,LockCurrentState,0,0,3,UNLOCKED,LOCKED,JAMMED,UNKNOWN); // indicates state of a lock
CREATE_CHAR(UINT8_t,LockPhysicalControls,0,0,1,CONTROL_LOCK_DISABLED,CONTROL_LOCK_ENABLED); // indicates if local control lock is enabled
CREATE_CHAR(UINT8_t,LockTargetState,0,0,1,UNLOCK,LOCK); // indicates desired state of lock
CREATE_CHAR(STRING_t,Manufacturer,"HomeSpan",NULL,NULL); // any string - informational only
CREATE_CHAR(STRING_t,Model,"HomeSpan-ESP32",NULL,NULL); // any string - informational only
CREATE_CHAR(BOOL_t,MotionDetected,0,0,1,NOT_DETECTED,DETECTED); // indicates if motion is detected
CREATE_CHAR(BOOL_t,Mute,0,0,1,OFF,ON); // not used
CREATE_CHAR(STRING_t,Name,"unnamed",NULL,NULL); // default display name of the Accessory
CREATE_CHAR(FLOAT_t,NitrogenDioxideDensity,0,0,1000); // measured in &micro;g/m<sup>3</sup>
CREATE_CHAR(BOOL_t,ObstructionDetected,0,0,1,NOT_DETECTED,DETECTED); // indicates if obstruction is detected
CREATE_CHAR(FLOAT_t,PM25Density,0,0,1000); // 2.5-micron particulate density, measured in &micro;g/m<sup>3</sup>
CREATE_CHAR(UINT8_t,OccupancyDetected,0,0,1,NOT_DETECTED,DETECTED); // indicates if occupanccy is detected
CREATE_CHAR(BOOL_t,OutletInUse,0,0,1,NOT_IN_USE,IN_USE); // indicates if an appliance or light is plugged into the outlet, regardless of whether on or off
CREATE_CHAR(BOOL_t,On,0,0,1,OFF,ON); // indicates if the Service is active/on
CREATE_CHAR(FLOAT_t,OzoneDensity,0,0,1000); // measured in &micro;g/m<sup>3</sup>
CREATE_CHAR(UINT8_t,PictureMode,0,0,13); // not used
CREATE_CHAR(FLOAT_t,PM10Density,0,0,1000); // 10-micron particulate density, measured in &micro;g/m<sup>3</sup>
CREATE_CHAR(UINT8_t,PositionState,2,0,2,GOING_TO_MINIMUM,GOING_TO_MAXIMUM,STOPPED); // deprecated
CREATE_CHAR(UINT8_t,PowerModeSelection,0,0,0,VIEW_SETTINGS); // when defined, creates a "View TV Settings" button in the Home App that triggers an update to this Characteristic when pressed
CREATE_CHAR(UINT8_t,ProgramMode,0,0,2,NONE,SCHEDULED,SCHEDULE_OVERRIDEN); // indicates if pre-scheduled program is running
CREATE_CHAR(UINT8_t,ProgrammableSwitchEvent,0,0,2,SINGLE_PRESS,DOUBLE_PRESS,LONG_PRESS); // specifies type of button press
CREATE_CHAR(FLOAT_t,RelativeHumidityDehumidifierThreshold,50,0,100); // dehumidfier turns on when humidity rises above this threshold
CREATE_CHAR(FLOAT_t,RelativeHumidityHumidifierThreshold,50,0,100); // humidfier turns on when humidity falls below this threshold
CREATE_CHAR(UINT32_t,RemainingDuration,60,0,3600); // duration (in seconds) remaining for Service to be active/on
CREATE_CHAR(UINT8_t,RemoteKey,4,4,15,UP=4,DOWN,LEFT,RIGHT,CENTER,BACK,PLAY_PAUSE=11,INFO=15); // triggers an update when the corresponding key is pressed in the Remote Control widget on an iPhone
CREATE_CHAR(UINT8_t,ResetFilterIndication,1,1,1,RESET_FILTER=1); // triggers an update when the user chooses to reset the <b>FilterChangeIndication</b> (only appears in Eve App, not Home App)
CREATE_CHAR(INT_t,RotationDirection,0,0,1,CLOCKWISE,COUNTERCLOCKWISE); // indicates the rotation direction of a fan
CREATE_CHAR(FLOAT_t,RotationSpeed,0,0,100); // measured as a percentage
CREATE_CHAR(FLOAT_t,Saturation,0,0,100); // color saturation, measured as a percentage
CREATE_CHAR(UINT8_t,SecuritySystemAlarmType,0,0,1,KNOWN,UNKNOWN); // indicates whether alarm was triggered for known reason
CREATE_CHAR(UINT8_t,SecuritySystemCurrentState,3,0,4,ARMED_STAY,ARMED_AWAY,ARMED_NIGHT,DISARMED,ALARM_TRIGGERED); // indicates current state of the security system
CREATE_CHAR(UINT8_t,SecuritySystemTargetState,3,0,3,ARM_STAY,ARM_AWAY,ARM_NIGHT,DISARM); // indicates desired state of the security system
CREATE_CHAR(STRING_t,SerialNumber,"HS-12345",NULL,NULL); // any string - informational only
CREATE_CHAR(UINT8_t,ServiceLabelIndex,1,1,255); // numerical index used to distinguish multiple copies of the same Service within an Accessory
CREATE_CHAR(UINT8_t,ServiceLabelNamespace,1,0,1,DOTS,NUMERALS); // indicates how un-named Services linked together with a <b>ServiceLabel</b> Service should be displayed in the Home App
CREATE_CHAR(UINT8_t,SlatType,0,0,1,HORIZONTAL,VERTICAL); // indicates the direction of a slat or group of slats
CREATE_CHAR(UINT8_t,SleepDiscoveryMode,0,0,1); // not used
CREATE_CHAR(UINT8_t,SmokeDetected,0,0,1,NOT_DETECTED,DETECTED); // indicates if smoke is detected
CREATE_CHAR(BOOL_t,StatusActive,1,0,1,NOT_FUNCTIONING,FUNCTIONING); // indicates whether the Service is properly functioning
CREATE_CHAR(UINT8_t,StatusFault,0,0,1,NO_FAULT,FAULT); // indicates whether the Service has a fault (only appears in Eve App, not Home App)
CREATE_CHAR(UINT8_t,StatusJammed,0,0,1,NOT_JAMMED,JAMMED); // indicates whether the Service has been "jammed"
CREATE_CHAR(UINT8_t,StatusLowBattery,0,0,1,NOT_LOW_BATTERY,LOW_BATTERY); // indicates state of battery
CREATE_CHAR(UINT8_t,StatusTampered,0,0,1,NOT_TAMPERED,TAMPERED); // indicates whether the Service has been tampered with
CREATE_CHAR(FLOAT_t,SulphurDioxideDensity,0,0,1000); // measured in &micro;g/m<sup>3</sup>
CREATE_CHAR(UINT8_t,SwingMode,0,0,1,SWING_DISABLED,SWING_ENABLED); // indicates whether swing-mode is enabled
CREATE_CHAR(UINT8_t,TargetAirPurifierState,1,0,1,MANUAL,AUTO); // indicates desired state of air purifier
CREATE_CHAR(UINT8_t,TargetFanState,1,0,1,MANUAL,AUTO); // indicates desired state of fan
CREATE_CHAR(INT_t,TargetTiltAngle,0,-90,90); // indicated desired angle (in degrees) of slats from fully up or left (-90) to fully open (0) to fully down or right (90)
CREATE_CHAR(UINT8_t,TargetHeaterCoolerState,0,0,2,AUTO,HEAT,COOL); // indicates desired state of heater/cooler
CREATE_CHAR(UINT32_t,SetDuration,60,0,3600); // specifies the duration (in seconds) for a Service to remain on once activated
CREATE_CHAR(INT_t,TargetHorizontalTiltAngle,0,-90,90); // indicates desired angle (in degrees) of slats from fully up (-90) to fully open (0) to fully down (90)
CREATE_CHAR(UINT8_t,TargetHumidifierDehumidifierState,0,0,2,AUTO,HUMIDIFY,DEHUMIDIFY); // indicates desired state of humidifier/dehumidifier
CREATE_CHAR(UINT8_t,TargetPosition,0,0,100); // indicates target position (as a percentage) from fully closed (0) to full open (100)
CREATE_CHAR(UINT8_t,TargetDoorState,1,0,1,OPEN,CLOSED); // indicates desired state of door
CREATE_CHAR(UINT8_t,TargetHeatingCoolingState,0,0,3,OFF,HEAT,COOL,AUTO); // indicates desired state of appliance
CREATE_CHAR(UINT8_t,TargetMediaState,0,0,2); // unused
CREATE_CHAR(FLOAT_t,TargetRelativeHumidity,0,0,100); // indicates desired humidity measured as a percentage
CREATE_CHAR(FLOAT_t,TargetTemperature,16,10,38); // indicates desired temperature measures in Celsius
CREATE_CHAR(UINT8_t,TargetVisibilityState,0,0,1,VISIBLE,NOT_VISIBLE); // indicates desired visibility of the Service, as selectable on the Settings Page of the Home App
CREATE_CHAR(UINT8_t,TemperatureDisplayUnits,0,0,1,CELSIUS,FAHRENHEIT); // indicates the desired units to display the temperature on the device itself (has no effect on Home App)
CREATE_CHAR(INT_t,TargetVerticalTiltAngle,0,-90,90); // indicates desired angle (in degrees) of slats from fully left (-90) to fully open (0) to fully right (90)
CREATE_CHAR(UINT8_t,ValveType,0,0,3,GENERIC,IRRIGATION,SHOWER_HEAD,FAUCET); // indicates the type of valve
CREATE_CHAR(STRING_t,Version,"1.0.0",NULL,NULL); // unused
CREATE_CHAR(FLOAT_t,VOCDensity,0,0,1000); // measured in &micro;g/m<sup>3</sup>
CREATE_CHAR(UINT8_t,Volume,0,0,100); // unused
CREATE_CHAR(UINT8_t,VolumeControlType,3,0,3,NONE,RELATIVE,RELATIVE_CURRENT,ABSOLUTE); // indicates the type of volume control
CREATE_CHAR(UINT8_t,VolumeSelector,0,0,1,VOLUME_UP,VOLUME_DOWN); // triggered by presses to the iPhone's volume up/down buttons when TV is selected in the Remote Control widget
CREATE_CHAR(FLOAT_t,WaterLevel,0,0,100); // measured as a percentage
}
@ -606,38 +607,25 @@ namespace Characteristic {
#define CUSTOM_CHAR(NAME,UUID,PERMISISONS,FORMAT,DEFVAL,MINVAL,MAXVAL,STATIC_RANGE) \
HapChar _CUSTOM_##NAME {#UUID,#NAME,(PERMS)(PERMISISONS),FORMAT,STATIC_RANGE}; \
namespace Characteristic { struct NAME : SpanCharacteristic { NAME(FORMAT##_t val=DEFVAL, boolean nvsStore=false) : SpanCharacteristic {&_CUSTOM_##NAME,true} { init(val,nvsStore,(FORMAT##_t)MINVAL,(FORMAT##_t)MAXVAL); } }; }
#define CUSTOM_CHAR_STRING(NAME,UUID,PERMISISONS,DEFVAL) \
HapChar _CUSTOM_##NAME {#UUID,#NAME,(PERMS)(PERMISISONS),STRING,true}; \
namespace Characteristic { struct NAME : SpanCharacteristic { NAME(const char * val=DEFVAL, boolean nvsStore=false) : SpanCharacteristic {&_CUSTOM_##NAME,true} { init(val,nvsStore); } }; }
#define CUSTOM_CHAR_DATA(NAME,UUID,PERMISISONS) \
HapChar _CUSTOM_##NAME {#UUID,#NAME,(PERMS)(PERMISISONS),DATA,true}; \
namespace Characteristic { struct NAME : SpanCharacteristic { NAME(const char * val="AA==", boolean nvsStore=false) : SpanCharacteristic {&_CUSTOM_##NAME,true} { init(val,nvsStore); } }; }
namespace Characteristic { struct NAME : SpanCharacteristic { NAME(FORMAT##_t val=DEFVAL, boolean nvsStore=false) : SpanCharacteristic {&_CUSTOM_##NAME,true} { init<FORMAT##_t>(val,nvsStore,MINVAL,MAXVAL); } }; }
#else
#define CUSTOM_CHAR(NAME,UUID,PERMISISONS,FORMAT,DEFVAL,MINVAL,MAXVAL,STATIC_RANGE) \
extern HapChar _CUSTOM_##NAME; \
namespace Characteristic { struct NAME : SpanCharacteristic { NAME(FORMAT##_t val=DEFVAL, boolean nvsStore=false) : SpanCharacteristic {&_CUSTOM_##NAME,true} { init(val,nvsStore,(FORMAT##_t)MINVAL,(FORMAT##_t)MAXVAL); } }; }
namespace Characteristic { struct NAME : SpanCharacteristic { NAME(FORMAT##_t val=DEFVAL, boolean nvsStore=false) : SpanCharacteristic {&_CUSTOM_##NAME,true} { init<FORMAT##_t>(val,nvsStore,MINVAL,MAXVAL); } }; }
#define CUSTOM_CHAR_STRING(NAME,UUID,PERMISISONS,DEFVAL) \
extern HapChar _CUSTOM_##NAME; \
namespace Characteristic { struct NAME : SpanCharacteristic { NAME(const char * val=DEFVAL, boolean nvsStore=false) : SpanCharacteristic {&_CUSTOM_##NAME,true} { init(val,nvsStore); } }; }
#endif
#define CUSTOM_CHAR_DATA(NAME,UUID,PERMISISONS) \
extern HapChar _CUSTOM_##NAME; \
namespace Characteristic { struct NAME : SpanCharacteristic { NAME(const char * val="AA==", boolean nvsStore=false) : SpanCharacteristic {&_CUSTOM_##NAME,true} { init(val,nvsStore); } }; }
#endif
#define CUSTOM_CHAR_STRING(NAME,UUID,PERMISISONS,DEFVAL) CUSTOM_CHAR(NAME,UUID,PERMISISONS,STRING,DEFVAL,NULL,NULL,true);
#define CUSTOM_CHAR_TLV8(NAME,UUID,PERMISISONS) CUSTOM_CHAR(NAME,UUID,PERMISISONS,TLV_ENC,NULL_TLV,NULL_TLV,NULL_TLV,true);
#define CUSTOM_CHAR_DATA(NAME,UUID,PERMISISONS) CUSTOM_CHAR(NAME,UUID,PERMISISONS,DATA,NULL_DATA,NULL_DATA,NULL_DATA,true);
#define CUSTOM_SERV(NAME,UUID) \
namespace Service { struct NAME : SpanService { NAME() : SpanService{#UUID,#NAME,true}{} }; }
////////////////////////////////////////////////////////
// MACROS TO ADD A NEW ACCESSORT WITH OPTIONAL NAME //
// MACROS TO ADD A NEW ACCESSORY WITH OPTIONAL NAME //
////////////////////////////////////////////////////////
#define SPAN_ACCESSORY(...) new SpanAccessory(); new Service::AccessoryInformation(); new Characteristic::Identify(); __VA_OPT__(new Characteristic::Name(__VA_ARGS__));

View File

@ -52,7 +52,7 @@ void tlv8_t::update(size_t addLen, const uint8_t *addVal){
/////////////////////////////////////
void tlv8_t::osprint(std::ostream& os){
void tlv8_t::osprint(std::ostream& os) const {
uint8_t *p=val.get(); // starting pointer
uint8_t *pend=p+len; // ending pointer (may equal starting if len=0)
@ -68,36 +68,60 @@ void tlv8_t::osprint(std::ostream& os){
/////////////////////////////////////
TLV8_it TLV8::add(uint8_t tag, size_t len, const uint8_t* val){
TLV8_itc TLV8::add(uint8_t tag, size_t len, const uint8_t* val) {
if(!empty() && front().tag==tag)
front().update(len,val);
if(!empty() && back().getTag()==tag)
back().update(len,val);
else
emplace_front(tag,len,val);
emplace_back(tag,len,val);
return(begin());
return(--end());
}
/////////////////////////////////////
TLV8_it TLV8::find(uint8_t tag, TLV8_it it1, TLV8_it it2){
TLV8_itc TLV8::add(uint8_t tag, TLV8 &subTLV){
auto it=add(tag,subTLV.pack_size(),NULL); // create space for inserting sub TLV and store iterator to new element
subTLV.pack(*it); // pack subTLV into new element
return(--end());
}
/////////////////////////////////////
TLV8_itc TLV8::add(uint8_t tag, uint64_t val){
uint8_t *p=reinterpret_cast<uint8_t *>(&val);
size_t nBytes=sizeof(uint64_t);
while(nBytes>1 && p[nBytes-1]==0) // TLV requires little endian of size 1, 2, 4, or 8 bytes (include trailing zeros as needed)
nBytes--;
if(nBytes==3) // need to include a trailing zero so that total bytes=4
nBytes=4;
else if(nBytes>4) // need to include multiple trailing zeros so that total bytes=8
nBytes=8;
return(add(tag, nBytes, p));
}
/////////////////////////////////////
TLV8_itc TLV8::find(uint8_t tag, TLV8_itc it1, TLV8_itc it2) const {
auto it=it1;
while(it!=it2 && (*it).tag!=tag)
while(it!=it2 && it->getTag()!=tag)
it++;
return(it==it2?end():it);
return(it);
}
/////////////////////////////////////
size_t TLV8::pack_size(TLV8_it it1, TLV8_it it2){
size_t TLV8::pack_size(TLV8_itc it1, TLV8_itc it2) const {
size_t nBytes=0;
while(it1!=it2){
nBytes+=2+(*it1).len;
if((*it1).len>255)
nBytes+=2*(((*it1).len-1)/255);
nBytes+=2+(*it1).getLen();
if((*it1).getLen()>255)
nBytes+=2*(((*it1).getLen()-1)/255);
it1++;
}
@ -106,7 +130,7 @@ size_t TLV8::pack_size(TLV8_it it1, TLV8_it it2){
/////////////////////////////////////
size_t TLV8::pack(uint8_t *buf, size_t bufSize){
size_t TLV8::pack(uint8_t *buf, size_t bufSize) const {
size_t nBytes=0;
@ -114,13 +138,13 @@ size_t TLV8::pack(uint8_t *buf, size_t bufSize){
switch(currentPackPhase){
case 0:
currentPackBuf=(*currentPackIt).val.get();
endPackBuf=(*currentPackIt).val.get()+(*currentPackIt).len;
currentPackBuf=*currentPackIt;
endPackBuf=(*currentPackIt)+currentPackIt->getLen();
currentPackPhase=1;
break;
case 1:
*buf++=(*currentPackIt).tag;
*buf++=currentPackIt->getTag();
nBytes++;
currentPackPhase=2;
break;
@ -160,7 +184,10 @@ size_t TLV8::pack(uint8_t *buf, size_t bufSize){
/////////////////////////////////////
void TLV8::unpack(uint8_t *buf, size_t bufSize){
int TLV8::unpack(uint8_t *buf, size_t bufSize){
if(bufSize==0)
return(-1);
if(empty())
unpackPhase=0;
@ -171,18 +198,17 @@ void TLV8::unpack(uint8_t *buf, size_t bufSize){
case 0:
unpackTag=*buf++;
bufSize--;
add(unpackTag);
unpackPhase=1;
break;
case 1:
unpackBytes=*buf++;
bufSize--;
if(unpackBytes==0){
add(unpackTag);
if(unpackBytes==0)
unpackPhase=0;
} else {
else
unpackPhase=2;
}
break;
case 2:
@ -196,12 +222,22 @@ void TLV8::unpack(uint8_t *buf, size_t bufSize){
break;
}
}
return(unpackPhase);
}
/////////////////////////////////////
const char *TLV8::getName(uint8_t tag){
int TLV8::unpack(TLV8_itc it){
if(it==end())
return(0);
return(unpack(*it,it->getLen()));
}
/////////////////////////////////////
const char *TLV8::getName(uint8_t tag) const {
if(names==NULL)
return(NULL);
@ -216,17 +252,23 @@ const char *TLV8::getName(uint8_t tag){
/////////////////////////////////////
void TLV8::print(TLV8_it it1, TLV8_it it2){
void TLV8::print(TLV8_itc it1, TLV8_itc it2) const {
while(it1!=it2){
const char *name=getName((*it1).tag);
const char *name=getName(it1->getTag());
if(name)
Serial.printf("%s",name);
else
Serial.printf("%d",(*it1).tag);
Serial.printf("(%d) ",(*it1).len);
for(int i=0;i<(*it1).len;i++)
Serial.printf("%02X",(*it1).val.get()[i]);
Serial.printf("%d",it1->getTag());
Serial.printf("(%d) ",it1->getLen());
for(int i=0;i<it1->getLen();i++)
Serial.printf("%02X",(*it1)[i]);
if(it1->getLen()==0)
Serial.printf(" [null]");
else if(it1->getLen()<=4)
Serial.printf(" [%u]",it1->getVal());
else if(it1->getLen()<=8)
Serial.printf(" [%llu]",it1->getVal<uint64_t>());
Serial.printf("\n");
it1++;
}
@ -234,7 +276,21 @@ void TLV8::print(TLV8_it it1, TLV8_it it2){
//////////////////////////////////////
void TLV8::osprint(std::ostream& os, TLV8_it it1, TLV8_it it2){
void TLV8::printAll_r(String label) const{
for(auto it=begin();it!=end();it++){
Serial.printf("%s",label.c_str());
print(it);
TLV8 tlv;
if(tlv.unpack(*it,(*it).getLen())==0)
tlv.printAll_r(label+String((*it).getTag())+"-");
}
Serial.printf("%sDONE\n",label.c_str());
}
//////////////////////////////////////
void TLV8::osprint(std::ostream& os, TLV8_itc it1, TLV8_itc it2) const {
for(auto it=it1;it!=it2;it++)
(*it).osprint(os);

View File

@ -29,41 +29,69 @@
#include <Arduino.h>
#include <sstream>
#include <forward_list>
#include <list>
#include <memory>
#include "PSRAM.h"
struct tlv8_t {
class tlv8_t {
private:
uint8_t tag;
size_t len;
std::unique_ptr<uint8_t> val;
public:
tlv8_t(uint8_t tag, size_t len, const uint8_t* val);
void update(size_t addLen, const uint8_t *addVal);
void osprint(std::ostream& os);
operator uint8_t*() const{
void osprint(std::ostream& os) const;
operator uint8_t*() const {
return(val.get());
}
uint8_t & operator[](int index) const {
return(val.get()[index]);
}
uint8_t *get() const {
return(val.get());
}
size_t getLen() const {
return(len);
}
uint8_t getTag() const {
return(tag);
}
template<class T=uint32_t> T getVal() const {
T iVal=0;
for(int i=0;i<len;i++)
iVal|=static_cast<T>(val.get()[i])<<(i*8);
return(iVal);
}
};
/////////////////////////////////////
typedef std::forward_list<tlv8_t, Mallocator<tlv8_t>>::iterator TLV8_it;
typedef std::list<tlv8_t, Mallocator<tlv8_t>>::const_iterator TLV8_itc;
typedef struct { const uint8_t tag; const char *name; } TLV8_names;
/////////////////////////////////////
class TLV8 : public std::forward_list<tlv8_t, Mallocator<tlv8_t>> {
class TLV8 : public std::list<tlv8_t, Mallocator<tlv8_t>> {
TLV8_it currentPackIt;
TLV8_it endPackIt;
uint8_t *currentPackBuf;
uint8_t *endPackBuf;
int currentPackPhase;
size_t currentPackLen;
TLV8_itc mutable currentPackIt;
TLV8_itc mutable endPackIt;
uint8_t mutable *currentPackBuf;
uint8_t mutable *endPackBuf;
int mutable currentPackPhase;
size_t mutable currentPackLen;
uint8_t unpackTag;
size_t unpackBytes;
@ -71,44 +99,49 @@ class TLV8 : public std::forward_list<tlv8_t, Mallocator<tlv8_t>> {
const TLV8_names *names=NULL;
int nNames=0;
void printAll_r(String label) const;
public:
TLV8(){};
TLV8(const TLV8_names *names, int nNames) : names{names}, nNames{nNames} {};
TLV8_it add(uint8_t tag, size_t len, const uint8_t *val);
TLV8_it add(uint8_t tag, uint8_t val){return(add(tag, 1, &val));}
TLV8_it add(uint8_t tag){return(add(tag, 0, NULL));}
TLV8_itc add(uint8_t tag, size_t len, const uint8_t *val);
TLV8_itc add(uint8_t tag, uint64_t val);
TLV8_itc add(uint8_t tag, TLV8 &subTLV);
TLV8_itc add(uint8_t tag){return(add(tag, 0, NULL));}
TLV8_itc add(uint8_t tag, const char *val){return(add(tag, strlen(val), reinterpret_cast<const uint8_t*>(val)));}
TLV8_it find(uint8_t tag, TLV8_it it1, TLV8_it it2);
TLV8_it find(uint8_t tag, TLV8_it it1){return(find(tag, it1, end()));}
TLV8_it find(uint8_t tag){return(find(tag, begin(), end()));}
TLV8_itc find(uint8_t tag, TLV8_itc it1, TLV8_itc it2) const;
TLV8_itc find(uint8_t tag, TLV8_itc it1) const {return(find(tag, it1, end()));}
TLV8_itc find(uint8_t tag) const {return(find(tag, begin(), end()));}
int len(TLV8_it it){return(it==end()?-1:(*it).len);}
int len(TLV8_itc it) const {return(it==end()?-1:(*it).getLen());}
size_t pack_size(TLV8_it it1, TLV8_it it2);
size_t pack_size(){return(pack_size(begin(), end()));}
size_t pack_size(TLV8_itc it1, TLV8_itc it2) const;
size_t pack_size() const {return(pack_size(begin(), end()));}
void pack_init(TLV8_it it1, TLV8_it it2){currentPackIt=it1; endPackIt=it2; currentPackPhase=0;}
void pack_init(TLV8_it it1){pack_init(it1, it1++);}
void pack_init(){pack_init(begin(),end());}
void pack_init(TLV8_itc it1, TLV8_itc it2) const {currentPackIt=it1; endPackIt=it2; currentPackPhase=0;}
void pack_init(TLV8_itc it1) const {pack_init(it1, std::next(it1));}
void pack_init() const {pack_init(begin(),end());}
size_t pack(uint8_t *buf, size_t bufSize);
size_t pack(uint8_t *buf){pack_init(); return(pack(buf,pack_size()));}
size_t pack(uint8_t *buf, size_t bufSize) const;
size_t pack(uint8_t *buf) const {pack_init(); return(pack(buf,pack_size()));}
const char *getName(uint8_t tag);
const char *getName(uint8_t tag) const;
void print(TLV8_it it1, TLV8_it it2);
void print(TLV8_it it1){print(it1, it1++);}
void print(){print(begin(), end());}
void print(TLV8_itc it1, TLV8_itc it2) const;
void print(TLV8_itc it1) const {print(it1, std::next(it1));}
void print() const {print(begin(), end());}
void printAll() const {printAll_r("");}
void osprint(std::ostream& os, TLV8_it it1, TLV8_it it2);
void osprint(std::ostream& os, TLV8_it it1){osprint(os, it1, it1++);}
void osprint(std::ostream& os){osprint(os, begin(), end());}
void osprint(std::ostream& os, TLV8_itc it1, TLV8_itc it2) const;
void osprint(std::ostream& os, TLV8_itc it1) const {osprint(os, it1, std::next(it1));}
void osprint(std::ostream& os) const {osprint(os, begin(), end());}
void unpack(uint8_t *buf, size_t bufSize);
void wipe(){std::forward_list<tlv8_t, Mallocator<tlv8_t>>().swap(*this);}
int unpack(uint8_t *buf, size_t bufSize);
int unpack(TLV8_itc it);
void wipe() {std::list<tlv8_t, Mallocator<tlv8_t>>().swap(*this);}
};

View File

@ -73,6 +73,20 @@ char *Utils::readSerial(char *c, int max){
//////////////////////////////////////
char *Utils::stripBackslash(char *c){
size_t n=strlen(c);
char *p=c;
for(int i=0;i<=n;i++){
*p=c[i];
if(*p!='\\')
p++;
}
return(c);
}
//////////////////////////////////////
String Utils::mask(char *c, int n){
String s="";
int len=strlen(c);

View File

@ -35,7 +35,7 @@ namespace Utils {
char *readSerial(char *c, int max); // read serial port into 'c' until <newline>, but storing only first 'max' characters (the rest are discarded)
String mask(char *c, int n); // simply utility that creates a String from 'c' with all except the first and last 'n' characters replaced by '*'
char *stripBackslash(char *c); // strips backslashes out of c (Apple unecessesarily "escapes" forward slashes in JSON)
}
/////////////////////////////////////////////////

View File

@ -27,60 +27,61 @@
#include "HomeSpan.h"
#define MAX_LIGHTS 2
CUSTOM_CHAR(TestChar,3F4F,PR+PW,UINT8,20,0,100,false)
CUSTOM_CHAR_STRING(TestString,3F45,PR+EV,"Hello");
CUSTOM_CHAR_TLV8(TestTLV,45674F457,PW+PR);
CUSTOM_CHAR_DATA(TestData,303,PW+PW);
void setup() {
Serial.begin(115200);
homeSpan.setLogLevel(2);
homeSpan.enableWebLog();
homeSpan.setLogLevel(1);
homeSpan.enableWebLog(50,"pool.ntp.org","UTC",NULL);
// homeSpan.enableWebLog(50,"pool.ntp.org","UTC","myStatus");
// homeSpan.enableWebLog(50,NULL,NULL,NULL);
homeSpan.begin(Category::Lighting,"HomeSpan LightBulb");
homeSpan.begin(Category::Lighting,"HomeSpan Max");
new SpanUserCommand('D', " - disconnect WiFi", [](const char *buf){WiFi.disconnect();});
new SpanAccessory();
new Service::AccessoryInformation();
new Characteristic::Identify();
new Service::LightBulb();
new Characteristic::On();
new Characteristic::TestChar(30);
new Characteristic::TestString();
new Characteristic::TestString("MyName");
new Characteristic::TestTLV();
Characteristic::TestData *testData = new Characteristic::TestData();
new SpanAccessory();
new Service::AccessoryInformation();
new Characteristic::Identify();
TLV8 myTLV;
for(int i=0;i<MAX_LIGHTS;i++){
new SpanAccessory();
new Service::AccessoryInformation();
new Characteristic::Identify();
char c[30];
sprintf(c,"Light-%d",i);
new Characteristic::Name(c);
new Service::LightBulb();
new Characteristic::On(0,false);
WEBLOG("Configuring %s",c);
}
myTLV.add(5,0x20);
myTLV.add(5,0x30);
myTLV.add(1);
myTLV.add(5,255);
new SpanUserCommand('w', " - get web log test",webLogTest); // simulate getting an HTTPS request for weblog
Characteristic::TestTLV *testTLV = new Characteristic::TestTLV(myTLV);
size_t n=testTLV->getData(NULL,0);
uint8_t buf[n];
testTLV->getData(buf,n);
Serial.printf("\n");
for(int i=0;i<n;i++)
Serial.printf("%d %0X\n",i,buf[i]);
Serial.printf("\n");
testData->setData(buf,8);
}
}
//////////////////////////////////////
void loop(){
homeSpan.poll();
homeSpan.poll();
}
//////////////////////////////////////
void webLogTest(const char *dummy){
Serial.printf("\n*** In Web Log Test. Starting Custom Web Log Handler\n"); // here is where you would perform any HTTPS initializations
homeSpan.getWebLog(webLogHandler,NULL); // this starts the normal weblog with output redirected to the specified handler (below)
}
void webLogHandler(const char *buf, void *args){
if(buf!=NULL){
Serial.printf("--------\n");
Serial.printf("%s",buf); // here is where you would transmit data to the HTTPS connection
Serial.printf("********\n");
}
else
Serial.print("*** DONE!\n\n"); // here is where you would close the HTTPS connection
}

View File

@ -35,16 +35,18 @@
// Single-Wire RGB/RGBW NeoPixels //
////////////////////////////////////////////
Pixel::Pixel(int pin, boolean isRGBW){
Pixel::Pixel(int pin, pixelType_t pixelType){
rf=new RFControl(pin,false,false); // set clock to 1/80 usec, no default driver
if(!*rf)
return;
if(isRGBW)
this->lastBit=0;
map=pixelType;
if(map[3])
bytesPerPixel=4;
else
this->lastBit=8;
bytesPerPixel=3;
setTiming(0.32, 0.88, 0.64, 0.56, 80.0); // set default timing parameters (suitable for most SK68 and WS28 RGB pixels)
@ -82,10 +84,10 @@ void Pixel::set(Color *c, int nPixels, boolean multiColor){
status.nPixels=nPixels;
status.color=c;
status.iMem=0;
status.iBit=32;
status.started=true;
status.px=this;
status.multiColor=multiColor;
status.iByte=0;
loadData(this); // load first two bytes of data to get started
loadData(this);
@ -112,12 +114,15 @@ void IRAM_ATTR Pixel::loadData(void *arg){
RMTMEM.chan[status.px->rf->getChannel()].data32[status.iMem].val=0;
return;
}
int startBit=status.px->map[status.iByte];
int endBit=startBit-8;
for(int i=0;i<8;i++)
RMTMEM.chan[status.px->rf->getChannel()].data32[status.iMem++].val=status.px->pattern[(status.color->val>>(--status.iBit))&1];
if(status.iBit==status.px->lastBit){
status.iBit=32;
for(int iBit=startBit;iBit>endBit;iBit--)
RMTMEM.chan[status.px->rf->getChannel()].data32[status.iMem++].val=status.px->pattern[(status.color->val>>iBit)&1];
if(++status.iByte==status.px->bytesPerPixel){
status.iByte=0;
status.color+=status.multiColor;
status.nPixels--;
}

View File

@ -37,20 +37,38 @@
[[maybe_unused]] static const char* PIXEL_TAG = "Pixel";
typedef const uint8_t pixelType_t[];
namespace PixelType {
pixelType_t RGB={31,23,15,0};
pixelType_t RBG={31,15,23,0};
pixelType_t BRG={23,15,31,0};
pixelType_t BGR={15,23,31,0};
pixelType_t GBR={15,31,23,0};
pixelType_t GRB={23,31,15,0};
pixelType_t RGBW={31,23,15,7};
pixelType_t RBGW={31,15,23,7};
pixelType_t BRGW={23,15,31,7};
pixelType_t BGRW={15,23,31,7};
pixelType_t GBRW={15,31,23,7};
pixelType_t GRBW={23,31,15,7};
};
////////////////////////////////////////////
// Single-Wire RGB/RGBW NeoPixels //
////////////////////////////////////////////
class Pixel : public Blinkable {
public:
public:
struct Color {
union{
struct {
uint8_t white:8;
uint8_t blue:8;
uint8_t red:8;
uint8_t green:8;
uint8_t red:8;
};
uint32_t val;
};
@ -121,11 +139,11 @@ class Pixel : public Blinkable {
struct pixel_status_t {
int nPixels;
Color *color;
int iBit;
int iMem;
boolean started;
Pixel *px;
boolean multiColor;
int iByte;
};
RFControl *rf; // Pixel utilizes RFControl
@ -133,7 +151,8 @@ class Pixel : public Blinkable {
uint32_t resetTime; // minimum time (in usec) between pulse trains
uint32_t txEndMask; // mask for end-of-transmission interrupt
uint32_t txThrMask; // mask for threshold interrupt
uint32_t lastBit; // 0=RGBW; 8=RGB
uint8_t bytesPerPixel; // RGBW=4; RGB=3
const uint8_t *map; // color map representing order in which color bytes are transmitted
Color onColor; // color used for on() command
const int memSize=sizeof(RMTMEM.chan[0].data32)/4; // determine size (in pulses) of one channel
@ -142,14 +161,16 @@ class Pixel : public Blinkable {
volatile static pixel_status_t status; // storage for volatile information modified in interupt handler
public:
Pixel(int pin, boolean isRGBW=false); // creates addressable single-wire RGB (false) or RGBW (true) LED connected to pin (such as the SK68 or WS28)
void set(Color *c, int nPixels, boolean multiColor=true); // sets colors of nPixels based on array of Colors c; setting multiColor to false repeats Color in c[0] for all nPixels
void set(Color c, int nPixels=1){set(&c,nPixels,false);} // sets color of nPixels to be equal to specific Color c
Pixel(int pin, pixelType_t pixelType=PixelType::GRB); // creates addressable single-wire LED of pixelType connected to pin (such as the SK68 or WS28)
void set(Color *c, int nPixels, boolean multiColor=true); // sets colors of nPixels based on array of Colors c; setting multiColor to false repeats Color in c[0] for all nPixels
void set(Color c, int nPixels=1){set(&c,nPixels,false);} // sets color of nPixels to be equal to specific Color c
static Color RGB(uint8_t r, uint8_t g, uint8_t b, uint8_t w=0){return(Color().RGB(r,g,b,w));} // an alternative method for returning an RGB Color
static Color HSV(float h, float s, float v, double w=0){return(Color().HSV(h,s,v,w));} // an alternative method for returning an HSV Color
int getPin(){return(rf->getPin());} // returns pixel pin if valid, else returns -1
boolean isRGBW(){return(bytesPerPixel==4);} // returns true if RGBW LED, else false if RGB LED
void setTiming(float high0, float low0, float high1, float low1, uint32_t lowReset); // changes default timings for bit pulse - note parameters are in MICROSECONDS
operator bool(){ // override boolean operator to return true/false if creation succeeded/failed
@ -159,6 +180,10 @@ class Pixel : public Blinkable {
void on() {set(onColor);}
void off() {set(RGB(0,0,0,0));}
Pixel *setOnColor(Color c){onColor=c;return(this);}
[[deprecated("Please use Pixel(int pin, pixelType_t pixelType) constructor instead.")]]
Pixel(int pin, boolean isRGBW):Pixel(pin,isRGBW?PixelType::GRBW:PixelType::GRB){};
};
////////////////////////////////////////////

View File

@ -251,16 +251,21 @@ void ServoPin::set(double degrees){
if(!channel)
return;
double usec=(degrees-minDegrees)*microsPerDegree+minMicros;
if(!isnan(degrees)){
double usec=(degrees-minDegrees)*microsPerDegree+minMicros;
if(usec<minMicros)
usec=minMicros;
else if(usec>maxMicros)
usec=maxMicros;
usec*=timer->freq_hz/1e6*(pow(2,(int)timer->duty_resolution)-1);
channel->duty=usec;
} else {
channel->duty=0;
}
if(usec<minMicros)
usec=minMicros;
else if(usec>maxMicros)
usec=maxMicros;
usec*=timer->freq_hz/1e6*(pow(2,(int)timer->duty_resolution)-1);
channel->duty=usec;
ledc_channel_config(channel);
}

View File

@ -25,48 +25,40 @@
*
********************************************************************************/
// This is a placeholder .ino file that allows you to easily edit the contents of this files using the Arduino IDE,
// as well as compile and test from this point. This file is ignored when the library is included in other sketches.
#include "PwmPin.h"
#include "StepperControl.h"
StepperControl *bigMotor;
StepperControl *smallMotor;
#define BIG_MOTOR_POSITION 1600
#define SMALL_MOTOR_POSITION 2064
///////////////////
ServoPin servo(21,0,500,2200,-60,60);
void setup() {
Serial.begin(115200);
delay(1000);
Serial.printf("\nHomeSpan Stepper Control\n\n");
bigMotor=(new Stepper_TB6612(23,32,22,14,33,27))->setStepType(StepperControl::HALF_STEP)->setAccel(10,20);
smallMotor=new Stepper_A3967(18,21,5,4,19);
Serial.print("\n\nReady\n\n");
// smallMotor->setStepType(StepperControl::EIGHTH_STEP);
for(int count=0;count<3;count++){
for(int i=-60;i<61;i++){
servo.set(i);
delay(10);
}
for(int i=60;i>-61;i--){
servo.set(i);
delay(10);
}
}
delay(5000);
servo.set(NAN);
delay(10000);
servo.set(0);
// bigMotor->setStepType(StepperControl::HALF_STEP);
// bigMotor->setAccel(10,20);
}
///////////////////
//////////////////////////////////////
void loop(){
if(smallMotor->position()==0)
smallMotor->moveTo(SMALL_MOTOR_POSITION,2);
else if(smallMotor->position()==SMALL_MOTOR_POSITION)
smallMotor->moveTo(0,2);
if(bigMotor->position()==0)
bigMotor->moveTo(BIG_MOTOR_POSITION,4);
else if(bigMotor->position()==BIG_MOTOR_POSITION)
bigMotor->moveTo(0,4);
delay(1000);
Serial.printf("Small Motor: %d Big Motor %d\n",smallMotor->stepsRemaining(),bigMotor->stepsRemaining());
}

67
src/version.h Normal file
View File

@ -0,0 +1,67 @@
/*********************************************************************************
* MIT License
*
* Copyright (c) 2020-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*
********************************************************************************/
#pragma once
//////////////////////////////////////////////////////
// HomeSpan Version //
#define HS_MAJOR 1
#define HS_MINOR 9
#define HS_PATCH 1
//////////////////////////////////////////////////////
#ifndef ARDUINO_ARCH_ESP32
#error ERROR: HOMESPAN IS ONLY AVAILABLE FOR ESP32 MICROCONTROLLERS!
#include <FATAL_ERROR>
#endif
#include <esp_arduino_version.h>
#if ESP_ARDUINO_VERSION_MAJOR!=2
#error ERROR: HOMESPAN REQUIRES VERSION 2 OF THE ARDUINO ESP32 LIBRARY. HOMESPAN IS NOT COMPATIBLE WITH VERSION 1 OR VERSION 3
#include <FATAL_ERROR>
#endif
#define STRINGIFY(x) _STR(x)
#define _STR(x) #x
#define HOMESPAN_VERSION STRINGIFY(HS_MAJOR) "." STRINGIFY(HS_MINOR) "." STRINGIFY(HS_PATCH)
#define VERSION(major,minor,patch) major*10000+minor*100+patch
#ifndef REQUIRED
#define REQUIRED 0
#endif
#if (REQUIRED>VERSION(HS_MAJOR,HS_MINOR,HS_PATCH))
#error ERROR: THIS SKETCH REQUIRES A LATER VERSION OF THE HOMESPAN LIBRARY
#include <FATAL_ERROR>
#endif
#define ARDUINO_ESP_VERSION STRINGIFY(ESP_ARDUINO_VERSION_MAJOR) "." STRINGIFY(ESP_ARDUINO_VERSION_MINOR) "." STRINGIFY(ESP_ARDUINO_VERSION_PATCH)

View File

@ -54,6 +54,8 @@ BEGIN {
uuid[char]=x[3]
perms[char]=x[4]
format[char]=tolower(x[5])
if(format[char]=="tlv_enc")
format[char]="tlv8"
static[char]=x[6]
}
@ -82,7 +84,7 @@ END {
printf("<td align=\"center\">%s</td>",format[char])
printf("<td align=\"center\">%s</td>",perms[char])
if(format[char]!="string")
if(format[char]!="string" && format[char]!="tlv8" && format[char]!="data")
printf("<td align=\"center\">%s</td><td align=\"center\">%s</td>",min[char],max[char])
else
printf("<td align=\"center\">-</td><td align=\"center\">-</td>")