Fetching Particle.publish for output in an html textbox

For a group final project I'm looking to fetch particle.publish statements from the photon and print them in a log box on an html site. The project works as a security system for a house in a very basic sense. You can toggle the system to armed or unarmed from the website, if armed and motion is detected, the door is locked with a servo motor. The issue I'm running into is ouputting the detection of motion with a timestamp on the website so the user can see it.
The method I was recommended was subscribing to the event like so:

String latestEvent = "No events yet";

  Particle.variable("latestEvent", latestEvent);
  Particle.subscribe("", handleEvent, MY_DEVICES);

and with the function

void handleEvent(const char *event, const char *data)
{
  String timeStr = Time.format(Time.now(), "%H:%M:%S");
  latestEvent = "[" + timeStr + "] " + String(event) + ": " + (data ? String(data) : "");
}

Then, to fetch it from the cloud in the html using

function pollLatestEvent() {
            fetch(`https://api.particle.io/v1/devices/${deviceId}/latestEvent?access_token=${accessToken}`)
                .then(res => res.json())
                .then(data => {
                    const latest = data.result;
                    if (logLines[0] !== latest) {
                        logLines.unshift(latest);
                        if (logLines.length > MAX_LOG_LINES) logLines.pop();
                        logBox.value = logLines.join("\n");
                    }
                })
                .catch(err => {
                    console.error("Failed to fetch event:", err);
                });
        }

        setInterval(pollLatestEvent, 2000);

However the website is not able to fetch the statement and returns an error every two seconds:
Failed to fetch events: ReferenceError: res is not defined at SecurITY.html:88:13

Any suggestions? The tutoring system for this class has been of no help due to lack of available office hours and email response times so I'm trying anything.

Which line is line 88?

You can no longer put the access token as a query parameter in a GET request. See sending your access token.

You can't subscribe to an empty event name. There is no way to subscribe to all events on a device, it needs to have a least a prefix of a name.

Hey @LandonM25 it seems like you're getting a Reference Error when trying to call res on line 88 of your script. It's possible you have a scoping issue or are calling res before it's defined.

line 88 is the beginning of this if statement
if (logLines[0] !== latest) {
logLines.unshift(latest);
if (logLines.length > MAX_LOG_LINES) logLines.pop();
logBox.value = logLines.join("\n");
}

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.