コード例 #1
0
ファイル: radio_helpers.py プロジェクト: maholli/PyGS
    def synctime(self, pool):
        try:
            requests = adafruit_requests.Session(pool)
            TIME_API = "http://worldtimeapi.org/api/ip"
            the_rtc = rtc.RTC()
            response = None
            while True:
                try:
                    print("Fetching time")
                    # print("Fetching json from", TIME_API)
                    response = requests.get(TIME_API)
                    break
                except (ValueError, RuntimeError) as e:
                    print("Failed to get data, retrying\n", e)
                    continue

            json1 = response.json()
            # print(json1)
            current_time = json1['datetime']
            the_date, the_time = current_time.split('T')
            year, month, mday = [int(x) for x in the_date.split('-')]
            the_time = the_time.split('.')[0]
            hours, minutes, seconds = [int(x) for x in the_time.split(':')]

            # We can also fill in these extra nice things
            year_day = json1['day_of_year']
            week_day = json1['day_of_week']
            is_dst = json1['dst']

            now = time.struct_time((year, month, mday, hours, minutes, seconds,
                                    week_day, year_day, is_dst))
            the_rtc.datetime = now
        except Exception as e:
            print('[WARNING]', e)
コード例 #2
0
def set_local_time():
    api_url = None
    aio_username = secrets['aio_username']
    aio_key = secrets['aio_key']
    location = secrets['timezone']
    print("Getting time for timezone", location)
    api_url = (TIME_SERVICE + "&tz=%s") % (aio_username, aio_key, location)
    api_url += TIME_SERVICE_STRFTIME
    response = requests.get(api_url)
    #print("Time request: ", api_url)
    print("Time reply: ", response.text)
    times = response.text.split(' ')
    the_date = times[0]
    the_time = times[1]
    year_day = int(times[2])
    week_day = int(times[3])
    is_dst = None  # no way to know yet
    year, month, mday = [int(x) for x in the_date.split('-')]
    the_time = the_time.split('.')[0]
    hours, minutes, seconds = [int(x) for x in the_time.split(':')]
    now = time.struct_time((year, month, mday, hours, minutes, seconds, week_day, year_day,
                            is_dst))
    rtc.RTC().datetime = now
    # now clean up
    response.close()
    response = None
    gc.collect()
コード例 #3
0
    def get_local_time(self, location=None):
        # pylint: disable=line-too-long
        """Fetch and "set" the local time of this microcontroller to the local time at the location, using an internet time API.

        :param str location: Your city and country, e.g. ``"New York, US"``.

        """
        # pylint: enable=line-too-long
        self.connect()
        api_url = None
        try:
            aio_username = secrets["aio_username"]
            aio_key = secrets["aio_key"]
        except KeyError:
            raise KeyError(
                "\n\nOur time service requires a login/password to rate-limit. Please register for a free adafruit.io account and place the user/key in your secrets file under 'aio_username' and 'aio_key'"  # pylint: disable=line-too-long
            ) from KeyError

        if location is None:
            location = secrets.get("timezone")
        if location:
            print("Getting time for timezone", location)
            api_url = (TIME_SERVICE + "&tz=%s") % (aio_username, aio_key, location)
        else:  # we'll try to figure it out from the IP address
            print("Getting time from IP address")
            api_url = TIME_SERVICE % (aio_username, aio_key)
        api_url += TIME_SERVICE_STRFTIME
        try:
            response = requests.get(api_url, timeout=10)
            if response.status_code != 200:
                error_message = (
                    "Error connection to Adafruit IO. The response was: "
                    + response.text
                )
                raise ValueError(error_message)
            if self._debug:
                print("Time request: ", api_url)
                print("Time reply: ", response.text)
            times = response.text.split(" ")
            the_date = times[0]
            the_time = times[1]
            year_day = int(times[2])
            week_day = int(times[3])
            is_dst = None  # no way to know yet
        except KeyError:
            raise KeyError(
                "Was unable to lookup the time, try setting secrets['timezone'] according to http://worldtimeapi.org/timezones"  # pylint: disable=line-too-long
            ) from KeyError
        year, month, mday = [int(x) for x in the_date.split("-")]
        the_time = the_time.split(".")[0]
        hours, minutes, seconds = [int(x) for x in the_time.split(":")]
        now = time.struct_time(
            (year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst)
        )
        rtc.RTC().datetime = now

        # now clean up
        response.close()
        response = None
        gc.collect()
コード例 #4
0
ファイル: events.py プロジェクト: nnja/py27_countdown
def update_local_time_from_internet(pyportal, timezone="Etc/UTC", debug=False):
    """
    Fetches the local time from the internet, and sets it on the PyPortal.

    Make sure you get the local time at the timezone you want, since
    the location set in your secrets file can override this value.

    Set debug to skip fetching time from the internet. Useful for
    faster startup time while reloading code.

    TODO NZ: Figure out why timezone doesn't match https://pythonclock.org/
    TODO NZ: The pyportal library clobbers all exceptions, and sleeps.
        Rewrite for better error handling.

    Args:
        pyportal (adafruit_pyportal.PyPortal): PyPortal instance.
        timezone (str, optional): Timezone to fetch time from.
            Overwritten by value in secrets.py. Defaults to "Etc/UTC".
        debug (bool, optional): Use the rtc clock time if set.
            Defaults to False.

    Returns:
        float: Monotonic timestamp of the current time.
    """
    is_rtc_clock_set = rtc.RTC().datetime.tm_year != 2000
    if debug and is_rtc_clock_set:
        print("Debug mode. Using cached localtime.")
    else:
        print("Trying to update local time from internet.")
        pyportal.get_local_time(location=timezone)

    time_now = time.monotonic()
    print("Time last refreshed at", time_now)
    return time_now
コード例 #5
0
    def get_local_time(self, location=None):
        # pylint: disable=line-too-long
        """
        Fetch and "set" the local time of this microcontroller to the local time at the location, using an internet time API.

        :param str location: Your city and country, e.g. ``"America/New_York"``.

        """
        reply = self.get_strftime(TIME_SERVICE_FORMAT, location=location)
        if reply:
            times = reply.split(" ")
            the_date = times[0]
            the_time = times[1]
            year_day = int(times[2])
            week_day = int(times[3])
            is_dst = None  # no way to know yet
            year, month, mday = [int(x) for x in the_date.split("-")]
            the_time = the_time.split(".")[0]
            hours, minutes, seconds = [int(x) for x in the_time.split(":")]
            now = time.struct_time((year, month, mday, hours, minutes, seconds,
                                    week_day, year_day, is_dst))

            if rtc is not None:
                rtc.RTC().datetime = now

        return reply
コード例 #6
0
    def _initialize_io(self):
        aio_username = self._secrets["aio_username"]
        aio_key = self._secrets["aio_key"]

        # Create an instance of the Adafruit IO HTTP client
        self.io = IO_HTTP(aio_username, aio_key, self.wifi)
        clock = rtc.RTC()
        clock.datetime = self.io.receive_time()
        self._initialize_feeds()
コード例 #7
0
 def set_time(self):
     """Fetches and sets the microcontroller's current time
     in seconds since since Jan 1, 1970.
     """
     try:
         now = self._esp.get_time()
         now = time.localtime(now[0])
         rtc.RTC().datetime = now
         self.valid_time = True
     except ValueError:
         return
コード例 #8
0
ファイル: main.py プロジェクト: bablokb/pyportal-wttrin
def set_time(con,tz):
  while True:
    try:
      response = con.get("http://worldtimeapi.org/api/timezone/"+tz)
      tinfo    = response.json()
      print(tinfo['datetime'])
      rtc.RTC().datetime = time.localtime(tinfo['unixtime']+tinfo['raw_offset'])
      response.close()
      return
    except Exception as ex:
      print("exception in set_time:")
      print(ex)
コード例 #9
0
ファイル: glitterpos.py プロジェクト: adafruit/glitterpos
    def advance_frame(self):
        """
        Check the radio for new packets, poll GPS and compass data, send a
        radio packet if coordinates have changed (or if it's been a while), and
        update NeoPixel display.  Called in an infinite loop by code.py.

        To inspect the state of the system, initialize a new GlitterPOS object
        from the CircuitPython REPL, and call gp.advance_frame() manually.  You
        can then access the instance variables defined in __init__() and
        init_()* methods.
        """

        current = time.monotonic()
        self.radio_rx(timeout=0.5)
        new_gps_data = self.gps.update()
        self.update_heading()
        self.display_pixels()

        if not self.gps.has_fix:
            # Try again if we don't have a fix yet.
            self.statuslight.fill(RED)
            return

        # We want to send coordinates out either on new GPS data or roughly
        # every 15 seconds:
        if (not new_gps_data) and (current - self.last_send < 15):
            return

        # Set the RTC to GPS time (UTC):
        if new_gps_data and not self.time_set:
            rtc.RTC().datetime = self.gps.timestamp_utc
            self.time_set = True

        gps_coords = (self.gps.latitude, self.gps.longitude)
        if gps_coords == self.coords:
            return

        self.coords = (self.gps.latitude, self.gps.longitude)

        self.statuslight.fill(BLUE)
        print(':: ' + str(current))  # Print a separator line.
        print(timestamp())
        send_packet = '{}:{}:{}:{}'.format(self.gps.latitude,
                                           self.gps.longitude,
                                           self.gps.speed_knots, self.heading)

        print('   quality: {}'.format(self.gps.fix_quality))
        print('   ' + str(gc.mem_free()) + " bytes free")

        # Send a location packet:
        self.radio_tx('l', send_packet)
コード例 #10
0
    def refresh_local_time(self):
        # pylint: disable=line-too-long
        """Fetch and "set" the local time of this microcontroller to the local time at the location, using an internet time API.
        Copied from adafruit_pyportal
        :param str location: Your city and country, e.g. ``"New York, US"``.
        """
        # pylint: enable=line-too-long
        api_url = None
        try:
            aio_username = secrets['aio_username']
            aio_key = secrets['aio_key']
        except KeyError:
            raise KeyError("\n\nOur time service requires a login/password to rate-limit. Please register for a free adafruit.io account and place the user/key in your secrets file under 'aio_username' and 'aio_key'")  # pylint: disable=line-too-long

        location = secrets['timezone']
        if location:
            logger.debug('Getting time for timezone %s', location)
            api_url = (TIME_SERVICE + "&tz=%s") % (aio_username, aio_key,
                                                   location)
        else:  # we'll try to figure it out from the IP address
            logger.debug("Getting time from IP address")
            api_url = TIME_SERVICE % (aio_username, aio_key)
        api_url += TIME_SERVICE_STRFTIME
        logger.debug('Requesting time from %s', api_url)
        try:
            self.connect()
            response = requests.get(api_url)
            logger.debug('Time reply: %s', response.text)
            times = response.text.split(' ')
            the_date = times[0]
            the_time = times[1]
            year_day = int(times[2])
            week_day = int(times[3])
            is_dst = None  # no way to know yet
        except KeyError:
            raise KeyError("Was unable to lookup the time, try setting secrets['timezone'] according to http://worldtimeapi.org/timezones")  # pylint: disable=line-too-long
        year, month, mday = [int(x) for x in the_date.split('-')]
        the_time = the_time.split('.')[0]
        hours, minutes, seconds = [int(x) for x in the_time.split(':')]
        now = time.struct_time((year, month, mday, hours, minutes, seconds,
                                week_day, year_day, is_dst))
        rtc.RTC().datetime = now
        logger.debug('Fetched time: %s', str(now))

        # now clean up
        response.close()
        response = None
        gc.collect()
        return now
コード例 #11
0
    def set_time(self, tz_offset=0):
        """Fetches and sets the microcontroller's current time
        in seconds since since Jan 1, 1970.

        :param int tz_offset: Timezone offset from GMT
        """
        try:
            now = self._esp.get_time()
            now = time.localtime(now[0] +
                                 (tz_offset * 3600))  # 3600 seconds in an hour
            rtc.RTC().datetime = now
            self.valid_time = True
        except ValueError as error:
            print(str(error))
            return
