Skip to content

Instantly share code, notes, and snippets.

@ElectricImpSampleCode
Last active September 10, 2018 10:32
Show Gist options
  • Save ElectricImpSampleCode/d876d5e50bf33d47cbcc to your computer and use it in GitHub Desktop.
Save ElectricImpSampleCode/d876d5e50bf33d47cbcc to your computer and use it in GitHub Desktop.
This example shows the creation of a simple HTTP GET request with a long-polling function to a remote service that delivers push notifications.
// Set up outgoing request object as a global (we may need to cancel it, so we need a reference to it)
request <- http.get(webServiceURL, webServiceHeaders);
// Define the response handler
function handleResponse(responseTable) {
// Called when the imp receives an immediate acknowledgement from the remote service
if (responseTable.statuscode == 200) {
// Remote service has responded with 'OK' so decode
// the response's body 'responseTable.body' and headers 'responseTable.headers'
// Code omitted for clarity...
} else {
// Log an error
server.log("Error response: " + responseTable.statuscode);
// And cancel the request (since the remote server clearly can't fulfil the push request)
request.cancel();
}
}
// Define the long-poll response handler
function handleLongResponse(responseTable) {
// Called when the imp receives a long-term response from the remote service
// This might be information 'pushed' to the device, so we need to re-submit
// the request in order to receive future notifications
if (responseTable.statuscode == 200) {
// Remote service has responded with 'OK' so decode
// the response's body 'responseTable.body' and headers 'responseTable.headers'
// Code omitted for clarity...
} else {
// Log an error
server.log("Error response: " + responseTable.statuscode);
}
// Re-submit the long-poll request. We must initialize a new request for this
request = http.get(webServiceURL, webServiceHeaders);
request.sendasync(handleResponse, handleLongResponse);
}
// Send the request asynchronously. This will not block the imp CPU
request.sendasync(handleResponse, handleLongResponse);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment