Query Agent URL Every 30 Seconds

I’m working on a project that lights an LED when my favorite hockey team scores a goal. I can get the LED to light when I hit the agent URL. I’d like to run a loop that hits the agent URL every 30 seconds, and I’m not sure how to go about doing this. I’m also not even sure if that’s the best way to do it. I’ve been reading up on imp.wakeup(), and am not sure if that’s what I’m looking for. If it is, I’m not clear on how to implement it. Some code:

Device Code
`
// pin9
led <- hardware.pin9;

// configure led to be a digital output
led.configure(DIGITAL_OUT);

ledState <- 0;

//hold score start at 0
score <- 0;

//function to light LED if goal is scored
//led stays lit for 2 seconds and then turns off
function setLed(ledState)
{
//log goal state to server
server.log("Set LED: " + ledState);
//write the state to the led
led.write(ledState);
//if a goal is scored, keep light on for 2 seconds
if (ledState == 1)
{
imp.sleep(5);
}
//turn led off
led.write(0);
ledState = 0;
server.log("Set LED: " + ledState);
}

//register a handler to check for goal scored
agent.on(“isGoalScored”, setLed);
`

Agent Code
`

local ledState;
local isGoalScored;
local urlGameId = @“2b846ffe-1c70-4cd5-a8d7-3a22ba0336e1”;
local url = “http://api.sportsdatallc.org/nhl-t3/games/” + urlGameId + “/boxscore.json?api_key=[KEY HERE]”;
local tblScores;

//
function getJSON(urlJSON)
{
local request = http.get(urlJSON);
local response = request.sendsync();
return response.body;
}

//Search and replace string
function stringReplace(string, original, replacement)
{
// make a regexp that will match the substring to be replaced
local expression = regexp(original);
local result = “”;
local position = 0;
// find the first match
local captures = expression.capture(string);
while (captures != null)
{
foreach (i, capture in captures)
{
// copy from the current position to the start of the match
//
result += string.slice(position, capture.begin);
// add the replacement substring instead of the original
//
result += replacement;
position = capture.end;
}
// find the next match
captures = expression.capture(string, position);
}
// add any remaining part of the string after the last match
result += string.slice(position);
return result;
}

function requestHandler(request, response)
{
try
{
http.onrequest(function(request, response){

	try 
	{
	    tblScores = getJSON(url);
	    
	    //convert table to string
		local jsonScores = http.jsonencode(tblScores);
		
	    //Remove backslashes
		jsonScores= stringReplace(jsonScores, @"\\\", @"");
		
		//Remove beginning quotation mark
	    local jsonScoresTemp = jsonScores.slice(1, jsonScores.len());
		jsonScores = jsonScoresTemp;
		
		//Remove quotation mark from end
	    local jsonScoresTemp = jsonScores.slice(0, jsonScores.len() - 1);
		jsonScores = jsonScoresTemp;
		
		//format scores as json
        local data = http.jsondecode(jsonScores);
        //server.log(jsonScores);
        //foreach(k , resp in data){
        //    server.log(" @" + k + " : " + resp + "@ ");
        //}

		// check if particular keys are in the json body
		if ("id" in data) 
		{
		    server.log(data.home.name.tostring() + ": " + data.home.points.tostring());
		    server.log(data.away.name.tostring() + ": " + data.away.points.tostring());

			//Turn LED light on
			//ledState = 1;
			//device.send("isGoalScored", ledState);
		}
	    
		// send response to whoever hit the agent url
		response.send(200, "JSON OK");
	} 
	catch (e) 
	{
		// send a response indicating invalid JSON
		response.send(500, "Invalid JSON");
	}
	});
} 
catch (ex) 
{
    response.send(500, "Internal Server Error: " + ex);
}

}

// register the HTTP handler
http.onrequest(requestHandler);
`

Yes, imp.wakeup() - which works fine in the agent too - is the right thing to use. You’d just use this to call your polling function that issues the outbound HTTP request to the sports server, and then re-queue the wakeup from within the polling function.

Note that the sports server may or may not like being bombarded with requests :slight_smile:

Awesome. Thanks for your reply.

I’m using a trial version of their service so I only get a certain amount per month. It is big bucks to pay for their service.

Allright, I guess I don’t understand as much as I thought. I’ve been been messing around with my code for 6 days now and can’t get it to work.

When you say my polling function, are you referring to my function called ‘getJSON(urlJSON)’ on line 10 or requestHandler(request, response) on line 49 (both in the agent code)?

I’ve tried to put it in both. To me, it makes more sense to put it in the requestHandler, as that is where all the requesting is done, but I can’t figure out how to use imp.wakeup() to call requestHandler.

When I add the following code in the request handler function
imp.wakeup(3.0, requestHandler);
I keep getting this error:
2014-12-01 22:38:18 UTC-7 [Agent] ERROR: callback must take 0 parameters in imp.wakeup(seconds, callback)

The help is much appreciated.

After 3 seconds requestHandler will be called with no parameters. You need to review the documentation and examples for http.onrequest() . You only need to call it once, to establish a handler.

`
function requestHandler(request, response) {
try {
// your code here
}
catch (ex) {
response.send(500, "Internal Server Error: " + ex);
}
}

// register the HTTP handler
http.onrequest(requestHandler);
`

Thank you so much for your reply. I read up on it, moved some code around, and it is working as expected. Thanks again.