Skip to content

Instantly share code, notes, and snippets.

@nrobinson2000
Last active May 16, 2020 11:49
Show Gist options
  • Save nrobinson2000/000f99eebbe8a8da361749f98b7fe96d to your computer and use it in GitHub Desktop.
Save nrobinson2000/000f99eebbe8a8da361749f98b7fe96d to your computer and use it in GitHub Desktop.
Call particle functions and get particle variables from a device in javascript
var token = "YOUR_PARTICLE_ACCESS_TOKEN";
var device = "YOUR_PARTICLE_DEVICEID";
function httpPost(url, params)
{
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.send(params);
}
function httpGet(url)
{
var xhr = new XMLHttpRequest();
xhr.open("GET", url, false); // false for synchronous request
xhr.send( null );
return xhr.responseText;
}
function callFunction(functionName, args)
{
var params = 'arg=' + args;
console.clear();
httpPost("https://api.particle.io/v1/devices/" + device + "/" + functionName, params);
console.log("Called function: "+ functionName);
console.log("On device: " + device);
console.log("With arguments: " + args);
}
function getVariable(variableName)
{
obj = JSON.parse(httpGet("https://api.particle.io/v1/devices/" + device + "/" + variableName + "?access_token=" + token));
return obj.result;
}
@KazemZ
Copy link

KazemZ commented May 16, 2020

Hi, Mr. Robinson
Thanks for sharing your good work
How about some advice on how to use this particular .JS file for people who are new to javascript and HTML
and where this line [[ callFunction("test1", '{"onH":1,"onM":35,"offH":2,"offM":55) ]] should be located within HTML

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment