Ejemplo n.º 1
0
    def syncSleepParams(self):
        todaySunset = ujson.loads(
            wifi.https_get(
                'https://api.sunrise-sunset.org/json?lat=40.45&lng=-3.72&date=today&formatted=0'
            ).split('\n')[-1])['results']['sunset']
        tomorrowSunrise = ujson.loads(
            wifi.https_get(
                'https://api.sunrise-sunset.org/json?lat=40.45&lng=-3.72&date=tomorrow&formatted=0'
            ).split('\n')[-1])['results']['sunrise']

        sleepTime = todaySunset.split('T')[-1].split('+')[0]

        sleepStart = mktime(
            tuple(int(i) for i in todaySunset.split('T')[0].split('-')) +
            tuple(
                int(i)
                for i in todaySunset.split('T')[-1].split('+')[0].split(':')) +
            (0, 0))
        sleepEnd = mktime(
            tuple(int(i)
                  for i in tomorrowSunrise.split('T')[0].split('-')) + tuple(
                      int(i) for i in tomorrowSunrise.split('T')[-1].split('+')
                      [0].split(':')) + (0, 0))

        sleepLength = (sleepEnd - sleepStart) * 1000  # ms
        sleepParams = sleepTime + ' ' + str(sleepLength)

        self.storeLastSyncedSleepParams(sleepParams)
Ejemplo n.º 2
0
 def getTime(self, analog=True):
     #year, month, day, hour, minute, second, ms, dayinyear = utime.localtime()
     #timezone issues, convert
     year = utime.localtime()[0]  #get current year
     #calculate last sunday of march and october
     HHMarch = utime.mktime((year, 3, (27 - (int(5 * year / 4 + 1)) % 7), 1,
                             0, 0, 0, 0, 0))  #Time of March change to Sumer
     HHOctober = utime.mktime(
         (year, 10, (31 - (int(5 * year / 4 + 1)) % 7), 1, 0, 0, 0, 0,
          0))  #Time of October change to Winter
     #then calculate and convert
     now = utime.time()
     SUMMER = 3600  #+1h in summer
     TIMEZONE = 3600  #TODO configure this parameter
     if now < HHMarch:  # WINTER
         dst = utime.localtime(now + TIMEZONE)
     elif now < HHOctober:  # SUMMER
         dst = utime.localtime(now + TIMEZONE + SUMMER)
     else:  # WINTER
         dst = utime.localtime(now + TIMEZONE)
     year, month, day, hour, minute, second, ms, dayinyear = dst
     if not analog:
         localtime = "{:0>2d}".format(hour) + ":" + "{:0>2d}".format(
             minute) + ":" + "{:0>2d}".format(
                 second) + "     " + "{:0>2d}".format(
                     day) + "/" + "{:0>2d}".format(month) + "/" + str(year)
         self.screen.writeText(text=localtime)
     else:
         self.screen.oled.fill(0)
         Clock().displayClock(screen=self.screen,
                              hours=hour,
                              minutes=minute,
                              seconds=second)
Ejemplo n.º 3
0
 def getcal(self, minutes=5):
     rtc.calibration(0)  # Clear existing cal
     self.save_time()  # Set DS3231 from RTC
     self.await_transition(
     )  # Wait for DS3231 to change: on a 1 second boundary
     tus = pyb.micros()
     st = rtc.datetime()[7]
     while rtc.datetime()[7] == st:  # Wait for RTC to change
         pass
     t1 = pyb.elapsed_micros(
         tus)  # t1 is duration (uS) between DS and RTC change (start)
     rtcstart = nownr()  # RTC start time in mS
     dsstart = utime.mktime(self.get_time())  # DS start time in secs
     pyb.delay(minutes * 60000)
     self.await_transition()  # DS second boundary
     tus = pyb.micros()
     st = rtc.datetime()[7]
     while rtc.datetime()[7] == st:
         pass
     t2 = pyb.elapsed_micros(
         tus)  # t2 is duration (uS) between DS and RTC change (end)
     rtcend = nownr()
     dsend = utime.mktime(self.get_time())
     dsdelta = (
         dsend - dsstart
     ) * 1000000  # Duration (uS) between DS edges as measured by DS3231
     rtcdelta = (
         rtcend - rtcstart
     ) * 1000 + t1 - t2  # Duration (uS) between DS edges as measured by RTC and corrected
     ppm = (1000000 * (rtcdelta - dsdelta)) / dsdelta
     return int(-ppm / 0.954)
