How does the API call know which Particle.function() to call? [Solved]

Hi,

I have been always curious how the online form and Particle.functions actually communicate. This is based on the example code that is posted on the Particle Documentation Website.

This is the code that we have

        int led = D0; // This is where your LED is plugged in. The other side goes to a resistor connected to GND.
            int photoresistor = A0; // This is where your photoresistor is plugged in. The other side goes to the "power" pin (below).
    
        int power = A5; // This is the other end of your photoresistor. The other side is plugged into the "photoresistor" pin (above).
         int analogvalue; 
        
    void setup() {
             pinMode(led,OUTPUT); // Our LED pin is output (lighting up the LED)
            pinMode(photoresistor,INPUT);  // Our photoresistor pin is input (reading the photoresistor)
            pinMode(power,OUTPUT); // The pin powering the photoresistor is output (sending out consistent power)
            Particle.variable("analogvalue", &analogvalue, INT);
            Particle.function("led",ledToggle);
            }  
        void loop() {
        analogvalue = analogRead(photoresistor);
        delay(100);
        }

        int ledToggle(String command) {
    
        if (command=="on") {
            digitalWrite(led,HIGH);
            return 1;
        }
        else if (command=="off") {
            digitalWrite(led,LOW);
            return 0;
        }
        else {
            return -1;
        }
        } 

And here is the HTML file from where we are controlling the LED:

        <html>
      <body>
      <center>
      <br>
      <br>
      <br>
      <form action="https://api.particle.io/v1/devices/your-device-ID-goes-here/led?access_token=your-access-token-goes-here" method="POST">
        Tell your device what to do!<br>
        <br>
        <input type="radio" name="args" value="on">Turn the LED on.
        <br>
        <input type="radio" name="args" value="off">Turn the LED off.
        <br>
        <br>
        <input type="submit" value="Do it!">
      </form>
      </center>
      </body>
    </html>

So, my question is how does the online form know it has to take the Particle.function(β€œled”,ledToggle); ? We might have multiple functions on the Wed Ide and we might have multiple forms on the website I am working on. Basically how does this work ? How does the form know which function to choose ?

The web form specifies which Cloud function to use in the api URL. in this case it goes after the device id and is "led"

I can see that now ! I am not sure why I never realized that :smile: Thank you so much.

2 Likes

This topic was automatically closed after 2 days. New replies are no longer allowed.