Completed Example 19 - Web Logs

Also updated SpanWebLog::addLog() so that the log message is also output to the Serial Monitor if the HomeSpan Log Level is set to 1 or greater.

To do: DOCUMENT ALL THIS!
This commit is contained in:
Gregg 2022-03-06 09:25:17 -06:00
parent 1be40ad6fc
commit db3bea3b5c
3 changed files with 45 additions and 107 deletions

View File

@ -30,7 +30,7 @@
// HomeSpan: A HomeKit implementation for the ESP32 // // HomeSpan: A HomeKit implementation for the ESP32 //
// ------------------------------------------------ // // ------------------------------------------------ //
// // // //
// Example 19: Web Logging // // Example 19: Web Logging with time-keeping //
// // // //
//////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////
@ -40,20 +40,25 @@
void setup() { void setup() {
// This is a duplicate of Example 5 (Two Working LEDs) with the addition of HomesSpan Web Logging // This is a duplicate of Example 5 (Two Working LEDs) with the addition of HomeSpan Web Logging
Serial.begin(115200); Serial.begin(115200);
// Below we enable Web Logging. The first parameter sets the maximum number of log messages to save (as the // Below we enable Web Logging. The first parameter sets the maximum number of log messages to save. As the
// log fills with messages, older ones are replaced by newer ones). The second parameter specifies a Timer Server // log fills with messages, older ones are replaced by newer ones. The second parameter specifies a Timer Server
// that HomeSpan calls to set its clock. Setting the clock in this fashion is optional, and you can leave this // that HomeSpan calls to set the device clock. Setting the clock is optional, and you can leave this
// argument blank (or set to NULL) if you don't care about setting the absolute time of the device. The third // argument blank (or set to NULL) if you don't care about setting the absolute time of the device. The third
// argument defines the Time Zone used for setting the device clock. See the HomeSpan API Reference for complete details // argument defines the Time Zone used for setting the device clock. The fourth argument specifies the URL page
// and more options related to this function call. // of the Web Log. See the HomeSpan API Reference for complete details, as well as additional options, related
// to this function call.
homeSpan.enableWebLog(10,"pool.ntp.org","UTC"); homeSpan.enableWebLog(10,"pool.ntp.org","UTC","myLog"); // creates a web log on the URL /HomeSpan-[DEVICE-ID].local:[TCP-PORT]/myLog
// The rest of the sketch below is identical to Example 5. All of the Web Logging occurs in DEV_LED.h // The full URL of the Web Log will be shown in the Serial Monitor at boot time for reference.
// The Web Log output displays a variety of device parameters, plus any log messages you choose
// to provide with the WEBLOG() macro (see DEV_LED.h)
// Note the rest of the sketch below is identical to Example 5. All of the Web Logging occurs in DEV_LED.h
homeSpan.begin(Category::Lighting,"HomeSpan LEDs"); homeSpan.begin(Category::Lighting,"HomeSpan LEDs");
@ -70,20 +75,7 @@ void setup() {
new Service::HAPProtocolInformation(); new Service::HAPProtocolInformation();
new Characteristic::Version("1.1.0"); 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 DEV_LED(16);
// 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 SpanAccessory();
@ -98,10 +90,7 @@ void setup() {
new Service::HAPProtocolInformation(); new Service::HAPProtocolInformation();
new Characteristic::Version("1.1.0"); new Characteristic::Version("1.1.0");
// new Service::LightBulb(); // Same as above, this line is deleted... new DEV_LED(17);
// 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() } // end of setup()

View File

@ -3,102 +3,48 @@
// DEVICE-SPECIFIC LED SERVICES // // DEVICE-SPECIFIC LED SERVICES //
//////////////////////////////////// ////////////////////////////////////
// HERE'S WHERE WE DEFINE OUR NEW LED SERVICE! struct DEV_LED : Service::LightBulb {
struct DEV_LED : Service::LightBulb { // First we create a derived class from the HomeSpan LightBulb Service int ledPin;
SpanCharacteristic *power;
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(){ 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 power=new Characteristic::On();
this->ledPin=ledPin; // don't forget to store ledPin... this->ledPin=ledPin;
pinMode(ledPin,OUTPUT); // ...and set the mode for ledPin to be an OUTPUT (standard Arduino function) pinMode(ledPin,OUTPUT);
WEBLOG("Configuring LED on Pin %d",ledPin); WEBLOG("Configuring LED on Pin %d",ledPin); // NEW! This creates a Web Log message announcing the configuration of the device
} // end constructor } // 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(){ 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) digitalWrite(ledPin,power->getNewVal());
WEBLOG("LED on Pin %d: %s",ledPin,power->getNewVal()?"ON":"OFF"); WEBLOG("LED on Pin %d: %s",ledPin,power->getNewVal()?"ON":"OFF"); // NEW! This creates a Web Log message whenever an LED is turned ON or OFF
LOG1("LOG1: LED on Pin %d: %s",ledPin,power->getNewVal()?"ON":"OFF"); return(true);
LOG2("LOG2: LED on Pin %d: %s",ledPin,power->getNewVal()?"ON":"OFF");
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 } // update
}; };
////////////////////////////////// //////////////////////////////////
// HOW update() WORKS: // SOME MORE ABOUT WEB LOGGING
// ------------------ // ---------------------------
// //
// Whenever a HomeKit controller requests HomeSpan to update a Characteristic, HomeSpan calls the update() method for the SERVICE that contains the // * The WEBLOG() macro operates by calling Serial.printf(), so the first argument always needs to be a text string containing printf-like format instructions.
// Characteristic. It calls this only one time, even if multiple Characteristics updates are requested for that Service. For example, if you // The rest of the arguments, if any, are the variables to print. For example, you cannot simply write WEBLOG(ledPin). This will cause errors at compile time,
// 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 // though you can write LOG1(ledPin) or LOG2(ledPin) to output log messages just to the Serial Monitor.
// 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 // * You do NOT need to include a "\n" at the end of your format string since all Web Log messages are formatted into an HTML table when presented, and HTML ignores "\n".
// 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 // * Every Web Log message is recorded with TWO timestamps. The first timestamp is relative to when the device first booted, and is presented as DAYS:HH:MM:SS. This timestamp
// types are defined by HAP for each Characteristic. Looking up whether a Characteristic is a uint8 or uint16 can be tiresome, so HomeSpan abstracts // is always present. The second timestamp is an absolute clock time, in standard Unix form, such as "Mon Aug 10 13:52:48 2020". This timestamp will only be present
// all these details. Since C++ adheres to strict variable typing, this is done through the use of template methods. Every Characteristic supports // if the clock time of the device was set, else it will be shown as "Unknown". Note that in the example above, the first Web Log message ("Configuring...") will
// the following two methods: // have a clock timestamp of "Unknown" even though we enabled Web Logging with a Time Server. This is because the Time Server cannot be configured until WiFi has
// been established, and the first Web Log message above is created during initial configuratin of the device, BEFORE a WiFi connection is made. This is perfectly fine to do.
// //
// getVal<type>() - returns the CURRENT value of the Characterisic, after casting into "type" // * Every Web Log message also includes the IP Address of the Client that made the request, unless the Web Log message was generated independently of any Client request,
// getNewVal<type>() - returns the NEW value (i.e. to be updated) of the Characteritic, after casting into "type" // such as in the first message above. In these cases the IP Address will be displayed as 0.0.0.0.
//
// For example, MyChar->getVal<int>() returns the current value of SpanCharacterstic MyChar as an int, REGARDLESS of how the value is stored by HomeSpan.
// Similarly, MyChar->getVal<double>() 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<uint8_t>().
// But it's perfectly okay to use getVal<int>() 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 <int> or even a <uint8_t>.
//
// Because most Characteristic values can properly be cast into int, getVal and getNewVal both default to <int> 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.
// //
// * Web Log messages are printed to the Serial Monitor whenever the HomeSpan Log Level is set to 1 or greater. Hence there is no reason to duplicate the same message
// using WEBLOG() and LOG1() at the same time.

View File

@ -1984,4 +1984,7 @@ void SpanWebLog::addLog(const char *fmt, ...){
log[index].clientIP=homeSpan.lastClientIP; log[index].clientIP=homeSpan.lastClientIP;
nEntries++; nEntries++;
if(homeSpan.logLevel>0)
Serial.printf("WEBLOG: %s\n",log[index].message);
} }