Ajax

Hello, I want to command from a web interface a common-cathode RGB LED connected to the imp’s pins 1, 2, and 5.
I want to turn then on or off or to change the color. I have some problem doing this in ajax I don’t know how to write.

the agent code

`// At the start, print a message to say we’re online, and print the agent URL:
server.log("LED Web Control Agent Online: " + http.agenturl());

// requestHandler handles all http requests coming into the agent. It’s only
// setup to look for a select few requests: “led”, “rgb”, “user” and “timer”.
http.onrequest(function (request, response) {
response.header(“Access-Control-Allow-Origin”, “*”);
response.header(“Access-Control-Allow-Headers”,“Origin, X-Requested-With, Content-Type, Accept”);
response.header(“Access-Control-Allow-Methods”, “POST, GET, OPTIONS”);

try { // Try provides us with exception handling, in case a runtime error occurs

    // check if the user sent led as a query parameter
    if ("led" in request.query) {
        // if they did, and led=1.. set our variable to 1
        if ((request.query.led == "1") || (request.query.led == "0"))
        {
            // convert the led query parameter to an integer
            local ledStatus = request.query.led.tointeger();

            // send "led" message to device, and send ledState as the data
            device.send("led", ledStatus); 
        }
    }
    // check if an "rgb" query was received:
    if ("rgb" in request.query) {
        // colors are sent as a string, we've got to do some work to convert
        // them to a number, which is eventually what we'll need to do
        // pwm on our RGB led pins.
        local color = request.query.rgb; // get the query into a variable
        if (color[0] == '#') { // The request should start with '#' (%23)
            // We'll construct a table with three parameters: r, g, and b
            // Do some work to convert r, g, and b from ASCII characters
            // to 0-255 values.
            local returnTable = {
                r = ASCIItoHex(color[1])*16 + ASCIItoHex(color[2])
                g = ASCIItoHex(color[3])*16 + ASCIItoHex(color[4])
                b = ASCIItoHex(color[5])*16 + ASCIItoHex(color[6])
            };
            device.send("rgb", returnTable); // send our color table to the imp
        }
    }
    // check if a "timer" query was received:
    if ("timer" in request.query) {
        // convert to an integer, and pass it out to the imp.
        device.send("timer", request.query.timer.tointeger());
    }
    // send a response back saying everything was OK.
    response.send(200, "OK");
} 
catch (ex) {
    response.send(500, "Internal Server Error: " + ex);
}

});

// This function converts an ASCII character to a number
function ASCIItoHex(colorNibble) {
if ((colorNibble >= ‘0’) && (colorNibble <= ‘9’)) {
return colorNibble - 48;
}
else if ((colorNibble >= ‘a’) && (colorNibble <= ‘f’)) {
return colorNibble - 87;
}
else if ((colorNibble >= ‘A’) && (colorNibble <= ‘F’)) {
return colorNibble - 55;
}
}`

and html and ajax

`!DOCTYPE html
html
head

script src=“http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js”>
/head

body
script type=“text/javascript”

function headingSearch(status)
{
$.ajax({
type: “get”,
url: “https://agent.electricimp.com/…”,
//datatype:“json”,
data: {led:status, rbg:status} ,
success: function(data) {
console.log(“Succes”);
},
contentType:"'Access-Control-Allow-Origin"
});
}

script
input type=“button” name=“led” value=“aprinde” onclick=“headingSearch(1);”>

input type=“button” name=“led” value=“stinge” onclick=“headingSearch(0);”>

input type=“button” name=“rgb” value=“red” onclick=“headingSearch(’#ff0000’);”>

/body
/html`

Edit - wrapped your code in code tags (the C above the entry box) - it helps with formatting, etc.

Can you explain your problem a bit more: What’s not working? Are you getting any javascript or Squirrel errors, etc?

the buttons on and off are working, the red one is not sending the value. And is from the ajax because if I type https://agent.electricimp.com/agentURL?rgb=%23ff0000 in the browser the led is red. and I need some help with ajax. please help me is from a project at school

Since you’re using a GET, you can’t send data in the ‘data’ field for AJAX… I think you want to do something like this:

`
function headingSearch(status)
{
var getUrl = “https://agent.electricimp.com/yourAgentUrl?led=” + status + “&rgb=” + status;

$.ajax({
      type: "get",
      url: getUrl,
      success: function(data) {
        console.log("Succes"); 
      },
});

}`

Alternatively, you could change the GET to the post, then http.jsondecode() the body data in the agent… although the above change is much simpler.

It’s working, but if I push the red button and I didn’t push the on button before, the led it’s red, and I don’t want this. If the led it’s off and I push the red button the led must remain off.

And I don’t understant how to write my program with http.jsondecode().

That’s likely a problem with how you’re handling your agent messages in the device code.

You need to be tracking whether the LED should be ON or OFF, and what colour it should be. When you get an “rgb” message from the agent, you should set a variable in the device to set the color, but ONLY change the LED if the current LED state is ON.

I have a function that I use to set the color for the rgb led. I found some examples with http.jsondecode but I have some difficulties understanding them.

this is the device code

`imp.configure(“LED Web Control”, [], []); // Configure the imp

// Setup variables for our pins:
lightreading <- hardware.pin9
redPin <- hardware.pin1; // R of RGB
greenPin <- hardware.pin2; // G of RGB
bluePin <- hardware.pin5; // B of RGB

// Configure our pins:
lightreading.configure(ANALOG_IN);
redPin.configure(PWM_OUT, 0.01, 0); // PWM output 10ms clock, off
greenPin.configure(PWM_OUT, 0.01, 0); // PWM output 10ms clock, off
bluePin.configure(PWM_OUT, 0.01, 0); // PWM output 10ms clock, off

/////////////////////////////////
// Agent Function Declarations //
/////////////////////////////////
// setLed will turn the lonely red LED on or off.
// This function will be called by the agent.
function setLed(ledStatergb)
{
redPin.write(ledStatergb);
greenPin.write(ledStatergb);
bluePin.write(ledStatergb);
}

// setRGB will take a table input, and set the RGB LED accordingly.
// the table input should have parameters ‘r’, ‘g’, and ‘b’.
// This function will be called by the agent.
function setRGB(rgbValue)
{
bluePin.write(rgbValue.b/255.0);
redPin.write(rgbValue.r/255.0);
greenPin.write(rgbValue.g/255.0);
}
// setTimer will turn the LEDs off after a specified number of seconds
// This function will be called by the agent.
function setTimer(time)
{
if (time != 0)
imp.wakeup(time, ledOff); // Call ledsOff in ‘time’ seconds.
}

light <- 0

function readSensor()
{
light=lightreading.read();
server.log(format(“Lightness is:” +light));
imp.wakeup(0.001, readSensor);
}

readSensor();

///////////////////////////////////
// Important Agent Handler Stuff //
///////////////////////////////////
// Each object that the agent can send us needs a handler, which we define with
// the agent.on function. The first parameter in agent.on is an identifier
// string which must be matched by the sending agent. The second parameter is
// the name of a function to be called. These functions are already defined up
// above.
agent.on(“led”, setLed);
agent.on(“rgb”, setRGB);
agent.on(“timer”, setTimer);

// ledsOff just turns all LEDs off.
function ledOff()
{
redPin.write(0);
greenPin.write(0);
bluePin.write(0);
}`

how can I put here a condition, when the led is on to have the posibility to change the color and when the led is off, the led remains off

Please make sure to sure your code in the < code > </ code > tags so it’s more readable.

The issue is that you’re directly setting the pins on an “rgb” message. You need to store the RGB value in a variable, then only set the pins if it’s currently set to on…

`ledState <- 0; // off
ledColor <- { r = 255, g = 255, b = 255 }; // default to white for color

function setRGB(rgbValue)
{
ledColor.r = rgbValue.r;
ledColor.g = rgbValue.g;
ledColor.b = rgbValue.b;

if (ledState) {
    bluePin.write(ledColor.b/255.0);
    redPin.write(ledColor.r/255.0);
    greenPin.write(ledColor.g/255.0);
}

}

function setLed(ledStatergb)
{
ledState = ledStatergb;
if (ledState) {
bluePin.write(ledColor.b/255.0);
redPin.write(ledColor.r/255.0);
greenPin.write(ledColor.g/255.0);
}
}`

That may or may not work, and is certainly not the best way of doing it… but give it a try, and see if you can figure out what you need to do!

It’s not working… I tried to modified your program but I can’t fix the problem

ledState <- 0; // off
ledColor <- { r = 255, g = 255, b = 255 }; // default to white for color

function setRGB(rgbValue)
{
if (ledState) {
ledColor.r = rgbValue.r;
ledColor.g = rgbValue.g;
ledColor.b = rgbValue.b;

    bluePin.write(ledColor.b/255.0);
    redPin.write(ledColor.r/255.0);
    greenPin.write(ledColor.g/255.0);
}

}

function setLed(ledStatergb)
{
ledState = ledStatergb;
if (ledState) {
bluePin.write(ledColor.b/255.0);
redPin.write(ledColor.r/255.0);
greenPin.write(ledColor.g/255.0);

}else{
    bluePin.write(0);
    redPin.write(0);
    greenPin.write(0);
    
    ledColor <- { r = 255, g = 255, b = 255 }; 
   
}

}
I found the problem

I need more help i want to know the status of the leds, if are off or on, how can I do that?

I modified the web interface communication

`

Light On/Off



`

Some help, please!!!:smiley: