README.md 67 KB
Newer Older
DV's avatar
DV committed
1
2
3
4
5
6
7
8
9
10
11
12
13
NodeManager is intended to take care on your behalf of all those common tasks a MySensors node has to accomplish, speeding up the development cycle of your projects.

NodeManager includes the following main components:

* Sleep manager: allows managing automatically the complexity behind battery-powered sensors spending most of their time sleeping
* Power manager: allows powering on your sensors only while the node is awake
* Battery manager: provides common functionalities to read and report the battery level
* Remote configuration: allows configuring remotely the node without the need to have physical access to it
* Built-in sensors: for the most common sensors, provide embedded code so to allow their configuration with a single line

## Features

* Manage all the aspects of a sleeping cycle by leveraging smart sleep
14
* Allow configuring the node and any attached sensors remotely
DV's avatar
DV committed
15
16
* Allow waking up a sleeping node remotely at the end of a sleeping cycle
* Allow powering on each connected sensor only while the node is awake to save battery
17
* Report battery level periodically and automatically or on demand
user2684's avatar
user2684 committed
18
* Report signal level periodically and automatically or on demand
DV's avatar
DV committed
19
20
21
* Calculate battery level without requiring an additional pin and the resistors
* Allow rebooting the board remotely
* Provide out-of-the-box sensors personalities and automatically execute their main task at each cycle
22
23
* Allow collecting and averaging multiple samples, tracking the last value and forcing periodic updates for any sensor
* Provide buil-in capabilities to handle interrupt-based sensors 
DV's avatar
DV committed
24

25
## Installation
26
27
* Download the package or clone the git repository from https://github.com/mysensors/NodeManager
* Open the provided sketch and save it under a different name
DV's avatar
DV committed
28
29
30
31
32
33
* Open `config.h` and customize both MySensors configuration and NodeManager global settings
* Register your sensors in the sketch file
* Upload the sketch to your arduino board

Please note NodeManager cannot be used as an arduino library since requires access to your MySensors configuration directives, hence its files have to be placed into the same directory of your sketch.

34
### Upgrade
35
36
37
38
* Download the package
* Replace the NodeManager.cpp and NodeManager.h of your project with those just downloaded
* Review the release notes in case there is any manual change required to the existing sketch or config.h file

39
## Configuration
40
NodeManager configuration includes compile-time configuration directives (which can be set in config.h), runtime global and per-sensor configuration settings (which can be set in your sketch).
DV's avatar
DV committed
41

42
### Setup MySensors
DV's avatar
DV committed
43
44
Since NodeManager has to communicate with the MySensors gateway on your behalf, it has to know how to do it. Place on top of the `config.h` file all the MySensors typical directives you are used to set on top of your sketch so both your sketch AND NodeManager will be able to share the same configuration. For example:
~~~c
45
46
47
48
/**********************************
 * Sketch configuration
 */

49
#define SKETCH_NAME "NodeManager"
50
51
52
53
54
55
56
#define SKETCH_VERSION "1.0"

/**********************************
 * MySensors node configuration
 */

// General settings
57
#define MY_BAUD_RATE 9600
DV's avatar
DV committed
58
//#define MY_DEBUG
59
//#define MY_NODE_ID 100
60
//#define MY_SMART_SLEEP_WAIT_DURATION_MS 500
DV's avatar
DV committed
61

62
// NRF24 radio settings
DV's avatar
DV committed
63
64
65
#define MY_RADIO_NRF24
//#define MY_RF24_ENABLE_ENCRYPTION
//#define MY_RF24_CHANNEL 76
66
//#define MY_RF24_PA_LEVEL RF24_PA_HIGH
67
68
//#define MY_DEBUG_VERBOSE_RF24
//#define MY_RF24_DATARATE RF24_250KBPS
DV's avatar
DV committed
69

70
// RFM69 radio settings
DV's avatar
DV committed
71
72
//#define MY_RADIO_RFM69
//#define MY_RFM69_FREQUENCY RF69_868MHZ
user2684's avatar
user2684 committed
73
//#define MY_RFM69_FREQUENCY RFM69_868MHZ
DV's avatar
DV committed
74
//#define MY_IS_RFM69HW
75
//#define MY_RFM69_NEW_DRIVER
DV's avatar
DV committed
76
77
//#define MY_RFM69_ENABLE_ENCRYPTION
//#define MY_RFM69_NETWORKID 100
user2684's avatar
user2684 committed
78
//#define MY_DEBUG_VERBOSE_RFM69
79
80
81
//#define MY_RF69_IRQ_PIN D1
//#define MY_RF69_IRQ_NUM MY_RF69_IRQ_PIN
//#define MY_RF69_SPI_CS D2
user2684's avatar
user2684 committed
82
//#define MY_RFM69_ATC_MODE_DISABLED
83

84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// RS485 serial transport settings
//#define MY_RS485
//#define MY_RS485_BAUD_RATE 9600
//#define MY_RS485_DE_PIN 2
//#define MY_RS485_MAX_MESSAGE_LENGTH 40
//#define MY_RS485_HWSERIAL Serial1

// Message signing settings
//#define MY_SIGNING_SOFT
//#define MY_SIGNING_SOFT_RANDOMSEED_PIN 7
//#define MY_SIGNING_REQUEST_SIGNATURES
//#define MY_SIGNING_ATSHA204

// OTA Firmware update settings
//#define MY_OTA_FIRMWARE_FEATURE
//#define OTA_WAIT_PERIOD 300
//#define FIRMWARE_MAX_REQUESTS 2
//#define MY_OTA_RETRY 2

103
104
105
106
107
108
109
110
111
112
113
114
115
116
/**********************************
 * 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
117
118
//#define MY_ESP8266_SSID ""
//#define MY_ESP8266_PASSWORD ""
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147

// 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
DV's avatar
DV committed
148
~~~
DV's avatar
DV committed
149

150
### Enable/Disable NodeManager's modules
DV's avatar
DV committed
151

152
The next step is to enable NodeManager's additional functionalities and the modules required for your sensors. The directives in the `config.h` file control which module/library/functionality will be made available to your sketch. Enable (e.g. set to 1) only what you need to ensure enough storage is left to your custom code.
DV's avatar
DV committed
153
154

~~~c
155
156
157
158
/***********************************
 * NodeManager configuration
 */

159
160
161
// if enabled, enable debug messages on serial port
#define DEBUG 1

DV's avatar
DV committed
162
// if enabled, enable the capability to power on sensors with the arduino's pins to save battery while sleeping
user2684's avatar
user2684 committed
163
#define POWER_MANAGER 1
DV's avatar
DV committed
164
// if enabled, will load the battery manager library to allow the battery level to be reported automatically or on demand
user2684's avatar
user2684 committed
165
#define BATTERY_MANAGER 1
DV's avatar
DV committed
166
// if enabled, allow modifying the configuration remotely by interacting with the configuration child id
user2684's avatar
user2684 committed
167
#define REMOTE_CONFIGURATION 1
168
// if enabled, persist the remote configuration settings on EEPROM
DV's avatar
DV committed
169
#define PERSIST 0
170
// if enabled, a battery sensor will be created at BATTERY_CHILD_ID and will report vcc voltage together with the battery level percentage
user2684's avatar
user2684 committed
171
172
#define BATTERY_SENSOR 1
// if enabled, a signal sensor will be created at RSSI_CHILD_ID (202 by default) and will report the signal quality of the transport layer
user2684's avatar
user2684 committed
173
#define SIGNAL_SENSOR 0
user2684's avatar
user2684 committed
174
// if enabled, send a SLEEPING and AWAKE service messages just before entering and just after leaving a sleep cycle and STARTED when starting/rebooting
175
#define SERVICE_MESSAGES 0
DV's avatar
DV committed
176

177
// Enable this module to use one of the following sensors: SENSOR_ANALOG_INPUT, SENSOR_LDR, SENSOR_THERMISTOR, SENSOR_ML8511, SENSOR_ACS712, SENSOR_RAIN, SENSOR_SOIL_MOISTURE
DV's avatar
DV committed
178
179
#define MODULE_ANALOG_INPUT 1
// Enable this module to use one of the following sensors: SENSOR_DIGITAL_INPUT
user2684's avatar
user2684 committed
180
#define MODULE_DIGITAL_INPUT 1
DV's avatar
DV committed
181
// Enable this module to use one of the following sensors: SENSOR_DIGITAL_OUTPUT, SENSOR_RELAY, SENSOR_LATCHING_RELAY
user2684's avatar
user2684 committed
182
#define MODULE_DIGITAL_OUTPUT 1
183
// Enable this module to use one of the following sensors: SENSOR_DHT11, SENSOR_DHT22
DV's avatar
DV committed
184
#define MODULE_DHT 0
user2684's avatar
user2684 committed
185
// Enable this module to use one of the following sensors: SENSOR_SHT21, SENSOR_HTU21D
186
#define MODULE_SHT21 0
DV's avatar
DV committed
187
// Enable this module to use one of the following sensors: SENSOR_SWITCH, SENSOR_DOOR, SENSOR_MOTION
user2684's avatar
user2684 committed
188
#define MODULE_SWITCH 0
DV's avatar
DV committed
189
190
// Enable this module to use one of the following sensors: SENSOR_DS18B20
#define MODULE_DS18B20 0
DV's avatar
DV committed
191
192
193
194
// 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
user2684's avatar
user2684 committed
195
196
// Enable this module to use one of the following sensors: SENSOR_BME280
#define MODULE_BME280 0
197
198
199
200
201
202
// 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
203
204
// Enable this module to use one of the following sensors: SENSOR_MCP9808
#define MODULE_MCP9808 0
205
206
// Enable this module to use one of the following sensors: SENSOR_MQ
#define MODULE_MQ 0
207
208
// Enable this module to use one of the following sensors: SENSOR_MHZ19
#define MODULE_MHZ19 0
209
// Enable this module to use one of the following sensors: SENSOR_AM2320    
210
#define MODULE_AM2320 0
211
// Enable this module to use one of the following sensors: SENSOR_TSL2561    
212
#define MODULE_TSL2561 0
213
214
215
216
// Enable this module to use one of the following sensors: SENSOR_PT100
#define MODULE_PT100 0
// Enable this module to use one of the following sensors: SENSOR_BMP280
#define MODULE_BMP280 0
217
218
// Enable this module to use one of the following sensors: SENSOR_DIMMER
#define MODULE_DIMMER 0
219
220
// Enable this module to use one of the following sensors: SENSOR_RAIN_GAUGE, SENSOR_POWER_METER, SENSOR_WATER_METER
#define MODULE_PULSE_METER 0
DV's avatar
DV committed
221
222
~~~

223
### Installing the dependencies
DV's avatar
DV committed
224

225
Some of the modules above rely on third party libraries. Those libraries are not included within NodeManager and have to be installed from the Arduino IDE Library Manager (Sketch -> Include Library -> Manager Libraries) or manually. You need to install the library ONLY if the module is enabled:
DV's avatar
DV committed
226
227
228
229

Module  | Required Library
 ------------- | -------------
MODULE_SHT21 | https://github.com/SodaqMoja/Sodaq_SHT2x
230
MODULE_DHT | https://github.com/mysensors/MySensorsArduinoExamples/tree/master/libraries/DHT
DV's avatar
DV committed
231
232
233
MODULE_DS18B20 | https://github.com/milesburton/Arduino-Temperature-Control-Library
MODULE_BH1750 | https://github.com/claws/BH1750
MODULE_MLX90614 | https://github.com/adafruit/Adafruit-MLX90614-Library
user2684's avatar
user2684 committed
234
MODULE_BME280 | https://github.com/adafruit/Adafruit_BME280_Library
235
236
237
MODULE_SONOFF | https://github.com/thomasfredericks/Bounce2
MODULE_BMP085 | https://github.com/adafruit/Adafruit-BMP085-Library
MODULE_HCSR04 | https://github.com/mysensors/MySensorsArduinoExamples/tree/master/libraries/NewPing
238
MODULE_MCP9808 | https://github.com/adafruit/Adafruit_MCP9808_Library
239
240
MODULE_AM2320 | https://github.com/thakshak/AM2320
MODULE_TSL2561 | https://github.com/adafruit/TSL2561-Arduino-Library
241
MODULE_BMP280 | https://github.com/adafruit/Adafruit_BMP280_Library
DV's avatar
DV committed
242

243
### Configure NodeManager
DV's avatar
DV committed
244

245
The next step is to configure NodeManager with settings which will instruct how the node should behave. To do so, go to the main sketch, inside the `before()` function and add call one or more of the functions below just before registering your sensors. The following methods are exposed for your convenience and can be called on the `nodeManager` object already created for you:
DV's avatar
DV committed
246
247

~~~c
248
    // [10] send the same service message multiple times (default: 1)
DV's avatar
DV committed
249
    void setRetries(int value);
250
    int getRetries();
DV's avatar
DV committed
251
    #if BATTERY_MANAGER == 1
252
      // [11] the expected vcc when the batter is fully discharged, used to calculate the percentage (default: 2.7)
DV's avatar
DV committed
253
      void setBatteryMin(float value);
254
      // [12] the expected vcc when the batter is fully charged, used to calculate the percentage (default: 3.3)
DV's avatar
DV committed
255
      void setBatteryMax(float value);
user2684's avatar
user2684 committed
256
      // [14] after how many minutes report the battery level to the controller. When reset the battery is always reported (default: 60 minutes)
257
      void setBatteryReportMinutes(int value);
user2684's avatar
user2684 committed
258
259
260
261
262
263
      // [40] after how many minutes report the battery level to the controller. When reset the battery is always reported (default: 60 minutes)
      void setBatteryReportSeconds(int value);
      // [41] after how many minutes report the battery level to the controller. When reset the battery is always reported (default: 60 minutes)
      void setBatteryReportHours(int value);
      // [42] after how many minutes report the battery level to the controller. When reset the battery is always reported (default: 60 minutes)
      void setBatteryReportDays(int value);
264
      // [15] 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)
265
      void setBatteryInternalVcc(bool value);
266
      // [16] 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)
267
      void setBatteryPin(int value);
268
      // [17] if setBatteryInternalVcc() is set to false, the volts per bit ratio used to calculate the battery voltage (default: 0.003363075)
269
      void setBatteryVoltsPerBit(float value);
270
      // [18] If true, wake up by an interrupt counts as a valid cycle for battery reports otherwise only uninterrupted sleep cycles would contribute (default: true)
271
      void setBatteryReportWithInterrupt(bool value);
272
273
      // [2] Send a battery level report to the controller
      void batteryReport();
DV's avatar
DV committed
274
    #endif
275
276
277
278
279
280
281
282
283
    // [3] set the duration (in seconds) of a sleep cycle
    void setSleepSeconds(int value);
    long getSleepSeconds();
    // [4] set the duration (in minutes) of a sleep cycle
    void setSleepMinutes(int value);
    // [5] set the duration (in hours) of a sleep cycle
    void setSleepHours(int value);
    // [29] set the duration (in days) of a sleep cycle
    void setSleepDays(int value);
284
    // [19] if enabled, when waking up from the interrupt, the board stops sleeping. Disable it when attaching e.g. a motion sensor (default: true)
285
    void setSleepInterruptPin(int value);
DV's avatar
DV committed
286
    // configure the interrupt pin and mode. Mode can be CHANGE, RISING, FALLING (default: MODE_NOT_DEFINED)
287
288
289
    void setInterrupt(int pin, int mode, int initial = -1);
    // [28] ignore two consecutive interrupts if happening within this timeframe in milliseconds (default: 100)
    void setInterruptMinDelta(long value);
290
    // [20] optionally sleep interval in milliseconds before sending each message to the radio network (default: 0)
DV's avatar
DV committed
291
    void setSleepBetweenSend(int value);
292
    int getSleepBetweenSend();
DV's avatar
DV committed
293
294
295
296
    // 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);
297
298
    // [26] un-register a sensor
    void unRegisterSensor(int sensor_index);
DV's avatar
DV committed
299
300
    // return a sensor by its index
    Sensor* get(int sensor_index);
301
302
    Sensor* getSensor(int sensor_index);
    // assign a different child id to a sensor
user2684's avatar
user2684 committed
303
    bool renameSensor(int old_child_id, int new_child_id);
DV's avatar
DV committed
304
305
    #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
306
307
      void setPowerPins(int ground_pin, int vcc_pin, int wait_time = 50);
      // [23] if enabled the pins will be automatically powered on while awake and off during sleeping (default: true)
DV's avatar
DV committed
308
      void setAutoPowerPins(bool value);
309
      // [24] manually turn the power on
DV's avatar
DV committed
310
      void powerOn();
311
      // [25] manually turn the power off
312
      void powerOff();
DV's avatar
DV committed
313
    #endif
314
    // [21] set this to true if you want destination node to send ack back to this node (default: false)
user2684's avatar
user2684 committed
315
    void setAck(bool value);
316
    bool getAck();
317
318
    // request and return the current timestamp from the controller
    long getTimestamp();
319
320
    // Request the controller's configuration on startup (default: true)
    void setGetControllerConfig(bool value);
321
    // [22] Manually set isMetric setting
322
323
324
325
    void setIsMetric(bool value);
    bool getIsMetric();
    // Convert a temperature from celsius to fahrenheit depending on how isMetric is set
    float celsiusToFahrenheit(float temperature);
326
327
    // return true if sleep or wait is configured and hence this is a sleeping node
    bool isSleepingNode();
328
329
330
331
332
333
334
335
336
337
338
    // [1] Send a hello message back to the controller
    void hello();
    // [6] reboot the board
    void reboot();
    // [8] send NodeManager's the version back to the controller
    void version();
    // [7] clear the EEPROM
    void clearEeprom();
    // [9] wake up the board
    void wakeup();
    // process a remote request
339
    void process(Request & request);
340
341
    // return the value stored at the requested index from the EEPROM
    int loadFromMemory(int index);
342
    // [27] save the given index of the EEPROM the provided value
343
    void saveToMemory(int index, int value);
344
345
    // return vcc in V
    float getVcc();
346
347
348
349
    // setup the configured interrupt pins
    void setupInterrupts();
    // return the pin from which the last interrupt came
    int getLastInterruptPin();
user2684's avatar
user2684 committed
350
    // [36] set the default interval in minutes all the sensors will report their measures. If the same function is called on a specific sensor, this will not change the previously set value. or sleeping sensors, the elapsed time can be evaluated only upon wake up (default: 10 minutes)
351
    void setReportIntervalSeconds(int value);
user2684's avatar
user2684 committed
352
353
354
355
356
357
    // [37] set the default interval in minutes all the sensors will report their measures. If the same function is called on a specific sensor, this will not change the previously set value. or sleeping sensors, the elapsed time can be evaluated only upon wake up (default: 10 minutes)
    void setReportIntervalMinutes(int value);
    // [38] set the default interval in minutes all the sensors will report their measures. If the same function is called on a specific sensor, this will not change the previously set value. or sleeping sensors, the elapsed time can be evaluated only upon wake up (default: 10 minutes)
    void setReportIntervalHours(int value);
    // [39] set the default interval in minutes all the sensors will report their measures. If the same function is called on a specific sensor, this will not change the previously set value. or sleeping sensors, the elapsed time can be evaluated only upon wake up (default: 10 minutes)
    void setReportIntervalDays(int value);
358
359
360
361
    // [30] if set and when the board is battery powered, sleep() is always called instead of wait() (default: true)
    void setSleepOrWait(bool value);
    // sleep if the node is a battery powered or wait if it is not for the given number of milliseconds 
    void sleepOrWait(long value);
362
363
364
365
    // [31] set which pin is connected to RST of the board to reboot the board when requested. If not set the software reboot is used instead (default: -1)
    void setRebootPin(int value);
    // [32] turn the ADC off so to save 0.2 mA
    void setADCOff();
user2684's avatar
user2684 committed
366
367
368
369
370
371
372
373
374
375
376
377
378
379
    #if SIGNAL_SENSOR == 1 && defined(MY_SIGNAL_REPORT_ENABLED)
      // [33] How frequenly to send a signal report to the controller (default: 60 minutes)
      void setSignalReportMinutes(int value);
      // [43] How frequenly to send a signal report to the controller (default: 60 minutes)
      void setSignalReportSeconds(int value);
      // [44] How frequenly to send a signal report to the controller (default: 60 minutes)
      void setSignalReportHours(int value);
      // [45] How frequenly to send a signal report to the controller (default: 60 minutes)
      void setSignalReportDays(int value);
      // [34] define which signal report to send. Possible values are SR_UPLINK_QUALITY, SR_TX_POWER_LEVEL, SR_TX_POWER_PERCENT, SR_TX_RSSI, SR_RX_RSSI, SR_TX_SNR, SR_RX_SNR (default: SR_RX_RSSI)
      void setSignalCommand(int value);
      // [35] report the signal level to the controller
      void signalReport();
    #endif
DV's avatar
DV committed
380
381
~~~

382
383
### Set reporting intervals and sleeping cycles

user2684's avatar
user2684 committed
384
If not instructed differently, the node will stay awake and all the sensors will report every 10 minutes, battery level and signal level will be automatically reported every 60 minutes. To change those settings, you can call the following functions on the nodeManager object:
DV's avatar
DV committed
385

386
387
Function  | Description
------------ | -------------
user2684's avatar
user2684 committed
388
389
390
391
setSleepSeconds(), setSleepMinutes(), setSleepHours(), setSleepDays() | the time interval the node will spend in a (smart) sleep cycle
setReportIntervalSeconds(), setReportIntervalMinutes(), setReportIntervalHours(), setReportIntervalDays() | the time interval the node will report the measures of all the attached sensors
setBatteryReportSeconds(), setBatteryReportMinutes(), setBatteryReportHours(), setBatteryReportDays() | the time interval the node will report the battery level
setSignalReportSeconds(), setSignalReportMinutes(), setSignalReportHours(), setSignalReportDays() | the time interval the node will report the radio signal level
392
393
394
395
396
397
398

For example, to put the node to sleep in cycles of 10 minutes:

~~~c
	nodeManager.setSleepMinutes(10);
~~~

user2684's avatar
user2684 committed
399
If you need every sensor to report at a different time interval, you can call `setBatteryReportSeconds(), setBatteryReportMinutes(), setBatteryReportHours(), setBatteryReportDays()` on the sensor's object. For example to have a DHT sensor reporting every 60 seconds while all the other sensors every 20 minutes:
DV's avatar
DV committed
400
~~~c
401
402
403
404
int id = nodeManager.registerSensor(SENSOR_DHT22,6);
SensorDHT* dht = (SensorDHT*)nodeManager.get(id);
dht->setReportIntervalSeconds(60);
nodeManager.setReportIntervalMinutes(20);
DV's avatar
DV committed
405
406
~~~

407
408
Please note, if you configure a sleep cycle, this may have an impact on the reporting interval since the sensor will be able to report its measures ONLY when awake. For example if you set a report interval of 5 minutes and a sleep cycle of 10 minutes, the sensors will report every 10 minutes.

409
### Register your sensors
410
Once configured the node, it is time to tell NodeManager which sensors are attached to the board and where. In your sketch, inside the `before()` function and just before calling `nodeManager.before()`, you can register your sensors against NodeManager. The following built-in sensor types are available. Remember the corresponding module should be enabled in `config.h` for a successful compilation: 
DV's avatar
DV committed
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427

Sensor type  | Description
 ------------- | -------------
SENSOR_ANALOG_INPUT | Generic analog sensor, return a pin's analog value or its percentage
SENSOR_LDR | LDR sensor, return the light level of an attached light resistor in percentage
SENSOR_THERMISTOR | Thermistor sensor, return the temperature based on the attached thermistor
SENSOR_DIGITAL_INPUT |  Generic digital sensor, return a pin's digital value
SENSOR_DIGITAL_OUTPUT | Generic digital output sensor, allows setting the digital output of a pin to the requested value
SENSOR_RELAY | Relay sensor, allows activating the relay
SENSOR_LATCHING_RELAY| Latching Relay sensor, allows activating the relay with a pulse
SENSOR_DHT11 | DHT11 sensor, return temperature/humidity based on the attached DHT sensor
SENSOR_DHT22 | DHT22 sensor, return temperature/humidity based on the attached DHT sensor
SENSOR_SHT21 | SHT21 sensor, return temperature/humidity based on the attached SHT21 sensor
SENSOR_SWITCH | Generic switch, wake up the board when a pin changes status
SENSOR_DOOR | Door sensor, wake up the board and report when an attached magnetic sensor has been opened/closed
SENSOR_MOTION | Motion sensor, wake up the board and report when an attached PIR has triggered
SENSOR_DS18B20 | DS18B20 sensor, return the temperature based on the attached sensor
DV's avatar
DV committed
428
429
430
SENSOR_HTU21D | HTU21D sensor, return temperature/humidity based on the attached HTU21D sensor
SENSOR_BH1750 | BH1750 sensor, return light level in lux
SENSOR_MLX90614 | MLX90614 contactless temperature sensor, return ambient and object temperature
user2684's avatar
user2684 committed
431
SENSOR_BME280 | BME280 sensor, return temperature/humidity/pressure based on the attached BME280 sensor
user2684's avatar
user2684 committed
432
SENSOR_MQ | MQ sensor, return ppm of the target gas
433
SENSOR_ML8511 | ML8511 sensor, return UV intensity
434
435
436
437
SENSOR_SONOFF | Sonoff wireless smart switch
SENSOR_BMP085 | BMP085/BMP180 sensor, return temperature and pressure
SENSOR_HCSR04 | HC-SR04 sensor, return the distance between the sensor and an object
SENSOR_ACS712 | ACS712 sensor, measure the current going through the attached module
438
SENSOR_MCP9808 | MCP9808 sensor, measure the temperature through the attached module
439
SENSOR_RAIN_GAUGE | Rain gauge sensor
440
441
SENSOR_RAIN | Rain sensor, return the percentage of rain from an attached analog sensor
SENSOR_SOIL_MOISTURE | Soil moisture sensor, return the percentage of moisture from an attached analog sensor
442
SENSOR_MHZ19 | MH-Z19 CO2 sensor via UART (SoftwareSerial, default on pins 6(Rx) and 7(Tx)
443
444
SENSOR_TSL2561 | TSL2561 sensor, return light in lux
SENSOR_AM2320 | AM2320 sensors, return temperature/humidity based on the attached AM2320 sensor
445
446
SENSOR_PT100 | High temperature sensor associated with DFRobot Driver, return the temperature in C° from the attached PT100 sensor
SENSOR_BMP280 | BMP280 sensor, return temperature/pressure based on the attached BMP280 sensor
447
SENSOR_DIMMER | Generic dimmer sensor used to drive a pwm output
448
449
SENSOR_POWER_METER | Power meter pulse sensor
SENSOR_WATER_METER | Water meter pulse sensor
DV's avatar
DV committed
450

451
To register a sensor simply call the NodeManager instance with the sensory type and the pin the sensor is conncted to and optionally a child id. For example:
DV's avatar
DV committed
452
~~~c
user2684's avatar
user2684 committed
453
	nodeManager.registerSensor(SENSOR_THERMISTOR,A2);
454
	nodeManager.registerSensor(SENSOR_DOOR,3,1);
DV's avatar
DV committed
455
456
~~~

457
Once registered, your job is done. NodeManager will assign a child id automatically if not instructed differently, present each sensor for you to the controller, query each sensor and report the measure back to the gateway/controller. For actuators (e.g. relays) those can be triggered by sending a `REQ` message with the expected type to their assigned child id.
DV's avatar
DV committed
458

459
When called, registerSensor returns the child_id of the sensor so you will be able to retrieve it later if needed. Please note for sensors creating multiple child IDs (like a DHT sensor which creates a temperature and humidity sensor with different IDs), the last id is returned.
DV's avatar
DV committed
460

461
#### Creating a custom sensor
DV's avatar
DV committed
462

463
If you want to create a custom sensor and register it with NodeManager so it can take care of all the common tasks, you can create an inline class inheriting from `Sensor` or other subclasses and implement the following methods:
DV's avatar
DV committed
464
465
466
~~~c
    // define what to do during before() to setup the sensor
    void onBefore();
user2684's avatar
user2684 committed
467
468
	// define what to do during setup() by executing the sensor's main task
    void onSetup();
DV's avatar
DV committed
469
470
471
472
    // define what to do during loop() by executing the sensor's main task
    void onLoop();
    // define what to do during receive() when the sensor receives a message
    void onReceive(const MyMessage & message);
473
	// define what to do when receiving a remote configuration message
user2684's avatar
user2684 committed
474
475
476
    void onProcess(Request & request);
    // define what to do when receiving an interrupt
    void onInterrupt();
DV's avatar
DV committed
477
478
~~~

user2684's avatar
user2684 committed
479
You can then instantiate your newly created class and register it with NodeManager:
DV's avatar
DV committed
480
~~~c
user2684's avatar
user2684 committed
481
    nodeManager.registerSensor(new SensorCustom(&nodeManager,child_id, pin));
DV's avatar
DV committed
482
483
~~~

484
### Configuring the sensors
DV's avatar
DV committed
485
486
Each built-in sensor class comes with reasonable default settings. In case you want/need to customize any of those settings, after having registered the sensor, you can retrieve it back and call set functions common to all the sensors or specific for a given class.

user2684's avatar
user2684 committed
487
To do so, use `nodeManager.getSensor(child_id)` which will return a pointer to the sensor. Remeber to cast it to the right class before calling their functions. For example:
DV's avatar
DV committed
488
489

~~~c
490
491
	SensorLatchingRelay* relay = (SensorLatchingRelay*) nodeManager.getSensor(2);
	relay->setPulseWidth(50);
DV's avatar
DV committed
492
493
494
~~~


495
#### Sensor's general configuration
DV's avatar
DV committed
496

497
The following methods are available for all the sensors and can be called on the object reference as per the example above:
DV's avatar
DV committed
498
~~~c
499
    // [1] where the sensor is attached to (default: not set)
DV's avatar
DV committed
500
    void setPin(int value);
501
502
    int getPin();
    // [2] child_id of this sensor (default: not set)
DV's avatar
DV committed
503
    void setChildId(int value);
504
    int getChildId();
DV's avatar
DV committed
505
506
    // presentation of this sensor (default: S_CUSTOM)
    void setPresentation(int value);
507
508
    int getPresentation();
    // [3] type of this sensor (default: V_CUSTOM)
DV's avatar
DV committed
509
    void setType(int value);
510
511
    int getType();
    // [4] description of the sensor (default: '')
user2684's avatar
user2684 committed
512
    void setDescription(char *value);
513
    // [5] For some sensors, the measurement can be queried multiple times and an average is returned (default: 1)
DV's avatar
DV committed
514
    void setSamples(int value);
515
    // [6] If more then one sample has to be taken, set the interval in milliseconds between measurements (default: 0)
DV's avatar
DV committed
516
    void setSamplesInterval(int value);
517
    // [7] if true will report the measure only if different than the previous one (default: false)
518
    void setTrackLastValue(bool value);
519
    // [9] if track last value is enabled, force to send an update after the configured number of minutes
520
    void setForceUpdateMinutes(int value);
521
522
    // [19] if track last value is enabled, force to send an update after the configured number of hours
    void setForceUpdateHours(int value);
523
    // [10] the value type of this sensor (default: TYPE_INTEGER)
DV's avatar
DV committed
524
    void setValueType(int value);
525
526
527
    int getValueType();
    // [11] for float values, set the float precision (default: 2)
    void  setFloatPrecision(int value);
528
529
    // [21] for double values, set the double precision (default: 4)
    void  setDoublePrecision(int value);
DV's avatar
DV committed
530
531
    #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
532
533
      void setPowerPins(int ground_pin, int vcc_pin, int wait_time = 50);
      // [12] if enabled the pins will be automatically powered on while awake and off during sleeping (default: true)
DV's avatar
DV committed
534
      void setAutoPowerPins(bool value);
535
      // [13] manually turn the power on
DV's avatar
DV committed
536
      void powerOn();
537
      // [14] manually turn the power off
DV's avatar
DV committed
538
539
      void powerOff();
    #endif
user2684's avatar
user2684 committed
540
    // get the latest recorded value from the sensor
541
542
543
    int getValueInt();
    float getValueFloat();
    char* getValueString();
544
545
    // [17] After how many minutes the sensor will report back its measure (default: 10 minutes)
    void setReportIntervalSeconds(int value);
user2684's avatar
user2684 committed
546
547
548
549
550
551
    // [16] After how many minutes the sensor will report back its measure (default: 10 minutes)
    void setReportIntervalMinutes(int value);
    // [19] After how many hours the sensor will report back its measure (default: 10 minutes)
    void setReportIntervalHours(int value);
    // [20] After how many days the sensor will report back its measure (default: 10 minutes)
    void setReportIntervalDays(int value);
552
553
    // return true if the report interval has been already configured
    bool isReportIntervalConfigured();
554
555
    // process a remote request
    void process(Request & request);
556
557
    // return the pin the interrupt is attached to
    int getInterruptPin();
558
559
    // listen for interrupts on the given pin so interrupt() will be called when occurring
    void setInterrupt(int pin, int mode, int initial);
DV's avatar
DV committed
560
561
~~~

562
#### Sensor's specific configuration
DV's avatar
DV committed
563
564
565

Each sensor class can expose additional methods.

566
* SensorAnalogInput / SensorLDR / SensorRain / SensorSoilMoisture
DV's avatar
DV committed
567
~~~c
568
    // [101] the analog reference to use (default: not set, can be either INTERNAL or DEFAULT)
DV's avatar
DV committed
569
    void setReference(int value);
570
    // [102] reverse the value or the percentage (e.g. 70% -> 30%) (default: false)
DV's avatar
DV committed
571
    void setReverse(bool value);
572
    // [103] when true returns the value as a percentage (default: true)
DV's avatar
DV committed
573
    void setOutputPercentage(bool value);
574
    // [104] minimum value for calculating the percentage (default: 0)
DV's avatar
DV committed
575
    void setRangeMin(int value);
576
    // [105] maximum value for calculating the percentage (default: 1024)
DV's avatar
DV committed
577
578
579
    void setRangeMax(int value);
~~~

580
* SensorThermistor
DV's avatar
DV committed
581
~~~c
582
    // [101] resistance at 25 degrees C (default: 10000)
583
    void setNominalResistor(long value);
584
    // [102] temperature for nominal resistance (default: 25)
DV's avatar
DV committed
585
    void setNominalTemperature(int value);
586
    // [103] The beta coefficient of the thermistor (default: 3950)
DV's avatar
DV committed
587
    void setBCoefficient(int value);
588
    // [104] the value of the resistor in series with the thermistor (default: 10000)
589
    void setSeriesResistor(long value);
590
    // [105] set a temperature offset
DV's avatar
DV committed
591
592
593
    void setOffset(float value);
~~~

594
* SensorMQ
user2684's avatar
user2684 committed
595
~~~c
596
    // [101] define the target gas whose ppm has to be returned. 0: LPG, 1: CO, 2: Smoke (default: 1);
user2684's avatar
user2684 committed
597
    void setTargetGas(int value);
598
    // [102] define the load resistance on the board, in kilo ohms (default: 1);
user2684's avatar
user2684 committed
599
    void setRlValue(float value);
600
    // [103] define the Ro resistance on the board (default: 10000);
user2684's avatar
user2684 committed
601
    void setRoValue(float value);
602
    // [104] Sensor resistance in clean air (default: 9.83);
user2684's avatar
user2684 committed
603
    void setCleanAirFactor(float value);
604
    // [105] define how many samples you are going to take in the calibration phase (default: 50);
user2684's avatar
user2684 committed
605
    void setCalibrationSampleTimes(int value);
606
    // [106] define the time interal(in milisecond) between each samples in the cablibration phase (default: 500);
user2684's avatar
user2684 committed
607
    void setCalibrationSampleInterval(int value);
608
    // [107] define how many samples you are going to take in normal operation (default: 50);
user2684's avatar
user2684 committed
609
    void setReadSampleTimes(int value);
610
    // [108] define the time interal(in milisecond) between each samples in the normal operations (default: 5);
user2684's avatar
user2684 committed
611
612
613
614
615
616
617
618
619
    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);
~~~

620
621
622
623
624
625
626
627
* SensorACS712
~~~c
    // [101] 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);
    // [102] set ACS offset (default: 2500);
    void setOffset(int value);
~~~

628
* SensorRainGauge / SensorPowerMeter / SensorWaterMeter
629
~~~c
630
631
    // [102] set how many pulses for each unit (e.g. 1000 pulses for 1 kwh of power, 9 pulses for 1 mm of rain, etc.)
    void setPulseFactor(float value);
632
633
    // set initial value - internal pull up (default: HIGH)
    void setInitialValue(int value);
634
635
    // set the interrupt mode to attach to (default: FALLING)
    void setInterruptMode(int value);
636
637
~~~

638
* SensorDigitalOutput / SensorRelay
DV's avatar
DV committed
639
~~~c
640
    // [103] define which value to set to the output when set to on (default: HIGH)
641
    void setOnValue(int value);
642
    // [104] when legacy mode is enabled expect a REQ message to trigger, otherwise the default SET (default: false)
643
    void setLegacyMode(bool value);
644
    // [105] automatically turn the output off after the given number of minutes
645
    void setSafeguard(int value);
646
    // [106] if true the input value becomes a duration in minutes after which the output will be automatically turned off (default: false)
647
    void setInputIsElapsed(bool value);
648
649
    // [107] optionally wait for the given number of milliseconds after changing the status (default: 0)
    void setWaitAfterSet(int value);
650
    // manually switch the output to the provided value
651
    void setStatus(int value);
652
    // get the current state
653
654
655
656
657
658
659
660
661
662
663
    int getStatus();
~~~

* SensorLatchingRelay (in addition to those available for SensorDigitalOutput / SensorRelay)
~~~c
    // [201] set the duration of the pulse to send in ms to activate the relay (default: 50)
    void setPulseWidth(int value);
    // [202] set the pin which turns the relay off (default: the pin provided while registering the sensor)
    void setPinOff(int value);
    // [203] set the pin which turns the relay on (default: the pin provided while registering the sensor + 1)
    void setPinOn(int value);
DV's avatar
DV committed
664
665
~~~

666
*  SensorSwitch / SensorDoor / SensorMotion
DV's avatar
DV committed
667
~~~c
668
    // [101] set the interrupt mode. Can be CHANGE, RISING, FALLING (default: CHANGE)
DV's avatar
DV committed
669
    void setMode(int value);
670
    // [102] milliseconds to wait before reading the input (default: 0)
DV's avatar
DV committed
671
    void setDebounce(int value);
672
    // [103] time to wait in milliseconds after a change is detected to allow the signal to be restored to its normal value (default: 0)
DV's avatar
DV committed
673
    void setTriggerTime(int value);
674
    // [104] Set initial value on the interrupt pin (default: HIGH)
675
    void setInitial(int value);
DV's avatar
DV committed
676
677
~~~

678
*  SensorDs18b20
user2684's avatar
user2684 committed
679
680
681
~~~c
    // returns the sensor's resolution in bits
    int getResolution();
682
    // [101] set the sensor's resolution in bits
user2684's avatar
user2684 committed
683
    void setResolution(int value);
684
    // [102] sleep while DS18B20 calculates temperature (default: false)
685
    void setSleepDuringConversion(bool value);
686
687
    // return the sensors' device address
    DeviceAddress* getDeviceAddress();
user2684's avatar
user2684 committed
688
689
~~~

690
691
692
693
694
695
*  SensorBH1750
~~~c
    // [101] set sensor reading mode, e.g. BH1750_ONE_TIME_HIGH_RES_MODE
    void setMode(uint8_t mode);
~~~

696
*  SensorBME280 / SensorBMP085 / SensorBMP280
697
~~~c
698
    // [101] define how many pressure samples to keep track of for calculating the forecast (default: 5)
699
700
701
    void setForecastSamplesCount(int value);
~~~

702
* SensorHCSR04
703
~~~c
704
    // [101] Arduino pin tied to trigger pin on the ultrasonic sensor (default: the pin set while registering the sensor)
705
    void setTriggerPin(int value);
706
    // [102] Arduino pin tied to echo pin on the ultrasonic sensor (default: the pin set while registering the sensor)
707
    void setEchoPin(int value);
708
    // [103] Maximum distance we want to ping for (in centimeters) (default: 300)
709
710
711
    void setMaxDistance(int value);
~~~

712
*  SensorSonoff
713
~~~c
714
715
716
717
718
719
    // [101] set the button's pin (default: 0)
    void setButtonPin(int value);
    // [102] set the relay's pin (default: 12)
    void setRelayPin(int value);
    // [103] set the led's pin (default: 13)
    void setLedPin(int value);
720
721
~~~

722
723
724
725
726
727
* SensorMHZ19
~~~c
    // set the RX and TX pins for the software serial port to talk to the sensor
    void setRxTx(int rxpin, int txpin);
~~~

728
729
730
731
732
733
734
735
736
737
738
739
* SensorTSL2561
~~~c
    // [101] set the gain, possible values are SensorTSL2561::GAIN_0X (0), SensorTSL2561::GAIN_16X (1) (default 16x)
    void setGain(int value);
    // [102] set the timing, possible values are SensorTSL2561::INTEGRATIONTIME_13MS (0), SensorTSL2561::INTEGRATIONTIME_101MS (1), SensorTSL2561::INTEGRATIONTIME_402MS (2) (default: 13ms)
    void setTiming(int value);
    // [103] set the spectrum, possible values are SensorTSL2561::VISIBLE (0), SensorTSL2561::FULLSPECTRUM (1), SensorTSL2561::INFRARED (2), SensorTSL2561::FULL (3) (default: visible)
    void setSpectrum(int value);
    // [104] set the i2c address values are SensorTSL2561::ADDR_FLOAT, SensorTSL2561::ADDR_LOW, SensorTSL2561::ADDR_HIGH
    void setAddress(int value);
~~~

740
741
742
743
744
745
746
747
748
749
750
751
* SensorDimmer
~~~c
    // [101] set the effect to use for a smooth transition, can be one of SensorDimmer::EASE_LINEAR, SensorDimmer::EASE_INSINE, SensorDimmer::EASE_OUTSINE, SensorDimmer::EASE_INOUTSINE (default: EASE_LINEAR)
    void setEasing(int value);
    // [102] the duration of entire the transition in seconds (default: 1)
    void setDuration(int value);
    // [103] the duration of a single step of the transition in milliseconds (default: 100)
    void setStepDuration(int value);
    // fade the output from the current value to the target provided in the range 0-100
    void fadeTo(int value);
~~~

user2684's avatar
user2684 committed
752
753
754
755
756
757
### Creating a gateway

NodeManager can be also used to create a MySensors gateway. Open your config.h file and look for the gateway-specific defines under "MySensors gateway configuration". The most common settings are reported there, just uncomment those you need to use based on the network you are creating.

Please note you don't necessarily need a NodeManager gateway to interact with a NodeManager node. The NodeManager node is fully compatible with any existing gateway you are currently operating with.

758
### Upload your sketch
DV's avatar
DV committed
759
760
761
762
763
764

Upload your sketch to your arduino board as you are used to.

Check your gateway's logs to ensure the node is working as expected. You should see the node presenting itself, reporting battery level, presenting all the registered sensors and the configuration child id service.
When `DEBUG` is enabled, detailed information is available through the serial port. Remember to disable debug once the tests have been completed.

765
### Communicate with NodeManager and its sensors
DV's avatar
DV committed
766

767
You can interact with each registered sensor by sending to the child id a `REQ` command (or a `SET` for output sensors like relays). For example to request the temperature to node_id 254 and child_id 1:
DV's avatar
DV committed
768
769
770

`254;1;2;0;0;`

771
To activate a relay connected to the same node, child_id 100 we need to send a `SET` command with payload set to 1:
DV's avatar
DV committed
772

773
`254;100;1;0;2;1`
DV's avatar
DV committed
774

775
No need to implement anything on your side since for built-in sensors this is handled automatically. 
776

777
NodeManager exposes also a configuration service which is by default on child_id 200 so you can interact with it by sending `V_CUSTOM` type of messages and commands within the payload. For each `REQ` message, the node will respond with a `SET` message if successful. 
user2684's avatar
user2684 committed
778

779
Almost all the functions made available through the API can be called remotely. To do so, the payload must be in the format `<function_id>[,<value_to_set>]` where `function_id` is the number between square brackets you can find in the description above and, if the function takes and argument, this can be passed along in `value_to_set`. 
780
781
782
783
784
For example, to request a battery report, find the function you need to call remotely within the documentation:
~~~c
    // [2] Send a battery level report to the controller
    void batteryReport();
~~~
785
In this case `function_id` will be 2. To request a battery report to the node_id 100, send the following message:
786
787
`<node_id>;<configuration_child_id>;<req>;0;<V_CUSTOM>;<function_id>`
`100;200;2;0;48;2`
788

789
The change the sleep time to e.g. 10 minutes:
790
~~~c
791
792
    // [4] set the duration (in minutes) of a sleep cycle
    void setSleepMinutes(int value);
793
794
~~~
`<node_id>;<configuration_child_id>;<req>;0;<V_CUSTOM>;<function_id>,<value>`
795
`100;200;2;0;48;4,10`
DV's avatar
DV committed
796

797
To wake up a node previously configured as sleeping, send the following as the node wakes up next:
798
799
800
801
802
~~~c
    // [9] wake up the board
    void wakeup();
~~~
`100;200;2;0;48;9`
DV's avatar
DV committed
803

804
The same protocol can be used to execute remotely also sensor-specific functions. In this case the message has to be sent to the sensor's child_id, with a `V_CUSTOM` type of message. For example if you want to collect and average 10 samples for child_id 1:
805
806
807
808
809
~~~c
    // [5] For some sensors, the measurement can be queried multiple times and an average is returned (default: 1)
    void setSamples(int value);
~~~
`100;1;2;0;48;5,10`
810

811
812
813
814
815
816
If you want to decrease the temperature offset of a thermistor sensor to -2:
~~~c
    // [105] set a temperature offset
    void setOffset(float value);
~~~
`100;1;2;0;48;105,-2`
DV's avatar
DV committed
817

user2684's avatar
user2684 committed
818
Please note that anything set remotely will NOT persist a reboot apart from the sleep interval which is saved to the EEPROM (provided `PERSIST` is enabled).
DV's avatar
DV committed
819

820
## Understanding NodeManager: how it works
DV's avatar
DV committed
821

user2684's avatar
user2684 committed
822
A NodeManager object is created for you at the beginning of your sketch and its main functions must be called from within `before()`, `presentation()`, `loop()` and `receive()` to work properly. NodeManager will do the following during each phase:
DV's avatar
DV committed
823

824
NodeManager::before():
825
* Setup the interrupt pins to wake up the board based on the configured interrupts
DV's avatar
DV committed
826
827
828
* If persistance is enabled, restore from the EEPROM the latest sleeping settings
* Call `before()` of each registered sensor

829
Sensor::before():
DV's avatar
DV committed
830
831
* Call sensor-specific implementation of before by invoking `onBefore()` to initialize the sensor

832
NodeManager::setup():
833
834
835
* Send a custom message with a STARTED payload to the controller
* Call `setup()` of each registered sensor

836
Sensor::setup():
837
838
* Call sensor-specific implementation of setup by invoking `onSetup()` to initialize the sensor

