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()
def get_strftime(time_format, location=None):
    """
    Fetch a custom strftime relative to your location.

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

    """
    # pylint: disable=line-too-long
    api_url = None
    reply = 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", 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 += "&fmt=" + url_encode(time_format)

    try:
        response = requests.get(api_url, timeout=10)
        if response.status_code != 200:
            print(response)
            error_message = (
                "Error connecting to Adafruit IO. The response was: " + response.text
            )
            raise RuntimeError(error_message)
        reply = response.text
    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
    # now clean up
    response.close()
    response = None
    gc.collect()

    return reply
    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()
    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()
Beispiel #5
0
def resolve_company(name):
    page_no = 1
    num_pages = 1
    
    while page_no <= num_pages:
        if secrets.get('api_token') is None:
            qs = urllib.parse.urlencode({"q": name, "page": page_no})
        else:
            qs = urllib.parse.urlencode({"q": name, "page": page_no, 'api_token': secrets['api_token']})
            
        r = requests.get("https://api.opencorporates.com/companies/search?%s" % qs).json()

        num_pages = int(r["results"]["total_pages"])

        for company in [x["company"] for x in r["results"]["companies"]]:
            # print(company["name"], name)
            if company["name"].lower() == name.lower():
                return company["jurisdiction_code"], company["company_number"]
        
        page_no += 1

    return None, None
### RPS module files
from rps_advertisements import JoinGameAdvertisement, \
                               RpsEncDataAdvertisement, \
                               RpsKeyDataAdvertisement, \
                               RpsRoundEndAdvertisement
from rps_audio import SampleJukebox
from rps_comms import broadcastAndReceive, addrToText, MIN_AD_INTERVAL
from rps_crypto import bytesPad, strUnpad, generateOTPadKey, \
                       enlargeKey, encrypt, decrypt
from rps_display import RPSDisplay, blankScreen

### Look for our name in secrets.py file if present
ble_name = None
try:
    from secrets import secrets
    ble_name = secrets.get("rps_name")
    if ble_name is None:
        ble_name = secrets.get("ble_name")
        if ble_name is None:
            print("INFO: No rps_name or ble_name entry found in secrets dict")
except ImportError:
    pass

debug = 3


def d_print(level, *args, **kwargs):
    """A simple conditional print for debugging based on global debug level."""
    if not isinstance(level, int):
        print(level, *args, **kwargs)
    elif debug >= level:
Beispiel #7
0
import time
import board
import terminalio
from adafruit_matrixportal.matrixportal import MatrixPortal
from adafruit_matrixportal.network import Network
import adafruit_minimqtt.adafruit_minimqtt as MQTT
import adafruit_esp32spi.adafruit_esp32spi_socket as socket
from secrets import secrets

# --- Display setup ---
matrixportal = MatrixPortal(status_neopixel=board.NEOPIXEL, debug=False)
network = matrixportal.network
network.connect()

mqtt = MQTT.MQTT(
    broker=secrets.get("mqtt_broker"),
    username=secrets.get("mqtt_user"),
    password=secrets.get("mqtt_password"),
    port=1883,
)

MQTT.set_socket(socket, network._wifi.esp)

TEAM_1_COLOR = 0x00AA00
TEAM_2_COLOR = 0xAAAAAA

# Team 1 Score
matrixportal.add_text(
    text_font=terminalio.FONT,
    text_position=(2, int(matrixportal.graphics.display.height * 0.75) - 3),
    text_color=TEAM_1_COLOR,
            score, max_score))

    # every time `interval_seconds` passes
    def on_interval(self, score):
        print()
        print("------------------------------")
        print("send motion data with score {}".format(score))
        print("------------------------------")
        print()
        self.client.send_data(self.feed_key, score)
        self.logger.info(score)
        # TODO: signal data sent with LEDs <here>


## setup Adafruit IO client
ADAFRUIT_IO_USERNAME = secrets.get("ADAFRUIT_IO_USERNAME")
ADAFRUIT_IO_KEY = secrets.get("ADAFRUIT_IO_KEY")
if ADAFRUIT_IO_USERNAME == None or ADAFRUIT_IO_KEY == None:
    print(
        "make sure ADAFRUIT_IO_USERNAME and ADAFRUIT_IO_KEY are set in secrets.py:"
    )
    print("")
    print("""
        secrets = {
            'ADAFRUIT_IO_USERNAME': '******',
            'ADAFRUIT_IO_KEY': 'io key'"
        }""")
    print("")
    exit(1)
aio = data_sender.DataSender(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY, debug=True)
Beispiel #9
0
def analyze_person(name, depth, require_strict_name_match=True):
    # Vi slutter søgningen hvis vi allerede har undersøgt personen, eller hvis vi er kommet for dybt
    if depth < 0:
        return;
    
    if name in name_cache and name_cache[name].scraped == True:
        try:
            if name_cache.get(name).scrape_depth >= depth:
                print("%s already in cache with a higher scrape depth [%d] than our current [%d], not iterating" % (name, name_cache.get(name).scrape_depth, depth))
                return name_cache.get(name)
        except AttributeError:
            #Turns out it didn't have a scrape_depth recorded, just redo it
            pass
            
    sanitized_name = name.replace(" ", "+").lower()

    cur_page = 1
    number_of_pages = 9999

    if name not in name_cache:
        person_neo = Person()
        person_neo.name = name
    else:
        person_neo = name_cache.get(name)
        
    person_neo.scrape_depth = depth
    name_cache[name] = person_neo
    graph.create(person_neo)
    

    # Only iterate if we're actually interested in adding some nodes
    if depth > 0:
        while cur_page < number_of_pages:
            if secrets.get('api_token') is None:
                api_url = "https://api.opencorporates.com/officers/search?q=%s&page=%d" % (sanitized_name, cur_page)
            else:
                api_url = "https://api.opencorporates.com/officers/search?q=%s&page=%d&api_token=%s" % (sanitized_name, cur_page, secrets["api_token"])
                
            
            r = requests.get(api_url)
            # print(r.json())
            number_of_pages = int(r.json()["results"]["total_pages"])

            for officer in r.json()["results"]["officers"]:
                officer = officer["officer"]

                if require_strict_name_match and officer["name"] != name:
                    continue

                assert officer["name"] == name

                print("  %s --[%s]--> %s" % (officer["name"], officer["position"], officer["company"]["name"]))

                # TODO: Check if the company has already been analyzed
                related_company = analyze_company(officer["company"]["jurisdiction_code"], officer["company"]["company_number"], depth - 1)

                if related_company is not None:
                    relation_label = officer["position"]
                    relation = Relationship(person_neo.__node__, officer["position"].upper(), related_company.__node__)
                    graph.create(relation)

            cur_page += 1

    person_neo.scraped = True
    graph.push(person_neo)
    return person_neo
Beispiel #10
0
def analyze_company(jurisdiction, cvr, depth):
    cvr_shorthand = "%s%s"%(jurisdiction,cvr)
    
    if depth < 0:
        return

    if cvr_shorthand in company_cache and company_cache[cvr_shorthand].scraped == True:
        try:
            if  company_cache.get(cvr_shorthand).scrape_depth >= depth:
                print("%s in already cache with a higher scrape depth [%d] than our current [%d], not iterating" % (company_cache.get(cvr_shorthand).name, company_cache.get(cvr_shorthand).scrape_depth, depth))
                return company_cache.get(cvr_shorthand)
        except AttributeError:
            #Turns out it didn't have a recorded scrape_depth, let's just redo it
            pass

        
    # get the company
    if secrets.get('api_token') is None:
        r = requests.get("https://api.opencorporates.com/companies/%s/%s" % (jurisdiction, cvr))
    else:
        r = requests.get("https://api.opencorporates.com/companies/%s/%s?api_token=%s" % (jurisdiction, cvr, secrets.get('api_token')))
        
    company_json_obj = r.json()["results"]["company"]
    # print(company_json_obj)

    if cvr_shorthand not in company_cache:
        company_neo = Company.from_oc(company_json_obj)
        print(colored("New company: %s" % company_neo.name, 'green'))
    else:
        company_neo = company_cache[cvr_shorthand]

    company_neo.scrape_depth = depth
    
    company_cache["%s%s" %(jurisdiction,cvr)] = company_neo
    graph.create(company_neo)

    
    # Only iterate if we're actually interested in adding some nodes
    if depth > 0:
        for officer in company_json_obj["officers"]:
            officer = officer["officer"]
            print("%s <--[%s]-- %s" % (company_json_obj["name"], officer["position"], officer["name"]))

            person_or_company = p_or_c_cache.get(officer["name"], None)
            while person_or_company != 'p' \
                  and person_or_company != 'c' \
                      and person_or_company != 'i':
                person_or_company = input(colored("-> Is %s a person or a company, or should the relation be ignored? p/c/i  " % officer["name"], 'red')).strip()

            # save it in the cache
            p_or_c_cache[officer["name"]] = person_or_company
            update_pickle_cache()

            if person_or_company == 'p':
                person = analyze_person(officer["name"], depth - 1)

                if person is not None:
                    # Create a relation
                    relation_label = officer["position"]
                    relation = Relationship(person.__node__, relation_label.upper(), company_neo.__node__)
                    graph.create(relation)

            elif person_or_company == 'c':
                print("Trying to find company %s" % officer["name"])
                r_jurisdiction, r_cvr = resolve_company(officer["name"])

                if r_cvr is not None:
                    print("Found it... analyzing")
                    related_company = analyze_company(r_jurisdiction, r_cvr, depth-1)

                    if related_company is not None:
                        relation_label = officer["position"]
                        relation = Relationship(related_company.__node__, relation_label.upper(), company_neo.__node__)
                        graph.create(relation)
                else:
                    print("Could not find company %s" % officer["name"])

    company_neo.scraped = True
    graph.push(company_neo)
    return company_neo
Beispiel #11
0
while True:
    if (time.monotonic() - LAST_SYNC) > 3600:  # Sync time once an hour
        MAGTAG.network.get_local_time()
        LAST_SYNC = time.monotonic()
        # Sun API requires a valid UTC offset. Adafruit IO's time API
        # offers this, but get_local_time() above (using AIO) doesn't
        # store it anywhere. I’ll put in a feature request for the
        # PortalBase library, but in the meantime this just makes a
        # second request to the time API asking for that one value.
        # Since time is synced only once per hour, the extra request
        # isn't particularly burdensome.
        try:
            RESPONSE = MAGTAG.network.requests.get(
                'https://io.adafruit.com/api/v2/%s/integrations/time/'
                'strftime?x-aio-key=%s&tz=%s' %
                (secrets.get('aio_username'), secrets.get('aio_key'),
                 secrets.get('timezone')) + '&fmt=%25z')
            if RESPONSE.status_code == 200:
                # Arrives as sHHMM, convert to sHH:MM
                print(RESPONSE.text)
                UTC_OFFSET = RESPONSE.text[:3] + ':' + RESPONSE.text[-2:]
        except:  # pylint: disable=bare-except
            # If query fails, prior value is kept until next query.
            # Only changes 2X a year anyway -- worst case, if these
            # events even align, is rise/set is off by an hour.
            pass

    NOW = time.localtime()  # Current time (as time_struct)

    # If minute has changed, refresh display
    if LAST_MINUTE != NOW.tm_min:
Beispiel #12
0
import rtc
from adafruit_display_shapes.rect import Rect
from adafruit_magtag.magtag import MagTag
from produce import Produce


# CONFIGURABLE SETTINGS and ONE-TIME INITIALIZATION ------------------------

TWELVE_HOUR = True # If set, show 12-hour vs 24-hour (e.g. 3:00 vs 15:00)
DD_MM = False      # If set, show DD/MM instead of MM/DD dates
# Location of produce data (file:// or http:// or https://):
JSON_URL = 'https://raw.githubusercontent.com/adafruit/Adafruit_Learning_System_Guides/master/MagTag_Seasonal_Produce/produce.json'

# Location is configured in secrets.py. If location is not contained there,
# default value below will be used.
LOCATION = secrets.get('location', 'NY') # default to 'NY'

PRODUCE = Produce(JSON_URL, LOCATION)
MAGTAG = MagTag(rotation=0) # Portrait (vertical) display


# SOME UTILITY FUNCTIONS ---------------------------------------------------

def hh_mm(time_struct, twelve_hour=True):
    """ Given a time.struct_time, return a string as H:MM or HH:MM, either
        12- or 24-hour style depending on twelve_hour flag.
    """
    if twelve_hour:
        if time_struct.tm_hour > 12:
            hour_string = str(time_struct.tm_hour - 12) # 13-23 -> 1-11 (pm)
        elif time_struct.tm_hour > 0:
while True:
    if (time.monotonic() - LAST_SYNC) > 3600: # Sync time once an hour
        MAGTAG.network.get_local_time()
        LAST_SYNC = time.monotonic()
        # Sun API requires a valid UTC offset. Adafruit IO's time API
        # offers this, but get_local_time() above (using AIO) doesn't
        # store it anywhere. I’ll put in a feature request for the
        # PortalBase library, but in the meantime this just makes a
        # second request to the time API asking for that one value.
        # Since time is synced only once per hour, the extra request
        # isn't particularly burdensome.
        try:
            RESPONSE = MAGTAG.network.requests.get(
                'https://io.adafruit.com/api/v2/%s/integrations/time/'
                'strftime?x-aio-key=%s&tz=%s' % (secrets.get('aio_username'),
                                                 secrets.get('aio_key'),
                                                 secrets.get('timezone')) +
                '&fmt=%25z')
            if RESPONSE.status_code == 200:
                # Arrives as sHHMM, convert to sHH:MM
                print(RESPONSE.text)
                UTC_OFFSET = RESPONSE.text[:3] + ':' + RESPONSE.text[-2:]
        except: # pylint: disable=bare-except
            # If query fails, prior value is kept until next query.
            # Only changes 2X a year anyway -- worst case, if these
            # events even align, is rise/set is off by an hour.
            pass

    NOW = time.localtime() # Current time (as time_struct)
Beispiel #14
0
ts = adafruit_touchscreen.Touchscreen(board.TOUCH_XL,
                                      board.TOUCH_XR,
                                      board.TOUCH_YD,
                                      board.TOUCH_YU,
                                      calibration=((7000, 59600), (8000,
                                                                   57100)),
                                      size=(320, 240))

pixels = neopixel.NeoPixel(board.D4, 60, brightness=.8, auto_write=False)
pixels.fill((0, 0, 0))
pixels.show()

# Set up where we'll be fetching data from
DARKSKY_API = "https://api.darksky.net/forecast/%s/%g,%g?units=us&lang=en&exclude=minutely,hourly,alerts,flags"  # NOQA

darksky = DARKSKY_API % (secrets.get(
    'darksky_key', 'KEYMISSING'), secrets.get('latitude',
                                              0), secrets.get('longitude', 0))
# the current working directory (where this file is)
cwd = ("/" + __file__).rsplit('/', 1)[0]
pyportal = PyPortal(url=darksky,
                    json_path=[],
                    status_neopixel=board.NEOPIXEL,
                    default_bg=cwd + "/pyportal_startup.bmp")

last_weather = 0
last_time = 0
last_flip = 0

pixel_around()

pyportal.set_background(cwd + "/pyportal_startup2.bmp")
            (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")


def _parse_temperature_house(topic, message):
    gfx.display_inside_temp(int(message))
    _inc_counter("inside_temp")


mqtt_topic = secrets.get("topic_prefix") or "/pyportal"
mqtt_pub_temperature = f"{mqtt_topic}/temperature"
mqtt_pub_light = f"{mqtt_topic}/light"
mqtt_pub_status = f"{mqtt_topic}/status"

mqtt_subs = {
    f"{mqtt_topic}/ping": _parse_ping,
    f"{mqtt_topic}/brightness": _parse_brightness,
    f"{mqtt_topic}/neopixel": _parse_neopixel,
    f"{mqtt_topic}/blinkrate": _parse_blinkrate,
    "/openweather/raw": _parse_openweather_message,
    "/aio/local_time": _parse_localtime_message,
    "/sensor/temperature_house": _parse_temperature_house,
}

Beispiel #16
0
# Add a secrets.py to your filesystem that has a dictionary called secrets with "ssid" and
# "password" keys with your WiFi credentials. DO NOT share that file or commit it into Git or other
# source control.
# pylint: disable=no-name-in-module,wrong-import-order
try:
    from secrets import secrets
except ImportError:
    print(
        "Credentials and tokens are kept in secrets.py, please add them there!"
    )
    raise

# Get our username, key and desired timezone
aio_username = secrets["aio_username"]
aio_key = secrets["aio_key"]
location = secrets.get("timezone", None)
TIME_URL = (
    "https://io.adafruit.com/api/v2/%s/integrations/time/strftime?x-aio-key=%s"
    % (aio_username, aio_key))
TIME_URL += "&fmt=%25H%3A%25M"

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

pool = socketpool.SocketPool(wifi.radio)
requests = adafruit_requests.Session(pool, ssl.create_default_context())

endpoint = (
    "https://covid.cdc.gov/covid-data-tracker/COVIDData/getAjaxData?id=vaccination_data"
)
import cv2
# from sklearn.cluster import KMeans
import random
import pyaudio

#####################
## Adafruit IO
#####################
from Adafruit_IO import Client
from datetime import datetime
from secrets import secrets

# local help libraries
from utils import identity

ADAFRUIT_IO_USERNAME = secrets.get('ADAFRUIT_IO_USERNAME')
ADAFRUIT_IO_KEY = secrets.get('ADAFRUIT_IO_KEY')

if ADAFRUIT_IO_USERNAME == None or ADAFRUIT_IO_KEY == None:
    print("make sure ADAFRUIT_IO_USERNAME and ADAFRUIT_IO_KEY are set in secrets.py:")
    print("")
    print("  secrets = {'ADAFRUIT_IO_USERNAME': '******', 'ADAFRUIT_IO_KEY': 'io key'}")
    print("")
    exit(1)

## setup Adafruit IO client
aio = Client(ADAFRUIT_IO_USERNAME, ADAFRUIT_IO_KEY)
monitor = aio.feeds('monitor')

message = "starting adafruit IO check on {}".format(identity.get_identity())
print(message)