IoT Library

The iot library encapsulates mPython IoT’s Wi-Fi networking and MQTT communication functionality, providing a simpler interface for quickly building IoT applications.

Hint

This library is built on top of the standard MicroPython network and umqtt.simple modules. For lower-level control, use the standard modules directly. See MQTT Communication .

Constructor

class iot.IoT

Creates an IoT object for managing Wi-Fi connections and MQTT communication.

Usage example:

from iot import IoT

myiot = IoT()

Wi-Fi Methods

IoT.connect(ssid, password)
  • ssid – Wi-Fi network name (string type)

  • password – Wi-Fi password (string type)

Connects to the specified Wi-Fi network. Returns True on success, False on failure.

IoT.disconnect()

Disconnects the current Wi-Fi connection and releases network resources.

IoT.isconnected()

Queries the current Wi-Fi connection status. Returns True if connected, False if not.

IoT.ifconfig()

Returns the current network configuration: IP address, subnet mask, gateway, and DNS server.

MQTT Methods

IoT.mqtt_init(server, port=1883, client_id=None, user=None, password=None, keepalive=0)
  • server – MQTT broker address

  • port – Server port, default 1883

  • client_id – Unique client ID

  • user – Authentication username (optional)

  • password – Authentication password (optional)

  • keepalive – Connection keepalive interval (seconds), 0 means disabled

Initializes and connects to the MQTT broker. Must be called after a successful Wi-Fi connection.

IoT.publish(topic, msg)
  • topic – Topic to publish to

  • msg – Message content

Publishes a message to the specified topic.

IoT.subscribe(topic)
  • topic – Topic to subscribe to

Subscribes to the specified topic and receives messages published to it.

IoT.set_callback(cb)
  • cb – Callback function in the form cb(topic, msg), where the first parameter is the received topic and the second is the message content

Sets the callback function invoked when a subscribed message is received. Must be called before subscribe().

IoT.wait_msg()

Blocking wait for server messages. Received subscribed messages are processed by the callback function set via set_callback().

IoT.check_msg()

Non-blocking check for pending messages. Suitable for programs that also need to perform other tasks.

Attention

  • MQTT topics and message contents are handled as byte types during network transmission. Pay attention to type conversion when comparing.

  • Before calling MQTT methods, ensure Wi-Fi is successfully connected.

Usage Example

from iot import IoT

myiot = IoT()
myiot.connect('your_ssid', 'your_password')     # Connect to Wi-Fi
myiot.mqtt_init("192.168.1.100", 1883)           # Connect to MQTT server

def sub_cb(topic, msg):
    print((topic, msg))

myiot.set_callback(sub_cb)
myiot.subscribe("classroom/data")
myiot.publish("classroom/data", "hello")

while True:
    myiot.wait_msg()