|
| 1 | +// Example sketch showing how to securely control locks. |
| 2 | +// This example will remember lock state even after power failure. |
| 3 | + |
| 4 | +#include <MySensor.h> |
| 5 | +#include <SPI.h> |
| 6 | + |
| 7 | +#ifndef MYSENSORS_SENSOR |
| 8 | +#error Please switch to MYSENSORS_SENSOR in MyConfig.h |
| 9 | +#endif |
| 10 | + |
| 11 | +#define LOCK_1 3 // Arduino Digital I/O pin number for first lock (second on pin+1 etc) |
| 12 | +#define NOF_LOCKS 1 // Total number of attached locks |
| 13 | +#define LOCK_LOCK 1 // GPIO value to write to lock attached lock |
| 14 | +#define LOCK_UNLOCK 0 // GPIO value to write to unlock attached lock |
| 15 | + |
| 16 | +MySensor gw; |
| 17 | + |
| 18 | +void setup() |
| 19 | +{ |
| 20 | + // Initialize library and add callback for incoming messages (signing is required) |
| 21 | + gw.begin(incomingMessage, AUTO, true, AUTO, true); |
| 22 | + // Send the sketch version information to the gateway and Controller |
| 23 | + gw.sendSketchInfo("Secure Lock", "1.0"); |
| 24 | + |
| 25 | + // Fetch lock status |
| 26 | + for (int lock=1, pin=LOCK_1; lock<=NOF_LOCKS;lock++, pin++) { |
| 27 | + // Register all locks to gw (they will be created as child devices) |
| 28 | + gw.present(lock, S_LOCK, false); |
| 29 | + // Then set lock pins in output mode |
| 30 | + pinMode(pin, OUTPUT); |
| 31 | + // Set lock to last known state (using eeprom storage) |
| 32 | + digitalWrite(pin, gw.loadState(lock)?LOCK_LOCK:LOCK_UNLOCK); |
| 33 | + } |
| 34 | +} |
| 35 | + |
| 36 | + |
| 37 | +void loop() |
| 38 | +{ |
| 39 | + // Alway process incoming messages whenever possible |
| 40 | + gw.process(); |
| 41 | +} |
| 42 | + |
| 43 | +void incomingMessage(const MyMessage &message) { |
| 44 | + // We only expect one type of message from controller. But we better check anyway. |
| 45 | + if (message.type==V_LOCK_STATUS && message.sensor<=NOF_LOCKS) { |
| 46 | + // Change relay state |
| 47 | + digitalWrite(message.sensor-1+LOCK_1, message.getBool()?LOCK_LOCK:LOCK_UNLOCK); |
| 48 | + // Store state in eeprom |
| 49 | + gw.saveState(message.sensor, message.getBool()); |
| 50 | + // Write some debug info |
| 51 | + Serial.print("Incoming change for lock:"); |
| 52 | + Serial.print(message.sensor); |
| 53 | + Serial.print(", New status: "); |
| 54 | + Serial.println(message.getBool()); |
| 55 | + } |
| 56 | +} |
| 57 | + |
0 commit comments