Networking in Python

 General audience classification icon  General audience classification icon
IoT microcontrollers contain an external or integrated communication module. Note that IoT MCUs may use a variety of wireless communication interfaces such as Bluetooth, 802.15.4 standards (Zigbee, Thread) or Lora; this chapter does not deplete all scenarios but instead presents a general idea. We have chosen a simple WiFi interface, which is the easiest to use in most scenarios. Still, we are obviously not paying attention to their drawbacks, e.g., high energy consumption. Below are code samples regarding programming in Python for Raspberry Pi and Micropython for RP2040 (Pico W) microcontrollers that integrate WiFi networking.

Connecting to the WiFi router

Python
In the case of fog class devices with Linux or Windows operating systems, connecting to the network is controlled at the OS level with configuration tools. It is possible to use Python script to execute those commands, but they are OS-specific or require a dedicated hardware-specific library installed for Python. Monitoring progress or failure is problematic and needs analysis of the standard output; thus, this approach is not advised. Once the connection is present on the OS level, Python can quickly implement application-level servers such as WWW, MQTT, CoAP, etc.

Micropython
In the case of the Micropython, it is necessary to set up a WiFi client on the Python code level and explicitly connect it to the WiFi router. A sample code that connects to the existing WiFi access point and prints the obtained configuration from the DHCP server is present below:

import network
import socket
from time import sleep
import machine
 
ssid = '<your SSID comes here>'
password = '<your WiFi passphrase comes here>'
 
def connect():
    #Connect to WLAN
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(ssid, password)
    while wlan.isconnected() == False:
        print('Waiting for connection...')
        sleep(1)
    print(wlan.ifconfig())
 
try:
    connect()
except KeyboardInterrupt:
    machine.reset()
Setting up an access point

Python
Similarly, in the case of the STA mode, when using fog class devices with Linux or Windows operating systems, the hosting of the WiFi access point is controlled on the OS level, and it is done with OS configuration tools.

Micropython
IoT end node (edge) devices programmed in Python, such as RPI, RP2040 (RPI Pico), ESP32, and many other network-enabled microcontrollers, can set up an access point to connect other devices. Obviously, due to the limited resources (mainly RAM), the number of hosted clients in parallel is limited. Below is a sample code (without an application layer server, just networking layer AP) for RP2040.

A simple ESP 8266 (ESP-01) IoT module can act as AP and STA in parallel, and it is possible to set up a fully functional IP router (including DHCP server and NAT) with quite decent bandwidth and automated mesh WiFi-based capability [1].
import network
 
ssid = 'MicroPython-WiFi-AP'
password = '0987654321'
 
ap = network.WLAN(network.AP_IF)
ap.config(essid=ssid, password=password)
ap.active(True)
 
while ap.active()==False:
    pass
 
print(ap.ifconfig());
Hosting a service

IoT devices and cloud solutions usually host some service, e.g. providing users with a temperature sensor reading or doing some activity, e.g. rotating a servo to unlock a smart lock at the front door. In the case of the cloud and PCs, services used to be implemented using some containerisation solution, such as Docker. End-node IoT devices (edge) have no virtualisation capability due to limited resources, lack of the multitasking OS and also because of direct access to the hardware components. However, fog-class devices such as Raspberry Pi or nVidia Jetson can use containerisation.

Python
Sample web server for RPi in Python, using Flask[2] is straightforward and takes just a few lines of code. Code, development and output are present in the figure 1. 192.168.1.171 is RPI's sample IP address obtained from the router, as the WiFi connection is managed on the OS level, not via the Python app. The default WWW port for Flask services is 5000; the sample result is in figure 1:

from flask import Flask
 
app = Flask(__name__)
 
@app.route('/')
 
def index(): 
     return 'Hello IOT-OPEN.EU'
if __name__ == '__main__':   
     app.run(debug=True, host='192.168.1.171')
 Sample web server for RPi, using Flask library
Figure 1: Sample web server for RPi, using Flask library

Micropython
In the case of Micropython, the network-level connection is included in the script, so there are two main sections in the following sample: connecting to the router and hosting a dummy service, as in the example above (for RPi). Code, development and output are present in the figure 2. The IP address of the example Micropython device is 192.168.1.170, and the service is hosted on port 5000:

import network
import socket
from time import sleep
import machine
 
ssid = '<Your WiFi SSID is here>'
password = '<Your WiFi passphrase is here>'
 
def connect():
    #Connect to WLAN
    wlan = network.WLAN(network.STA_IF)
    wlan.active(True)
    wlan.connect(ssid, password)
    while wlan.isconnected() == False:
        print('Waiting for connection...')
        sleep(1)
    print(wlan.ifconfig())
 
def index(): 
     return 'Hello IOT-OPEN.EU'    
 
try:
    connect()
    addr = socket.getaddrinfo('0.0.0.0', 5000)[0][-1]
    s = socket.socket()
    s.bind(addr)
    s.listen(1)
 
    while True:
        try:
            cl, addr = s.accept()
            print('client connected from', addr)
            request = cl.recv(1024)
            cl.send(index())
            cl.close()
        except OSError as e:
            print('Error, connection closed')
 
except KeyboardInterrupt:
    machine.reset()
 Sample web server for RP2040 (Pico W)
Figure 2: Sample web server for RP2040 (Pico W)

An example of how to integrate GPIO and web service in one solution for Micropython can be found on the official RPI website [3].

en/iot-open/getting_familiar_with_your_hardware_rtu_itmo_sut/raspberrypi_rpi/networking_python.txt · Last modified: 2024/03/20 08:46 by pczekalski
CC Attribution-Share Alike 4.0 International
www.chimeric.de Valid CSS Driven by DokuWiki do yourself a favour and use a real browser - get firefox!! Recent changes RSS feed Valid XHTML 1.0