Micro:bit MicroPython: UART OBLOQ HTTP GET Request to Flask server

In this tutorial we are going to check how to send a HTTP GET request using a micro:bit board and a UART OBLOQ. We will be using MicroPython to program the micro:bit board.

Introduction

In this tutorial we are going to check how to send a HTTP GET request using a micro:bit board and a UART OBLOQ. We will be using MicroPython to program the micro:bit board.

The connection diagram between both devices can be seen on this tutorial.

We will setup a very simple Python Flask server, which will be the destination of our HTTP GET request. You can check here a Flask “Hello World” tutorial.

The Flask code

The Flask code we are going to write on this section will be very simple and similar to this previous tutorial.

We will start by importing the Flask class, so we can configure our server, and the request object, which allows to obtain both the request headers and body.

In our case, since we will be receiving a GET request, it should not have a body. So, we will use the request object to access the headers of the request.

from flask import Flask, request

Then we will create an object of class Flask. We will need this object to configure the server. More precisely, we will use it to configure the route that will be listening to incoming GET requests.

app = Flask(__name__)

We will setup a single route which will listen, as already said, to GET requests. We will call our route “/get“.

@app.route('/get', methods = ["GET"])
def get():

In the implementation of our route handling function, we will simply print the headers of the request and then return a “Received” string back to the client, for testing purposes.

print(request.headers)
return 'Received'

Finally, we will call the run method on the Flask object, in order for the server to start listening to incoming requests.

We will pass the value “0.0.0.0” in the host parameter, thus indicating the server should listen on all available IPs of the machine. As port we will use the value 8090.

app.run(host='0.0.0.0', port= 8090)

The final Flask code can be seen below.

from flask import Flask, request

app = Flask(__name__)

@app.route('/get', methods = ["GET"])
def get():

    print(request.headers)
    return 'Received'

app.run(host='0.0.0.0', port= 8090)

The micro:bit code

We will start the code by importing the uart object and the sleep function from the microbit module.

from microbit import uart, sleep

Then, like we did on the previous tutorial, we will define a readUntil function that reads characters from the serial port until a specific character is received. As output, the function returns the content read until the character was found.

This function will help us handling the response to commands sent to the UART OBLOQ.

def readUntil(uartObject, termination):
  result = ''

  while True:
    if uartObject.any():

        byte = uartObject.read(1)

        result = result + chr(byte[0])

        if chr(byte[0]) == termination:
          break

    sleep(100)

  return result

After this, we will initialize the serial interface to work with pins 0 and 1 from the micro:bit board. After this, the MicroPython prompt will become unavailable until we re-enable it again.

uart.init(baudrate=9600, tx = pin0, rx = pin1)

Then, we will take care of flushing the dummy byte that is sent to the serial port after we initialize the serial interface. Note however that this issue only happens in older versions of MicroPython, such as 1.7.0 (the one I’m using). In newer versions that no longer have this issue, we can skip this procedure.

uart.write("\r")
readUntil(uart, '\r')

Next, we will send the command to connect the UART OBLOQ to the WiFi network and wait for the procedure to finish, leveraging again the readUntil function. You can read in more detail about the WiFi connection procedure here.

uart.write("|2|1|yourNetworkName,yourNetworkPassword|\r")
readUntil(uart, '3')
readUntil(uart, '\r')

Finally, after the UART OBLOQ is connected to the WiFi network, we will send the GET request. You can read more about the details of the command we need to send on this tutorial. To sum up, the command takes the format shown below.

|3|1|destinationURL|

The destination URL has the following format, where you should change #yourFlaskMachineIp# by the IP of the machine that is hosting the Flask server:

http://#yourFlaskMachineIp#:8090/get

You can check below the MicroPython code to send this command:

uart.write("|3|1|http://192.168.1.83:8090/get|\r")

The UART OBLOQ answers to the command in the following format:

|3|HTTPResponseCode|ResponseBody|

So, we will leverage again the readUntil function to wait for the ‘3‘ character to be sent to the serial port. We don’t need to store the result of this function call in a variable since this part of the command response doesn’t contain any useful information.

Then, we will call the function again, now to wait for the “\r” character, which signals the end of the UART OBLOQ command response. This time, we will store the readUntil function response, which contains the HTTP response code and body.

readUntil(uart, '3')
result = readUntil(uart, '\r')

To finalize, we will re-enable the Python prompt and then print the request response we have obtained and stored in a variable. The final code can be seen below.

from microbit import uart, sleep

def readUntil(uartObject, termination):
  result = ''

  while True:
    if uartObject.any():

        byte = uartObject.read(1)

        result = result + chr(byte[0])

        if chr(byte[0]) == termination:
          break

    sleep(100)

  return result

uart.init(baudrate=9600, tx = pin0, rx = pin1)

uart.write("\r")
readUntil(uart, '\r')

uart.write("|2|1|yourNetworkName,yourNetworkPassword|\r")

readUntil(uart, '3')
readUntil(uart, '\r')

uart.write("|3|1|http://192.168.1.83:8090/get|\r")

readUntil(uart, '3')
result = readUntil(uart, '\r')

uart.init(baudrate=115200)
print(result)

Testing the code

To test the whole system, first run the Flask server using a Python tool of your choice. I’m using IDLE, a Python IDE.

Then, after connecting the micro:bit to the UART OBLOQ and powering both devices, simply run the previous MicroPython script. You should get an output similar to figure 1 after the script finishes the execution.

As can be seen, the code 200 was returned by the server, thus indicating success. Also, the body of the response corresponds to the “Received” string we have defined on Flask.

micro:bit UART OBLOQ GET request response

Figure 1 – Response of the GET request.

If you go back to the tool where you are running the Flask server, you should see the headers of the request getting printed.

Related Posts

 

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s