Beispiel #1
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()
Beispiel #2
0
def wget(url, filename, *, chunk_size = 512):

    global statusNeopixel

    """Download a url and save to filename location, like the command wget.

    :param url: The URL from which to obtain the data.
    :param filename: The name of the file to save the data to.
    :param chunk_size: how much data to read/write at a time.

    """
    statusNeopixel.fill((100, 100, 0))
    r = requests.get(url, stream=True)

    content_length = int(r.headers['content-length'])
    remaining = content_length
    file = open(filename, "wb")

    for i in r.iter_content(min(remaining, chunk_size)):  # huge chunks!
        statusNeopixel.fill((0, 100, 100))
        remaining -= len(i)
        file.write(i)

        if not remaining:
            break

        statusNeopixel.fill((100, 100, 0))

    file.close()
    r.close()
    statusNeopixel.fill((0, 0, 0))
Beispiel #3
0
    def touch(self, t, touched):
        if t and not touched:  # only process the initial touch
            max = len(self.buttons
                      ) - 1  # only do state stuff with the first two buttons
            for button_index in range(max):
                b = self.buttons[button_index]
                if touch_in_button(t, b):
                    change_to_state(b['next_state'])
                    break
            if touch_in_button(t, self.buttons[2]):  # next button
                logger.debug('NEXT song touched')

                #TODO: Make this a call to requests.post()
                #      Docs: https://circuitpython.readthedocs.io/projects/esp32spi/en/latest/api.html#adafruit_esp32spi.adafruit_esp32spi_requests.post
                response = requests.get(
                    'http://192.168.1.82:8080/onebeartoe-jukebox-ee/controls/song/next'
                )
                #                response = requests.get('http://192.168.1.80:1978/?action=next')
                #                response = requests.get('http://192.168.1.80:8080/continuous/')
                self.text_areas[1].text = 'ploop'
                print('lalal')
                print(response)
                print('lalal')
#                logger.debug(response)
        return bool(t)
Beispiel #4
0
def updateTime(time_url):
    
    # get time info and format string
    print("\nFetching json from", time_url)
    r = requests.get(time_url)
    print('-'*40)
    print(r.json())
    print('-'*40)
    time = json.loads(r.text)
    datetime = time['datetime']
    times = datetime.split(":")
    hour = int(times[0][-2:])
    minute = int(times[1])
    r.close()
    format_str = "%d:%02d"
    if hour >= 12:
        hour = hour - 12
        format_str = format_str+" PM"
    else:
        format_str = format_str+" AM"
    if hour == 0:
        hour = 12
    time_str = format_str % (hour, minute)
    print(time_str)
    print('-'*40)
    
    # display info
    display.txt_set_cursor(530, 0)
    display.txt_trans(WHITE)
    display.txt_size(3)
    display.txt_write(time_str)
Beispiel #5
0
    def wget(self, url, filename):
        print("Fetching stream from", url)

        self.neo_status((100, 100, 0))
        r = requests.get(url, stream=True)

        if self._debug:
            print(r.headers)
        content_length = int(r.headers['content-length'])
        remaining = content_length
        print("Saving data to ", filename)
        stamp = time.monotonic()
        with open(filename, "wb") as f:
            for i in r.iter_content(min(remaining, 12000)):  # huge chunks!
                self.neo_status((0, 100, 100))
                remaining -= len(i)
                f.write(i)
                if self._debug:
                    print("Read %d bytes, %d remaining" %
                          (content_length - remaining, remaining))
                else:
                    print(".", end='')
                if not remaining:
                    break
                self.neo_status((100, 100, 0))

        r.close()
        stamp = time.monotonic() - stamp
        print("Created file of %d bytes in %0.1f seconds" %
              (os.stat(filename)[6], stamp))
        self.neo_status((0, 0, 0))
Beispiel #6
0
 def mfetch(self, url, headers):
     self._connect_esp()
     print("Retrieving data...", end='')
     self.neo_status((100, 100, 0))  # yellow = fetching data
     gc.collect()
     r = requests.get(url, headers=headers)
     gc.collect()
     self.neo_status((0, 0, 100))  # green = got data
     print(r.content)
     return r.json()
Beispiel #7
0
def showYoutubeStats(channelId):

    global rootDirectory
    global statusNeopixel
    global setBackground
    global jsonTraverse
    global board
    global collegiateFont
    global primaryDisplayGroup

    url = "https://www.googleapis.com/youtube/v3/channels/?part=statistics&id=" + channelId + "&key=" + secrets['youtube_token']
    countJsonPropPath = ["items", 0, "statistics", "viewCount"]
    count2JsonPropPath = ["items", 0, "statistics", "subscriberCount"]

    # get data from url
    statusNeopixel.fill((100, 100, 0))   # yellow = fetching data
    gc.collect()
    r = requests.get(url)
    gc.collect()
    statusNeopixel.fill((0, 0, 100))   # green = got data
    jsonData = r.json()
    r.close()
    gc.collect()

    count = jsonTraverse(jsonData, countJsonPropPath)
    count2 = jsonTraverse(jsonData, count2JsonPropPath)

    # display data
    countLabel = Label(collegiateFont, text=str(count))
    countLabel.x = 100
    countLabel.y = 129
    countLabel.color = 0xFFFFFF

    countLabel2 = Label(collegiateFont, text=str(count))
    countLabel2.x = 155
    countLabel2.y = 180
    countLabel2.color = 0xFFFFFF

    primaryDisplayGroup.append(countLabel)
    primaryDisplayGroup.append(countLabel2)

    # load github stat background
    setBackground(rootDirectory + "/youtube_background.bmp")

    # wait
    time.sleep(60)

    # cleanup!
    while countLabel:
        countLabel.pop()

    while countLabel2:
        countLabel.pop()
Beispiel #8
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
        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:
            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)
            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
        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()
 def curl(self, URL):
     if URL:
         self._connect_esp()
         # great, lets get the data
         print("Retrieving data from URL...", URL)
         self.neo_status((100, 100, 0))  # yellow = fetching data
         gc.collect()
         r = requests.get(URL, headers=self._headers)
         gc.collect()
         self.neo_status((0, 0, 100))  # green = got data
         print("Reply is OK!")
         values = r.text
         r = None
         gc.collect()
         return values
     else:
         return None
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
    def get(self, url, **kw):
        """
        Pass the Get request to requests and update status LED

        :param str url: The URL to retrieve data from
        :param dict data: (Optional) Form data to submit
        :param dict json: (Optional) JSON data to submit. (Data must be None)
        :param dict header: (Optional) Header data to include
        :param bool stream: (Optional) Whether to stream the Response
        :return: The response from the request
        :rtype: Response
        """
        if not self._esp.is_connected:
            self.connect()
        self.pixel_status((0, 0, 100))
        return_val = requests.get(url, **kw)
        self.pixel_status(0)
        return return_val
Beispiel #12
0
def showRedditStats(subreddit):

    global rootDirectory
    global statusNeopixel
    global setBackground
    global jsonTraverse
    global board
    global collegiateFont
    global primaryDisplayGroup

    url = "https://www.reddit.com/r/" + subreddit + "/about.json"
    countJsonPropPath = ["data", "subscribers"]

    # get data from url
    statusNeopixel.fill((100, 100, 0))   # yellow = fetching data
    gc.collect()
    r = requests.get(url)
    gc.collect()
    statusNeopixel.fill((0, 0, 100))   # green = got data
    jsonData = r.json()
    r.close()
    gc.collect()

    count = jsonTraverse(jsonData, countJsonPropPath)

    # display data
    countLabel = Label(collegiateFont, text=str(count))
    countLabel.x = 200
    countLabel.y = 100
    countLabel.color = 0xFFFFFF
    primaryDisplayGroup.append(countLabel)

    # load github stat background
    setBackground(rootDirectory + "/reddit_background.bmp")

    # wait
    time.sleep(60)

    # cleanup!
    while countLabel:
        countLabel.pop()
Beispiel #13
0
def showGithubStats(repo):

    global rootDirectory
    global statusNeopixel
    global setBackground
    global jsonTraverse
    global board
    global collegiateFont
    global primaryDisplayGroup

    url = "https://api.github.com/repos" + repo + "?access_token="+secrets['github_token']
    countJsonPropPath = ["stargazers_count"]

    # get data from url
    statusNeopixel.fill((100, 100, 0))   # yellow = fetching data
    gc.collect()
    r = requests.get(url)
    gc.collect()
    statusNeopixel.fill((0, 0, 100))   # green = got data
    jsonData = r.json()
    r.close()
    gc.collect()

    count = jsonTraverse(jsonData, countJsonPropPath)

    # display data
    countLabel = Label(collegiateFont, text=str(count))
    countLabel.x = 200
    countLabel.y = 100
    countLabel.color = 0xFFFFFF
    primaryDisplayGroup.append(countLabel)

    # load github stat background
    setBackground(rootDirectory + "/githubstar.bmp")

    # wait
    time.sleep(60)

    # cleanup!
    while countLabel:
        countLabel.pop()
    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()
    def wget(self, url, filename, *, chunk_size=12000):
        """Download a url and save to filename location, like the command wget.

        :param url: The URL from which to obtain the data.
        :param filename: The name of the file to save the data to.
        :param chunk_size: how much data to read/write at a time.

        """
        print("Fetching stream from", url)

        self.neo_status((100, 100, 0))
        r = requests.get(url, stream=True)

        if self._debug:
            print(r.headers)
        content_length = int(r.headers['content-length'])
        remaining = content_length
        print("Saving data to ", filename)
        stamp = time.monotonic()
        file = open(filename, "wb")
        for i in r.iter_content(min(remaining, chunk_size)):  # huge chunks!
            self.neo_status((0, 100, 100))
            remaining -= len(i)
            file.write(i)
            if self._debug:
                print("Read %d bytes, %d remaining" %
                      (content_length - remaining, remaining))
            else:
                print(".", end='')
            if not remaining:
                break
            self.neo_status((100, 100, 0))
        file.close()

        r.close()
        stamp = time.monotonic() - stamp
        print("Created file of %d bytes in %0.1f seconds" %
              (os.stat(filename)[6], stamp))
        self.neo_status((0, 0, 0))
        if not content_length == os.stat(filename)[6]:
            raise RuntimeError
Beispiel #16
0
def showTwitterStats(twitterName):

    global rootDirectory
    global statusNeopixel
    global setBackground
    global jsonTraverse
    global board
    global collegiateFont
    global primaryDisplayGroup

    url = "https://cdn.syndication.twimg.com/widgets/followbutton/info.json?screen_names=" + twitterName
    countJsonPropPath = [0, "followers_count"]

    # get data from url
    statusNeopixel.fill((100, 100, 0))   # yellow = fetching data
    gc.collect()
    r = requests.get(url)
    gc.collect()
    statusNeopixel.fill((0, 0, 100))   # green = got data
    jsonData = r.json()
    r.close()
    gc.collect()

    count = jsonTraverse(jsonData, countJsonPropPath)

    # display data
    countLabel = Label(collegiateFont, text=str(count))
    countLabel.x = 200
    countLabel.y = 100
    countLabel.color = 0xFFFFFF
    primaryDisplayGroup.append(countLabel)

    # load github stat background
    setBackground(rootDirectory + "/twitter_background.bmp")

    # wait
    time.sleep(60)

    # cleanup!
    while countLabel:
        countLabel.pop()
Beispiel #17
0
def time():
    r = requests.get(TIME_URL)
    time = json.loads(r.text)
    datetime = time['datetime']
    times = datetime.split(":")
    hour = int(times[0][-2:])
    minute = int(times[1])
    r.close()

    format_str = "%d:%02d"
    if hour >= 12:
        hour = hour - 12
        format_str = format_str+" PM"
    else:
        format_str = format_str+" AM"
    if hour == 0:
        hour = 12
    time_str = format_str % (hour, minute)

    # Time
    display.txt_set_cursor(530, 0)
    display.txt_trans(WHITE)
    display.txt_size(3)
    display.txt_write(time_str)
Beispiel #18
0
    def fetch(self):
        json_out = None
        image_url = None
        values = []

        gc.collect()
        if self._debug:
            print("Free mem: ", gc.mem_free())

        r = None
        if self._uselocal:
            print("*** USING LOCALFILE FOR DATA - NOT INTERNET!!! ***")
            r = fake_requests(LOCALFILE)

        if not r:
            self.neo_status((0, 0, 100))
            while not self._esp.is_connected:
                if self._debug:
                    print("Connecting to AP")
                # settings dictionary must contain 'ssid' and 'password' at a minimum
                self.neo_status((100, 0, 0))  # red = not connected
                self._esp.connect(settings)
            # great, lets get the data
            print("Retrieving data...", end='')
            self.neo_status((100, 100, 0))  # yellow = fetching data
            gc.collect()
            r = requests.get(self._url)
            gc.collect()
            self.neo_status((0, 0, 100))  # green = got data
            print("Reply is OK!")

        if self._debug:
            print(r.text)

        if self._image_json_path or self._json_path:
            try:
                gc.collect()
                json_out = r.json()
                gc.collect()
            except ValueError:  # failed to parse?
                print("Couldn't parse json: ", r.text)
                raise
            except MemoryError:
                supervisor.reload()

        if self._xml_path:
            try:
                import xmltok
                print("*" * 40)
                tokens = []
                for i in xmltok.tokenize(r.text):
                    print(i)
                print(tokens)
                print("*" * 40)
            except ValueError:  # failed to parse?
                print("Couldn't parse XML: ", r.text)
                raise

        # extract desired text/values from json
        if self._json_path:
            for path in self._json_path:
                values.append(self._json_pather(json_out, path))
        else:
            values = r.text

        if self._image_json_path:
            image_url = self._json_pather(json_out, self._image_json_path)

        # we're done with the requests object, lets delete it so we can do more!
        json_out = None
        r = None
        gc.collect()

        if image_url:
            print("original URL:", image_url)
            image_url = IMAGE_CONVERTER_SERVICE + image_url
            print("convert URL:", image_url)
            # convert image to bitmap and cache
            #print("**not actually wgetting**")
            self.wget(image_url, "/cache.bmp")
            self.set_background("/cache.bmp")
            image_url = None
            gc.collect()

        # if we have a callback registered, call it now
        if self._success_callback:
            self._success_callback(values)

        # fill out all the text blocks
        if self._text:
            for i in range(len(self._text)):
                string = None
                try:
                    string = "{:,d}".format(int(values[i]))
                except ValueError:
                    string = values[i]  # ok its a string
                if self._debug:
                    print("Drawing text", string)
                if self._text_wrap[i]:
                    if self._debug:
                        print("Wrapping text")
                    string = '\n'.join(
                        self.wrap_nicely(string, self._text_wrap[i]))
                self.set_text(string, index=i)
        if len(values) == 1:
            return values[0]
        return values
Beispiel #19
0
    board.DISPLAY.brightness = val


while True:

    try:  # WiFi Connection
        set_backlight(1)

        print('Getting time from Adafruit IO...')
        datetime = io.receive_time()
        print('displaying time...')
        gfx.display_date_time(datetime)

        CITY_1_URL = "http://api.openweathermap.org/data/2.5/weather?id=" + CITY_1_ID + "&APPID=" + OPEN_WEATHER_KEY
        print("Fetching text from", CITY_1_URL)
        r = requests.get(CITY_1_URL)
        json1 = json.loads(r.text)
        print(json)

        gfx.display_city_name(json1["name"], 1)
        gfx.display_city_temp(json1["main"]["temp"], 1)

        first_desc1 = json1["weather"][0]["description"]

        if len(first_desc1) > 18:
            words = first_desc1.split(" ", 2)
            if len(words) == 2:
                line1 = words[0]
                gfx.display_weather_desc(line1, 1)
                line2 = words[1]
                gfx.display_weather_additional_desc(line2, 1)
print("Connecting to AP...")
while not esp.is_connected:
    try:
        esp.connect_AP(b'MY_SSID_NAME', b'MY_SSID_PASSWORD')
    except RuntimeError as e:
        print("could not connect to AP, retrying: ", e)
        continue
print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi)
print("My IP address is", esp.pretty_ip(esp.ip_address))
print("IP lookup adafruit.com: %s" %
      esp.pretty_ip(esp.get_host_by_name("adafruit.com")))
print("Ping google.com: %d ms" % esp.ping("google.com"))

#esp._debug = True
print("Fetching text from", TEXT_URL)
r = requests.get(TEXT_URL)
print('-' * 40)
print(r.text)
print('-' * 40)
r.close()

print()
print("Fetching json from", JSON_URL)
r = requests.get(JSON_URL)
print('-' * 40)
print(r.json())
print('-' * 40)
r.close()

print("Done!")
Beispiel #21
0
        print("could not connect to AP, retrying: ", e)
        continue

print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi)
print("My IP address is", esp.pretty_ip(esp.ip_address))