コード例 #12
0
def ds1307slave_func():
    import board
    import time
    import ds1307slave
    import rtc
    from i2cslave import I2CSlave

    # Adapted from CPython
    class BytesIO:
        def __init__(self, initial_bytes):
            self._buffer = initial_bytes
            self._pos = 0

        def read(self, size):
            if len(self._buffer) <= self._pos:
                return b''
            newpos = min(len(self._buffer), self._pos + size)
            b = self._buffer[self._pos:newpos]
            self._pos = newpos
            return bytes(b)

        def write(self, b):
            n = len(b)
            pos = self._pos
            if n == 0 or pos + n > len(self._buffer):
                return 0
            self._buffer[pos:pos + n] = b
            self._pos += n

        def seek(self, pos):
            self._pos = pos

    ram = BytesIO(bytearray(56))
    ds1307 = ds1307slave.DS1307Slave(rtc.RTC(), ram=ram)

    with I2CSlave(board.SCL, board.SDA, (0x68, ), smbus=False) as slave:
        while True:
            try:
                r = slave.request()
                if not r:
                    continue
                with r:
                    if r.address == 0x68:
                        ds1307.process(r)
            except OSError as e:
                print('ERROR:', e)
コード例 #13
0
 def _get_local_time(self):
     """Fetch and "set" the local time of this microcontroller to the
     local time at the location, using an internet time API.
     from Adafruit IO Arduino
     """
     api_url = None
     try:
         aio_username = self._secrets["aio_username"]
         aio_key = self._secrets["aio_key"]
     except KeyError:
         raise KeyError(
             "\n\nOur time service requires a login/password to rate-limit. Please register for a free adafruit.io account and place the user/key in your secrets file under 'aio_username' and 'aio_key'"
         )
     location = None
     location = self._secrets.get("timezone", location)
     if location:
         if self._logger:
             self._logger.debug("Getting time for timezone.")
         api_url = (TIME_SERVICE + "&tz=%s") % (aio_username, aio_key,
                                                location)
     else:  # we'll try to figure it out from the IP address
         self._logger.debug("Getting time from IP Address..")
         api_url = TIME_SERVICE % (aio_username, aio_key)
     api_url += TIME_SERVICE_STRFTIME
     try:
         response = self._wifi.get(api_url)
         times = response.text.split(" ")
         the_date = times[0]
         the_time = times[1]
         year_day = int(times[2])
         week_day = int(times[3])
         is_dst = None  # no way to know yet
     except KeyError:
         raise KeyError(
             "Was unable to lookup the time, try setting secrets['timezone'] according to http://worldtimeapi.org/timezones"
         )  # pylint: disable=line-too-long
     year, month, mday = [int(x) for x in the_date.split("-")]
     the_time = the_time.split(".")[0]
     hours, minutes, seconds = [int(x) for x in the_time.split(":")]
     now = time.struct_time((year, month, mday, hours, minutes, seconds,
                             week_day, year_day, is_dst))
     rtc.RTC().datetime = now
     # now clean up
     response.close()
     response = None
     gc.collect()
コード例 #14
0
    def set_time(self, tz_offset=0):
        """Fetches and sets the microcontroller's current time
        in seconds since since Jan 1, 1970.

        :param int tz_offset: The offset of the local timezone,
            in seconds west of UTC (negative in most of Western Europe,
            positive in the US, zero in the UK).
        """

        try:
            now = self._esp.get_time()
            now = time.localtime(now[0] + tz_offset)
            rtc.RTC().datetime = now
            self.valid_time = True
        except ValueError as error:
            print(str(error))
            return
コード例 #15
0
    def get_local_time(self, location=None):
        api_url = None
        try:
            aio_username = secrets["aio_username"]
            aio_key = secrets["aio_key"]
        except KeyError:
            raise KeyError(
                "\n\nOur time service requires a login/password to rate-limit. Please register for a free adafruit.io account and place the user/key in your secrets file under 'aio_username' and 'aio_key'"  # pylint: disable=line-too-long
            )

        location = secrets.get("timezone", location)
        if location:
            api_url = (TIME_SERVICE + "&tz=%s") % (aio_username, aio_key, location)
        else:  # we'll try to figure it out from the IP address
            api_url = TIME_SERVICE % (aio_username, aio_key)
        api_url += TIME_SERVICE_STRFTIME
        try:
            response = requests.get(api_url, timeout=10)
            if response.status_code != 200:
                raise ValueError(response.text)
            if self.debug:
                print("Time request: ", api_url)
                print("Time reply: ", response.text)
            times = response.text.split(" ")
            the_date = times[0]
            the_time = times[1]
            year_day = int(times[2])
            week_day = int(times[3])
            is_dst = None  # no way to know yet
        except KeyError:
            raise KeyError(
                "Was unable to lookup the time, try setting secrets['timezone'] according to http://worldtimeapi.org/timezones"
            )
        year, month, mday = [int(x) for x in the_date.split("-")]
        the_time = the_time.split(".")[0]
        hours, minutes, seconds = [int(x) for x in the_time.split(":")]
        now = time.struct_time(
            (year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst)
        )
        print(now)
        rtc.RTC().datetime = now

        # now clean up
        response.close()
        response = None
        gc.collect()
コード例 #16
0
def get_local_time():
    IMAGE_CONVERTER_SERVICE = "https://io.adafruit.com/api/v2/%s/integrations/image-formatter?x-aio-key=%s&width=%d&height=%d&output=BMP%d&url=%s"
    TIME_SERVICE = "https://io.adafruit.com/api/v2/%s/integrations/time/strftime?x-aio-key=%s"
    TIME_SERVICE_STRFTIME = '&fmt=%25Y-%25m-%25d+%25H%3A%25M%3A%25S.%25L+%25j+%25u+%25z+%25Z'

    api_url = None
    try:
        aio_username = secrets['aio_username']
        aio_key = secrets['aio_key']
        location = secrets['timezone']
    except KeyError:
        raise KeyError("\n\nOur time service requires a login/password to rate-limit. Please register for a free adafruit.io account and place the user/key in your secrets file under 'aio_username' and 'aio_key'")

    if location:
        print("Getting time for timezone", location)
        api_url = (TIME_SERVICE + "&tz=%s") % (aio_username, aio_key, location)
    else:
        print("Getting time from IP address")
        api_url = TIME_SERVICE % (aio_username, aio_key)
    api_url += TIME_SERVICE_STRFTIME
    print(api_url)

    try:
        response = requests.get(api_url)
        
        if esp._debug:
            print("Time request: ", api_url)
            print("Time reply: ", response.text)
        print("Time reply: ", response.text)
        times = response.text.split(' ')
        the_date = times[0]
        the_time = times[1]
        year_day = int(times[2])
        week_day = int(times[3])
        is_dst = None
    except KeyError:
        raise KeyError("Was unable to lookup the time, try setting secrets['timezone'] according to http://worldtimeapi.org/timezones")

    year, month, mday = [int(x) for x in the_date.split('-')]
    the_time = the_time.split('.')[0]
    hours, minutes, seconds = [int(x) for x in the_time.split(':')]
    now_struct = time.struct_time((year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst))
    rtc.RTC().datetime = now_struct
    response.close()
    response = None
コード例 #17
0
def _set_time(st, tolerance=5):
    import time
    host = time.mktime(st)
    local = time.time()
    if abs(host - local) < tolerance:
        return
    try:
        # CircuitPython
        import rtc
        rtc.RTC().datetime = st
    except ImportError:
        # MicroPython
        import machine
        # convert to Micropython's non-standard ordering ...
        st = list(st)
        st.insert(3, st[6])
        st[7] = 0
        machine.RTC().datetime(st[:8])
コード例 #18
0
def update_NTP():
    pixels.fill((0, 128, 255))
    pixels.show()
    seg_print(" UPDATE NTP ")
    log_info("Update from NTP")
    try:
        wifi.radio.enabled = True
        log_info("Connect Wifi")
        connect_wifi(verbose=True)
        rtc.RTC().datetime = get_ntp_time(socket_pool)
        time.sleep(0.1)
    except Exception as ex:
        print("Exception")
        print(ex)
        seg_print(" NTP FAILED ")
        time.sleep(2)
    finally:
        log_info("Turn off Wifi")
        wifi.radio.enabled = False
コード例 #19
0
def ds1307slave_func(addresses):
    import board
    import time
    import ds1307slave
    import rtc
    from i2cslave import I2CSlave

    ds1307 = ds1307slave.DS1307Slave(rtc.RTC())

    with I2CSlave(board.SCL, board.SDA, addresses, smbus=False) as slave:
        while True:
            try:
                r = slave.request(timeout=2)

                with r:
                    if r.address == 0x68:
                        ds1307.process(r)

            except OSError as e:
                print('ERROR:', e)
コード例 #20
0
    def get_local_time(self, location=None):
        # pylint: disable=line-too-long
        """Fetch and "set" the local time of this microcontroller to the local time at the location, using an internet time API.

        :param str location: Your city and country, e.g. ``"New York, US"``.

        """
        # pylint: enable=line-too-long
        self._connect_esp()
        api_url = None
        location = secrets.get('timezone', location)
        if location:
            print("Getting time for timezone", location)
            api_url = TIME_SERVICE_LOCATION + location
        else:  # we'll try to figure it out from the IP address
            print("Getting time from IP address")
            api_url = TIME_SERVICE_IPADDR

        try:
            response = requests.get(api_url)
            time_json = response.json()
            current_time = time_json['datetime']
            year_day = time_json['day_of_year']
            week_day = time_json['day_of_week']
            is_dst = time_json['dst']
        except KeyError:
            raise KeyError("Was unable to lookup the time, try setting secrets['timezone'] according to http://worldtimeapi.org/timezones")  # pylint: disable=line-too-long
        the_date, the_time = current_time.split('T')
        year, month, mday = [int(x) for x in the_date.split('-')]
        the_time = the_time.split('.')[0]
        hours, minutes, seconds = [int(x) for x in the_time.split(':')]
        now = time.struct_time((year, month, mday, hours, minutes, seconds,
                                week_day, year_day, is_dst))
        print(now)
        rtc.RTC().datetime = now

        # now clean up
        time_json = None
        response.close()
        response = None
        gc.collect()
コード例 #21
0
def _parse_localtime_message(topic, message):
    # /aio/local_time : 2021-01-15 23:07:36.339 015 5 -0500 EST
    try:
        print(f"Local time mqtt: {message}")
        times = message.split(" ")
        the_date = times[0]
        the_time = times[1]
        year_day = int(times[2])
        week_day = int(times[3])
        is_dst = None  # no way to know yet
        year, month, mday = [int(x) for x in the_date.split("-")]
        the_time = the_time.split(".")[0]
        hours, minutes, seconds = [int(x) for x in the_time.split(":")]
        now = time.struct_time(
            (year, month, mday, hours, minutes, seconds, week_day, year_day, is_dst)
        )
        rtc.RTC().datetime = now
        tss["localtime"] = time.monotonic()  # reset so no new update is needed
        _inc_counter("local_time_mqtt")
    except Exception as e:
        print(f"Error in _parse_localtime_message -", e)
        _inc_counter("local_time_mqtt_failed")
コード例 #22
0
ファイル: glitterpos.py プロジェクト: adafruit/glitterpos
    def __init__(self):
        """configure sensors, radio, blinkenlights"""

        # Our id and the dict for storing coords of other glitterpos_boxes:
        self.glitterpos_id = MY_ID
        self.glitterpos_boxes = DEFAULT_BOX_COORDS

        # Set the RTC to an obviously bogus time for debugging purposes:
        # time_struct takes: (tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec, tm_wday, tm_yday, tm_isdst)
        rtc.RTC().datetime = time.struct_time((2000, 1, 1, 0, 0, 0, 0, 0, 0))
        print("startup time: " + timestamp())
        self.time_set = False
        self.last_send = time.monotonic()

        # A tuple for our lat/long:
        self.coords = (0, 0)
        self.heading = 0.0

        # Status light on the board, we'll use to indicate GPS fix, etc.:
        self.statuslight = neopixel.NeoPixel(board.NEOPIXEL,
                                             1,
                                             brightness=0.005,
                                             auto_write=True)
        self.statuslight.fill(RED)

        # Neopixel ring:
        self.pixels = neopixel.NeoPixel(board.A1,
                                        16,
                                        brightness=0.01,
                                        auto_write=False)
        self.startup_animation()
        time.sleep(2)

        self.init_radio()
        self.init_gps()
        self.init_compass()

        self.statuslight.fill(YELLOW)
