Example #1
0
def main() -> None:
    print("Connecting to %s" % SSID_NAME)
    try:
        wifi.radio.connect(SSID_NAME, SSID_PSW)
    except:
        magtag.exit_and_deep_sleep(2)
    print("Connected to %s!" % SSID_NAME)
    print("My IP address is", wifi.radio.ipv4_address)

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

    print("Fetching json from", WEATHER_URL)

    response = requests.get(WEATHER_URL)

    if response.status_code < 200 or response.status_code >= 300:
        if response.status_code == 500:
            set_text("Got 500 status! Kuuki might be down!", 0)

        magtag.exit_and_deep_sleep(60)

    json_dict = response.json()

    set_text(json_dict["TimeData"] + "\n" + \
             "Temperature: " + str(json_dict["Temp"]) + " C\n" + \
             "Humidity: " + str(json_dict["Humid"]) + " %\n" + \
             "Air Pressure: " + str(json_dict["AirPressure"]) + "\n" + \
             "PM25Standard/Env: " + str(json_dict["PM25Standard"]) + " / " + str(json_dict["PM25Env"]) + "\n" + \
             "PM100Standard/Env: " + str(json_dict["PM100Standard"]) + " / " + str(json_dict["PM100Env"]), 0)

    magtag.exit_and_deep_sleep(60)
Example #2
0
def connect_mqtt():
    # Create a socket pool
    pool = socketpool.SocketPool(wifi.radio)

    # Set up a MiniMQTT Client
    mqtt_client = MQTT.MQTT(
        broker=secrets["mqtt_broker"],
        port=port,
        socket_pool=pool,
        ssl_context=None,
    )

    # Setup the callback methods above
    mqtt_client.on_connect = on_connect
    mqtt_client.on_disconnect = on_disconnect
    mqtt_client.on_message = on_message

    # Connect the client to the MQTT broker.
    print("Connecting to MQTT Broker...")
    # set will message to track status of client disconnects
    mqtt_client.will_set(will_status_topic, time.time(), 2, True)

    try:
        mqtt_client.connect()
        print('mqtt client status = ', mqtt_client.is_connected())
    except Exception as sensor_err:
        return 'mqtt_client not connected'

    mqtt_client.publish(will_status_topic, 1, 2, True)
    mqtt_client.connected_flag = False  # create flags
    mqtt_client.bad_connection_flag = False  #
    mqtt_client.retry_count = 0  #

    return mqtt_client
def post_data(msg):
    try:
        socket = socketpool.SocketPool(wifi.radio)
        https = requests.Session(socket, ssl.create_default_context())
        response = https.post(JSON_POST_URL, data=data)
        json_resp = response.json()
    except Exception as e:
        print("Exception in post_data ", str(e))
        uart.write(bytearray("\n\rException in post_data " + str(e)))
        alarm_deepSleep(2)
Example #4
0
    def connect(self, ssid, password):
        """
        Connect to the WiFi Network using the information provided

        :param ssid: The WiFi name
        :param password: The WiFi password

        """
        wifi.radio.connect(ssid, password)
        pool = socketpool.SocketPool(wifi.radio)
        self.requests = adafruit_requests.Session(pool,
                                                  ssl.create_default_context())
        self._connected = True
def connect_wifi(verbose=False):
    global socket_pool
    import wifi
    import socketpool
    try:
        from secrets import secrets
    except ImportError:
        log_info("WiFi secrets are kept in secrets.py, please add them there!")
        raise
    if verbose:
        log_info("Connecting to ", secrets["ssid"])
    wifi.radio.connect(ssid=secrets["ssid"], password=secrets["password"])
    socket_pool = socketpool.SocketPool(wifi.radio)
    if verbose:
        log_info("Connected with IP ", wifi.radio.ipv4_address)
Example #6
0
def initialise_wifi():
    """
    Connect to WiFi as configured in `secrets.py`
    """
    print("Initialising WiFi ...")
    try:
        from secrets import secrets
    except ImportError:
        print("WiFi secrets are kept in secrets.py, please add them there!")
        raise

    wifi.radio.connect(secrets["ssid"], secrets["password"])
    pool = socketpool.SocketPool(wifi.radio)
    requests = adafruit_requests.Session(pool, ssl.create_default_context())
    print("Initialising WiFi ... {} connected".format(secrets['ssid']))
    return(requests)
Example #7
0
 def __init__(self, app_id, password, tenant_id, subscription_id):
     """
     Parameters:
     -----------
     app_id : str
         The application id from Azure
     password : str
         Secret generated by Azure for the application
     Tenant_id : str
         tenant id for the application
     subscription_id : str
         Azure subscription id
     """
     self._app_id = app_id
     self._password = password
     self._tenant_id = tenant_id
     self._subscription_id = subscription_id
     pool = socketpool.SocketPool(wifi.radio)
     self._https = requests.Session(pool, ssl.create_default_context())
Example #8
0
    def connect_wifi():

        print("FeatherS2 Wifi Request with Button Test")

        print("My MAC addr:", [hex(i) for i in wifi.radio.mac_address])

        print("Available WiFi networks:")
        for network in wifi.radio.start_scanning_networks():
            print(
                "\t%s\t\tRSSI: %d\tChannel: %d"
                % (str(network.ssid, "utf-8"), network.rssi, network.channel)
            )
        wifi.radio.stop_scanning_networks()

        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)

        return socketpool.SocketPool(wifi.radio)
Example #9
0
        return io.create_new_feed(feed_name)


# Send the data. Requires a feed name and a value to send.
def send_io_data(feed, value):
    return io.send_data(feed["key"], value)


# Wi-Fi connections can have issues! This ensures the code will continue to run.
try:
    # Connect to Wi-Fi
    wifi.radio.connect(secrets["ssid"], secrets["password"])
    print("Connected to {}!".format(secrets["ssid"]))
    print("IP:", wifi.radio.ipv4_address)

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

# Wi-Fi connectivity fails with error messages, not specific errors, so this except is broad.
except Exception as e:  # pylint: disable=broad-except
    print(e)
    go_to_sleep(60)

# Set your Adafruit IO Username and Key in secrets.py
# (visit io.adafruit.com if you need to create an account,
# or if you need your Adafruit IO key.)
aio_username = secrets["aio_username"]
aio_key = secrets["aio_key"]

# Initialize an Adafruit IO HTTP API object
io = IO_HTTP(aio_username, aio_key, requests)
Example #10
0
def get_new_request_session():
    if not attempt_wifi_connection():
        return "Couldn't connect to Wifi"

    pool = socketpool.SocketPool(wifi.radio)
    return adafruit_requests.Session(pool, ssl.create_default_context())
Example #11
0
def initialize_network_client():
    wifi.radio.connect(secrets["ssid"], secrets["password"])
    time.sleep(0.5)
    pool = socketpool.SocketPool(wifi.radio)
    return adafruit_requests.Session(pool, ssl.create_default_context())