Using Spark.publish() with Simple JSON Data

Is there a better way to publish serial data? I am trying to do some research on how something behaves before and after an event. For that I am trying to publish the serial data at an interval so that I can inspect it after an event.

Ok, I am not sure what is happening, but I fixed the &quot issue. Basically, it looks like the {ā€œdataā€ :} field that is published with events was being published, even though I specified that the keen event data should be published under ā€œserial_dataā€. Meaning that there were two properties with the same data, one with &quot and one with ". When I deleted the one that I specified ( ā€œSerial_dataā€ : ā€œ{{SPARK_EVENT_VALUE}}ā€) I was left with ā€œdataā€: that was included with my webhook event. Only publishing one removed the &quot and the \ before the quotation. Here is the JSON for my webhook:

{
    "event": "keen",
    "url": "https://api.keen.io/3.0/projects/MYPROJECT/events/serial_events?api_key=MYAPIKEY",
    "requestType": "POST",
    "json": {
        "published_at": "{{SPARK_PUBLISHED_AT}}",
        "coreid": "{{SPARK_CORE_ID}}"
    },
    "mydevices": true
}

And here is the event that I am seeing posted now that I removed {{SPARK_EVENT_VALUE}}:

{
    "coreid": "55ff72066678505547401367",
    "keen": {
        "timestamp": "2015-08-07T01:22:30.098Z",
        "created_at": "2015-08-07T01:22:30.098Z",
        "id": "55c40856d2eaaa43c7569818"
    },
    "published_at": "2015-08-07T01:22:29.785Z",
    "data": "{\"one\": \"2\", \"onPointFive\": \"0\", \"Two\": \"0\", \"TwoPointFive\": \"0\", \"twoPointNine\": \"0\"}",
    "event": "keen"
} 

It is still not working because my { is wrapped in quotes, but I am one step closer.

Ok I confirmed that it is an issue with ā€œā€ being included in the post event. Even when I post the following (with " removed from the beginning and end):

sprintf(keenString, "%d\", \"serial_data\": {\"one\": \"%d\", \"onPointFive\": \"%d\", \"Two\": \"%d\", \"TwoPointFive\": \"%d\", \"twoPointNine\": \"%d\"} \"numberOfConsecutiveBarks\": \"%d", lastAlert, half, one, oneHalf, two, twoPlus, numberOfConsecutive)

I still get an output where the JSON is not recognized:

{
    "coreid": "55ff72066678505547401367",
    "keen": {
        "timestamp": "2015-08-07T01:40:56.160Z",
        "created_at": "2015-08-07T01:40:56.160Z",
        "id": "55c40ca8672e6c4eed8a13b5"
    },
    "published_at": "2015-08-07T01:40:55.898Z",
    "data": "0\", \"serial_data\": {\"one\": \"3\", \"onPointFive\": \"0\", \"Two\": \"0\", \"TwoPointFive\": \"0\", \"twoPointNine\": \"0\"} \"numberOfConsecutive\": \"50",
    "event": "keen"
}

Because it is wrapped in quotes, the \ is published with all of the data I need, and that is screwing up how the data is published.

Have you tried adding a JSON header to your web hook to send the right MIME type?

...
  "headers": {
    "Content-Type": "application/json"
    },
...

I get errors when I use headers as opposed to ā€œjsonā€:{}. Can you give me an example of a webhook using headers to specify content type, maybe I am formatting it incorrectly?

Hi @BarryAllen

There are some examples over in this thread:

I have not tried it myself.

Two other good things to try/know:

  • You can create a temporary place to test using the request.in web service and point your web hook at it for testing. This will let you see exactly what your hook is sending.
  • You should also make sure you can do your POST operation via a tool like curl from the command line to your actual host.
  • You can then switch curl to your requestb.in and see what the exact difference is that is causing your request to not work.

Hi everyone, i got something really weird with my published JSON :weary: .

my code looks like :

double temperature;
double humidity;
char relayState[4] = "LOW";
char status[64];

........

void update() {
    sprintf(
        status,
        "{\"temp\": %u, \"humi\": %u, \"relay\": \"%u\"}",
         temperature, humidity, relayState
    );
    Spark.publish("update", status);
}

and my published JSON :

{
    "data":"{\"temp\": 0, \"humi\": 1077280768, \"relay\": \"0\"}",
    "ttl":"60",
    "published_at":"2015-09-02T12:30:21.603Z",
    "coreid":"48ff6d065067555052462387",
    "name":"update"
}

Iā€™m sure that my variables temperature and relay arenā€™t equals to 0 and that humidity isnā€™t equal to 1077280768.
Any idea ? :boy:

AAAHHHH :smile:
I got it, itā€™s about my specifiers !

It looks like you already figured out that %u is for "unsigned" types. Here a nice reference to bookmark:

http://www.cplusplus.com/reference/cstdio/printf/

I am trying to use data saved on a form page to work with Particle.Publish code that you gave in the example. HTML for the form looks like this

<!DOCTYPE html>
<html>

<head> 
<meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link type="text/css" rel="stylesheet" href="css/main.css" >

<title> WEBAPP </title>

<script>
function sendIt(myValue){     // simplifies sending info to the photon
    document.all.myParameter.value=myValue
    document.myForm.action = 'https://api.spark.io/v1/devices/' + document.all.myDeviceId.value + '/SWITCH'
    document.all.mySend.value = document.myForm.action 
    
    document.myForm.submit();
    
}
</script>
    

    

</head>

<body onload="{
   myStorage1 = localStorage.getItem('myStoredText1')
   if(myStorage1  != null){      
      document.getElementById('myToken').value = myStorage1 
    }
    
    myStorage2 = localStorage.getItem('myStoredText2')
    if(myStorage2  != null){
       document.getElementById('myDeviceId').value = myStorage2 
      
    }
    
      
}">

  

<h2 align=center><a href="http://www.somename.net/" >UC</a> TESTING WEBAPP </h2>

<div>

<align=center>  ENTER DEVICE ID AND TOKEN.</align> <br>



Device ID:<br>
<input id="myDeviceId" name="myCoreID" type=password size=40 placeholder="78dd12345678123456"> 
something


<input id="myFunctionName" name="myFunction"  type=hidden  value="SWITCH" > 




<form name="myForm" method="POST" action = "https://api.spark.io/v1/devices/sparkCoreName/myTurnOn" target="myFrameName">

<input id="myParameter" name="params" type=hidden > 

Access Token:
<input id="myToken" name="access_token" type=password size=40 placeholder="5622ce6bba702ef6bd3456d5ed26aaa4a28d7c9"> something</a><br><br>
    

</form>

<input type="button" class="differentbutton" value="SAVE LOGIN!" onClick="{
   localStorage.setItem('myStoredText1', document.all.myToken.value)   
   localStorage.setItem('myStoredText2', document.all.myDeviceId.value)
   alert( document.all.myToken.value + ' ' +document.all.myDeviceId.value + ' \nHas been stored')
}">
</div>

