Search

Particle core/photon/electron function post data using curl or wget

Particle core/photon/electron function post data using curl or wget

This is a quick howto on using curl, wget or any other web based method to pass data to a Particle (formerly Spark) Core, Photon or Electron.
Prerequisites:

  • working Particle device as listed above
  • software on the device waiting for user passed data
  • The device’s access token

A simple code example which exports a function is below.

int ledPin = D7; //D7 on Particle devices has an attached LED
int lastLedStatus = LOW;

void setLed(int ledStatus)
{
    digitalWrite(ledPin, ledStatus);
    lastLedStatus = ledStatus;
}

/*
    The function labbyFunc() receives data from the internet and can act on it.
    It returns a value that can be parsed by your HTTP client.
    Return values:
    0 LED is off (off)
    1 LED is on (on)
    2 LED was off, now it is on (toggle)
    3 LED was on, now it is off (toggle)
    4 unrecognised command
*/
int labbyFunc(String command)
{
    if(command.toLowerCase() == "off")
    {
        setLed(LOW);
        return 0;
    }
    else if(command.toLowerCase() == "on")
    {
        setLed(HIGH);
        return 1;
    }
    else if(command.toLowerCase() == "toggle")
    {
        setLed(HIGH - lastLedStatus);
        if(lastLedStatus == HIGH)
        {
            return 2;
        }
        else
        {
            return 3;
        }
    }
    else
    {
        return 4;
    }
}

void setup()
{
    Particle.function("labbyFunc", labbyFunc);
    pinMode(ledPin, OUTPUT);
    setLed(lastLedStatus);
}

void loop()
{
    //There is nothing to see here, all the work is done in the labbyFunc function
    //whenever it receives data.
}

For the remote side we can use the HTTP POST method of talking to the device such as a web browser (using a form), curl or wget.
We need some information before we can send the request, deviceID and accesstoken.
deviceID can be found in the Devices section of the Particle build page https://build.particle.io#devices
accesstoken can be found in the Settings section https://build.particle.io#settings

curl:

curl https://api.particle.io/v1/devices/deviceID/labbyFunc -d labbyFunc="ON" -d access_token="accesstoken"

wget:

wget -q https://api.particle.io/v1/devices/deviceID/labbyFunc --post_data="labbyFunc=ON&access_token=accesstoken"

Errors and their solutions:
{“ok”:false,”error”:”Variable not found”}
Are you trying to send the data using GET eg ?labbyFunc=on – if so use POST.
If you have forgotten the function name you can get the function list using https://api.particle.io/v1/devices/{deviceID}?access_token={accesstoken}

If you need any help just drop a message in the comments and I will get back to you.

Related posts

Leave a Comment