Relay control through cloud functions

I am using this library https://github.com/jithurbide/SimpleRelay/tree/master/firmware, and trying to use this example https://github.com/jithurbide/SimpleRelay/blob/master/firmware/examples/2_Internet_Relays.cpp. I would like to use the different functions in the library. In my curl to the particle cloud functions. What do I pass for (String command) to control the different relays? I think it would help debugging if I could figure out how to pass back the parameters that went into the function and return them.(like below instead of returning 1 return what relay was turned on.

int relayOn(String command){
// Ritual incantation to convert String into Int
char inputStr[64];
command.toCharArray(inputStr,64);
int i = atoi(inputStr);

// Turn the desired relay on
myRelays.on(i);

// Respond
return 1;

}

Since you cannot return two ints… you could return either, but in this example, we return the state of the elay you pass the command to:

int relayPins[] = {D7, D1, D2, D3};  // any bunch of pins

void setup() 
{
  Particle.function("relay", relayCommand);  //message format is = Relay:2:1 or Relay:2:0 or even  Relay1:1 Relay1:0
  for(int i = 0; i < sizeof(relayPins)/sizeof(relayPins[0]); i++)
  {
      pinMode(relayPins[i], OUTPUT);
  }
}

void loop() 
{

}

int relayCommand(const char* params)
{
    char message[125] = "";
    strcpy(message, params);
    if(strstr(message, "Relay") != NULL)
    {
        int relayNumber = atoi(strtok(message,"Relay:"));
        int relayState = atoi(strtok(NULL, ":"));
        if(relayNumber >=0 && relayNumber < sizeof(relayPins)/sizeof(relayPins[0]))
        {
            char buffer[125] = "";
            sprintf(buffer,"Relay %d requested %s", relayNumber, relayState? "ON" : "OFF");
            Particle.publish("message", buffer);
            digitalWrite(relayPins[relayNumber], relayState? HIGH : LOW);
            return relayState? 1: 0;
        }
        else
        {
            Particle.publish("message", "invalid relay");
        }
    }
    Particle.publish("message", "invalid command");
    return -99;
}

and you don’t need the library…

2 Likes

… or you could encode multiple values into one as long the “sub-entries” don’t use the full in length.

e.g.

uint8_t v1 = 1;    // status 
uint8_t v2 = 6;    // relay nr
uint8_t v3 = 180;  // value

return v1*10000000 + v2*10000 + v3; // comes back as 10060180

@palsen, instead of toCharArray() and atoi() you could just use command.toInt().
And just return i instead if constant 1.

Very nice what would a curl look like, lets say relay D7?

1 Like

@palsen

Sort of like this:

Relay 0 ON:

curl https://api.particle.io/v1/devices/yourDeviceID/relay/ -d access_token=yourAccessToken -d "args=Relay:0:1"

Relay 0 OFF:

curl https://api.particle.io/v1/devices/yourDeviceID/relay/ -d access_token=yourAccessToken -d "args=Relay:0:0"

D7 in my example is Relay zero:

int relayPins[] = {D7, D1, D2, D3};  // any bunch of pins