Nahyeahnah
Posts: 5
Joined: Mon Jul 15, 2019 8:01 am

Problem with my OLED time, date, weather script.

Sun Aug 04, 2019 4:45 am

Hi,

I'm relatively new to coding python and am trying to get my OLED display to show the time, date, and weather. Pre-implementing the weather part, the time and date worked perfectly fine, and showed on the OLED.

Now that I've implemented the weather using openweathermaps, I'm getting the error show in the image.

This is the code that I'm using currently:

Code: Select all

"""
An analog clockface with date, time & temp.


"""

import math
import time
import datetime
import json
import sqlite3
import urllib
import calendar
from demo_opts import get_device
from luma.core.render import canvas

APP_ID = '497f4bcadd7291213189485776f0a8c7'
WEATHER_DATA_URL = 'http://api.openweathermap.org/data/2.5/weather?q=Adelaide,de&units=metric&APPID=' + APP_ID



def posn(angle, arm_length):
    dx = int(math.cos(math.radians(angle)) * arm_length)
    dy = int(math.sin(math.radians(angle)) * arm_length)
    return (dx, dy)


def get_data():
    """get weather data from openweathermap"""
    response = urllib.urlopen(WEATHER_DATA_URL)
    data = json.loads(response.read())

    temp = data['main']['temp']
    pressure = data['main']['pressure']
    temp_min = data['main']['temp_min']
    temp_max = data['main']['temp_max']
    humidity = data['main']['humidity']
    wind_speed = data['wind']['speed']
    try:
        wind_gust = data['wind']['gust']
    except KeyError:
        wind_gust = None
    wind_deg = data['wind']['deg']
    clouds = data['clouds']['all']
    try:
        rain = data['rain']['3h']
    except KeyError:
        rain = None
    try:
        snow = data['snow']['3h']
    except KeyError:
        snow = None
    weather_id = data['weather'][0]['id']
    sunrise = data['sys']['sunrise']
    sunset = data['sys']['sunset']

    return [temp, pressure, temp_min, temp_max, humidity, wind_speed, wind_gust, wind_deg, clouds, rain, snow,
            weather_id, sunrise, sunset]

def save_data_to_db(data):
    con = sqlite3.connect("/home/pi/dumbGlasses/Weatherdata/db_files/data.db")
    con.isolation_level = None
    cur = con.cursor()

    query = '''INSERT INTO weather_data VALUES (null, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)'''

    cur.execute(query, tuple([datetime.datetime.now().isoformat()] + data[:-2]))

    con.commit()
    con.close()


def main():
    data = get_data()
    now = calendar.timegm(datetime.datetime.now().timetuple())
    if data[-2] < now < data[-1]:
        save_data_to_db(data)    

    today_last_time = "Unknown"
    while True:
        now = datetime.datetime.now()
        today_date = now.strftime("%d %b %y")
        today_time = now.strftime("%H:%M:%S")
        if today_time != today_last_time:
            today_last_time = today_time
            with canvas(device) as draw:
                now = datetime.datetime.now()
                today_date = now.strftime("%d %b %y")

                margin = 4

                cx = 30
                cy = min(device.height, 64) / 2

                left = cx - cy
                right = cx + cy

                hrs_angle = 270 + (30 * (now.hour + (now.minute / 60.0)))
                hrs = posn(hrs_angle, cy - margin - 7)

                min_angle = 270 + (6 * now.minute)
                mins = posn(min_angle, cy - margin - 2)

                sec_angle = 270 + (6 * now.second)
                secs = posn(sec_angle, cy - margin - 2)

                draw.ellipse((left + margin, margin, right - margin, min(device.height, 64) - margin), outline="white")
                draw.line((cx, cy, cx + hrs[0], cy + hrs[1]), fill="white")
                draw.line((cx, cy, cx + mins[0], cy + mins[1]), fill="white")
                draw.line((cx, cy, cx + secs[0], cy + secs[1]), fill="red")
                draw.ellipse((cx - 2, cy - 2, cx + 2, cy + 2), fill="white", outline="white")
                draw.text((2 * (cx + margin), cy - 8), today_date, fill="yellow")
                draw.text((2 * (cx + margin), cy), today_time, fill="yellow")
        draw.text((2 * (cx + margin), cy + 8), temp, fill="yellow")
                
        
        time.sleep(0.1)


if __name__ == "__main__":
    try:
        device = get_device()
        main()
    except KeyboardInterrupt:
        pass

Thanks for any help! :D
Attachments
dumbglassespythonproblem.PNG
dumbglassespythonproblem.PNG (131.12 KiB) Viewed 363 times

ghp
Posts: 1409
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: Problem with my OLED time, date, weather script.

Sun Aug 04, 2019 10:14 am

Code: Select all

    data = json.loads(response.read())
    print("data from response is", data)  # add this statement and look what the data structure is
    temp = data['main']['temp']

Nahyeahnah
Posts: 5
Joined: Mon Jul 15, 2019 8:01 am

Re: Problem with my OLED time, date, weather script.

Thu Aug 08, 2019 8:02 am

This is what I've gotten after adding the print function.
dumbglasses python problem 2.PNG
dumbglasses python problem 2.PNG (255.34 KiB) Viewed 308 times

Andyroo
Posts: 4479
Joined: Sat Jun 16, 2018 12:49 am
Location: Lincs U.K.

Re: Problem with my OLED time, date, weather script.

Thu Aug 08, 2019 1:08 pm

That’s saying Adelaide DE is not a valid location.

OpenWeatherMaps recommendation is
We recommend to call API by city ID to get unambiguous result for your city.
You can find this by going to the main page and searching for the location you are after and then looking at the URL once you have found it.

You then use ?id={city ID} (replacing {city} with the number you found above} in your search string.
Need Pi spray - these things are breeding in my house...

Nahyeahnah
Posts: 5
Joined: Mon Jul 15, 2019 8:01 am

Re: Problem with my OLED time, date, weather script.

Sun Aug 11, 2019 9:29 am

Thanks for all the help guys! :D
After properly adding the city ID, it's gathering all the weather data.

However, now there's an issue drawing the 'temp' data in main. I've tried defining temp as a global function, but nothing seems to be working.

This is what the terminal responds with:
dumbglasses python problem 3.PNG
dumbglasses python problem 3.PNG (212.18 KiB) Viewed 273 times
Again, thanks for the help guys!

Andyroo
Posts: 4479
Joined: Sat Jun 16, 2018 12:49 am
Location: Lincs U.K.

Re: Problem with my OLED time, date, weather script.

Sun Aug 11, 2019 11:54 am

Without seeing you code its just about impossible to debug this!

You could check:

1) That temp is defined in the main code
2) That temp is used consistently and not Temp (python is case sensitive)
3) You have Global temp in the function that has the error
Need Pi spray - these things are breeding in my house...

Nahyeahnah
Posts: 5
Joined: Mon Jul 15, 2019 8:01 am

Re: Problem with my OLED time, date, weather script.

Sun Aug 11, 2019 10:59 pm

I'll give this a shot tonight! Thanks man.
The code is in the first post. The only thing that has changed in it has been the area code for openweathermap.
Andyroo wrote:
Sun Aug 11, 2019 11:54 am
Without seeing you code its just about impossible to debug this!

You could check:

1) That temp is defined in the main code
2) That temp is used consistently and not Temp (python is case sensitive)
3) You have Global temp in the function that has the error

Return to “Python”