Tutorial for a simple web app

Part 5 - Reading Information from Device

I initially used the ‘device.getVariable’ function from the JS SDK, called every few seconds using a JS timer, however I eventually found this to be too unreliable. When the device went offline, requests would stack up with no response and the page didn’t seem to recover after the device came back online again. The online parameter from the device body can be used to stop getVariable calls if the device is offline but from my experience there was a delay of around 30 seconds or so before the Particle servers knew the device had gone offline. By that time there were enough getVariable calls stacked up to mess things up.

I’ve since been using SSE’s (Server Sent Events) and have had better success.
bko has a nice tutorial of this here: Using Spark.publish() with Simple JSON Data
It’s well explained so I won’t repost my code but it has made my web app more reliable.
One issue here is that IE11 doesn’t support SSE and as such will show an error in the console when it tries to create the EventSource. I’m still trying to decide whether I’ll add a third party event source library or just ask customers to install a decent browser (not sure how that will go down :confused:)

Part 6 - Removing a Device

For some reason I couldn’t find this in the docs for the Cloud API but @jvanier helped me out here. The following can be used to remove a device from the logged in user

function removeDevice(){
   var jqxhr = $.ajax({
   type: "DELETE",
   url: "https://api.particle.io/v1/devices/"+deviceID,
   data: {
       access_token: accessToken,
   }
   })
   .done(function() {
   alert('This device has been removed from your account');
   })
   .fail(function() {
    alert('There was a problem removing this device from your account.');
   });
}

Note, you’ll probably want to use something nicer than the standard JS alert, I’ve just included it here to show the basics of it. I use Toastr which does nice messages which time out meaning the user doesn’t have to click out of a popup http://codeseven.github.io/toastr/demo.html

7 Likes