Sky showed me Particle’s javascript library, and I thought I would post what I had to do to get it working.
Particle’s documentation can be found at: https://docs.particle.io/reference/javascript/
My updated files are at: https://github.com/arathorn593/IDeATePhysCompProject03-Cardboard
- From the terminal, run:
npm install particle-api-js
- To allow you to use the library in the main
script.js
file, you must add this line to your index.html file:<script type="text/javascript" src="//cdn.jsdelivr.net/particle-api-js/5/particle.min.js"></script>
. This line needs to go before you import thescript.js
file, so you should have your new line followed by the existing line that includes the script:
12345/* this is the added line */<script type="text/javascript" src="//cdn.jsdelivr.net/particle-api-js/5/particle.min.js"></script>/* this is the existing line */<script src="js/script.js"></script> - Next, add the code to login at the top of your init function. Make sure to save your token to a global variable and don’t include the
var Particle = require('particle-api-js');
line that the particle documentation says to include. Thus, the top of your init file should look something like:
123456789101112131415161718var particle;var token;function init() {particle = new Particle();particle.login({username: user, password: pass}).then(function(data){console.log('API call completed on promise resolve: ', data.body.access_token);token = data.body.access_token;},function(err) {console.log('API call completed on promise fail: ', err);});//....} - Now, you are set up and you can use the functions in the library. The only one I am using right now is the callFunction function. I call it whenever the default stool object is selected (check out the picker function in script.js). To call a function on your photon, you also need to register the function to the cloud within you photon code (see https://docs.particle.io/reference/firmware/photon/).
- My photon code:
123456789101112131415161718192021222324252627bool state = false;void setup() {pinMode(D7, OUTPUT);//register the function with the cloudParticle.function("light", light);}void loop() {//don't need to do anything here}//this function is called from the script.js file when//the stool is selectedint light (String str) {//toggle the state of the lightstate = !state;//write to the lightif (state) {digitalWrite(D7, HIGH);} else {digitalWrite(D7, LOW);}return 3; //return any number} - The code to call the light function:
12345678var fnPr = particle.callFunction({ deviceId: deviceID, name: 'light', argument: 'hi', auth: token });fnPr.then(function(data) {console.log('Function called succesfully:', data);}, function(err) {console.log('An error occurred:', err);});
- My photon code:
Let me know if I need to add anything to this post.
Leave a Reply