HTTPD and Testing - mriksman/esp-idf-homekit GitHub Wiki
HTTP Server and Testing
Running Flask
Flask is a lightweight templating system but is also handy for quickly serving up static HTML and responding to POST/GET.
Install flask with pip install flask
.
Create a python script file (server.py
) and put this in the contents;
#!/usr/bin/env python
from flask import Flask, request, jsonify
import os
import os.path
import logging
import json
base_path = os.path.join(os.path.dirname(os.path.realpath(__file__)), '..')
app = Flask(
__name__,
static_folder=os.path.join(base_path, 'web')
)
@app.route('/')
def root():
return app.send_static_file('wifi.html')
@app.route("/ap.json", methods=["GET"])
def ap_json():
with open(base_path+'\\tools\\ap.json') as json_file:
data = json.load(json_file)
return jsonify(data)
@app.route("/status.json", methods=["GET"])
def status_json():
with open(base_path+'\\tools\\status.json') as json_file:
data = json.load(json_file)
return jsonify(data)
@app.route("/connect.json", methods=["POST"])
def json_example():
if request.is_json:
req = request.get_json()
print(req)
return "JSON received!", 200
else:
return "Request was not JSON", 400
app.run(host='0.0.0.0', debug=True)
ESP HTTPD Server
Legacy Changes
ESP8266 RTOS SDK sent error responses with helper functions;
esp_err_t httpd_resp_send_404(httpd_req_t *r);
esp_err_t httpd_resp_send_408(httpd_req_t *r);
esp_err_t httpd_resp_send_500(httpd_req_t *r);
Which calls a private function httpd_resp_send_err(r, HTTPD_404_NOT_FOUND)
;
case HTTPD_404_NOT_FOUND:
status = "404 Not Found";
msg = "This URI doesn't exist";
httpd_resp_set_status (req, status);
httpd_resp_set_type (req, HTTPD_TYPE_TEXT);
httpd_resp_send (req, msg, strlen(msg));
It also had these defines
#define HTTPD_200 "200 OK" /*!< HTTP Response 200 */
#define HTTPD_204 "204 No Content" /*!< HTTP Response 204 */
#define HTTPD_207 "207 Multi-Status" /*!< HTTP Response 207 */
#define HTTPD_400 "400 Bad Request" /*!< HTTP Response 400 */
#define HTTPD_404 "404 Not Found" /*!< HTTP Response 404 */
#define HTTPD_408 "408 Request Timeout" /*!< HTTP Response 408 */
#define HTTPD_500 "500 Internal Server Error" /*!< HTTP Response 500 */
So you can send other errors;
httpd_resp_set_status(req, HTTPD_500);
httpd_resp_send(req, STR, strlen(STR));
ESP-IDF has consolidated this function and made it a public function httpd_resp_send_err(httpd_req_t *req, httpd_err_code_t error, const char *msg)
with an enumeration
typedef enum {
HTTPD_500_INTERNAL_SERVER_ERROR = 0,
HTTPD_501_METHOD_NOT_IMPLEMENTED,
HTTPD_505_VERSION_NOT_SUPPORTED,
HTTPD_400_BAD_REQUEST,
HTTPD_404_NOT_FOUND,
HTTPD_405_METHOD_NOT_ALLOWED,
HTTPD_408_REQ_TIMEOUT,
HTTPD_411_LENGTH_REQUIRED,
HTTPD_414_URI_TOO_LONG,
HTTPD_431_REQ_HDR_FIELDS_TOO_LARGE,
HTTPD_ERR_CODE_MAX
} httpd_err_code_t;
It supports the old helper functions as well
static inline esp_err_t httpd_resp_send_404(httpd_req_t *r) {
return httpd_resp_send_err(r, HTTPD_404_NOT_FOUND, NULL);
}