Skip to content

Commit

Permalink
Add online/offline logic
Browse files Browse the repository at this point in the history
CL: Add online/offline logic

PUBLISHED_FROM=100e4d2535371bde936e65f495c19ab0313a6caa
  • Loading branch information
cpq authored and cesantabot committed Oct 22, 2018
1 parent 0adbe1d commit 92b3111
Showing 1 changed file with 18 additions and 16 deletions.
34 changes: 18 additions & 16 deletions fs/init.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
load('api_config.js');
load('api_events.js');
load('api_gpio.js');
load('api_shadow.js');
load('api_timer.js');
Expand All @@ -7,7 +8,7 @@ load('api_sys.js');
let led = Cfg.get('board.led1.pin'); // Built-in LED GPIO number
let onhi = Cfg.get('board.led1.active_high'); // LED on when high?
let state = {on: false, uptime: 0}; // Device state
let timer = null; // Initialize when connected
let online = false; // Connected to the cloud?

let setLED = function(on) {
let level = onhi ? on : !on;
Expand All @@ -19,33 +20,34 @@ GPIO.set_mode(led, GPIO.MODE_OUTPUT);
setLED(state.on);

let reportState = function() {
state.uptime = Sys.uptime();
print(JSON.stringify(state));
Shadow.update(0, state);
};

// Update state every second, and report to cloud if online
Timer.set(1000, Timer.REPEAT, function() {
state.uptime = Sys.uptime();
if (online) reportState();
}, null);

// Set up Shadow handler to synchronise device state with the shadow state
Shadow.addHandler(function(event, obj) {
if (event === 'CONNECTED') {
print('Connected to the device shadow');
print(' Reporting our current state..');
Shadow.update(0, state); // Report current state. This may generate the
// delta on the cloud, in which case the
// cloud will send UPDATE_DELTA to us

print(' Setting up timer to periodically report device state..');
if (!timer) timer = Timer.set(1000, Timer.REPEAT, reportState, null);

} else if (event === 'UPDATE_DELTA') {
if (event === 'UPDATE_DELTA') {
print('GOT DELTA:', JSON.stringify(obj));
for (let key in obj) { // Iterate over all keys in delta
if (key === 'on') { // We know about the 'on' key. Handle it!
state.on = obj.on; // Synchronise the state
setLED(state.on); // according to the delta
} else {
print('Dont know how to handle key', key);
}
}
Shadow.update(0, state); // Report our new state, hopefully clearing delta
reportState(); // Report our new state, hopefully clearing delta
}
});

Event.on(Event.CLOUD_CONNECTED, function() {
online = true;
}, null);

Event.on(Event.CLOUD_DISCONNECTED, function() {
online = false;
}, null);

0 comments on commit 92b3111

Please sign in to comment.