[request] Latest Particle API Javascript SDK Examples

I’m getting a similar error, as well as other errors that were not present until I updated to the latest SDK. That was part of the reason I asked about a tutorial for this latest build. Doing a little search I found that there seems to be a fair amount of people getting the https://api.particle.io/oauth/token error.

Hello James.

I made a thread about the error with https://api.particle.io/oauth/token error.

Maybe you could pass your findings in to the thread aswell

So the developer can get a picture how big the issue is.

BR
Dimi

Hello james.

I did some small test today, i moved some code for the server part instead of client part
and if the login is located on the server part i dont get any issues.

It might be so its a meteor issue and not particle-api-js as i first though.

i have not been able to varify it yet if everything is working.
if you get the time please post back how it goes.

BR
Dimi

Hey Dimi,

I’m actually not using a server, nor am I using a login, just the device ID and token. The project I’m working on will only be used in home LAN environments. Here is my project in case you were wondering - Peristaltic Doser - Doser set amount over 24hr period

If I do make any progress I’ll certainly let you know. I have no javascript experience so in my case I feel as though its a bit of a guessing game.

Thank you.

Haha im on the same road, its hard indeed and as you say most of the tutorials out there are for spark and not particle.

Have a look at this guys tutorial, he accomplish what you want but in a slight different way.

But atleast its a great tutorial but he dont use the particle-api-js as of now.
So i guess if you are doing this because you want to learn the particle-api-js
or that you just want to make it work on your local wifi.

Also we have rickkas7 tutorial, ofcourse :slight_smile:
Someday when i have the time i want to collect all this tutorials in one thread for easy access and a explanation what they do.

So for the issue you are getting, check your version, They corrected some user-agent issues in version 5.2.3, (It could be after this your issue started aswell?, what version did you have when it was working?, look at the official git location and check closed issues.) so if you are using an older version you might encounter issues.
else i guess you should make a new thread about the issues.
Remember to add alot of information of the issue, i tend to always forget that.

Hope you can continue the project, i will bang my head to the wall untill i have a working app atleast :smile:

BR
Dimi

Thank you for chiming in. The build I’m using was the one from the particle documentation. I dont have anything in front of me at the moment so I can’t be sure which version that is.

I’m traveling at the moment so don’t have much time to read further or even mess with anything at the moment. I’ve essentially hit a wall.

As for my previous build, that was built on a an old spark version that is long deprecated so I needed to update regardless.

As someone who only does this on a hobby basis it’s tough to learn this stuff. I do love it, but my money job takes up most of my time, therefore prohibiting me from taking the time to learn. I’m usually able to accomplish my goals through examples, tutorials and other posted projects. I’ve found there is a lack of up-to-date tutorials though with the current Java SDK making my situation, and yours, particularly frustrating. I don’t feel I can complain too much as the forums are free and it is out the goodness of people’s hearts to take the time to write the tutorials. At least that’s my assumption any way.

Anyway, enough chit chat…thank you for sending a few more bits of info my way. I’ll check them out and I’ll also check out the current builds.

Thank you!

Hello James. this code is working fine for me. Hope it get you pass were you are :slight_smile:
I will work on on more but this is a starter for me atleast.

var Particle = require('particle-api-js');
var particle = new Particle();
var token;
var device;

//Initialise the login
particle.login({username: 'ur email on particle.io', password: 'ur password on particle.io'}).then(
  function(data){
    console.log('API call completed on promise resolve: ', data.body.access_token);
    token = data.body.access_token;
    device = data.body.id;
    console.log('token data: ', token);
    console.log('device data: ', device);

    // list all the devices that is accossiated with the token that we got from the login
    var devicesPr = particle.listDevices({ auth: token });

    devicesPr.then(
      function(devices){
        console.log('Devices: ', devices);
      },
      function(err) {
        console.log('List devices call failed: ', err);
      }
    );

    //Get events from the device's, deviceID = mine is needed so we dont get events from all public events. 
    particle.getEventStream({ deviceId: 'mine', auth: token }).then(function(stream) {
      stream.on('event', function(data) {
        console.log("Event: " + data.name);
      });
    });
  },
  // if login failes
  function(err) {
    console.log('API call completed on promise fail: ', err);
  }
);

BR
Dimi

Thanks Dimi,

Would you mind sharing your html as well? I’m curious how your complete page works. I haven’t had a moment to play with anything for a while now, hopefully this week. I appreciate you keeping me in the loop.

Hello James.

I have not started with the HTML yet :slight_smile:
The code above shows everything in the consol so i also need to figure out how to
show the data i want in the page hehe.

My next step is to collect the events and put it in to a database
and make a eventview that list them. that part i will not be able to explain when im done if you dont know meteor that uses mongodb.

I am using meteor www.meteor.com.
Why i do so is because when i was looking for a framework to work with as a beginner i needed good tutorial and they have that so i advise you to look at the same. their tutorial goes fast and explain the basic.

When you have done the tutorial you create a new project
and you do the following. you will understand some of it after the tutorial.

  1. Install nodejs they have tutorial on their website https://nodejs.org/en/ its so you can use npm package.
  2. install meteor www.meteor.com - its the framework you will use to code
  3. npm install particle-api-js - when you have created your project,
  4. install git https://git-scm.com/book/en/v2/Getting-Started-Installing-Git - its so you can clone other peoples boilerplate
  5. git clone https://github.com/Differential/meteor-boilerplate.git (https://github.com/Differential/meteor-boilerplate/tree/materialize) - its an boilerplate aka template, code that other people have done, its makes ur site looks good so you dont have to do all the work yourself, for this one i recommend you have a look at iron:router. http://iron-meteor.github.io/iron-router/

This is by all means not a must :slight_smile: most of it is because of the boilerplate and that one i dont know much about, im simply looking in to what they have done and try to understand it as much as i can, eventhou 90% i will not understand.
It dosent matter thou since i do progress all the time and i dont need to understand everything.

All my code from particle needs to be run under the server part ( you will understand after the tutorial )

skip step 5 untill you have a understanding of everything, when you think you understand you do step 5 and that template helps you to make the site good looking.

You might encounter some issues with
var Particle = require(‘particle-api-js’); part of the code.

I cant remember right now but it was something that you need to install “meteor install npm” , as i remember i got a message about it.

Anyway i talk alot. but this is the only way i know of about since i have not done any other framework and meteor looks like a program for beginner aswell.

I will do a tutorial of all this when im done but i dont think that will be in some month from now since i also have limited time with work and family hehe.

good luck and i keep you posted what i do.

/Emilkl

1 Like

@james211 Here’s a very rough html (I know little of html) throw together example:

<html>
<head>
  <meta charset="UTF-8">
  <title>Particle Promise Login Example</title>
  <script src="https://cdn.jsdelivr.net/particle-api-js/5.2.6/particle.min.js"></script>
</head>

<body>
  <style type="text/css">
  textarea.fixed {
      overflow-x:hidden;
      height: 60em;
      }
  </style>
  <div>
<label>MyDevices</label>
</div>
<div>
<textarea name="outputtext" label="MyDevices" form=""class="fixed" rows="4" cols="160"  autofocus="true" readonly="true" id="outputtext" ></textarea>
</div>

<script type="text/javascript">

var timeoptions = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' };
//var Particle = require('particle-api-js');
var particle = new Particle();
var token;
var device;

    // Login to particle
    particle.login({
      username: 'your email',
      password: 'your password'}).then(function(data){
    console.log('API call completed on promise resolve: ', data.body.access_token);
    token = data.body.access_token;
    device = data.body.id;
    console.log('token data: ', token);
    console.log('device data: ', device);

    // list all the devices that is accossiated with the token that we got from the login
    var devicesPr = particle.listDevices({ auth: token });
        devicesPr.then(
          function(devices){
            console.log('Devices: ', devices);
          },
          function(err) {
            console.log('List devices call failed: ', err);
          }
        );
        particle.getEventStream({ deviceId: 'mine', auth: token }).then(function(stream) {
          stream.on('event', function(data) {
            console.log("Event: " + data.name);
//           console.log("Event: " + JSON.stringify(data));
            document.getElementById("outputtext").innerHTML +=
              JSON.stringify(new Date(data.published_at).toLocaleString('en-US', timeoptions)) +
                "   " + JSON.stringify(data.data) + "\n";
          });
        });
      },
      // if login fails
      function(err) {
        console.log('API call completed on promise fail: ', err);
      });

  </script>
</body>
</html>
1 Like

Thank you @bpr … why is this commented out? //var Particle = require('particle-api-js');

The require is used in node.js. In a web page, the library is loaded via the script tag at the top.

Ah, but since I’m loading at the top for a web its not necessary then?

The example he gave me I have to embed my username and login in the html file. With the new SDK can I just use my token and device ID to login?

I guess in the end it won’t matter given this file will only exist on a LAN network and never hit the web.

@james211 Thank you for asking that question! Didn’t consider that. Just tested it and yes you only need the auth token like so:

