Exemplo n.º 1
0
def __connect(cs_pin, ready_pin, reset_pin, secrets) -> ESPSPI_WiFiManager:
    logger = logging.getLogger("log")

    spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
    esp = adafruit_esp32spi.ESP_SPIcontrol(spi, cs_pin, ready_pin, reset_pin)

    wifi = ESPSPI_WiFiManager(esp, secrets, attempts=5)

    MQTT.set_socket(socket, esp)

    logger.debug("MAC addr: " + ", ".join([hex(i) for i in esp.MAC_address]))
    logger.debug("Connecting to AP...")

    wifi.connect()

    logger.info("Connected to " + str(esp.ssid, "utf-8") + "\tRSSI: " +
                str(esp.rssi))
    logger.debug("My IP address is " + esp.pretty_ip(esp.ip_address))

    logger.debug("Setting time")

    ntp = NTP(esp)
    while not ntp.valid_time:
        ntp.set_time()
        logger.debug("Failed to obtain time, retrying in 1 second...")
        time.sleep(1)

    logger.info("Time: " + str(time.time()))

    return wifi
Exemplo n.º 2
0
    def _try_create_mqtt_client(self, hostname):
        minimqtt.set_socket(socket, self._wifi_manager.esp)

        self._mqtts = MQTT(
            broker=hostname,
            username=self._username,
            password=self._passwd,
            port=8883,
            keep_alive=120,
            is_ssl=True,
            client_id=self._device_id,
            log=True,
        )

        self._mqtts.logger.setLevel(logging.INFO)

        # set actions to take throughout connection lifecycle
        self._mqtts.on_connect = self._on_connect
        self._mqtts.on_message = self._on_message
        self._mqtts.on_log = self._on_log
        self._mqtts.on_publish = self._on_publish
        self._mqtts.on_disconnect = self._on_disconnect

        # initiate the connection using the adafruit_minimqtt library
        self._mqtts.last_will()
        self._mqtts.connect()
Exemplo n.º 3
0
def wifi_mqtt_setup():
    print("Connecting to WiFi...")
    wifi.connect()
    print("Connected!")
    MQTT.set_socket(socket, esp)
    mqtt_client.on_connect = connected
    mqtt_client.on_disconnect = disconnected
    mqtt_client.on_message = message
    print("Connecting to MQTT broker...")
    mqtt_client.connect()
Exemplo n.º 4
0
    def _create_mqtt_client(self) -> None:
        minimqtt.set_socket(self._socket, self._iface)

        self._mqtts = MQTT(
            broker=self._hostname,
            username=self._username,
            password=self._passwd,
            port=8883,
            keep_alive=120,
            is_ssl=True,
            client_id=self._device_id,
            log=True,
        )

        self._mqtts.logger.setLevel(self._logger.getEffectiveLevel())

        # set actions to take throughout connection lifecycle
        self._mqtts.on_connect = self._on_connect
        self._mqtts.on_log = self._on_log
        self._mqtts.on_publish = self._on_publish
        self._mqtts.on_disconnect = self._on_disconnect

        # initiate the connection using the adafruit_minimqtt library
        self._mqtts.connect()
Exemplo n.º 5
0
gfx = aws_gfx_helper.AWS_GFX()
print("Graphics loaded!")

# Set AWS Device Certificate
esp.set_certificate(DEVICE_CERT)

# Set AWS RSA Private Key
esp.set_private_key(DEVICE_KEY)

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

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

# Soil Sensor Setup
i2c_bus = busio.I2C(board.SCL, board.SDA)
ss = Seesaw(i2c_bus, addr=0x36)


# Define callback methods which are called when events occur
# pylint: disable=unused-argument, redefined-outer-name
def connect(client, userdata, flags, rc):
    # This function will be called when the client is connected
    # successfully to the broker.
    print('Connected to AWS IoT!')
    print('Flags: {0}\nRC: {1}'.format(flags, rc))

    # Subscribe client to all shadow updates
Exemplo n.º 6
0
        datesuffix = "rd"
    else:
        datesuffix = "th"

    writemessage("Good %s!" % (timeofday), 20, 90, "black",
                 "BioRhyme-ExtraBold-17.bdf", clockgroup)
    writemessage(
        "Today is %s %s %s%s" %
        (response.json()['dayOfTheWeek'], month, day, datesuffix), 20, 130,
        "black", "BioRhyme-ExtraBold-17.bdf", clockgroup)
    writemessage("The current time is: %s" % (cleantime), 20, 170, "black",
                 "BioRhyme-ExtraBold-17.bdf", clockgroup)


### MQTT Setup ###
MQTT.set_socket(socket, pyportal._esp)
try:
    # Set up a MiniMQTT Client
    mqtt_client = MQTT.MQTT(broker=secrets["broker"],
                            username=secrets["user"],
                            password=secrets["pass"],
                            client_id=secrets["clientid"],
                            is_ssl=False,
                            port=16392)
except Exception as err:
    print("Except: {0}".format(err))
    print("Failed to create MQTT Client")

# Setup the callback methods
mqtt_client.on_connect = connected
mqtt_client.on_disconnect = disconnected
# Initialize GSM modem
gsm = GSM(fona, (secrets["apn"], secrets["apn_username"], secrets["apn_password"]))

while not gsm.is_attached:
    print("Attaching to network...")
    time.sleep(0.5)
print("Attached to network!")

while not gsm.is_connected:
    print("Connecting to network...")
    gsm.connect()
    time.sleep(5)
print("Connected to network!")

# Initialize MQTT interface with the cellular interface
MQTT.set_socket(socket, fona)

# Set up a MiniMQTT Client
# NOTE: We'll need to connect insecurely for ethernet configurations.
mqtt_client = MQTT.MQTT(
    broker="http://io.adafruit.com",
    username=secrets["aio_username"],
    password=secrets["aio_key"],
)

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

Exemplo n.º 8
0
    # This method is called when the client subscribes to a new feed.
    print("Subscribed to {0} with QOS level {1}".format(topic, granted_qos))


def unsubscribe(client, userdata, topic, pid):
    # This method is called when the client unsubscribes from a feed.
    print("Unsubscribed from {0} with PID {1}".format(topic, pid))


def publish(client, userdata, topic, pid):
    # This method is called when the client publishes data to a feed.
    print("Published to {0} with PID {1}".format(topic, pid))


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

# Set up a MiniMQTT Client
client = MQTT.MQTT(broker=secrets["broker"],
                   username=secrets["user"],
                   password=secrets["pass"])

# Connect callback handlers to client
client.on_connect = connect
client.on_disconnect = disconnect
client.on_subscribe = subscribe
client.on_unsubscribe = unsubscribe
client.on_publish = publish

print("Attempting to connect to %s" % client.broker)
client.connect()
Exemplo n.º 9
0
# pylint: disable=unused-argument
def disconnected(client):
    # Disconnected function will be called when the client disconnects.
    print("Disconnected from Adafruit IO!")


# pylint: disable=unused-argument
def message(client, feed_id, payload):
    # Message function will be called when a subscribed feed has a new value.
    # The feed_id parameter identifies the feed, and the payload parameter has
    # the new value.
    print("Feed {0} received new value: {1}".format(feed_id, payload))


# Initialize MQTT interface with the ethernet interface
MQTT.set_socket(cellular_socket, fona)

# Initialize a new MQTT Client object
mqtt_client = MQTT.MQTT(
    broker="http://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