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()
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
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"]))
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 _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()
# 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)) # 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
# 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(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
network = network.CELLULAR( fona, (secrets["apn"], secrets["apn_username"], secrets["apn_password"])) while not network.is_attached: print("Attaching to network...") 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
Isconnected = False # Get MQTT details and more from a secrets.py file 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!")
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()
"""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)) # Connect to WiFi print("Connecting to WiFi...") wifi.connect() print("Connected!") # Initialize MQTT interface with the esp interface # pylint: disable=protected-access MQTT.set_socket(socket, pyportal._esp) # Set up a MiniMQTT Client mqtt_client = MQTT.MQTT( broker=secrets["broker"], username=secrets["user"], password=secrets["pass"], is_ssl=False, ) # 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.
def disconnected(client, userdata, rc): # This method is called when the client is disconnected print("Disconnected from MQTT Broker!") 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:
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, ) # Team 2 Score matrixportal.add_text( text_font=terminalio.FONT,
"""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)) # Connect to WiFi print("Connecting to WiFi...") pyportal.network.connect() print("Connected!") # Initialize MQTT interface with the esp interface # pylint: disable=protected-access MQTT.set_socket(socket, pyportal.network._wifi.esp) # Set up a MiniMQTT Client mqtt_client = MQTT.MQTT( broker=secrets["broker"], username=secrets["user"], password=secrets["pass"], is_ssl=False, ) # 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.
# 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="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