io.on_disconnect = disconnected
io.on_message = message

# Connect to Adafruit IO
io.connect()

# Set data
data_value = 42

# Set up metadata associated with data_value
# lat, lon, ele
metadata = "40.726190, -74.005334, -6"

# Send data and location metadata to the 'location' feed
print("Sending data and location metadata to IO...")
io.publish("location", data_value, metadata)
print("Data sent!")

# Start a blocking message loop...
# NOTE: NO code below this loop will execute
# NOTE: Network reconnection is handled within this loop
while True:
    try:
        io.loop()
    except (ValueError, RuntimeError) as e:
        print("Failed to get data, retrying\n", e)
        wifi.reset()
        io.reconnect()
        continue
    time.sleep(1)
class Network(NetworkBase):
    """Class representing the Adafruit FunHouse.

    :param status_dotstar: The initialized object for status DotStar. Defaults to ``None``,
                           to not use the status LED
    :param bool extract_values: If true, single-length fetched values are automatically extracted
                                from lists and tuples. Defaults to ``True``.
    :param debug: Turn on debug print outs. Defaults to False.

    """

    # pylint: disable=too-many-instance-attributes, too-many-locals, too-many-branches, too-many-statements
    def __init__(
        self,
        *,
        status_dotstar=None,
        extract_values=True,
        debug=False,
    ):
        super().__init__(
            WiFi(status_dotstar=status_dotstar),
            extract_values=extract_values,
            debug=debug,
        )
        self._mqtt_client = None

    def init_io_mqtt(self):
        """Initialize MQTT for Adafruit IO"""
        try:
            aio_username = self._secrets["aio_username"]
            aio_key = self._secrets["aio_key"]
        except KeyError:
            raise KeyError(
                "Adafruit IO secrets are kept in secrets.py, please add them there!\n\n"
            ) from KeyError

        return self.init_mqtt(IO_MQTT_BROKER, 8883, aio_username, aio_key, True)

    # pylint: disable=too-many-arguments
    def init_mqtt(
        self,
        broker,
        port=8883,
        username=None,
        password=None,
        use_io=False,
    ):
        """Initialize MQTT"""
        self.connect()
        self._mqtt_client = MQTT.MQTT(
            broker=broker,
            port=port,
            username=username,
            password=password,
            socket_pool=self._wifi.pool,
            ssl_context=ssl.create_default_context(),
        )
        if use_io:
            self._mqtt_client = IO_MQTT(self._mqtt_client)

        return self._mqtt_client

    # pylint: enable=too-many-arguments

    def _get_mqtt_client(self):
        print(self._mqtt_client)
        if self._mqtt_client is not None:
            return self._mqtt_client
        raise RuntimeError("Please initialize MQTT before using")

    def mqtt_loop(self, *args, suppress_mqtt_errors=True, **kwargs):
        """Run the MQTT Loop"""
        self._get_mqtt_client()
        if suppress_mqtt_errors:
            try:
                if self._mqtt_client is not None:
                    self._mqtt_client.loop(*args, **kwargs)
            except MQTT.MMQTTException as err:
                print("MMQTTException: {0}".format(err))
            except OSError as err:
                print("OSError: {0}".format(err))
        else:
            if self._mqtt_client is not None:
                self._mqtt_client.loop(*args, **kwargs)

    def mqtt_publish(self, *args, suppress_mqtt_errors=True, **kwargs):
        """Publish to MQTT"""
        self._get_mqtt_client()
        if suppress_mqtt_errors:
            try:
                if self._mqtt_client is not None:
                    self._mqtt_client.publish(*args, **kwargs)
            except OSError as err:
                print("OSError: {0}".format(err))
        else:
            if self._mqtt_client is not None:
                self._mqtt_client.publish(*args, **kwargs)

    def mqtt_connect(self, *args, **kwargs):
        """Connect to MQTT"""
        self._get_mqtt_client()
        if self._mqtt_client is not None:
            self._mqtt_client.connect(*args, **kwargs)

    @property
    def on_mqtt_connect(self):
        """
        Get or Set the MQTT Connect Handler

        """
        if self._mqtt_client:
            return self._mqtt_client.on_connect
        return None

    @on_mqtt_connect.setter
    def on_mqtt_connect(self, value):
        self._get_mqtt_client()
        self._mqtt_client.on_connect = value

    @property
    def on_mqtt_disconnect(self):
        """
        Get or Set the MQTT Disconnect Handler

        """
        if self._mqtt_client:
            return self._mqtt_client.on_disconnect
        return None

    @on_mqtt_disconnect.setter
    def on_mqtt_disconnect(self, value):
        self._get_mqtt_client().on_disconnect = value

    @property
    def on_mqtt_subscribe(self):
        """
        Get or Set the MQTT Subscribe Handler

        """
        if self._mqtt_client:
            return self._mqtt_client.on_subscribe
        return None

    @on_mqtt_subscribe.setter
    def on_mqtt_subscribe(self, value):
        self._get_mqtt_client().on_subscribe = value

    @property
    def on_mqtt_unsubscribe(self):
        """
        Get or Set the MQTT Unsubscribe Handler

        """
        if self._mqtt_client:
            return self._mqtt_client.on_unsubscribe
        return None

    @on_mqtt_unsubscribe.setter
    def on_mqtt_unsubscribe(self, value):
        self._get_mqtt_client().on_unsubscribe = value

    @property
    def on_mqtt_message(self):
        """
        Get or Set the MQTT Message Handler

        """
        if self._mqtt_client:
            return self._mqtt_client.on_message
        return None

    @on_mqtt_message.setter
    def on_mqtt_message(self, value):
        self._get_mqtt_client().on_message = value

    @property
    def enabled(self):
        """
        Return whether the WiFi is enabled

        """
        return self._wifi.enabled
    fill_water(moisture_percentage)
    print("disp filled..")

    print("temp: " + str(temp) + "  moisture: " + str(moisture))

    # Play water level alarms
    if moisture <= SOIL_LEVEL_MIN:
        print("Playing low water level warning...")
        pyportal.play_file(wav_water_low)
    elif moisture >= SOIL_LEVEL_MAX:
        print("Playing high water level warning...")
        pyportal.play_file(wav_water_high)


    if now - initial > (DELAY_PUBLISH * 60):
        try:
            print("Publishing data to Adafruit IO...")
            label_status.text = "Sending to IO..."
            io.publish("moisture", moisture)
            io.publish("temperature", temp)
            print("Published")
            label_status.text = "Data Sent!"

            # reset timer
            initial = now
        except (ValueError, RuntimeError) as e:
            label_status.text = "ERROR!"
            print("Failed to get data, retrying...\n", e)
            wifi.reset()
    time.sleep(DELAY_SENSOR)
Beispiel #4
0
# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()

# Subscribe to all messages on the led feed
io.subscribe("led")

prv_refresh_time = 0.0
while True:
    # Poll for incoming messages
    try:
        io.loop()
    except (ValueError, RuntimeError) as e:
        print("Failed to get data, retrying\n", e)
        wifi.reset()
        io.reconnect()
        continue
    # Send a new temperature reading to IO every 30 seconds
    if (time.monotonic() - prv_refresh_time) > 30:
        # take the cpu's temperature
        cpu_temp = cpu.temperature
        # truncate to two decimal points
        cpu_temp = str(cpu_temp)[:5]
        print("CPU temperature is %s degrees C" % cpu_temp)
        # publish it to io
        print("Publishing %s to temperature feed..." % cpu_temp)
        io.publish("temperature", cpu_temp)
        print("Published!")
        prv_refresh_time = time.monotonic()
                                             height=HEIGHT)

splash = displayio.Group(max_size=10)
display.show(splash)

digital_label = label.Label(terminalio.FONT,
                            text="Battery Percent: ",
                            color=0xFFFFFF,
                            x=4,
                            y=4)
splash.append(digital_label)
alarm_label = label.Label(terminalio.FONT,
                          text="Voltage: ",
                          color=0xFFFFFF,
                          x=4,
                          y=14)
splash.append(alarm_label)

sensor = LC709203F(board.I2C())

start = 0
while True:
    io.loop()
    percent = sensor.cell_percent
    if time.time() - start > 60:
        io.publish("battery", int(percent))
        start = time.time()
    splash[0].text = f"Percent: {str(int(percent))}%"
    splash[1].text = f"Voltage: {str(sensor.cell_voltage)}"
    time.sleep(1)
Beispiel #6
0
    username=secrets["aio_user"],
    password=secrets["aio_key"],
)

# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)

# Connect the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_disconnect = disconnected
io.on_subscribe = subscribe
io.on_unsubscribe = unsubscribe
io.on_message = message

# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()

# Below is an example of manually publishing a new  value to Adafruit IO.
last = 0
print("Publishing a new message every 10 seconds...")
while True:
    # Explicitly pump the message loop.
    io.loop()
    # Send a new message every 10 seconds.
    if (time.monotonic() - last) >= 5:
        value = randint(0, 100)
        print("Publishing {0} to DemoFeed.".format(value))
        io.publish("DemoFeed", value)
        last = time.monotonic()
Beispiel #7
0
class DataWarehouse():
    SECRETS_REQUIRED = ("ssid", "password", "aio_username", "aio_key")

    def __init__(
            self,
            secrets_,
            *,
            esp01_pins=[],
            esp01_uart=None,
            esp01_baud=115200,
            pub_prefix="",
            debug=False  ### pylint: disable=redefined-outer-name
    ):

        if esp01_uart:
            self.esp01_uart = esp01_uart
        else:
            self.esp01_uart = busio.UART(*esp01_pins,
                                         receiver_buffer_size=2048)

        self.debug = debug
        self.esp = adafruit_espatcontrol.ESP_ATcontrol(self.esp01_uart,
                                                       esp01_baud,
                                                       debug=debug)
        self.esp_version = ""
        self.wifi = None
        try:
            _ = [secrets_[key] for key in self.SECRETS_REQUIRED]
        except KeyError:
            raise RuntimeError("secrets.py must contain: " +
                               " ".join(self.SECRETS_REQUIRED))
        self.secrets = secrets_
        self.io = None
        self.pub_prefix = pub_prefix
        self.pub_name = {}
        self.init_connect()

    def init_connect(self):
        self.esp.soft_reset()

        self.wifi = adafruit_espatcontrol_wifimanager.ESPAT_WiFiManager(
            self.esp, self.secrets)
        ### A few retries here seems to greatly improve reliability
        for _ in range(4):
            if self.debug:
                print("Connecting to WiFi...")
            try:
                self.wifi.connect()
                self.esp_version = self.esp.get_version()
                if self.debug:
                    print("Connected!")
                break
            except (RuntimeError, TypeError,
                    adafruit_espatcontrol.OKError) as ex:
                if self.debug:
                    print("EXCEPTION: Failed to publish()", repr(ex))
                time.sleep(RECONNECT_SLEEP)

        ### This uses global variables
        socket.set_interface(self.esp)

        ### MQTT Client
        ### pylint: disable=protected-access
        self.mqtt_client = MQTT.MQTT(broker="io.adafruit.com",
                                     username=self.secrets["aio_username"],
                                     password=self.secrets["aio_key"],
                                     socket_pool=socket,
                                     ssl_context=MQTT._FakeSSLContext(
                                         self.esp))
        self.io = IO_MQTT(self.mqtt_client)
        ### Callbacks of interest on io are
        ### on_connect on_disconnect on_subscribe
        self.io.connect()

    def reset_and_reconnect(self):
        self.wifi.reset()
        self.io.reconnect()

    def update_pub_name(self, field_name):
        pub_name = self.pub_prefix + field_name
        return pub_name

    def poll(self):
        dw_poll_ok = False
        try_reconnect = False
        for _ in range(2):
            try:
                ### Process any incoming messages
                if try_reconnect:
                    self.reset_and_reconnect()
                    try_reconnect = False
                self.io.loop()
                dw_poll_ok = True
            except (ValueError, RuntimeError, AttributeError,
                    MQTT.MMQTTException, adafruit_espatcontrol.OKError,
                    AdafruitIO_MQTTError) as ex:
                if self.debug:
                    print("EXCEPTION: Failed to get data in loop()", repr(ex))
                try_reconnect = True

        return dw_poll_ok

    def publish(self, p_data, p_fields):
        ok = [False] * len(p_fields)
        try_reconnect = False
        if self.debug:
            print("publish()")

        for idx, field_name in enumerate(p_fields):
            try:
                pub_name = self.pub_name[field_name]
            except KeyError:
                pub_name = self.update_pub_name(field_name)
            for _ in range(2):
                try:
                    if try_reconnect:
                        self.reset_and_reconnect()
                        try_reconnect = False
                    self.io.publish(pub_name, p_data[field_name])
                    ok[idx] = True
                    break
                except (ValueError, RuntimeError, AttributeError,
                        MQTT.MMQTTException, adafruit_espatcontrol.OKError,
                        AdafruitIO_MQTTError) as ex:
                    if self.debug:
                        print("EXCEPTION: Failed to publish()", repr(ex))
                    try_reconnect = True
                    time.sleep(RECONNECT_SLEEP)

        return all(ok)
Beispiel #8
0
io = IO_MQTT(mqtt_client)

# Connect the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_disconnect = disconnected
io.on_message = message

# Group name
group_name = "weatherstation"

# Feeds within the group
temp_feed = "weatherstation.temperature"
humid_feed = "weatherstation.humidity"

# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()

print("Publishing new messages to group feeds every 5 seconds...")

while True:
    io.loop()
    temp_reading = randint(0, 100)
    print("Publishing value {0} to feed: {1}".format(temp_reading, temp_feed))
    io.publish(temp_feed, temp_reading)

    humid_reading = randint(0, 100)
    print("Publishing value {0} to feed: {1}".format(humid_reading, humid_feed))
    io.publish(humid_feed, humid_reading)
    time.sleep(5)
print("Connecting to WIFI")
wifi.radio.connect(secrets["ssid"], secrets["password"])
pool = socketpool.SocketPool(wifi.radio)

print("Connecting to Adafruit IO")
mqtt_client = MQTT.MQTT(
    broker="io.adafruit.com",
    username=secrets["aio_username"],
    password=secrets["aio_key"],
    socket_pool=pool,
    ssl_context=ssl.create_default_context(),
)
mqtt_client.connect()
io = IO_MQTT(mqtt_client)
# Blank out any previously published message
io.publish(feed_name, "\ufeff")

qrdecoder = qrio.QRDecoder(cam.width, cam.height)
bitmap = displayio.Bitmap(cam.width, cam.height, 65536)

# Create a greyscale palette
pal = displayio.Palette(256)
for i in range(256):
    pal[i] = 0x10101 * i

label = Label(
    font=FONT,
    text="Scan QR Code...",
    color=0xFFFFFF,
    background_color=0x0,
    padding_top=2,
# Set up the callback methods above
io.on_connect = connected
io.on_message = message

timestamp = 0
while True:
    try:
        # If Adafruit IO is not connected...
        if not io.is_connected:
            # Connect the client to the MQTT broker.
            print("Connecting to Adafruit IO...")
            io.connect()

        # Explicitly pump the message loop.
        io.loop()
        # Obtain the "random" value, print it and publish it to Adafruit IO every 10 seconds.
        if (time.monotonic() - timestamp) >= 10:
            random_number = "{}".format(randint(0, 255))
            print("Current 'random' number: {}".format(random_number))
            io.publish("random", random_number)
            timestamp = time.monotonic()

    # Adafruit IO fails with internal error types and WiFi fails with specific messages.
    # This except is broad to handle any possible failure.
    except Exception as e:  # pylint: disable=broad-except
        print("Failed to get or send data, or connect. Error:", e,
              "\nBoard will hard reset in 30 seconds.")
        time.sleep(30)
        microcontroller.reset()
# Initialize MQTT interface with the esp interface
MQTT.set_socket(socket, esp)

# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
    broker="io.adafruit.com",
    username=secrets["aio_username"],
    password=secrets["aio_key"],
)

# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)

# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()

while True:
    switch.update()
    print(switch.state)

    if switch.rose:
        print("Door is open")
        io.publish("door", 0)
        print("sent")

    if switch.fell:
        print("Door is closed")
        io.publish("door", 1)
        print("sent")
Beispiel #12
0
magtag.add_text(
    text_position=(50, (2 * 128) / 4,), text_scale=2,
)

magtag.add_text(
    text_position=(50, (3 * 128) / 4,), text_scale=2,
)

temperature, relative_humidity = sht.measurements
magtag.set_text("Temperature: %0.1f C" % temperature, 0, False)
magtag.set_text("Humidity: %0.1f %%" % relative_humidity, 1, False)
T = temperature * 1.8 + 32
humidity = relative_humidity
HI = (
    -42.379
    + 2.04901523 * T
    + 10.14333127 * humidity
    - 0.22475541 * T * humidity
    - 0.00683783 * T * T
    - 0.05481717 * humidity ** 2
    + 0.00122874 * T * T * humidity
    + 0.00085282 * T * humidity ** 2
    - 0.00000199 * T * T * humidity ** 2
)
magtag.set_text("Feels like: %0.1f F" % HI, 2)
if connected:
    io.publish("temperature", temperature)
    io.publish("humidity", relative_humidity)
    io.publish("heatindex", HI)
magtag.exit_and_deep_sleep(600)
io.on_message = message

# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()
plant_feed = "plant"

START = 0

while True:
    # read moisture level through capacitive touch pad
    touch = seesaw.moisture_read()

    # read temperature from the temperature sensor
    temp = seesaw.get_temp()

    if touch < MIN:
        if not LOW:
            io.publish(plant_feed, touch)
            print("published")
        LOW = True

    elif touch >= MIN and time.time() - START > 10:
        io.publish(plant_feed, touch)
        print("published to Adafruit IO")
        START = time.time()
        LOW = False

    print("temp: " + str(temp) + "  moisture: " + str(touch))
    time.sleep(1)
# Initialize an Adafruit IO MQTT Client
io = IO_MQTT(mqtt_client)

# Connect the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_disconnect = disconnected
io.on_subscribe = subscribe
io.on_unsubscribe = unsubscribe
io.on_message = message

io.add_feed_callback("alarm-clock.alarm", on_alarm)

# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()

io.get("alarm-clock.alarm")

LAST = 0
while True:
    io.loop()
    if ALARM and time.monotonic() - LAST >= 0.2:
        led.value = not led.value
        LAST = time.monotonic()
    if btn1.value:
        io.publish("alarm-clock.alarm", "False")
        led.value = False
        led.value = True
        time.sleep(1)
        led.value = False
Beispiel #15
0
# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()

START = 0
LOW = False

MIN = 500

while True:
    # read moisture level through capacitive touch pad
    touch = seesaw.moisture_read()

    # read temperature from the temperature sensor
    temp = seesaw.get_temp()

    if touch < MIN:
        if not LOW:
            io.publish("plant", touch)
            print("published")
        LOW = True

    elif touch >= MIN and time.time() - START > 10:
        io.publish("plant", touch)
        print("published to Adafruit IO")
        START = time.time()
        LOW = False

    print("temp: " + str(temp) + "  moisture: " + str(touch))
    time.sleep(1)