From 42a396363c1d1828610cba2b37dda86b0300d342 Mon Sep 17 00:00:00 2001 From: Simon Milvert Date: Sat, 17 Mar 2018 20:57:18 +0100 Subject: [PATCH] Remove node manager on controller --- mysensors_controller/src/NodeManager.cpp | 2627 ----------------- mysensors_controller/src/NodeManager.h | 1075 ------- mysensors_controller/src/config.h | 136 - .../src/mysensors_controller.ino | 140 +- 4 files changed, 79 insertions(+), 3899 deletions(-) delete mode 100644 mysensors_controller/src/NodeManager.cpp delete mode 100644 mysensors_controller/src/NodeManager.h delete mode 100644 mysensors_controller/src/config.h diff --git a/mysensors_controller/src/NodeManager.cpp b/mysensors_controller/src/NodeManager.cpp deleted file mode 100644 index cfb1c42..0000000 --- a/mysensors_controller/src/NodeManager.cpp +++ /dev/null @@ -1,2627 +0,0 @@ -/* - * 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/mysensors_controller/src/NodeManager.h b/mysensors_controller/src/NodeManager.h deleted file mode 100644 index 6e3ed5e..0000000 --- a/mysensors_controller/src/NodeManager.h +++ /dev/null @@ -1,1075 +0,0 @@ -/* - * 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/mysensors_controller/src/config.h b/mysensors_controller/src/config.h deleted file mode 100644 index 0dfefb1..0000000 --- a/mysensors_controller/src/config.h +++ /dev/null @@ -1,136 +0,0 @@ -#ifndef config_h -#define config_h - -/********************************** - * Sketch configuration - */ - -#define SKETCH_NAME "Serial gateway" -#define SKETCH_VERSION "1.1" - -/********************************** - * MySensors node configuration - */ - -// General settings -#define MY_BAUD_RATE 9600 -#define MY_DEBUG -//#define MY_NODE_ID 32 - -// 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_RF24_PA_LEVEL_GW 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 0 -// if enabled, will load the battery manager library to allow the battery level to be reported automatically or on demand -#define BATTERY_MANAGER 0 -// 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 0 -// 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 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/mysensors_controller/src/mysensors_controller.ino b/mysensors_controller/src/mysensors_controller.ino index caf11eb..800ca02 100644 --- a/mysensors_controller/src/mysensors_controller.ino +++ b/mysensors_controller/src/mysensors_controller.ino @@ -1,71 +1,89 @@ -/* -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. +/** +* 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. +* +******************************* +* +* DESCRIPTION +* The ArduinoGateway prints data received from sensors on the serial link. +* The gateway accepts input on seral which will be sent out on radio network. +* +* The GW code is designed for Arduino Nano 328p / 16MHz +* +* Wire connections (OPTIONAL): +* - Inclusion button should be connected between digital pin 3 and GND +* - RX/TX/ERR leds need to be connected between +5V (anode) and digital pin 6/5/4 with resistor 270-330R in a series +* +* LEDs (OPTIONAL): +* - To use the feature, uncomment any of the MY_DEFAULT_xx_LED_PINs +* - RX (green) - blink fast on radio message recieved. In inclusion mode will blink fast only on presentation recieved +* - TX (yellow) - blink fast on radio message transmitted. In inclusion mode will blink slowly +* - ERR (red) - fast blink on error during transmission error or recieve crc error +* +*/ -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 to serial monitor +#define MY_DEBUG + + +// Enable and select radio type attached +#define MY_RADIO_NRF24 + +//#define MY_RF24_PA_LEVEL RF24_PA_LOW + +// Enable serial gateway +#define MY_GATEWAY_SERIAL + +// Define a lower baud rate for Arduino's running on 8 MHz (Arduino Pro Mini 3.3V & SenseBender) +#if F_CPU == 8000000L +#define MY_BAUD_RATE 38400 +#endif + +// Enable inclusion mode +#define MY_INCLUSION_MODE_FEATURE +// Enable Inclusion mode button on gateway +//#define MY_INCLUSION_BUTTON_FEATURE + +// Inverses behavior of inclusion button (if using external pullup) +//#define MY_INCLUSION_BUTTON_EXTERNAL_PULLUP + +// Set inclusion mode duration (in seconds) +#define MY_INCLUSION_MODE_DURATION 60 +// Digital pin used for inclusion mode button +//#define MY_INCLUSION_MODE_BUTTON_PIN 3 + +// Set blinking period +#define MY_DEFAULT_LED_BLINK_PERIOD 300 -// load user settings -#include "config.h" -// include supporting libraries -// 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(); +void setup() +{ + // Setup locally attached sensors + sendSketchInfo("Controller", "1.1"); } -// presentation -void presentation() { - // call NodeManager presentation routine - nodeManager.presentation(); +void presentation() +{ + // Present locally attached sensors } -// setup -void setup() { - // call NodeManager setup routine - nodeManager.setup(); +void loop() +{ + // Send locally attached sensor data here } - -// 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); -} - -