Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HTTP/S Server/Client documentations (examples + FW API) #256

Open
wants to merge 8 commits into
base: development-publish
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -744,6 +744,27 @@ theme = "doc-theme"
parent = "firmwareapi@pycom@network"
weight = 20

[[menu.main]]
name = "HTTPS"
url = "/firmwareapi/pycom/network/https/"
identifier = "firmwareapi@pycom@network@https"
parent = "firmwareapi@pycom@network"
weight = 40

[[menu.main]]
name = "Server"
url = "/firmwareapi/pycom/network/https/server/"
identifier = "firmwareapi@pycom@network@https@server"
parent = "firmwareapi@pycom@network@https"
weight = 10

[[menu.main]]
name = "Client"
url = "/firmwareapi/pycom/network/https/client/"
identifier = "firmwareapi@pycom@network@https@client"
parent = "firmwareapi@pycom@network@https"
weight = 10

[[menu.main]]
name = "Bluetooth"
url = "/firmwareapi/pycom/network/bluetooth/"
Expand Down
70 changes: 70 additions & 0 deletions content/firmwareapi/pycom/network/https/_index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
---
title: "HTTP/S"
aliases:
- chapter/firmwareapi/pycom/network/https
---

This module implements an HTTP and HTTPS Server and Client, operating individually or as both at the same time.

## Quick Usage Example
Below is an example demonstrating the usage of `HTTP_Server` and `HTTP_Client` at the same time:

```python
from network import WLAN
from network import HTTP_Server
from network import HTTP_Client

# The callback that handles the responses generated from the requests sent to a HTTP/S Server
def server_callback(uri, method, headers, body, new_uri, status):
print("Request URI: {}".format(uri))
print("Request Method: {}".format(method))
for key, value in headers.items():
print("Request headers:", (key, value))
print("Request Body: {}".format(body))
print("Request New URI: {}".format(new_uri))
print("Request Status: {}".format(status))

# The callback that handles the responses generated from the requests sent to a HTTP/S Server
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

that's the same comment as for server_callback

def client_callback(status, headers, body):
print("Response Status: {}".format(status))
for key, value in headers.items():
print("Response headers:", (key, value))
print("Response Body: {}".format(body))

# Connect to the network
wlan = WLAN(mode=WLAN.STA)
wlan.connect('your-ssid', auth=(WLAN.WPA2, 'your-key'))
while not wlan.isconnected():
pass
print(wlan.ifconfig())

# Initilise an HTTP Server
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Initi_A_lise

HTTP_Server.init()

# Add new resource to Server
res = HTTP_Server.add_resource('/resource', value = "Hello Client!")
# Register resource request handler
res.register_request_handler(HTTP_Server.GET, callback=server_callback)

# Initialize an HTTP Client
HTTP_Client.init('http://' + str(wlan.ifconfig()[0] + '/resource'), callback=client_callback)
# Send request with body
HTTP_Client.send_request(body='Hello Server!')
```
To implement HTTPS Server and Client, only the two init methods need to be changed. HTTP Server and Client init:

```python
# HTTP Server init
HTTP_Server.init()

# HTTP Client init
HTTP_Client.init('http://' + str(wlan.ifconfig()[0] + '/resource'), callback=client_callback)
```
HTTPS Server and Client init:
```python
# HTTPS Server init
HTTP_Server.init(port=443, keyfile='/flash/cert/prvtkey.pem', certfile='/flash/cert/cacert.pem')

# HTTPS Client init
HTTP_Client.init('https://' + str(wlan.ifconfig()[0] + '/resource'), callback=client_callback)
```
141 changes: 141 additions & 0 deletions content/firmwareapi/pycom/network/https/client.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
---
title: "HTTP/S Client"
aliases:
- firmwareapi/pycom/network/https/client.html
- firmwareapi/pycom/network/https/client.md
- chapter/firmwareapi/pycom/network/https/client
---
This module implements HTTP/S Client.

## Quick Usage Example

```python
from network import WLAN
from network import HTTP_Client

# The callback that handles the responses generated from the requests sent to a HTTP/S Server
def client_callback(status, headers, body):
print("Status Code: {}".format(status))
for key, value in headers.items():
print(key, ":", value)
print("Body: {}".format(body))

# Connect to the network
wlan = WLAN(mode=WLAN.STA)
wlan.connect('your-ssid', auth=(WLAN.WPA2, 'your-key'))
while not wlan.isconnected():
pass
print(wlan.ifconfig())

# Initialize HTTP Client
HTTP_Client.init("http://httpbin.org/get", callback=client_callback)
# Send request with GET method
HTTP_Client.send_request(method=HTTP_Client.GET)

# Set HTTPS url
HTTP_Client.url("https://httpbin.org/post")
# Send request with POST method and custom body
HTTP_Client.send_request(method=HTTP_Client.POST, body='post data')

# Optionally deinit Client
HTTP_Client.deinit()
```

## Initialization

#### HTTP_Client.init(url, *, auth=None, callback=None)

Initialize the HTTP_Client module.

The arguments are:

* `url` is the address where the HTTP_Client module handles communication. Based on HTTP or HTTPS Client mode, `url` string must be started with 'http://' or 'https://' respectively.
* `auth` is a tuple with (username, password). `Basic` authentication is supported in case of configured username and password.
* `callback` registers a callback function which will be called when a response received on the Client's request. `callback` must have the following arguments:
* `status` is the status code issued by a Server in response to a Client's request (e.g. `200` OK or `404` Not Found).
* `headers` is a dictionary contains all the response headers as key-value pairs. Size of `headers` depends on the number of headers received.
* `body` is the message body or payload transmitted in response.

## Methods:

#### HTTP_Client.deinit()

Disables and deinitiates HTTP_Client module.

#### HTTP_Client.url(url)

Get or set the `url` for HTTP_Client.
* Calling method without argument gets the currently set `url` as string.
* `url` is the address where the HTTP_Client module handles communication. Based on HTTP or HTTPS Client mode, `url` string must be started with 'http://' or 'https://.
This method (re)initiates HTTP_Client.

```python
# Get the url of Client
HTTP_Client.url()

# Set the url for Client
HTTP_Client.url("http://httpbin.org/get")
```

#### HTTP_Client.auth(auth)

Get or set the `auth` for HTTP_Client.
* Calling method without argument gets the currently set `auth` as tuple.
* `auth` is a tuple with (username, password). `Basic` authentication is supported in case of configured username and password. Setting empty strings ("") for username and password disables `Basic` authentication.

```python
# Get the auth of Client
HTTP_Client.auth()

# Set the auth for Client
HTTP_Client.auth("user", "pass")

# Disable the auth for Client
HTTP_Client.auth("", "")
```

#### HTTP_Client.callback(callback, *, action=True)

Register or unregister method for HTTP_Client's response handler.
* `callback` registers/unregisters (based on `action` flag) a callback function which will be called when a response received on the Client's request. `callback` must have the following arguments:
* `status` is the status code issued by a Server in response to a Client's request (e.g. `200` OK or `404` Not Found).
* `headers` is a dictionary contains all the response headers as key-value pairs. Size of `headers` depends on the number of headers received.
* `body` is the message body or payload transmitted in response.
* `action` is a flag which decides if the given `callback` is registered (`action`=True) or unregistered(`action`=False).

```python
# The callback that handles the responses generated from the requests sent to a HTTP/S Server
def client_callback(status, headers, body):
# Define callback method
pass

# Register callback for Client
HTTP_Client.callback(client_callback)

# Unregister callback for Client
HTTP_Client.callback(client_callback, action=False)
```

#### HTTP\_Client.send\_request(method=HTTP_Client.GET, body=None, content_type=HTTP_Client.TEXT, accept=None, user_agent='ESP32 HTTP Client/1.0')

* `method` is the method to be sent to the server, can be: `HTTP_Client.GET`, `HTTP_Client.POST`, `HTTP_Client.PUT` or `HTTP_Client.DELETE`.
* `body` is the message body (or content) of the request in string format.
* `content_type` is the Content-Type header of the request, can be: `HTTP_Client.TEXT`, `HTTP_Client.XML`, `HTTP_Client.PLAIN`, `HTTP_Client.JSON`, `HTTP_Client.OCTET` or `HTTP_Client.APP_XML`.
* `accept` is the Accept header of the request in string format.
* `user_agent` is the User-Agent header of the request in string format, which lets server identify the client. The default value is: \'ESP32 HTTP Client/1.0\'.

## Constants
* HTTP_Client methods: `HTTP_Client.GET`, `HTTP_Client.POST`, `HTTP_Client.PUT`, `HTTP_Client.DELETE`
* HTTP_Client media types:

`HTTP_Client.TEXT`: HyperText Markup Language (HTML): "text/html"

`HTTP_Client.XML`: XML format: "text/xml"

`HTTP_Client.PLAIN`: Text format: "text/plain"

`HTTP_Client.JSON`: Json format: "application/json"

`HTTP_Client.OCTET`: Binary data: "application/octet-stream"

`HTTP_Client.APP_XML`: Json format: "application/xml
Loading