From 6e9a4d9244c6595bbbb5cfc2c1fe50558fb9555d Mon Sep 17 00:00:00 2001 From: DV Date: Thu, 16 Feb 2017 16:17:13 +0100 Subject: [PATCH] Initial commit --- .gitignore | 6 + NodeManagerTemplate/NodeManager.cpp | 1366 +++++++++++++++++++ NodeManagerTemplate/NodeManager.h | 533 ++++++++ NodeManagerTemplate/NodeManagerTemplate.ino | 74 + NodeManagerTemplate/README.md | 364 +++++ NodeManagerTemplate/config.h | 48 + 6 files changed, 2391 insertions(+) create mode 100644 .gitignore create mode 100644 NodeManagerTemplate/NodeManager.cpp create mode 100644 NodeManagerTemplate/NodeManager.h create mode 100644 NodeManagerTemplate/NodeManagerTemplate.ino create mode 100644 NodeManagerTemplate/README.md create mode 100644 NodeManagerTemplate/config.h diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..126fc83f --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +.DS_Store +*.autosave +*.save +*~ +*.tmp +*.part diff --git a/NodeManagerTemplate/NodeManager.cpp b/NodeManagerTemplate/NodeManager.cpp new file mode 100644 index 00000000..72c7eeb2 --- /dev/null +++ b/NodeManagerTemplate/NodeManager.cpp @@ -0,0 +1,1366 @@ +/* + * NodeManager + */ + +#include "NodeManager.h" + + +/*************************************** + PowerManager +*/ + +// set the vcc and ground pin the sensor is connected to +void PowerManager::setPowerPins(int ground_pin, int vcc_pin, long wait = 0) { + #if DEBUG == 1 + Serial.print("PowerPins vcc="); + Serial.print(vcc_pin); + Serial.print(", gnd="); + Serial.println(ground_pin); + #endif + // configure the vcc pin as output and initialize to low (power off) + _vcc_pin = vcc_pin; + pinMode(_vcc_pin, OUTPUT); + digitalWrite(_vcc_pin, LOW); + // configure the ground pin as output and initialize to low + _ground_pin = ground_pin; + pinMode(_ground_pin, OUTPUT); + digitalWrite(_ground_pin, LOW); + _wait = wait; +} + +// return true if power pins have been configured +bool PowerManager::_hasPowerManager() { + if (_vcc_pin != -1 && _ground_pin != -1) return true; + return false; +} + +// turn on the sensor by activating its power pins +void PowerManager::powerOn() { + if (! _hasPowerManager()) return; + #if DEBUG == 1 + Serial.print("PowerOn pin="); + Serial.println(_vcc_pin); + #endif + // power on the sensor by turning high the vcc pin + digitalWrite(_vcc_pin, HIGH); + // wait a bit for the device to settle down + if (_wait > 0) sleep(_wait); +} + +// turn off the sensor +void PowerManager::powerOff() { + if (! _hasPowerManager()) return; + #if DEBUG == 1 + Serial.print("PowerOff pin="); + Serial.println(_vcc_pin); + #endif + // power off the sensor by turning low the vcc pin + digitalWrite(_vcc_pin, LOW); +} + +/****************************************** + Sensors +*/ + +/* + Sensor class +*/ +// constructor +Sensor::Sensor(int child_id, int pin) { + _child_id = child_id; + _pin = pin; + _msg = MyMessage(_child_id, _type); +} + +// setter/getter +void Sensor::setPin(int value) { + _pin = value; +} +int Sensor::getPin() { + return _pin; +} +void Sensor::setChildId(int value) { + _child_id = value; +} +int Sensor::getChildId() { + return _child_id; +} +void Sensor::setPresentation(int value) { + _presentation = value; +} +int Sensor::getPresentation() { + return _presentation; +} +void Sensor::setType(int value) { + _type = value; + _msg.setType(_type); +} +int Sensor::getType() { + return _type; +} +void Sensor::setRetries(int value) { + _retries = value; +} +void Sensor::setSamples(int value) { + _samples = value; +} +void Sensor::setSamplesInterval(int value) { + _samples_interval = value; +} +void Sensor::setTackLastValue(bool value) { + _track_last_value = value; +} +void Sensor::setForceUpdate(int value) { + _force_update = value; +} +void Sensor::setValueType(int value) { + _value_type = value; +} +void Sensor::setFloatPrecision(int value) { + _float_precision = value; +} +#if POWER_MANAGER == 1 + void Sensor::setPowerPins(int ground_pin, int vcc_pin, long wait = 0) { + _powerManager.setPowerPins(ground_pin, vcc_pin, wait); + } + void Sensor::powerOn() { + _powerManager.powerOn(); + } + void Sensor::powerOff() { + _powerManager.powerOff(); + } +#endif + +// present the sensor to the gateway and controller +void Sensor::presentation() { + #if DEBUG == 1 + Serial.print("Present id="); + Serial.print(_child_id); + Serial.print(", pres="); + Serial.println(_presentation); + #endif + present(_child_id, _presentation); +} + +// call the sensor-specific implementation of before +void Sensor::before() { + if (_pin == -1) return; + onBefore(); +} + +// call the sensor-specific implementation of loop +void Sensor::loop(const MyMessage & message) { + if (_pin == -1) return; + #if POWER_MANAGER == 1 + // turn the sensor on + powerOn(); + #endif + // for numeric sensor requiring multiple samples, keep track of the total + float total = 0; + // keep track of the number of cycles since the last update + _cycles++; + // collect multiple samples if needed + for (int i = 0; i < _samples; i++) { + // call the sensor-specific implementation of the main task which will store the result in the _value variable + if (message.sender == 0 && message.sensor == 0 && message.getCommand() == 0 && message.type == 0) { + // empty message, we'be been called from loop() + onLoop(); + } + else { + // we've been called from receive(), pass the message along + onReceive(message); + } + // for integers and floats, keep track of the total + if (_value_type == TYPE_INTEGER) total += (float)_value_int; + else if (_value_type == TYPE_FLOAT) total += _value_float; + // wait between samples + if (_samples_interval > 0) sleep(_samples_interval); + } + // process the result and send a response back. + if (_value_type == TYPE_INTEGER && total > -1) { + // if the value is an integer, calculate the average value of the samples + int avg = (int) (total / _samples); + // if track last value is disabled or if enabled and the current value is different then the old value, send it back + if (! _track_last_value || (_track_last_value && avg != _last_value_int) || (_track_last_value && _force_update > 0 && _cycles > _force_update)) { + _cycles = 0; + _last_value_int = avg; + _send(_msg.set(avg)); + } + } + // process a float value + else if (_value_type == TYPE_FLOAT && total > -1) { + // calculate the average value of the samples + float avg = total / _samples; + // if track last value is disabled or if enabled and the current value is different then the old value, send it back + if (! _track_last_value || (_track_last_value && avg != _last_value_float) || (_track_last_value && _cycles >= _force_update)) { + _cycles = 0; + _last_value_float = avg; + _send(_msg.set(avg, _float_precision)); + } + } + // process a string value + else if (_value_type == TYPE_STRING) { + // if track last value is disabled or if enabled and the current value is different then the old value, send it back + if (! _track_last_value || (_track_last_value && strcmp(_value_string, _last_value_string) != 0) || (_track_last_value && _cycles >= _force_update)) { + _cycles = 0; + _last_value_string = _value_string; + _send(_msg.set(_value_string)); + } + } + // turn the sensor off + #if POWER_MANAGER == 1 + powerOff(); + #endif +} + +// receive a message from the radio network +void Sensor::receive(const MyMessage &message) { + // return if not for this sensor + if (message.sensor != _child_id || message.type != _type) return; + // a request would make the sensor executing its main task + loop(message); +} + +// send a message to the network +void Sensor::_send(MyMessage & message) { + // send the message, multiple times if requested + for (int i = 0; i < _retries; i++) { + #if DEBUG == 1 + Serial.print("Send to="); + Serial.print(message.destination); + Serial.print(" id="); + Serial.print(message.sensor); + Serial.print(" cmd="); + Serial.print(message.getCommand()); + Serial.print(" type="); + Serial.print(message.type); + Serial.print(" str="); + Serial.print(message.getString()); + Serial.print(" int="); + Serial.print(message.getInt()); + Serial.print(" float="); + Serial.println(message.getFloat()); + #endif + send(message); + } +} + +/* + SensorAnalogInput +*/ + +// contructor +SensorAnalogInput::SensorAnalogInput(int child_id, int pin): Sensor(child_id, pin) { +} + +// setter/getter +void SensorAnalogInput::setReference(int value) { + _reference = value; +} +void SensorAnalogInput::setReverse(bool value) { + _reverse = value; +} +void SensorAnalogInput::setOutputPercentage(bool value) { + _output_percentage = value; +} +void SensorAnalogInput::setRangeMin(int value) { + _range_min = value; +} +void SensorAnalogInput::setRangeMax(int value) { + _range_max = value; +} + +// what do to during setup +void SensorAnalogInput::onBefore() { + // prepare the pin for input + pinMode(_pin, INPUT); +} + +// what do to during loop +void SensorAnalogInput::onLoop() { + // read the input + int adc = _getAnalogRead(); + // calculate the percentage + int percentage = 0; + if (_output_percentage) percentage = _getPercentage(adc); + #if DEBUG == 1 + Serial.print(" AnalogInput id="); + Serial.print(_child_id); + Serial.print(", val="); + Serial.print(adc); + Serial.print(", %="); + Serial.println(percentage); + #endif + // store the result + _value_int = _output_percentage ? percentage : adc; +} + +// what do to during loop +void SensorAnalogInput::onReceive(const MyMessage & message) { + onLoop(); +} + +// read the analog input +int SensorAnalogInput::_getAnalogRead() { + // set the reference + if (_reference != -1) { + analogReference(_reference); + sleep(100); + } + // read and return the value + int value = analogRead(_pin); + if (_reverse) value = _range_max - value; + return value; +} + +// return a percentage from an analog value +int SensorAnalogInput::_getPercentage(int adc) { + float value = (float)adc; + // scale the percentage based on the range provided + float percentage = ((value - _range_min) / (_range_max - _range_min)) * 100; + if (percentage > 100) percentage = 100; + if (percentage < 0) percentage = 0; + return (int)percentage; +} + +/* + SensorLDR +*/ + +// contructor +SensorLDR::SensorLDR(int child_id, int pin): SensorAnalogInput(child_id, pin) { + // set presentation and type and reverse (0: no light, 100: max light) + setPresentation(S_LIGHT_LEVEL); + setType(V_LIGHT_LEVEL); + setReverse(true); +} + +/* + SensorThermistor +*/ + +// contructor +SensorThermistor::SensorThermistor(int child_id, int pin): Sensor(child_id, pin) { + // set presentation, type and value type + setPresentation(S_TEMP); + setType(V_TEMP); + setValueType(TYPE_FLOAT); +} + +// setter/getter +void SensorThermistor::setNominalResistor(int value) { + _nominal_resistor = value; +} +void SensorThermistor::setNominalTemperature(int value) { + _nominal_temperature = value; +} +void SensorThermistor::setBCoefficient(int value) { + _b_coefficient = value; +} +void SensorThermistor::setSeriesResistor(int value) { + _series_resistor = value; +} +void SensorThermistor::setOffset(float value) { + _offset = value; +} + +// what do to during setup +void SensorThermistor::onBefore() { + // set the pin as input + pinMode(_pin, INPUT); +} + +// what do to during loop +void SensorThermistor::onLoop() { + // read the voltage across the thermistor + float adc = analogRead(_pin); + // calculate the temperature + float reading = (1023 / adc) - 1; + reading = _series_resistor / reading; + float temperature; + temperature = reading / _nominal_resistor; // (R/Ro) + temperature = log(temperature); // ln(R/Ro) + temperature /= _b_coefficient; // 1/B * ln(R/Ro) + temperature += 1.0 / (_nominal_temperature + 273.15); // + (1/To) + temperature = 1.0 / temperature; // Invert + temperature -= 273.15; // convert to C + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(" Thermistor id="); + Serial.print(_child_id); + Serial.print(", adc="); + Serial.print(adc); + Serial.print(", tmp="); + Serial.println(temperature); + Serial.print(", m="); + Serial.println(getControllerConfig().isMetric); + #endif + // store the value + _value_float = temperature; +} + +// what do to as the main task when receiving a message +void SensorThermistor::onReceive(const MyMessage & message) { + onLoop(); +} + +/* + SensorDigitalInput +*/ + +// contructor +SensorDigitalInput::SensorDigitalInput(int child_id, int pin): Sensor(child_id, pin) { +} + +// what do to during setup +void SensorDigitalInput::onBefore() { + // set the pin for input + pinMode(_pin, INPUT); +} + +// what do to during loop +void SensorDigitalInput::onLoop() { + // read the value + int value = digitalRead(_pin); + #if DEBUG == 1 + Serial.print("DigitalInput id="); + Serial.print(_child_id); + Serial.print(", pin="); + Serial.print(_pin); + Serial.print(", val="); + Serial.println(value); + #endif + // store the value + _value_int = value; +} + +// what do to as the main task when receiving a message +void SensorDigitalInput::onReceive(const MyMessage & message) { + onLoop(); +} + + +/* + SensorDigitalOutput +*/ + +// contructor +SensorDigitalOutput::SensorDigitalOutput(int child_id, int pin): Sensor(child_id, pin) { +} + +void SensorDigitalOutput::onBefore() { + // set the pin as output and initialize it accordingly + pinMode(_pin, OUTPUT); + digitalWrite(_pin, _initial_value == LOW ? LOW : HIGH); + // the initial value is now the current value + _value_int = _initial_value; +} + +// setter/getter +void SensorDigitalOutput::setInitialValue(int value) { + _initial_value = value; +} +void SensorDigitalOutput::setPulseWidth(int value) { + _pulse_width = value; +} + +// main task +void SensorDigitalOutput::onLoop() { + // do nothing on loop +} + +// what do to as the main task when receiving a message +void SensorDigitalOutput::onReceive(const MyMessage & message) { + // retrieve from the message the value to set + int value = message.getInt(); + if (value != 0 && value != 1) return; + #if DEBUG == 1 + Serial.print("DigitalOutput id="); + Serial.print(_child_id); + Serial.print(", pin="); + Serial.print(_pin); + Serial.print(", init="); + Serial.print(_initial_value); + Serial.print(", val="); + Serial.print(value); + Serial.print(", pls="); + Serial.println(_pulse_width); + #endif + // set the value + digitalWrite(_pin, value); + if (_pulse_width > 0) { + // if this is a pulse output, restore the value to the original value after the pulse + sleep(_pulse_width); + digitalWrite(_pin, value == 0 ? HIGH: LOW); + } + // store the current value + _value_int = value; +} + +/* + SensorRelay +*/ + +// contructor +SensorRelay::SensorRelay(int child_id, int pin): SensorDigitalOutput(child_id, pin) { + // set presentation and type + setPresentation(S_BINARY); + setType(V_STATUS); +} + +/* + SensorLatchingRelay +*/ + +// contructor +SensorLatchingRelay::SensorLatchingRelay(int child_id, int pin): SensorRelay(child_id, pin) { + // like a sensor with a default pulse set + setPulseWidth(50); +} + +/* + SensorDHT +*/ +#if MODULE_DHT == 1 +// contructor +SensorDHT::SensorDHT(int child_id, int pin, DHT* dht, int sensor_type, int dht_type): Sensor(child_id, pin) { + // store the dht object + _dht = dht; + // store the sensor type (0: temperature, 1: humidity) + _sensor_type = sensor_type; + _dht_type = dht_type; + if (_sensor_type == 0) { + // temperature sensor + setPresentation(S_TEMP); + setType(V_TEMP); + setValueType(TYPE_FLOAT); + } + else if (_sensor_type == 1) { + // humidity sensor + setPresentation(S_HUM); + setType(V_HUM); + setValueType(TYPE_FLOAT); + } +} + +// what do to during setup +void SensorDHT::onBefore() { + // initialize the dht library + _dht->begin(); +} + +// what do to during loop +void SensorDHT::onLoop() { + // temperature sensor + if (_sensor_type == 0) { + // read the temperature + float temperature = _dht->readTemperature(); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(" DHT id="); + Serial.print(_child_id); + Serial.print(", tmp="); + Serial.println(temperature); + #endif + // store the value + if (! isnan(temperature)) _value_float = temperature; + } + // humidity sensor + else if (_sensor_type == 1) { + // read humidity + float humidity = _dht->readHumidity(); + if (isnan(humidity)) return; + #if DEBUG == 1 + Serial.print(" DHT id="); + Serial.print(_child_id); + Serial.print(", %="); + Serial.println(humidity); + #endif + // store the value + if (! isnan(humidity)) _value_float = humidity; + } +} + +// what do to as the main task when receiving a message +void SensorDHT::onReceive(const MyMessage & message) { + onLoop(); +} +#endif + +/* + SensorSHT21 +*/ +#if MODULE_SHT21 == 1 +// contructor +SensorSHT21::SensorSHT21(int child_id, int sensor_type): Sensor(child_id, -1) { + // store the sensor type (0: temperature, 1: humidity) + _sensor_type = sensor_type; + if (_sensor_type == 0) { + // temperature sensor + setPresentation(S_TEMP); + setType(V_TEMP); + setValueType(TYPE_FLOAT); + } + else if (_sensor_type == 1) { + // humidity sensor + setPresentation(S_HUM); + setType(V_HUM); + setValueType(TYPE_FLOAT); + } +} + +// what do to during setup +void SensorSHT21::onBefore() { + // initialize the library + Wire.begin(); +} + +// what do to during loop +void SensorSHT21::onLoop() { + // temperature sensor + if (_sensor_type == 0) { + // read the temperature + float temperature = SHT2x.GetTemperature(); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(" SHT21 id="); + Serial.print(_child_id); + Serial.print(", tmp="); + Serial.println(temperature); + #endif + // store the value + if (! isnan(temperature)) _value_float = temperature; + } + // Humidity Sensor + else if (_sensor_type == 1) { + // read humidity + float humidity = SHT2x.GetHumidity(); + if (isnan(humidity)) return; + #if DEBUG == 1 + Serial.print(" SHT21 id="); + Serial.print(_child_id); + Serial.print(", %="); + Serial.println(humidity); + #endif + // store the value + if (! isnan(humidity)) _value_float = humidity; + } +} + +// what do to as the main task when receiving a message +void SensorSHT21::onReceive(const MyMessage & message) { + onLoop(); +} +#endif + +/* + * SensorSwitch + */ +SensorSwitch::SensorSwitch(int child_id, int pin): Sensor(child_id,pin) { + setType(V_TRIPPED); +} + +// setter/getter +void SensorSwitch::setMode(int value) { + _mode = value; +} +int SensorSwitch::getMode() { + return _mode; +} +// setter/getter +void SensorSwitch::setDebounce(int value) { + _debounce = value; +} +// setter/getter +void SensorSwitch::setTriggerTime(int value) { + _trigger_time = value; +} + +// what do to during setup +void SensorSwitch::onBefore() { + // initialize the value + if (_mode == RISING) _value_int = LOW; + else if (_mode == FALLING) _value_int = HIGH; +} + +// what do to during loop +void SensorSwitch::onLoop() { + // wait to ensure the the input is not floating + if (_debounce > 0) sleep(_debounce); + // read the value of the pin + int value = digitalRead(_pin); + // process the value + if ( (_mode == RISING && value == HIGH ) || (_mode == FALLING && value == LOW) || (_mode == CHANGE) ) { + #if DEBUG == 1 + Serial.print("Switch id="); + Serial.print(_child_id); + Serial.print(", pin="); + Serial.print(_pin); + Serial.print(", val="); + Serial.println(value); + #endif + _value_int = value; + // allow the signal to be restored to its normal value + if (_trigger_time > 0) sleep(_trigger_time); + } else { + // invalid + _value_int = -1; + } +} +// what do to as the main task when receiving a message +void SensorSwitch::onReceive(const MyMessage & message) { + onLoop(); +} + +/* + * SensorDoor + */ +SensorDoor::SensorDoor(int child_id, int pin): SensorSwitch(child_id,pin) { + setPresentation(S_DOOR); +} + +/* + * SensorMotion + */ +SensorMotion::SensorMotion(int child_id, int pin): SensorSwitch(child_id,pin) { + setPresentation(S_MOTION); + // capture only when it triggers + setMode(RISING); +} + +/* + SensorDs18b20 +*/ +#if MODULE_DS18B20 == 1 +// contructor +SensorDs18b20::SensorDs18b20(int child_id, int pin, DallasTemperature* sensors, int index): Sensor(child_id, pin) { + setPresentation(S_TEMP); + setType(V_TEMP); + setValueType(TYPE_FLOAT); + _index = index; + _sensors = sensors; +} + +// what do to during setup +void SensorDs18b20::onBefore() { +} + +// what do to during loop +void SensorDs18b20::onLoop() { + // request the temperature + _sensors->requestTemperaturesByIndex(_index); + // read the temperature + float temperature = _sensors->getTempCByIndex(_index); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(" Ds18b20 id="); + Serial.print(_child_id); + Serial.print(", tmp="); + Serial.println(temperature); + #endif + // store the value + _value_float = temperature; +} + +// what do to as the main task when receiving a message +void SensorDs18b20::onReceive(const MyMessage & message) { + onLoop(); +} + + +#endif + +/******************************************* + NodeManager +*/ + +// initialize the node manager +NodeManager::NodeManager() { + // setup the service message container + _msg = MyMessage(CONFIGURATION_CHILD_ID, V_CUSTOM); +} + +// setter/getter +void NodeManager::setRebootPin(int value) { + _reboot_pin = value; +} +#if BATTERY_MANAGER == 1 + void NodeManager::setBatteryMin(float value) { + _battery_min = value; + } + void NodeManager::setBatteryMax(float value) { + _battery_max = value; + } + void NodeManager::setBatteryReportCycles(int value) { + _battery_report_cycles = value; + } +#endif +#if SLEEP_MANAGER == 1 + void NodeManager::setSleepMode(int value) { + _sleep_mode = value; + } + void NodeManager::setSleepTime(int value) { + _sleep_time = value; + } + void NodeManager::setSleepUnit(int value) { + _sleep_unit = value; + } + void NodeManager::setSleep(int value1, int value2, int value3) { + _sleep_mode = value1; + _sleep_time = value1; + _sleep_unit = value3; + } + void NodeManager::setSleepInterruptPin(int value) { + _sleep_interrupt_pin = value; + } +#endif +void NodeManager::setInterrupt(int pin, int mode, int pull = -1) { + if (pin == INTERRUPT_PIN_1) { + _interrupt_1_mode = mode; + _interrupt_1_pull = pull; + } + if (pin == INTERRUPT_PIN_2) { + _interrupt_2_mode = mode; + _interrupt_2_pull = pull; + } +} +#if POWER_MANAGER == 1 + void NodeManager::setPowerPins(int ground_pin, int vcc_pin, long wait = 10) { + _powerManager.setPowerPins(ground_pin, vcc_pin, wait); + } + void NodeManager::powerOn() { + _powerManager.powerOn(); + } + void NodeManager::powerOff() { + _powerManager.powerOff(); + } +#endif + +// register a sensor to this manager +int NodeManager::registerSensor(int sensor_type, int pin = -1, int child_id = -1) { + #if DEBUG == 1 + if (_startup) { + Serial.print("NodeManager v"); + Serial.println(VERSION); + _startup = false; + } + #endif + // get a child_id if not provided by the user + if (child_id < 0) child_id = _getAvailableChildId(); + // based on the given sensor type instantiate the appropriate class + if (sensor_type == 0) return; + #if MODULE_ANALOG_INPUT == 1 + else if (sensor_type == SENSOR_ANALOG_INPUT) return registerSensor(new SensorAnalogInput(child_id, pin)); + else if (sensor_type == SENSOR_LDR) return registerSensor(new SensorLDR(child_id, pin)); + else if (sensor_type == SENSOR_THERMISTOR) return registerSensor(new SensorThermistor(child_id, pin)); + #endif + #if MODULE_DIGITAL_INPUT == 1 + else if (sensor_type == SENSOR_DIGITAL_INPUT) return registerSensor(new SensorDigitalInput(child_id, pin)); + #endif + #if MODULE_DIGITAL_OUTPUT == 1 + else if (sensor_type == SENSOR_DIGITAL_OUTPUT) return registerSensor(new SensorDigitalOutput(child_id, pin)); + else if (sensor_type == SENSOR_RELAY) return registerSensor(new SensorRelay(child_id, pin)); + else if (sensor_type == SENSOR_LATCHING_RELAY) return registerSensor(new SensorLatchingRelay(child_id, pin)); + #endif + #if MODULE_DHT == 1 + else if (sensor_type == SENSOR_DHT11 || sensor_type == SENSOR_DHT22) { + DHT* dht = new DHT(pin,DHT22); + int dht_type = sensor_type == SENSOR_DHT11 ? DHT11 : DHT22; + registerSensor(new SensorDHT(child_id,pin,dht,0,dht_type)); + child_id = _getAvailableChildId(); + registerSensor(new SensorDHT(child_id,pin,dht,1,dht_type)); + } + #endif + #if MODULE_SHT21 == 1 + else if (sensor_type == SENSOR_SHT21) { + registerSensor(new SensorSHT21(child_id,0)); + child_id = _getAvailableChildId(); + registerSensor(new SensorSHT21(child_id,1)); + } + #endif + #if MODULE_SWITCH == 1 + else if (sensor_type == SENSOR_SWITCH || sensor_type == SENSOR_DOOR || sensor_type == SENSOR_MOTION) { + // ensure an interrupt pin is provided + if (pin != INTERRUPT_PIN_1 && pin != INTERRUPT_PIN_2) return; + // register the sensor + int index = 0; + if (sensor_type == SENSOR_SWITCH) index = registerSensor(new SensorSwitch(child_id, pin)); + else if (sensor_type == SENSOR_DOOR) index = registerSensor(new SensorDoor(child_id, pin)); + else if (sensor_type == SENSOR_MOTION) index = registerSensor(new SensorMotion(child_id, pin)); + // set an interrupt on the pin and activate internal pull up + setInterrupt(pin,((SensorSwitch*)get(index))->getMode(),HIGH); + return index; + } + #endif + #if MODULE_DS18B20 == 1 + else if (sensor_type == SENSOR_DS18B20) { + // initialize the library + OneWire* oneWire = new OneWire(pin); + DallasTemperature* sensors = new DallasTemperature(oneWire); + // initialize the sensors + sensors->begin(); + // register a new child for each sensor on the bus + for(int i = 0; i < sensors->getDeviceCount(); i++) { + if (i > 0) child_id = _getAvailableChildId(); + registerSensor(new SensorDs18b20(child_id,pin,sensors,i)); + } + } + #endif + else { + #if DEBUG == 1 + Serial.print("Invalid sensor type="); + Serial.println(sensor_type); + #endif + return -1; + }; +} + +// attach a built-in or custom sensor to this manager +int NodeManager::registerSensor(Sensor* sensor) { + #if DEBUG == 1 + Serial.print("Register id="); + Serial.print(sensor->getChildId()); + Serial.print(", pin="); + Serial.print(sensor->getPin()); + Serial.print(", pres="); + Serial.print(sensor->getPresentation()); + Serial.print(", type="); + Serial.println(sensor->getType()); + #endif + // add the sensor to the array of registered sensors + _sensors[sensor->getChildId()] = sensor; + // return the child_id + return sensor->getChildId(); +} + +// return a sensor given its index +Sensor* NodeManager::get(int child_id) { + // return a pointer to the sensor from the given child_id + return _sensors[child_id]; +} + +// setup NodeManager +void NodeManager::before() { + #if DEBUG == 1 + Serial.print("node_id="); + Serial.print(getNodeId()); + Serial.print(", metric="); + Serial.println(getControllerConfig().isMetric); + #endif + if (_reboot_pin > -1) { + #if DEBUG == 1 + Serial.print("Reboot pin="); + Serial.println(_reboot_pin); + #endif + // setup the reboot pin + pinMode(_reboot_pin, OUTPUT); + digitalWrite(_reboot_pin, HIGH); + } + // setup the sleep interrupt pin + if (_sleep_interrupt_pin > -1) { + // set the interrupt when the pin is connected to ground + setInterrupt(_sleep_interrupt_pin,FALLING,HIGH); + } + // setup the interrupt pins + if (_interrupt_1_mode != MODE_NOT_DEFINED) { + pinMode(INTERRUPT_PIN_1,INPUT); + if (_interrupt_1_pull > -1) digitalWrite(INTERRUPT_PIN_1,_interrupt_1_pull); + } + if (_interrupt_2_mode != MODE_NOT_DEFINED) { + pinMode(INTERRUPT_PIN_2, INPUT); + if (_interrupt_2_pull > -1) digitalWrite(INTERRUPT_PIN_2,_interrupt_2_pull); + } + #if DEBUG == 1 + Serial.print("Interrupt1 mode="); + Serial.println(_interrupt_1_mode); + Serial.print("Interrupt2 mode="); + Serial.println(_interrupt_2_mode); + #endif + #if REMOTE_CONFIGURATION == 1 && SLEEP_MANAGER == 1 && PERSIST == 1 + // restore sleep configuration from eeprom + if (loadState(EEPROM_SLEEP_SAVED) == 1) { + // sleep settings found in the eeprom, restore them + _sleep_mode = loadState(EEPROM_SLEEP_MODE); + _sleep_time = loadState(EEPROM_SLEEP_TIME_MINOR); + int major = loadState(EEPROM_SLEEP_TIME_MAJOR); + if (major == 1) _sleep_time = _sleep_time + 250; + else if (major == 2) _sleep_time = _sleep_time + 250 * 2; + else if (major == 3) _sleep_time = _sleep_time + 250 * 3; + _sleep_unit = loadState(EEPROM_SLEEP_UNIT); + #if DEBUG == 1 + Serial.print("Load sleep mode="); + Serial.print(_sleep_mode); + Serial.print(" time="); + Serial.print(_sleep_time); + Serial.print(" unit="); + Serial.println(_sleep_unit); + #endif + } + #endif + // setup individual sensors + for (int i = 0; i < 255; i++) { + if (_sensors[i] == 0) continue; + // call each sensor's setup() + _sensors[i]->before(); + } +} + +// present NodeManager and its sensors +void NodeManager::presentation() { + // present the service as a custom sensor to the controller + #if DEBUG == 1 + Serial.print("Present id="); + Serial.print(CONFIGURATION_CHILD_ID); + Serial.print(", type="); + Serial.println(S_CUSTOM); + #endif + present(CONFIGURATION_CHILD_ID, S_CUSTOM); + #if BATTERY_MANAGER == 1 && BATTERY_SENSOR == 1 + #if DEBUG == 1 + Serial.print("Present id="); + Serial.print(BATTERY_CHILD_ID); + Serial.print(", type="); + Serial.println(S_MULTIMETER); + #endif + // present the battery service + present(BATTERY_CHILD_ID, S_MULTIMETER); + // report battery level + _process("BATTERY"); + #endif + // present each sensor + for (int i = 0; i < 255; i++) { + if (_sensors[i] == 0) continue; + // call each sensor's presentation() + _sensors[i]->presentation(); + } + #if DEBUG == 1 + Serial.println("Ready"); + Serial.println(""); + #endif +} + +// run the main function for all the register sensors +void NodeManager::loop() { + #if SLEEP_MANAGER == 1 + MyMessage empty; + if (_sleep_mode != IDLE && _sleep_time != 0) { + #if POWER_MANAGER == 1 + // turn on the pin powering all the sensors + powerOn(); + #endif + // run loop for all the registered sensors + for (int i = 0; i < 255; i++) { + if (_sensors[i] == 0) continue; + // call each sensor's loop() + _sensors[i]->loop(empty); + } + #if POWER_MANAGER == 1 + // turn off the pin powering all the sensors + powerOff(); + #endif + // continue/start sleeping as requested + _sleep(); + } + #endif +} + +// dispacth inbound messages +void NodeManager::receive(const MyMessage &message) { + #if DEBUG == 1 + Serial.print("Recv from="); + Serial.print(message.sender); + Serial.print(" id="); + Serial.print(message.sensor); + Serial.print(" cmd="); + Serial.print(message.getCommand()); + Serial.print(" type="); + Serial.print(message.type); + Serial.print(" data="); + Serial.println(message.getString()); + #endif + // process incoming service messages + if (message.sensor == CONFIGURATION_CHILD_ID && message.getCommand() == C_REQ && message.type == V_CUSTOM) { + _process(message.getString()); + } + // dispatch the message to the registered sensor + else if (message.getCommand() == C_REQ && _sensors[message.sensor] != 0) { + #if POWER_MANAGER == 1 + // turn on the pin powering all the sensors + powerOn(); + #endif + // call the sensor's receive() + _sensors[message.sensor]->receive(message); + #if POWER_MANAGER == 1 + // turn off the pin powering all the sensors + powerOff(); + #endif + } +} + +// process a service message +void NodeManager::_process(const char * message) { + // HELLO: hello request + if (strcmp(message, "HELLO") == 0) { + send(_msg.set(message)); + } + #if BATTERY_MANAGER == 1 + // BATTERY: return the battery level + else if (strcmp(message, "BATTERY") == 0) { + // measure the board vcc + float volt = _getVcc(); + // calculate the percentage + int percentage = ((volt - _battery_min) / (_battery_max - _battery_min)) * 100; + if (percentage > 100) percentage = 100; + if (percentage < 0) percentage = 0; + #if DEBUG == 1 + Serial.print("Battery v="); + Serial.print(volt); + Serial.print(", %="); + Serial.println(percentage); + #endif + #if BATTERY_MANAGER == 1 && BATTERY_SENSOR == 1 + // report battery voltage + MyMessage battery_msg(BATTERY_CHILD_ID, V_VOLTAGE); + send(battery_msg.set(volt, 2)); + #endif + // report battery level percentage + sendBatteryLevel(percentage); + } + #endif + // REBOOT: reboot the board + else if (strcmp(message, "REBOOT") == 0 && _reboot_pin > -1) { + #if DEBUG == 1 + Serial.println("Reboot"); + #endif + // set the reboot pin connected to RST to low so to reboot the board + send(_msg.set(message)); + digitalWrite(_reboot_pin, LOW); + } + // CLEAR: clear the user's eeprom + else if (strcmp(message, "CLEAR") == 0) { + #if DEBUG == 1 + Serial.println("Clear"); + #endif + for (int i = 0; i <= EEPROM_LAST_ID; i++) saveState(i, 0xFF); + send(_msg.set(message)); + } + // VERSION: send back the extension's version + else if (strcmp(message, "VERSION") == 0) { + send(_msg.set(VERSION, 1)); + } + #if REMOTE_CONFIGURATION == 1 + // IDxxx: change the node id to the provided one. E.g. ID025: change the node id to 25. Requires a reboot/restart + else if (strlen(message) == 5 && strncmp("ID", message, strlen("ID")) == 0) { + // extract the node id + char s[4]; + s[0] = message[2]; + s[1] = message[3]; + s[2] = message[4]; + s[3] = '\0'; + int node_id = atoi(s); + #if DEBUG == 1 + Serial.print("Set node_id="); + Serial.println(node_id); + #endif + // Save static ID to eeprom + hwWriteConfig(EEPROM_NODE_ID_ADDRESS, (uint8_t)node_id); + // reboot the board + #if REBOOT_PIN == 1 + _process("REBOOT"); + #endif + } + #if SLEEP_MANAGER == 1 + // MODEx: change the way the board behaves. 0: stay awake, 1: go to sleep for the configured interval, 2: wait for the configured interval (e.g. MODE1) + else if (strlen(message) == 5 && strncmp("MODE", message, strlen("MODE")) == 0) { + // extract mode + char s[2]; + s[0] = message[4]; + s[1] = '\0'; + _sleep_mode = atoi(s); + #if DEBUG == 1 + Serial.print("Set sleep mode="); + Serial.println(_sleep_mode); + #endif + #if PERSIST == 1 + // save it to the eeprom + saveState(EEPROM_SLEEP_SAVED, 1); + saveState(EEPROM_SLEEP_MODE, _sleep_mode); + #endif + send(_msg.set(message)); + } + // INTVLnnnX: set and save the wait/sleep interval to nnn where X is S=Seconds, M=mins, H=Hours, D=Days. E.g. INTVL010M would be 10 minutes + else if (strlen(message) == 9 && strncmp("INTVL", message, strlen("INTVL")) == 0) { + // parse and set the sleep interval + int offset = 5; + // extract the unit (S=secs, M=mins, H=hours, D=Days) + char unit[2]; + sprintf(unit, "%c", message[3 + offset]); + unit[1] = '\0'; + if (strcmp(unit, "S") == 0) _sleep_unit = SECONDS; + else if (strcmp(unit, "M") == 0) _sleep_unit = MINUTES; + else if (strcmp(unit, "H") == 0) _sleep_unit = HOURS; + else if (strcmp(unit, "D") == 0) _sleep_unit = DAYS; + else return; + // extract the requested time + char s[4]; + s[0] = message[0 + offset]; + s[1] = message[1 + offset]; + s[2] = message[2 + offset]; + s[3] = '\0'; + _sleep_time = atoi(s); + #if DEBUG == 1 + Serial.print("Set sleep time="); + Serial.print(_sleep_time); + Serial.print(", unit="); + Serial.println(_sleep_unit); + #endif + #if PERSIST == 1 + // save it to eeprom + saveState(EEPROM_SLEEP_UNIT, _sleep_unit); + // encode sleep time + int major = 0; + if (_sleep_time > 750) major = 3; + else if (_sleep_time > 500) major = 2; + else if (_sleep_time > 250) major = 1; + int minor = _sleep_time - 250 * major; + saveState(EEPROM_SLEEP_SAVED, 1); + saveState(EEPROM_SLEEP_TIME_MINOR, minor); + saveState(EEPROM_SLEEP_TIME_MAJOR, major); + #endif + // interval set, reply back with the same message to acknowledge. + send(_msg.set(message)); + } + #endif + // end remote configuration + #endif + // WAKEUP: when received after a sleeping cycle or during wait, abort the cycle and stay awake + #if SLEEP_MANAGER == 1 + else if (strcmp(message, "WAKEUP") == 0) { + #if DEBUG == 1 + Serial.println("Requested wake-up"); + #endif + send(_msg.set(message)); + _sleep_mode = IDLE; + } + #endif +} + +// wrapper of smart sleep +void NodeManager::_sleep() { + // calculate the seconds to sleep + long sleep_sec = _sleep_time; + if (_sleep_unit == MINUTES) sleep_sec = sleep_sec * 60; + else if (_sleep_unit == HOURS) sleep_sec = sleep_sec * 3600; + else if (_sleep_unit == DAYS) sleep_sec = sleep_sec * 43200; + long sleep_ms = sleep_sec * 1000; + #if DEBUG == 1 + Serial.print("Sleeping for "); + Serial.print(sleep_sec); + Serial.println("s"); + #endif + #if SERVICE_MESSAGES == 1 + // notify the controller I'm going to sleep + send(_msg.set("SLEEPING")); + #endif + #if DEBUG == 1 + // print a new line to separate the different cycles + Serial.println(""); + #endif + // go to sleep + if (_sleep_mode == WAIT) { + // wait for the given interval + wait(sleep_ms); + } + else if (_sleep_mode == SLEEP) { + // setup interrupt pins + int interrupt_1_pin = _interrupt_1_mode == MODE_NOT_DEFINED ? INTERRUPT_NOT_DEFINED : digitalPinToInterrupt(INTERRUPT_PIN_1); + int interrupt_2_pin = _interrupt_2_mode == MODE_NOT_DEFINED ? INTERRUPT_NOT_DEFINED : digitalPinToInterrupt(INTERRUPT_PIN_2); + // enter smart sleep for the requested sleep interval and with the configured interrupts + int ret = sleep(interrupt_1_pin,_interrupt_1_mode,interrupt_2_pin,_interrupt_2_mode,sleep_ms, true); + if (ret > -1) { + int pin_number = -1; + int interrupt_mode = -1; + if (digitalPinToInterrupt(INTERRUPT_PIN_1) == ret) { + pin_number = INTERRUPT_PIN_1; + interrupt_mode = _interrupt_1_mode; + } + if (digitalPinToInterrupt(INTERRUPT_PIN_2) == ret) { + pin_number = INTERRUPT_PIN_2; + interrupt_mode = _interrupt_2_mode; + } + #if DEBUG == 1 + Serial.print("Woke up pin="); + Serial.print(pin_number); + Serial.print(", mode="); + Serial.println(interrupt_mode); + #endif + // when waking up from an interrupt on the wakup pin, stop sleeping + if (_sleep_interrupt_pin == pin_number) _sleep_mode = IDLE; + // if (_interrupt_abort_sleep) _sleep_mode = IDLE; + // restore the interrupt pin value to its original value + // if (pin_number > 0) digitalWrite(pin_number, interrupt_mode == FALLING ? HIGH : LOW); + } + } + // coming out of sleep + #if DEBUG == 1 + Serial.println("Awake"); + #endif + #if SERVICE_MESSAGES == 1 + // notify the controller I am awake + send(_msg.set("AWAKE")); + #endif + #if BATTERY_MANAGER == 1 + // keep track of the number of sleeping cycles + _cycles++; + // battery has to be reported after the configured number of sleep cycles + if (_battery_report_cycles == _cycles) { + // time to report the battery level again + _process("BATTERY"); + _cycles = 0; + } + #endif +} + + +// return the next available child_id +int NodeManager::_getAvailableChildId() { + for (int i = 1; i < 255; i++) { + if (i == CONFIGURATION_CHILD_ID) continue; + if (i == BATTERY_CHILD_ID) continue; + // empty place, return it + if (_sensors[i] == 0) return i; + } +} + +// return vcc in V +float NodeManager::_getVcc() { + // Measure Vcc against 1.1V Vref + #if defined(__AVR_ATmega32U4__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega2560__) + ADMUX = (_BV(REFS0) | _BV(MUX4) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1)); + #elif defined (__AVR_ATtiny24__) || defined(__AVR_ATtiny44__) || defined(__AVR_ATtiny84__) + ADMUX = (_BV(MUX5) | _BV(MUX0)); + #elif defined (__AVR_ATtiny25__) || defined(__AVR_ATtiny45__) || defined(__AVR_ATtiny85__) + ADMUX = (_BV(MUX3) | _BV(MUX2)); + #else + ADMUX = (_BV(REFS0) | _BV(MUX3) | _BV(MUX2) | _BV(MUX1)); + #endif + // Vref settle + delay(70); + // Do conversion + ADCSRA |= _BV(ADSC); + while (bit_is_set(ADCSRA, ADSC)) {}; + // return Vcc in mV + return (float)((1125300UL) / ADC) / 1000; +} + + +// guess the initial value of a digital output based on the configured interrupt mode +int NodeManager::_getInterruptInitialValue(int mode) { + if (mode == RISING) return LOW; + if (mode == FALLING) return HIGH; + return -1; +} + diff --git a/NodeManagerTemplate/NodeManager.h b/NodeManagerTemplate/NodeManager.h new file mode 100644 index 00000000..8c731f4d --- /dev/null +++ b/NodeManagerTemplate/NodeManager.h @@ -0,0 +1,533 @@ +/* + * NodeManager + */ + +#ifndef NodeManager_h +#define NodeManager_h + +#include + +/*********************************** + Sensors types +*/ +// Generic analog sensor, return a pin's analog value or its percentage +#define SENSOR_ANALOG_INPUT 0 +// LDR sensor, return the light level of an attached light resistor in percentage +#define SENSOR_LDR 1 +// Thermistor sensor, return the temperature based on the attached thermistor +#define SENSOR_THERMISTOR 2 +// Generic digital sensor, return a pin's digital value +#define SENSOR_DIGITAL_INPUT 3 +// Generic digital output sensor, allows setting the digital output of a pin to the requested value +#define SENSOR_DIGITAL_OUTPUT 4 +// Relay sensor, allows activating the relay +#define SENSOR_RELAY 5 +// Latching Relay sensor, allows activating the relay with a pulse +#define SENSOR_LATCHING_RELAY 6 +// DHT11/DHT22 sensors, return temperature/humidity based on the attached DHT sensor +#define SENSOR_DHT11 7 +#define SENSOR_DHT22 8 +// SHT21 sensor, return temperature/humidity based on the attached SHT21 sensor +#define SENSOR_SHT21 9 +// Generic switch, wake up the board when a pin changes status +#define SENSOR_SWITCH 10 +// Door sensor, wake up the board and report when an attached magnetic sensor has been opened/closed +#define SENSOR_DOOR 11 +// Motion sensor, wake up the board and report when an attached PIR has triggered +#define SENSOR_MOTION 12 +// DS18B20 sensor, return the temperature based on the attached sensor +#define SENSOR_DS18B20 13 + +/*********************************** + Constants +*/ + +// define sleep mode +#define IDLE 0 +#define SLEEP 1 +#define WAIT 2 + +// define time unit +#define SECONDS 0 +#define MINUTES 1 +#define HOURS 2 +#define DAYS 3 + +// define value type +#define TYPE_INTEGER 0 +#define TYPE_FLOAT 1 +#define TYPE_STRING 2 + +// define interrupt pins +#define INTERRUPT_PIN_1 3 +#define INTERRUPT_PIN_2 2 + +// define eeprom addresses +#define EEPROM_LAST_ID 4 +#define EEPROM_SLEEP_SAVED 0 +#define EEPROM_SLEEP_MODE 1 +#define EEPROM_SLEEP_TIME_MAJOR 2 +#define EEPROM_SLEEP_TIME_MINOR 3 +#define EEPROM_SLEEP_UNIT 4 + +// define NodeManager version +#define VERSION 1.0 + +/*********************************** + Configuration settings +*/ +// default configuration settings + +// if enabled, will load the sleep manager library. Sleep mode and sleep interval have to be configured to make the board sleeping/waiting +#define SLEEP_MANAGER 1 +// if enabled, enable the capability to power on sensors with the arduino's pins to save battery while sleeping +#define POWER_MANAGER 1 +// if enabled, will load the battery manager library to allow the battery level to be reported automatically or on demand +#define BATTERY_MANAGER 1 +// if enabled, allow modifying the configuration remotely by interacting with the configuration child id +#define REMOTE_CONFIGURATION 1 +// if enabled, persist the configuration settings on EEPROM +#define PERSIST 0 + +// if enabled, enable debug messages on serial port +#define DEBUG 1 + +// if enabled, send a SLEEPING and AWAKE service messages just before entering and just after leaving a sleep cycle +#define SERVICE_MESSAGES 1 +// if enabled, a battery sensor will be created at BATTERY_CHILD_ID and will report vcc voltage together with the battery level percentage +#define BATTERY_SENSOR 1 + +// the child id used to allow remote configuration +#define CONFIGURATION_CHILD_ID 200 +// the child id used to report the battery voltage to the controller +#define BATTERY_CHILD_ID 201 + +// Enable this module to use one of the following sensors: SENSOR_ANALOG_INPUT, SENSOR_LDR, SENSOR_THERMISTOR +#define MODULE_ANALOG_INPUT 1 +// Enable this module to use one of the following sensors: SENSOR_DIGITAL_INPUT +#define MODULE_DIGITAL_INPUT 1 +// Enable this module to use one of the following sensors: SENSOR_DIGITAL_OUTPUT, SENSOR_RELAY, SENSOR_LATCHING_RELAY +#define MODULE_DIGITAL_OUTPUT 1 +// Enable this module to use one of the following sensors: SENSOR_SHT21 +#define MODULE_SHT21 0 +// Enable this module to use one of the following sensors: SENSOR_DHT11, SENSOR_DHT22 +#define MODULE_DHT 0 +// Enable this module to use one of the following sensors: SENSOR_SWITCH, SENSOR_DOOR, SENSOR_MOTION +#define MODULE_SWITCH 0 +// Enable this module to use one of the following sensors: SENSOR_DS18B20 +#define MODULE_DS18B20 0 + +// include user defined configuration difrectives +#include "config.h" + +/*********************************** + Libraries +*/ + +// include MySensors libraries +#include +#include + +// include third party libraries +#if MODULE_DHT == 1 + #include +#endif +#if MODULE_SHT21 == 1 + #include + #include +#endif +#if MODULE_SHT21 == 1 + #include + #include +#endif +#if MODULE_DS18B20 == 1 + #include + #include +#endif + + +/************************************** + Classes +*/ + +/* + PowerManager +*/ + +class PowerManager { + public: + PowerManager() {}; + // to save battery the sensor can be optionally connected to two pins which will act as vcc and ground and activated on demand + void setPowerPins(int ground_pin, int vcc_pin, long wait = 0); + void powerOn(); + void powerOff(); + private: + int _vcc_pin = -1; + int _ground_pin = -1; + long _wait = 0; + bool _hasPowerManager(); +}; + + +/*************************************** + Sensor: generic sensor class +*/ +class Sensor { + public: + Sensor(int child_id, int pin); + // where the sensor is attached to (default: not set) + void setPin(int value); + int getPin(); + // child_id of this sensor (default: not set) + void setChildId(int value); + int getChildId(); + // presentation of this sensor (default: S_CUSTOM) + void setPresentation(int value); + int getPresentation(); + // type of this sensor (default: V_CUSTOM) + void setType(int value); + int getType(); + // when queried, send the message multiple times (default: 1) + void setRetries(int value); + // For some sensors, the measurement can be queried multiple times and an average is returned (default: 1) + void setSamples(int value); + // If more then one sample has to be taken, set the interval in milliseconds between measurements (default: 0) + void setSamplesInterval(int value); + // if true will report the measure only if different then the previous one (default: false) + void setTackLastValue(bool value); + // if track last value is enabled, force to send an update after the configured number of cycles (default: -1) + void setForceUpdate(int value); + // the value type of this sensor (default: TYPE_INTEGER) + void setValueType(int value); + // for float values, set the float precision (default: 2) + void setFloatPrecision(int value); + #if POWER_MANAGER == 1 + // to save battery the sensor can be optionally connected to two pins which will act as vcc and ground and activated on demand + void setPowerPins(int ground_pin, int vcc_pin, long wait = 0); + void powerOn(); + void powerOff(); + #endif + // define what to do at each stage of the sketch + virtual void before(); + virtual void presentation(); + virtual void loop(const MyMessage & message); + virtual void receive(const MyMessage & message); + // abstract functions, subclasses need to implement + virtual void onBefore() = 0; + virtual void onLoop() = 0; + virtual void onReceive(const MyMessage & message) = 0; + protected: + MyMessage _msg; + int _pin = -1; + int _child_id; + int _presentation = S_CUSTOM; + int _type = V_CUSTOM; + int _retries = 1; + int _samples = 1; + int _samples_interval = 0; + bool _track_last_value = false; + int _cycles = 0; + int _force_update = -1; + void _send(MyMessage & msg); + #if POWER_MANAGER == 1 + PowerManager _powerManager; + #endif + int _value_type = TYPE_INTEGER; + int _float_precision = 2; + int _value_int = -1; + float _value_float = -1; + char * _value_string = ""; + int _last_value_int = -1; + float _last_value_float = -1; + char * _last_value_string = ""; +}; + +/* + SensorAnalogInput: read the analog input of a configured pin +*/ +class SensorAnalogInput: public Sensor { + public: + SensorAnalogInput(int child_id, int pin); + // the analog reference to use (default: not set, can be either INTERNAL or DEFAULT) + void setReference(int value); + // reverse the value or the percentage (e.g. 70% -> 30%) (default: false) + void setReverse(bool value); + // when true returns the value as a percentage (default: true) + void setOutputPercentage(bool value); + // minimum value for calculating the percentage (default: 0) + void setRangeMin(int value); + // maximum value for calculating the percentage (default: 1024) + void setRangeMax(int value); + // define what to do at each stage of the sketch + void onBefore(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + int _reference = -1; + bool _reverse = false; + bool _output_percentage = true; + int _range_min = 0; + int _range_max = 1024; + int _getPercentage(int value); + int _getAnalogRead(); +}; + +/* + SensorLDR: return the percentage of light from a Light dependent resistor +*/ +class SensorLDR: public SensorAnalogInput { + public: + SensorLDR(int child_id, int pin); +}; + +/* + SensorThermistor: read the temperature from a thermistor +*/ +class SensorThermistor: public Sensor { + public: + SensorThermistor(int child_id, int pin); + // resistance at 25 degrees C (default: 10000) + void setNominalResistor(int value); + // temperature for nominal resistance (default: 25) + void setNominalTemperature(int value); + // The beta coefficient of the thermistor (default: 3950) + void setBCoefficient(int value); + // the value of the resistor in series with the thermistor (default: 10000) + void setSeriesResistor(int value); + // set a temperature offset + void setOffset(float value); + // define what to do at each stage of the sketch + void onBefore(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + int _nominal_resistor = 10000; + int _nominal_temperature = 25; + int _b_coefficient = 3950; + int _series_resistor = 10000; + float _offset = 0; +}; + +/* + SensorDigitalInput: read the digital input of the configured pin +*/ +class SensorDigitalInput: public Sensor { + public: + SensorDigitalInput(int child_id, int pin); + // define what to do at each stage of the sketch + void onBefore(); + void onLoop(); + void onReceive(const MyMessage & message); +}; + +/* + SensorDigitalOutput: control a digital output of the configured pin +*/ +class SensorDigitalOutput: public Sensor { + public: + SensorDigitalOutput(int child_id, int pin); + // set how to initialize the output (default: LOW) + void setInitialValue(int value); + // if greater than 0, send a pulse of the given duration in ms and then restore the output back to the original value (default: 0) + void setPulseWidth(int value); + // define what to do at each stage of the sketch + void onBefore(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + int _initial_value = LOW; + int _pulse_width = 0; +}; + + +/* + SensorRelay +*/ +class SensorRelay: public SensorDigitalOutput { + public: + SensorRelay(int child_id, int pin); +}; + +/* + SensorLatchingRelay +*/ +class SensorLatchingRelay: public SensorRelay { + public: + SensorLatchingRelay(int child_id, int pin); +}; + +/* + SensorDHT +*/ +#if MODULE_DHT == 1 +class SensorDHT: public Sensor { + public: + SensorDHT(int child_id, int pin, DHT* dht, int sensor_type, int dht_type); + // define what to do at each stage of the sketch + void onBefore(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + DHT* _dht; + int _dht_type = DHT11; + float _offset = 0; + int _sensor_type = 0; +}; +#endif + +/* + SensorSHT21 +*/ +#if MODULE_SHT21 == 1 +class SensorSHT21: public Sensor { + public: + SensorSHT21(int child_id, int sensor_type); + // define what to do at each stage of the sketch + void onBefore(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + float _offset = 0; + int _sensor_type = 0; +}; +#endif + +/* + * SensorSwitch + */ +class SensorSwitch: public Sensor { + public: + SensorSwitch(int child_id, int pin); + // set the interrupt mode. Can be CHANGE, RISING, FALLING (default: CHANGE) + void setMode(int value); + int getMode(); + // milliseconds to wait before reading the input (default: 0) + void setDebounce(int value); + // time to wait in milliseconds after a change is detected to allow the signal to be restored to its normal value (default: 0) + void setTriggerTime(int value); + // define what to do at each stage of the sketch + void onBefore(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + int _debounce = 0; + int _trigger_time = 0; + int _mode = CHANGE; +}; + +/* + * SensorDoor + */ +class SensorDoor: public SensorSwitch { + public: + SensorDoor(int child_id, int pin); +}; + +/* + * SensorMotion + */ +class SensorMotion: public SensorSwitch { + public: + SensorMotion(int child_id, int pin); +}; + +/* + SensorDs18b20 +*/ +#if MODULE_DS18B20 == 1 +class SensorDs18b20: public Sensor { + public: + SensorDs18b20(int child_id, int pin, DallasTemperature* sensors, int index); + // define what to do at each stage of the sketch + void onBefore(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + float _offset = 0; + int _index; + DallasTemperature* _sensors; +}; +#endif + + +/*************************************** + NodeManager: manages all the aspects of the node +*/ +class NodeManager { + public: + NodeManager(); + // the pin to connect to the RST pin to reboot the board (default: 4) + void setRebootPin(int value); + #if BATTERY_MANAGER == 1 + // the expected vcc when the batter is fully discharged, used to calculate the percentage (default: 2.7) + void setBatteryMin(float value); + // the expected vcc when the batter is fully charged, used to calculate the percentage (default: 3.3) + void setBatteryMax(float value); + // how frequently (in hours) to report the battery level to the controller. When reset the battery is always reported (default: 1) + void setBatteryReportCycles(int value); + #endif + #if SLEEP_MANAGER == 1 + // define if the board has to sleep every time entering loop (default: IDLE). It can be IDLE (no sleep), SLEEP (sleep at every cycle), WAIT (wait at every cycle + void setSleepMode(int value); + // define for how long the board will sleep (default: 0) + void setSleepTime(int value); + // define the unit of SLEEP_TIME. It can be SECONDS, MINUTES, HOURS or DAYS (default: MINUTES) + void setSleep(int value1, int value2, int value3); + void setSleepUnit(int value); + // if enabled, when waking up from the interrupt, the board stops sleeping. Disable it when attaching e.g. a motion sensor (default: true) + void setSleepInterruptPin(int value); + #endif + // configure the interrupt pin and mode. Mode can be CHANGE, RISING, FALLING (default: MODE_NOT_DEFINED) + void setInterrupt(int pin, int mode, int pull = -1); + // register a built-in sensor + int registerSensor(int sensor_type, int pin = -1, int child_id = -1); + // register a custom sensor + int registerSensor(Sensor* sensor); + // return a sensor by its index + Sensor* get(int sensor_index); + #if POWER_MANAGER == 1 + // to save battery the sensor can be optionally connected to two pins which will act as vcc and ground and activated on demand + void setPowerPins(int ground_pin, int vcc_pin, long wait = 10); + void powerOn(); + void powerOff(); + #endif + + // hook into the main sketch functions + void before(); + void presentation(); + void loop(); + void receive(const MyMessage & msg); + private: + #if SLEEP_MANAGER == 1 + int _sleep_mode = IDLE; + int _sleep_time = 0; + int _sleep_unit = MINUTES; + int _sleep_interrupt_pin = -1; + #endif + #if BATTERY_MANAGER == 1 + float _battery_min = 2.6; + float _battery_max = 3.3; + int _battery_report_cycles = 10; + int _cycles = 0; + float _getVcc(); + #endif + + #if POWER_MANAGER == 1 + // to optionally controller power pins + PowerManager _powerManager; + #endif + MyMessage _msg; + int _interrupt_1_mode = MODE_NOT_DEFINED; + int _interrupt_2_mode = MODE_NOT_DEFINED; + int _interrupt_1_pull = -1; + int _interrupt_2_pull = -1; + int _reboot_pin = -1; + Sensor* _sensors[255] = {0}; + void _process(const char * message); + void _sleep(); + int _getAvailableChildId(); + int _getInterruptInitialValue(int mode); + bool _startup = true; +}; + +#endif diff --git a/NodeManagerTemplate/NodeManagerTemplate.ino b/NodeManagerTemplate/NodeManagerTemplate.ino new file mode 100644 index 00000000..62b3a0ca --- /dev/null +++ b/NodeManagerTemplate/NodeManagerTemplate.ino @@ -0,0 +1,74 @@ +/* +NodeManager is intended to take care on your behalf of all those common tasks a MySensors node has to accomplish, speeding up the development cycle of your projects. + +NodeManager includes the following main components: +- Sleep manager: allows managing automatically the complexity behind battery-powered sensors spending most of their time sleeping +- Power manager: allows powering on your sensors only while the node is awake +- Battery manager: provides common functionalities to read and report the battery level +- Remote configuration: allows configuring remotely the node without the need to have physical access to it +- Built-in personalities: for the most common sensors, provide embedded code so to allow their configuration with a single line + +Documentation available on: https://mynodemanager.sourceforge.io + */ + + +// load user settings +#include "config.h" +// load MySensors library +#include +// load NodeManager library +#include "NodeManager.h" + +// create a NodeManager instance +NodeManager nodeManager; + +// before +void before() { + // setup the serial port baud rate + Serial.begin(9600); + // connect pin 4 to RST to enable rebooting the board with a message + nodeManager.setRebootPin(4); + // set battery minimum voltage. This will be used to calculate the level percentage + //nodeManager.setBatteryMin(1.8); + // instruct the board to sleep for 10 minutes for each cycle + //nodeManager.setSleep(SLEEP,10,MINUTES); + // When pin 3 is connected to ground, the board will stop sleeping + //nodeManager.setSleepInterruptPin(3) + // all the sensors' vcc and ground are connected to pin 6 (vcc) and 7 (ground). NodeManager will enable the vcc pin every time just before loop() and wait for 100ms for the sensors to settle + //nodeManager.setPowerPins(6,7,100); + // register a thermistor sensor attached to pin A2 + //nodeManager.registerSensor(SENSOR_THERMISTOR,A2); + // register a LDR sensor attached to pin A1 and average 3 samples + //int sensor_ldr = nodeManager.registerSensor(SENSOR_LDR,A1); + //((SensorLDR*)nodeManager.get(sensor_ldr))->setSamples(3); + + nodeManager.before(); +} + +// presentation +void presentation() { + // Send the sketch version information to the gateway and Controller + sendSketchInfo("NodeManager", "1.0"); + // call NodeManager presentation routine + nodeManager.presentation(); + +} + +// setup +void setup() { +} + +// loop +void loop() { + // call NodeManager loop routine + nodeManager.loop(); + +} + +// receive +void receive(const MyMessage &message) { + // call NodeManager receive routine + nodeManager.receive(message); +} + + diff --git a/NodeManagerTemplate/README.md b/NodeManagerTemplate/README.md new file mode 100644 index 00000000..7949e33c --- /dev/null +++ b/NodeManagerTemplate/README.md @@ -0,0 +1,364 @@ +NodeManager + +# Introduction + +MySensors () is an open source hardware and software community focusing on do-it-yourself home automation and Internet of Things which allows creating original and affordable sensors. + +NodeManager is intended to take care on your behalf of all those common tasks a MySensors node has to accomplish, speeding up the development cycle of your projects. + +NodeManager includes the following main components: + +* Sleep manager: allows managing automatically the complexity behind battery-powered sensors spending most of their time sleeping +* Power manager: allows powering on your sensors only while the node is awake +* Battery manager: provides common functionalities to read and report the battery level +* Remote configuration: allows configuring remotely the node without the need to have physical access to it +* Built-in sensors: for the most common sensors, provide embedded code so to allow their configuration with a single line + +## Features + +* Manage all the aspects of a sleeping cycle by leveraging smart sleep +* Allow configuring the sleep mode and the sleep duration remotely +* Allow waking up a sleeping node remotely at the end of a sleeping cycle +* Allow powering on each connected sensor only while the node is awake to save battery +* Report battery level periodically and automatically +* Calculate battery level without requiring an additional pin and the resistors +* Report battery voltage through a built-in sensor +* Can report battery level on demand +* Allow rebooting the board remotely +* Provide out-of-the-box sensors personalities and automatically execute their main task at each cycle + +# Installation +* Download the package from https://mynodemanager.sourceforge.io +* Open the provided sketch template and save it under a different name +* Open `config.h` and customize both MySensors configuration and NodeManager global settings +* Register your sensors in the sketch file +* Upload the sketch to your arduino board + +Please note NodeManager cannot be used as an arduino library since requires access to your MySensors configuration directives, hence its files have to be placed into the same directory of your sketch. + +# Configuration +NodeManager configuration includes compile-time configuration directives (which can be set in config.h), runtime global and per-sensor configuration settings (which can be set in your sketch) and settings that can be customized remotely (via a special child id). + +## Setup MySensors +Since NodeManager has to communicate with the MySensors gateway on your behalf, it has to know how to do it. Place on top of the `config.h` file all the MySensors typical directives you are used to set on top of your sketch so both your sketch AND NodeManager will be able to share the same configuration. + +## Enable/Disable NodeManager's modules + +Those NodeManager's directives in the `config.h` file control which module/library/functionality will be made available to your sketch. Enable (e.g. set to 1) only what you need to ensure enough space is left to your custom code. + +~~~c +// if enabled, will load the sleep manager library. Sleep mode and sleep interval have to be configured to make the board sleeping/waiting +#define SLEEP_MANAGER 1 +// if enabled, enable the capability to power on sensors with the arduino's pins to save battery while sleeping +#define POWER_MANAGER 1 +// if enabled, will load the battery manager library to allow the battery level to be reported automatically or on demand +#define BATTERY_MANAGER 1 +// if enabled, allow modifying the configuration remotely by interacting with the configuration child id +#define REMOTE_CONFIGURATION 1 +// if enabled, persist the configuration settings on EEPROM +#define PERSIST 0 + +// if enabled, enable debug messages on serial port +#define DEBUG 1 + +// if enabled, send a SLEEPING and AWAKE service messages just before entering and just after leaving a sleep cycle +#define SERVICE_MESSAGES 1 +// if enabled, a battery sensor will be created at BATTERY_CHILD_ID and will report vcc voltage together with the battery level percentage +#define BATTERY_SENSOR 1 + + +// Enable this module to use one of the following sensors: SENSOR_ANALOG_INPUT, SENSOR_LDR, SENSOR_THERMISTOR +#define MODULE_ANALOG_INPUT 1 +// Enable this module to use one of the following sensors: SENSOR_DIGITAL_INPUT +#define MODULE_DIGITAL_INPUT 1 +// Enable this module to use one of the following sensors: SENSOR_DIGITAL_OUTPUT, SENSOR_RELAY, SENSOR_LATCHING_RELAY +#define MODULE_DIGITAL_OUTPUT 1 +// Enable this module to use one of the following sensors: SENSOR_SHT21 +#define MODULE_SHT21 0 +// Enable this module to use one of the following sensors: SENSOR_DHT11, SENSOR_DHT22 +#define MODULE_DHT 0 +// Enable this module to use one of the following sensors: SENSOR_SWITCH, SENSOR_DOOR, SENSOR_MOTION +#define MODULE_SWITCH 0 +// Enable this module to use one of the following sensors: SENSOR_DS18B20 +#define MODULE_DS18B20 0 +~~~ + +## Configure NodeManager + +Node Manager comes with a reasonable default configuration. If you want/need to change its settings, this can be done in your sketch, inside the `before()` function and just before registering your sensors. The following methods are exposed for your convenience: + +~~~c + // the pin to connect to the RST pin to reboot the board (default: 4) + void setRebootPin(int value); + #if BATTERY_MANAGER == 1 + // the expected vcc when the batter is fully discharged, used to calculate the percentage (default: 2.7) + void setBatteryMin(float value); + // the expected vcc when the batter is fully charged, used to calculate the percentage (default: 3.3) + void setBatteryMax(float value); + // how frequently (in hours) to report the battery level to the controller. When reset the battery is always reported (default: 1) + void setBatteryReportCycles(int value); + #endif + #if SLEEP_MANAGER == 1 + // define if the board has to sleep every time entering loop (default: IDLE). It can be IDLE (no sleep), SLEEP (sleep at every cycle), WAIT (wait at every cycle + void setSleepMode(int value); + // define for how long the board will sleep (default: 0) + void setSleepTime(int value); + // define the unit of SLEEP_TIME. It can be SECONDS, MINUTES, HOURS or DAYS (default: MINUTES) + void setSleep(int value1, int value2, int value3); + void setSleepUnit(int value); + // if enabled, when waking up from the interrupt, the board stops sleeping. Disable it when attaching e.g. a motion sensor (default: true) + void setSleepInterruptPin(int value); + #endif + // configure the interrupt pin and mode. Mode can be CHANGE, RISING, FALLING (default: MODE_NOT_DEFINED) + void setInterrupt(int pin, int mode, int pull = -1); + // register a built-in sensor + int registerSensor(int sensor_type, int pin = -1, int child_id = -1); + // register a custom sensor + int registerSensor(Sensor* sensor); + // return a sensor by its index + Sensor* get(int sensor_index); + #if POWER_MANAGER == 1 + // to save battery the sensor can be optionally connected to two pins which will act as vcc and ground and activated on demand + void setPowerPins(int ground_pin, int vcc_pin, long wait = 10); + void powerOn(); + void powerOff(); + #endif +~~~ + +For example + +~~~c +nodeManager.setBatteryMin(1.8); +~~~ + +## Register your sensors +In your sketch, inside the `before()` function and just before calling `nodeManager.before()`, you can register your sensors against NodeManager. The following built-in sensor types are available: + +Sensor type | Description + ------------- | ------------- +SENSOR_ANALOG_INPUT | Generic analog sensor, return a pin's analog value or its percentage +SENSOR_LDR | LDR sensor, return the light level of an attached light resistor in percentage +SENSOR_THERMISTOR | Thermistor sensor, return the temperature based on the attached thermistor +SENSOR_DIGITAL_INPUT | Generic digital sensor, return a pin's digital value +SENSOR_DIGITAL_OUTPUT | Generic digital output sensor, allows setting the digital output of a pin to the requested value +SENSOR_RELAY | Relay sensor, allows activating the relay +SENSOR_LATCHING_RELAY| Latching Relay sensor, allows activating the relay with a pulse +SENSOR_DHT11 | DHT11 sensor, return temperature/humidity based on the attached DHT sensor +SENSOR_DHT22 | DHT22 sensor, return temperature/humidity based on the attached DHT sensor +SENSOR_SHT21 | SHT21 sensor, return temperature/humidity based on the attached SHT21 sensor +SENSOR_SWITCH | Generic switch, wake up the board when a pin changes status +SENSOR_DOOR | Door sensor, wake up the board and report when an attached magnetic sensor has been opened/closed +SENSOR_MOTION | Motion sensor, wake up the board and report when an attached PIR has triggered +SENSOR_DS18B20 | DS18B20 sensor, return the temperature based on the attached sensor + +To register a sensor simply call the NodeManager instance with the sensory type and the pin the sensor is conncted to. For example: +~~~c +nodeManager.registerSensor(SENSOR_THERMISTOR,A2); +nodeManager.registerSensor(SENSOR_DOOR,3); +~~~ + +Once registered, your job is done. NodeManager will assign a child id automatically, present each sensor for you to the controller, query each sensor and report the value back to the gateway/controller at at the end of each sleep cycle . For actuators (e.g. relays) those can be triggered by sending a `REQ` message to their assigned child id. + +When called, registerSensor returns the child_id of the sensor so you will be able to retrieve it later if needed. If you want to set a child_id manually, this can be passed as third argument to the function. + +### Creating a custom sensor + +If you want to create a custom sensor and register it with NodeManager so it can take care of all the common tasks, you can create a class inheriting from `Sensor` and implement the following methods: +~~~c + // define what to do during before() to setup the sensor + void onBefore(); + // define what to do during loop() by executing the sensor's main task + void onLoop(); + // define what to do during receive() when the sensor receives a message + void onReceive(const MyMessage & message); +~~~ + +You can then instantiate your newly created class and register with NodeManager: +~~~c +nodeManager.registerSensor(new SensorCustom(child_id, pin)); +~~~ + +## Configuring the sensors +Each built-in sensor class comes with reasonable default settings. In case you want/need to customize any of those settings, after having registered the sensor, you can retrieve it back and call set functions common to all the sensors or specific for a given class. + +To do so, use `nodeManager.get(child_id)` which will return a pointer to the sensor. Remeber to cast it to the right class before calling their functions. For example: + +~~~c +((SensorLatchingRelay*)nodeManager.get(2))->setPulseWidth(50); +~~~ + + +### Sensor's general configuration + +The following methods are available for all the sensors: +~~~c + // where the sensor is attached to (default: not set) + void setPin(int value); + // child_id of this sensor (default: not set) + void setChildId(int value); + // presentation of this sensor (default: S_CUSTOM) + void setPresentation(int value); + // type of this sensor (default: V_CUSTOM) + void setType(int value); + // when queried, send the message multiple times (default: 1) + void setRetries(int value); + // For some sensors, the measurement can be queried multiple times and an average is returned (default: 1) + void setSamples(int value); + // If more then one sample has to be taken, set the interval in milliseconds between measurements (default: 0) + void setSamplesInterval(int value); + // if true will report the measure only if different then the previous one (default: false) + void setTackLastValue(bool value); + // if track last value is enabled, force to send an update after the configured number of cycles (default: -1) + void setForceUpdate(int value); + // the value type of this sensor (default: TYPE_INTEGER) + void setValueType(int value); +// for float values, set the float precision (default: 2) + void setFloatPrecision(int value); + #if POWER_MANAGER == 1 + // to save battery the sensor can be optionally connected to two pins which will act as vcc and ground and activated on demand + void setPowerPins(int ground_pin, int vcc_pin, long wait = 0); + void powerOn(); + void powerOff(); + #endif +~~~ + +### Sensor's specific configuration + +Each sensor class can expose additional methods. + +#### SensorAnalogInput / SensorLDR +~~~c + // the analog reference to use (default: not set, can be either INTERNAL or DEFAULT) + void setReference(int value); + // reverse the value or the percentage (e.g. 70% -> 30%) (default: false) + void setReverse(bool value); + // when true returns the value as a percentage (default: true) + void setOutputPercentage(bool value); + // minimum value for calculating the percentage (default: 0) + void setRangeMin(int value); + // maximum value for calculating the percentage (default: 1024) + void setRangeMax(int value); +~~~ + +#### SensorThermistor +~~~c + // resistance at 25 degrees C (default: 10000) + void setNominalResistor(int value); + // temperature for nominal resistance (default: 25) + void setNominalTemperature(int value); + // The beta coefficient of the thermistor (default: 3950) + void setBCoefficient(int value); + // the value of the resistor in series with the thermistor (default: 10000) + void setSeriesResistor(int value); + // set a temperature offset + void setOffset(float value); +~~~ + +#### SensorDigitalOutput / SensorRelay / SensorLatchingRelay +~~~c + // set how to initialize the output (default: LOW) + void setInitialValue(int value); + // if greater than 0, send a pulse of the given duration in ms and then restore the output back to the original value (default: 0) + void setPulseWidth(int value); +~~~ + +#### SensorSwitch / SensorDoor / SensorMotion +~~~c + // set the interrupt mode. Can be CHANGE, RISING, FALLING (default: CHANGE) + void setMode(int value); + // milliseconds to wait before reading the input (default: 0) + void setDebounce(int value); + // time to wait in milliseconds after a change is detected to allow the signal to be restored to its normal value (default: 0) + void setTriggerTime(int value); +~~~ + +## Upload your sketch + +Upload your sketch to your arduino board as you are used to. + +## Verify if everything works fine + +Check your gateway's logs to ensure the node is working as expected. You should see the node presenting itself, reporting battery level, presenting all the registered sensors and the configuration child id service. +When `DEBUG` is enabled, detailed information is available through the serial port. Remember to disable debug once the tests have been completed. + +## Communicate with each sensor + +You can interact with each registered sensor asking to execute their main tasks by sending to the child id a `REQ` command. For example to request the temperature to node_id 254 and child_id 1: + +`254;1;2;0;0;` + +To activate a relay connected to the same node, child_id 100: + +`254;100;2;0;2;1` + +No need to implement anything on your side since for built-in sensor types this is handled automatically. +Once the node will be sleeping, it will report automatically each measure at the end of every sleep cycle. + +## Communicate with the node + +NodeManager exposes a configuration service by default on child_id 200 so you can interact with it by sending `V_CUSTOM` type of messages and commands within the payload. For each `REQ` message, the node will respond with a `SET` message. +The following custom commands are available: + +NodeManager command | Description + ------------- | ------------- +BATTERY | Report the battery level back to the gateway/controller +HELLO | Hello request +REBOOT | Reboot the board +CLEAR | Wipe from the EEPROM NodeManager's settings +VERSION | Respond with NodeManager's version +IDxxx | Change the node id to the provided one. E.g. ID025: change the node id to 25. Requires a reboot to take effect +INTVLnnnX | Set the wait/sleep interval to nnn where X is S=Seconds, M=mins, H=Hours, D=Days. E.g. INTVL010M would be 10 minutes +MODEx | Change the way the board behaves (e.g. MODE1). 0: stay awake, 1: go to sleep for the configured interval, 2: wait for the configured interval +AWAKE | When received after a sleeping cycle or during wait, abort the cycle and stay awake + +For example, to request the battery level to node id 254: + +`254;200;2;0;48;BATTERY` + +To set the sleeping cycle to 1 hour: + +`254;200;2;0;48;INTVL001H` + +To ask the node to start sleeping (and waking up based on the previously configured interval): + +`254;200;2;0;48;MODE1` + +To wake up a node previously configured with `MODE1`, send the following just after reporting `AWAKE`: + +`254;200;2;0;48;WAKEUP` + +In addition, NodeManager will report with custom messages every time the board is going to sleep (`SLEEPING`) or it is awake (`AWAKE`). + +If `PERSIST` is enabled, the settings provided with `INTVLnnnX` and `MODEx` are saved to the EEPROM to be persistent even after rebooting the board. + +# How it works + +A NodeManager object must be created and called from within your sketch during `before()`, `presentation()`, `loop()` and `receive()` to work properly. NodeManager will do the following during each phase: + +## NodeManager::before() +* Configure the reboot pin so to allow rebooting the board +* Setup the interrupt pins to wake up the board based on the configured interrupts (e.g. stop sleeping when the pin is connected to ground or wake up and notify when a motion sensor has trigger) +* If persistance is enabled, restore from the EEPROM the latest sleeping settings +* Call `before()` of each registered sensor + +### Sensor::before() +* Call sensor-specific implementation of before by invoking `onBefore()` to initialize the sensor + +## NodeManager::loop() +* If all the sensors are powered by an arduino pin, this is set to HIGH +* Call `loop()` of each registered sensor +* If all the sensors are powered by an arduino pin, this is set to LOW + +### Sensor::loop() +* If the sensor is powered by an arduino pin, this is set to HIGH +* For each registered sensor, the sensor-specific `onLoop()` is called. If multiple samples are requested, this is run multiple times. +* In case multiple samples have been collected, the average is calculated +* A message is sent to the gateway with the calculated value. Depending on the configuration, this is not sent if it is the same as the previous value or sent anyway after a given number of cycles. These functionalies are not sensor-specific and common to all the sensors inheriting from the `Sensor` class. +* If the sensor is powered by an arduino pin, this is set to LOW + +## NodeManager::receive() +* Receive a message from the radio network +* If the destination child id is the configuration node, it will handle the incoming message, otherwise will dispatch the message to the recipient sensor + +### Sensor::receive() +* Invoke `Sensor::loop()` which will execute the sensor main taks and eventually call `Sensor::onReceive()` \ No newline at end of file diff --git a/NodeManagerTemplate/config.h b/NodeManagerTemplate/config.h new file mode 100644 index 00000000..f22a56cb --- /dev/null +++ b/NodeManagerTemplate/config.h @@ -0,0 +1,48 @@ +#ifndef config_h +#define config_h + +/********************************** + * MySensors configuration + */ +//#define MY_DEBUG +#define MY_RADIO_NRF24 + + +/*********************************** + * NodeManager configuration + */ +// if enabled, will load the sleep manager library. Sleep mode and sleep interval have to be configured to make the board sleeping/waiting +#define SLEEP_MANAGER 1 +// if enabled, enable the capability to power on sensors with the arduino's pins to save battery while sleeping +#define POWER_MANAGER 1 +// if enabled, will load the battery manager library to allow the battery level to be reported automatically or on demand +#define BATTERY_MANAGER 1 +// if enabled, allow modifying the configuration remotely by interacting with the configuration child id +#define REMOTE_CONFIGURATION 1 +// if enabled, persist the configuration settings on EEPROM +#define PERSIST 0 + +// if enabled, enable debug messages on serial port +#define DEBUG 1 + +// if enabled, send a SLEEPING and AWAKE service messages just before entering and just after leaving a sleep cycle +#define SERVICE_MESSAGES 1 +// if enabled, a battery sensor will be created at BATTERY_CHILD_ID and will report vcc voltage together with the battery level percentage +#define BATTERY_SENSOR 1 + +// Enable this module to use one of the following sensors: SENSOR_ANALOG_INPUT, SENSOR_LDR, SENSOR_THERMISTOR +#define MODULE_ANALOG_INPUT 1 +// Enable this module to use one of the following sensors: SENSOR_DIGITAL_INPUT +#define MODULE_DIGITAL_INPUT 1 +// Enable this module to use one of the following sensors: SENSOR_DIGITAL_OUTPUT, SENSOR_RELAY, SENSOR_LATCHING_RELAY +#define MODULE_DIGITAL_OUTPUT 1 +// Enable this module to use one of the following sensors: SENSOR_SHT21 +#define MODULE_SHT21 0 +// Enable this module to use one of the following sensors: SENSOR_DHT11, SENSOR_DHT22 +#define MODULE_DHT 0 +// Enable this module to use one of the following sensors: SENSOR_SWITCH, SENSOR_DOOR, SENSOR_MOTION +#define MODULE_SWITCH 0 +// Enable this module to use one of the following sensors: SENSOR_DS18B20 +#define MODULE_DS18B20 0 + +#endif