Simple example of web server using Agent Code?

Does anyone have Hello World serving a web page with Agent Code?
It should be easy right? Using my external URL?
How about displaying the status of a Pin?

You are in luck - a month or two ago I was playing around with agents trying to build a “proper API.”

The project consists of an april board hooked up to a red and a green LED. You can turn the LEDs on and off through POSTs, and get their current states with a GET.

I made a handy GIST with the agent and device code, you can find it here (the code is also below).

Let me know if you have any questions!

Agent Code:
`local greenState = 0;
local redState = 0;

device.on(“setRed”, function(data) {
redState = data;
});

device.on(“setGreen”, function(data) {
greenState = data;
});

http.onrequest(function(request, response) {
local code = null;
local message = null;

if (request.path == "/lights")
{
    if (request.method == "GET")
    {            
        code = 200;
        message = "{ 'red': " + redState + ", 'green': " + greenState + " }";
    }
    else if (request.method == "POST")
    {
        try {
            local data = http.jsondecode(request.body);
            if ("red" in data)
            {
                server.log("red: " + data.red);
                device.send("setRed", data.red);
            }
            if("green" in data)
            {
                server.log("green: " + data.green);
                device.send("setGreen", data.green);
            }
            code = 200;
            message = "OK";
        }
        catch (e) {
            code = 501;
            message = "Unacceptable";
            server.log(e);
        }
    }
}
else
{
    code = 404; 
    message = "Not Found";
}

response.send(code, message);

});`

Device Code
`class LEDController{
pin = null;
colour = null
state = 0;

constructor(ledPin, ledColour){
    pin = ledPin;
    colour = ledColour;
    pin.configure(DIGITAL_OUT);
}

function TurnOn(){
    Write(1);
}

function TurnOff(){
    Write(0);
}

function Write(newState){
    if (newState == 0 || newState == 1)
    {
        state = newState;
        server.log(colour + ": " + newState);
        agent.send("set" + colour, newState);
        pin.write(newState);
    }
    else
    {
        server.log(newState + " is not a valid LED state. Please use 0 or 1.");
    }
    
}

};

local RedLED = LEDController(hardware.pin2, “Red”);
local GreenLED = LEDController(hardware.pin5, “Green”);

RedLED.TurnOff();
GreenLED.TurnOff();

agent.on(“setGreen”, function(state) {
GreenLED.Write(state);
});

agent.on(“setRed”, function(state) {
RedLED.Write(state);
});

imp.configure(“Red Light Green Light”,[],[]);`

How do I post from my web page? Like this?

`

`

To post from a webpage, change the form’s action from “blah.php” to the agent/external URL.

To find the agent url:

  1. Add an Http handler to your agent code (http.onrequest)
  2. Click ‘Device Settings’ - you should see ‘External URL’ at the top of the device settings page. This is what we’ll put in our action.

Here is a sample webpage + agent:

Webpage:
`






`

Agent:
http.onrequest(function(req, resp){ server.log("Got a request"); if (req.method == "POST"){ local body = http.urldecode(req.body) server.log(body.data); } resp.send(200, "OK"); });

The dev wiki has a fair bit of useful information about working with http requests, but feel free to also post questions here :slight_smile:

Edited for formatting

@sbright33 I’ve been building some tutorials aimed at makers might be a bit too simple for you but I’ve done a complete digital in & our from web app using Ajax & Jquery mobile to an April.
//App just enter your external URL by clicking on gear icon in meun bar
http://industrialinternet.co.uk/eimp/t123_digital/April_Digitial_OUT_app.html
//Source code for imp/agent/web app

I’ve not written up the digital output but if your posting Json you might want to take a look at this http://forums.electricimp.com/discussion/1017#Item_1

Can I just copy your code to my web host?
Put my external URL in line 17?
Wow Simple and Elegant!

I mean instead of clicking the gear icon.
I don’t see where pollRate is used in your code?

Can I just copy your code to my web host?
Yep that was the idea

Put my external URL in line 17?
Yep

I don’t see where pollRate is used in your code?
Polling is only used digital IN or IN_OUT examples
https://gist.github.com/industrialinternet/5419730
https://gist.github.com/industrialinternet/5441741

This is awesome! Thanks!

many thanks to @controlCloud for the above examples on github. I have used these to help create a simple self-hosted web page using agents.

This really a killer feature of the electric imp.

I wanted to point out that I had a bit of trouble with security features wanting to block the java.

the solution seems to have been to change this:

<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>

to this

`

`

my understanding is pretty shallow but it seems the mix of http and https was not allowed.

@mjkuwp94 not sure either why it causes an issue, will try and find out. If your interested I’ve added web sliders to allow changing of values and analog outputs. There on github.

This was first noticed (at least for me) when I switched to a web page served from the agent. This page is https://agent.electricimp.com/yEe

When I hosted my own web page it was not SSL I guess and so there was no complaints from the browser about that resource.

thanks gents, this helps a lot.

@beardedinventor mat thanks for this makes sense will modify my examples.

@mjkuwp94 @controlCloud - web browsers don’t like mixing https and http for security reasons.

Basically, HTTPS ensures your HTTP traffic is SSL encrypted (a Good thing). If you load a HTTP resource (in this case, a javascript file), there will be portions of the site that are no longer secure (as far as SSL is concerned).

Most CDN’s offer both HTTP and HTTPS versions of their resources - you can use “//code.jquery…” as above, or explicitly ask for the https version:

<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>