コード例 #23
0
lasttimefetch_stamp = None
while True:
    if not lasttimefetch_stamp or (time.monotonic() - lasttimefetch_stamp) > 3600:
        try:
            response = magtag.network.requests.get(DATA_SOURCE)
            datetime_str = response.json()['datetime']
            datesplit = datetime_str.split("-")
            year = int(datesplit[0])
            month = int(datesplit[1])
            timesplit = datesplit[2].split("T")
            mday = int(timesplit[0])
            timesplit = timesplit[1].split(":")
            hours = int(timesplit[0])
            minutes = int(timesplit[1])
            seconds = int(float(timesplit[2].split("-")[0]))
            rtc.RTC().datetime = time.struct_time((year, month, mday, hours, minutes, seconds, 0, 0, False))
            lasttimefetch_stamp = time.monotonic()
        except (ValueError, RuntimeError) as e:
            print("Some error occured, retrying! -", e)
            continue

    if not timestamp or (time.monotonic() - timestamp) > 60:  # once a minute
        now = time.localtime()
        print("Current time:", now)
        remaining = time.mktime(event_time) - time.mktime(now)
        print("Time remaining (s):", remaining)
        if remaining < 0:
            print("EVENT TIME")
            magtag.set_text("It's Time\nTo Party!")
            magtag.peripherals.neopixel_disable = False
            while True:  # that's all folks
コード例 #24
0
                   MAGTAG.graphics.display.height - 1),
    text_color=0xFFFFFF,
    text_anchor_point=(0.5, 1),  # Center bottom
    is_data=False,  # Text will be set manually
)

# MAIN LOOP ----------------------------------------------------------------

PRIOR_LIST = ''  # Initialize these to nonsense values
PRIOR_DAY = -1  # so the list or day change always triggers on first pass

while True:
    try:
        print('Updating time')
        MAGTAG.get_local_time()
        NOW = rtc.RTC().datetime

        print('Updating tasks')
        RESPONSE = MAGTAG.network.fetch(JSON_URL)
        if RESPONSE.status_code == 200:
            JSON_DATA = RESPONSE.json()
            print('OK')

        ENTRIES = JSON_DATA['feed']['entry']  # List of cell data

        # tm_wday uses 0-6 for Mon-Sun, we want 1-7 for Sun-Sat
        COLUMN = (NOW.tm_wday + 1) % 7 + 1

        TASK_LIST = ''  # Clear task list string
        for entry in ENTRIES:
            cell = entry['gs$cell']
