Converted AutoOff to TimedResets

This commit is contained in:
Gregg 2020-07-29 07:26:13 -05:00
parent 59494a129f
commit 861a37c7a1
6 changed files with 293 additions and 23 deletions

View File

@ -0,0 +1,72 @@
////////////////////////////////////////////////////////////
// //
// HomeSpan: A HomeKit implementation for the ESP32 //
// ------------------------------------------------ //
// //
// Example 9: Logging messages to the Serial Monitor //
// //
// //
////////////////////////////////////////////////////////////
#include "HomeSpan.h"
#include "DEV_LED.h"
#include "DEV_Identify.h"
void setup() {
// HomeSpan sends a variety of messages to the Serial Monitor of the Arduino IDE whenever the device is connected
// to a computer. Message output is performed either by the usual Serial.print() function, or by one of two macros,
// LOG1() and LOG2(). These two macros are defined as Serial.print() or as no operation (), depending on the
// level of the VERBOSITY constant specified in the "Settings.h" file. Setting VERBOSITY to 0 sets both LOG1() and
// LOG2() to no-op, which means only messages explicitly sent with Serial.print() will be output by HomeSpan. Setting
// VERBOSITY to 1 means messages formed by the LOG1() macros will also be sent. And setting VERBOSITY to 2 causes
// both LOG1() and LOG2() messages to be sent.
//
// You can create your own log messages as needed through Serial.print() statements, but you can also create them with
// the LOG1() or LOG2() macros enabling you can turn them on or off by setting VERBOSITY to the appropriate level.
// Use LOG1() and LOG2() just as you would Serial.print().
//
// Example 9 illustrates how to add such log messages. The code is identical to Example 8 (without comments), except
// that Serial.print() and LOG1() messages have been added to DEV_LED.h. The Serial.print() messages will always be
// output to the Arduino Serial Monitor. The LOG1() messages will only be output if VERBOSITY is set to 1 or 2.
//
// RECOMMENDATION: Since a HomeSpan ESP32 is meant to be physically connected to real-world devices, you may find
// yourself with numerous ESP32s each configured with a different set of Accessories. To aid in identification
// you may want to add Serial.print() statements containing some sort of initialization message to the constructors for
// each derived Service, such as DEV_LED. Doing so allows HomeSpan to "report" on its configuration upon start-up. See
// DEV_LED for examples.
Serial.begin(115200);
homeSpan.begin(Category::Bridges,"HomeSpan Bridge");
// Defines the Bridge Accessory
new SpanAccessory();
new DEV_Identify("Bridge #1","HomeSpan","123-ABC","HS Bridge","0.9",3);
new Service::HAPProtocolInformation();
new Characteristic::Version("1.1.0");
// Defines an ON/OFF LED Accessory attached to pin 16
new SpanAccessory();
new DEV_Identify("LED #1","HomeSpan","123-ABC","20mA LED","0.9",0);
new DEV_LED(16);
new SpanTimedReset(2000);
// Defines a Dimmable LED Accessory attached to pin 17 using PWM channel 0
new SpanAccessory();
new DEV_Identify("LED #2","HomeSpan","123-ABC","20mA LED","0.9",0);
new DEV_DimmableLED(0,17);
} // end of setup()
//////////////////////////////////////
void loop(){
homeSpan.poll();
} // end of loop()

View File

@ -0,0 +1,63 @@
//////////////////////////////////
// DEVICE-SPECIFIC SERVICES //
//////////////////////////////////
// Here we define the DEV_Identify Service as derived class of AccessoryInformation
struct DEV_Identify : Service::AccessoryInformation {
int nBlinks; // number of times to blink built-in LED in identify routine
SpanCharacteristic *identify; // reference to the Identify Characteristic
// Next we define the constructor using all the arguments needed to implement the required Characteristics
// of AccessoryInformation, plus one extra argument at the end called "nBlinks" we will use to specify how many
// times HomeSpan should blink the built-in LED when HomeKit calls this device's Identify routine during pairing.
DEV_Identify(char *name, char *manu, char *sn, char *model, char *version, int nBlinks) : Service::AccessoryInformation(){
new Characteristic::Name(name); // create all the required Characteristics with values set based on above arguments
new Characteristic::Manufacturer(manu);
new Characteristic::SerialNumber(sn);
new Characteristic::Model(model);
new Characteristic::FirmwareRevision(version);
identify=new Characteristic::Identify(); // store a reference to the Identify Characteristic for use below
this->nBlinks=nBlinks; // store the number of times to blink the built-in LED
pinMode(LED_BUILTIN,OUTPUT); // make sure built-in LED is set for output
}
// How HomeKit Identifies Devices:
//
// When HomeKit first pairs with a new device it "calls" that device's identify routine for every defined Accessory.
// To do so, HomeKit requests the Identify Characteristic for each defined AccessoryInformation Service to be set to "true".
// The Identify Characteristic is write-only, so no value is ever stored, even though HomeKit is requesting its value
// be updated. We can therefore use the same update() method as if the Identify Characteristic was the same as any
// other boolean Characteristic.
// There are many ways to implement some form of identification. For an LED, you could blink it one or more times.
// For a LightBulb, you can flash it on and off. For window shade, you could raise and lower it.
// Most commerical devices don't do anything. Because HomeSpan can be used to control many different types of
// device, below we implement a very generic routine that simply blinks the internal LED of the ESP32 the
// number of times specified above. In principle, this code could call a user-defined routine that is different
// for each physcially-attached device (light, shade, fan, etc), but in practice this is overkill.
// Note that the blink routine below starts by turning off the built-in LED and then leaves it on once it has blinked
// the specified number of times. This is because when HomeSpan starts up if confirms to user that it has connected
// to the WiFi network by turning on the built-in LED. Thus we want to leave it on when blinking is completed.
StatusCode update(){
for(int i=0;i<nBlinks;i++){
digitalWrite(LED_BUILTIN,LOW);
delay(250);
digitalWrite(LED_BUILTIN,HIGH);
delay(250);
}
return(StatusCode::OK);
} // update
};

View File