Thats the code from your example modified to work with my sketch

<span id="tempC"></span><br>
<span id="tempA"></span><br>    
<script type="text/javascript">
    function start() {

        document.getElementById("tempC").innerHTML = "Waiting for data...";
        var deviceID = "2a0038000847343337373738";
        var accessToken = "8c8a591d74d01b100dbd1a4d70db0db5f497ae63";
        var eventSource = new EventSource("https://api.spark.io/v1/devices/" + deviceID + "/events/?access_token=" + accessToken);

        eventSource.addEventListener('open', function(e) {
            console.log("Opened!"); },false);

        eventSource.addEventListener('error', function(e) {
            console.log("Errored!"); },false);

        eventSource.addEventListener('temperature', function(e) {
            var parsedData = JSON.parse(e.data);
            var tempSpan = document.getElementById("tempC");
            
            tempSpan.innerHTML = parsedData.data + " &deg; C";
           
        }, false);
    }
        start();
    </script>

How can i make new eventSource get Device ID and Token from the form values that have been stored?

Hi @Ali

It is not completely clear to me what you are trying to do here, but I take it that you want to store the credentials locally in the browser to avoid typing them in over and over. Some your particle API calls do not make sense to me, like your POST request.

If I were starting this today, I would recommend using ParticleJS, the Javascript API that is officially supported:

https://docs.particle.io/reference/javascript/

Thatā€™s is right. I am trying to store them locally. I will look into particleJS and see if that makes it any easier for me.

Iā€™ve used that library on this page. Thereā€™s also local storage included, should you be interested.

1 Like

Thank you!

I keep getting this error when trying to install spark.js.
I have CLI installed and its working fine.

@Moors7
The link for your example page opens fine on my phone. But does not show me the button when i open it using Chrome on my Desktop.

I just installed the latest Node.js on a clean system and get the same errors. Disregarding that, I do find the Library in there.
You should be able to find them in the directory_you_were_in\node_modules\spark path. Depending on what you want to do, you might not even need them like that. You can use the CDN to include the minified library into your webpage, if thatā€™s what youā€™re making.

I also installed the latest Chrome version in which I do see the button. Not sure whatā€™s going on there. Works in Edge, Chrome, Opera, (mobile) Safari at first glance. Havenā€™t tried others as of yet. The code is on GitHub as well, Should you find that easier.

1 Like

Yea i will use CDN. The button doesnt show in Chrome or Firefox on another computer. It shows on my iphone. its connected to the same network. What im trying to make is a webapp that can use one login page and carry over DeviceID and Token over multiple pages. Pages would have Post events and Publish events.

Hi @Ali

When I have problems with Chrome (in particular) and Firefox, I always try incognito mode. Chrome in particular tries to cache lots of junk other browsers donā€™t and it can cause problems. These days when I want to run the web IDE, I always just start it in incognito mode to avoid problems, for instance.

Its not just Chrome. The browsers donā€™t seem to be downloading spark.min.js Couldnā€™t get anything to work. I just pointed the source to read locally to get it working for now

Hi again,

@andreh posted an amazing WEBAPP written in Angular Here. I modified the files to work for my project. He has however been missing on the forum and i desperately need some help with getting my publish events working. I am a novice at everything programming. His app.js file has a function for events built into it.

 /** Register a handler which will be called for each incoming event from any owned device. */
        registerMineEvents: function(handler) {
            this.registerDeviceEvents('mine', handler);
        },

        publishEvent: function(event) {
            return $http.post(baseUrl + '/devices/events', event);
        }
    }
});

and he uses ng-repeat to show all the events in a list format.

 <div ng-show="events[device.id] && events[device.id].length > 0">
                            <h3>Events</h3>
                            <table class="table">
                                <thead>
                                    <tr>
                                        <th class="hidden-xs">Time</th>
                                        <th>Event</th>
                                        <th>Data</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <tr ng-repeat="event in events[device.id]">
                                        <td class="hidden-xs">{{event.published_at}}</td>
                                        <td>{{event.name}}</td>
                                        <td>{{event.data}}</td>
                                       
                                    </tr>
                                </tbody>
                            </table>
                        </div>                        

What if i want to show specific events by themselves instead of them creating sequential duplicates and update those events whenever a new value is pushed as per the programming in Photon. Kind of like the tutorial you did.

Any help will be greatly appreciated as i am quite stuck.