Copyright © https://mongoose-os.com

Mongoose OS Forum

frame

Wait until SNTP connect to time.google.com to run function

CuyiCuyi Santiago, Chile
edited February 27 in Mongoose OS

I'm reading a epoch time "date" from a file when the thing start, and I need calculate alarm = date - Time.now(). But I've a problem because Time.now() return Sys.uptime() by a while until the thing connect to time.google.com.

Is there a way that I could calculate alarm only if sntp is connected to time.google.com?

EDIT: I'm using javascript

Comments

  • Something like this:

    load('api_events.js');
    
    let timeInit = false;
    function timeChangedHandler(ev, evdata, userdata)
    {
        timeInit = true;
        if (timeInit) {
            print('=== time synchronized ===');
            timeInit = false;
        }
    }
    
    // Add handler for MGOS_EVENT_TIME_CHANGED
    // https://github.com/cesanta/mongoose-os/blob/1508fece2cf563b15ea52ba453487195332439e3/fw/include/mgos_event.h#L101
    // https://github.com/mongoose-os-libs/mjs/blob/fcb2a816d57a30da3a558ee07e1e8c39dde6d995/fs/api_events.js#L2
    Event.addHandler(Event.SYS + 5, timeChangedHandler, null);
    
    Thanked by 1Cuyi
  • There are several solutions to this, but another trick you can try is to to have a timer that checks every second to see if the time.now is greater than some big number like 1,000,000,000. If it is, you have the sntp time, otherwise, you don't. However, the first solution is probably better and more efficient since you would need to stop the timer once done and may be more ram consuming.

    Thanked by 1Cuyi
  • CuyiCuyi Santiago, Chile

    nliviu thanks for all, it works.

  • CuyiCuyi Santiago, Chile

    Ok, the solution of nliviu doesn't work with the timer, when I tried:

    function timeChangedHandler(ev, evdata, userdata)
    {
         setAlarm(alarma);
    }
    
    Event.addHandler(Event.SYS + 5, timeChangedHandler, null);
    

    The timer in setAlarm never trigger, instead the solution of applecrusher works

    let tula = Timer.set(1000, Timer.REPEAT, function() {
      if( Timer.now() > 1000 ){
        setAlarm(alarma);
        Timer.del(tula);
      }
    }, null);
    
Sign In or Register to comment.