def iot(self,type='mqtt',group='light-group',action=None,conn=None,disc=None):
        from adafruit_esp32spi import adafruit_esp32spi_wifimanager
        import adafruit_esp32spi.adafruit_esp32spi_socket as socket
        import adafruit_requests as requests
        from adafruit_io.adafruit_io import IO_HTTP

        from secrets import secrets
        from adafruit_io.adafruit_io import IO_MQTT
        from adafruit_minimqtt import MQTT
        if not self.hardware['ESP32']:
            raise
        if not action: action=self.message
        if not conn: conn=self.connected
        if not disc: disc=self.disconnected
        # try:
        requests.set_socket(socket,self._esp)
        self.WIFI = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(self._esp, secrets, status_pixel=None)
        self.group_name = group

        self.WIFI.connect()

        mqtt_client = MQTT(
        socket=socket,
        broker="io.adafruit.com",
        username=secrets["aio_username"],
        password=secrets["aio_key"],
        network_manager=self.WIFI
        )
        self.io = IO_MQTT(mqtt_client)
        self.io.on_connect = conn
        self.io.on_disconnect = disc
        self.io.on_message = action
        # else:
        #     return
        self.io.connect()
    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
Beispiel #3
0
    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()
Beispiel #4
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)
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")

# 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 the callback methods defined above to Adafruit IO
io.on_connect = connected
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"
Beispiel #6
0
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")

# 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 the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_disconnect = disconnected
io.on_subscribe = subscribe

# Set up a callback for the led feed
io.add_feed_callback("led", on_led_msg)

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

# Subscribe to all messages on the led feed
io.subscribe("led")
Beispiel #7
0
    # the new value.
    print("Feed {0} received new value: {1}".format(feed_id, payload))


# Initialize MQTT interface with the ethernet interface
MQTT.set_socket(socket, eth)

# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
    broker="io.adafruit.com",
    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...")
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")

# 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 the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_subscribe = subscribe
io.on_message = message

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

display_bus = displayio.I2CDisplay(board.I2C(), device_address=0x3C)

WIDTH = 128
HEIGHT = 32
BORDER = 2
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")

# 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:
Beispiel #10
0
    status_light.fill(color_tuple)

# connect to wifi
wifi.connect()

# initialize MQTT client
mqtt_client = MQTT(
    socket=socket,
    broker="io.adafruit.com",
    username=secrets["aio_username"],
    password=secrets["aio_key"],
    network_manager=wifi
)

# initialize an Adafruit IO MQTT client
io = IO_MQTT(mqtt_client)

# init. adt7410 # temperature sensor for data logging
i2c_bus = busio.I2C(board.SCL, board.SDA)
adt = adafruit_adt7410.ADT7410(i2c_bus, address=0x48)
adt.high_resolution = True

# connect callback methods for adafruit io mqtt
io.on_connect = connected
io.on_disconnect = disconnected
io.on_subscribe = subscribe
io.on_unsubscribe = unsubscribe
io.on_message = message

# connect to adafruits
io.connect()
Beispiel #11
0
    print("Connected to %s!" % secrets["ssid"])

    # Create a socket pool
    pool = socketpool.SocketPool(wifi.radio)

    # Initialize a new MQTT Client object
    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(),
    )

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

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

    connected = True
except ConnectionError:
    pass

i2c = busio.I2C(board.SCL, board.SDA)
sht = adafruit_sht4x.SHT4x(i2c)
print("Found SHT4x with serial number", hex(sht.serial_number))

sht.mode = adafruit_sht4x.Mode.NOHEAT_HIGHPRECISION
# Can also set the mode to enable heater
Beispiel #12
0
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")

# 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 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 = on_message

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

# Set up a message handler for the battery feed
io.add_feed_callback("enge-1216.digital", on_digital_msg)
io.add_feed_callback("enge-1216.alarm-time", on_time)
Beispiel #13
0

def subscribe(client, userdata, topic, granted_qos):
    # This method is called when the client subscribes to a new feed.
    print('Subscribed to {0} with QOS level {1}'.format(topic, granted_qos))


# pylint: disable=unused-argument
def disconnected(client):
    # Disconnected function will be called if the client disconnects
    # from the Adafruit IO MQTT broker.
    print("Disconnected from Adafruit IO!")


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

# Connect the callback methods defined above to the Adafruit IO MQTT Client
io.on_connect = connected
io.on_subscribe = subscribe
io.on_disconnect = disconnected

## Connect to Adafruit IO
#print("Connecting to Adafruit IO...")
#io.connect()
#label_status.text = " "
#print("Connected!")

fill_val = 0.0

print("Connecting to WiFi...")
wifi.connect()
print("Connected!")

# 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 the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_subscribe = subscribe
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
cam.colorspace = adafruit_ov2640.OV2640_COLOR_YUV

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,
Beispiel #16
0
# Connect to WiFi
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")

# 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_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_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...")
Beispiel #17
0
class DevBoard:
    def __init__(self):
        """
        Big init routine as the whole board is brought up.
        """
        self.hardware = {
            'SDcard': False,
            'ESP32': False,
            'Neopixel': False,
        }
        self.payload = None
        self.filename = ''
        # Define LEDs:
        self._led = digitalio.DigitalInOut(board.LED)
        self._led.switch_to_output()

        # Define battery voltage
        # self._vbatt = analogio.AnalogIn(board.BATTERY)

        # Define SPI,I2C,UART
        self._spi = busio.SPI(board.SCK, MOSI=board.MOSI, MISO=board.MISO)
        self._uart = busio.UART(board.TX2, board.RX2)

        # Define sdcard
        self._sdcs = digitalio.DigitalInOut(board.xSDCS)
        self._sdcs.direction = digitalio.Direction.OUTPUT
        self._sdcs.value = True

        # Initialize sdcard
        try:
            import adafruit_sdcard
            self._sd = adafruit_sdcard.SDCard(self._spi, self._sdcs)
            self._vfs = storage.VfsFat(self._sd)
            storage.mount(self._vfs, "/sd")
            sys.path.append("/sd")
            self.hardware['SDcard'] = True
        except Exception as e:
            print('[WARNING]', e)

        # Define ESP32
        self._esp_dtr = digitalio.DigitalInOut(board.DTR)
        self._esp_rts = digitalio.DigitalInOut(board.RTS)
        self._esp_cs = digitalio.DigitalInOut(board.TMS)  #GPIO14
        self._esp_rdy = digitalio.DigitalInOut(board.TCK)  #GPIO13
        self._esp_cs.direction = digitalio.Direction.OUTPUT
        self._esp_dtr.direction = digitalio.Direction.OUTPUT
        self._esp_rts.direction = digitalio.Direction.OUTPUT
        self._esp_cs.value = True
        self._esp_dtr.value = False
        self._esp_rts.value = False

        # Initialize Neopixel
        try:
            self.neopixel = neopixel.NeoPixel(board.NEOPIXEL,
                                              1,
                                              brightness=0.2,
                                              pixel_order=neopixel.GRB)
            self.neopixel[0] = (0, 0, 0)
            self.hardware['Neopixel'] = True
        except Exception as e:
            print('[WARNING]', e)

    def esp_init(self):
        from adafruit_esp32spi import adafruit_esp32spi
        # Initialize ESP32
        try:
            self._esp = adafruit_esp32spi.ESP_SPIcontrol(
                self._spi,
                self._esp_cs,
                self._esp_rdy,
                self._esp_rts,
                gpio0_pin=self._esp_dtr,
                debug=False)
            if self._esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
                self.hardware['ESP32'] = True
        except Exception as e:
            print('[WARNING]', e, '- have you programed the ESP32?')

    @property
    def temperature_cpu(self):
        return microcontroller.cpu.temperature  # Celsius

    @property
    def LED(self):
        return self._led.value

    @LED.setter
    def LED(self, value):
        self._led.value = value

    @property
    def RGB(self):
        return self.neopixel[0]

    @RGB.setter
    def RGB(self, value):
        if self.hardware['Neopixel']:
            try:
                self.neopixel[0] = value
            except Exception as e:
                print('[WARNING]', e)

    @property
    def brightness(self):
        return self.neopixel.brightness

    @brightness.setter
    def brightness(self, value):
        if self.hardware['Neopixel']:
            try:
                self.neopixel.brightness = value
            except Exception as e:
                print('[WARNING]', e)

    def unique_file(self):
        import os
        if not self.hardware['SDcard']:
            return False
        try:
            name = 'DATA_000'
            files = []
            for i in range(0, 50):
                _filename = name[:-2] + str(int(i / 10)) + str(int(
                    i % 10)) + '.txt'
                if _filename not in os.listdir('/sd/'):
                    with open('/sd/' + _filename, "a") as f:
                        time.sleep(0.01)
                    self.filename = '/sd/' + _filename
                    print('filename is:', self.filename)
                    return True
        except Exception as e:
            print('--- SD card error ---', e)
            self.RGB = (255, 0, 0)
            return False

    def save(self, dataset, savefile=None):
        if savefile == None:
            savefile = self.filename
        try:
            with open(savefile, "a") as file:
                for item in dataset:
                    for i in item:
                        if isinstance(i, float):
                            file.write(',{:.9E}'.format(i))
                        else:
                            file.write(',{}'.format(i))
                    file.write('\n')
        except Exception as e:
            print(e)

    def print_file(self, filedir):
        try:
            print('--- Printing File: {} ---'.format(filedir))
            with open(filedir, "r") as file:
                for line in file:
                    print(line.strip())
        except Exception as e:
            print('[WARNING]', e)

    def wheel(self, pos):
        # Input a value 0 to 255 to get a color value.
        # The colours are a transition r - g - b - back to r.
        if pos < 0 or pos > 255:
            r = g = b = 0
        elif pos < 85:
            r = int(pos * 3)
            g = int(255 - pos * 3)
            b = 0
        elif pos < 170:
            pos -= 85
            r = int(255 - pos * 3)
            g = 0
            b = int(pos * 3)
        else:
            pos -= 170
            r = 0
            g = int(pos * 3)
            b = int(255 - pos * 3)
        return (r, g, b)

    def rainbow(self):
        try:
            print('\n\tPress any key to stop')
            self.neopixel.auto_write = False
            while True:
                for j in range(255):
                    if supervisor.runtime.serial_bytes_available:
                        self.neopixel.auto_write = True
                        self.neopixel[0] = (0, 0, 0)
                        return
                    else:
                        pixel_index = (256 // 1) + j
                        self.neopixel[0] = self.wheel(pixel_index & 255)
                        self.neopixel.show()
                        time.sleep(0.1)
        except Exception as e:
            print('[WARNING]', e)
            self.neopixel.auto_write = True

    def battery_voltage(self):
        _voltage = self._vbatt.value * 3.3 / (2**16)
        _voltage = _voltage / 2  # voltage divider
        return _voltage  # in volts

    def esp_status(self):
        if self.hardware['ESP32']:
            try:
                if self._esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
                    print('\tESP32 is idle')
                else:
                    print('\t', self._esp.status)
            except Exception as e:
                print('[WARNING]', e)
        else:
            print('[WARNING] ESP32 not initialized')

    def ap_scan(self):
        if self.hardware['ESP32']:
            try:
                for ap in self._esp.scan_networks():
                    print("\t%s\tRSSI: %d" %
                          (str(ap['ssid'], 'utf-8'), ap['rssi']))
            except Exception as e:
                print('[WARNING]', e)
        else:
            print('[WARNING] ESP32 not initialized')

    def wifi(self, ssid, pswrd):
        if self.hardware['ESP32']:
            try:
                print("\tConnecting to AP...")
                while not self._esp.is_connected:
                    try:
                        self._esp.connect_AP(bytes(bytearray(ssid)),
                                             bytes(bytearray(pswrd)))
                    except RuntimeError as e:
                        print("\t\tCould not connect to AP, retrying: ", e)
                        continue
                print("\tConnected to", str(self._esp.ssid, 'utf-8'),
                      "\tRSSI:", self._esp.rssi)
                print("\tMy IP address is",
                      self._esp.pretty_ip(self._esp.ip_address))
                print("\tPing google.com: %d ms" %
                      self._esp.ping("google.com"))
            except Exception as e:
                print('[WARNING]', e)
        else:
            print('[WARNING] ESP32 not initialized')

    def esp_prog(self):
        if self.hardware['SDcard']:
            try:
                import adafruit_miniesptool
                esptool = adafruit_miniesptool.miniesptool(self._uart,
                                                           self._esp_dtr,
                                                           self._esp_rts,
                                                           flashsize=4 * 1024 *
                                                           1024)
                esptool.debug = False  #True
                time.sleep(0.5)

                esptool.sync()

                print("\tSynced")
                print("\tFound:", esptool.chip_name)
                if esptool.chip_name != "ESP32":
                    raise RuntimeError("\tfor ESP32 only")
                esptool.baudrate = 19200  #912600
                print("\tMAC ADDR: ", [hex(i) for i in esptool.mac_addr])

                esptool.flash_file('/sd/NINA_W102-1.3.0_sam32.bin', 0x00)

                esptool.reset()
                time.sleep(0.5)
            except Exception as e:
                print('[WARNING]', e)
        else:
            print('[WARNING] no SD card found')

    def esp_repl(self):
        if self.hardware['ESP32']:
            while True:
                try:
                    if self._uart.in_waiting:
                        try:
                            data = self._uart.read()
                            data_string = ''.join([chr(b) for b in data])
                            print('\t', data_string, end='')
                        except:
                            pass
                    if supervisor.runtime.serial_bytes_available:
                        call = input()
                        if call == 'exit':
                            print('=== exiting ESP32 REPL ===')
                            return
                        self._uart.write(
                            bytes(call, 'utf-8') +
                            b'\x0d\x0a')  #add CR+LF to end of call
                        try:
                            data = self._uart.read()
                            data_string = ''.join([chr(b) for b in data])
                            print(data_string, end='')
                        except:
                            pass
                except Exception as e:
                    print('[WARNING]', e)

    def connected(self, client):
        self.io.subscribe(group_key=self.group_name)

    def disconnected(self, client):
        print("Disconnected from Adafruit IO!")

    def message(self, client, feed_id, payload):
        print("Feed {0} received new value: {1}".format(feed_id, payload))
        self.payload = payload

    def iot(self,
            type='mqtt',
            group='light-group',
            action=None,
            conn=None,
            disc=None):
        from adafruit_esp32spi import adafruit_esp32spi_wifimanager
        import adafruit_esp32spi.adafruit_esp32spi_socket as socket
        import adafruit_requests as requests
        from adafruit_io.adafruit_io import IO_HTTP

        from secrets import secrets
        from adafruit_io.adafruit_io import IO_MQTT
        from adafruit_minimqtt import MQTT
        if not self.hardware['ESP32']:
            raise
        if not action: action = self.message
        if not conn: conn = self.connected
        if not disc: disc = self.disconnected
        # try:
        requests.set_socket(socket, self._esp)
        self.WIFI = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(
            self._esp, secrets, status_pixel=None)
        self.group_name = group

        self.WIFI.connect()

        mqtt_client = MQTT(socket=socket,
                           broker="io.adafruit.com",
                           username=secrets["aio_username"],
                           password=secrets["aio_key"],
                           network_manager=self.WIFI)
        self.io = IO_MQTT(mqtt_client)
        self.io.on_connect = conn
        self.io.on_disconnect = disc
        self.io.on_message = action
        # else:
        #     return
        self.io.connect()
print("Connected to %s!" % secrets["ssid"])

# Create a socket pool
pool = socketpool.SocketPool(wifi.radio)

# Initialize a new MQTT Client object
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(),
)

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

iot = Hub(display=display, io=io, nav=(up, select, down, back, submit))

iot.add_device(
    feed_key="lamp",
    default_text="Lamp: ",
    formatted_text="Lamp: {}",
    pub_method=pub_lamp,
)
iot.add_device(
    feed_key="temperature",
    default_text="Temperature: ",
    formatted_text="Temperature: {:.1f} C",
)
iot.add_device(feed_key="humidity",
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")

# 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)

io.add_feed_callback("lamp", on_lamp)
# Connect the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_subscribe = subscribe

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

io.get("lamp")

while True:
    io.loop()
def connected(client):
    # Connected function will be called when the client is connected to Adafruit IO.
    print('Connected to Adafruit IO!')

def subscribe(client, userdata, topic, granted_qos):
    # This method is called when the client subscribes to a new feed.
    print('Subscribed to {0} with QOS level {1}'.format(topic, granted_qos))

# pylint: disable=unused-argument
def disconnected(client):
    # Disconnected function will be called if the client disconnects
    # from the Adafruit IO MQTT broker.
    print("Disconnected from Adafruit IO!")

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

# Connect the callback methods defined above to the Adafruit IO MQTT Client
io.on_connect = connected
io.on_subscribe = subscribe
io.on_disconnect = disconnected

# Connect to Adafruit IO
print("Connecting to Adafruit IO...")
io.connect()
label_status.text = " "
print("Connected!")

fill_val = 0.0
def fill_water(fill_percent):
    """Fills the background water.
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")

# 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)

io.add_feed_callback("heatindex", on_hi)
# Connect the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_subscribe = subscribe

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

io.get("heatindex")

while True:
    io.loop()
Beispiel #22
0
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")

# 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 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 = on_message

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

# Set up a message handler for the battery feed
io.add_feed_callback("battery", on_battery_msg)
Beispiel #23
0
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")

# 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)

io.add_feed_callback("neopixel", on_neopixel)
# Connect the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_subscribe = subscribe

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

io.get("neopixel")

while True:
    io.loop()
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

# Create a socket pool
pool = socketpool.SocketPool(wifi.radio)

# Initialize a new MQTT Client object
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(),
)

# Initialize Adafruit IO MQTT "helper"
io = IO_MQTT(mqtt_client)

# 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.
print("Connecting to WiFi...")
wifi.connect()
print("Connected!")

# 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 the callback methods defined above to Adafruit IO
io.on_connect = connected
io.on_disconnect = disconnected
io.on_message = message

# Connect to Adafruit IO
io.connect()

# 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()

# Create a socket pool
pool = socketpool.SocketPool(wifi.radio)

# Initialize a new MQTT Client object
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(),
)

# 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")