Search code examples
ctimeresp8266ledmongoose-os

Turn on 2 LED's at a particular time in C mongoose os


So I have an espressif chip connected to 2 LEDs, and mongoose os runs on it

I would like to get time from the internet/computer and make the led's turn on at a particular time.

eg. at 10:00 turn on/off led 1 connected to pin 2 and at 16:00 turn on/off led 2 connected to pin 3 in C.


Solution

  • Step 1: Add wifi setup to your mos.yml so it can connect to your wireless AP:

    config_schema:
      - ["wifi.sta.enable", true]
      - ["wifi.sta.ssid", "MyAP"]
      - ["wifi.sta.pass", "Passwd"]
    

    Step 2: Add these to your mos.yml. Leave off rpc-uart if you have no intention of making rpc calls over UART.

    libs:
      - origin: https://github.com/mongoose-os-libs/sntp
      - origin: https://github.com/mongoose-os-libs/crontab
      - origin: https://github.com/mongoose-os-libs/rpc-service-cron
      - origin: https://github.com/mongoose-os-libs/rpc-service-config
      - origin: https://github.com/mongoose-os-libs/wifi
      - origin: https://github.com/mongoose-os-libs/rpc-uart
    

    Step 3: Add crontab handlers for LED on and LED off:

    enum mgos_app_init_result mgos_app_init(void) {
      /* Set LED GPIOs as outputs */
      mgos_gpio_set_mode(YOUR_LED_GPIO, MGOS_GPIO_MODE_OUTPUT);
    
      /* Register crontab handler - LED OFF */
      mgos_crontab_register_handler(mg_mk_str("ledoff"), ledoff, NULL);
    
      /* Register crontab handler - LED ON */
      mgos_crontab_register_handler(mg_mk_str("ledon"), ledon, NULL);
    
      return MGOS_APP_INIT_SUCCESS;
    }
    

    Step 4: Add callbacks:

    void ledoff(struct mg_str action, struct mg_str payload, void *userdata) {
      mgos_gpio_write(YOUR_LED_GPIO, 0);
      (void) payload;
      (void) userdata;
      (void) action;
    }
    
    void ledon(struct mg_str action, struct mg_str payload, void *userdata) {
      mgos_gpio_write(YOUR_LED_GPIO, 1);
      (void) payload;
      (void) userdata;
      (void) action;
    }
    

    Step 5: From Web UI or UART:

    call Cron.Add '{"at":"0 0 10 00 * *", "action":"ledon"}'
    call Cron.Add '{"at":"0 0 16 00 * *", "action":"ledoff"}'
    

    See https://github.com/mongoose-os-libs/cron as a reference for the syntax of cron expressions on mgos.