[request] Latest Particle API Javascript SDK Examples

Has there been any new tutorials written with the latest version of the javscript API? I’ve been looking around for some basic examples and haven’t had much luck.

I just posted one. I wrote it some time ago, but kind of forgot about it until you mentioned it.

1 Like

I love tutorials like this :slight_smile: i will have a check on it and learn. i checked some other examples on the net but i always get this issue

XMLHttpRequest cannot load https://api.particle.io/oauth/token. A wildcard ‘*’ cannot be used in the ‘Access-Control-Allow-Origin’ header when the credentials flag is true. Origin ‘http://localhost:3000’ is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.

Anything you have seen or heard about?

BR
Dimi

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