<!DOCTYPE html>
  <head>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>events display test</title>
  </head>
  <body onload="init()">

  <style type="text/css">
  textarea.fixed {
      overflow-x:hidden;
      height: 60em;
      }
  </style>
  <div>
<label>MyDevices</label>
</div>
<div>
<textarea name="outputtext" label="MyDevices" form=""class="fixed" rows="4" cols="160"  autofocus="true" readonly="true" id="outputtext" ></textarea>
</div>


    <script type="text/javascript" src="https://cdn.jsdelivr.net/particle-api-js/5.2.6/particle.min.js"></script>
<script type="text/javascript">
var timeoptions = { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric' };

    function init() {
      var particle = new Particle();
// no login needed!     particle.login({username: 'XXXXXXXXXXXXXX', password: 'XXXXXX'});
      particle.getEventStream({ deviceId: 'mine', auth: 'yourauthtoken' }).then(function(stream) {
        stream.on('event', function(e) {
          console.log("Event: " + JSON.stringify(e));

          document.getElementById("outputtext").innerHTML +=
           JSON.stringify(new Date(e.published_at).toLocaleString('en-US', timeoptions)) +
             "   " + JSON.stringify(e.data) +
             JSON.stringify(e) +
             JSON.stringify(e.coreid) +
             "\n";
       });
    });
}

</script>

  </body>
</html>

Here’s what I currently have, and I keep getting the error the functionPost is not defined.

<!DOCTYPE html>
<html>
  <head>
  <script type="text/javascript" src="https://cdn.jsdelivr.net/particle-api-js/5.2.6/particle.min.js"></script>
  <meta charset="UTF-8">
  </head>
  <body>
  <button type="button" onclick="functionPost('manual', '1,on')">Manual</button>

  <script type="text/javascript">
var deviceID = '35002400094734343231xxxx';
var token = '3aaacdf9121d404c1a60d5f5f853585c156axxxx';
var particle = new Particle();

    function functionPost(functionName, functionArgument){
    var fnPr = particle.callFunction({ deviceId, functionName, functionArgument, token});
       fnPr.then(
  function(data) {
    console.log('Function called succesfully:', data);
  }, function(err) {
    console.log('An error occurred:', err);
  });
}
    }

</script>

  </body>
</html>

@james211 what are you trying to accomplish with functionPost?

I have several functions in my particle code that need to be called, setupChannel, manual and calibrate. I’m trying to figure out one for the moment, with hopes of being able to figure out the rest. I had some great help with the code for the project but now I’m really having a hard time with the webpage I’m trying to get up and running to control it.

Here are two of the call functions I use, the other is to setup the relays, dosing, and timing.
particle call doser-4 manual 1,off
particle call doser-4 calibrate 1,on

Here is the project:
https://community.particle.io/t/peristaltic-doser-doser-set-amount-over-24hr-period/21158/88?source_topic_id=21587

So I was able to get the first group of code working, but seeing that I know there is an easier way to do it, I tried the second half, but that didn’t work. Any thoughts?

So this is the one that works.

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/particle-api-js/5.2.6/particle.min.js"></script>
    <meta charset="UTF-8">
  </head>
  
  <body>
    <p> <b>Manual ON/OFF</b></p>
    <p>Pump 1
      <button type="button" id="manual-0-ON" functionName='manual', functionArgument='0,on'>ON</button>
      <button type="button" id="manual-0-OFF" functionName='manual', functionArgument='0,off'>OFF</button>
    </p>
    <p>Pump 2
      <button type="button" id="manual-1-ON" functionName='manual', functionArgument='1,on'>ON</button>
      <button type="button" id="manual-1-OFF" functionName='manual', functionArgument='1,off'>OFF</button>
    </p>

    <script type="text/javascript">
    var particle = new Particle();
          
    document.getElementById("manual-0-ON").addEventListener ("click", functionPost, false);

    function functionPost(functionName, functionArgument){
      var fnPr = particle.callFunction({ deviceId: '35002400094734343231xxxx' , name: 'manual' , argument: '0,on',  auth: '3aaacdf9121d404c1a60d5f5f853585c156axxxx'});
      document.getElementById("manual-0-OFF").addEventListener ("click", functionPost, false);
        function functionPost(functionName, functionArgument){
        var fnPr = particle.callFunction({ deviceId: '35002400094734343231xxxx' , name: 'manual' , argument: '0,off',  auth:'3aaacdf9121d404c1a60d5f5f853585c156axxxx'});
        document.getElementById("manual-1-ON").addEventListener ("click", functionPost, false);
        function functionPost(functionName, functionArgument){
          var fnPr = particle.callFunction({ deviceId: '35002400094734343231xxxx' , name: 'manual' , argument: '1,on',  auth: '3aaacdf9121d404c1a60d5f5f853585c156axxxx'});
          document.getElementById("manual-1-OFF").addEventListener ("click", functionPost, false);
          function functionPost(functionName, functionArgument){
            var fnPr = particle.callFunction({ deviceId: '35002400094734343231xxxx' , name: 'manual' , argument: '1,off',  auth:'3aaacdf9121d404c1a60d5f5f853585c156axxxx'});
          }
        }
      }
    }
    </script>
  </body>
</html>

This one doesn’t work:

<!DOCTYPE html>
<html>
  <head>
    <script type="text/javascript" src="https://cdn.jsdelivr.net/particle-api-js/5.2.6/particle.min.js"></script>
    <meta charset="UTF-8">
  </head>
  <body>
    <p> <b>Manual ON/OFF</b></p>
    <p>Pump 1
      <button type="button" id="postfunction" functionName='manual', functionArgument='0,on'>ON</button>
      <button type="button" id="postfunction" functionName='manual', functionArgument='0,off'>OFF</button>
    </p>

  <script type="text/javascript">
  var deviceId = "35002400094734343231xxxx";
  var auth = "3aaacdf9121d404c1a60d5f5f853585c156axxxx";
  var name = "functionName";
  var argument = "functionArgument";
  var particle = new Particle();
        
    document.getElementById("postfunction").addEventListener ("click", functionPost, false);
    
    function functionPost(name, argument){
      var fnPr = particle.callFunction({ deviceId, name, argument, auth});
      fnPr.then(
        function(data) {
          console.log('Function called succesfully:', data);
        }, function(err) {
          console.log('An error occurred:', err);
        }
      );
    }
  </script>
  </body>
</html>

I’ll try and explain why it does/doesn’t work, though I feel you should first decide what route you want to take, and stick to it. SDK/JQuery, either is fine, just please don’t keep using them through one another when asking about them on different posts. Better yet, stick to one posts.


The ‘working’ one…

<button type="button" id="manual-0-ON" functionName='manual', functionArgument='0,on'>ON</button>

In there, you’re adding custom attributes to the HTML, which may, or may not be, something you want to do. In this case, you probably don’t want to do that. Also, the comma after ‘manual’ shouldn’t be there regardless. Not to mention that adding them is utterly useless, since they’re not being used whatsoever, but we’ll get to that…

document.getElementById("manual-0-ON").addEventListener ("click", functionPost, false);

So, when the element with ID “manual-0-ON” is clicked you call the functionPost function. Fair enough. Let’s take a look at that function, shall we?

function functionPost(functionName, functionArgument){
  var fnPr = particle.callFunction({ deviceId: '35002400094734343231xxxx' , name: 'manual' , argument: '0,on',  auth: '3aaacdf9121d404c1a60d5f5f853585c156axxxx'});
  document.getElementById("manual-0-OFF").addEventListener ("click", functionPost, false);
  function functionPost(functionName, functionArgument){
    var fnPr = particle.callFunction({ deviceId: '35002400094734343231xxxx' , name: 'manual' , argument: '0,off',  auth:'3aaacdf9121d404c1a60d5f5f853585c156axxxx'});
    document.getElementById("manual-1-ON").addEventListener ("click", functionPost, false);
    function functionPost(functionName, functionArgument){
      var fnPr = particle.callFunction({ deviceId: '35002400094734343231xxxx' , name: 'manual' , argument: '1,on',  auth: '3aaacdf9121d404c1a60d5f5f853585c156axxxx'});
      document.getElementById("manual-1-OFF").addEventListener ("click", functionPost, false);
      function functionPost(functionName, functionArgument){
        var fnPr = particle.callFunction({ deviceId: '35002400094734343231xxxx' , name: 'manual' , argument: '1,off',  auth:'3aaacdf9121d404c1a60d5f5f853585c156axxxx'});
      }
    }
  }
}

That right there is the entire functionPost function. For some reason you’re creating another function within that, and a new one within that, and a new one within that. It probably should have been four separate functions, but now we’ve got a single (messed up) one.
Now for the interesting part. The eventlistener from earlier will call the ‘top’ level function, which is the only one it sees. That function expects two arguments functionPost(functionName, functionArgument), and you give it none addEventListener ("click", functionPost, false);.
The following code will then be executed:

var fnPr = particle.callFunction({ deviceId: '50ff6c065067545646580487' , name: 'temp' , argument: '0,on',  auth: 'd09a315a122f41d8b2b119d0010317e2948a6198'});
document.getElementById("manual-0-OFF").addEventListener ("click", functionPost, false);

The first line calls the actual functions, though there’s no need to make it a variable, since you’re not using it anyhow.
The second line registers a new event listener to listen to the second button (pump 1 off). Since you’re making it activate the same function as the last one, I’m thinking it’s only working because it uses the function within the same scope. Not sure, but that’s the only thing that seems to make sense. That’s then repeated for the other buttons as well.
Now, when I say ‘working’, that’s only partially true. Due tot he way it’s set up, with the cascading, only the first button will work initially. You need to press them sequentially at least once to have them all work. That’s only logical because the listeners aren’t attached until after you’ve executed the first function. And then the second, and finally the third.

Then back to the function arguments… Taking a look at the first function call only:

function functionPost(functionName, functionArgument){
  var fnPr = particle.callFunction({ deviceId: '50ff6c065067545646580487' , name: 'temp' , argument: '0,on',  auth: 'd09a315a122f41d8b2b119d0010317e2948a6198'});
  document.getElementById("manual-0-OFF").addEventListener ("click", functionPost, false);
  //cascaded other functions below...
} 

So, you’ve got a function that expects two arguments. As we’ve established before, you’re not giving them any. Not only that, but even if you did give them any, they wouldn’t be used regardless. Nowhere in that function do you use either of the arguments, rather you’ve hard coded the data.
From the example I gave you here:

function functionPost(functionName, functionArgument){
  var fnPr = particle.callFunction({ deviceId: ActualDeviceID, name: functionName, argument: functionArgument, auth: token });
}

I called that function, and handed it the two parameters it was expecting, as such:

<button type="button" onclick="functionPost('functionName', 'functionArgument')">function 1</button>

I then actually used those parameters in the function to replace some values. That way, I din’t have to hard code them into the function, which made it reusable. That was the whole point of using those parameters, otherwise, don’t bother adding them, they’re then pointless.

So, that’s the only classified as ‘working’.


The ‘not working’ one:

<button type="button" id="postfunction" functionName='manual', functionArgument='0,on'>ON</button>
<button type="button" id="postfunction" functionName='manual', functionArgument='0,off'>OFF</button>

Same thing as before, useless arguments, don’t bother.
More importantly, you’re giving both the same ID. Not only does it not make sense, it’s also not a good thing to do. They’re identifiers. Hard to identify if there are duplicates. Some more on StackExchange here. Just don’t do that…

var name = "functionName";
var argument = "functionArgument";

Unless you’ve changed those like you did in the button, this won’t be of much help, would it?

document.getElementById("postfunction").addEventListener ("click", functionPost, false);

Okay, duplicate IDs aside assuming they work, if you click either button, the same functionPost will be activated. Makes sense so far, let’s see what that function does…

function functionPost(name, argument){
  var fnPr = particle.callFunction({ deviceId, name, argument, auth});
  fnPr.then(
    function(data) {
      console.log('Function called succesfully:', data);
    }, function(err) {
      console.log('An error occurred:', err);
    }
  );
}

Well, would you look at that, it expects two arguments, neither of which it’s given.Just to be sure the variables declared earlier weren’t actually used, I had the arguments printed over the console, and it was complete garbage.
Disregarding that for a bit, let’s check the cloud call:

var fnPr = particle.callFunction({ deviceId, name, argument, auth});

This time around it makes sense to make it a variable, since you’ll be using that as a promise.
The function arguments however… are messed up. Let’s check the documentation how it’s supposed to look:

var fnPr = particle.callFunction({ deviceId: 'DEVICE_ID', name: 'brew', argument: 'D0:HIGH', auth: token });

You can’t just delete stuff and expect it to still work. That syntax is there for a reason, and if you don’t stick to it, chances are things won’t work. The way you’ve got it set up, the four arguments are actually variables. As said before, the name and argument are garbage, since they’re function arguments, but aren’t passed through. deviceID and auth do actually use the variables declared before. Then again, it won’t matter, because you didn’t stick to the syntax.


All in all, plenty of reasons why things aren’t working, for either version. And once again a great example of why cross-posting isn’t the way to go, since I’ve posted a working example over here, in response to another question of yours. Had these all been in the same topic, things might not have gotten this confusing.

Regardless, try to see if you understand why the above doesn’t work, got to start somewhere…

2 Likes

thank you for this…back to my original post now.