Ejemplo n.º 4
0
    def __init__(self, ledController):
        self.ledController = ledController

        self.dirty = False
        self.mode = "schedule"
        self.static_colour = (5, 4, 3, 0)

        self.rainbow_brightness = 85
        self.rainbow_hue = 0

        timeset = False
        while not timeset:
            try:
                settime()
                timeset = True
            except Exception:
                print("Exception calling settime, retrying...")
                utime.sleep_ms(5000)

        now = utime.localtime()
        midnight_ticks_today = utime.mktime((now[0], now[1], now[2], 0, 0, 0, 0, 0))
        midnight_ticks_tomorrow = utime.mktime((now[0], now[1], now[2] + 1, 0, 0, 0, 0, 0))
        self.ticks_in_a_day = midnight_ticks_tomorrow - midnight_ticks_today

        self.load_scheduler_config()
    def rtc_test(self, runtime=600, ppm=False, verbose=True):
        if rtc is None:
            raise RuntimeError('machine.RTC does not exist')
        verbose and print('Waiting {} minutes for result'.format(runtime//60))
        factor = 1_000_000 if ppm else 114_155_200  # seconds per year

        self.await_transition()  # Start on transition of DS3231. Record time in .timebuf
        t = utime.ticks_ms()  # Get system time now
        ss = rtc.datetime()[6]  # Seconds from system RTC
        while ss == rtc.datetime()[6]:
            pass
        ds = utime.ticks_diff(utime.ticks_ms(), t)  # ms to transition of RTC
        ds3231_start = utime.mktime(self.convert())  # Time when transition occurred
        t = rtc.datetime()
        rtc_start = utime.mktime((t[0], t[1], t[2], t[4], t[5], t[6], t[3] - 1, 0))  # y m d h m s wday 0

        utime.sleep(runtime)  # Wait a while (precision doesn't matter)

        self.await_transition()  # of DS3231 and record the time
        t = utime.ticks_ms()  # and get system time now
        ss = rtc.datetime()[6]  # Seconds from system RTC
        while ss == rtc.datetime()[6]:
            pass
        de = utime.ticks_diff(utime.ticks_ms(), t)  # ms to transition of RTC
        ds3231_end = utime.mktime(self.convert())  # Time when transition occurred
        t = rtc.datetime()
        rtc_end = utime.mktime((t[0], t[1], t[2], t[4], t[5], t[6], t[3] - 1, 0))  # y m d h m s wday 0

        d_rtc = 1000 * (rtc_end - rtc_start) + de - ds  # ms recorded by RTC
        d_ds3231 = 1000 * (ds3231_end - ds3231_start)  # ms recorded by DS3231
        ratio = (d_ds3231 - d_rtc) / d_ds3231
        ppm = ratio * 1_000_000
        verbose and print('DS3231 leads RTC by {:4.1f}ppm {:4.1f}mins/yr'.format(ppm, ppm*1.903))
        return ratio * factor
Ejemplo n.º 6
0
    def _getcal_d(self, minutes, cal, verbose):
        verbose and print('Pyboard D. Waiting {} minutes for calibration factor.'.format(minutes))
        rtc.calibration(cal)  # Clear existing cal
        self.save_time()  # Set DS3231 from RTC
        self.await_transition()  # Wait for DS3231 to change: on a 1 second boundary
        t = rtc.datetime()  # Get RTC time
        # Time of DS3231 transition measured by RTC in μs since start of day
        rtc_start_us = get_us(t)
        dsstart = utime.mktime(self.convert())  # DS start time in secs

        utime.sleep(minutes * 60)

        self.await_transition()  # Wait for DS second boundary
        t = rtc.datetime()
        # Time of DS3231 transition measured by RTC in μs since start of day
        rtc_end_us = get_us(t)
        dsend = utime.mktime(self.convert()) # DS end time in secs
        if rtc_end_us < rtc_start_us:  # It's run past midnight. Assumption: run time < 1 day!
            rtc_end_us += 24 * 3_600_000_000

        dsdelta = (dsend - dsstart) * 1_000_000   # Duration (μs) between DS3231 edges as measured by DS3231
        rtcdelta = rtc_end_us - rtc_start_us  # Duration (μs) between DS edges as measured by RTC
        ppm = (1_000_000 * (rtcdelta - dsdelta)) / dsdelta
        if cal:  # We've already calibrated. Just report results.
            verbose and print('Error {:4.1f}ppm {:4.1f}mins/year.'.format(ppm, ppm * 1.903))
            return 0
        cal = int(-ppm / 0.954)
        verbose and print('Error {:4.1f}ppm {:4.1f}mins/year. Cal factor {}'.format(ppm, ppm * 1.903, cal))
        return cal
Ejemplo n.º 7
0
def init_on_cold_boot():
    # configure and connect WLAN
    wlan = network.WLAN(network.STA_IF)
    if not wlan.isconnected():
        print("connecting to network")
        wlan.active(True)
        wlan.connect("yourSSID", "yourPassword")
        while not wlan.isconnected():
            print(".", end="")
            utime.sleep(1)
    print()
    print('network config:', wlan.ifconfig())

    # set the time from the network
    settime()
    print(utime.localtime())

    # get current local time and convert it to a modifiable list
    first_schedule_time = list(utime.localtime())
    # When setting the second part to 0,
    # the time will be in the past so the function is scheduled immeditelly
    # and then again after repeatAfterSec from the time it was supposed to be scheduled (seconds 0).
    first_schedule_time[5] = 0  # seconds
    sl.schedule_at_sec(__name__, led_on_even_minute,
                       utime.mktime(first_schedule_time), 60)
    sl.schedule_at_sec(__name__, raw_temperature_every_half_a_minute,
                       utime.mktime(first_schedule_time), 30)
    sl.schedule_at_sec(__name__, hall_sensor_every_15_seconds,
                       utime.mktime(first_schedule_time), 15)
Ejemplo n.º 8
0
def cleanup():
    logging.info('Starting cleanup...')
    dir = uos.listdir()
    for f in dir:
        if f.endswith('.log'):
            logging.info('Found file: {}', f)
            try:
                year = int(f[:4])
                month = int(f[4:6])
                mday = int(f[6:8])
                filedate = time.mktime((year, month, mday, 0, 0, 0, 0, 0))
                year, month, mday, hour, minute, second, weekday, yearday = time.localtime(
                )
                two_days_ago = time.mktime(
                    (year, month, mday - 2, 0, 0, 0, 0, 0))
                if filedate < two_days_ago:
                    logging.debug('Removing...')
                    uos.remove(f)
                else:
                    logging.debug('Keeping...')

            except Exception as e:
                # logging.error('ERROR: cleanup {}', str(e))
                logging.debug('Skipping...')
                pass
    logging.info('Cleanup ended')
Ejemplo n.º 9
0
 def add_schedule_item(self, r, g, b, w, hour, minute):
     now = utime.localtime()
     midnight_ticks = utime.mktime((now[0], now[1], now[2], 0, 0, 0, 0, 0))
     new_schedule_ticks = utime.mktime((now[0], now[1], now[2], hour, minute, 0, 0, 0))
     new_schedule_ticks_past_midnight = new_schedule_ticks - midnight_ticks
     self.schedule[new_schedule_ticks_past_midnight] = ScheduleItem(r, g, b, w, new_schedule_ticks_past_midnight)
     self.save_scheduler_config()
     self.dirty = True
Ejemplo n.º 10
0
 def delete_schedule_item(self, hour, minute):
     now = utime.localtime()
     midnight_ticks = utime.mktime((now[0], now[1], now[2], 0, 0, 0, 0, 0))
     new_schedule_ticks = utime.mktime((now[0], now[1], now[2], hour, minute, 0, 0, 0))
     new_schedule_ticks_past_midnight = new_schedule_ticks - midnight_ticks
     del self.schedule[new_schedule_ticks_past_midnight]
     self.save_scheduler_config()
     self.dirty = True
def calc_days_until_christmas(year, month, day, hour):
    day -= (1 if hour < 8 else 0) # convert UTC -> PST
    today = utime.mktime([year, month, day, 0, 0, 0, 0, 0])
    if month == 12 and day > 25:
        year += 1
    christmas = utime.mktime([year, 12, 25, 0, 0, 0, 0, 0])
    days_until_christmas = (christmas - today) // (60*60*24)
    return days_until_christmas
Ejemplo n.º 12
0
def time_as_utime(offset=0):
    '''
    Returns the number of seconds since UTC epoch adjusted to the 
    calendar timezone.
    '''

    t = utime.mktime(utime.localtime())  # Seconds since UTC Epoch
    t += int(offset * 3600)  # 3600 = 1 hr in seconds
    # Convert it back to epoch for roll over
    return utime.mktime(utime.localtime(t))
Ejemplo n.º 13
0
 def is_fixed(self, eps=5*60):
     """
     Check if position is fixed ()
     """
     if self._lastfixon is None:
         return False
     else:
         tnow = utime.mktime(self._to_utime(self._RTC.now()))
         tlf = utime.mktime(self._to_utime(self._lastfixon))
         return abs(tnow - tlf) < eps
Ejemplo n.º 14
0
def nvs_write():
	while True:
		time.sleep(1)
		print('Write.....')
		p = int(pycom.nvs_get('p'))
		pycom.nvs_set('t'+str(p), utime.mktime(utime.gmtime()))
		pycom.nvs_set('d'+str(p), utime.mktime(utime.gmtime()))
		p = p + 1
		pycom.nvs_set('p', p)
		print(pycom.nvs_get('p'))
Ejemplo n.º 15
0
 def rtc_test(self, runtime=600, ppm=False):
     factor = 1000000 if ppm else 31557600
     self.await_transition()
     rtc_start = utime.ticks_ms()
     ds3231_start = utime.mktime(self.convert())
     utime.sleep(runtime)
     self.await_transition()
     d_rtc = utime.ticks_diff(utime.ticks_ms(), rtc_start)
     d_ds3231 = 1000 * (utime.mktime(self.convert()) - ds3231_start)
     return (d_ds3231 - d_rtc) * factor / d_ds3231
Ejemplo n.º 16
0
 def rtc_test(self, runtime=600, ppm=False):
     factor = 1000000 if ppm else 31557600  # seconds per year
     self.await_transition()  # Start on transition
     rtc_start = utime.ticks_ms()  # and get RTC time NOW
     ds3231_start = utime.mktime(self.convert())
     utime.sleep(runtime)  # Wait a while (precision doesn't matter)
     self.await_transition()
     d_rtc = utime.ticks_diff(utime.ticks_ms(), rtc_start)
     d_ds3231 = 1000 * (utime.mktime(self.convert()) - ds3231_start)
     return (d_ds3231 - d_rtc) * factor / d_ds3231
Ejemplo n.º 17
0
async def main():
    MQTTClient.DEBUG = False
    try:
        await client.connect()
    except OSError as ex:
        print(
            "Error %s. Perhaps mqtt username or password is wrong or missing or broker down?"
            % ex)
        raise
    asyncio.create_task(mqtt_up_loop())
    asyncio.create_task(show_what_i_do())
    #  Initialize distance reading loops
    asyncio.create_task(inside_distance.measure_distance_cm_loop())
    asyncio.create_task(outside_distance.measure_distance_cm_loop())
    # Curtain shall be down when operation is started, but if limiter switch is 1, then we
    # have to first release some wire to lower the curtain.
    if limiter_switch.value() == 1:
        await pulley_motor.release_x_rotations(
            5833)  # about 35 cm with 1:4 gear ratio
    #  Rotate pulley until limiter switch is 1 - wait time max 60 seconds
    await pulley_motor.wind_to_toplimiter()
    # if pulley_motor.curtain_steps = 0, then operation failed to find top position
    if pulley_motor.curtain_steps == 0:
        print("Check limiter switch!")
        await error_reporting("Check limiter switch!")
        utime.sleep(30)
        raise
    # more wire
    # await pulley_motor.release_x_rotations(1000)
    # less wire
    # await pulley_motor.wind_x_rotations(1000)

    while True:
        if outdoor_open is True:
            if inside_distance.distancecm is not None:
                if (inside_distance.distancecm <= INSIDE_DISTANCE_CM) and (pulley_motor.curtain_up is False) and \
                        (pulley_motor.curtain_rolling == 0):
                    await pulley_motor.wind_to_toplimiter()
                elif (inside_distance.distancecm > INSIDE_DISTANCE_CM) and (pulley_motor.curtain_up is True) and \
                        (pulley_motor.curtain_rolling == 0) and \
                        ((utime.mktime(utime.localtime()) - utime.mktime(pulley_motor.curtain_up_time)) >
                         KEEP_CURTAIN_UP_DELAY):
                    await pulley_motor.roll_curtain_down()
            if outside_distance.distancecm is not None:
                if (outside_distance.distancecm <= OUTSIDE_DISTANCE_CM) and (pulley_motor.curtain_up is False) and \
                        (pulley_motor.curtain_rolling == 0):
                    await pulley_motor.wind_to_toplimiter()
                elif (outside_distance.distancecm > OUTSIDE_DISTANCE_CM) and (pulley_motor.curtain_up is True) and \
                     (pulley_motor.curtain_rolling == 0) and \
                        ((utime.mktime(utime.localtime()) - utime.mktime(pulley_motor.curtain_up_time)) >
                         KEEP_CURTAIN_UP_DELAY):
                    await pulley_motor.roll_curtain_down()
        elif (outdoor_open is False) and (pulley_motor.curtain_up is True):
            await pulley_motor.roll_curtain_down()
        await asyncio.sleep(1)
Ejemplo n.º 18
0
 def current_day(self):
     if self._schedule and self._schedule.get('items') and self._schedule.get('start'):
         day_no = 0
         start = utime.mktime(self._schedule['start'])
         today = utime.mktime(machine.RTC().datetime())
         if start < today:
             day_no = int((today-start)/86400)
         if day_no >= len(self._schedule['items']):
             day_no = len(self._schedule['items']) - 1
         return self._schedule['items'][day_no]
     else:
         return None
Ejemplo n.º 19
0
def get_sun_times(coords):

    sun = Sun()
    date = sun.getCurrentUTC()[::-1]
    res = sun.getSunriseTime(coords)
    print('Sunrise: ',res)
    sunrise = utime.mktime(date+[int(res['hr']), int(res['min'])]+[0,0,0])
    res = sun.getSunsetTime(coords)
    print('Sunset:', res)
    sunset = utime.mktime(date+[int(res['hr']), int(res['min'])]+[0,0,0])

    return (sunrise,sunset)
Ejemplo n.º 20
0
 def _set_RTC(self, data, eps=20):
     """
     Set Real Time Clock based on G*RMC sentence
     """
     # Date vector:
     vec = list(data['date']) + list(data['time'])
     # Time arithmetic:
     tnow = utime.mktime(L76GNSS._to_utime(vec))
     trtc = utime.mktime(L76GNSS._to_utime(self._RTC.now()))
     dt = tnow - trtc
     if abs(dt) > eps:
         self._RTC.init(vec)
         print("DEVICE [RTC]: Time set to {}, dt = {} [s]".format(self._RTC.now(), dt))  
Ejemplo n.º 21
0
    def getcal(self, minutes=5, cal=0, verbose=True):
        if d_series:
            return self._getcal_d(minutes, cal, verbose)
        verbose and print(
            'Pyboard 1.x. Waiting {} minutes for calibration factor.'.format(
                minutes))
        rtc.calibration(cal)  # Clear existing cal
        self.save_time()  # Set DS3231 from RTC
        self.await_transition(
        )  # Wait for DS3231 to change: on a 1 second boundary
        tus = utime.ticks_us()
        st = rtc.datetime()[7]
        while rtc.datetime()[7] == st:  # Wait for RTC to change
            pass
        t1 = utime.ticks_diff(
            utime.ticks_us(),
            tus)  # t1 is duration (μs) between DS and RTC change (start)
        rtcstart = get_ms(rtc.datetime())  # RTC start time in mS
        dsstart = utime.mktime(self.convert(
        ))  # DS start time in secs as recorded by await_transition

        utime.sleep(minutes * 60)

        self.await_transition()  # DS second boundary
        tus = utime.ticks_us()
        st = rtc.datetime()[7]
        while rtc.datetime()[7] == st:
            pass
        t2 = utime.ticks_diff(
            utime.ticks_us(),
            tus)  # t2 is duration (μs) between DS and RTC change (end)
        rtcend = get_ms(rtc.datetime())
        dsend = utime.mktime(self.convert())
        dsdelta = (
            dsend - dsstart
        ) * 1000000  # Duration (μs) between DS edges as measured by DS3231
        if rtcend < rtcstart:  # It's run past midnight. Assumption: run time < 1 day!
            rtcend += 24 * 3_600_000
        rtcdelta = (
            rtcend - rtcstart
        ) * 1000 + t1 - t2  # Duration (μs) between DS edges as measured by RTC and corrected
        ppm = (1000000 * (rtcdelta - dsdelta)) / dsdelta
        if cal:
            verbose and print('Error {:4.1f}ppm {:4.1f}mins/year.'.format(
                ppm, ppm * 1.903))
            return 0
        cal = int(-ppm / 0.954)
        verbose and print(
            'Error {:4.1f}ppm {:4.1f}mins/year. Cal factor {}'.format(
                ppm, ppm * 1.903, cal))
        return cal
Ejemplo n.º 22
0
def resolve_dst_and_set_time():
    global TIMEZONE_DIFFERENCE
    global dst_on
    dst_on = 1
    TIMEZONE_DIFFERENCE = 1
    print(' resolve_dst_and_set_time()..... ')
    
    # This is most stupid thing what humans can do!
    # Rules for Finland: DST ON: March last Sunday at 03:00 + 1h, DST OFF: October last Sunday at 04:00 - 1h
    # Sets localtime to DST localtime
    '''
    if network.WLAN(network.STA_IF).config('essid') == '':
        now = mktime(localtime())
        if DEBUG_ENABLED == 1:
            print("Network down! Can not set time from NTP!")
    else:
        now = ntptime.time()
    '''
    now = ntptime.time()
    #(year, month, mdate, hour, minute, second, wday, yday) = utime.localtime(now)
    
    year = utime.localtime(now)[0]  
    if year < 2020:
        if DEBUG_ENABLED == 1:
            print("Time not set correctly!")
        return False

    dstend = utime.mktime((year, 10, (31 - (int(5 * year / 4 + 1)) % 7), 4, 0, 0, 0, 6, 0))
    dstbegin = utime.mktime((year, 3, (31 - (int(5 * year / 4 + 4)) % 7), 3, 0, 0, 0, 6, 0))

    if TIMEZONE_DIFFERENCE >= 0:
        if (now > dstbegin) and (now < dstend):
            dst_on = True
            ntptime.NTP_DELTA = 3155673600 - ((TIMEZONE_DIFFERENCE + 1) * 3600)
        else:
            dst_on = False
            ntptime.NTP_DELTA = 3155673600 - (TIMEZONE_DIFFERENCE * 3600)
    else:
        if (now > dstend) and (now < dstbegin):
            dst_on = False
            ntptime.NTP_DELTA = 3155673600 - (TIMEZONE_DIFFERENCE * 3600)
        else:
            dst_on = True
            ntptime.NTP_DELTA = 3155673600 - ((TIMEZONE_DIFFERENCE + 1) * 3600)
    if dst_on is None:
        if DEBUG_ENABLED == 1:
            print("DST calculation failed!")
            return False
    else:
        ntptime.settime()  
Ejemplo n.º 23
0
def cettime():
    year = utime.localtime()[0]  #get current year
    HHMarch = utime.mktime((year, 3, (31 - (int(5 * year / 4 + 4)) % 7), 1, 0,
                            0, 0, 0, 0))  #Time of March change to CEST
    HHOctober = utime.mktime((year, 10, (31 - (int(5 * year / 4 + 1)) % 7), 1,
                              0, 0, 0, 0, 0))  #Time of October change to CET
    now = utime.time()
    if now < HHMarch:  # we are before last sunday of march
        cet = utime.localtime(now + 3600)  # CET:  UTC+1H
    elif now < HHOctober:  # we are before last sunday of october
        cet = utime.localtime(now + 7200)  # CEST: UTC+2H
    else:  # we are after last sunday of october
        cet = utime.localtime(now + 3600)  # CET:  UTC+1H
    return (cet)
Ejemplo n.º 24
0
def read_key_unpressed():
    start_time = utime.mktime(utime.localtime())
    key = ""
    test = "Anything"

    while (test != "" or key == ""):
        if utime.mktime(utime.localtime()) - start_time > 1:
            return "?"

        test = read_key()
        if not test == "":
            key = test

    return key
Ejemplo n.º 25
0
def days_til_date(oled, target_year, target_mon, target_day):
    #rtc = RTC()
    utc_time = utime.time()
    utc_time = utc_time - (5 * 60 * 60)
    (year, mon, day, hour, minute, sec, dayno, a) = utime.localtime(utc_time)
    dtString = str(year) + ' ' + str(mon) + ' ' + str(day) + ' ' + str(
        hour) + ' ' + str(minute)
    oled.text('                    ', 0, 0)
    oled.text(dtString, 0, 0)
    #print( dtString )

    future_time = utime.mktime(
        (target_year, target_mon, target_day, 0, 0, 0, 0, 0))
    today = utime.mktime((year, mon, day, hour, minute, sec, dayno, a))
    return int((future_time - today) / (24 * 60 * 60))
Ejemplo n.º 26
0
    def _set_clock(self):
        """Sets up the instrument RTC.

        mm ss DD hh YY MM (3 words of 2 bytes each)
        """
        start = utime.time()
        while True:
            if self._timeout(start):
                utils.log_file("{} => unable to sync clock".format(
                    self.__qualname__))  # DEBUG
                return False
            if self._break():
                now = utime.localtime()
                tx = "{:02d}{:02d}{:02d}{:02d}{:02d}{:02d}".format(
                    now[4], now[5], now[2], now[3], int(str(now[0])[2:]),
                    now[1])
                self.uart.write("SC")
                self.uart.write(ubinascii.unhexlify(tx))
                utils.verbose("=> SC" + str(tx), constants.VERBOSE)
                if self._ack(self._get_reply()):
                    utils.log_file(
                        "{} => clock synced (dev: {} board: {})".format(
                            self.__qualname__, self._get_clock(),
                            utils.time_string(utime.mktime(now))))  # DEBUG
                    return True
Ejemplo n.º 27
0
 def get_localtime(raw=False):
     import utime
     localtime = utime.localtime()
     if raw:
         return utime.mktime(localtime)
     else:
         return DateTimeCmd.datetime_str(localtime)
Ejemplo n.º 28
0
def uptime():
  ntptime.settime()
  rtc = machine.RTC()
  utc_shift = -3
  tm = utime.localtime(utime.mktime(utime.localtime()) + utc_shift*3600)
  tm = tm[0:3] + (0,) + tm[3:6] + (0,)
  rtc.datetime(tm)
Ejemplo n.º 29
0
def sync_time():        #пробуем синхронизировать время
    try:
        ntptime.settime()
        #oled.fill(0)
        #oled.show()
        #oled.text('sync is succesful', 0, 10)
        #oled.show()
        time.sleep(1)
    except Exception as ex:
        #oled.fill(0)
        #oled.show()
        #oled.text('something went wrong', 0, 10)
        #oled.show()
        time.sleep(15)
    else:
        #oled.fill(0)
        #oled.text('OK', 0, 10)
        oled.show()
        time.sleep(1)
    finally:
        #oled.fill(0)
        #oled.text('OK!', 0, 10)
        oled.show()
        time.sleep(1)
    
    tm = utime.localtime(utime.mktime(utime.localtime()) + utc_shift*3600)
    tm = tm[0:3] + (0,) + tm[3:6] + (0,)
    rtc.datetime(tm)
Ejemplo n.º 30
0
 def convert(
         self,
         set_rtc=False):  # Return a tuple in localtime() format (less yday)
     data = self.timebuf
     ss = bcd2dec(data[0])
     mm = bcd2dec(data[1])
     if data[2] & 0x40:
         hh = bcd2dec(data[2] & 0x1f)
         if data[2] & 0x20:
             hh += 12
     else:
         hh = bcd2dec(data[2])
     wday = data[3]
     DD = bcd2dec(data[4])
     MM = bcd2dec(data[5] & 0x1f)
     YY = bcd2dec(data[6])
     if data[5] & 0x80:
         YY += 2000
     else:
         YY += 1900
     # Time from DS3231 in time.localtime() format (less yday)
     result = YY, MM, DD, hh, mm, ss, wday - 1, 0
     if set_rtc:
         if rtc is None:
             # Best we can do is to set local time
             secs = utime.mktime(result)
             utime.localtime(secs)
         else:
             if sys.platform == 'pyboard':
                 rtc.datetime((YY, MM, DD, wday, hh, mm, ss, 0))
             else:
                 rtc.init((YY, MM, DD, hh, mm, ss))
     return result
Ejemplo n.º 31
0
 def convert(self, set_rtc=False):
     data = self.timebuf
     ss = bcd2dec(data[0])
     mm = bcd2dec(data[1])
     if data[2] & 0x40:
         hh = bcd2dec(data[2] & 0x1f)
         if data[2] & 0x20:
             hh += 12
     else:
         hh = bcd2dec(data[2])
     wday = data[3]
     DD = bcd2dec(data[4])
     MM = bcd2dec(data[5] & 0x1f)
     YY = bcd2dec(data[6])
     if data[5] & 0x80:
         YY += 2000
     else:
         YY += 1900
     result = YY, MM, DD, hh, mm, ss, wday - 1, 0
     if set_rtc:
         if rtc is None:
             secs = utime.mktime(result)
             utime.localtime(secs)
         else:
             rtc.datetime((YY, MM, DD, wday, hh, mm, ss, 0))
     return result
Ejemplo n.º 32
0
 def getcal(self, minutes=5):
     rtc.calibration(0)                      # Clear existing cal
     self.save_time()                        # Set DS3231 from RTC
     self.await_transition()                 # Wait for DS3231 to change: on a 1 second boundary
     tus = pyb.micros()
     st = rtc.datetime()[7]
     while rtc.datetime()[7] == st:          # Wait for RTC to change
         pass
     t1 = pyb.elapsed_micros(tus)            # t1 is duration (uS) between DS and RTC change (start)
     rtcstart = nownr()                      # RTC start time in mS
     dsstart = utime.mktime(self.get_time()) # DS start time in secs
     pyb.delay(minutes * 60000)
     self.await_transition()                 # DS second boundary
     tus = pyb.micros()
     st = rtc.datetime()[7]
     while rtc.datetime()[7] == st:
         pass
     t2 = pyb.elapsed_micros(tus)            # t2 is duration (uS) between DS and RTC change (end)
     rtcend = nownr()
     dsend = utime.mktime(self.get_time())
     dsdelta = (dsend - dsstart) * 1000000   # Duration (uS) between DS edges as measured by DS3231
     rtcdelta = (rtcend - rtcstart) * 1000 + t1 -t2 # Duration (uS) between DS edges as measured by RTC and corrected
     ppm = (1000000* (rtcdelta - dsdelta))/dsdelta
     return int(-ppm/0.954)
Ejemplo n.º 33
0
 def secs_since_midnight(localtime) :
     secs = utime.mktime(localtime)
     return secs - Scheduler.midnight_epoch_secs(localtime)
Ejemplo n.º 34
0
 def midnight_epoch_secs(localtime) :
     (year, month, mday, hour, minute, second, wday, yday) = localtime
     return utime.mktime((year, month, mday, 0, 0, 0, wday, yday))
Ejemplo n.º 35
0
def date(secs=False):
    localtime = utime.localtime()
    if secs:
        print(utime.mktime(localtime))
    else:
        print(core.util.localtime_to_string(localtime))
Ejemplo n.º 36
0
 def delta(self):                            # Return no. of mS RTC leads DS3231
     self.await_transition()
     rtc_ms = now()
     t_ds3231 = utime.mktime(self.get_time())  # To second precision, still in same sec as transition
     return rtc_ms - 1000 * t_ds3231