Reading Spark Variables with Your Own HTML File

Hi @Moors7,

I have cross checked the ID and Token value and they are correct. Should i need to install jquery or Ajax or any other software?
I have checked it on chrome and firefox too.

Thanks.

<html>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>

The above line loads jquery.min.js from Google.

What browser are you using? You need to use a modern browser like Chrome or Firefox and not IE.

What I would do is fire up the debugging console in the browser and see if I could see any errors.

1 Like

Hi bko,

Iā€™m having trouble with this as well.

Hereā€™s the code for the .ino file:

// -----------------
// Read temperature
// -----------------

// Create a variable that will store the temperature value
int temperature = 0;

void setup()
{
  // Register a Spark variable here
  Spark.variable("temperature", &temperature, INT);

  // Connect the temperature sensor to A7 and configure it
  // to be an input
  pinMode(A7, INPUT);
}

void loop()
{
  // Keep reading the temperature so when we make an API
  // call to read its value, we have the latest one
  temperature = analogRead(A7);
}

Hereā€™s the HTML file:

<!DOCTYPE HTML>
<html>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<body>
    <span id="temp"></span><br>
    <span id="tstamp"></span><br>

    <button id="connectbutton" onclick="start()">Read Temp</button>

    <script type="text/javascript">

    function start(objButton) {

        document.getElementById("temp").innerHTML = "Waiting for data...";
        document.getElementById("tstamp").innerHTML ="";
        var deviceID = "put_my_device_id_here";
        var accessToken = "put_my_access_token_here";
        var varName = "temperature";

        requestURL = "https://api.particle.io/v1/devices" + deviceID + "/" + varName + "/?access_token=" + accessToken;
        $.getJSON(requestURL, function(json) {
                 document.getElementById("temp").innerHTML = json.result + "&deg; F";
                 document.getElementById("temp").style.fontSize = "28px";
                 document.getElementById("tstamp").innerHTML = json.coreInfo.last_heard;
                 });
    }
    </script>
</body>
</html>

Any help would be tremendously appreciated. When I inspect in chrome the error Iā€™m getting is Failed to load resource: the server responded with a status of 404 (Not Found).

Hi @tallman2525

I cut and pasted your exact HTML into and it worked for me after I changed these two lines:

        var deviceID = "put_my_device_id_here";
        var accessToken = "put_my_access_token_here";

to have the correct info for my device and access token (which you can find in the web IDE Build Button menus among other places).

You could also make sure you can load the AJAX library here

http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js

which should appear as a block of text if you load this in a browser window.

1 Like

5 posts were merged into an existing topic: Peristaltic Doser - Doser set amount over 24hr period

Hey there @Herner I am a UI designer myself and very interested in displaying live graphs. Which solution did you use for creating the graph in your interface? Can you share some more insight?

Cheers!
John

@bko
this is a great tutorial!

I adapted this for a dimmer and a relay and thought Iā€™d share the test HTML and JavaScript I adapted from your code:

<!DOCTYPE HTML>
<html>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript" ></script>
<body>
    <P>Set Dimmer Level:<br><br>
    <input type="range" name="degBox" id="fadeBoxID" min="0" max="100" step="1" value="0" list="myData" onchange="setValue(this)">
    <datalist id="myData">
       <option value="0">
       <option value="10">
       <option value="20">
       <option value="30">
       <option value="40">
       <option value="50">
       <option value="60">
       <option value="70">
       <option value="80">
       <option value="90">
       <option value="100">
    </datalist>
    <br><br>
    <button id="minusbutton" onclick="fineAdjust(-10)">-10%</button>
    <button id="plusbutton"  onclick="fineAdjust(+10)">+10%</button>
    <br><br>
    <P>Current Dim Level: <span id="curPos"></span><br>
    <br><br>
    <h2>Relay Device</h2>
    <p><input type="radio" id="relayRadio1" value="0" onclick="toggleParticlePower(relayID, relayPowerFunction, this.value)" name="relay" /> Off
    <input type="radio" id="relayRadio2" value="1" onclick="toggleParticlePower(relayID, relayPowerFunction, this.value)" name="relay"/> On
    </p>
    <p>Current Relay State: <span id="relayState"></span><br></p>


    <script type="text/javascript">

    $.ajaxSetup({
      timeout: 5*1000
    });

    var accessToken = "yourAccessTokenHere";
    // relayTV
    var relayID    = "yourDeviceID";
    var relayVariable = "Power";
    var relayPowerFunction = "Power";
    // Kitchen Dimmer
    var deviceID    = "yourDeviceID";
    var setFunc = "setDimLevel";
    var getFunc = "currentLevel";

    setInterval(function()
    {
      // Ajax call to Kitchen Dimmer
      requestURL = "https://api.spark.io/v1/devices/" + deviceID + "/" + getFunc + "/?access_token=" + accessToken;
      $.getJSON(requestURL, function(json) {
                 document.getElementById("curPos").innerHTML = json.result + "%";
                 document.getElementById("curPos").style.fontSize = "28px";
                 document.getElementById("fadeBoxID").value = json.result;
             });
      // Ajax call to relayTV
      myURL = "https://api.spark.io/v1/devices/" + relayID + "/" + relayVariable + "/?access_token=" + accessToken;
      $.getJSON(myURL, function(data) {
               var returnValue = (parseInt(data.result)? "On" : "Off");
               document.getElementById("relayState").innerHTML = returnValue;
               document.getElementById("relayState").style.fontSize = "28px";
               $('#relayRadio1').attr('checked', !parseInt(data.result));
               $('#relayRadio2').attr('checked', parseInt(data.result));
               });
    }, 1000);

    function setValue(obj)
    {
      var newValue = document.getElementById('fadeBoxID').value;
      particleSetDimVal(newValue);
    }

    function fineAdjust(value)
    {
      var currentValue = parseInt(document.getElementById('curPos').innerHTML);
      var setValue = value + Math.round(currentValue / 10) * 10;  // increment and decriment along the 10's
      particleSetDimVal(setValue);
      document.getElementById("fadeBoxID").value = setValue;
    }

    function particleSetDimVal(newValue) {
    var requestURL = "https://api.spark.io/v1/devices/" +deviceID + "/" + setFunc + "/";
      $.post( requestURL, { params: newValue, access_token: accessToken });
    }

    function toggleParticlePower(particleDeviceID, particleFunction, newValue)
    {
      var requestURL = "https://api.spark.io/v1/devices/" + particleDeviceID + "/" + particleFunction + "/";
      $.post( requestURL, { params: newValue, access_token: accessToken });
    }

    </script>
