Last active
June 8, 2018 22:11
-
-
Save electricimp/9ad7db2f391058fa742f to your computer and use it in GitHub Desktop.
Agent-Device Communications
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Agent Globals | |
locationLong <- 999 | |
locationLat <- 999 | |
dummyValue <- 0 | |
// Weather functions | |
function getForecast() | |
{ | |
local apikey = "YOUR API KEY HERE" | |
local request = http.get("https://api.forecast.io/forecast/" + apikey + "/" + locationLong.tostring() + "," + locationLat.tostring()) | |
request.sendasync(forecastHandler) | |
} | |
function forecastHandler(response) | |
{ | |
// Decode the JSON (error thrown if invalid) | |
local forecast = http.jsondecode(a_response.body) | |
if ("hourly" in forecast) | |
{ | |
if ("data" in forecast.hourly) | |
{ | |
// Get second item in array: weather one hour hence | |
local weather = forecast.hourly.data[1] | |
device.send("set.forecast", weather.icon) | |
} | |
} | |
} | |
// Location determination functions | |
function addColons(bssid) | |
{ | |
local result = bssid.slice(0, 2) | |
for (local i = 2 ; i < 12 ; i += 2) | |
{ | |
result += ":" + bssid.slice(i, (i + 2)) | |
} | |
return result | |
} | |
function getLocation(networks) | |
{ | |
// Passes the results of the device's WiFi scan to Google to triangulate the device's location | |
local url = "https://maps.googleapis.com/maps/api/browserlocation/json?browser=electric-imp&sensor=false" | |
foreach (network in networks) | |
{ | |
url += ("&wifi=mac:" + addColons(network.bssid) + "|ss:" + network.rssi) | |
} | |
if (url.len() > 356) url.slice(0, 356) | |
local request = http.get(url) | |
local response = request.sendsync() | |
if (response.statuscode == 200) | |
{ | |
local data = http.jsondecode(response.body) | |
if ("location" in data) | |
{ | |
locationLat = data.location.lat | |
locationLong = data.location.lng | |
} | |
// Now we have a location, check the weather | |
// Note: this is function is omitted for clarity, but | |
// it is envisaged that it returns a value representing | |
// the next hour's weather | |
forecast = getForecast() | |
} | |
} | |
function locationLookup(dummy) | |
{ | |
// This message triggers an action on the part of the device but | |
// we still need to send a value (even though it will be ignored) | |
if (locationLong == 999 && locationLat == 999) | |
{ | |
device.send("get.networks", dummyValue) | |
} | |
else | |
{ | |
getForecast() | |
} | |
} | |
// Register device event triggers | |
device.on("get.forecast", locationLookup) | |
device.on("set.location", getLocation) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment