The Pico In MicroPython: Sockets
Written by Mike James & Harry Fairhead   
Monday, 05 August 2024
Article Index
The Pico In MicroPython: Sockets
Socket Address
A Socket Web Client
SSL Socket Based HTTPS Client

SSL Socket Based HTTPS Client

Many websites now refuse to serve unencrypted data and insist on HTTPS. Fortunately it is very easy to create an HTTPS client as you don’t need to create a digital certificate. If you need to prove to a server that it is indeed you trying to connect then you should install a new certificate and use it. This is exactly the same procedure as installing a new server certificate, see later.

MicroPython has a very minimal implementation of the Python ssl module. It only has a single function wrap_socket but it is enough to do what you need to make an HTTPS client or server. What this does is to add encryption and in some cases authentication to an existing socket. At the time of writing MicroPython for the Pico doesn’t support authentication.

The wrap_socket function is:

ssl.wrap_socket(sock, keyfile=None, certfile=None,
server_side=False, cert_reqs=CERT_NONE,
ca_certs=None,
do_handshake_on_connect=True,
)

This takes an existing socket specified by sock and turns it into an encrypted SSL socket. Apart from sock all of the other parameters, including keyfile and certfile which specify files which contain the certificate and/or key, are optional.

All certificates have to be in PEM format. If the key is stored in the certificate then you only need to use certfile. If the key is stored separately from the certificate you need both certfile and keyfile.

server_side sets the behavior appropriate to a client (False) or server (True)

cert_reqs determines the level of certificate checking, from CERT_NONE, CERT_OPTIONAL to CERT_REQUIRED. The validity of the certificate is only checked if you select CERT_REQUIRED and currently the Pico never checks the certificate for validity.

ca_certs is a bytes object contains the certificate change to be used to validate the client’s certificate.

server_hostname is used to set the server’s hostname so that the certificate can be checked to ascertain that it does belong to the web site and to allow the server to present the appropriate certificate if it is hosting multiple sites.

do_handshake should be used with non-blocking sockets and if True defers the handshake . If False, wrap_socket doesn’t return until the handshake is complete.

Notice that not all of the full Python wrap_socket parameters are supported and not all TLS and encryption levels work. What this means is that you will discover that connecting to some websites is difficult, if not impossible, at the moment. However, in many case it should simply work, as long as the website concerned is not using a cutting edge implementation.

The only modification that the previous HTTP client needs to work with an HTTPS web site is:

import network
import socket
import rp2
from machine import Pin, Timer from time import sleep_ms def setup(country, ssid, key): . . . wifi = setup("country", "ssid", "key") ai = socket.getaddrinfo("example.com", 443,
socket.AF_INET)
addr = ai[0][-1] s = socket.socket(socket.AF_INET) s.connect(addr) sslSock=ssl.wrap_socket(s) request = b"GET / HTTP/1.1\r\nHost:example.com\r\n\r\n"
sslSock.write(request) print(sslSock.read(1024))

where the setup function has been omitted.

Notice that all we need to do is perform a default wrap_socket after making the connection. The downloaded HTML is now fetched using HTTPS. The sslSock returned by the wrap_socket function only has stream read and write methods.

In chapter but not in this extract

  • Socket Server
  • A Socket Temperature Server
  • An SSL HTTPS Server
  • Non-Blocking Sockets
  • The Connection Queue

Summary

  • The Pico W’s new WiFi hardware is connected via an SPI bus and this makes use of several GPIO lines that are used in the Pico for different things. In particular, GP25 is no longer used to control the internal LED. The internal LED is now controlled by a GPIO line on the WiFi chip.

  • Connecting to a WiFi network is a matter of using the WLAN class.

  • Implementing error handling for a WiFi connection can be challenging.

  • The simplest way of implementing an HTTP client is to use urequests.

  • An HTTP client can both send and receive data. The only thing it cannot do is accept an incoming connection, which is what a server does.

  • If you want to do anything beyond HTTP, or you want to implement an HTTP server, then you need to make use of sockets.

  • Sockets are completely general and you can use them to implement an HTTP client.

  • Implementing a socket server is easy, but it can be difficult to ensure that both clients and internal services are both attended to.

  • The simplest solution to the server problem is to implement a polling loop and to do this you need to make use of non-blocking sockets.

Programming the Raspberry Pi Pico/W In MicroPython Second Edition

By Harry Fairhead & Mike James

picopython2e360

Buy from Amazon.

Contents

  • Preface
  • Chapter 1 The Raspberry Pi Pico – Before We Begin
  • Chapter 2 Getting Started
  • Chapter 3 Getting Started With The GPIO
  • Chapter 4 Simple Output
  • Chapter 5 Some Electronics
  • Chapter 6 Simple Input
             Extract: Simple Input 
  • Chapter 7 Advanced Input – Events and Interrupts
  • Chapter 8 Pulse Width Modulation
             Extract: PWM 
  • Chapter 9 Controlling Motors And Servos
             Extract: DC Motors
  • Chapter 10 Getting Started With The SPI Bus
  • Chapter 11 A-To-D and The SPI Bus 
  • Chapter 12 Using The I2C Bus
  • Chapter 13 Using The PIO   
  • Chapter 14 The DHT22 Sensor Implementing A Custom Protocol
             Extract: A PIO Driver For The DHT22  
  • Chapter 15 The 1‑Wire Bus And The DS1820
  • Chapter 16 The Serial Port
  • Chapter 17 Using The Pico W - WiFi
             Extract: HTTP Client 
             Extract: Sockets***NEW!
  • Chapter 18 Asyncio And Servers
  • Chapter 19 Direct To The Hardware
             Extract: Direct To The Hardware

Also of interest:

Raspberry Pico File System

<ASIN:B0BR8LWYMZ>

<ASIN:B0BL1HS3QD>

 

To be informed about new articles on I Programmer, sign up for our weekly newsletter, subscribe to the RSS feed and follow us on Twitter, Facebook or Linkedin.

Banner


Google Opensources Privacy Library
08/11/2024

Google is making a new differential privacy library available as open source. PipelineDP4J is a Java-based library that can be used to analyse data sets while preserving privacy.



IBM Updates Granite Models
28/10/2024

IBM has released new Granite models that it says provide state-of-the-art performance relative to model size. The Granite 3.0 collection includes a new, instruction-tuned, dense decoder-only LLM.


More News

espbook

 

Comments




or email your comment to: comments@i-programmer.info



Last Updated ( Tuesday, 06 August 2024 )