コード例 #25
0
"""


print("ESP AT commands")
esp = adafruit_espatcontrol.ESP_ATcontrol(uart, 115200,
                                          reset_pin=resetpin, rts_pin=rtspin, debug=False)
wifi = adafruit_espatcontrol_wifimanager.ESPAT_WiFiManager(esp, secrets, status_light)



print("ESP32 local time")

TIME_API = "http://worldtimeapi.org/api/ip"


the_rtc = rtc.RTC()

response = None
while True:
    try:
        print("Fetching json from", TIME_API)
        response = wifi.get(TIME_API)
        break
    except (ValueError, RuntimeError,  adafruit_espatcontrol.OKError) as e:
        print("Failed to get data, retrying\n", e)
        continue

json = response.json()
current_time = json['datetime']
the_date, the_time = current_time.split('T')
year, month, mday = [int(x) for x in the_date.split('-')]
コード例 #26
0
import ssl
import wifi
import socketpool
import adafruit_requests
from adafruit_io.adafruit_io import IO_HTTP, AdafruitIO_RequestError

from digitalio import DigitalInOut, Direction, Pull
import pulseio

# OFFSETS for my panel meters so the dial starts at 0
# it takes some tweaking to get them to align just right
# you could also play with their physical orientation as well
HOUR_OFFSET = 700
MIN_OFFSET = 2200
SEC_OFFSET = 500
RTC_CLOCK = rtc.RTC()

# Get wifi details and more from a secrets.py file
try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

print("Connecting to %s" % secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
print("Connected to %s!" % secrets["ssid"])
print("My IP address is", wifi.radio.ipv4_address)

# Test and debug Connection
ipv4 = ipaddress.ip_address("8.8.4.4")
コード例 #27
0
lasttimefetch_stamp = None
while True:
    if not lasttimefetch_stamp or (time.monotonic() -
                                   lasttimefetch_stamp) > 3600:
        try:
            # America/New_York - 2020-11-15T11:14:49.970836-05:00
            # Europe/Stockholm - 2020-11-15T17:15:01.186119+01:00
            response = magtag.network.requests.get(DATA_SOURCE)
            datetime_str = response.json()['datetime']
            year = int(datetime_str[0:4])
            month = int(datetime_str[5:7])
            mday = int(datetime_str[8:10])
            hours = int(datetime_str[11:13])
            minutes = int(datetime_str[14:16])
            seconds = int(datetime_str[17:19])
            rtc.RTC().datetime = time.struct_time(
                (year, month, mday, hours, minutes, seconds, 0, 0, False))
            lasttimefetch_stamp = time.monotonic()
        except (ValueError, RuntimeError) as e:
            print("Some error occured, retrying! -", e)
            continue

    if not timestamp or (time.monotonic() - timestamp) > 60:  # once a minute
        now = time.localtime()
        print("Current time:", now)
        remaining = time.mktime(event_time) - time.mktime(now)
        print("Time remaining (s):", remaining)
        if remaining < 0:
            print("EVENT TIME")
            magtag.set_text("It's Time\nTo Party!")
            magtag.peripherals.neopixel_disable = False
コード例 #28
0
        magtag.splash.append(label_event_time)

        label_event_desc = label.Label(
            font_event,
            x=88,
            y=40 + (event_idx * 35),
            color=0x000000,
            text=event_name,
            line_spacing=0.65,
        )
        magtag.splash.append(label_event_desc)


# Create a new MagTag object
magtag = MagTag()
r = rtc.RTC()

# DisplayIO Setup
magtag.set_background(0xFFFFFF)

# Add the header
line_header = Line(0, 30, 320, 30, color=0x000000)
magtag.splash.append(line_header)

font_h1 = bitmap_font.load_font("fonts/Arial-18.pcf")
label_header = label.Label(font_h1, x=5, y=15, color=0x000000, max_glyphs=30)
magtag.splash.append(label_header)

# Set up calendar event fonts
font_event = bitmap_font.load_font("fonts/Arial-12.pcf")
コード例 #29
0

try:
    from secrets import secrets
except ImportError:
    print("WiFi secrets are kept in secrets.py, please add them there!")
    raise

print("Connecting to ", secrets["ssid"])
wifi.radio.connect(ssid=secrets["ssid"], password=secrets["password"])
socket_pool = socketpool.SocketPool(wifi.radio)
print("Connected with IP ", wifi.radio.ipv4_address)

now = get_ntp_time(socket_pool)
print(now)
rtc.RTC().datetime = now
print("Synced with NTP")
time.sleep(1.0)

display = None
if hasattr(board, "DISPLAY"):
    display = board.DISPLAY
else:
    pass
    # insert external display init

if display:
    group = displayio.Group()
    display.show(group)
    text_area = label.Label(
        terminalio.FONT,
コード例 #30
0
ファイル: net.py プロジェクト: dcsim0n/aqi-monitor
def time_set(utc_time):
    r = rtc.RTC()
    r.datetime = utc_time
    print("setting system time to:", utc_time)