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.