From 7e9e432991c20a7d261bd91cfed7ab306f5fa05d Mon Sep 17 00:00:00 2001 From: HomeSpan Date: Sun, 7 Jan 2024 12:05:36 -0600 Subject: [PATCH 01/12] Update Stepper.md --- docs/Stepper.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/docs/Stepper.md b/docs/Stepper.md index 3f89bea..22a1727 100644 --- a/docs/Stepper.md +++ b/docs/Stepper.md @@ -136,7 +136,7 @@ Below is a simple sketch demonstrating the above methods: ```C++ // StepperControl Example using TB6612-based Driver Board with HALF STEP PWM MODE -#include "Stepper_TB6612.h" // include the driver for a TB6612 chip +#include "extras/Stepper_TB6612.h" // include the driver for a TB6612 chip StepperControl *motor; // create a global pointer to StepperControl so it can be accessed in both setup() and loop() @@ -199,7 +199,7 @@ Only the first method, `onStep()`, is required to be defined. You can leave any As an example, below is the complete code for the **Stepper_A3967** class: ```C++ -#include "StepperControl.h" +#include "extras/StepperControl.h" ////////////////////////// From e118061cff59c88ade0d8f17ebd7d508de7ccab5 Mon Sep 17 00:00:00 2001 From: HomeSpan Date: Tue, 16 Jan 2024 06:07:41 -0600 Subject: [PATCH 02/12] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index b0b59f8..0897c26 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ 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.11 (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.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 Highlights From 84b3d29954fd91e4ea0d5544c5f6f903a0a7b384 Mon Sep 17 00:00:00 2001 From: HomeSpan Date: Sat, 20 Jan 2024 18:10:11 -0600 Subject: [PATCH 03/12] Update FAQ.md --- docs/FAQ.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/FAQ.md b/docs/FAQ.md index 8164dcd..bedebf6 100644 --- a/docs/FAQ.md +++ b/docs/FAQ.md @@ -76,7 +76,7 @@ #### 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 stanadlone 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. --- [↩️](../README.md) Back to the Welcome page From 3563dc109a28025b50fd25392955540089bf299c Mon Sep 17 00:00:00 2001 From: HomeSpan Date: Sun, 21 Jan 2024 10:14:11 -0600 Subject: [PATCH 04/12] Update TVServices.md --- docs/TVServices.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/TVServices.md b/docs/TVServices.md index ee0754e..4af359e 100644 --- a/docs/TVServices.md +++ b/docs/TVServices.md @@ -50,7 +50,7 @@ All of this is accomplished by using a combination of some, or all, of the follo * `Characteristic::ConfiguredName()` - similar to how its used when applied to `Service::Television()`, this Characteristic allows you set the default name for an Input Source. Note that if you change the name of an Input Source in the Home App, an update will be sent to HomeSpan with the new name for you to use in your sketch if needed. This is very different from the usual `Characteristic::Name()` used for many other Services, and for which name changes performed in the Home App are never communicated back to the Accessory -* `Characteristic::Identifier()` - this numerical Characteristic sets an ID for each Input Source. Any unsigned 32-bit number can be used as an ID, provided it is *unique* and not used by any other Input Source in the same TV Service. When you use the Input Source Selector in the Home App to choose a particular Input Soure, the `Characteristic::ActiveIdentifier()` from the Television Service (see above) will be updated with a value that matches the ID corresponding to the chosen Input Source. Within HomeSpan you simply use the `update()` method to determine when `Characteristic::ActiveIdentifer()` is updated, and, based on its value, which Input Source was chosen. HomeKit does not seem to require `Characteristic::Identifier()` be defined for an Input Source. However, if it not set, the Home App will not allow it to be displayed as a choice in the Input Source Selector, which defeats the purpose of creating an Input Source! +* `Characteristic::Identifier()` - this numerical Characteristic sets an ID for each Input Source. Any unsigned 32-bit number can be used as an ID, provided it is *unique* and not used by any other Input Source in the same TV Service. When you use the Input Source Selector in the Home App to choose a particular Input Source, the `Characteristic::ActiveIdentifier()` from the Television Service (see above) will be updated with a value that matches the ID corresponding to the chosen Input Source. Within HomeSpan you simply use the `update()` method to determine when `Characteristic::ActiveIdentifer()` is updated, and, based on its value, which Input Source was chosen. HomeKit does not seem to require `Characteristic::Identifier()` be defined for an Input Source. However, if it not set, the Home App will not allow it to be displayed as a choice in the Input Source Selector, which defeats the purpose of creating an Input Source! * `Characteristic::IsConfigured()` - this Characteristic determines whether an Input Source is allowed to appear as a choice in the Input Source Selector of the Home App. If IsConfigured() is defined and set to 0, the Input Source will appear in the Settings page, but it will be excluded as a choice from the Input Source Selector. If IsConfigured() is defined and set to 1, the Input Source will appear in the Settings page, and will also be included as a choice in the Input Source Selector. If `Characteristic::IsConfigured()` is not defined for an Input Source, that source will still appear as a choice in the Input Source Selector, but it will *not* appear in the list of Input Sources found on the Settings page. This means you will not be able to rename the Input Source from the Home App, nor toggle it as an allowable choice in the Input Selector (see below) From d10f73e3c72c3e7775bd03b5635ea55e0565754c Mon Sep 17 00:00:00 2001 From: HomeSpan Date: Sat, 17 Feb 2024 18:11:17 -0500 Subject: [PATCH 05/12] 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::buf(tagType tag, int len)` Also updated HAP.cpp to use new `uint8_t *TLV::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 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 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 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 instead of 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 Co-authored-by: Francois Co-authored-by: Michael Geramb Co-authored-by: frankonski --- README.md | 101 +- docs/Logging.md | 60 +- docs/NOW.md | 10 + docs/PWM.md | 4 +- docs/Pixels.md | 4 - docs/RMT.md | 5 +- docs/Reference.md | 126 +- docs/ServiceList.md | 620 ++++-- docs/Solutions.md | 12 +- docs/Stepper.md | 36 +- docs/StepperDrivers/Stepper_A3967.md | 8 +- docs/StepperDrivers/Stepper_TB6612.md | 2 +- docs/StepperDrivers/Stepper_ULN2003A.md | 37 + docs/StepperDrivers/Stepper_UNIPOLAR.md | 73 + docs/Tutorials.md | 10 +- examples/06-DimmableLED/06-DimmableLED.ino | 11 +- examples/06-DimmableLED/DEV_LED.h | 2 - .../07-AccessoryNames/07-AccessoryNames.ino | 12 +- examples/07-AccessoryNames/DEV_LED.h | 2 - examples/08-Bridges/DEV_LED.h | 2 - examples/09-MessageLogging/DEV_LED.h | 2 - examples/10-RGB_LED/DEV_LED.h | 4 - examples/11-ServiceNames/11-ServiceNames.ino | 179 +- examples/13-TargetStates/DEV_DoorsWindows.h | 7 +- examples/15-RealPushButtons/DEV_LED.h | 4 - .../17-LinkedServices/17-LinkedServices.ino | 28 +- examples/18-SavingStatus/DEV_LED.h | 4 - .../CustomNVSPartition/CustomNVSPartition.ino | 138 ++ .../CustomNVSPartition/partitions.csv | 14 + .../ExternalReference/ExternalReference.ino | 119 ++ .../Other Examples/FadingLED/FadingLED.ino | 1 - .../MotorizedWindowShade.ino | 2 - examples/Other Examples/Pixel/Pixel.ino | 13 +- .../RemoteControl/RemoteControl.ino | 1 - .../RemoteDevice/RemoteDevice.ino | 3 +- .../ServoControl/DEV_DoorsWindows.h | 4 - library.properties | 2 +- src/Characteristics.h | 2 +- src/FeatherPins.h | 4 +- src/HAP.cpp | 1853 ++++++++--------- src/HAP.h | 172 +- src/HAPConstants.h | 3 +- src/HKDF.cpp | 2 +- src/HKDF.h | 2 +- src/HapQR.h | 2 +- src/HomeSpan.cpp | 594 +++--- src/HomeSpan.h | 233 ++- src/Network.cpp | 41 +- src/Network.h | 7 +- src/PSRAM.h | 61 + src/SRP.cpp | 278 ++- src/SRP.h | 74 +- src/Settings.h | 12 +- src/Span.h | 858 ++++---- src/TLV.h | 314 --- src/TLV8.cpp | 243 +++ src/TLV8.h | 114 + src/Utils.cpp | 4 +- src/Utils.h | 76 +- src/src.ino | 92 +- src/src/extras/Blinker.cpp | 2 +- src/src/extras/Blinker.h | 2 +- src/src/extras/Pixel.cpp | 2 +- src/src/extras/Pixel.h | 2 +- src/src/extras/PwmPin.cpp | 2 +- src/src/extras/PwmPin.h | 2 +- src/src/extras/RFControl.cpp | 2 +- src/src/extras/RFControl.h | 2 +- src/src/extras/StepperControl.cpp | 2 +- src/src/extras/StepperControl.h | 12 +- src/src/extras/Stepper_A3967.h | 8 +- src/src/extras/Stepper_TB6612.h | 9 +- src/src/extras/Stepper_UNIPOLAR.h | 169 ++ src/src/extras/extras.ino | 5 +- tools/makeServiceList | 6 + tools/makeServices | 109 + 76 files changed, 4162 insertions(+), 2877 deletions(-) create mode 100644 docs/StepperDrivers/Stepper_ULN2003A.md create mode 100644 docs/StepperDrivers/Stepper_UNIPOLAR.md create mode 100644 examples/Other Examples/CustomNVSPartition/CustomNVSPartition.ino create mode 100644 examples/Other Examples/CustomNVSPartition/partitions.csv create mode 100644 examples/Other Examples/ExternalReference/ExternalReference.ino create mode 100644 src/PSRAM.h delete mode 100644 src/TLV.h create mode 100644 src/TLV8.cpp create mode 100644 src/TLV8.h create mode 100644 src/src/extras/Stepper_UNIPOLAR.h create mode 100755 tools/makeServiceList create mode 100755 tools/makeServices diff --git a/README.md b/README.md index 0897c26..33d0b42 100644 --- a/README.md +++ b/README.md @@ -6,13 +6,16 @@ HomeSpan provides a microcontroller-focused implementation of Apple's HomeKit Ac 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. +> [!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. + ### HomeSpan Highlights * Provides a natural, intuitive, and **very** easy-to-use framework * Utilizes a unique *Service-Centric* approach to creating HomeKit devices * Takes full advantage of the widely-popular Arduino IDE * 100% HAP-R2 compliance -* 41 integrated HomeKit Services +* 38 integrated HomeKit Services * Operates in either Accessory or Bridge mode * Supports pairing with Setup Codes or QR Codes @@ -49,40 +52,82 @@ 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.8.0 (7/8/2023) +## ❗Latest Update - HomeSpan 1.9.0 (2/17/2024) -* **New Stepper Motor Control!** +* **HomeSpan has been optimized to use significantly less RAM!** - * adds new **StepperControl** class that allows for smooth, uninterrupted operation of one or more stepper motors running in the background while HomeSpan continues to run simultaneously in the foreground - * supports driver boards with or without PWM, including microstepping modes - * supports automatic acceleration and deceleration for smooth starts and stops - * motors can be set to an absolute position or instructucted to move a specified number of steps - * provides options to automatically enter into a "brake" state after motor stops to conserve power - * includes a fully worked example of a motorized window shade - * see [Stepper Motor Control](docs/Stepper.md) for details - -* **Upgrades to HomeSpan Web Log output** + * 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 method `void homeSpan.setWebLogCSS(const char *css)` that allows you to define *Custom Style Sheets (CSS)* for the Web Log text, tables, and background - * adds version numbers for the Sodium and MbedTLS libraries, HomeKit pairing status, and a text description of Reset Reason code +* **HomeSpan has been optimized to use significantly less Non-Volatile Storage (NVS)** + + * 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 + +* **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 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 -* **Upgrades to Web Log Time Server initialization** +* **Added ability to "chain" *homeSpan* methods** - * the process for retrieving the time and date from an NTP server upon booting now runs in the background as a separate task - * HomeSpan is no longer blocked from running during the NTP query + * 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 -* **Adds new methods to disable HomeSpan's use of the USB Serial port** - - * new Log Level, -1, causes HomeSpan to suppress all OUTPUT messages - * new homeSpan method `setSerialInputDisable(boolean val)` disables/re-enables HomeSpan's reading of CLI commands INPUT into the Arduino Serial Monitor +* **Added ability to disable SpanPoint encryption** -* **Adds ability to use a non-standard LED as the HomeSpan Status LED** + * without encryption increases the maximum number of allowed SpanPoint devices from 7 to 20 + * see [SpanPoint](docs/NOW.md) for details + +* **Other new *homeSpan* methods included in this release:** - * new homeSpan method `setStatusDevice(Blinkable *sDev)` sets the Status LED to the Blinkable object *sDev* - * allows an LED connected to a pin expander, or any other non-standard LED controller (such as an inverted LED that lights when a pin is LOW instead of HIGH) to be used as the HomeSpan Status LED - * see [Blinkable.md](docs/Blinkable.md) for details (including an example) on how to create Blinkable objects - + * `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 + +* **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* + +> [!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. + See [Releases](https://github.com/HomeSpan/HomeSpan/releases) for details on all changes and bug fixes included in this update. # HomeSpan Resources @@ -116,9 +161,7 @@ Note that all documentation is version-controlled and tied to each branch. The # External Resources -In addition to HomeSpan resources, developers who are new to HomeKit programming should download Apple's HomeKit Accessory Protocol Specification, Non-Commercial Version, Release R2 (HAP-R2). This document is unfortunately no longer available from Apple (perhaps because it was last updated July, 2019, and is now somewhat out-of-date). However, you may be able find copies of this document elsewhere on the web. Note Apple has not replaced the HAP-R2 document with any other versions for non-commercial use, and Apple's open-source [HomeKit ADK](https://github.com/apple/HomeKitADK) only reflects the original HAP-R2 specs (rather than all the latest Services and Characteristics available in HomeKit for commercial devices). - -You ***do not*** need to read the entire HAP-R2 document. The whole point of HomeSpan is that it implements all the required HAP operations under the hood so you can focus on just programming whatever logic is needed to control your real-world appliances (lights, fans, RF remote controls, etc.) with the device. However, you will find Chapters 8 and 9 of the HAP guide to be an invaluable reference as it lists and describes all of the Services and Characteristics implemented in HomeSpan, many of which you will routinely utilize in your own HomeSpan sketches. +In addition to HomeSpan resources, developers who are new to HomeKit programming may find useful Chapters 8 and 9 of Apple's HomeKit Accessory Protocol Specification, Non-Commercial Version, Release R2 (HAP-R2). This document is unfortunately no longer available from Apple (perhaps because it was last updated July, 2019, and is now somewhat out-of-date). However, you may be able find copies of this document elsewhere on the web. Note Apple has not replaced the HAP-R2 document with any other versions for non-commercial use, and Apple's open-source [HomeKit ADK](https://github.com/apple/HomeKitADK) only reflects the original HAP-R2 specs (rather than all the latest Services and Characteristics available in HomeKit for commercial devices). --- diff --git a/docs/Logging.md b/docs/Logging.md index 66d09f0..0529df5 100644 --- a/docs/Logging.md +++ b/docs/Logging.md @@ -53,7 +53,7 @@ To enable Web Logging (it's turned off by default), call the method `homeSpan.en * the total number of WEBLOG() messages to be stored - older messages are discarded in favor of newer ones once the limit you set is reached * the URL of an NTP time server - this is optional and only needed if you want to set the clock of the device at start-up * the time zone for the device - this is only needed if an NTP time server has been specified -* the URL of the Web Log page - if unspecified, HomeSpan will serve the Web Log at a page named "status" +* the URL of the Web Log page - if unspecified, HomeSpan will serve the Web Log at a page named "status". If set to NULL, HomeSpan will process Web Log data but will *not* serve any Web Log pages to any HTTP requests. However, Web Log data in the form of a finished HTML page can still be accessed by the user by calling `homeSpan.getWebLog()` as described further below Additional notes: @@ -81,7 +81,63 @@ For example, the following CSS changes the background color of the Web Log page ``` Note that HomeSpan outputs the full content of the Web Log HTML, including whatever CSS you may have specified above, to the Serial Monitor whenever the Log Level is set to 1 or greater. Reviewing this output can be helpful when creating your own CSS. - + +### Adding User-Defined Data and/or Custom HTML + +Homespan provides a hook into the text used to generate the Web Log that you can extend to add your own data to the initial table as well as more generally add any custom HTML. + +To access this text, set a Web Log callback using `homeSpan.setWebLogCallback(void (*func)(String &htmlText))` where + + * *func* is a function of type *void* that takes a single argument of type *String*, and + * *htmlText* will be set by HomeSpan to a String reference containing all the HTML text that the Web Log has already generated to produce the initial table. + +To add your own data to the table, simply extend the String *htmlText* by adding as many `` and `` HTML tags as needed. If you wish to end the table and add any other HTML, simple include the `` tag in *htmlText*, and then add any other custom HTML. For example, the following function could be used to extend the initial Web Log table to show free DRAM, end the table, and provide a hot link to the HomeSpan Repo: + +```C++ +void extraData(String &r){ + r+="Free DRAM:" + String(esp_get_free_internal_heap_size()) + " bytes\n"; + r+="

Click Here to Access HomeSpan Repo

"; +} +``` + +To embed this custom HTML text in the Web Log, call `homeSpan.setWebLogCallback(extraData)` in your sketch. + +### Accessing Web Log HTML from within your sketch + +In addition to (or as an alternative to) having HomeSpan serve HTML Web Log pages in response to HTTP requests, users can directly access the HTML text for a Web Log page from within their sketch for customized processing and handling. Since the HTML for a Web Log page can be very large, HomeSpan only generates the HTML for a Web Log page when the page has been requested, and streams the HTML in sequential chunks of 1024 bytes in response to a Web Log HTTP request. It is therefore not possible for HomeSpan to simply provide the user with a `char *` pointer to the HTML text for a complete Web Log. Instead, HomeSpan provides the user with the following *homeSpan* method to trigger the production of a Web Log page and access the resulting HTML text whenever needed: + +`getWebLog(void (*f)(const char *htmlText, void *data), void *userData)` + + * *f()* - a user-defined function that returns `void` and takes two arguments: + * *htmlText* - a null-terminated `const char *` pointer to a chunk of HTML text (max 1024 bytes) provided by HomeSpan + * *data* - a `void *` pointer to any user-provided data, *userData* + * *userData* - a `void *` pointer to any optional user-provided data that is passed to *f()* as its second argument, *data* + +When the above method is called from a sketch, HomeSpan will repeatedly call the user-defined function *f()* and provide sequential chunks of HTML text for the Web Log page as the first argument, *htmlText*. Once all HTML chunks have been sent to the function *f()*, HomeSpan calls *f()* one final time with *htmlText* set to NULL to indicate there are no more HTML chunks to be sent. + +The primary purpose of this function is for the user to provide their own method of serving an HTML Web Log page, such as through a secure HTTPS channel. Note this channel can be in addition to, or instead of, HomeSpan's normal serving of Web Log pages through HTTP requests depending on whether or not the URL argument used in the `homeSpan.enableWebLog()` method was set to NULL (disabling HomeSpan from serving Web Log pages in response to HTTP requests). + +The following psuedo-code snippet shows how `getWebLog()` can be used: + +```C++ +... +homeSpan.enableWebLog(50,"pool.ntp.org","UTC",NULL); // this enables the Web Log for 50 entries and sets the clock, but prevents HomeSpan from responding to any HTTP requests for a Web Log page +... +IF WEBLOG NEEDED THEN{ + homeSpan.getWebLog(myWebLogHandler,NULL); // this triggers HomeSpan to produce the HTML text for a Web Log page and stream the data to myWebLogHandler without any extra user data +} +... +void myWebLogHandler(const char *htmlText, void *args){ // this is the user-defined Web Log handler (note the optional *arg parameter is not used in this example) + if(htmlText!=NULL){ + DO SOMETHING WITH htmlText (e.g. transmit it to the user via an HTTPS connection) + } + else + PERFORM ANY CLEAN-UP PROCESSING (e.g. close the HTTPS connection) + } +} +``` + + --- diff --git a/docs/NOW.md b/docs/NOW.md index bd8f82e..986b7e0 100644 --- a/docs/NOW.md +++ b/docs/NOW.md @@ -61,6 +61,16 @@ Also note that regardless of whether or not the queue if full, if the size of a * if used, this method must be called *before* the instantiation of any SpanPoint objects. Example: `SpanPoint::setPassword("MyPassword");` * the same passphrase must be used among all devices that are communicating via SpanPoint, else the receiving device will not be able to decrypt messages it receives +* `static void setEncryption(boolean encrypt)` + + * this *optional* **class-level** method provides the ability to enable or disable encryption according to whether *encrypt* is set to *true* or *false* + * by default, encryption is normally enabled (using the password above) + * if used, this method must be called *before* the instantiation of any SpanPoint objects. Example: `SpanPoint::setEncryption(false);` disables encryption for all SpanPoint connections + * note that this is a global setting - if SpanPoint encryption is disabled on the main device, it must also be disabled on every remote device, else communication between devices will fail + * enabling/disabling encryption impacts that total number of SpanPoint connections that can be supported by the ESP32's ESP-NOW functionality: + * with encryption enabled, the ESP32 can support a maximum of 7 ESP-NOW links (i.e. 7 instances of SpanPoint) + * with encryption disabled, the ESP32 can support a maximum of 20 ESP-NOW links (i.e. 20 instances of SpanPoint) + * `static void setChannelMask(uint16_t mask)` * this *optional* **class-level** method changes the default channel bitmask from 0x3FFE (i.e. 0011 1111 1111 1110) to *mask* diff --git a/docs/PWM.md b/docs/PWM.md index c0a647b..ea6c7c2 100644 --- a/docs/PWM.md +++ b/docs/PWM.md @@ -1,8 +1,6 @@ # Pulse Width Modulation (PWM) -The ESP32 has up to 16 PWM channels that can be used to drive a variety of devices. HomeSpan includes an integrated PWM library with dedicated classes designed for controlling **Dimmable LEDs** as well as **Servo Motors**. Both classes are provided in a standalone header file that is accessed by placing the following near the top of your sketch: - -`#include "extras/PwmPin.h"` +The ESP32 has up to 16 PWM channels that can be used to drive a variety of devices. HomeSpan includes an integrated PWM library with dedicated classes designed for controlling **Dimmable LEDs** as well as **Servo Motors**. ## *LedPin(uint8_t pin [,float level [,uint16_t frequency [,boolean invert]]])* diff --git a/docs/Pixels.md b/docs/Pixels.md index 2074e35..e50a3b9 100644 --- a/docs/Pixels.md +++ b/docs/Pixels.md @@ -6,10 +6,6 @@ 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. -Both classes are provided in a standalone header file that is accessed by placing the following near the top of your sketch: - -`#include "extras/Pixel.h"` - ## *Pixel(uint8_t pin, [boolean isRGBW])* 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: diff --git a/docs/RMT.md b/docs/RMT.md index 5be3d6e..de916da 100644 --- a/docs/RMT.md +++ b/docs/RMT.md @@ -1,8 +1,6 @@ # Remote Control Radio Frequency / Infrared Signal Generation -The ESP32 has an on-chip signal-generator peripheral designed to drive an RF or IR transmitter. HomeSpan includes an easy-to-use library that interfaces with this peripheral so that with a few additional electronic components you can create a HomeSpan device that controls an RF or IR appliance directly from the Home App on your iPhone, or via Siri. The library is accessed by placing the following near the top of your sketch: - -`#include "extras/RFControl.h"` +The ESP32 has an on-chip Remote Control (RMT) signal-generator designed to drive an RF or IR transmitter. HomeSpan includes a dedicated, easy-to-use class, **RFControl()**, that interfaces with the ESP32 RMT peripheral so that with a few additional electronic components you can create a HomeSpan device that controls an RF or IR appliance directly from the Home App on your iPhone, or via Siri. ## *RFControl(int pin, boolean refClock=true)* @@ -93,7 +91,6 @@ Below is a complete sketch that produces two different pulse trains with the sig /* HomeSpan Remote Control Example */ #include "HomeSpan.h" // include the HomeSpan library -#include "extras/RFControl.h" // include RF Control Library void setup() { diff --git a/docs/Reference.md b/docs/Reference.md index 1c49200..36542a8 100644 --- a/docs/Reference.md +++ b/docs/Reference.md @@ -8,7 +8,7 @@ The HomeSpan Library is invoked by including *HomeSpan.h* in your Arduino sketch ## *homeSpan* -At runtime HomeSpan will create a global **object** named `homeSpan` that supports the following methods: +At runtime HomeSpan will create a global **object** named `homeSpan` (of type *class Span*) that supports the following methods: * `void begin(Category catID, const char *displayName, const char *hostNameBase, const char *modelName)` * initializes HomeSpan @@ -26,21 +26,31 @@ At runtime HomeSpan will create a global **object** named `homeSpan` that suppor --- -The following **optional** `homeSpan` methods override various HomeSpan initialization parameters used in `begin()`, and therefore **should** be called before `begin()` to take effect. If a method is *not* called, HomeSpan uses the default parameter indicated below: +The following **optional** `homeSpan` methods override various HomeSpan initialization parameters used in `begin()`, and therefore **should** be called before `begin()` to take effect. +Methods with a return type of `Span&` return a reference to `homeSpan` itself and can thus be chained together (e.g. `homeSpan.setControlPin(21).setStatusPin(13);`). If a method is *not* called, HomeSpan uses the default parameter indicated below: -* `void setControlPin(uint8_t pin)` - * sets the ESP32 pin to use for the HomeSpan Control Button (which must connect the specified pin to **ground** when pushed). If not specified, HomeSpan will assume there is no Control Button +* `Span& setControlPin(uint8_t pin, triggerType=PushButton::TRIGGER_ON_LOW)` + * sets the ESP32 *pin* to use for the HomeSpan Control Button + * if this method is not called, HomeSpan will assume there is no Control Button + * the optional second argument, *triggerType*, configures the Control Button as follows: + * `PushButton::TRIGGER_ON_LOW` - triggers when *pin* is driven LOW + * suitable for buttons that connect *pin* to GROUND (this is the default when *triggerType* is not specified) + * `PushButton::TRIGGER_ON_HIGH` - triggers when *pin* is driven HIGH + * suitable for buttons that connect *pin* to VCC (typically 3.3V) + * `PushButton::TRIGGER_ON_TOUCH` - uses the device's touch-sensor peripheral to trigger when *pin* has been touched + * not available on ESP32-C3 + * as an alternative, you can set *triggerType* to any user-defined function of the form `boolean(int arg)` to utilize any device as a Control Button. See **SpanButton** below for details * `int getControlPin()` * returns the pin number of the HomeSpan Control Button as set by `setControlPin(pin)`, or -1 if no pin has been set -* `void setStatusPin(uint8_t pin)` - * sets the ESP32 pin to use for the HomeSpan Status LED +* `Span& setStatusPin(uint8_t pin)` + * sets the ESP32 *pin* to use for the HomeSpan Status LED * assumes a standard LED will be connected to *pin* * if neither this method nor any equivalent method is called, HomeSpan will assume there is no Status LED -* `void setStatusPixel(uint8_t pin, float h=0, float s=100, float v=100)` - * sets the ESP32 pin to use for the HomeSpan Status LED +* `Span& setStatusPixel(uint8_t pin, float h=0, float s=100, float v=100)` + * sets the ESP32 *pin* to use for the HomeSpan Status LED * this method is an *alternative* to using `setStatusPin()` above * assumes an RGB NeoPixel (or equivalent) will be connected to *pin* * works well with ESP32 boards that have a built-in NeoPixel LED, though adding an external NeoPixel is fine @@ -52,14 +62,14 @@ The following **optional** `homeSpan` methods override various HomeSpan initiali * example: `homeSpan.setStatusPixel(8,120,100,20)` sets the Status LED to light green using a NeoPixel attached to pin 8 * if neither this method nor any equivalent method is called, HomeSpan will assume there is no Status LED -* `void setStatusDevice(Blinkable *sDev)` +* `Span& setStatusDevice(Blinkable *sDev)` * sets the Status LED to a user-specified Blinkable device, *sDev* * this method is an *alternative* to using either `setStatusPin()` or `setStatusPixel()` above * see [Blinkable](Blinkable.md) for details on how to create generic Blinkable devices * useful when using an LED connected to a pin expander, or other specialized driver, as the Status LED * if neither this method nor any equivalent method is called, HomeSpan will assume there is no Status LED -* `void setStatusAutoOff(uint16_t duration)` +* `Span& setStatusAutoOff(uint16_t duration)` * sets Status LED to automatically turn off after *duration* seconds * Status LED will automatically turn on, and duration timer will be reset, whenever HomeSpan activates a new blinking pattern * if *duration* is set to zero, auto-off is disabled (Status LED will remain on indefinitely) @@ -67,19 +77,19 @@ The following **optional** `homeSpan` methods override various HomeSpan initiali * `int getStatusPin()` * returns the pin number of the Status LED as set by `setStatusPin(pin)`, or -1 if no pin has been set -* `void setApSSID(const char *ssid)` +* `Span& setApSSID(const char *ssid)` * sets the SSID (network name) of the HomeSpan Setup Access Point (default="HomeSpan-Setup") -* `void setApPassword(const char *pwd)` +* `Span& setApPassword(const char *pwd)` * sets the password of the HomeSpan Setup Access Point (default="homespan") -* `void setApTimeout(uint16_t nSec)` +* `Span& setApTimeout(uint16_t nSec)` * sets the duration (in seconds) that the HomeSpan Setup Access Point, once activated, stays alive before timing out (default=300 seconds) -* `void setCommandTimeout(uint16_t nSec)` +* `Span& setCommandTimeout(uint16_t nSec)` * sets the duration (in seconds) that the HomeSpan End-User Command Mode, once activated, stays alive before timing out (default=120 seconds) -* `void setLogLevel(int level)` +* `Span& setLogLevel(int level)` * sets the logging level for diagnostic messages, where: * 0 = top-level HomeSpan status messages, and any `LOG0()` messages specified in the sketch by the user (default) * 1 = all HomeSpan status messages, and any `LOG1()` messages specified in the sketch by the user @@ -93,7 +103,7 @@ The following **optional** `homeSpan` methods override various HomeSpan initiali * `int getLogLevel()` * returns the current Log Level as set by `setLogLevel(level)` -* `void reserveSocketConnections(uint8_t nSockets)` +* `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* @@ -102,16 +112,16 @@ The following **optional** `homeSpan` methods override various HomeSpan initiali * 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 -* `void setPortNum(uint16_t port)` +* `Span& setPortNum(uint16_t port)` * sets the TCP port number used for communication between HomeKit and HomeSpan (default=80) -* `void setHostNameSuffix(const char *suffix)` +* `Span& setHostNameSuffix(const char *suffix)` * sets the suffix HomeSpan appends to *hostNameBase* to create the full hostName * if not specified, the default is for HomeSpan to append a dash "-" followed the 6-byte Accessory ID of the HomeSpan device * setting *suffix* to a null string "" is permitted * example: `homeSpan.begin(Category::Fans, "Living Room Ceiling Fan", "LivingRoomFan");` will yield a default *hostName* of the form *LivingRoomFan-A1B2C3D4E5F6.local*. Calling `homeSpan.setHostNameSuffix("v2")` prior to `homeSpan.begin()` will instead yield a *hostName* of *LivingRoomFanv2.local* -* `void setQRID(const char *id)` +* `Span& setQRID(const char *id)` * changes the Setup ID, which is used for pairing a device with a [QR Code](QRCodes.md), from the HomeSpan default to *id* * the HomeSpan default is "HSPN" unless permanently changed for the device via the [HomeSpan CLI](CLI.md) using the 'Q' command * *id* must be exactly 4 alphanumeric characters (0-9, A-Z, and a-z). If not, the request to change the Setup ID is silently ignored and the default is used instead @@ -135,11 +145,11 @@ The following **optional** `homeSpan` methods enable additional features and pro * this command causes HomeSpan to ignore, but does not otherwise alter, any password stored using the 'O' command * returns 0 if enabling OTA was successful, or -1 and reports an error to the Serial Monitor if not -* `void enableAutoStartAP()` +* `Span& enableAutoStartAP()` * enables automatic start-up of WiFi Access Point if WiFi Credentials are **not** found at boot time * methods to alter the behavior of HomeSpan's Access Point, such as `setApTimeout()`, must be called prior to `enableAutoStartAP()` to have an effect -* `void setApFunction(void (*func)())` +* `Span& setApFunction(void (*func)())` * replaces HomeSpan's built-in WiFi Access Point with user-defined function *func* * *func* must be of type *void* and have no arguments * *func* will be called instead of HomeSpan's built-in WiFi Access Point whenever the Access Point is launched: @@ -149,22 +159,30 @@ The following **optional** `homeSpan` methods enable additional features and pro * after identifying the SSID and password of the desired network, *func* must call `setWifiCredentials()` to save and use these values * it is recommended that *func* terminates by restarting the device using `ESP.restart()`. Upon restart HomeSpan will use the SSID and password just saved -* `void setWifiCredentials(const char *ssid, const char *pwd)` +* `Span& setWifiCredentials(const char *ssid, const char *pwd)` * sets the SSID (*ssid*) and password (*pwd*) of the WiFi network to which HomeSpan will connect * *ssid* and *pwd* are automatically saved in HomeSpan's non-volatile storage (NVS) for retrieval when the device restarts * note that the saved values are truncated if they exceed the maximum allowable characters (ssid=32; pwd=64) * :warning: SECURITY WARNING: The purpose of this function is to allow advanced users to *dynamically* set the device's WiFi Credentials using a customized Access Point function specified by `setApFunction(func)`. It it NOT recommended to use this function to hardcode your WiFi SSID and password directly into your sketch. Instead, use one of the more secure methods provided by HomeSpan, such as typing 'W' from the CLI, or launching HomeSpan's Access Point, to set your WiFi credentials without hardcoding them into your sketch + +* `Span& setVerboseWifiReconnect(bool verbose)` + * when trying connecting to WiFi, HomeSpan normally logs "Trying to connect to..." messages to the Serial Monitor and the Web Log + * calling this method with *verbose* set to *false* supresses these messages + * calling this method a second time with *verbose* set to *true* re-activates these messages (default behavior) -* `void setWifiCallback(void (*func)())` - * sets an optional user-defined callback function, *func*, to be called by HomeSpan upon start-up just after WiFi connectivity has been established. This one-time call to *func* is provided for users that are implementing other network-related services as part of their sketch, but that cannot be started until WiFi connectivity is established. The function *func* must be of type *void* and have no arguments +* `Span& setWifiCallback(void (*func)())` + * sets an optional user-defined callback function, *func*, to be called by HomeSpan upon start-up just after WiFi connectivity has been initially established. This one-time call to *func* is provided for users that are implementing other network-related services as part of their sketch, but that cannot be started until WiFi connectivity is established. The function *func* must be of type *void* and have no arguments -* `void setPairCallback(void (*func)(boolean status))` +* `Span& setWifiCallbackAll(void (*func)(int count))` + * similar to `setWiFiCallback()` above, but the user-defined callback function, *func*, is called by HomeSpan *every* time WiFi connectivity has been established or re-established after a disconnect. The function *func* must be of type *void* and accept a single *int* argument, *count*, into which HomeSpan passes the number of times WiFi has been established or re-established (i.e. *count*=1 on initial WiFi connection; *count*=2 if re-established after the first disconnect, etc.) + +* `Span& setPairCallback(void (*func)(boolean status))` * sets an optional user-defined callback function, *func*, to be called by HomeSpan upon completion of pairing to a controller (*status=true*) or unpairing from a controller (*status=false*) * 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 -* `void setStatusCallback(void (*func)(HS_STATUS status))` +* `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 * this allows users to reflect changes to the current state of HomeSpan using alternative methods, such as outputting messages to an embedded LCD or E-Ink display @@ -174,14 +192,14 @@ The following **optional** `homeSpan` methods enable additional features and pro * returns a pre-defined character string message representing *s*, which must be of enum type [HS_STATUS](HS_STATUS.md) * typically used in conjunction with `setStatusCallback()` above -* `void setPairingCode(const char *s)` +* `Span& setPairingCode(const char *s)` * 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 * :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 \' from the CLI, or launching HomeSpan's Access Point, to set your Pairing Code without hardcoding it into your sketch -* `void setSketchVersion(const char *sVer)` +* `Span& setSketchVersion(const char *sVer)` * sets the version of a HomeSpan sketch to *sVer*, which can be any arbitrary character string * if unspecified, HomeSpan uses "n/a" as the default version text * HomeSpan displays the version of the sketch in the Arduino IDE Serial Monitor upon start-up @@ -191,31 +209,56 @@ The following **optional** `homeSpan` methods enable additional features and pro * returns the version of a HomeSpan sketch, as set using `void setSketchVersion(const char *sVer)`, or "n/a" if not set * can by called from anywhere in a sketch -* `void enableWebLog(uint16_t maxEntries, const char *timeServerURL, const char *timeZone, const char *logURL)` +* `Span& enableWebLog(uint16_t maxEntries, const char *timeServerURL, const char *timeZone, const char *logURL)` * enables a rolling Web Log that displays the most recent *maxEntries* entries created by the user with the `WEBLOG()` macro. Parameters, and their default values if unspecified, are as follows: * *maxEntries* - maximum number of (most recent) entries to save. If unspecified, defaults to 0, in which case the Web Log will only display status without any log entries - * *timeServerURL* - the URL of a time server that HomeSpan will use to set its clock upon startup after a WiFi connection has been established. If unspecified, defaults to NULL, in which case HomeSpan skips setting the device clock - * *timeZone* - specifies the time zone to use for setting the clock. Uses standard Unix timezone formatting as interpreted by Espressif IDF. Note the IDF uses a somewhat non-intuitive convention such that a timezone of "UTC+5:00" *subtracts* 5 hours from UTC time, and "UTC-5:00" *adds* 5 hours to UTC time. If *serverURL=NULL* this field is ignored; if *serverURL!=NULL* this field is required - * *logURL* - the URL of the Web Log page for this device. If unspecified, defaults to "status" + * *timeServerURL* - the URL of a time server that HomeSpan will use to set its clock upon startup after a WiFi connection has been established. HomeSpan will reserve one extra socket connection when a time server is specified. If unspecified, defaults to NULL, in which case HomeSpan skips setting the device clock + * *timeZone* - specifies the time zone to use for setting the clock. Uses POSIX.1 format only and does not support the *Time Zone Database*, or *tzdata*. As per [GNU libc documentation for TZ](https://www.gnu.org/software/libc/manual/html_node/TZ-Variable.html), *the offset specifies the time value you must **add to the local time** to get a Coordinated Universal Time value*. "UTC+5:00" means that local time + 5 hours give UTC time. See the GNU libc documentation for some examples, including how to specify North American Eastern Standard Time (EST) and Eastern Daylight Time (EDT) with start and end dates of EDT. If *serverURL=NULL* this field is ignored; if *serverURL!=NULL* this field is required + * *logURL* - the URL of the Web Log page for this device. If unspecified, defaults to "status". If *logURL* is set to NULL HomeSpan will use the *timeServerURL* and *timeZone* parameters to set the clock, but it will *not* serve any Web Log pages in response to any HTTP requests. However, Web Log data is still accumulated internally and the resulting HTML can be accessed anytime by calling the `homeSpan.getWebLog()` method (see below) * example: `homeSpan.enableWebLog(50,"pool.ntp.org","UTC-1:00","myLog");` creates a web log at the URL *http://HomeSpan-\[DEVICE-ID\].local:\[TCP-PORT\]/myLog* that will display the 50 most-recent log messages produced with the WEBLOG() macro. Upon start-up (after a WiFi connection has been established) HomeSpan will attempt to set the device clock by calling the server "pool.ntp.org" and adjusting the time to be 1 hour ahead of UTC. * when attemping to connect to *timeServerURL*, HomeSpan waits 120 seconds for a response. This is done in the background and does not block HomeSpan from running as usual while it tries to set the time. If no response is received after the 120-second timeout period, HomeSpan assumes the server is unreachable and skips the clock-setting procedure. Use `setTimeServerTimeout()` to re-configure the 120-second timeout period to another value * see [Message Logging](Logging.md) for complete details -* `void setTimeServerTimeout(uint32_t tSec)` +* `Span& setTimeServerTimeout(uint32_t tSec)` * changes the default 120-second timeout period HomeSpan uses when `enableWebLog()` tries set the device clock from an internet time server to *tSec* seconds -* `void setWebLogCSS(const char *css)` +* `Span& setWebLogCSS(const char *css)` * sets the format of the HomeSpan Web Log to the custom style sheet specified by *css* * see [Message Logging](Logging.md) for details on how to construct *css* - + +* `Span& setWebLogCallback(void (*func)(String &htmlText))` + * sets an optional user-defined callback function, *func*, to be called by HomeSpan whenever the Web Log is produced + * allows user to add additional custom data to the initial table of the Web Log by **extending** the String *htmlText*, which is passed as a reference to *func* + * the function *func* must be of type *void* and accept one argument of type *String* + * see [Message Logging](Logging.md) for details on how to construct *htmlText* + +* `void getWebLog(void (*f)(const char *htmlBuf, void *args), void *userData)` + * when called, HomeSpan *streams* the current Web Log HTML text, and any optionally-specified *userData*, directly to the user-defined function, *f()*, which should return a *void* and accept the following two arguments: + * *htmlBuf* - pointer to part of the HTML text for the Web Log page + * *args* - a pass-through of the *userData* argument + * if user-defined data is not needed, set *userData* to NULL + * to avoid creating a single large text buffer, HomeSpan splits the HTML for the Web Log into chunks of 1024 bytes and repeatedly calls *f()* until all the HTML has been streamed; HomeSpan then makes a final call to *f()* with *htmlBuf* set to NULL indicating to the user that the end of the HTML text has been reached + * this command is primarily used to redirect Web Log pages to a user-defined process for alternative handling, display, or transmission + * see [Message Logging](Logging.md) for more details + * `void processSerialCommand(const char *CLIcommand)` * processes the *CLIcommand* just as if were typed into the Serial Monitor * allows for programmatic access to all CLI commands, included any custom commands defined by the user * will work whether or not device is connected to a computer * example: `homeSpan.processSerialCommand("A");` starts the HomeSpan Setup Access Point * example: `homeSpan.processSerialCommand("Q HUB3");` changes the HomeKit Setup ID for QR Codes to "HUB3" + +* `Span& setRebootCallback(void (*func)(uint8_t count), uint32_t upTime)` + * sets an optional user-defined callback function, *func*, that is called (just once) when *upTime* milliseconds after rebooting have elapsed (default *upTime*=5000 ms if not specified) + * the function *func* must be of type *void* and accept one argument of type *uint8_t* + * the parameter *count*, which HomeSpan passes to *func*, indicates the number of "short" reboots that have occured prior to the current reboot, where a "short" reboot is any that occurs **before** *upTime* milliseconds have elapsed + * this allows the user to provide a generic form of input to a sketch by rapidly turning on/off power to the device a specified number of times, typically to provide a method of resetting some aspect of a remote device + * example using a lamba function: + * `homeSpan.setRebootCallback( [](uint8_t c) {if(c==3) homeSpan.processSerialCommand("X");} );` + * causes HomeSpan to run the 'X' Serial Command, which erases WiFi data, if the device is "short" rebooted exactly 3 times, where each reboot is for less than 5 seconds + * note that creating 3 short reboots means you actually cycle the power (or press the reset button) a total of 4 times, since the last time you allow the sketch to run without rebooting -* `void setSerialInputDisable(boolean val)` +* `Span& setSerialInputDisable(boolean val)` * if *val* is true, disables HomeSpan from reading input from the Serial port * if *val* is false, re-enables HomeSpan reading input from the Serial port * useful when the main USB Serial port is needed for reading data from an external Serial peripheral, rather than being used to read input from the Arduino Serial Monitor @@ -258,18 +301,21 @@ The following `homeSpan` methods are considered experimental, since not all use * *stackSize* - size of stack, in bytes, used by the polling task. Default=8192 if unspecified * *priority* - priority at which task runs. Minimum is 1. Maximum is typically 24, but it depends on how the ESP32 operating system is configured. If you set it to an arbitrarily high value (e.g. 999), it will be set to the maximum priority allowed. Default=1 if unspecified - * *cpu* - specifies the CPU on which the polling task will run. Valid values are 0 and 1. This paramater is ignored on single-cpu boards. Default=0 if unspecified + * *cpu* - specifies the CPU on which the polling task will run. Valid values are 0 and 1. This parameter is ignored on single-cpu boards. Default=0 if unspecified * if used, **must** be placed in a sketch as the last line in the Arduino `setup()` method * HomeSpan will throw and error and halt if both `poll()`and `autoPoll()` are used in the same sketch - either place `poll()` in the Arduino `loop()` method **or** place `autoPoll()` at the the end of the Arduino `setup()` method * if this method is used, and you have no need to add your own code to the main Arduino `loop()`, you can safely skip defining a blank `void loop(){}` function in your sketch * warning: if any code you add to the Arduino `loop()` method tries to alter any HomeSpan settings or functions running in the background `poll()` task, race conditions may yield undefined results +* `TaskHandle_t getAutoPollTask()` + * returns the task handle for the Auto Poll Task, or NULL if Auto Polling has not been used + ## *SpanAccessory(uint32_t aid)* Creating an instance of this **class** adds a new HAP Accessory to the HomeSpan HAP Database. * every HomeSpan sketch requires at least one Accessory - * a sketch can contain a maximum of 41 Accessories per sketch (if exceeded, a runtime error will the thrown and the sketch will halt) + * a sketch can contain a maximum of 150 Accessories per sketch (if exceeded, a runtime error will the thrown and the sketch will halt) * there are no associated methods * the argument *aid* is optional. @@ -496,7 +542,7 @@ Creating an instance of this **class** attaches a toggle-switch handler to the E * 3=switch is closed (`SpanToggle::CLOSED`) * 4=switch is open (`SpanToggle::OPEN`) -Note there are no *singleTime*, *longTime*, or *doubleTime* paramaters in the constructor since you can't single-press, double-press, or long-press a toggle switch. Instead, the constructor supports the single parameter *toggleTime* (default=5ms if left unspecified) that sets the minimum time at which the switch needs to be moved to the closed position in order to trigger a call to the `button()` method. This effectively "debounces" the toggle switch. +Note there are no *singleTime*, *longTime*, or *doubleTime* parameters in the constructor since you can't single-press, double-press, or long-press a toggle switch. Instead, the constructor supports the single parameter *toggleTime* (default=5ms if left unspecified) that sets the minimum time at which the switch needs to be moved to the closed position in order to trigger a call to the `button()` method. This effectively "debounces" the toggle switch. SpanToggle also supports the following additional method: @@ -548,7 +594,7 @@ To create more than one user-defined command, simply create multiple instances o 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): -* *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 +* *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 diff --git a/docs/ServiceList.md b/docs/ServiceList.md index 1416fd6..abff6e9 100644 --- a/docs/ServiceList.md +++ b/docs/ServiceList.md @@ -1,204 +1,454 @@ # HomeSpan Services and Characteristics -HomeSpan implements all HAP-R2 Services and Characteristics except for those that involve video or audio streaming, Apple TV, or advanced lock management (i.e. all HAP Services except those that require Characteristics with a TLV8 data type). +Below is a list of all Services supported by HomeSpan, along with a brief description of each Service. Click on the arrow next to the description of any Service to see a list of all Characteristics supported by the Service, as well as a description of each Characteristic.[^1] +A blue diamond (🔹) next to a Characteristic means it is **required** for that Service, otherwise it is optional. Information included for each Characteristic is as follows: + +* **Format** - the native format of the Characteristic's value. Note that *string* means a standard C-string (i.e. char \*) +* **Perms**, where + * PR = Paired Read. This means HomeKit can read the value from HomeSpan[^2] + * PW = Paired Write. This means HomeKit can write the value to HomeSpan, which triggers a call to `update()` + * EV = Event Notification. This means HomeSpan can push notifications of value changes to HomeKit using `setVal()` +* **Min** / **Max** - the default minimum and maximum values allowed in HomeKit. For applicable numerical Characteristics, you can change the allowed minimum and maximum values using `setRange()` +* **Constants/Defaults** + * for enumerated Characteristics, a list of all allowed values in the form of pre-defined constant expressions and their equivalent numeric values. A check mark next to a constant indicates that it is the default value. If your Accessory does not support certain states of a Characteristic, you can change the allowed values using `setValidValues()` + * for all other Characteristics, the actual default value that is used if you do not specify one when instantiating the Characteristic + + [^1]: The hexidecimal numbers in parentheses next to each Service and Characteristic represent the short-form of the Apple's UUID for that Service or Characteristic. These are provided for informational purposes only (you do not need to use them, or even know about them, to create HomeSpan sketches) + + [^2]: Though rarely needed, you can change the permissions of a Characteristic using `setPerms()`, `addPerms()`, and `removePerms()` + HomeSpan Services and Characteristics are implemented as C++ Classes with names that exactly match the spelling and capitalization specified by Apple in Sections 8 and 9 of HAP-R2, but without any spaces. HomeSpan Services are defined in HomeSpan's `Service` namespace. HomeSpan Characteristics are defined in HomeSpan's `Characteristic` namespace. For example, HomeSpan defines the *Carbon Dioxide Sensor* Service (HAP Service 8.7) as `Service::CarbonDioxideSensor`, and the *Carbon Dioxide Detected* Characteristic (HAP Characteristic 9.16) as `Characteristic::CarbonDioxideDetected`. -HomeSpan Services and Characteristics are instantiated with a C++ `new` command. Services do not take any arguments, whereas Characteristics take a single, optional argument that is used to initialize the value of the Characteristic at startup. If this argument is not specified, HomeSpan will apply a reasonable [default value](#characteristic-types-and-defaults) based on the Characteristic's type and allowed range. +The pre-defined constant expressions for enumerated Characteristics are in namespaces that match the name of the Characteristic. For example, to set the *Air Quality* Characteristic of an *Air Quality Sensor* Service, you could use `setVal(Characteristic::AirQuality::GOOD)` or, equivalently, `setVal(2)`.[^3] -A list of all HomeSpan Services is provided in the table below. For each Service the table also indicates which Characteristics are required and which are optional. For example, a dimmable light bulb could be configured in HomeSpan as such: +[^3]: Note that a Characteristic's pre-defined constants are inherited by objects that you create from that Characteristic. This means that if you create a pointer to the *AirQuality* Characteristic using `Characteristic::AirQuality *air = new Characteristic::AirQuality;` then later in your code you can either say
`air->setVal(Characteristic::AirQuality::GOOD)` or `air->GOOD`. Both will work, but the latter is much easier to type. -```C++ -new Service::LightBulb(); // instantiate a Light Bulb Service - new Characteristic:On(); // instantiate the required On Characteristic without setting initial value - new Characteristic::Brightness(50); // instantiate an optional Brightness Characteristic and set initial value to 50% - new Characteristic::Name("Living Room Lamp"); // instantiate an optional Name Characteristic for this Service, and set to "Living Room Lamp" -``` + -Please see Sections 8 and 9 of HAP-R2 for a complete description of all HAP Services and Characteristics. Note that HomeSpan's Service and Characteristic Classes already contain all the required HAP fields, such as the UUID, Format, and Permissions, so you don't need to specify any of these parameters. -Additionally, when first starting up, HomeSpan begins by validating the device's configuration to ensure each Service you instantiate includes all required Characteristics, but does not include any Characteristics that are neither required nor optional. If any errors are found, HomeSpan reports them to the Arduino Serial Monitor. +## MANDATORY SERVICES +### AccessoryInformation (3E) + Required Identification Information. For each Accessory in a HomeSpan device this must be included as the first Service.
+ + + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
Identify (14) :small_blue_diamond:
  • triggers an update when HomeKit wants HomeSpan to run its identification routine for an Accessory
boolPW11
  • RUN_ID (1) 
Name (23)
  • default display name of the Accessory
stringPR--"unnamed"
FirmwareRevision (52)
  • must be in form x[.y[.z]] - informational only
stringPR+EV--"1.0.0"
Manufacturer (20)
  • any string - informational only
stringPR--"HomeSpan"
Model (21)
  • any string - informational only
stringPR--"HomeSpan-ESP32"
SerialNumber (30)
  • any string - informational only
stringPR--"HS-12345"
HardwareRevision (53)
  • must be in form x[.y[.z]] - informational only
stringPR--"1.0.0"

-### Service List +## LIGHTS, POWER, AND SWITCHES +### BatteryService (96) + Defines a standalone Battery Service.
+ + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
BatteryLevel (68) :small_blue_diamond:
  • measured as a percentage
uint8PR+EV0100100
ChargingState (8F) :small_blue_diamond:
  • indicates state of battery charging
uint8PR+EV02
  • NOT_CHARGING (0) :heavy_check_mark:
  • CHARGING (1) 
  • NOT_CHARGEABLE (2) 
StatusLowBattery (79) :small_blue_diamond:
  • indicates state of battery
uint8PR+EV01
  • NOT_LOW_BATTERY (0) :heavy_check_mark:
  • LOW_BATTERY (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

-|Service|Required Characteristics|Optional Characteristics| -|-|-|-| -|AccessoryInformation|Identify|FirmwareRevision
Manufacturer
Model
Name
SerialNumber
HardwareRevision
AccessoryFlags| -|AirPurifier|Active
CurrentAirPurifierState
TargetAirPurifierState|Name
RotationSpeed
SwingMode
LockPhysicalControls| -|AirQualitySensor|AirQuality|Name
OzoneDensity
NitrogenDioxideDensity
SulphurDioxideDensity
PM25Density
PM10Density
VOCDensity
StatusActive
StatusFault
StatusTampered
StatusLowBattery| -|BatteryService|BatteryLevel
ChargingState
StatusLowBattery|Name| -|CarbonDioxideSensor|CarbonDioxideDetected|Name
StatusActive
StatusFault
StatusTampered
StatusLowBattery
CarbonDioxideLevel
CarbonDioxidePeakLevel| -|CarbonMonoxideSensor|CarbonMonoxideDetected|Name
StatusActive
StatusFault
StatusTampered
StatusLowBattery
CarbonMonoxideLevel
CarbonMonoxidePeakLevel| -|ContactSensor|ContactSensorState|Name
StatusActive
StatusFault
StatusTampered
StatusLowBattery| -|Door|CurrentPosition
TargetPosition
PositionState|Name
HoldPosition
ObstructionDetected| -|Doorbell|ProgrammableSwitchEvent|Name
Volume
Brightness| -|Fan|Active|Name
CurrentFanState
TargetFanState
RotationDirection
RotationSpeed
SwingMode
LockPhysicalControls| -|Faucet|Active|StatusFault
Name| -|FilterMaintenance|FilterChangeIndication|Name
FilterLifeLevel
ResetFilterIndication| -|GarageDoorOpener|CurrentDoorState
TargetDoorState
ObstructionDetected|LockCurrentState
LockTargetState
Name| -|HAPProtocolInformation|Version||HeaterCooler|Active
CurrentTemperature
CurrentHeaterCoolerState
TargetHeaterCoolerState|Name
RotationSpeed
TemperatureDisplayUnits
SwingMode
CoolingThresholdTemperature
HeatingThresholdTemperature
LockPhysicalControls| -|HumidifierDehumidifier|Active
CurrentRelativeHumidity
CurrentHumidifierDehumidifierState
TargetHumidifierDehumidifierState|Name
RelativeHumidityDehumidifierThreshold
RelativeHumidityHumidifierThreshold
RotationSpeed
SwingMode
WaterLevel
LockPhysicalControls| -|HumiditySensor|CurrentRelativeHumidity|Name
StatusActive
StatusFault
StatusTampered
StatusLowBattery| -|InputSource|Identifier|ConfiguredName
IsConfigured
CurrentVisibilityState
TargetVisibilityState| -|IrrigationSystem|Active
ProgramMode
InUse|RemainingDuration
StatusFault| -|LeakSensor|LeakDetected|Name
StatusActive
StatusFault
StatusTampered
StatusLowBattery| -|LightBulb|On|Brightness
Hue
Name
Saturation
ColorTemperature| -|LightSensor|CurrentAmbientLightLevel|Name
StatusActive
StatusFault
StatusTampered
StatusLowBattery| -|LockMechanism|LockCurrentState
LockTargetState|Name| -|Microphone|Mute|Name
Volume| -|MotionSensor|MotionDetected|Name
StatusActive
StatusFault
StatusTampered
StatusLowBattery| -|OccupancySensor|OccupancyDetected|Name
StatusActive
StatusFault
StatusTampered
StatusLowBattery| -|Outlet|On
OutletInUse|Name| -|SecuritySystem|SecuritySystemCurrentState
SecuritySystemTargetState|Name
SecuritySystemAlarmType
StatusFault
StatusTampered| -|ServiceLabel|ServiceLabelNamespace||Slat|CurrentSlatState
SlatType|Name
SwingMode
CurrentTiltAngle
TargetTiltAngle| -|SmokeSensor|SmokeDetected|Name
StatusActive
StatusFault
StatusTampered
StatusLowBattery| -|Speaker|Mute|Name
Volume| -|StatelessProgrammableSwitch|ProgrammableSwitchEvent|Name
ServiceLabelIndex| -|Switch|On|Name| -|Television|Active|ConfiguredName
ActiveIdentifier
RemoteKey
PowerModeSelection| -|TelevisionSpeaker|VolumeControlType
VolumeSelector| -|TemperatureSensor|CurrentTemperature|Name
StatusActive
StatusFault
StatusTampered
StatusLowBattery| -|Thermostat|CurrentHeatingCoolingState
TargetHeatingCoolingState
CurrentTemperature
TargetTemperature
TemperatureDisplayUnits|CoolingThresholdTemperature
CurrentRelativeHumidity
HeatingThresholdTemperature
Name
TargetRelativeHumidity| -|Valve|Active
InUse
ValveType|SetDuration
RemainingDuration
IsConfigured
ServiceLabelIndex
StatusFault
Name| -|Window|CurrentPosition
TargetPosition
PositionState|Name
HoldPosition
ObstructionDetected| -|WindowCovering|TargetPosition
CurrentPosition
PositionState|Name
HoldPosition
CurrentHorizontalTiltAngle
TargetHorizontalTiltAngle
CurrentVerticalTiltAngle
TargetVerticalTiltAngle
ObstructionDetected| +### LightBulb (43) + Defines any type of Light.
+ + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
On (25) :small_blue_diamond:
  • indicates if the Service is active/on
boolPR+PW+EV01
  • OFF (0) :heavy_check_mark:
  • ON (1) 
Brightness (8)
  • measured as a percentage
intPR+PW+EV01000
Hue (13)
  • color (in degrees) from red (0) to green (120) to blue (240) and back to red (360)
floatPR+PW+EV03600
Saturation (2F)
  • color saturation, measured as a percentage
floatPR+PW+EV01000
ColorTemperature (CE)
  • measured in inverse megaKelvin (= 1,000,000 / Kelvin)
uint32PR+PW+EV140500200
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

-### Characteristic Types and Defaults +### Outlet (47) + Defines a controllable Outlet used to power any light or appliance.
+ + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
On (25) :small_blue_diamond:
  • indicates if the Service is active/on
boolPR+PW+EV01
  • OFF (0) :heavy_check_mark:
  • ON (1) 
OutletInUse (26) :small_blue_diamond:
  • indicates if an appliance or light is plugged into the outlet, regardless of whether on or off
boolPR+EV01
  • NOT_IN_USE (0) :heavy_check_mark:
  • IN_USE (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

-|Characteristic|Type|Default|Range| -|-|-|-|-| -AccessoryFlags|uint32_t|1|[1,1]| -Active|uint8_t|0|[0,1]| -ActiveIdentifier|uint32_t|0|[0,255]| -AirQuality|uint8_t|0|[0,5]| -BatteryLevel|uint8_t|0|[0,100]| -Brightness|int|0|[0,100]| -CarbonMonoxideLevel|double|0|[0,100]| -CarbonMonoxidePeakLevel|double|0|[0,100]| -CarbonMonoxideDetected|uint8_t|0|[0,1]| -CarbonDioxideLevel|double|0|[0,100000]| -CarbonDioxidePeakLevel|double|0|[0,100000]| -CarbonDioxideDetected|uint8_t|0|[0,1]| -ChargingState|uint8_t|0|[0,2]| -ClosedCaptions|uint8_t|0|[0,1]| -CoolingThresholdTemperature|double|10|[10,35]| -ColorTemperature|uint32_t|200|[140,500]| -ContactSensorState|uint8_t|1|[0,1]| -ConfiguredName|char \*|"unnamed"||| -CurrentAmbientLightLevel|double|1|[0.0001,100000]| -CurrentHorizontalTiltAngle|int|0|[-90,90]| -CurrentAirPurifierState|uint8_t|1|[0,2]| -CurrentSlatState|uint8_t|0|[0,2]| -CurrentPosition|uint8_t|0|[0,100]| -CurrentVerticalTiltAngle|int|0|[-90,90]| -CurrentVisibilityState|uint8_t|0|[0,1]| -CurrentHumidifierDehumidifierState|uint8_t|1|[0,3]| -CurrentDoorState|uint8_t|1|[0,4]| -CurrentFanState|uint8_t|1|[0,2]| -CurrentHeatingCoolingState|uint8_t|0|[0,2]| -CurrentHeaterCoolerState|uint8_t|1|[0,3]| -CurrentMediaState|uint8_t|0|[0,5]| -CurrentRelativeHumidity|double|0|[0,100]| -CurrentTemperature|double|0|[0,100]| -CurrentTiltAngle|int|0|[-90,90]| -FilterLifeLevel|double|0|[0,100]| -FilterChangeIndication|uint8_t|0|[0,1]| -FirmwareRevision|char \*|"1.0.0"||| -HardwareRevision|char \*|"1.0.0"||| -HeatingThresholdTemperature|double|16|[0,25]| -HoldPosition|boolean|false|[0,1]| -Hue|double|0|[0,360]| -Identify|boolean|false|[0,1]| -Identifier|uint32_t|0|[0,255]| -InputDeviceType|uint8_t|0|[0,6]| -InputSourceType|uint8_t|0|[0,10]| -InUse|uint8_t|0|[0,1]| -IsConfigured|uint8_t|0|[0,1]| -LeakDetected|uint8_t|0|[0,1]| -LockCurrentState|uint8_t|0|[0,3]| -LockPhysicalControls|uint8_t|0|[0,1]| -LockTargetState|uint8_t|0|[0,1]| -Manufacturer|char \*|"HomeSpan"||| -Model|char \*|"HomeSpan-ESP32"||| -MotionDetected|boolean|false|[0,1]| -Mute|boolean|false|[0,1]| -Name|char \*|"unnamed"||| -NitrogenDioxideDensity|double|0|[0,1000]| -ObstructionDetected|boolean|false|[0,1]| -PM25Density|double|0|[0,1000]| -OccupancyDetected|uint8_t|0|[0,1]| -OutletInUse|boolean|false|[0,1]| -On|boolean|false|[0,1]| -OzoneDensity|double|0|[0,1000]| -PictureMode|uint8_t|0|[0,13]| -PM10Density|double|0|[0,1000]| -PositionState|uint8_t|2|[0,2]| -PowerModeSelection|uint8_t|0|[0,1]| -ProgramMode|uint8_t|0|[0,2]| -ProgrammableSwitchEvent|uint8_t|0|[0,2]| -RelativeHumidityDehumidifierThreshold|double|50|[0,100]| -RelativeHumidityHumidifierThreshold|double|50|[0,100]| -RemainingDuration|uint32_t|60|[0,3600]| -RemoteKey|uint8_t|0|[0,16]| -ResetFilterIndication|uint8_t|0|[1,1]| -RotationDirection|int|0|[0,1]| -RotationSpeed|double|0|[0,100]| -Saturation|double|0|[0,100]| -SecuritySystemAlarmType|uint8_t|0|[0,1]| -SecuritySystemCurrentState|uint8_t|3|[0,4]| -SecuritySystemTargetState|uint8_t|3|[0,3]| -SerialNumber|char \*|"HS-12345"||| -ServiceLabelIndex|uint8_t|1|[1,255]| -ServiceLabelNamespace|uint8_t|1|[0,1]| -SlatType|uint8_t|0|[0,1]| -SleepDiscoveryMode|uint8_t|0|[0,1]| -SmokeDetected|uint8_t|0|[0,1]| -StatusActive|boolean|true|[0,1]| -StatusFault|uint8_t|0|[0,1]| -StatusJammed|uint8_t|0|[0,1]| -StatusLowBattery|uint8_t|0|[0,1]| -StatusTampered|uint8_t|0|[0,1]| -SulphurDioxideDensity|double|0|[0,1000]| -SwingMode|uint8_t|0|[0,1]| -TargetAirPurifierState|uint8_t|1|[0,1]| -TargetFanState|uint8_t|1|[0,1]| -TargetTiltAngle|int|0|[-90,90]| -TargetHeaterCoolerState|uint8_t|0|[0,2]| -SetDuration|uint32_t|60|[0,3600]| -TargetHorizontalTiltAngle|int|0|[-90,90]| -TargetHumidifierDehumidifierState|uint8_t|0|[0,2]| -TargetPosition|uint8_t|0|[0,100]| -TargetDoorState|uint8_t|1|[0,1]| -TargetHeatingCoolingState|uint8_t|0|[0,3]| -TargetMediaState|uint8_t|0|[0,2]| -TargetRelativeHumidity|double|0|[0,100]| -TargetTemperature|double|16|[10,38]| -TargetVisibilityState|uint8_t|0|[0,1]| -TemperatureDisplayUnits|uint8_t|0|[0,1]| -TargetVerticalTiltAngle|int|0|[-90,90]| -ValveType|uint8_t|0|[0,3]| -Version|char \*|"1.0.0"||| -VOCDensity|double|0|[0,1000]| -Volume|uint8_t|0|[0,100]| -VolumeControlType|uint8_t|0|[0,3]| -VolumeSelector|uint8_t|0|[0,1]| -WaterLevel|double|0|[0,100]| +### StatelessProgrammableSwitch (89) + Defines a "Stateless" Programmable Switch that can be used to trigger actions in the Home App.
+ + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
ProgrammableSwitchEvent (73) :small_blue_diamond:
  • specifies type of button press
uint8PR+EV+NV02
  • SINGLE_PRESS (0) :heavy_check_mark:
  • DOUBLE_PRESS (1) 
  • LONG_PRESS (2) 
ServiceLabelIndex (CB)
  • numerical index used to distinguish multiple copies of the same Service within an Accessory
uint8PR12551

-### HAP Format Codes (HAP-R2 Table 6-5) +### Switch (49) + Defines a generic Switch.
+ + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
On (25) :small_blue_diamond:
  • indicates if the Service is active/on
boolPR+PW+EV01
  • OFF (0) :heavy_check_mark:
  • ON (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

-|HAP-R2 Format Code|HomeSpan C++ Type| -|------------------|-----------------| -|BOOL|boolean| -|UINT8|uint8_t| -|UINT16|uint16_t| -|UINT32|uint32_t| -|UINT64|uint64_t| -|INT|int| -|FLOAT|double| -|STRING|char \*| -|TLV8|(not implemented)| -|DATA|uint8_t *| +## HEATING, VENTILATION, AND AIR CONDITIONING (HVAC) +### AirPurifier (BB) + Defines a basic Air Purifier with an optional fan and swing mode. Optional Linked Services: FilterMaintenance. Combine with an AirSensor Service for automated operations.
+ + + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
Active (B0) :small_blue_diamond:
  • indicates if the Service is active/on
uint8PW+PR+EV01
  • INACTIVE (0) :heavy_check_mark:
  • ACTIVE (1) 
CurrentAirPurifierState (A9) :small_blue_diamond:
  • indicates current state of air purification
uint8PR+EV02
  • INACTIVE (0) :heavy_check_mark:
  • IDLE (1) 
  • PURIFYING (2) 
TargetAirPurifierState (A8) :small_blue_diamond:
  • indicates desired state of air purifier
uint8PW+PR+EV01
  • MANUAL (0) 
  • AUTO (1) :heavy_check_mark:
RotationSpeed (29)
  • measured as a percentage
floatPR+PW+EV01000
SwingMode (B6)
  • indicates whether swing-mode is enabled
uint8PR+EV+PW01
  • SWING_DISABLED (0) :heavy_check_mark:
  • SWING_ENABLED (1) 
LockPhysicalControls (A7)
  • indicates if local control lock is enabled
uint8PW+PR+EV01
  • CONTROL_LOCK_DISABLED (0) :heavy_check_mark:
  • CONTROL_LOCK_ENABLED (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### Fan (B7) + Defines a Fan. Combine with a LightBulb Service to create a Lighted Ceiling Fan.
+ + + + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
Active (B0) :small_blue_diamond:
  • indicates if the Service is active/on
uint8PW+PR+EV01
  • INACTIVE (0) :heavy_check_mark:
  • ACTIVE (1) 
CurrentFanState (AF)
  • indicates current state of a fan
uint8PR+EV02
  • INACTIVE (0) 
  • IDLE (1) :heavy_check_mark:
  • BLOWING (2) 
TargetFanState (BF)
  • indicates desired state of fan
uint8PW+PR+EV01
  • MANUAL (0) 
  • AUTO (1) :heavy_check_mark:
RotationDirection (28)
  • indicates the rotation direction of a fan
intPR+PW+EV01
  • CLOCKWISE (0) :heavy_check_mark:
  • COUNTERCLOCKWISE (1) 
RotationSpeed (29)
  • measured as a percentage
floatPR+PW+EV01000
SwingMode (B6)
  • indicates whether swing-mode is enabled
uint8PR+EV+PW01
  • SWING_DISABLED (0) :heavy_check_mark:
  • SWING_ENABLED (1) 
LockPhysicalControls (A7)
  • indicates if local control lock is enabled
uint8PW+PR+EV01
  • CONTROL_LOCK_DISABLED (0) :heavy_check_mark:
  • CONTROL_LOCK_ENABLED (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### FilterMaintenance (BA) + Defines a Filter Maintainence check. Use only as a Linked Service for the AirPurifier Service.
+ + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
FilterChangeIndication (AC) :small_blue_diamond:
  • indicates state of filter
uint8PR+EV01
  • NO_CHANGE_NEEDED (0) :heavy_check_mark:
  • CHANGE_NEEDED (1) 
FilterLifeLevel (AB)
  • measured as a percentage of remaining life
floatPR+EV0100100
ResetFilterIndication (AD)
  • triggers an update when the user chooses to reset the FilterChangeIndication (only appears in Eve App, not Home App)
uint8PW11
  • RESET_FILTER (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### HeaterCooler (BC) + Defines a standalone Heater, Cooler, or combined Heater/Cooler.
+ + + + + + + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
Active (B0) :small_blue_diamond:
  • indicates if the Service is active/on
uint8PW+PR+EV01
  • INACTIVE (0) :heavy_check_mark:
  • ACTIVE (1) 
CurrentTemperature (11) :small_blue_diamond:
  • current temperature measured in Celsius
floatPR+EV01000
CurrentHeaterCoolerState (B1) :small_blue_diamond:
  • indicates whether appliance is currently heating, cooling, idle, or off
uint8PR+EV03
  • INACTIVE (0) 
  • IDLE (1) :heavy_check_mark:
  • HEATING (2) 
  • COOLING (3) 
TargetHeaterCoolerState (B2) :small_blue_diamond:
  • indicates desired state of heater/cooler
uint8PW+PR+EV02
  • AUTO (0) :heavy_check_mark:
  • HEAT (1) 
  • COOL (2) 
RotationSpeed (29)
  • measured as a percentage
floatPR+PW+EV01000
TemperatureDisplayUnits (36)
  • indicates the desired units to display the temperature on the device itself (has no effect on Home App)
uint8PW+PR+EV01
  • CELSIUS (0) :heavy_check_mark:
  • FAHRENHEIT (1) 
SwingMode (B6)
  • indicates whether swing-mode is enabled
uint8PR+EV+PW01
  • SWING_DISABLED (0) :heavy_check_mark:
  • SWING_ENABLED (1) 
CoolingThresholdTemperature (D)
  • cooling turns on when temperature (in Celsius) rises above this threshold
floatPR+PW+EV103510
HeatingThresholdTemperature (12)
  • heating turns on when temperature (in Celsius) falls below this threshold
floatPR+PW+EV02516
LockPhysicalControls (A7)
  • indicates if local control lock is enabled
uint8PW+PR+EV01
  • CONTROL_LOCK_DISABLED (0) :heavy_check_mark:
  • CONTROL_LOCK_ENABLED (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### HumidifierDehumidifier (BD) + Defines a Humidifer, Dehumidifier, or combined Humidifer/Dehumidifier.
+ + + + + + + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
Active (B0) :small_blue_diamond:
  • indicates if the Service is active/on
uint8PW+PR+EV01
  • INACTIVE (0) :heavy_check_mark:
  • ACTIVE (1) 
CurrentRelativeHumidity (10) :small_blue_diamond:
  • current humidity measured as a percentage
floatPR+EV01000
CurrentHumidifierDehumidifierState (B3) :small_blue_diamond:
  • indicates current state of humidifier/dehumidifer
uint8PR+EV03
  • INACTIVE (0) 
  • IDLE (1) :heavy_check_mark:
  • HUMIDIFYING (2) 
  • DEHUMIDIFYING (3) 
TargetHumidifierDehumidifierState (B4) :small_blue_diamond:
  • indicates desired state of humidifier/dehumidifier
uint8PW+PR+EV02
  • AUTO (0) :heavy_check_mark:
  • HUMIDIFY (1) 
  • DEHUMIDIFY (2) 
RelativeHumidityDehumidifierThreshold (C9)
  • dehumidfier turns on when humidity rises above this threshold
floatPR+PW+EV010050
RelativeHumidityHumidifierThreshold (CA)
  • humidfier turns on when humidity falls below this threshold
floatPR+PW+EV010050
RotationSpeed (29)
  • measured as a percentage
floatPR+PW+EV01000
SwingMode (B6)
  • indicates whether swing-mode is enabled
uint8PR+EV+PW01
  • SWING_DISABLED (0) :heavy_check_mark:
  • SWING_ENABLED (1) 
WaterLevel (B5)
  • measured as a percentage
floatPR+EV01000
LockPhysicalControls (A7)
  • indicates if local control lock is enabled
uint8PW+PR+EV01
  • CONTROL_LOCK_DISABLED (0) :heavy_check_mark:
  • CONTROL_LOCK_ENABLED (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### Slat (B9) + Defines a motorized ventilation Slat(s).
+ + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
CurrentSlatState (AA) :small_blue_diamond:
  • indicates current state of slats
uint8PR+EV02
  • FIXED (0) :heavy_check_mark:
  • JAMMED (1) 
  • SWINGING (2) 
SlatType (C0) :small_blue_diamond:
  • indicates the direction of a slat or group of slats
uint8PR01
  • HORIZONTAL (0) :heavy_check_mark:
  • VERTICAL (1) 
SwingMode (B6)
  • indicates whether swing-mode is enabled
uint8PR+EV+PW01
  • SWING_DISABLED (0) :heavy_check_mark:
  • SWING_ENABLED (1) 
CurrentTiltAngle (C1)
  • current angle (in degrees) of slats from fully up or left (-90) to fully open (0) to fully down or right (90)
intPR+EV-90900
TargetTiltAngle (C2)
  • indicated desired angle (in degrees) of slats from fully up or left (-90) to fully open (0) to fully down or right (90)
intPW+PR+EV-90900
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### Thermostat (4A) + Defines a Thermostat used to control a furnace, air conditioner, or both.
+ + + + + + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
CurrentHeatingCoolingState (F) :small_blue_diamond:
  • indicates whether appliance is currently heating, cooling, or just idle
uint8PR+EV02
  • IDLE (0) :heavy_check_mark:
  • HEATING (1) 
  • COOLING (2) 
TargetHeatingCoolingState (33) :small_blue_diamond:
  • indicates desired state of appliance
uint8PW+PR+EV03
  • OFF (0) :heavy_check_mark:
  • HEAT (1) 
  • COOL (2) 
  • AUTO (3) 
CurrentTemperature (11) :small_blue_diamond:
  • current temperature measured in Celsius
floatPR+EV01000
TargetTemperature (35) :small_blue_diamond:
  • indicates desired temperature measures in Celsius
floatPW+PR+EV103816
TemperatureDisplayUnits (36) :small_blue_diamond:
  • indicates the desired units to display the temperature on the device itself (has no effect on Home App)
uint8PW+PR+EV01
  • CELSIUS (0) :heavy_check_mark:
  • FAHRENHEIT (1) 
CoolingThresholdTemperature (D)
  • cooling turns on when temperature (in Celsius) rises above this threshold
floatPR+PW+EV103510
CurrentRelativeHumidity (10)
  • current humidity measured as a percentage
floatPR+EV01000
HeatingThresholdTemperature (12)
  • heating turns on when temperature (in Celsius) falls below this threshold
floatPR+PW+EV02516
TargetRelativeHumidity (34)
  • indicates desired humidity measured as a percentage
floatPW+PR+EV01000
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +## STANDALONE SENSORS +### AirQualitySensor (8D) + Defines an Air Quality Sensor.
+ + + + + + + + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
AirQuality (95) :small_blue_diamond:
  • a subjective description
uint8PR+EV05
  • UNKNOWN (0) :heavy_check_mark:
  • EXCELLENT (1) 
  • GOOD (2) 
  • FAIR (3) 
  • INFERIOR (4) 
  • POOR (5) 
OzoneDensity (C3)
  • measured in µg/m3
floatPR+EV010000
NitrogenDioxideDensity (C4)
  • measured in µg/m3
floatPR+EV010000
SulphurDioxideDensity (C5)
  • measured in µg/m3
floatPR+EV010000
PM25Density (C6)
  • 2.5-micron particulate density, measured in µg/m3
floatPR+EV010000
PM10Density (C7)
  • 10-micron particulate density, measured in µg/m3
floatPR+EV010000
VOCDensity (C8)
  • measured in µg/m3
floatPR+EV010000
StatusActive (75)
  • indicates whether the Service is properly functioning
boolPR+EV01
  • NOT_FUNCTIONING (0) 
  • FUNCTIONING (1) :heavy_check_mark:
StatusFault (77)
  • indicates whether the Service has a fault (only appears in Eve App, not Home App)
uint8PR+EV01
  • NO_FAULT (0) :heavy_check_mark:
  • FAULT (1) 
StatusTampered (7A)
  • indicates whether the Service has been tampered with
uint8PR+EV01
  • NOT_TAMPERED (0) :heavy_check_mark:
  • TAMPERED (1) 
StatusLowBattery (79)
  • indicates state of battery
uint8PR+EV01
  • NOT_LOW_BATTERY (0) :heavy_check_mark:
  • LOW_BATTERY (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### CarbonDioxideSensor (97) + Defines a Carbon Dioxide Sensor.
+ + + + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
CarbonDioxideDetected (92) :small_blue_diamond:
  • indicates if abnormal level is detected
uint8PR+EV01
  • NORMAL (0) :heavy_check_mark:
  • ABNORMAL (1) 
CarbonDioxideLevel (93)
  • measured on parts per million (ppm)
floatPR+EV01000000
CarbonDioxidePeakLevel (94)
  • measured in parts per million (ppm)
floatPR+EV01000000
StatusActive (75)
  • indicates whether the Service is properly functioning
boolPR+EV01
  • NOT_FUNCTIONING (0) 
  • FUNCTIONING (1) :heavy_check_mark:
StatusFault (77)
  • indicates whether the Service has a fault (only appears in Eve App, not Home App)
uint8PR+EV01
  • NO_FAULT (0) :heavy_check_mark:
  • FAULT (1) 
StatusTampered (7A)
  • indicates whether the Service has been tampered with
uint8PR+EV01
  • NOT_TAMPERED (0) :heavy_check_mark:
  • TAMPERED (1) 
StatusLowBattery (79)
  • indicates state of battery
uint8PR+EV01
  • NOT_LOW_BATTERY (0) :heavy_check_mark:
  • LOW_BATTERY (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### CarbonMonoxideSensor (7F) + Defines a Carbon Monoxide Sensor.
+ + + + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
CarbonMonoxideDetected (69) :small_blue_diamond:
  • indicates if abnormal level is detected
uint8PR+EV01
  • NORMAL (0) :heavy_check_mark:
  • ABNORMAL (1) 
CarbonMonoxideLevel (90)
  • measured in parts per million (ppm)
floatPR+EV01000
CarbonMonoxidePeakLevel (91)
  • measured in parts per million (ppm)
floatPR+EV01000
StatusActive (75)
  • indicates whether the Service is properly functioning
boolPR+EV01
  • NOT_FUNCTIONING (0) 
  • FUNCTIONING (1) :heavy_check_mark:
StatusFault (77)
  • indicates whether the Service has a fault (only appears in Eve App, not Home App)
uint8PR+EV01
  • NO_FAULT (0) :heavy_check_mark:
  • FAULT (1) 
StatusTampered (7A)
  • indicates whether the Service has been tampered with
uint8PR+EV01
  • NOT_TAMPERED (0) :heavy_check_mark:
  • TAMPERED (1) 
StatusLowBattery (79)
  • indicates state of battery
uint8PR+EV01
  • NOT_LOW_BATTERY (0) :heavy_check_mark:
  • LOW_BATTERY (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### ContactSensor (80) + Defines a Contact Sensor.
+ + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
ContactSensorState (6A) :small_blue_diamond:
  • indictates if contact is detected (i.e. closed)
uint8PR+EV01
  • DETECTED (0) 
  • NOT_DETECTED (1) :heavy_check_mark:
StatusActive (75)
  • indicates whether the Service is properly functioning
boolPR+EV01
  • NOT_FUNCTIONING (0) 
  • FUNCTIONING (1) :heavy_check_mark:
StatusFault (77)
  • indicates whether the Service has a fault (only appears in Eve App, not Home App)
uint8PR+EV01
  • NO_FAULT (0) :heavy_check_mark:
  • FAULT (1) 
StatusTampered (7A)
  • indicates whether the Service has been tampered with
uint8PR+EV01
  • NOT_TAMPERED (0) :heavy_check_mark:
  • TAMPERED (1) 
StatusLowBattery (79)
  • indicates state of battery
uint8PR+EV01
  • NOT_LOW_BATTERY (0) :heavy_check_mark:
  • LOW_BATTERY (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### HumiditySensor (82) + Defines a Humidity Sensor.
+ + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
CurrentRelativeHumidity (10) :small_blue_diamond:
  • current humidity measured as a percentage
floatPR+EV01000
StatusActive (75)
  • indicates whether the Service is properly functioning
boolPR+EV01
  • NOT_FUNCTIONING (0) 
  • FUNCTIONING (1) :heavy_check_mark:
StatusFault (77)
  • indicates whether the Service has a fault (only appears in Eve App, not Home App)
uint8PR+EV01
  • NO_FAULT (0) :heavy_check_mark:
  • FAULT (1) 
StatusTampered (7A)
  • indicates whether the Service has been tampered with
uint8PR+EV01
  • NOT_TAMPERED (0) :heavy_check_mark:
  • TAMPERED (1) 
StatusLowBattery (79)
  • indicates state of battery
uint8PR+EV01
  • NOT_LOW_BATTERY (0) :heavy_check_mark:
  • LOW_BATTERY (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### LeakSensor (83) + Defines a Leak Sensor.
+ + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
LeakDetected (70) :small_blue_diamond:
  • indictates if a leak is detected
uint8PR+EV01
  • NOT_DETECTED (0) :heavy_check_mark:
  • DETECTED (1) 
StatusActive (75)
  • indicates whether the Service is properly functioning
boolPR+EV01
  • NOT_FUNCTIONING (0) 
  • FUNCTIONING (1) :heavy_check_mark:
StatusFault (77)
  • indicates whether the Service has a fault (only appears in Eve App, not Home App)
uint8PR+EV01
  • NO_FAULT (0) :heavy_check_mark:
  • FAULT (1) 
StatusTampered (7A)
  • indicates whether the Service has been tampered with
uint8PR+EV01
  • NOT_TAMPERED (0) :heavy_check_mark:
  • TAMPERED (1) 
StatusLowBattery (79)
  • indicates state of battery
uint8PR+EV01
  • NOT_LOW_BATTERY (0) :heavy_check_mark:
  • LOW_BATTERY (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### LightSensor (84) + Defines a Light Sensor.
+ + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
CurrentAmbientLightLevel (6B) :small_blue_diamond:
  • measured in Lux (lumens/m2
floatPR+EV0.00011000001
StatusActive (75)
  • indicates whether the Service is properly functioning
boolPR+EV01
  • NOT_FUNCTIONING (0) 
  • FUNCTIONING (1) :heavy_check_mark:
StatusFault (77)
  • indicates whether the Service has a fault (only appears in Eve App, not Home App)
uint8PR+EV01
  • NO_FAULT (0) :heavy_check_mark:
  • FAULT (1) 
StatusTampered (7A)
  • indicates whether the Service has been tampered with
uint8PR+EV01
  • NOT_TAMPERED (0) :heavy_check_mark:
  • TAMPERED (1) 
StatusLowBattery (79)
  • indicates state of battery
uint8PR+EV01
  • NOT_LOW_BATTERY (0) :heavy_check_mark:
  • LOW_BATTERY (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### MotionSensor (85) + Defines a Motion Sensor.
+ + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
MotionDetected (22) :small_blue_diamond:
  • indicates if motion is detected
boolPR+EV01
  • NOT_DETECTED (0) :heavy_check_mark:
  • DETECTED (1) 
StatusActive (75)
  • indicates whether the Service is properly functioning
boolPR+EV01
  • NOT_FUNCTIONING (0) 
  • FUNCTIONING (1) :heavy_check_mark:
StatusFault (77)
  • indicates whether the Service has a fault (only appears in Eve App, not Home App)
uint8PR+EV01
  • NO_FAULT (0) :heavy_check_mark:
  • FAULT (1) 
StatusTampered (7A)
  • indicates whether the Service has been tampered with
uint8PR+EV01
  • NOT_TAMPERED (0) :heavy_check_mark:
  • TAMPERED (1) 
StatusLowBattery (79)
  • indicates state of battery
uint8PR+EV01
  • NOT_LOW_BATTERY (0) :heavy_check_mark:
  • LOW_BATTERY (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### OccupancySensor (86) + Defines and Occupancy Sensor.
+ + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
OccupancyDetected (71) :small_blue_diamond:
  • indicates if occupanccy is detected
uint8PR+EV01
  • NOT_DETECTED (0) :heavy_check_mark:
  • DETECTED (1) 
StatusActive (75)
  • indicates whether the Service is properly functioning
boolPR+EV01
  • NOT_FUNCTIONING (0) 
  • FUNCTIONING (1) :heavy_check_mark:
StatusFault (77)
  • indicates whether the Service has a fault (only appears in Eve App, not Home App)
uint8PR+EV01
  • NO_FAULT (0) :heavy_check_mark:
  • FAULT (1) 
StatusTampered (7A)
  • indicates whether the Service has been tampered with
uint8PR+EV01
  • NOT_TAMPERED (0) :heavy_check_mark:
  • TAMPERED (1) 
StatusLowBattery (79)
  • indicates state of battery
uint8PR+EV01
  • NOT_LOW_BATTERY (0) :heavy_check_mark:
  • LOW_BATTERY (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### SmokeSensor (87) + Defines a Smoke Sensor.
+ + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
SmokeDetected (76) :small_blue_diamond:
  • indicates if smoke is detected
uint8PR+EV01
  • NOT_DETECTED (0) :heavy_check_mark:
  • DETECTED (1) 
StatusActive (75)
  • indicates whether the Service is properly functioning
boolPR+EV01
  • NOT_FUNCTIONING (0) 
  • FUNCTIONING (1) :heavy_check_mark:
StatusFault (77)
  • indicates whether the Service has a fault (only appears in Eve App, not Home App)
uint8PR+EV01
  • NO_FAULT (0) :heavy_check_mark:
  • FAULT (1) 
StatusTampered (7A)
  • indicates whether the Service has been tampered with
uint8PR+EV01
  • NOT_TAMPERED (0) :heavy_check_mark:
  • TAMPERED (1) 
StatusLowBattery (79)
  • indicates state of battery
uint8PR+EV01
  • NOT_LOW_BATTERY (0) :heavy_check_mark:
  • LOW_BATTERY (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### TemperatureSensor (8A) + Defines a Temperature Sensor.
+ + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
CurrentTemperature (11) :small_blue_diamond:
  • current temperature measured in Celsius
floatPR+EV01000
StatusActive (75)
  • indicates whether the Service is properly functioning
boolPR+EV01
  • NOT_FUNCTIONING (0) 
  • FUNCTIONING (1) :heavy_check_mark:
StatusFault (77)
  • indicates whether the Service has a fault (only appears in Eve App, not Home App)
uint8PR+EV01
  • NO_FAULT (0) :heavy_check_mark:
  • FAULT (1) 
StatusTampered (7A)
  • indicates whether the Service has been tampered with
uint8PR+EV01
  • NOT_TAMPERED (0) :heavy_check_mark:
  • TAMPERED (1) 
StatusLowBattery (79)
  • indicates state of battery
uint8PR+EV01
  • NOT_LOW_BATTERY (0) :heavy_check_mark:
  • LOW_BATTERY (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +## DOORS, LOCKS, AND WINDOWS +### Door (81) + Defines a motorized Door.
+ + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
CurrentPosition (6D) :small_blue_diamond:
  • current position (as a percentage) from fully closed (0) to full open (100)
uint8PR+EV01000
TargetPosition (7C) :small_blue_diamond:
  • indicates target position (as a percentage) from fully closed (0) to full open (100)
uint8PW+PR+EV01000
ObstructionDetected (24)
  • indicates if obstruction is detected
boolPR+EV01
  • NOT_DETECTED (0) :heavy_check_mark:
  • DETECTED (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### Doorbell (121) + Defines a Doorbell. Can be used on a standalone basis or in conjunction with a LockMechanism Service.
+ + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
ProgrammableSwitchEvent (73) :small_blue_diamond:
  • specifies type of button press
uint8PR+EV+NV02
  • SINGLE_PRESS (0) :heavy_check_mark:
  • DOUBLE_PRESS (1) 
  • LONG_PRESS (2) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### GarageDoorOpener (41) + Defines a motorized Garage Door Opener.
+ + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
CurrentDoorState (E) :small_blue_diamond:
  • indicates current state of a door
uint8PR+EV04
  • OPEN (0) 
  • CLOSED (1) :heavy_check_mark:
  • OPENING (2) 
  • CLOSING (3) 
  • STOPPED (4) 
TargetDoorState (32) :small_blue_diamond:
  • indicates desired state of door
uint8PW+PR+EV01
  • OPEN (0) 
  • CLOSED (1) :heavy_check_mark:
ObstructionDetected (24) :small_blue_diamond:
  • indicates if obstruction is detected
boolPR+EV01
  • NOT_DETECTED (0) :heavy_check_mark:
  • DETECTED (1) 
LockCurrentState (1D)
  • indicates state of a lock
uint8PR+EV03
  • UNLOCKED (0) :heavy_check_mark:
  • LOCKED (1) 
  • JAMMED (2) 
  • UNKNOWN (3) 
LockTargetState (1E)
  • indicates desired state of lock
uint8PW+PR+EV01
  • UNLOCK (0) :heavy_check_mark:
  • LOCK (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### LockMechanism (45) + Defines an electronic Lock.
+ + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
LockCurrentState (1D) :small_blue_diamond:
  • indicates state of a lock
uint8PR+EV03
  • UNLOCKED (0) :heavy_check_mark:
  • LOCKED (1) 
  • JAMMED (2) 
  • UNKNOWN (3) 
LockTargetState (1E) :small_blue_diamond:
  • indicates desired state of lock
uint8PW+PR+EV01
  • UNLOCK (0) :heavy_check_mark:
  • LOCK (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### Window (8B) + Defines a motorized Window.
+ + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
CurrentPosition (6D) :small_blue_diamond:
  • current position (as a percentage) from fully closed (0) to full open (100)
uint8PR+EV01000
TargetPosition (7C) :small_blue_diamond:
  • indicates target position (as a percentage) from fully closed (0) to full open (100)
uint8PW+PR+EV01000
ObstructionDetected (24)
  • indicates if obstruction is detected
boolPR+EV01
  • NOT_DETECTED (0) :heavy_check_mark:
  • DETECTED (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### WindowCovering (8C) + Defines a motorized Window Shade, Screen, Awning, etc.
+ + + + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
TargetPosition (7C) :small_blue_diamond:
  • indicates target position (as a percentage) from fully closed (0) to full open (100)
uint8PW+PR+EV01000
CurrentPosition (6D) :small_blue_diamond:
  • current position (as a percentage) from fully closed (0) to full open (100)
uint8PR+EV01000
CurrentHorizontalTiltAngle (6C)
  • current angle (in degrees) of slats from fully up (-90) to fully open (0) to fully down (90)
intPR+EV-90900
TargetHorizontalTiltAngle (7B)
  • indicates desired angle (in degrees) of slats from fully up (-90) to fully open (0) to fully down (90)
intPW+PR+EV-90900
CurrentVerticalTiltAngle (6E)
  • current angle (in degrees) of slats from fully left (-90) to fully open (0) to fully right (90)
intPR+EV-90900
TargetVerticalTiltAngle (7D)
  • indicates desired angle (in degrees) of slats from fully left (-90) to fully open (0) to fully right (90)
intPW+PR+EV-90900
ObstructionDetected (24)
  • indicates if obstruction is detected
boolPR+EV01
  • NOT_DETECTED (0) :heavy_check_mark:
  • DETECTED (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +## WATER SYSTEMS +### Faucet (D7) + Defines the master control for a multi-Valve appliance. Linked Services: Valve (at least one required), and HeaterCooler (optional).
+ + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
Active (B0) :small_blue_diamond:
  • indicates if the Service is active/on
uint8PW+PR+EV01
  • INACTIVE (0) :heavy_check_mark:
  • ACTIVE (1) 
StatusFault (77)
  • indicates whether the Service has a fault (only appears in Eve App, not Home App)
uint8PR+EV01
  • NO_FAULT (0) :heavy_check_mark:
  • FAULT (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### IrrigationSystem (CF) + Defines an Irrigation System. Linked Services: Valve Service (at least one required).
+ + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
Active (B0) :small_blue_diamond:
  • indicates if the Service is active/on
uint8PW+PR+EV01
  • INACTIVE (0) :heavy_check_mark:
  • ACTIVE (1) 
ProgramMode (D1) :small_blue_diamond:
  • indicates if pre-scheduled program is running
uint8PR+EV02
  • NONE (0) :heavy_check_mark:
  • SCHEDULED (1) 
  • SCHEDULE_OVERRIDEN (2) 
InUse (D2) :small_blue_diamond:
  • if Service is set to active, this indictes whether it is currently in use
uint8PR+EV01
  • NOT_IN_USE (0) :heavy_check_mark:
  • IN_USE (1) 
RemainingDuration (D4)
  • duration (in seconds) remaining for Service to be active/on
uint32PR+EV0360060
StatusFault (77)
  • indicates whether the Service has a fault (only appears in Eve App, not Home App)
uint8PR+EV01
  • NO_FAULT (0) :heavy_check_mark:
  • FAULT (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### Valve (D0) + Defines an electronic Valve. Can be used standalone or as a Linked Service for either a Faucet or IrrigationSystem Service.
+ + + + + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
Active (B0) :small_blue_diamond:
  • indicates if the Service is active/on
uint8PW+PR+EV01
  • INACTIVE (0) :heavy_check_mark:
  • ACTIVE (1) 
InUse (D2) :small_blue_diamond:
  • if Service is set to active, this indictes whether it is currently in use
uint8PR+EV01
  • NOT_IN_USE (0) :heavy_check_mark:
  • IN_USE (1) 
ValveType (D5) :small_blue_diamond:
  • indicates the type of valve
uint8PR+EV03
  • GENERIC (0) :heavy_check_mark:
  • IRRIGATION (1) 
  • SHOWER_HEAD (2) 
  • FAUCET (3) 
SetDuration (D3)
  • specifies the duration (in seconds) for a Service to remain on once activated
uint32PW+PR+EV0360060
RemainingDuration (D4)
  • duration (in seconds) remaining for Service to be active/on
uint32PR+EV0360060
IsConfigured (D6)
  • indicates if a predefined Service has been configured
uint8PR+EV01
  • NOT_CONFIGURED (0) :heavy_check_mark:
  • CONFIGURED (1) 
ServiceLabelIndex (CB)
  • numerical index used to distinguish multiple copies of the same Service within an Accessory
uint8PR12551
StatusFault (77)
  • indicates whether the Service has a fault (only appears in Eve App, not Home App)
uint8PR+EV01
  • NO_FAULT (0) :heavy_check_mark:
  • FAULT (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +## SECURITY SYSTEMS +### SecuritySystem (7E) + Defines a Security System. Often used in combination with MotionSensor and ContactSensor Services.
+ + + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
SecuritySystemCurrentState (66) :small_blue_diamond:
  • indicates current state of the security system
uint8PR+EV04
  • ARMED_STAY (0) 
  • ARMED_AWAY (1) 
  • ARMED_NIGHT (2) 
  • DISARMED (3) :heavy_check_mark:
  • ALARM_TRIGGERED (4) 
SecuritySystemTargetState (67) :small_blue_diamond:
  • indicates desired state of the security system
uint8PW+PR+EV03
  • ARM_STAY (0) 
  • ARM_AWAY (1) 
  • ARM_NIGHT (2) 
  • DISARM (3) :heavy_check_mark:
SecuritySystemAlarmType (8E)
  • indicates whether alarm was triggered for known reason
uint8PR+EV01
  • KNOWN (0) :heavy_check_mark:
  • UNKNOWN (1) 
StatusFault (77)
  • indicates whether the Service has a fault (only appears in Eve App, not Home App)
uint8PR+EV01
  • NO_FAULT (0) :heavy_check_mark:
  • FAULT (1) 
StatusTampered (7A)
  • indicates whether the Service has been tampered with
uint8PR+EV01
  • NOT_TAMPERED (0) :heavy_check_mark:
  • TAMPERED (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +## TELEVISIONS +### InputSource (D9) + Defines an Input Source for a TV. Use only as a Linked Service for the Television Service.
+ + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
Identifier (E6) :small_blue_diamond:
  • numerical Identifer of the InputSource.
uint32PR02550
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"
IsConfigured (D6)
  • indicates if a predefined Service has been configured
uint8PR+EV01
  • NOT_CONFIGURED (0) :heavy_check_mark:
  • CONFIGURED (1) 
CurrentVisibilityState (135)
  • current visibility of the Service, as selectable on the Settings Page of the Home App
uint8PR+EV01
  • VISIBLE (0) :heavy_check_mark:
  • NOT_VISIBLE (1) 
TargetVisibilityState (134)
  • indicates desired visibility of the Service, as selectable on the Settings Page of the Home App
uint8PW+PR+EV01
  • VISIBLE (0) :heavy_check_mark:
  • NOT_VISIBLE (1) 

+ +### Television (D8) + Defines a TV. Optional Linked Services: InputSource and TelevisionSpeaker.
+ + + + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
Active (B0) :small_blue_diamond:
  • indicates if the Service is active/on
uint8PW+PR+EV01
  • INACTIVE (0) :heavy_check_mark:
  • ACTIVE (1) 
ActiveIdentifier (E7)
  • numerical Identifier of the InputSource selected in the Home App.
uint32PW+PR+EV02550
RemoteKey (E1)
  • triggers an update when the corresponding key is pressed in the Remote Control widget on an iPhone
uint8PW415
  • UP (4) 
  • DOWN (5) 
  • LEFT (6) 
  • RIGHT (7) 
  • CENTER (8) 
  • BACK (9) 
  • PLAY_PAUSE (11) 
  • INFO (15) 
PowerModeSelection (DF)
  • when defined, creates a "View TV Settings" button in the Home App that triggers an update to this Characteristic when pressed
uint8PW00
  • VIEW_SETTINGS (0) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +### TelevisionSpeaker (113) + Defines a Television Speaker that can be controlled via the Remote Control widget on an iPhone. Use only as a Linked Service for the Television Service.
+ + + + +
CharacteristicFormatPermsMinMaxConstants/Defaults
VolumeControlType (E9) :small_blue_diamond:
  • indicates the type of volume control
uint8PR+EV03
  • NONE (0) 
  • RELATIVE (1) 
  • RELATIVE_CURRENT (2) 
  • ABSOLUTE (3) :heavy_check_mark:
VolumeSelector (EA) :small_blue_diamond:
  • triggered by presses to the iPhone's volume up/down buttons when TV is selected in the Remote Control widget
uint8PW01
  • VOLUME_UP (0) 
  • VOLUME_DOWN (1) 
ConfiguredName (E3)
  • default display name of this Service
stringPW+PR+EV--"unnamed"

+ +## MISCELLANEOUS +### ServiceLabel (CC) + Defines a naming scheme for un-nameable Services, such as a StatelessProgrammableSwitch, by Linking them to this Service. When used, those other Services must each include a ServiceLabelIndex Characteristic with a unique value.
+ + +
CharacteristicFormatPermsMinMaxConstants/Defaults
ServiceLabelNamespace (CD) :small_blue_diamond:
  • indicates how un-named Services linked together with a ServiceLabel Service should be displayed in the Home App
uint8PR01
  • DOTS (0) 
  • NUMERALS (1) :heavy_check_mark:

--- [↩️](../README.md) Back to the Welcome page + diff --git a/docs/Solutions.md b/docs/Solutions.md index 5b56ec8..7f8fd0a 100644 --- a/docs/Solutions.md +++ b/docs/Solutions.md @@ -12,16 +12,8 @@ * 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. - -#### *Compiler Error - `core_version.h` file not found* - -* HomeSpan requires the file `core_version.h`. This file is part of each Arduino-ESP32 release package and is properly installed if you use the Arduino Board Manager. If you install the Arduino-ESP32 package manually by downloading the official release zip file (listed under the "Assets" section for each release), you will also find the `core_version.h` is included. - -* If you receive the above error when you try to compile a HomeSpan sketch, that means the Arduino-ESP32 package was not properly installed. This can occur if instead of using one of the two methods above, you've tried to manually install the Arduino-ESP32 package by downloading a zip file created live from a specific branch of the Arduino-ESP32 code (typically via the `<> Code` button on GitHub when browsing a particular branch). The `core_version.h` file is usually not included in any of the branches, and thus will not be part of any zip files you request directly from a specific branch. - -* **Resolution:** Use the Arduino Board manager to install the Arduino-ESP32 package (recommended), or install manually using an *official release zip* file found under the "Assets" section of each release version shown on the Arduino-ESP32 GitHub site. - +* *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. + --- [↩️](../README.md) Back to the Welcome page diff --git a/docs/Stepper.md b/docs/Stepper.md index 22a1727..dd169ea 100644 --- a/docs/Stepper.md +++ b/docs/Stepper.md @@ -2,28 +2,28 @@ HomeSpan includes dedicated classes that provide for easy control of a stepper motor connected to an ESP32 via a stepper motor driver board. These classes allow one or more stepper motors to operate smoothly and asynchronously in the background while HomeSpan continues to run in the foreground. On devices with dual processors, stepper-motor control can be run either on the same or a different processor from HomeSpan. -The HomeSpan class that contains all the methods to control a stepper motor is called **StepperControl**. However, this is an abstract class and cannot be instantiated directly. Instead you instantiate stepper motor objects using driver-specific child-classes (derived from **StepperControl**) that contain all the logic to configure and operate a particular driver board. Each child class supports one or more constructors allowing you to specify which output pins on your ESP32 device will be connected to the required pins on your driver board: +The HomeSpan class that contains all the methods to control a stepper motor is called **StepperControl**. However, this is an abstract class and cannot be instantiated directly. Instead you instantiate stepper motor objects using driver-specific child-classes (derived from **StepperControl**) that contain all the logic to configure and operate a particular driver board. Each child class supports one or more constructors allowing you to specify which output pins on your ESP32 device will be connected to the required pins on your driver board. + +The following drivers are currently included in HomeSpan: * **[Stepper_TB6612](StepperDrivers/Stepper_TB6612.md)** - * This class is used to operate stepper motors driven by a [Toshiba TB6612](https://cdn-shop.adafruit.com/datasheets/TB6612FNG_datasheet_en_20121101.pdf) chip, either with or without the use of ESP32 PWM pins + * This class is used to operate stepper motors driven by a [Toshiba TB6612](https://cdn-shop.adafruit.com/datasheets/TB6612FNG_datasheet_en_20121101.pdf) (or equivalent) chip + * Can be used either with or without ESP32 PWM pins * See, for example, the [Adafruit TB6612 1.2A DC/Stepper Motor Driver Breakout Board](https://www.adafruit.com/product/2448) - * To use, add the following to the top of your sketch: `#include "extras/Stepper_TB6612.h"` - * Constructor 1: `Stepper_TB6612(int AIN1, int AIN2, int BIN1, int BIN2)` - * controls the driver board using only 4 digital pins from the ESP32 - * does not provide ability to microstep the motor - * Constructor 2: `Stepper_TB6612(int AIN1, int AIN2, int BIN1, int BIN2, int PWMA, int PWMB)` - * controls the driver board using 4 digital pins and 2 PWM pins from the ESP32 - * the addition of the PWM pins provides the ability to microstep the motor * **[Stepper_A3967](StepperDrivers/Stepper_A3967.md)** - * This class is used to operate stepper motors driven by an [Allegro A3967](https://cdn.sparkfun.com/datasheets/Robotics/A3967-Datasheet.pdf) chip + * This class is used to operate stepper motors driven by an [Allegro A3967](https://cdn.sparkfun.com/datasheets/Robotics/A3967-Datasheet.pdf) (or equivalent) chip * See, for example, the [Sparkfun EasyDriver Stepper Motor Board](https://www.sparkfun.com/products/12779) - * To use, add the following to the top of your sketch: `#include "extras/Stepper_A3967.h"` - * Contructor: `Stepper_A3967(int M1, int M2, int STEP, int DIR, int ENABLE)` - * controls the driver board using 5 digital pins from the ESP32 - * microstepping is built into the driver board (separate ESP32 PWM pins are not needed) -Click on either of the driver-specific classes above for complete details on how to wire and configure a particular driver board. +* **[Stepper_ULN2003A](StepperDrivers/Stepper_ULN2003A.md)** + * This class is used to operate stepper motors driven by a [Texas Instruments ULN2003A](https://www.ti.com/lit/ds/symlink/uln2003a.pdf) (or equivalent) chip + * See, for example, the [Opencircuit ULN2003 Stepper Motor Driver Board](https://opencircuit.shop/product/uln2003-stepper-motor-driver-module) + +* **[Stepper_UNIPOLAR](StepperDrivers/Stepper_UNIPOLAR.md)** + * This class provides a generic driver for use with any center-tapped unipolar stepper motor + * Use requires a driver board that can convert the low-voltage/low-current digital signals from 4 pins on the ESP32 to higher-voltage/higher-current signals suitable for operating the stepper motor + +Click on any of the driver-specific classes above for complete details on how to wire and configure a particular driver board. ## StepperControl Methods @@ -136,7 +136,7 @@ Below is a simple sketch demonstrating the above methods: ```C++ // StepperControl Example using TB6612-based Driver Board with HALF STEP PWM MODE -#include "extras/Stepper_TB6612.h" // include the driver for a TB6612 chip +#include "HomeSpan.h" // HomeSpan includes all the StepperControl classes StepperControl *motor; // create a global pointer to StepperControl so it can be accessed in both setup() and loop() @@ -186,7 +186,7 @@ A fully worked example showing how to use the *StepperControl* class within a co ## Creating your own **StepperControl** Driver -If neither of the above motor driver classes works for your specific chip or driver board, it is relatively straightfoward to create a new driver to use in your sketch. This is because all the logic to operate a stepper motor in the background is already embedded in the abstract **StepperControl** class. To create your own driver, start by creating a child class derived from **StepperControl**. Next, add a constructor that defines the pins and performs any initializations if needed. Finally, define the following methods that **StepperControl** calls to operate the motor: +If none of the above motor driver classes works for your specific chip or driver board, it is relatively straightfoward to create a new driver to use in your sketch. This is because all the logic to operate a stepper motor in the background is already embedded in the abstract **StepperControl** class. To create your own driver, start by creating a child class derived from **StepperControl**. Next, add a constructor that defines the pins and performs any initializations if needed. Finally, define the following methods that **StepperControl** calls to operate the motor: * `void onStep(boolean direction)` - contains the logic to advance the motor by a single step based on the *direction* parameter * `void onEnable()` - contains the logic that enables the motor driver @@ -199,7 +199,7 @@ Only the first method, `onStep()`, is required to be defined. You can leave any As an example, below is the complete code for the **Stepper_A3967** class: ```C++ -#include "extras/StepperControl.h" +#include "HomeSpan.h" ////////////////////////// diff --git a/docs/StepperDrivers/Stepper_A3967.md b/docs/StepperDrivers/Stepper_A3967.md index 7d0ef6a..d5e52d8 100644 --- a/docs/StepperDrivers/Stepper_A3967.md +++ b/docs/StepperDrivers/Stepper_A3967.md @@ -1,6 +1,6 @@ # Stepper_A3967 -This is a derived class of **StepperControl** designed to operate stepper motors driven by an [Allegro A3967](https://cdn.sparkfun.com/datasheets/Robotics/A3967-Datasheet.pdf) chip. To use, add `#include "extras/Stepper_A3967.h"` to the top of your sketch. +This is a derived class of **StepperControl** designed to operate stepper motors driven by an [Allegro A3967](https://cdn.sparkfun.com/datasheets/Robotics/A3967-Datasheet.pdf) (or equivalent) chip. The Allegro A3967 is a specialized driver designed for stepper motors. It contains a built-in PWM generator and pre-programmed stepping modes. Wiring for the [Sparkfun EasyDriver Stepper Motor Board](https://learn.sparkfun.com/tutorials/easy-driver-hook-up-guide?_ga=2.152816825.1841726212.1688220137-156607829.1686369274) that uses this chip is as follows: @@ -11,14 +11,14 @@ The Allegro A3967 is a specialized driver designed for stepper motors. It contai * *Motor A* - connect to the "A" coil of the stepper motor * *Motor B* - connect to the "B" coil of the stepper motor #### **Control Connections** - * *ENABLE* - connect to a digital pin on the ESP32 - used to enable/disable to motor driver - * *STEP, DIR* - connect to two digital pins on the ESP32 - used to step the motor and set the direction * *MS1, MS2* - connect to two digital pins on the ESP32 - used to set the step type mode + * *STEP, DIR* - connect to two digital pins on the ESP32 - used to step the motor and set the direction + * *ENABLE* - connect to a digital pin on the ESP32 - used to enable/disable to motor driver * *SLEEP, RESET* - already pulled high on the EasyDriver board, so no connection neeed. If using a different driver board, ensure these pins are pulled high, else connect to VCC * *PFD* - not used The **Stepper_A3967** class includes the following constructor: - * `Stepper_A3967(int M1, int M2, int STEP, int DIR, int ENABLE)` + * `Stepper_A3967(int MS1, int MS2, int STEP, int DIR, int ENABLE)` * controls the driver board using 5 digital pins from the ESP32, where the parameters specify the pin numbers. Supports the following step type modes: * FULL_STEP_TWO_PHASE diff --git a/docs/StepperDrivers/Stepper_TB6612.md b/docs/StepperDrivers/Stepper_TB6612.md index 960679e..2758316 100644 --- a/docs/StepperDrivers/Stepper_TB6612.md +++ b/docs/StepperDrivers/Stepper_TB6612.md @@ -1,6 +1,6 @@ # Stepper_TB6612 -This is a derived class of **StepperControl** designed to operate stepper motors driven by a [Toshiba TB6612](https://cdn-shop.adafruit.com/datasheets/TB6612FNG_datasheet_en_20121101.pdf) chip, either with or without the use of ESP32 PWM pins. To use, add `#include "extras/Stepper_TB6612.h"` to the top of your sketch. +This is a derived class of **StepperControl** designed to operate stepper motors driven by a [Toshiba TB6612](https://cdn-shop.adafruit.com/datasheets/TB6612FNG_datasheet_en_20121101.pdf) (or equivalent) chip, either with or without the use of ESP32 PWM pins. The Toshiba TB6612 is a generic motor driver providing direct control of two full H-bridges. Wiring for the [Adafruit TB6612 1.2A DC/Stepper Motor Driver Breakout Board](https://learn.adafruit.com/adafruit-tb6612-h-bridge-dc-stepper-motor-driver-breakout) that uses this chip is as follows: diff --git a/docs/StepperDrivers/Stepper_ULN2003A.md b/docs/StepperDrivers/Stepper_ULN2003A.md new file mode 100644 index 0000000..60b6fd4 --- /dev/null +++ b/docs/StepperDrivers/Stepper_ULN2003A.md @@ -0,0 +1,37 @@ +# Stepper_ULN2003A + +This is a derived class of **StepperControl** designed to operate stepper motors driven by a [Texas Instruments ULN2003A](https://www.ti.com/lit/ds/symlink/uln2003a.pdf) (or equivalent) chip. + +The Texas Instruments ULN2003A chip containins an array of seven Darlington transistor pairs each capable of converting low-voltage/low-current digital signals into higher-voltage/higher-current outputs suitable for driving a stepper motor.[^1] + +[^1]: Only four of the seven Darlington transistor pairs in the ULN2003A are needed to drive a typical unipolar stepper motor. + +Various manufacturers have incorporated this chip into a dedicated stepper motor board designed to drive unipolar motors such the [28BYJ‑48 5‑Volt Stepper](https://opencircuit.shop/product/28byj-48-5v-stepper-motor-4-phase-5-wire) and [28BYJ‑48 12‑Volt Stepper](https://opencircuit.shop/product/28byj-48-12v-stepper-motor-4-phase-5-wire). Wiring for the [Opencircuit ULN2003 Stepper Motor Driver Board](https://opencircuit.shop/product/uln2003-stepper-motor-driver-module) that uses this chip is as follows: + +#### **Power Connections**[^2] + * ➕ - connect to an external DC power supply that will drive stepper motor (5-12V) + * ➖ - connect to GND on the ESP32, and to ground of external DC power supply +#### **Motor Connections** + * plug the motor directly into the board's 5-pin connector +#### **Control Connections** + * *IN1, IN2, IN3, IN4* - connect to four digital pins on the ESP32 - used to step the motor in either direction + +The **Stepper_ULN2003A** class includes the following constructors: + * `Stepper_ULN2003A(int IN1, int IN2, int IN3, int IN4)` + * controls the driver board using only 4 digital pins from the ESP32, where the parameters specify the pin numbers. Supports the following step type modes: + + * FULL_STEP_ONE_PHASE + * FULL_STEP_TWO_PHASE + * HALF_STEP + +❗Note: The ULN2003A chip does not support a short brake state. Calls to the `brake()` method, as well as setting the *endAction* parameter in the `move()` and `moveTo()` methods to **StepperControl::BRAKE** have no effect on the motor driver.

+ +> [!TIP] +> If you set the motor to move very slowly (e.g. 500ms per step) you will be able to track how the current is turned on and off for each phase of the motor coils depending on the *step mode* selected by observing the four LEDs (labeled *A, B, C, D*) built into the driver board. See also this [Last Minute Engineers Tutorial](https://lastminuteengineers.com/28byj48-stepper-motor-arduino-tutorial) for a detailed presentation of the ULN2003A and its use to drive a 28BYJ‑48 5‑Volt Stepper Motor. + + +[^2]: the ULN2003A is a passive chip - there is no VCC power connection between the driver board and the ESP32 + +--- + +[↩️](../Stepper.md) Back to the Stepper Motor Control page diff --git a/docs/StepperDrivers/Stepper_UNIPOLAR.md b/docs/StepperDrivers/Stepper_UNIPOLAR.md new file mode 100644 index 0000000..8c47dd9 --- /dev/null +++ b/docs/StepperDrivers/Stepper_UNIPOLAR.md @@ -0,0 +1,73 @@ +# Stepper_UNIPOLAR + +This class provides a generic driver for use with any center-tapped unipolar stepper motor. Requires the use of a driver board that can convert the low-voltage/low-current digital signals from 4 pins on the ESP32 to higher-voltage/higher-current outputs suitable for direct connection to the two phases (*A* and *B*) of each coil (*1* and *2*) in the stepper motor. + +The **Stepper_UNIPOLAR** class includes the following constructor: + * `Stepper_UNIPOLAR(int coil1A, int coil1B, int coil2A, int coil2B)` + * controls the driver board using 4 digital pins from the ESP32, where the parameters specify the pin numbers + * the driver circuit should be connected and configured such that when any of ESP32 pins specified above are set to are HIGH, current flows through the corresponding coil/phase. Similarly, when a pin is set LOW, the driver circuit should stop the flow of current through the corresponding coil/phase. + * supported modes are as follows: + + * FULL_STEP_ONE_PHASE + * FULL_STEP_TWO_PHASE + * HALF_STEP + +❗Note: This class does not support a short brake state. Calls to the `brake()` method, as well as setting the *endAction* parameter in the `move()` and `moveTo()` methods to **StepperControl::BRAKE** have no effect on the motor driver.

+ +> [!WARNING] +> **Note the order of the constructor parameters!** The first two parameters specify the ESP32 pins that control the current flowing through phases *A* and *B* of ***Coil 1***; the second two parameters are for phases *A* and *B* of ***Coil 2***. + +It does *not* matter which coil is defined as *1* or *2*, nor which side is called *A* or *B*, as long as the first two parameters are for one of the coils and the second two are for the other coil. You'll know if you mis-specified the order of the pins because the motor will vibrate back and forth instead of turning clockwise or counterclockwise. + +## Technical Details + +The patterns by which this class sets the specified pins HIGH and LOW depend on the *step mode* chosen as follows: + +#### FULL_STEP_ONE_PHASE + +* 4-step cycles where in each step current flows only through **one** phase of **one** of the coils + + + + + + + + +
Phase APhase B
Coil 1Coil 2Coil 1Coil 2
Step 1HIGH---
Step 2-HIGH--
Step 3--HIGH-
Step 4---HIGH
+
+ +#### FULL_STEP_TWO_PHASE + +* 4-step cycles where in each step current flows through **one** phase of **each** of the coils + + + + + + + + +
Phase APhase B
Coil 1Coil 2Coil 1Coil 2
Step 1HIGHHIGH--
Step 2-HIGHHIGH-
Step 3--HIGHHIGH
Step 4HIGH--HIGH
+
+ +#### HALF_STEP + +* 8-step cycles formed by interleaving the 4 steps of the FULL_STEP_ONE_PHASE mode with the 4 steps of the FULL_STEP_TWO_PHASE mode + + + + + + + + + + + + +
Phase APhase B
Coil 1Coil 2Coil 1Coil 2
Step 1HIGH---
Step 2HIGHHIGH--
Step 3-HIGH--
Step 4-HIGHHIGH-
Step 5--HIGH-
Step 6--HIGHHIGH
Step 7---HIGH
Step 8HIGH--HIGH
+ +--- + +[↩️](../Stepper.md) Back to the Stepper Motor Control page diff --git a/docs/Tutorials.md b/docs/Tutorials.md index 9b38147..d92e8ce 100644 --- a/docs/Tutorials.md +++ b/docs/Tutorials.md @@ -1,6 +1,6 @@ # HomeSpan Tutorials -The HomeSpan library includes 16 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! +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. @@ -133,7 +133,7 @@ Demonstrates how to create Custom Services and Custom Characteristics in HomeSpa Demonstrates how to implement a fully programmable Light Accessory Hub that allows the user to *dynamically* add/delete up to 12 Light Accessories directly through a device-hosted *web interface* or via HomeSpan's *command-line inteface*. Each light can be configured as dimmable/non-dimmable with either no color control, full RGB color control, or color-temperature control. Builds upon many of the techniques used in [Example 20](../examples/20-AdvancedTechniques) ### [RemoteSensors](../examples/Other%20Examples/RemoteSensors) -Demonstrates how *SpanPoint* can be used to transmit messages from battery-powered Remote Devices running light-weight sketches that measure the local temperature, to a wall-powered Main Device running a full HomeSpan sketch implementing Temperature Sensor Accessories. See [SpanPoint: Point-to-Point Communication between ESP32 Devices](NOW.md) for full details regarding the *SpanPoint* class and all of its methods. +Demonstrates how *SpanPoint* can be used to transmit messages from battery-powered Remote Devices running light-weight sketches that measure the local temperature, to a wall-powered Main Device running a full HomeSpan sketch implementing Temperature Sensor Accessories. See [SpanPoint: Point-to-Point Communication between ESP32 Devices](NOW.md) for full details regarding the *SpanPoint* class and all of its methods ### [FadingLED](../examples/Other%20Examples/FadingLED) Demonstrates how the *LedPin* class can use the ESP32's built-in fading control to automatically fade an LED from from one level of brightness to another over a specified period of time. See the [LedPin](PWM.md#pulse-width-modulation-pwm) page for full details @@ -141,6 +141,12 @@ Demonstrates how the *LedPin* class can use the ESP32's built-in fading control ### [MotorizedWindowShade](../examples/Other%20Examples/MotorizedWindowShade) Demonstrates how to use the *StepperControl* class to operate a stepper motor. Implements a motorized window shade based on [Example 13](../examples/13-TargetStates) above. See the [Stepper Motor Control](Stepper.md) page for full details +### [CustomNVSPartition](../examples/Other%20Examples/CustomNVSPartition) +Demonstrates how to create a Custom Partition Scheme for your sketch by adding a *partitions.csv* file to your sketch folder. Can be used to expand the size of the non-volatile-storage (NVS) partition, which may be needed when creating a HomeSpan device with many Accessories whose Characteristics you want to save in NVS + +### [ExternalReference](../examples/Other%20Examples/ExternalReference) +Demonstrates how to access Characteristics of Services from outside those Services, such as from within the main Arduino `loop()`. In this sketch we re-create the two LEDs in Example 5 with an added function in the main Arduino `loop()` that checks if both LEDs are on at the same time, and if so, they are automatically turned off + --- [↩️](../README.md) Back to the Welcome page diff --git a/examples/06-DimmableLED/06-DimmableLED.ino b/examples/06-DimmableLED/06-DimmableLED.ino index 804b116..edeba4b 100644 --- a/examples/06-DimmableLED/06-DimmableLED.ino +++ b/examples/06-DimmableLED/06-DimmableLED.ino @@ -50,12 +50,11 @@ void setup() { // As usual, all previous comments have been deleted and only new changes from the previous example are shown. // NOTE: The Arduino/ESP32 code base does not include the function analogWrite() which is typically used to create a PWM - // output to drive the brightness of an LED. The ESP32 code base itself includes a set of functions to create PWM output - // and the ESP32 chip has built-in PWM functionality specifically for this purpose. There are numerous libraries - // you can download that mimics or reproduces analogWrite() in some form or another. HomeSpan conveniently comes with - // its own version of a wrapper around the ESP32 PWM classes that make it very easy to define LED pins, and set the - // PWM level (or duty cycle) from 0-100%. These functions are encapsualted in the LedPin class, as defined in - // extras/PwmPin.h. We will include this file in our updated DEV_LED.h for use with DEV_DimmableLED. + // output to drive the brightness of an LED. Instead, the ESP32 code base itself includes a set of functions to create PWM output + // and the ESP32 chip has built-in PWM functionality specifically for this purpose. + + // HomeSpan wraps all of this PWM functionality into a single integrated class called LedPin, making it very easy to define + // dimmable LED pins and set the PWM level (i.e. duty cycle) from 0-100%. Use of this LedPin class is shown in DEV_DimmableLED. Serial.begin(115200); diff --git a/examples/06-DimmableLED/DEV_LED.h b/examples/06-DimmableLED/DEV_LED.h index d9445e9..8fc95f0 100644 --- a/examples/06-DimmableLED/DEV_LED.h +++ b/examples/06-DimmableLED/DEV_LED.h @@ -3,8 +3,6 @@ // DEVICE-SPECIFIC LED SERVICES // //////////////////////////////////// -#include "extras/PwmPin.h" // NEW! Include this HomeSpan "extra" to create LED-compatible PWM signals on one or more pins - struct DEV_LED : Service::LightBulb { // ON/OFF LED int ledPin; // pin number defined for this LED diff --git a/examples/07-AccessoryNames/07-AccessoryNames.ino b/examples/07-AccessoryNames/07-AccessoryNames.ino index dc7b82c..3830d46 100644 --- a/examples/07-AccessoryNames/07-AccessoryNames.ino +++ b/examples/07-AccessoryNames/07-AccessoryNames.ino @@ -54,8 +54,8 @@ void setup() { // Rather, the default name of the first Accessory Tile will always be shown by the Home App as the name specified in // homeSpan.begin() regardless of whether or not the Name Characteristic has been added to the Accessory Information Service. - // Below is a replay of Example 6 showing how the Name Characteristic can be used to change the default names of the second, - // but not the first, Accessory Tile. + // Below is a replay of Example 6 showing how the Name Characteristic can be used to change the default names of the second + // and third, but not the first, Accessory Tile. Serial.begin(115200); @@ -77,6 +77,14 @@ void setup() { new DEV_DimmableLED(17); + new SpanAccessory(); + + new Service::AccessoryInformation(); + new Characteristic::Identify(); + new Characteristic::Name(u8"Special chars ÄÖÜß"); // Use UTF-8 coded string for non-ASCII characters + + new DEV_DimmableLED(18); + } // end of setup() ////////////////////////////////////// diff --git a/examples/07-AccessoryNames/DEV_LED.h b/examples/07-AccessoryNames/DEV_LED.h index d9445e9..8fc95f0 100644 --- a/examples/07-AccessoryNames/DEV_LED.h +++ b/examples/07-AccessoryNames/DEV_LED.h @@ -3,8 +3,6 @@ // DEVICE-SPECIFIC LED SERVICES // //////////////////////////////////// -#include "extras/PwmPin.h" // NEW! Include this HomeSpan "extra" to create LED-compatible PWM signals on one or more pins - struct DEV_LED : Service::LightBulb { // ON/OFF LED int ledPin; // pin number defined for this LED diff --git a/examples/08-Bridges/DEV_LED.h b/examples/08-Bridges/DEV_LED.h index 36c05de..55b7ce4 100644 --- a/examples/08-Bridges/DEV_LED.h +++ b/examples/08-Bridges/DEV_LED.h @@ -3,8 +3,6 @@ // DEVICE-SPECIFIC LED SERVICES // //////////////////////////////////// -#include "extras/PwmPin.h" // allows PWM control of LED brightness - struct DEV_LED : Service::LightBulb { // ON/OFF LED int ledPin; // pin number defined for this LED diff --git a/examples/09-MessageLogging/DEV_LED.h b/examples/09-MessageLogging/DEV_LED.h index 94726e8..5e9cb8a 100644 --- a/examples/09-MessageLogging/DEV_LED.h +++ b/examples/09-MessageLogging/DEV_LED.h @@ -3,8 +3,6 @@ // DEVICE-SPECIFIC LED SERVICES // //////////////////////////////////// -#include "extras/PwmPin.h" // allows PWM control of LED brightness - struct DEV_LED : Service::LightBulb { // ON/OFF LED int ledPin; // pin number defined for this LED diff --git a/examples/10-RGB_LED/DEV_LED.h b/examples/10-RGB_LED/DEV_LED.h index 480f3ce..8a3c10a 100644 --- a/examples/10-RGB_LED/DEV_LED.h +++ b/examples/10-RGB_LED/DEV_LED.h @@ -3,10 +3,6 @@ // DEVICE-SPECIFIC LED SERVICES // //////////////////////////////////// -#include "extras/PwmPin.h" // library of various PWM functions - -//////////////////////////////////// - struct DEV_LED : Service::LightBulb { // ON/OFF LED int ledPin; // pin number defined for this LED diff --git a/examples/11-ServiceNames/11-ServiceNames.ino b/examples/11-ServiceNames/11-ServiceNames.ino index 9547c02..c529843 100644 --- a/examples/11-ServiceNames/11-ServiceNames.ino +++ b/examples/11-ServiceNames/11-ServiceNames.ino @@ -25,33 +25,47 @@ * ********************************************************************************/ -//////////////////////////////////////////////////////////// -// // -// HomeSpan: A HomeKit implementation for the ESP32 // -// ------------------------------------------------ // -// // -// Example 11: Service Names: // -// * setting the names of individual Services // -// * changing the icons in a bridge Accessory // -// // -//////////////////////////////////////////////////////////// +//////////////////////////////////////////////////////////////// +// // +// HomeSpan: A HomeKit implementation for the ESP32 // +// ------------------------------------------------ // +// // +// Example 11: Service Names: // +// * setting the names of individual Services // +// * "changing" the icons in a bridge Accessory // +// // +//////////////////////////////////////////////////////////////// #include "HomeSpan.h" + // INITIAL NOTE: Apple is constantly updating how the Home App Icons are chosen and how/if/where/when the Names for + // Accessories and Services are displayed. This example has been tested and verified as of iOS 17.2.1. + void setup() { // As described in previous examples, when pairing a device the Home App will choose default names for each // Accessory Tile, unless you override those default names with your own names by adding a Name Characteristic // to the Accessory Information Service for each Accessory (except the first, which is typically the Bridge Accessory). - // The same process holds true for the names of the Services in an Accessory with multiple Services, such as a Ceiling Fan with a Light. - // When pairing, the Home App will choose default names for each Service (such as Fan, Fan 2, Light, Light 2) depending on the types - // of Services included. Similar to the names of Accessory Tiles, you can change the names of individual Services when prompted - // during the pairing process, or at any time after pairing from within the appropriate settings pages in the Home App. More importantly, - // you can override the default Service names generated by the Home App by simply adding the Name Characteristic to any Service. + // The same process holds true for the names of the Services in an Accessory with multiple Services: if a Service is not named, + // the Home App will generate one. You can of course change the names of individual Services when prompted + // during the pairing process, or at any time after pairing from within the appropriate settings pages in the Home App. + + // But more importantly, you can name Services in your sketch so that those name show up when pairing, saving you the need to + // rename them from the settings pages in the Home App. - // However, note that Service names (whether or not overridden) only appear in the Home App if there is a chance of ambiguity, - // such as a Accessory with two Services of the same type. But even if a Service name does not appear in the Home App, + // Whereas we previously used the *Name* Characteristic to provide names for Accessory Tiles, we use the *ConfiguredName* Characteristic + // to provide names for individual Services within each Accessory. + + // One important distinction between Name and ConfigureName is that Name is only used by the Home App during pairing. After that, + // any changes you make to the name of an Accessory Tile from within the Home App are never communicated back to HomeSpan, and any changes + // you might make to those names in your sketch will not be reflected in the Home App unless you unpair and re-pair the device. In contrast, + // ConfiguredName works like any other Characteristic: changes made to ConfiguredName from within a sketch are proporgated to the Home App, + // and any edits you make to a Service's name in the Home App trigger a corresponding call to update() in HomeSpan so HomeSpan and the Home App + // are always in sync with regard to the names of any Services that includes the ConfiguredName Characteristic. + + // NOTE: Service names (whether those generated by the Home App or specified via the ConfiguredName Characteristic) are only displayed on the + // control screen of an Accessory Tile if there are two more more Services of the same type. But even if a Service name does not appear in the Home App, // it will still be used by Siri to control a specific Service within an Accessory by voice. // In the example below we create 5 different functional Accessories, each illustrating how names, as well as icons, are chosen by the Home App @@ -62,103 +76,92 @@ void setup() { homeSpan.begin(Category::Bridges,"HomeSpan Bridge"); - // Our first Accessory is the "Bridge" Accessory + // Our initial Accessory is therefore the "Bridge" Accessory new SpanAccessory(); new Service::AccessoryInformation(); new Characteristic::Identify(); - // Our second Accessory is a Ceiling Fan with a single Light. There are three things to note: - // - // * when pairing, the Home App will generate default names of "Light" and "Fan" for the two Services. - // However, these names are not displayed on the control screen of the Accessory since there is no - // ambiguity between the Light and Fan controls - the Home App displays them differently - // - // * the icon used by the Home App for the Accessory Tile is a Lightbulb. Why does it choose this instead of a Fan icon? - // Recall from Example 3 that for Accessories with multiple Services, if there is any ambiguity of which icon to use, - // the Home App chooses based on the Category of the device. But since this device is configured as a Bridge, the - // Category provides no helpful information to the Home App. In such cases the Home App picks an icon for the - // Accessory Tile that matches the first functional Service in the Accessory, which in this instance in a LightBulb - // - // * when opening the control screen by clicking the Accessory Tile, the LightBulb control will appear on the left, and - // the Fan control will appear on the right + // Our first "functional" Accessory is a combination of a LightBulb, Outlet, and Switch. Note that when pairing, the Home App generates + // default names of "Light", "Outlet", and "Switch" for these three Services, though these names are NOT displayed on the control screen + // of the Accessory since there is only one type of each Service. Also note that the Home App selects a LightBulb icon for the Accessory Tile new SpanAccessory(); new Service::AccessoryInformation(); new Characteristic::Identify(); - new Characteristic::Name("Light with Fan"); // this sets the name of the Accessory Tile - new Service::LightBulb(); // the icon of the Accessory Tile will be a Lightbulb, since this is the first functional Service + new Characteristic::Name("Light First"); // this sets the name of the Accessory Tile + new Service::LightBulb(); // the icon of the Accessory Tile will be a Lightbulb, since this is the first functional Service new Characteristic::On(); - new Service::Fan(); - new Characteristic::Active(); - - // Our third Accessory is identical to the second, except we swapped the order of the Lightbulb and Fan Services. - // The result is that the Home App now displays the Accessory Tile with a Fan icon intead of a Lightbulb icon. - // Also, when opening the control screen by clicking on the Accessory Tile, the Fan control will now appear on the - // left, and the LightBulb control on the right. - - new SpanAccessory(); - new Service::AccessoryInformation(); - new Characteristic::Identify(); - new Characteristic::Name("Fan with Light"); // this sets the name of the Accessory Tile - new Service::Fan(); // the icon of the Accessory Tile will be a Fan, since this is the first functional Service - new Characteristic::Active(); - new Service::LightBulb(); + new Service::Outlet(); + new Characteristic::On(); + new Characteristic::OutletInUse(); + new Service::Switch(); new Characteristic::On(); - // Our fourth Accessory shows what happens if we implement two identical LightBulb Services (without any Fan Service). - // Since both Services are LightBulbs, the Home App sensibly picks a Lightbulb icon for the Accessory Tile. However, - // when you click the Accessory Tile and open the control screen, you'll note that the Home App now does display the names - // of the Service beneath each control. In this case the Home App uses the default names "Light 1" and "Light 2". The Home App - // presumably shows the names of each Service since the two controls are identical and there is otherwise no way of telling which - // control operates which light. - - new SpanAccessory(); + // Our second Accessory is similar to the first, but here we define the Switch Service first. Note that the Home App now selects + // a Switch icon for the Accessory Tile + + new SpanAccessory(); new Service::AccessoryInformation(); new Characteristic::Identify(); - new Characteristic::Name("Ceiling Lights"); // this sets the name of the Accessory Tile - new Service::LightBulb(); + new Characteristic::Name("Switch First"); // this sets the name of the Accessory Tile + new Service::Switch(); // the icon of the Accessory Tile will be a Switch, since this is the first functional Service new Characteristic::On(); - new Service::LightBulb(); + new Service::Outlet(); + new Characteristic::On(); + new Characteristic::OutletInUse(); + new Service::LightBulb(); new Characteristic::On(); - // Our fifth Accessory combines a single Fan Service with two identical LightBulb Services. Since the first functional Service implemented - // is a Fan, the Home App will pick a Fan icon for the Accessory Tile. Also, since we added Name Characteristics to two LightBulb - // Services, their default names generated by the Home App ("Light 1" and "Light 2") will be changed to the names specified. Finally, - // note that the Home App displays a more compact form of controls on the control screen since there are three Services. The arrangement - // and style of the controls will depend on what combination of Characteristics are implemented for each Service. - - new SpanAccessory(); + // Our third Accessory is similar to the second, but here we define 2 Switches, 2 LightBulbs, but still only 1 Outlet. This time, during pairing + // the Home App generates default names of Switch, Switch 2, Light, Light 2, and Outlet. Importantly, note that on the control screen for + // this Accessory, the Home App now displays the names of the Switches ("Switch" and "Switch 2") as well as the LightBulbs ("Light" and "Light 2") + // under each corresponding control, but it does NOT display the name "Outlet" under the Outlet control since there is only one Outlet Service + + new SpanAccessory(); new Service::AccessoryInformation(); new Characteristic::Identify(); - new Characteristic::Name("Fan with Lights"); // this sets the name of the Accessory Tile - new Service::Fan(); - new Characteristic::Active(); - new Service::LightBulb(); - new Characteristic::Name("Main Light"); // this changes the default name of this LightBulb Service from "Light 1" to "Main Light" + new Characteristic::Name("Two Switches"); // this sets the name of the Accessory Tile + new Service::Switch(); // the icon of the Accessory Tile will be a Switch, since this is the first functional Service + new Characteristic::On(); + new Service::Switch(); + new Characteristic::On(); + new Service::Outlet(); new Characteristic::On(); - new Service::LightBulb(); - new Characteristic::Name("Night Light"); // this changes the default name of this LightBulb Service from "Light 2" to "Night Light" + new Characteristic::OutletInUse(); + new Service::LightBulb(); + new Characteristic::On(); + new Service::LightBulb(); new Characteristic::On(); - // Our sixth Accessory is similar to the fifth, except we added some more features to some of the Services. Note how this changes - // the layout of the controls on the control screen. + // Our fourth and final Accessory is the same as the third, but this time we use the ConfiguredName Characteristic to define a name for each Service. + // When pairing, you should see the Home App now uses the names below instead of generating default names as it did in the other examples. You + // should also see these names displayed under each control on the control screen for the Accessory, with the exception of the Outlet Service. + // Though we did provide a name for the Outlet, since there is only one Outlet Service in this Accessory, the Home App does not display its name. + // Howevever, if from the settings screen for this Accessory you further navigate to the "Accessories" page, you will indeed see the names for each + // Service exactly as specified below, including the Outlet name "Aux Power" - new SpanAccessory(); + new SpanAccessory(); new Service::AccessoryInformation(); - new Characteristic::Identify(); - new Characteristic::Name("Multi-Function Fan"); - new Service::Fan(); - new Characteristic::Active(); - new Characteristic::RotationDirection(); // add a control to change the direcion of rotation - new Characteristic::RotationSpeed(0); // add a control to set the rotation speed - new Service::LightBulb(); - new Characteristic::Name("Main Light"); + new Characteristic::Identify(); + new Characteristic::Name("Central Control"); // this sets the name of the Accessory Tile + new Service::Switch(); // the icon of the Accessory Tile will be a Switch, since this is the first functional Service new Characteristic::On(); - new Characteristic::Brightness(100); // make this light dimmable (with intitial value set to 100%) - new Service::LightBulb(); - new Characteristic::Name("Night Light"); // don't add anything new to this light + new Characteristic::ConfiguredName("High Voltage"); // this sets the name of the first Switch Service + new Service::Switch(); + new Characteristic::On(); + new Characteristic::ConfiguredName("Low Voltage"); // this sets the name of the second Switch Service + new Service::Outlet(); new Characteristic::On(); + new Characteristic::OutletInUse(); + new Characteristic::ConfiguredName("Aux Power"); // this sets the name of the Outlet Service + new Service::LightBulb(); + new Characteristic::On(); + new Characteristic::ConfiguredName("Main Lights"); // this sets the name of the first LightBulb Service + new Service::LightBulb(); + new Characteristic::On(); + new Characteristic::ConfiguredName("Accent Lights"); // this sets the name of the second LightBulb Service + } // end of setup() diff --git a/examples/13-TargetStates/DEV_DoorsWindows.h b/examples/13-TargetStates/DEV_DoorsWindows.h index a42fa6c..e3aa128 100644 --- a/examples/13-TargetStates/DEV_DoorsWindows.h +++ b/examples/13-TargetStates/DEV_DoorsWindows.h @@ -5,8 +5,8 @@ struct DEV_GarageDoor : Service::GarageDoorOpener { // A Garage Door Opener - SpanCharacteristic *current; // reference to the Current Door State Characteristic (specific to Garage Door Openers) - SpanCharacteristic *target; // reference to the Target 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) DEV_GarageDoor() : Service::GarageDoorOpener(){ // constructor() method @@ -118,8 +118,7 @@ struct DEV_WindowShade : Service::WindowCovering { // A motorized Window Sha // 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. HomeSpan will warn you if Position State is not defined (since it - // is technically required) but this works fine without it. + // at all given the way HomeKit uses current position. } // loop diff --git a/examples/15-RealPushButtons/DEV_LED.h b/examples/15-RealPushButtons/DEV_LED.h index 93a3657..b1d750d 100644 --- a/examples/15-RealPushButtons/DEV_LED.h +++ b/examples/15-RealPushButtons/DEV_LED.h @@ -3,10 +3,6 @@ // DEVICE-SPECIFIC LED SERVICES // //////////////////////////////////// -#include "extras/PwmPin.h" // library of various PWM functions - -//////////////////////////////////// - struct DEV_DimmableLED : Service::LightBulb { // Dimmable LED // This version of the Dimmable LED Service is similar to the one last used in Example 11, but now includes support for 3 physical PushButtons diff --git a/examples/17-LinkedServices/17-LinkedServices.ino b/examples/17-LinkedServices/17-LinkedServices.ino index 78555d7..c9bc469 100644 --- a/examples/17-LinkedServices/17-LinkedServices.ino +++ b/examples/17-LinkedServices/17-LinkedServices.ino @@ -35,12 +35,6 @@ // // //////////////////////////////////////////////////////////// -// WARNING: THIS EXAMPLE STOPPED WORKING CORRECTLY SOMEWHERE AROUND THE IOS 15.2 OR IOS 15.3 UPDATE -// AND DOES NOT WORK AS OF IOS 15.4.1 -// -// THE PROBLEM APPEARS TO BE IN THE RENDERING OF INDIVIDUAL VALVES IN THE HOME APP INTERFACE. THEY -// APPEAR IN THE EVE HOMEKIT APPLICATION, BUT NOT APPLE'S HOME APP. - #include "HomeSpan.h" // HAP normally treats multiple Services created within the same Accessory as independent of one another. However, certain HAP Services are designed to represent a central point @@ -112,19 +106,19 @@ struct Shower : Service::Faucet { // this is our Shower structur SpanCharacteristic *active=new Characteristic::Active(); // our implementation only requires the Active Characteristic - Shower(int nHeads){ // this is the constructor for Shower. It takes a single argument that specifies the number of spray heads (WaterValves) - for(int i=0;iactive->getVal() && active->getVal() && !inUse->getVal()) // If the Shower is Active, and the Valve is Active, but InUse is NOT Active... - inUse->setVal(1); // ...set the InUse Characteristic to Active - else if(!shower->active->getVal() && inUse->getVal()) // Otherwise, if the Shower is NOT Active but InUse is Active... - inUse->setVal(0); // ...set the InUse Characteristic to NOT Active + if(shower->active->getVal() && active->getVal() && !inUse->getVal()) // If the Shower is Active, and the Valve is Active but NOT showing InUse... + inUse->setVal(1); // ...show Valve as InUse + else if(!shower->active->getVal() && inUse->getVal()) // Otherwise, if the Shower is NOT Active but Valve IS showing InUse... + inUse->setVal(0); // ...show Valve as NOT InUse } }; // WaterValve diff --git a/examples/18-SavingStatus/DEV_LED.h b/examples/18-SavingStatus/DEV_LED.h index 04839b6..7efa977 100644 --- a/examples/18-SavingStatus/DEV_LED.h +++ b/examples/18-SavingStatus/DEV_LED.h @@ -3,10 +3,6 @@ // DEVICE-SPECIFIC LED SERVICES // //////////////////////////////////// -#include "extras/PwmPin.h" // library of various PWM functions - -//////////////////////////////////// - struct DEV_DimmableLED : Service::LightBulb { // Dimmable LED // This version of the Dimmable LED Service includes a PushButton that can be used to turn on/off the LED. Status of both the diff --git a/examples/Other Examples/CustomNVSPartition/CustomNVSPartition.ino b/examples/Other Examples/CustomNVSPartition/CustomNVSPartition.ino new file mode 100644 index 0000000..598ae19 --- /dev/null +++ b/examples/Other Examples/CustomNVSPartition/CustomNVSPartition.ino @@ -0,0 +1,138 @@ +/********************************************************************************* + * MIT License + * + * Copyright (c) 2020-2023 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. + * + ********************************************************************************/ + +// This example demonstrates the use of a custom Partition Scheme file: "partitions.csv" + +// During compilation, if a file with this EXACT name is placed in the sketch folder, +// the esptool performing the compilation will use the partition scheme found +// in "partitions.csv" regardless of what partition scheme you selected in the Arduino IDE. + +// Note if you change the partition scheme it is highly recommended that you fully erase the flash +// upon your next compile/upload by enabling the "Erase All Flash" option from the Arduino IDE menu. +// NOTE: remember to turn OFF this option after you've successully uploaded a sketch with the new +// partition scheme, else you will continue to erase everything saved in the NVS every time you upload +// a new sketch (which is likely NOT what you want to occur). + +// The main reason for wanting to create your own partition scheme is to expand the NVS space. +// All of the pre-configured partition scheme you can select from the Arduino IDE provide +// for 504 records of NVS space. This is usuall sufficient for most HomeSpan projects, but if +// you have a LOT of Accessories (as per below) AND you are saving their states in NVS, you can +// use up all the NVS space. If this occurs, HomeSpan will warn you of low NVS space upon boot-up. + +// The custom partition scheme included in this sketch folder solves this problem by eliminating +// the SPIFFs partition (which is generally not used by HomeSpan) and using this portion of the flash +// to provide an NVS space with 3906 records --- more than enough for even the largest projects. + +// For reference, in addition to HomeSpan's internal use of NVS (about 32 records), saving a +// numerical Characteristic consumes one additional NVS record, and saving a string Characteristic (of +// less than 32 characters) consumes two NVS records. Also, the ESP32 WiFi stack consumes about 130 +// additional NVS records once initialized. As such, the sketch below requires: + +// 32 records (internal HomeSpan use) +// + 320 records (80 Accessories * 4 saved numerical Characterstics) +// + 160 records (80 Accessories * 2 records per saved string Characterstic) +// + 130 records (with WiFi initialized) +// ---------------------------------------- +// = 642 NVS records needed (which exceeds the normal 504 limit, unless a custom partition scheme is used) + +// Note that once HomeSpan is paired with HomeKit, additional NVS records will be consumed to store the +// pairing information for each verified HomeKit Controller. + +// Note also that when compiling under the Arduino IDE, the IDE reports the size of partition based on the +// Partition Scheme you selected in the IDE menu, even though that scheme is not actually used if you have your +// own "partition.csv" file, as in this example. This may lead the IDE to report an incorrect partition size. + +/////////////////////////////////////////////////////////////////////////////////////////// + +#include "HomeSpan.h" + +#define MAX_LIGHTS 80 // configure for 80 Light Accessories + +struct RGB_Light : Service::LightBulb { + + Characteristic::On power{0,true}; // save these 4 numerical Characteristics (4*80 = 320 NVS records) + Characteristic::Hue H{0,true}; + Characteristic::Saturation S{0,true}; + Characteristic::Brightness V{0,true}; + + int lightNumber; + + RGB_Light(int n) : Service::LightBulb(){ + + lightNumber=n; + LOG0("Configured RGB Light-%0d\n",lightNumber); + } + + boolean update(){ + + if(power.updated()) + LOG0("Light-%d: Power=%s",lightNumber,power.getNewVal()?"ON":"OFF"); + + if(H.updated()) + LOG0("Light-%d: Hue=%d",lightNumber,H.getNewVal()); + + if(S.updated()) + LOG0("Light-%d: Saturation=%d",lightNumber,S.getNewVal()); + + if(V.updated()) + LOG0("Light-%d: Brightness=%d",lightNumber,V.getNewVal()); + + return(false); + + } +}; + +void setup() { + + Serial.begin(115200); + + homeSpan.begin(Category::Lighting,"HomeSpan Max"); + + new SpanAccessory(); + new Service::AccessoryInformation(); + new Characteristic::Identify(); + + for(int i=1;i<=MAX_LIGHTS;i++){ + char c[60]; + sprintf(c,"Light-%02d",i); + + new SpanAccessory(); + new Service::AccessoryInformation(); + new Characteristic::Identify(); + new Characteristic::Name(c,true); // save this string Characteristic (2*80 = 160 NVS records) + + new RGB_Light(i); + } + +} + +////////////////////////////////////// + +void loop(){ + + homeSpan.poll(); +} diff --git a/examples/Other Examples/CustomNVSPartition/partitions.csv b/examples/Other Examples/CustomNVSPartition/partitions.csv new file mode 100644 index 0000000..0fffd77 --- /dev/null +++ b/examples/Other Examples/CustomNVSPartition/partitions.csv @@ -0,0 +1,14 @@ +# --- Custom Partition Table for HomeSpan --- +# +# Similar to min_spiffs, except that the 128K SPIFF block at the end +# is replaced by a 128K NVS block, and the initial 20K NVS block +# is no longer used. Note this table is designed for use with 4MB Flash. +# To use with 8MB Flash, increase app0 and app1 by 2048K to become 3968K each. +# To use with 16MB Flash, increase app0 and app1 by 6144K to become 8064K each +# +unused_nvs,data,nvs,,20K, +otadata,data,ota,,8K, +app0,app,ota_0,,1920K, +app1,app,ota_1,,1920K, +nvs,data,nvs,,128K, +coredump,data,coredump,,64K, \ No newline at end of file diff --git a/examples/Other Examples/ExternalReference/ExternalReference.ino b/examples/Other Examples/ExternalReference/ExternalReference.ino new file mode 100644 index 0000000..40455c6 --- /dev/null +++ b/examples/Other Examples/ExternalReference/ExternalReference.ino @@ -0,0 +1,119 @@ +/********************************************************************************* + * 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. + * + ********************************************************************************/ + +// Sometimes you need to access Characteristics from outside of the Service structure +// in which they were created so you can read and/or modify them in other parts of +// a sketch, such as from within the main Arduino loop(). + +// This sketch is basically the same as Tutorial Example 5, in which we created +// two working LEDs attached to pins 16, and 17. However, in this sketch we will +// create global pointers to the LED Services that we can then use in the main loop() to +// do something unique. + +#include "HomeSpan.h" + +////////////////////////////////////// + +// First we define our DEV_LED Service exactly the same as in Tutorial Example 5. +// This Service contains a single Characteristic named "power" of type Chacracteristic::On + +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()); + return(true); + } +}; + +////////////////////////////////////// + +// Next we create two pointers to the DEV_LED Service. These are created +// outside of any class or function so they are globally-scoped and can be +// accessed from anywhere else in this sketch. + +// Note that there are just POINTERS to DEV_LED objects. The objects themselves +// are not yet created. + +DEV_LED *led16; // pointer to a DEV_LED structure to be used below to reference a DEV_LED object assigned to pin 16 +DEV_LED *led17; // pointer to a DEV_LED structure to be used below to reference a DEV_LED object assigned to pin 17 + +////////////////////////////////////// + +void setup() { + + Serial.begin(115200); + + homeSpan.begin(Category::Lighting,"HomeSpan LED"); + + new SpanAccessory(); + new Service::AccessoryInformation(); + new Characteristic::Identify(); + led16=new DEV_LED(16); // this is the key step - we SAVE the pointer returned by 'new DEV_LED(16)' in the global variable led16 created above + + + new SpanAccessory(); + new Service::AccessoryInformation(); + new Characteristic::Identify(); + led17=new DEV_LED(17); // also save the pointer to the second LED object using the global variable led17 created above + +} + +////////////////////////////////////// + +void loop(){ + + homeSpan.poll(); + +// Because the pointers led16 and led17 were created in the global scope, they will still exist even after setup() is completed. +// This means we can use them to access the Characteristics within each of those Services. + +// Here we access the power Characteristic of both Services and check to see if they are BOTH on, and if so, +// we turn them both off and print a "power overload" message. + +// Note how you can use all the same methods, such as getVal() and setVal(), just as you would do in the Service itself. +// Caution: always use getVal(), not getNewVal(), which is only formally defined from within the Service update() method. + + if(led16->power->getVal() && led17->power->getVal()){ + Serial.printf("Power overload! Can't have both LED's on at the same time. Turn off both LEDs...\n"); + led16->power->setVal(false); + led17->power->setVal(false); + } + +} + +////////////////////////////////////// diff --git a/examples/Other Examples/FadingLED/FadingLED.ino b/examples/Other Examples/FadingLED/FadingLED.ino index 9ca5a81..ef890ad 100644 --- a/examples/Other Examples/FadingLED/FadingLED.ino +++ b/examples/Other Examples/FadingLED/FadingLED.ino @@ -40,7 +40,6 @@ // off. #include "HomeSpan.h" -#include "extras/PwmPin.h" // library of various PWM functions //////////////////////////////////// diff --git a/examples/Other Examples/MotorizedWindowShade/MotorizedWindowShade.ino b/examples/Other Examples/MotorizedWindowShade/MotorizedWindowShade.ino index 39314ff..f7830e6 100644 --- a/examples/Other Examples/MotorizedWindowShade/MotorizedWindowShade.ino +++ b/examples/Other Examples/MotorizedWindowShade/MotorizedWindowShade.ino @@ -40,8 +40,6 @@ // as well as for instructions on how you can easily extend StepperControl to create a custom driver for any board. #include "HomeSpan.h" -#include "extras/Stepper_TB6612.h" // this contains HomeSpan's StepperControl Class for the Adafruit TB6612 driver board -#include "extras/Stepper_A3967.h" // this contains HomeSpan's StepperControl Class for the Sparkfun A3967 driver board //////////////////////////////////// diff --git a/examples/Other Examples/Pixel/Pixel.ino b/examples/Other Examples/Pixel/Pixel.ino index 5723de4..30df9c7 100644 --- a/examples/Other Examples/Pixel/Pixel.ino +++ b/examples/Other Examples/Pixel/Pixel.ino @@ -61,7 +61,6 @@ #endif #include "HomeSpan.h" -#include "extras/Pixel.h" // include the HomeSpan Pixel class /////////////////////////////// @@ -72,9 +71,9 @@ struct NeoPixel_RGB : Service::LightBulb { // Addressable single-wire RGB L Characteristic::Saturation S{0,true}; Characteristic::Brightness V{100,true}; Pixel *pixel; - uint8_t nPixels; + int nPixels; - NeoPixel_RGB(uint8_t pin, uint8_t nPixels) : Service::LightBulb(){ + 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 @@ -106,9 +105,9 @@ struct NeoPixel_RGBW : Service::LightBulb { // Addressable single-wire RGBW Characteristic::Brightness V{100,true}; Characteristic::ColorTemperature T{140,true}; Pixel *pixel; - uint8_t nPixels; + int nPixels; - NeoPixel_RGBW(uint8_t pin, uint8_t nPixels) : Service::LightBulb(){ + 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 @@ -142,9 +141,9 @@ struct DotStar_RGB : Service::LightBulb { // Addressable two-wire RGB LED S Characteristic::Saturation S{0,true}; Characteristic::Brightness V{100,true}; Dot *pixel; - uint8_t nPixels; + int nPixels; - DotStar_RGB(uint8_t dataPin, uint8_t clockPin, uint8_t nPixels) : Service::LightBulb(){ + DotStar_RGB(uint8_t dataPin, uint8_t clockPin, 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 Dot(dataPin,clockPin); // creates Dot LED on specified pins diff --git a/examples/Other Examples/RemoteControl/RemoteControl.ino b/examples/Other Examples/RemoteControl/RemoteControl.ino index bc752ef..e7b356f 100644 --- a/examples/Other Examples/RemoteControl/RemoteControl.ino +++ b/examples/Other Examples/RemoteControl/RemoteControl.ino @@ -26,7 +26,6 @@ ********************************************************************************/ #include "HomeSpan.h" // include the HomeSpan library -#include "extras/RFControl.h" // include RF Control Library void setup() { diff --git a/examples/Other Examples/RemoteSensors/RemoteDevice/RemoteDevice.ino b/examples/Other Examples/RemoteSensors/RemoteDevice/RemoteDevice.ino index 9859362..7dba05b 100644 --- a/examples/Other Examples/RemoteSensors/RemoteDevice/RemoteDevice.ino +++ b/examples/Other Examples/RemoteSensors/RemoteDevice/RemoteDevice.ino @@ -57,7 +57,8 @@ void setup() { Serial.begin(115200); delay(1000); - Serial.printf("Starting\n\n"); + Serial.printf("\n\nThis is a REMOTE Device with MAC Address = %s\n",WiFi.macAddress().c_str()); + Serial.printf("NOTE: This MAC Address must be entered into the corresponding SpanPoint() call of the MAIN Device.\n\n"); // In the line below, replace the MAC Address with that of your MAIN HOMESPAN DEVICE diff --git a/examples/Other Examples/ServoControl/DEV_DoorsWindows.h b/examples/Other Examples/ServoControl/DEV_DoorsWindows.h index bc82648..4bfe3a7 100644 --- a/examples/Other Examples/ServoControl/DEV_DoorsWindows.h +++ b/examples/Other Examples/ServoControl/DEV_DoorsWindows.h @@ -3,10 +3,6 @@ // DEVICE-SPECIFIC LED SERVICES // //////////////////////////////////// -#include - -//////////////////////////////////// - struct DEV_WindowShade : Service::WindowCovering { // A motorized Window Shade with Hold Feature SpanCharacteristic *current; // reference to a "generic" Current Position Characteristic (used by a variety of different Service) diff --git a/library.properties b/library.properties index 1209647..31f678e 100644 --- a/library.properties +++ b/library.properties @@ -1,5 +1,5 @@ name=HomeSpan -version=1.8.0 +version=1.9.0 author=Gregg maintainer=Gregg sentence=A robust and extremely easy-to-use HomeKit implementation for the Espressif ESP32 running on the Arduino IDE. diff --git a/src/Characteristics.h b/src/Characteristics.h index 65aac71..c5703de 100644 --- a/src/Characteristics.h +++ b/src/Characteristics.h @@ -1,7 +1,7 @@ /********************************************************************************* * MIT License * - * Copyright (c) 2020-2023 Gregg E. Berman + * Copyright (c) 2020-2024 Gregg E. Berman * * https://github.com/HomeSpan/HomeSpan * diff --git a/src/FeatherPins.h b/src/FeatherPins.h index 8998a17..e513d94 100644 --- a/src/FeatherPins.h +++ b/src/FeatherPins.h @@ -1,7 +1,7 @@ /********************************************************************************* * MIT License * - * Copyright (c) 2020-2023 Gregg E. Berman + * Copyright (c) 2020-2024 Gregg E. Berman * * https://github.com/HomeSpan/HomeSpan * @@ -61,7 +61,7 @@ #elif defined(ARDUINO_ESP32S3_DEV) enum { - F13=5,F12=6,F27=7,F15=16,F32=17,F14=18,F16=37,F17=36,F21=35, // Digital Only (9 pins) + F13=5,F12=6,F27=7,F15=16,F32=17,F14=18,F16=37,F17=36,F21=38, // Digital Only (9 pins) F26=1,F25=2,F34=20,F39=19,F36=15,F4=4, // A0-A5 F22=9,F23=8, // I2C SCL/SDA F5=12,F18=11,F19=13,F33=10, // SPI SCK/SDO/SDI/CS diff --git a/src/HAP.cpp b/src/HAP.cpp index 39bed60..4f08076 100644 --- a/src/HAP.cpp +++ b/src/HAP.cpp @@ -1,7 +1,7 @@ /********************************************************************************* * MIT License * - * Copyright (c) 2020-2023 Gregg E. Berman + * Copyright (c) 2020-2024 Gregg E. Berman * * https://github.com/HomeSpan/HomeSpan * @@ -36,7 +36,7 @@ void HAPClient::init(){ - size_t len; // not used but required to read blobs from NVS + 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 @@ -48,39 +48,22 @@ void HAPClient::init(){ homeSpan.spanOTA.setPassword(DEFAULT_OTA_PASSWORD); // ...use default password } } + + 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.pairingCodeCommand)){ // load verification setup code if provided - homeSpan.processSerialCommand(homeSpan.pairingCodeCommand); // if load failed due to invalid code, the logic below still runs and will pick up previous code or use the default one - } - - struct { // temporary structure to hold SRP verification code and salt stored in NVS - uint8_t salt[16]; - uint8_t verifyCode[384]; - } verifyData; - - if(!nvs_get_blob(srpNVS,"VERIFYDATA",NULL,&len)){ // if found verification code data in NVS - nvs_get_blob(srpNVS,"VERIFYDATA",&verifyData,&len); // retrieve data - srp.loadVerifyCode(verifyData.verifyCode,verifyData.salt); // load verification code and salt into SRP structure - } else { - LOG0("Generating SRP verification data for default Setup Code: %.3s-%.2s-%.3s\n",homeSpan.defaultSetupCode,homeSpan.defaultSetupCode+3,homeSpan.defaultSetupCode+5); - srp.createVerifyCode(homeSpan.defaultSetupCode,verifyData.verifyCode,verifyData.salt); // create verification code from default Setup Code and random salt - nvs_set_blob(srpNVS,"VERIFYDATA",&verifyData,sizeof(verifyData)); // update data - nvs_commit(srpNVS); // commit to NVS - LOG0("Setup Payload for Optional QR Code: %s\n\n",homeSpan.qrCode.get(atoi(homeSpan.defaultSetupCode),homeSpan.qrID,atoi(homeSpan.category))); - } - - if(!strlen(homeSpan.qrID)){ // 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)){ // 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 } else { - sprintf(homeSpan.qrID,"%s",DEFAULT_QR_ID); // use default + sprintf(homeSpan.qrID,"%s",DEFAULT_QR_ID); // use default } } - 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(hapNVS,"ACCESSORY",NULL,&len)){ // if found long-term Accessory data in NVS + nvs_get_blob(hapNVS,"ACCESSORY",&accessory,&len); // retrieve data } else { - LOG0("Generating new random Accessory ID and Long-Term Ed25519 Signature Keys...\n"); + LOG0("Generating new random Accessory ID and Long-Term Ed25519 Signature Keys...\n\n"); uint8_t buf[6]; char cBuf[18]; @@ -91,21 +74,19 @@ 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(hapNVS,"ACCESSORY",&accessory,sizeof(accessory)); // update data + nvs_commit(hapNVS); // commit to NVS } - if(!nvs_get_blob(hapNVS,"CONTROLLERS",NULL,&len)){ // if found long-term Controller Pairings data from NVS - nvs_get_blob(hapNVS,"CONTROLLERS",controllers,&len); // retrieve data - } else { - LOG0("Initializing storage for Paired Controllers data...\n\n"); - - HAPClient::removeControllers(); // clear all Controller data - - nvs_set_blob(hapNVS,"CONTROLLERS",controllers,sizeof(controllers)); // update data - nvs_commit(hapNVS); // commit to NVS + if(!nvs_get_blob(hapNVS,"CONTROLLERS",NULL,&len)){ // if found long-term Controller Pairings data from NVS + TempBuffer tBuf(len/sizeof(Controller)); + nvs_get_blob(hapNVS,"CONTROLLERS",tBuf,&len); // retrieve data + for(int i=0;iMAX_HTTP){ // exceeded maximum number of bytes allowed + badRequestError(); + LOG0("\n*** ERROR: HTTP message of %d bytes exceeds maximum allowed (%d)\n\n",messageSize,MAX_HTTP); + return; + } + + TempBuffer httpBuf(messageSize+1); // leave room for null character added below - if(cPair){ // expecting encrypted message + if(cPair){ // expecting encrypted message LOG2("<<<< #### "); LOG2(client.remoteIP()); LOG2(" #### <<<<\n"); - nBytes=receiveEncrypted(); // decrypt and return number of bytes + nBytes=receiveEncrypted(httpBuf,messageSize); // decrypt and return number of bytes read - if(!nBytes){ // decryption failed (error message already printed in function) + if(!nBytes){ // decryption failed (error message already printed in function) badRequestError(); return; } - } else { // expecting plaintext message + } else { // expecting plaintext message LOG2("<<<<<<<<< "); LOG2(client.remoteIP()); LOG2(" <<<<<<<<<\n"); - nBytes=client.read(httpBuf,MAX_HTTP+1); // read all available bytes up to maximum allowed+1 - - if(nBytes>MAX_HTTP){ // exceeded maximum number of bytes allowed + nBytes=client.read(httpBuf,messageSize); // read expected number of bytes + + if(nBytes!=messageSize || client.available()!=0){ badRequestError(); - LOG0("\n*** ERROR: Exceeded maximum HTTP message length\n\n"); + LOG0("\n*** ERROR: HTTP message not read correctly. Expected %d bytes, read %d bytes, %d bytes remaining\n\n",messageSize,nBytes,client.available()); return; } - + } // encrypted/plaintext - httpBuf[nBytes]='\0'; // add null character to enable string functions + httpBuf[nBytes]='\0'; // add null character to enable string functions - char *body=(char *)httpBuf; // char pointer to start of HTTP Body - char *p; // char pointer used for searches - - if(!(p=strstr((char *)httpBuf,"\r\n\r\n"))){ + char *body=(char *)httpBuf.get(); // char pointer to start of HTTP Body + char *p; // char pointer used for searches + + if(!(p=strstr((char *)httpBuf.get(),"\r\n\r\n"))){ badRequestError(); LOG0("\n*** ERROR: Malformed HTTP request (can't find blank line indicating end of BODY)\n\n"); return; @@ -209,115 +183,72 @@ void HAPClient::processRequest(){ LOG2(body); LOG2("\n------------ END BODY! ------------\n"); - if(!strncmp(body,"POST ",5)){ // this is a POST request + if(!strncmp(body,"POST ",5)){ // this is a POST request if(cLen==0){ badRequestError(); LOG0("\n*** ERROR: HTTP POST request contains no Content\n\n"); - return; } - if(!strncmp(body,"POST /pair-setup ",17) && // POST PAIR-SETUP - strstr(body,"Content-Type: application/pairing+tlv8") && // check that content is TLV8 - tlv8.unpack(content,cLen)){ // read TLV content - tlv8.print(2); // print TLV records in form "TAG(INT) LENGTH(INT) VALUES(HEX)" - LOG2("------------ END TLVS! ------------\n"); - - postPairSetupURL(); // process URL - return; - } + else if(!strncmp(body,"POST /pair-setup ",17) && strstr(body,"Content-Type: application/pairing+tlv8")) // POST PAIR-SETUP + postPairSetupURL(content,cLen); - if(!strncmp(body,"POST /pair-verify ",18) && // POST PAIR-VERIFY - strstr(body,"Content-Type: application/pairing+tlv8") && // check that content is TLV8 - tlv8.unpack(content,cLen)){ // read TLV content - tlv8.print(2); // print TLV records in form "TAG(INT) LENGTH(INT) VALUES(HEX)" - LOG2("------------ END TLVS! ------------\n"); - - postPairVerifyURL(); // process URL - return; - } + else if(!strncmp(body,"POST /pair-verify ",18) && strstr(body,"Content-Type: application/pairing+tlv8")) // POST PAIR-VERIFY + postPairVerifyURL(content,cLen); - if(!strncmp(body,"POST /pairings ",15) && // POST PAIRINGS - strstr(body,"Content-Type: application/pairing+tlv8") && // check that content is TLV8 - tlv8.unpack(content,cLen)){ // read TLV content - tlv8.print(2); // print TLV records in form "TAG(INT) LENGTH(INT) VALUES(HEX)" - LOG2("------------ END TLVS! ------------\n"); - - postPairingsURL(); // process URL - return; - } + else if(!strncmp(body,"POST /pairings ",15) && strstr(body,"Content-Type: application/pairing+tlv8")) // POST PAIRINGS + postPairingsURL(content,cLen); - if(!strncmp(body,"POST /pairings ",15) && // POST PAIRINGS - strstr(body,"Content-Type: application/pairing+tlv8") && // check that content is TLV8 - tlv8.unpack(content,cLen)){ // read TLV content - tlv8.print(2); // print TLV records in form "TAG(INT) LENGTH(INT) VALUES(HEX)" - LOG2("------------ END TLVS! ------------\n"); - - postPairingsURL(); // process URL - return; + else { + notFoundError(); + LOG0("\n*** ERROR: Bad POST request - URL not found\n\n"); } - - notFoundError(); - LOG0("\n*** ERROR: Bad POST request - URL not found\n\n"); - return; - + + return; } // POST request - if(!strncmp(body,"PUT ",4)){ // this is a PUT request + if(!strncmp(body,"PUT ",4)){ // this is a PUT request if(cLen==0){ badRequestError(); LOG0("\n*** ERROR: HTTP PUT request contains no Content\n\n"); - return; + return; } + + LOG2((char *)content); + LOG2("\n------------ END JSON! ------------\n"); - if(!strncmp(body,"PUT /characteristics ",21) && // PUT CHARACTERISTICS - strstr(body,"Content-Type: application/hap+json")){ // check that content is JSON + if(!strncmp(body,"PUT /characteristics ",21) && strstr(body,"Content-Type: application/hap+json")) // PUT CHARACTERISTICS + putCharacteristicsURL((char *)content); - content[cLen]='\0'; // add a trailing null on end of JSON - LOG2((char *)content); // print JSON - LOG2("\n------------ END JSON! ------------\n"); - - putCharacteristicsURL((char *)content); // process URL - return; + else if(!strncmp(body,"PUT /prepare ",13) && strstr(body,"Content-Type: application/hap+json")) // PUT PREPARE + putPrepareURL((char *)content); + + else { + notFoundError(); + LOG0("\n*** ERROR: Bad PUT request - URL not found\n\n"); } - - if(!strncmp(body,"PUT /prepare ",13) && // PUT PREPARE - strstr(body,"Content-Type: application/hap+json")){ // check that content is JSON - - content[cLen]='\0'; // add a trailing null on end of JSON - LOG2((char *)content); // print JSON - LOG2("\n------------ END JSON! ------------\n"); - - putPrepareURL((char *)content); // process URL - return; - } - - notFoundError(); - LOG0("\n*** ERROR: Bad PUT request - URL not found\n\n"); + return; } // PUT request - if(!strncmp(body,"GET ",4)){ // this is a GET request + if(!strncmp(body,"GET ",4)){ // this is a GET request - if(!strncmp(body,"GET /accessories ",17)){ // GET ACCESSORIES + if(!strncmp(body,"GET /accessories ",17)) // GET ACCESSORIES getAccessoriesURL(); - return; - } - if(!strncmp(body,"GET /characteristics?",21)){ // GET CHARACTERISTICS + else if(!strncmp(body,"GET /characteristics?",21)) // GET CHARACTERISTICS getCharacteristicsURL(body+21); - return; + + else if(homeSpan.webLog.isEnabled && !strncmp(body,homeSpan.webLog.statusURL.c_str(),homeSpan.webLog.statusURL.length())) // GET STATUS - AN OPTIONAL, NON-HAP-R2 FEATURE + getStatusURL(this,NULL,NULL); + + else { + notFoundError(); + LOG0("\n*** ERROR: Bad GET request - URL not found\n\n"); } - - if(homeSpan.webLog.isEnabled && !strncmp(body,homeSpan.webLog.statusURL.c_str(),homeSpan.webLog.statusURL.length())){ // GET STATUS - AN OPTIONAL, NON-HAP-R2 FEATURE - getStatusURL(); - return; - } - - notFoundError(); - LOG0("\n*** ERROR: Bad GET request - URL not found\n\n"); + return; } // GET request @@ -383,112 +314,129 @@ int HAPClient::unauthorizedError(){ ////////////////////////////////////// -int HAPClient::postPairSetupURL(){ +int HAPClient::postPairSetupURL(uint8_t *content, size_t len){ - LOG1("In Pair Setup..."); + HAPTLV iosTLV; + HAPTLV responseTLV; + HAPTLV subTLV; + + iosTLV.unpack(content,len); + if(homeSpan.getLogLevel()>1) + iosTLV.print(); + LOG2("------------ END TLVS! ------------\n"); + + LOG1("In Pair Setup #%d (%s)...",conNum,client.remoteIP().toString().c_str()); - int tlvState=tlv8.val(kTLVType_State); - char buf[64]; + auto itState=iosTLV.find(kTLVType_State); - if(tlvState==-1){ // missing STATE TLV - LOG0("\n*** ERROR: Missing State TLV\n\n"); - badRequestError(); // return with 400 error, which closes connection + if(iosTLV.len(itState)!=1){ // missing STATE TLV + LOG0("\n*** ERROR: Missing or invalid 'State' TLV\n\n"); + badRequestError(); // return with 400 error, which closes connection return(0); } - 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! + int tlvState=(*itState)[0]; + + 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"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,tlvState+1); // set response STATE to requested state+1 (which should match the state that was expected by the controller) - tlv8.val(kTLVType_Error,tagError_Unavailable); // set Error=Unavailable - tlvRespond(); // send response to client + responseTLV.add(kTLVType_State,tlvState+1); // set response STATE to requested state+1 (which should match the state that was expected by the controller) + responseTLV.add(kTLVType_Error,tagError_Unavailable); // set Error=Unavailable + tlvRespond(responseTLV); // send response to client return(0); }; - sprintf(buf,"Found . Expected \n",tlvState,pairStatus); - LOG2(buf); + LOG2("Found . Expected .\n",tlvState,pairStatus); - if(tlvState!=pairStatus){ // error: Device is not yet paired, but out-of-sequence pair-setup STATE was received + 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"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,tlvState+1); // set response STATE to requested state+1 (which should match the state that was expected by the controller) - tlv8.val(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for out-of-sequence steps) - tlvRespond(); // send response to client - pairStatus=pairState_M1; // reset pairStatus to first step of unpaired accessory (M1) + responseTLV.add(kTLVType_State,tlvState+1); // set response STATE to requested state+1 (which should match the state that was expected by the controller) + responseTLV.add(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for out-of-sequence steps) + tlvRespond(responseTLV); // send response to client + pairStatus=pairState_M1; // reset pairStatus to first step of unpaired accessory (M1) return(0); }; - switch(tlvState){ // valid and in-sequence Pair-Setup STATE received -- process request! (HAP Section 5.6) + switch(tlvState){ // valid and in-sequence Pair-Setup STATE received -- process request! (HAP Section 5.6) - case pairState_M1: // 'SRP Start Request' + case pairState_M1:{ // 'SRP Start Request' - if(tlv8.val(kTLVType_Method)!=0){ // error: "Pair Setup" method must always be 0 to indicate setup without MiFi Authentification (HAP Table 5-3) - LOG0("\n*** ERROR: Pair Method not set to 0\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M2); // set State= - tlv8.val(kTLVType_Error,tagError_Unavailable); // set Error=Unavailable - tlvRespond(); // send response to client + responseTLV.add(kTLVType_State,pairState_M2); // set State= + + 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) + 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 return(0); }; - tlv8.clear(); - tlv8.val(kTLVType_State,pairState_M2); // set State= - srp.createPublicKey(); // create accessory public key from random Pair-Setup code (displayed to user) - srp.loadTLV(kTLVType_PublicKey,&srp.B,384); // load server public key, B - srp.loadTLV(kTLVType_Salt,&srp.s,16); // load salt, s - tlvRespond(); // send response to client + auto itPublicKey=responseTLV.add(kTLVType_PublicKey,384,NULL); // create blank PublicKey TLV with space for 384 bytes - pairStatus=pairState_M3; // set next expected pair-state request from client - return(1); + if(srp==NULL) // create instance of SRP (if not already created) to persist until Pairing-Setup M5 completes + srp=new SRP6A; + + TempBuffer verifyData; // retrieve verification data (should already be stored in NVS) + size_t len=verifyData.len(); + nvs_get_blob(srpNVS,"VERIFYDATA",verifyData,&len); + + responseTLV.add(kTLVType_Salt,16,verifyData.get()->salt); // write Salt from verification data into TLV + srp->createPublicKey(verifyData,*itPublicKey); // create accessory Public Key from stored verification data and write result into PublicKey TLV + + tlvRespond(responseTLV); // send response to client + pairStatus=pairState_M3; // set next expected pair-state request from client + return(1); + } break; - case pairState_M3: // 'SRP Verify Request' + case pairState_M3:{ // 'SRP Verify Request' - if(!srp.writeTLV(kTLVType_PublicKey,&srp.A) || // try to write TLVs into mpi structures - !srp.writeTLV(kTLVType_Proof,&srp.M1)){ - + responseTLV.add(kTLVType_State,pairState_M4); // set State= + + auto itPublicKey=iosTLV.find(kTLVType_PublicKey); + auto itClientProof=iosTLV.find(kTLVType_Proof); + + if(iosTLV.len(itPublicKey)<=0 || iosTLV.len(itClientProof)!=64){ LOG0("\n*** ERROR: One or both of the required 'PublicKey' and 'Proof' TLV records for this step is bad or missing\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M4); // set State= - tlv8.val(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for missing/bad TLV data) - tlvRespond(); // send response to client - pairStatus=pairState_M1; // reset pairStatus to first step of unpaired + responseTLV.add(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for missing/bad TLV data) + tlvRespond(responseTLV); // send response to client + pairStatus=pairState_M1; // reset pairStatus to first step of unpaired return(0); }; - srp.createSessionKey(); // create session key, K, from receipt of HAP Client public key, A + srp->createSessionKey(*itPublicKey,(*itPublicKey).len); // create session key, K, from client Public Key, A - if(!srp.verifyProof()){ // verify proof, M1, received from HAP Client + if(!srp->verifyClientProof(*itClientProof)){ // verify client Proof, M1 LOG0("\n*** ERROR: SRP Proof Verification Failed\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M4); // set State= - tlv8.val(kTLVType_Error,tagError_Authentication); // set Error=Authentication - tlvRespond(); // send response to client - pairStatus=pairState_M1; // reset pairStatus to first step of unpaired + responseTLV.add(kTLVType_Error,tagError_Authentication); // set Error=Authentication + tlvRespond(responseTLV); // send response to client + pairStatus=pairState_M1; // reset pairStatus to first step of unpaired return(0); }; - srp.createProof(); // M1 has been successully verified; now create accessory proof M2 - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M4); // set State= - srp.loadTLV(kTLVType_Proof,&srp.M2,64); // load M2 counter-proof - tlvRespond(); // send response to client + auto itAccProof=responseTLV.add(kTLVType_Proof,64,NULL); // create blank accessory Proof TLV with space for 64 bytes - pairStatus=pairState_M5; // set next expected pair-state request from client + srp->createAccProof(*itAccProof); // M1 has been successully verified; now create accessory Proof M2 + + tlvRespond(responseTLV); // send response to client + pairStatus=pairState_M5; // set next expected pair-state request from client + return(1); - + } break; - case pairState_M5: // 'Exchange Request' + case pairState_M5:{ // 'Exchange Request' - if(!tlv8.buf(kTLVType_EncryptedData)){ + responseTLV.add(kTLVType_State,pairState_M6); // set State= + + auto itEncryptedData=iosTLV.find(kTLVType_EncryptedData); + + if(iosTLV.len(itEncryptedData)<=0){ LOG0("\n*** ERROR: Required 'EncryptedData' TLV record for this step is bad or missing\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M6); // set State= - tlv8.val(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for missing/bad TLV data) - tlvRespond(); // send response to client - pairStatus=pairState_M1; // reset pairStatus to first step of unpaired + responseTLV.add(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for missing/bad TLV data) + tlvRespond(responseTLV); // send response to client + pairStatus=pairState_M1; // reset pairStatus to first step of unpaired return(0); }; @@ -500,45 +448,38 @@ int HAPClient::postPairSetupURL(){ // 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. - hkdf.create(sessionKey, srp.sharedSecret,64,"Pair-Setup-Encrypt-Salt","Pair-Setup-Encrypt-Info"); // create SessionKey + TempBuffer 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 - uint8_t decrypted[1024]; // temporary storage for decrypted data - unsigned long long decryptedLen; // length (in bytes) of decrypted data + LOG2("------- DECRYPTING SUB-TLVS -------\n"); - if(crypto_aead_chacha20poly1305_ietf_decrypt( // use SessionKey to decrypt encryptedData TLV with padded nonce="PS-Msg05" - decrypted, &decryptedLen, NULL, - tlv8.buf(kTLVType_EncryptedData), tlv8.len(kTLVType_EncryptedData), NULL, 0, - (unsigned char *)"\x00\x00\x00\x00PS-Msg05", sessionKey)==-1){ - + // use SessionKey to decrypt encryptedData TLV with padded nonce="PS-Msg05" + + TempBuffer decrypted((*itEncryptedData).len-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){ LOG0("\n*** ERROR: Exchange-Request Authentication Failed\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M6); // set State= - tlv8.val(kTLVType_Error,tagError_Authentication); // set Error=Authentication - tlvRespond(); // send response to client - pairStatus=pairState_M1; // reset pairStatus to first step of unpaired + responseTLV.add(kTLVType_Error,tagError_Authentication); // set Error=Authentication + tlvRespond(responseTLV); // send response to client + pairStatus=pairState_M1; // reset pairStatus to first step of unpaired return(0); } - if(!tlv8.unpack(decrypted,decryptedLen)){ - LOG0("\n*** ERROR: Can't parse decrypted data into separate TLV records\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M6); // set State= - tlv8.val(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for missing/bad TLV data) - tlvRespond(); // send response to client - pairStatus=pairState_M1; // reset pairStatus to first step of unpaired - return(0); - } + subTLV.unpack(decrypted,decrypted.len()); // unpack TLV + if(homeSpan.getLogLevel()>1) + subTLV.print(); // print decrypted TLV data + + LOG2("---------- END SUB-TLVS! ----------\n"); - tlv8.print(2); // print decrypted TLV data - LOG2("------- END DECRYPTED TLVS! -------\n"); - - if(!tlv8.buf(kTLVType_Identifier) || !tlv8.buf(kTLVType_PublicKey) || !tlv8.buf(kTLVType_Signature)){ + auto itIdentifier=subTLV.find(kTLVType_Identifier); + auto itSignature=subTLV.find(kTLVType_Signature); + auto itPublicKey=subTLV.find(kTLVType_PublicKey); + + if(subTLV.len(itIdentifier)!=hap_controller_IDBYTES || subTLV.len(itSignature)!=crypto_sign_BYTES || subTLV.len(itPublicKey)!=crypto_sign_PUBLICKEYBYTES){ LOG0("\n*** ERROR: One or more of required 'Identifier,' 'PublicKey,' and 'Signature' TLV records for this step is bad or missing\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M6); // set State= - tlv8.val(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for missing/bad TLV data) - tlvRespond(); // send response to client - pairStatus=pairState_M1; // reset pairStatus to first step of unpaired + responseTLV.add(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for missing/bad TLV data) + tlvRespond(responseTLV); // send response to client + pairStatus=pairState_M1; // reset pairStatus to first step of unpaired return(0); }; @@ -547,100 +488,72 @@ int HAPClient::postPairSetupURL(){ // Rather, it purposely does not transmit "iosDeviceX", which is derived from the SRP Shared Secret that only the Client and this Server know. // Note that the SALT and INFO text fields now match those in HAP Section 5.6.6.1 - uint8_t iosDeviceX[32]; - hkdf.create(iosDeviceX,srp.sharedSecret,64,"Pair-Setup-Controller-Sign-Salt","Pair-Setup-Controller-Sign-Info"); // derive iosDeviceX from SRP Shared Secret using HKDF - size_t iosDeviceXLen=32; + TempBuffer 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 - uint8_t *iosDevicePairingID = tlv8.buf(kTLVType_Identifier); // set iosDevicePairingID from TLV record - size_t iosDevicePairingIDLen = tlv8.len(kTLVType_Identifier); + // Concatenate iosDeviceX, IOS ID, and IOS PublicKey into iosDeviceInfo + + TempBuffer iosDeviceInfo(iosDeviceX,iosDeviceX.len(),(*itIdentifier).val.get(),(*itIdentifier).len,(*itPublicKey).val.get(),(*itPublicKey).len,NULL); - uint8_t *iosDeviceLTPK = tlv8.buf(kTLVType_PublicKey); // set iosDeviceLTPK (Ed25519 long-term public key) from TLV record - size_t iosDeviceLTPKLen = tlv8.len(kTLVType_PublicKey); - - size_t iosDeviceInfoLen=iosDeviceXLen+iosDevicePairingIDLen+iosDeviceLTPKLen; // total size of re-constituted message, iosDeviceInfo - uint8_t iosDeviceInfo[iosDeviceInfoLen]; - - memcpy(iosDeviceInfo,iosDeviceX,iosDeviceXLen); // iosDeviceInfo = iosDeviceX - memcpy(iosDeviceInfo+iosDeviceXLen,iosDevicePairingID,iosDevicePairingIDLen); // +iosDevicePairingID - memcpy(iosDeviceInfo+iosDeviceXLen+iosDevicePairingIDLen,iosDeviceLTPK,iosDeviceLTPKLen); // +iosDeviceLTPK - - uint8_t *iosDeviceSignature = tlv8.buf(kTLVType_Signature); // set iosDeviceSignature from TLV record (an Ed25519 should always be 64 bytes) - - if(crypto_sign_verify_detached(iosDeviceSignature, iosDeviceInfo, iosDeviceInfoLen, iosDeviceLTPK) != 0){ // verify signature of iosDeviceInfo using iosDeviceLTPK + 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"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M6); // set State= - tlv8.val(kTLVType_Error,tagError_Authentication); // set Error=Authentication - tlvRespond(); // send response to client - pairStatus=pairState_M1; // reset pairStatus to first step of unpaired + responseTLV.add(kTLVType_Error,tagError_Authentication); // set Error=Authentication + tlvRespond(responseTLV); // send response to client + pairStatus=pairState_M1; // reset pairStatus to first step of unpaired return(0); } - addController(iosDevicePairingID,iosDeviceLTPK,true); // save Pairing ID and LTPK for this Controller with admin privileges - - nvs_set_blob(hapNVS,"CONTROLLERS",controllers,sizeof(controllers)); // update data - nvs_commit(hapNVS); // commit to NVS + addController(*itIdentifier,*itPublicKey,true); // save Pairing ID and LTPK for this Controller with admin privileges // Now perform the above steps in reverse to securely transmit the AccessoryLTPK to the Controller (HAP Section 5.6.6.2) - uint8_t accessoryX[32]; - hkdf.create(accessoryX,srp.sharedSecret,64,"Pair-Setup-Accessory-Sign-Salt","Pair-Setup-Accessory-Sign-Info"); // derive accessoryX from SRP Shared Secret using HKDF - size_t accessoryXLen=32; + TempBuffer 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 - uint8_t *accessoryPairingID=accessory.ID; // set accessoryPairingID from storage - size_t accessoryPairingIDLen=17; + // Concatenate accessoryX, Accessory ID, and Accessory PublicKey into accessoryInfo - uint8_t *accessoryLTPK=accessory.LTPK; // set accessoryLTPK (Ed25519 long-term public key) from storage - size_t accessoryLTPKLen=32; + TempBuffer accessoryInfo(accessoryX,accessoryX.len(),accessory.ID,hap_accessory_IDBYTES,accessory.LTPK,crypto_sign_PUBLICKEYBYTES,NULL); - size_t accessoryInfoLen=accessoryXLen+accessoryPairingIDLen+accessoryLTPKLen; // total size of accessoryInfo - uint8_t accessoryInfo[accessoryInfoLen]; + subTLV.clear(); // clear existing SUBTLV records - memcpy(accessoryInfo,accessoryX,accessoryXLen); // accessoryInfo = accessoryX - memcpy(accessoryInfo+accessoryXLen,accessoryPairingID,accessoryPairingIDLen); // +accessoryPairingID - memcpy(accessoryInfo+accessoryXLen+accessoryPairingIDLen,accessoryLTPK,accessoryLTPKLen); // +accessoryLTPK + itSignature=subTLV.add(kTLVType_Signature,64,NULL); // create blank Signature TLV with space for 64 bytes - tlv8.clear(); // clear existing TLV records + crypto_sign_detached(*itSignature,NULL,accessoryInfo,accessoryInfo.len(),accessory.LTSK); // produce signature of accessoryInfo using AccessoryLTSK (Ed25519 long-term secret key) - crypto_sign_detached(tlv8.buf(kTLVType_Signature,64),NULL,accessoryInfo,accessoryInfoLen,accessory.LTSK); // produce signature of accessoryInfo using AccessoryLTSK (Ed25519 long-term secret key) - - memcpy(tlv8.buf(kTLVType_Identifier,accessoryPairingIDLen),accessoryPairingID,accessoryPairingIDLen); // set Identifier TLV record as accessoryPairingID - memcpy(tlv8.buf(kTLVType_PublicKey,accessoryLTPKLen),accessoryLTPK,accessoryLTPKLen); // set PublicKey TLV record as accessoryLTPK + subTLV.add(kTLVType_Identifier,hap_accessory_IDBYTES,accessory.ID); // set Identifier TLV record as accessoryPairingID + subTLV.add(kTLVType_PublicKey,crypto_sign_PUBLICKEYBYTES,accessory.LTPK); // set PublicKey TLV record as accessoryLTPK LOG2("------- ENCRYPTING SUB-TLVS -------\n"); - tlv8.print(2); + if(homeSpan.getLogLevel()>1) + subTLV.print(); - size_t subTLVLen=tlv8.pack(NULL); // get size of buffer needed to store sub-TLV - uint8_t subTLV[subTLVLen]; - subTLVLen=tlv8.pack(subTLV); // create sub-TLV by packing Identifier, PublicKey, and Signature TLV records together + TempBuffer subPack(subTLV.pack_size()); // create sub-TLV by packing Identifier, PublicKey and Signature TLV records together + subTLV.pack(subPack); - tlv8.clear(); // clear existing TLV records + // Encrypt the subTLV data using the same SRP Session Key as above with ChaCha20-Poly1305 - // Final step is to encrypt the subTLV data using the same sessionKey as above with ChaCha20-Poly1305 - - unsigned long long edLen; + 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(tlv8.buf(kTLVType_EncryptedData),&edLen,subTLV,subTLVLen,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",sessionKey); + LOG2("---------- END SUB-TLVS! ----------\n"); - - tlv8.buf(kTLVType_EncryptedData,edLen); // set length of EncryptedData TLV record, which should now include the Authentication Tag at the end as required by HAP - tlv8.val(kTLVType_State,pairState_M6); // set State= - tlvRespond(); // send response to client + tlvRespond(responseTLV); // send response to client - mdns_service_txt_item_set("_hap","_tcp","sf","0"); // broadcast new status + delete srp; // delete SRP - no longer needed once pairing is completed + + mdns_service_txt_item_set("_hap","_tcp","sf","0"); // broadcast new status LOG1("\n*** ACCESSORY PAIRED! ***\n"); STATUS_UPDATE(on(),HS_PAIRED) - if(homeSpan.pairCallback) // if set, invoke user-defined Pairing Callback to indicate device has been paired + if(homeSpan.pairCallback) // if set, invoke user-defined Pairing Callback to indicate device has been paired homeSpan.pairCallback(true); return(1); - + } break; } // switch @@ -651,194 +564,183 @@ int HAPClient::postPairSetupURL(){ ////////////////////////////////////// -int HAPClient::postPairVerifyURL(){ +int HAPClient::postPairVerifyURL(uint8_t *content, size_t len){ - LOG2("In Pair Verify #"); - LOG2(conNum); - LOG2(" ("); - LOG2(client.remoteIP()); - LOG2(")..."); - - char buf[64]; - - int tlvState=tlv8.val(kTLVType_State); + HAPTLV iosTLV; + HAPTLV responseTLV; + HAPTLV subTLV; - if(tlvState==-1){ // missing STATE TLV - LOG0("\n*** ERROR: Missing State TLV\n\n"); - badRequestError(); // return with 400 error, which closes connection + iosTLV.unpack(content,len); + if(homeSpan.getLogLevel()>1) + iosTLV.print(); + LOG2("------------ END TLVS! ------------\n"); + + LOG1("In Pair Verify #%d (%s)...",conNum,client.remoteIP().toString().c_str()); + + auto itState=iosTLV.find(kTLVType_State); + + if(iosTLV.len(itState)!=1){ // missing STATE TLV + LOG0("\n*** ERROR: Missing or invalid 'State' TLV\n\n"); + badRequestError(); // return with 400 error, which closes connection return(0); } + int tlvState=(*itState)[0]; + 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"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,tlvState+1); // set response STATE to requested state+1 (which should match the state that was expected by the controller) - tlv8.val(kTLVType_Error,tagError_Unknown); // set Error=Unknown - tlvRespond(); // send response to client + responseTLV.add(kTLVType_State,tlvState+1); // set response STATE to requested state+1 (which should match the state that was expected by the controller) + responseTLV.add(kTLVType_Error,tagError_Unknown); // set Error=Unknown + tlvRespond(responseTLV); // send response to client return(0); }; - sprintf(buf,"Found \n",tlvState); // unlike pair-setup, out-of-sequencing can be handled gracefully for pair-verify (HAP requirement). No need to keep track of pairStatus - LOG2(buf); + LOG2("Found \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) + switch(tlvState){ // Pair-Verify STATE received -- process request! (HAP Section 5.7) - case pairState_M1: // 'Verify Start Request' + case pairState_M1:{ // 'Verify Start Request' - if(!tlv8.buf(kTLVType_PublicKey)){ + auto itPublicKey=iosTLV.find(kTLVType_PublicKey); + + if(iosTLV.len(itPublicKey)!=crypto_box_PUBLICKEYBYTES){ LOG0("\n*** ERROR: Required 'PublicKey' TLV record for this step is bad or missing\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M2); // set State= - tlv8.val(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for missing/bad TLV data) - tlvRespond(); // send response to client - return(0); - - } else { - - uint8_t secretCurveKey[32]; // Accessory's secret key for Curve25519 encryption (32 bytes). Ephemeral usage - created below and used only in this block - - crypto_box_keypair(publicCurveKey,secretCurveKey); // generate Curve25519 public key pair (will persist until end of verification process) - - memcpy(iosCurveKey,tlv8.buf(kTLVType_PublicKey),32); // save iosCurveKey (will persist until end of verification process) - - crypto_scalarmult_curve25519(sharedCurveKey,secretCurveKey,iosCurveKey); // generate (and persist) Pair Verify SharedSecret CurveKey from Accessory's Curve25519 secret key and Controller's Curve25519 public key (32 bytes) - - uint8_t *accessoryPairingID = accessory.ID; // set accessoryPairingID - size_t accessoryPairingIDLen = 17; - - size_t accessoryInfoLen=32+accessoryPairingIDLen+32; // total size of accessoryInfo - uint8_t accessoryInfo[accessoryInfoLen]; - - memcpy(accessoryInfo,publicCurveKey,32); // accessoryInfo = Accessory's Curve25519 public key - memcpy(accessoryInfo+32,accessoryPairingID,accessoryPairingIDLen); // +accessoryPairingID - memcpy(accessoryInfo+32+accessoryPairingIDLen,iosCurveKey,32); // +Controller's Curve25519 public key - - tlv8.clear(); // clear existing TLV records - - crypto_sign_detached(tlv8.buf(kTLVType_Signature,64),NULL,accessoryInfo,accessoryInfoLen,accessory.LTSK); // produce signature of accessoryInfo using AccessoryLTSK (Ed25519 long-term secret key) - - memcpy(tlv8.buf(kTLVType_Identifier,accessoryPairingIDLen),accessoryPairingID,accessoryPairingIDLen); // set Identifier TLV record as accessoryPairingID - - LOG2("------- ENCRYPTING SUB-TLVS -------\n"); - - tlv8.print(2); - - size_t subTLVLen=tlv8.pack(NULL); // get size of buffer needed to store sub-TLV - uint8_t subTLV[subTLVLen]; - subTLVLen=tlv8.pack(subTLV); // create sub-TLV by packing Identifier and Signature TLV records together - - tlv8.clear(); // clear existing TLV records - - // create SessionKey from Curve25519 SharedSecret using HKDF-SHA-512, then encrypt subTLV data with SessionKey using ChaCha20-Poly1305. Output stored in EncryptedData TLV - - unsigned long long edLen; - - hkdf.create(sessionKey,sharedCurveKey,32,"Pair-Verify-Encrypt-Salt","Pair-Verify-Encrypt-Info"); // create SessionKey (32 bytes) - - crypto_aead_chacha20poly1305_ietf_encrypt(tlv8.buf(kTLVType_EncryptedData),&edLen,subTLV,subTLVLen,NULL,0,NULL,(unsigned char *)"\x00\x00\x00\x00PV-Msg02",sessionKey); - - LOG2("---------- END SUB-TLVS! ----------\n"); - - tlv8.buf(kTLVType_EncryptedData,edLen); // set length of EncryptedData TLV record, which should now include the Authentication Tag at the end as required by HAP - tlv8.val(kTLVType_State,pairState_M2); // set State= - memcpy(tlv8.buf(kTLVType_PublicKey,32),publicCurveKey,32); // set PublicKey to Accessory's Curve25519 public key - - tlvRespond(); // send response to client - return(1); - } - - break; - - case pairState_M3: // 'Verify Finish Request' - - if(!tlv8.buf(kTLVType_EncryptedData)){ - LOG0("\n*** ERROR: Required 'EncryptedData' TLV record for this step is bad or missing\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M4); // set State= - tlv8.val(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for missing/bad TLV data) - tlvRespond(); // send response to client - return(0); - }; - - uint8_t decrypted[1024]; // temporary storage for decrypted data - unsigned long long decryptedLen; // length (in bytes) of decrypted data - - if(crypto_aead_chacha20poly1305_ietf_decrypt( // use SessionKey to decrypt encrypytedData TLV with padded nonce="PV-Msg03" - decrypted, &decryptedLen, NULL, - tlv8.buf(kTLVType_EncryptedData), tlv8.len(kTLVType_EncryptedData), NULL, 0, - (unsigned char *)"\x00\x00\x00\x00PV-Msg03", sessionKey)==-1){ - - LOG0("\n*** ERROR: Verify Authentication Failed\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M4); // set State= - tlv8.val(kTLVType_Error,tagError_Authentication); // set Error=Authentication - tlvRespond(); // send response to client + responseTLV.add(kTLVType_State,pairState_M2); // set State= + responseTLV.add(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for missing/bad TLV data) + tlvRespond(responseTLV); // send response to client return(0); } - if(!tlv8.unpack(decrypted,decryptedLen)){ - LOG0("\n*** ERROR: Can't parse decrypted data into separate TLV records\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M4); // set State= - tlv8.val(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for missing/bad TLV data) - tlvRespond(); // send response to client - return(0); - } + publicCurveKey=(uint8_t *)HS_MALLOC(crypto_box_PUBLICKEYBYTES); // temporary space - will be deleted at end of verification process + TempBuffer 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 - tlv8.print(2); // print decrypted TLV data - LOG2("------- END DECRYPTED TLVS! -------\n"); + 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 + + // concatenate Accessory's Curve25519 Public Key, Accessory's Pairing ID, and Controller's Curve25519 Public Key into accessoryInfo + + TempBuffer accessoryInfo(publicCurveKey,crypto_box_PUBLICKEYBYTES,accessory.ID,hap_accessory_IDBYTES,iosCurveKey,crypto_box_PUBLICKEYBYTES,NULL); - if(!tlv8.buf(kTLVType_Identifier) || !tlv8.buf(kTLVType_Signature)){ - LOG0("\n*** ERROR: One or more of required 'Identifier,' and 'Signature' TLV records for this step is bad or missing\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M4); // set State= - tlv8.val(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for missing/bad TLV data) - tlvRespond(); // send response to client + 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 + crypto_sign_detached(*itSignature,NULL,accessoryInfo,accessoryInfo.len(),accessory.LTSK); // produce Signature of accessoryInfo using Accessory's LTSK + + LOG2("------- ENCRYPTING SUB-TLVS -------\n"); + + if(homeSpan.getLogLevel()>1) + subTLV.print(); + + TempBuffer 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 + + 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 + + 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" + + LOG2("---------- END SUB-TLVS! ----------\n"); + + responseTLV.add(kTLVType_State,pairState_M2); // set State= + responseTLV.add(kTLVType_PublicKey,crypto_box_PUBLICKEYBYTES,publicCurveKey); // set PublicKey to Accessory's Curve25519 Public Key + + tlvRespond(responseTLV); // send response to client + } + break; + + case pairState_M3:{ // 'Verify Finish Request' + + auto itEncryptedData=iosTLV.find(kTLVType_EncryptedData); + + if(iosTLV.len(itEncryptedData)<=0){ + LOG0("\n*** ERROR: Required 'EncryptedData' TLV record for this step is bad or missing\n\n"); + responseTLV.add(kTLVType_State,pairState_M4); // set State= + responseTLV.add(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for missing/bad TLV data) + tlvRespond(responseTLV); // send response to client return(0); }; - Controller *tPair; // temporary pointer to Controller + LOG2("------- DECRYPTING SUB-TLVS -------\n"); - if(!(tPair=findController(tlv8.buf(kTLVType_Identifier)))){ - LOG0("\n*** ERROR: Unrecognized Controller PairingID\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M4); // set State= - tlv8.val(kTLVType_Error,tagError_Authentication); // set Error=Authentication - tlvRespond(); // send response to client + // use Session Curve25519 Key (from previous step) to decrypt encrypytedData TLV with padded nonce="PV-Msg03" + + TempBuffer decrypted((*itEncryptedData).len-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){ + LOG0("\n*** ERROR: Verify Authentication Failed\n\n"); + responseTLV.add(kTLVType_State,pairState_M4); // set State= + responseTLV.add(kTLVType_Error,tagError_Authentication); // set Error=Authentication + tlvRespond(responseTLV); // send response to client + return(0); + } + + subTLV.unpack(decrypted,decrypted.len()); // unpack TLV + if(homeSpan.getLogLevel()>1) + subTLV.print(); // print decrypted TLV data + + LOG2("---------- END SUB-TLVS! ----------\n"); + + auto itIdentifier=subTLV.find(kTLVType_Identifier); + auto itSignature=subTLV.find(kTLVType_Signature); + + if(subTLV.len(itIdentifier)!=hap_controller_IDBYTES || subTLV.len(itSignature)!=crypto_sign_BYTES){ + LOG0("\n*** ERROR: One or more of required 'Identifier,' and 'Signature' TLV records for this step is bad or missing\n\n"); + responseTLV.add(kTLVType_State,pairState_M4); // set State= + responseTLV.add(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for missing/bad TLV data) + tlvRespond(responseTLV); // send response to client return(0); } - size_t iosDeviceInfoLen=32+36+32; - uint8_t iosDeviceInfo[iosDeviceInfoLen]; - - memcpy(iosDeviceInfo,iosCurveKey,32); - memcpy(iosDeviceInfo+32,tPair->ID,36); - memcpy(iosDeviceInfo+32+36,publicCurveKey,32); + Controller *tPair; // temporary pointer to Controller - if(crypto_sign_verify_detached(tlv8.buf(kTLVType_Signature), iosDeviceInfo, iosDeviceInfoLen, tPair->LTPK) != 0){ // verify signature of iosDeviceInfo using iosDeviceLTPK + if(!(tPair=findController(*itIdentifier))){ + LOG0("\n*** ERROR: Unrecognized Controller ID: "); + charPrintRow(*itIdentifier,hap_controller_IDBYTES,2); + LOG0("\n\n"); + responseTLV.add(kTLVType_State,pairState_M4); // set State= + responseTLV.add(kTLVType_Error,tagError_Authentication); // set Error=Authentication + tlvRespond(responseTLV); // send response to client + return(0); + } + + LOG2("\n*** Verifying session with Controller ID: "); + charPrintRow(tPair->ID,hap_controller_IDBYTES,2); + LOG2("...\n"); + + // 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 iosDeviceInfo(iosCurveKey,crypto_box_PUBLICKEYBYTES,tPair->ID,hap_controller_IDBYTES,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"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M4); // set State= - tlv8.val(kTLVType_Error,tagError_Authentication); // set Error=Authentication - tlvRespond(); // send response to client + responseTLV.add(kTLVType_State,pairState_M4); // set State= + responseTLV.add(kTLVType_Error,tagError_Authentication); // set Error=Authentication + tlvRespond(responseTLV); // send response to client return(0); } - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M4); // set State= - tlvRespond(); // send response to client (unencrypted since cPair=NULL) + responseTLV.add(kTLVType_State,pairState_M4); // set State= + tlvRespond(responseTLV); // send response to client (unencrypted since cPair=NULL) - cPair=tPair; // save Controller for this connection slot - connection is not verified and should be encrypted going forward + 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 (HAP Section 6.5.2) - hkdf.create(c2aKey,sharedCurveKey,32,"Control-Salt","Control-Write-Encryption-Key"); // create ControllerToAccessoryKey (HAP Section 6.5.2) + 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) a2cNonce.zero(); // reset Nonces for this session to zero c2aNonce.zero(); - LOG2("\n*** SESSION VERIFICATION COMPLETE *** \n"); - return(1); + 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; } // switch @@ -849,6 +751,140 @@ int HAPClient::postPairVerifyURL(){ ////////////////////////////////////// +int HAPClient::postPairingsURL(uint8_t *content, size_t len){ + + if(!cPair){ // unverified, unencrypted session + unauthorizedError(); + return(0); + } + + HAPTLV iosTLV; + HAPTLV responseTLV; + + iosTLV.unpack(content,len); + if(homeSpan.getLogLevel()>1) + iosTLV.print(); + LOG2("------------ END TLVS! ------------\n"); + + LOG1("In Post Pairings #%d (%s)...",conNum,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 + LOG0("\n*** ERROR: Parirings 'State' is either missing or not set to \n\n"); + badRequestError(); // return with 400 error, which closes connection + return(0); + } + + if(iosTLV.len(itMethod)!=1){ // missing METHOD TLV + LOG0("\n*** ERROR: Missing or invalid 'Method' TLV\n\n"); + badRequestError(); // return with 400 error, which closes connection + return(0); + } + + int tlvMethod=(*itMethod)[0]; + + responseTLV.add(kTLVType_State,pairState_M2); // all responses include State=M2 + + switch(tlvMethod){ // List-Pairings received -- process request! (HAP Sections 5.10-5.12) + + case 3: { + LOG1("Add...\n"); + + auto itIdentifier=iosTLV.find(kTLVType_Identifier); + auto itPublicKey=iosTLV.find(kTLVType_PublicKey); + auto itPermissions=iosTLV.find(kTLVType_Permissions); + + if(iosTLV.len(itIdentifier)!=hap_controller_IDBYTES || iosTLV.len(itPublicKey)!=crypto_sign_PUBLICKEYBYTES || iosTLV.len(itPermissions)!=1){ + LOG0("\n*** ERROR: One or more of required 'Identifier,' 'PublicKey,' and 'Permissions' TLV records for this step is bad or missing\n\n"); + responseTLV.add(kTLVType_Error,tagError_Unknown); + tlvRespond(responseTLV); + return(0); + } + + if(!cPair->admin){ + LOG0("\n*** ERROR: Controller making request does not have admin privileges to add/update other Controllers\n\n"); + responseTLV.add(kTLVType_Error,tagError_Authentication); + tlvRespond(responseTLV); + return(0); + } + + tagError err=addController(*itIdentifier,*itPublicKey,(*itPermissions)[0]); + if(err!=tagError_None) + responseTLV.add(kTLVType_Error,err); + + tlvRespond(responseTLV); + return(1); + } + break; + + case 4: { + LOG1("Remove...\n"); + + auto itIdentifier=iosTLV.find(kTLVType_Identifier); + + if(iosTLV.len(itIdentifier)!=hap_controller_IDBYTES){ + LOG0("\n*** ERROR: Required 'Identifier' TLV record for this step is bad or missing\n\n"); + responseTLV.add(kTLVType_Error,tagError_Unknown); + tlvRespond(responseTLV); + return(0); + } + + if(!cPair->admin){ + LOG0("\n*** ERROR: Controller making request does not have admin privileges to remove Controllers\n\n"); + responseTLV.add(kTLVType_Error,tagError_Authentication); + tlvRespond(responseTLV); + return(0); + } + + tlvRespond(responseTLV); // must send response before removing Controller + removeController(*itIdentifier); + + return(1); + } + break; + + case 5: { + LOG1("List...\n"); + + if(!cPair->admin){ + LOG0("\n*** ERROR: Controller making request does not have admin privileges to remove Controllers\n\n"); + responseTLV.add(kTLVType_Error,tagError_Authentication); + tlvRespond(responseTLV); + return(0); + } + + boolean addSeparator=false; + + for(auto it=controllerList.begin();it!=controllerList.end();it++){ + if((*it).allocated){ + if(addSeparator) + responseTLV.add(kTLVType_Separator); + responseTLV.add(kTLVType_Permissions,(*it).admin); + responseTLV.add(kTLVType_Identifier,hap_controller_IDBYTES,(*it).ID); + responseTLV.add(kTLVType_PublicKey,crypto_sign_PUBLICKEYBYTES,(*it).LTPK); + addSeparator=true; + } + } + + tlvRespond(responseTLV); + return(1); + } + break; + + default: { + LOG0("\n*** ERROR: Undefined List-Pairings Method: %d. Must be 3, 4, or 5\n\n",tlvMethod); + badRequestError(); // return with 400 error, which closes connection + return(0); + } + } // switch + + return(1); +} + +////////////////////////////////////// + int HAPClient::getAccessoriesURL(){ if(!cPair){ // unverified, unencrypted session @@ -856,187 +892,45 @@ int HAPClient::getAccessoriesURL(){ return(0); } - LOG1("In Get Accessories #"); - LOG1(conNum); - LOG1(" ("); - LOG1(client.remoteIP()); - LOG1(")...\n"); + LOG1("In Get Accessories #%d (%s)...\n",conNum,client.remoteIP().toString().c_str()); - int nBytes = homeSpan.sprintfAttributes(NULL); // get size of HAP attributes JSON - TempBuffer jBuf(nBytes+1); - homeSpan.sprintfAttributes(jBuf.buf); // create JSON database (will need to re-cast to uint8_t* below) + homeSpan.printfAttributes(); + size_t nBytes=hapOut.getSize(); + hapOut.flush(); - int nChars=snprintf(NULL,0,"HTTP/1.1 200 OK\r\nContent-Type: application/hap+json\r\nContent-Length: %d\r\n\r\n",nBytes); // create '200 OK' Body with Content Length = size of JSON Buf - char body[nChars+1]; - sprintf(body,"HTTP/1.1 200 OK\r\nContent-Type: application/hap+json\r\nContent-Length: %d\r\n\r\n",nBytes); - - LOG2("\n>>>>>>>>>> "); - LOG2(client.remoteIP()); - LOG2(" >>>>>>>>>>\n"); - LOG2(body); - LOG2(jBuf.buf); - LOG2("\n"); - - sendEncrypted(body,(uint8_t *)jBuf.buf,nBytes); - + LOG2("\n>>>>>>>>>> %s >>>>>>>>>>\n",client.remoteIP().toString().c_str()); + + hapOut.setLogLevel(2).setHapClient(this); + hapOut << "HTTP/1.1 200 OK\r\nContent-Type: application/hap+json\r\nContent-Length: " << nBytes << "\r\n\r\n"; + homeSpan.printfAttributes(); + hapOut.flush(); + + LOG2("\n-------- SENT ENCRYPTED! --------\n"); + return(1); } // getAccessories ////////////////////////////////////// -int HAPClient::postPairingsURL(){ - - if(!cPair){ // unverified, unencrypted session - unauthorizedError(); - return(0); - } - - Controller *newCont; - - LOG1("In Post Pairings #"); - LOG1(conNum); - LOG1(" ("); - LOG1(client.remoteIP()); - LOG1(")..."); - - if(tlv8.val(kTLVType_State)!=1){ - LOG0("\n*** ERROR: 'State' TLV record is either missing or not set to as required\n\n"); - badRequestError(); // return with 400 error, which closes connection - return(0); - } - - switch(tlv8.val(kTLVType_Method)){ - - case 3: - LOG1("Add...\n"); - - if(!tlv8.buf(kTLVType_Identifier) || !tlv8.buf(kTLVType_PublicKey) || !tlv8.buf(kTLVType_Permissions)){ - LOG0("\n*** ERROR: One or more of required 'Identifier,' 'PublicKey,' and 'Permissions' TLV records for this step is bad or missing\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M2); // set State= - tlv8.val(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for missing/bad TLV data) - break; - } - - if(!cPair->admin){ - LOG0("\n*** ERROR: Controller making request does not have admin privileges to add/update other Controllers\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M2); // set State= - tlv8.val(kTLVType_Error,tagError_Authentication); // set Error=Authentication - break; - } - - if((newCont=findController(tlv8.buf(kTLVType_Identifier))) && memcmp(tlv8.buf(kTLVType_PublicKey),newCont->LTPK,32)){ // requested Controller already exists, but LTPKs don't match - LOG0("\n*** ERROR: Invalid request to update the LTPK of an exsiting Controller\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M2); // set State= - tlv8.val(kTLVType_Error,tagError_Unknown); // set Error=Unknown - break; - } - - if(!addController(tlv8.buf(kTLVType_Identifier),tlv8.buf(kTLVType_PublicKey),tlv8.val(kTLVType_Permissions)==1?true:false)){ - LOG0("\n*** ERROR: Can't pair more than %d Controllers\n\n",MAX_CONTROLLERS); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M2); // set State= - tlv8.val(kTLVType_Error,tagError_MaxPeers); // set Error=MaxPeers - break; - } - - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M2); // set State= - break; - - case 4: - LOG1("Remove...\n"); - - if(!tlv8.buf(kTLVType_Identifier)){ - LOG0("\n*** ERROR: Required 'Identifier' TLV record for this step is bad or missing\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M2); // set State= - tlv8.val(kTLVType_Error,tagError_Unknown); // set Error=Unknown (there is no specific error type for missing/bad TLV data) - break; - } - - if(!cPair->admin){ - LOG0("\n*** ERROR: Controller making request does not have admin privileges to remove Controllers\n\n"); - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M2); // set State= - tlv8.val(kTLVType_Error,tagError_Authentication); // set Error=Authentication - break; - } - - removeController(tlv8.buf(kTLVType_Identifier)); - - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M2); // set State= - break; - - case 5: - LOG1("List...\n"); - - // NEEDS TO BE IMPLEMENTED - UNSURE IF THIS IS EVER USED BY HOMEKIT - - tlv8.clear(); // clear TLV records - tlv8.val(kTLVType_State,pairState_M2); // set State= - break; - - default: - LOG0("\n*** ERROR: 'Method' TLV record is either missing or not set to either 3, 4, or 5 as required\n\n"); - badRequestError(); // return with 400 error, which closes connection - return(0); - break; - } - - nvs_set_blob(hapNVS,"CONTROLLERS",controllers,sizeof(controllers)); // update Controller data - nvs_commit(hapNVS); // commit to NVS - - tlvRespond(); - - // re-check connections and close any (or all) clients as a result of controllers that were removed above - // must be performed AFTER sending the TLV response, since that connection itself may be terminated below - - for(int i=0;iclient){ // if slot is connected - - if(!nAdminControllers() || (hap[i]->cPair && !hap[i]->cPair->allocated)){ // accessory unpaired, OR client connection is verified but points to a newly *unallocated* controller - LOG1("*** Terminating Client #"); - LOG1(i); - LOG1("\n"); - hap[i]->client.stop(); - } - - } // if client connected - } // loop over all connection slots - - return(1); -} - -////////////////////////////////////// - int HAPClient::getCharacteristicsURL(char *urlBuf){ - if(!cPair){ // unverified, unencrypted session unauthorizedError(); return(0); } - LOG1("In Get Characteristics #"); - LOG1(conNum); - LOG1(" ("); - LOG1(client.remoteIP()); - LOG1(")...\n"); + LOG1("In Get Characteristics #%d (%s)...\n",conNum,client.remoteIP().toString().c_str()); - int len=strlen(urlBuf); // determine number of IDs specificed by counting commas in URL + int len=strlen(urlBuf); // determine number of IDs specified by counting commas in URL int numIDs=1; for(int i=0;i ids(numIDs); // reserve space for number of IDs found + int flags=GET_VALUE|GET_AID; // flags indicating which characteristic fields to include in response (HAP Table 6-13) + numIDs=0; // reset number of IDs found char *lastSpace=strchr(urlBuf,' '); if(lastSpace) @@ -1071,25 +965,17 @@ int HAPClient::getCharacteristicsURL(char *urlBuf){ if(!numIDs) // could not find any IDs return(0); - int nBytes=homeSpan.sprintfAttributes(ids,numIDs,flags,NULL); // get JSON response - includes terminating null (will be recast to uint8_t* below) - char jsonBuf[nBytes+1]; - homeSpan.sprintfAttributes(ids,numIDs,flags,jsonBuf); + boolean statusFlag=homeSpan.printfAttributes(ids,numIDs,flags); // get statusFlag returned to use below + size_t nBytes=hapOut.getSize(); + hapOut.flush(); - boolean sFlag=strstr(jsonBuf,"status"); // status attribute found? + hapOut.setLogLevel(2).setHapClient(this); + hapOut << "HTTP/1.1 " << (!statusFlag?"200 OK":"207 Multi-Status") << "\r\nContent-Type: application/hap+json\r\nContent-Length: " << nBytes << "\r\n\r\n"; + homeSpan.printfAttributes(ids,numIDs,flags); + hapOut.flush(); - int nChars=snprintf(NULL,0,"HTTP/1.1 %s\r\nContent-Type: application/hap+json\r\nContent-Length: %d\r\n\r\n",!sFlag?"200 OK":"207 Multi-Status",nBytes); - char body[nChars+1]; - sprintf(body,"HTTP/1.1 %s\r\nContent-Type: application/hap+json\r\nContent-Length: %d\r\n\r\n",!sFlag?"200 OK":"207 Multi-Status",nBytes); - - LOG2("\n>>>>>>>>>> "); - LOG2(client.remoteIP()); - LOG2(" >>>>>>>>>>\n"); - LOG2(body); - LOG2(jsonBuf); - LOG2("\n"); - - sendEncrypted(body,(uint8_t *)jsonBuf,nBytes); // note recasting of jsonBuf into uint8_t* - + LOG2("\n-------- SENT ENCRYPTED! --------\n"); + return(1); } @@ -1102,11 +988,7 @@ int HAPClient::putCharacteristicsURL(char *json){ return(0); } - LOG1("In Put Characteristics #"); - LOG1(conNum); - LOG1(" ("); - LOG1(client.remoteIP()); - LOG1(")...\n"); + LOG1("In Put Characteristics #%d (%s)...\n",conNum,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 @@ -1121,38 +1003,28 @@ int HAPClient::putCharacteristicsURL(char *json){ if(pObj[i].status!=StatusCode::OK) multiCast=1; + LOG2("\n>>>>>>>>>> %s >>>>>>>>>>\n",client.remoteIP().toString().c_str()); + if(!multiCast){ // JSON object has no content - - char body[]="HTTP/1.1 204 No Content\r\n\r\n"; - - LOG2("\n>>>>>>>>>> "); - LOG2(client.remoteIP()); - LOG2(" >>>>>>>>>>\n"); - LOG2(body); - sendEncrypted(body,NULL,0); + hapOut.setLogLevel(2).setHapClient(this); + hapOut << "HTTP/1.1 204 No Content\r\n\r\n"; + hapOut.flush(); - } else { // multicast respose is required + } else { // multicast respose is required - int nBytes=homeSpan.sprintfAttributes(pObj,n,NULL); // get JSON response - includes terminating null (will be recast to uint8_t* below) - char jsonBuf[nBytes+1]; - homeSpan.sprintfAttributes(pObj,n,jsonBuf); - - int nChars=snprintf(NULL,0,"HTTP/1.1 207 Multi-Status\r\nContent-Type: application/hap+json\r\nContent-Length: %d\r\n\r\n",nBytes); // create Body with Content Length = size of JSON Buf - char body[nChars+1]; - sprintf(body,"HTTP/1.1 207 Multi-Status\r\nContent-Type: application/hap+json\r\nContent-Length: %d\r\n\r\n",nBytes); - - LOG2("\n>>>>>>>>>> "); - LOG2(client.remoteIP()); - LOG2(" >>>>>>>>>>\n"); - LOG2(body); - LOG2(jsonBuf); - LOG2("\n"); - - sendEncrypted(body,(uint8_t *)jsonBuf,nBytes); // note recasting of jsonBuf into uint8_t* + homeSpan.printfAttributes(pObj,n); + size_t nBytes=hapOut.getSize(); + hapOut.flush(); + hapOut.setLogLevel(2).setHapClient(this); + hapOut << "HTTP/1.1 207 Multi-Status\r\nContent-Type: application/hap+json\r\nContent-Length: " << nBytes << "\r\n\r\n"; + homeSpan.printfAttributes(pObj,n); + hapOut.flush(); } + LOG2("\n-------- SENT ENCRYPTED! --------\n"); + // 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 @@ -1169,11 +1041,7 @@ int HAPClient::putPrepareURL(char *json){ return(0); } - LOG1("In Put Prepare #"); - LOG1(conNum); - LOG1(" ("); - LOG1(client.remoteIP()); - LOG1(")...\n"); + LOG1("In Put Prepare #%d (%s)...\n",conNum,client.remoteIP().toString().c_str()); char ttlToken[]="\"ttl\":"; char pidToken[]="\"pid\":"; @@ -1188,7 +1056,6 @@ int HAPClient::putPrepareURL(char *json){ if((cBuf=strstr(json,pidToken))) sscanf(cBuf+strlen(ttlToken),"%llu",&pid); - char jsonBuf[32]; StatusCode status=StatusCode::OK; if(ttl>0 && pid>0){ // found required elements @@ -1197,28 +1064,26 @@ int HAPClient::putPrepareURL(char *json){ status=StatusCode::InvalidValue; } - sprintf(jsonBuf,"{\"status\":%d}",(int)status); - int nBytes=strlen(jsonBuf); - int nChars=snprintf(NULL,0,"HTTP/1.1 200 OK\r\nContent-Type: application/hap+json\r\nContent-Length: %d\r\n\r\n",nBytes); // create Body with Content Length = size of JSON Buf - char body[nChars+1]; - sprintf(body,"HTTP/1.1 200 OK\r\nContent-Type: application/hap+json\r\nContent-Length: %d\r\n\r\n",nBytes); - - LOG2("\n>>>>>>>>>> "); - LOG2(client.remoteIP()); - LOG2(" >>>>>>>>>>\n"); - LOG2(body); - LOG2(jsonBuf); - LOG2("\n"); - - sendEncrypted(body,(uint8_t *)jsonBuf,nBytes); // note recasting of jsonBuf into uint8_t* - + LOG2("\n>>>>>>>>>> %s >>>>>>>>>>\n",client.remoteIP().toString().c_str()); + + hapOut << "{\"status\":" << (int)status << "}"; + size_t nBytes=hapOut.getSize(); + hapOut.flush(); + + hapOut.setLogLevel(2).setHapClient(this); + hapOut << "HTTP/1.1 200 OK\r\nContent-Type: application/hap+json\r\nContent-Length: " << nBytes << "\r\n\r\n"; + hapOut << "{\"status\":" << (int)status << "}"; + hapOut.flush(); + + LOG2("\n-------- SENT ENCRYPTED! --------\n"); + return(1); } ////////////////////////////////////// -int HAPClient::getStatusURL(){ - +void HAPClient::getStatusURL(HAPClient *hapClient, void (*callBack)(const char *, void *), void *user_data){ + char clocktime[33]; if(homeSpan.webLog.timeInit){ @@ -1238,78 +1103,92 @@ int HAPClient::getStatusURL(){ sprintf(uptime,"%d:%02d:%02d:%02d",days,hours,mins,secs); - String response="HTTP/1.1 200 OK\r\nContent-type: text/html; charset=utf-8\r\n\r\n"; + if(hapClient) + LOG2("\n>>>>>>>>>> %s >>>>>>>>>>\n",hapClient->client.remoteIP().toString().c_str()); + + hapOut.setHapClient(hapClient).setLogLevel(2).setCallback(callBack).setCallbackUserData(user_data); - response+="" + String(homeSpan.displayName) + "\n"; - response+="\n"; - response+="

" + String(homeSpan.displayName) + "

\n"; + if(!callBack) + hapOut << "HTTP/1.1 200 OK\r\nContent-type: text/html; charset=utf-8\r\n\r\n"; + + hapOut << "" << homeSpan.displayName << "\n"; + hapOut << "\n"; + hapOut << "

" << homeSpan.displayName << "

\n"; - response+="\n"; - response+="\n"; - response+="\n"; - response+="\n"; + hapOut << "
Up Time:" + String(uptime) + "
Current Time:" + String(clocktime) + "
Boot Time:" + String(homeSpan.webLog.bootTime) + "
\n"; + hapOut << "\n"; + hapOut << "\n"; + hapOut << "\n"; + hapOut << "\n"; - response+="\n"; - response+="\n"; - response+="\n"; - response+="\n"; - response+="\n"; - response+="\n"; - response+="\n"; - response+="\n"; - response+="\n"; + hapOut << " (" << esp_reset_reason() << ")\n"; + + hapOut << "\n"; + hapOut << "\n"; + hapOut << "\n"; + hapOut << "\n"; + hapOut << "\n"; + hapOut << "\n"; + hapOut << "\n"; + hapOut << "\n"; + hapOut << "\n"; char mbtlsv[64]; mbedtls_version_get_string_full(mbtlsv); - response+="\n"; - - response+="\n"; - response+="\n"; - response+="
Up Time:" << uptime << "
Current Time:" << clocktime << "
Boot Time:" << homeSpan.webLog.bootTime << "
Reset Reason:"; - response+="
Reset Reason:"; switch(esp_reset_reason()) { case ESP_RST_UNKNOWN: - response += "Cannot be determined"; + hapOut << "Cannot be determined"; break; case ESP_RST_POWERON: - response += "Power-on event"; + hapOut << "Power-on event"; break; case ESP_RST_EXT: - response += "External pin"; + hapOut << "External pin"; break; case ESP_RST_SW: - response += "Software reboot via esp_restart"; + hapOut << "Software reboot via esp_restart"; break; case ESP_RST_PANIC: - response += "Software Exception/Panic"; + hapOut << "Software Exception/Panic"; break; case ESP_RST_INT_WDT: - response += "Interrupt watchdog"; + hapOut << "Interrupt watchdog"; break; case ESP_RST_TASK_WDT: - response += "Task watchdog"; + hapOut << "Task watchdog"; break; case ESP_RST_WDT: - response += "Other watchdogs"; + hapOut << "Other watchdogs"; break; case ESP_RST_DEEPSLEEP: - response += "Exiting deep sleep mode"; + hapOut << "Exiting deep sleep mode"; break; case ESP_RST_BROWNOUT: - response += "Brownout"; + hapOut << "Brownout"; break; case ESP_RST_SDIO: - response += "SDIO"; + hapOut << "SDIO"; break; default: - response += "Unknown Reset Code"; + hapOut << "Unknown Reset Code"; } - response+=" (" + String(esp_reset_reason()) + ")
WiFi Disconnects:" + String(homeSpan.connected/2) + "
WiFi Signal:" + String(WiFi.RSSI()) + " dBm
WiFi Gateway:" + WiFi.gatewayIP().toString() + "
ESP32 Board:" + String(ARDUINO_BOARD) + "
Arduino-ESP Version:" + String(ARDUINO_ESP_VERSION) + "
ESP-IDF Version:" + String(ESP_IDF_VERSION_MAJOR) + "." + String(ESP_IDF_VERSION_MINOR) + "." + String(ESP_IDF_VERSION_PATCH) + "
HomeSpan Version:" + String(HOMESPAN_VERSION) + "
Sketch Version:" + String(homeSpan.getSketchVersion()) + "
Sodium Version:" + String(sodium_version_string()) + " Lib " + String(sodium_library_version_major()) + "." + String(sodium_library_version_minor()) +"
WiFi Disconnects:" << homeSpan.connected/2 << "
WiFi Signal:" << (int)WiFi.RSSI() << " dBm
WiFi Gateway:" << WiFi.gatewayIP().toString().c_str() << "
ESP32 Board:" << ARDUINO_BOARD << "
Arduino-ESP Version:" << ARDUINO_ESP_VERSION << "
ESP-IDF Version:" << ESP_IDF_VERSION_MAJOR << "." << ESP_IDF_VERSION_MINOR << "." << ESP_IDF_VERSION_PATCH << "
HomeSpan Version:" << HOMESPAN_VERSION << "
Sketch Version:" << homeSpan.getSketchVersion() << "
Sodium Version:" << sodium_version_string() << " Lib " << sodium_library_version_major() << "." << sodium_library_version_minor() << "
MbedTLS Version:" + String(mbtlsv) + "
HomeKit Status:" + String(nAdminControllers()?"PAIRED":"NOT PAIRED") + "
Max Log Entries:" + String(homeSpan.webLog.maxEntries) + "
\n"; - response+="

"; + hapOut << "MbedTLS Version:" << mbtlsv << "\n"; + + hapOut << "HomeKit Status:" << (HAPClient::nAdminControllers()?"PAIRED":"NOT PAIRED") << "\n"; + hapOut << "Max Log Entries:" << homeSpan.webLog.maxEntries << "\n"; + if(homeSpan.weblogCallback){ + String usrString; + homeSpan.weblogCallback(usrString); // Callback to add user-defined html in top table. + hapOut << usrString.c_str(); + } + + hapOut << "\n"; + hapOut << "

"; + if(homeSpan.webLog.maxEntries>0){ - response+="\n"; + hapOut << "
EntryUp TimeLog TimeClientMessage
\n"; int lastIndex=homeSpan.webLog.nEntries-homeSpan.webLog.maxEntries; if(lastIndex<0) lastIndex=0; @@ -1328,25 +1207,18 @@ int HAPClient::getStatusURL(){ else sprintf(clocktime,"Unknown"); - response+="\n"; + hapOut << "\n"; } - response+="
EntryUp TimeLog TimeClientMessage
" + String(i+1) + "" + String(uptime) + "" + String(clocktime) + "" + homeSpan.webLog.log[index].clientIP + "" + String(homeSpan.webLog.log[index].message) + "
" << i+1 << "" << uptime << "" << clocktime << "" << homeSpan.webLog.log[index].clientIP.c_str() << "" << homeSpan.webLog.log[index].message << "
\n"; + hapOut << "\n"; } - - response+=""; + + hapOut << "\n"; + hapOut.flush(); - LOG2("\n>>>>>>>>>> "); - LOG2(client.remoteIP()); - LOG2(" >>>>>>>>>>\n"); - LOG2(response); - LOG2("\n"); - client.print(response); - LOG2("------------ SENT! --------------\n"); - - delay(1); - client.stop(); - - return(1); + if(hapClient){ + hapClient->client.stop(); + LOG2("------------ SENT! --------------\n"); + } } ////////////////////////////////////// @@ -1365,13 +1237,10 @@ void HAPClient::checkTimedWrites(){ unsigned long cTime=millis(); // get current time - char c[64]; - auto tw=homeSpan.TimedWrites.begin(); while(tw!=homeSpan.TimedWrites.end()){ - if(cTime>tw->second){ // timer has expired - sprintf(c,"Removing PID=%llu ALARM=%u\n",tw->first,tw->second); - LOG2(c); + if(cTime>tw->second){ // timer has expired + LOG2("Removing PID=%llu ALARM=%u\n",tw->first,tw->second); tw=homeSpan.TimedWrites.erase(tw); } else @@ -1384,85 +1253,81 @@ void HAPClient::checkTimedWrites(){ void HAPClient::eventNotify(SpanBuf *pObj, int nObj, int ignoreClient){ - for(int cNum=0;cNumclient && 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) + for(int cNum=0;cNumclient && 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) - int nBytes=homeSpan.sprintfNotify(pObj,nObj,NULL,cNum); // get JSON response for notifications to client cNum - includes terminating null (will be recast to uint8_t* below) + homeSpan.printfNotify(pObj,nObj,cNum); // 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 - char jsonBuf[nBytes+1]; - homeSpan.sprintfNotify(pObj,nObj,jsonBuf,cNum); + if(nBytes>0){ // if there ARE notifications to send to client cNum + + LOG2("\n>>>>>>>>>> %s >>>>>>>>>>\n",hap[cNum]->client.remoteIP().toString().c_str()); - int nChars=snprintf(NULL,0,"EVENT/1.0 200 OK\r\nContent-Type: application/hap+json\r\nContent-Length: %d\r\n\r\n",nBytes); // create Body with Content Length = size of JSON Buf - char body[nChars+1]; - sprintf(body,"EVENT/1.0 200 OK\r\nContent-Type: application/hap+json\r\nContent-Length: %d\r\n\r\n",nBytes); - - LOG2("\n>>>>>>>>>> "); - LOG2(hap[cNum]->client.remoteIP()); - LOG2(" >>>>>>>>>>\n"); - LOG2(body); - LOG2(jsonBuf); - LOG2("\n"); - - hap[cNum]->sendEncrypted(body,(uint8_t *)jsonBuf,nBytes); // note recasting of jsonBuf into uint8_t* - - } // if there are characteristic updates to notify client cNum - } // if client exists - } + hapOut.setLogLevel(2).setHapClient(hap[cNum]); + 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); + hapOut.flush(); + LOG2("\n-------- SENT ENCRYPTED! --------\n"); + } + } + } } ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// -void HAPClient::tlvRespond(){ +void HAPClient::tlvRespond(TLV8 &tlv8){ - int nBytes=tlv8.pack(NULL); // return number of bytes needed to pack TLV records into a buffer - uint8_t tlvData[nBytes]; // create buffer - tlv8.pack(tlvData); // pack TLV records into buffer - - int nChars=snprintf(NULL,0,"HTTP/1.1 200 OK\r\nContent-Type: application/pairing+tlv8\r\nContent-Length: %d\r\n\r\n",nBytes); // create Body with Content Length = size of TLV data - char body[nChars+1]; - sprintf(body,"HTTP/1.1 200 OK\r\nContent-Type: application/pairing+tlv8\r\nContent-Length: %d\r\n\r\n",nBytes); + tlv8.osprint(hapOut); + size_t nBytes=hapOut.getSize(); + hapOut.flush(); - LOG2("\n>>>>>>>>>> "); - LOG2(client.remoteIP()); - LOG2(" >>>>>>>>>>\n"); + char *body; + asprintf(&body,"HTTP/1.1 200 OK\r\nContent-Type: application/pairing+tlv8\r\nContent-Length: %d\r\n\r\n",nBytes); // create Body with Content Length = size of TLV data + + LOG2("\n>>>>>>>>>> %s >>>>>>>>>>\n",client.remoteIP().toString().c_str()); LOG2(body); - tlv8.print(2); + if(homeSpan.getLogLevel()>1) + tlv8.print(); - if(!cPair){ // unverified, unencrypted session - client.print(body); - client.write(tlvData,nBytes); + hapOut.setHapClient(this); + hapOut << body; + tlv8.osprint(hapOut); + hapOut.flush(); + + if(!cPair) LOG2("------------ SENT! --------------\n"); - } else { - sendEncrypted(body,tlvData,nBytes); - } - + else + LOG2("-------- SENT ENCRYPTED! --------\n"); + } // tlvRespond ////////////////////////////////////// -int HAPClient::receiveEncrypted(){ +int HAPClient::receiveEncrypted(uint8_t *httpBuf, int messageSize){ - uint8_t buf[1042]; // maximum size of encoded message = 2+1024+16 bytes (HAP Section 6.5.2) + uint8_t aad[2]; int nBytes=0; - while(client.read(buf,2)==2){ // read initial 2-byte AAD record + while(client.read(aad,2)==2){ // read initial 2-byte AAD record - int n=buf[0]+buf[1]*256; // compute number of bytes expected in encoded message + int n=aad[0]+aad[1]*256; // compute number of bytes expected in message after decoding - if(nBytes+n>MAX_HTTP){ // exceeded maximum number of bytes allowed in plaintext message - LOG0("\n\n*** ERROR: Exceeded maximum HTTP message length\n\n"); + if(nBytes+n>messageSize){ // exceeded maximum number of bytes allowed in plaintext message + LOG0("\n\n*** ERROR: Decrypted message of %d bytes exceeded maximum expected message length of %d bytes\n\n",nBytes+n,messageSize); return(0); } - if(client.read(buf+2,n+16)!=n+16){ // read expected number of total bytes = n bytes in encoded message + 16 bytes for appended authentication tag + TempBuffer tBuf(n+16); // expected number of total bytes = n bytes in encoded message + 16 bytes for appended authentication tag + + if(client.read(tBuf,tBuf.len())!=tBuf.len()){ LOG0("\n\n*** ERROR: Malformed encrypted message frame\n\n"); return(0); } - if(crypto_aead_chacha20poly1305_ietf_decrypt(httpBuf+nBytes, NULL, NULL, buf+2, n+16, buf, 2, c2aNonce.get(), c2aKey)==-1){ + if(crypto_aead_chacha20poly1305_ietf_decrypt(httpBuf+nBytes, NULL, NULL, tBuf, tBuf.len(), aad, 2, c2aNonce.get(), c2aKey)==-1){ LOG0("\n\n*** ERROR: Can't Decrypt Message\n\n"); return(0); } @@ -1477,57 +1342,6 @@ int HAPClient::receiveEncrypted(){ } // receiveEncrypted -////////////////////////////////////// - -void HAPClient::sendEncrypted(char *body, uint8_t *dataBuf, int dataLen){ - - const int FRAME_SIZE=1024; // number of bytes to use in each ChaCha20-Poly1305 encrypted frame when sending encrypted JSON content to Client - - int bodyLen=strlen(body); - - int count=0; - unsigned long long nBytes; - - int totalBytes=2+bodyLen+16; // 2-byte AAD + bodyLen + 16-byte authentication tag - totalBytes+=(dataLen/FRAME_SIZE)*(2+FRAME_SIZE+16); // number of full frames * size of full frame with 2-byte AAD + 16-byte authentication tag - - if(dataLen%FRAME_SIZE) // if there is a residual last partial frame - totalBytes+=2+dataLen%FRAME_SIZE+16; // 2-byte AAD + residual of last partial frame + 16-byte authentication tag - - TempBuffer tBuf(totalBytes); - - tBuf.buf[count]=bodyLen%256; // store number of bytes in first frame that encrypts the Body (AAD bytes) - tBuf.buf[count+1]=bodyLen/256; - - crypto_aead_chacha20poly1305_ietf_encrypt(tBuf.buf+count+2,&nBytes,(uint8_t *)body,bodyLen,tBuf.buf+count,2,NULL,a2cNonce.get(),a2cKey); // encrypt the Body with authentication tag appended - - a2cNonce.inc(); // increment nonce - - count+=2+bodyLen+16; // increment count by 2-byte AAD record + length of Body + 16-byte authentication tag - - for(int i=0;iFRAME_SIZE) // maximum number of bytes to encrypt=FRAME_SIZE - n=FRAME_SIZE; - - tBuf.buf[count]=n%256; // store number of bytes that encrypts this frame (AAD bytes) - tBuf.buf[count+1]=n/256; - - crypto_aead_chacha20poly1305_ietf_encrypt(tBuf.buf+count+2,&nBytes,dataBuf+i,n,tBuf.buf+count,2,NULL,a2cNonce.get(),a2cKey); // encrypt the next portion of dataBuf with authentication tag appended - - a2cNonce.inc(); // increment nonce - - count+=2+n+16; // increment count by 2-byte AAD record + length of JSON + 16-byte authentication tag - } - - client.write(tBuf.buf,count); // transmit all encrypted frames to Client - - LOG2("-------- SENT ENCRYPTED! --------\n"); - -} // sendEncrypted - ///////////////////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////////////////// @@ -1565,10 +1379,10 @@ void HAPClient::charPrintRow(uint8_t *buf, int n, int minLogLevel){ ////////////////////////////////////// Controller *HAPClient::findController(uint8_t *id){ - - for(int i=0;iLTPK,ltpk,32); - slot->admin=admin; - LOG2("\n*** Updated Controller: "); - charPrintRow(id,36,2); - LOG2(slot->admin?" (admin)\n\n":" (regular)\n\n"); - return(slot); - } - - if((slot=getFreeController())){ // get slot for new controller, if available - slot->allocated=true; - memcpy(slot->ID,id,36); - memcpy(slot->LTPK,ltpk,32); - slot->admin=admin; - LOG2("\n*** Added Controller: "); - charPrintRow(id,36,2); - LOG2(slot->admin?" (admin)\n\n":" (regular)\n\n"); - return(slot); - } - - return(NULL); -} - -////////////////////////////////////// - int HAPClient::nAdminControllers(){ int n=0; - - for(int i=0;iLTPK,crypto_sign_PUBLICKEYBYTES)){ // existing controller with same LTPK + LOG2("\n*** Updated Controller: "); + charPrintRow(id,hap_controller_IDBYTES,2); + LOG2(" from %s to %s\n\n",cTemp->admin?"(admin)":"(regular)",admin?"(admin)":"(regular)"); + cTemp->admin=admin; + saveControllers(); + } else { + LOG0("\n*** ERROR: Invalid request to update the LTPK of an existing Controller\n\n"); + err=tagError_Unknown; + } + + return(err); +} ////////////////////////////////////// void HAPClient::removeController(uint8_t *id){ - Controller *slot; - - if((slot=findController(id))){ // remove controller if found - LOG2("\n***Removed Controller: "); - charPrintRow(id,36,2); - LOG2(slot->admin?" (admin)\n":" (regular)\n"); - slot->allocated=false; - - if(nAdminControllers()==0){ // if no more admins, remove all controllers - removeControllers(); - LOG1("That was last Admin Controller! Removing any remaining Regular Controllers and unpairing Accessory\n"); - mdns_service_txt_item_set("_hap","_tcp","sf","1"); // set Status Flag = 1 (Table 6-8) - - STATUS_UPDATE(start(LED_PAIRING_NEEDED),HS_PAIRING_NEEDED) - - if(homeSpan.pairCallback) // if set, invoke user-defined Pairing Callback to indicate device has been paired - homeSpan.pairCallback(false); - } + auto it=std::find_if(controllerList.begin(), controllerList.end(), [id](const Controller& cTemp){return(!memcmp(cTemp.ID,id,hap_controller_IDBYTES));}); + if(it==controllerList.end()){ + LOG2("\n*** Request to Remove Controller Ignored - Controller Not Found: "); + charPrintRow(id,hap_controller_IDBYTES,2); LOG2("\n"); + return; } -} + LOG1("\n*** Removing Controller: "); + charPrintRow((*it).ID,hap_controller_IDBYTES,2); + LOG1((*it).admin?" (admin)\n":" (regular)\n"); + + tearDown((*it).ID); // teardown any connections using this Controller + controllerList.erase(it); // remove Controller + + if(!nAdminControllers()){ // no more admin Controllers + + LOG1("That was last Admin Controller! Removing any remaining Regular Controllers and unpairing Accessory\n"); + + tearDown(NULL); // teardown all remaining connections + controllerList.clear(); // remove all remaining Controllers + mdns_service_txt_item_set("_hap","_tcp","sf","1"); // set Status Flag = 1 (Table 6-8) + STATUS_UPDATE(start(LED_PAIRING_NEEDED),HS_PAIRING_NEEDED) // set optional Status LED + if(homeSpan.pairCallback) // if set, invoke user-defined Pairing Callback to indicate device has been un-paired + homeSpan.pairCallback(false); + } + + saveControllers(); +} + +////////////////////////////////////// + +void HAPClient::tearDown(uint8_t *id){ + + for(int i=0;iclient && (id==NULL || (hap[i]->cPair && !memcmp(id,hap[i]->cPair->ID,hap_controller_IDBYTES)))){ + LOG1("*** Terminating Client #%d\n",i); + hap[i]->client.stop(); + } + } +} ////////////////////////////////////// @@ -1670,26 +1484,41 @@ void HAPClient::printControllers(int minLogLevel){ if(homeSpan.logLevel 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 + + nvs_set_blob(hapNVS,"CONTROLLERS",tBuf,tBuf.len()); // update data + nvs_commit(hapNVS); // commit to NVS +} + + +////////////////////////////////////// +////////////////////////////////////// + Nonce::Nonce(){ zero(); } @@ -1714,19 +1543,159 @@ void Nonce::inc(){ x[5]++; } +////////////////////////////////////// +////////////////////////////////////// + +HapOut::HapStreamBuffer::HapStreamBuffer(){ + + // note - must require all memory allocation to be pulled from INTERNAL heap only + + const uint32_t caps=MALLOC_CAP_DEFAULT | MALLOC_CAP_INTERNAL; + + buffer=(char *)heap_caps_malloc(bufSize+1,caps); // add 1 for adding null terminator when printing text + encBuf=(uint8_t *)heap_caps_malloc(bufSize+18,caps); // 2-byte AAD + encrypted data + 16-byte authentication tag + hash=(uint8_t *)heap_caps_malloc(48,caps); // space for SHA-384 hash output + ctx = (mbedtls_sha512_context *)heap_caps_malloc(sizeof(mbedtls_sha512_context),caps); // space for hash context + + mbedtls_sha512_init(ctx); // initialize context + mbedtls_sha512_starts_ret(ctx,1); // start SHA-384 hash (note second argument=1) + + setp(buffer, buffer+bufSize-1); // assign buffer pointers +} + +////////////////////////////////////// + +HapOut::HapStreamBuffer::~HapStreamBuffer(){ + + sync(); + free(buffer); +} + +////////////////////////////////////// + +void HapOut::HapStreamBuffer::flushBuffer(){ + + int num=pptr()-pbase(); + + byteCount+=num; + + buffer[num]='\0'; // add null terminator but DO NOT increment num (we don't want terminator considered as part of buffer) + + if(callBack) + callBack(buffer,callBackUserData); + + if(logLevel<=homeSpan.getLogLevel()){ + if(enablePrettyPrint) // if pretty print needed, use formatted method + printFormatted(buffer,num,2); + else // if not, just print + Serial.print(buffer); + } + + if(hapClient!=NULL){ + if(!hapClient->cPair){ // if not encrypted + hapClient->client.write(buffer,num); // transmit data buffer + + } else { // if encrypted + + encBuf[0]=num%256; // store number of bytes that encrypts this frame (AAD bytes) + encBuf[1]=num/256; + crypto_aead_chacha20poly1305_ietf_encrypt(encBuf+2,NULL,(uint8_t *)buffer,num,encBuf,2,NULL,hapClient->a2cNonce.get(),hapClient->a2cKey); // encrypt buffer with AAD prepended and authentication tag appended + + hapClient->client.write(encBuf,num+18); // transmit encrypted frame + hapClient->a2cNonce.inc(); // increment nonce + } + delay(1); + } + + mbedtls_sha512_update_ret(ctx,(uint8_t *)buffer,num); // update hash + + pbump(-num); // reset buffer pointers +} + +////////////////////////////////////// + +std::streambuf::int_type HapOut::HapStreamBuffer::overflow(std::streambuf::int_type c){ + + if(c!=EOF){ + *pptr() = c; + pbump(1); + } + + flushBuffer(); + return(c); +} + +////////////////////////////////////// + +int HapOut::HapStreamBuffer::sync(){ + + flushBuffer(); + + logLevel=255; + hapClient=NULL; + enablePrettyPrint=false; + byteCount=0; + indent=0; + + if(callBack){ + callBack(NULL,callBackUserData); + callBack=NULL; + callBackUserData=NULL; + } + + mbedtls_sha512_finish_ret(ctx,hash); // finish SHA-384 and store hash + mbedtls_sha512_starts_ret(ctx,1); // re-start hash for next time + + return(0); +} + +////////////////////////////////////// + +void HapOut::HapStreamBuffer::printFormatted(char *buf, size_t nChars, size_t nsp){ + + for(int i=0;i HAPClient::tlv8; nvs_handle HAPClient::hapNVS; nvs_handle HAPClient::srpNVS; -uint8_t HAPClient::httpBuf[MAX_HTTP+1]; HKDF HAPClient::hkdf; pairState HAPClient::pairStatus; Accessory HAPClient::accessory; -Controller HAPClient::controllers[MAX_CONTROLLERS]; -SRP6A HAPClient::srp; +list> HAPClient::controllerList; +SRP6A *HAPClient::srp=NULL; int HAPClient::conNum; diff --git a/src/HAP.h b/src/HAP.h index 8c8b937..bbf6feb 100644 --- a/src/HAP.h +++ b/src/HAP.h @@ -1,7 +1,7 @@ /********************************************************************************* * MIT License * - * Copyright (c) 2020-2023 Gregg E. Berman + * Copyright (c) 2020-2024 Gregg E. Berman * * https://github.com/HomeSpan/HomeSpan * @@ -27,14 +27,32 @@ #pragma once +#include #include #include "HomeSpan.h" -#include "TLV.h" #include "HAPConstants.h" #include "HKDF.h" #include "SRP.h" +#include "TLV8.h" +const TLV8_names HAP_Names[] = { + {kTLVType_Separator,"SEPARATOR"}, + {kTLVType_State,"STATE"}, + {kTLVType_PublicKey,"PUBKEY"}, + {kTLVType_Method,"METHOD"}, + {kTLVType_Salt,"SALT"}, + {kTLVType_Error,"ERROR"}, + {kTLVType_Proof,"PROOF"}, + {kTLVType_EncryptedData,"ENC.DATA"}, + {kTLVType_Signature,"SIGNATURE"}, + {kTLVType_Identifier,"IDENTIFIER"}, + {kTLVType_Permissions,"PERMISSION"} +}; + +#define hap_controller_IDBYTES 36 +#define hap_accessory_IDBYTES 17 + ///////////////////////////////////////////////// // NONCE Structure (HAP used last 64 of 96 bits) @@ -50,19 +68,29 @@ struct Nonce { // Paired Controller Structure for Permanently-Stored Data struct Controller { - boolean allocated=false; // slot is allocated with Controller data - boolean admin; // Controller has admin privileges - uint8_t ID[36]; // Pairing ID - uint8_t LTPK[32]; // Long Term Ed2519 Public Key + 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 struct Accessory { - uint8_t ID[17]; // Pairing ID in form "XX:XX:XX:XX:XX:XX" - uint8_t LTSK[64]; // secret key for Ed25519 signatures - uint8_t LTPK[32]; // public key for Ed25519 signatures + uint8_t ID[hap_accessory_IDBYTES]; // Pairing ID in form "XX:XX:XX:XX:XX:XX" (no null terminator) + uint8_t LTSK[crypto_sign_SECRETKEYBYTES]; // Long Term Ed2519 Secret Key + uint8_t LTPK[crypto_sign_PUBLICKEYBYTES]; // Long Term Ed2519 Public Key }; ///////////////////////////////////////////////// @@ -73,32 +101,30 @@ struct HAPClient { // common structures and data shared across all HAP Clients - static const int MAX_HTTP=8095; // max number of bytes in HTTP message buffer + static const int MAX_HTTP=8096; // max number of bytes allowed for HTTP message static const int MAX_CONTROLLERS=16; // maximum number of paired controllers (HAP requires at least 16) - static const int MAX_ACCESSORIES=41; // maximum number of allowed Acessories (HAP limit=150, but not enough memory in ESP32 to run that many) + static const int MAX_ACCESSORIES=150; // maximum number of allowed Accessories (HAP limit=150) - static TLV tlv8; // TLV8 structure (HAP Section 14.1) with space for 10 TLV records of type kTLVType (HAP Table 5-6) - 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 uint8_t httpBuf[MAX_HTTP+1]; // buffer to store HTTP messages (+1 to leave room for storing an extra 'overflow' character) - 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 - static Accessory accessory; // Accessory ID and Ed25519 public and secret keys- permanently stored - static Controller controllers[MAX_CONTROLLERS]; // 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 + 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 list> 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 - Controller *cPair; // pointer to info on current, session-verified Paired Controller (NULL=un-verified, and therefore un-encrypted, connection) + Controller *cPair=NULL; // pointer to info on current, session-verified Paired Controller (NULL=un-verified, and therefore un-encrypted, connection) - // These 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 + // 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[32]; // public key for Curve25519 encryption - uint8_t sharedCurveKey[32]; // Pair-Verfied Shared Secret key derived from Accessory's epehmeral secretCurveKey and Controller's iosCurveKey - uint8_t sessionKey[32]; // shared Session Key (derived with various HKDF calls) - uint8_t iosCurveKey[32]; // Curve25519 public key for associated paired controller + 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 // CurveKey and CurveKey Nonces are created once each new session is verified in /pair-verify. Keys persist for as long as connection is open @@ -109,19 +135,17 @@ struct HAPClient { // define member methods - void processRequest(); // process HAP request - int postPairSetupURL(); // POST /pair-setup (HAP Section 5.6) - int postPairVerifyURL(); // POST /pair-verify (HAP Section 5.7) - int getAccessoriesURL(); // GET /accessories (HAP Section 6.6) - int postPairingsURL(); // POST /pairings (HAP Sections 5.10-5.12) - int getCharacteristicsURL(char *urlBuf); // GET /characteristics (HAP Section 6.7.4) - int putCharacteristicsURL(char *json); // PUT /characteristics (HAP Section 6.7.2) - int putPrepareURL(char *json); // PUT /prepare (HAP Section 6.7.2.4) - int getStatusURL(); // GET / status (an optional, non-HAP feature) + void processRequest(); // process HAP request + int postPairSetupURL(uint8_t *content, size_t len); // POST /pair-setup (HAP Section 5.6) + int postPairVerifyURL(uint8_t *content, size_t len); // POST /pair-verify (HAP Section 5.7) + int postPairingsURL(uint8_t *content, size_t len); // POST /pairings (HAP Sections 5.10-5.12) + int getAccessoriesURL(); // GET /accessories (HAP Section 6.6) + int getCharacteristicsURL(char *urlBuf); // GET /characteristics (HAP Section 6.7.4) + int putCharacteristicsURL(char *json); // PUT /characteristics (HAP Section 6.7.2) + int putPrepareURL(char *json); // PUT /prepare (HAP Section 6.7.2.4) - void tlvRespond(); // respond to client with HTTP OK header and all defined TLV data records (those with length>0) - void sendEncrypted(char *body, uint8_t *dataBuf, int dataLen); // send client complete ChaCha20-Poly1305 encrypted HTTP mesage comprising a null-terminated 'body' and 'dataBuf' with 'dataLen' bytes - int receiveEncrypted(); // decrypt HTTP request (HAP Section 6.5) + void tlvRespond(TLV8 &tlv8); // respond to client with HTTP OK header and all defined TLV data records + int receiveEncrypted(uint8_t *httpBuf, int messageSize); // decrypt HTTP request (HAP Section 6.5) int notFoundError(); // return 404 error int badRequestError(); // return 400 error @@ -129,25 +153,83 @@ struct HAPClient { // define static methods - static void init(); // initialize HAP after start-up + 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 Controller *findController(uint8_t *id); // returns pointer to controller with mathching ID (or NULL if no match) - static Controller *getFreeController(); // return pointer to next free controller slot (or NULL if no free slots) - static Controller *addController(uint8_t *id, uint8_t *ltpk, boolean admin); // stores data for new Controller with specified data. Returns pointer to Controller slot on success, else NULL - static int nAdminControllers(); // returns number of admin Controllers stored - static void removeControllers(); // removes all Controllers (sets allocated flags to false for all slots) + 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) static void removeController(uint8_t *id); // removes specific Controller. If no remaining admin Controllers, remove all others (if any) as per HAP requirements. static void printControllers(int minLogLevel=0); // prints IDs of all allocated (paired) Controller, subject to specified minimum log level + static void saveControllers(); // saves Controller list in NVS + static int nAdminControllers(); // returns number of admin Controller + 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 getStatusURL(HAPClient *, void (*)(const char *, void *), void *); // GET / status (an optional, non-HAP feature) + + class HAPTLV : public TLV8 { // dedicated class for HAP TLV8 records + public: + HAPTLV() : TLV8(HAP_Names,11){} + }; + +}; + +///////////////////////////////////////////////// +// HapOut Structure + +class HapOut : public std::ostream { + + private: + + struct HapStreamBuffer : public std::streambuf { + + const size_t bufSize=1024; // max allowed for HAP encrypted records + char *buffer; + uint8_t *encBuf; + HAPClient *hapClient=NULL; + int logLevel=255; // default is NOT to print anything + boolean enablePrettyPrint=false; + size_t byteCount=0; + size_t indent=0; + uint8_t *hash; + mbedtls_sha512_context *ctx; + void (*callBack)(const char *, void *)=NULL; + void *callBackUserData = NULL; + + void flushBuffer(); + int_type overflow(int_type c) override; + int sync() override; + size_t getSize(){return(byteCount+pptr()-pbase());} + void printFormatted(char *buf, size_t nChars, size_t nsp); + + HapStreamBuffer(); + ~HapStreamBuffer(); + + }; + + HapStreamBuffer hapBuffer; + + public: + + HapOut() : std::ostream(&hapBuffer){} + + HapOut& setHapClient(HAPClient *hapClient){hapBuffer.hapClient=hapClient;return(*this);} + HapOut& setLogLevel(int logLevel){hapBuffer.logLevel=logLevel;return(*this);} + HapOut& prettyPrint(){hapBuffer.enablePrettyPrint=true;hapBuffer.logLevel=0;return(*this);} + HapOut& setCallback(void(*f)(const char *, void *)){hapBuffer.callBack=f;return(*this);} + HapOut& setCallbackUserData(void *userData){hapBuffer.callBackUserData=userData;return(*this);} + + uint8_t *getHash(){return(hapBuffer.hash);} + size_t getSize(){return(hapBuffer.getSize());} }; ///////////////////////////////////////////////// // Extern Variables extern HAPClient **hap; +extern HapOut hapOut; diff --git a/src/HAPConstants.h b/src/HAPConstants.h index 5ed6ab3..2bbf02c 100644 --- a/src/HAPConstants.h +++ b/src/HAPConstants.h @@ -1,7 +1,7 @@ /********************************************************************************* * MIT License * - * Copyright (c) 2020-2023 Gregg E. Berman + * Copyright (c) 2020-2024 Gregg E. Berman * * https://github.com/HomeSpan/HomeSpan * @@ -52,6 +52,7 @@ typedef enum { // HAP Error Codes (HAP Table 5-5) typedef enum { + tagError_None=0x00, tagError_Unknown=0x01, tagError_Authentication=0x02, tagError_Backoff=0x03, diff --git a/src/HKDF.cpp b/src/HKDF.cpp index 5194ad7..4398070 100644 --- a/src/HKDF.cpp +++ b/src/HKDF.cpp @@ -1,7 +1,7 @@ /********************************************************************************* * MIT License * - * Copyright (c) 2020-2023 Gregg E. Berman + * Copyright (c) 2020-2024 Gregg E. Berman * * https://github.com/HomeSpan/HomeSpan * diff --git a/src/HKDF.h b/src/HKDF.h index 46933ed..deb2760 100644 --- a/src/HKDF.h +++ b/src/HKDF.h @@ -1,7 +1,7 @@ /********************************************************************************* * MIT License * - * Copyright (c) 2020-2023 Gregg E. Berman + * Copyright (c) 2020-2024 Gregg E. Berman * * https://github.com/HomeSpan/HomeSpan * diff --git a/src/HapQR.h b/src/HapQR.h index d97e9ad..3ff15f2 100644 --- a/src/HapQR.h +++ b/src/HapQR.h @@ -1,7 +1,7 @@ /********************************************************************************* * MIT License * - * Copyright (c) 2020-2023 Gregg E. Berman + * Copyright (c) 2020-2024 Gregg E. Berman * * https://github.com/HomeSpan/HomeSpan * diff --git a/src/HomeSpan.cpp b/src/HomeSpan.cpp index 07dd911..fd8d50a 100644 --- a/src/HomeSpan.cpp +++ b/src/HomeSpan.cpp @@ -1,7 +1,7 @@ /********************************************************************************* * MIT License * - * Copyright (c) 2020-2023 Gregg E. Berman + * Copyright (c) 2020-2024 Gregg E. Berman * * https://github.com/HomeSpan/HomeSpan * @@ -39,11 +39,13 @@ #include "HomeSpan.h" #include "HAP.h" +#include const __attribute__((section(".rodata_custom_desc"))) SpanPartition spanPartition = {HOMESPAN_MAGIC_COOKIE,0}; using namespace Utils; +HapOut hapOut; // Specialized output stream that can both print to serial monitor and encrypt/transmit to HAP Clients with minimal memory usage (global-scope) HAPClient **hap; // HAP Client structure containing HTTP client connections, parsing routines, and state variables (global-scoped variable) Span homeSpan; // HAP Attributes database and all related control functions for this Accessory (global-scoped variable) HapCharacteristics hapChars; // Instantiation of all HAP Characteristics (used to create SpanCharacteristics) @@ -53,6 +55,8 @@ HapCharacteristics hapChars; // Instantiation of all HAP Characteristics /////////////////////////////// void Span::begin(Category catID, const char *displayName, const char *hostNameBase, const char *modelName){ + + loopTaskHandle=xTaskGetCurrentTaskHandle(); // a roundabout way of getting the current task handle this->displayName=displayName; this->hostNameBase=hostNameBase; @@ -68,7 +72,7 @@ void Span::begin(Category catID, const char *displayName, const char *hostNameBa if(requestedMaxConreset(); LOG0("%s is READY!\n\n",displayName); - isInitialized=true; + isInitialized=true; } // isInitialized @@ -260,7 +273,7 @@ void Span::pollTask() { homeSpan.lastClientIP="0.0.0.0"; // reset stored IP address to show "0.0.0.0" if homeSpan.getClientIP() is used in any other context if(!hap[i]->client){ // client disconnected by server - LOG1("** Disconnecting Client #"); + LOG1("** Disconnected Client #"); LOG1(i); LOG1(" ("); LOG1(millis()/1000); @@ -301,7 +314,13 @@ void Span::pollTask() { statusLED->check(); - vTaskDelay(5); + if(rebootCallback && snapTime>rebootCallbackTime){ + rebootCallback(rebootCount-1); + rebootCount=0; + rebootCallback=NULL; + nvs_set_u8(wifiNVS,"REBOOTS",rebootCount); + nvs_commit(wifiNVS); + } } // poll @@ -408,7 +427,8 @@ void Span::checkConnect(){ LOG0("\n*** Can't connect to %s. You may type 'W ' to re-configure WiFi, or 'X ' to erase WiFi credentials. Will try connecting again in 60 seconds.\n\n",network.wifiData.ssid); waitTime=60000; } else { - addWebLog(true,"Trying to connect to %s. Waiting %d sec...",network.wifiData.ssid,waitTime/1000); + if(verboseWifiReconnect) + addWebLog(true,"Trying to connect to %s. Waiting %d sec...",network.wifiData.ssid,waitTime/1000); WiFi.begin(network.wifiData.ssid,network.wifiData.pwd); } @@ -422,38 +442,34 @@ void Span::checkConnect(){ addWebLog(true,"WiFi Connected! IP Address = %s",WiFi.localIP().toString().c_str()); - if(connected>1) // Do not initialize everything below if this is only a reconnect + if(connected>1){ // Do not initialize everything below if this is only a reconnect + if(wifiCallbackAll) + wifiCallbackAll((connected+1)/2); return; + } char id[18]; // create string version of Accessory ID for MDNS broadcast memcpy(id,HAPClient::accessory.ID,17); // copy ID bytes id[17]='\0'; // add terminating null - // create broadcaset name from server base name plus accessory ID (without ':') - - int nChars; - - if(!hostNameSuffix) - nChars=snprintf(NULL,0,"%s-%.2s%.2s%.2s%.2s%.2s%.2s",hostNameBase,id,id+3,id+6,id+9,id+12,id+15); - else - nChars=snprintf(NULL,0,"%s%s",hostNameBase,hostNameSuffix); - - char hostName[nChars+1]; + // create broadcast name from server base name plus accessory ID (without ':') if(!hostNameSuffix) - sprintf(hostName,"%s-%.2s%.2s%.2s%.2s%.2s%.2s",hostNameBase,id,id+3,id+6,id+9,id+12,id+15); + asprintf(&hostName,"%s-%.2s%.2s%.2s%.2s%.2s%.2s",hostNameBase,id,id+3,id+6,id+9,id+12,id+15); else - sprintf(hostName,"%s%s",hostNameBase,hostNameSuffix); + asprintf(&hostName,"%s%s",hostNameBase,hostNameSuffix); - char d[strlen(hostName)+1]; - sscanf(hostName,"%[A-Za-z0-9-]",d); + char *d; + sscanf(hostName,"%m[A-Za-z0-9-]",&d); - if(strlen(hostName)>255|| hostName[0]=='-' || hostName[strlen(hostName)-1]=='-' || strlen(hostName)!=strlen(d)){ + if(strlen(hostName)>255 || hostName[0]=='-' || hostName[strlen(hostName)-1]=='-' || strlen(hostName)!=strlen(d)){ LOG0("\n*** Error: Can't start MDNS due to invalid hostname '%s'.\n",hostName); LOG0("*** Hostname must consist of 255 or less alphanumeric characters or a hyphen, except that the hyphen cannot be the first or last character.\n"); LOG0("*** PROGRAM HALTED!\n\n"); while(1); } + + free(d); LOG0("\nStarting MDNS...\n\n"); LOG0("HostName: %s.local:%d\n",hostName,tcpPortNum); @@ -519,9 +535,10 @@ void Span::checkConnect(){ mdns_service_txt_item_set("_hap","_tcp","logURL",webLog.statusURL.c_str()+4); // Web Log status (info only - NOT used by HAP) LOG0("Web Logging enabled at http://%s.local:%d%swith max number of entries=%d\n\n",hostName,tcpPortNum,webLog.statusURL.c_str()+4,webLog.maxEntries); - if(webLog.timeServer) - xTaskCreateUniversal(webLog.initTime, "timeSeverTaskHandle", 8096, &webLog, 1, NULL, 0); } + + if(webLog.timeServer) + xTaskCreateUniversal(webLog.initTime, "timeSeverTaskHandle", 8096, &webLog, 1, NULL, 0); LOG0("Starting HAP Server on port %d supporting %d simultaneous HomeKit Controller Connections...\n\n",tcpPortNum,maxConnections); @@ -534,12 +551,15 @@ void Span::checkConnect(){ if(wifiCallback) wifiCallback(); + + if(wifiCallbackAll) + wifiCallbackAll((connected+1)/2); } // initWiFi /////////////////////////////// -void Span::setQRID(const char *id){ +Span& Span::setQRID(const char *id){ char tBuf[5]; sscanf(id,"%4[0-9A-Za-z]",tBuf); @@ -547,7 +567,8 @@ void Span::setQRID(const char *id){ if(strlen(id)==4 && strlen(tBuf)==4){ sprintf(qrID,"%s",id); } - + + return(*this); } // setQRID /////////////////////////////// @@ -555,13 +576,15 @@ void Span::setQRID(const char *id){ void Span::processSerialCommand(const char *c){ switch(c[0]){ - + case 's': { LOG0("\n*** HomeSpan Status ***\n\n"); - LOG0("IP Address: %s\n\n",WiFi.localIP().toString().c_str()); - LOG0("Accessory ID: "); + LOG0("IP Address: %s\n",WiFi.localIP().toString().c_str()); + if(webLog.isEnabled && hostName!=NULL) + LOG0("Web Logging: http://%s.local:%d%s\n",hostName,tcpPortNum,webLog.statusURL.c_str()+4); + LOG0("\nAccessory ID: "); HAPClient::charPrintRow(HAPClient::accessory.ID,17); LOG0(" LTPK: "); HAPClient::hexPrintRow(HAPClient::accessory.LTPK,32); @@ -595,18 +618,19 @@ void Span::processSerialCommand(const char *c){ } break; - case 'd': { - - TempBuffer qBuf(sprintfAttributes(NULL)+1); - sprintfAttributes(qBuf.buf); + case 'd': { - LOG0("\n*** Attributes Database: size=%d configuration=%d ***\n\n",qBuf.len()-1,hapConfig.configNumber); - prettyPrint(qBuf.buf); - LOG0("\n*** End Database ***\n\n"); + LOG0("\n*** Attributes Database ***\n\n"); + hapOut.prettyPrint(); + printfAttributes(); + size_t nBytes=hapOut.getSize(); + hapOut.flush(); + LOG0("\n\n*** End Database: size=%d configuration=%d ***\n\n",nBytes,hapConfig.configNumber); } break; case 'Q': { + char tBuf[5]; const char *s=c+1+strspn(c+1," "); sscanf(s," %4[0-9A-Za-z]",tBuf); @@ -652,52 +676,20 @@ void Span::processSerialCommand(const char *c){ break; case 'S': { - - char setupCode[10]; - struct { // temporary structure to hold SRP verification code and salt stored in NVS - uint8_t salt[16]; - uint8_t verifyCode[384]; - } verifyData; - - sscanf(c+1," %9[0-9]",setupCode); - - if(strlen(setupCode)!=8){ - LOG0("\n*** Invalid request to change Setup Code. Code must be exactly 8 digits.\n\n"); - } else - - if(!network.allowedCode(setupCode)){ - LOG0("\n*** Invalid request to change Setup Code. Code too simple.\n\n"); - } else { - - LOG0("\nGenerating SRP verification data for new Setup Code: %.3s-%.2s-%.3s ... ",setupCode,setupCode+3,setupCode+5); - HAPClient::srp.createVerifyCode(setupCode,verifyData.verifyCode,verifyData.salt); // create verification code from default Setup Code and random salt - nvs_set_blob(HAPClient::srpNVS,"VERIFYDATA",&verifyData,sizeof(verifyData)); // update data - nvs_commit(HAPClient::srpNVS); // commit to NVS - LOG0("New Code Saved!\n"); - LOG0("Setup Payload for Optional QR Code: %s\n\n",qrCode.get(atoi(setupCode),qrID,atoi(category))); - } + setPairingCode(c+1); } break; case 'U': { - HAPClient::removeControllers(); // clear all Controller data - nvs_set_blob(HAPClient::hapNVS,"CONTROLLERS",HAPClient::controllers,sizeof(HAPClient::controllers)); // update data - nvs_commit(HAPClient::hapNVS); // commit to NVS + HAPClient::controllerList.clear(); // clear all Controller data + HAPClient::saveControllers(); LOG0("\n*** HomeSpan Pairing Data DELETED ***\n\n"); - - for(int i=0;iclient){ // if slot is connected - LOG1("*** Terminating Client #"); - LOG1(i); - LOG1("\n"); - hap[i]->client.stop(); - } - } - + HAPClient::tearDown(NULL); // tear down all verified connections + LOG0("\nDEVICE NOT YET PAIRED -- PLEASE PAIR WITH HOMEKIT APP\n\n"); - mdns_service_txt_item_set("_hap","_tcp","sf","1"); // set Status Flag = 1 (Table 6-8) + mdns_service_txt_item_set("_hap","_tcp","sf","1"); // set Status Flag = 1 (Table 6-8) if(homeSpan.pairCallback) homeSpan.pairCallback(false); @@ -831,13 +823,26 @@ void Span::processSerialCommand(const char *c){ break; case 'm': { - multi_heap_info_t heapInfo; - heap_caps_get_info(&heapInfo,MALLOC_CAP_INTERNAL); - LOG0("Total Heap=%d ",heapInfo.total_free_bytes); - heap_caps_get_info(&heapInfo,MALLOC_CAP_DEFAULT); - LOG0("DRAM-Capable=%d ",heapInfo.total_free_bytes); - heap_caps_get_info(&heapInfo,MALLOC_CAP_EXEC); - LOG0("IRAM-Capable=%d\n",heapInfo.total_free_bytes); + multi_heap_info_t heapAll; + multi_heap_info_t heapInternal; + multi_heap_info_t heapPSRAM; + + heap_caps_get_info(&heapAll,MALLOC_CAP_DEFAULT); + heap_caps_get_info(&heapInternal,MALLOC_CAP_DEFAULT|MALLOC_CAP_INTERNAL); + heap_caps_get_info(&heapPSRAM,MALLOC_CAP_DEFAULT|MALLOC_CAP_SPIRAM); + + Serial.printf("\n Allocated Free Largest Low\n"); + Serial.printf(" --------- --------- --------- ---------\n"); + Serial.printf("Total Heap: %9d %9d %9d %9d\n",heapAll.total_allocated_bytes,heapAll.total_free_bytes,heapAll.largest_free_block,heapAll.minimum_free_bytes); + Serial.printf(" Internal: %9d %9d %9d %9d\n",heapInternal.total_allocated_bytes,heapInternal.total_free_bytes,heapInternal.largest_free_block,heapInternal.minimum_free_bytes); + Serial.printf(" PSRAM: %9d %9d %9d %9d\n\n",heapPSRAM.total_allocated_bytes,heapPSRAM.total_free_bytes,heapPSRAM.largest_free_block,heapPSRAM.minimum_free_bytes); + + if(getAutoPollTask()) + LOG0("Lowest stack level: %d bytes (%s)\n",uxTaskGetStackHighWaterMark(getAutoPollTask()),pcTaskGetName(getAutoPollTask())); + LOG0("Lowest stack level: %d bytes (%s)\n",uxTaskGetStackHighWaterMark(loopTaskHandle),pcTaskGetName(loopTaskHandle)); + nvs_stats_t nvs_stats; + nvs_get_stats(NULL, &nvs_stats); + LOG0("NVS Flash Partition: %d of %d records used\n\n",nvs_stats.used_entries,nvs_stats.total_entries-126); } break; @@ -848,7 +853,7 @@ void Span::processSerialCommand(const char *c){ int nErrors=0; int nWarnings=0; - unordered_set aidValues; + vector> aidValues; char pNames[][7]={"PR","PW","EV","AA","TW","HD","WR"}; for(auto acc=Accessories.begin(); acc!=Accessories.end(); acc++){ @@ -858,10 +863,10 @@ void Span::processSerialCommand(const char *c){ if(acc==Accessories.begin() && (*acc)->aid!=1) LOG0(" *** ERROR #%d! AID of first Accessory must always be 1 ***\n",++nErrors); - if(aidValues.find((*acc)->aid)!=aidValues.end()) + if(std::find(aidValues.begin(),aidValues.end(),(*acc)->aid)!=aidValues.end()) LOG0(" *** ERROR #%d! AID already in use for another Accessory ***\n",++nErrors); - aidValues.insert((*acc)->aid); + aidValues.push_back((*acc)->aid); for(auto svc=(*acc)->Services.begin(); svc!=(*acc)->Services.end(); svc++){ LOG0(" \u279f Service %s: IID=%d, %sUUID=\"%s\"\n",(*svc)->hapName,(*svc)->iid,(*svc)->isCustom?"Custom-":"",(*svc)->type); @@ -873,9 +878,7 @@ void Span::processSerialCommand(const char *c){ } else if((*acc)->aid==1) // this is an Accessory with aid=1, but it has more than just AccessoryInfo. So... isBridge=false; // ...this is not a bridge device - - unordered_set hapChar; - + for(auto chr=(*svc)->Characteristics.begin(); chr!=(*svc)->Characteristics.end(); chr++){ LOG0(" \u21e8 Characteristic %s(%s): IID=%d, %sUUID=\"%s\", %sPerms=", (*chr)->hapName,(*chr)->uvPrint((*chr)->value).c_str(),(*chr)->iid,(*chr)->isCustom?"Custom-":"",(*chr)->type,(*chr)->perms!=(*chr)->hapChar->perms?"Custom-":""); @@ -899,13 +902,13 @@ void Span::processSerialCommand(const char *c){ LOG0(" (nvs)"); LOG0("\n"); - if(!(*chr)->isCustom && !(*svc)->isCustom && (*svc)->req.find((*chr)->hapChar)==(*svc)->req.end() && (*svc)->opt.find((*chr)->hapChar)==(*svc)->opt.end()) + if(!(*chr)->isCustom && !(*svc)->isCustom && std::find((*svc)->req.begin(),(*svc)->req.end(),(*chr)->hapChar)==(*svc)->req.end() && std::find((*svc)->opt.begin(),(*svc)->opt.end(),(*chr)->hapChar)==(*svc)->opt.end()) LOG0(" *** WARNING #%d! Service does not support this Characteristic ***\n",++nWarnings); else if(invalidUUID((*chr)->type,(*chr)->isCustom)) LOG0(" *** ERROR #%d! Format of UUID is invalid ***\n",++nErrors); else - if(hapChar.find((*chr)->hapChar)!=hapChar.end()) + if(std::find_if((*svc)->Characteristics.begin(),chr,[chr](SpanCharacteristic *c)->boolean{return(c->hapChar==(*chr)->hapChar);})!=chr) LOG0(" *** ERROR #%d! Characteristic already defined for this Service ***\n",++nErrors); if((*chr)->setRangeError) @@ -914,15 +917,13 @@ void Span::processSerialCommand(const char *c){ if((*chr)->setValidValuesError) LOG0(" *** WARNING #%d! Attempt to set Custom Valid Values for this Characteristic ignored ***\n",++nWarnings); - if((*chr)->format!=STRING && ((*chr)->uvGet((*chr)->value) < (*chr)->uvGet((*chr)->minValue) || (*chr)->uvGet((*chr)->value) > (*chr)->uvGet((*chr)->maxValue))) + if((*chr)->format!=STRING && (!(((*chr)->uvGet((*chr)->value) >= (*chr)->uvGet((*chr)->minValue)) && ((*chr)->uvGet((*chr)->value) <= (*chr)->uvGet((*chr)->maxValue))))) LOG0(" *** WARNING #%d! Value of %g is out of range [%g,%g] ***\n",++nWarnings,(*chr)->uvGet((*chr)->value),(*chr)->uvGet((*chr)->minValue),(*chr)->uvGet((*chr)->maxValue)); - - hapChar.insert((*chr)->hapChar); } // Characteristics for(auto req=(*svc)->req.begin(); req!=(*svc)->req.end(); req++){ - if(hapChar.find(*req)==hapChar.end()) + if(std::find_if((*svc)->Characteristics.begin(),(*svc)->Characteristics.end(),[req](SpanCharacteristic *c)->boolean{return(c->hapChar==*req);})==(*svc)->Characteristics.end()) LOG0(" *** WARNING #%d! Required '%s' Characteristic for this Service not found ***\n",++nWarnings,(*req)->hapName); } @@ -956,15 +957,10 @@ void Span::processSerialCommand(const char *c){ if(!foundInfo) LOG0(" *** ERROR #%d! Required 'AccessoryInformation' Service not found ***\n",++nErrors); - } // Accessories - - LOG0("\nConfigured as Bridge: %s\n",isBridge?"YES":"NO"); - if(hapConfig.configNumber>0) - LOG0("Configuration Number: %d\n",hapConfig.configNumber); - LOG0("\nDatabase Validation: Warnings=%d, Errors=%d\n\n",nWarnings,nErrors); + } // Accessories char d[]="------------------------------"; - LOG0("%-30s %8s %10s %s %s %s %s %s\n","Service","UUID","AID","IID","Update","Loop","Button","Linked Services"); + LOG0("\n%-30s %8s %10s %s %s %s %s %s\n","Service","UUID","AID","IID","Update","Loop","Button","Linked Services"); LOG0("%.30s %.8s %.10s %.3s %.6s %.4s %.6s %.15s\n",d,d,d,d,d,d,d,d); for(int i=0;iServices.size();j++){ @@ -989,18 +985,23 @@ void Span::processSerialCommand(const char *c){ uint8_t channel; wifi_second_chan_t channel2; esp_wifi_get_channel(&channel,&channel2); - LOG0("\nFound %d SpanPoint Links:\n\n",SpanPoint::SpanPoints.size()); + LOG0("\nFound %d %s SpanPoint Links:\n\n",SpanPoint::SpanPoints.size(),SpanPoint::useEncryption?"encrypted":"unencrypted"); LOG0("%-17s %18s %7s %7s %7s\n","Local MAC Address","Remote MAC Address","Send","Receive","Depth"); LOG0("%.17s %.18s %.7s %.7s %.7s\n",d,d,d,d,d); for(auto it=SpanPoint::SpanPoints.begin();it!=SpanPoint::SpanPoints.end();it++) - LOG0("%-18s %02X:%02X:%02X:%02X:%02X:%02X %7d %7d %7d\n",(*it)->peerInfo.ifidx==WIFI_IF_AP?WiFi.softAPmacAddress().c_str():WiFi.macAddress().c_str(), + LOG0("%-18s %02X:%02X:%02X:%02X:%02X:%02X %7d %7d %7d %s\n",(*it)->peerInfo.ifidx==WIFI_IF_AP?WiFi.softAPmacAddress().c_str():WiFi.macAddress().c_str(), (*it)->peerInfo.peer_addr[0],(*it)->peerInfo.peer_addr[1],(*it)->peerInfo.peer_addr[2],(*it)->peerInfo.peer_addr[3],(*it)->peerInfo.peer_addr[4],(*it)->peerInfo.peer_addr[5], - (*it)->sendSize,(*it)->receiveSize,uxQueueSpacesAvailable((*it)->receiveQueue)); + (*it)->sendSize,(*it)->receiveSize,uxQueueSpacesAvailable((*it)->receiveQueue),esp_now_is_peer_exist((*it)->peerInfo.peer_addr)?"":"(max connections exceeded!)"); LOG0("\nSpanPoint using WiFi Channel %d%s\n",channel,WiFi.status()!=WL_CONNECTED?" (subject to change once WiFi connection established)":""); } - + + LOG0("\nConfigured as Bridge: %s\n",isBridge?"YES":"NO"); + if(hapConfig.configNumber>0) + LOG0("Configuration Number: %d\n",hapConfig.configNumber); + LOG0("\nDatabase Validation: Warnings=%d, Errors=%d\n",nWarnings,nErrors); LOG0("\n*** End Info ***\n\n"); } + break; case 'P': { @@ -1008,13 +1009,11 @@ void Span::processSerialCommand(const char *c){ LOG0("\n*** Pairing Data used for Cloning another Device\n\n"); size_t olen; TempBuffer tBuf(256); - mbedtls_base64_encode((uint8_t *)tBuf.buf,256,&olen,(uint8_t *)&HAPClient::accessory,sizeof(struct Accessory)); - LOG0("Accessory data: %s\n",tBuf.buf); - for(int i=0;i tBuf(200); size_t olen; - tBuf.buf[0]='\0'; + tBuf[0]='\0'; LOG0(">>> Accessory data: "); - readSerial(tBuf.buf,199); - if(strlen(tBuf.buf)==0){ + readSerial(tBuf,199); + if(strlen(tBuf)==0){ LOG0("(cancelled)\n\n"); return; } - mbedtls_base64_decode((uint8_t *)&HAPClient::accessory,sizeof(struct Accessory),&olen,(uint8_t *)tBuf.buf,strlen(tBuf.buf)); + mbedtls_base64_decode((uint8_t *)&HAPClient::accessory,sizeof(struct Accessory),&olen,(uint8_t *)tBuf.get(),strlen(tBuf)); if(olen!=sizeof(struct Accessory)){ LOG0("\n*** Error in size of Accessory data - cloning cancelled. Restarting...\n\n"); reboot(); @@ -1041,22 +1040,25 @@ void Span::processSerialCommand(const char *c){ HAPClient::charPrintRow(HAPClient::accessory.ID,17); LOG0("\n"); } + + HAPClient::controllerList.clear(); + Controller tCont; - for(int i=0;i>> Controller data: "); - readSerial(tBuf.buf,199); - if(strlen(tBuf.buf)==0){ + readSerial(tBuf,199); + if(strlen(tBuf)==0){ LOG0("(done)\n"); - while(i verifyData; // temporary storage for verification data + SRP6A *srp=new SRP6A; // create temporary instance of SRP + + LOG0("\nGenerating SRP verification data for new Setup Code: %.3s-%.2s-%.3s ... ",setupCode,setupCode+3,setupCode+5); + + srp->createVerifyCode(setupCode,verifyData); // create random salt and compute verification code from specified Setup Code + nvs_set_blob(HAPClient::srpNVS,"VERIFYDATA",verifyData,verifyData.len()); // update data + nvs_commit(HAPClient::srpNVS); // commit to NVS + + LOG0("New Code Saved!\n"); + LOG0("Setup Payload for Optional QR Code: %s\n\n",qrCode.get(atoi(setupCode),qrID,atoi(category))); + + delete srp; + return(*this); +} + +/////////////////////////////// + +Span& Span::setWifiCredentials(const char *ssid, const char *pwd){ sprintf(network.wifiData.ssid,"%.*s",MAX_SSID,ssid); sprintf(network.wifiData.pwd,"%.*s",MAX_PWD,pwd); if(wifiNVS){ // is begin() already called and wifiNVS is open nvs_set_blob(wifiNVS,"WIFIDATA",&network.wifiData,sizeof(network.wifiData)); // update data nvs_commit(wifiNVS); // commit to NVS } + + return(*this); } /////////////////////////////// -int Span::sprintfAttributes(char *cBuf, int flags){ +void Span::printfAttributes(int flags){ - int nBytes=0; - - nBytes+=snprintf(cBuf,cBuf?64:0,"{\"accessories\":["); + hapOut << "{\"accessories\":["; for(int i=0;isprintfAttributes(cBuf?(cBuf+nBytes):NULL,flags); + Accessories[i]->printfAttributes(flags); if(i+1uvSet(pObj[j].characteristic->value,pObj[j].characteristic->newValue); // update characteristic value with new value if(pObj[j].characteristic->nvsKey){ // if storage key found if(pObj[j].characteristic->format!=FORMAT::STRING && pObj[j].characteristic->format!=FORMAT::DATA) - nvs_set_blob(charNVS,pObj[j].characteristic->nvsKey,&(pObj[j].characteristic->value),sizeof(pObj[j].characteristic->value)); // store data + nvs_set_u64(charNVS,pObj[j].characteristic->nvsKey,pObj[j].characteristic->value.UINT64); // store data as uint64_t regardless of actual type (it will be read correctly when access through uvGet()) else nvs_set_str(charNVS,pObj[j].characteristic->nvsKey,pObj[j].characteristic->value.STRING); // store data nvs_commit(charNVS); @@ -1465,125 +1459,108 @@ void Span::clearNotify(int slotNum){ /////////////////////////////// -int Span::sprintfNotify(SpanBuf *pObj, int nObj, char *cBuf, int conNum){ +void Span::printfNotify(SpanBuf *pObj, int nObj, int conNum){ - int nChars=0; boolean notifyFlag=false; - nChars+=snprintf(cBuf,cBuf?64:0,"{\"characteristics\":["); - - for(int i=0;iev[conNum]){ // if notifications requested for this characteristic by specified connection number - - if(notifyFlag) // already printed at least one other characteristic - nChars+=snprintf(cBuf?(cBuf+nChars):NULL,cBuf?64:0,","); // add preceeding comma before printing next characteristic + if(pObj[i].characteristic->ev[conNum]){ // if notifications requested for this characteristic by specified connection number + + if(!notifyFlag) // this is first notification for any characteristic + hapOut << "{\"characteristics\":["; // print start of JSON array + else // else already printed at least one other characteristic + hapOut << ","; // add preceeding comma before printing this characteristic - nChars+=pObj[i].characteristic->sprintfAttributes(cBuf?(cBuf+nChars):NULL,GET_VALUE|GET_AID|GET_NV); // get JSON attributes for characteristic - notifyFlag=true; - - } // notification requested - } // characteristic updated - } // loop over all objects - - nChars+=snprintf(cBuf?(cBuf+nChars):NULL,cBuf?64:0,"]}"); - - return(notifyFlag?nChars:0); // if notifyFlag is not set, return 0, else return number of characters printed to cBuf -} - -/////////////////////////////// - -int Span::sprintfAttributes(SpanBuf *pObj, int nObj, char *cBuf){ - - int nChars=0; - - nChars+=snprintf(cBuf,cBuf?64:0,"{\"characteristics\":["); - - for(int i=0;iprintfAttributes(GET_VALUE|GET_AID|GET_NV); // print JSON attributes for this characteristic + notifyFlag=true; + } + } } - nChars+=snprintf(cBuf?(cBuf+nChars):NULL,cBuf?64:0,"]}"); - - return(nChars); + if(notifyFlag) + hapOut << "]}"; } /////////////////////////////// -int Span::sprintfAttributes(char **ids, int numIDs, int flags, char *cBuf){ +void Span::printfAttributes(SpanBuf *pObj, int nObj){ + + hapOut << "{\"characteristics\":["; + + for(int i=0;iperms&PERMS::PR){ // if permissions allow reading - status[i]=StatusCode::OK; // always set status to OK (since no actual reading of device is needed) + if(Characteristics[i]){ // if found + if(Characteristics[i]->perms&PERMS::PR){ // if permissions allow reading + status[i]=StatusCode::OK; // always set status to OK (since no actual reading of device is needed) } else { - Characteristics[i]=NULL; + Characteristics[i]=NULL; // set to NULL to trigger not-found in Pass 2 below status[i]=StatusCode::WriteOnly; - sFlag=true; // set flag indicating there was an error + flags|=GET_STATUS; // update flags to require status attribute for all characteristics } } else { status[i]=StatusCode::UnknownResource; - sFlag=true; // set flag indicating there was an error + flags|=GET_STATUS; // update flags to require status attribute for all characteristics } } - nChars+=snprintf(cBuf,cBuf?64:0,"{\"characteristics\":["); + hapOut << "{\"characteristics\":["; - for(int i=0;isprintfAttributes(cBuf?(cBuf+nChars):NULL,flags); // get JSON attributes for characteristic - else{ - sscanf(ids[i],"%u.%d",&aid,&iid); // parse aid and iid - nChars+=snprintf(cBuf?(cBuf+nChars):NULL,cBuf?64:0,"{\"iid\":%d,\"aid\":%u}",iid,aid); // else create JSON attributes based on requested aid/iid + if(Characteristics[i]) // if found + Characteristics[i]->printfAttributes(flags); // get JSON attributes for characteristic (may or may not include status=0 attribute) + else{ // else create JSON status attribute based on requested aid/iid + sscanf(ids[i],"%u.%d",&aid,&iid); + hapOut << "{\"iid\":" << iid << ",\"aid\":" << aid << ",\"status\":" << (int)status[i] << "}"; } - - if(sFlag){ // status flag is needed - overlay at end - nChars--; - nChars+=snprintf(cBuf?(cBuf+nChars):NULL,cBuf?64:0,",\"status\":%d}",(int)status[i]); - } - + if(i+1 tBuf(sprintfAttributes(NULL,GET_META|GET_PERMS|GET_TYPE|GET_DESC)+1); - sprintfAttributes(tBuf.buf,GET_META|GET_PERMS|GET_TYPE|GET_DESC); - mbedtls_sha512_ret((uint8_t *)tBuf.buf,tBuf.len(),tHash,1); // create SHA-384 hash of JSON (can be any hash - just looking for a unique key) + printfAttributes(GET_META|GET_PERMS|GET_TYPE|GET_DESC); // stream attributes database, which automtically produces a SHA-384 hash + hapOut.flush(); boolean changed=false; - if(memcmp(tHash,hapConfig.hashCode,48)){ // if hash code of current HAP database does not match stored hash code - memcpy(hapConfig.hashCode,tHash,48); // update stored hash code - hapConfig.configNumber++; // increment configuration number - if(hapConfig.configNumber==65536) // reached max value - hapConfig.configNumber=1; // reset to 1 + if(memcmp(hapOut.getHash(),hapConfig.hashCode,48)){ // if hash code of current HAP database does not match stored hash code + memcpy(hapConfig.hashCode,hapOut.getHash(),48); // update stored hash code + hapConfig.configNumber++; // increment configuration number + if(hapConfig.configNumber==65536) // reached max value + hapConfig.configNumber=1; // reset to 1 nvs_set_blob(HAPClient::hapNVS,"HAPHASH",&hapConfig,sizeof(hapConfig)); // update data nvs_commit(HAPClient::hapNVS); // commit to NVS @@ -1596,6 +1573,11 @@ boolean Span::updateDatabase(boolean updateMDNS){ } } + nvs_stats_t nvs_stats; + nvs_get_stats(NULL, &nvs_stats); + if(nvs_stats.free_entries<=130) + LOG0("\n*** WARNING: NVS is running low on space. Try erasing with 'E'. If that fails, increase size of NVS partition or reduce NVS usage.\n\n"); + Loops.clear(); for(auto acc=Accessories.begin(); acc!=Accessories.end(); acc++){ // identify all services with over-ridden loop() methods @@ -1651,20 +1633,17 @@ SpanAccessory::~SpanAccessory(){ /////////////////////////////// -int SpanAccessory::sprintfAttributes(char *cBuf, int flags){ - int nBytes=0; +void SpanAccessory::printfAttributes(int flags){ - nBytes+=snprintf(cBuf,cBuf?64:0,"{\"aid\":%u,\"services\":[",aid); + hapOut << "{\"aid\":" << aid << ",\"services\":["; for(int i=0;isprintfAttributes(cBuf?(cBuf+nBytes):NULL,flags); + Services[i]->printfAttributes(flags); if(i+1iid); + hapOut << linkedServices[i]->iid; if(i+1sprintfAttributes(cBuf?(cBuf+nBytes):NULL,flags); + Characteristics[i]->printfAttributes(flags); if(i+1Services.back(); aid=homeSpan.Accessories.back()->aid; - ev=(boolean *)calloc(homeSpan.maxConnections,sizeof(boolean)); + ev=(boolean *)HS_CALLOC(homeSpan.maxConnections,sizeof(boolean)); } /////////////////////////////// @@ -1830,72 +1806,71 @@ SpanCharacteristic::~SpanCharacteristic(){ /////////////////////////////// -int SpanCharacteristic::sprintfAttributes(char *cBuf, int flags){ - int nBytes=0; +void SpanCharacteristic::printfAttributes(int flags){ const char permCodes[][7]={"pr","pw","ev","aa","tw","hd","wr"}; - const char formatCodes[][9]={"bool","uint8","uint16","uint32","uint64","int","float","string","data"}; - nBytes+=snprintf(cBuf,cBuf?64:0,"{\"iid\":%d",iid); + hapOut << "{\"iid\":" << iid; - if(flags&GET_TYPE) - nBytes+=snprintf(cBuf?(cBuf+nBytes):NULL,cBuf?64:0,",\"type\":\"%s\"",type); + if(flags&GET_TYPE) + hapOut << ",\"type\":\"" << type << "\""; if((perms&PR) && (flags&GET_VALUE)){ if(perms&NV && !(flags&GET_NV)) - nBytes+=snprintf(cBuf?(cBuf+nBytes):NULL,cBuf?64:0,",\"value\":null"); + hapOut << ",\"value\":null"; else - nBytes+=snprintf(cBuf?(cBuf+nBytes):NULL,cBuf?64:0,",\"value\":%s",uvPrint(value).c_str()); + hapOut << ",\"value\":" << uvPrint(value).c_str(); } if(flags&GET_META){ - nBytes+=snprintf(cBuf?(cBuf+nBytes):NULL,cBuf?64:0,",\"format\":\"%s\"",formatCodes[format]); + hapOut << ",\"format\":\"" << formatCodes[format] << "\""; if(customRange && (flags&GET_META)){ - nBytes+=snprintf(cBuf?(cBuf+nBytes):NULL,cBuf?128:0,",\"minValue\":%s,\"maxValue\":%s",uvPrint(minValue).c_str(),uvPrint(maxValue).c_str()); + hapOut << ",\"minValue\":" << uvPrint(minValue).c_str() << ",\"maxValue\":" << uvPrint(maxValue).c_str(); if(uvGet(stepValue)>0) - nBytes+=snprintf(cBuf?(cBuf+nBytes):NULL,cBuf?128:0,",\"minStep\":%s",uvPrint(stepValue).c_str()); + hapOut << ",\"minStep\":" << uvPrint(stepValue).c_str(); } if(unit){ if(strlen(unit)>0) - nBytes+=snprintf(cBuf?(cBuf+nBytes):NULL,cBuf?128:0,",\"unit\":\"%s\"",unit); + hapOut << ",\"unit\":\"" << unit << "\""; else - nBytes+=snprintf(cBuf?(cBuf+nBytes):NULL,cBuf?128:0,",\"unit\":null"); + hapOut << ",\"unit\":null"; } if(validValues){ - nBytes+=snprintf(cBuf?(cBuf+nBytes):NULL,cBuf?128:0,",\"valid-values\":%s",validValues); + hapOut << ",\"valid-values\":" << validValues; } } if(desc && (flags&GET_DESC)){ - nBytes+=snprintf(cBuf?(cBuf+nBytes):NULL,cBuf?128:0,",\"description\":\"%s\"",desc); + hapOut << ",\"description\":\"" << desc << "\""; } if(flags&GET_PERMS){ - nBytes+=snprintf(cBuf?(cBuf+nBytes):NULL,cBuf?64:0,",\"perms\":["); + hapOut << ",\"perms\":["; for(int i=0;i<7;i++){ if(perms&(1<=(1<<(i+1))) - nBytes+=snprintf(cBuf?(cBuf+nBytes):NULL,cBuf?64:0,","); + hapOut << ","; } } - nBytes+=snprintf(cBuf?(cBuf+nBytes):NULL,cBuf?64:0,"]"); + hapOut << "]"; } if(flags&GET_AID) - nBytes+=snprintf(cBuf?(cBuf+nBytes):NULL,cBuf?64:0,",\"aid\":%u",aid); + hapOut << ",\"aid\":" << aid; if(flags&GET_EV) - nBytes+=snprintf(cBuf?(cBuf+nBytes):NULL,cBuf?64:0,",\"ev\":%s",ev[HAPClient::conNum]?"true":"false"); + hapOut << ",\"ev\":" << (ev[HAPClient::conNum]?"true":"false"); - nBytes+=snprintf(cBuf?(cBuf+nBytes):NULL,cBuf?64:0,"}"); + if(flags&GET_STATUS) + hapOut << ",\"status\":0"; - return(nBytes); + hapOut << "}"; } /////////////////////////////// @@ -2044,7 +2019,7 @@ SpanCharacteristic *SpanCharacteristic::setValidValues(int n, ...){ va_end(vl); s+="]"; - validValues=(char *)realloc(validValues, strlen(s.c_str()) + 1); + validValues=(char *)HS_REALLOC(validValues, strlen(s.c_str()) + 1); strcpy(validValues,s.c_str()); return(this); @@ -2124,12 +2099,14 @@ SpanUserCommand::SpanUserCommand(char c, const char *s, void (*f)(const char *, /////////////////////////////// void SpanWebLog::init(uint16_t maxEntries, const char *serv, const char *tz, const char *url){ - isEnabled=true; this->maxEntries=maxEntries; timeServer=serv; timeZone=tz; - statusURL="GET /" + String(url) + " "; - log = (log_t *)calloc(maxEntries,sizeof(log_t)); + if(url){ + statusURL="GET /" + String(url) + " "; + isEnabled=true; + } + log = (log_t *)HS_CALLOC(maxEntries,sizeof(log_t)); if(timeServer) homeSpan.reserveSocketConnections(1); } @@ -2175,7 +2152,7 @@ void SpanWebLog::vLog(boolean sysMsg, const char *fmt, va_list ap){ else log[index].clockTime.tm_year=0; - log[index].message=(char *)realloc(log[index].message, strlen(buf) + 1); + log[index].message=(char *)HS_REALLOC(log[index].message, strlen(buf) + 1); strcpy(log[index].message, buf); log[index].clientIP=homeSpan.lastClientIP; @@ -2305,7 +2282,7 @@ SpanPoint::SpanPoint(const char *macAddress, int sendSize, int receiveSize, int peerInfo.ifidx=useAPaddress?WIFI_IF_AP:WIFI_IF_STA; // specify interface as either STA or AP - peerInfo.encrypt=true; // turn on encryption for this peer + peerInfo.encrypt=useEncryption; // set encryption for this peer memcpy(peerInfo.lmk, lmk, 16); // set local key esp_now_add_peer(&peerInfo); // add peer to ESP-NOW @@ -2469,7 +2446,8 @@ void SpanPoint::dataReceived(const uint8_t *mac, const uint8_t *incomingData, in uint8_t SpanPoint::lmk[16]; boolean SpanPoint::initialized=false; boolean SpanPoint::isHub=false; -vector SpanPoint::SpanPoints; +boolean SpanPoint::useEncryption=true; +vector> SpanPoint::SpanPoints; uint16_t SpanPoint::channelMask=0x3FFE; QueueHandle_t SpanPoint::statusQueue; nvs_handle SpanPoint::pointNVS; diff --git a/src/HomeSpan.h b/src/HomeSpan.h index 5a22b59..201bcdd 100644 --- a/src/HomeSpan.h +++ b/src/HomeSpan.h @@ -1,7 +1,7 @@ /********************************************************************************* * MIT License * - * Copyright (c) 2020-2023 Gregg E. Berman + * Copyright (c) 2020-2024 Gregg E. Berman * * https://github.com/HomeSpan/HomeSpan * @@ -37,14 +37,18 @@ #include #include #include -#include +#include #include #include #include #include -#include "extras/Blinker.h" -#include "extras/Pixel.h" +#include "src/extras/Blinker.h" +#include "src/extras/Pixel.h" +#include "src/extras/RFControl.h" +#include "src/extras/PwmPin.h" +#include "src/extras/StepperControl.h" + #include "Settings.h" #include "Utils.h" #include "Network.h" @@ -54,7 +58,7 @@ using std::vector; using std::unordered_map; -using std::unordered_set; +using std::list; enum { GET_AID=1, @@ -64,7 +68,8 @@ enum { GET_EV=16, GET_DESC=32, GET_NV=64, - GET_VALUE=128 + GET_VALUE=128, + GET_STATUS=256 }; /////////////////////////////// @@ -143,7 +148,7 @@ struct SpanWebLog{ // optional web status/log data boolean isEnabled=false; // flag to inidicate WebLog has been enabled uint16_t maxEntries=0; // max number of log entries; int nEntries=0; // total cumulative number of log entries - const char *timeServer; // optional time server to use for acquiring clock time + const char *timeServer=NULL; // optional time server to use for acquiring clock time const char *timeZone; // optional time-zone specification boolean timeInit=false; // flag to indicate time has been initialized char bootTime[33]="Unknown"; // boot time @@ -202,7 +207,7 @@ class Span{ 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 *hostName; // full host name of this device - constructed from hostNameBase and 6-byte AccessoryID + char *hostName=NULL; // derived full hostname const 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() @@ -212,11 +217,13 @@ class Span{ 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 storaget of OTA 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) boolean serialInputDisabled=false; // flag indiating that serial input is disabled + 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 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 @@ -230,11 +237,14 @@ class Span{ 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 - void (*wifiCallback)()=NULL; // optional callback function to invoke once WiFi connectivity is established + void (*wifiCallback)()=NULL; // optional callback function to invoke once WiFi connectivity is initially established + void (*wifiCallbackAll)(int)=NULL; // optional callback function to invoke every time WiFi connectivity is established or re-established + void (*weblogCallback)(String &)=NULL; // optional callback function to invoke after header table in Web Log is produced void (*pairCallback)(boolean isPaired)=NULL; // optional callback function to invoke when pairing is established (true) or lost (false) boolean autoStartAPEnabled=false; // enables auto start-up of Access Point when WiFi Credentials not found 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 WiFiServer *hapServer; // pointer to the HAP Server connection Blinker *statusLED; // indicates HomeSpan status @@ -243,13 +253,15 @@ class Span{ Network network; // configures WiFi and Setup Code via either serial monitor or temporary Access Point SpanWebLog webLog; // optional web status/log TaskHandle_t pollTaskHandle = NULL; // optional task handle to use for poll() function + TaskHandle_t loopTaskHandle; // Arduino Loop Task handle + boolean verboseWifiReconnect = true; // set to false to not print WiFi reconnect attempts messages 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 Accessories; // vector of pointers to all Accessories - vector Loops; // vector of pointer to all Services that have over-ridden loop() methods - vector Notifications; // vector of SpanBuf objects that store info for Characteristics that are updated with setVal() and require a Notification Event - vector PushButtons; // vector of pointer to all PushButtons + vector> Accessories; // vector of pointers to all Accessories + vector> Loops; // vector of pointer to all Services that have over-ridden loop() methods + vector> Notifications; // vector of SpanBuf objects that store info for Characteristics that are updated with setVal() and require a Notification Event + vector> PushButtons; // vector of pointer to all PushButtons unordered_map TimedWrites; // map of timed-write PIDs and Alarm Times (based on TTLs) unordered_map UserCommands; // map of pointers to all UserCommands @@ -261,16 +273,15 @@ class Span{ void resetStatus(); // resets statusLED and calls statusCallback based on current HomeSpan status void reboot(); // reboots device - int sprintfAttributes(char *cBuf, int flags=GET_VALUE|GET_META|GET_PERMS|GET_TYPE|GET_DESC); // prints Attributes JSON database into buf, unless buf=NULL; return number of characters printed, excluding null terminator + void printfAttributes(int flags=GET_VALUE|GET_META|GET_PERMS|GET_TYPE|GET_DESC); // writes Attributes JSON database to hapOut stream - void prettyPrint(char *buf, int nsp=2, int minLogLevel=0); // print arbitrary JSON from buf to serial monitor, formatted with indentions of 'nsp' spaces, subject to specified minimum log level SpanCharacteristic *find(uint32_t aid, int 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 - int sprintfAttributes(SpanBuf *pObj, int nObj, char *cBuf); // prints SpanBuf object into buf, unless buf=NULL; return number of characters printed, excluding null terminator, even if buf=NULL - int sprintfAttributes(char **ids, int numIDs, int flags, char *cBuf); // prints accessory.characteristic ids into buf, unless buf=NULL; return number of characters printed, excluding null terminator, even if buf=NULL + 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 - int sprintfNotify(SpanBuf *pObj, int nObj, char *cBuf, int conNum); // prints notification JSON into buf based on SpanBuf objects and specified connection number + void printfNotify(SpanBuf *pObj, int nObj, int conNum); // writes notification JSON to hapOut stream based on SpanBuf objects and specified connection number static boolean invalidUUID(const char *uuid, boolean isCustom){ int x=0; @@ -291,49 +302,55 @@ class Span{ boolean updateDatabase(boolean updateMDNS=true); // updates HAP Configuration Number and Loop vector; if updateMDNS=true and config number has changed, re-broadcasts MDNS 'c#' record; returns true if config number changed boolean deleteAccessory(uint32_t aid); // deletes Accessory with matching aid; returns true if found, else returns false - void setControlPin(uint8_t pin){controlButton=new PushButton(pin);} // sets Control Pin - void setStatusPin(uint8_t pin){statusDevice=new GenericLED(pin);} // sets Status Device to a simple LED on specified pin - void setStatusAutoOff(uint16_t duration){autoOffLED=duration;} // sets Status LED auto off (seconds) - int getStatusPin(){return(statusLED->getPin());} // get Status Pin (getPin will return -1 if underlying statusDevice is undefined) - int getControlPin(){return(controlButton?controlButton->getPin():-1);} // get Control Pin (returns -1 if undefined) - - void setStatusPixel(uint8_t pin,float h=0,float s=100,float v=100){ // sets Status Device to an RGB Pixel on specified pin + Span& setControlPin(uint8_t pin, PushButton::triggerType_t triggerType=PushButton::TRIGGER_ON_LOW){ // sets Control Pin, with optional trigger type + controlButton=new PushButton(pin, triggerType); + return(*this); + } + + int getControlPin(){return(controlButton?controlButton->getPin():-1);} // get Control Pin (returns -1 if undefined) + + Span& setStatusPin(uint8_t pin){statusDevice=new GenericLED(pin);return(*this);} // sets Status Device to a simple LED on specified pin + Span& setStatusPixel(uint8_t pin,float h=0,float s=100,float v=100){ // sets Status Device to an RGB Pixel on specified pin statusDevice=((new Pixel(pin))->setOnColor(Pixel::HSV(h,s,v))); + return(*this); } - - void setStatusDevice(Blinkable *sDev){statusDevice=sDev;} - void refreshStatusDevice(){if(statusLED)statusLED->refresh();} - - void setApSSID(const char *ssid){network.apSSID=ssid;} // sets Access Point SSID - void setApPassword(const char *pwd){network.apPassword=pwd;} // sets Access Point Password - void setApTimeout(uint16_t nSec){network.lifetime=nSec*1000;} // sets Access Point Timeout (seconds) - void setCommandTimeout(uint16_t nSec){comModeLife=nSec*1000;} // sets Command Mode Timeout (seconds) - void setLogLevel(int level){logLevel=level;} // sets Log Level for log messages (0=baseline, 1=intermediate, 2=all, -1=disable all serial input/output) - int getLogLevel(){return(logLevel);} // get Log Level - void setSerialInputDisable(boolean val){serialInputDisabled=val;} // 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 - void reserveSocketConnections(uint8_t n){maxConnections-=n;} // reserves n socket connections *not* to be used for HAP - void setHostNameSuffix(const char *suffix){hostNameSuffix=suffix;} // sets the hostName suffix to be used instead of the 6-byte AccessoryID - void setPortNum(uint16_t port){tcpPortNum=port;} // sets the TCP port number to use for communications between HomeKit and HomeSpan - void setQRID(const char *id); // sets the Setup ID for optional pairing with a QR Code - void setSketchVersion(const char *sVer){sketchVersion=sVer;} // set optional sketch version number - const char *getSketchVersion(){return sketchVersion;} // get sketch version number - void setWifiCallback(void (*f)()){wifiCallback=f;} // sets an optional user-defined function to call once WiFi connectivity is established - void setPairCallback(void (*f)(boolean isPaired)){pairCallback=f;} // sets an optional user-defined function to call when Pairing is established (true) or lost (false) - void setApFunction(void (*f)()){apFunction=f;} // sets an optional user-defined function to call when activating the WiFi Access Point - void enableAutoStartAP(){autoStartAPEnabled=true;} // enables auto start-up of Access Point when WiFi Credentials not found - void setWifiCredentials(const char *ssid, const char *pwd); // sets WiFi Credentials - void setStatusCallback(void (*f)(HS_STATUS status)){statusCallback=f;} // 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& setStatusDevice(Blinkable *sDev){statusDevice=sDev;return(*this);} // sets Status Device to a generic Blinkable object - void setPairingCode(const char *s){sprintf(pairingCodeCommand,"S %9s",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& setStatusAutoOff(uint16_t duration){autoOffLED=duration;return(*this);} // sets Status LED auto off (seconds) + int getStatusPin(){return(statusLED->getPin());} // get Status Pin (returns -1 if undefined) + void refreshStatusDevice(){if(statusLED)statusLED->refresh();} // refreshes state of Status LED + + Span& setApSSID(const char *ssid){network.apSSID=ssid;return(*this);} // sets Access Point SSID + Span& setApPassword(const char *pwd){network.apPassword=pwd;return(*this);} // sets Access Point Password + Span& setApTimeout(uint16_t nSec){network.lifetime=nSec*1000;return(*this);} // sets Access Point Timeout (seconds) + Span& setCommandTimeout(uint16_t nSec){comModeLife=nSec*1000;return(*this);} // sets Command Mode Timeout (seconds) + Span& setLogLevel(int level){logLevel=level;return(*this);} // sets Log Level for log messages (0=baseline, 1=intermediate, 2=all, -1=disable all serial input/output) + 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 + const char *getSketchVersion(){return sketchVersion;} // get sketch version number + Span& setWifiCallback(void (*f)()){wifiCallback=f;return(*this);} // sets an optional user-defined function to call once WiFi connectivity is initially established + Span& setWifiCallbackAll(void (*f)(int)){wifiCallbackAll=f;return(*this);} // sets an optional user-defined function to call every time WiFi connectivity is established or re-established + Span& setPairCallback(void (*f)(boolean isPaired)){pairCallback=f;return(*this);} // sets an optional user-defined function to call when Pairing is established (true) or lost (false) + Span& setApFunction(void (*f)()){apFunction=f;return(*this);} // sets an optional user-defined function to call when activating the WiFi Access Point + Span& enableAutoStartAP(){autoStartAPEnabled=true;return(*this);} // enables auto start-up of Access Point when WiFi Credentials not found + 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 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) - void enableWebLog(uint16_t maxEntries=0, const char *serv=NULL, const char *tz="UTC", const char *url=DEFAULT_WEBLOG_URL){ // enable Web Logging + Span& enableWebLog(uint16_t maxEntries=0, const char *serv=NULL, const char *tz="UTC", const char *url=DEFAULT_WEBLOG_URL){ // enable Web Logging webLog.init(maxEntries, serv, tz, url); + return(*this); } void addWebLog(boolean sysMsg, const char *fmt, ...){ // add Web Log entry @@ -343,14 +360,28 @@ class Span{ va_end(ap); } - void setWebLogCSS(const char *css){webLog.css="\n" + String(css) + "\n";} + Span& setWebLogCSS(const char *css){webLog.css="\n" + String(css) + "\n";return(*this);} + Span& setWebLogCallback(void (*f)(String &)){weblogCallback=f;return(*this);} + void getWebLog(void (*f)(const char *, void *), void *); + + Span& setVerboseWifiReconnect(bool verbose=true){verboseWifiReconnect=verbose;return(*this);} + + Span& setRebootCallback(void (*f)(uint8_t),uint32_t t=DEFAULT_REBOOT_CALLBACK_TIME){rebootCallback=f;rebootCallbackTime=t;return(*this);} void autoPoll(uint32_t stackSize=8192, uint32_t priority=1, uint32_t cpu=0){ // start pollTask() - xTaskCreateUniversal([](void *parms){for(;;)homeSpan.pollTask();}, "pollTask", stackSize, NULL, priority, &pollTaskHandle, cpu); + xTaskCreateUniversal([](void *parms){ + for(;;){ + homeSpan.pollTask(); + vTaskDelay(5); + } + }, + "pollTask", stackSize, NULL, priority, &pollTaskHandle, cpu); LOG0("\n*** AutoPolling Task started with priority=%d\n\n",uxTaskPriorityGet(pollTaskHandle)); } - void setTimeServerTimeout(uint32_t tSec){webLog.waitTime=tSec*1000;} // sets wait time (in seconds) for optional web log time server to connect + 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 @@ -368,17 +399,18 @@ class SpanAccessory{ 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 Services; // vector of pointers to all Services in this Accessory + vector> Services; // vector of pointers to all Services in this Accessory - int sprintfAttributes(char *cBuf, int flags); // prints Accessory JSON database into buf, unless buf=NULL; return number of characters printed, excluding null terminator, even if buf=NULL + void printfAttributes(int flags); // writes Accessory JSON to hapOut stream protected: ~SpanAccessory(); // destructor public: - - SpanAccessory(uint32_t aid=0); // constructor + + void *operator new(size_t size){return(HS_MALLOC(size));} // override new operator to use PSRAM when available + SpanAccessory(uint32_t aid=0); // constructor }; /////////////////////////////// @@ -395,26 +427,27 @@ class SpanService{ const char *hapName; // HAP Name boolean hidden=false; // optional property indicating service is hidden boolean primary=false; // optional property indicating service is primary - vector Characteristics; // vector of pointers to all Characteristics in this Service - vector linkedServices; // vector of pointers to any optional linked Services + vector> Characteristics; // vector of pointers to all Characteristics in this Service + vector> 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 - int sprintfAttributes(char *cBuf, int flags); // prints Service JSON records into buf; return number of characters printed, excluding null terminator + void printfAttributes(int flags); // writes Service JSON to hapOut stream protected: virtual ~SpanService(); // destructor - unordered_set req; // unordered set of pointers to all required HAP Characteristic Types for this Service - unordered_set opt; // unordered set of pointers to all optional HAP Characteristic Types for this Service + vector> req; // vector of pointers to all required HAP Characteristic Types for this Service + vector> 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 getLinks(){return(linkedServices);} // returns linkedServices vector for use as range in "for-each" loops + vector> getLinks(){return(linkedServices);} // returns linkedServices vector for use as range in "for-each" loops 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 @@ -465,12 +498,12 @@ class SpanCharacteristic{ 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 - - int sprintfAttributes(char *cBuf, int flags); // prints Characteristic JSON records into buf, according to flags mask; return number of characters printed, excluding null terminator + + 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.) String uvPrint(UVal &u){ - char c[64]; + char c[67]; // space for 64 characters + surrounding quotes + terminating null switch(format){ case FORMAT::BOOL: return(String(u.BOOL)); @@ -490,7 +523,7 @@ class SpanCharacteristic{ return(String(c)); case FORMAT::STRING: case FORMAT::DATA: - sprintf(c,"\"%s\"",u.STRING); + sprintf(c,"\"%.64s\"",u.STRING); // Truncating string to 64 chars return(String(c)); } // switch return(String()); // included to prevent compiler warnings @@ -504,7 +537,7 @@ class SpanCharacteristic{ } void uvSet(UVal &u, const char *val){ - u.STRING = (char *)realloc(u.STRING, strlen(val) + 1); + u.STRING = (char *)HS_REALLOC(u.STRING, strlen(val) + 1); strcpy(u.STRING, val); } @@ -558,7 +591,7 @@ class SpanCharacteristic{ case FORMAT::DATA: break; } - return(0); // included to prevent compiler warnings + return((T)0); // included to prevent compiler warnings } protected: @@ -570,28 +603,24 @@ class SpanCharacteristic{ uvSet(value,val); if(nvsStore){ - nvsKey=(char *)malloc(16); + nvsKey=(char *)HS_MALLOC(16); uint16_t t; sscanf(type,"%hx",&t); sprintf(nvsKey,"%04X%08X%03X",t,aid,iid&0xFFF); size_t len; if(format!=FORMAT::STRING && format!=FORMAT::DATA){ - if(!nvs_get_blob(homeSpan.charNVS,nvsKey,NULL,&len)){ - nvs_get_blob(homeSpan.charNVS,nvsKey,&value,&len); - } - else { - nvs_set_blob(homeSpan.charNVS,nvsKey,&value,sizeof(UVal)); // store data - nvs_commit(homeSpan.charNVS); // commit to NVS + 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 } } else { if(!nvs_get_str(homeSpan.charNVS,nvsKey,NULL,&len)){ - char c[len]; - nvs_get_str(homeSpan.charNVS,nvsKey,c,&len); - uvSet(value,(const char *)c); + value.STRING = (char *)HS_REALLOC(value.STRING,len); + nvs_get_str(homeSpan.charNVS,nvsKey,value.STRING,&len); } else { - nvs_set_str(homeSpan.charNVS,nvsKey,value.STRING); // store string data + nvs_set_str(homeSpan.charNVS,nvsKey,value.STRING); // store string data nvs_commit(homeSpan.charNVS); // commit to NVS } } @@ -609,6 +638,7 @@ class SpanCharacteristic{ 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 template T getVal(){ @@ -649,7 +679,7 @@ class SpanCharacteristic{ sb.characteristic=this; // set characteristic sb.status=StatusCode::OK; // set status char dummy[]=""; - sb.val=dummy; // set dummy "val" so that sprintfNotify knows to consider this "update" + 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){ @@ -710,8 +740,8 @@ class SpanCharacteristic{ 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 tBuf(olen); // create temporary string buffer, with room for trailing null - mbedtls_base64_encode((uint8_t*)tBuf.buf,olen,&olen,data,len ); // encode data into string buf - setString(tBuf.buf); // call setString to continue processing as if characteristic was a string + 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 void setVal(T val, boolean notify=true){ @@ -721,8 +751,8 @@ class SpanCharacteristic{ return; } - if(val < uvGet(minValue) || val > uvGet(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-reponsive!\n\n", + if(!((val >= uvGet(minValue)) && (val <= uvGet(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(minValue),uvGet(maxValue)); } @@ -736,11 +766,11 @@ class SpanCharacteristic{ sb.characteristic=this; // set characteristic sb.status=StatusCode::OK; // set status char dummy[]=""; - sb.val=dummy; // set dummy "val" so that sprintfNotify knows to consider this "update" + 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_blob(homeSpan.charNVS,nvsKey,&value,sizeof(UVal)); // store data + 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); } } @@ -782,13 +812,13 @@ class SpanCharacteristic{ } SpanCharacteristic *setDescription(const char *c){ - desc = (char *)realloc(desc, strlen(c) + 1); + desc = (char *)HS_REALLOC(desc, strlen(c) + 1); strcpy(desc, c); return(this); } SpanCharacteristic *setUnit(const char *c){ - unit = (char *)realloc(unit, strlen(c) + 1); + unit = (char *)HS_REALLOC(unit, strlen(c) + 1); strcpy(unit, c); return(this); } @@ -825,15 +855,6 @@ class SpanButton : public PushButton { buttonType_t buttonType=HS_BUTTON; // type of SpanButton public: - - static constexpr triggerType_t TRIGGER_ON_LOW=PushButton::TRIGGER_ON_LOW; - static constexpr triggerType_t TRIGGER_ON_HIGH=PushButton::TRIGGER_ON_HIGH; - -#if SOC_TOUCH_SENSOR_NUM > 0 - static constexpr triggerType_t TRIGGER_ON_TOUCH=PushButton::TRIGGER_ON_TOUCH; - static void setTouchCycles(uint16_t measureTime, uint16_t sleepTime){PushButton::setTouchCycles(measureTime,sleepTime);} - static void setTouchThreshold(touch_value_t thresh){PushButton::setTouchThreshold(thresh);} -#endif SpanButton(int pin, uint16_t longTime=2000, uint16_t singleTime=5, uint16_t doubleTime=200, triggerType_t triggerType=TRIGGER_ON_LOW); SpanButton(int pin, triggerType_t triggerType, uint16_t longTime=2000, uint16_t singleTime=5, uint16_t doubleTime=200) : SpanButton(pin,longTime,singleTime,doubleTime,triggerType){}; @@ -882,7 +903,8 @@ class SpanPoint { static uint8_t lmk[16]; static boolean initialized; static boolean isHub; - static vector SpanPoints; + static boolean useEncryption; + static vector> SpanPoints; static uint16_t channelMask; // channel mask (only used for remote devices) static QueueHandle_t statusQueue; // queue for communication between SpanPoint::dataSend and SpanPoint::send static nvs_handle pointNVS; // NVS storage for channel number (only used for remote devices) @@ -899,8 +921,9 @@ class SpanPoint { public: SpanPoint(const char *macAddress, int sendSize, int receiveSize, int queueDepth=1, boolean useAPaddress=false); - static void setPassword(const char *pwd){init(pwd);}; - static void setChannelMask(uint16_t mask); + static void setPassword(const char *pwd){init(pwd);} + static void setChannelMask(uint16_t mask); + static void setEncryption(boolean encrypt){useEncryption=encrypt;} boolean get(void *dataBuf); boolean send(const void *data); uint32_t time(){return(millis()-receiveTime);} diff --git a/src/Network.cpp b/src/Network.cpp index bcfe676..ea024bb 100644 --- a/src/Network.cpp +++ b/src/Network.cpp @@ -1,7 +1,7 @@ /********************************************************************************* * MIT License * - * Copyright (c) 2020-2023 Gregg E. Berman + * Copyright (c) 2020-2024 Gregg E. Berman * * https://github.com/HomeSpan/HomeSpan * @@ -40,7 +40,7 @@ void Network::scan(){ int n=WiFi.scanNetworks(); free(ssidList); - ssidList=(char **)calloc(n,sizeof(char *)); + ssidList=(char **)HS_CALLOC(n,sizeof(char *)); numSSID=0; for(int i=0;i tempBuffer(MAX_HTTP+1); - uint8_t *httpBuf=tempBuffer.buf; - + const byte DNS_PORT = 53; DNSServer dnsServer; IPAddress apIP(192, 168, 4, 1); @@ -178,20 +175,30 @@ void Network::apConfigure(){ LOG2("<<<<<<<<< "); LOG2(client.remoteIP()); LOG2(" <<<<<<<<<\n"); - - int nBytes=client.read(httpBuf,MAX_HTTP+1); // read all available bytes up to maximum allowed+1 - - if(nBytes>MAX_HTTP){ // exceeded maximum number of bytes allowed + + int messageSize=client.available(); + + if(messageSize>MAX_HTTP){ // exceeded maximum number of bytes allowed badRequestError(); - LOG0("\n*** ERROR: Exceeded maximum HTTP message length\n\n"); + LOG0("\n*** ERROR: HTTP message of %d bytes exceeds maximum allowed (%d)\n\n",messageSize,MAX_HTTP); + continue; + } + + TempBuffer httpBuf(messageSize+1); // leave room for null character added below + + int nBytes=client.read(httpBuf,messageSize); // read all available bytes up to maximum allowed+1 + + if(nBytes!=messageSize || client.available()!=0){ + badRequestError(); + LOG0("\n*** ERROR: HTTP message not read correctly. Expected %d bytes, read %d bytes, %d bytes remaining\n\n",messageSize,nBytes,client.available()); continue; } - - httpBuf[nBytes]='\0'; // add null character to enable string functions - char *body=(char *)httpBuf; // char pointer to start of HTTP Body + + httpBuf[nBytes]='\0'; // add null character to enable string functions + char *body=(char *)httpBuf.get(); // char pointer to start of HTTP Body char *p; // char pointer used for searches - if(!(p=strstr((char *)httpBuf,"\r\n\r\n"))){ + if(!(p=strstr((char *)httpBuf.get(),"\r\n\r\n"))){ badRequestError(); LOG0("\n*** ERROR: Malformed HTTP request (can't find blank line indicating end of BODY)\n\n"); continue; @@ -230,7 +237,7 @@ void Network::processRequest(char *body, char *formData){ String responseHead="HTTP/1.1 200 OK\r\nContent-type: text/html\r\n"; - String responseBody="