</body>
</html>

I made them a little prettier in my UI, though :blush:

1 Like

Hi bko ā€“

Iā€™m interested in using my Dropbox account as a secure location for my Photonā€™s access token, but Iā€™m not sure how to go about it. Could you elaborate on the process you use, or point me towards any resources to accomplish this. Iā€™ve done some research but canā€™t seem to find a straightforward solution.

Really appreciate your tutorials. Thanks much.

I'd say he means to put the html file containing the page (including the access token) on your dropbox and then you can open that html from there, wherever you are and on whichever machine.

2 Likes

Hi @dmack

You just put the HTML file with your code including your access token into a folder on your Dropbox. Then from any computer or phone that you use Dropbox on, you can open the HTML file is a browser and use it as a web page.

I see that @ScruffR types faster than I do today!

2 Likes

Hello bko

When I run this code locally (file on my hard drive directly) I have no issue, the variable updates post haste! But when I run the very same code on my github.io hosted page it sits waiting foreverā€¦

Iā€™m super new to the web page get post javascript etcā€¦ Any direction you can point me?

Thank you,
rjones

Unfortunately I donā€™t know much about github.io pages. I read some of the doc and it does not seem like there are any limitations that could cause what you are seeing, but it is hard to know. It certainly is not meant for this type of page.

In any event, a page like will not keep your access token secure and probably should not be used! I would look for a hosting solution that allows for PHP so you can keep your token secret or at least rewrite the code to ask for username/password and only store a temporary token in javascript.

I generally avoid these issues and run the page locally, usually from Dropbox so I can have it available on multiple computers & devices I am using.

2 Likes

So it was an SSL thing apparently. The github.io hosted pages are https and it was seeing the initial AJAX ā€œcallā€ (?) as an unsecured script trying to run on a secured page. I changed the http to https just as a longshot and it works fine now. Iā€™m pretty new to the web side of things.

src=ā€œhttps://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.jsā€ type=ā€œtext/javascriptā€ charset=ā€œutf-8ā€>

Thanks!
rjones

I have question with your code, in script about the source what kind of source did you put? I m using photon and I m using a photon as my voltage sensor with a circuit.
Basically i m sending variable in html, but i m having difficulty getting that variable to my webpage. I m trying to use your example to see if it works.

Waiting for data...

<script type="text/javascript">

  window.setInterval(function() {

    var deviceID = <redacted>;
    var accessToken = <redacted>;
    var varName = "voltaje";

    requestURL = "https://api.particle.io/v1/devices/" + deviceID + "/" + varName + "/?access_token=" + accessToken;
    $.getJSON(requestURL, function(json) {
             document.getElementById("v").innerHTML = json.result + "&deg; F";
             document.getElementById("v").style.fontSize = "28px";
             document.getElementById("vstand").innerHTML = json.coreInfo.last_heard;
             });
}, 10000);
</script>

this is ur code with my variables

Hi @cora121

The variable name needs to match exactly, including the upper or lowercase letters, so make sure on your Photon you are using ā€œvoltajeā€ in your code where you declare the Particle variable.

When I redacted your post to hide confidential data, I noticed you had a leading blank in your deviceID.
This would probably also throw off the functionality.

1 Like

Thanks for the tutorial. I was able to get it working with my particle(argon). Iā€™m placing the HTML/javascript in a sites.google.com page. Works great on PC, however the $.getJSON call does not work on an Iphone. Can you offer any suggestions.

I just double-checked and this still works for me on my iPhone using Dropbox to hold the html file. When I browse to that file in the Dropbox app and select it, it launches a web browser that works correctly. I am not sure why is doesn't work from google sites.

That said on my phone, I have completely switched over to use Siri Shortcuts to do things like this. You can set up a shortcut with your deviceID, token, and variable name and have Siri read the value to you, which has a high "wow" factor.

1 Like

Inspired by BKOā€™s superb tutorials, I am now reading 7 Particle Variables with my own HTML File. Three of those variables are 600-byte long Strings that I constructed from char arrays applying snprinf in the Photon code (as documented in this forum on several places).
I found out that my HTML page however cannot read the variables right after another: on unexpected instances the status LED starts blinking cyan at a rather high frequency and in the WebPage I can see that then only some of the Particle variables are displayed. After a short while the communication with the cloud restores again automatically.
As I can perfectly read all those varables from the Particle console, I concluded that the problem that I am facing with the HTML page might have something to do with the timing of the communication with the cloud.
So I have build in some delays between the JSON functions pulling the variables from the cloud. That works fine!

However it was a rather trial-and-error approach finding out about the size of the delays, and I would feel more confident when there was a more structured way to determine those delays, or at least indicate what parameters play a role in the ā€œdynamicsā€ of getting fairly large amounts of data from Particle Cloud.
Is there???