Ejemplo n.º 1
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
Ejemplo n.º 2
0
    def _create_mqtt_client(self) -> None:
        minimqtt.set_socket(self._socket, self._iface)

        self._logger.debug(
            str.replace(
                f"- iot_mqtt :: _on_connect :: username = {self._username}, password = {self._passwd}",
                "%",
                "%%",
            ))

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

        self._mqtts.enable_logger(logging, self._logger.getEffectiveLevel())

        # set actions to take throughout connection lifecycle
        self._mqtts.on_connect = self._on_connect
        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()
Ejemplo n.º 3
0
def initialize(myName, motorFunc):

    robotName = myName
    esp32_cs = DigitalInOut(board.D13)
    esp32_ready = DigitalInOut(board.D11)
    esp32_reset = DigitalInOut(board.D12)

    spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
    esp = adafruit_esp32spi.ESP_SPIcontrol(spi, esp32_cs, esp32_ready,
                                           esp32_reset)

    if esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
        broadcast.send("ESP32 found")
    """Use below for Most Boards"""
    status_light = neopixel.NeoPixel(
        board.NEOPIXEL, 1, brightness=0.2)  # Uncomment for Most Boards

    wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(
        esp, secrets, status_light)

    ### Feeds ###
    publishes["status"] = "{}/status".format(robotName)
    subscribes["motor"] = "{}/cmd/motor".format(robotName)
    subscribe_funcs["{}/cmd/motor".format(robotName)] = motorFunc
    subscribes["beep"] = "{}/cmd/beep".format(robotName)
    subscribes["servo"] = "{}/cmd/servo".format(robotName)

    # Connect to WiFi
    broadcast.send("Connecting to WiFi...")
    try:
        wifi.connect()
        broadcast.send("Connected!")
    except:
        broadcast.send("Could not connect")
        raise

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

    # Set up a MiniMQTT Client
    global mqtt_client
    mqtt_client = minimqtt.MQTT(
        broker=secrets["mqtt_broker"],
        port=1883,
    )

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

    # Connect the client to the MQTT broker.
    broadcast.send("Connecting to MQTT Broker {}...".format(
        secrets["mqtt_broker_name"]))
    mqtt_client.connect()

    broadcast.send("MQTT initialized")
    global MQTT
    MQTT = True
Ejemplo n.º 4
0
    def __init__(self):
        # Get wifi details and more from a secrets.py file

        esp32_cs = DigitalInOut(board.D13)
        esp32_ready = DigitalInOut(board.D11)
        esp32_reset = DigitalInOut(board.D12)

        self.spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
        self.esp = adafruit_esp32spi.ESP_SPIcontrol(self.spi, esp32_cs,
                                                    esp32_ready, esp32_reset)

        if self.esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
            print("ESP32 found and in idle mode")
        print("Firmware vers.", self.esp.firmware_version)
        print("MAC addr:", [hex(i) for i in self.esp.MAC_address])
        """Use below for Most Boards"""
        # status_light = neopixel.NeoPixel(board.NEOPIXEL, 1, brightness=0.2)  # Uncomment for Most Boards

        #status_light = pygamer.pygamerNeoPixels

        self.wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(
            self.esp, secrets)  #, status_light)

        ### Feeds ###
        self.status_feed = "roger/status/#"
        self.motor_cmd_feed = "roger/cmd/feather/motor"
        self.beep_cmd_feed = "roger/cmd/feather/beep"
        self.servo_cmd_feed = "roger/cmd/feather/servo"

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

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

        # Set up a MiniMQTT Client
        self.mqtt_client = MQTT.MQTT(
            broker=secrets["mqtt_broker"],
            port=1883,
        )

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

        # Connect the client to the MQTT broker.
        print("Connecting to MQTT...Broker {0}".format(
            secrets["mqtt_broker_name"]))
        self.mqtt_client.connect()
        print("Connected to broker {0}".format(secrets["mqtt_broker_name"]))
Ejemplo n.º 5
0
def mqtt_init(broker, port=1883, username=None, password=None):
    global mqtt_client, mqtt_connect_info
    mqtt_client = MQTT.MQTT(
        broker=broker,
        port=port,
        username=username,
        password=password,
        socket_pool=socket,
        ssl_context=ssl.create_default_context(),
    )

    mqtt_client.on_connect = connect
    mqtt_client.on_disconnect = disconnect
    mqtt_client.on_message = message
Ejemplo n.º 6
0
    def __init__(self, name, status_light):
        esp32_cs = DigitalInOut(board.D13)
        esp32_ready = DigitalInOut(board.D11)
        esp32_reset = DigitalInOut(board.D12)

        self.spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
        self.esp = adafruit_esp32spi.ESP_SPIcontrol(self.spi, esp32_cs, esp32_ready, esp32_reset)

        if self.esp.status == adafruit_esp32spi.WL_IDLE_STATUS:
            print("ESP32 found and in idle mode")
        print("Firmware vers.", self.esp.firmware_version)
        print("MAC addr:", [hex(i) for i in self.esp.MAC_address])

        self.status_light = status_light  # pygamer.pygamerNeoPixels

        self.wifi = adafruit_esp32spi_wifimanager.ESPSPI_WiFiManager(self.esp, secrets, self.status_light)

        ### Feeds ###
        self.name = name
        self.status_feed = "{0}/status".format(name)

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

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

        # Set up a MiniMQTT Client
        self.mqtt_client = MQTT.MQTT(
            broker=secrets["mqtt_broker"],
            port=1883,
        )

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

        # Connect the client to the MQTT broker.
        print("Connecting to MQTT...Broker {0}".format(secrets["mqtt_broker_name"]))
        self.mqtt_client.connect()
        print("Connected to broker {0}".format(secrets["mqtt_broker_name"]))
        self.publish_message(self.status_feed, "{0} has connected to {1}".format(name, secrets["mqtt_broker_name"]))
    def register_device(self, expiry: int) -> str:
        """
        Registers the device with the IoT Central device registration service.
        Returns the hostname of the IoT hub to use over MQTT
        :param int expiry: The expiry time for the registration
        :returns: The underlying IoT Hub that this device should connect to
        :rtype: str
        :raises DeviceRegistrationError: if the device cannot be registered successfully
        :raises RuntimeError: if the internet connection is not responding or is unable to connect
        """

        username = f"{self._id_scope}/registrations/{self._device_id}/api-version={constants.DPS_API_VERSION}"

        # pylint: disable=C0103
        sr = self._id_scope + "%2Fregistrations%2F" + self._device_id
        sig_no_encode = compute_derived_symmetric_key(self._key,
                                                      sr + "\n" + str(expiry))
        sig_encoded = quote(sig_no_encode, "~()*!.'")
        auth_string = f"SharedAccessSignature sr={sr}&sig={sig_encoded}&se={str(expiry)}&skn=registration"

        minimqtt.set_socket(self._socket, self._iface)

        self._mqtt = minimqtt.MQTT(
            broker=constants.DPS_END_POINT,
            username=username,
            password=auth_string,
            port=8883,
            keep_alive=120,
            is_ssl=True,
            client_id=self._device_id,
        )

        self._mqtt.enable_logger(logging, self._logger.getEffectiveLevel())

        self._connect_to_mqtt()
        self._start_registration()
        self._wait_for_operation()

        self._mqtt.disconnect()

        return str(self._hostname)
    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
Ejemplo n.º 9
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()
Ejemplo n.º 10
0

# ------------- Network Connection ------------- #

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

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

# Set up a MiniMQTT Client
client = MQTT.MQTT(
    broker=secrets["broker"],
    port=1883,
    username=secrets["broker_user"],
    password=secrets["broker_pass"],
)
try:
    client.enable_logger(logging, logging.DEBUG)
except:
    client.attach_logger()
    client.set_logger_level("DEBUG")

# Connect callback handlers to client
client.on_connect = connect
client.on_disconnect = disconnected
client.on_subscribe = subscribe
client.on_publish = publish
client.on_message = message
Ejemplo n.º 11
0
mqtt_broker = "test.mosquitto.org"
mqtt_topic = "hello"


def handle_connect(client, userdata, flags, rc):
    print("Connected to {0}".format(client.broker))
    mqtt_client.subscribe(mqtt_topic)


def handle_subscribe(client, userdata, topic, granted_qos):
    print("Subscribed to {0} with QOS {1}".format(topic, granted_qos))


def handle_message(client, topic, message):
    print("Received on {0}: {1}".format(topic, message))


adafruit_minimqtt.set_socket(adafruit_esp32spi_socket, wifi)

mqtt_client = adafruit_minimqtt.MQTT(broker=mqtt_broker, is_ssl=False)

# Set callback handlers
mqtt_client.on_connect = handle_connect
mqtt_client.on_subscribe = handle_subscribe
mqtt_client.on_message = handle_message

print("\nConnecting to {0}".format(mqtt_broker))
mqtt_client.connect()

while True:
    mqtt_client.loop()
Ejemplo n.º 12
0
print("Wi-Fi connected to", str(esp.ssid, "utf-8"))
print("IP address", esp.pretty_ip(esp.ip_address))


def handle_connect(client, userdata, flags, rc):
    print("Connected to {0}".format(client.broker))


def handle_publish(client, userdata, topic, pid):
    print("Published to {0} with PID {1}".format(topic, pid))


adafruit_minimqtt.set_socket(adafruit_esp32spi_socket, esp)

mqtt_client = adafruit_minimqtt.MQTT(broker=TS_MQTT_BROKER, is_ssl=False)

# Set callback handlers
mqtt_client.on_connect = handle_connect
mqtt_client.on_publish = handle_publish

try:
    # Connect to ThingSpeak
    print("Connecting to {0}".format(TS_MQTT_BROKER))
    mqtt_client.connect()

    # Some test data
    humidity = 55
    temperature = 25

    # Setup topic (see https://ch.mathworks.com/help/thingspeak/publishtoachannelfeed.html)
Ejemplo n.º 13
0
# 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)

# Set up a new MiniMQTT Client
client = MQTT.MQTT(broker=secrets["broker"], client_id=secrets["client_id"])

# Initialize AWS IoT MQTT API Client
aws_iot = MQTT_CLIENT(client)

# Connect callback handlers to AWS IoT MQTT Client
aws_iot.on_connect = connect
aws_iot.on_disconnect = disconnect
aws_iot.on_subscribe = subscribe
aws_iot.on_unsubscribe = unsubscribe
aws_iot.on_publish = publish
aws_iot.on_message = message

print("Attempting to connect to %s" % client.broker)
aws_iot.connect()
Ejemplo n.º 14
0
    gfx.show_gcp_status('Plant watered!')
    print("Turning pump off")
    water_pump.value = False


# Initialize Google Cloud IoT Core interface
google_iot = Cloud_Core(esp, secrets)

# JSON-Web-Token (JWT) Generation
print("Generating JWT...")
jwt = google_iot.generate_jwt()
print("Your JWT is: ", jwt)

# Set up a new MiniMQTT Client
client = MQTT.MQTT(broker=google_iot.broker,
                   username=google_iot.username,
                   password=jwt,
                   client_id=google_iot.cid)

# Initialize Google MQTT API Client
google_mqtt = MQTT_API(client)

# Connect callback handlers to Google MQTT Client
google_mqtt.on_connect = connect
google_mqtt.on_disconnect = disconnect
google_mqtt.on_subscribe = subscribe
google_mqtt.on_unsubscribe = unsubscribe
google_mqtt.on_publish = publish
google_mqtt.on_message = message

print('Attempting to connect to %s' % client.broker)
google_mqtt.connect()
    :param str message: The new value
    """
    print("New message on topic {0}: {1}".format(topic, message))


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

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

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

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

# Connect the client to the MQTT broker.
print("Connecting to MQTT broker...")
mqtt_client.connect()

# Start a blocking message loop...
# NOTE: NO code below this loop will execute
# NOTE: Network reconnection is handled within this loop
while True:
def publish(mqtt_client, userdata, topic, pid):
    # This method is called when the mqtt_client publishes data to a feed.
    print("Published to {0} with PID {1}".format(topic, pid))


def message(client, topic, message):
    print("New message on topic {0}: {1}".format(topic, message))


socket.set_interface(esp)
MQTT.set_socket(socket, esp)

# Set up a MiniMQTT Client
mqtt_client = MQTT.MQTT(
    broker=secrets["broker"],
    port=secrets["port"],
    username=secrets["username"],
    password=secrets["password"],
)

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

print("Attempting to connect to %s" % mqtt_client.broker)
mqtt_client.connect()

print("Subscribing to %s" % mqtt_topic)
Ejemplo n.º 17
0
                    else:
                        # radio, time, gs id, msg, rssi, new?
                        new_messages[r]={"RD":r,"T":time.time(),"I":gs.ID,"MSG":hexlify(msg),"RS":gs.last_rssi,"N":1}
            print()
    radios = gs.init_radios(SAT)

if new_messages:
    gs.msg_count = gs.msg_count + 1

# if we have wifi, connect to mqtt broker
if wifi.radio.ap_info is not None:
    # try:
    # Set up a MiniMQTT Client
    mqtt_client = MQTT.MQTT(
        broker=secrets['broker'],
        port=secrets['port'],
        socket_pool=pool,
        is_ssl=False,
    )
    mqtt_client.on_connect = connected
    mqtt_client.on_message = mqtt_message

    status = {
        'T':time.time(),
        'I':gs.ID,
        '#':gs.counter,
        'M':gs.msg_count,
        'C':gs.msg_cache,
        'B':gs.battery_voltage,
        'R':wifi.radio.ap_info.rssi,
    }
Ejemplo n.º 18
0
# or if you need your Adafruit IO key.)
aio_username = secrets["aio_username"]
aio_key = secrets["aio_key"]

print("Connecting to %s" % secrets["ssid"])
wifi.radio.connect(secrets["ssid"], secrets["password"])
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,
)
Ejemplo n.º 19
0
try:
    from secrets import secrets
except ImportError:
    print("MQTT secrets are kept in secrets.py, please add them there!")
    raise

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

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

# Set up a MiniMQTT Client
mqtt_client = MQTT.MQTT(broker=secrets["broker"], port=secrets["port"])

### MQTT Code ###
# Define callback methods which are called when events occur
# pylint: disable=unused-argument, redefined-outer-name


def connected(client, userdata, flags, rc):
    global Isconnected
    Isconnected = True
    # This function will be called when the client is connected
    # successfully to the broker.
    print("Connected to MQTT broker!")
    # Subscribe to all changes on the default_topic feed.
    client.subscribe("ledStrip/power")
    client.subscribe("ledStrip/color")
Ejemplo n.º 20
0
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))


# Connect to WiFi
wifi.connect()
print("Connected to", str(esp.ssid, 'utf-8'), "\tRSSI:", esp.rssi)
print("My IP address is", esp.pretty_ip(esp.ip_address))

try:

    # Initialize MQTT interface with the esp interface
    MQTT.set_socket(socket, esp)
    # Set up a MiniMQTT Client
    client = MQTT.MQTT(broker='192.168.1.164', port=1883)

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

    print('Subscribing to %s' % mqtt_topic)
    client.subscribe(mqtt_topic)

    print('Publishing to %s' % mqtt_topic)
    time.sleep(0.5)
print("Attached!")

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

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

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

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

print("Subscribing to %s" % mqtt_topic)
client.subscribe(mqtt_topic)
Ejemplo n.º 22
0
def disconnected(client, userdata, rc):
    # This method is called when the client is disconnected
    print("Disconnected from Adafruit IO!")


def message(client, topic, message):
    # This method is called when a topic the client is subscribed to
    # has a new message.
    print("New message on topic {0}: {1}".format(topic, message))


# Set up a MiniMQTT Client
mqtt_client = MQTT.MQTT(
    broker=secrets["broker"],
    port=1883,
    username=secrets["aio_username"],
    password=secrets["aio_key"],
    socket_pool=socket,
)

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

# Connect the client to the MQTT broker.
print("Connecting to Adafruit IO...")
mqtt_client.connect()

photocell_val = 0
while True:
Ejemplo n.º 23
0
# Initialize MQTT interface with the esp interface
MQTT.set_socket(socket, esp)

# Initialize Google Cloud IoT Core interface
google_iot = Cloud_Core(esp, secrets)

# Optional JSON-Web-Token (JWT) Generation
# print("Generating JWT...")
# jwt = google_iot.generate_jwt()
# print("Your JWT is: ", jwt)

# Set up a new MiniMQTT Client
client = MQTT.MQTT(
    broker=google_iot.broker,
    username=google_iot.username,
    password=secrets["jwt"],
    client_id=google_iot.cid,
)

# Initialize Google MQTT API Client
google_mqtt = MQTT_API(client)

# Connect callback handlers to Google MQTT Client
google_mqtt.on_connect = connect
google_mqtt.on_disconnect = disconnect
google_mqtt.on_subscribe = subscribe
google_mqtt.on_unsubscribe = unsubscribe
google_mqtt.on_publish = publish
google_mqtt.on_message = message

print("Attempting to connect to %s" % client.broker)
Ejemplo n.º 24
0
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,
    text_scale=2,
)
Ejemplo n.º 25
0

def message(client, topic, message):
    # This method is called when a topic the client is subscribed to
    # has a new message.
    print("New message on topic {0}: {1}".format(topic, message))


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

# Set up a MiniMQTT Client
mqtt_client = MQTT.MQTT(
    broker=secrets["aio_broker"],
    port=secrets["aio_port"],
    username=secrets["aio_username"],
    password=secrets["aio_key"],
    socket_pool=pool,
    ssl_context=ssl.create_default_context(),
)

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

# Connect the client to the MQTT broker.
print("Connecting to Adafruit IO ...")
mqtt_client.connect()

photocell_val = 0
while True:
def message(client, topic, message):
    """Method callled when a client's subscribed feed has a new
    value.
    :param str topic: The topic of the feed with a new value.
    :param str message: The new value
    """
    print("New message on topic {0}: {1}".format(topic, message))


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

# Set up a MiniMQTT Client
mqtt_client = MQTT.MQTT(broker=secrets['broker'],
                        port=443,
                        username=secrets['user'],
                        password=secrets['pass'])

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

photocell_val = 0

while True:
    print("start_advertising")
    ble.start_advertising(advertisement)
    while not ble.connected:
        pass
    if ble.connected:
    # the new value.
    print("Feed {0} received new value: {1}".format(feed_id, payload))


# 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_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...
Ejemplo n.º 28
0
    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 topic.
    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 topic.
    print('Published to {0} with PID {1}'.format(topic, pid))

def message(client, topic, msg):
    # This method is called when the client receives data from a topic.
    print("Message from {}: {}".format(topic, msg))

# Set up a new MiniMQTT Client
client =  MQTT.MQTT(broker = secrets['broker'],
                    client_id = secrets['client_id'])

# Initialize AWS IoT MQTT API Client
aws_iot = MQTT_CLIENT(client)

# Connect callback handlers to AWS IoT MQTT Client
aws_iot.on_connect = connect
aws_iot.on_disconnect = disconnect
aws_iot.on_subscribe = subscribe
aws_iot.on_unsubscribe = unsubscribe
aws_iot.on_publish = publish
aws_iot.on_message = message

print('Attempting to connect to %s'%client.broker)
aws_iot.connect()