839
NodeManager::loop():
840
* If all the sensors are powered by an arduino pin, this is turned on
DV's avatar
DV committed
841
* Call `loop()` of each registered sensor
842
* If all the sensors are powered by an arduino pin, this is turned off
DV's avatar
DV committed
843

844
Sensor::loop():
845
846
* If the sensor is powered by an arduino pin, this is set to on
* For each registered sensor, the sensor-specific `onLoop()` is called. If multiple samples are requested, this is run multiple times. `onLoop()` is not intended to send out any message but just sets a new value to a local variable
DV's avatar
DV committed
847
848
* In case multiple samples have been collected, the average is calculated
* A message is sent to the gateway with the calculated value. Depending on the configuration, this is not sent if it is the same as the previous value or sent anyway after a given number of cycles. These functionalies are not sensor-specific and common to all the sensors inheriting from the `Sensor` class.
849
* If the sensor is powered by an arduino pin, this is turned off
DV's avatar
DV committed
850

851
NodeManager::receive():
DV's avatar
DV committed
852
853
854
* Receive a message from the radio network 
* If the destination child id is the configuration node, it will handle the incoming message, otherwise will dispatch the message to the recipient sensor

855
Sensor::receive(): 
DV's avatar
DV committed
856
857
* Invoke `Sensor::loop()` which will execute the sensor main taks and eventually call `Sensor::onReceive()`

858
859
860
861
862
NodeManager::process():
* Process an incoming remote configuration request

Sensor::process():
* Process a sensor-generic incoming remote configuration request
863
* Calls `onProcess()` for sensor-specific incoming remote configuration request
864
865

Sensor::interrupt():
866
* Calls the sensor's implementation of `onInterrupt()` to handle the interrupt
867

868
## Examples
DV's avatar
DV committed
869
870
All the examples below takes place within the before() function in the main sketch, just below the "Register below your sensors" comment.

DV's avatar
DV committed
871
872
873
874
875
876
877
878
879
880
Set battery minimum and maxium voltage. This will be used to calculate the level percentage:

~~~c
    nodeManager.setBatteryMin(1.8);
    nodeManager.setBatteryMin(3.2);
~~~

Instruct the board to sleep for 10 minutes at each cycle:

~~~c
881
    nodeManager.setSleepMinutes(10);
DV's avatar
DV committed
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
~~~

Configure a wake up pin. When pin 3 is connected to ground, the board will stop sleeping:

~~~c
    nodeManager.setSleepInterruptPin(3);
~~~

Use the arduino pins to power on and off the attached sensors. All the sensors' vcc and ground are connected to pin 6 (ground) and 7 (vcc). NodeManager will enable the vcc pin every time just before loop() and wait for 100ms for the power to settle before running loop() of each sensor:

~~~c
   nodeManager.setPowerPins(6,7,100);
~~~

Register a thermistor sensor attached to pin A2. NodeManager will then send the temperature to the controller at the end of each sleeping cycle:

~~~c
   nodeManager.registerSensor(SENSOR_THERMISTOR,A2);
DV's avatar
DV committed
900
901
~~~

902
Register a SHT21 temperature/humidity sensor; since using I2C for communicating with the sensor, the pins used are implicit (A4 and A5). NodeManager will then send the temperature and the humidity to the controller at the end of each sleeping cycle:
DV's avatar
DV committed
903
904
905

~~~c
   nodeManager.registerSensor(SENSOR_SHT21);
DV's avatar
DV committed
906
907
908
909
910
911
~~~

Register a LDR sensor attached to pin A1 and send to the gateway the average of 3 samples:

~~~c
  int sensor_ldr = nodeManager.registerSensor(SENSOR_LDR,A1);
user2684's avatar
user2684 committed
912
  ((SensorLDR*)nodeManager.getSensor(sensor_ldr))->setSamples(3);
DV's avatar
DV committed
913
914
~~~

user2684's avatar
user2684 committed
915
Register a rain sensor connected to A0. This will be powered with via pins 4 (ground) and 5 (vcc) just before reading its value at each cycle, it will be presented as S_RAIN. sending V_RAINRATE messages, the output will be a percentage (calculated between 200 and 1024) and the value will be reversed (so that no rain will be 0%):
DV's avatar
DV committed
916
917
918

~~~c
  int rain = nodeManager.registerSensor(SENSOR_ANALOG_INPUT,A0);
user2684's avatar
user2684 committed
919
  SensorAnalogInput* rainSensor = ((SensorAnalogInput*)nodeManager.getSensor(rain));
DV's avatar
DV committed
920
921
922
923
924
925
926
927
928
929
930
931
932
  rainSensor->setPowerPins(4,5,300);
  rainSensor->setPresentation(S_RAIN);
  rainSensor->setType(V_RAINRATE);
  rainSensor->setOutputPercentage(true);
  rainSensor->setRangeMin(200);
  rainSensor->setRangeMax(1024);
  rainSensor->setReverse(true);
~~~

Register a latching relay connecting to pin 6 (set) and pin 7 (unset):

~~~c
  nodeManager.registerSensor(SENSOR_LATCHING_RELAY,6);
user2684's avatar
user2684 committed
933
934
~~~

935
## Example Sketches
user2684's avatar
user2684 committed
936

937
*  Analog Light and Temperature Sensor
user2684's avatar
user2684 committed
938

user2684's avatar
user2684 committed
939
940
The following sketch can be used to report the temperature and the light level based on a thermistor and LDR sensors attached to two analog pins of the arduino board (A1 and A2). Both the thermistor and the LDR are connected to ground on one side and to vcc via a resistor on the other so to measure the voltage drop across each of them through the analog pins. 

941
The sensor will be put to sleep after startup and will report both the measures every 10 minutes. NodeManager will take care of presenting the sensors, managing the sleep cycle, reporting the battery level every hour and report the measures in the appropriate format. This sketch requires MODULE_ANALOG_INPUT enabled in the global config.h file.
user2684's avatar
user2684 committed
942

943
Even if the sensor is sleeping most of the time, it can be potentially woke up by sending a V_CUSTOM message to NodeManager service child id (200 by default) just after having reported its heartbeat. At this point the node will report awake and the user can interact with it by e.g. sending REQ messages to its child IDs, changing the duration of a sleep cycle, etc.
user2684's avatar
user2684 committed
944
945
946
947
948
949
950
951
952
953
954
955

~~~c
/*
NodeManager is intended to take care on your behalf of all those common tasks a MySensors node has to accomplish, speeding up the development cycle of your projects.

NodeManager includes the following main components:
- Sleep manager: allows managing automatically the complexity behind battery-powered sensors spending most of their time sleeping
- Power manager: allows powering on your sensors only while the node is awake
- Battery manager: provides common functionalities to read and report the battery level
- Remote configuration: allows configuring remotely the node without the need to have physical access to it
- Built-in personalities: for the most common sensors, provide embedded code so to allow their configuration with a single line