# Location
LOCATION = "Palo Alto, US"

# Grabbing weather data
DATA_SOURCE = "http://api.openweathermap.org/data/2.5/weather?q=" + LOCATION
DATA_SOURCE += "&appid=" + secrets['openweather_token']
DATA_LOCATION = []

# Parse JSON file
r = requests.get(DATA_SOURCE)
print(r.json())
weather = json.loads(r.text)
city_name = weather['name']
country = weather['sys']['country']
weather_desc = weather['weather'][0]['icon']
weather_info = weather['weather'][0]['description']
min_temp = weather['main']['temp_min']
max_temp = weather['main']['temp_max']
cur_temp = weather['main']['temp']
humidity = weather['main']['humidity']
r.close()


####################################################################################################################################
# Get images displayed on display
Beispiel #22
0
def updateWeather(weather_url):
    
    # get weather info and format strings
    print("\nFetching json from", weather_url)
    r = requests.get(weather_url)
    print('-'*40)
    print(r.json())
    print('-'*40)
    weather = json.loads(r.text)
    city_name =  weather['name'] # + ", " + weather['sys']['country']
    print("OpenWeather data for " + city_name)
    main = weather['weather'][0]['main']
    main = main[0].upper() + main[1:]
    print(main)
    description = weather['weather'][0]['description']
    description_words = description.split(" ")
    description = ""
    for word in description_words:
        word = word[0].upper() + word[1:]
        description += word + " "
    print(description)
    temp = (weather['main']['temp'] - 273.15) * 9 / 5 + 32 # it's...in kelvin
    print("Current temp: " + str(int(temp)) + " F")
    tempH = (weather['main']['temp_max'] - 273.15) * 9 / 5 + 32
    print("High: " + str(int(tempH)) + " F")
    tempL = (weather['main']['temp_min'] - 273.15) * 9 / 5 + 32
    print("Low: " + str(int(tempL)) + " F")
    icon = weather['weather'][0]['icon']
    print(icon)
    print('-'*40)
    r.close()
    
    # display parsed and prcessed informaiton on the screen
    display.txt_set_cursor(15, 0)
    display.txt_trans(WHITE)
    display.txt_size(3)
    display.txt_write(city_name)    # location
    
    display.txt_set_cursor(610, 360)
    display.txt_trans(WHITE)
    display.txt_size(3)
    display.txt_write("%d°F" % int(temp))   # temp
    
    display.txt_set_cursor(610, 430)
    display.txt_trans(WHITE)
    display.txt_size(1)
    display.txt_write("%d°" % int(tempH) + "/ %d°" % int(tempL))    # temp H/L
    
    display.txt_set_cursor(15, 360)
    display.txt_trans(WHITE)
    display.txt_size(3)
    display.txt_write(main)    # main
    
    display.txt_set_cursor(15, 430)
    display.txt_trans(WHITE)
    display.txt_size(1)
    display.txt_write(description)    # descrioption
    
    fp = open("/sd/icons/" + icon + ".bmp", "r")
    bitmap = BMP("/sd/icons/" + icon + ".bmp")
    bitmap.draw(display, (display.width - bitmap.width) // 2, (display.height - bitmap.height) // 2)    # icon
Beispiel #23
0
def weather():
    # Location
    LOCATION = "Palo Alto, US"

    # Grabbing weather data
    DATA_SOURCE = "http://api.openweathermap.org/data/2.5/weather?q=" + LOCATION
    DATA_SOURCE += "&appid=" + secrets['openweather_token']
    DATA_LOCATION = []

    # Parse JSON file
    r = requests.get(DATA_SOURCE)
    print(r.json())
    weather = json.loads(r.text)
    city_name = weather['name']
    country = weather['sys']['country']
    weather_desc = weather['weather'][0]['icon']
    main = weather['weather'][0]['main']
    main = main[0].upper() + main[1:]
    weather_info = weather['weather'][0]['description']
    description_words = weather_info.split(" ")
    weather_info = ""
    for word in description_words:
        word = word[0].upper() + word[1:]
        weather_info += word + " "
    min_temp = weather['main']['temp_min']
    max_temp = weather['main']['temp_max']
    cur_temp = weather['main']['temp']
    humidity = weather['main']['humidity']
    r.close()

    fp = open("/sd/icons/" + weather_desc + ".bmp", 'r')
    weather_icon = BMP("/sd/icons/" + weather_desc + ".bmp")

    # Location
    display.txt_set_cursor(15, 0)
    display.txt_size(3)
    display.txt_write(city_name + ", " + country)

    # Main
    display.txt_set_cursor(15, 360)
    display.txt_trans(WHITE)
    display.txt_size(3)
    display.txt_write(main)

    # Weather description
    display.txt_set_cursor(15, 430)
    display.txt_size(1)
    display.txt_write(weather_info)

    # Current temp
    display.txt_set_cursor(610, 360)
    display.txt_size(3)
    display.txt_write("{0}".format(round(((cur_temp- 273 )* 9 / 5) + 32, 1)) + "°F")

    # Min and max temp
    display.txt_set_cursor(610, 430)
    display.txt_size(1)
    display.txt_write("{0}".format(round(((min_temp- 273 )* 9 / 5) + 32, 1))  + "°/" +
    "{0}".format(round(((max_temp - 273 )* 9 / 5) + 32, 1)) + "°")

    # Icon
    weather_icon.draw(display, (display.width - weather_icon.width)// 2, (display.height - weather_icon.height) // 2)
def checksite(site):
    r = requests.get(site)
    r.close()
    return str(r.status_code)
Beispiel #25
0
print("Connecting to AP...")
while not esp.is_connected:
    try:
        esp.connect_AP(b'mayB', b'notlikely')
    except RuntimeError as e:
        print("could not connect to AP, retrying: ", e)
        continue
print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi)
print("My IP address is", esp.pretty_ip(esp.ip_address))
print("IP lookup adafruit.com: %s" %
      esp.pretty_ip(esp.get_host_by_name("adafruit.com")))
print("Ping google.com: %d ms" % esp.ping("google.com"))

#esp._debug = True
print("Fetching text from", TEXT_URL)
r = requests.get(TEXT_URL)
print('-' * 40)
print(r.text)
print('-' * 40)
r.close()

print()
print("Fetching json from", JSON_URL)
r = requests.get(JSON_URL)
print('-' * 40)
print(r.json())
print('-' * 40)
r.close()

####
    # UPDATE LOCAL TIME ##################################################################################
    if (not localtime_refresh) or ((time.monotonic() - localtime_refresh) > 60 and (time.monotonic() - localtime_last_failed_try) > 30) :
        try:
            print("Getting time from internet!")
            get_local_time()
            localtime_refresh = time.monotonic()
            print('Local time updated\n')
        except RuntimeError as e:
            localtime_last_failed_try = time.monotonic()
            print("Some error occured, retrying in 5'! -", e)
            continue

    # UPDATE CURRENT WEATHER ###################################################################### LAYER 1
    if (not current_weather_refresh) or (time.monotonic() - current_weather_refresh) > 30:
        try:
            json_weather_data_1 = requests.get(CURRENT_WEATHER_DATA_SOURCE_1).json() # JSON 1
            weather_1 = json_weather_data_1['weather'][0]['description']
            temperature_1 = "{:.1f}".format(json_weather_data_1['main']['temp'])
            humidity_1 = "{:.0f}".format(json_weather_data_1['main']['humidity'])
            wind_1 = "{:.0f}".format(json_weather_data_1['wind']['speed'])
            SUNRISE = json_weather_data_1['sys']['sunrise']
            SUNSET = json_weather_data_1['sys']['sunset']
            
            text_temp = temperature_1 + " C"
            TEMP_text_area = label.Label(font, text=text_temp, color=color)
            TEMP_text_area.x = 40
            TEMP_text_area.y = 80
            group[1] = TEMP_text_area
            
            text_hum = humidity_1 + ' %'
            HUM_text_area = label.Label(font, text=text_hum, color=color)
Beispiel #27
0
    def fetch(self):
        """Fetch data from the url we initialized with, perfom any parsing,
        and display text or graphics. This function does pretty much everything"""
        json_out = None
        image_url = None
        values = []

        gc.collect()
        if self._debug:
            print("Free mem: ", gc.mem_free())  # pylint: disable=no-member

        r = None
        if self._uselocal:
            print("*** USING LOCALFILE FOR DATA - NOT INTERNET!!! ***")
            r = Fake_Requests(LOCALFILE)

        if not r:
            self._connect_esp()
            # great, lets get the data
            print("Retrieving data...", end='')
            self.neo_status((100, 100, 0))  # yellow = fetching data
            gc.collect()
            r = requests.get(self._url)
            gc.collect()
            self.neo_status((0, 0, 100))  # green = got data
            print("Reply is OK!")

        if self._debug:
            print(r.text)

        if self._image_json_path or self._json_path:
            try:
                gc.collect()
                json_out = r.json()
                gc.collect()
            except ValueError:  # failed to parse?
                print("Couldn't parse json: ", r.text)
                raise
            except MemoryError:
                supervisor.reload()

        if self._regexp_path:
            import re

        # extract desired text/values from json
        if self._json_path:
            for path in self._json_path:
                try:
                    values.append(PyPortal._json_traverse(json_out, path))
                except KeyError:
                    print(json_out)
                    raise
        elif self._regexp_path:
            for regexp in self._regexp_path:
                values.append(re.search(regexp, r.text).group(1))
        else:
            values = r.text

        if self._image_json_path:
            try:
                image_url = PyPortal._json_traverse(json_out,
                                                    self._image_json_path)
            except KeyError as error:
                print("Error finding image data. '" + error.args[0] +
                      "' not found.")
                self.set_background(self._default_bg)

        # we're done with the requests object, lets delete it so we can do more!
        json_out = None
        r = None
        gc.collect()

        if image_url:
            try:
                print("original URL:", image_url)
                image_url = self.image_converter_url(image_url,
                                                     self._image_resize[0],
                                                     self._image_resize[1])
                print("convert URL:", image_url)
                # convert image to bitmap and cache
                #print("**not actually wgetting**")
                filename = "/cache.bmp"
                chunk_size = 12000  # default chunk size is 12K (for QSPI)
                if self._sdcard:
                    filename = "/sd" + filename
                    chunk_size = 512  # current bug in big SD writes -> stick to 1 block
                try:
                    self.wget(image_url, filename, chunk_size=chunk_size)
                except OSError as error:
                    print(error)
                    raise OSError("""\n\nNo writable filesystem found for saving datastream. Insert an SD card or set internal filesystem to be unsafe by setting 'disable_concurrent_write_protection' in the mount options in boot.py""")  # pylint: disable=line-too-long
                self.set_background(filename, self._image_position)
            except ValueError as error:
                print("Error displaying cached image. " + error.args[0])
                self.set_background(self._default_bg)
            finally:
                image_url = None
                gc.collect()

        # if we have a callback registered, call it now
        if self._success_callback:
            self._success_callback(values)

        # fill out all the text blocks
        if self._text:
            for i in range(len(self._text)):
                string = None
                if self._text_transform[i]:
                    func = self._text_transform[i]
                    string = func(values[i])
                else:
                    try:
                        string = "{:,d}".format(int(values[i]))
                    except (TypeError, ValueError):
                        string = values[i]  # ok its a string
                if self._debug:
                    print("Drawing text", string)
                if self._text_wrap[i]:
                    if self._debug:
                        print("Wrapping text")
                    lines = PyPortal.wrap_nicely(string, self._text_wrap[i])
                    string = '\n'.join(lines)
                self.set_text(string, index=i)
        if len(values) == 1:
            return values[0]
        return values
# Make ESP32 connection
esp32_cs = DigitalInOut(microcontroller.pin.PB14)
esp32_ready = DigitalInOut(microcontroller.pin.PB16)
esp32_gpio0 = DigitalInOut(microcontroller.pin.PB15)
esp32_reset = DigitalInOut(microcontroller.pin.PB17)
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)

esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready, esp32_reset,
                                       esp32_gpio0)
requests.set_interface(esp)
esp.connect_AP(b'adafruit', b'ffffffff')
print("Connected to", str(esp.ssid, 'utf-8'), "RSSI", esp.rssi)

print("Fetching stream from", URL)
r = requests.get(URL, stream=True)
#esp._debug = True

print(r.headers)
content_length = int(r.headers['content-length'])
remaining = content_length
print("Saving data to ", FILENAME)

stamp = time.monotonic()
with open(FILENAME, "wb") as f:
    for i in r.iter_content(min(remaining, 12000)):
        remaining -= len(i)
        f.write(i)
        print("Read %d bytes, %d remaining" %
              (content_length - remaining, remaining))
        if not remaining: