Exemplo n.º 1
0
def ntptime(utc_shift=0):
    """
    Set NTP time with utc shift
    :param utc_shift: +/- hour (int)
    :return: None
    """

    if not WLAN(STA_IF).isconnected():
        errlog_add("STA not connected: ntptime")
        return False

    import struct

    def getntp():
        host = "pool.ntp.org"
        # (date(2000, 1, 1) - date(1900, 1, 1)).days * 24*60*60
        NTP_DELTA = 3155673600
        NTP_QUERY = bytearray(48)
        NTP_QUERY[0] = 0x1B
        addr = getaddrinfo(host, 123)[0][-1]
        s = socket(AF_INET, SOCK_DGRAM)
        try:
            s.settimeout(2)
            res = s.sendto(NTP_QUERY, addr)
            msg = s.recv(48)
        finally:
            s.close()
        val = struct.unpack("!I", msg[40:44])[0]
        return val - NTP_DELTA

    t = getntp()
    tm = localtime(t + utc_shift * 3600)
    # Get localtime + GMT shift
    RTC().datetime((tm[0], tm[1], tm[2], tm[6] + 1, tm[3], tm[4], tm[5], 0))
    return True
Exemplo n.º 2
0
def getTime():
    rtc = RTC()
    t = rtc.datetime()
    day = (t[0:3])
    week = (t[3])
    tm = (t[4:6])
    return day,week,tm
Exemplo n.º 3
0
    def __init__(self, file_, dt=1.0):
        self.dt = dt
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

        while 1:
            try:
                self.s.connect((HOST, PORT))
                self.socket_ = True
            except:
                time.sleep(1)
                continue
                #print('no connection to {}'.format(HOST))
                #self.f = open(file_, 'w')
                #self.socket_ = False
            break

        self.n = 0
        self.buf_index = 0
        self.buf_0_len = 1
        self.buf_0 = [[0, 0, 0] for i in range(self.buf_0_len)]

        self.rtc = RTC()
        self.i2c = I2C(baudrate=400000)
        self._setup()
        self.begin = time.ticks_ms()

        self.__alarm = Timer.Alarm(self._handler, dt, periodic=True)
Exemplo n.º 4
0
def setNTP_RTC():
    if WLAN(STA_IF).isconnected():
        for _ in range(4):
            try:
                # Sync with NTP server
                settime()
                # Get localtime + GMT
                (year, month, mday, hour, minute, second, weekday,
                 yearday) = localtime(time() + int(cfgget('gmttime')) * 3600)
                # Create RealTimeClock + Set RTC with time (+timezone)
                RTC().datetime((year, month, mday, 0, hour, minute, second, 0))
                # Print time
                console_write("NTP setup DONE: {}".format(localtime()))
                return True
            except Exception as e:
                console_write("NTP setup errer.:{}".format(e))
            sleep(0.5)
    else:
        console_write("NTP setup errer: STA not connected!")
    # Recursion to get actual time for cron execution
    if cfgget('cron'):
        console_write("[!] NTP setup retry due to cron is {}".format(
            cfgget('cron')))
        return setNTP_RTC()
    return False
Exemplo n.º 5
0
def syncTime():
  t = time()
  if t==0:
    return 0
  t+=3600*8
  tm = utime.localtime(t)
  tm = tm[0:3] + (0,) + tm[3:6] + (0,)
  print(tm)
  year=tm[0]
  print(year)
  month=tm[1]
  day=tm[2]
  hour=tm[4]
  second=tm[6]
  min=tm[5]

  print(month)
  print(day)
  print(hour)
  print(min)
  print(second)
  
  rtc = RTC() 
  rtc.init((year,month,day,2,hour,min,second,0))
  return 1
  '''
Exemplo n.º 6
0
def rtc_ntp_sync(TZ=0, timeout_s=30):
    from machine import RTC
    print("sync rtc via ntp, TZ=", TZ)
    rtc = RTC()
    print("synced?", rtc.synced())
    rtc.ntp_sync('nl.pool.ntp.org')
    print("synced?", rtc.synced())
    #time.sleep_ms(750)
    time.timezone(TZ * 3600)

    timeout_ms = 1000 * timeout_s
    for i in range(0, timeout_ms):
        if rtc.synced():
            print("rtc is synced after", i / 1000, "s")
            # if rtc.now()[0] == 1970:
            #     print()
            break
        if i % 100 == 0:
            print(".", end="")
        time.sleep_ms(1)
    if not rtc.synced():
        raise Exception("RTC did not sync in", timeout_ms / 1000, "s")

    print("rtc.now", rtc.now())
    print("time.gmtime", time.gmtime())
    print("time.localtime", time.localtime())
    print("gmt  ", end=" ")
    pretty_gmt()
    print("local", end=" ")
    pretty_local()
def draw_dynamic_screen(temp="N/A", humi="N/A", press="N/A"):
    local_time = "N/A"
    local_date = "N/A"
    print("Internet time acquired", internet_time_acquired)
    if (internet_time_acquired == True):
        rtc = RTC()
        date_time = rtc.datetime()
        print(date_time)  # print date and time
        print("Current date (year, month, day, day of week): ", date_time[0],
              "/", date_time[1], "/", date_time[2], " | ", date_time[3])
        print("Current time (hour:minute:second): ", date_time[4], ":",
              date_time[5], ":", date_time[6])

        local_time = str(date_time[4]) + ":" + str(date_time[5]) + ":" + str(
            date_time[6])
        local_date = str(date_time[0]) + "/" + str(date_time[1]) + "/" + str(
            date_time[2])

    print(local_time)

    display.text(temp, 45, 5, 1)
    display.text(humi, 45, 15, 1)
    display.text(press, 45, 25, 1)
    display.text(local_time, 45, 35, 1)
    display.text(local_date, 45, 45, 1)
    print("iftt_notification_sent: ", iftt_notification_sent)
    print("iftt_notification_counter: ", iftt_notification_counter)
    display.text('IFTTT in', 5, 55, 1)
    display.text(
        str(iftt_notification_interval_sec - iftt_notification_counter) + "s",
        80, 55, 1)  # This will show a countdown.
 def confService(self, atributes):
     self.connectionService = atributes['connectionService']
     self.errorLogService = atributes['errorLogService']
     self.uart = UART(1)
     self.ubx = ubx7(self.uart)  # UBX7 device declaration
     self.cmd = ubx7msg()  # commands to be sent to the ubx device
     self.res = ubx7msg()  # responses to be received from the ubx device
     self.ack = ubx7msg(
     )  #   ack (or nak) to be received from the ubx device
     self.rtc = RTC()
     if ('mode' in atributes) and ('frequency' in atributes):
         if not str(atributes['frequency']).isdigit() or atributes[
                 'frequency'] < 0:  #Comprobar si es un numero (isdigit) y si es negativo
             self.errorLogService.regError(
                 self.serviceID, -9)  #Incorrect AtributeValue Error
         else:
             self.frequency = atributes['frequency']
         if not str(atributes['mode']).isdigit() or atributes[
                 'mode'] < 0:  #Comprobar si es un numero (isdigit) y si es negativo
             self.errorLogService.regError(
                 self.serviceID, -9)  #Incorrect AtributeValue Error
         else:
             self.mode = atributes['mode']
     else:
         self.errorLogService.regError(self.serviceID, -2)  #ConfFile Error
Exemplo n.º 9
0
def set_NTP_time():
    import time
    from machine import RTC
    print("Setting time from NTP")

    t = get_NTP_time()
    if t is None:
        print("Could not set time from NTP")
        return False

    tm = time.localtime(t)
    tm = tm[0:6]

    offset = machine.nvs_getstr("badge", "time.offset")

    if not offset:
        offset = 1
        if tm[1] > 3 and tm[1] < 11:
            offset = 2
    tm = time.localtime(t + offset * 3600)
    tm = tm[0:6]

    rtc = RTC()
    rtc.init(tm)
    #rtc.datetime(tm)

    return True
Exemplo n.º 10
0
 async def reset(self, reason):
     if reason != "reset":
         RTC().memory(reason)
     await self.publish(DEVICE_STATE, reason)
     await self.mqtt.disconnect()
     await sleep_ms(500)
     reset()
Exemplo n.º 11
0
 def get_hhmmss(separator=":"):
     rtc = RTC()  # real time
     # get_hhmm(separator) | separator = string: "-" / " "
     hh = add0(rtc.datetime()[4])
     mm = add0(rtc.datetime()[5])
     ss = add0(rtc.datetime()[6])
     return hh + separator + mm + separator + ss
Exemplo n.º 12
0
 def confService(self, atributes):
     self.connectionService = atributes['connectionService']
     self.errorLogService = atributes['errorLogService']
     self.sensorsList = atributes['sensorsList']
     self.lock = atributes['lock']
     self.rtc = RTC()
     if ('sendingFrequency'
             in atributes) and ('sleepTime'
                                in atributes) and ('wakeTime' in atributes):
         if not str(atributes['sendingFrequency']).isdigit() or atributes[
                 'sendingFrequency'] < 0:  #Comprobar si es un numero (isdigit) y si es negativo
             self.errorLogService.regError(
                 self.serviceID, -9)  #Incorrect AtributeValue Error
         else:
             self.sendingFrequency = atributes['sendingFrequency']
         if not str(
                 atributes['sleepTime']).isdigit() and self.checkValidTime(
                     atributes['sleepTime']) == True:
             self.sleepTimeSeconds = self.conversionTime(
                 atributes['sleepTime'])
         else:
             self.errorLogService.regError(
                 self.serviceID, -9)  #Incorrect AtributeValue Error
         if not str(
                 atributes['wakeTime']).isdigit() and self.checkValidTime(
                     atributes['wakeTime']) == True:
             self.wakeTimeSeconds = self.conversionTime(
                 atributes['wakeTime'])
             self.timeInit(atributes['wakeTime'])
         else:
             self.errorLogService.regError(
                 self.serviceID, -9)  #Incorrect AtributeValue Error
     else:
         self.errorLogService.regError(self.serviceID, -2)  #ConfFile Error
     self.checkSleep()
def get_internet_time():
    global internet_time_acquired
    #ntptime.host = "0.au.pool.ntp.org"  # Find your local NTP server here: https://www.ntppool.org/en/
    print("GET TIME Connected? ", wlan.isconnected())
    rtc = RTC()

    try:
        print("Utime time before synchronization:%s" % str(utime.localtime()))
        #make sure to have internet connection
        ntptime.settime()
        print("Utime/UTC time after synchronization:%s" %
              str(utime.localtime()))
        current_time_date_utc = utime.localtime(
        )  # The ntptime library will set utime.localtime to the UTC time automatically.
        current_time_date_local = utime.mktime(
            current_time_date_utc
        )  # Create a new time object to store the local time.
        current_time_date_local += 11 * 3600  # Sydney is 11 hours ahead of UTC. One hour has 60*60 = 3600 seconds
        print("Local time:, ", utime.localtime(
            current_time_date_local))  # This show time at your location

        rtc.datetime((utime.localtime(current_time_date_local)[0],
                      utime.localtime(current_time_date_local)[1],
                      utime.localtime(current_time_date_local)[2], 0,
                      utime.localtime(current_time_date_local)[3],
                      utime.localtime(current_time_date_local)[4],
                      utime.localtime(current_time_date_local)[5], 0))

        internet_time_acquired = True
        print("Internet time received: ", internet_time_acquired)
    except:
        print("Error syncing time")
Exemplo n.º 14
0
def esp_sleep(seconds):
    print("Going to sleep for " + str(seconds) + "seconds")
    rtc = RTC()
    rtc.irq(trigger=rtc.ALARM0, wake=machine.DEEPSLEEP)
    time.sleep(2)
    rtc.alarm(rtc.ALARM0, seconds * 1000)
    machine.deepsleep()
Exemplo n.º 15
0
    def __init__(self, device_type, node_number, data_measure_interval,
                 template_measure_interval, data_sets_per_message):

        if (machine.reset_cause() == machine.DEEPSLEEP_RESET):
            f = open("variables.json", "r")
            self.variable_dict = ujson.loads(f.read())
            f.close()
            self.sequence_number = self.variable_dict["sequence_number"]
            self.node_number = node_number
            self.rtc = RTC()

            if (device_type == 'esp32'):
                self.tx = 17
                self.rx = 16
                self.xbee_power_pin = machine.Pin(18, machine.Pin.OUT)
                self.xbee_power_pin.value(1)
                self.xbee_clear_to_send = machine.Pin(19, machine.Pin.IN)
            elif (device_type == 'superb'):
                self.tx = 32
                self.rx = 33
                self.xbee_power_pin = machine.Pin(22, machine.Pin.OUT)
                self.xbee_power_pin.value(1)
                self.xbee_clear_to_send = machine.Pin(23, machine.Pin.IN)
            else:
                raise Exception("Device Type not known")

            self.data_measure_interval = data_measure_interval
            self.template_measure_interval = template_measure_interval
            self.data_sets_per_message = data_sets_per_message
            self.data_records_set_list = self.variable_dict[
                "data_records_set_list"]

        else:
            self.set_clock()
            self.sequence_number = 0
            self.node_number = node_number

            if (device_type == 'esp32'):
                self.tx = 17
                self.rx = 16
                self.xbee_power_pin = machine.Pin(18, machine.Pin.OUT)
                self.xbee_power_pin.value(1)
                self.xbee_clear_to_send = machine.Pin(19, machine.Pin.IN)
            elif (device_type == 'superb'):
                self.tx = 32
                self.rx = 33
                self.xbee_power_pin = machine.Pin(22, machine.Pin.OUT)
                self.xbee_power_pin.value(1)
                self.xbee_clear_to_send = machine.Pin(23, machine.Pin.IN)
            else:
                raise Exception("Device Type not known")

            self.variable_dict = {}
            self.data_measure_interval = data_measure_interval
            self.template_measure_interval = template_measure_interval
            self.data_sets_per_message = data_sets_per_message
            self.variable_dict["template_i"] = 0
            self.variable_dict["data_i"] = data_measure_interval
            self.variable_dict["data_records_set_list"] = []
Exemplo n.º 16
0
def do_something_else():   
#The other script to be executed besides of the blocking socket
    url = "http://worldtimeapi.org/api/timezone/Europe/Rome" #http://worldtimeapi.org/timezone/Europe/Rome" # see http://worldtimeapi.org/timezones
    web_query_delay = 60000 # interval time of web JSON query
    retry_delay = 5000 # interval time of retry after a failed Web query
    rtc=RTC()
    # set timer
    update_time = utime.ticks_ms() - web_query_delay
    #settime()
    tempo=utime.localtime()
    print((str(tempo)))
    
#     oled.text(str(tempo), 10, 50)
#     oled.show()
   # while True:
        # query and get web JSON every web_query_delay ms
    if utime.ticks_ms() - update_time >= web_query_delay:
    
        # HTTP GET data
        response_tempo = urequests.get(url)
    
        if response_tempo.status_code == 200: # query success
        
            print("JSON response:\n", response_tempo.text)
            
            # parse JSON
            parsed = response_tempo.json()
            datetime_str = str(parsed["datetime"])
            year = int(datetime_str[0:4])
            month = int(datetime_str[5:7])
            day = int(datetime_str[8:10])
            hour = int(datetime_str[11:13])
            minute = int(datetime_str[14:16])
            second = int(datetime_str[17:19])
            subsecond = int(round(int(datetime_str[20:26]) / 10000))
            #if minute ==31:
                #Client_handler(LEDON0=6)
                #LED2.value(1)
                #print (("LED0 value="),LED0.value())
            # update internal RTC
            rtc.datetime((year, month, day, 0, hour, minute, second, subsecond))
            update_time = utime.ticks_ms()
            print("RTC updated\n")
   
        else: # query failed, retry retry_delay ms later
            update_time = utime.ticks_ms() - web_query_delay + retry_delay
        
    # generate formated date/time strings from internal RTC
    date_str = "Date: {2:02d}/{1:02d}/{0:4d}".format(*rtc.datetime())  
    time_str = "Time: {4:02d}:{5:02d}:{6:02d}".format(*rtc.datetime())

    # update SSD1306 OLED display
    oled.fill(0)
    oled.text("ESP32 WebClock", 0, 5)
    oled.text(date_str, 0, 25)
    oled.text(time_str, 0, 45)
    oled.show()
    
    utime.sleep(0.1)
Exemplo n.º 17
0
def setlocal(h=2):
    import utime
    from machine import RTC
    rtc = RTC()
    localtime = utime.time() + h * 3600
    (year, month, mday, hour, minute, second, weekday,
     yearday) = utime.localtime(localtime)
    rtc.datetime((year, month, mday, 0, hour, minute, second, 0))
Exemplo n.º 18
0
def time_init():
    from ntptime import settime
    from machine import RTC

    rtc = RTC()
    # w()
    settime(zone=0)
    print("--- time: " + get_hhmm(rtc))
Exemplo n.º 19
0
def UpdateTime():
    try:
        if ((time.localtime()[4] == RTC().datetime()[5])
                and (time.localtime()[3] == RTC().datetime()[4])
                and (time.localtime()[5] - RTC().datetime()[6]) <= 3):
            print("同步前本地时间:%s" % str(time.localtime()))
            NetTimeSync()
            time.sleep(1)
        #(year, month, mday, hour, minute, second, weekday, yearday)=utime.localtime()
    except Exception as e:
        print('NTP server connection failed,please reboot board!')
        print("Couldn't parse")
        print('Reason:', e)
        display_sync_fail()
    else:
        #判断时,分相同,秒差3秒只内不同步,否则同步,目前只考虑rtc秒低于Internet
        print(" 同步后本地时间:%s" % str(time.localtime()))
Exemplo n.º 20
0
 def __init__(self):
     self.__datetime = Datetime()
     self.__timetuple = ()
     self.__seconds = 0
     self.__rtc = RTC()
     self.__rtc.ntp_sync("pool.ntp.org")  # sync to UTC time
     while not self.__rtc.synced():
         sleep(1)
Exemplo n.º 21
0
def update_time():
      ntptime.host='ntp1.aliyun.com'
      ntptime.settime()
      list=time.localtime(time.time()+8*60*60)
      rtc = RTC()
      #rtc.datetime((year, month, mday, 0, hour, minute, second, 0))
      rtc.datetime((list[0], list[1], list[2] ,None,list[3], list[4], list[5] ,0)) 
      print (rtc.datetime()) # get date and time
Exemplo n.º 22
0
	def __init__(self, message):
		#parse time recieved from the broker 
		date_time = message.split(" ")
		date = date_time[0].split('-')
		time = date_time[1].split(":")
		#use rtc to keep track of time on board
		self.__rtc = RTC()
		self.__rtc.datetime((int(date[0]), int(date[1]), int(date[2]), 0, int(time[0]), int(time[1]), int(time[2][0:2]), 0)) 
Exemplo n.º 23
0
def time_corr():
    if machine.reset_cause() == 1:
        import PST_time
        PST_time.time_pull()

    curr_min = RTC().datetime()[5]  #current minutes
    curr_sec = RTC().datetime()[6]  #current seconds
    i = 0
    min_diff = 60 - curr_min
    sec_diff = 60 - curr_sec
    if min_diff == 0:
        slep_time = 3660000 - (1000 * sec_diff)
    else:
        slep_time = (min_diff * 60000) + (60000) - (1000 * sec_diff)

    print(slep_time)
    return (slep_time)
Exemplo n.º 24
0
def start_app(act_name, msg):
    global tft
    tft.text(msg, 5, 5, WHITE)
    from machine import RTC, deepsleep
    rtc = RTC()
    rtc.memory(act_name)
    time.sleep(1)
    deepsleep(1)  # use deepsleep to reset and release memory
Exemplo n.º 25
0
def setRTCLocalTime():
    rtc = RTC()
    print("Time before sync: ", rtc.now())
    rtc.ntp_sync("pool.ntp.org")
    while not rtc.synced():
        utime.sleep(1)
        print("Waiting for NTP server...")
    print('\nTime after sync: ', rtc.now())
Exemplo n.º 26
0
def main(vs):
    global var_store, free_mem
    var_store = vs
    print("tfth.main")
    horo_main=var_store['horo_main']
    sd = var_store['sd']
    tft = var_store['tft']
    free_mem = var_store['free_mem']
    tzone = load_tzone()
    lat,lon,drx = load_geo_cfg()
    syn=sync_time()
    tm = get_time()
    ct = time.localtime(tm)
    yr,mon,mday,hr,minu,sec,wday,_,=ct    
    tfth = TFTHoro(tft,tzone=tzone, lat=lat,lon=lon,drx=drx)
    tfth.set_datetime(yr,mon,mday,hr,minu,sec)
    var_store['tfth']=tfth
    var_store['tft']=tft
    tft.start_spi()
    first_cycle=True
    while True:
        if chk_btn():
            break
        try:
            _t(horo_main,tfth,tft,first_cycle)
            if first_cycle:
                first_cycle=False
        except Exception as e:
            sys.print_exception(e)
            time.sleep(1)
        i=0
        while True:
            if chk_btn():
                break
            time.sleep(0.5)
            tm = get_time()
            ct = time.localtime(tm)
            yr,mon,mday,hr,minu,sec,wday,_,=ct
            colon=' '
            if i:
                colon=':'
            i = not i
            tft.draw_string_at(colon,244,165,fnt,fg=WHITE,bg=NAVY)
            if sec==0:
                if minu==0 or not syn:
                    # sync every hour
                    syn = sync_time()
                break
    # command mode
    free_mem()
    if btn['A']:
        print('ap_lunar')
        from machine import RTC, deepsleep
        rtc = RTC()
        rtc.memory('ap_lunar')
        #tft.text('Lunar calendar...',5,5)
        #time.sleep(1)
        deepsleep(1) # use deepsleep to reset and release all memory        
Exemplo n.º 27
0
def setup():
    global logger, rtc, sd, iCAM, iACC, CTLR_IPADDRESS, logfile, filename
    global wdt, ow, temp, py, sensor

    gc.enable()

    # HW Setup
    wdt = WDT(timeout=wdt_timeout)
    sd = SD()
    rtc = RTC()
    os.mount(sd,'/sd')
    # Enable WiFi Antenna
    Pin('P12', mode=Pin.OUT)(True)

    # TEMPERATURE SENSORS: DS18B20 and SI7006A20
    ow = OneWire(Pin('P10'))
    temp = DS18X20(ow)
    py = Pysense()
    sensor = SI7006A20(py)


    # SYSTEM VARIABLES
    iCAM = pycom.nvs_get('iCAM') # pycom.nvs_set('iCAM',1)
    iACC = pycom.nvs_get('iACC') # pycom.nvs_set('iACC',1)

    logfile='/sd/log/{}.log'.format(datetime_string(time.time()))
    logging.basicConfig(level=logging.DEBUG,filename=logfile)
    logger = logging.getLogger(__name__)

    # # NETWORK VARIABLES
    # pbconf = pybytes.get_config()
    # AP = pbconf['wifi']['ssid']
    # if AP == 'wings':
    #     CTLR_IPADDRESS = '192.168.1.51'
    # elif AP == 'RUT230_7714':
    #     CTLR_IPADDRESS = '192.168.1.100'
    #     # CONNECT TO AP
    #     wlan = WLAN(mode=WLAN.STA)
    #     while not wlan.isconnected():
    #         nets = wlan.scan()
    #         for net in nets:
    #             if net.ssid == 'RUT230_7714':
    #                 pybytes.connect_wifi()
    #
        # wlan.ifconfig(config=('192.168.1.100', '255.255.255.0', '192.168.1.1', '8.8.8.8'))
        # wlan.connect('RUT230_7714', auth=(WLAN.WPA2, 'Ei09UrDg'), timeout=5000)
        # while not wlan.isconnected():
        #     machine.idle() # save power while waiting
    socket_client.CTLR_IPADDRESS = CTLR_IPADDRESS

    # GREETING
    logger.info('--------------------')
    logger.info(' Starting CAM{}-ACC{}'.format(iCAM, iACC))
    logger.info('--------------------')
    logger.info('AP={}'.format(AP))
    gc.collect()

    return
Exemplo n.º 28
0
    def sync_clock(self, epoc):
        try:
            rtc = RTC()
            rtc.init(utime.gmtime(epoc))
        except Exception as ex:
            print("Exception setting system data/time: {}".format(ex))
            return False

        return True
Exemplo n.º 29
0
def get_datestring():
    from gc import collect
    from machine import RTC
    d = RTC().datetime()
    del RTC
    res = "{}-{}-{} {}:{}:{}".format(
        str(d[0])[2:], d[1], d[2], d[4], d[5], d[6])
    collect()
    return res
Exemplo n.º 30
0
def sync_sch():
    time = ("{:02d}:{:02d}:{:02d}".format(RTC().datetime()[4],
                                          RTC().datetime()[5],
                                          RTC().datetime()[6]))
    wday = int(RTC().datetime()[3])

    global sch0

    if (("weekdays" in sch0) and (len(sch0["weekdays"]) == 7)):
        #print('[Day %d] v2 -> %s' % (wday, len(sch0["weekdays"][wday])))
        for j in range(0, len(sch0["weekdays"][wday])):
            if (("when" in sch0["weekdays"][wday][j])
                    and ("what" in sch0["weekdays"][wday][j])
                    and (sch0["weekdays"][wday][j]["when"] >= time)):
                #print('\t [Time: %s] -> %d' % (sch["weekdays"][wday][j]["when"], sch["weekdays"][wday][j]["what"]))
                if ((sch0["weekdays"][wday][j]["when"] == time) and
                    (state_omap[0] != int(sch0["weekdays"][wday][j]["what"]))):
                    state_omap[0] = int(sch0["weekdays"][wday][j]["what"])