From cf22ff1a92e19758d25e053113ff0b90a7e880a1 Mon Sep 17 00:00:00 2001 From: Gregg Date: Sat, 5 Mar 2022 22:06:34 -0600 Subject: [PATCH] Added homeSpan.getClientIP() Gets IP address (as char *) of last client to send a request. Useful as part of web log messages. Will return 0.0.0.0 if used outside of any code that is responding to a client request. --- examples/19-WebLog/19-WebLog.ino | 129 +++++++++++++++++++++++++++++++ examples/19-WebLog/DEV_LED.h | 101 ++++++++++++++++++++++++ src/HomeSpan.cpp | 6 +- src/HomeSpan.h | 2 + 4 files changed, 236 insertions(+), 2 deletions(-) create mode 100644 examples/19-WebLog/19-WebLog.ino create mode 100644 examples/19-WebLog/DEV_LED.h diff --git a/examples/19-WebLog/19-WebLog.ino b/examples/19-WebLog/19-WebLog.ino new file mode 100644 index 0000000..8706e94 --- /dev/null +++ b/examples/19-WebLog/19-WebLog.ino @@ -0,0 +1,129 @@ +/********************************************************************************* + * MIT License + * + * Copyright (c) 2020 Gregg E. Berman + * + * https://github.com/HomeSpan/HomeSpan + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to deal + * in the Software without restriction, including without limitation the rights + * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + * copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in all + * copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + * SOFTWARE. + * + ********************************************************************************/ + +//////////////////////////////////////////////////////////// +// // +// HomeSpan: A HomeKit implementation for the ESP32 // +// ------------------------------------------------ // +// // +// Example 5: Two working on/off LEDs based on the // +// LightBulb Service // +// // +//////////////////////////////////////////////////////////// + + +#include "HomeSpan.h" +#include "DEV_LED.h" // NEW! Include this new file, DEV_LED.h, which will be fully explained below + +void setup() { + + // First light! Control an LED from HomeKit! + + // Example 5 expands on Example 2 by adding in the code needed to actually control LEDs connected to the ESP32 from HomeKit. + // In Example 2 we built out all the functionality to create a "Tile" Acessories inside HomeKit that displayed an on/off light, but + // these control did not actually operate anything on the ESP32. To operate actual devices HomeSpan needs to be programmed to + // respond to "update" requests from HomeKit by performing some form of operation. + + // Though HomeKit itself sends "update" requests to individual Characteristics, this is not intuitive and leads to complex coding requirements + // when a Service has more than one Characteristic, such as both "On" and "Brightness." To make this MUCH easier for the user, HomeSpan + // uses a framework in which Services are updated instead of individual Characteristics. It does so by calling the update() method of + // each Service with flags indicating all the Characteristics in that Service that HomeKit requested to update. The user simply + // implements code to perform the actual operation, and returns either true or false if the update was successful. HomeSpan takes care of all + // the underlying nuts and bolts. + + // Every Service defined in HomeKit, such as Service:LightBulb and Service:Fan (and even Service::AccessoryInformation) implements an update() + // method that, as a default, does nothing but returns a value of true. To actually operate real devices you need to over-ride this default update() + // method with your own code. The easiest way to do this is by creating a DERIVED class based on one of the built-in HomeSpan Services. + // Within this derived class you can perform initial set-up routines (if needed), over-ride the update() method with your own code, and even create + // any other methods or class-specific variables you need to fully operate complex devices. Most importantly, the derived class can take arguments + // so that you can make them more generic, re-use them multiple times (as will be seen below), and convert them to standalone modules (also shown below). + + // All of the HomeKit Services implemented by HomeSpan can be found in the Services.h file. Any can be used as the parent for a derived Service. + + // We begin by repeating nearly the same code from Example 2, but with a few key changes. For ease of reading, all prior comments have been removed + // from lines that simply repeat Example 2, and new comments have been added to explictly show the new code. + + Serial.begin(115200); + + homeSpan.enableWebLog(10,"pool.ntp.org","CST6CDT"); + homeSpan.begin(Category::Lighting,"HomeSpan LEDs"); + + new SpanAccessory(); + + new Service::AccessoryInformation(); + new Characteristic::Name("LED #1"); + new Characteristic::Manufacturer("HomeSpan"); + new Characteristic::SerialNumber("123-ABC"); + new Characteristic::Model("20mA LED"); + new Characteristic::FirmwareRevision("0.9"); + new Characteristic::Identify(); + + new Service::HAPProtocolInformation(); + new Characteristic::Version("1.1.0"); + + // In Example 2 we instantiated a LightBulb Service and its "On" Characteristic here. We are now going to replace these two lines (by commenting them out)... + + // new Service::LightBulb(); + // new Characteristic::On(); + + // ...with a single new line instantiating a new class we will call DEV_LED(): + + new DEV_LED(16); // this instantiates a new LED Service. Where is this defined? What happpened to Characteristic::On? Keep reading... + + // The full definition and code for DEV_LED is implemented in a separate file called "DEV_LED.h" that is specified using the #include at the top of this program. + // The prefix DEV_ is not required but it's a helpful convention when naming all your device-specific Services. Note that DEV_LED will include all the required + // Characterictics of the Service, so you DO NOT have to separately instantiate Characteristic::On --- everything HomeSpan needs for DEV_LED should be implemented + // in DEV_LED itself (though it's not all that much). Finally, note that we created DEV_LED to take a single integer argument. If you guessed this is + // the number of the Pin to which you have attached an LED, you'd be right. See DEV_LED.h for a complete explanation of how it works. + + new SpanAccessory(); + + new Service::AccessoryInformation(); + new Characteristic::Name("LED #2"); + new Characteristic::Manufacturer("HomeSpan"); + new Characteristic::SerialNumber("123-ABC"); + new Characteristic::Model("20mA LED"); + new Characteristic::FirmwareRevision("0.9"); + new Characteristic::Identify(); + + new Service::HAPProtocolInformation(); + new Characteristic::Version("1.1.0"); + + // new Service::LightBulb(); // Same as above, this line is deleted... + // new Characteristic::On(); // This line is also deleted... + + new DEV_LED(17); // ...and replaced with a single line that instantiates a second DEV_LED Service on Pin 17 + +} // end of setup() + +////////////////////////////////////// + +void loop(){ + + homeSpan.poll(); + +} // end of loop() diff --git a/examples/19-WebLog/DEV_LED.h b/examples/19-WebLog/DEV_LED.h new file mode 100644 index 0000000..0dbe012 --- /dev/null +++ b/examples/19-WebLog/DEV_LED.h @@ -0,0 +1,101 @@ + +//////////////////////////////////// +// DEVICE-SPECIFIC LED SERVICES // +//////////////////////////////////// + +// HERE'S WHERE WE DEFINE OUR NEW LED SERVICE! + +struct DEV_LED : Service::LightBulb { // First we create a derived class from the HomeSpan LightBulb Service + + int ledPin; // this variable stores the pin number defined for this LED + SpanCharacteristic *power; // here we create a generic pointer to a SpanCharacteristic named "power" that we will use below + + // Next we define the constructor for DEV_LED. Note that it takes one argument, ledPin, + // which specifies the pin to which the LED is attached. + + DEV_LED(int ledPin) : Service::LightBulb(){ + + power=new Characteristic::On(); // this is where we create the On Characterstic we had previously defined in setup(). Save this in the pointer created above, for use below + this->ledPin=ledPin; // don't forget to store ledPin... + pinMode(ledPin,OUTPUT); // ...and set the mode for ledPin to be an OUTPUT (standard Arduino function) + + } // end constructor + + // Finally, we over-ride the default update() method with instructions that actually turn on/off the LED. Note update() returns type boolean + + boolean update(){ + + digitalWrite(ledPin,power->getNewVal()); // use a standard Arduino function to turn on/off ledPin based on the return of a call to power->getNewVal() (see below for more info) + WEBLOG("LED on Pin %d: %s (%s)",ledPin,power->getNewVal()?"ON":"OFF",homeSpan.getClientIP()); + + return(true); // return true to indicate the update was successful (otherwise create code to return false if some reason you could not turn on the LED) + + } // update +}; + +////////////////////////////////// + +// HOW update() WORKS: +// ------------------ +// +// Whenever a HomeKit controller requests HomeSpan to update a Characteristic, HomeSpan calls the update() method for the SERVICE that contains the +// Characteristic. It calls this only one time, even if multiple Characteristics updates are requested for that Service. For example, if you +// direct HomeKit to turn on a light and set it to 50% brightness, it will send HomeSpan two requests: one to update the "On" Characteristic of the +// LightBulb Service from "false" to "true" and another to update the "Brightness" Characteristic of that same Service to 50. This is VERY inefficient +// and would require the user to process multiple updates to the same Service. +// +// Instead, HomeSpan combines both requests into a single call to update() for the Service itself, where you can process all of the Characteristics +// that change at the same time. In the example above, we only have a single Characteristic to deal with, so this does not mean much. But in later +// examples we'll see how this works with multiple Characteristics. + +// HOW TO ACCESS A CHARACTERISTIC'S NEW AND CURRENT VALUES +// ------------------------------------------------------- +// +// HomeSpan stores the values for its Characteristics in a union structure that allows for different types, such as floats, booleans, etc. The specific +// types are defined by HAP for each Characteristic. Looking up whether a Characteristic is a uint8 or uint16 can be tiresome, so HomeSpan abstracts +// all these details. Since C++ adheres to strict variable typing, this is done through the use of template methods. Every Characteristic supports +// the following two methods: +// +// getVal() - returns the CURRENT value of the Characterisic, after casting into "type" +// getNewVal() - returns the NEW value (i.e. to be updated) of the Characteritic, after casting into "type" +// +// For example, MyChar->getVal() returns the current value of SpanCharacterstic MyChar as an int, REGARDLESS of how the value is stored by HomeSpan. +// Similarly, MyChar->getVal() returns a value as a double, even it is stored as as a boolean (in which case you'll either get 0.00 or 1.00). +// Of course you need to make sure you understand the range of expected values so that you don't try to access a value stored as 2-byte int using getVal(). +// But it's perfectly okay to use getVal() to access the value of a Characteristic that HAP insists on storing as a float, even though its range is +// strictly between 0 and 100 in steps of 1. Knowing the range and step size is all you need to know in determining you can access this as an or even a . +// +// Because most Characteristic values can properly be cast into int, getVal and getNewVal both default to if the template parameter is not specified. +// As you can see above, we retrieved the new value HomeKit requested for the On Characteristic that we named "power" by simply calling power->getNewVal(). +// Since no template parameter is specified, getNewVal() will return an int. And since the On Characteristic is natively stored as a boolean, getNewVal() +// will either return a 0 or a 1, depending on whether HomeKit is requesting the Characteristic to be turned off or on. +// +// You may also note that in the above example we needed to use getNewVal(), but did not use getVal() anywhere. This is because we know exactly what +// to do if HomeKit requests an LED to be turned on or off. The current status of the LED (on or off) does not matter. In latter examples we will see +// instances where the current state of the device DOES matter, and we will need to access both current and new values. +// +// Finally, there is one additional method for Characteristics that is not used above but will be in later examples: updated(). This method returns a +// boolean indicating whether HomeKit has requested a Characteristic to be updated, which means that getNewVal() will contain the new value it wants to set +// for that Characteristic. For a Service with only one Characteristic, as above, we don't need to ask if "power" was updated using power->updated() because +// the fact the the update() method for the Service is being called means that HomeKit is requesting an update, and the only thing to update is "power". +// But for Services with two or more Characteristics, update() can be called with a request to update only a subset of the Characteristics. We will +// find good use for the updated() method in later, multi-Characteristic examples. + +// UNDER THE HOOD: WHAT THE RETURN CODE FOR UPDATE() DOES +// ------------------------------------------------------ +// +// HomeKit requires each Characteristic to return a special HAP status code when an attempt to update its value is made. HomeSpan automatically takes care of +// most of the errors, such as a Characteristic not being found, or a request to update a Characteristic that is read only. In these cases update() is never +// even called. But if it is, HomeSpan needs to return a HAP status code for each of the Characteristics that were to be updated in that Service. +// By returning "true" you tell HomeSpan that the newValues requested are okay and you've made the required updates to the physical device. Upon +// receiving a true return value, HomeSpan updates the Characteristics themselves by copying the "newValue" data elements into the current "value" data elements. +// HomeSpan then sends a message back to HomeKit with a HAP code representing "OK," which lets the Controller know that the new values it requested have been +// sucessfully processed. At no point does HomeKit ask for, or allow, a data value to be sent back from HomeSpan indicating the data in a Characteristic. +// When requesting an update, HomeKit simply expects a HAP status code of OK, or some other status code representing an error. To tell HomeSpan to send the Controller +// an error code, indicating that you were not able to successfully process the update, simply have update() return a value of "false." HomeSpan converts a +// return of "false" to the HAP status code representing "UNABLE," which will cause the Controller to show that the device is not responding. + +// There are very few reasons you should need to return "false" since so much checking is done in advance by either HomeSpan or HomeKit +// itself. For instance, HomeKit does not allow you to use the Controller, or even Siri, to change the brightness of LightBulb to a value outside the +// range of allowable values you specified. This means that any update() requests you receive should only contain newValue data elements that are in-range. +// diff --git a/src/HomeSpan.cpp b/src/HomeSpan.cpp index cab148b..1e768fe 100644 --- a/src/HomeSpan.cpp +++ b/src/HomeSpan.cpp @@ -257,8 +257,10 @@ void Span::poll() { if(hap[i]->client && hap[i]->client.available()){ // if connection exists and data is available - HAPClient::conNum=i; // set connection number - hap[i]->processRequest(); // process HAP request + HAPClient::conNum=i; // set connection number + homeSpan.lastClientIP=hap[i]->client.remoteIP().toString(); // store IP Address for web logging + hap[i]->processRequest(); // process HAP request + 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 #"); diff --git a/src/HomeSpan.h b/src/HomeSpan.h index 7916fa2..d115498 100644 --- a/src/HomeSpan.h +++ b/src/HomeSpan.h @@ -138,6 +138,7 @@ struct Span{ nvs_handle charNVS; // handle for non-volatile-storage of Characteristics data nvs_handle wifiNVS=0; // handle for non-volatile-storage of WiFi 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 connected=false; // WiFi connection status unsigned long waitTime=60000; // time to wait (in milliseconds) between WiFi connection attempts @@ -220,6 +221,7 @@ struct Span{ 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 + const char *getClientIP(){return(lastClientIP.c_str());} // get IP address of last client to send an encrypted request - to be used only in update() commands 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