Crontab and mgos_crontab_register_handler

My goal is to activate a pump at certain intervals, using ESP32-Wroom32D. I thought using cron would be a good idea and more specifically chose crontab. But I have firstly not understood how to name the JSON file with the crontab and where to connect it to my code. Secondly, I get these errors when building:

error: incompatible type for argument 1 of ‘mgos_crontab_register_handler’

and

note: expected ‘struct mg_str’ but argument is of type ‘char *’

Here are relevant parts of my code.

//Switching H2O2 pump off
static void timerPumpH2O2(void *user_data) {
  if(statePumpH2O2 == 1) {
    LOG(LL_INFO, ("Pump H2O2 off"));
    statePumpH2O2 = 0;
    mgos_gpio_write(pinPumpH2O2, statePumpH2O2);
  }
}

void activateH2O2pump(struct mg_str action, struct mg_str payload, void *userdata) {
  statePumpH2O2 = 1;
  mgos_gpio_write(pinPumpH2O2, statePumpH2O2);
  mgos_set_timer(20000, false, timerPumpH2O2, NULL); // Set timer for switching pump off, false = only once
  (void) payload;
  (void) userdata;
  (void) action;
}

enum mgos_app_init_result mgos_app_init(void) {
  mgos_crontab_register_handler("pump", activateH2O2pump, NULL);  //This is where I get the errors

  mgos_gpio_set_mode(pinPumpH2O2, MGOS_GPIO_MODE_OUTPUT);
  
  return MGOS_APP_INIT_SUCCESS;
}

This is the json file with the crontab.

{"items":[
  ["1", {
    "at": "0 */6 * * *",
    "enable": true,
    "action": "pump",
    "payload": {"a": 1, "b": 2}
  }]
]}

Am grateful for help, thanks.

mgos_crontab_register_handler(“pump”,
"pump" is a string, what in C is an array of chars, a char *
a struct mg_str is Mongoose internal way of representing strings.
The documentation here incorrectly leads you to do that.
mg_str is documented here, try this fix:

mgos_crontab_register_handler(mg_mk_str("pump"), 

If you need to modify the schedule dynamically, crontab is the way to go. Otherwise use the cron library.

The crontab.json file is maintained by the rpc-service-cron library.
E.g to connect the pump action to a schedule

mos call cron.add '{"at":"0 */6 * * * *","action":"pump"}'

To disable it

mos call cron.edit '{"id":1,"at":"0 */6 * * * *","action":"pump","enable":false}'
1 Like