@ -0,0 +1,131 @@
////////////////////////////////////
// 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
SpanCharacteristic *power; // reference to the On Characteristic
DEV_LED(int ledPin) : Service::LightBulb(){ // constructor() method
power=new Characteristic::On();
this->ledPin=ledPin;
pinMode(ledPin,OUTPUT);
// Here we output log messages when the constructor is initially called.
// We use Serial.print() since to ensure the message is always output
// regardless of the VERBOSITY setting.
Serial.print("Configuring On/Off LED: Pin="); // initialization message
Serial.print(ledPin);
Serial.print("\n");
} // end constructor
StatusCode update(){ // update() method
// Here we output log messages whenever update() is called,
// which is helpful for debugging purposes if your physical device
// is not functioning as expected. Since it's just for debugging,
// we use LOG1() instead of Serial.print(). Note we can output
// both the current as well as the new power settings.
LOG1("Updating On/Off LED on pin=");
LOG1(ledPin);
LOG1(": Current Power=");
LOG1(power->value.BOOL?"true":"false");
LOG1(" New Power=");
LOG1(power->newValue.BOOL?"true":"false");
LOG1("\n");
digitalWrite(ledPin,power->newValue.BOOL);
return(StatusCode::OK); // return OK status code
} // update
};
//////////////////////////////////
struct DEV_DimmableLED : Service::LightBulb { // Dimmable LED
PwmPin *pwmPin; // reference to PWM Pin
int ledPin; // pin number defined for this LED <- NEW!!
int channel; // PWM channel used for this LED (should be unique for each LED)
SpanCharacteristic *power; // reference to the On Characteristic
SpanCharacteristic *level; // reference to the Brightness Characteristic
DEV_DimmableLED(int channel, int ledPin) : Service::LightBulb(){ // constructor() method
power=new Characteristic::On();
level=new Characteristic::Brightness(50); // Brightness Characteristic with an initial value of 50%
new SpanRange(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%
this->channel=channel; // save the channel number (from 0-15)
this->ledPin=ledPin; // LED pin number <- NEW!!
this->pwmPin=new PwmPin(channel, ledPin); // configure the PWM channel and attach the specified ledPin. pinMode() does NOT need to be called.
// Here we output log messages when the constructor is initially called.
// We use Serial.print() since to ensure the message is always output
// regardless of the VERBOSITY setting.
Serial.print("Configuring Dimmable LED: Pin="); // initialization message
Serial.print(ledPin);
Serial.print(" Channel=");
Serial.print(channel);
Serial.print("\n");
} // end constructor
StatusCode update(){ // update() method
// Here we output log messages whenever update() is called,
// which is helpful for debugging purposes if your physical device
// is not functioning as expected. Since it's just for debugging,
// we use LOG1() instead of Serial.print().
// Note that in the prior example we did not save the ledPin number for
// DimmableLED since it was only needed by the constructor for initializing
// PwmPin(). For this example we add ledPin as a saved variable (see the two
// lines marketed NEW!! above) for the sole purpose of this log message.
LOG1("Updating Dimmable LED on pin=");
LOG1(ledPin);
LOG1(": Current Power=");
LOG1(power->value.BOOL?"true":"false");
LOG1(" Current Brightness=");
LOG1(level->value.INT);
// Note that since Dimmable_LED has two updateable Characteristics,
// HomeKit may be requesting either or both to be updated. We can
// use the "isUpdated" flag of each Characteristic to output a message
// only if HomeKit actually requested an update for that Characteristic.
// Since update() is called whenever there is an update to at least
// one of the Characteristics in a Service, either power, level, or both
// will have its "isUpdated" flag set.
if(power->isUpdated){
LOG1(" New Power=");
LOG1(power->newValue.BOOL?"true":"false");
}
if(level->isUpdated){
LOG1(" New Brightness=");
LOG1(level->newValue.INT);
}
LOG1("\n");
pwmPin->set(channel,power->newValue.BOOL*level->newValue.INT);
return(StatusCode::OK); // return OK status code
} // update
};
//////////////////////////////////

View File

@ -1126,11 +1126,10 @@ int HAPClient::putCharacteristicsURL(char *json){
void HAPClient::checkNotifications(){ void HAPClient::checkNotifications(){
SpanPBList *pb=homeSpan.pbHead;
int n=0; int n=0;
while(pb){ // PASS 1: loop through all characteristics registered as Push Buttons for(int i=0;i<homeSpan.TimedResets.size();i++){ // PASS 1: loop through all defined Timed Resets
SpanTimedReset *pb=homeSpan.TimedResets[i];
if(!pb->characteristic->value.BOOL){ // characteristic is off if(!pb->characteristic->value.BOOL){ // characteristic is off
pb->start=false; // ensure timer is not started pb->start=false; // ensure timer is not started
pb->trigger=false; // turn off trigger pb->trigger=false; // turn off trigger
@ -1143,17 +1142,16 @@ void HAPClient::checkNotifications(){
pb->trigger=true; // set trigger pb->trigger=true; // set trigger
n++; // increment number of Push Buttons found that need to be turned off n++; // increment number of Push Buttons found that need to be turned off
} }
pb=pb->next;
} }
if(!n) // nothing to do (either no Push Button characteristics, or none that need to be turned off) if(!n) // nothing to do (either no Push Button characteristics, or none that need to be turned off)
return; return;
SpanPut pObj[n]; // use a SpanPut object (for convenience) to load characteristics to be updated SpanPut pObj[n]; // use a SpanPut object (for convenience) to load characteristics to be updated
pb=homeSpan.pbHead; // reset Push Button list
n=0; // reset number of PBs found that need to be turned off n=0; // reset number of PBs found that need to be turned off
while(pb){ // PASS 2: loop through all characteristics registered as Push Buttons for(int i=0;i<homeSpan.TimedResets.size();i++){ // PASS 2: loop through all defined Timed Resets
SpanTimedReset *pb=homeSpan.TimedResets[i];
if(pb->trigger){ // characteristic is triggered if(pb->trigger){ // characteristic is triggered
pb->characteristic->value.BOOL=false; // turn off characteristic pb->characteristic->value.BOOL=false; // turn off characteristic
pObj[n].status=StatusCode::OK; // populate pObj pObj[n].status=StatusCode::OK; // populate pObj
@ -1161,7 +1159,6 @@ void HAPClient::checkNotifications(){
pObj[n].val=""; // dummy object needed to ensure sprintfNotify knows to consider this "update" pObj[n].val=""; // dummy object needed to ensure sprintfNotify knows to consider this "update"
n++; // increment number of Push Buttons found that need to be turned off n++; // increment number of Push Buttons found that need to be turned off
} }
pb=pb->next;
} }
for(int i=0;i<MAX_CONNECTIONS;i++){ // loop over all connection slots for(int i=0;i<MAX_CONNECTIONS;i++){ // loop over all connection slots

View File

@ -1053,18 +1053,26 @@ StatusCode SpanCharacteristic::loadUpdate(char *val, char *ev){
return(StatusCode::TBD); return(StatusCode::TBD);
} }
///////////////////////////////
// SpanTimedReset //
/////////////////////////////// ///////////////////////////////
void SpanCharacteristic::autoOff(int waitTime){ SpanTimedReset::SpanTimedReset(int waitTime){
SpanPBList **pb=&homeSpan.pbHead; if(homeSpan.Accessories.empty() || homeSpan.Accessories.back()->Services.empty() || homeSpan.Accessories.back()->Services.back()->Characteristics.empty() ){
Serial.print("*** FATAL ERROR: Can't create new TimedReset without a defined Characteristic. Program halted!\n\n");
while(1);
}
while(*pb) // traverse list until end if(homeSpan.Accessories.back()->Services.back()->Characteristics.back()->format!=SpanCharacteristic::BOOL){
pb=&((*pb)->next); Serial.print("*** FATAL ERROR: Can't create new TimedReset for non-Boolean Characteristic. Program halted!\n\n");
while(1);
}
this->characteristic=homeSpan.Accessories.back()->Services.back()->Characteristics.back();
this->waitTime=waitTime;
homeSpan.TimedResets.push_back(this);
*pb=new SpanPBList;
(*pb)->characteristic=this;
(*pb)->waitTime=waitTime;
} }
/////////////////////////////// ///////////////////////////////

View File

@ -23,7 +23,7 @@ struct SpanService;
struct SpanCharacteristic; struct SpanCharacteristic;
struct SpanRange; struct SpanRange;
struct SpanPut; struct SpanPut;
struct SpanPBList; struct SpanTimedReset;
/////////////////////////////// ///////////////////////////////
@ -43,9 +43,9 @@ struct Span{
int resetPin=21; // drive this pin low to "factory" reset NVS data on start-up int resetPin=21; // drive this pin low to "factory" reset NVS data on start-up
SpanPBList *pbHead=NULL; // head of linked-list of characteristics to auto-turnoff after they are turned on (to emulate a single-shot PushButton)
SpanConfig hapConfig; // track configuration changes to the HAP Accessory database; used to increment the configuration number (c#) when changes found SpanConfig hapConfig; // track configuration changes to the HAP Accessory database; used to increment the configuration number (c#) when changes found
vector<SpanAccessory *> Accessories; // vector of pointers to all Accessories vector<SpanAccessory *> Accessories; // vector of pointers to all Accessories
vector<SpanTimedReset *> TimedResets; // vector of pointers to all TimedResets
void begin(Category catID, void begin(Category catID,
char *displayName="HomeSpan Server", char *displayName="HomeSpan Server",
@ -164,7 +164,6 @@ struct SpanCharacteristic{
int sprintfAttributes(char *cBuf, int flags); // prints Characteristic JSON records into buf, according to flags mask; return number of characters printed, excluding null terminator int sprintfAttributes(char *cBuf, int flags); // prints Characteristic JSON records into buf, according to flags mask; return number of characters printed, excluding null terminator
StatusCode loadUpdate(char *val, char *ev); // load updated val/ev from PUT /characteristic JSON request. Return intiial HAP status code (checks to see if characteristic is found, is writable, etc.) StatusCode loadUpdate(char *val, char *ev); // load updated val/ev from PUT /characteristic JSON request. Return intiial HAP status code (checks to see if characteristic is found, is writable, etc.)
void autoOff(int waitTime=250); // turns Characteristic off (false) automatically after waitTime milliseconds; only applicable to BOOL characteristics
}; };
/////////////////////////////// ///////////////////////////////
@ -190,15 +189,15 @@ struct SpanPut{ // storage to process PUT /charact
/////////////////////////////// ///////////////////////////////
struct SpanPBList{ struct SpanTimedReset{
SpanPBList *next=NULL; // next item in linked-list SpanCharacteristic *characteristic; // characteristic to auto-reset whenever activated
SpanCharacteristic *characteristic; // characteristic to auto-turnoff whenever activated int waitTime; // time to wait until auto-reset (in milliseconds)
int waitTime; // time to wait until auto-turnoff (in milliseconds) unsigned long alarmTime; // alarm time for trigger to auto-reset
unsigned long alarmTime; // alarm time for trigger to auto-turnoff
boolean start=false; // alarm timer started boolean start=false; // alarm timer started
boolean trigger=false; // alarm timer triggered boolean trigger=false; // alarm timer triggered
};
SpanTimedReset(int waitTime);
};
///////////////////////////////////////////////// /////////////////////////////////////////////////
// Extern Variables // Extern Variables