diff --git a/README.md b/README.md
index 4a25c9a..aecc425 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,12 @@ Welcome to HomeSpan - a robust and extremely easy-to-use Arduino library for cre
HomeSpan provides a microcontroller-focused implementation of Apple's HomeKit Accessory Protocol Specification Release R2 (HAP-R2) designed specifically for the Espressif ESP32 microcontroller running within the Arduino IDE. HomeSpan pairs directly to HomeKit via your home WiFi network without the need for any external bridges or components. With HomeSpan you can use the full power of the ESP32's I/O functionality to create custom control software and/or hardware to automatically operate external devices from the Home App on your iPhone, iPad, or Mac, or with Siri.
-HomeSpan requires version 2.0.0 or later of the [Arduino-ESP32 Board Manager](https://github.com/espressif/arduino-esp32), and has been tested up through version 2.0.9 (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 is currently NOT compatible with version 3.X of the Arduino-ESP32 Board Manager, since version 3 contains many breaking changes and is not backwards-compatible with verison 2.X of the Arduino-ESP32 Board Manager. At present, HomeSpan can only be compiled under version 2.X of the Board Manager.
+
+> [!NOTE]
+> Apple's new HomeKit architecture [requires the use of a Home Hub](https://support.apple.com/en-us/HT207057) (either a HomePod or Apple TV) for full and proper operation of any HomeKit device, including those based on HomeSpan. Without a Home Hub, HomeSpan cannot send notifications to the Home App - things like pushbuttons and temperature sensors will not be able to transmit updates to the Home App.
### HomeSpan Highlights
@@ -12,7 +17,7 @@ HomeSpan requires version 2.0.0 or later of the [Arduino-ESP32 Board Manager](ht
* Utilizes a unique *Service-Centric* approach to creating HomeKit devices
* Takes full advantage of the widely-popular Arduino IDE
* 100% HAP-R2 compliance
-* 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 +54,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 +163,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/FAQ.md b/docs/FAQ.md
index 8164dcd..9c042fe 100644
--- a/docs/FAQ.md
+++ b/docs/FAQ.md
@@ -20,7 +20,7 @@
#### Can you use more than one HomeSpan device on the same HomeKit network?
-* Yes, multiple ESP32's, each running a separate copy of HomeSpan, can be used on the same HomeKit network, provided that each device has a unique *Device ID*, a unique *Host Name*, and a unique *Display Name*. Normally, the *Device ID* is randomly-generated by HomeSpan at start-up and will therefore automatically be unique across multiple devices. Also, unless you override the suffix of the default *Host Name*, it will also be unique across multiple devices since HomeSpan uses the *Device ID* as the suffix of the *Host Name*. The only thing you need to ensure is that you assign a different *Display Name* to each of your devices. See the [HomeSpan API Reference](https://github.com/HomeSpan/HomeSpan/blob/master/docs/Reference.md) for details on how to do this.
+* Yes, multiple ESP32's, each running a separate copy of HomeSpan, can be used on the same HomeKit network, provided that each device has a unique *Device ID*, a unique *Host Name*, and a unique *Display Name*. Normally, the *Device ID* is randomly-generated by HomeSpan at start-up and will therefore automatically be unique across multiple devices. Also, unless you override the suffix of the default *Host Name*, it will also be unique across multiple devices since HomeSpan uses the *Device ID* as the suffix of the *Host Name*. The only thing you need to ensure is that you assign a different *Display Name* to each of your devices. See the [HomeSpan API Reference](Reference.md) for details on how to do this.
#### Does HomeSpan require the use of a HomeKit Hub, such as a HomePod or Apple TV?
@@ -36,7 +36,7 @@
#### Will HomeSpan work on an ESP8266 device?
-* No, HomeSpan is coded specifically for the ESP32 and will not operate on an ESP8266 device, though an ESP8266 can be used as a remote [SpanPoint ESP-NOW](../docs/NOW.md) Device.
+* No, HomeSpan is coded specifically for the ESP32 and will not operate on an ESP8266 device, though an ESP8266 can be used as a remote [SpanPoint ESP-NOW](NOW.md) Device.
#### How can I read HomeSpan's MDNS broadcast mentioned in the [OTA](OTA.md) documentation?
@@ -48,7 +48,7 @@
#### Does HomeSpan support Television Services?
-* Yes. Though undocumented by Apple and not officially part of HAP-R2, HomeSpan supports HomeKit Television controls. See [Television Services](../docs/TVServices.md) for details.
+* Yes. Though undocumented by Apple and not officially part of HAP-R2, HomeSpan supports HomeKit Television controls. See [Television Services](TVServices.md) for details.
#### Can you use HomeSpan via Bluetooth?
@@ -68,7 +68,7 @@
#### Can you add *custom* Services and Characteristics to HomeSpan?
-* Yes, HomeSpan includes two easy-to-use macros to define your own custom Services and custom Characteristics beyond those specified in HAP-R2. See the [HomeSpan API Reference](https://github.com/HomeSpan/HomeSpan/blob/master/docs/Reference.md) for details and examples demonstrating how to do this. Note that any new Characteristics you create will be *completely ignored* by the Home App. Similarly, any new Services you create will be shown in the Home App on a tile labeled "Not Supported". Apple ***does not*** provide any mechanism to extend the functionality of the Home App itself. However, the place where custom Services and Characteristics can be used is in third-party applications designed for these extra features. For example, the *Eve for HomeKit* App properly handles all the Services and Characteristics defined in HAP-R2, *plus* a variety of additional Services and Characteristics designed explictly for use with Eve products. If you know the UUID codes for these extra Services and Characteristics you can add them to HomeKit and use them within the Eve App just as if they were HAP-R2 Services and Characteristics.
+* Yes, HomeSpan includes two easy-to-use macros to define your own custom Services and custom Characteristics beyond those specified in HAP-R2. See the [HomeSpan API Reference](Reference.md#custom-characteristics-and-custom-services-macros) for details and examples demonstrating how to do this. Note that any new Characteristics you create will be *completely ignored* by the Home App. Similarly, any new Services you create will be shown in the Home App on a tile labeled "Not Supported". Apple ***does not*** provide any mechanism to extend the functionality of the Home App itself. However, the place where custom Services and Characteristics can be used is in third-party applications designed for these extra features. For example, the *Eve for HomeKit* App properly handles all the Services and Characteristics defined in HAP-R2, *plus* a variety of additional Services and Characteristics designed explictly for use with Eve products. If you know the UUID codes for these extra Services and Characteristics you can add them to HomeKit and use them within the Eve App just as if they were HAP-R2 Services and Characteristics.
#### Can HomeSpan be used for commercial devices?
@@ -76,7 +76,22 @@
#### Why does the Home App indicate the Doorbell Service is unsupported?
-* Though not documented in HAP-R2, it appears that the Doorbell Service is designed to be used in conjunction with another service, such as the Lock Mechanism. If you add in a second service, the Home App will show the appropriate Tile (such as a Lock) with the Doorbell being the second service. However, you can still use the Doorbell Service on a 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.
+
+#### How can I read the current date and time from within my sketch?
+
+* HomeSpan can automatically acquire the current date and time for your local timezone when you enable the HomeSpan Web Log using `homeSpan.enableWebLog()`. Note this command can be used to set the date and time even without enabling the Web Log itself (see the [HomeSpan API Reference](Reference.md) for details on how to do this). Once the date and time has been acquired, you can use the built-in Arduino-ESP32 `getLocalTime(struct tm *info)` command whenever needed to populate *info* with the current date and time. Note *info* is in [standard Unix](https://man7.org/linux/man-pages/man0/time.h.0p.html) `struct tm` format which is easily parsed as follows:
+
+```C++
+struct tm myTime; // create a tm structure
+getLocalTime(&myTime); // populate the tm structure with current date and time
+
+// print the individual elements of the tm structure (see standard Unix tm structure for details)
+
+Serial.printf("Current Date = %02d/%02d/%04d\n", myTime.tm_mon+1, myTime.tm_mday, myTime.tm_year+1900);
+Serial.printf("Current Time = %02d:%02d:%02d\n", myTime.tm_hour, myTime.tm_min, myTime.tm_sec);
+```
+
---
[↩️](../README.md) Back to the Welcome page
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..af4626a 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*
@@ -81,6 +91,9 @@ Examples showing such a configuration can be found in the Arduino IDE under [*Fi
* *RemoteDevice.ino* - a lightweight sketch that simulates taking periodic temperature measurements, which are then transmitted to the Main Device via SpanPoint
* *RemoteTempSensor.ino* - a lightweight sketch that is similar to *RemoteDevice.ino*, except that instead of simulating a temperature sensor, it implements an actual Adafruit ADT7410 I2C-based temperature sensor. This sketch also uses some power-management techniques to extend battery life, such as lowering the CPU frequency and entering into deep-sleep after each measurement is taken
* *RemoteDevice8266.ino* - similar in function to *RemoteDevice.ino*, but implemented to run on an ESP8266 device using native ESP-NOW commands (since neither HomeSpan nor SpanPoint support the ESP8266). Note that the "complementary" SpanPoint object on the ESP32 that receives data from the ESP8266 must be configured to use the ESP32's *AP MAC Address* (instead of the *STA MAC Address*) by setting *useAPaddress* to *true* in the SpanPoint constructor
+
+Please also see the [SpanPointLightSwitch Repository](https://github.com/HomeSpan/SpanPointLightSwitch/tree/main) for a detailed example that shows how to use SpanPoint for *bi-directional communication* between an ESP32 "Central Hub" device implementing two HomeKit Lighbulb Accessories, an remote ESP32 device controlling an LED, and a separate ESP8266 device controlling another LED.
+
---
[↩️](../README.md) Back to the Welcome page
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 472c8cb..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. 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.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+Identify (14) :small_blue_diamond:- triggers an update when HomeKit wants HomeSpan to run its identification routine for an Accessory
| bool | PW | 1 | 1 | |
+Name (23) - default display name of the Accessory
| string | PR | - | - | "unnamed" |
+FirmwareRevision (52) - must be in form x[.y[.z]] - informational only
| string | PR+EV | - | - | "1.0.0" |
+Manufacturer (20) - any string - informational only
| string | PR | - | - | "HomeSpan" |
+Model (21) - any string - informational only
| string | PR | - | - | "HomeSpan-ESP32" |
+SerialNumber (30) - any string - informational only
| string | PR | - | - | "HS-12345" |
+HardwareRevision (53) - must be in form x[.y[.z]] - informational only
| string | PR | - | - | "1.0.0" |
+
-### Service List
+## LIGHTS, POWER, AND SWITCHES
+### BatteryService (96)
+ Defines a standalone Battery Service.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+| BatteryLevel (68) :small_blue_diamond: | uint8 | PR+EV | 0 | 100 | 100 |
+ChargingState (8F) :small_blue_diamond:- indicates state of battery charging
| uint8 | PR+EV | 0 | 2 | - NOT_CHARGING (0) :heavy_check_mark:
- CHARGING (1)
- NOT_CHARGEABLE (2)
|
+StatusLowBattery (79) :small_blue_diamond:- indicates state of battery
| uint8 | PR+EV | 0 | 1 | - NOT_LOW_BATTERY (0) :heavy_check_mark:
- LOW_BATTERY (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+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.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+On (25) :small_blue_diamond:- indicates if the Service is active/on
| bool | PR+PW+EV | 0 | 1 | - OFF (0) :heavy_check_mark:
- ON (1)
|
+| Brightness (8) | int | PR+PW+EV | 0 | 100 | 0 |
+Hue (13) - color (in degrees) from red (0) to green (120) to blue (240) and back to red (360)
| float | PR+PW+EV | 0 | 360 | 0 |
+Saturation (2F) - color saturation, measured as a percentage
| float | PR+PW+EV | 0 | 100 | 0 |
+ColorTemperature (CE) - measured in inverse megaKelvin (= 1,000,000 / Kelvin)
| uint32 | PR+PW+EV | 140 | 500 | 200 |
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
-### Characteristic Types and Defaults
+### Outlet (47)
+ Defines a controllable Outlet used to power any light or appliance.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+On (25) :small_blue_diamond:- indicates if the Service is active/on
| bool | PR+PW+EV | 0 | 1 | - 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
| bool | PR+EV | 0 | 1 | - NOT_IN_USE (0) :heavy_check_mark:
- IN_USE (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+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.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+ProgrammableSwitchEvent (73) :small_blue_diamond:- specifies type of button press
| uint8 | PR+EV+NV | 0 | 2 | - 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
| uint8 | PR | 1 | 255 | 1 |
+
-### HAP Format Codes (HAP-R2 Table 6-5)
+### Switch (49)
+ Defines a generic Switch.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+On (25) :small_blue_diamond:- indicates if the Service is active/on
| bool | PR+PW+EV | 0 | 1 | - OFF (0) :heavy_check_mark:
- ON (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+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.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+Active (B0) :small_blue_diamond:- indicates if the Service is active/on
| uint8 | PW+PR+EV | 0 | 1 | - INACTIVE (0) :heavy_check_mark:
- ACTIVE (1)
|
+CurrentAirPurifierState (A9) :small_blue_diamond:- indicates current state of air purification
| uint8 | PR+EV | 0 | 2 | - INACTIVE (0) :heavy_check_mark:
- IDLE (1)
- PURIFYING (2)
|
+TargetAirPurifierState (A8) :small_blue_diamond:- indicates desired state of air purifier
| uint8 | PW+PR+EV | 0 | 1 | - MANUAL (0)
- AUTO (1) :heavy_check_mark:
|
+| RotationSpeed (29) | float | PR+PW+EV | 0 | 100 | 0 |
+SwingMode (B6) - indicates whether swing-mode is enabled
| uint8 | PR+EV+PW | 0 | 1 | - SWING_DISABLED (0) :heavy_check_mark:
- SWING_ENABLED (1)
|
+LockPhysicalControls (A7) - indicates if local control lock is enabled
| uint8 | PW+PR+EV | 0 | 1 | - CONTROL_LOCK_DISABLED (0) :heavy_check_mark:
- CONTROL_LOCK_ENABLED (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### Fan (B7)
+ Defines a Fan. Combine with a LightBulb Service to create a Lighted Ceiling Fan.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+Active (B0) :small_blue_diamond:- indicates if the Service is active/on
| uint8 | PW+PR+EV | 0 | 1 | - INACTIVE (0) :heavy_check_mark:
- ACTIVE (1)
|
+CurrentFanState (AF) - indicates current state of a fan
| uint8 | PR+EV | 0 | 2 | - INACTIVE (0)
- IDLE (1) :heavy_check_mark:
- BLOWING (2)
|
+TargetFanState (BF) - indicates desired state of fan
| uint8 | PW+PR+EV | 0 | 1 | - MANUAL (0)
- AUTO (1) :heavy_check_mark:
|
+RotationDirection (28) - indicates the rotation direction of a fan
| int | PR+PW+EV | 0 | 1 | - CLOCKWISE (0) :heavy_check_mark:
- COUNTERCLOCKWISE (1)
|
+| RotationSpeed (29) | float | PR+PW+EV | 0 | 100 | 0 |
+SwingMode (B6) - indicates whether swing-mode is enabled
| uint8 | PR+EV+PW | 0 | 1 | - SWING_DISABLED (0) :heavy_check_mark:
- SWING_ENABLED (1)
|
+LockPhysicalControls (A7) - indicates if local control lock is enabled
| uint8 | PW+PR+EV | 0 | 1 | - CONTROL_LOCK_DISABLED (0) :heavy_check_mark:
- CONTROL_LOCK_ENABLED (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### FilterMaintenance (BA)
+ Defines a Filter Maintainence check. Use only as a Linked Service for the AirPurifier Service.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+FilterChangeIndication (AC) :small_blue_diamond:- indicates state of filter
| uint8 | PR+EV | 0 | 1 | - NO_CHANGE_NEEDED (0) :heavy_check_mark:
- CHANGE_NEEDED (1)
|
+FilterLifeLevel (AB) - measured as a percentage of remaining life
| float | PR+EV | 0 | 100 | 100 |
+ResetFilterIndication (AD) - triggers an update when the user chooses to reset the FilterChangeIndication (only appears in Eve App, not Home App)
| uint8 | PW | 1 | 1 | |
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### HeaterCooler (BC)
+ Defines a standalone Heater, Cooler, or combined Heater/Cooler.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+Active (B0) :small_blue_diamond:- indicates if the Service is active/on
| uint8 | PW+PR+EV | 0 | 1 | - INACTIVE (0) :heavy_check_mark:
- ACTIVE (1)
|
+CurrentTemperature (11) :small_blue_diamond:- current temperature measured in Celsius
| float | PR+EV | 0 | 100 | 0 |
+CurrentHeaterCoolerState (B1) :small_blue_diamond:- indicates whether appliance is currently heating, cooling, idle, or off
| uint8 | PR+EV | 0 | 3 | - INACTIVE (0)
- IDLE (1) :heavy_check_mark:
- HEATING (2)
- COOLING (3)
|
+TargetHeaterCoolerState (B2) :small_blue_diamond:- indicates desired state of heater/cooler
| uint8 | PW+PR+EV | 0 | 2 | - AUTO (0) :heavy_check_mark:
- HEAT (1)
- COOL (2)
|
+| RotationSpeed (29) | float | PR+PW+EV | 0 | 100 | 0 |
+TemperatureDisplayUnits (36) - indicates the desired units to display the temperature on the device itself (has no effect on Home App)
| uint8 | PW+PR+EV | 0 | 1 | - CELSIUS (0) :heavy_check_mark:
- FAHRENHEIT (1)
|
+SwingMode (B6) - indicates whether swing-mode is enabled
| uint8 | PR+EV+PW | 0 | 1 | - SWING_DISABLED (0) :heavy_check_mark:
- SWING_ENABLED (1)
|
+CoolingThresholdTemperature (D) - cooling turns on when temperature (in Celsius) rises above this threshold
| float | PR+PW+EV | 10 | 35 | 10 |
+HeatingThresholdTemperature (12) - heating turns on when temperature (in Celsius) falls below this threshold
| float | PR+PW+EV | 0 | 25 | 16 |
+LockPhysicalControls (A7) - indicates if local control lock is enabled
| uint8 | PW+PR+EV | 0 | 1 | - CONTROL_LOCK_DISABLED (0) :heavy_check_mark:
- CONTROL_LOCK_ENABLED (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### HumidifierDehumidifier (BD)
+ Defines a Humidifer, Dehumidifier, or combined Humidifer/Dehumidifier.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+Active (B0) :small_blue_diamond:- indicates if the Service is active/on
| uint8 | PW+PR+EV | 0 | 1 | - INACTIVE (0) :heavy_check_mark:
- ACTIVE (1)
|
+CurrentRelativeHumidity (10) :small_blue_diamond:- current humidity measured as a percentage
| float | PR+EV | 0 | 100 | 0 |
+CurrentHumidifierDehumidifierState (B3) :small_blue_diamond:- indicates current state of humidifier/dehumidifer
| uint8 | PR+EV | 0 | 3 | - INACTIVE (0)
- IDLE (1) :heavy_check_mark:
- HUMIDIFYING (2)
- DEHUMIDIFYING (3)
|
+TargetHumidifierDehumidifierState (B4) :small_blue_diamond:- indicates desired state of humidifier/dehumidifier
| uint8 | PW+PR+EV | 0 | 2 | - AUTO (0) :heavy_check_mark:
- HUMIDIFY (1)
- DEHUMIDIFY (2)
|
+RelativeHumidityDehumidifierThreshold (C9) - dehumidfier turns on when humidity rises above this threshold
| float | PR+PW+EV | 0 | 100 | 50 |
+RelativeHumidityHumidifierThreshold (CA) - humidfier turns on when humidity falls below this threshold
| float | PR+PW+EV | 0 | 100 | 50 |
+| RotationSpeed (29) | float | PR+PW+EV | 0 | 100 | 0 |
+SwingMode (B6) - indicates whether swing-mode is enabled
| uint8 | PR+EV+PW | 0 | 1 | - SWING_DISABLED (0) :heavy_check_mark:
- SWING_ENABLED (1)
|
+| WaterLevel (B5) | float | PR+EV | 0 | 100 | 0 |
+LockPhysicalControls (A7) - indicates if local control lock is enabled
| uint8 | PW+PR+EV | 0 | 1 | - CONTROL_LOCK_DISABLED (0) :heavy_check_mark:
- CONTROL_LOCK_ENABLED (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### Slat (B9)
+ Defines a motorized ventilation Slat(s).
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+CurrentSlatState (AA) :small_blue_diamond:- indicates current state of slats
| uint8 | PR+EV | 0 | 2 | - FIXED (0) :heavy_check_mark:
- JAMMED (1)
- SWINGING (2)
|
+SlatType (C0) :small_blue_diamond:- indicates the direction of a slat or group of slats
| uint8 | PR | 0 | 1 | - HORIZONTAL (0) :heavy_check_mark:
- VERTICAL (1)
|
+SwingMode (B6) - indicates whether swing-mode is enabled
| uint8 | PR+EV+PW | 0 | 1 | - 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)
| int | PR+EV | -90 | 90 | 0 |
+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)
| int | PW+PR+EV | -90 | 90 | 0 |
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### Thermostat (4A)
+ Defines a Thermostat used to control a furnace, air conditioner, or both.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+CurrentHeatingCoolingState (F) :small_blue_diamond:- indicates whether appliance is currently heating, cooling, or just idle
| uint8 | PR+EV | 0 | 2 | - IDLE (0) :heavy_check_mark:
- HEATING (1)
- COOLING (2)
|
+TargetHeatingCoolingState (33) :small_blue_diamond:- indicates desired state of appliance
| uint8 | PW+PR+EV | 0 | 3 | - OFF (0) :heavy_check_mark:
- HEAT (1)
- COOL (2)
- AUTO (3)
|
+CurrentTemperature (11) :small_blue_diamond:- current temperature measured in Celsius
| float | PR+EV | 0 | 100 | 0 |
+TargetTemperature (35) :small_blue_diamond:- indicates desired temperature measures in Celsius
| float | PW+PR+EV | 10 | 38 | 16 |
+TemperatureDisplayUnits (36) :small_blue_diamond:- indicates the desired units to display the temperature on the device itself (has no effect on Home App)
| uint8 | PW+PR+EV | 0 | 1 | - CELSIUS (0) :heavy_check_mark:
- FAHRENHEIT (1)
|
+CoolingThresholdTemperature (D) - cooling turns on when temperature (in Celsius) rises above this threshold
| float | PR+PW+EV | 10 | 35 | 10 |
+CurrentRelativeHumidity (10) - current humidity measured as a percentage
| float | PR+EV | 0 | 100 | 0 |
+HeatingThresholdTemperature (12) - heating turns on when temperature (in Celsius) falls below this threshold
| float | PR+PW+EV | 0 | 25 | 16 |
+TargetRelativeHumidity (34) - indicates desired humidity measured as a percentage
| float | PW+PR+EV | 0 | 100 | 0 |
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+## STANDALONE SENSORS
+### AirQualitySensor (8D)
+ Defines an Air Quality Sensor.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+| AirQuality (95) :small_blue_diamond: | uint8 | PR+EV | 0 | 5 | - UNKNOWN (0) :heavy_check_mark:
- EXCELLENT (1)
- GOOD (2)
- FAIR (3)
- INFERIOR (4)
- POOR (5)
|
+| OzoneDensity (C3) | float | PR+EV | 0 | 1000 | 0 |
+| NitrogenDioxideDensity (C4) | float | PR+EV | 0 | 1000 | 0 |
+| SulphurDioxideDensity (C5) | float | PR+EV | 0 | 1000 | 0 |
+PM25Density (C6) - 2.5-micron particulate density, measured in µg/m3
| float | PR+EV | 0 | 1000 | 0 |
+PM10Density (C7) - 10-micron particulate density, measured in µg/m3
| float | PR+EV | 0 | 1000 | 0 |
+| VOCDensity (C8) | float | PR+EV | 0 | 1000 | 0 |
+StatusActive (75) - indicates whether the Service is properly functioning
| bool | PR+EV | 0 | 1 | - 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)
| uint8 | PR+EV | 0 | 1 | - NO_FAULT (0) :heavy_check_mark:
- FAULT (1)
|
+StatusTampered (7A) - indicates whether the Service has been tampered with
| uint8 | PR+EV | 0 | 1 | - NOT_TAMPERED (0) :heavy_check_mark:
- TAMPERED (1)
|
+StatusLowBattery (79) - indicates state of battery
| uint8 | PR+EV | 0 | 1 | - NOT_LOW_BATTERY (0) :heavy_check_mark:
- LOW_BATTERY (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### CarbonDioxideSensor (97)
+ Defines a Carbon Dioxide Sensor.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+CarbonDioxideDetected (92) :small_blue_diamond:- indicates if abnormal level is detected
| uint8 | PR+EV | 0 | 1 | - NORMAL (0) :heavy_check_mark:
- ABNORMAL (1)
|
+CarbonDioxideLevel (93) - measured on parts per million (ppm)
| float | PR+EV | 0 | 100000 | 0 |
+CarbonDioxidePeakLevel (94) - measured in parts per million (ppm)
| float | PR+EV | 0 | 100000 | 0 |
+StatusActive (75) - indicates whether the Service is properly functioning
| bool | PR+EV | 0 | 1 | - 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)
| uint8 | PR+EV | 0 | 1 | - NO_FAULT (0) :heavy_check_mark:
- FAULT (1)
|
+StatusTampered (7A) - indicates whether the Service has been tampered with
| uint8 | PR+EV | 0 | 1 | - NOT_TAMPERED (0) :heavy_check_mark:
- TAMPERED (1)
|
+StatusLowBattery (79) - indicates state of battery
| uint8 | PR+EV | 0 | 1 | - NOT_LOW_BATTERY (0) :heavy_check_mark:
- LOW_BATTERY (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### CarbonMonoxideSensor (7F)
+ Defines a Carbon Monoxide Sensor.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+CarbonMonoxideDetected (69) :small_blue_diamond:- indicates if abnormal level is detected
| uint8 | PR+EV | 0 | 1 | - NORMAL (0) :heavy_check_mark:
- ABNORMAL (1)
|
+CarbonMonoxideLevel (90) - measured in parts per million (ppm)
| float | PR+EV | 0 | 100 | 0 |
+CarbonMonoxidePeakLevel (91) - measured in parts per million (ppm)
| float | PR+EV | 0 | 100 | 0 |
+StatusActive (75) - indicates whether the Service is properly functioning
| bool | PR+EV | 0 | 1 | - 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)
| uint8 | PR+EV | 0 | 1 | - NO_FAULT (0) :heavy_check_mark:
- FAULT (1)
|
+StatusTampered (7A) - indicates whether the Service has been tampered with
| uint8 | PR+EV | 0 | 1 | - NOT_TAMPERED (0) :heavy_check_mark:
- TAMPERED (1)
|
+StatusLowBattery (79) - indicates state of battery
| uint8 | PR+EV | 0 | 1 | - NOT_LOW_BATTERY (0) :heavy_check_mark:
- LOW_BATTERY (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### ContactSensor (80)
+ Defines a Contact Sensor.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+ContactSensorState (6A) :small_blue_diamond:- indictates if contact is detected (i.e. closed)
| uint8 | PR+EV | 0 | 1 | - DETECTED (0)
- NOT_DETECTED (1) :heavy_check_mark:
|
+StatusActive (75) - indicates whether the Service is properly functioning
| bool | PR+EV | 0 | 1 | - 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)
| uint8 | PR+EV | 0 | 1 | - NO_FAULT (0) :heavy_check_mark:
- FAULT (1)
|
+StatusTampered (7A) - indicates whether the Service has been tampered with
| uint8 | PR+EV | 0 | 1 | - NOT_TAMPERED (0) :heavy_check_mark:
- TAMPERED (1)
|
+StatusLowBattery (79) - indicates state of battery
| uint8 | PR+EV | 0 | 1 | - NOT_LOW_BATTERY (0) :heavy_check_mark:
- LOW_BATTERY (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### HumiditySensor (82)
+ Defines a Humidity Sensor.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+CurrentRelativeHumidity (10) :small_blue_diamond:- current humidity measured as a percentage
| float | PR+EV | 0 | 100 | 0 |
+StatusActive (75) - indicates whether the Service is properly functioning
| bool | PR+EV | 0 | 1 | - 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)
| uint8 | PR+EV | 0 | 1 | - NO_FAULT (0) :heavy_check_mark:
- FAULT (1)
|
+StatusTampered (7A) - indicates whether the Service has been tampered with
| uint8 | PR+EV | 0 | 1 | - NOT_TAMPERED (0) :heavy_check_mark:
- TAMPERED (1)
|
+StatusLowBattery (79) - indicates state of battery
| uint8 | PR+EV | 0 | 1 | - NOT_LOW_BATTERY (0) :heavy_check_mark:
- LOW_BATTERY (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### LeakSensor (83)
+ Defines a Leak Sensor.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+LeakDetected (70) :small_blue_diamond:- indictates if a leak is detected
| uint8 | PR+EV | 0 | 1 | - NOT_DETECTED (0) :heavy_check_mark:
- DETECTED (1)
|
+StatusActive (75) - indicates whether the Service is properly functioning
| bool | PR+EV | 0 | 1 | - 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)
| uint8 | PR+EV | 0 | 1 | - NO_FAULT (0) :heavy_check_mark:
- FAULT (1)
|
+StatusTampered (7A) - indicates whether the Service has been tampered with
| uint8 | PR+EV | 0 | 1 | - NOT_TAMPERED (0) :heavy_check_mark:
- TAMPERED (1)
|
+StatusLowBattery (79) - indicates state of battery
| uint8 | PR+EV | 0 | 1 | - NOT_LOW_BATTERY (0) :heavy_check_mark:
- LOW_BATTERY (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### LightSensor (84)
+ Defines a Light Sensor.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+CurrentAmbientLightLevel (6B) :small_blue_diamond:- measured in Lux (lumens/m2
| float | PR+EV | 0.0001 | 100000 | 1 |
+StatusActive (75) - indicates whether the Service is properly functioning
| bool | PR+EV | 0 | 1 | - 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)
| uint8 | PR+EV | 0 | 1 | - NO_FAULT (0) :heavy_check_mark:
- FAULT (1)
|
+StatusTampered (7A) - indicates whether the Service has been tampered with
| uint8 | PR+EV | 0 | 1 | - NOT_TAMPERED (0) :heavy_check_mark:
- TAMPERED (1)
|
+StatusLowBattery (79) - indicates state of battery
| uint8 | PR+EV | 0 | 1 | - NOT_LOW_BATTERY (0) :heavy_check_mark:
- LOW_BATTERY (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### MotionSensor (85)
+ Defines a Motion Sensor.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+MotionDetected (22) :small_blue_diamond:- indicates if motion is detected
| bool | PR+EV | 0 | 1 | - NOT_DETECTED (0) :heavy_check_mark:
- DETECTED (1)
|
+StatusActive (75) - indicates whether the Service is properly functioning
| bool | PR+EV | 0 | 1 | - 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)
| uint8 | PR+EV | 0 | 1 | - NO_FAULT (0) :heavy_check_mark:
- FAULT (1)
|
+StatusTampered (7A) - indicates whether the Service has been tampered with
| uint8 | PR+EV | 0 | 1 | - NOT_TAMPERED (0) :heavy_check_mark:
- TAMPERED (1)
|
+StatusLowBattery (79) - indicates state of battery
| uint8 | PR+EV | 0 | 1 | - NOT_LOW_BATTERY (0) :heavy_check_mark:
- LOW_BATTERY (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### OccupancySensor (86)
+ Defines and Occupancy Sensor.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+OccupancyDetected (71) :small_blue_diamond:- indicates if occupanccy is detected
| uint8 | PR+EV | 0 | 1 | - NOT_DETECTED (0) :heavy_check_mark:
- DETECTED (1)
|
+StatusActive (75) - indicates whether the Service is properly functioning
| bool | PR+EV | 0 | 1 | - 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)
| uint8 | PR+EV | 0 | 1 | - NO_FAULT (0) :heavy_check_mark:
- FAULT (1)
|
+StatusTampered (7A) - indicates whether the Service has been tampered with
| uint8 | PR+EV | 0 | 1 | - NOT_TAMPERED (0) :heavy_check_mark:
- TAMPERED (1)
|
+StatusLowBattery (79) - indicates state of battery
| uint8 | PR+EV | 0 | 1 | - NOT_LOW_BATTERY (0) :heavy_check_mark:
- LOW_BATTERY (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### SmokeSensor (87)
+ Defines a Smoke Sensor.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+SmokeDetected (76) :small_blue_diamond:- indicates if smoke is detected
| uint8 | PR+EV | 0 | 1 | - NOT_DETECTED (0) :heavy_check_mark:
- DETECTED (1)
|
+StatusActive (75) - indicates whether the Service is properly functioning
| bool | PR+EV | 0 | 1 | - 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)
| uint8 | PR+EV | 0 | 1 | - NO_FAULT (0) :heavy_check_mark:
- FAULT (1)
|
+StatusTampered (7A) - indicates whether the Service has been tampered with
| uint8 | PR+EV | 0 | 1 | - NOT_TAMPERED (0) :heavy_check_mark:
- TAMPERED (1)
|
+StatusLowBattery (79) - indicates state of battery
| uint8 | PR+EV | 0 | 1 | - NOT_LOW_BATTERY (0) :heavy_check_mark:
- LOW_BATTERY (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### TemperatureSensor (8A)
+ Defines a Temperature Sensor.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+CurrentTemperature (11) :small_blue_diamond:- current temperature measured in Celsius
| float | PR+EV | 0 | 100 | 0 |
+StatusActive (75) - indicates whether the Service is properly functioning
| bool | PR+EV | 0 | 1 | - 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)
| uint8 | PR+EV | 0 | 1 | - NO_FAULT (0) :heavy_check_mark:
- FAULT (1)
|
+StatusTampered (7A) - indicates whether the Service has been tampered with
| uint8 | PR+EV | 0 | 1 | - NOT_TAMPERED (0) :heavy_check_mark:
- TAMPERED (1)
|
+StatusLowBattery (79) - indicates state of battery
| uint8 | PR+EV | 0 | 1 | - NOT_LOW_BATTERY (0) :heavy_check_mark:
- LOW_BATTERY (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+## DOORS, LOCKS, AND WINDOWS
+### Door (81)
+ Defines a motorized Door.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+CurrentPosition (6D) :small_blue_diamond:- current position (as a percentage) from fully closed (0) to full open (100)
| uint8 | PR+EV | 0 | 100 | 0 |
+TargetPosition (7C) :small_blue_diamond:- indicates target position (as a percentage) from fully closed (0) to full open (100)
| uint8 | PW+PR+EV | 0 | 100 | 0 |
+ObstructionDetected (24) - indicates if obstruction is detected
| bool | PR+EV | 0 | 1 | - NOT_DETECTED (0) :heavy_check_mark:
- DETECTED (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### Doorbell (121)
+ Defines a Doorbell. Can be used on a standalone basis or in conjunction with a LockMechanism Service.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+ProgrammableSwitchEvent (73) :small_blue_diamond:- specifies type of button press
| uint8 | PR+EV+NV | 0 | 2 | - SINGLE_PRESS (0) :heavy_check_mark:
- DOUBLE_PRESS (1)
- LONG_PRESS (2)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### GarageDoorOpener (41)
+ Defines a motorized Garage Door Opener.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+CurrentDoorState (E) :small_blue_diamond:- indicates current state of a door
| uint8 | PR+EV | 0 | 4 | - OPEN (0)
- CLOSED (1) :heavy_check_mark:
- OPENING (2)
- CLOSING (3)
- STOPPED (4)
|
+TargetDoorState (32) :small_blue_diamond:- indicates desired state of door
| uint8 | PW+PR+EV | 0 | 1 | - OPEN (0)
- CLOSED (1) :heavy_check_mark:
|
+ObstructionDetected (24) :small_blue_diamond:- indicates if obstruction is detected
| bool | PR+EV | 0 | 1 | - NOT_DETECTED (0) :heavy_check_mark:
- DETECTED (1)
|
+LockCurrentState (1D) - indicates state of a lock
| uint8 | PR+EV | 0 | 3 | - UNLOCKED (0) :heavy_check_mark:
- LOCKED (1)
- JAMMED (2)
- UNKNOWN (3)
|
+LockTargetState (1E) - indicates desired state of lock
| uint8 | PW+PR+EV | 0 | 1 | - UNLOCK (0) :heavy_check_mark:
- LOCK (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### LockMechanism (45)
+ Defines an electronic Lock.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+LockCurrentState (1D) :small_blue_diamond:- indicates state of a lock
| uint8 | PR+EV | 0 | 3 | - UNLOCKED (0) :heavy_check_mark:
- LOCKED (1)
- JAMMED (2)
- UNKNOWN (3)
|
+LockTargetState (1E) :small_blue_diamond:- indicates desired state of lock
| uint8 | PW+PR+EV | 0 | 1 | - UNLOCK (0) :heavy_check_mark:
- LOCK (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### Window (8B)
+ Defines a motorized Window.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+CurrentPosition (6D) :small_blue_diamond:- current position (as a percentage) from fully closed (0) to full open (100)
| uint8 | PR+EV | 0 | 100 | 0 |
+TargetPosition (7C) :small_blue_diamond:- indicates target position (as a percentage) from fully closed (0) to full open (100)
| uint8 | PW+PR+EV | 0 | 100 | 0 |
+ObstructionDetected (24) - indicates if obstruction is detected
| bool | PR+EV | 0 | 1 | - NOT_DETECTED (0) :heavy_check_mark:
- DETECTED (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### WindowCovering (8C)
+ Defines a motorized Window Shade, Screen, Awning, etc.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+TargetPosition (7C) :small_blue_diamond:- indicates target position (as a percentage) from fully closed (0) to full open (100)
| uint8 | PW+PR+EV | 0 | 100 | 0 |
+CurrentPosition (6D) :small_blue_diamond:- current position (as a percentage) from fully closed (0) to full open (100)
| uint8 | PR+EV | 0 | 100 | 0 |
+CurrentHorizontalTiltAngle (6C) - current angle (in degrees) of slats from fully up (-90) to fully open (0) to fully down (90)
| int | PR+EV | -90 | 90 | 0 |
+TargetHorizontalTiltAngle (7B) - indicates desired angle (in degrees) of slats from fully up (-90) to fully open (0) to fully down (90)
| int | PW+PR+EV | -90 | 90 | 0 |
+CurrentVerticalTiltAngle (6E) - current angle (in degrees) of slats from fully left (-90) to fully open (0) to fully right (90)
| int | PR+EV | -90 | 90 | 0 |
+TargetVerticalTiltAngle (7D) - indicates desired angle (in degrees) of slats from fully left (-90) to fully open (0) to fully right (90)
| int | PW+PR+EV | -90 | 90 | 0 |
+ObstructionDetected (24) - indicates if obstruction is detected
| bool | PR+EV | 0 | 1 | - NOT_DETECTED (0) :heavy_check_mark:
- DETECTED (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+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).
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+Active (B0) :small_blue_diamond:- indicates if the Service is active/on
| uint8 | PW+PR+EV | 0 | 1 | - INACTIVE (0) :heavy_check_mark:
- ACTIVE (1)
|
+StatusFault (77) - indicates whether the Service has a fault (only appears in Eve App, not Home App)
| uint8 | PR+EV | 0 | 1 | - NO_FAULT (0) :heavy_check_mark:
- FAULT (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+### IrrigationSystem (CF)
+ Defines an Irrigation System. Linked Services: Valve Service (at least one required).
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+Active (B0) :small_blue_diamond:- indicates if the Service is active/on
| uint8 | PW+PR+EV | 0 | 1 | - INACTIVE (0) :heavy_check_mark:
- ACTIVE (1)
|
+ProgramMode (D1) :small_blue_diamond:- indicates if pre-scheduled program is running
| uint8 | PR+EV | 0 | 2 | - 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
| uint8 | PR+EV | 0 | 1 | - NOT_IN_USE (0) :heavy_check_mark:
- IN_USE (1)
|
+RemainingDuration (D4) - duration (in seconds) remaining for Service to be active/on
| uint32 | PR+EV | 0 | 3600 | 60 |
+StatusFault (77) - indicates whether the Service has a fault (only appears in Eve App, not Home App)
| uint8 | PR+EV | 0 | 1 | - NO_FAULT (0) :heavy_check_mark:
- FAULT (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+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.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+Active (B0) :small_blue_diamond:- indicates if the Service is active/on
| uint8 | PW+PR+EV | 0 | 1 | - 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
| uint8 | PR+EV | 0 | 1 | - NOT_IN_USE (0) :heavy_check_mark:
- IN_USE (1)
|
+ValveType (D5) :small_blue_diamond:- indicates the type of valve
| uint8 | PR+EV | 0 | 3 | - 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
| uint32 | PW+PR+EV | 0 | 3600 | 60 |
+RemainingDuration (D4) - duration (in seconds) remaining for Service to be active/on
| uint32 | PR+EV | 0 | 3600 | 60 |
+IsConfigured (D6) - indicates if a predefined Service has been configured
| uint8 | PR+EV | 0 | 1 | - NOT_CONFIGURED (0) :heavy_check_mark:
- CONFIGURED (1)
|
+ServiceLabelIndex (CB) - numerical index used to distinguish multiple copies of the same Service within an Accessory
| uint8 | PR | 1 | 255 | 1 |
+StatusFault (77) - indicates whether the Service has a fault (only appears in Eve App, not Home App)
| uint8 | PR+EV | 0 | 1 | - NO_FAULT (0) :heavy_check_mark:
- FAULT (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+## SECURITY SYSTEMS
+### SecuritySystem (7E)
+ Defines a Security System. Often used in combination with MotionSensor and ContactSensor Services.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+SecuritySystemCurrentState (66) :small_blue_diamond:- indicates current state of the security system
| uint8 | PR+EV | 0 | 4 | - 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
| uint8 | PW+PR+EV | 0 | 3 | - ARM_STAY (0)
- ARM_AWAY (1)
- ARM_NIGHT (2)
- DISARM (3) :heavy_check_mark:
|
+SecuritySystemAlarmType (8E) - indicates whether alarm was triggered for known reason
| uint8 | PR+EV | 0 | 1 | - KNOWN (0) :heavy_check_mark:
- UNKNOWN (1)
|
+StatusFault (77) - indicates whether the Service has a fault (only appears in Eve App, not Home App)
| uint8 | PR+EV | 0 | 1 | - NO_FAULT (0) :heavy_check_mark:
- FAULT (1)
|
+StatusTampered (7A) - indicates whether the Service has been tampered with
| uint8 | PR+EV | 0 | 1 | - NOT_TAMPERED (0) :heavy_check_mark:
- TAMPERED (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+
+
+## TELEVISIONS
+### InputSource (D9)
+ Defines an Input Source for a TV. Use only as a Linked Service for the Television Service.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+Identifier (E6) :small_blue_diamond:- numerical Identifer of the InputSource.
| uint32 | PR | 0 | 255 | 0 |
+ConfiguredName (E3) - default display name of this Service
| string | PW+PR+EV | - | - | "unnamed" |
+IsConfigured (D6) - indicates if a predefined Service has been configured
| uint8 | PR+EV | 0 | 1 | - 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
| uint8 | PR+EV | 0 | 1 | - 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
| uint8 | PW+PR+EV | 0 | 1 | - VISIBLE (0) :heavy_check_mark:
- NOT_VISIBLE (1)
|
+
+
+### Television (D8)
+ Defines a TV. Optional Linked Services: InputSource and TelevisionSpeaker.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+Active (B0) :small_blue_diamond:- indicates if the Service is active/on
| uint8 | PW+PR+EV | 0 | 1 | - INACTIVE (0) :heavy_check_mark:
- ACTIVE (1)
|
+ActiveIdentifier (E7) - numerical Identifier of the InputSource selected in the Home App.
| uint32 | PW+PR+EV | 0 | 255 | 0 |
+RemoteKey (E1) - triggers an update when the corresponding key is pressed in the Remote Control widget on an iPhone
| uint8 | PW | 4 | 15 | - 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
| uint8 | PW | 0 | 0 | |
+ConfiguredName (E3) - default display name of this Service
| string | PW+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.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+VolumeControlType (E9) :small_blue_diamond:- indicates the type of volume control
| uint8 | PR+EV | 0 | 3 | - 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
| uint8 | PW | 0 | 1 | - VOLUME_UP (0)
- VOLUME_DOWN (1)
|
+ConfiguredName (E3) - default display name of this Service
| string | PW+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.
+| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
+ServiceLabelNamespace (CD) :small_blue_diamond:- indicates how un-named Services linked together with a ServiceLabel Service should be displayed in the Home App
| uint8 | PR | 0 | 1 | - 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..cb85745 100644
--- a/docs/Solutions.md
+++ b/docs/Solutions.md
@@ -1,6 +1,18 @@
# Common Problems and Potential Solutions
-#### *HomeSpan works correctly when my ESP32 is plugged into a computer or separately powered through the USB port, but it fails to work when powered directly through the ESP32 5V pin without any USB connection*
+### *My HomeSpan device does not appear in the Home App when I try to pair it*
+
+* There are a few reasons this may occur:
+
+ * **You have not yet entered your WiFi credentials**. HomeSpan can't connect to your WiFi network until you provide it with your WiFi SSID and password. If HomeSpan can't find these Credentials it outputs a warning message to the Serial Monitor during start-up. You can enter your WiFi Credentials into HomeSpan either directly from the Serial Monitor by using the 'W' CLI command, or via the HomeSpan Access Point Setup Page, or by hardcoding it into your sketch with the `homeSpan.setWifiCredentials()` function, though this last method is not recommended for security reasons.
+
+ * **You are out of range of your WiFi network, or entered the wrong WiFi Credentials**. When HomeSpan first boots, if you've previously entered your WiFi Credentials (see above) it will use them to connect to your WiFi network. Check the Serial Monitor for status on whether a connection has been successfully made. If not, make sure your device is in the range of your WiFi network, and re-enter your WiFi Credentials in case you entered them incorrectly the first time. To double-check that your HomeSpan device is indeed connected to your network after HomeSpan reports a successful connection, open up a terminal window on your computer and use the `ping` command to confirm you can reach the device.
+
+ * **Your iPhone and ESP32 device are not connected to the same WiFi network**. Make sure your HomeSpan device is connected to the same SSID as your iPhone and any HomeKit Hubs (e.g. HomePods or Apple TV). Some routers provide a separate SSID to use for IoT ("Internet of Things") devices. If you decide to use a separate SSID, make sure to configure your router so that message traffic flows unimpeded between your main SSID and your dedicated IoT SSID with absolutely no filtering of any messages. Also note that like most commercial HomeKit devices, ESP32 devices operate only on the 2.4 GHz WiFi band. Most iPhones can operate on either the 2.4 GHz or the 5.0 GHz WiFi bands, so if your router provides multi-band access, you need to make sure it is configured to allow unimpeded cross-traffic between the bands.
+
+ * **Your device thinks it is already paired (this is the most common reason)**. Check the Serial Monitor when HomeSpan first boots - it will let you know if the device is currently *paired* or *unpaired*. If its already *paired* you must unpair it before it can be paired again with the Home App. Normally you would unpair the device from the Home App itself, but if for whatever reason you can't (perhaps the device is no longer showing up in the Home App) you can force HomeSpan to forget all its pairing data and reset its state to *unpaired* by typing either the 'U' or 'H' CLI command into the Serial Monitor. The 'U' command instructs HomeSpan to simply erase all its *Controller* pairing data and reset its state to *unpaired*. The 'H' command instructs HomeSpan to erase all its *Controller* pairing data **and** its *HomeKit Device ID*, after which it reboots into the *unpaired* state and generates a new *HomeKit Device ID*. Typing 'H' is recommended to get the cleanest refresh. Note that your WiFi Credentials and Pairing Setup Code are not changed by either of these commands.
+
+### *HomeSpan works correctly when my ESP32 is plugged into a computer or separately powered through the USB port, but it fails to work when powered directly through the ESP32 5V pin without any USB connection*
* On some ESP32 boards, the USB-UART chip only receives power if power is applied through the USB port, and thus remains unpowered if the ESP32 is powered solely through the ESP32 5V pin. As a result, the Serial RX pin associated with UART0 on the ESP32, which is normally driven by the USB-UART chip, is free to float at any voltage. If this pin floats low, the ESP32 thinks there is data to be read from the Serial Monitor, and HomeSpan falls into an infinite loop trying to read this non-existent data.
@@ -12,15 +24,33 @@
* Note that adding this pull-up resistor should **not** interefere with normal serial operation of the board, such as using the Serial Monitor or uploading sketches.
-* *As an alternative*, instead of adding a pull-up resistor, you can simply exclude (or comment out) the `Serial.begin()` line in your sketch. This prevents the problem of HomeSpan hanging when you power it through the 5V pin, but it unfortunately means the Serial Monitor will not function when you connect the board to your computer, and you will need to add back `Serial.begin()` whenever you want to use the Serial Monitor.
+* *As an alternative*, instead of adding a pull-up resistor, you can simply exclude (or comment out) the `Serial.begin()` line in your sketch, or call `homeSpan.setSerialInputDisable(false)` to disable HomeSpan reading from the Serial port. This should prevent the problem of HomeSpan hanging when you power it through the 5V pin, but it unfortunately means the Serial Monitor will not function when you connect the board to your computer, and you will need to add back `Serial.begin()`, or remove `homeSpan.setSerialInputDisable(false)` whenever you want to use the Serial Monitor.
-#### *Compiler Error - `core_version.h` file not found*
+### *HomeSpan crashes when I enable PSRAM, but works fine if I disable PSRAM*
-* 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 your ESP32 comes with Quad or Octal PSRAM, the chip will likely need to use one or more additional I/O pins so that it can access the PSRAM using an extended SPI bus, as required for these types of PSRAM. If you happen to use one of those pins for something else (e.g an input button, an LED, etc.) the ESP32 will likely crash whenever PSRAM is enabled.
+
+* **Resolution:** Check the documentation for your board to see what pins are reserved for use when PSRAM is enabled, and *don't use those pins for anything else.*
-* 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.
+### *The Serial Monitor is reporting* "gpio: gpio_set_level(226): GPIO output gpio_num error"
-* **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.
+* This is an ESP32-generated error message and it occurs if you try to set the output of a pin that either does not exist on your chip, or does exist but it is input-only (i.e. it cannot be used as a output). This typically occurs when you try to compile code for one chip (such as an ESP32-S2) on another chip (such as an ESP32-C3). The code will compile fine, but may produce the above error during run-time.
+
+* **Resolution:** Check the documentation for your board and *use only pins that exist for your chip, and are not reserved for internal functions, and are not input-only.*
+
+### *My sketch is too large to be uploaded (error when trying to upload)*
+
+* Though all ESP32 chips have a minimum of 4MB of flash memory, the amount that can be used to store a program depends on the *partition scheme* selected. By default, the ESP32 uses a parition scheme that reserves 1408 KB for a SPIFFS partition (SPI Flash File Storage) and splits the majority of the remaining flash into two equal OTA partitions of 1280 KB each for program storage. Most HomeSpan sketches come close to filling up an entire OTA partition, and if you add a lot of other libraries you will likely exceed 1280 KB.
+
+* **Resolution:** Select a different partition table that does not reserve so much flash memory for a SPIFFS partition since SPIFFS is not used at all by HomeSpan and *this partition is just wasting space.*
+
+* From within the Arduino IDE, the easiest way to reduce the SPIFFS partition is to select the *Minimal SPIFFS* partition scheme from under the Tools menu, and then simply recompile and upload your sketch. This scheme reserves only 128 KB for the SPIFFS partition, which leaves a full 1920 KB of program storage for each OTA partition. This represents a 50% increase in program size, which should suffice for most applications.
+
+* If for some reason you still need more space, and you only have 4MB of flash, you can try selecting the *Huge App* partition scheme, which reserves 896 KB for SPIFFS and leaves a *single* partition of 3072 KB for program storage. OTA will unfortunately *not* be available in this scheme.
+
+* Note: if you are not using the Arduino IDE to compile and upload HomeSpan sketches, please consult the documentation for your IDE to learn how to change the partition scheme.
+
+* Note: if none of the built-in partition schemes contain the right balance of partition sizes for your sketch, you can always create a custom partition scheme as demonstrated in HomeSpan's [CustomNVSParititon Example](../examples/Other%20Examples/CustomNVSPartition). This technique should work even if not using the Arduino IDE.
---
diff --git a/docs/Stepper.md b/docs/Stepper.md
index 3f89bea..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 "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 "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 A | Phase B |
+ | Coil 1 | Coil 2 | Coil 1 | Coil 2 |
+| Step 1 | HIGH | - | - | - |
+| 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 A | Phase B |
+ | Coil 1 | Coil 2 | Coil 1 | Coil 2 |
+| Step 1 | HIGH | HIGH | - | - |
+| Step 2 | - | HIGH | HIGH | - |
+| Step 3 | - | - | HIGH | HIGH |
+| Step 4 | HIGH | - | - | 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 A | Phase B |
+ | Coil 1 | Coil 2 | Coil 1 | Coil 2 |
+| Step 1 | HIGH | - | - | - |
+| Step 2 | HIGH | HIGH | - | - |
+| Step 3 | - | HIGH | - | - |
+| Step 4 | - | HIGH | HIGH | - |
+| Step 5 | - | - | HIGH | - |
+| Step 6 | - | - | HIGH | HIGH |
+| Step 7 | - | - | - | HIGH |
+| Step 8 | HIGH | - | - | HIGH |
+
+
+---
+
+[↩️](../Stepper.md) Back to the Stepper Motor Control page
diff --git a/docs/TVServices.md b/docs/TVServices.md
index ee0754e..34710a9 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)
@@ -66,7 +66,7 @@ This Service allows you to change the volume of a television using the iPhone's
### Examples
-Please see [*File → Examples → HomeSpan → Other Examples → Television*](../Other%20Examples/Television) for a complete worked example demonstrating the effects of using different combinations of the above Characteristics. Also, don't forget to check out the [HomeSpan Projects](https://github.com/topics/homespan) page for some real-world examples of TV sketches and controllers.
+Please see [*File → Examples → HomeSpan → Other Examples → Television*](../examples/Other%20Examples/Television) for a complete worked example demonstrating the effects of using different combinations of the above Characteristics. Also, don't forget to check out the [HomeSpan Projects](https://github.com/topics/homespan) page for some real-world examples of TV sketches and controllers.
### Credits
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/15-RealPushButtons.ino b/examples/15-RealPushButtons/15-RealPushButtons.ino
index 491a97f..25f3fd1 100644
--- a/examples/15-RealPushButtons/15-RealPushButtons.ino
+++ b/examples/15-RealPushButtons/15-RealPushButtons.ino
@@ -248,7 +248,7 @@ void loop(){
// For example, if you were using an MCP I/O Port Expander with the Adafruit mcp library, you could create a triggerType function for a pin
// on the MCP device that is connected to ground through a pushbutton as such:
//
- // boolean MCP_READ(int mcpPin) { return ( !mcp.digitalRead(mcpPin); ) }
+ // boolean MCP_READ(int mcpPin) { return ( !mcp.digitalRead(mcpPin) ); }
//
// And then simply pass MCP_READ to SpanButton as the triggerType parameter using any of the SpanButton constuctors:
//
@@ -258,7 +258,7 @@ void loop(){
//
// Alternatively, you can use a lambda function as the triggerType parameter, thus creating your function on the fly when instantiating a SpanButton:
//
- // new SpanButton(23,[](int mcpPin)->boolean{ return ( !mcp.digitalRead(mcpPin); ) }
+ // new SpanButton(23,[](int mcpPin)->boolean{ return ( !mcp.digitalRead(mcpPin) ); });
//
// Note: If you create your own triggerType function, don't forget to perform any initialization of the "pin", or setup/configuration of a
// pin extender, etc., prior to instantiating a SpanButton that uses your custom function. HomeSpan cannot do this for you.
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+="| Up Time: | " + String(uptime) + " |
\n";
- response+="| Current Time: | " + String(clocktime) + " |
\n";
- response+="| Boot Time: | " + String(homeSpan.webLog.bootTime) + " |
\n";
+ hapOut << "\n";
+ hapOut << "| Up Time: | " << uptime << " |
\n";
+ hapOut << "| Current Time: | " << clocktime << " |
\n";
+ hapOut << "| Boot Time: | " << homeSpan.webLog.bootTime << " |
\n";
+ hapOut << "| 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()) + ") |
\n";
- response+="| WiFi Disconnects: | " + String(homeSpan.connected/2) + " |
\n";
- response+="| WiFi Signal: | " + String(WiFi.RSSI()) + " dBm |
\n";
- response+="| WiFi Gateway: | " + WiFi.gatewayIP().toString() + " |
\n";
- response+="| ESP32 Board: | " + String(ARDUINO_BOARD) + " |
\n";
- response+="| Arduino-ESP Version: | " + String(ARDUINO_ESP_VERSION) + " |
\n";
- response+="| ESP-IDF Version: | " + String(ESP_IDF_VERSION_MAJOR) + "." + String(ESP_IDF_VERSION_MINOR) + "." + String(ESP_IDF_VERSION_PATCH) + " |
\n";
- response+="| HomeSpan Version: | " + String(HOMESPAN_VERSION) + " |
\n";
- response+="| Sketch Version: | " + String(homeSpan.getSketchVersion()) + " |
\n";
- response+="| Sodium Version: | " + String(sodium_version_string()) + " Lib " + String(sodium_library_version_major()) + "." + String(sodium_library_version_minor()) +" |
\n";
+ hapOut << " (" << esp_reset_reason() << ")\n";
+
+ hapOut << "| WiFi Disconnects: | " << homeSpan.connected/2 << " |
\n";
+ hapOut << "| WiFi Signal: | " << (int)WiFi.RSSI() << " dBm |
\n";
+ hapOut << "| WiFi Gateway: | " << WiFi.gatewayIP().toString().c_str() << " |
\n";
+ hapOut << "| ESP32 Board: | " << ARDUINO_BOARD << " |
\n";
+ hapOut << "| Arduino-ESP Version: | " << ARDUINO_ESP_VERSION << " |
\n";
+ hapOut << "| ESP-IDF Version: | " << ESP_IDF_VERSION_MAJOR << "." << ESP_IDF_VERSION_MINOR << "." << ESP_IDF_VERSION_PATCH << " |
\n";
+ hapOut << "| HomeSpan Version: | " << HOMESPAN_VERSION << " |
\n";
+ hapOut << "| Sketch Version: | " << homeSpan.getSketchVersion() << " |
\n";
+ hapOut << "| Sodium Version: | " << sodium_version_string() << " Lib " << sodium_library_version_major() << "." << sodium_library_version_minor() << " |
\n";
char mbtlsv[64];
mbedtls_version_get_string_full(mbtlsv);
- response+="| MbedTLS Version: | " + String(mbtlsv) + " |
\n";
-
- response+="| HomeKit Status: | " + String(nAdminControllers()?"PAIRED":"NOT PAIRED") + " |
\n";
- response+="| Max Log Entries: | " + String(homeSpan.webLog.maxEntries) + " |
\n";
- response+="
\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+="| Entry | Up Time | Log Time | Client | Message |
\n";
+ hapOut << "| Entry | Up Time | Log Time | Client | Message |
\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+="| " + String(i+1) + " | " + String(uptime) + " | " + String(clocktime) + " | " + homeSpan.webLog.log[index].clientIP + " | " + String(homeSpan.webLog.log[index].message) + " | \n";
+ hapOut << "
| " << i+1 << " | " << uptime << " | " << clocktime << " | " << homeSpan.webLog.log[index].clientIP.c_str() << " | " << homeSpan.webLog.log[index].message << " |
\n";
}
- response+="
\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 1afe931..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;
diff --git a/src/Network.h b/src/Network.h
index 679ecfe..97843a5 100644
--- a/src/Network.h
+++ b/src/Network.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
*
@@ -28,11 +28,8 @@
#pragma once
#include
-#include
#include "Settings.h"
-using std::unordered_set;
-
const int MAX_SSID=32; // max number of characters in WiFi SSID
const int MAX_PWD=64; // max number of characters in WiFi Password
@@ -43,7 +40,7 @@ struct Network {
const int MAX_HTTP=4095; // max number of bytes in HTTP message
const char *apSSID=DEFAULT_AP_SSID; // Access Point SSID
- const char *apPassword=DEFAULT_AP_PASSWORD; // Access Point password (does not need to be secret - only used to ensure excrypted WiFi connection)
+ const char *apPassword=DEFAULT_AP_PASSWORD; // Access Point password (does not need to be secret - only used to ensure encrypted WiFi connection)
unsigned long lifetime=DEFAULT_AP_TIMEOUT*1000; // length of time (in milliseconds) to keep Access Point alive before shutting down and restarting
char **ssidList=NULL;
diff --git a/src/PSRAM.h b/src/PSRAM.h
new file mode 100644
index 0000000..dd9e03a
--- /dev/null
+++ b/src/PSRAM.h
@@ -0,0 +1,61 @@
+/*********************************************************************************
+ * MIT License
+ *
+ * Copyright (c) 2020-2024 Gregg E. Berman
+ *
+ * https://github.com/HomeSpan/HomeSpan
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ ********************************************************************************/
+
+#pragma once
+
+#ifndef HS_MALLOC
+
+#if defined(BOARD_HAS_PSRAM)
+#define HS_MALLOC ps_malloc
+#define HS_CALLOC ps_calloc
+#define HS_REALLOC ps_realloc
+#define ps_new(X) new(ps_malloc(sizeof(X)))X
+#else
+#define HS_MALLOC malloc
+#define HS_CALLOC calloc
+#define HS_REALLOC realloc
+#define ps_new(X) new X
+#endif
+
+template
+struct Mallocator {
+ typedef T value_type;
+ Mallocator() = default;
+ template constexpr Mallocator(const Mallocator&) noexcept {}
+ [[nodiscard]] T* allocate(std::size_t n) {
+ if(n > std::size_t(-1) / sizeof(T)) throw std::bad_alloc();
+ if(auto p = static_cast(HS_MALLOC(n*sizeof(T)))) return p;
+ throw std::bad_alloc();
+ }
+ void deallocate(T* p, std::size_t) noexcept { std::free(p); }
+};
+template
+bool operator==(const Mallocator&, const Mallocator&) { return true; }
+template
+bool operator!=(const Mallocator&, const Mallocator&) { return false; }
+
+#endif
diff --git a/src/SRP.cpp b/src/SRP.cpp
index aaa1e27..93ec8dc 100644
--- a/src/SRP.cpp
+++ b/src/SRP.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
*
@@ -29,29 +29,12 @@
#include
#include "SRP.h"
-#include "HAP.h"
/////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////
SRP6A::SRP6A(){
- uint8_t tBuf[768]; // temporary buffer for staging
- uint8_t tHash[64]; // temporary buffer for storing SHA-512 results
-
- char N3072[]="FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74"
- "020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437"
- "4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
- "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF05"
- "98DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB"
- "9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
- "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
- "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33"
- "A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
- "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864"
- "D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E2"
- "08E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF";
-
// initialize MPI structures
mbedtls_mpi_init(&N);
@@ -65,134 +48,156 @@ SRP6A::SRP6A(){
mbedtls_mpi_init(&S);
mbedtls_mpi_init(&k);
mbedtls_mpi_init(&u);
- mbedtls_mpi_init(&K);
- mbedtls_mpi_init(&M1);
- mbedtls_mpi_init(&M1V);
- mbedtls_mpi_init(&M2);
mbedtls_mpi_init(&_rr);
mbedtls_mpi_init(&t1);
mbedtls_mpi_init(&t2);
mbedtls_mpi_init(&t3);
- // load N and g into mpi structures
+ // load N and g into MPI structures
mbedtls_mpi_read_string(&N,16,N3072);
- mbedtls_mpi_lset(&g,5);
+ mbedtls_mpi_lset(&g,g3072);
+
+}
+//////////////////////////////////////
+
+SRP6A::~SRP6A(){
+
+ mbedtls_mpi_free(&N);
+ mbedtls_mpi_free(&g);
+ mbedtls_mpi_free(&s);
+ mbedtls_mpi_free(&x);
+ mbedtls_mpi_free(&v);
+ mbedtls_mpi_free(&A);
+ mbedtls_mpi_free(&b);
+ mbedtls_mpi_free(&B);
+ mbedtls_mpi_free(&S);
+ mbedtls_mpi_free(&k);
+ mbedtls_mpi_free(&u);
+ mbedtls_mpi_free(&_rr);
+ mbedtls_mpi_free(&t1);
+ mbedtls_mpi_free(&t2);
+ mbedtls_mpi_free(&t3);
+
+}
+
+//////////////////////////////////////
+
+void SRP6A::createVerifyCode(const char *setupCode, Verification *vData){
+
+ TempBuffer tBuf(80); // temporary buffer for staging
+ TempBuffer tHash(64); // temporary buffer for storing SHA-512 results
+ char *icp; // storage for I:P
+
+ // generate random salt, s
+
+ randombytes_buf(vData->salt,16); // generate 16 random bytes for salt
+
+ // create I:P
+
+ asprintf(&icp,"%s:%.3s-%.2s-%.3s",I,setupCode,setupCode+3,setupCode+5);
+
+ // compute x = SHA512( s | SHA512( I | ":" | P ) )
+
+ memcpy(tBuf,vData->salt,16); // write salt into first 16 bytes of staging buffer
+ mbedtls_sha512_ret((uint8_t *)icp,strlen(icp),tBuf+16,0); // create hash of username:password and write into last 64 bytes of staging buffer
+ mbedtls_sha512_ret(tBuf,80,tHash,0); // create second hash of salted, hashed username:password
+ mbedtls_mpi_read_binary(&x,tHash,64); // load hash result into x
+
+ // compute v = g^x %N
+
+ mbedtls_mpi_exp_mod(&v,&g,&x,&N,&_rr); // create verifier, v (_rr is an internal "helper" structure that mbedtls uses to speed up subsequent exponential calculations)
+ mbedtls_mpi_write_binary(&v,vData->verifyCode,384); // write v into verifyCode (padding with initial zeros is less than 384 bytes)
+
+ free(icp);
+
+}
+
+//////////////////////////////////////
+
+void SRP6A::createPublicKey(const Verification *vData, uint8_t *publicKey){
+
+ TempBuffer tBuf(768); // temporary buffer for staging
+ TempBuffer tHash(64); // temporary buffer for storing SHA-512 results
+ TempBuffer privateKey(32); // temporary buffer for generating private key random numbers
+
+ // load stored salt, s, and verification code, v
+
+ mbedtls_mpi_read_binary(&s,vData->salt,16); // load salt into s for use in later steps
+ mbedtls_mpi_read_binary(&v,vData->verifyCode,384); // load verifyCode into v for use below
+
+ // generate random private key, b
+
+ randombytes_buf(privateKey,32); // generate 32 random bytes for private key
+ mbedtls_mpi_read_binary(&b,privateKey,32); // load private key into b
+
// compute k = SHA512( N | PAD(g) )
mbedtls_mpi_write_binary(&N,tBuf,384); // write N into first half of staging buffer
mbedtls_mpi_write_binary(&g,tBuf+384,384); // write g into second half of staging buffer (fully padded with leading zeros)
mbedtls_sha512_ret(tBuf,768,tHash,0); // create hash of data
- mbedtls_mpi_read_binary(&k,tHash,64); // load hash result into mpi structure k
+ mbedtls_mpi_read_binary(&k,tHash,64); // load hash result into k
+
+ // compute B = (k*v + g^b) %N
+
+ mbedtls_mpi_mul_mpi(&t1,&k,&v); // t1 = k*v
+ mbedtls_mpi_exp_mod(&t2,&g,&b,&N,&_rr); // t2 = g^b %N
+ mbedtls_mpi_add_mpi(&t3,&t1,&t2); // t3 = t1 + t2
+ mbedtls_mpi_mod_mpi(&B,&t3,&N); // B = t3 %N = ACCESSORY PUBLIC KEY
+
+ mbedtls_mpi_write_binary(&B,publicKey,384); // write B into publicKey (padding with initial zeros is less than 384 bytes)
}
//////////////////////////////////////
-void SRP6A::createVerifyCode(const char *setupCode, uint8_t *verifyCode, uint8_t *salt){
+void SRP6A::createSessionKey(const uint8_t *publicKey, size_t len){
- uint8_t tBuf[80]; // temporary buffer for staging
- uint8_t tHash[64]; // temporary buffer for storing SHA-512 results
- char icp[22]; // storage for I:P
+ TempBuffer tBuf(768); // temporary buffer for staging
+ TempBuffer tHash(64); // temporary buffer for storing SHA-512 results
- randombytes_buf(salt,16); // generate 16 random bytes using libsodium (which uses the ESP32 hardware-based random number generator)
- mbedtls_mpi_read_binary(&s,salt,16);
-
- sprintf(icp,"Pair-Setup:%.3s-%.2s-%.3s",setupCode,setupCode+3,setupCode+5);
-
- // compute x = SHA512( s | SHA512( I | ":" | P ) )
-
- mbedtls_mpi_write_binary(&s,tBuf,16); // write s into first 16 bytes of staging buffer
- mbedtls_sha512_ret((uint8_t *)icp,strlen(icp),tBuf+16,0); // create hash of username:password and write into last 64 bytes of staging buffer
- mbedtls_sha512_ret(tBuf,80,tHash,0); // create second hash of salted, hashed username:password
- mbedtls_mpi_read_binary(&x,tHash,64); // load hash result into mpi structure x
-
- // compute v = g^x % N
-
- mbedtls_mpi_exp_mod(&v,&g,&x,&N,&_rr); // create verifier, v (_rr is an internal "helper" structure that mbedtls uses to speed up subsequent exponential calculations)
- mbedtls_mpi_write_binary(&v,verifyCode,384); // write v into verifyCode
-
-}
-
-//////////////////////////////////////
-
-void SRP6A::loadVerifyCode(uint8_t *verifyCode, uint8_t *salt){
-
- mbedtls_mpi_read_binary(&s,salt,16);
- mbedtls_mpi_read_binary(&v,verifyCode,384);
-
-}
-
-//////////////////////////////////////
-
-void SRP6A::createPublicKey(){
-
- getPrivateKey(); // create and load b (random 32 bytes)
-
- // compute B = kv + g^b %N
-
- mbedtls_mpi_mul_mpi(&t1,&k,&v); // t1 = k*v
- mbedtls_mpi_exp_mod(&t2,&g,&b,&N,&_rr); // t2 = g^b %N
- mbedtls_mpi_add_mpi(&t3,&t1,&t2); // t3 = t1 + t2
- mbedtls_mpi_mod_mpi(&B,&t3,&N); // B = t3 %N = ACCESSORY PUBLIC KEY
-
-}
-
-//////////////////////////////////////
-
-void SRP6A::getPrivateKey(){
-
- uint8_t privateKey[32];
-
- randombytes_buf(privateKey,32); // generate 32 random bytes using libsodium (which uses the ESP32 hardware-based random number generator)
- mbedtls_mpi_read_binary(&b,privateKey,32);
-}
-
-//////////////////////////////////////
-
-void SRP6A::createSessionKey(){
-
- uint8_t tBuf[768]; // temporary buffer for staging
- uint8_t tHash[64]; // temporary buffer for storing SHA-512 results
+ mbedtls_mpi_read_binary(&A,publicKey,len); // load client PublicKey into A
// compute u = SHA512( PAD(A) | PAD(B) )
- mbedtls_mpi_write_binary(&A,tBuf,384); // write A into first half of staging buffer
- mbedtls_mpi_write_binary(&B,tBuf+384,384); // write B into second half of staging buffer
+ mbedtls_mpi_write_binary(&A,tBuf,384); // write A into first half of staging buffer (padding with initial zeros is less than 384 bytes)
+ mbedtls_mpi_write_binary(&B,tBuf+384,384); // write B into second half of staging buffer (padding with initial zeros is less than 384 bytes)
mbedtls_sha512_ret(tBuf,768,tHash,0); // create hash of data
mbedtls_mpi_read_binary(&u,tHash,64); // load hash result into mpi structure u
- // compute S = (Av^u)^b %N
+ // compute S = (A * v^u)^b %N
mbedtls_mpi_exp_mod(&t1,&v,&u,&N,&_rr); // t1 = v^u %N
mbedtls_mpi_mul_mpi(&t2,&A,&t1); // t2 = A*t1
mbedtls_mpi_mod_mpi(&t1,&t2,&N); // t1 = t2 %N (this is needed to reduce size of t2 before next calculation)
mbedtls_mpi_exp_mod(&S,&t1,&b,&N,&_rr); // S = t1^b %N
- // compute K = SHA512( S )
+ // compute K = SHA512( PAD(S) )
mbedtls_mpi_write_binary(&S,tBuf,384); // write S into staging buffer (only first half of buffer will be used)
- mbedtls_sha512_ret(tBuf,384,tHash,0); // create hash of data
- mbedtls_mpi_read_binary(&K,tHash,64); // load hash result into mpi structure K. This is the SRP SHARED SECRET KEY
-
- mbedtls_mpi_write_binary(&K,sharedSecret,64); // store SHARED SECRET in easy-to-use binary (uint8_t) format
+ mbedtls_sha512_ret(tBuf,384,K,0); // create hash of data - this is the SRP SHARED SESSION KEY, K
}
//////////////////////////////////////
-int SRP6A::verifyProof(){
- uint8_t tBuf[976]; // temporary buffer for staging
- uint8_t tHash[64]; // temporary buffer for storing SHA-512 results
+int SRP6A::verifyClientProof(const uint8_t *proof){
- size_t count=0; // total number of bytes for final hash
+ TempBuffer tBuf(976); // temporary buffer for staging
+ TempBuffer tHash(64); // temporary buffer for storing SHA-512 results
+
+ memcpy(M1,proof,64); // load client Proof into M1
+
+ size_t count=0; // total number of bytes for final hash
size_t sLen;
-
+
+ // compute M1V = SHA512( SHA512(N) xor SHA512(g) | SHA512(I) | s | A | B | K )
+
mbedtls_mpi_write_binary(&N,tBuf,384); // write N into staging buffer
mbedtls_sha512_ret(tBuf,384,tHash,0); // create hash of data
- mbedtls_sha512_ret((uint8_t *)g3072,1,tBuf,0); // create hash of g, but place output directly into staging buffer
+ mbedtls_sha512_ret(&g3072,1,tBuf,0); // create hash of g, but place output directly into staging buffer
for(int i=0;i<64;i++) // H(g) -> H(g) XOR H(N), with results in first 64 bytes of staging buffer
tBuf[i]^=tHash[i];
@@ -209,13 +214,12 @@ int SRP6A::verifyProof(){
mbedtls_mpi_write_binary(&B,tBuf+count,sLen); // concatenate B to staging buffer. Note B is NOT padded with leading zeros (so may be less than 384 bytes)
count+=sLen; // increment total bytes written to staging buffer
- mbedtls_mpi_write_binary(&K,tBuf+count,64); // concatenate K to staging buffer (should always be 64 bytes since it is a hashed value)
+ memcpy(tBuf+count,K,64); // concatenate K to staging buffer (should always be 64 bytes since it is a hashed value)
count+=64; // final total of bytes written to staging buffer
- mbedtls_sha512_ret(tBuf,count,tHash,0); // create hash of data
- mbedtls_mpi_read_binary(&M1V,tHash,64); // load hash result into mpi structure M1V
-
- if(!mbedtls_mpi_cmp_mpi(&M1,&M1V)) // cmp_mpi uses same logic as strcmp: returns 0 if EQUAL, otherwise +/- 1
+ mbedtls_sha512_ret(tBuf,count,tHash,0); // create hash of data - this is M1V
+
+ if(!memcmp(M1,tHash,64)) // check that client Proof M1 matches M1V
return(1); // success - proof from HAP Client is verified
return(0);
@@ -223,60 +227,34 @@ int SRP6A::verifyProof(){
//////////////////////////////////////
-void SRP6A::createProof(){
+void SRP6A::createAccProof(uint8_t *proof){
- uint8_t tBuf[512]; // temporary buffer for staging
+ TempBuffer tBuf(512); // temporary buffer for staging
- // compute M2 = H( A | M1 | K )
+ // compute M2 = SHA512( A | M1 | K )
mbedtls_mpi_write_binary(&A,tBuf,384); // write A into staging buffer
- mbedtls_mpi_write_binary(&M1,tBuf+384,64); // concatenate M1 (now verified) to staging buffer
- mbedtls_mpi_write_binary(&K,tBuf+448,64); // concatenate K to staging buffer
- mbedtls_sha512_ret(tBuf,512,tBuf,0); // create hash of data
- mbedtls_mpi_read_binary(&M2,tBuf,64); // load hash results into mpi structure M2
-
+ memcpy(tBuf+384,M1,64); // concatenate M1 (now verified) to staging buffer
+ memcpy(tBuf+448,K,64); // concatenate K to staging buffer
+ mbedtls_sha512_ret(tBuf,512,proof,0); // create hash of data writing directly to proof - this is M2
+
}
//////////////////////////////////////
-int SRP6A::loadTLV(kTLVType tag, mbedtls_mpi *mpi, int nBytes){
-
- uint8_t *buf=HAPClient::tlv8.buf(tag,nBytes);
-
- if(!buf)
- return(0);
-
- mbedtls_mpi_write_binary(mpi,buf,nBytes);
- return(1);
-}
-
-//////////////////////////////////////
-
-int SRP6A::writeTLV(kTLVType tag, mbedtls_mpi *mpi){
-
- int nBytes=HAPClient::tlv8.len(tag);
-
- if(nBytes>0){
- mbedtls_mpi_read_binary(mpi,HAPClient::tlv8.buf(tag),nBytes);
- return(1);
- };
-
- return(0);
-}
-
-//////////////////////////////////////
-
-void SRP6A::print(mbedtls_mpi *mpi, int minLogLevel){
-
- if(homeSpan.getLogLevel() sBuf(sLen);
+ mbedtls_mpi_write_string(mpi,16,sBuf,sLen,&sLen);
- Serial.printf("%d %s\n",(sLen-1)/2,sBuf); // subtract 1 for null-terminator, and then divide by 2 to get number of bytes (e.g. 4F = 2 characters, but represents just one mpi byte)
+ Serial.printf("%d %s\n",(sLen-1)/2,sBuf.get()); // subtract 1 for null-terminator, and then divide by 2 to get number of bytes (e.g. 4F = 2 characters, but represents just one mpi byte)
}
//////////////////////////////////////
+
+constexpr char SRP6A::N3072[];
+constexpr char SRP6A::I[];
+const uint8_t SRP6A::g3072;
diff --git a/src/SRP.h b/src/SRP.h
index 562d20c..24aece6 100644
--- a/src/SRP.h
+++ b/src/SRP.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
*
@@ -31,11 +31,19 @@
#include
#include
-#include "HAPConstants.h"
+#include "Utils.h"
+
+/////////////////////////////////////////////////
+// Pair-Setup Code Verification Data and Salt
+
+struct Verification {
+ uint8_t salt[16];
+ uint8_t verifyCode[384];
+};
/////////////////////////////////////////////////
// SRP-6A Structure from RFC 5054 (Nov 2007)
-// ** HAP uses N=3072-bit Group specified in RFC 5054
+// ** HAP uses N=3072-bit Group specified in RFC 5054 with Generator g=5
// ** HAP replaces H=SHA-1 with H=SHA-512 (HAP Section 5.5)
//
// I = SRP-6A username, defined by HAP to be the word "Pair-Setup"
@@ -43,6 +51,22 @@
struct SRP6A {
+ static constexpr char N3072[]="FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD129024E088A67CC74"
+ "020BBEA63B139B22514A08798E3404DDEF9519B3CD3A431B302B0A6DF25F1437"
+ "4FE1356D6D51C245E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED"
+ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3DC2007CB8A163BF05"
+ "98DA48361C55D39A69163FA8FD24CF5F83655D23DCA3AD961C62F356208552BB"
+ "9ED529077096966D670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B"
+ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9DE2BCBF695581718"
+ "3995497CEA956AE515D2261898FA051015728E5A8AAAC42DAD33170D04507A33"
+ "A85521ABDF1CBA64ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7"
+ "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6BF12FFA06D98A0864"
+ "D87602733EC86A64521F2B18177B200CBBE117577A615D6C770988C0BAD946E2"
+ "08E24FA074E5AB3143DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF";
+
+ static const uint8_t g3072=5;
+ static constexpr char I[]="Pair-Setup";
+
mbedtls_mpi N; // N - 3072-bit Group pre-defined prime used for all SRP-6A calculations (384 bytes)
mbedtls_mpi g; // g - pre-defined generator for the specified 3072-bit Group (g=5)
mbedtls_mpi k; // k = H(N | PAD(g)) - SRP-6A multiplier (which is different from versions SRP-6 or SRP-3)
@@ -54,39 +78,25 @@ struct SRP6A {
mbedtls_mpi A; // A - public key RECEIVED from HAP Client (max 384 bytes)
mbedtls_mpi u; // u = H(PAD(A) | PAB(B)) - "u-factor" (64 bytes)
mbedtls_mpi S; // S = (A*v^u)^b %N - SRP shared "premaster" key, based on accessory private key and client public key (max 384 bytes)
- mbedtls_mpi K; // K = H( S ) - SRP SHARED SECRET KEY (64 bytes)
- mbedtls_mpi M1; // M1 - proof RECEIVED from HAP Client (64 bytes)
- mbedtls_mpi M1V; // M1V - accessory's independent computation of M1 to verify proof (see code for details of computation)
- mbedtls_mpi M2; // M2 - accessory's counter-proof to send to HAP Client after M1=M1V has been verified (64 bytes)
-
- mbedtls_mpi t1; // temporary mpi structures for intermediate results
- mbedtls_mpi t2;
- mbedtls_mpi t3;
-
+ uint8_t K[64]; // K = H(S) - SRP SHARED SECRET KEY (64 bytes)
+ uint8_t M1[64]; // M1 - proof RECEIVED from HAP Client (64 bytes)
+ mbedtls_mpi t1; // temp1 - temporary mpi structures for intermediate results
+ mbedtls_mpi t2; // temp2 - temporary mpi structures for intermediate results
+ mbedtls_mpi t3; // temp3 - temporary mpi structures for intermediate results
mbedtls_mpi _rr; // _rr - temporary "helper" for large exponential modulus calculations
- char I[11]="Pair-Setup"; // I - userName pre-defined by HAP pairing setup protocol
- char g3072[2]="\x05"; // g - 3072-bit Group generator
-
- uint8_t sharedSecret[64]; // permanent storage for binary version of SHARED SECRET KEY for ease of use upstream
SRP6A(); // initializes N, G, and computes k
-
- void createVerifyCode(const char *setupCode, uint8_t *verifyCode, uint8_t *salt);
- void loadVerifyCode(uint8_t *verifyCode, uint8_t *salt);
-
- void getSalt(); // generates and stores random 16-byte salt, s
- void getPrivateKey(); // generates and stores random 32-byte private key, b
- void getSetupCode(char *c); // generates and displays random 8-digit Pair-Setup code, P, in format XXX-XX-XXX
- void createPublicKey(); // computes x, v, and B from random s, P, and b
- void createSessionKey(); // computes u from A and B, and then S from A, v, u, and b
-
- int loadTLV(kTLVType tag, mbedtls_mpi *mpi, int nBytes); // load binary contents of mpi into a TLV record and set its length
- int writeTLV(kTLVType tag, mbedtls_mpi *mpi); // write binary contents of a TLV record into an mpi
-
- int verifyProof(); // verify M1 SRP6A Proof received from HAP client (return 1 on success, 0 on failure)
- void createProof(); // create M2 server-side SRP6A Proof based on M1 as received from HAP Client
+ ~SRP6A();
- void print(mbedtls_mpi *mpi, int minLogLevel=0); // prints size of mpi (in bytes), followed by the mpi itself (as a hex charcter string), subject to specified minimum log level
+ void *operator new(size_t size){return(HS_MALLOC(size));} // override new operator to use PSRAM when available
+
+ void createVerifyCode(const char *setupCode, Verification *vData); // generates random s and computes v; writes back resulting Verification Data
+ void createPublicKey(const Verification *vData, uint8_t *publicKey); // generates random b and computes k and B; writes back resulting Accessory Public Key
+ void createSessionKey(const uint8_t *publicKey, size_t len); // computes u, S, and K from Client Public Key, A (of variable length)
+ int verifyClientProof(const uint8_t *proof); // verifies Client Proof, M1, received from HAP client (return 1 on success, 0 on failure)
+ void createAccProof(uint8_t *proof); // computes M2; write back resulting Accessory Proof
+
+ void print(mbedtls_mpi *mpi); // prints size of mpi (in bytes), followed by the mpi itself (as a hex character string)
};
diff --git a/src/Settings.h b/src/Settings.h
index 4f9841f..9a9c3c5 100644
--- a/src/Settings.h
+++ b/src/Settings.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,7 +27,7 @@
// USER-DEFINED SETTINGS AND REFERENCE ENUMERATION CLASSES
-#include
+#include
#pragma once
@@ -35,7 +35,7 @@
// HomeSpan Version //
#define HS_MAJOR 1
-#define HS_MINOR 8
+#define HS_MINOR 9
#define HS_PATCH 0
#define STRINGIFY(x) _STR(x)
@@ -53,7 +53,7 @@
#error THIS SKETCH REQUIRES A LATER VERSION OF THE HOMESPAN LIBRARY
#endif
-#define ARDUINO_ESP_VERSION STRINGIFY(ARDUINO_ESP32_GIT_DESC)
+#define ARDUINO_ESP_VERSION STRINGIFY(ESP_ARDUINO_VERSION_MAJOR) "." STRINGIFY(ESP_ARDUINO_VERSION_MINOR) "." STRINGIFY(ESP_ARDUINO_VERSION_PATCH)
#if ESP_ARDUINO_VERSION_MAJOR<2
#error HOMESPAN REQUIRES VERSION 2 OF THE ARDUINO ESP32 LIBRARY
@@ -84,6 +84,10 @@
#define DEFAULT_WEBLOG_URL "status" // change with optional fourth argument in homeSpan.enableWebLog()
+#define DEFAULT_LOW_MEM_THRESHOLD 80000 // default low watermark memory (for internal RAM) threshold that triggers warning
+
+#define DEFAULT_REBOOT_CALLBACK_TIME 5000 // default time (in milliseconds) to check for reboot callback
+
/////////////////////////////////////////////////////
// OTA PARTITION INFO //
diff --git a/src/Span.h b/src/Span.h
index ff43382..1dc1395 100644
--- a/src/Span.h
+++ b/src/Span.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
*
@@ -32,38 +32,168 @@
// Macros to define services, along with vectors of required and optional characteristics for each Span Service structure
// The names of the macros are picked up by external scripts to help generate documentation
+// Note: These macros below are also parsed by an external awk script to auto-generate Services and Characteristics documentation.
+//
+// The CREATE_SERV_DEP() macro is the same as the CREATE_SERV() macro, except that it is used for deprecated Services that will not
+// be included in documentation. The OPT_DEP() macro is that same as the OPT() macro, except that it is used for deprecated Characteristics
+// that will not be included in documentation.
+
#define CREATE_SERV(NAME,UUID) struct NAME : SpanService { NAME() : SpanService{#UUID,#NAME}{
+#define CREATE_SERV_DEP(NAME,UUID) struct NAME : SpanService { NAME() : SpanService{#UUID,#NAME}{
#define END_SERV }};
-#define REQ(HAPCHAR) req.insert(&hapChars.HAPCHAR)
-#define OPT(HAPCHAR) opt.insert(&hapChars.HAPCHAR)
+#define REQ(HAPCHAR) req.push_back(&hapChars.HAPCHAR)
+#define REQ_DEP(HAPCHAR) req.push_back(&hapChars.HAPCHAR)
+#define OPT(HAPCHAR) opt.push_back(&hapChars.HAPCHAR)
+#define OPT_DEP(HAPCHAR) opt.push_back(&hapChars.HAPCHAR)
+
+#define SERVICES_GROUP
namespace Service {
- CREATE_SERV(AccessoryInformation,3E)
+ SERVICES_GROUP // Mandatory Services
+
+ CREATE_SERV(AccessoryInformation,3E) // Required Identification Information. For each Accessory in a HomeSpan device this must be included as the first Service.
REQ(Identify);
+ OPT(Name);
OPT(FirmwareRevision);
OPT(Manufacturer);
OPT(Model);
- OPT(Name);
OPT(SerialNumber);
OPT(HardwareRevision);
- OPT(AccessoryFlags);
+ OPT_DEP(AccessoryFlags);
END_SERV
- CREATE_SERV(AirPurifier,BB)
+ SERVICES_GROUP // Lights, Power, and Switches
+
+ CREATE_SERV(BatteryService,96) // Defines a standalone Battery Service.
+ REQ(BatteryLevel);
+ REQ(ChargingState);
+ REQ(StatusLowBattery);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(LightBulb,43) // Defines any type of Light.
+ REQ(On);
+ OPT(Brightness);
+ OPT(Hue);
+ OPT(Saturation);
+ OPT(ColorTemperature);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(Outlet,47) // Defines a controllable Outlet used to power any light or appliance.
+ REQ(On);
+ REQ(OutletInUse);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(StatelessProgrammableSwitch,89) // Defines a "Stateless" Programmable Switch that can be used to trigger actions in the Home App.
+ REQ(ProgrammableSwitchEvent);
+ OPT(ServiceLabelIndex);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(Switch,49) // Defines a generic Switch.
+ REQ(On);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ SERVICES_GROUP // Heating, Ventilation, and Air Conditioning (HVAC)
+
+ CREATE_SERV(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.
REQ(Active);
REQ(CurrentAirPurifierState);
REQ(TargetAirPurifierState);
- OPT(Name);
OPT(RotationSpeed);
OPT(SwingMode);
OPT(LockPhysicalControls);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(Fan,B7) // Defines a Fan. Combine with a LightBulb Service to create a Lighted Ceiling Fan.
+ REQ(Active);
+ OPT(CurrentFanState);
+ OPT(TargetFanState);
+ OPT(RotationDirection);
+ OPT(RotationSpeed);
+ OPT(SwingMode);
+ OPT(LockPhysicalControls);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
END_SERV
- CREATE_SERV(AirQualitySensor,8D)
+ CREATE_SERV(FilterMaintenance,BA) // Defines a Filter Maintainence check. Use only as a Linked Service for the AirPurifier Service.
+ REQ(FilterChangeIndication);
+ OPT(FilterLifeLevel);
+ OPT(ResetFilterIndication);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(HeaterCooler,BC) // Defines a standalone Heater, Cooler, or combined Heater/Cooler.
+ REQ(Active);
+ REQ(CurrentTemperature);
+ REQ(CurrentHeaterCoolerState);
+ REQ(TargetHeaterCoolerState);
+ OPT(RotationSpeed);
+ OPT(TemperatureDisplayUnits);
+ OPT(SwingMode);
+ OPT(CoolingThresholdTemperature);
+ OPT(HeatingThresholdTemperature);
+ OPT(LockPhysicalControls);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(HumidifierDehumidifier,BD) // Defines a Humidifer, Dehumidifier, or combined Humidifer/Dehumidifier.
+ REQ(Active);
+ REQ(CurrentRelativeHumidity);
+ REQ(CurrentHumidifierDehumidifierState);
+ REQ(TargetHumidifierDehumidifierState);
+ OPT(RelativeHumidityDehumidifierThreshold);
+ OPT(RelativeHumidityHumidifierThreshold);
+ OPT(RotationSpeed);
+ OPT(SwingMode);
+ OPT(WaterLevel);
+ OPT(LockPhysicalControls);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(Slat,B9) // Defines a motorized ventilation Slat(s).
+ REQ(CurrentSlatState);
+ REQ(SlatType);
+ OPT(SwingMode);
+ OPT(CurrentTiltAngle);
+ OPT(TargetTiltAngle);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(Thermostat,4A) // Defines a Thermostat used to control a furnace, air conditioner, or both.
+ REQ(CurrentHeatingCoolingState);
+ REQ(TargetHeatingCoolingState);
+ REQ(CurrentTemperature);
+ REQ(TargetTemperature);
+ REQ(TemperatureDisplayUnits);
+ OPT(CoolingThresholdTemperature);
+ OPT(CurrentRelativeHumidity);
+ OPT(HeatingThresholdTemperature);
+ OPT(TargetRelativeHumidity);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ SERVICES_GROUP // Standalone Sensors
+
+ CREATE_SERV(AirQualitySensor,8D) // Defines an Air Quality Sensor.
REQ(AirQuality);
- OPT(Name);
OPT(OzoneDensity);
OPT(NitrogenDioxideDensity);
OPT(SulphurDioxideDensity);
@@ -74,299 +204,194 @@ namespace Service {
OPT(StatusFault);
OPT(StatusTampered);
OPT(StatusLowBattery);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
END_SERV
-
- CREATE_SERV(BatteryService,96)
- REQ(BatteryLevel);
- REQ(ChargingState);
- REQ(StatusLowBattery);
- OPT(Name);
- END_SERV
-
- CREATE_SERV(CarbonDioxideSensor,97)
+
+ CREATE_SERV(CarbonDioxideSensor,97) // Defines a Carbon Dioxide Sensor.
REQ(CarbonDioxideDetected);
- OPT(Name);
- OPT(StatusActive);
- OPT(StatusFault);
- OPT(StatusTampered);
- OPT(StatusLowBattery);
OPT(CarbonDioxideLevel);
OPT(CarbonDioxidePeakLevel);
- END_SERV
-
- CREATE_SERV(CarbonMonoxideSensor,7F)
- REQ(CarbonMonoxideDetected);
- OPT(Name);
OPT(StatusActive);
OPT(StatusFault);
OPT(StatusTampered);
OPT(StatusLowBattery);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(CarbonMonoxideSensor,7F) // Defines a Carbon Monoxide Sensor.
+ REQ(CarbonMonoxideDetected);
OPT(CarbonMonoxideLevel);
OPT(CarbonMonoxidePeakLevel);
- END_SERV
-
- CREATE_SERV(ContactSensor,80)
- REQ(ContactSensorState);
- OPT(Name);
OPT(StatusActive);
OPT(StatusFault);
OPT(StatusTampered);
OPT(StatusLowBattery);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(ContactSensor,80) // Defines a Contact Sensor.
+ REQ(ContactSensorState);
+ OPT(StatusActive);
+ OPT(StatusFault);
+ OPT(StatusTampered);
+ OPT(StatusLowBattery);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
END_SERV
- CREATE_SERV(Door,81)
+ CREATE_SERV(HumiditySensor,82) // Defines a Humidity Sensor.
+ REQ(CurrentRelativeHumidity);
+ OPT(StatusActive);
+ OPT(StatusFault);
+ OPT(StatusTampered);
+ OPT(StatusLowBattery);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(LeakSensor,83) // Defines a Leak Sensor.
+ REQ(LeakDetected);
+ OPT(StatusActive);
+ OPT(StatusFault);
+ OPT(StatusTampered);
+ OPT(StatusLowBattery);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(LightSensor,84) // Defines a Light Sensor.
+ REQ(CurrentAmbientLightLevel);
+ OPT(StatusActive);
+ OPT(StatusFault);
+ OPT(StatusTampered);
+ OPT(StatusLowBattery);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(MotionSensor,85) // Defines a Motion Sensor.
+ REQ(MotionDetected);
+ OPT(StatusActive);
+ OPT(StatusFault);
+ OPT(StatusTampered);
+ OPT(StatusLowBattery);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(OccupancySensor,86) // Defines and Occupancy Sensor.
+ REQ(OccupancyDetected);
+ OPT(StatusActive);
+ OPT(StatusFault);
+ OPT(StatusTampered);
+ OPT(StatusLowBattery);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(SmokeSensor,87) // Defines a Smoke Sensor.
+ REQ(SmokeDetected);
+ OPT(StatusActive);
+ OPT(StatusFault);
+ OPT(StatusTampered);
+ OPT(StatusLowBattery);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV(TemperatureSensor,8A) // Defines a Temperature Sensor.
+ REQ(CurrentTemperature);
+ OPT(StatusActive);
+ OPT(StatusFault);
+ OPT(StatusTampered);
+ OPT(StatusLowBattery);
+ OPT(ConfiguredName);
+ END_SERV
+
+ SERVICES_GROUP // Doors, Locks, and Windows
+
+ CREATE_SERV(Door,81) // Defines a motorized Door.
REQ(CurrentPosition);
REQ(TargetPosition);
- REQ(PositionState);
- OPT(Name);
- OPT(HoldPosition);
OPT(ObstructionDetected);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ OPT_DEP(PositionState);
+ OPT_DEP(HoldPosition);
END_SERV
- CREATE_SERV(Doorbell,121)
+ CREATE_SERV(Doorbell,121) // Defines a Doorbell. Can be used on a standalone basis or in conjunction with a LockMechanism Service.
REQ(ProgrammableSwitchEvent);
- OPT(Name);
- OPT(Volume);
- OPT(Brightness);
+ OPT_DEP(Volume);
+ OPT_DEP(Brightness);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
END_SERV
- CREATE_SERV(Fan,B7)
- REQ(Active);
- OPT(Name);
- OPT(CurrentFanState);
- OPT(TargetFanState);
- OPT(RotationDirection);
- OPT(RotationSpeed);
- OPT(SwingMode);
- OPT(LockPhysicalControls);
- END_SERV
-
- CREATE_SERV(Faucet,D7)
- REQ(Active);
- OPT(StatusFault);
- OPT(Name);
- END_SERV
-
- CREATE_SERV(FilterMaintenance,BA)
- REQ(FilterChangeIndication);
- OPT(Name);
- OPT(FilterLifeLevel);
- OPT(ResetFilterIndication);
- END_SERV
-
- CREATE_SERV(GarageDoorOpener,41)
+ CREATE_SERV(GarageDoorOpener,41) // Defines a motorized Garage Door Opener.
REQ(CurrentDoorState);
REQ(TargetDoorState);
REQ(ObstructionDetected);
OPT(LockCurrentState);
OPT(LockTargetState);
- OPT(Name);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
END_SERV
- CREATE_SERV(HAPProtocolInformation,A2)
- REQ(Version);
+ CREATE_SERV(LockMechanism,45) // Defines an electronic Lock.
+ REQ(LockCurrentState);
+ REQ(LockTargetState);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
END_SERV
- CREATE_SERV(HeaterCooler,BC)
+ CREATE_SERV(Window,8B) // Defines a motorized Window.
+ REQ(CurrentPosition);
+ REQ(TargetPosition);
+ OPT(ObstructionDetected);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ OPT_DEP(PositionState);
+ OPT_DEP(HoldPosition);
+ END_SERV
+
+ CREATE_SERV(WindowCovering,8C) // Defines a motorized Window Shade, Screen, Awning, etc.
+ REQ(TargetPosition);
+ REQ(CurrentPosition);
+ OPT(CurrentHorizontalTiltAngle);
+ OPT(TargetHorizontalTiltAngle);
+ OPT(CurrentVerticalTiltAngle);
+ OPT(TargetVerticalTiltAngle);
+ OPT(ObstructionDetected);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
+ OPT_DEP(PositionState);
+ OPT_DEP(HoldPosition);
+ END_SERV
+
+ SERVICES_GROUP // Water Systems
+
+ CREATE_SERV(Faucet,D7) // Defines the master control for a multi-Valve appliance. Linked Services: Valve (at least one required), and HeaterCooler (optional).
REQ(Active);
- REQ(CurrentTemperature);
- REQ(CurrentHeaterCoolerState);
- REQ(TargetHeaterCoolerState);
- OPT(Name);
- OPT(RotationSpeed);
- OPT(TemperatureDisplayUnits);
- OPT(SwingMode);
- OPT(CoolingThresholdTemperature);
- OPT(HeatingThresholdTemperature);
- OPT(LockPhysicalControls);
- END_SERV
-
- CREATE_SERV(HumidifierDehumidifier,BD)
- REQ(Active);
- REQ(CurrentRelativeHumidity);
- REQ(CurrentHumidifierDehumidifierState);
- REQ(TargetHumidifierDehumidifierState);
- OPT(Name);
- OPT(RelativeHumidityDehumidifierThreshold);
- OPT(RelativeHumidityHumidifierThreshold);
- OPT(RotationSpeed);
- OPT(SwingMode);
- OPT(WaterLevel);
- OPT(LockPhysicalControls);
- END_SERV
-
- CREATE_SERV(HumiditySensor,82)
- REQ(CurrentRelativeHumidity);
- OPT(Name);
- OPT(StatusActive);
OPT(StatusFault);
- OPT(StatusTampered);
- OPT(StatusLowBattery);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
END_SERV
- CREATE_SERV(InputSource,D9)
- OPT(ConfiguredName);
- OPT(IsConfigured);
- REQ(Identifier);
- OPT(CurrentVisibilityState);
- OPT(TargetVisibilityState);
- END_SERV
-
- CREATE_SERV(IrrigationSystem,CF)
+ CREATE_SERV(IrrigationSystem,CF) // Defines an Irrigation System. Linked Services: Valve Service (at least one required).
REQ(Active);
REQ(ProgramMode);
REQ(InUse);
OPT(RemainingDuration);
OPT(StatusFault);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
END_SERV
- CREATE_SERV(LeakSensor,83)
- REQ(LeakDetected);
- OPT(Name);
- OPT(StatusActive);
- OPT(StatusFault);
- OPT(StatusTampered);
- OPT(StatusLowBattery);
- END_SERV
-
- CREATE_SERV(LightBulb,43)
- REQ(On);
- OPT(Brightness);
- OPT(Hue);
- OPT(Name);
- OPT(Saturation);
- OPT(ColorTemperature);
- END_SERV
-
- CREATE_SERV(LightSensor,84)
- REQ(CurrentAmbientLightLevel);
- OPT(Name);
- OPT(StatusActive);
- OPT(StatusFault);
- OPT(StatusTampered);
- OPT(StatusLowBattery);
- END_SERV
-
- CREATE_SERV(LockMechanism,45)
- REQ(LockCurrentState);
- REQ(LockTargetState);
- OPT(Name);
- END_SERV
-
- CREATE_SERV(Microphone,112)
- REQ(Mute);
- OPT(Name);
- OPT(Volume);
- END_SERV
-
- CREATE_SERV(MotionSensor,85)
- REQ(MotionDetected);
- OPT(Name);
- OPT(StatusActive);
- OPT(StatusFault);
- OPT(StatusTampered);
- OPT(StatusLowBattery);
- END_SERV
-
- CREATE_SERV(OccupancySensor,86)
- REQ(OccupancyDetected);
- OPT(Name);
- OPT(StatusActive);
- OPT(StatusFault);
- OPT(StatusTampered);
- OPT(StatusLowBattery);
- END_SERV
-
- CREATE_SERV(Outlet,47)
- REQ(On);
- REQ(OutletInUse);
- OPT(Name);
- END_SERV
-
- CREATE_SERV(SecuritySystem,7E)
- REQ(SecuritySystemCurrentState);
- REQ(SecuritySystemTargetState);
- OPT(Name);
- OPT(SecuritySystemAlarmType);
- OPT(StatusFault);
- OPT(StatusTampered);
- END_SERV
-
- CREATE_SERV(ServiceLabel,CC)
- REQ(ServiceLabelNamespace);
- END_SERV
-
- CREATE_SERV(Slat,B9)
- REQ(CurrentSlatState);
- REQ(SlatType);
- OPT(Name);
- OPT(SwingMode);
- OPT(CurrentTiltAngle);
- OPT(TargetTiltAngle);
- END_SERV
-
- CREATE_SERV(SmokeSensor,87)
- REQ(SmokeDetected);
- OPT(Name);
- OPT(StatusActive);
- OPT(StatusFault);
- OPT(StatusTampered);
- OPT(StatusLowBattery);
- END_SERV
-
- CREATE_SERV(Speaker,113)
- REQ(Mute);
- OPT(Name);
- OPT(Volume);
- END_SERV
-
- CREATE_SERV(StatelessProgrammableSwitch,89)
- REQ(ProgrammableSwitchEvent);
- OPT(Name);
- OPT(ServiceLabelIndex);
- END_SERV
-
- CREATE_SERV(Switch,49)
- REQ(On);
- OPT(Name);
- END_SERV
-
- CREATE_SERV(Television,D8)
- REQ(Active);
- OPT(ConfiguredName);
- OPT(ActiveIdentifier);
- OPT(RemoteKey);
- OPT(PowerModeSelection);
- END_SERV
-
- CREATE_SERV(TelevisionSpeaker,113)
- REQ(VolumeControlType);
- REQ(VolumeSelector);
- END_SERV
-
- CREATE_SERV(TemperatureSensor,8A)
- REQ(CurrentTemperature);
- OPT(Name);
- OPT(StatusActive);
- OPT(StatusFault);
- OPT(StatusTampered);
- OPT(StatusLowBattery);
- END_SERV
-
- CREATE_SERV(Thermostat,4A)
- REQ(CurrentHeatingCoolingState);
- REQ(TargetHeatingCoolingState);
- REQ(CurrentTemperature);
- REQ(TargetTemperature);
- REQ(TemperatureDisplayUnits);
- OPT(CoolingThresholdTemperature);
- OPT(CurrentRelativeHumidity);
- OPT(HeatingThresholdTemperature);
- OPT(Name);
- OPT(TargetRelativeHumidity);
- END_SERV
-
- CREATE_SERV(Valve,D0)
+ CREATE_SERV(Valve,D0) // Defines an electronic Valve. Can be used standalone or as a Linked Service for either a Faucet or IrrigationSystem Service.
REQ(Active);
REQ(InUse);
REQ(ValveType);
@@ -375,29 +400,70 @@ namespace Service {
OPT(IsConfigured);
OPT(ServiceLabelIndex);
OPT(StatusFault);
- OPT(Name);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
END_SERV
- CREATE_SERV(Window,8B)
- REQ(CurrentPosition);
- REQ(TargetPosition);
- REQ(PositionState);
- OPT(Name);
- OPT(HoldPosition);
- OPT(ObstructionDetected);
+ SERVICES_GROUP // Security Systems
+
+ CREATE_SERV(SecuritySystem,7E) // Defines a Security System. Often used in combination with MotionSensor and ContactSensor Services.
+ REQ(SecuritySystemCurrentState);
+ REQ(SecuritySystemTargetState);
+ OPT(SecuritySystemAlarmType);
+ OPT(StatusFault);
+ OPT(StatusTampered);
+ OPT(ConfiguredName);
+ OPT_DEP(Name);
END_SERV
- CREATE_SERV(WindowCovering,8C)
- REQ(TargetPosition);
- REQ(CurrentPosition);
- REQ(PositionState);
- OPT(Name);
- OPT(HoldPosition);
- OPT(CurrentHorizontalTiltAngle);
- OPT(TargetHorizontalTiltAngle);
- OPT(CurrentVerticalTiltAngle);
- OPT(TargetVerticalTiltAngle);
- OPT(ObstructionDetected);
+ SERVICES_GROUP // Televisions
+
+ CREATE_SERV(InputSource,D9) // Defines an Input Source for a TV. Use only as a Linked Service for the Television Service.
+ REQ(Identifier);
+ OPT(ConfiguredName);
+ OPT(IsConfigured);
+ OPT(CurrentVisibilityState);
+ OPT(TargetVisibilityState);
+ END_SERV
+
+ CREATE_SERV(Television,D8) // Defines a TV. Optional Linked Services: InputSource and TelevisionSpeaker.
+ REQ(Active);
+ OPT(ActiveIdentifier);
+ OPT(RemoteKey);
+ OPT(PowerModeSelection);
+ OPT(ConfiguredName);
+ END_SERV
+
+ CREATE_SERV(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.
+ REQ(VolumeControlType);
+ REQ(VolumeSelector);
+ OPT(ConfiguredName);
+ END_SERV
+
+ SERVICES_GROUP // Miscellaneous
+
+ CREATE_SERV(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.
+ REQ(ServiceLabelNamespace);
+ END_SERV
+
+ // Deprecated or unsupported Services
+
+ CREATE_SERV_DEP(HAPProtocolInformation,A2)
+ REQ_DEP(Version);
+ END_SERV
+
+ CREATE_SERV_DEP(Microphone,112)
+ REQ_DEP(Mute);
+ OPT_DEP(Volume);
+ OPT_DEP(ConfiguredName);
+ OPT_DEP(Name);
+ END_SERV
+
+ CREATE_SERV_DEP(Speaker,113)
+ REQ_DEP(Mute);
+ OPT_DEP(Volume);
+ OPT_DEP(ConfiguredName);
+ OPT_DEP(Name);
END_SERV
}
@@ -408,127 +474,127 @@ namespace Service {
// Macro to define Span Characteristic structures based on name of HAP Characteristic, default value, and min/max value (not applicable for STRING or BOOL which default to min=0, max=1)
-#define CREATE_CHAR(TYPE,HAPCHAR,DEFVAL,MINVAL,MAXVAL) \
- struct HAPCHAR : SpanCharacteristic { HAPCHAR(TYPE val=DEFVAL, boolean nvsStore=false) : SpanCharacteristic {&hapChars.HAPCHAR} { init(val,nvsStore,(TYPE)MINVAL,(TYPE)MAXVAL); } };
+#define CREATE_CHAR(TYPE,HAPCHAR,DEFVAL,MINVAL,MAXVAL,...) \
+ struct HAPCHAR : SpanCharacteristic { __VA_OPT__(enum{) __VA_ARGS__ __VA_OPT__(};) HAPCHAR(TYPE val=DEFVAL, boolean nvsStore=false) : SpanCharacteristic {&hapChars.HAPCHAR} { init(val,nvsStore,(TYPE)MINVAL,(TYPE)MAXVAL); } };
namespace Characteristic {
- CREATE_CHAR(uint32_t,AccessoryFlags,1,1,1);
- CREATE_CHAR(uint8_t,Active,0,0,1);
- CREATE_CHAR(uint32_t,ActiveIdentifier,0,0,255);
- CREATE_CHAR(uint8_t,AirQuality,0,0,5);
- CREATE_CHAR(uint8_t,BatteryLevel,0,0,100);
- CREATE_CHAR(int,Brightness,0,0,100);
- CREATE_CHAR(double,CarbonMonoxideLevel,0,0,100);
- CREATE_CHAR(double,CarbonMonoxidePeakLevel,0,0,100);
- CREATE_CHAR(uint8_t,CarbonMonoxideDetected,0,0,1);
- CREATE_CHAR(double,CarbonDioxideLevel,0,0,100000);
- CREATE_CHAR(double,CarbonDioxidePeakLevel,0,0,100000);
- CREATE_CHAR(uint8_t,CarbonDioxideDetected,0,0,1);
- CREATE_CHAR(uint8_t,ChargingState,0,0,2);
- CREATE_CHAR(uint8_t,ClosedCaptions,0,0,1);
- CREATE_CHAR(double,CoolingThresholdTemperature,10,10,35);
- CREATE_CHAR(uint32_t,ColorTemperature,200,140,500);
- CREATE_CHAR(uint8_t,ContactSensorState,1,0,1);
- CREATE_CHAR(const char *,ConfiguredName,"unnamed",0,1);
- CREATE_CHAR(double,CurrentAmbientLightLevel,1,0.0001,100000);
- CREATE_CHAR(int,CurrentHorizontalTiltAngle,0,-90,90);
- CREATE_CHAR(uint8_t,CurrentAirPurifierState,1,0,2);
- CREATE_CHAR(uint8_t,CurrentSlatState,0,0,2);
- CREATE_CHAR(uint8_t,CurrentPosition,0,0,100);
- CREATE_CHAR(int,CurrentVerticalTiltAngle,0,-90,90);
- CREATE_CHAR(uint8_t,CurrentVisibilityState,0,0,1);
- CREATE_CHAR(uint8_t,CurrentHumidifierDehumidifierState,1,0,3);
- CREATE_CHAR(uint8_t,CurrentDoorState,1,0,4);
- CREATE_CHAR(uint8_t,CurrentFanState,1,0,2);
- CREATE_CHAR(uint8_t,CurrentHeatingCoolingState,0,0,2);
- CREATE_CHAR(uint8_t,CurrentHeaterCoolerState,1,0,3);
- CREATE_CHAR(uint8_t,CurrentMediaState,0,0,5);
- CREATE_CHAR(double,CurrentRelativeHumidity,0,0,100);
- CREATE_CHAR(double,CurrentTemperature,0,0,100);
- CREATE_CHAR(int,CurrentTiltAngle,0,-90,90);
- CREATE_CHAR(double,FilterLifeLevel,0,0,100);
- CREATE_CHAR(uint8_t,FilterChangeIndication,0,0,1);
- CREATE_CHAR(const char *,FirmwareRevision,"1.0.0",0,1);
- CREATE_CHAR(const char *,HardwareRevision,"1.0.0",0,1);
- CREATE_CHAR(double,HeatingThresholdTemperature,16,0,25);
- CREATE_CHAR(boolean,HoldPosition,false,0,1);
- CREATE_CHAR(double,Hue,0,0,360);
- CREATE_CHAR(boolean,Identify,false,0,1);
- CREATE_CHAR(uint32_t,Identifier,0,0,255);
- CREATE_CHAR(uint8_t,InputDeviceType,0,0,6);
- CREATE_CHAR(uint8_t,InputSourceType,0,0,10);
- CREATE_CHAR(uint8_t,InUse,0,0,1);
- CREATE_CHAR(uint8_t,IsConfigured,0,0,1);
- CREATE_CHAR(uint8_t,LeakDetected,0,0,1);
- CREATE_CHAR(uint8_t,LockCurrentState,0,0,3);
- CREATE_CHAR(uint8_t,LockPhysicalControls,0,0,1);
- CREATE_CHAR(uint8_t,LockTargetState,0,0,1);
- CREATE_CHAR(const char *,Manufacturer,"HomeSpan",0,1);
- CREATE_CHAR(const char *,Model,"HomeSpan-ESP32",0,1);
- CREATE_CHAR(boolean,MotionDetected,false,0,1);
- CREATE_CHAR(boolean,Mute,false,0,1);
- CREATE_CHAR(const char *,Name,"unnamed",0,1);
- CREATE_CHAR(double,NitrogenDioxideDensity,0,0,1000);
- CREATE_CHAR(boolean,ObstructionDetected,false,0,1);
- CREATE_CHAR(double,PM25Density,0,0,1000);
- CREATE_CHAR(uint8_t,OccupancyDetected,0,0,1);
- CREATE_CHAR(boolean,OutletInUse,false,0,1);
- CREATE_CHAR(boolean,On,false,0,1);
- CREATE_CHAR(double,OzoneDensity,0,0,1000);
- CREATE_CHAR(uint8_t,PictureMode,0,0,13);
- CREATE_CHAR(double,PM10Density,0,0,1000);
- CREATE_CHAR(uint8_t,PositionState,2,0,2);
- CREATE_CHAR(uint8_t,PowerModeSelection,0,0,1);
- CREATE_CHAR(uint8_t,ProgramMode,0,0,2);
- CREATE_CHAR(uint8_t,ProgrammableSwitchEvent,0,0,2);
- CREATE_CHAR(double,RelativeHumidityDehumidifierThreshold,50,0,100);
- CREATE_CHAR(double,RelativeHumidityHumidifierThreshold,50,0,100);
- CREATE_CHAR(uint32_t,RemainingDuration,60,0,3600);
- CREATE_CHAR(uint8_t,RemoteKey,0,0,16);
- CREATE_CHAR(uint8_t,ResetFilterIndication,0,1,1);
- CREATE_CHAR(int,RotationDirection,0,0,1);
- CREATE_CHAR(double,RotationSpeed,0,0,100);
- CREATE_CHAR(double,Saturation,0,0,100);
- CREATE_CHAR(uint8_t,SecuritySystemAlarmType,0,0,1);
- CREATE_CHAR(uint8_t,SecuritySystemCurrentState,3,0,4);
- CREATE_CHAR(uint8_t,SecuritySystemTargetState,3,0,3);
- CREATE_CHAR(const char *,SerialNumber,"HS-12345",0,1);
- CREATE_CHAR(uint8_t,ServiceLabelIndex,1,1,255);
- CREATE_CHAR(uint8_t,ServiceLabelNamespace,1,0,1);
- CREATE_CHAR(uint8_t,SlatType,0,0,1);
- CREATE_CHAR(uint8_t,SleepDiscoveryMode,0,0,1);
- CREATE_CHAR(uint8_t,SmokeDetected,0,0,1);
- CREATE_CHAR(boolean,StatusActive,true,0,1);
- CREATE_CHAR(uint8_t,StatusFault,0,0,1);
- CREATE_CHAR(uint8_t,StatusJammed,0,0,1);
- CREATE_CHAR(uint8_t,StatusLowBattery,0,0,1);
- CREATE_CHAR(uint8_t,StatusTampered,0,0,1);
- CREATE_CHAR(double,SulphurDioxideDensity,0,0,1000);
- CREATE_CHAR(uint8_t,SwingMode,0,0,1);
- CREATE_CHAR(uint8_t,TargetAirPurifierState,1,0,1);
- CREATE_CHAR(uint8_t,TargetFanState,1,0,1);
- CREATE_CHAR(int,TargetTiltAngle,0,-90,90);
- CREATE_CHAR(uint8_t,TargetHeaterCoolerState,0,0,2);
- CREATE_CHAR(uint32_t,SetDuration,60,0,3600);
- CREATE_CHAR(int,TargetHorizontalTiltAngle,0,-90,90);
- CREATE_CHAR(uint8_t,TargetHumidifierDehumidifierState,0,0,2);
- CREATE_CHAR(uint8_t,TargetPosition,0,0,100);
- CREATE_CHAR(uint8_t,TargetDoorState,1,0,1);
- CREATE_CHAR(uint8_t,TargetHeatingCoolingState,0,0,3);
- CREATE_CHAR(uint8_t,TargetMediaState,0,0,2);
- CREATE_CHAR(double,TargetRelativeHumidity,0,0,100);
- CREATE_CHAR(double,TargetTemperature,16,10,38);
- CREATE_CHAR(uint8_t,TargetVisibilityState,0,0,1);
- CREATE_CHAR(uint8_t,TemperatureDisplayUnits,0,0,1);
- CREATE_CHAR(int,TargetVerticalTiltAngle,0,-90,90);
- CREATE_CHAR(uint8_t,ValveType,0,0,3);
- CREATE_CHAR(const char *,Version,"1.0.0",0,1);
- CREATE_CHAR(double,VOCDensity,0,0,1000);
- CREATE_CHAR(uint8_t,Volume,0,0,100);
- CREATE_CHAR(uint8_t,VolumeControlType,0,0,3);
- CREATE_CHAR(uint8_t,VolumeSelector,0,0,1);
- CREATE_CHAR(double,WaterLevel,0,0,100);
+ CREATE_CHAR(uint32_t,AccessoryFlags,1,1,1); // not applicable for HomeSpan
+ CREATE_CHAR(uint8_t,Active,0,0,1,INACTIVE,ACTIVE); // indicates if the Service is active/on
+ CREATE_CHAR(uint32_t,ActiveIdentifier,0,0,255); // numerical Identifier of the InputSource selected in the Home App.
+ CREATE_CHAR(uint8_t,AirQuality,0,0,5,UNKNOWN,EXCELLENT,GOOD,FAIR,INFERIOR,POOR); // a subjective description
+ CREATE_CHAR(uint8_t,BatteryLevel,100,0,100); // measured as a percentage
+ CREATE_CHAR(int,Brightness,0,0,100); // measured as a percentage
+ CREATE_CHAR(double,CarbonMonoxideLevel,0,0,100); // measured in parts per million (ppm)
+ CREATE_CHAR(double,CarbonMonoxidePeakLevel,0,0,100); // measured in parts per million (ppm)
+ CREATE_CHAR(uint8_t,CarbonMonoxideDetected,0,0,1,NORMAL,ABNORMAL); // indicates if abnormal level is detected
+ CREATE_CHAR(double,CarbonDioxideLevel,0,0,100000); // measured on parts per million (ppm)
+ CREATE_CHAR(double,CarbonDioxidePeakLevel,0,0,100000); // measured in parts per million (ppm)
+ CREATE_CHAR(uint8_t,CarbonDioxideDetected,0,0,1,NORMAL,ABNORMAL); // indicates if abnormal level is detected
+ CREATE_CHAR(uint8_t,ChargingState,0,0,2,NOT_CHARGING,CHARGING,NOT_CHARGEABLE); // indicates state of battery charging
+ CREATE_CHAR(uint8_t,ClosedCaptions,0,0,1); // unused by any Service
+ CREATE_CHAR(double,CoolingThresholdTemperature,10,10,35); // cooling turns on when temperature (in Celsius) rises above this threshold
+ CREATE_CHAR(uint32_t,ColorTemperature,200,140,500); // measured in inverse megaKelvin (= 1,000,000 / Kelvin)
+ CREATE_CHAR(uint8_t,ContactSensorState,1,0,1,DETECTED,NOT_DETECTED); // indictates if contact is detected (i.e. closed)
+ CREATE_CHAR(const char *,ConfiguredName,"unnamed",0,1); // default display name of this Service
+ CREATE_CHAR(double,CurrentAmbientLightLevel,1,0.0001,100000); // measured in Lux (lumens/m2
+ CREATE_CHAR(int,CurrentHorizontalTiltAngle,0,-90,90); // current angle (in degrees) of slats from fully up (-90) to fully open (0) to fully down (90)
+ CREATE_CHAR(uint8_t,CurrentAirPurifierState,0,0,2,INACTIVE,IDLE,PURIFYING); // indicates current state of air purification
+ CREATE_CHAR(uint8_t,CurrentSlatState,0,0,2,FIXED,JAMMED,SWINGING); // indicates current state of slats
+ CREATE_CHAR(uint8_t,CurrentPosition,0,0,100); // current position (as a percentage) from fully closed (0) to full open (100)
+ CREATE_CHAR(int,CurrentVerticalTiltAngle,0,-90,90); // current angle (in degrees) of slats from fully left (-90) to fully open (0) to fully right (90)
+ CREATE_CHAR(uint8_t,CurrentVisibilityState,0,0,1,VISIBLE,NOT_VISIBLE); // current visibility of the Service, as selectable on the Settings Page of the Home App
+ CREATE_CHAR(uint8_t,CurrentHumidifierDehumidifierState,1,0,3,INACTIVE,IDLE,HUMIDIFYING,DEHUMIDIFYING); // indicates current state of humidifier/dehumidifer
+ CREATE_CHAR(uint8_t,CurrentDoorState,1,0,4,OPEN,CLOSED,OPENING,CLOSING,STOPPED); // indicates current state of a door
+ CREATE_CHAR(uint8_t,CurrentFanState,1,0,2,INACTIVE,IDLE,BLOWING); // indicates current state of a fan
+ CREATE_CHAR(uint8_t,CurrentHeatingCoolingState,0,0,2,IDLE,HEATING,COOLING); // indicates whether appliance is currently heating, cooling, or just idle
+ CREATE_CHAR(uint8_t,CurrentHeaterCoolerState,1,0,3,INACTIVE,IDLE,HEATING,COOLING); // indicates whether appliance is currently heating, cooling, idle, or off
+ CREATE_CHAR(uint8_t,CurrentMediaState,0,0,5); // not used
+ CREATE_CHAR(double,CurrentRelativeHumidity,0,0,100); // current humidity measured as a percentage
+ CREATE_CHAR(double,CurrentTemperature,0,0,100); // current temperature measured in Celsius
+ CREATE_CHAR(int,CurrentTiltAngle,0,-90,90); // current angle (in degrees) of slats from fully up or left (-90) to fully open (0) to fully down or right (90)
+ CREATE_CHAR(double,FilterLifeLevel,100,0,100); // measured as a percentage of remaining life
+ CREATE_CHAR(uint8_t,FilterChangeIndication,0,0,1,NO_CHANGE_NEEDED,CHANGE_NEEDED); // indicates state of filter
+ CREATE_CHAR(const char *,FirmwareRevision,"1.0.0",0,1); // must be in form x[.y[.z]] - informational only
+ CREATE_CHAR(const char *,HardwareRevision,"1.0.0",0,1); // must be in form x[.y[.z]] - informational only
+ CREATE_CHAR(double,HeatingThresholdTemperature,16,0,25); // heating turns on when temperature (in Celsius) falls below this threshold
+ CREATE_CHAR(boolean,HoldPosition,false,0,1); // deprecated
+ CREATE_CHAR(double,Hue,0,0,360); // color (in degrees) from red (0) to green (120) to blue (240) and back to red (360)
+ CREATE_CHAR(boolean,Identify,1,1,1,RUN_ID=1); // triggers an update when HomeKit wants HomeSpan to run its identification routine for an Accessory
+ CREATE_CHAR(uint32_t,Identifier,0,0,255); // numerical Identifer of the InputSource.
+ CREATE_CHAR(uint8_t,InputDeviceType,0,0,6); // not used
+ CREATE_CHAR(uint8_t,InputSourceType,0,0,10); // not used
+ CREATE_CHAR(uint8_t,InUse,0,0,1,NOT_IN_USE,IN_USE); // if Service is set to active, this indictes whether it is currently in use
+ CREATE_CHAR(uint8_t,IsConfigured,0,0,1,NOT_CONFIGURED,CONFIGURED); // indicates if a predefined Service has been configured
+ CREATE_CHAR(uint8_t,LeakDetected,0,0,1,NOT_DETECTED,DETECTED); // indictates if a leak is detected
+ CREATE_CHAR(uint8_t,LockCurrentState,0,0,3,UNLOCKED,LOCKED,JAMMED,UNKNOWN); // indicates state of a lock
+ CREATE_CHAR(uint8_t,LockPhysicalControls,0,0,1,CONTROL_LOCK_DISABLED,CONTROL_LOCK_ENABLED); // indicates if local control lock is enabled
+ CREATE_CHAR(uint8_t,LockTargetState,0,0,1,UNLOCK,LOCK); // indicates desired state of lock
+ CREATE_CHAR(const char *,Manufacturer,"HomeSpan",0,1); // any string - informational only
+ CREATE_CHAR(const char *,Model,"HomeSpan-ESP32",0,1); // any string - informational only
+ CREATE_CHAR(boolean,MotionDetected,0,0,1,NOT_DETECTED,DETECTED); // indicates if motion is detected
+ CREATE_CHAR(boolean,Mute,0,0,1,OFF,ON); // not used
+ CREATE_CHAR(const char *,Name,"unnamed",0,1); // default display name of the Accessory
+ CREATE_CHAR(double,NitrogenDioxideDensity,0,0,1000); // measured in µg/m3
+ CREATE_CHAR(boolean,ObstructionDetected,0,0,1,NOT_DETECTED,DETECTED); // indicates if obstruction is detected
+ CREATE_CHAR(double,PM25Density,0,0,1000); // 2.5-micron particulate density, measured in µg/m3
+ CREATE_CHAR(uint8_t,OccupancyDetected,0,0,1,NOT_DETECTED,DETECTED); // indicates if occupanccy is detected
+ CREATE_CHAR(boolean,OutletInUse,0,0,1,NOT_IN_USE,IN_USE); // indicates if an appliance or light is plugged into the outlet, regardless of whether on or off
+ CREATE_CHAR(boolean,On,0,0,1,OFF,ON); // indicates if the Service is active/on
+ CREATE_CHAR(double,OzoneDensity,0,0,1000); // measured in µg/m3
+ CREATE_CHAR(uint8_t,PictureMode,0,0,13); // not used
+ CREATE_CHAR(double,PM10Density,0,0,1000); // 10-micron particulate density, measured in µg/m3
+ CREATE_CHAR(uint8_t,PositionState,2,0,2,GOING_TO_MINIMUM,GOING_TO_MAXIMUM,STOPPED); // deprecated
+ CREATE_CHAR(uint8_t,PowerModeSelection,0,0,0,VIEW_SETTINGS); // when defined, creates a "View TV Settings" button in the Home App that triggers an update to this Characteristic when pressed
+ CREATE_CHAR(uint8_t,ProgramMode,0,0,2,NONE,SCHEDULED,SCHEDULE_OVERRIDEN); // indicates if pre-scheduled program is running
+ CREATE_CHAR(uint8_t,ProgrammableSwitchEvent,0,0,2,SINGLE_PRESS,DOUBLE_PRESS,LONG_PRESS); // specifies type of button press
+ CREATE_CHAR(double,RelativeHumidityDehumidifierThreshold,50,0,100); // dehumidfier turns on when humidity rises above this threshold
+ CREATE_CHAR(double,RelativeHumidityHumidifierThreshold,50,0,100); // humidfier turns on when humidity falls below this threshold
+ CREATE_CHAR(uint32_t,RemainingDuration,60,0,3600); // duration (in seconds) remaining for Service to be active/on
+ CREATE_CHAR(uint8_t,RemoteKey,4,4,15,UP=4,DOWN,LEFT,RIGHT,CENTER,BACK,PLAY_PAUSE=11,INFO=15); // triggers an update when the corresponding key is pressed in the Remote Control widget on an iPhone
+ CREATE_CHAR(uint8_t,ResetFilterIndication,1,1,1,RESET_FILTER=1); // triggers an update when the user chooses to reset the FilterChangeIndication (only appears in Eve App, not Home App)
+ CREATE_CHAR(int,RotationDirection,0,0,1,CLOCKWISE,COUNTERCLOCKWISE); // indicates the rotation direction of a fan
+ CREATE_CHAR(double,RotationSpeed,0,0,100); // measured as a percentage
+ CREATE_CHAR(double,Saturation,0,0,100); // color saturation, measured as a percentage
+ CREATE_CHAR(uint8_t,SecuritySystemAlarmType,0,0,1,KNOWN,UNKNOWN); // indicates whether alarm was triggered for known reason
+ CREATE_CHAR(uint8_t,SecuritySystemCurrentState,3,0,4,ARMED_STAY,ARMED_AWAY,ARMED_NIGHT,DISARMED,ALARM_TRIGGERED); // indicates current state of the security system
+ CREATE_CHAR(uint8_t,SecuritySystemTargetState,3,0,3,ARM_STAY,ARM_AWAY,ARM_NIGHT,DISARM); // indicates desired state of the security system
+ CREATE_CHAR(const char *,SerialNumber,"HS-12345",0,1); // any string - informational only
+ CREATE_CHAR(uint8_t,ServiceLabelIndex,1,1,255); // numerical index used to distinguish multiple copies of the same Service within an Accessory
+ CREATE_CHAR(uint8_t,ServiceLabelNamespace,1,0,1,DOTS,NUMERALS); // indicates how un-named Services linked together with a ServiceLabel Service should be displayed in the Home App
+ CREATE_CHAR(uint8_t,SlatType,0,0,1,HORIZONTAL,VERTICAL); // indicates the direction of a slat or group of slats
+ CREATE_CHAR(uint8_t,SleepDiscoveryMode,0,0,1); // not used
+ CREATE_CHAR(uint8_t,SmokeDetected,0,0,1,NOT_DETECTED,DETECTED); // indicates if smoke is detected
+ CREATE_CHAR(boolean,StatusActive,1,0,1,NOT_FUNCTIONING,FUNCTIONING); // indicates whether the Service is properly functioning
+ CREATE_CHAR(uint8_t,StatusFault,0,0,1,NO_FAULT,FAULT); // indicates whether the Service has a fault (only appears in Eve App, not Home App)
+ CREATE_CHAR(uint8_t,StatusJammed,0,0,1,NOT_JAMMED,JAMMED); // indicates whether the Service has been "jammed"
+ CREATE_CHAR(uint8_t,StatusLowBattery,0,0,1,NOT_LOW_BATTERY,LOW_BATTERY); // indicates state of battery
+ CREATE_CHAR(uint8_t,StatusTampered,0,0,1,NOT_TAMPERED,TAMPERED); // indicates whether the Service has been tampered with
+ CREATE_CHAR(double,SulphurDioxideDensity,0,0,1000); // measured in µg/m3
+ CREATE_CHAR(uint8_t,SwingMode,0,0,1,SWING_DISABLED,SWING_ENABLED); // indicates whether swing-mode is enabled
+ CREATE_CHAR(uint8_t,TargetAirPurifierState,1,0,1,MANUAL,AUTO); // indicates desired state of air purifier
+ CREATE_CHAR(uint8_t,TargetFanState,1,0,1,MANUAL,AUTO); // indicates desired state of fan
+ CREATE_CHAR(int,TargetTiltAngle,0,-90,90); // indicated desired angle (in degrees) of slats from fully up or left (-90) to fully open (0) to fully down or right (90)
+ CREATE_CHAR(uint8_t,TargetHeaterCoolerState,0,0,2,AUTO,HEAT,COOL); // indicates desired state of heater/cooler
+ CREATE_CHAR(uint32_t,SetDuration,60,0,3600); // specifies the duration (in seconds) for a Service to remain on once activated
+ CREATE_CHAR(int,TargetHorizontalTiltAngle,0,-90,90); // indicates desired angle (in degrees) of slats from fully up (-90) to fully open (0) to fully down (90)
+ CREATE_CHAR(uint8_t,TargetHumidifierDehumidifierState,0,0,2,AUTO,HUMIDIFY,DEHUMIDIFY); // indicates desired state of humidifier/dehumidifier
+ CREATE_CHAR(uint8_t,TargetPosition,0,0,100); // indicates target position (as a percentage) from fully closed (0) to full open (100)
+ CREATE_CHAR(uint8_t,TargetDoorState,1,0,1,OPEN,CLOSED); // indicates desired state of door
+ CREATE_CHAR(uint8_t,TargetHeatingCoolingState,0,0,3,OFF,HEAT,COOL,AUTO); // indicates desired state of appliance
+ CREATE_CHAR(uint8_t,TargetMediaState,0,0,2); // unused
+ CREATE_CHAR(double,TargetRelativeHumidity,0,0,100); // indicates desired humidity measured as a percentage
+ CREATE_CHAR(double,TargetTemperature,16,10,38); // indicates desired temperature measures in Celsius
+ CREATE_CHAR(uint8_t,TargetVisibilityState,0,0,1,VISIBLE,NOT_VISIBLE); // indicates desired visibility of the Service, as selectable on the Settings Page of the Home App
+ CREATE_CHAR(uint8_t,TemperatureDisplayUnits,0,0,1,CELSIUS,FAHRENHEIT); // indicates the desired units to display the temperature on the device itself (has no effect on Home App)
+ CREATE_CHAR(int,TargetVerticalTiltAngle,0,-90,90); // indicates desired angle (in degrees) of slats from fully left (-90) to fully open (0) to fully right (90)
+ CREATE_CHAR(uint8_t,ValveType,0,0,3,GENERIC,IRRIGATION,SHOWER_HEAD,FAUCET); // indicates the type of valve
+ CREATE_CHAR(const char *,Version,"1.0.0",0,1); // unused
+ CREATE_CHAR(double,VOCDensity,0,0,1000); // measured in µg/m3
+ CREATE_CHAR(uint8_t,Volume,0,0,100); // unused
+ CREATE_CHAR(uint8_t,VolumeControlType,3,0,3,NONE,RELATIVE,RELATIVE_CURRENT,ABSOLUTE); // indicates the type of volume control
+ CREATE_CHAR(uint8_t,VolumeSelector,0,0,1,VOLUME_UP,VOLUME_DOWN); // triggered by presses to the iPhone's volume up/down buttons when TV is selected in the Remote Control widget
+ CREATE_CHAR(double,WaterLevel,0,0,100); // measured as a percentage
}
diff --git a/src/TLV.h b/src/TLV.h
deleted file mode 100644
index 505c4f8..0000000
--- a/src/TLV.h
+++ /dev/null
@@ -1,314 +0,0 @@
-/*********************************************************************************
- * 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.
- *
- ********************************************************************************/
-
-#pragma once
-
-template
-class TLV {
-
- int cLen; // total number of bytes in all defined TLV records, including TAG andf LEN (suitable for use as Content-Length in HTTP Body)
- int numTags; // actual number of tags defined
-
- struct tlv_t {
- tagType tag; // TAG
- int len; // LENGTH
- uint8_t *val; // VALUE buffer
- int maxLen; // maximum length of VALUE buffer
- const char *name; // abbreviated name of this TAG
- };
-
- tlv_t tlv[maxTags]; // pointer to array of TLV record structures
- tlv_t *find(tagType tag); // returns pointer to TLV record with matching TAG (or NULL if no match)
-
-public:
-
- TLV();
-
- int create(tagType tag, int maxLen, const char *name); // creates a new TLV record of type 'tag' with 'maxLen' bytes and display 'name'
-
- void clear(); // clear all TLV structures
- int val(tagType tag); // returns VAL for TLV with matching TAG (or -1 if no match)
- int val(tagType tag, uint8_t val); // sets and returns VAL for TLV with matching TAG (or -1 if no match)
- uint8_t *buf(tagType tag); // returns VAL Buffer for TLV with matching TAG (or NULL if no match)
- uint8_t *buf(tagType tag, int len); // set length and returns VAL Buffer for TLV with matching TAG (or NULL if no match or if LEN>MAX)
- int len(tagType tag); // returns LEN for TLV matching TAG (or 0 if TAG is found but LEN not yet set; -1 if no match at all)
- void print(int minLogLevel=0); // prints all defined TLVs (those with length>0), subject to specified minimum log level
- int unpack(uint8_t *tlvBuf, int nBytes); // unpacks nBytes of TLV content from single byte buffer into individual TLV records (return 1 on success, 0 if fail)
- int pack(uint8_t *tlvBuf); // if tlvBuf!=NULL, packs all defined TLV records (LEN>0) into a single byte buffer, spitting large TLVs into separate 255-byte chunks. Returns number of bytes (that would be) stored in buffer
- int pack_old(uint8_t *buf); // packs all defined TLV records (LEN>0) into a single byte buffer, spitting large TLVs into separate 255-byte records. Returns number of bytes stored in buffer
-
-}; // TLV
-
-//////////////////////////////////////
-// TLV contructor()
-
-template
-TLV::TLV(){
- numTags=0;
-}
-
-//////////////////////////////////////
-// TLV create(tag, maxLen, name)
-
-template
-int TLV::create(tagType tag, int maxLen, const char *name){
-
- if(numTags==maxTags){
- Serial.print("\n*** ERROR: Can't create new TLC tag type with name='");
- Serial.print(name);
- Serial.print("' - exceeded number of records reserved\n\n");
- return(0);
- }
-
- tlv[numTags].tag=tag;
- tlv[numTags].maxLen=maxLen;
- tlv[numTags].name=name;
- tlv[numTags].len=-1;
- tlv[numTags].val=(uint8_t *)malloc(maxLen);
- numTags++;
-
- return(1);
-}
-
-//////////////////////////////////////
-// TLV find(tag)
-
-template
-typename TLV::tlv_t *TLV::find(tagType tag){
-
- for(int i=0;i
-void TLV::clear(){
-
- cLen=0;
-
- for(int i=0;i
-int TLV::val(tagType tag){
-
- tlv_t *tlv=find(tag);
-
- if(tlv && tlv->len>0)
- return(tlv->val[0]);
-
- return(-1);
-}
-
-//////////////////////////////////////
-// TLV val(tag, val)
-
-template
-int TLV::val(tagType tag, uint8_t val){
-
- tlv_t *tlv=find(tag);
-
- if(tlv){
- tlv->val[0]=val;
- tlv->len=1;
- cLen+=tlv->len+2;
- return(val);
- }
-
- return(-1);
-}
-
-//////////////////////////////////////
-// TLV buf(tag)
-
-template
-uint8_t *TLV::buf(tagType tag){
-
- tlv_t *tlv=find(tag);
-
- if(tlv)
- return(tlv->val);
-
- return(NULL);
-}
-
-//////////////////////////////////////
-// TLV buf(tag, len)
-
-template
-uint8_t *TLV::buf(tagType tag, int len){
-
- tlv_t *tlv=find(tag);
-
- if(tlv && len<=tlv->maxLen){
- tlv->len=len;
- cLen+=tlv->len;
-
- for(int i=0;ilen;i+=255)
- cLen+=2;
-
- return(tlv->val);
- }
-
- return(NULL);
-}
-
-//////////////////////////////////////
-// TLV print()
-
-template
-void TLV::print(int minLogLevel){
-
- if(homeSpan.getLogLevel()0){
- Serial.printf("%s(%d) ",tlv[i].name,tlv[i].len);
-
- for(int j=0;j0
- } // loop over all TLVs
-}
-
-//////////////////////////////////////
-// TLV pack(tlvBuf)
-
-template
-int TLV::pack(uint8_t *tlvBuf){
-
- int n=0;
- int nBytes;
-
- for(int i=0;i0){
- for(int j=0;j255?255:nBytes;
- memcpy(tlvBuf,tlv[i].val+j,nBytes>255?255:nBytes);
- tlvBuf+=nBytes>255?255:nBytes;
- }
- n+=(nBytes>255?255:nBytes)+2;
- } // j-loop
- } // len>0
-
- } // loop over all TLVs
-
-return(n);
-}
-
-//////////////////////////////////////
-// TLV len(tag)
-
-template
-int TLV::len(tagType tag){
-
- tlv_t *tlv=find(tag);
-
- if(tlv)
- return(tlv->len>0?tlv->len:0);
-
- return(-1);
-}
-
-//////////////////////////////////////
-// TLV unpack(tlvBuf, nBytes)
-
-template
-int TLV::unpack(uint8_t *tlvBuf, int nBytes){
-
- clear();
-
- tagType tag;
- int tagLen;
- uint8_t *val;
- int currentLen;
- int state=0;
-
- for(int i=0;i maxLen)
- clear();
- return(0);
- }
-
- val+=currentLen; // move val to end of current length (tag repeats to load more than 255 bytes)
-
- if(tagLen==0) // no bytes to read
- state=0;
- else // move to next state
- state=2;
- break;
-
- case 2: // ready to read another byte into VAL
- *val=tlvBuf[i]; // copy byte into VAL buffer
- val++; // increment VAL buffer (already checked for sufficient length above)
- tagLen--; // decrement number of bytes to continue copying
- if(tagLen==0) // no more bytes to copy
- state=0;
- break;
-
- } // switch
- } // for-loop
-
- if(state==0) // should always end back in state=0
- return(1); // return success
-
- clear();
- return(0); // return fail
-}
diff --git a/src/TLV8.cpp b/src/TLV8.cpp
new file mode 100644
index 0000000..9fd6e16
--- /dev/null
+++ b/src/TLV8.cpp
@@ -0,0 +1,243 @@
+/*********************************************************************************
+ * 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.
+ *
+ ********************************************************************************/
+
+#include "TLV8.h"
+
+//////////////////////////////////////
+
+tlv8_t::tlv8_t(uint8_t tag, size_t len, const uint8_t* val) : tag{tag}, len{len} {
+ if(len>0){
+ this->val=std::unique_ptr((uint8_t *)HS_MALLOC(len));
+ if(val!=NULL)
+ memcpy((this->val).get(),val,len);
+ }
+}
+
+//////////////////////////////////////
+
+void tlv8_t::update(size_t addLen, const uint8_t *addVal){
+ if(addLen>0){
+ uint8_t *p=val.release();
+ p=(uint8_t *)HS_REALLOC(p,len+addLen);
+ val=std::unique_ptr(p);
+ if(addVal!=NULL)
+ memcpy(p+len,addVal,addLen);
+ len+=addLen;
+ }
+}
+
+/////////////////////////////////////
+
+void tlv8_t::osprint(std::ostream& os){
+
+ uint8_t *p=val.get(); // starting pointer
+ uint8_t *pend=p+len; // ending pointer (may equal starting if len=0)
+
+ do{
+ uint8_t nBytes=(pend-p)>255?255:(pend-p); // max is 255 bytes per TLV record
+ os.write((char *)&tag,1);
+ os.write((char *)&nBytes,1);
+ os.write((char *)p,nBytes);
+ p+=nBytes;
+ } while(p255)
+ nBytes+=2*(((*it1).len-1)/255);
+ it1++;
+ }
+
+ return(nBytes);
+}
+
+/////////////////////////////////////
+
+size_t TLV8::pack(uint8_t *buf, size_t bufSize){
+
+ size_t nBytes=0;
+
+ while(nBytes255)
+ currentPackLen=255;
+ *buf++=currentPackLen;
+ nBytes++;
+ currentPackPhase=3;
+ break;
+
+ case 3:
+ if(currentPackLen==0){
+ if(endPackBuf==currentPackBuf){
+ currentPackIt++;
+ currentPackPhase=0;
+ } else {
+ currentPackPhase=1;
+ }
+ break;
+ }
+
+ size_t copyBytes=(currentPackLen<(bufSize-nBytes)) ? currentPackLen : (bufSize-nBytes);
+ memcpy(buf,currentPackBuf,copyBytes);
+ buf+=copyBytes;
+ currentPackBuf+=copyBytes;
+ currentPackLen-=copyBytes;
+ nBytes+=copyBytes;
+ break;
+ }
+ }
+
+ return(nBytes);
+}
+
+/////////////////////////////////////
+
+void TLV8::unpack(uint8_t *buf, size_t bufSize){
+
+ if(empty())
+ unpackPhase=0;
+
+ while(bufSize>0){
+ switch(unpackPhase){
+
+ case 0:
+ unpackTag=*buf++;
+ bufSize--;
+ unpackPhase=1;
+ break;
+
+ case 1:
+ unpackBytes=*buf++;
+ bufSize--;
+ if(unpackBytes==0){
+ add(unpackTag);
+ unpackPhase=0;
+ } else {
+ unpackPhase=2;
+ }
+ break;
+
+ case 2:
+ size_t copyBytes=unpackBytes
+#include
+#include
+#include
+
+#include "PSRAM.h"
+
+struct tlv8_t {
+ uint8_t tag;
+ size_t len;
+ std::unique_ptr val;
+
+ tlv8_t(uint8_t tag, size_t len, const uint8_t* val);
+ void update(size_t addLen, const uint8_t *addVal);
+ void osprint(std::ostream& os);
+
+ operator uint8_t*() const{
+ return(val.get());
+ }
+
+};
+
+/////////////////////////////////////
+
+typedef std::forward_list>::iterator TLV8_it;
+typedef struct { const uint8_t tag; const char *name; } TLV8_names;
+
+/////////////////////////////////////
+
+class TLV8 : public std::forward_list> {
+
+ TLV8_it currentPackIt;
+ TLV8_it endPackIt;
+ uint8_t *currentPackBuf;
+ uint8_t *endPackBuf;
+ int currentPackPhase;
+ size_t currentPackLen;
+
+ uint8_t unpackTag;
+ size_t unpackBytes;
+ int unpackPhase;
+
+ const TLV8_names *names=NULL;
+ int nNames=0;
+
+ public:
+
+ TLV8(){};
+ TLV8(const TLV8_names *names, int nNames) : names{names}, nNames{nNames} {};
+
+ TLV8_it add(uint8_t tag, size_t len, const uint8_t *val);
+ TLV8_it add(uint8_t tag, uint8_t val){return(add(tag, 1, &val));}
+ TLV8_it add(uint8_t tag){return(add(tag, 0, NULL));}
+
+ TLV8_it find(uint8_t tag, TLV8_it it1, TLV8_it it2);
+ TLV8_it find(uint8_t tag, TLV8_it it1){return(find(tag, it1, end()));}
+ TLV8_it find(uint8_t tag){return(find(tag, begin(), end()));}
+
+ int len(TLV8_it it){return(it==end()?-1:(*it).len);}
+
+ size_t pack_size(TLV8_it it1, TLV8_it it2);
+ size_t pack_size(){return(pack_size(begin(), end()));}
+
+ void pack_init(TLV8_it it1, TLV8_it it2){currentPackIt=it1; endPackIt=it2; currentPackPhase=0;}
+ void pack_init(TLV8_it it1){pack_init(it1, it1++);}
+ void pack_init(){pack_init(begin(),end());}
+
+ size_t pack(uint8_t *buf, size_t bufSize);
+ size_t pack(uint8_t *buf){pack_init(); return(pack(buf,pack_size()));}
+
+ const char *getName(uint8_t tag);
+
+ void print(TLV8_it it1, TLV8_it it2);
+ void print(TLV8_it it1){print(it1, it1++);}
+ void print(){print(begin(), end());}
+
+ void osprint(std::ostream& os, TLV8_it it1, TLV8_it it2);
+ void osprint(std::ostream& os, TLV8_it it1){osprint(os, it1, it1++);}
+ void osprint(std::ostream& os){osprint(os, begin(), end());}
+
+ void unpack(uint8_t *buf, size_t bufSize);
+
+ void wipe(){std::forward_list>().swap(*this);}
+
+};
diff --git a/src/Utils.cpp b/src/Utils.cpp
index 7af158e..0b2e46c 100644
--- a/src/Utils.cpp
+++ b/src/Utils.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
*
@@ -278,4 +278,4 @@ void PushButton::reset(){
//////////////////////////////////////
-touch_value_t PushButton::threshold=0;
+PushButton::touch_value_t PushButton::threshold=0;
diff --git a/src/Utils.h b/src/Utils.h
index 0a06462..255d602 100644
--- a/src/Utils.h
+++ b/src/Utils.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
*
@@ -28,7 +28,8 @@
#pragma once
#include
-#include
+
+#include "PSRAM.h"
namespace Utils {
@@ -42,27 +43,58 @@ String mask(char *c, int n); // simply utility that creates a String fr
// going out of scope
template
-struct TempBuffer {
- bufType *buf;
- int nBytes;
+class TempBuffer {
+
+ private:
- TempBuffer(size_t len){
- nBytes=len*sizeof(bufType);
- buf=(bufType *)heap_caps_malloc(nBytes,MALLOC_CAP_8BIT);
+ bufType *buf=NULL;
+ size_t nElements;
+
+ public:
+
+ TempBuffer(size_t _nElements=1) : nElements(_nElements) {
+ buf=(bufType *)HS_MALLOC(nElements*sizeof(bufType));
if(buf==NULL){
- Serial.print("\n\n*** FATAL ERROR: Requested allocation of ");
- Serial.print(nBytes);
- Serial.print(" bytes failed. Program Halting.\n\n");
+ Serial.printf("\n\n*** FATAL ERROR: Requested allocation of %d bytes failed. Program Halting.\n\n",nElements*sizeof(bufType));
while(1);
}
}
+ TempBuffer(bufType *addBuf...) : nElements(0) {
+ va_list args;
+ va_start(args,addBuf);
+ while(addBuf!=NULL){
+ size_t addElements=va_arg(args,size_t);
+ buf=(bufType *)HS_REALLOC(buf,(nElements+addElements)*sizeof(bufType));
+ if(buf==NULL){
+ Serial.printf("\n\n*** FATAL ERROR: Requested allocation of %d bytes failed. Program Halting.\n\n",nElements*sizeof(bufType));
+ while(1);
+ }
+ memcpy(buf+nElements,addBuf,addElements*sizeof(bufType));
+ nElements+=addElements;
+ addBuf=va_arg(args,bufType *);
+ }
+ va_end(args);
+ }
+
~TempBuffer(){
- heap_caps_free(buf);
+ free(buf);
}
int len(){
- return(nBytes);
+ return(nElements*sizeof(bufType));
+ }
+
+ int size(){
+ return(nElements);
+ }
+
+ bufType *get(){
+ return(buf);
+ }
+
+ operator bufType*() const{
+ return(buf);
}
};
@@ -71,12 +103,6 @@ struct TempBuffer {
// PushButton //
////////////////////////////////
-#if SOC_TOUCH_VERSION_2
-typedef uint32_t touch_value_t;
-#else
-typedef uint16_t touch_value_t;
-#endif
-
class PushButton{
int status;
@@ -85,15 +111,23 @@ class PushButton{
uint32_t singleAlarm;
uint32_t doubleAlarm;
uint32_t longAlarm;
+
+#if SOC_TOUCH_VERSION_2
+ typedef uint32_t touch_value_t;
+#else
+ typedef uint16_t touch_value_t;
+#endif
static touch_value_t threshold;
static const int calibCount=20;
+
+ public:
+
+ typedef boolean (*triggerType_t)(int pin);
protected:
int pressType;
- typedef boolean (*triggerType_t)(int pin);
-
int pin;
triggerType_t triggerType;
diff --git a/src/src.ino b/src/src.ino
index d82cf30..43de092 100644
--- a/src/src.ino
+++ b/src/src.ino
@@ -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,66 +27,60 @@
#include "HomeSpan.h"
-struct LED_Service : Service::LightBulb {
-
- int ledPin;
- SpanCharacteristic *power;
-
- LED_Service(int ledPin) : Service::LightBulb(){
- power=new Characteristic::On();
- this->ledPin=ledPin;
- pinMode(ledPin,OUTPUT);
- }
-
- boolean update(){
- digitalWrite(ledPin,power->getNewVal());
- return(true);
- }
-
-};
-
-//////////////////////////////////////
-
-struct invertedLED : Blinkable { // create a child class derived from Blinkable
-
- int pin; // variable to store the pin number
-
- invertedLED(int pin) : pin{pin} { // constructor that initializes the pin parameter
- pinMode(pin,OUTPUT); // set the pin to OUTPUT
- digitalWrite(pin,HIGH); // set pin HIGH (which is off for an inverted LED)
- }
-
- void on() override { digitalWrite(pin,LOW); } // required function on() - sets pin LOW
- void off() override { digitalWrite(pin,HIGH); } // required function off() - sets pin HIGH
- int getPin() override { return(pin); } // required function getPin() - returns pin number
-};
-
-
-//////////////////////////////////////
+#define MAX_LIGHTS 2
void setup() {
-
+
Serial.begin(115200);
-// homeSpan.setLogLevel(-1);
-// homeSpan.setSerialInputDisable(true);
- homeSpan.enableOTA();
+ homeSpan.setLogLevel(1);
+ homeSpan.enableWebLog(50,"pool.ntp.org","UTC",NULL);
+// homeSpan.enableWebLog(50,"pool.ntp.org","UTC","myStatus");
+// homeSpan.enableWebLog(50,NULL,NULL,NULL);
- homeSpan.setStatusDevice(new invertedLED(13)); // set Status LED to be a new Blinkable device attached to pin 13
- homeSpan.setStatusAutoOff(30);
+ homeSpan.begin(Category::Lighting,"HomeSpan Max");
- homeSpan.begin(Category::Lighting,"HomeSpan LED");
-
- new SpanAccessory();
- new Service::AccessoryInformation();
+ new SpanAccessory();
+ new Service::AccessoryInformation();
new Characteristic::Identify();
- new LED_Service(13);
+
+ for(int i=0;i
+#include "PwmPin.h"
[[maybe_unused]] static const char* STEPPER_TAG = "StepperControl";
@@ -103,3 +104,12 @@ class StepperControl {
};
//////////////////////////
+
+#include "Stepper_UNIPOLAR.h"
+#include "Stepper_TB6612.h" // https://www.adafruit.com/product/2448
+#include "Stepper_A3967.h" // https://www.sparkfun.com/products/12779
+
+
+struct Stepper_ULN2003A : Stepper_UNIPOLAR {
+ Stepper_ULN2003A(int IN1, int IN2, int IN3, int IN4, std::pair taskParams = {1,0}) : Stepper_UNIPOLAR(IN1,IN3,IN2,IN4,taskParams){}
+};
diff --git a/src/src/extras/Stepper_A3967.h b/src/src/extras/Stepper_A3967.h
index e13beca..31f9371 100644
--- a/src/src/extras/Stepper_A3967.h
+++ b/src/src/extras/Stepper_A3967.h
@@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
- * Copyright (c) 2023 Gregg E. Berman
+ * Copyright (c) 2023-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*
@@ -25,6 +25,8 @@
*
********************************************************************************/
+#pragma once
+
// Implementation of StepperControl for a Sparkfun A3967 EasyDriver Stepper Motor Driver
// Breakout Board (https://www.sparkfun.com/products/12779)
@@ -37,10 +39,6 @@
// disabled (no current / high impedence). The EasyDriver board does NOT support
// the short brake mode.
-#pragma once
-
-#include "StepperControl.h"
-
//////////////////////////
struct Stepper_A3967 : StepperControl {
diff --git a/src/src/extras/Stepper_TB6612.h b/src/src/extras/Stepper_TB6612.h
index b8bf06a..cae82c5 100644
--- a/src/src/extras/Stepper_TB6612.h
+++ b/src/src/extras/Stepper_TB6612.h
@@ -1,7 +1,7 @@
/*********************************************************************************
* MIT License
*
- * Copyright (c) 2023 Gregg E. Berman
+ * Copyright (c) 2023-2024 Gregg E. Berman
*
* https://github.com/HomeSpan/HomeSpan
*
@@ -25,6 +25,8 @@
*
********************************************************************************/
+#pragma once
+
// Implementation of StepperControl for an Adafruit TB6612 1.2A DC/Stepper Motor Driver
// Breakout Board (https://www.adafruit.com/product/2448)
@@ -44,11 +46,6 @@
// In either configuration the motor outputs can be enabled (current running through the coils)
// disabled (no current / high impedence) or set to a short brake.
-#pragma once
-
-#include "StepperControl.h"
-#include "PwmPin.h"
-
//////////////////////////
struct Stepper_TB6612 : StepperControl {
diff --git a/src/src/extras/Stepper_UNIPOLAR.h b/src/src/extras/Stepper_UNIPOLAR.h
new file mode 100644
index 0000000..dcc83c4
--- /dev/null
+++ b/src/src/extras/Stepper_UNIPOLAR.h
@@ -0,0 +1,169 @@
+/*********************************************************************************
+ * MIT License
+ *
+ * Copyright (c) 2024 Gregg E. Berman
+ *
+ * https://github.com/HomeSpan/HomeSpan
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining a copy
+ * of this software and associated documentation files (the "Software"), to deal
+ * in the Software without restriction, including without limitation the rights
+ * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+ * copies of the Software, and to permit persons to whom the Software is
+ * furnished to do so, subject to the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be included in all
+ * copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+ * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+ * SOFTWARE.
+ *
+ ********************************************************************************/
+
+#pragma once
+
+// Implementation of a basic 4-wire controller for a center-tapped Unipolar Stepper Motor
+// with two coils (Coil 1 and Coil 2) each having two driving inputs (A and B).
+//
+// Requires 4 pins on the ESP32 connected to an appropriate driver circuit, such as a set
+// of Darlington transitors, that are in turn connected to each of the 4 Stepper Motor wires:
+//
+// * Coil 1, Input A (1A)
+// * Coil 1, Input B (1B)
+// * Coil 2, Input A (2A)
+// * Coil 2, Input B (2B)
+//
+// When any of the pins are HIGH, the driver circuit should cause current to flow in the corresponding
+// half of the coil. When the pin is set LOW, the driver circuit should stop the flow of current through
+// that half of the coil. Supported modes and driving logic are as follows:
+//
+// FULL_STEP_ONE_PHASE (4 steps, where current flows only through ONE of the phases of ONE of the coils at each step):
+//
+// 1A 2A 1B 2B
+// Step 1: HI -- -- --
+// Step 2: -- HI -- --
+// Step 3: -- -- HI --
+// Step 4: -- -- -- HI
+//
+// FULL_STEP_TWO_PHASE (4 steps, where current flows through ONE of the phases of EACH of the coils at each step):
+//
+// 1A 2A 1B 2B
+// Step 1: HI HI -- --
+// Step 2: -- HI HI --
+// Step 3: -- -- HI HI
+// Step 4: HI -- -- HI
+//
+// HALF_STEP (8 steps that alternate between the 4 steps of the FULL_STEP modes above):
+//
+// 1A 2A 1B 2B
+// Step 1: HI -- -- --
+// Step 2: HI HI -- --
+// Step 3: -- HI -- --
+// Step 4: -- HI HI --
+// Step 5: -- -- HI --
+// Step 6: -- -- HI HI
+// Step 7: -- -- -- HI
+// Step 8: HI -- -- HI
+
+// NOTE ORDER OF CONSTRUCTOR PARAMETERS: First the two pins that drive the A and B side of Coil 1,
+// followed by the two pints that drive the A and B side 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.
+
+// Note: This driver supports enabling and disabling all current flow, but does NOT support a short brake.
+
+//////////////////////////
+
+struct Stepper_UNIPOLAR : StepperControl {
+
+ int c1A, c1B, c2A, c2B;
+ uint8_t phase, nPhases;
+ double offset;
+
+//////////////////////////
+
+ Stepper_UNIPOLAR(int coil1A, int coil1B, int coil2A, int coil2B, std::pair taskParams = {1,0}) : StepperControl(taskParams.first,taskParams.second) {
+
+ c1A=coil1A;
+ c1B=coil1B;
+ c2A=coil2A;
+ c2B=coil2B;
+
+ pinMode(c1A,OUTPUT);
+ pinMode(c1B,OUTPUT);
+ pinMode(c2A,OUTPUT);
+ pinMode(c2B,OUTPUT);
+
+ setStepType(FULL_STEP_ONE_PHASE);
+ }
+
+//////////////////////////
+
+ void onEnable() override {
+ setPins();
+ }
+
+//////////////////////////
+
+ void onDisable() override {
+ digitalWrite(c1A,0);
+ digitalWrite(c1B,0);
+ digitalWrite(c2A,0);
+ digitalWrite(c2B,0);
+ }
+
+//////////////////////////
+
+ void onStep(boolean direction) override {
+ if(direction)
+ phase=(phase+1)%nPhases;
+ else
+ phase=(phase+nPhases-1)%nPhases;
+
+ setPins();
+ }
+
+//////////////////////////
+
+ void setPins(){
+ float levelA=cos(phase*TWO_PI/nPhases+offset)*100.0;
+ float levelB=sin(phase*TWO_PI/nPhases+offset)*100.0;
+ digitalWrite(c1A,levelA>0.01);
+ digitalWrite(c1B,levelA<-0.01);
+ digitalWrite(c2A,levelB>0.01);
+ digitalWrite(c2B,levelB<-0.01);
+ }
+
+//////////////////////////
+
+ StepperControl *setStepType(int mode) override {
+
+ switch(mode){
+ case FULL_STEP_ONE_PHASE:
+ phase=0;
+ nPhases=4;
+ offset=0;
+ break;
+ case FULL_STEP_TWO_PHASE:
+ phase=0;
+ nPhases=4;
+ offset=TWO_PI/8.0;
+ break;
+ case HALF_STEP:
+ phase=0;
+ nPhases=8;
+ offset=0;
+ break;
+ default:
+ ESP_LOGE(STEPPER_TAG,"Unknown StepType=%d",mode);
+ }
+ return(this);
+ }
+
+};
diff --git a/src/src/extras/extras.ino b/src/src/extras/extras.ino
index 9a8d440..c86d0cc 100644
--- a/src/src/extras/extras.ino
+++ b/src/src/extras/extras.ino
@@ -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
*
@@ -28,8 +28,7 @@
// This is a placeholder .ino file that allows you to easily edit the contents of this files using the Arduino IDE,
// as well as compile and test from this point. This file is ignored when the library is included in other sketches.
-#include "Stepper_TB6612.h" // include the driver for a TB6612 chip
-#include "Stepper_A3967.h"
+#include "StepperControl.h"
StepperControl *bigMotor;
StepperControl *smallMotor;
diff --git a/tools/makeServiceList b/tools/makeServiceList
new file mode 100755
index 0000000..6d35c56
--- /dev/null
+++ b/tools/makeServiceList
@@ -0,0 +1,6 @@
+#!/bin/zsh
+
+grep -B 1000 "AUTOGENERATED_TEXT" ../docs/ServiceList.md > ServiceList.md
+./makeServices ../src/Characteristics.h ../src/Span.h >> ServiceList.md
+mv ServiceList.md ../docs/ServiceList.md
+
diff --git a/tools/makeServices b/tools/makeServices
new file mode 100755
index 0000000..279262b
--- /dev/null
+++ b/tools/makeServices
@@ -0,0 +1,109 @@
+#!/usr/bin/awk -f
+
+BEGIN {
+
+ ws="[ \t,();]+" # regexp of separators
+ ltws="^" ws "|" ws "$" # regexp of leading and trailing separators
+
+ nServs=0 # number of Services found
+}
+
+{
+ split($0,line,"//") # separate line into program and (optional) comment
+ gsub(ltws,"",line[1]) # strip out leading or trailing separators
+ gsub("[ \t]+","",line[1]) # strip out any other spaces
+
+ n=split(line[1],x,ws) # split program portion according to separators
+
+ if(x[1]=="CREATE_SERV"){
+ currentService=x[2]
+ services[nServs++]=currentService
+ uuid[currentService]=x[3]
+ desc[currentService]=line[2] # save optional comment as description of Service
+ nChars[currentService]=0
+ }
+
+ else if(x[1]=="REQ" || x[1]=="OPT"){
+ servChars[currentService,nChars[currentService]]=x[2]
+ servReq[currentService,nChars[currentService]]=(x[1]=="REQ")
+ nChars[currentService]++
+ }
+
+ else if(x[1]=="CREATE_CHAR"){
+ char=x[3]
+ default[char]=x[4]
+ min[char]=x[5]
+ max[char]=x[6]
+ nConstants[char]=n-6 # parse any pre-defined constants
+ value=0 # default starting value of constants
+ for(i=0;i%s
\n",desc[s])
+ printf("| Characteristic | Format | Perms | Min | Max | Constants/Defaults |
\n")
+
+ for(j=0;j")
+ printf("%s (%s) %s | ",char,uuid[char],servReq[s,j]?":small_blue_diamond:":"",notes[char])
+ printf("%s | ",format[char])
+ printf("%s | ",perms[char])
+
+ if(format[char]!="string")
+ printf("%s | %s | ",min[char],max[char])
+ else
+ printf("- | - | ")
+
+ if(nConstants[char]>0){
+ printf("")
+ for(k=0;k%s (%d) %s",constantName[char,k],constantValue[char,k],defaultMark[char,k])
+ printf(" | ")
+ } else {
+ printf("%s | ",default[char])
+ }
+
+ printf("\n")
+ }
+
+ printf("
\n\n")
+ }
+
+ printf("---\n\n")
+ printf("[↩️](../README.md) Back to the Welcome page\n\n")
+}
+
+