The Pico In MicroPython: HTTP Client
Written by Harry Fairhead & Mike James   
Monday, 02 January 2023
Article Index
The Pico In MicroPython: HTTP Client
A Custom Server
A Temperature Sensor Client

A Temperature Sensor Client

The standard approach to implementing a sensor device that makes its readings available to other devices is to implement a web server or a custom protocol that allows other devices to connect. A simpler solution is to implement an HTTP client and allow the sensor device to send data to a server which other devices can then connect to as required.

As we have already seen in Chapter 15, it is very easy to use the DS18B20 to collect data about ambient temperature. All we have to do is take a reading every so often, convert the floating-point value to a byte object and send it to the server using a PUT:

from machine import Pin, Timer
import network
import rp2
import onewire
import ds18x20
from time import sleep_ms
import urequests
wifi = setup("country", "ssid", "key")
url = "http://192.168.253.45:8080"
ow = onewire.OneWire(Pin(22))
presence = ow.reset()
if presence:
    print("Device present")
else:
    print("No device")
DS = ds18x20.DS18X20(ow)
roms = DS.scan()
while True:
    DS.convert_temp()
    temp = DS.read_temp(roms[0])
    buf = str(temp).encode("utf-8")
    try:
        r = urequests.put(url, data=buf)
        r.close()
    except:
        print("Server Not Online")
    sleep_ms(500)

The setup function given earlier which makes the WiFi connection has been omitted.

The server simply has to respond to the PUT request and convert the bytes to a string and then a float:

from http.server import HTTPServer, 
BaseHTTPRequestHandler
from io import BytesIO
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def log_message(self,*args, **kwargs): pass
def do_PUT(self): content_length =
int(self.headers['Content-Length']) body = self.rfile.read(content_length) bodyString= body.decode(encoding="utf-8") temp=float(bodyString) print(temp) self.send_response(200) self.end_headers()
httpd = HTTPServer(('', 8080), SimpleHTTPRequestHandler) httpd.serve_forever()

As before, it is simple enough to convert the server to HTTPS. The overriding of the log_message method is to suppress the regular printing of status messages. The do_PUT handler method simply prints the temperature. It could, of course, do much more.

You can appreciate that this architecture works well if you can allocate a simple device to act as a server. If the sensor supplies more data than a single measurement then using a JSON encoding makes things easier. For example, if you want to send a timestamp along with the temperature you could change the while loop to read:

while True:
    DS.convert_temp()
    temp = DS.read_temp(roms[0])
    jsonData={"temp":temp,"time":time()}
      
    try:
        r = urequests.put(url,json=jsonData)
        r.close()
    except:
        print("Server Not Online")
    sleep_ms(500)

You can see that the only difference is that now we make up a dictionary with key/value pairs corresponding to the data we want to send to the server. The only other difference is that we now set json=jsonData rather than setting it to data and the urequests module converts the dictionary into a JSON string.

To process the JSON string the server’s do_PUT method now has to use the json module to convert the received JSON string back into a dictionary object:

    def do_PUT(self):
        content_length = 
int(self.headers['Content-Length']) body = self.rfile.read(content_length) bodyString= body.decode(encoding="utf-8") jsonData=json.loads(bodyString) print(jsonData) self.send_response(200) self.end_headers()

If you run the client and the server with these changes you will see something like:

{'time': 1609459985, 'temp': 14.4375}
{'time': 1609459986, 'temp': 14.5}
{'time': 1609459987, 'temp': 14.4375}

You can unpack the data from the dictionary and use it as you would any other data.

In chapter but not in this extract

  • Sockets
  • Socket Address
  • Client Sockets
  • A Socket Web Client
  • SSL Socket Based HTTPS Client
  • 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


Ai-Da's Portrait of Alan Turing At Auction
01/11/2024

Sotheby's Digital Art Day Action, now underway, features a large-scale portrait of  Alan Turing created by Ai-Da, the humanoid robot artist whose work, including this canvas, was exhibited at the [ ... ]



Meta Releases OpenSource Podcast Generating Tool
28/11/2024

Meta has released an open source project that can be used to automatically convert a PDF file into a podcast. Meta says Notebook Llama can be considered an open-source version of Google's NotebookLM.

 [ ... ]


More News

espbook

 

Comments




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

 

 



Last Updated ( Monday, 02 January 2023 )