diff --git a/libraries/NodeManager/NodeManager.cpp b/libraries/NodeManager/NodeManager.cpp new file mode 100644 index 0000000..0624c7a --- /dev/null +++ b/libraries/NodeManager/NodeManager.cpp @@ -0,0 +1,2627 @@ +/* + * NodeManager + */ + +#include "NodeManager.h" + +/*************************************** + Global functions +*/ + +// return vcc in V +float getVcc() { + #ifndef MY_GATEWAY_ESP8266 + // 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 + wait(70); + // Do conversion + ADCSRA |= _BV(ADSC); + while (bit_is_set(ADCSRA, ADSC)) {}; + // return Vcc in mV + return (float)((1125300UL) / ADC) / 1000; + #else + return (float)0; + #endif +} + + +/*************************************** + PowerManager +*/ + +// set the vcc and ground pin the sensor is connected to +void PowerManager::setPowerPins(int ground_pin, int vcc_pin, int wait_time) { + #if DEBUG == 1 + Serial.print(F("PWR G=")); + Serial.print(ground_pin); + Serial.print(F(" V=")); + Serial.println(vcc_pin); + #endif + // configure the vcc pin as output and initialize to high (power on) + _vcc_pin = vcc_pin; + pinMode(_vcc_pin, OUTPUT); + digitalWrite(_vcc_pin, HIGH); + // configure the ground pin as output and initialize to low + _ground_pin = ground_pin; + pinMode(_ground_pin, OUTPUT); + digitalWrite(_ground_pin, LOW); + _wait = wait_time; +} + +// return true if power pins have been configured +bool PowerManager::isConfigured() { + if (_vcc_pin != -1 && _ground_pin != -1) return true; + return false; +} + +// turn on the sensor by activating its power pins +void PowerManager::powerOn() { + if (! isConfigured()) return; + #if DEBUG == 1 + Serial.print(F("ON P=")); + 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) wait(_wait); +} + +// turn off the sensor +void PowerManager::powerOff() { + if (! isConfigured()) return; + #if DEBUG == 1 + Serial.print(F("OFF P=")); + 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::setDescription(char* value) { + _description = value; +} +void Sensor::setAck(bool value) { + _ack = value; +} +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; +} +int Sensor::getValueType() { + return _value_type; +} +void Sensor::setFloatPrecision(int value) { + _float_precision = value; +} +#if POWER_MANAGER == 1 + void Sensor::setPowerPins(int ground_pin, int vcc_pin, int wait_time) { + _powerManager.setPowerPins(ground_pin, vcc_pin, wait_time); + } + void Sensor::setAutoPowerPins(bool value) { + _auto_power_pins = value; + } + void Sensor::powerOn() { + _powerManager.powerOn(); + } + void Sensor::powerOff() { + _powerManager.powerOff(); + } +#endif +void Sensor::setSleepBetweenSend(int value) { + _sleep_between_send = value; +} +void Sensor::setInterruptPin(int value) { + _interrupt_pin = value; +} +int Sensor::getInterruptPin() { + return _interrupt_pin; +} +int Sensor::getValueInt() { + return _last_value_int; +} +float Sensor::getValueFloat() { + return _last_value_float; +} +char* Sensor::getValueString() { + return _last_value_string; +} + +// present the sensor to the gateway and controller +void Sensor::presentation() { + #if DEBUG == 1 + Serial.print(F("PRES I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(_presentation); + #endif + present(_child_id, _presentation,_description,_ack); +} + +// call the sensor-specific implementation of before +void Sensor::before() { + if (_pin == -1) return; + onBefore(); +} + +// call the sensor-specific implementation of setup +void Sensor::setup() { + if (_pin == -1) return; + onSetup(); +} + +// 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 + if (_auto_power_pins) 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 + if (_force_update > 0) _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) wait(_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 + if (_auto_power_pins) 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 passing along the message + 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 configured, sleep beetween each send + if (_sleep_between_send > 0) sleep(_sleep_between_send); + #if DEBUG == 1 + Serial.print(F("SEND D=")); + Serial.print(message.destination); + Serial.print(F(" I=")); + Serial.print(message.sensor); + Serial.print(F(" C=")); + Serial.print(message.getCommand()); + Serial.print(F(" T=")); + Serial.print(message.type); + Serial.print(F(" S=")); + Serial.print(message.getString()); + Serial.print(F(" I=")); + Serial.print(message.getInt()); + Serial.print(F(" F=")); + Serial.println(message.getFloat()); + #endif + send(message,_ack); + } +} + +/* + 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 to do during before +void SensorAnalogInput::onBefore() { + // prepare the pin for input + pinMode(_pin, INPUT); +} + +// what to do during setup +void SensorAnalogInput::onSetup() { +} + +// what to do 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(F("A-IN I=")); + Serial.print(_child_id); + Serial.print(F(" V=")); + Serial.print(adc); + Serial.print(F(" %=")); + Serial.println(percentage); + #endif + // store the result + _value_int = _output_percentage ? percentage : adc; +} + +// what to do during loop +void SensorAnalogInput::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} + +// read the analog input +int SensorAnalogInput::_getAnalogRead() { + #ifndef MY_GATEWAY_ESP8266 + // set the reference + if (_reference != -1) { + analogReference(_reference); + wait(100); + } + #endif + // 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; + // restore the original value + if (_reverse) value = 1024 - value; + // scale the percentage based on the range provided + float percentage = ((value - _range_min) / (_range_max - _range_min)) * 100; + if (_reverse) percentage = 100 - percentage; + 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(long value) { + _nominal_resistor = value; +} +void SensorThermistor::setNominalTemperature(int value) { + _nominal_temperature = value; +} +void SensorThermistor::setBCoefficient(int value) { + _b_coefficient = value; +} +void SensorThermistor::setSeriesResistor(long value) { + _series_resistor = value; +} +void SensorThermistor::setOffset(float value) { + _offset = value; +} + +// what to do during before +void SensorThermistor::onBefore() { + // set the pin as input + pinMode(_pin, INPUT); +} + +// what to do during setup +void SensorThermistor::onSetup() { +} + +// what to do 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(F("THER I=")); + Serial.print(_child_id); + Serial.print(F(" V=")); + Serial.print(adc); + Serial.print(F(" T=")); + Serial.print(temperature); + Serial.print(F(" M=")); + Serial.println(getControllerConfig().isMetric); + #endif + // store the value + _value_float = temperature; +} + +// what to do as the main task when receiving a message +void SensorThermistor::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} + + +/* + SensorML8511 +*/ + +// contructor +SensorML8511::SensorML8511(int child_id, int pin): Sensor(child_id, pin) { + // set presentation, type and value type + setPresentation(S_UV); + setType(V_UV); + setValueType(TYPE_FLOAT); +} + +// what to do during before +void SensorML8511::onBefore() { + // set the pin as input + pinMode(_pin, INPUT); +} + +// what to do during setup +void SensorML8511::onSetup() { +} + +// what to do during loop +void SensorML8511::onLoop() { + // read the voltage + int uvLevel = analogRead(_pin); + int refLevel = getVcc()*1024/3.3; + //Use the 3.3V power pin as a reference to get a very accurate output value from sensor + float outputVoltage = 3.3 / refLevel * uvLevel; + //Convert the voltage to a UV intensity level + float uvIntensity = _mapfloat(outputVoltage, 0.99, 2.8, 0.0, 15.0); + #if DEBUG == 1 + Serial.print(F("UV I=")); + Serial.print(_child_id); + Serial.print(F(" V=")); + Serial.print(outputVoltage); + Serial.print(F(" I=")); + Serial.println(uvIntensity); + #endif + // store the value + _value_float = uvIntensity; +} + +// what to do as the main task when receiving a message +void SensorML8511::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} + +// The Arduino Map function but for floats +float SensorML8511::_mapfloat(float x, float in_min, float in_max, float out_min, float out_max) { + return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; +} + +/* + SensorACS712 +*/ + +// contructor +SensorACS712::SensorACS712(int child_id, int pin): Sensor(child_id, pin) { + // set presentation, type and value type + setPresentation(S_MULTIMETER); + setType(V_CURRENT); + setValueType(TYPE_FLOAT); +} + +// setter/getter +void SensorACS712::setmVPerAmp(int value) { + _mv_per_amp = value; +} +void SensorACS712::setOffset(int value) { + _ACS_offset = value; +} + +// what to do during before +void SensorACS712::onBefore() { + // set the pin as input + pinMode(_pin, INPUT); +} + +// what to do during setup +void SensorACS712::onSetup() { +} + +// what to do during loop +void SensorACS712::onLoop() { + int value = analogRead(_pin); + // convert the analog read in mV + double voltage = (value / 1024.0) * 5000; + // convert voltage in amps + _value_float = ((voltage - _ACS_offset) / _mv_per_amp); + #if DEBUG == 1 + Serial.print(F("ACS I=")); + Serial.print(_child_id); + Serial.print(F(" A=")); + Serial.println(_value_float); + #endif +} + +// what to do as the main task when receiving a message +void SensorACS712::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} + +/* + SensorRainGauge +*/ + +// contructor +SensorRainGauge::SensorRainGauge(int child_id, int pin): Sensor(child_id, pin) { + // set presentation, type and value type + setPresentation(S_RAIN); + setType(V_RAIN); + setValueType(TYPE_FLOAT); + +} + +// initialize static variables +long SensorRainGauge::_last_tip = 0; +long SensorRainGauge::_count = 0; + +// setter/getter +void SensorRainGauge::setReportInterval(int value) { + _report_interval = value; +} +void SensorRainGauge::setSingleTip(float value) { + _single_tip = value; +} + +// what to do during before +void SensorRainGauge::onBefore() { + // set the pin as input and enabled pull up + pinMode(_pin, INPUT_PULLUP); + // attach to the pin's interrupt and execute the routine on falling + attachInterrupt(digitalPinToInterrupt(_pin), _onTipped, FALLING); +} + +// what to do during setup +void SensorRainGauge::onSetup() { +} + +// what to do when when receiving an interrupt +void SensorRainGauge::_onTipped() { + long now = millis(); + // on tipping, two consecutive interrupts are received, ignore the second one + if ( (now - _last_tip > 100) || (now < _last_tip) ){ + // increase the counter + _count++; + #if DEBUG == 1 + Serial.println(F("RAIN+")); + #endif + } + _last_tip = now; +} + +// what to do during loop +void SensorRainGauge::onLoop() { + // avoid reporting the same value multiple times + _value_float = -1; + long now = millis(); + // time elapsed since the last report + long elapsed = now - _last_report; + // minimum time interval between reports + long min_interval = ((long)_report_interval*1000)*60; + // time to report or millis() reset + if ( (elapsed > min_interval) || (now < _last_report)) { + // report the total amount of rain for the last period + _value_float = _count*_single_tip; + #if DEBUG == 1 + Serial.print(F("RAIN I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(_value_float); + #endif + // reset the counters + _count = 0; + _last_report = now; + } +} + +// what to do as the main task when receiving a message +void SensorRainGauge::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) { + // report the total amount of rain for the last period + _value_float = _count*_single_tip; + } +} + + +/* + * SensorMQ + */ +SensorMQ::SensorMQ(int child_id, int pin): Sensor(child_id,pin) { + setPresentation(S_AIR_QUALITY); + setType(V_LEVEL); +} + +//setter/getter +void SensorMQ::setRlValue(float value) { + _rl_value = value; +} +void SensorMQ::setRoValue(float value) { + _ro = value; +} +void SensorMQ::setCleanAirFactor(float value) { + _ro_clean_air_factor = value; +} +void SensorMQ::setCalibrationSampleTimes(int value) { + _calibration_sample_times = value; +} +void SensorMQ::setCalibrationSampleInterval(int value){ + _calibration_sample_interval = value; +} +void SensorMQ::setReadSampleTimes(int value) { + _read_sample_times = value; +} +void SensorMQ::setReadSampleInterval(int value) { + _read_sample_interval = value; +} +void SensorMQ::setLPGCurve(float *value) { + _LPGCurve[0] = value[0]; + _LPGCurve[2] = value[1]; + _LPGCurve[2] = value[2]; +} +void SensorMQ::setCOCurve(float *value) { + _COCurve[0] = value[0]; + _COCurve[2] = value[1]; + _COCurve[2] = value[2]; +} +void SensorMQ::setSmokeCurve(float *value) { + _SmokeCurve[0] = value[0]; + _SmokeCurve[2] = value[1]; + _SmokeCurve[2] = value[2]; +} + +// what to do during before +void SensorMQ::onBefore() { + // prepare the pin for input + pinMode(_pin, INPUT); +} + +// what to do during setup +void SensorMQ::onSetup() { + _ro = _MQCalibration(); +} + +// what to do during loop +void SensorMQ::onLoop() { + if (_pin == -1) return; + // calculate rs/ro + float mq = _MQRead()/_ro; + // calculate the ppm + float lpg = _MQGetGasPercentage(mq,_gas_lpg); + float co = _MQGetGasPercentage(mq,_gas_co); + float smoke = _MQGetGasPercentage(mq,_gas_smoke); + // assign to the value the requested gas + uint16_t value; + if (_target_gas == _gas_lpg) value = lpg; + if (_target_gas == _gas_co) value = co; + if (_target_gas == _gas_smoke) value = smoke; + #if DEBUG == 1 + Serial.print(F("MQ I=")); + Serial.print(_child_id); + Serial.print(F(" V=")); + Serial.print(value); + Serial.print(F(" LPG=")); + Serial.print(lpg); + Serial.print(F(" CO=")); + Serial.print(co); + Serial.print(F(" SMOKE=")); + Serial.println(smoke); + #endif + // store the value + _value_int = (int16_t)ceil(value); +} + +// what to do as the main task when receiving a message +void SensorMQ::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} + +// returns the calculated sensor resistance +float SensorMQ::_MQResistanceCalculation(int raw_adc) { + return ( ((float)_rl_value*(1023-raw_adc)/raw_adc)); +} + +// This function assumes that the sensor is in clean air +float SensorMQ::_MQCalibration() { + int i; + float val=0; + //take multiple samples + for (i=0; i< _calibration_sample_times; i++) { + val += _MQResistanceCalculation(analogRead(_pin)); + wait(_calibration_sample_interval); + } + //calculate the average value + val = val/_calibration_sample_times; + //divided by RO_CLEAN_AIR_FACTOR yields the Ro + val = val/_ro_clean_air_factor; + //according to the chart in the datasheet + return val; +} + +// This function use MQResistanceCalculation to caculate the sensor resistenc (Rs). +float SensorMQ::_MQRead() { + int i; + float rs=0; + for (i=0; i<_read_sample_times; i++) { + rs += _MQResistanceCalculation(analogRead(_pin)); + wait(_read_sample_interval); + } + rs = rs/_read_sample_times; + return rs; +} + +// This function passes different curves to the MQGetPercentage function which calculates the ppm (parts per million) of the target gas. +int SensorMQ::_MQGetGasPercentage(float rs_ro_ratio, int gas_id) { + if ( gas_id == _gas_lpg ) { + return _MQGetPercentage(rs_ro_ratio,_LPGCurve); + } else if ( gas_id == _gas_co) { + return _MQGetPercentage(rs_ro_ratio,_COCurve); + } else if ( gas_id == _gas_smoke) { + return _MQGetPercentage(rs_ro_ratio,_SmokeCurve); + } + return 0; +} + +// returns ppm of the target gas +int SensorMQ::_MQGetPercentage(float rs_ro_ratio, float *pcurve) { + return (pow(10,( ((log10(rs_ro_ratio)-pcurve[1])/pcurve[2]) + pcurve[0]))); +} + + +/* + SensorDigitalInput +*/ + +// contructor +SensorDigitalInput::SensorDigitalInput(int child_id, int pin): Sensor(child_id, pin) { +} + +// what to do during before +void SensorDigitalInput::onBefore() { + // set the pin for input + pinMode(_pin, INPUT); +} + +// what to do during setup +void SensorDigitalInput::onSetup() { +} + +// what to do during loop +void SensorDigitalInput::onLoop() { + // read the value + int value = digitalRead(_pin); + #if DEBUG == 1 + Serial.print(F("D-IN I=")); + Serial.print(_child_id); + Serial.print(F(" P=")); + Serial.print(_pin); + Serial.print(F(" V=")); + Serial.println(value); + #endif + // store the value + _value_int = value; +} + +// what to do as the main task when receiving a message +void SensorDigitalInput::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} + + +/* + SensorDigitalOutput +*/ + +// contructor +SensorDigitalOutput::SensorDigitalOutput(int child_id, int pin): Sensor(child_id, pin) { +} + +// what to do during before +void SensorDigitalOutput::onBefore() { + // set the pin as output and initialize it accordingly + pinMode(_pin, OUTPUT); + _state = _initial_value == LOW ? LOW : HIGH; + digitalWrite(_pin, _state); + // the initial value is now the current value + _value_int = _initial_value; +} + +// what to do during setup +void SensorDigitalOutput::onSetup() { +} + +// setter/getter +void SensorDigitalOutput::setInitialValue(int value) { + _initial_value = value; +} +void SensorDigitalOutput::setPulseWidth(int value) { + _pulse_width = value; +} +void SensorDigitalOutput::setOnValue(int value) { + _on_value = value; +} +void SensorDigitalOutput::setLegacyMode(bool value) { + _legacy_mode = value; +} + +// main task +void SensorDigitalOutput::onLoop() { + // do nothing on loop +} + +// what to do as the main task when receiving a message +void SensorDigitalOutput::onReceive(const MyMessage & message) { + // by default handle a SET message but when legacy mode is set when a REQ message is expected instead + if ( (message.getCommand() == C_SET && ! _legacy_mode) || (message.getCommand() == C_REQ && _legacy_mode)) { + // retrieve from the message the value to set + int value = message.getInt(); + if (value != 0 && value != 1) return; + #if DEBUG == 1 + Serial.print(F("DOUT I=")); + Serial.print(_child_id); + Serial.print(F(" P=")); + Serial.print(_pin); + Serial.print(F(" V=")); + Serial.print(value); + Serial.print(F(" P=")); + Serial.println(_pulse_width); + #endif + // reverse the value if needed + int value_to_write = value; + if (_on_value == LOW) { + if (value == HIGH) value_to_write = LOW; + if (value == LOW) value_to_write = HIGH; + } + // set the value + digitalWrite(_pin, value_to_write); + if (_pulse_width > 0) { + // if this is a pulse output, restore the value to the original value after the pulse + wait(_pulse_width); + digitalWrite(_pin, value_to_write == 0 ? HIGH: LOW); + } + // store the current value so it will be sent to the controller + _state = value; + _value_int = value; + } + if (message.getCommand() == C_REQ && ! _legacy_mode) { + // return the current status + _value_int = _state; + } +} + +/* + SensorRelay +*/ + +// contructor +SensorRelay::SensorRelay(int child_id, int pin): SensorDigitalOutput(child_id, pin) { + // set presentation and type + setPresentation(S_BINARY); + setType(V_STATUS); +} + +// define what to do during loop +void SensorRelay::onLoop() { + // set the value to -1 so to avoid reporting to the gateway during loop + _value_int = -1; +} + +/* + 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; + _sensor_type = sensor_type; + _dht_type = dht_type; + if (_sensor_type == SensorDHT::TEMPERATURE) { + // temperature sensor + setPresentation(S_TEMP); + setType(V_TEMP); + setValueType(TYPE_FLOAT); + } + else if (_sensor_type == SensorDHT::HUMIDITY) { + // humidity sensor + setPresentation(S_HUM); + setType(V_HUM); + setValueType(TYPE_FLOAT); + } +} + +// what to do during before +void SensorDHT::onBefore() { + // initialize the dht library + _dht->begin(); +} + +// what to do during setup +void SensorDHT::onSetup() { +} + +// what to do during loop +void SensorDHT::onLoop() { + // temperature sensor + if (_sensor_type == SensorDHT::TEMPERATURE) { + // read the temperature + float temperature = _dht->readTemperature(); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(F("DHT I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(temperature); + #endif + // store the value + if (! isnan(temperature)) _value_float = temperature; + } + // humidity sensor + else if (_sensor_type == SensorDHT::HUMIDITY) { + // read humidity + float humidity = _dht->readHumidity(); + if (isnan(humidity)) return; + #if DEBUG == 1 + Serial.print(F("DHT I=")); + Serial.print(_child_id); + Serial.print(F(" H=")); + Serial.println(humidity); + #endif + // store the value + if (! isnan(humidity)) _value_float = humidity; + } +} + +// what to do as the main task when receiving a message +void SensorDHT::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} +#endif + +/* + SensorSHT21 +*/ +#if MODULE_SHT21 == 1 +// contructor +SensorSHT21::SensorSHT21(int child_id, int sensor_type): Sensor(child_id,A2) { + // store the sensor type (0: temperature, 1: humidity) + _sensor_type = sensor_type; + if (_sensor_type == SensorSHT21::TEMPERATURE) { + // temperature sensor + setPresentation(S_TEMP); + setType(V_TEMP); + setValueType(TYPE_FLOAT); + } + else if (_sensor_type == SensorSHT21::HUMIDITY) { + // humidity sensor + setPresentation(S_HUM); + setType(V_HUM); + setValueType(TYPE_FLOAT); + } +} + +// what to do during before +void SensorSHT21::onBefore() { + // initialize the library + Wire.begin(); +} + +// what to do during setup +void SensorSHT21::onSetup() { +} + +// what to do during loop +void SensorSHT21::onLoop() { + // temperature sensor + if (_sensor_type == SensorSHT21::TEMPERATURE) { + // read the temperature + float temperature = SHT2x.GetTemperature(); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(F("SHT I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(temperature); + #endif + // store the value + if (! isnan(temperature)) _value_float = temperature; + } + // Humidity Sensor + else if (_sensor_type == SensorSHT21::HUMIDITY) { + // read humidity + float humidity = SHT2x.GetHumidity(); + if (isnan(humidity)) return; + #if DEBUG == 1 + Serial.print(F("SHT I=")); + Serial.print(_child_id); + Serial.print(F(" H=")); + Serial.println(humidity); + #endif + // store the value + if (! isnan(humidity)) _value_float = humidity; + } +} + +// what to do as the main task when receiving a message +void SensorSHT21::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} +#endif + +/* + * SensorHTU21D + */ + #if MODULE_SHT21 == 1 +// constructor +SensorHTU21D::SensorHTU21D(int child_id, int pin): SensorSHT21(child_id, pin) { +} +#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; +} +void SensorSwitch::setDebounce(int value) { + _debounce = value; +} +void SensorSwitch::setTriggerTime(int value) { + _trigger_time = value; +} +void SensorSwitch::setInitial(int value) { + _initial = value; +} +int SensorSwitch::getInitial() { + return _initial; +} + +// what to do during before +void SensorSwitch::onBefore() { + // initialize the value + if (_mode == RISING) _value_int = LOW; + else if (_mode == FALLING) _value_int = HIGH; +} + +// what to do during setup +void SensorSwitch::onSetup() { +} + +// what to do during loop +void SensorSwitch::onLoop() { + // wait to ensure the the input is not floating + if (_debounce > 0) wait(_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(F("SWITCH I=")); + Serial.print(_child_id); + Serial.print(F(" P=")); + Serial.print(_pin); + Serial.print(F(" V=")); + Serial.println(value); + #endif + _value_int = value; + // allow the signal to be restored to its normal value + if (_trigger_time > 0) wait(_trigger_time); + } else { + // invalid + _value_int = -1; + } +} +// what to do as the main task when receiving a message +void SensorSwitch::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) 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); + // set initial value to LOW + setInitial(LOW); +} + +/* + 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; + // retrieve and store the address from the index + _sensors->getAddress(_device_address, index); +} + +// what to do during before +void SensorDs18b20::onBefore() { +} + +// what to do during setup +void SensorDs18b20::onSetup() { +} + +// what to do during loop +void SensorDs18b20::onLoop() { + // do not wait for conversion, will sleep manually during it + if (_sleep_during_conversion) _sensors->setWaitForConversion(false); + // request the temperature + _sensors->requestTemperatures(); + if (_sleep_during_conversion) { + // calculate conversion time and sleep + int16_t conversion_time = _sensors->millisToWaitForConversion(_sensors->getResolution()); + sleep(conversion_time); + } + // read the temperature + float temperature = _sensors->getTempCByIndex(_index); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(F("DS18B20 I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(temperature); + #endif + // store the value + _value_float = temperature; +} + +// what to do as the main task when receiving a message +void SensorDs18b20::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} + +// function to print a device address +DeviceAddress* SensorDs18b20::getDeviceAddress() { + return &_device_address; +} + +// returns the sensor's resolution in bits +int SensorDs18b20::getResolution() { + return _sensors->getResolution(_device_address); +} + +// set the sensor's resolution in bits +void SensorDs18b20::setResolution(int value) { + _sensors->setResolution(_device_address, value); +} + +// sleep while DS18B20 calculates temperature +void SensorDs18b20::setSleepDuringConversion(bool value) { + _sleep_during_conversion = value; +} + +#endif + +/* + SensorBH1750 +*/ +#if MODULE_BH1750 == 1 +// contructor +SensorBH1750::SensorBH1750(int child_id): Sensor(child_id,A4) { + setPresentation(S_LIGHT_LEVEL); + setType(V_LEVEL); + _lightSensor = new BH1750(); +} + +// what to do during before +void SensorBH1750::onBefore() { + _lightSensor->begin(); +} + +// what to do during setup +void SensorBH1750::onSetup() { +} + +// what to do during loop +void SensorBH1750::onLoop() { + // request the light level + _value_int = _lightSensor->readLightLevel(); + #if DEBUG == 1 + Serial.print(F("BH1 I=")); + Serial.print(_child_id); + Serial.print(F(" L=")); + Serial.println(_value_int); + #endif +} + +// what to do as the main task when receiving a message +void SensorBH1750::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} +#endif + +/* + SensorMLX90614 +*/ +#if MODULE_MLX90614 == 1 +// contructor +SensorMLX90614::SensorMLX90614(int child_id, Adafruit_MLX90614* mlx, int sensor_type): Sensor(child_id,A4) { + _sensor_type = sensor_type; + _mlx = mlx; + // set presentation and type + setPresentation(S_TEMP); + setType(V_TEMP); + setValueType(TYPE_FLOAT); +} + +// what to do during before +void SensorMLX90614::onBefore() { + // initialize the library + _mlx->begin(); +} + +// what to do during setup +void SensorMLX90614::onSetup() { +} + +// what to do during loop +void SensorMLX90614::onLoop() { + float temperature = _sensor_type == SensorMLX90614::TEMPERATURE_OBJECT ? _mlx->readAmbientTempC() : _mlx->readObjectTempC(); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(F("MLX I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(temperature); + #endif + if (! isnan(temperature)) _value_float = temperature; +} + +// what to do as the main task when receiving a message +void SensorMLX90614::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} +#endif + + +/* + SensorBosch +*/ +#if MODULE_BME280 == 1 || MODULE_BMP085 == 1 +// contructor +SensorBosch::SensorBosch(int child_id, int sensor_type): Sensor(child_id,A4) { + _sensor_type = sensor_type; + if (_sensor_type == SensorBosch::TEMPERATURE) { + // temperature sensor + setPresentation(S_TEMP); + setType(V_TEMP); + setValueType(TYPE_FLOAT); + } + else if (_sensor_type == SensorBosch::HUMIDITY) { + // humidity sensor + setPresentation(S_HUM); + setType(V_HUM); + setValueType(TYPE_FLOAT); + } + else if (_sensor_type == SensorBosch::PRESSURE) { + // pressure sensor + setPresentation(S_BARO); + setType(V_PRESSURE); + setValueType(TYPE_FLOAT); + } + else if (_sensor_type == SensorBosch::FORECAST) { + // pressure sensor + setPresentation(S_BARO); + setType(V_FORECAST); + setValueType(TYPE_STRING); + } +} + +// setter/getter +void SensorBosch::setForecastSamplesCount(int value) { + _forecast_samples_count = value; +} + +// what to do during before +void SensorBosch::onBefore() { + // initialize the forecast samples array + _forecast_samples = new float[_forecast_samples_count]; +} + +// what to do during setup +void SensorBosch::onSetup() { +} + +// what to do during loop +void SensorBosch::onLoop() { +} + +// what to do as the main task when receiving a message +void SensorBosch::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} + + +void SensorBosch::_forecast(float pressure) { + if (isnan(pressure)) return; + // Calculate the average of the last n minutes. + int index = _minute_count % _forecast_samples_count; + _forecast_samples[index] = pressure; + _minute_count++; + if (_minute_count > 185) _minute_count = 6; + if (_minute_count == 5) _pressure_avg = _getLastPressureSamplesAverage(); + else if (_minute_count == 35) { + float last_pressure_avg = _getLastPressureSamplesAverage(); + float change = (last_pressure_avg - _pressure_avg) * 0.1; + // first time initial 3 hour + if (_first_round) _dP_dt = change * 2; // note this is for t = 0.5hour + else _dP_dt = change / 1.5; // divide by 1.5 as this is the difference in time from 0 value. + } + else if (_minute_count == 65) { + float last_pressure_avg = _getLastPressureSamplesAverage(); + float change = (last_pressure_avg - _pressure_avg) * 0.1; + //first time initial 3 hour + if (_first_round) _dP_dt = change; //note this is for t = 1 hour + else _dP_dt = change / 2; //divide by 2 as this is the difference in time from 0 value + } + else if (_minute_count == 95) { + float last_pressure_avg = _getLastPressureSamplesAverage(); + float change = (last_pressure_avg - _pressure_avg) * 0.1; + // first time initial 3 hour + if (_first_round)_dP_dt = change / 1.5; // note this is for t = 1.5 hour + else _dP_dt = change / 2.5; // divide by 2.5 as this is the difference in time from 0 value + } + else if (_minute_count == 125) { + float last_pressure_avg = _getLastPressureSamplesAverage(); + // store for later use. + _pressure_avg2 = last_pressure_avg; + float change = (last_pressure_avg - _pressure_avg) * 0.1; + if (_first_round) _dP_dt = change / 2; // note this is for t = 2 hour + else _dP_dt = change / 3; // divide by 3 as this is the difference in time from 0 value + } + else if (_minute_count == 155) { + float last_pressure_avg = _getLastPressureSamplesAverage(); + float change = (last_pressure_avg - _pressure_avg) * 0.1; + if (_first_round) _dP_dt = change / 2.5; // note this is for t = 2.5 hour + else _dP_dt = change / 3.5; // divide by 3.5 as this is the difference in time from 0 value + } + else if (_minute_count == 185) { + float last_pressure_avg = _getLastPressureSamplesAverage(); + float change = (last_pressure_avg - _pressure_avg) * 0.1; + if (_first_round) _dP_dt = change / 3; // note this is for t = 3 hour + else _dP_dt = change / 4; // divide by 4 as this is the difference in time from 0 value + } + // Equating the pressure at 0 to the pressure at 2 hour after 3 hours have past. + _pressure_avg = _pressure_avg2; + // flag to let you know that this is on the past 3 hour mark. Initialized to 0 outside main loop. + _first_round = false; + // calculate the forecast (STABLE = 0, SUNNY = 1, CLOUDY = 2, UNSTABLE = 3, THUNDERSTORM = 4, UNKNOWN = 5) + int forecast = 5; + //if time is less than 35 min on the first 3 hour interval. + if (_minute_count < 35 && _first_round) forecast = 5; + else if (_dP_dt < (-0.25)) forecast = 5; + else if (_dP_dt > 0.25) forecast = 4; + else if ((_dP_dt > (-0.25)) && (_dP_dt < (-0.05))) forecast = 2; + else if ((_dP_dt > 0.05) && (_dP_dt < 0.25)) forecast = 1; + else if ((_dP_dt >(-0.05)) && (_dP_dt < 0.05)) forecast = 0; + else forecast = 5; + _value_string = _weather[forecast]; + #if DEBUG == 1 + Serial.print(F("BMP I=")); + Serial.print(_child_id); + Serial.print(F(" M=")); + Serial.print(_minute_count); + Serial.print(F(" dP=")); + Serial.print(_dP_dt); + Serial.print(F(" F=")); + Serial.println(_value_string); + #endif +} + +// returns the average of the latest pressure samples +float SensorBosch::_getLastPressureSamplesAverage() { + float avg = 0; + for (int i = 0; i < _forecast_samples_count; i++) avg += _forecast_samples[i]; + avg /= _forecast_samples_count; + return avg; +} + +// search for a given chip on i2c bus +uint8_t SensorBosch::GetI2CAddress(uint8_t chip_id) { + uint8_t addresses[] = {0x77, 0x76}; + uint8_t register_address = 0xD0; + for (int i = 0; i <= sizeof(addresses); i++) { + uint8_t i2c_address = addresses[i]; + uint8_t value; + Wire.beginTransmission((uint8_t)i2c_address); + Wire.write((uint8_t)register_address); + Wire.endTransmission(); + Wire.requestFrom((uint8_t)i2c_address, (byte)1); + value = Wire.read(); + if (value == chip_id) { + #if DEBUG == 1 + Serial.print(F("I2C=")); + Serial.println(i2c_address); + #endif + return i2c_address; + } + } + return addresses[0]; +} +#endif + +/* + * SensorBME280 + */ +#if MODULE_BME280 == 1 +SensorBME280::SensorBME280(int child_id, Adafruit_BME280* bme, int sensor_type): SensorBosch(child_id,sensor_type) { + _bme = bme; +} + +void SensorBME280::onLoop() { + // temperature sensor + if (_sensor_type == SensorBME280::TEMPERATURE) { + // read the temperature + float temperature = _bme->readTemperature(); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(F("BME I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(temperature); + #endif + if (isnan(temperature)) return; + // store the value + _value_float = temperature; + } + // Humidity Sensor + else if (_sensor_type == SensorBME280::HUMIDITY) { + // read humidity + float humidity = _bme->readHumidity(); + #if DEBUG == 1 + Serial.print(F("BME I=")); + Serial.print(_child_id); + Serial.print(F(" H=")); + Serial.println(humidity); + #endif + if (isnan(humidity)) return; + // store the value + _value_float = humidity; + } + // Pressure Sensor + else if (_sensor_type == SensorBME280::PRESSURE) { + // read pressure + float pressure = _bme->readPressure() / 100.0F; + if (isnan(pressure)) return; + #if DEBUG == 1 + Serial.print(F("BME I=")); + Serial.print(_child_id); + Serial.print(F(" P=")); + Serial.println(pressure); + #endif + if (isnan(pressure)) return; + // store the value + _value_float = pressure; + } + // Forecast Sensor + else if (_sensor_type == SensorBME280::FORECAST) { + float pressure = _bme->readPressure() / 100.0F; + _forecast(pressure); + } +} +#endif + +/* + SensorBMP085 +*/ +#if MODULE_BMP085 == 1 +// contructor +SensorBMP085::SensorBMP085(int child_id, Adafruit_BMP085* bmp, int sensor_type): SensorBosch(child_id,sensor_type) { + _bmp = bmp; +} + +// what to do during loop +void SensorBMP085::onLoop() { + // temperature sensor + if (_sensor_type == SensorBMP085::TEMPERATURE) { + // read the temperature + float temperature = _bmp->readTemperature(); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(F("BMP I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(temperature); + #endif + if (isnan(temperature)) return; + // store the value + _value_float = temperature; + } + // Pressure Sensor + else if (_sensor_type == SensorBMP085::PRESSURE) { + // read pressure + float pressure = _bmp->readPressure() / 100.0F; + #if DEBUG == 1 + Serial.print(F("BMP I=")); + Serial.print(_child_id); + Serial.print(F(" P=")); + Serial.println(pressure); + #endif + if (isnan(pressure)) return; + // store the value + _value_float = pressure; + } + // Forecast Sensor + else if (_sensor_type == SensorBMP085::FORECAST) { + float pressure = _bmp->readPressure() / 100.0F; + _forecast(pressure); + } +} +#endif + + +/* + SensorSonoff +*/ +#if MODULE_SONOFF == 1 +// contructor +SensorSonoff::SensorSonoff(int child_id): Sensor(child_id,1) { + setPresentation(S_BINARY); + setType(V_STATUS); +} + +// setter/getter +void SensorSonoff::setButtonPin(int value) { + _button_pin = value; +} +void SensorSonoff::setRelayPin(int value) { + _relay_pin = value; +} +void SensorSonoff::setLedPin(int value) { + _led_pin = value; +} + +// what to do during before +void SensorSonoff::onBefore() { +} + +// what to do during setup +void SensorSonoff::onSetup() { + // Setup the button + pinMode(_button_pin, INPUT_PULLUP); + // After setting up the button, setup debouncer + _debouncer.attach(_button_pin); + _debouncer.interval(5); + // Make sure relays and LED are off when starting up + digitalWrite(_relay_pin, _relay_off); + digitalWrite(_led_pin, _led_off); + // Then set relay pins in output mode + pinMode(_relay_pin, OUTPUT); + pinMode(_led_pin, OUTPUT); + _blink(); +} + +// what to do during loop +void SensorSonoff::onLoop() { + // set the value to -1 so to avoid reporting to the gateway during loop + _value_int = -1; + _debouncer.update(); + // Get the update value from the button + int value = _debouncer.read(); + if (value != _old_value && value == 0) { + // button pressed, toggle the state + _toggle(); + } + _old_value = value; +} + +// what to do as the main task when receiving a message +void SensorSonoff::onReceive(const MyMessage & message) { + if (message.getCommand() == C_SET) { + // retrieve from the message the value to set + int value = message.getInt(); + if (value != 0 && value != 1 || value == _state) return; + // toggle the state + _toggle(); + } + if (message.getCommand() == C_REQ) { + // return the current state + _value_int = _state; + } +} + +// toggle the state +void SensorSonoff::_toggle() { + // toggle the state + _state = _state ? false : true; + // Change relay state + digitalWrite(_relay_pin, _state? _relay_on: _relay_off); + // Change LED state + digitalWrite(_led_pin, _state? _led_on: _led_off); + #if DEBUG == 1 + Serial.print(F("SONOFF I=")); + Serial.print(_child_id); + Serial.print(F(" V=")); + Serial.println(_state); + #endif + _value_int = _state; +} + +// blink the led +void SensorSonoff::_blink() { + digitalWrite(_led_pin, digitalRead(_led_pin) ? _led_on : _led_off); + wait(200); + digitalWrite(_led_pin, digitalRead(_led_pin) ? _led_on : _led_off); + wait(200); + digitalWrite(_led_pin, digitalRead(_led_pin) ? _led_on : _led_off); + wait(200); + digitalWrite(_led_pin, digitalRead(_led_pin) ? _led_on : _led_off); +} +#endif + + +/* + SensorHCSR04 +*/ +#if MODULE_HCSR04 == 1 +// contructor +SensorHCSR04::SensorHCSR04(int child_id, int pin): Sensor(child_id, pin) { + // set presentation and type + setPresentation(S_DISTANCE); + setType(V_DISTANCE); + _trigger_pin = pin; + _echo_pin = pin; +} + +// what to do during before +void SensorHCSR04::onBefore() { + // initialize the library + _sonar = new NewPing(_trigger_pin,_echo_pin,_max_distance); +} + +// setter/getter +void SensorHCSR04::setTriggerPin(int value) { + _trigger_pin = value; +} +void SensorHCSR04::setEchoPin(int value) { + _echo_pin = value; +} +void SensorHCSR04::setMaxDistance(int value) { + _max_distance = value; +} + +// what to do during setup +void SensorHCSR04::onSetup() { +} + +// what to do during loop +void SensorHCSR04::onLoop() { + int distance = getControllerConfig().isMetric ? _sonar->ping_cm() : _sonar->ping_in(); + #if DEBUG == 1 + Serial.print(F("HC I=")); + Serial.print(_child_id); + Serial.print(F(" D=")); + Serial.println(distance); + #endif + _value_int = distance; +} + +// what to do as the main task when receiving a message +void SensorHCSR04::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} +#endif + +/* + SensorMCP9808 +*/ +#if MODULE_MCP9808 == 1 +// contructor +SensorMCP9808::SensorMCP9808(int child_id, Adafruit_MCP9808* mcp): Sensor(child_id,A2) { + _mcp = mcp; + setPresentation(S_TEMP); + setType(V_TEMP); + setValueType(TYPE_FLOAT); +} + +// what to do during before +void SensorMCP9808::onBefore() { +} + +// what to do during setup +void SensorMCP9808::onSetup() { +} + +// what to do during loop +void SensorMCP9808::onLoop() { + float temperature = _mcp->readTempC(); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(F("MCP I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(temperature); + #endif + // store the value + if (! isnan(temperature)) _value_float = temperature; +} + +// what to do as the main task when receiving a message +void SensorMCP9808::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) 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::setRetries(int value) { + _retries = 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; + } + void NodeManager::setBatteryInternalVcc(bool value) { + _battery_internal_vcc = value; + } + void NodeManager::setBatteryPin(int value) { + _battery_pin = value; + } + void NodeManager::setBatteryVoltsPerBit(float value) { + _battery_volts_per_bit = value; + } + void NodeManager::setBatteryReportWithInterrupt(bool value) { + _battery_report_with_interrupt = value; + } +#endif +void NodeManager::setSleepMode(int value) { + _sleep_mode = value; +} +void NodeManager::setMode(int value) { + setSleepMode(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 = value2; + _sleep_unit = value3; +} +void NodeManager::setSleepInterruptPin(int value) { + _sleep_interrupt_pin = value; +} +void NodeManager::setInterrupt(int pin, int mode, int pull) { + 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, int wait_time) { + _powerManager.setPowerPins(ground_pin, vcc_pin, wait_time); + } + void NodeManager::setAutoPowerPins(bool value) { + _auto_power_pins = value; + } + void NodeManager::powerOn() { + _powerManager.powerOn(); + } + void NodeManager::powerOff() { + _powerManager.powerOff(); + } +#endif +void NodeManager::setSleepBetweenSend(int value) { + _sleep_between_send = value; +} +void NodeManager::setAck(bool value) { + _ack = value; +} + +// register a sensor to this manager +int NodeManager::registerSensor(int sensor_type, int pin, int child_id) { + // 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 -1; + #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)); + else if (sensor_type == SENSOR_MQ) return registerSensor(new SensorMQ(child_id, pin)); + else if (sensor_type == SENSOR_ML8511) return registerSensor(new SensorML8511(child_id, pin)); + else if (sensor_type == SENSOR_ACS712) return registerSensor(new SensorACS712(child_id, pin)); + else if (sensor_type == SENSOR_RAIN_GAUGE) return registerSensor(new SensorRainGauge(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) { + int dht_type = sensor_type == SENSOR_DHT11 ? DHT11 : DHT22; + DHT* dht = new DHT(pin,dht_type); + // register temperature sensor + registerSensor(new SensorDHT(child_id,pin,dht,SensorDHT::TEMPERATURE,dht_type)); + // register humidity sensor + child_id = _getAvailableChildId(); + return registerSensor(new SensorDHT(child_id,pin,dht,SensorDHT::HUMIDITY,dht_type)); + } + #endif + #if MODULE_SHT21 == 1 + else if (sensor_type == SENSOR_SHT21) { + // register temperature sensor + registerSensor(new SensorSHT21(child_id,SensorSHT21::TEMPERATURE)); + // register humidity sensor + child_id = _getAvailableChildId(); + return registerSensor(new SensorSHT21(child_id,SensorSHT21::HUMIDITY)); + } + else if (sensor_type == SENSOR_HTU21D) { + // register temperature sensor + registerSensor(new SensorHTU21D(child_id,SensorHTU21D::TEMPERATURE)); + // register humidity sensor + child_id = _getAvailableChildId(); + return registerSensor(new SensorHTU21D(child_id,SensorHTU21D::HUMIDITY)); + } + #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 -1; + // 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 set the initial value + SensorSwitch* sensor = (SensorSwitch*)getSensor(index); + sensor->setInterruptPin(pin); + setInterrupt(pin,sensor->getMode(),sensor->getInitial()); + 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(); + int index = 0; + // register a new child for each sensor on the bus + for(int i = 0; i < sensors->getDeviceCount(); i++) { + if (i > 0) child_id = _getAvailableChildId(); + index = registerSensor(new SensorDs18b20(child_id,pin,sensors,i)); + } + return index; + } + #endif + #if MODULE_BH1750 == 1 + else if (sensor_type == SENSOR_BH1750) { + return registerSensor(new SensorBH1750(child_id)); + } + #endif + #if MODULE_MLX90614 == 1 + else if (sensor_type == SENSOR_MLX90614) { + Adafruit_MLX90614* mlx = new Adafruit_MLX90614(); + // register ambient temperature sensor + registerSensor(new SensorMLX90614(child_id,mlx,SensorMLX90614::TEMPERATURE_AMBIENT)); + // register object temperature sensor + child_id = _getAvailableChildId(); + return registerSensor(new SensorMLX90614(child_id,mlx,SensorMLX90614::TEMPERATURE_OBJECT)); + } + #endif + #if MODULE_BME280 == 1 + else if (sensor_type == SENSOR_BME280) { + Adafruit_BME280* bme = new Adafruit_BME280(); + if (! bme->begin(SensorBosch::GetI2CAddress(0x60))) { + #if DEBUG == 1 + Serial.println(F("NO BME")); + #endif + return -1; + } + // register temperature sensor + registerSensor(new SensorBME280(child_id,bme,SensorBME280::TEMPERATURE)); + child_id = _getAvailableChildId(); + // register humidity sensor + registerSensor(new SensorBME280(child_id,bme,SensorBME280::HUMIDITY)); + // register pressure sensor + child_id = _getAvailableChildId(); + registerSensor(new SensorBME280(child_id,bme,SensorBME280::PRESSURE)); + // register forecast sensor + child_id = _getAvailableChildId(); + return registerSensor(new SensorBME280(child_id,bme,SensorBME280::FORECAST)); + } + #endif + #if MODULE_SONOFF == 1 + else if (sensor_type == SENSOR_SONOFF) { + return registerSensor(new SensorSonoff(child_id)); + } + #endif + #if MODULE_BMP085 == 1 + else if (sensor_type == SENSOR_BMP085) { + Adafruit_BMP085* bmp = new Adafruit_BMP085(); + if (! bmp->begin(SensorBosch::GetI2CAddress(0x55))) { + #if DEBUG == 1 + Serial.println(F("NO BMP")); + #endif + return -1; + } + // register temperature sensor + registerSensor(new SensorBMP085(child_id,bmp,SensorBMP085::TEMPERATURE)); + // register pressure sensor + child_id = _getAvailableChildId(); + registerSensor(new SensorBMP085(child_id,bmp,SensorBMP085::PRESSURE)); + // register forecast sensor + child_id = _getAvailableChildId(); + return registerSensor(new SensorBMP085(child_id,bmp,SensorBMP085::FORECAST)); + } + #endif + #if MODULE_HCSR04 == 1 + else if (sensor_type == SENSOR_HCSR04) { + return registerSensor(new SensorHCSR04(child_id, pin)); + } + #endif + #if MODULE_MCP9808 == 1 + else if (sensor_type == SENSOR_MCP9808) { + Adafruit_MCP9808 * mcp = new Adafruit_MCP9808(); + if (! mcp->begin()) { + #if DEBUG == 1 + Serial.println(F("NO MCP")); + #endif + return -1; + } + // register temperature sensor + registerSensor(new SensorMCP9808(child_id,mcp)); + } + #endif + else { + #if DEBUG == 1 + Serial.print(F("INVALID ")); + 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(F("REG I=")); + Serial.print(sensor->getChildId()); + Serial.print(F(" P=")); + Serial.print(sensor->getPin()); + Serial.print(F(" P=")); + Serial.print(sensor->getPresentation()); + Serial.print(F(" T=")); + Serial.println(sensor->getType()); + #endif + #if POWER_MANAGER == 1 + // set auto power pin + sensor->setAutoPowerPins(_auto_power_pins); + #endif + // add the sensor to the array of registered sensors + _sensors[sensor->getChildId()] = sensor; + // return the child_id + return sensor->getChildId(); +} + +// un-register a sensor to this manager +void NodeManager::unRegisterSensor(int sensor_index) { + // unlink the pointer to this sensor + _sensors[sensor_index] == 0; +} + +// 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]; +} +Sensor* NodeManager::getSensor(int child_id) { + return get(child_id); +} + +// assign a different child id to a sensor' +bool NodeManager::renameSensor(int old_child_id, int new_child_id) { + // ensure the old id exists and the new is available + if (_sensors[old_child_id] == 0 || _sensors[new_child_id] != 0) return false; + // assign the sensor to new id + _sensors[new_child_id] = _sensors[old_child_id]; + // set the new child id + _sensors[new_child_id]->setChildId(new_child_id); + // free up the old id + _sensors[old_child_id] = 0; + return true; +} + +// setup NodeManager +void NodeManager::before() { + #if DEBUG == 1 + Serial.print(F("NodeManager v")); + Serial.println(VERSION); + #endif + // 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(F("INT1 M=")); + Serial.println(_interrupt_1_mode); + Serial.print(F("INT2 M=")); + Serial.println(_interrupt_2_mode); + #endif + #if REMOTE_CONFIGURATION == 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(F("LOADSLP M=")); + Serial.print(_sleep_mode); + Serial.print(F(" T=")); + Serial.print(_sleep_time); + Serial.print(F(" U=")); + Serial.println(_sleep_unit); + #endif + } + #endif + #if BATTERY_MANAGER == 1 && !defined(MY_GATEWAY_ESP8266) + // set analogReference to internal if measuring the battery through a pin + if (! _battery_internal_vcc && _battery_pin > -1) analogReference(INTERNAL); + #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() { + #if DEBUG == 1 + Serial.println(F("RADIO OK")); + #endif + // Send the sketch version information to the gateway and Controller + if (_sleep_between_send > 0) sleep(_sleep_between_send); + sendSketchInfo(SKETCH_NAME,SKETCH_VERSION); + // present the service as a custom sensor to the controller + _present(CONFIGURATION_CHILD_ID, S_CUSTOM); + #if BATTERY_MANAGER == 1 && BATTERY_SENSOR == 1 + // 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() + if (_sleep_between_send > 0) sleep(_sleep_between_send); + _sensors[i]->presentation(); + } + #if DEBUG == 1 + Serial.println(F("READY")); + Serial.println(""); + #endif +} + + +// setup NodeManager +void NodeManager::setup() { + #if DEBUG == 1 + Serial.print(F("MY I=")); + Serial.print(getNodeId()); + Serial.print(F(" M=")); + Serial.println(getControllerConfig().isMetric); + #endif + #if SERVICE_MESSAGES == 1 + _send(_msg.set("STARTED")); + #endif + // run setup for all the registered sensors + for (int i = 0; i < 255; i++) { + if (_sensors[i] == 0) continue; + // call each sensor's setup() + _sensors[i]->setup(); + } +} + +// run the main function for all the register sensors +void NodeManager::loop() { + MyMessage empty; + // if in idle mode, do nothing + if (_sleep_mode == IDLE) return; + // if sleep time is not set, do nothing + if ((_sleep_mode == SLEEP || _sleep_mode == WAIT) && _sleep_time == 0) return; + #if POWER_MANAGER == 1 + // turn on the pin powering all the sensors + if (_auto_power_pins) powerOn(); + #endif + // run loop for all the registered sensors + for (int i = 0; i < 255; i++) { + // skip not configured sensors + if (_sensors[i] == 0) continue; + // if waking up from an interrupt skip all the sensor without that interrupt configured + if (_last_interrupt_pin != -1 && _sensors[i]->getInterruptPin() != _last_interrupt_pin) continue; + // call each sensor's loop() + _sensors[i]->loop(empty); + } + #if POWER_MANAGER == 1 + // turn off the pin powering all the sensors + if (_auto_power_pins) powerOff(); + #endif + // continue/start sleeping as requested + if (_sleep_mode == SLEEP || _sleep_mode == WAIT) _sleep(); +} + +// dispacth inbound messages +void NodeManager::receive(const MyMessage &message) { + #if DEBUG == 1 + Serial.print(F("RECV S=")); + Serial.print(message.sender); + Serial.print(F(" I=")); + Serial.print(message.sensor); + Serial.print(F(" C=")); + Serial.print(message.getCommand()); + Serial.print(F(" T=")); + Serial.print(message.type); + Serial.print(F(" P=")); + 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 (_sensors[message.sensor] != 0) { + #if POWER_MANAGER == 1 + // turn on the pin powering all the sensors + if (_auto_power_pins) powerOn(); + #endif + // call the sensor's receive() + _sensors[message.sensor]->receive(message); + #if POWER_MANAGER == 1 + // turn off the pin powering all the sensors + if (_auto_power_pins) powerOff(); + #endif + } +} + +// request and return the current timestamp from the controller +long NodeManager::getTimestamp() { + int retries = 3; + _timestamp = -1; + while (_timestamp == -1 && retries > 0) { + #if DEBUG == 1 + Serial.println(F("TIME")); + #endif + // request the time to the controller + requestTime(); + // keep asking every 1 second + wait(1000); + retries--; + } + return _timestamp; +} + +// receive the time from the controller and save it +void NodeManager::receiveTime(unsigned long ts) { + _timestamp = ts; + #if DEBUG == 1 + Serial.print(F("TIME T=")); + Serial.print(_timestamp); + #endif +} + +// send a message to the network +void NodeManager::_send(MyMessage & message) { + // send the message, multiple times if requested + for (int i = 0; i < _retries; i++) { + // if configured, sleep beetween each send + if (_sleep_between_send > 0) sleep(_sleep_between_send); + #if DEBUG == 1 + Serial.print(F("SEND D=")); + Serial.print(message.destination); + Serial.print(F(" I=")); + Serial.print(message.sensor); + Serial.print(F(" C=")); + Serial.print(message.getCommand()); + Serial.print(F(" T=")); + Serial.print(message.type); + Serial.print(F(" S=")); + Serial.print(message.getString()); + Serial.print(F(" I=")); + Serial.print(message.getInt()); + Serial.print(F(" F=")); + Serial.println(message.getFloat()); + #endif + send(message,_ack); + } +} + +// 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 = 0; + if (_battery_internal_vcc || _battery_pin == -1) volt = getVcc(); + else volt = analogRead(_battery_pin) * _battery_volts_per_bit; + // 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(F("BATT V=")); + Serial.print(volt); + Serial.print(F(" P=")); + Serial.println(percentage); + #endif + #if 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,_ack); + } + #endif + #ifndef MY_GATEWAY_ESP8266 + // REBOOT: reboot the board + else if (strcmp(message, "REBOOT") == 0) { + #if DEBUG == 1 + Serial.println(F("REBOOT")); + #endif + // set the reboot pin connected to RST to low so to reboot the board + _send(_msg.set(message)); + // Software reboot with watchdog timer. Enter Watchdog Configuration mode: + WDTCSR |= (1< -1) { + // woke up by an interrupt + int pin_number = -1; + int interrupt_mode = -1; + // map the interrupt to the pin + if (digitalPinToInterrupt(INTERRUPT_PIN_1) == interrupt) { + pin_number = INTERRUPT_PIN_1; + interrupt_mode = _interrupt_1_mode; + } + if (digitalPinToInterrupt(INTERRUPT_PIN_2) == interrupt) { + pin_number = INTERRUPT_PIN_2; + interrupt_mode = _interrupt_2_mode; + } + _last_interrupt_pin = pin_number; + #if DEBUG == 1 + Serial.print(F("WAKE P=")); + Serial.print(pin_number); + Serial.print(F(", M=")); + 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; + } + } + // coming out of sleep + #if DEBUG == 1 + Serial.println(F("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 (ignoring if woke up by an interrupt) + if (interrupt == -1 || _battery_report_with_interrupt) _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 +} + +// present the service +void NodeManager::_present(int child_id, int type) { + #if DEBUG == 1 + Serial.print(F("PRES I=")); + Serial.print(child_id); + Serial.print(F(", T=")); + Serial.println(type); + #endif + if (_sleep_between_send > 0) sleep(_sleep_between_send); + present(child_id,type,"",_ack); +} + +// 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; + } +} + +// 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/libraries/NodeManager/NodeManager.h b/libraries/NodeManager/NodeManager.h new file mode 100644 index 0000000..6e3ed5e --- /dev/null +++ b/libraries/NodeManager/NodeManager.h @@ -0,0 +1,1075 @@ +/* + * NodeManager + */ +#ifndef NodeManager_h +#define NodeManager_h + +#include + +// define NodeManager version +#define VERSION "1.5" + +/*********************************** + Constants +*/ + +// define sleep mode +#define IDLE 0 +#define SLEEP 1 +#define WAIT 2 +#define ALWAYS_ON 3 + +// 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 + +/************************************ + * Include user defined configuration settings + */ + +#include "config.h" + +/*********************************** + Default configuration settings +*/ + +// if enabled, enable the capability to power on sensors with the arduino's pins to save battery while sleeping +#ifndef POWER_MANAGER + #define POWER_MANAGER 1 +#endif +// if enabled, will load the battery manager library to allow the battery level to be reported automatically or on demand +#ifndef BATTERY_MANAGER + #define BATTERY_MANAGER 1 +#endif +// if enabled, allow modifying the configuration remotely by interacting with the configuration child id +#ifndef REMOTE_CONFIGURATION + #define REMOTE_CONFIGURATION 1 +#endif +// if enabled, persist the configuration settings on EEPROM +#ifndef PERSIST + #define PERSIST 0 +#endif + +// if enabled, enable debug messages on serial port +#ifndef DEBUG + #define DEBUG 1 +#endif + +// if enabled, send a SLEEPING and AWAKE service messages just before entering and just after leaving a sleep cycle +#ifndef SERVICE_MESSAGES + #define SERVICE_MESSAGES 1 +#endif +// if enabled, a battery sensor will be created at BATTERY_CHILD_ID and will report vcc voltage together with the battery level percentage +#ifndef BATTERY_SENSOR + #define BATTERY_SENSOR 1 +#endif + +// the child id used to allow remote configuration +#ifndef CONFIGURATION_CHILD_ID + #define CONFIGURATION_CHILD_ID 200 +#endif +// the child id used to report the battery voltage to the controller +#ifndef BATTERY_CHILD_ID + #define BATTERY_CHILD_ID 201 +#endif + +// Enable this module to use one of the following sensors: SENSOR_ANALOG_INPUT, SENSOR_LDR, SENSOR_THERMISTOR, SENSOR_MQ, SENSOR_ACS712 +#ifndef MODULE_ANALOG_INPUT + #define MODULE_ANALOG_INPUT 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_DIGITAL_INPUT +#ifndef MODULE_DIGITAL_INPUT + #define MODULE_DIGITAL_INPUT 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_DIGITAL_OUTPUT, SENSOR_RELAY, SENSOR_LATCHING_RELAY +#ifndef MODULE_DIGITAL_OUTPUT + #define MODULE_DIGITAL_OUTPUT 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_SHT21, SENSOR_HTU21D +#ifndef MODULE_SHT21 + #define MODULE_SHT21 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_DHT11, SENSOR_DHT22 +#ifndef MODULE_DHT + #define MODULE_DHT 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_SWITCH, SENSOR_DOOR, SENSOR_MOTION +#ifndef MODULE_SWITCH + #define MODULE_SWITCH 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_DS18B20 +#ifndef MODULE_DS18B20 + #define MODULE_DS18B20 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_BH1750 +#ifndef MODULE_BH1750 + #define MODULE_BH1750 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_MLX90614 +#ifndef MODULE_MLX90614 + #define MODULE_MLX90614 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_BME280 +#ifndef MODULE_BME280 + #define MODULE_BME280 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_SONOFF +#ifndef MODULE_SONOFF + #define MODULE_SONOFF 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_BMP085 +#ifndef MODULE_BMP085 + #define MODULE_BMP085 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_HCSR04 +#ifndef MODULE_HCSR04 + #define MODULE_HCSR04 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_MCP9808 +#ifndef MODULE_MCP9808 + #define MODULE_MCP9808 0 +#endif + +/*********************************** + Sensors types +*/ +#if MODULE_ANALOG_INPUT == 1 + // Generic analog sensor, return a pin's analog value or its percentage + #define SENSOR_ANALOG_INPUT 1 + // LDR sensor, return the light level of an attached light resistor in percentage + #define SENSOR_LDR 2 + // Thermistor sensor, return the temperature based on the attached thermistor + #define SENSOR_THERMISTOR 3 + // MQ2 air quality sensor + #define SENSOR_MQ 19 + // ML8511 UV sensor + #define SENSOR_ML8511 20 + // Current sensor + #define SENSOR_ACS712 24 + // rain gauge sensor + #define SENSOR_RAIN_GAUGE 26 +#endif +#if MODULE_DIGITAL_INPUT == 1 + // Generic digital sensor, return a pin's digital value + #define SENSOR_DIGITAL_INPUT 4 +#endif +#if MODULE_DIGITAL_OUTPUT == 1 + // Generic digital output sensor, allows setting the digital output of a pin to the requested value + #define SENSOR_DIGITAL_OUTPUT 5 + // Relay sensor, allows activating the relay + #define SENSOR_RELAY 6 + // Latching Relay sensor, allows activating the relay with a pulse + #define SENSOR_LATCHING_RELAY 7 +#endif +#if MODULE_DHT == 1 + // DHT11/DHT22 sensors, return temperature/humidity based on the attached DHT sensor + #define SENSOR_DHT11 8 + #define SENSOR_DHT22 9 +#endif +#if MODULE_SHT21 == 1 + // SHT21 sensor, return temperature/humidity based on the attached SHT21 sensor + #define SENSOR_SHT21 10 + #define SENSOR_HTU21D 15 +#endif +#if MODULE_SWITCH == 1 + // Generic switch, wake up the board when a pin changes status + #define SENSOR_SWITCH 11 + // Door sensor, wake up the board and report when an attached magnetic sensor has been opened/closed + #define SENSOR_DOOR 12 + // Motion sensor, wake up the board and report when an attached PIR has triggered + #define SENSOR_MOTION 13 +#endif +#if MODULE_DS18B20 == 1 + // DS18B20 sensor, return the temperature based on the attached sensor + #define SENSOR_DS18B20 14 +#endif +#if MODULE_BH1750 == 1 + // BH1750 sensor, return light in lux + #define SENSOR_BH1750 16 +#endif +#if MODULE_MLX90614 == 1 + // MLX90614 sensor, contactless temperature sensor + #define SENSOR_MLX90614 17 +#endif +#if MODULE_BME280 == 1 + // MLX90614 sensor, contactless temperature sensor + #define SENSOR_BME280 18 +#endif +#if MODULE_SONOFF == 1 + // Sonoff wireless smart switch + #define SENSOR_SONOFF 21 +#endif +#if MODULE_BMP085 == 1 + // BMP085/BMP180 sensor, return temperature and pressure + #define SENSOR_BMP085 22 +#endif +#if MODULE_HCSR04 == 1 + // HC-SR04 sensor, return the distance between the sensor and an object + #define SENSOR_HCSR04 23 +#endif +#if MODULE_MCP9808 == 1 + // MCP9808 sensor, precision temperature sensor + #define SENSOR_MCP9808 25 +#endif +// last Id: 26 +/*********************************** + Libraries +*/ + +// include supporting libraries +#ifdef MY_USE_UDP + #include +#endif +#ifdef MY_GATEWAY_ESP8266 + #include +#endif + +// include MySensors libraries +#include + +// include third party libraries +#if MODULE_DHT == 1 + #include +#endif +#if MODULE_SHT21 == 1 + #include + #include +#endif +#if MODULE_DS18B20 == 1 + #include + #include +#endif +#if MODULE_BH1750 == 1 + #include + #include +#endif +#if MODULE_MLX90614 == 1 + #include + #include +#endif +#if MODULE_BME280 == 1 + #include + #include + #include + #include +#endif +#if MODULE_SONOFF == 1 + #include +#endif +#if MODULE_BMP085 == 1 + #include + #include +#endif +#if MODULE_HCSR04 == 1 + #include +#endif +#if MODULE_MCP9808 == 1 + #include + #include "Adafruit_MCP9808.h" +#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, int wait_time = 50); + void powerOn(); + void powerOff(); + float getVcc(); + bool isConfigured(); + private: + int _vcc_pin = -1; + int _ground_pin = -1; + long _wait = 0; +}; + + +/*************************************** + 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(); + // description of the sensor (default: '') + void setDescription(char *value); + // set this to true if you want destination node to send ack back to this node (default: false) + void setAck(bool 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); + int getValueType(); + // for float values, set the float precision (default: 2) + void setFloatPrecision(int value); + // optionally sleep interval in milliseconds before sending each message to the radio network (default: 0) + void setSleepBetweenSend(int value); + // set the interrupt pin the sensor is attached to so its loop() will be executed only upon that interrupt (default: -1) + void setInterruptPin(int value); + int getInterruptPin(); + #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, int wait_time = 50); + // if enabled the pins will be automatically powered on while awake and off during sleeping (default: true) + void setAutoPowerPins(bool value); + // manually turn the power on + void powerOn(); + // manually turn the power off + void powerOff(); + #endif + // get the latest recorded value from the sensor + int getValueInt(); + float getValueFloat(); + char* getValueString(); + // define what to do at each stage of the sketch + virtual void before(); + virtual void presentation(); + virtual void setup(); + virtual void loop(const MyMessage & message); + virtual void receive(const MyMessage & message); + // abstract functions, subclasses need to implement + virtual void onBefore() = 0; + virtual void onSetup() = 0; + virtual void onLoop() = 0; + virtual void onReceive(const MyMessage & message) = 0; + protected: + MyMessage _msg; + int _sleep_between_send = 0; + int _pin = -1; + int _child_id; + int _presentation = S_CUSTOM; + int _type = V_CUSTOM; + char* _description = ""; + bool _ack = false; + int _retries = 1; + int _samples = 1; + int _samples_interval = 0; + bool _track_last_value = false; + int _cycles = 0; + int _force_update = -1; + 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 = ""; + int _interrupt_pin = -1; + #if POWER_MANAGER == 1 + PowerManager _powerManager; + bool _auto_power_pins = true; + #endif + void _send(MyMessage & msg); +}; + +/* + 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 onSetup(); + 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(long 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(long value); + // set a temperature offset + void setOffset(float value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + long _nominal_resistor = 10000; + int _nominal_temperature = 25; + int _b_coefficient = 3950; + long _series_resistor = 10000; + float _offset = 0; +}; + +/* + SensorMQ + */ +class SensorMQ: public Sensor { + public: + SensorMQ(int child_id, int pin); + // define the target gas whose ppm has to be returned. 0: LPG, 1: CO, 2: Smoke (default: 1); + void setTargetGas(int value); + // define the load resistance on the board, in kilo ohms (default: 1); + void setRlValue(float value); + // define the Ro resistance on the board (default: 10000); + void setRoValue(float value); + // Sensor resistance in clean air (default: 9.83); + void setCleanAirFactor(float value); + // define how many samples you are going to take in the calibration phase (default: 50); + void setCalibrationSampleTimes(int value); + // define the time interal(in milisecond) between each samples in the cablibration phase (default: 500); + void setCalibrationSampleInterval(int value); + // define how many samples you are going to take in normal operation (default: 50); + void setReadSampleTimes(int value); + // define the time interal(in milisecond) between each samples in the normal operations (default: 5); + void setReadSampleInterval(int value); + // set the LPGCurve array (default: {2.3,0.21,-0.47}) + void setLPGCurve(float *value); + // set the COCurve array (default: {2.3,0.72,-0.34}) + void setCOCurve(float *value); + // set the SmokeCurve array (default: {2.3,0.53,-0.44}) + void setSmokeCurve(float *value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + float _rl_value = 1.0; + float _ro_clean_air_factor = 9.83; + int _calibration_sample_times = 50; + int _calibration_sample_interval = 500; + int _read_sample_interval = 50; + int _read_sample_times = 5; + float _ro = 10000.0; + float _LPGCurve[3] = {2.3,0.21,-0.47}; + float _COCurve[3] = {2.3,0.72,-0.34}; + float _SmokeCurve[3] = {2.3,0.53,-0.44}; + float _MQResistanceCalculation(int raw_adc); + float _MQCalibration(); + float _MQRead(); + int _MQGetGasPercentage(float rs_ro_ratio, int gas_id); + int _MQGetPercentage(float rs_ro_ratio, float *pcurve); + int _gas_lpg = 0; + int _gas_co = 1; + int _gas_smoke = 2; + int _target_gas = _gas_co; +}; + +/* + SensorML8511 +*/ + +class SensorML8511: public Sensor { + public: + SensorML8511(int child_id, int pin); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + float _mapfloat(float x, float in_min, float in_max, float out_min, float out_max); +}; + +/* + SensorACS712 +*/ + +class SensorACS712: public Sensor { + public: + SensorACS712(int child_id, int pin); + // set how many mV are equivalent to 1 Amp. The value depends on the module (100 for 20A Module, 66 for 30A Module) (default: 185); + void setmVPerAmp(int value); + // set ACS offset (default: 2500); + void setOffset(int value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + int _ACS_offset = 2500; + int _mv_per_amp = 185; +}; + +/* + SensorRainGauge +*/ + +class SensorRainGauge: public Sensor { + public: + SensorRainGauge(int child_id, int pin); + // set how frequently to report back to the controller in minutes. After reporting the measure is resetted (default: 60); + void setReportInterval(int value); + // set how many mm of rain to count for each tip (default: 0.11); + void setSingleTip(float value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + public: + static void _onTipped(); + static long _last_tip; + static long _count; + protected: + int _report_interval = 60; + float _single_tip = 0.11; + long _last_report = 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 onSetup(); + 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 which value to set to the output when set to on (default: HIGH) + void setOnValue(int value); + // when legacy mode is enabled expect a REQ message to trigger, otherwise the default SET (default: false) + void setLegacyMode(bool value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + int _initial_value = LOW; + int _on_value = HIGH; + int _state = 0; + int _pulse_width = 0; + bool _legacy_mode = false; +}; + + +/* + SensorRelay +*/ +class SensorRelay: public SensorDigitalOutput { + public: + SensorRelay(int child_id, int pin); + // define what to do at each stage of the sketch + void onLoop(); +}; + +/* + 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 onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + // constants + const static int TEMPERATURE = 0; + const static int HUMIDITY = 1; + protected: + DHT* _dht; + int _dht_type = DHT11; + float _offset = 0; + int _sensor_type = 0; +}; +#endif + +/* + SensorSHT21: temperature and humidity sensor +*/ +#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 onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + // constants + const static int TEMPERATURE = 0; + const static int HUMIDITY = 1; + protected: + float _offset = 0; + int _sensor_type = 0; +}; + +/* + SensorHTU21D: temperature and humidity sensor +*/ + +class SensorHTU21D: public SensorSHT21 { + public: + SensorHTU21D(int child_id, int pin); +}; +#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); + // Set initial value on the interrupt pin (default: HIGH) + void setInitial(int value); + int getInitial(); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + int _debounce = 0; + int _trigger_time = 0; + int _mode = CHANGE; + int _initial = HIGH; +}; + +/* + * 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); + // return the sensors' device address + DeviceAddress* getDeviceAddress(); + // returns the sensor's resolution in bits + int getResolution(); + // set the sensor's resolution in bits + void setResolution(int value); + // sleep while DS18B20 calculates temperature (default: false) + void setSleepDuringConversion(bool value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + float _offset = 0; + int _index; + bool _sleep_during_conversion = false; + DallasTemperature* _sensors; + DeviceAddress _device_address; +}; +#endif + +/* + SensorBH1750 +*/ +#if MODULE_BH1750 == 1 +class SensorBH1750: public Sensor { + public: + SensorBH1750(int child_id); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + BH1750* _lightSensor; +}; +#endif + +/* + SensorMLX90614 +*/ +#if MODULE_MLX90614 == 1 +class SensorMLX90614: public Sensor { + public: + SensorMLX90614(int child_id, Adafruit_MLX90614* mlx, int sensor_type); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + // constants + const static int TEMPERATURE_AMBIENT = 0; + const static int TEMPERATURE_OBJECT = 1; + protected: + Adafruit_MLX90614* _mlx; + int _sensor_type; +}; +#endif + + +/* + * SensorBosch +*/ + +#if MODULE_BME280 == 1 || MODULE_BMP085 == 1 +class SensorBosch: public Sensor { + public: + SensorBosch(int child_id, int sensor_type); + // define how many pressure samples to keep track of for calculating the forecast (default: 5) + void setForecastSamplesCount(int value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + // constants + const static int TEMPERATURE = 0; + const static int HUMIDITY = 1; + const static int PRESSURE = 2; + const static int FORECAST = 3; + static uint8_t GetI2CAddress(uint8_t chip_id); + protected: + int _sensor_type; + char* _weather[6] = { "stable", "sunny", "cloudy", "unstable", "thunderstorm", "unknown" }; + int _forecast_samples_count = 5; + float* _forecast_samples; + int _minute_count = 0; + float _pressure_avg; + float _pressure_avg2; + float _dP_dt; + bool _first_round = true; + float _getLastPressureSamplesAverage(); + void _forecast(float pressure); +}; +#endif + +/* + SensorBME280 +*/ +#if MODULE_BME280 == 1 +class SensorBME280: public SensorBosch { + public: + SensorBME280(int child_id, Adafruit_BME280* bme, int sensor_type); + void onLoop(); + protected: + Adafruit_BME280* _bme; +}; +#endif + +/* + SensorBMP085 +*/ +#if MODULE_BMP085 == 1 +class SensorBMP085: public SensorBosch { + public: + SensorBMP085(int child_id, Adafruit_BMP085* bmp, int sensor_type); + void onLoop(); + protected: + Adafruit_BMP085* _bmp; +}; +#endif + +/* + SensorHCSR04 +*/ +#if MODULE_HCSR04 == 1 +class SensorHCSR04: public Sensor { + public: + SensorHCSR04(int child_id, int pin); + // Arduino pin tied to trigger pin on the ultrasonic sensor (default: the pin set while registering the sensor) + void setTriggerPin(int value); + // Arduino pin tied to echo pin on the ultrasonic sensor (default: the pin set while registering the sensor) + void setEchoPin(int value); + // Maximum distance we want to ping for (in centimeters) (default: 300) + void setMaxDistance(int value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + int _trigger_pin; + int _echo_pin; + int _max_distance = 300; + NewPing* _sonar; +}; +#endif + +/* + SensorSonoff +*/ +#if MODULE_SONOFF == 1 +class SensorSonoff: public Sensor { + public: + SensorSonoff(int child_id); + // set the button's pin (default: 0) + void setButtonPin(int value); + // set the relay's pin (default: 12) + void setRelayPin(int value); + // set the led's pin (default: 13) + void setLedPin(int value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + Bounce _debouncer = Bounce(); + int _button_pin = 0; + int _relay_pin = 12; + int _led_pin = 13; + int _old_value = 0; + bool _state = false; + int _relay_on = 1; + int _relay_off = 0; + int _led_on = 0; + int _led_off = 1; + void _blink(); + void _toggle(); +}; +#endif + +/* + SensorMCP9808 +*/ +#if MODULE_MCP9808 == 1 +class SensorMCP9808: public Sensor { + public: + SensorMCP9808(int child_id, Adafruit_MCP9808* mcp); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + Adafruit_MCP9808* _mcp; +}; +#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); + // send the same service message multiple times (default: 1) + void setRetries(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); + // after how many sleeping cycles report the battery level to the controller. When reset the battery is always reported (default: 10) + void setBatteryReportCycles(int value); + // if true, the battery level will be evaluated by measuring the internal vcc without the need to connect any pin, if false the voltage divider methon will be used (default: true) + void setBatteryInternalVcc(bool value); + // if setBatteryInternalVcc() is set to false, the analog pin to which the battery's vcc is attached (https://www.mysensors.org/build/battery) (default: -1) + void setBatteryPin(int value); + // if setBatteryInternalVcc() is set to false, the volts per bit ratio used to calculate the battery voltage (default: 0.003363075) + void setBatteryVoltsPerBit(float value); + // If true, wake up by an interrupt counts as a valid cycle for battery reports otherwise only uninterrupted sleep cycles would contribute (default: true) + void setBatteryReportWithInterrupt(bool value); + #endif + // define the way the node should behave. It can be IDLE (stay awake withtout executing each sensors' loop), SLEEP (go to sleep for the configured interval), WAIT (wait for the configured interval), ALWAYS_ON (stay awake and execute each sensors' loop) + void setSleepMode(int value); + void setMode(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 setSleepUnit(int value); + // configure the node's behavior, parameters are mode, time and unit + void setSleep(int value1, int value2, int value3); + // 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); + // 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); + // optionally sleep interval in milliseconds before sending each message to the radio network (default: 0) + void setSleepBetweenSend(int value); + // 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); + // un-register a sensor + void unRegisterSensor(int sensor_index); + // return a sensor by its index + Sensor* get(int sensor_index); + Sensor* getSensor(int sensor_index); + // assign a different child id to a sensor + bool renameSensor(int old_child_id, int new_child_id); + #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, int wait_time = 50); + // if enabled the pins will be automatically powered on while awake and off during sleeping (default: true) + void setAutoPowerPins(bool value); + // manually turn the power on + void powerOn(); + // manually turn the power off + void powerOff(); + #endif + // set this to true if you want destination node to send ack back to this node (default: false) + void setAck(bool value); + // request and return the current timestamp from the controller + long getTimestamp(); + // hook into the main sketch functions + void before(); + void presentation(); + void setup(); + void loop(); + void receive(const MyMessage & msg); + void receiveTime(unsigned long ts); + private: + #if BATTERY_MANAGER == 1 + float _battery_min = 2.6; + float _battery_max = 3.3; + int _battery_report_cycles = 10; + bool _battery_report_with_interrupt = true; + bool _battery_internal_vcc = true; + int _battery_pin = -1; + float _battery_volts_per_bit = 0.003363075; + int _cycles = 0; + float _getVcc(); + #endif + #if POWER_MANAGER == 1 + // to optionally controller power pins + PowerManager _powerManager; + bool _auto_power_pins = true; + #endif + MyMessage _msg; + void _send(MyMessage & msg); + int _sleep_mode = IDLE; + int _sleep_time = 0; + int _sleep_unit = MINUTES; + int _sleep_interrupt_pin = -1; + int _sleep_between_send = 0; + int _retries = 1; + 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 _last_interrupt_pin = -1; + long _timestamp = -1; + Sensor* _sensors[255] = {0}; + bool _ack = false; + void _process(const char * message); + void _sleep(); + void _present(int child_id, int type); + int _getAvailableChildId(); + int _getInterruptInitialValue(int mode); +}; + +#endif diff --git a/libraries/NodeManager/NodeManager.ino b/libraries/NodeManager/NodeManager.ino new file mode 100644 index 0000000..148442d --- /dev/null +++ b/libraries/NodeManager/NodeManager.ino @@ -0,0 +1,76 @@ +/* +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://github.com/mysensors/NodeManager + */ + + +// load user settings +#include "config.h" +// include supporting libraries +#ifdef MY_GATEWAY_ESP8266 + #include +#endif +// 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(MY_BAUD_RATE); + /* + * Register below your sensors + */ + + + + /* + * Register above your sensors + */ + nodeManager.before(); +} + +// presentation +void presentation() { + // call NodeManager presentation routine + nodeManager.presentation(); +} + +// setup +void setup() { + // call NodeManager setup routine + nodeManager.setup(); +} + +// loop +void loop() { + // call NodeManager loop routine + nodeManager.loop(); + +} + +// receive +void receive(const MyMessage &message) { + // call NodeManager receive routine + nodeManager.receive(message); +} + +// receiveTime +void receiveTime(unsigned long ts) { + // call NodeManager receiveTime routine + nodeManager.receiveTime(ts); +} + + diff --git a/libraries/NodeManager/README.md b/libraries/NodeManager/README.md new file mode 100644 index 0000000..f7a40c3 --- /dev/null +++ b/libraries/NodeManager/README.md @@ -0,0 +1,1100 @@ +# Introduction + +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 or clone the git repository at https://github.com/mysensors/NodeManager +* 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. + +## Upgrade +* Download the package +* Replace the NodeManager.cpp and NodeManager.h of your project with those just downloaded +* Review the release notes in case there is any manual change required to the existing sketch or config.h file + +# 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. For example: +~~~c +/********************************** + * Sketch configuration + */ + +#define SKETCH_NAME "NodeManagerTemplate" +#define SKETCH_VERSION "1.0" + +/********************************** + * MySensors node configuration + */ + +// General settings +#define MY_BAUD_RATE 9600 +//#define MY_DEBUG +//#define MY_NODE_ID 100 + +// NRF24 radio settings +#define MY_RADIO_NRF24 +//#define MY_RF24_ENABLE_ENCRYPTION +//#define MY_RF24_CHANNEL 76 +//#define MY_RF24_PA_LEVEL RF24_PA_HIGH + +// RFM69 radio settings +//#define MY_RADIO_RFM69 +//#define MY_RFM69_FREQUENCY RF69_868MHZ +//#define MY_IS_RFM69HW +//#define MY_RFM69_NEW_DRIVER +//#define MY_RFM69_ENABLE_ENCRYPTION +//#define MY_RFM69_NETWORKID 100 +//#define MY_RF69_IRQ_PIN D1 +//#define MY_RF69_IRQ_NUM MY_RF69_IRQ_PIN +//#define MY_RF69_SPI_CS D2 + +/********************************** + * MySensors gateway configuration + */ +// Common gateway settings +//#define MY_REPEATER_FEATURE + +// Serial gateway settings +//#define MY_GATEWAY_SERIAL + +// Ethernet gateway settings +//#define MY_GATEWAY_W5100 + +// ESP8266 gateway settings +//#define MY_GATEWAY_ESP8266 +//#define MY_ESP8266_SSID "MySSID" +//#define MY_ESP8266_PASSWORD "MyVerySecretPassword" + +// Gateway networking settings +//#define MY_IP_ADDRESS 192,168,178,87 +//#define MY_IP_GATEWAY_ADDRESS 192,168,178,1 +//#define MY_IP_SUBNET_ADDRESS 255,255,255,0 +//#define MY_PORT 5003 +//#define MY_GATEWAY_MAX_CLIENTS 2 +//#define MY_USE_UDP + +// Gateway MQTT settings +//#define MY_GATEWAY_MQTT_CLIENT +//#define MY_CONTROLLER_IP_ADDRESS 192, 168, 178, 68 +//#define MY_PORT 1883 +//#define MY_MQTT_USER "username" +//#define MY_MQTT_PASSWORD "password" +//#define MY_MQTT_CLIENT_ID "mysensors-1" +//#define MY_MQTT_PUBLISH_TOPIC_PREFIX "mygateway1-out" +//#define MY_MQTT_SUBSCRIBE_TOPIC_PREFIX "mygateway1-in" + +// Gateway inclusion mode +//#define MY_INCLUSION_MODE_FEATURE +//#define MY_INCLUSION_BUTTON_FEATURE +//#define MY_INCLUSION_MODE_DURATION 60 +//#define MY_DEFAULT_LED_BLINK_PERIOD 300 + +// Gateway Leds settings +//#define MY_DEFAULT_ERR_LED_PIN 4 +//#define MY_DEFAULT_RX_LED_PIN 5 +//#define MY_DEFAULT_TX_LED_PIN 6 +~~~ + +## 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, 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 and STARTED when starting/rebooting +#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, SENSOR_MQ, SENSOR_ML8511, SENSOR_ACS712, SENSOR_RAIN_GAUGE +#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 +// Enable this module to use one of the following sensors: SENSOR_BH1750 +#define MODULE_BH1750 0 +// Enable this module to use one of the following sensors: SENSOR_MLX90614 +#define MODULE_MLX90614 0 +// Enable this module to use one of the following sensors: SENSOR_BME280 +#define MODULE_BME280 0 +// Enable this module to use one of the following sensors: SENSOR_SONOFF +#define MODULE_SONOFF 0 +// Enable this module to use one of the following sensors: SENSOR_BMP085 +#define MODULE_BMP085 0 +// Enable this module to use one of the following sensors: SENSOR_HCSR04 +#define MODULE_HCSR04 0 +// Enable this module to use one of the following sensors: SENSOR_MCP9808 +#define MODULE_MCP9808 0 +~~~ + +## Installing the dependencies + +Some of the modules above rely on third party libraries. Those libraries are not included within NodeManager and have to be installed from the Arduino IDE Library Manager (Sketch -> Include Library -> Manager Libraries). You need to install the library ONLY if the module is enabled: + +Module | Required Library + ------------- | ------------- +MODULE_SHT21 | https://github.com/SodaqMoja/Sodaq_SHT2x +MODULE_DHT | https://github.com/adafruit/DHT-sensor-library +MODULE_DS18B20 | https://github.com/milesburton/Arduino-Temperature-Control-Library +MODULE_BH1750 | https://github.com/claws/BH1750 +MODULE_MLX90614 | https://github.com/adafruit/Adafruit-MLX90614-Library +MODULE_BME280 | https://github.com/adafruit/Adafruit_BME280_Library +MODULE_SONOFF | https://github.com/thomasfredericks/Bounce2 +MODULE_BMP085 | https://github.com/adafruit/Adafruit-BMP085-Library +MODULE_HCSR04 | https://github.com/mysensors/MySensorsArduinoExamples/tree/master/libraries/NewPing +MODULE_MCP9808 | https://github.com/adafruit/Adafruit_MCP9808_Library + +## 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 + // send the same service message multiple times (default: 1) + void setRetries(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); + // after how many sleeping cycles report the battery level to the controller. When reset the battery is always reported (default: 10) + void setBatteryReportCycles(int value); + // if true, the battery level will be evaluated by measuring the internal vcc without the need to connect any pin, if false the voltage divider methon will be used (default: true) + void setBatteryInternalVcc(bool value); + // if setBatteryInternalVcc() is set to false, the analog pin to which the battery's vcc is attached (https://www.mysensors.org/build/battery) (default: -1) + void setBatteryPin(int value); + // if setBatteryInternalVcc() is set to false, the volts per bit ratio used to calculate the battery voltage (default: 0.003363075) + void setBatteryVoltsPerBit(float value); + // If true, wake up by an interrupt counts as a valid cycle for battery reports otherwise only uninterrupted sleep cycles would contribute (default: true) + void setBatteryReportWithInterrupt(bool value); + #endif + // define the way the node should behave. It can be IDLE (stay awake withtout executing each sensors' loop), SLEEP (go to sleep for the configured interval), WAIT (wait for the configured interval), ALWAYS_ON (stay awake and execute each sensors' loop) + void setSleepMode(int value); + void setMode(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 setSleepUnit(int value); + // configure the node's behavior, parameters are mode, time and unit + void setSleep(int value1, int value2, int value3); + // 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); + // optionally sleep interval in milliseconds before sending each message to the radio network (default: 0) + void setSleepBetweenSend(int value); + // set the interrupt pin the sensor is attached to so its loop() will be executed only upon that interrupt (default: -1) + void setInterruptPin(int value); + // register a built-in sensor + int registerSensor(int sensor_type, int pin = -1, int child_id = -1); + // un-register a sensor + void unRegisterSensor(int sensor_index); + // register a custom sensor + int registerSensor(Sensor* sensor); + // return a sensor by its index + Sensor* get(int sensor_index); + Sensor* getSensor(int sensor_index); + // assign a different child id to a sensor + bool renameSensor(int old_child_id, int new_child_id); + #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); + // if enabled the pins will be automatically powered on while awake and off during sleeping (default: true) + void setAutoPowerPins(bool value); + // manually turn the power on + void powerOn(); + // manually turn the power off + void powerOff(); + #endif + // set this to true if you want destination node to send ack back to this node (default: false) + void setAck(bool value); + // request and return the current timestamp from the controller + long getTimestamp(); +~~~ + +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 +SENSOR_HTU21D | HTU21D sensor, return temperature/humidity based on the attached HTU21D sensor +SENSOR_BH1750 | BH1750 sensor, return light level in lux +SENSOR_MLX90614 | MLX90614 contactless temperature sensor, return ambient and object temperature +SENSOR_BME280 | BME280 sensor, return temperature/humidity/pressure based on the attached BME280 sensor +SENSOR_MQ | MQ sensor, return ppm of the target gas +SENSOR_ML8511 | ML8511 sensor, return UV intensity +SENSOR_SONOFF | Sonoff wireless smart switch +SENSOR_BMP085 | BMP085/BMP180 sensor, return temperature and pressure +SENSOR_HCSR04 | HC-SR04 sensor, return the distance between the sensor and an object +SENSOR_ACS712 | ACS712 sensor, measure the current going through the attached module +SENSOR_MCP9808 | MCP9808 sensor, measure the temperature through the attached module +SENSOR_RAIN_GAUGE | Rain gauge 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. An optional child id can be provided as a third argument if you want to assign it manually. 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 setup() by executing the sensor's main task + void onSetup(); + // 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.getSensor(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.getSensor(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); + 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(); + // description of the sensor (default: '') + void setDescription(char *value); + // set this to true if you want destination node to send ack back to this node (default: false) + void setAck(bool 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); + int getValueType(); + // for float values, set the float precision (default: 2) + void setFloatPrecision(int value); + // optionally sleep interval in milliseconds before sending each message to the radio network (default: 0) + void setSleepBetweenSend(int value); + // set the interrupt pin the sensor is attached to so its loop() will be executed only upon that interrupt (default: -1) + void setInterruptPin(int value); + int getInterruptPin(); + #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); + // if enabled the pins will be automatically powered on while awake and off during sleeping (default: true) + void setAutoPowerPins(bool value); + // manually turn the power on + void powerOn(); + // manually turn the power off + void powerOff(); + #endif + // get the latest recorded value from the sensor + int getValueInt(); + float getValueFloat(); + char* getValueString(); +~~~ + +### 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(long 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(long value); + // set a temperature offset + void setOffset(float value); +~~~ + +#### SensorMQ +~~~c + // define the target gas whose ppm has to be returned. 0: LPG, 1: CO, 2: Smoke (default: 1); + void setTargetGas(int value); + // define the load resistance on the board, in kilo ohms (default: 1); + void setRlValue(float value); + // define the Ro resistance on the board (default: 10000); + void setRoValue(float value); + // Sensor resistance in clean air (default: 9.83); + void setCleanAirFactor(float value); + // define how many samples you are going to take in the calibration phase (default: 50); + void setCalibrationSampleTimes(int value); + // define the time interal(in milisecond) between each samples in the cablibration phase (default: 500); + void setCalibrationSampleInterval(int value); + // define how many samples you are going to take in normal operation (default: 50); + void setReadSampleTimes(int value); + // define the time interal(in milisecond) between each samples in the normal operations (default: 5); + void setReadSampleInterval(int value); + // set the LPGCurve array (default: {2.3,0.21,-0.47}) + void setLPGCurve(float *value); + // set the COCurve array (default: {2.3,0.72,-0.34}) + void setCOCurve(float *value); + // set the SmokeCurve array (default: {2.3,0.53,-0.44}) + void setSmokeCurve(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); + // define which value to set to the output when set to on (default: HIGH) + void setOnValue(int value); + // when legacy mode is enabled expect a REQ message to trigger, otherwise the default SET (default: false) + void setLegacyMode(bool 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); + // Set initial value on the interrupt pin (default: HIGH) + void setInitial(int value); +~~~ + +#### SensorDs18b20 +~~~c + // return the sensors' device address + DeviceAddress* getDeviceAddress(); + // returns the sensor's resolution in bits + int getResolution(); + // set the sensor's resolution in bits + void setResolution(int value); + // sleep while DS18B20 calculates temperature (default: false) + void setSleepDuringConversion(bool value); +~~~ + +#### SensorBME280 +~~~c + // define how many pressure samples to keep track of for calculating the forecast (default: 5) + void setForecastSamplesCount(int value); +~~~ + +#### SensorSonoff +~~~c + // set the button's pin (default: 0) + void setButtonPin(int value); + // set the relay's pin (default: 12) + void setRelayPin(int value); + // set the led's pin (default: 13) + void setLedPin(int value); +~~~ + +#### SensorBMP085 +~~~c + // define how many pressure samples to keep track of for calculating the forecast (default: 5) + void setForecastSamplesCount(int value); +~~~ + +#### SensorHCSR04 +~~~c + // Arduino pin tied to trigger pin on the ultrasonic sensor (default: the pin set while registering the sensor) + void setTriggerPin(int value); + // Arduino pin tied to echo pin on the ultrasonic sensor (default: the pin set while registering the sensor) + void setEchoPin(int value); + // Maximum distance we want to ping for (in centimeters) (default: 300) + void setMaxDistance(int value); +~~~ + +#### SensorACS712 +~~~c + // set how many mV are equivalent to 1 Amp. The value depends on the module (100 for 20A Module, 66 for 30A Module) (default: 185); + void setmVPerAmp(int value); + // set ACS offset (default: 2500); + void setOffset(int value); +~~~ + +#### SensorRainGauge +~~~c + // set how frequently to report back to the controller in minutes. After reporting the measure is resetted (default: 60); + void setReportInterval(int value); + // set how many mm of rain to count for each tip (default: 0.11); + void setSingleTip(float 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 node behaves. 0: stay awake withtout executing each sensors' loop(), 1: go to sleep for the configured interval, 2: wait for the configured interval, 3: stay awake and execute each sensors' loop() +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() +* 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::setup() +* Send a custom message with a STARTED payload to the controller +* Call `setup()` of each registered sensor + +### Sensor::setup() +* Call sensor-specific implementation of setup by invoking `onSetup()` 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()` + +# Examples +All the examples below takes place within the before() function in the main sketch, just below the "Register below your sensors" comment. + +Set battery minimum and maxium voltage. This will be used to calculate the level percentage: + +~~~c + nodeManager.setBatteryMin(1.8); + nodeManager.setBatteryMin(3.2); +~~~ + +Instruct the board to sleep for 10 minutes at each cycle: + +~~~c + nodeManager.setSleep(SLEEP,10,MINUTES); +~~~ + +Configure a wake up pin. When pin 3 is connected to ground, the board will stop sleeping: + +~~~c + nodeManager.setSleepInterruptPin(3); +~~~ + +Use the arduino pins to power on and off the attached sensors. All the sensors' vcc and ground are connected to pin 6 (ground) and 7 (vcc). NodeManager will enable the vcc pin every time just before loop() and wait for 100ms for the power to settle before running loop() of each sensor: + +~~~c + nodeManager.setPowerPins(6,7,100); +~~~ + +Register a thermistor sensor attached to pin A2. NodeManager will then send the temperature to the controller at the end of each sleeping cycle: + +~~~c + nodeManager.registerSensor(SENSOR_THERMISTOR,A2); +~~~ + +Register a SHT21 temperature/humidity sensor; since using i2c for communicating with the sensor, the pins used are implicit (A4 and A5). NodeManager will then send the temperature and the humidity to the controller at the end of each sleeping cycle: + +~~~c + nodeManager.registerSensor(SENSOR_SHT21); +~~~ + +Register a LDR sensor attached to pin A1 and send to the gateway the average of 3 samples: + +~~~c + int sensor_ldr = nodeManager.registerSensor(SENSOR_LDR,A1); + ((SensorLDR*)nodeManager.getSensor(sensor_ldr))->setSamples(3); +~~~ + +Register a rain sensor connected to A0. This will be powered with via pins 4 (ground) and 5 (vcc) just before reading its value at each cycle, it will be presented as S_RAIN. sending V_RAINRATE messages, the output will be a percentage (calculated between 200 and 1024) and the value will be reversed (so that no rain will be 0%): + +~~~c + int rain = nodeManager.registerSensor(SENSOR_ANALOG_INPUT,A0); + SensorAnalogInput* rainSensor = ((SensorAnalogInput*)nodeManager.getSensor(rain)); + rainSensor->setPowerPins(4,5,300); + rainSensor->setPresentation(S_RAIN); + rainSensor->setType(V_RAINRATE); + rainSensor->setOutputPercentage(true); + rainSensor->setRangeMin(200); + rainSensor->setRangeMax(1024); + rainSensor->setReverse(true); +~~~ + +Register a latching relay connecting to pin 6 (set) and pin 7 (unset): + +~~~c + nodeManager.registerSensor(SENSOR_LATCHING_RELAY,6); + nodeManager.registerSensor(SENSOR_LATCHING_RELAY,7); +~~~ + +# Example Sketches + +## Analog Light and Temperature Sensor + +The following sketch can be used to report the temperature and the light level based on a thermistor and LDR sensors attached to two analog pins of the arduino board (A1 and A2). Both the thermistor and the LDR are connected to ground on one side and to vcc via a resistor on the other so to measure the voltage drop across each of them through the analog pins. + +The sensor will be put to sleep after startup and will report both the measures every 10 minutes. NodeManager will take care of presenting the sensors, managing the sleep cycle, reporting the battery level every 10 cycles and report the measures in the appropriate format. This sketch requires MODULE_ANALOG_INPUT enabled in the global config.h file. + +Even if the sensor is sleeping most of the time, it can be potentially woke up by sending a V_CUSTOM message with a WAKEUP payload to NodeManager service child id (200 by default) just after having reported its heartbeat. At this point the node will report AWAKE and the user can interact with it by e.g. sending REQ messages to its child IDs, changing the duration of a sleep cycle with a V_CUSTOM message to the NodeManager service child id, etc. + +~~~c +/* +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://github.com/mysensors/NodeManager + */ + + +// 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(MY_BAUD_RATE); + /* + * Register below your sensors + */ + nodeManager.setSleep(SLEEP,10,MINUTES); + nodeManager.registerSensor(SENSOR_THERMISTOR,A1); + nodeManager.registerSensor(SENSOR_LDR,A2); + /* + * Register above your sensors + */ + nodeManager.before(); +} + +// presentation +void presentation() { + // Send the sketch version information to the gateway and Controller + sendSketchInfo(SKETCH_NAME,SKETCH_VERSION); + // call NodeManager presentation routine + nodeManager.presentation(); + +} + +// setup +void setup() { + // call NodeManager setup routine + nodeManager.setup(); +} + +// loop +void loop() { + // call NodeManager loop routine + nodeManager.loop(); + +} + +// receive +void receive(const MyMessage &message) { + // call NodeManager receive routine + nodeManager.receive(message); +} +~~~ + +## Motion Sensor + +The following sketch can be used to report back to the controller when a motion sensor attached to the board's pin 3 triggers. In this example, the board will be put to sleep just after startup and will report a heartbeat every hour. NodeManager will take care of configuring an interrupt associated to the provided pin so automatically wake up when a motion is detected and report a V_TRIPPED message back. This sketch requires MODULE_SWITCH to be enabled in the global config.h file. + +~~~c +/* +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://github.com/mysensors/NodeManager + */ + + +// 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(MY_BAUD_RATE); + /* + * Register below your sensors + */ + nodeManager.setSleep(SLEEP,60,MINUTES); + nodeManager.registerSensor(SENSOR_MOTION,3); + + /* + * Register above your sensors + */ + nodeManager.before(); +} + +// presentation +void presentation() { + // Send the sketch version information to the gateway and Controller + sendSketchInfo(SKETCH_NAME,SKETCH_VERSION); + // call NodeManager presentation routine + nodeManager.presentation(); + +} + +// setup +void setup() { + // call NodeManager setup routine + nodeManager.setup(); +} + +// loop +void loop() { + // call NodeManager loop routine + nodeManager.loop(); + +} + +// receive +void receive(const MyMessage &message) { + // call NodeManager receive routine + nodeManager.receive(message); +} +~~~ + +## Boiler Sensor + +The following sketch controls a latching relay connected to a boiler. A latching relay (requiring only a pulse to switch) has been chosen to minimize the power consumption required by a traditional relay to stay on. This relay has normally two pins, one for closing and the other for opening the controlled circuit, connected to pin 6 and 7 of the arduino board. This is why we have to register two sensors against NodeManager so to control the two funtions indipendently. Since using a SENSOR_LATCHING_RELAY type of sensor, NodeManager will take care of just sending out a single pulse only when a REQ command of type V_STATUS is sent to one or the other child id. + +In this example, the board also runs at 1Mhz so it can go down to 1.8V: by setting setBatteryMin() and setBatteryMax(), the battery percentage will be calculated and reported (by default, automatically every 10 sleeping cycles) based on these custom boundaries. + +The board will be put to sleep just after startup and will report back to the controller every 5 minutes. It is the controller's responsability to catch when the board reports its heartbeat (using smart sleep behind the scene) and send a command back if needed. This sketch requires MODULE_DIGITAL_OUTPUT to be enabled in the config.h file. + +~~~c +/* +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://github.com/mysensors/NodeManager + */ + + +// 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(MY_BAUD_RATE); + /* + * Register below your sensors + */ + nodeManager.setBatteryMin(1.8); + nodeManager.setBatteryMax(3.2); + nodeManager.setSleep(SLEEP,5,MINUTES); + nodeManager.registerSensor(SENSOR_LATCHING_RELAY,6); + nodeManager.registerSensor(SENSOR_LATCHING_RELAY,7); + + /* + * Register above your sensors + */ + nodeManager.before(); +} + +// presentation +void presentation() { + // Send the sketch version information to the gateway and Controller + sendSketchInfo(SKETCH_NAME,SKETCH_VERSION); + // call NodeManager presentation routine + nodeManager.presentation(); + +} + +// setup +void setup() { + // call NodeManager setup routine + nodeManager.setup(); +} + +// loop +void loop() { + // call NodeManager loop routine + nodeManager.loop(); + +} + +// receive +void receive(const MyMessage &message) { + // call NodeManager receive routine + nodeManager.receive(message); +} +~~~ + + +## Rain and Soil Moisture Sensor + +The following sketch can be used to report the rain level and the soil moisture based on two sensors connected to the board's analog pins (A1 and A2). In this case we are customizing the out-of-the-box SENSOR_ANALOG_INPUT sensor type since we just need to measure an analog input but we also want to provide the correct type and presentation for each sensor. + +We register the sensors first with registerSensor() which returns the child id assigned to the sensor. We then retrieve the sensor's reference by calling getSensor() so we can invoke the sensor-specific functions, like setPresentation() and setType(). + +In this example, the two sensors are not directly connected to the battery's ground and vcc but, to save additional power, are powered through two arduino's pins. By using e.g. setPowerPins(4,5,300), NodeManger will assume pin 4 is ground and pin 5 is vcc for that specific sensor so it will turn on the power just before reading the analog input (and waiting 300ms for the sensor to initialize) and back off before going to sleep. + +For both the sensors we want a percentage output and with setRangeMin() and setRangeMax() we define the boundaries for calculating the percentage (if we read e.g. 200 when the rain sensor is completely into the water, we know for sure it will not go below this value which will represent the new lower boundary). +Finally, since both the sensors reports low when wet and high when dry but we need the opposite, we set setReverse() so to have 0% reported when there is no rain/moisture, 100% on the opposite situation. + +~~~c +/* +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://github.com/mysensors/NodeManager + */ + + +// 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(MY_BAUD_RATE); + /* + * Register below your sensors + */ + analogReference(DEFAULT); + nodeManager.setSleep(SLEEP,10,MINUTES); + + int rain = nodeManager.registerSensor(SENSOR_ANALOG_INPUT,A1); + int soil = nodeManager.registerSensor(SENSOR_ANALOG_INPUT,A2); + + SensorAnalogInput* rainSensor = ((SensorAnalogInput*)nodeManager.getSensor(rain)); + SensorAnalogInput* soilSensor = ((SensorAnalogInput*)nodeManager.getSensor(soil)); + + rainSensor->setPresentation(S_RAIN); + rainSensor->setType(V_RAINRATE); + rainSensor->setPowerPins(4,5,300); + rainSensor->setOutputPercentage(true); + rainSensor->setRangeMin(200); + rainSensor->setRangeMax(1024); + rainSensor->setReverse(true); + + soilSensor->setPresentation(S_MOISTURE); + soilSensor->setType(V_LEVEL); + soilSensor->setPowerPins(6,7,300); + soilSensor->setOutputPercentage(true); + soilSensor->setRangeMin(300); + soilSensor->setRangeMax(1024); + soilSensor->setReverse(true); + + /* + * Register above your sensors + */ + nodeManager.before(); +} + +// presentation +void presentation() { + // Send the sketch version information to the gateway and Controller + sendSketchInfo(SKETCH_NAME,SKETCH_VERSION); + // call NodeManager presentation routine + nodeManager.presentation(); + +} + +// setup +void setup() { + // call NodeManager setup routine + nodeManager.setup(); +} + +// loop +void loop() { + // call NodeManager loop routine + nodeManager.loop(); + +} + +// receive +void receive(const MyMessage &message) { + // call NodeManager receive routine + nodeManager.receive(message); +} +~~~ + +# Release Notes + +v1.0: + +* Initial release + +v1.1: +* Added ability to sleep between send() so to save additional battery +* Bug fixes + +v1.2: + +* Added out-of-the-box support for BH1750 light sensor +* Added out-of-the-box support for HTU21D temperature and humidity sensor +* Added out-of-the-box support for MLX90614 contactless temperature sensor +* Added a few examples to the documentation +* Fixed a few bugs + +v1.3: + +* Added support for BME280 temperature/humudity/pressure sensor +* Added option to measure battery level via a pin in addition to internal Vcc +* Added example sketches to the documentation +* Fixed a few bugs + +v1.4: + +* Added support for ML8511 UV intensity sensor +* Added support for MQ air quality sensor +* Added ability to manually assign a child id to a sensor +* Ensured compatibility for non-sleeping nodes +* Ability to control if waking up from an interrupt counts for a battery level report +* When power pins are set the sensor is powered on just after +* Service messages are disabled by default +* Bug fixes + +v1.5: + +* Added support for ACS712 current sensor +* Added support for HC-SR04 distance sensor +* Added support for BMP085/BMP180 temperature and pressure sensor +* Added support for Sonoff smart switch +* Added support for Rain Gauge sensor +* Added support for MCP9808 temperature sensor +* Added forecast output to all Bosch sensors +* Added I2C address auto-discovery for all Bosch sensors +* Added support for running as a gateway +* Added option to retrieve the latest value of a sensor from outside NodeManager +* Remote reboot now does not need a reboot pin configured +* A heartbeat is now sent also when waking up from a wait cycle +* When waking up for an interrupt, only the code of the sensor expecting that interrupt is executed +* Added capability to retrieve the time from the controller +* Optimized battery life for DS18B20 sensors +* SLEEP_MANAGER has been deprecated (now always enabled) and setMode() replaces setSleepMode() +* New mode ALWAYS_ON to let the node staying awake and executing each sensors' loop +* ESP8266WiFi.h has to be included in the main sketch if MY_GATEWAY_ESP8266 is defined +* Added receiveTime() wrapper in the main sketch +* Fixed the logic for output sensors +* Added common gateway settings in config.h \ No newline at end of file diff --git a/libraries/NodeManager/config.h b/libraries/NodeManager/config.h new file mode 100644 index 0000000..eded817 --- /dev/null +++ b/libraries/NodeManager/config.h @@ -0,0 +1,134 @@ +#ifndef config_h +#define config_h + +/********************************** + * Sketch configuration + */ + +#define SKETCH_NAME "NodeManager" +#define SKETCH_VERSION "1.0" + +/********************************** + * MySensors node configuration + */ + +// General settings +#define MY_BAUD_RATE 9600 +//#define MY_DEBUG +//#define MY_NODE_ID 100 + +// NRF24 radio settings +#define MY_RADIO_NRF24 +//#define MY_RF24_ENABLE_ENCRYPTION +//#define MY_RF24_CHANNEL 76 +//#define MY_RF24_PA_LEVEL RF24_PA_HIGH +//#define MY_DEBUG_VERBOSE_RF24 + +// RFM69 radio settings +//#define MY_RADIO_RFM69 +//#define MY_RFM69_FREQUENCY RF69_868MHZ +//#define MY_IS_RFM69HW +//#define MY_DEBUG_VERBOSE_RFM69 +//#define MY_RFM69_NEW_DRIVER +//#define MY_RFM69_ENABLE_ENCRYPTION +//#define MY_RFM69_NETWORKID 100 +//#define MY_RF69_IRQ_PIN D1 +//#define MY_RF69_IRQ_NUM MY_RF69_IRQ_PIN +//#define MY_RF69_SPI_CS D2 + +/********************************** + * MySensors gateway configuration + */ +// Common gateway settings +//#define MY_REPEATER_FEATURE + +// Serial gateway settings +//#define MY_GATEWAY_SERIAL + +// Ethernet gateway settings +//#define MY_GATEWAY_W5100 + +// ESP8266 gateway settings +//#define MY_GATEWAY_ESP8266 +//#define MY_ESP8266_SSID "" +//#define MY_ESP8266_PASSWORD "" + +// Gateway networking settings +//#define MY_IP_ADDRESS 192,168,178,87 +//#define MY_IP_GATEWAY_ADDRESS 192,168,178,1 +//#define MY_IP_SUBNET_ADDRESS 255,255,255,0 +//#define MY_PORT 5003 +//#define MY_GATEWAY_MAX_CLIENTS 2 +//#define MY_USE_UDP + +// Gateway MQTT settings +//#define MY_GATEWAY_MQTT_CLIENT +//#define MY_CONTROLLER_IP_ADDRESS 192, 168, 178, 68 +//#define MY_PORT 1883 +//#define MY_MQTT_USER "username" +//#define MY_MQTT_PASSWORD "password" +//#define MY_MQTT_CLIENT_ID "mysensors-1" +//#define MY_MQTT_PUBLISH_TOPIC_PREFIX "mygateway1-out" +//#define MY_MQTT_SUBSCRIBE_TOPIC_PREFIX "mygateway1-in" + +// Gateway inclusion mode +//#define MY_INCLUSION_MODE_FEATURE +//#define MY_INCLUSION_BUTTON_FEATURE +//#define MY_INCLUSION_MODE_DURATION 60 +//#define MY_DEFAULT_LED_BLINK_PERIOD 300 + +// Gateway Leds settings +//#define MY_DEFAULT_ERR_LED_PIN 4 +//#define MY_DEFAULT_RX_LED_PIN 5 +//#define MY_DEFAULT_TX_LED_PIN 6 + +/*********************************** + * NodeManager configuration + */ + +// if enabled, enable debug messages on serial port +#define DEBUG 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 remote configuration settings on EEPROM +#define PERSIST 0 +// 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 +// if enabled, send a SLEEPING and AWAKE service messages just before entering and just after leaving a sleep cycle and STARTED when starting/rebooting +#define SERVICE_MESSAGES 0 + +// Enable this module to use one of the following sensors: SENSOR_ANALOG_INPUT, SENSOR_LDR, SENSOR_THERMISTOR, SENSOR_MQ, SENSOR_ML8511, SENSOR_ACS712, SENSOR_RAIN_GAUGE +#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_DHT11, SENSOR_DHT22 +#define MODULE_DHT 0 +// 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_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 +// Enable this module to use one of the following sensors: SENSOR_BH1750 +#define MODULE_BH1750 0 +// Enable this module to use one of the following sensors: SENSOR_MLX90614 +#define MODULE_MLX90614 0 +// Enable this module to use one of the following sensors: SENSOR_BME280 +#define MODULE_BME280 0 +// Enable this module to use one of the following sensors: SENSOR_SONOFF +#define MODULE_SONOFF 0 +// Enable this module to use one of the following sensors: SENSOR_BMP085 +#define MODULE_BMP085 0 +// Enable this module to use one of the following sensors: SENSOR_HCSR04 +#define MODULE_HCSR04 0 +// Enable this module to use one of the following sensors: SENSOR_MCP9808 +#define MODULE_MCP9808 0 +#endif + diff --git a/temp_hum_sensor/lib/DHT/DHT.cpp b/temp_hum_sensor/lib/DHT/DHT.cpp deleted file mode 100644 index 525e32a..0000000 --- a/temp_hum_sensor/lib/DHT/DHT.cpp +++ /dev/null @@ -1,206 +0,0 @@ -/****************************************************************** - DHT Temperature & Humidity Sensor library for Arduino. - - Features: - - Support for DHT11 and DHT22/AM2302/RHT03 - - Auto detect sensor model - - Very low memory footprint - - Very small code - - http://www.github.com/markruys/arduino-DHT - - Written by Mark Ruys, mark@paracas.nl. - - BSD license, check license.txt for more information. - All text above must be included in any redistribution. - - Datasheets: - - http://www.micro4you.com/files/sensor/DHT11.pdf - - http://www.adafruit.com/datasheets/DHT22.pdf - - http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/Weather/RHT03.pdf - - http://meteobox.tk/files/AM2302.pdf - - Changelog: - 2013-06-10: Initial version - 2013-06-12: Refactored code - 2013-07-01: Add a resetTimer method - ******************************************************************/ - -#include "DHT.h" - -void DHT::setup(uint8_t pin, DHT_MODEL_t model) -{ - DHT::pin = pin; - DHT::model = model; - DHT::resetTimer(); // Make sure we do read the sensor in the next readSensor() - - if ( model == AUTO_DETECT) { - DHT::model = DHT22; - readSensor(); - if ( error == ERROR_TIMEOUT ) { - DHT::model = DHT11; - // Warning: in case we auto detect a DHT11, you should wait at least 1000 msec - // before your first read request. Otherwise you will get a time out error. - } - } -} - -void DHT::resetTimer() -{ - DHT::lastReadTime = millis() - 3000; -} - -float DHT::getHumidity() -{ - readSensor(); - return humidity; -} - -float DHT::getTemperature() -{ - readSensor(); - return temperature; -} - -#ifndef OPTIMIZE_SRAM_SIZE - -const char* DHT::getStatusString() -{ - switch ( error ) { - case DHT::ERROR_TIMEOUT: - return "TIMEOUT"; - - case DHT::ERROR_CHECKSUM: - return "CHECKSUM"; - - default: - return "OK"; - } -} - -#else - -// At the expense of 26 bytes of extra PROGMEM, we save 11 bytes of -// SRAM by using the following method: - -prog_char P_OK[] PROGMEM = "OK"; -prog_char P_TIMEOUT[] PROGMEM = "TIMEOUT"; -prog_char P_CHECKSUM[] PROGMEM = "CHECKSUM"; - -const char *DHT::getStatusString() { - prog_char *c; - switch ( error ) { - case DHT::ERROR_CHECKSUM: - c = P_CHECKSUM; break; - - case DHT::ERROR_TIMEOUT: - c = P_TIMEOUT; break; - - default: - c = P_OK; break; - } - - static char buffer[9]; - strcpy_P(buffer, c); - - return buffer; -} - -#endif - -void DHT::readSensor() -{ - // Make sure we don't poll the sensor too often - // - Max sample rate DHT11 is 1 Hz (duty cicle 1000 ms) - // - Max sample rate DHT22 is 0.5 Hz (duty cicle 2000 ms) - unsigned long startTime = millis(); - if ( (unsigned long)(startTime - lastReadTime) < (model == DHT11 ? 999L : 1999L) ) { - return; - } - lastReadTime = startTime; - - temperature = NAN; - humidity = NAN; - - // Request sample - - digitalWrite(pin, LOW); // Send start signal - pinMode(pin, OUTPUT); - if ( model == DHT11 ) { - delay(18); - } - else { - // This will fail for a DHT11 - that's how we can detect such a device - delayMicroseconds(800); - } - - pinMode(pin, INPUT); - digitalWrite(pin, HIGH); // Switch bus to receive data - - // We're going to read 83 edges: - // - First a FALLING, RISING, and FALLING edge for the start bit - // - Then 40 bits: RISING and then a FALLING edge per bit - // To keep our code simple, we accept any HIGH or LOW reading if it's max 85 usecs long - - uint16_t rawHumidity = 0; - uint16_t rawTemperature = 0; - uint16_t data = 0; - - for ( int8_t i = -3 ; i < 2 * 40; i++ ) { - byte age; - startTime = micros(); - - do { - age = (unsigned long)(micros() - startTime); - if ( age > 90 ) { - error = ERROR_TIMEOUT; - return; - } - } - while ( digitalRead(pin) == (i & 1) ? HIGH : LOW ); - - if ( i >= 0 && (i & 1) ) { - // Now we are being fed our 40 bits - data <<= 1; - - // A zero max 30 usecs, a one at least 68 usecs. - if ( age > 30 ) { - data |= 1; // we got a one - } - } - - switch ( i ) { - case 31: - rawHumidity = data; - break; - case 63: - rawTemperature = data; - data = 0; - break; - } - } - - // Verify checksum - - if ( (byte)(((byte)rawHumidity) + (rawHumidity >> 8) + ((byte)rawTemperature) + (rawTemperature >> 8)) != data ) { - error = ERROR_CHECKSUM; - return; - } - - // Store readings - - if ( model == DHT11 ) { - humidity = rawHumidity >> 8; - temperature = rawTemperature >> 8; - } - else { - humidity = rawHumidity * 0.1; - - if ( rawTemperature & 0x8000 ) { - rawTemperature = -(int16_t)(rawTemperature & 0x7FFF); - } - temperature = ((int16_t)rawTemperature) * 0.1; - } - - error = ERROR_NONE; -} diff --git a/temp_hum_sensor/lib/DHT/DHT.h b/temp_hum_sensor/lib/DHT/DHT.h deleted file mode 100644 index 9e24518..0000000 --- a/temp_hum_sensor/lib/DHT/DHT.h +++ /dev/null @@ -1,96 +0,0 @@ -/****************************************************************** - DHT Temperature & Humidity Sensor library for Arduino. - - Features: - - Support for DHT11 and DHT22/AM2302/RHT03 - - Auto detect sensor model - - Very low memory footprint - - Very small code - - http://www.github.com/markruys/arduino-DHT - - Written by Mark Ruys, mark@paracas.nl. - - BSD license, check license.txt for more information. - All text above must be included in any redistribution. - - Datasheets: - - http://www.micro4you.com/files/sensor/DHT11.pdf - - http://www.adafruit.com/datasheets/DHT22.pdf - - http://dlnmh9ip6v2uc.cloudfront.net/datasheets/Sensors/Weather/RHT03.pdf - - http://meteobox.tk/files/AM2302.pdf - - Changelog: - 2013-06-10: Initial version - 2013-06-12: Refactored code - 2013-07-01: Add a resetTimer method - ******************************************************************/ - -#ifndef dht_h -#define dht_h - -#if ARDUINO < 100 - #include -#else - #include -#endif - -class DHT -{ -public: - - typedef enum { - AUTO_DETECT, - DHT11, - DHT22, - AM2302, // Packaged DHT22 - RHT03 // Equivalent to DHT22 - } - DHT_MODEL_t; - - typedef enum { - ERROR_NONE = 0, - ERROR_TIMEOUT, - ERROR_CHECKSUM - } - DHT_ERROR_t; - - void setup(uint8_t pin, DHT_MODEL_t model=AUTO_DETECT); - void resetTimer(); - - float getTemperature(); - float getHumidity(); - - DHT_ERROR_t getStatus() { return error; }; - const char* getStatusString(); - - DHT_MODEL_t getModel() { return model; } - - int getMinimumSamplingPeriod() { return model == DHT11 ? 1000 : 2000; } - - int8_t getNumberOfDecimalsTemperature() { return model == DHT11 ? 0 : 1; }; - int8_t getLowerBoundTemperature() { return model == DHT11 ? 0 : -40; }; - int8_t getUpperBoundTemperature() { return model == DHT11 ? 50 : 125; }; - - int8_t getNumberOfDecimalsHumidity() { return 0; }; - int8_t getLowerBoundHumidity() { return model == DHT11 ? 20 : 0; }; - int8_t getUpperBoundHumidity() { return model == DHT11 ? 90 : 100; }; - - static float toFahrenheit(float fromCelcius) { return 1.8 * fromCelcius + 32.0; }; - static float toCelsius(float fromFahrenheit) { return (fromFahrenheit - 32.0) / 1.8; }; - -protected: - void readSensor(); - - float temperature; - float humidity; - - uint8_t pin; - -private: - DHT_MODEL_t model; - DHT_ERROR_t error; - unsigned long lastReadTime; -}; - -#endif /*dht_h*/ diff --git a/temp_hum_sensor/lib/DHT/README.md b/temp_hum_sensor/lib/DHT/README.md deleted file mode 100644 index 812f044..0000000 --- a/temp_hum_sensor/lib/DHT/README.md +++ /dev/null @@ -1,49 +0,0 @@ -DHT -=== - -An Arduino library for reading the DHT family of temperature and humidity sensors. - -Written by Mark Ruys, . - -Features --------- - - Support for DHT11 and DHT22, AM2302, RHT03 - - Auto detect sensor model - - Low memory footprint - - Very small code - -Usage ------ - -``` -#include "DHT.h" - -DHT dht; - -void setup() -{ - Serial.begin(9600); - - dht.setup(2); // data pin 2 -} - -void loop() -{ - delay(dht.getMinimumSamplingPeriod()); - - Serial.print(dht.getHumidity()); - Serial.print("\t"); - Serial.print(dht.getTemperature()); -} -``` -Also check out the [example] how to read out your sensor. For all the options, see [dht.h][header]. - -Installation ------------- - -Place the [DHT][download] library folder in your `/libraries/` folder. You may need to create the `libraries` subfolder if its your first library. Restart the Arduino IDE. - -[download]: https://github.com/markruys/arduino-DHT/archive/master.zip "Download DHT library" -[example]: https://github.com/markruys/arduino-DHT/blob/master/examples/DHT_Test/DHT_Test.pde "Show DHT example" -[header]: https://github.com/markruys/arduino-DHT/blob/master/DHT.h "Show header file" - diff --git a/temp_hum_sensor/lib/DHT/examples/DHT_Test/DHT_Test.pde b/temp_hum_sensor/lib/DHT/examples/DHT_Test/DHT_Test.pde deleted file mode 100644 index e6afba3..0000000 --- a/temp_hum_sensor/lib/DHT/examples/DHT_Test/DHT_Test.pde +++ /dev/null @@ -1,29 +0,0 @@ -#include "DHT.h" - -DHT dht; - -void setup() -{ - Serial.begin(9600); - Serial.println(); - Serial.println("Status\tHumidity (%)\tTemperature (C)\t(F)"); - - dht.setup(2); // data pin 2 -} - -void loop() -{ - delay(dht.getMinimumSamplingPeriod()); - - float humidity = dht.getHumidity(); - float temperature = dht.getTemperature(); - - Serial.print(dht.getStatusString()); - Serial.print("\t"); - Serial.print(humidity, 1); - Serial.print("\t\t"); - Serial.print(temperature, 1); - Serial.print("\t\t"); - Serial.println(dht.toFahrenheit(temperature), 1); -} - diff --git a/temp_hum_sensor/lib/DHT/keywords.txt b/temp_hum_sensor/lib/DHT/keywords.txt deleted file mode 100644 index c969b6f..0000000 --- a/temp_hum_sensor/lib/DHT/keywords.txt +++ /dev/null @@ -1,42 +0,0 @@ -####################################### -# Syntax Coloring Map For DHT -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -DHT KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -setup KEYWORD2 -getTemperature KEYWORD2 -getHumidity KEYWORD2 -getStatus KEYWORD2 -getStatusString KEYWORD2 -getModel KEYWORD2 -getMinimumSamplingPeriod KEYWORD2 -toFahrenheit KEYWORD2 -toCelsius KEYWORD2 - -####################################### -# Instances (KEYWORD2) -####################################### - - -####################################### -# Constants (LITERAL1) -####################################### - -AUTO_DETECT LITERAL1 -DHT11 LITERAL1 -DHT22 LITERAL1 -AM2302 LITERAL1 -RHT03 LITERAL1 - -ERROR_NONE LITERAL1 -ERROR_TIMEOUT LITERAL1 -ERROR_CHECKSUM LITERAL1 diff --git a/temp_hum_sensor/lib/DHT/license.txt b/temp_hum_sensor/lib/DHT/license.txt deleted file mode 100755 index 320f064..0000000 --- a/temp_hum_sensor/lib/DHT/license.txt +++ /dev/null @@ -1,26 +0,0 @@ -Software License Agreement (BSD License) - -Copyright (c) 2013, Mark Ruys. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: - - * Redistributions of source code must retain the above copyright - notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above copyright - notice, this list of conditions and the following disclaimer in the - documentation and/or other materials provided with the distribution. - * Neither the name of the University of California, Berkeley nor the - names of its contributors may be used to endorse or promote products - derived from this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS "AS IS" AND ANY -EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY -DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/temp_hum_sensor/lib/DHT/readme.pdf b/temp_hum_sensor/lib/DHT/readme.pdf deleted file mode 100644 index 2c8706c..0000000 Binary files a/temp_hum_sensor/lib/DHT/readme.pdf and /dev/null differ diff --git a/temp_hum_sensor/src/NodeManager.cpp b/temp_hum_sensor/src/NodeManager.cpp new file mode 100644 index 0000000..cfb1c42 --- /dev/null +++ b/temp_hum_sensor/src/NodeManager.cpp @@ -0,0 +1,2627 @@ +/* + * NodeManager + */ + +#include "NodeManager.h" + +/*************************************** + Global functions +*/ + +// return vcc in V +float getVcc() { + #ifndef MY_GATEWAY_ESP8266 + // 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 + wait(70); + // Do conversion + ADCSRA |= _BV(ADSC); + while (bit_is_set(ADCSRA, ADSC)) {}; + // return Vcc in mV + return (float)((1125300UL) / ADC) / 1000; + #else + return (float)0; + #endif +} + + +/*************************************** + PowerManager +*/ + +// set the vcc and ground pin the sensor is connected to +void PowerManager::setPowerPins(int ground_pin, int vcc_pin, int wait_time) { + #if DEBUG == 1 + Serial.print(F("PWR G=")); + Serial.print(ground_pin); + Serial.print(F(" V=")); + Serial.println(vcc_pin); + #endif + // configure the vcc pin as output and initialize to high (power on) + _vcc_pin = vcc_pin; + pinMode(_vcc_pin, OUTPUT); + digitalWrite(_vcc_pin, HIGH); + // configure the ground pin as output and initialize to low + _ground_pin = ground_pin; + pinMode(_ground_pin, OUTPUT); + digitalWrite(_ground_pin, LOW); + _wait = wait_time; +} + +// return true if power pins have been configured +bool PowerManager::isConfigured() { + if (_vcc_pin != -1 && _ground_pin != -1) return true; + return false; +} + +// turn on the sensor by activating its power pins +void PowerManager::powerOn() { + if (! isConfigured()) return; + #if DEBUG == 1 + Serial.print(F("ON P=")); + 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) wait(_wait); +} + +// turn off the sensor +void PowerManager::powerOff() { + if (! isConfigured()) return; + #if DEBUG == 1 + Serial.print(F("OFF P=")); + 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::setDescription(char* value) { + _description = value; +} +void Sensor::setAck(bool value) { + _ack = value; +} +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; +} +int Sensor::getValueType() { + return _value_type; +} +void Sensor::setFloatPrecision(int value) { + _float_precision = value; +} +#if POWER_MANAGER == 1 + void Sensor::setPowerPins(int ground_pin, int vcc_pin, int wait_time) { + _powerManager.setPowerPins(ground_pin, vcc_pin, wait_time); + } + void Sensor::setAutoPowerPins(bool value) { + _auto_power_pins = value; + } + void Sensor::powerOn() { + _powerManager.powerOn(); + } + void Sensor::powerOff() { + _powerManager.powerOff(); + } +#endif +void Sensor::setSleepBetweenSend(int value) { + _sleep_between_send = value; +} +void Sensor::setInterruptPin(int value) { + _interrupt_pin = value; +} +int Sensor::getInterruptPin() { + return _interrupt_pin; +} +int Sensor::getValueInt() { + return _last_value_int; +} +float Sensor::getValueFloat() { + return _last_value_float; +} +char* Sensor::getValueString() { + return _last_value_string; +} + +// present the sensor to the gateway and controller +void Sensor::presentation() { + #if DEBUG == 1 + Serial.print(F("PRES I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(_presentation); + #endif + present(_child_id, _presentation,_description,_ack); +} + +// call the sensor-specific implementation of before +void Sensor::before() { + if (_pin == -1) return; + onBefore(); +} + +// call the sensor-specific implementation of setup +void Sensor::setup() { + if (_pin == -1) return; + onSetup(); +} + +// 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 + if (_auto_power_pins) 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 + if (_force_update > 0) _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) wait(_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 + if (_auto_power_pins) 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 passing along the message + 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 configured, sleep beetween each send + if (_sleep_between_send > 0) sleep(_sleep_between_send); + #if DEBUG == 1 + Serial.print(F("SEND D=")); + Serial.print(message.destination); + Serial.print(F(" I=")); + Serial.print(message.sensor); + Serial.print(F(" C=")); + Serial.print(message.getCommand()); + Serial.print(F(" T=")); + Serial.print(message.type); + Serial.print(F(" S=")); + Serial.print(message.getString()); + Serial.print(F(" I=")); + Serial.print(message.getInt()); + Serial.print(F(" F=")); + Serial.println(message.getFloat()); + #endif + send(message,_ack); + } +} + +/* + 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 to do during before +void SensorAnalogInput::onBefore() { + // prepare the pin for input + pinMode(_pin, INPUT); +} + +// what to do during setup +void SensorAnalogInput::onSetup() { +} + +// what to do 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(F("A-IN I=")); + Serial.print(_child_id); + Serial.print(F(" V=")); + Serial.print(adc); + Serial.print(F(" %=")); + Serial.println(percentage); + #endif + // store the result + _value_int = _output_percentage ? percentage : adc; +} + +// what to do during loop +void SensorAnalogInput::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} + +// read the analog input +int SensorAnalogInput::_getAnalogRead() { + #ifndef MY_GATEWAY_ESP8266 + // set the reference + if (_reference != -1) { + analogReference(_reference); + wait(100); + } + #endif + // 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; + // restore the original value + if (_reverse) value = 1024 - value; + // scale the percentage based on the range provided + float percentage = ((value - _range_min) / (_range_max - _range_min)) * 100; + if (_reverse) percentage = 100 - percentage; + 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(long value) { + _nominal_resistor = value; +} +void SensorThermistor::setNominalTemperature(int value) { + _nominal_temperature = value; +} +void SensorThermistor::setBCoefficient(int value) { + _b_coefficient = value; +} +void SensorThermistor::setSeriesResistor(long value) { + _series_resistor = value; +} +void SensorThermistor::setOffset(float value) { + _offset = value; +} + +// what to do during before +void SensorThermistor::onBefore() { + // set the pin as input + pinMode(_pin, INPUT); +} + +// what to do during setup +void SensorThermistor::onSetup() { +} + +// what to do 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(F("THER I=")); + Serial.print(_child_id); + Serial.print(F(" V=")); + Serial.print(adc); + Serial.print(F(" T=")); + Serial.print(temperature); + Serial.print(F(" M=")); + Serial.println(getControllerConfig().isMetric); + #endif + // store the value + _value_float = temperature; +} + +// what to do as the main task when receiving a message +void SensorThermistor::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} + + +/* + SensorML8511 +*/ + +// contructor +SensorML8511::SensorML8511(int child_id, int pin): Sensor(child_id, pin) { + // set presentation, type and value type + setPresentation(S_UV); + setType(V_UV); + setValueType(TYPE_FLOAT); +} + +// what to do during before +void SensorML8511::onBefore() { + // set the pin as input + pinMode(_pin, INPUT); +} + +// what to do during setup +void SensorML8511::onSetup() { +} + +// what to do during loop +void SensorML8511::onLoop() { + // read the voltage + int uvLevel = analogRead(_pin); + int refLevel = getVcc()*1024/3.3; + //Use the 3.3V power pin as a reference to get a very accurate output value from sensor + float outputVoltage = 3.3 / refLevel * uvLevel; + //Convert the voltage to a UV intensity level + float uvIntensity = _mapfloat(outputVoltage, 0.99, 2.8, 0.0, 15.0); + #if DEBUG == 1 + Serial.print(F("UV I=")); + Serial.print(_child_id); + Serial.print(F(" V=")); + Serial.print(outputVoltage); + Serial.print(F(" I=")); + Serial.println(uvIntensity); + #endif + // store the value + _value_float = uvIntensity; +} + +// what to do as the main task when receiving a message +void SensorML8511::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} + +// The Arduino Map function but for floats +float SensorML8511::_mapfloat(float x, float in_min, float in_max, float out_min, float out_max) { + return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min; +} + +/* + SensorACS712 +*/ + +// contructor +SensorACS712::SensorACS712(int child_id, int pin): Sensor(child_id, pin) { + // set presentation, type and value type + setPresentation(S_MULTIMETER); + setType(V_CURRENT); + setValueType(TYPE_FLOAT); +} + +// setter/getter +void SensorACS712::setmVPerAmp(int value) { + _mv_per_amp = value; +} +void SensorACS712::setOffset(int value) { + _ACS_offset = value; +} + +// what to do during before +void SensorACS712::onBefore() { + // set the pin as input + pinMode(_pin, INPUT); +} + +// what to do during setup +void SensorACS712::onSetup() { +} + +// what to do during loop +void SensorACS712::onLoop() { + int value = analogRead(_pin); + // convert the analog read in mV + double voltage = (value / 1024.0) * 5000; + // convert voltage in amps + _value_float = ((voltage - _ACS_offset) / _mv_per_amp); + #if DEBUG == 1 + Serial.print(F("ACS I=")); + Serial.print(_child_id); + Serial.print(F(" A=")); + Serial.println(_value_float); + #endif +} + +// what to do as the main task when receiving a message +void SensorACS712::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} + +/* + SensorRainGauge +*/ + +// contructor +SensorRainGauge::SensorRainGauge(int child_id, int pin): Sensor(child_id, pin) { + // set presentation, type and value type + setPresentation(S_RAIN); + setType(V_RAIN); + setValueType(TYPE_FLOAT); + +} + +// initialize static variables +long SensorRainGauge::_last_tip = 0; +long SensorRainGauge::_count = 0; + +// setter/getter +void SensorRainGauge::setReportInterval(int value) { + _report_interval = value; +} +void SensorRainGauge::setSingleTip(float value) { + _single_tip = value; +} + +// what to do during before +void SensorRainGauge::onBefore() { + // set the pin as input and enabled pull up + pinMode(_pin, INPUT_PULLUP); + // attach to the pin's interrupt and execute the routine on falling + attachInterrupt(digitalPinToInterrupt(_pin), _onTipped, FALLING); +} + +// what to do during setup +void SensorRainGauge::onSetup() { +} + +// what to do when when receiving an interrupt +void SensorRainGauge::_onTipped() { + long now = millis(); + // on tipping, two consecutive interrupts are received, ignore the second one + if ( (now - _last_tip > 100) || (now < _last_tip) ){ + // increase the counter + _count++; + #if DEBUG == 1 + Serial.println(F("RAIN+")); + #endif + } + _last_tip = now; +} + +// what to do during loop +void SensorRainGauge::onLoop() { + // avoid reporting the same value multiple times + _value_float = -1; + long now = millis(); + // time elapsed since the last report + long elapsed = now - _last_report; + // minimum time interval between reports + long min_interval = ((long)_report_interval*1000)*60; + // time to report or millis() reset + if ( (elapsed > min_interval) || (now < _last_report)) { + // report the total amount of rain for the last period + _value_float = _count*_single_tip; + #if DEBUG == 1 + Serial.print(F("RAIN I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(_value_float); + #endif + // reset the counters + _count = 0; + _last_report = now; + } +} + +// what to do as the main task when receiving a message +void SensorRainGauge::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) { + // report the total amount of rain for the last period + _value_float = _count*_single_tip; + } +} + + +/* + * SensorMQ + */ +SensorMQ::SensorMQ(int child_id, int pin): Sensor(child_id,pin) { + setPresentation(S_AIR_QUALITY); + setType(V_LEVEL); +} + +//setter/getter +void SensorMQ::setRlValue(float value) { + _rl_value = value; +} +void SensorMQ::setRoValue(float value) { + _ro = value; +} +void SensorMQ::setCleanAirFactor(float value) { + _ro_clean_air_factor = value; +} +void SensorMQ::setCalibrationSampleTimes(int value) { + _calibration_sample_times = value; +} +void SensorMQ::setCalibrationSampleInterval(int value){ + _calibration_sample_interval = value; +} +void SensorMQ::setReadSampleTimes(int value) { + _read_sample_times = value; +} +void SensorMQ::setReadSampleInterval(int value) { + _read_sample_interval = value; +} +void SensorMQ::setLPGCurve(float *value) { + _LPGCurve[0] = value[0]; + _LPGCurve[2] = value[1]; + _LPGCurve[2] = value[2]; +} +void SensorMQ::setCOCurve(float *value) { + _COCurve[0] = value[0]; + _COCurve[2] = value[1]; + _COCurve[2] = value[2]; +} +void SensorMQ::setSmokeCurve(float *value) { + _SmokeCurve[0] = value[0]; + _SmokeCurve[2] = value[1]; + _SmokeCurve[2] = value[2]; +} + +// what to do during before +void SensorMQ::onBefore() { + // prepare the pin for input + pinMode(_pin, INPUT); +} + +// what to do during setup +void SensorMQ::onSetup() { + _ro = _MQCalibration(); +} + +// what to do during loop +void SensorMQ::onLoop() { + if (_pin == -1) return; + // calculate rs/ro + float mq = _MQRead()/_ro; + // calculate the ppm + float lpg = _MQGetGasPercentage(mq,_gas_lpg); + float co = _MQGetGasPercentage(mq,_gas_co); + float smoke = _MQGetGasPercentage(mq,_gas_smoke); + // assign to the value the requested gas + uint16_t value; + if (_target_gas == _gas_lpg) value = lpg; + if (_target_gas == _gas_co) value = co; + if (_target_gas == _gas_smoke) value = smoke; + #if DEBUG == 1 + Serial.print(F("MQ I=")); + Serial.print(_child_id); + Serial.print(F(" V=")); + Serial.print(value); + Serial.print(F(" LPG=")); + Serial.print(lpg); + Serial.print(F(" CO=")); + Serial.print(co); + Serial.print(F(" SMOKE=")); + Serial.println(smoke); + #endif + // store the value + _value_int = (int16_t)ceil(value); +} + +// what to do as the main task when receiving a message +void SensorMQ::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} + +// returns the calculated sensor resistance +float SensorMQ::_MQResistanceCalculation(int raw_adc) { + return ( ((float)_rl_value*(1023-raw_adc)/raw_adc)); +} + +// This function assumes that the sensor is in clean air +float SensorMQ::_MQCalibration() { + int i; + float val=0; + //take multiple samples + for (i=0; i< _calibration_sample_times; i++) { + val += _MQResistanceCalculation(analogRead(_pin)); + wait(_calibration_sample_interval); + } + //calculate the average value + val = val/_calibration_sample_times; + //divided by RO_CLEAN_AIR_FACTOR yields the Ro + val = val/_ro_clean_air_factor; + //according to the chart in the datasheet + return val; +} + +// This function use MQResistanceCalculation to caculate the sensor resistenc (Rs). +float SensorMQ::_MQRead() { + int i; + float rs=0; + for (i=0; i<_read_sample_times; i++) { + rs += _MQResistanceCalculation(analogRead(_pin)); + wait(_read_sample_interval); + } + rs = rs/_read_sample_times; + return rs; +} + +// This function passes different curves to the MQGetPercentage function which calculates the ppm (parts per million) of the target gas. +int SensorMQ::_MQGetGasPercentage(float rs_ro_ratio, int gas_id) { + if ( gas_id == _gas_lpg ) { + return _MQGetPercentage(rs_ro_ratio,_LPGCurve); + } else if ( gas_id == _gas_co) { + return _MQGetPercentage(rs_ro_ratio,_COCurve); + } else if ( gas_id == _gas_smoke) { + return _MQGetPercentage(rs_ro_ratio,_SmokeCurve); + } + return 0; +} + +// returns ppm of the target gas +int SensorMQ::_MQGetPercentage(float rs_ro_ratio, float *pcurve) { + return (pow(10,( ((log10(rs_ro_ratio)-pcurve[1])/pcurve[2]) + pcurve[0]))); +} + + +/* + SensorDigitalInput +*/ + +// contructor +SensorDigitalInput::SensorDigitalInput(int child_id, int pin): Sensor(child_id, pin) { +} + +// what to do during before +void SensorDigitalInput::onBefore() { + // set the pin for input + pinMode(_pin, INPUT); +} + +// what to do during setup +void SensorDigitalInput::onSetup() { +} + +// what to do during loop +void SensorDigitalInput::onLoop() { + // read the value + int value = digitalRead(_pin); + #if DEBUG == 1 + Serial.print(F("D-IN I=")); + Serial.print(_child_id); + Serial.print(F(" P=")); + Serial.print(_pin); + Serial.print(F(" V=")); + Serial.println(value); + #endif + // store the value + _value_int = value; +} + +// what to do as the main task when receiving a message +void SensorDigitalInput::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} + + +/* + SensorDigitalOutput +*/ + +// contructor +SensorDigitalOutput::SensorDigitalOutput(int child_id, int pin): Sensor(child_id, pin) { +} + +// what to do during before +void SensorDigitalOutput::onBefore() { + // set the pin as output and initialize it accordingly + pinMode(_pin, OUTPUT); + _state = _initial_value == LOW ? LOW : HIGH; + digitalWrite(_pin, _state); + // the initial value is now the current value + _value_int = _initial_value; +} + +// what to do during setup +void SensorDigitalOutput::onSetup() { +} + +// setter/getter +void SensorDigitalOutput::setInitialValue(int value) { + _initial_value = value; +} +void SensorDigitalOutput::setPulseWidth(int value) { + _pulse_width = value; +} +void SensorDigitalOutput::setOnValue(int value) { + _on_value = value; +} +void SensorDigitalOutput::setLegacyMode(bool value) { + _legacy_mode = value; +} + +// main task +void SensorDigitalOutput::onLoop() { + // do nothing on loop +} + +// what to do as the main task when receiving a message +void SensorDigitalOutput::onReceive(const MyMessage & message) { + // by default handle a SET message but when legacy mode is set when a REQ message is expected instead + if ( (message.getCommand() == C_SET && ! _legacy_mode) || (message.getCommand() == C_REQ && _legacy_mode)) { + // retrieve from the message the value to set + int value = message.getInt(); + if (value != 0 && value != 1) return; + #if DEBUG == 1 + Serial.print(F("DOUT I=")); + Serial.print(_child_id); + Serial.print(F(" P=")); + Serial.print(_pin); + Serial.print(F(" V=")); + Serial.print(value); + Serial.print(F(" P=")); + Serial.println(_pulse_width); + #endif + // reverse the value if needed + int value_to_write = value; + if (_on_value == LOW) { + if (value == HIGH) value_to_write = LOW; + if (value == LOW) value_to_write = HIGH; + } + // set the value + digitalWrite(_pin, value_to_write); + if (_pulse_width > 0) { + // if this is a pulse output, restore the value to the original value after the pulse + wait(_pulse_width); + digitalWrite(_pin, value_to_write == 0 ? HIGH: LOW); + } + // store the current value so it will be sent to the controller + _state = value; + _value_int = value; + } + if (message.getCommand() == C_REQ && ! _legacy_mode) { + // return the current status + _value_int = _state; + } +} + +/* + SensorRelay +*/ + +// contructor +SensorRelay::SensorRelay(int child_id, int pin): SensorDigitalOutput(child_id, pin) { + // set presentation and type + setPresentation(S_BINARY); + setType(V_STATUS); +} + +// define what to do during loop +void SensorRelay::onLoop() { + // set the value to -1 so to avoid reporting to the gateway during loop + _value_int = -1; +} + +/* + 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; + _sensor_type = sensor_type; + _dht_type = dht_type; + if (_sensor_type == SensorDHT::TEMPERATURE) { + // temperature sensor + setPresentation(S_TEMP); + setType(V_TEMP); + setValueType(TYPE_FLOAT); + } + else if (_sensor_type == SensorDHT::HUMIDITY) { + // humidity sensor + setPresentation(S_HUM); + setType(V_HUM); + setValueType(TYPE_FLOAT); + } +} + +// what to do during before +void SensorDHT::onBefore() { + // initialize the dht library + _dht->begin(); +} + +// what to do during setup +void SensorDHT::onSetup() { +} + +// what to do during loop +void SensorDHT::onLoop() { + // temperature sensor + if (_sensor_type == SensorDHT::TEMPERATURE) { + // read the temperature + float temperature = _dht->readTemperature(); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(F("DHT I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(temperature); + #endif + // store the value + if (! isnan(temperature)) _value_float = temperature; + } + // humidity sensor + else if (_sensor_type == SensorDHT::HUMIDITY) { + // read humidity + float humidity = _dht->readHumidity(); + if (isnan(humidity)) return; + #if DEBUG == 1 + Serial.print(F("DHT I=")); + Serial.print(_child_id); + Serial.print(F(" H=")); + Serial.println(humidity); + #endif + // store the value + if (! isnan(humidity)) _value_float = humidity; + } +} + +// what to do as the main task when receiving a message +void SensorDHT::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} +#endif + +/* + SensorSHT21 +*/ +#if MODULE_SHT21 == 1 +// contructor +SensorSHT21::SensorSHT21(int child_id, int sensor_type): Sensor(child_id,A2) { + // store the sensor type (0: temperature, 1: humidity) + _sensor_type = sensor_type; + if (_sensor_type == SensorSHT21::TEMPERATURE) { + // temperature sensor + setPresentation(S_TEMP); + setType(V_TEMP); + setValueType(TYPE_FLOAT); + } + else if (_sensor_type == SensorSHT21::HUMIDITY) { + // humidity sensor + setPresentation(S_HUM); + setType(V_HUM); + setValueType(TYPE_FLOAT); + } +} + +// what to do during before +void SensorSHT21::onBefore() { + // initialize the library + Wire.begin(); +} + +// what to do during setup +void SensorSHT21::onSetup() { +} + +// what to do during loop +void SensorSHT21::onLoop() { + // temperature sensor + if (_sensor_type == SensorSHT21::TEMPERATURE) { + // read the temperature + float temperature = SHT2x.GetTemperature(); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(F("SHT I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(temperature); + #endif + // store the value + if (! isnan(temperature)) _value_float = temperature; + } + // Humidity Sensor + else if (_sensor_type == SensorSHT21::HUMIDITY) { + // read humidity + float humidity = SHT2x.GetHumidity(); + if (isnan(humidity)) return; + #if DEBUG == 1 + Serial.print(F("SHT I=")); + Serial.print(_child_id); + Serial.print(F(" H=")); + Serial.println(humidity); + #endif + // store the value + if (! isnan(humidity)) _value_float = humidity; + } +} + +// what to do as the main task when receiving a message +void SensorSHT21::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} +#endif + +/* + * SensorHTU21D + */ + #if MODULE_SHT21 == 1 +// constructor +SensorHTU21D::SensorHTU21D(int child_id, int pin): SensorSHT21(child_id, pin) { +} +#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; +} +void SensorSwitch::setDebounce(int value) { + _debounce = value; +} +void SensorSwitch::setTriggerTime(int value) { + _trigger_time = value; +} +void SensorSwitch::setInitial(int value) { + _initial = value; +} +int SensorSwitch::getInitial() { + return _initial; +} + +// what to do during before +void SensorSwitch::onBefore() { + // initialize the value + if (_mode == RISING) _value_int = LOW; + else if (_mode == FALLING) _value_int = HIGH; +} + +// what to do during setup +void SensorSwitch::onSetup() { +} + +// what to do during loop +void SensorSwitch::onLoop() { + // wait to ensure the the input is not floating + if (_debounce > 0) wait(_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(F("SWITCH I=")); + Serial.print(_child_id); + Serial.print(F(" P=")); + Serial.print(_pin); + Serial.print(F(" V=")); + Serial.println(value); + #endif + _value_int = value; + // allow the signal to be restored to its normal value + if (_trigger_time > 0) wait(_trigger_time); + } else { + // invalid + _value_int = -1; + } +} +// what to do as the main task when receiving a message +void SensorSwitch::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) 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); + // set initial value to LOW + setInitial(LOW); +} + +/* + 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; + // retrieve and store the address from the index + _sensors->getAddress(_device_address, index); +} + +// what to do during before +void SensorDs18b20::onBefore() { +} + +// what to do during setup +void SensorDs18b20::onSetup() { +} + +// what to do during loop +void SensorDs18b20::onLoop() { + // do not wait for conversion, will sleep manually during it + if (_sleep_during_conversion) _sensors->setWaitForConversion(false); + // request the temperature + _sensors->requestTemperatures(); + if (_sleep_during_conversion) { + // calculate conversion time and sleep + int16_t conversion_time = _sensors->millisToWaitForConversion(_sensors->getResolution()); + sleep(conversion_time); + } + // read the temperature + float temperature = _sensors->getTempCByIndex(_index); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(F("DS18B20 I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(temperature); + #endif + // store the value + _value_float = temperature; +} + +// what to do as the main task when receiving a message +void SensorDs18b20::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} + +// function to print a device address +DeviceAddress* SensorDs18b20::getDeviceAddress() { + return &_device_address; +} + +// returns the sensor's resolution in bits +int SensorDs18b20::getResolution() { + return _sensors->getResolution(_device_address); +} + +// set the sensor's resolution in bits +void SensorDs18b20::setResolution(int value) { + _sensors->setResolution(_device_address, value); +} + +// sleep while DS18B20 calculates temperature +void SensorDs18b20::setSleepDuringConversion(bool value) { + _sleep_during_conversion = value; +} + +#endif + +/* + SensorBH1750 +*/ +#if MODULE_BH1750 == 1 +// contructor +SensorBH1750::SensorBH1750(int child_id): Sensor(child_id,A4) { + setPresentation(S_LIGHT_LEVEL); + setType(V_LEVEL); + _lightSensor = new BH1750(); +} + +// what to do during before +void SensorBH1750::onBefore() { + _lightSensor->begin(); +} + +// what to do during setup +void SensorBH1750::onSetup() { +} + +// what to do during loop +void SensorBH1750::onLoop() { + // request the light level + _value_int = _lightSensor->readLightLevel(); + #if DEBUG == 1 + Serial.print(F("BH1 I=")); + Serial.print(_child_id); + Serial.print(F(" L=")); + Serial.println(_value_int); + #endif +} + +// what to do as the main task when receiving a message +void SensorBH1750::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} +#endif + +/* + SensorMLX90614 +*/ +#if MODULE_MLX90614 == 1 +// contructor +SensorMLX90614::SensorMLX90614(int child_id, Adafruit_MLX90614* mlx, int sensor_type): Sensor(child_id,A4) { + _sensor_type = sensor_type; + _mlx = mlx; + // set presentation and type + setPresentation(S_TEMP); + setType(V_TEMP); + setValueType(TYPE_FLOAT); +} + +// what to do during before +void SensorMLX90614::onBefore() { + // initialize the library + _mlx->begin(); +} + +// what to do during setup +void SensorMLX90614::onSetup() { +} + +// what to do during loop +void SensorMLX90614::onLoop() { + float temperature = _sensor_type == SensorMLX90614::TEMPERATURE_OBJECT ? _mlx->readAmbientTempC() : _mlx->readObjectTempC(); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(F("MLX I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(temperature); + #endif + if (! isnan(temperature)) _value_float = temperature; +} + +// what to do as the main task when receiving a message +void SensorMLX90614::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} +#endif + + +/* + SensorBosch +*/ +#if MODULE_BME280 == 1 || MODULE_BMP085 == 1 +// contructor +SensorBosch::SensorBosch(int child_id, int sensor_type): Sensor(child_id,A4) { + _sensor_type = sensor_type; + if (_sensor_type == SensorBosch::TEMPERATURE) { + // temperature sensor + setPresentation(S_TEMP); + setType(V_TEMP); + setValueType(TYPE_FLOAT); + } + else if (_sensor_type == SensorBosch::HUMIDITY) { + // humidity sensor + setPresentation(S_HUM); + setType(V_HUM); + setValueType(TYPE_FLOAT); + } + else if (_sensor_type == SensorBosch::PRESSURE) { + // pressure sensor + setPresentation(S_BARO); + setType(V_PRESSURE); + setValueType(TYPE_FLOAT); + } + else if (_sensor_type == SensorBosch::FORECAST) { + // pressure sensor + setPresentation(S_BARO); + setType(V_FORECAST); + setValueType(TYPE_STRING); + } +} + +// setter/getter +void SensorBosch::setForecastSamplesCount(int value) { + _forecast_samples_count = value; +} + +// what to do during before +void SensorBosch::onBefore() { + // initialize the forecast samples array + _forecast_samples = new float[_forecast_samples_count]; +} + +// what to do during setup +void SensorBosch::onSetup() { +} + +// what to do during loop +void SensorBosch::onLoop() { +} + +// what to do as the main task when receiving a message +void SensorBosch::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} + + +void SensorBosch::_forecast(float pressure) { + if (isnan(pressure)) return; + // Calculate the average of the last n minutes. + int index = _minute_count % _forecast_samples_count; + _forecast_samples[index] = pressure; + _minute_count++; + if (_minute_count > 185) _minute_count = 6; + if (_minute_count == 5) _pressure_avg = _getLastPressureSamplesAverage(); + else if (_minute_count == 35) { + float last_pressure_avg = _getLastPressureSamplesAverage(); + float change = (last_pressure_avg - _pressure_avg) * 0.1; + // first time initial 3 hour + if (_first_round) _dP_dt = change * 2; // note this is for t = 0.5hour + else _dP_dt = change / 1.5; // divide by 1.5 as this is the difference in time from 0 value. + } + else if (_minute_count == 65) { + float last_pressure_avg = _getLastPressureSamplesAverage(); + float change = (last_pressure_avg - _pressure_avg) * 0.1; + //first time initial 3 hour + if (_first_round) _dP_dt = change; //note this is for t = 1 hour + else _dP_dt = change / 2; //divide by 2 as this is the difference in time from 0 value + } + else if (_minute_count == 95) { + float last_pressure_avg = _getLastPressureSamplesAverage(); + float change = (last_pressure_avg - _pressure_avg) * 0.1; + // first time initial 3 hour + if (_first_round)_dP_dt = change / 1.5; // note this is for t = 1.5 hour + else _dP_dt = change / 2.5; // divide by 2.5 as this is the difference in time from 0 value + } + else if (_minute_count == 125) { + float last_pressure_avg = _getLastPressureSamplesAverage(); + // store for later use. + _pressure_avg2 = last_pressure_avg; + float change = (last_pressure_avg - _pressure_avg) * 0.1; + if (_first_round) _dP_dt = change / 2; // note this is for t = 2 hour + else _dP_dt = change / 3; // divide by 3 as this is the difference in time from 0 value + } + else if (_minute_count == 155) { + float last_pressure_avg = _getLastPressureSamplesAverage(); + float change = (last_pressure_avg - _pressure_avg) * 0.1; + if (_first_round) _dP_dt = change / 2.5; // note this is for t = 2.5 hour + else _dP_dt = change / 3.5; // divide by 3.5 as this is the difference in time from 0 value + } + else if (_minute_count == 185) { + float last_pressure_avg = _getLastPressureSamplesAverage(); + float change = (last_pressure_avg - _pressure_avg) * 0.1; + if (_first_round) _dP_dt = change / 3; // note this is for t = 3 hour + else _dP_dt = change / 4; // divide by 4 as this is the difference in time from 0 value + } + // Equating the pressure at 0 to the pressure at 2 hour after 3 hours have past. + _pressure_avg = _pressure_avg2; + // flag to let you know that this is on the past 3 hour mark. Initialized to 0 outside main loop. + _first_round = false; + // calculate the forecast (STABLE = 0, SUNNY = 1, CLOUDY = 2, UNSTABLE = 3, THUNDERSTORM = 4, UNKNOWN = 5) + int forecast = 5; + //if time is less than 35 min on the first 3 hour interval. + if (_minute_count < 35 && _first_round) forecast = 5; + else if (_dP_dt < (-0.25)) forecast = 5; + else if (_dP_dt > 0.25) forecast = 4; + else if ((_dP_dt > (-0.25)) && (_dP_dt < (-0.05))) forecast = 2; + else if ((_dP_dt > 0.05) && (_dP_dt < 0.25)) forecast = 1; + else if ((_dP_dt >(-0.05)) && (_dP_dt < 0.05)) forecast = 0; + else forecast = 5; + _value_string = _weather[forecast]; + #if DEBUG == 1 + Serial.print(F("BMP I=")); + Serial.print(_child_id); + Serial.print(F(" M=")); + Serial.print(_minute_count); + Serial.print(F(" dP=")); + Serial.print(_dP_dt); + Serial.print(F(" F=")); + Serial.println(_value_string); + #endif +} + +// returns the average of the latest pressure samples +float SensorBosch::_getLastPressureSamplesAverage() { + float avg = 0; + for (int i = 0; i < _forecast_samples_count; i++) avg += _forecast_samples[i]; + avg /= _forecast_samples_count; + return avg; +} + +// search for a given chip on i2c bus +uint8_t SensorBosch::GetI2CAddress(uint8_t chip_id) { + uint8_t addresses[] = {0x77, 0x76}; + uint8_t register_address = 0xD0; + for (int i = 0; i <= sizeof(addresses); i++) { + uint8_t i2c_address = addresses[i]; + uint8_t value; + Wire.beginTransmission((uint8_t)i2c_address); + Wire.write((uint8_t)register_address); + Wire.endTransmission(); + Wire.requestFrom((uint8_t)i2c_address, (byte)1); + value = Wire.read(); + if (value == chip_id) { + #if DEBUG == 1 + Serial.print(F("I2C=")); + Serial.println(i2c_address); + #endif + return i2c_address; + } + } + return addresses[0]; +} +#endif + +/* + * SensorBME280 + */ +#if MODULE_BME280 == 1 +SensorBME280::SensorBME280(int child_id, Adafruit_BME280* bme, int sensor_type): SensorBosch(child_id,sensor_type) { + _bme = bme; +} + +void SensorBME280::onLoop() { + // temperature sensor + if (_sensor_type == SensorBME280::TEMPERATURE) { + // read the temperature + float temperature = _bme->readTemperature(); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(F("BME I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(temperature); + #endif + if (isnan(temperature)) return; + // store the value + _value_float = temperature; + } + // Humidity Sensor + else if (_sensor_type == SensorBME280::HUMIDITY) { + // read humidity + float humidity = _bme->readHumidity(); + #if DEBUG == 1 + Serial.print(F("BME I=")); + Serial.print(_child_id); + Serial.print(F(" H=")); + Serial.println(humidity); + #endif + if (isnan(humidity)) return; + // store the value + _value_float = humidity; + } + // Pressure Sensor + else if (_sensor_type == SensorBME280::PRESSURE) { + // read pressure + float pressure = _bme->readPressure() / 100.0F; + if (isnan(pressure)) return; + #if DEBUG == 1 + Serial.print(F("BME I=")); + Serial.print(_child_id); + Serial.print(F(" P=")); + Serial.println(pressure); + #endif + if (isnan(pressure)) return; + // store the value + _value_float = pressure; + } + // Forecast Sensor + else if (_sensor_type == SensorBME280::FORECAST) { + float pressure = _bme->readPressure() / 100.0F; + _forecast(pressure); + } +} +#endif + +/* + SensorBMP085 +*/ +#if MODULE_BMP085 == 1 +// contructor +SensorBMP085::SensorBMP085(int child_id, Adafruit_BMP085* bmp, int sensor_type): SensorBosch(child_id,sensor_type) { + _bmp = bmp; +} + +// what to do during loop +void SensorBMP085::onLoop() { + // temperature sensor + if (_sensor_type == SensorBMP085::TEMPERATURE) { + // read the temperature + float temperature = _bmp->readTemperature(); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(F("BMP I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(temperature); + #endif + if (isnan(temperature)) return; + // store the value + _value_float = temperature; + } + // Pressure Sensor + else if (_sensor_type == SensorBMP085::PRESSURE) { + // read pressure + float pressure = _bmp->readPressure() / 100.0F; + #if DEBUG == 1 + Serial.print(F("BMP I=")); + Serial.print(_child_id); + Serial.print(F(" P=")); + Serial.println(pressure); + #endif + if (isnan(pressure)) return; + // store the value + _value_float = pressure; + } + // Forecast Sensor + else if (_sensor_type == SensorBMP085::FORECAST) { + float pressure = _bmp->readPressure() / 100.0F; + _forecast(pressure); + } +} +#endif + + +/* + SensorSonoff +*/ +#if MODULE_SONOFF == 1 +// contructor +SensorSonoff::SensorSonoff(int child_id): Sensor(child_id,1) { + setPresentation(S_BINARY); + setType(V_STATUS); +} + +// setter/getter +void SensorSonoff::setButtonPin(int value) { + _button_pin = value; +} +void SensorSonoff::setRelayPin(int value) { + _relay_pin = value; +} +void SensorSonoff::setLedPin(int value) { + _led_pin = value; +} + +// what to do during before +void SensorSonoff::onBefore() { +} + +// what to do during setup +void SensorSonoff::onSetup() { + // Setup the button + pinMode(_button_pin, INPUT_PULLUP); + // After setting up the button, setup debouncer + _debouncer.attach(_button_pin); + _debouncer.interval(5); + // Make sure relays and LED are off when starting up + digitalWrite(_relay_pin, _relay_off); + digitalWrite(_led_pin, _led_off); + // Then set relay pins in output mode + pinMode(_relay_pin, OUTPUT); + pinMode(_led_pin, OUTPUT); + _blink(); +} + +// what to do during loop +void SensorSonoff::onLoop() { + // set the value to -1 so to avoid reporting to the gateway during loop + _value_int = -1; + _debouncer.update(); + // Get the update value from the button + int value = _debouncer.read(); + if (value != _old_value && value == 0) { + // button pressed, toggle the state + _toggle(); + } + _old_value = value; +} + +// what to do as the main task when receiving a message +void SensorSonoff::onReceive(const MyMessage & message) { + if (message.getCommand() == C_SET) { + // retrieve from the message the value to set + int value = message.getInt(); + if (value != 0 && value != 1 || value == _state) return; + // toggle the state + _toggle(); + } + if (message.getCommand() == C_REQ) { + // return the current state + _value_int = _state; + } +} + +// toggle the state +void SensorSonoff::_toggle() { + // toggle the state + _state = _state ? false : true; + // Change relay state + digitalWrite(_relay_pin, _state? _relay_on: _relay_off); + // Change LED state + digitalWrite(_led_pin, _state? _led_on: _led_off); + #if DEBUG == 1 + Serial.print(F("SONOFF I=")); + Serial.print(_child_id); + Serial.print(F(" V=")); + Serial.println(_state); + #endif + _value_int = _state; +} + +// blink the led +void SensorSonoff::_blink() { + digitalWrite(_led_pin, digitalRead(_led_pin) ? _led_on : _led_off); + wait(200); + digitalWrite(_led_pin, digitalRead(_led_pin) ? _led_on : _led_off); + wait(200); + digitalWrite(_led_pin, digitalRead(_led_pin) ? _led_on : _led_off); + wait(200); + digitalWrite(_led_pin, digitalRead(_led_pin) ? _led_on : _led_off); +} +#endif + + +/* + SensorHCSR04 +*/ +#if MODULE_HCSR04 == 1 +// contructor +SensorHCSR04::SensorHCSR04(int child_id, int pin): Sensor(child_id, pin) { + // set presentation and type + setPresentation(S_DISTANCE); + setType(V_DISTANCE); + _trigger_pin = pin; + _echo_pin = pin; +} + +// what to do during before +void SensorHCSR04::onBefore() { + // initialize the library + _sonar = new NewPing(_trigger_pin,_echo_pin,_max_distance); +} + +// setter/getter +void SensorHCSR04::setTriggerPin(int value) { + _trigger_pin = value; +} +void SensorHCSR04::setEchoPin(int value) { + _echo_pin = value; +} +void SensorHCSR04::setMaxDistance(int value) { + _max_distance = value; +} + +// what to do during setup +void SensorHCSR04::onSetup() { +} + +// what to do during loop +void SensorHCSR04::onLoop() { + int distance = getControllerConfig().isMetric ? _sonar->ping_cm() : _sonar->ping_in(); + #if DEBUG == 1 + Serial.print(F("HC I=")); + Serial.print(_child_id); + Serial.print(F(" D=")); + Serial.println(distance); + #endif + _value_int = distance; +} + +// what to do as the main task when receiving a message +void SensorHCSR04::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) onLoop(); +} +#endif + +/* + SensorMCP9808 +*/ +#if MODULE_MCP9808 == 1 +// contructor +SensorMCP9808::SensorMCP9808(int child_id, Adafruit_MCP9808* mcp): Sensor(child_id,A2) { + _mcp = mcp; + setPresentation(S_TEMP); + setType(V_TEMP); + setValueType(TYPE_FLOAT); +} + +// what to do during before +void SensorMCP9808::onBefore() { +} + +// what to do during setup +void SensorMCP9808::onSetup() { +} + +// what to do during loop +void SensorMCP9808::onLoop() { + float temperature = _mcp->readTempC(); + // convert it + if (! getControllerConfig().isMetric) temperature = temperature * 1.8 + 32; + #if DEBUG == 1 + Serial.print(F("MCP I=")); + Serial.print(_child_id); + Serial.print(F(" T=")); + Serial.println(temperature); + #endif + // store the value + if (! isnan(temperature)) _value_float = temperature; +} + +// what to do as the main task when receiving a message +void SensorMCP9808::onReceive(const MyMessage & message) { + if (message.getCommand() == C_REQ) 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::setRetries(int value) { + _retries = 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; + } + void NodeManager::setBatteryInternalVcc(bool value) { + _battery_internal_vcc = value; + } + void NodeManager::setBatteryPin(int value) { + _battery_pin = value; + } + void NodeManager::setBatteryVoltsPerBit(float value) { + _battery_volts_per_bit = value; + } + void NodeManager::setBatteryReportWithInterrupt(bool value) { + _battery_report_with_interrupt = value; + } +#endif +void NodeManager::setSleepMode(int value) { + _sleep_mode = value; +} +void NodeManager::setMode(int value) { + setSleepMode(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 = value2; + _sleep_unit = value3; +} +void NodeManager::setSleepInterruptPin(int value) { + _sleep_interrupt_pin = value; +} +void NodeManager::setInterrupt(int pin, int mode, int pull) { + 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, int wait_time) { + _powerManager.setPowerPins(ground_pin, vcc_pin, wait_time); + } + void NodeManager::setAutoPowerPins(bool value) { + _auto_power_pins = value; + } + void NodeManager::powerOn() { + _powerManager.powerOn(); + } + void NodeManager::powerOff() { + _powerManager.powerOff(); + } +#endif +void NodeManager::setSleepBetweenSend(int value) { + _sleep_between_send = value; +} +void NodeManager::setAck(bool value) { + _ack = value; +} + +// register a sensor to this manager +int NodeManager::registerSensor(int sensor_type, int pin, int child_id) { + // 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 -1; + #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)); + else if (sensor_type == SENSOR_MQ) return registerSensor(new SensorMQ(child_id, pin)); + else if (sensor_type == SENSOR_ML8511) return registerSensor(new SensorML8511(child_id, pin)); + else if (sensor_type == SENSOR_ACS712) return registerSensor(new SensorACS712(child_id, pin)); + else if (sensor_type == SENSOR_RAIN_GAUGE) return registerSensor(new SensorRainGauge(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) { + int dht_type = sensor_type == SENSOR_DHT11 ? DHT11 : DHT22; + DHT* dht = new DHT(pin,dht_type); + // register temperature sensor + registerSensor(new SensorDHT(child_id,pin,dht,SensorDHT::TEMPERATURE,dht_type)); + // register humidity sensor + child_id = _getAvailableChildId(); + return registerSensor(new SensorDHT(child_id,pin,dht,SensorDHT::HUMIDITY,dht_type)); + } + #endif + #if MODULE_SHT21 == 1 + else if (sensor_type == SENSOR_SHT21) { + // register temperature sensor + registerSensor(new SensorSHT21(child_id,SensorSHT21::TEMPERATURE)); + // register humidity sensor + child_id = _getAvailableChildId(); + return registerSensor(new SensorSHT21(child_id,SensorSHT21::HUMIDITY)); + } + else if (sensor_type == SENSOR_HTU21D) { + // register temperature sensor + registerSensor(new SensorHTU21D(child_id,SensorHTU21D::TEMPERATURE)); + // register humidity sensor + child_id = _getAvailableChildId(); + return registerSensor(new SensorHTU21D(child_id,SensorHTU21D::HUMIDITY)); + } + #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 -1; + // 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 set the initial value + SensorSwitch* sensor = (SensorSwitch*)getSensor(index); + sensor->setInterruptPin(pin); + setInterrupt(pin,sensor->getMode(),sensor->getInitial()); + 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(); + int index = 0; + // register a new child for each sensor on the bus + for(int i = 0; i < sensors->getDeviceCount(); i++) { + if (i > 0) child_id = _getAvailableChildId(); + index = registerSensor(new SensorDs18b20(child_id,pin,sensors,i)); + } + return index; + } + #endif + #if MODULE_BH1750 == 1 + else if (sensor_type == SENSOR_BH1750) { + return registerSensor(new SensorBH1750(child_id)); + } + #endif + #if MODULE_MLX90614 == 1 + else if (sensor_type == SENSOR_MLX90614) { + Adafruit_MLX90614* mlx = new Adafruit_MLX90614(); + // register ambient temperature sensor + registerSensor(new SensorMLX90614(child_id,mlx,SensorMLX90614::TEMPERATURE_AMBIENT)); + // register object temperature sensor + child_id = _getAvailableChildId(); + return registerSensor(new SensorMLX90614(child_id,mlx,SensorMLX90614::TEMPERATURE_OBJECT)); + } + #endif + #if MODULE_BME280 == 1 + else if (sensor_type == SENSOR_BME280) { + Adafruit_BME280* bme = new Adafruit_BME280(); + if (! bme->begin(SensorBosch::GetI2CAddress(0x60))) { + #if DEBUG == 1 + Serial.println(F("NO BME")); + #endif + return -1; + } + // register temperature sensor + registerSensor(new SensorBME280(child_id,bme,SensorBME280::TEMPERATURE)); + child_id = _getAvailableChildId(); + // register humidity sensor + registerSensor(new SensorBME280(child_id,bme,SensorBME280::HUMIDITY)); + // register pressure sensor + child_id = _getAvailableChildId(); + registerSensor(new SensorBME280(child_id,bme,SensorBME280::PRESSURE)); + // register forecast sensor + child_id = _getAvailableChildId(); + return registerSensor(new SensorBME280(child_id,bme,SensorBME280::FORECAST)); + } + #endif + #if MODULE_SONOFF == 1 + else if (sensor_type == SENSOR_SONOFF) { + return registerSensor(new SensorSonoff(child_id)); + } + #endif + #if MODULE_BMP085 == 1 + else if (sensor_type == SENSOR_BMP085) { + Adafruit_BMP085* bmp = new Adafruit_BMP085(); + if (! bmp->begin(SensorBosch::GetI2CAddress(0x55))) { + #if DEBUG == 1 + Serial.println(F("NO BMP")); + #endif + return -1; + } + // register temperature sensor + registerSensor(new SensorBMP085(child_id,bmp,SensorBMP085::TEMPERATURE)); + // register pressure sensor + child_id = _getAvailableChildId(); + registerSensor(new SensorBMP085(child_id,bmp,SensorBMP085::PRESSURE)); + // register forecast sensor + child_id = _getAvailableChildId(); + return registerSensor(new SensorBMP085(child_id,bmp,SensorBMP085::FORECAST)); + } + #endif + #if MODULE_HCSR04 == 1 + else if (sensor_type == SENSOR_HCSR04) { + return registerSensor(new SensorHCSR04(child_id, pin)); + } + #endif + #if MODULE_MCP9808 == 1 + else if (sensor_type == SENSOR_MCP9808) { + Adafruit_MCP9808 * mcp = new Adafruit_MCP9808(); + if (! mcp->begin()) { + #if DEBUG == 1 + Serial.println(F("NO MCP")); + #endif + return -1; + } + // register temperature sensor + registerSensor(new SensorMCP9808(child_id,mcp)); + } + #endif + else { + #if DEBUG == 1 + Serial.print(F("INVALID ")); + 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(F("REG I=")); + Serial.print(sensor->getChildId()); + Serial.print(F(" P=")); + Serial.print(sensor->getPin()); + Serial.print(F(" P=")); + Serial.print(sensor->getPresentation()); + Serial.print(F(" T=")); + Serial.println(sensor->getType()); + #endif + #if POWER_MANAGER == 1 + // set auto power pin + sensor->setAutoPowerPins(_auto_power_pins); + #endif + // add the sensor to the array of registered sensors + _sensors[sensor->getChildId()] = sensor; + // return the child_id + return sensor->getChildId(); +} + +// un-register a sensor to this manager +void NodeManager::unRegisterSensor(int sensor_index) { + // unlink the pointer to this sensor + _sensors[sensor_index] == 0; +} + +// 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]; +} +Sensor* NodeManager::getSensor(int child_id) { + return get(child_id); +} + +// assign a different child id to a sensor' +bool NodeManager::renameSensor(int old_child_id, int new_child_id) { + // ensure the old id exists and the new is available + if (_sensors[old_child_id] == 0 || _sensors[new_child_id] != 0) return false; + // assign the sensor to new id + _sensors[new_child_id] = _sensors[old_child_id]; + // set the new child id + _sensors[new_child_id]->setChildId(new_child_id); + // free up the old id + _sensors[old_child_id] = 0; + return true; +} + +// setup NodeManager +void NodeManager::before() { + #if DEBUG == 1 + Serial.print(F("NodeManager v")); + Serial.println(VERSION); + #endif + // 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(F("INT1 M=")); + Serial.println(_interrupt_1_mode); + Serial.print(F("INT2 M=")); + Serial.println(_interrupt_2_mode); + #endif + #if REMOTE_CONFIGURATION == 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(F("LOADSLP M=")); + Serial.print(_sleep_mode); + Serial.print(F(" T=")); + Serial.print(_sleep_time); + Serial.print(F(" U=")); + Serial.println(_sleep_unit); + #endif + } + #endif + #if BATTERY_MANAGER == 1 && !defined(MY_GATEWAY_ESP8266) + // set analogReference to internal if measuring the battery through a pin + if (! _battery_internal_vcc && _battery_pin > -1) analogReference(INTERNAL); + #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() { + #if DEBUG == 1 + Serial.println(F("RADIO OK")); + #endif + // Send the sketch version information to the gateway and Controller + if (_sleep_between_send > 0) sleep(_sleep_between_send); + sendSketchInfo(SKETCH_NAME,SKETCH_VERSION); + // present the service as a custom sensor to the controller + _present(CONFIGURATION_CHILD_ID, S_CUSTOM); + #if BATTERY_MANAGER == 1 && BATTERY_SENSOR == 1 + // 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() + if (_sleep_between_send > 0) sleep(_sleep_between_send); + _sensors[i]->presentation(); + } + #if DEBUG == 1 + Serial.println(F("READY")); + Serial.println(""); + #endif +} + + +// setup NodeManager +void NodeManager::setup() { + #if DEBUG == 1 + Serial.print(F("MY I=")); + Serial.print(getNodeId()); + Serial.print(F(" M=")); + Serial.println(getControllerConfig().isMetric); + #endif + #if SERVICE_MESSAGES == 1 + _send(_msg.set("STARTED")); + #endif + // run setup for all the registered sensors + for (int i = 0; i < 255; i++) { + if (_sensors[i] == 0) continue; + // call each sensor's setup() + _sensors[i]->setup(); + } +} + +// run the main function for all the register sensors +void NodeManager::loop() { + MyMessage empty; + // if in idle mode, do nothing + if (_sleep_mode == IDLE) return; + // if sleep time is not set, do nothing + if ((_sleep_mode == SLEEP || _sleep_mode == WAIT) && _sleep_time == 0) return; + #if POWER_MANAGER == 1 + // turn on the pin powering all the sensors + if (_auto_power_pins) powerOn(); + #endif + // run loop for all the registered sensors + for (int i = 0; i < 255; i++) { + // skip not configured sensors + if (_sensors[i] == 0) continue; + // if waking up from an interrupt skip all the sensor without that interrupt configured + if (_last_interrupt_pin != -1 && _sensors[i]->getInterruptPin() != _last_interrupt_pin) continue; + // call each sensor's loop() + _sensors[i]->loop(empty); + } + #if POWER_MANAGER == 1 + // turn off the pin powering all the sensors + if (_auto_power_pins) powerOff(); + #endif + // continue/start sleeping as requested + if (_sleep_mode == SLEEP || _sleep_mode == WAIT) _sleep(); +} + +// dispacth inbound messages +void NodeManager::receive(const MyMessage &message) { + #if DEBUG == 1 + Serial.print(F("RECV S=")); + Serial.print(message.sender); + Serial.print(F(" I=")); + Serial.print(message.sensor); + Serial.print(F(" C=")); + Serial.print(message.getCommand()); + Serial.print(F(" T=")); + Serial.print(message.type); + Serial.print(F(" P=")); + 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 (_sensors[message.sensor] != 0) { + #if POWER_MANAGER == 1 + // turn on the pin powering all the sensors + if (_auto_power_pins) powerOn(); + #endif + // call the sensor's receive() + _sensors[message.sensor]->receive(message); + #if POWER_MANAGER == 1 + // turn off the pin powering all the sensors + if (_auto_power_pins) powerOff(); + #endif + } +} + +// request and return the current timestamp from the controller +long NodeManager::getTimestamp() { + int retries = 3; + _timestamp = -1; + while (_timestamp == -1 && retries > 0) { + #if DEBUG == 1 + Serial.println(F("TIME")); + #endif + // request the time to the controller + requestTime(); + // keep asking every 1 second + wait(1000); + retries--; + } + return _timestamp; +} + +// receive the time from the controller and save it +void NodeManager::receiveTime(unsigned long ts) { + _timestamp = ts; + #if DEBUG == 1 + Serial.print(F("TIME T=")); + Serial.print(_timestamp); + #endif +} + +// send a message to the network +void NodeManager::_send(MyMessage & message) { + // send the message, multiple times if requested + for (int i = 0; i < _retries; i++) { + // if configured, sleep beetween each send + if (_sleep_between_send > 0) sleep(_sleep_between_send); + #if DEBUG == 1 + Serial.print(F("SEND D=")); + Serial.print(message.destination); + Serial.print(F(" I=")); + Serial.print(message.sensor); + Serial.print(F(" C=")); + Serial.print(message.getCommand()); + Serial.print(F(" T=")); + Serial.print(message.type); + Serial.print(F(" S=")); + Serial.print(message.getString()); + Serial.print(F(" I=")); + Serial.print(message.getInt()); + Serial.print(F(" F=")); + Serial.println(message.getFloat()); + #endif + send(message,_ack); + } +} + +// 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 = 0; + if (_battery_internal_vcc || _battery_pin == -1) volt = getVcc(); + else volt = analogRead(_battery_pin) * _battery_volts_per_bit; + // 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(F("BATT V=")); + Serial.print(volt); + Serial.print(F(" P=")); + Serial.println(percentage); + #endif + #if 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,_ack); + } + #endif + #ifndef MY_GATEWAY_ESP8266 + // REBOOT: reboot the board + else if (strcmp(message, "REBOOT") == 0) { + #if DEBUG == 1 + Serial.println(F("REBOOT")); + #endif + // set the reboot pin connected to RST to low so to reboot the board + _send(_msg.set(message)); + // Software reboot with watchdog timer. Enter Watchdog Configuration mode: + WDTCSR |= (1< -1) { + // woke up by an interrupt + int pin_number = -1; + int interrupt_mode = -1; + // map the interrupt to the pin + if (digitalPinToInterrupt(INTERRUPT_PIN_1) == interrupt) { + pin_number = INTERRUPT_PIN_1; + interrupt_mode = _interrupt_1_mode; + } + if (digitalPinToInterrupt(INTERRUPT_PIN_2) == interrupt) { + pin_number = INTERRUPT_PIN_2; + interrupt_mode = _interrupt_2_mode; + } + _last_interrupt_pin = pin_number; + #if DEBUG == 1 + Serial.print(F("WAKE P=")); + Serial.print(pin_number); + Serial.print(F(", M=")); + 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; + } + } + // coming out of sleep + #if DEBUG == 1 + Serial.println(F("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 (ignoring if woke up by an interrupt) + if (interrupt == -1 || _battery_report_with_interrupt) _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 +} + +// present the service +void NodeManager::_present(int child_id, int type) { + #if DEBUG == 1 + Serial.print(F("PRES I=")); + Serial.print(child_id); + Serial.print(F(", T=")); + Serial.println(type); + #endif + if (_sleep_between_send > 0) sleep(_sleep_between_send); + present(child_id,type,"",_ack); +} + +// 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; + } +} + +// 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/temp_hum_sensor/src/NodeManager.h b/temp_hum_sensor/src/NodeManager.h new file mode 100644 index 0000000..6e3ed5e --- /dev/null +++ b/temp_hum_sensor/src/NodeManager.h @@ -0,0 +1,1075 @@ +/* + * NodeManager + */ +#ifndef NodeManager_h +#define NodeManager_h + +#include + +// define NodeManager version +#define VERSION "1.5" + +/*********************************** + Constants +*/ + +// define sleep mode +#define IDLE 0 +#define SLEEP 1 +#define WAIT 2 +#define ALWAYS_ON 3 + +// 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 + +/************************************ + * Include user defined configuration settings + */ + +#include "config.h" + +/*********************************** + Default configuration settings +*/ + +// if enabled, enable the capability to power on sensors with the arduino's pins to save battery while sleeping +#ifndef POWER_MANAGER + #define POWER_MANAGER 1 +#endif +// if enabled, will load the battery manager library to allow the battery level to be reported automatically or on demand +#ifndef BATTERY_MANAGER + #define BATTERY_MANAGER 1 +#endif +// if enabled, allow modifying the configuration remotely by interacting with the configuration child id +#ifndef REMOTE_CONFIGURATION + #define REMOTE_CONFIGURATION 1 +#endif +// if enabled, persist the configuration settings on EEPROM +#ifndef PERSIST + #define PERSIST 0 +#endif + +// if enabled, enable debug messages on serial port +#ifndef DEBUG + #define DEBUG 1 +#endif + +// if enabled, send a SLEEPING and AWAKE service messages just before entering and just after leaving a sleep cycle +#ifndef SERVICE_MESSAGES + #define SERVICE_MESSAGES 1 +#endif +// if enabled, a battery sensor will be created at BATTERY_CHILD_ID and will report vcc voltage together with the battery level percentage +#ifndef BATTERY_SENSOR + #define BATTERY_SENSOR 1 +#endif + +// the child id used to allow remote configuration +#ifndef CONFIGURATION_CHILD_ID + #define CONFIGURATION_CHILD_ID 200 +#endif +// the child id used to report the battery voltage to the controller +#ifndef BATTERY_CHILD_ID + #define BATTERY_CHILD_ID 201 +#endif + +// Enable this module to use one of the following sensors: SENSOR_ANALOG_INPUT, SENSOR_LDR, SENSOR_THERMISTOR, SENSOR_MQ, SENSOR_ACS712 +#ifndef MODULE_ANALOG_INPUT + #define MODULE_ANALOG_INPUT 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_DIGITAL_INPUT +#ifndef MODULE_DIGITAL_INPUT + #define MODULE_DIGITAL_INPUT 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_DIGITAL_OUTPUT, SENSOR_RELAY, SENSOR_LATCHING_RELAY +#ifndef MODULE_DIGITAL_OUTPUT + #define MODULE_DIGITAL_OUTPUT 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_SHT21, SENSOR_HTU21D +#ifndef MODULE_SHT21 + #define MODULE_SHT21 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_DHT11, SENSOR_DHT22 +#ifndef MODULE_DHT + #define MODULE_DHT 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_SWITCH, SENSOR_DOOR, SENSOR_MOTION +#ifndef MODULE_SWITCH + #define MODULE_SWITCH 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_DS18B20 +#ifndef MODULE_DS18B20 + #define MODULE_DS18B20 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_BH1750 +#ifndef MODULE_BH1750 + #define MODULE_BH1750 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_MLX90614 +#ifndef MODULE_MLX90614 + #define MODULE_MLX90614 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_BME280 +#ifndef MODULE_BME280 + #define MODULE_BME280 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_SONOFF +#ifndef MODULE_SONOFF + #define MODULE_SONOFF 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_BMP085 +#ifndef MODULE_BMP085 + #define MODULE_BMP085 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_HCSR04 +#ifndef MODULE_HCSR04 + #define MODULE_HCSR04 0 +#endif +// Enable this module to use one of the following sensors: SENSOR_MCP9808 +#ifndef MODULE_MCP9808 + #define MODULE_MCP9808 0 +#endif + +/*********************************** + Sensors types +*/ +#if MODULE_ANALOG_INPUT == 1 + // Generic analog sensor, return a pin's analog value or its percentage + #define SENSOR_ANALOG_INPUT 1 + // LDR sensor, return the light level of an attached light resistor in percentage + #define SENSOR_LDR 2 + // Thermistor sensor, return the temperature based on the attached thermistor + #define SENSOR_THERMISTOR 3 + // MQ2 air quality sensor + #define SENSOR_MQ 19 + // ML8511 UV sensor + #define SENSOR_ML8511 20 + // Current sensor + #define SENSOR_ACS712 24 + // rain gauge sensor + #define SENSOR_RAIN_GAUGE 26 +#endif +#if MODULE_DIGITAL_INPUT == 1 + // Generic digital sensor, return a pin's digital value + #define SENSOR_DIGITAL_INPUT 4 +#endif +#if MODULE_DIGITAL_OUTPUT == 1 + // Generic digital output sensor, allows setting the digital output of a pin to the requested value + #define SENSOR_DIGITAL_OUTPUT 5 + // Relay sensor, allows activating the relay + #define SENSOR_RELAY 6 + // Latching Relay sensor, allows activating the relay with a pulse + #define SENSOR_LATCHING_RELAY 7 +#endif +#if MODULE_DHT == 1 + // DHT11/DHT22 sensors, return temperature/humidity based on the attached DHT sensor + #define SENSOR_DHT11 8 + #define SENSOR_DHT22 9 +#endif +#if MODULE_SHT21 == 1 + // SHT21 sensor, return temperature/humidity based on the attached SHT21 sensor + #define SENSOR_SHT21 10 + #define SENSOR_HTU21D 15 +#endif +#if MODULE_SWITCH == 1 + // Generic switch, wake up the board when a pin changes status + #define SENSOR_SWITCH 11 + // Door sensor, wake up the board and report when an attached magnetic sensor has been opened/closed + #define SENSOR_DOOR 12 + // Motion sensor, wake up the board and report when an attached PIR has triggered + #define SENSOR_MOTION 13 +#endif +#if MODULE_DS18B20 == 1 + // DS18B20 sensor, return the temperature based on the attached sensor + #define SENSOR_DS18B20 14 +#endif +#if MODULE_BH1750 == 1 + // BH1750 sensor, return light in lux + #define SENSOR_BH1750 16 +#endif +#if MODULE_MLX90614 == 1 + // MLX90614 sensor, contactless temperature sensor + #define SENSOR_MLX90614 17 +#endif +#if MODULE_BME280 == 1 + // MLX90614 sensor, contactless temperature sensor + #define SENSOR_BME280 18 +#endif +#if MODULE_SONOFF == 1 + // Sonoff wireless smart switch + #define SENSOR_SONOFF 21 +#endif +#if MODULE_BMP085 == 1 + // BMP085/BMP180 sensor, return temperature and pressure + #define SENSOR_BMP085 22 +#endif +#if MODULE_HCSR04 == 1 + // HC-SR04 sensor, return the distance between the sensor and an object + #define SENSOR_HCSR04 23 +#endif +#if MODULE_MCP9808 == 1 + // MCP9808 sensor, precision temperature sensor + #define SENSOR_MCP9808 25 +#endif +// last Id: 26 +/*********************************** + Libraries +*/ + +// include supporting libraries +#ifdef MY_USE_UDP + #include +#endif +#ifdef MY_GATEWAY_ESP8266 + #include +#endif + +// include MySensors libraries +#include + +// include third party libraries +#if MODULE_DHT == 1 + #include +#endif +#if MODULE_SHT21 == 1 + #include + #include +#endif +#if MODULE_DS18B20 == 1 + #include + #include +#endif +#if MODULE_BH1750 == 1 + #include + #include +#endif +#if MODULE_MLX90614 == 1 + #include + #include +#endif +#if MODULE_BME280 == 1 + #include + #include + #include + #include +#endif +#if MODULE_SONOFF == 1 + #include +#endif +#if MODULE_BMP085 == 1 + #include + #include +#endif +#if MODULE_HCSR04 == 1 + #include +#endif +#if MODULE_MCP9808 == 1 + #include + #include "Adafruit_MCP9808.h" +#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, int wait_time = 50); + void powerOn(); + void powerOff(); + float getVcc(); + bool isConfigured(); + private: + int _vcc_pin = -1; + int _ground_pin = -1; + long _wait = 0; +}; + + +/*************************************** + 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(); + // description of the sensor (default: '') + void setDescription(char *value); + // set this to true if you want destination node to send ack back to this node (default: false) + void setAck(bool 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); + int getValueType(); + // for float values, set the float precision (default: 2) + void setFloatPrecision(int value); + // optionally sleep interval in milliseconds before sending each message to the radio network (default: 0) + void setSleepBetweenSend(int value); + // set the interrupt pin the sensor is attached to so its loop() will be executed only upon that interrupt (default: -1) + void setInterruptPin(int value); + int getInterruptPin(); + #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, int wait_time = 50); + // if enabled the pins will be automatically powered on while awake and off during sleeping (default: true) + void setAutoPowerPins(bool value); + // manually turn the power on + void powerOn(); + // manually turn the power off + void powerOff(); + #endif + // get the latest recorded value from the sensor + int getValueInt(); + float getValueFloat(); + char* getValueString(); + // define what to do at each stage of the sketch + virtual void before(); + virtual void presentation(); + virtual void setup(); + virtual void loop(const MyMessage & message); + virtual void receive(const MyMessage & message); + // abstract functions, subclasses need to implement + virtual void onBefore() = 0; + virtual void onSetup() = 0; + virtual void onLoop() = 0; + virtual void onReceive(const MyMessage & message) = 0; + protected: + MyMessage _msg; + int _sleep_between_send = 0; + int _pin = -1; + int _child_id; + int _presentation = S_CUSTOM; + int _type = V_CUSTOM; + char* _description = ""; + bool _ack = false; + int _retries = 1; + int _samples = 1; + int _samples_interval = 0; + bool _track_last_value = false; + int _cycles = 0; + int _force_update = -1; + 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 = ""; + int _interrupt_pin = -1; + #if POWER_MANAGER == 1 + PowerManager _powerManager; + bool _auto_power_pins = true; + #endif + void _send(MyMessage & msg); +}; + +/* + 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 onSetup(); + 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(long 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(long value); + // set a temperature offset + void setOffset(float value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + long _nominal_resistor = 10000; + int _nominal_temperature = 25; + int _b_coefficient = 3950; + long _series_resistor = 10000; + float _offset = 0; +}; + +/* + SensorMQ + */ +class SensorMQ: public Sensor { + public: + SensorMQ(int child_id, int pin); + // define the target gas whose ppm has to be returned. 0: LPG, 1: CO, 2: Smoke (default: 1); + void setTargetGas(int value); + // define the load resistance on the board, in kilo ohms (default: 1); + void setRlValue(float value); + // define the Ro resistance on the board (default: 10000); + void setRoValue(float value); + // Sensor resistance in clean air (default: 9.83); + void setCleanAirFactor(float value); + // define how many samples you are going to take in the calibration phase (default: 50); + void setCalibrationSampleTimes(int value); + // define the time interal(in milisecond) between each samples in the cablibration phase (default: 500); + void setCalibrationSampleInterval(int value); + // define how many samples you are going to take in normal operation (default: 50); + void setReadSampleTimes(int value); + // define the time interal(in milisecond) between each samples in the normal operations (default: 5); + void setReadSampleInterval(int value); + // set the LPGCurve array (default: {2.3,0.21,-0.47}) + void setLPGCurve(float *value); + // set the COCurve array (default: {2.3,0.72,-0.34}) + void setCOCurve(float *value); + // set the SmokeCurve array (default: {2.3,0.53,-0.44}) + void setSmokeCurve(float *value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + float _rl_value = 1.0; + float _ro_clean_air_factor = 9.83; + int _calibration_sample_times = 50; + int _calibration_sample_interval = 500; + int _read_sample_interval = 50; + int _read_sample_times = 5; + float _ro = 10000.0; + float _LPGCurve[3] = {2.3,0.21,-0.47}; + float _COCurve[3] = {2.3,0.72,-0.34}; + float _SmokeCurve[3] = {2.3,0.53,-0.44}; + float _MQResistanceCalculation(int raw_adc); + float _MQCalibration(); + float _MQRead(); + int _MQGetGasPercentage(float rs_ro_ratio, int gas_id); + int _MQGetPercentage(float rs_ro_ratio, float *pcurve); + int _gas_lpg = 0; + int _gas_co = 1; + int _gas_smoke = 2; + int _target_gas = _gas_co; +}; + +/* + SensorML8511 +*/ + +class SensorML8511: public Sensor { + public: + SensorML8511(int child_id, int pin); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + float _mapfloat(float x, float in_min, float in_max, float out_min, float out_max); +}; + +/* + SensorACS712 +*/ + +class SensorACS712: public Sensor { + public: + SensorACS712(int child_id, int pin); + // set how many mV are equivalent to 1 Amp. The value depends on the module (100 for 20A Module, 66 for 30A Module) (default: 185); + void setmVPerAmp(int value); + // set ACS offset (default: 2500); + void setOffset(int value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + int _ACS_offset = 2500; + int _mv_per_amp = 185; +}; + +/* + SensorRainGauge +*/ + +class SensorRainGauge: public Sensor { + public: + SensorRainGauge(int child_id, int pin); + // set how frequently to report back to the controller in minutes. After reporting the measure is resetted (default: 60); + void setReportInterval(int value); + // set how many mm of rain to count for each tip (default: 0.11); + void setSingleTip(float value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + public: + static void _onTipped(); + static long _last_tip; + static long _count; + protected: + int _report_interval = 60; + float _single_tip = 0.11; + long _last_report = 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 onSetup(); + 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 which value to set to the output when set to on (default: HIGH) + void setOnValue(int value); + // when legacy mode is enabled expect a REQ message to trigger, otherwise the default SET (default: false) + void setLegacyMode(bool value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + int _initial_value = LOW; + int _on_value = HIGH; + int _state = 0; + int _pulse_width = 0; + bool _legacy_mode = false; +}; + + +/* + SensorRelay +*/ +class SensorRelay: public SensorDigitalOutput { + public: + SensorRelay(int child_id, int pin); + // define what to do at each stage of the sketch + void onLoop(); +}; + +/* + 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 onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + // constants + const static int TEMPERATURE = 0; + const static int HUMIDITY = 1; + protected: + DHT* _dht; + int _dht_type = DHT11; + float _offset = 0; + int _sensor_type = 0; +}; +#endif + +/* + SensorSHT21: temperature and humidity sensor +*/ +#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 onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + // constants + const static int TEMPERATURE = 0; + const static int HUMIDITY = 1; + protected: + float _offset = 0; + int _sensor_type = 0; +}; + +/* + SensorHTU21D: temperature and humidity sensor +*/ + +class SensorHTU21D: public SensorSHT21 { + public: + SensorHTU21D(int child_id, int pin); +}; +#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); + // Set initial value on the interrupt pin (default: HIGH) + void setInitial(int value); + int getInitial(); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + int _debounce = 0; + int _trigger_time = 0; + int _mode = CHANGE; + int _initial = HIGH; +}; + +/* + * 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); + // return the sensors' device address + DeviceAddress* getDeviceAddress(); + // returns the sensor's resolution in bits + int getResolution(); + // set the sensor's resolution in bits + void setResolution(int value); + // sleep while DS18B20 calculates temperature (default: false) + void setSleepDuringConversion(bool value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + float _offset = 0; + int _index; + bool _sleep_during_conversion = false; + DallasTemperature* _sensors; + DeviceAddress _device_address; +}; +#endif + +/* + SensorBH1750 +*/ +#if MODULE_BH1750 == 1 +class SensorBH1750: public Sensor { + public: + SensorBH1750(int child_id); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + BH1750* _lightSensor; +}; +#endif + +/* + SensorMLX90614 +*/ +#if MODULE_MLX90614 == 1 +class SensorMLX90614: public Sensor { + public: + SensorMLX90614(int child_id, Adafruit_MLX90614* mlx, int sensor_type); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + // constants + const static int TEMPERATURE_AMBIENT = 0; + const static int TEMPERATURE_OBJECT = 1; + protected: + Adafruit_MLX90614* _mlx; + int _sensor_type; +}; +#endif + + +/* + * SensorBosch +*/ + +#if MODULE_BME280 == 1 || MODULE_BMP085 == 1 +class SensorBosch: public Sensor { + public: + SensorBosch(int child_id, int sensor_type); + // define how many pressure samples to keep track of for calculating the forecast (default: 5) + void setForecastSamplesCount(int value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + // constants + const static int TEMPERATURE = 0; + const static int HUMIDITY = 1; + const static int PRESSURE = 2; + const static int FORECAST = 3; + static uint8_t GetI2CAddress(uint8_t chip_id); + protected: + int _sensor_type; + char* _weather[6] = { "stable", "sunny", "cloudy", "unstable", "thunderstorm", "unknown" }; + int _forecast_samples_count = 5; + float* _forecast_samples; + int _minute_count = 0; + float _pressure_avg; + float _pressure_avg2; + float _dP_dt; + bool _first_round = true; + float _getLastPressureSamplesAverage(); + void _forecast(float pressure); +}; +#endif + +/* + SensorBME280 +*/ +#if MODULE_BME280 == 1 +class SensorBME280: public SensorBosch { + public: + SensorBME280(int child_id, Adafruit_BME280* bme, int sensor_type); + void onLoop(); + protected: + Adafruit_BME280* _bme; +}; +#endif + +/* + SensorBMP085 +*/ +#if MODULE_BMP085 == 1 +class SensorBMP085: public SensorBosch { + public: + SensorBMP085(int child_id, Adafruit_BMP085* bmp, int sensor_type); + void onLoop(); + protected: + Adafruit_BMP085* _bmp; +}; +#endif + +/* + SensorHCSR04 +*/ +#if MODULE_HCSR04 == 1 +class SensorHCSR04: public Sensor { + public: + SensorHCSR04(int child_id, int pin); + // Arduino pin tied to trigger pin on the ultrasonic sensor (default: the pin set while registering the sensor) + void setTriggerPin(int value); + // Arduino pin tied to echo pin on the ultrasonic sensor (default: the pin set while registering the sensor) + void setEchoPin(int value); + // Maximum distance we want to ping for (in centimeters) (default: 300) + void setMaxDistance(int value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + int _trigger_pin; + int _echo_pin; + int _max_distance = 300; + NewPing* _sonar; +}; +#endif + +/* + SensorSonoff +*/ +#if MODULE_SONOFF == 1 +class SensorSonoff: public Sensor { + public: + SensorSonoff(int child_id); + // set the button's pin (default: 0) + void setButtonPin(int value); + // set the relay's pin (default: 12) + void setRelayPin(int value); + // set the led's pin (default: 13) + void setLedPin(int value); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + Bounce _debouncer = Bounce(); + int _button_pin = 0; + int _relay_pin = 12; + int _led_pin = 13; + int _old_value = 0; + bool _state = false; + int _relay_on = 1; + int _relay_off = 0; + int _led_on = 0; + int _led_off = 1; + void _blink(); + void _toggle(); +}; +#endif + +/* + SensorMCP9808 +*/ +#if MODULE_MCP9808 == 1 +class SensorMCP9808: public Sensor { + public: + SensorMCP9808(int child_id, Adafruit_MCP9808* mcp); + // define what to do at each stage of the sketch + void onBefore(); + void onSetup(); + void onLoop(); + void onReceive(const MyMessage & message); + protected: + Adafruit_MCP9808* _mcp; +}; +#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); + // send the same service message multiple times (default: 1) + void setRetries(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); + // after how many sleeping cycles report the battery level to the controller. When reset the battery is always reported (default: 10) + void setBatteryReportCycles(int value); + // if true, the battery level will be evaluated by measuring the internal vcc without the need to connect any pin, if false the voltage divider methon will be used (default: true) + void setBatteryInternalVcc(bool value); + // if setBatteryInternalVcc() is set to false, the analog pin to which the battery's vcc is attached (https://www.mysensors.org/build/battery) (default: -1) + void setBatteryPin(int value); + // if setBatteryInternalVcc() is set to false, the volts per bit ratio used to calculate the battery voltage (default: 0.003363075) + void setBatteryVoltsPerBit(float value); + // If true, wake up by an interrupt counts as a valid cycle for battery reports otherwise only uninterrupted sleep cycles would contribute (default: true) + void setBatteryReportWithInterrupt(bool value); + #endif + // define the way the node should behave. It can be IDLE (stay awake withtout executing each sensors' loop), SLEEP (go to sleep for the configured interval), WAIT (wait for the configured interval), ALWAYS_ON (stay awake and execute each sensors' loop) + void setSleepMode(int value); + void setMode(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 setSleepUnit(int value); + // configure the node's behavior, parameters are mode, time and unit + void setSleep(int value1, int value2, int value3); + // 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); + // 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); + // optionally sleep interval in milliseconds before sending each message to the radio network (default: 0) + void setSleepBetweenSend(int value); + // 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); + // un-register a sensor + void unRegisterSensor(int sensor_index); + // return a sensor by its index + Sensor* get(int sensor_index); + Sensor* getSensor(int sensor_index); + // assign a different child id to a sensor + bool renameSensor(int old_child_id, int new_child_id); + #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, int wait_time = 50); + // if enabled the pins will be automatically powered on while awake and off during sleeping (default: true) + void setAutoPowerPins(bool value); + // manually turn the power on + void powerOn(); + // manually turn the power off + void powerOff(); + #endif + // set this to true if you want destination node to send ack back to this node (default: false) + void setAck(bool value); + // request and return the current timestamp from the controller + long getTimestamp(); + // hook into the main sketch functions + void before(); + void presentation(); + void setup(); + void loop(); + void receive(const MyMessage & msg); + void receiveTime(unsigned long ts); + private: + #if BATTERY_MANAGER == 1 + float _battery_min = 2.6; + float _battery_max = 3.3; + int _battery_report_cycles = 10; + bool _battery_report_with_interrupt = true; + bool _battery_internal_vcc = true; + int _battery_pin = -1; + float _battery_volts_per_bit = 0.003363075; + int _cycles = 0; + float _getVcc(); + #endif + #if POWER_MANAGER == 1 + // to optionally controller power pins + PowerManager _powerManager; + bool _auto_power_pins = true; + #endif + MyMessage _msg; + void _send(MyMessage & msg); + int _sleep_mode = IDLE; + int _sleep_time = 0; + int _sleep_unit = MINUTES; + int _sleep_interrupt_pin = -1; + int _sleep_between_send = 0; + int _retries = 1; + 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 _last_interrupt_pin = -1; + long _timestamp = -1; + Sensor* _sensors[255] = {0}; + bool _ack = false; + void _process(const char * message); + void _sleep(); + void _present(int child_id, int type); + int _getAvailableChildId(); + int _getInterruptInitialValue(int mode); +}; + +#endif diff --git a/temp_hum_sensor/src/config.h b/temp_hum_sensor/src/config.h new file mode 100644 index 0000000..ffbdd90 --- /dev/null +++ b/temp_hum_sensor/src/config.h @@ -0,0 +1,134 @@ +#ifndef config_h +#define config_h + +/********************************** + * Sketch configuration + */ + +#define SKETCH_NAME "NodeManager" +#define SKETCH_VERSION "1.0" + +/********************************** + * MySensors node configuration + */ + +// General settings +#define MY_BAUD_RATE 9600 +//#define MY_DEBUG +//#define MY_NODE_ID 100 + +// NRF24 radio settings +#define MY_RADIO_NRF24 +//#define MY_RF24_ENABLE_ENCRYPTION +//#define MY_RF24_CHANNEL 76 +//#define MY_RF24_PA_LEVEL RF24_PA_HIGH +//#define MY_DEBUG_VERBOSE_RF24 + +// RFM69 radio settings +//#define MY_RADIO_RFM69 +//#define MY_RFM69_FREQUENCY RF69_868MHZ +//#define MY_IS_RFM69HW +//#define MY_DEBUG_VERBOSE_RFM69 +//#define MY_RFM69_NEW_DRIVER +//#define MY_RFM69_ENABLE_ENCRYPTION +//#define MY_RFM69_NETWORKID 100 +//#define MY_RF69_IRQ_PIN D1 +//#define MY_RF69_IRQ_NUM MY_RF69_IRQ_PIN +//#define MY_RF69_SPI_CS D2 + +/********************************** + * MySensors gateway configuration + */ +// Common gateway settings +//#define MY_REPEATER_FEATURE + +// Serial gateway settings +//#define MY_GATEWAY_SERIAL + +// Ethernet gateway settings +//#define MY_GATEWAY_W5100 + +// ESP8266 gateway settings +//#define MY_GATEWAY_ESP8266 +//#define MY_ESP8266_SSID "" +//#define MY_ESP8266_PASSWORD "" + +// Gateway networking settings +//#define MY_IP_ADDRESS 192,168,178,87 +//#define MY_IP_GATEWAY_ADDRESS 192,168,178,1 +//#define MY_IP_SUBNET_ADDRESS 255,255,255,0 +//#define MY_PORT 5003 +//#define MY_GATEWAY_MAX_CLIENTS 2 +//#define MY_USE_UDP + +// Gateway MQTT settings +//#define MY_GATEWAY_MQTT_CLIENT +//#define MY_CONTROLLER_IP_ADDRESS 192, 168, 178, 68 +//#define MY_PORT 1883 +//#define MY_MQTT_USER "username" +//#define MY_MQTT_PASSWORD "password" +//#define MY_MQTT_CLIENT_ID "mysensors-1" +//#define MY_MQTT_PUBLISH_TOPIC_PREFIX "mygateway1-out" +//#define MY_MQTT_SUBSCRIBE_TOPIC_PREFIX "mygateway1-in" + +// Gateway inclusion mode +//#define MY_INCLUSION_MODE_FEATURE +//#define MY_INCLUSION_BUTTON_FEATURE +//#define MY_INCLUSION_MODE_DURATION 60 +//#define MY_DEFAULT_LED_BLINK_PERIOD 300 + +// Gateway Leds settings +//#define MY_DEFAULT_ERR_LED_PIN 4 +//#define MY_DEFAULT_RX_LED_PIN 5 +//#define MY_DEFAULT_TX_LED_PIN 6 + +/*********************************** + * NodeManager configuration + */ + +// if enabled, enable debug messages on serial port +#define DEBUG 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 remote configuration settings on EEPROM +#define PERSIST 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 +// if enabled, send a SLEEPING and AWAKE service messages just before entering and just after leaving a sleep cycle and STARTED when starting/rebooting +#define SERVICE_MESSAGES 0 + +// Enable this module to use one of the following sensors: SENSOR_ANALOG_INPUT, SENSOR_LDR, SENSOR_THERMISTOR, SENSOR_MQ, SENSOR_ML8511, SENSOR_ACS712, SENSOR_RAIN_GAUGE +#define MODULE_ANALOG_INPUT 0 +// Enable this module to use one of the following sensors: SENSOR_DIGITAL_INPUT +#define MODULE_DIGITAL_INPUT 0 +// Enable this module to use one of the following sensors: SENSOR_DIGITAL_OUTPUT, SENSOR_RELAY, SENSOR_LATCHING_RELAY +#define MODULE_DIGITAL_OUTPUT 0 +// Enable this module to use one of the following sensors: SENSOR_DHT11, SENSOR_DHT22 +#define MODULE_DHT 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_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 +// Enable this module to use one of the following sensors: SENSOR_BH1750 +#define MODULE_BH1750 0 +// Enable this module to use one of the following sensors: SENSOR_MLX90614 +#define MODULE_MLX90614 0 +// Enable this module to use one of the following sensors: SENSOR_BME280 +#define MODULE_BME280 0 +// Enable this module to use one of the following sensors: SENSOR_SONOFF +#define MODULE_SONOFF 0 +// Enable this module to use one of the following sensors: SENSOR_BMP085 +#define MODULE_BMP085 0 +// Enable this module to use one of the following sensors: SENSOR_HCSR04 +#define MODULE_HCSR04 0 +// Enable this module to use one of the following sensors: SENSOR_MCP9808 +#define MODULE_MCP9808 0 +#endif + diff --git a/temp_hum_sensor/src/temp_hum_sensor.ino b/temp_hum_sensor/src/temp_hum_sensor.ino index 021c8fc..7ee288b 100644 --- a/temp_hum_sensor/src/temp_hum_sensor.ino +++ b/temp_hum_sensor/src/temp_hum_sensor.ino @@ -1,142 +1,81 @@ -/** - * The MySensors Arduino library handles the wireless radio link and protocol - * between your home built sensors/actuators and HA controller of choice. - * The sensors forms a self healing radio network with optional repeaters. Each - * repeater and gateway builds a routing tables in EEPROM which keeps track of the - * network topology allowing messages to be routed to nodes. - * - * Created by Henrik Ekblad - * Copyright (C) 2013-2015 Sensnology AB - * Full contributor list: https://github.com/mysensors/Arduino/graphs/contributors - * - * Documentation: http://www.mysensors.org - * Support Forum: http://forum.mysensors.org - * - * This program is free software; you can redistribute it and/or - * modify it under the terms of the GNU General Public License - * version 2 as published by the Free Software Foundation. - * - ******************************* - * - * REVISION HISTORY - * Version 1.0 - Henrik EKblad - * - * DESCRIPTION - * This sketch provides an example how to implement a humidity/temperature - * sensor using DHT11/DHT-22 - * http://www.mysensors.org/build/humidity +/* +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://github.com/mysensors/NodeManager */ -// Enable debug prints -#define MY_DEBUG -// Enable and select radio type attached -#define MY_RADIO_NRF24 -#define MY_RF24_PA_LEVEL RF24_PA_LOW -#if F_CPU == 8000000L -#define MY_BAUD_RATE 38400 +// load user settings +#include "config.h" +// include supporting libraries +#ifdef MY_GATEWAY_ESP8266 + #include #endif - -#define MY_GATEWAY_SERIAL -//#define MY_RADIO_RFM69 - -#include +// load MySensors library #include -#include -#define MY_NODE_ID 10 -#define MY_PARENT_NODE_ID 0 -#define CHILD_ID_HUM 0 -#define CHILD_ID_TEMP 1 -#define DHT_DATA_PIN 3 +// load NodeManager library +#include "NodeManager.h" -static const uint64_t UPDATE_INTERVAL = 6000; -static const uint8_t FORCE_UPDATE_N_READS = 10; +// create a NodeManager instance +NodeManager nodeManager; -DHT dht; -float lastTemp; -float lastHum; -boolean metric = true; +// before +void before() { + // setup the serial port baud rate + Serial.begin(MY_BAUD_RATE); + /* + * Register below your sensors + */ + nodeManager.setSleep(SLEEP,10,MINUTES); + nodeManager.setBatteryMin(1.8); + nodeManager.setBatteryMax(2.4); + nodeManager.setBatteryInternalVcc(true); + nodeManager.setBatteryPin(A0); -uint8_t nNoUpdatesTemp; -uint8_t nNoUpdatesHum; + nodeManager.registerSensor(SENSOR_DHT11, 3); -MyMessage msgHum(CHILD_ID_HUM, V_HUM); -MyMessage msgTemp(CHILD_ID_TEMP, V_TEMP); - -void setup() -{ - dht.setup(DHT_DATA_PIN); - - metric = getConfig().isMetric; - if (UPDATE_INTERVAL <= dht.getMinimumSamplingPeriod()) { - Serial.println("Warning: UPDATE_INTERVAL is smaller than supported by the sensor!"); - } - MY_SERIALDEVICE.println(__FILE__); - MY_SERIALDEVICE.println(MYSENSORS_LIBRARY_VERSION); - MY_SERIALDEVICE.println(hwFreeMem()); - MY_SERIALDEVICE.println(hwCPUVoltage()); - MY_SERIALDEVICE.println(hwCPUFrequency()); - MY_SERIALDEVICE.println(F_CPU); - MY_SERIALDEVICE.println(F("**********")); - sleep(dht.getMinimumSamplingPeriod()); + /* + * Register above your sensors + */ + nodeManager.before(); } -void presentation() -{ - // Send the Sketch Version Information to the Gateway - sendSketchInfo("Humidity", "1.0"); +// presentation +void presentation() { + // call NodeManager presentation routine + nodeManager.presentation(); +} - // Register all sensors to gw (they will be created as child devices) - present(CHILD_ID_HUM, S_HUM); - present(CHILD_ID_TEMP, S_TEMP); +// setup +void setup() { + // call NodeManager setup routine + nodeManager.setup(); +} + +// loop +void loop() { + // call NodeManager loop routine + nodeManager.loop(); + +} + +// receive +void receive(const MyMessage &message) { + // call NodeManager receive routine + nodeManager.receive(message); +} + +// receiveTime +void receiveTime(unsigned long ts) { + // call NodeManager receiveTime routine + nodeManager.receiveTime(ts); } -void loop() -{ - delay(dht.getMinimumSamplingPeriod()); - - float temperature = dht.getTemperature(); - if (isnan(temperature)) { - Serial.println("Failed reading temperature from DHT"); - } else if (temperature != lastTemp || - nNoUpdatesTemp == FORCE_UPDATE_N_READS) { - lastTemp = temperature; - if (!metric) { - temperature = dht.toFahrenheit(temperature); - } - - nNoUpdatesTemp = 0; - send(msgTemp.set(temperature, 1)); -#ifdef MYDEBUG - Serial.print("T: "); - Serial.println(temperature); -#endif - - } else { - // Increase no update counter if the temperature stayed the same - nNoUpdatesTemp++; - } - - float humidity = dht.getHumidity(); - if (isnan(humidity)) { - Serial.println("Failed reading humidity from DHT"); - } else if (humidity != lastHum || nNoUpdatesHum == FORCE_UPDATE_N_READS) { - // Only send humidity if it changed since the last measurement or if we didn't send an update for n times - lastHum = humidity; - // Reset no updates counter - nNoUpdatesHum = 0; - send(msgHum.set(humidity, 1)); - -#ifdef MY_DEBUG - Serial.print("H: "); - Serial.println(humidity); -#endif - } else { - // Increase no update counter if the humidity stayed the same - nNoUpdatesHum++; - } - - - sleep(UPDATE_INTERVAL); //sleep a bit -}