Skip to content

Instantly share code, notes, and snippets.

@ElectricImpSampleCode
Last active June 6, 2022 11:39
Show Gist options
  • Save ElectricImpSampleCode/0e3a339849ef1e10a263cc389c72285a to your computer and use it in GitHub Desktop.
Save ElectricImpSampleCode/0e3a339849ef1e10a263cc389c72285a to your computer and use it in GitHub Desktop.
Electric Imp imp API GNSS example code: get the device’s location
// Hold a reference to the GNSS Session object
gnssSession <- null;
// Store device location
location <- { "lat": 0, "lon": 0 };
function isGnssEnabled() {
// Is GNSS ready to use?
if (gnssSession == null) return false;
try {
local resp = gnssSession.getstate();
return (resp.status == 1);
} catch (err) {
return false;
}
}
function enableGNSS() {
// Is GNSS ready?
if (!isGnssEnabled()) {
// Check the modem has a GNSS session in place
if (gnssSession == null) {
// Initiate a session
try {
gnssSession = hardware.gnss.open(function(result) {
server.log("[DEBUG] GNSS Session is " + (result.ready == 0 ? "not ready" : "ready"));
if (result.ready == 1) {
// We're good to enable GNSS operations
enableGNSS();
}
});
} catch (error) {
// Back off and try again
imp.wakeup(1, enableGNSS);
}
return;
}
// We have a GNSS session, so enable GNSS operations
local resp = gnssSession.enable();
if (resp.status != 0) {
// Error enabling GNSS
if (resp.status == 504) {
// Wait while an ongoing op. completes
imp.wakeup(1, enableGNSS);
return;
}
// Can't proceed any further, so report error
server.error("Could not enable GNSS (" + resp.status + ")");
return;
}
}
// GNSS is ready, so get the location
getLocation();
}
function getLocation() {
// Use the session to get a location --
// this may not yield results immediately
try {
gnssSession.readposition(function(resp) {
if (resp.status != 0) {
// An error is indicated, but this may not be a problem
if (resp.status == 516) {
// Fix not yet found
server.log("[DEBUG] GPS location request in progress...");
} else {
server.error("GPS location request failed with error: " + resp.status);
}
return;
}
if ("quectel" in resp) {
location.lat = resp.quectel.latitude;
location.lon = resp.quectel.longitude;
server.log(format("Device at %.4f, %.4f", location.lat.tofloat(), location.lon.tofloat()));
}
}.bindenv(this), 2); // '2' is the co-ordinates display mode: (-)dd.ddddd, (-)dd.ddddd
} catch (error) {
// Error condition
server.error("Modem reported an error:");
server.log(error);
}
}
// Enable GNSS
enableGNSS();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment