コード例 #1
0
import time
import displayio
from adafruit_magtag.magtag import MagTag
from adafruit_display_shapes.circle import Circle

#  create MagTag and connect to network
try:
    magtag = MagTag()
    magtag.network.connect()
except (ConnectionError, ValueError, RuntimeError) as e:
    print("*** MagTag(), Some error occured, retrying! -", e)
    # Exit program and restart in 1 seconds.
    magtag.exit_and_deep_sleep(1)

#  displayio groups
group = displayio.Group(max_size=30)
tree_group = displayio.Group(max_size=30)
circle_group = displayio.Group(max_size=30)

#  import tree bitmap
tree = displayio.OnDiskBitmap(open("/atree.bmp", "rb"))

tree_grid = displayio.TileGrid(tree, pixel_shader=displayio.ColorConverter())

#  add bitmap to its group
tree_group.append(tree_grid)
#  add tree group to the main group
group.append(tree_group)

#  list of circle positions
spots = ((246, 53), (246, 75), (206, 42), (206, 64), (206, 86), (176, 31),
コード例 #2
0
        Administered_Dose1_Pop_Pct = location["Administered_Dose1_Pop_Pct"]
        Administered_Dose2_Pop_Pct = location["Administered_Dose2_Pop_Pct"]

        if location["Location"] == "NY":
            magtag.set_text(
                f"{Location}: {Administered_Dose1_Pop_Pct}%",
                index=1,
                auto_refresh=False,
            )
            dose1_ny_progress_bar.progress = Administered_Dose1_Pop_Pct / 100.0
            dose2_ny_progress_bar.progress = Administered_Dose2_Pop_Pct / 100.0
        elif location["Location"] == "US":
            magtag.set_text(
                f"{Location}: {Administered_Dose1_Pop_Pct}%",
                index=2,
                auto_refresh=False,
            )
            dose1_us_progress_bar.progress = Administered_Dose1_Pop_Pct / 100.0
            dose2_us_progress_bar.progress = Administered_Dose2_Pop_Pct / 100.0

response = requests.get(TIME_URL)
print("-" * 40)
print(response.text)
print("-" * 40)

Date += f" at {response.text}"

magtag.set_text(f"{Date}", index=3, auto_refresh=False)
magtag.refresh()
magtag.exit_and_deep_sleep(12 * 60 * 60)  # Half day
コード例 #3
0
    # Scan cells in row #1 to find the column number for naughty vs nice.
    # This allows the order of columns in the spreadsheet to be changed,
    # though they still must have a "Naughty" or "Nice" heading at top.
    for entry in ENTRIES:
        cell = entry['gs$cell']
        if int(cell['row']) is 1:  # Only look at top row
            head = cell['$t'].lower()  # Case-insensitive compare
            if ((NICE and head == 'nice') or (not NICE and head == 'naughty')):
                NAME_COLUMN = int(cell['col'])

    # Now that we know which column number contains the names we want,
    # a second pass is made through all the cells. Items where row > 1
    # and column is equal to NAME_COLUMN are joined in a string.
    NAME_LIST = ''  # Clear name list
    for entry in ENTRIES:
        cell = entry['gs$cell']
        if int(cell['row']) > 1 and int(cell['col']) is NAME_COLUMN:
            NAME_LIST += cell['$t'] + '\n'  # Name + newline character

    MAGTAG.set_text(NAME_LIST)  # Update list on the display

    time.sleep(2)  # Allow refresh to finish before deep sleep
    print('Zzzz time')
    MAGTAG.exit_and_deep_sleep(24 * 60 * 60)  # 24 hour deep sleep

except RuntimeError as error:
    # If there's an error above, no harm, just try again in ~15 minutes.
    # Usually it's a common network issue or time server hiccup.
    print('Retrying in 15 min - ', error)
    MAGTAG.exit_and_deep_sleep(15 * 60)  # 15 minute deep sleep
コード例 #4
0
# ===========
#  M A I N
# ===========
# get current time
magtag.get_local_time()
now = time.localtime()

# show today's date
show_today()

# get and plot tide levels
tide_data = get_tide_data()
plot_tides()

# get and show hilo tide times
hilo_data = get_hilo_data()
show_hilo()

# refresh display
time.sleep(magtag.display.time_to_refresh + 1)
magtag.display.refresh()
time.sleep(magtag.display.time_to_refresh + 1)

# ZZZZZZzzzzzzzzz
now = time.localtime()
magtag.exit_and_deep_sleep(time_to_sleep())
#
# code.py runs again when board wakes up
#
コード例 #5
0
access_token_obtained = int(time.monotonic())

while True:
    # check if we need to refresh token
    if (int(time.monotonic()) - access_token_obtained >=
            google_auth.access_token_expiration):
        print("Access token expired, refreshing...")
        if not google_auth.refresh_access_token():
            raise RuntimeError(
                "Unable to refresh access token - has the token been revoked?")
        access_token_obtained = int(time.monotonic())

    # fetch calendar events!
    print("fetching local time...")
    now = get_current_time()

    # setup header label
    label_header.text = format_datetime(now, pretty_date=True)

    print("fetching calendar events...")
    events = get_calendar_events(CALENDAR_ID, MAX_EVENTS, now)

    print("displaying events")
    display_calendar_events(events)

    board.DISPLAY.show(magtag.splash)
    board.DISPLAY.refresh()

    print("Sleeping for %d minutes" % REFRESH_TIME)
    magtag.exit_and_deep_sleep(REFRESH_TIME * 60)
コード例 #6
0
# A full battery has 4 volts. It supplies 3.7V to the board so I decided
# to start warning at 3.8v but maybe there's a better number
if (magtag.peripherals.battery > 3.3):
    voltage_text.text = ' '
else:
    voltage_text.text = 'Battery Low'
print(f'battery: {magtag.peripherals.battery} V')

try:
    magtag.network.connect()
    response = magtag.network.requests.get(data_source)
    value = response.json()
    results = value['results'][0]
except (ConnectionError, ValueError, RuntimeError) as e:
    print("Some error occured, retrying in 10 seconds -", e)
    magtag.exit_and_deep_sleep(10)

# Default time zone is Pacific Standard
timezone_offset = secrets['timezone_offset']
valid_offsets = [
    "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "-1",
    "-2", "-3", "-4", "-5", "-6", "-7", "-8", "-9", "-10", "-11", "-12"
]
if (timezone_offset not in valid_offsets):
    print("timezone_offset must be one of the following values", valid_offsets)
    print("Using default offset -8 for Pacific Standard Time")
    timezone_offset = -8  # Pacific Standard Time
last_seen = results['LastSeen'] + (int(timezone_offset) * 60 * 60)
last_modified = time.localtime(last_seen)
hour = int(last_modified[3])
min = int(last_modified[4])
コード例 #7
0
magtag.add_text(text_position=(5, 30), text_scale=2)

magtag.add_text(text_position=(10, 50),
                text_transform=lambda x: "Current: {}F".format(x),
                text_scale=2)

magtag.add_text(text_position=(10, 75),
                text_transform=lambda x: "Max: {}F".format(x),
                text_scale=2)

magtag.add_text(text_position=(120, 75),
                text_transform=lambda x: "Min: {}F".format(x),
                text_scale=2)

magtag.add_text(text_position=(10, 110), text_scale=2)

magtag.add_text(text_position=(130, 110),
                text_transform=lambda x: "{} mph".format(x),
                text_scale=2)

magtag.peripherals.neopixels.brightness = 0.1
magtag.peripherals.neopixels.disable = False
magtag.peripherals.neopixels.fill(0x0F0000)

raw = magtag.fetch()

print(raw)

magtag.exit_and_deep_sleep(900)
コード例 #8
0
mins_till_next_eventstart = min(remaining_starttimes)
mins_till_next_eventend = min(remaining_endtimes)
next_up = events[remaining_starttimes.index(mins_till_next_eventstart)]

# OK find the one with the smallest minutes remaining
sleep_time = None
if current_event:
    print("Currently: ", current_event)
    magtag.set_background("bmps/" + current_event["graphic"])
    magtag.set_text("Currently streaming until " +
                    time_format(current_event["end_time"]))
    remaining_starttimes.index(mins_till_next_eventstart)
    if BEEP_ON_EVENTSTART:
        for _ in range(3):
            magtag.peripherals.play_tone(1760, 0.1)
            time.sleep(0.2)
    sleep_time = mins_till_next_eventend + 1
else:
    print("Next up! ", next_up)
    magtag.set_background("bmps/" + next_up["graphic"])

    string = ("Coming up on " + next_up["day_of_week"] + " at " +
              time_format(next_up["start_time"]))
    magtag.set_text(string)
    sleep_time = mins_till_next_eventstart

print("Sleeping for %d minutes" % sleep_time)
time.sleep(2)
magtag.exit_and_deep_sleep(sleep_time * 60)
コード例 #9
0
BAR_WIDTH = magtag.graphics.display.width - 80
BAR_HEIGHT = 30

BAR_X = magtag.graphics.display.width // 2 - BAR_WIDTH // 2
BAR_Y = 80

# Create a new progress_bar object at (x, y)
progress_bar = ProgressBar(BAR_X,
                           BAR_Y,
                           BAR_WIDTH,
                           BAR_HEIGHT,
                           1.0,
                           bar_color=0x999999,
                           outline_color=0x000000)

magtag.graphics.splash.append(progress_bar)

try:
    magtag.network.get_local_time()
    now = rtc.RTC().datetime
    progress_bar.progress = now.tm_yday / days_in_year(now)
    magtag.set_text("{:.2f}%".format(now.tm_yday / days_in_year(now) * 100.0),
                    index=1)

    print(now)
    magtag.exit_and_deep_sleep(24 * 60 * 60)  # one day

except (ValueError, RuntimeError) as e:
    print("Some error occurred, retrying after 1 minute! -", e)
    magtag.exit_and_deep_sleep(60)  # one  minute
コード例 #10
0
ファイル: 1768.py プロジェクト: jhaip/programmable-space
from adafruit_magtag.magtag import MagTag
import re
DATA_SOURCE = "http://192.168.1.34:5000/select?first=1&subscription=%5B%22reading%20list%20%24%20is%20%24title%20%24%20%24%22%5D"
magtag = MagTag(url=DATA_SOURCE)
magtag.network.connect()
magtag.add_text(
    text_position=(
        (magtag.graphics.display.width // 2) - 1,
        (magtag.graphics.display.height // 2) - 1,
    ),
    text_scale=3,
    text_anchor_point=(0.5, 0.5),
    is_data=False,
)
try:
    value = magtag.fetch()
    print("Response is", value)
    title = re.search(r"title\":\"(.+)\"", value).group(1)
    magtag.set_text("Read\n" + title, 0)
except (ValueError, RuntimeError) as e:
    print("Some error occured, retrying! -", e)
magtag.exit_and_deep_sleep(60)
コード例 #11
0
    columns = l_split(table[0])
    latest = l_split(table[-2])
    print(columns)
    print(latest)
    value = dict(zip(columns, latest))
    print("Response is", value)
    print(value)

    vaccinated = int(value["people_vaccinated"]) / 331984513
    fully_vaccinated = int(value["people_fully_vaccinated"]) / 331984513

    magtag.set_text(f"{value['location']} Vaccination Rates", 0, False)
    magtag.set_text(value["date"], 1, False)
    magtag.set_text("Vaccinated: {:.2f}%".format(vaccinated * 100), 2, False)
    magtag.set_text("Fully Vaccinated: {:.2f}%".format(fully_vaccinated * 100),
                    3, False)

    progress_bar.progress = vaccinated
    progress_bar_1.progress = fully_vaccinated

    magtag.refresh()

    SECONDS_TO_SLEEP = 24 * 60 * 60  # Sleep for one day

except (ValueError, RuntimeError) as e:
    print("Some error occured, retrying in one hour! -", e)
    seconds_to_sleep = 60 * 60  # Sleep for one hour

print(f"Sleeping for {SECONDS_TO_SLEEP} seconds")
magtag.exit_and_deep_sleep(SECONDS_TO_SLEEP)
コード例 #12
0
    print('Updating produce')
    PRODUCE.fetch(MAGTAG)

    # Set the "Updated" date and time label
    if DD_MM:
        DATE = '%d/%d' % (NOW.tm_mday, NOW.tm_mon)
    else:
        DATE = '%d/%d' % (NOW.tm_mon, NOW.tm_mday)
    MAGTAG.set_text('Updated %s %s' % (DATE, hh_mm(NOW, TWELVE_HOUR)), 1,
                    auto_refresh=False)

    # Look up the matching produce data (returned as list of strings)
    PRODUCE_LIST = PRODUCE.in_season(NOW.tm_mon)
    NUM_ITEMS = len(PRODUCE_LIST)
    print('Produce list: ', PRODUCE_LIST)
    # List one item per line since some may be long
    VEGGIE_LIST = ''
    for item in PRODUCE_LIST:
        VEGGIE_LIST += '\n'.join(MAGTAG.wrap_nicely(item, 15)) + '\n'
    MAGTAG.set_text(VEGGIE_LIST) # Update list on the display

    time.sleep(2) # Allow refresh to finish before deep sleep
    print('Zzzz time')
    MAGTAG.exit_and_deep_sleep(24 * 60 * 60) # 24 hour snooze

except RuntimeError as error:
    # If there's an error above, no harm, just try again in ~15 minutes.
    # Usually it's a common network issue or time server hiccup.
    print('Retrying in 15 min - ', error)
    MAGTAG.exit_and_deep_sleep(15 * 60) # 15 minute snooze
コード例 #13
0
    text_scale=1,
    line_spacing=0.7,
    text_anchor_point=(0, 0),
)

magtag.add_text(
    text_font="fonts/ArialMT-9.bdf",
    text_position=(5, 38),
    text_scale=1,
    line_spacing=0.6,
    text_anchor_point=(0, 0),
)

# Create the QR code
url = f"https://certification.oshwa.org/{selected['oshwaUid'].lower()}.html"
magtag.graphics.qrcode(url, qr_size=4, x=173, y=3)

# Prepare to wrap the text correctly by getting the width of each character for every font
arial_12 = font_width_to_dict("fonts/Arial-Bold-12.bdf")
arial_9 = font_width_to_dict("fonts/ArialMT-9.bdf")

# Set the text. On some characters, this fails. If so, run the whole file again in 5 seconds
try:
    magtag.set_text(wrap(selected["projectName"], 545, 2, arial_12), 0, False)
    magtag.set_text(wrap(selected["projectDescription"], 530, 19, arial_9), 1)
    magtag.exit_and_deep_sleep(3600)
except Exception:  # pylint: disable=broad-except
    print("Could not set title or description: unsupported glyphs.")
    print("Trying again in 10 seconds.")
    magtag.exit_and_deep_sleep(10)
コード例 #14
0
    print("Now: ", now)

    # display the current time since its the last-update
    updated_at = "%d/%d\n%d:%02d" % now[1:5]
    magtag.set_text(updated_at, 6, False)

    # get data from the Covid Tracking Project
    value = magtag.fetch()
    print("Response is", value)

    # OK we're done!
    magtag.peripherals.neopixels.fill(0x000F00)  # greten
except (ValueError, RuntimeError) as e:
    print("Some error occured, trying again later -", e)

time.sleep(2)  # let screen finish updating

# we only wanna wake up once a day, around the event update time:
event_time = time.struct_time(
    (now[0], now[1], now[2], DAILY_UPDATE_HOUR, 0, 0, -1, -1, now[8]))
# how long is that from now?
remaining = time.mktime(event_time) - time.mktime(now)
if remaining < 0:  # ah its aready happened today...
    remaining += 24 * 60 * 60  # wrap around to the next day
remaining_hrs = remaining // 3660
remaining_min = (remaining % 3600) // 60
print("Gonna zzz for %d hours, %d minutes" % (remaining_hrs, remaining_min))

# Turn it all off and go to bed till the next update time
magtag.exit_and_deep_sleep(remaining)
コード例 #15
0
magtag.add_text(
    text_font="/fonts/Arial-Bold-12.bdf",
    text_wrap=28,
    text_maxlen=120,
    text_position=(
        (magtag.graphics.display.width // 2),
        (magtag.graphics.display.height // 2) - 10,
    ),
    line_spacing=0.75,
    text_anchor_point=(0.5, 0.5),  # center the text on x & y
)

# author in italic text, no wrapping
magtag.add_text(
    text_font="/fonts/Arial-Italic-12.bdf",
    text_position=(magtag.graphics.display.width // 2, 118),
    text_anchor_point=(0.5, 0.5),  # center it in the nice scrolly thing
)

# OK now we're ready to connect to the network, fetch data and update screen!
try:
    magtag.network.connect()
    value = magtag.fetch()
    print("Response is", value)
except (ValueError, RuntimeError) as e:
    magtag.set_text(e)
    print("Some error occured, retrying later -", e)
# wait 2 seconds for display to complete
time.sleep(2)
magtag.exit_and_deep_sleep(TIME_BETWEEN_REFRESHES)
コード例 #16
0
    text_font="/fonts/Arial-Bold-12.pcf",
    text_position=(10, 38),
    text_transform=time_transform
)

# Formatting for the Temperature text
magtag.add_text(
    text_font="/fonts/Arial-Bold-12.pcf",
    text_position=(10, 60),
    text_transform=Temperature_transform
)

# Formatting for the Humidity text
magtag.add_text(
    text_font="/fonts/Arial-Bold-12.pcf",
    text_position=(10, 82),
    text_transform=Humidity_transform
)

try:
    # Have the MagTag connect to the internet
    magtag.network.connect()
    # This statement gets the JSON data and displays it automagically
    value = magtag.fetch()
    print("Response is", value)
except Exception as e:
    print("Some error occured, retrying! -", e)
    magtag.exit_and_deep_sleep(2)
# wait 2 seconds for display to complete
time.sleep(2)
magtag.exit_and_deep_sleep(60 * 5)
コード例 #17
0
magtag.add_text(
    text_position=(70, 30),
    text_font="/fonts/Arial-12.bdf",
    text_transform=lambda x: "@%s" % x,
)

# Tweet text
magtag.add_text(
    text_font="/fonts/Arial-Bold-12.pcf",
    text_wrap=30,
    text_maxlen=160,
    text_position=(
        5,
        (magtag.graphics.display.height // 2) + 20,
    ),
    line_spacing=0.75,
)

# preload characters
magtag.preload_font()

try:
    value = magtag.fetch()
    print("Response is", value)
except (ValueError, RuntimeError) as e:
    print("Some error occured, retrying! -", e)

time.sleep(2)
print("Sleeping!")
magtag.exit_and_deep_sleep(SLEEP_TIME * 60)
コード例 #18
0
            set_neo(pixels, default_pixels, color_keynum, True)

            refresh_needed = True

    elif t4:
        #Only T2 pressed.  In normal mode, send the currently selected password like a keyboard.  In "enter xform" mode, add a "True/casechange" to the xform list.
        if unlock_entry_mode:
            unlock_list.append(3)
            #print(str(unlock_list))
        elif xform_entry_mode:
            xform_list.append(True)
            #print(str(xform_list))
        elif unlock_list != secrets['unlock']:
            flash_neo(pixels, [3, 2], color_unlock_mode, 0.5)
        else:
            #FIXME - use pw_dict instead
            target_string = transform_raw(
                load_raw_keyfile(data_dir,
                                 pw_filenames[selected_keynum] + ".pass"),
                xform_list)
            if target_string:
                keyboard_layout.write(target_string)

    new_pw_filenames, new_pw_dict = load_pw_files(data_dir)
    if set(new_pw_filenames) != set(pw_filenames):
        pw_filenames = new_pw_filenames
        pw_dict = new_pw_dict

#Future: Make sure we have a successful refresh before sleeping.
magtag.exit_and_deep_sleep(15 * 60)