Async handling of API calls on Electron

This seems like the simplest use of an Electron but I can’t seem to find the answer.

I want the Electron to close a relay (bit goes high), wait for 2 minutes and have that bit go low. This should be triggered with a POST like:
curl https://api.particle.io/v1/devices/12341234123412341234/backsprink/ -d access_token=brokenpokentoken -d args=zone3

Problem is: as I am doing it I get timeouts on the client side, since my code waits too long to report it is done. Really I want the electron to report back right away “ok” that it is starting the cycle and have the cycle just run asynchronously. Bonus would be if I can make another call while the timer was running and have it interrupted.

my code is like:

    int led1 = D0;
    int led2 = D1; 

    void setup() {
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      
      Particle.function("backsprink", backSprink);
    }

    void loop() {
    }

    int backSprink(String command) {
        if(command == "zone1") {
            digitalWrite(led1, HIGH);
            delay(120000);
            digitalWrite(led1, LOW);
        }
        return(0);
    }

Any help would be much appreciated!!

    int led1 = D0;
    int led2 = D1; 
    bool flag = false;

    void setup() {
      pinMode(led1, OUTPUT);
      pinMode(led2, OUTPUT);
      
      Particle.function("backsprink", backSprink);
    }

    void loop() {
        if (flag){
            digitalWrite(led1, HIGH);
            delay(120000);
            digitalWrite(led1, LOW);
        }
    }

    int backSprink(String command) {
        if(command == "zone1") {
            flag = true;
        }
        return(0);
    }

Setting a flag in a function, and checking on that in the main loop is one of the solutions.
As for interrupting it while the timer is running, there are several options. Millis() timers are one of them, while software timers would be another choice.

1 Like

I think this makes sense. Basically: do everything in the loop. Initiate from the functions but do the “business” in the loop.

1 Like