mirror of
https://github.com/espressif/esp-idf.git
synced 2026-05-19 23:45:28 +02:00
Merge branch 'master' into feature/cmake
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
# Protocols Examples
|
||||
|
||||
Implementation of internet communication protocols and services.
|
||||
|
||||
See the [README.md](../README.md) file in the upper level [examples](../) directory for more information about examples.
|
||||
# Protocols Examples
|
||||
|
||||
Implementation of internet communication protocols and services.
|
||||
|
||||
See the [README.md](../README.md) file in the upper level [examples](../) directory for more information about examples.
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
#
|
||||
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
|
||||
# project subdirectory.
|
||||
#
|
||||
PROJECT_NAME := asio_chatclient
|
||||
|
||||
include $(IDF_PATH)/make/project.mk
|
||||
@@ -0,0 +1,19 @@
|
||||
# ASIO chat server example
|
||||
|
||||
Simple asio chat client using WiFi STA
|
||||
|
||||
## Example workflow
|
||||
|
||||
- WiFi STA is started and trying to connect to the access point defined through `make menuconfig`
|
||||
- Once connected and acquired IP address ASIO chat client connects to a corresponding server whose port number and ip are defined through `make menuconfig`
|
||||
- Chat client receives all messages from other chat clients, also it sends message received from stdin using `make monitor`
|
||||
|
||||
## Running the example
|
||||
|
||||
- Run `make menuconfig` to configure the access point's SSID and Password and server ip address and port number
|
||||
- Start chat server either on host machine or as another ESP device running chat_server example
|
||||
- Run `make flash monitor` to build and upload the example to your board and connect to it's serial terminal
|
||||
- Wait for WiFi to connect to your access point
|
||||
- Receive and send messages to/from other clients on stdin/stdout via serial terminal.
|
||||
|
||||
See the README.md file in the upper level 'examples' directory for more information about examples.
|
||||
@@ -0,0 +1,100 @@
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
from socket import *
|
||||
from threading import Thread
|
||||
import time
|
||||
|
||||
# this is a test case write with tiny-test-fw.
|
||||
# to run test cases outside tiny-test-fw,
|
||||
# we need to set environment variable `TEST_FW_PATH`,
|
||||
# then get and insert `TEST_FW_PATH` to sys path before import FW module
|
||||
test_fw_path = os.getenv("TEST_FW_PATH")
|
||||
if test_fw_path and test_fw_path not in sys.path:
|
||||
sys.path.insert(0, test_fw_path)
|
||||
|
||||
import TinyFW
|
||||
import IDF
|
||||
|
||||
global g_client_response;
|
||||
global g_msg_to_client;
|
||||
|
||||
g_client_response = ""
|
||||
g_msg_to_client = " 3XYZ"
|
||||
|
||||
def get_my_ip():
|
||||
s1 = socket(AF_INET, SOCK_DGRAM)
|
||||
s1.connect(("8.8.8.8", 80))
|
||||
my_ip = s1.getsockname()[0]
|
||||
s1.close()
|
||||
return my_ip
|
||||
|
||||
def chat_server_sketch(my_ip):
|
||||
global g_client_response
|
||||
print("Starting the server on {}".format(my_ip))
|
||||
port=2222
|
||||
s=socket(AF_INET, SOCK_STREAM)
|
||||
s.settimeout(600)
|
||||
s.bind((my_ip, port))
|
||||
s.listen(1)
|
||||
q,addr=s.accept()
|
||||
print("connection accepted")
|
||||
q.settimeout(30)
|
||||
q.send(g_msg_to_client)
|
||||
data = q.recv(1024)
|
||||
# check if received initial empty message
|
||||
if (len(data)>4):
|
||||
g_client_response = data
|
||||
else:
|
||||
g_client_response = q.recv(1024)
|
||||
print("received from client {}".format(g_client_response))
|
||||
s.close()
|
||||
print("server closed")
|
||||
|
||||
@IDF.idf_example_test(env_tag="Example_WIFI")
|
||||
def test_examples_protocol_asio_chat_client(env, extra_data):
|
||||
"""
|
||||
steps: |
|
||||
1. Test to start simple tcp server
|
||||
2. `dut1` joins AP
|
||||
3. Test injects server IP to `dut1`via stdin
|
||||
4. Test evaluates `dut1` receives a message server placed
|
||||
5. Test injects a message to `dut1` to be sent as chat_client message
|
||||
6. Test evaluates received test message in host server
|
||||
"""
|
||||
global g_client_response
|
||||
global g_msg_to_client
|
||||
test_msg="ABC"
|
||||
dut1 = env.get_dut("chat_client", "examples/protocols/asio/chat_client")
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "asio_chatclient.bin")
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
IDF.log_performance("asio_chatclient_size", "{}KB".format(bin_size//1024))
|
||||
IDF.check_performance("asio_chatclient_size", bin_size//1024)
|
||||
# 1. start a tcp server on the host
|
||||
host_ip = get_my_ip()
|
||||
thread1 = Thread(target = chat_server_sketch, args = (host_ip,))
|
||||
thread1.start()
|
||||
# 2. start the dut test and wait till client gets IP address
|
||||
dut1.start_app()
|
||||
data = dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)
|
||||
# 3. send host's IP to the client i.e. the `dut1`
|
||||
dut1.write(host_ip)
|
||||
# 4. client `dut1` should receive a message
|
||||
dut1.expect(g_msg_to_client[4:]) # Strip out the front 4 bytes of message len (see chat_message protocol)
|
||||
# 5. write test message from `dut1` chat_client to the server
|
||||
dut1.write(test_msg)
|
||||
while g_client_response == "":
|
||||
time.sleep(1)
|
||||
print(g_client_response)
|
||||
# 6. evaluate host_server received this message
|
||||
if (g_client_response[4:7] == test_msg):
|
||||
print("PASS: Received correct message")
|
||||
pass
|
||||
else:
|
||||
print("Failure!")
|
||||
raise ValueError('Wrong data received from asi tcp server: {} (expected:{})'.format(g_client_response, test_msg))
|
||||
thread1.join()
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_examples_protocol_asio_chat_client()
|
||||
@@ -0,0 +1,10 @@
|
||||
#
|
||||
# Component Makefile
|
||||
#
|
||||
# This Makefile should, at the very least, just include $(SDK_PATH)/Makefile. By default,
|
||||
# this will take the sources in the src/ directory, compile them and link them into
|
||||
# lib(subdirectory_name).a in the build directory. This behaviour is entirely configurable,
|
||||
# please read the SDK documents if you need to do this.
|
||||
#
|
||||
|
||||
COMPONENT_SRCDIRS = .
|
||||
@@ -0,0 +1,136 @@
|
||||
/* Common WiFi Init as STA for ASIO examples
|
||||
|
||||
This example code is in the Public Domain (or CC0 licensed, at your option.)
|
||||
|
||||
Unless required by applicable law or agreed to in writing, this
|
||||
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
CONDITIONS OF ANY KIND, either express or implied.
|
||||
*/
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/event_groups.h"
|
||||
#include "esp_system.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_event_loop.h"
|
||||
#include "esp_log.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "driver/uart.h"
|
||||
#include "esp_console.h"
|
||||
#include "esp_vfs_dev.h"
|
||||
|
||||
#include "lwip/err.h"
|
||||
#include "lwip/sys.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
/* The examples use simple WiFi configuration that you can set via
|
||||
'make menuconfig'.
|
||||
|
||||
If you'd rather not, just change the below entries to strings with
|
||||
the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid"
|
||||
*/
|
||||
#define EXAMPLE_ESP_WIFI_SSID CONFIG_ESP_WIFI_SSID
|
||||
#define EXAMPLE_ESP_WIFI_PASS CONFIG_ESP_WIFI_PASSWORD
|
||||
|
||||
/* FreeRTOS event group to signal when we are connected*/
|
||||
static EventGroupHandle_t wifi_event_group;
|
||||
|
||||
/* The event group allows multiple bits for each event,
|
||||
but we only care about one event - are we connected
|
||||
to the AP with an IP? */
|
||||
const int WIFI_CONNECTED_BIT = BIT0;
|
||||
|
||||
static const char *TAG = "asio example wifi init";
|
||||
|
||||
/**
|
||||
* Definition of ASIO main method, which is called after network initialized
|
||||
*/
|
||||
void asio_main();
|
||||
|
||||
static esp_err_t event_handler(void *ctx, system_event_t *event)
|
||||
{
|
||||
switch(event->event_id) {
|
||||
case SYSTEM_EVENT_STA_START:
|
||||
esp_wifi_connect();
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_GOT_IP:
|
||||
ESP_LOGI(TAG, "got ip:%s",
|
||||
ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
|
||||
xEventGroupSetBits(wifi_event_group, WIFI_CONNECTED_BIT);
|
||||
break;
|
||||
case SYSTEM_EVENT_AP_STACONNECTED:
|
||||
ESP_LOGI(TAG, "station:" MACSTR " join, AID=%d",
|
||||
MAC2STR(event->event_info.sta_connected.mac),
|
||||
event->event_info.sta_connected.aid);
|
||||
break;
|
||||
case SYSTEM_EVENT_AP_STADISCONNECTED:
|
||||
ESP_LOGI(TAG, "station:" MACSTR "leave, AID=%d",
|
||||
MAC2STR(event->event_info.sta_disconnected.mac),
|
||||
event->event_info.sta_disconnected.aid);
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_DISCONNECTED:
|
||||
esp_wifi_connect();
|
||||
xEventGroupClearBits(wifi_event_group, WIFI_CONNECTED_BIT);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void wifi_init_sta()
|
||||
{
|
||||
wifi_event_group = xEventGroupCreate();
|
||||
|
||||
tcpip_adapter_init();
|
||||
ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL) );
|
||||
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||
wifi_config_t wifi_config;
|
||||
// zero out the config struct to ensure defaults are setup
|
||||
memset(&wifi_config, 0, sizeof(wifi_sta_config_t));
|
||||
// only copy ssid&password from example config
|
||||
strcpy((char*)(wifi_config.sta.ssid), EXAMPLE_ESP_WIFI_SSID);
|
||||
strcpy((char*)(wifi_config.sta.password), EXAMPLE_ESP_WIFI_PASS);
|
||||
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) );
|
||||
ESP_ERROR_CHECK(esp_wifi_start() );
|
||||
|
||||
ESP_LOGI(TAG, "wifi_init_sta finished.");
|
||||
ESP_LOGI(TAG, "connect to ap SSID:%s password:%s",
|
||||
EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
|
||||
}
|
||||
|
||||
extern "C" void app_main()
|
||||
{
|
||||
//Initialize NVS
|
||||
esp_err_t ret = nvs_flash_init();
|
||||
if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
ret = nvs_flash_init();
|
||||
}
|
||||
ESP_ERROR_CHECK(ret);
|
||||
|
||||
ESP_LOGI(TAG, "ESP_WIFI_MODE_AP");
|
||||
wifi_init_sta();
|
||||
|
||||
// Initialize VFS & UART so we can use std::cout/cin
|
||||
setvbuf(stdin, NULL, _IONBF, 0);
|
||||
setvbuf(stdout, NULL, _IONBF, 0);
|
||||
/* Install UART driver for interrupt-driven reads and writes */
|
||||
ESP_ERROR_CHECK( uart_driver_install( (uart_port_t)CONFIG_CONSOLE_UART_NUM,
|
||||
256, 0, 0, NULL, 0) );
|
||||
/* Tell VFS to use UART driver */
|
||||
esp_vfs_dev_uart_use_driver(CONFIG_CONSOLE_UART_NUM);
|
||||
esp_vfs_dev_uart_set_rx_line_endings(ESP_LINE_ENDINGS_CR);
|
||||
/* Move the caret to the beginning of the next line on '\n' */
|
||||
esp_vfs_dev_uart_set_tx_line_endings(ESP_LINE_ENDINGS_CRLF);
|
||||
|
||||
// wait till we receive IP, so asio realated code can be started
|
||||
xEventGroupWaitBits(wifi_event_group, WIFI_CONNECTED_BIT, 1, 1, portMAX_DELAY);
|
||||
|
||||
// network is ready, let's proceed with ASIO example
|
||||
asio_main();
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
menu "Example Configuration"
|
||||
|
||||
config ESP_WIFI_SSID
|
||||
string "WiFi SSID"
|
||||
default "myssid"
|
||||
help
|
||||
SSID (network name) for the example to connect to.
|
||||
|
||||
config ESP_WIFI_PASSWORD
|
||||
string "WiFi Password"
|
||||
default "mypassword"
|
||||
help
|
||||
WiFi password (WPA or WPA2) for the example to use.
|
||||
|
||||
config EXAMPLE_PORT
|
||||
string "asio example port number"
|
||||
default "2222"
|
||||
help
|
||||
Port number used by ASIO example
|
||||
|
||||
config EXAMPLE_SERVER_IP
|
||||
string "asio example server ip for this client to connect to (leave defalut=FROM_STDIN to enter the server address via serial terminal)"
|
||||
default "FROM_STDIN"
|
||||
help
|
||||
Please set the host name or ip address of corespondant server running
|
||||
|
||||
endmenu
|
||||
@@ -0,0 +1,165 @@
|
||||
//
|
||||
// chat_client.cpp
|
||||
// ~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <cstdlib>
|
||||
#include <deque>
|
||||
#include <iostream>
|
||||
#include <thread>
|
||||
#include "asio.hpp"
|
||||
#include "chat_message.hpp"
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
typedef std::deque<chat_message> chat_message_queue;
|
||||
|
||||
class chat_client
|
||||
{
|
||||
public:
|
||||
chat_client(asio::io_context& io_context,
|
||||
const tcp::resolver::results_type& endpoints)
|
||||
: io_context_(io_context),
|
||||
socket_(io_context)
|
||||
{
|
||||
do_connect(endpoints);
|
||||
}
|
||||
|
||||
void write(const chat_message& msg)
|
||||
{
|
||||
asio::post(io_context_,
|
||||
[this, msg]()
|
||||
{
|
||||
bool write_in_progress = !write_msgs_.empty();
|
||||
write_msgs_.push_back(msg);
|
||||
if (!write_in_progress)
|
||||
{
|
||||
do_write();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void close()
|
||||
{
|
||||
asio::post(io_context_, [this]() { socket_.close(); });
|
||||
}
|
||||
|
||||
private:
|
||||
void do_connect(const tcp::resolver::results_type& endpoints)
|
||||
{
|
||||
asio::async_connect(socket_, endpoints,
|
||||
[this](std::error_code ec, tcp::endpoint)
|
||||
{
|
||||
if (!ec)
|
||||
{
|
||||
do_read_header();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void do_read_header()
|
||||
{
|
||||
asio::async_read(socket_,
|
||||
asio::buffer(read_msg_.data(), chat_message::header_length),
|
||||
[this](std::error_code ec, std::size_t /*length*/)
|
||||
{
|
||||
if (!ec && read_msg_.decode_header())
|
||||
{
|
||||
do_read_body();
|
||||
}
|
||||
else
|
||||
{
|
||||
socket_.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void do_read_body()
|
||||
{
|
||||
asio::async_read(socket_,
|
||||
asio::buffer(read_msg_.body(), read_msg_.body_length()),
|
||||
[this](std::error_code ec, std::size_t /*length*/)
|
||||
{
|
||||
if (!ec)
|
||||
{
|
||||
std::cout.write(read_msg_.body(), read_msg_.body_length());
|
||||
std::cout << "\n";
|
||||
do_read_header();
|
||||
}
|
||||
else
|
||||
{
|
||||
socket_.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void do_write()
|
||||
{
|
||||
asio::async_write(socket_,
|
||||
asio::buffer(write_msgs_.front().data(),
|
||||
write_msgs_.front().length()),
|
||||
[this](std::error_code ec, std::size_t /*length*/)
|
||||
{
|
||||
if (!ec)
|
||||
{
|
||||
write_msgs_.pop_front();
|
||||
if (!write_msgs_.empty())
|
||||
{
|
||||
do_write();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
socket_.close();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
asio::io_context& io_context_;
|
||||
tcp::socket socket_;
|
||||
chat_message read_msg_;
|
||||
chat_message_queue write_msgs_;
|
||||
};
|
||||
|
||||
void read_line(char * line, int max_chars);
|
||||
|
||||
|
||||
void asio_main()
|
||||
{
|
||||
std::string name(CONFIG_EXAMPLE_SERVER_IP);
|
||||
std::string port(CONFIG_EXAMPLE_PORT);
|
||||
char line[chat_message::max_body_length + 1] = { 0 };
|
||||
|
||||
if (name == "FROM_STDIN") {
|
||||
std::cout << "Please enter ip address of chat server" << std::endl;
|
||||
if (std::cin.getline(line, chat_message::max_body_length + 1)) {
|
||||
name = line;
|
||||
std::cout << "Chat server IP:" << name << std::endl;
|
||||
}
|
||||
}
|
||||
|
||||
asio::io_context io_context;
|
||||
tcp::resolver resolver(io_context);
|
||||
auto endpoints = resolver.resolve(name, port);
|
||||
|
||||
chat_client c(io_context, endpoints);
|
||||
|
||||
std::thread t([&io_context](){ io_context.run(); });
|
||||
|
||||
while (std::cin.getline(line, chat_message::max_body_length + 1) && std::string(line) != "exit\n") {
|
||||
chat_message msg;
|
||||
msg.body_length(std::strlen(line));
|
||||
std::memcpy(msg.body(), line, msg.body_length());
|
||||
msg.encode_header();
|
||||
c.write(msg);
|
||||
}
|
||||
|
||||
c.close();
|
||||
t.join();
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//
|
||||
// chat_message.hpp
|
||||
// ~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef CHAT_MESSAGE_HPP
|
||||
#define CHAT_MESSAGE_HPP
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
class chat_message
|
||||
{
|
||||
public:
|
||||
enum { header_length = 4 };
|
||||
enum { max_body_length = 512 };
|
||||
|
||||
chat_message()
|
||||
: body_length_(0)
|
||||
{
|
||||
}
|
||||
|
||||
const char* data() const
|
||||
{
|
||||
return data_;
|
||||
}
|
||||
|
||||
char* data()
|
||||
{
|
||||
return data_;
|
||||
}
|
||||
|
||||
std::size_t length() const
|
||||
{
|
||||
return header_length + body_length_;
|
||||
}
|
||||
|
||||
const char* body() const
|
||||
{
|
||||
return data_ + header_length;
|
||||
}
|
||||
|
||||
char* body()
|
||||
{
|
||||
return data_ + header_length;
|
||||
}
|
||||
|
||||
std::size_t body_length() const
|
||||
{
|
||||
return body_length_;
|
||||
}
|
||||
|
||||
void body_length(std::size_t new_length)
|
||||
{
|
||||
body_length_ = new_length;
|
||||
if (body_length_ > max_body_length)
|
||||
body_length_ = max_body_length;
|
||||
}
|
||||
|
||||
bool decode_header()
|
||||
{
|
||||
char header[header_length + 1] = "";
|
||||
std::strncat(header, data_, header_length);
|
||||
body_length_ = std::atoi(header);
|
||||
if (body_length_ > max_body_length)
|
||||
{
|
||||
body_length_ = 0;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void encode_header()
|
||||
{
|
||||
char header[header_length + 1] = "";
|
||||
std::sprintf(header, "%4d", static_cast<int>(body_length_));
|
||||
std::memcpy(data_, header, header_length);
|
||||
}
|
||||
|
||||
private:
|
||||
char data_[header_length + max_body_length];
|
||||
std::size_t body_length_;
|
||||
};
|
||||
|
||||
#endif // CHAT_MESSAGE_HPP
|
||||
@@ -0,0 +1,8 @@
|
||||
#
|
||||
# Main component makefile.
|
||||
#
|
||||
# This Makefile can be left empty. By default, it will take the sources in the
|
||||
# src/ directory, compile them and link them into lib(subdirectory_name).a
|
||||
# in the build directory. This behaviour is entirely configurable,
|
||||
# please read the ESP-IDF documents if you need to do this.
|
||||
#
|
||||
@@ -0,0 +1 @@
|
||||
CONFIG_MAIN_TASK_STACK_SIZE=8192
|
||||
@@ -0,0 +1,7 @@
|
||||
#
|
||||
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
|
||||
# project subdirectory.
|
||||
#
|
||||
PROJECT_NAME := asio_chatserver
|
||||
|
||||
include $(IDF_PATH)/make/project.mk
|
||||
@@ -0,0 +1,22 @@
|
||||
# ASIO chat server example
|
||||
|
||||
Simple asio chat server using WiFi STA
|
||||
|
||||
## Example workflow
|
||||
|
||||
- WiFi STA is started and trying to connect to the access point defined through `make menuconfig`
|
||||
- Once connected and acquired IP address, ASIO chat server is started on port number defined through `make menuconfig`
|
||||
- Chat server echoes a message (received from any client) to all connected clients
|
||||
|
||||
## Running the example
|
||||
|
||||
- Run `make menuconfig` to configure the access point's SSID and Password and port number
|
||||
- Run `make flash monitor` to build and upload the example to your board and connect to it's serial terminal
|
||||
- Wait for WiFi to connect to your access point (note the IP address)
|
||||
- Connect to the server using multiple clients, for example using any option below
|
||||
- build and run asi chat client on your host machine
|
||||
- run chat_client asio example on ESP platform
|
||||
- since chat message consist of ascii size and message, it is possible to
|
||||
netcat `nc IP PORT` and type for example ` 4ABC<CR>` to transmit 'ABC\n'
|
||||
|
||||
See the README.md file in the upper level 'examples' directory for more information about examples.
|
||||
@@ -0,0 +1,57 @@
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
from socket import *
|
||||
|
||||
|
||||
# this is a test case write with tiny-test-fw.
|
||||
# to run test cases outside tiny-test-fw,
|
||||
# we need to set environment variable `TEST_FW_PATH`,
|
||||
# then get and insert `TEST_FW_PATH` to sys path before import FW module
|
||||
test_fw_path = os.getenv("TEST_FW_PATH")
|
||||
if test_fw_path and test_fw_path not in sys.path:
|
||||
sys.path.insert(0, test_fw_path)
|
||||
|
||||
import TinyFW
|
||||
import IDF
|
||||
|
||||
|
||||
|
||||
|
||||
@IDF.idf_example_test(env_tag="Example_WIFI")
|
||||
def test_examples_protocol_asio_chat_server(env, extra_data):
|
||||
"""
|
||||
steps: |
|
||||
1. join AP
|
||||
2. Start server
|
||||
3. Test connects to server and sends a test message
|
||||
4. Test evaluates received test message from server
|
||||
"""
|
||||
test_msg=" 4ABC\n"
|
||||
dut1 = env.get_dut("chat_server", "examples/protocols/asio/chat_server")
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "asio_chatserver.bin")
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
IDF.log_performance("asio_chatserver_bin_size", "{}KB".format(bin_size//1024))
|
||||
IDF.check_performance("asio_chatserver_size", bin_size//1024)
|
||||
# 1. start test
|
||||
dut1.start_app()
|
||||
# 2. get the server IP address
|
||||
data = dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)
|
||||
# 3. create tcp client and connect to server
|
||||
cli = socket(AF_INET,SOCK_STREAM)
|
||||
cli.settimeout(30)
|
||||
cli.connect((data[0],80))
|
||||
cli.send(test_msg)
|
||||
data = cli.recv(1024)
|
||||
# 4. check the message received back from the server
|
||||
if (data == test_msg):
|
||||
print("PASS: Received correct message {}".format(data))
|
||||
pass
|
||||
else:
|
||||
print("Failure!")
|
||||
raise ValueError('Wrong data received from asi tcp server: {} (expoected:{})'.format(data, test_msg))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_examples_protocol_asio_chat_server()
|
||||
@@ -0,0 +1,10 @@
|
||||
#
|
||||
# Component Makefile
|
||||
#
|
||||
# This Makefile should, at the very least, just include $(SDK_PATH)/Makefile. By default,
|
||||
# this will take the sources in the src/ directory, compile them and link them into
|
||||
# lib(subdirectory_name).a in the build directory. This behaviour is entirely configurable,
|
||||
# please read the SDK documents if you need to do this.
|
||||
#
|
||||
|
||||
COMPONENT_SRCDIRS = .
|
||||
@@ -0,0 +1,136 @@
|
||||
/* Common WiFi Init as STA for ASIO examples
|
||||
|
||||
This example code is in the Public Domain (or CC0 licensed, at your option.)
|
||||
|
||||
Unless required by applicable law or agreed to in writing, this
|
||||
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
CONDITIONS OF ANY KIND, either express or implied.
|
||||
*/
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/event_groups.h"
|
||||
#include "esp_system.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_event_loop.h"
|
||||
#include "esp_log.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "driver/uart.h"
|
||||
#include "esp_console.h"
|
||||
#include "esp_vfs_dev.h"
|
||||
|
||||
#include "lwip/err.h"
|
||||
#include "lwip/sys.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
/* The examples use simple WiFi configuration that you can set via
|
||||
'make menuconfig'.
|
||||
|
||||
If you'd rather not, just change the below entries to strings with
|
||||
the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid"
|
||||
*/
|
||||
#define EXAMPLE_ESP_WIFI_SSID CONFIG_ESP_WIFI_SSID
|
||||
#define EXAMPLE_ESP_WIFI_PASS CONFIG_ESP_WIFI_PASSWORD
|
||||
|
||||
/* FreeRTOS event group to signal when we are connected*/
|
||||
static EventGroupHandle_t wifi_event_group;
|
||||
|
||||
/* The event group allows multiple bits for each event,
|
||||
but we only care about one event - are we connected
|
||||
to the AP with an IP? */
|
||||
const int WIFI_CONNECTED_BIT = BIT0;
|
||||
|
||||
static const char *TAG = "asio example wifi init";
|
||||
|
||||
/**
|
||||
* Definition of ASIO main method, which is called after network initialized
|
||||
*/
|
||||
void asio_main();
|
||||
|
||||
static esp_err_t event_handler(void *ctx, system_event_t *event)
|
||||
{
|
||||
switch(event->event_id) {
|
||||
case SYSTEM_EVENT_STA_START:
|
||||
esp_wifi_connect();
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_GOT_IP:
|
||||
ESP_LOGI(TAG, "got ip:%s",
|
||||
ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
|
||||
xEventGroupSetBits(wifi_event_group, WIFI_CONNECTED_BIT);
|
||||
break;
|
||||
case SYSTEM_EVENT_AP_STACONNECTED:
|
||||
ESP_LOGI(TAG, "station:" MACSTR " join, AID=%d",
|
||||
MAC2STR(event->event_info.sta_connected.mac),
|
||||
event->event_info.sta_connected.aid);
|
||||
break;
|
||||
case SYSTEM_EVENT_AP_STADISCONNECTED:
|
||||
ESP_LOGI(TAG, "station:" MACSTR "leave, AID=%d",
|
||||
MAC2STR(event->event_info.sta_disconnected.mac),
|
||||
event->event_info.sta_disconnected.aid);
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_DISCONNECTED:
|
||||
esp_wifi_connect();
|
||||
xEventGroupClearBits(wifi_event_group, WIFI_CONNECTED_BIT);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void wifi_init_sta()
|
||||
{
|
||||
wifi_event_group = xEventGroupCreate();
|
||||
|
||||
tcpip_adapter_init();
|
||||
ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL) );
|
||||
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||
wifi_config_t wifi_config;
|
||||
// zero out the config struct to ensure defaults are setup
|
||||
memset(&wifi_config, 0, sizeof(wifi_sta_config_t));
|
||||
// only copy ssid&password from example config
|
||||
strcpy((char*)(wifi_config.sta.ssid), EXAMPLE_ESP_WIFI_SSID);
|
||||
strcpy((char*)(wifi_config.sta.password), EXAMPLE_ESP_WIFI_PASS);
|
||||
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) );
|
||||
ESP_ERROR_CHECK(esp_wifi_start() );
|
||||
|
||||
ESP_LOGI(TAG, "wifi_init_sta finished.");
|
||||
ESP_LOGI(TAG, "connect to ap SSID:%s password:%s",
|
||||
EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
|
||||
}
|
||||
|
||||
extern "C" void app_main()
|
||||
{
|
||||
//Initialize NVS
|
||||
esp_err_t ret = nvs_flash_init();
|
||||
if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
ret = nvs_flash_init();
|
||||
}
|
||||
ESP_ERROR_CHECK(ret);
|
||||
|
||||
ESP_LOGI(TAG, "ESP_WIFI_MODE_AP");
|
||||
wifi_init_sta();
|
||||
|
||||
// Initialize VFS & UART so we can use std::cout/cin
|
||||
setvbuf(stdin, NULL, _IONBF, 0);
|
||||
setvbuf(stdout, NULL, _IONBF, 0);
|
||||
/* Install UART driver for interrupt-driven reads and writes */
|
||||
ESP_ERROR_CHECK( uart_driver_install( (uart_port_t)CONFIG_CONSOLE_UART_NUM,
|
||||
256, 0, 0, NULL, 0) );
|
||||
/* Tell VFS to use UART driver */
|
||||
esp_vfs_dev_uart_use_driver(CONFIG_CONSOLE_UART_NUM);
|
||||
esp_vfs_dev_uart_set_rx_line_endings(ESP_LINE_ENDINGS_CR);
|
||||
/* Move the caret to the beginning of the next line on '\n' */
|
||||
esp_vfs_dev_uart_set_tx_line_endings(ESP_LINE_ENDINGS_CRLF);
|
||||
|
||||
// wait till we receive IP, so asio realated code can be started
|
||||
xEventGroupWaitBits(wifi_event_group, WIFI_CONNECTED_BIT, 1, 1, portMAX_DELAY);
|
||||
|
||||
// network is ready, let's proceed with ASIO example
|
||||
asio_main();
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
menu "Example Configuration"
|
||||
|
||||
config ESP_WIFI_SSID
|
||||
string "WiFi SSID"
|
||||
default "myssid"
|
||||
help
|
||||
SSID (network name) for the example to connect to.
|
||||
|
||||
config ESP_WIFI_PASSWORD
|
||||
string "WiFi Password"
|
||||
default "mypassword"
|
||||
help
|
||||
WiFi password (WPA or WPA2) for the example to use.
|
||||
|
||||
config EXAMPLE_PORT
|
||||
string "asio example port number"
|
||||
default "80"
|
||||
help
|
||||
Port number used by ASIO example
|
||||
|
||||
endmenu
|
||||
@@ -0,0 +1,91 @@
|
||||
//
|
||||
// chat_message.hpp
|
||||
// ~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#ifndef CHAT_MESSAGE_HPP
|
||||
#define CHAT_MESSAGE_HPP
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
class chat_message
|
||||
{
|
||||
public:
|
||||
enum { header_length = 4 };
|
||||
enum { max_body_length = 512 };
|
||||
|
||||
chat_message()
|
||||
: body_length_(0)
|
||||
{
|
||||
}
|
||||
|
||||
const char* data() const
|
||||
{
|
||||
return data_;
|
||||
}
|
||||
|
||||
char* data()
|
||||
{
|
||||
return data_;
|
||||
}
|
||||
|
||||
std::size_t length() const
|
||||
{
|
||||
return header_length + body_length_;
|
||||
}
|
||||
|
||||
const char* body() const
|
||||
{
|
||||
return data_ + header_length;
|
||||
}
|
||||
|
||||
char* body()
|
||||
{
|
||||
return data_ + header_length;
|
||||
}
|
||||
|
||||
std::size_t body_length() const
|
||||
{
|
||||
return body_length_;
|
||||
}
|
||||
|
||||
void body_length(std::size_t new_length)
|
||||
{
|
||||
body_length_ = new_length;
|
||||
if (body_length_ > max_body_length)
|
||||
body_length_ = max_body_length;
|
||||
}
|
||||
|
||||
bool decode_header()
|
||||
{
|
||||
char header[header_length + 1] = "";
|
||||
std::strncat(header, data_, header_length);
|
||||
body_length_ = std::atoi(header);
|
||||
if (body_length_ > max_body_length)
|
||||
{
|
||||
body_length_ = 0;
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void encode_header()
|
||||
{
|
||||
char header[header_length + 1] = "";
|
||||
std::sprintf(header, "%4d", static_cast<int>(body_length_));
|
||||
std::memcpy(data_, header, header_length);
|
||||
}
|
||||
|
||||
private:
|
||||
char data_[header_length + max_body_length];
|
||||
std::size_t body_length_;
|
||||
};
|
||||
|
||||
#endif // CHAT_MESSAGE_HPP
|
||||
@@ -0,0 +1,214 @@
|
||||
//
|
||||
// chat_server.cpp
|
||||
// ~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <cstdlib>
|
||||
#include <deque>
|
||||
#include <iostream>
|
||||
#include <list>
|
||||
#include <memory>
|
||||
#include <set>
|
||||
#include <utility>
|
||||
#include "asio.hpp"
|
||||
#include "chat_message.hpp"
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
//----------------------------------------------------------------------
|
||||
|
||||
typedef std::deque<chat_message> chat_message_queue;
|
||||
|
||||
//----------------------------------------------------------------------
|
||||
|
||||
class chat_participant
|
||||
{
|
||||
public:
|
||||
virtual ~chat_participant() {}
|
||||
virtual void deliver(const chat_message& msg) = 0;
|
||||
};
|
||||
|
||||
typedef std::shared_ptr<chat_participant> chat_participant_ptr;
|
||||
|
||||
//----------------------------------------------------------------------
|
||||
|
||||
class chat_room
|
||||
{
|
||||
public:
|
||||
void join(chat_participant_ptr participant)
|
||||
{
|
||||
participants_.insert(participant);
|
||||
for (auto msg: recent_msgs_)
|
||||
participant->deliver(msg);
|
||||
}
|
||||
|
||||
void leave(chat_participant_ptr participant)
|
||||
{
|
||||
participants_.erase(participant);
|
||||
}
|
||||
|
||||
void deliver(const chat_message& msg)
|
||||
{
|
||||
recent_msgs_.push_back(msg);
|
||||
while (recent_msgs_.size() > max_recent_msgs)
|
||||
recent_msgs_.pop_front();
|
||||
|
||||
for (auto participant: participants_)
|
||||
participant->deliver(msg);
|
||||
}
|
||||
|
||||
private:
|
||||
std::set<chat_participant_ptr> participants_;
|
||||
enum { max_recent_msgs = 100 };
|
||||
chat_message_queue recent_msgs_;
|
||||
};
|
||||
|
||||
//----------------------------------------------------------------------
|
||||
|
||||
class chat_session
|
||||
: public chat_participant,
|
||||
public std::enable_shared_from_this<chat_session>
|
||||
{
|
||||
public:
|
||||
chat_session(tcp::socket socket, chat_room& room)
|
||||
: socket_(std::move(socket)),
|
||||
room_(room)
|
||||
{
|
||||
}
|
||||
|
||||
void start()
|
||||
{
|
||||
room_.join(shared_from_this());
|
||||
do_read_header();
|
||||
}
|
||||
|
||||
void deliver(const chat_message& msg)
|
||||
{
|
||||
bool write_in_progress = !write_msgs_.empty();
|
||||
write_msgs_.push_back(msg);
|
||||
if (!write_in_progress)
|
||||
{
|
||||
do_write();
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
void do_read_header()
|
||||
{
|
||||
auto self(shared_from_this());
|
||||
asio::async_read(socket_,
|
||||
asio::buffer(read_msg_.data(), chat_message::header_length),
|
||||
[this, self](std::error_code ec, std::size_t /*length*/)
|
||||
{
|
||||
if (!ec && read_msg_.decode_header())
|
||||
{
|
||||
do_read_body();
|
||||
}
|
||||
else
|
||||
{
|
||||
room_.leave(shared_from_this());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void do_read_body()
|
||||
{
|
||||
auto self(shared_from_this());
|
||||
asio::async_read(socket_,
|
||||
asio::buffer(read_msg_.body(), read_msg_.body_length()),
|
||||
[this, self](std::error_code ec, std::size_t /*length*/)
|
||||
{
|
||||
if (!ec)
|
||||
{
|
||||
room_.deliver(read_msg_);
|
||||
do_read_header();
|
||||
}
|
||||
else
|
||||
{
|
||||
room_.leave(shared_from_this());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void do_write()
|
||||
{
|
||||
auto self(shared_from_this());
|
||||
asio::async_write(socket_,
|
||||
asio::buffer(write_msgs_.front().data(),
|
||||
write_msgs_.front().length()),
|
||||
[this, self](std::error_code ec, std::size_t /*length*/)
|
||||
{
|
||||
if (!ec)
|
||||
{
|
||||
write_msgs_.pop_front();
|
||||
if (!write_msgs_.empty())
|
||||
{
|
||||
do_write();
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
room_.leave(shared_from_this());
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
tcp::socket socket_;
|
||||
chat_room& room_;
|
||||
chat_message read_msg_;
|
||||
chat_message_queue write_msgs_;
|
||||
};
|
||||
|
||||
//----------------------------------------------------------------------
|
||||
|
||||
class chat_server
|
||||
{
|
||||
public:
|
||||
chat_server(asio::io_context& io_context,
|
||||
const tcp::endpoint& endpoint)
|
||||
: acceptor_(io_context, endpoint)
|
||||
{
|
||||
do_accept();
|
||||
}
|
||||
|
||||
private:
|
||||
void do_accept()
|
||||
{
|
||||
acceptor_.async_accept(
|
||||
[this](std::error_code ec, tcp::socket socket)
|
||||
{
|
||||
if (!ec)
|
||||
{
|
||||
std::make_shared<chat_session>(std::move(socket), room_)->start();
|
||||
}
|
||||
|
||||
do_accept();
|
||||
});
|
||||
}
|
||||
|
||||
tcp::acceptor acceptor_;
|
||||
chat_room room_;
|
||||
};
|
||||
|
||||
//----------------------------------------------------------------------
|
||||
|
||||
int asio_main()
|
||||
{
|
||||
asio::io_context io_context;
|
||||
|
||||
std::list<chat_server> servers;
|
||||
|
||||
{
|
||||
tcp::endpoint endpoint(tcp::v4(), std::atoi(CONFIG_EXAMPLE_PORT));
|
||||
servers.emplace_back(io_context, endpoint);
|
||||
}
|
||||
|
||||
io_context.run();
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#
|
||||
# Main component makefile.
|
||||
#
|
||||
# This Makefile can be left empty. By default, it will take the sources in the
|
||||
# src/ directory, compile them and link them into lib(subdirectory_name).a
|
||||
# in the build directory. This behaviour is entirely configurable,
|
||||
# please read the ESP-IDF documents if you need to do this.
|
||||
#
|
||||
@@ -0,0 +1 @@
|
||||
CONFIG_MAIN_TASK_STACK_SIZE=8192
|
||||
@@ -0,0 +1,7 @@
|
||||
#
|
||||
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
|
||||
# project subdirectory.
|
||||
#
|
||||
PROJECT_NAME := asio_tcp_echoserver
|
||||
|
||||
include $(IDF_PATH)/make/project.mk
|
||||
@@ -0,0 +1,18 @@
|
||||
# ASIO tcp echo server example
|
||||
|
||||
Simple asio echo server using WiFi STA
|
||||
|
||||
## Example workflow
|
||||
|
||||
- WiFi STA is started and trying to connect to the access point defined through `make menuconfig`
|
||||
- Once connected and acquired IP address, ASIO tcp server is started on port number defined through `make menuconfig`
|
||||
- Server receives and echoes back messages transmitted from client
|
||||
|
||||
## Running the example
|
||||
|
||||
- Run `make menuconfig` to configure the access point's SSID and Password and port number
|
||||
- Run `make flash monitor` to build and upload the example to your board and connect to it's serial terminal
|
||||
- Wait for WiFi to connect to your access point (note the IP address)
|
||||
- You can now send a tcp message and check it is repeated, for example using netcat `nc IP PORT`
|
||||
|
||||
See the README.md file in the upper level 'examples' directory for more information about examples.
|
||||
@@ -0,0 +1,60 @@
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
from socket import *
|
||||
|
||||
|
||||
# this is a test case write with tiny-test-fw.
|
||||
# to run test cases outside tiny-test-fw,
|
||||
# we need to set environment variable `TEST_FW_PATH`,
|
||||
# then get and insert `TEST_FW_PATH` to sys path before import FW module
|
||||
test_fw_path = os.getenv("TEST_FW_PATH")
|
||||
if test_fw_path and test_fw_path not in sys.path:
|
||||
sys.path.insert(0, test_fw_path)
|
||||
|
||||
import TinyFW
|
||||
import IDF
|
||||
|
||||
|
||||
|
||||
|
||||
@IDF.idf_example_test(env_tag="Example_WIFI")
|
||||
def test_examples_protocol_asio_tcp_server(env, extra_data):
|
||||
"""
|
||||
steps: |
|
||||
1. join AP
|
||||
2. Start server
|
||||
3. Test connects to server and sends a test message
|
||||
4. Test evaluates received test message from server
|
||||
5. Test evaluates received test message on server stdout
|
||||
"""
|
||||
test_msg="echo message from client to server"
|
||||
dut1 = env.get_dut("tcp_echo_server", "examples/protocols/asio/tcp_echo_server")
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "asio_tcp_echoserver.bin")
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
IDF.log_performance("asio_tcp_echoserver_bin_size", "{}KB".format(bin_size//1024))
|
||||
IDF.check_performance("asio_tcp_echoserver_size", bin_size//1024)
|
||||
# 1. start test
|
||||
dut1.start_app()
|
||||
# 2. get the server IP address
|
||||
data = dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)
|
||||
# 3. create tcp client and connect to server
|
||||
cli = socket(AF_INET,SOCK_STREAM)
|
||||
cli.settimeout(30)
|
||||
cli.connect((data[0],80))
|
||||
cli.send(test_msg)
|
||||
data = cli.recv(1024)
|
||||
# 4. check the message received back from the server
|
||||
if (data == test_msg):
|
||||
print("PASS: Received correct message")
|
||||
pass
|
||||
else:
|
||||
print("Failure!")
|
||||
raise ValueError('Wrong data received from asi tcp server: {} (expoected:{})'.format(data, test_msg))
|
||||
# 5. check the client message appears also on server terminal
|
||||
dut1.expect(test_msg)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_examples_protocol_asio_tcp_server()
|
||||
@@ -0,0 +1,10 @@
|
||||
#
|
||||
# Component Makefile
|
||||
#
|
||||
# This Makefile should, at the very least, just include $(SDK_PATH)/Makefile. By default,
|
||||
# this will take the sources in the src/ directory, compile them and link them into
|
||||
# lib(subdirectory_name).a in the build directory. This behaviour is entirely configurable,
|
||||
# please read the SDK documents if you need to do this.
|
||||
#
|
||||
|
||||
COMPONENT_SRCDIRS = .
|
||||
@@ -0,0 +1,136 @@
|
||||
/* Common WiFi Init as STA for ASIO examples
|
||||
|
||||
This example code is in the Public Domain (or CC0 licensed, at your option.)
|
||||
|
||||
Unless required by applicable law or agreed to in writing, this
|
||||
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
CONDITIONS OF ANY KIND, either express or implied.
|
||||
*/
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/event_groups.h"
|
||||
#include "esp_system.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_event_loop.h"
|
||||
#include "esp_log.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "driver/uart.h"
|
||||
#include "esp_console.h"
|
||||
#include "esp_vfs_dev.h"
|
||||
|
||||
#include "lwip/err.h"
|
||||
#include "lwip/sys.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
/* The examples use simple WiFi configuration that you can set via
|
||||
'make menuconfig'.
|
||||
|
||||
If you'd rather not, just change the below entries to strings with
|
||||
the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid"
|
||||
*/
|
||||
#define EXAMPLE_ESP_WIFI_SSID CONFIG_ESP_WIFI_SSID
|
||||
#define EXAMPLE_ESP_WIFI_PASS CONFIG_ESP_WIFI_PASSWORD
|
||||
|
||||
/* FreeRTOS event group to signal when we are connected*/
|
||||
static EventGroupHandle_t wifi_event_group;
|
||||
|
||||
/* The event group allows multiple bits for each event,
|
||||
but we only care about one event - are we connected
|
||||
to the AP with an IP? */
|
||||
const int WIFI_CONNECTED_BIT = BIT0;
|
||||
|
||||
static const char *TAG = "asio example wifi init";
|
||||
|
||||
/**
|
||||
* Definition of ASIO main method, which is called after network initialized
|
||||
*/
|
||||
void asio_main();
|
||||
|
||||
static esp_err_t event_handler(void *ctx, system_event_t *event)
|
||||
{
|
||||
switch(event->event_id) {
|
||||
case SYSTEM_EVENT_STA_START:
|
||||
esp_wifi_connect();
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_GOT_IP:
|
||||
ESP_LOGI(TAG, "got ip:%s",
|
||||
ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
|
||||
xEventGroupSetBits(wifi_event_group, WIFI_CONNECTED_BIT);
|
||||
break;
|
||||
case SYSTEM_EVENT_AP_STACONNECTED:
|
||||
ESP_LOGI(TAG, "station:" MACSTR " join, AID=%d",
|
||||
MAC2STR(event->event_info.sta_connected.mac),
|
||||
event->event_info.sta_connected.aid);
|
||||
break;
|
||||
case SYSTEM_EVENT_AP_STADISCONNECTED:
|
||||
ESP_LOGI(TAG, "station:" MACSTR "leave, AID=%d",
|
||||
MAC2STR(event->event_info.sta_disconnected.mac),
|
||||
event->event_info.sta_disconnected.aid);
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_DISCONNECTED:
|
||||
esp_wifi_connect();
|
||||
xEventGroupClearBits(wifi_event_group, WIFI_CONNECTED_BIT);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void wifi_init_sta()
|
||||
{
|
||||
wifi_event_group = xEventGroupCreate();
|
||||
|
||||
tcpip_adapter_init();
|
||||
ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL) );
|
||||
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||
wifi_config_t wifi_config;
|
||||
// zero out the config struct to ensure defaults are setup
|
||||
memset(&wifi_config, 0, sizeof(wifi_sta_config_t));
|
||||
// only copy ssid&password from example config
|
||||
strcpy((char*)(wifi_config.sta.ssid), EXAMPLE_ESP_WIFI_SSID);
|
||||
strcpy((char*)(wifi_config.sta.password), EXAMPLE_ESP_WIFI_PASS);
|
||||
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) );
|
||||
ESP_ERROR_CHECK(esp_wifi_start() );
|
||||
|
||||
ESP_LOGI(TAG, "wifi_init_sta finished.");
|
||||
ESP_LOGI(TAG, "connect to ap SSID:%s password:%s",
|
||||
EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
|
||||
}
|
||||
|
||||
extern "C" void app_main()
|
||||
{
|
||||
//Initialize NVS
|
||||
esp_err_t ret = nvs_flash_init();
|
||||
if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
ret = nvs_flash_init();
|
||||
}
|
||||
ESP_ERROR_CHECK(ret);
|
||||
|
||||
ESP_LOGI(TAG, "ESP_WIFI_MODE_AP");
|
||||
wifi_init_sta();
|
||||
|
||||
// Initialize VFS & UART so we can use std::cout/cin
|
||||
setvbuf(stdin, NULL, _IONBF, 0);
|
||||
setvbuf(stdout, NULL, _IONBF, 0);
|
||||
/* Install UART driver for interrupt-driven reads and writes */
|
||||
ESP_ERROR_CHECK( uart_driver_install( (uart_port_t)CONFIG_CONSOLE_UART_NUM,
|
||||
256, 0, 0, NULL, 0) );
|
||||
/* Tell VFS to use UART driver */
|
||||
esp_vfs_dev_uart_use_driver(CONFIG_CONSOLE_UART_NUM);
|
||||
esp_vfs_dev_uart_set_rx_line_endings(ESP_LINE_ENDINGS_CR);
|
||||
/* Move the caret to the beginning of the next line on '\n' */
|
||||
esp_vfs_dev_uart_set_tx_line_endings(ESP_LINE_ENDINGS_CRLF);
|
||||
|
||||
// wait till we receive IP, so asio realated code can be started
|
||||
xEventGroupWaitBits(wifi_event_group, WIFI_CONNECTED_BIT, 1, 1, portMAX_DELAY);
|
||||
|
||||
// network is ready, let's proceed with ASIO example
|
||||
asio_main();
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
menu "Example Configuration"
|
||||
|
||||
config ESP_WIFI_SSID
|
||||
string "WiFi SSID"
|
||||
default "myssid"
|
||||
help
|
||||
SSID (network name) for the example to connect to.
|
||||
|
||||
config ESP_WIFI_PASSWORD
|
||||
string "WiFi Password"
|
||||
default "mypassword"
|
||||
help
|
||||
WiFi password (WPA or WPA2) for the example to use.
|
||||
|
||||
config EXAMPLE_PORT
|
||||
string "asio example port number"
|
||||
default "80"
|
||||
help
|
||||
Port number used by ASIO example
|
||||
|
||||
endmenu
|
||||
@@ -0,0 +1,9 @@
|
||||
#
|
||||
# Main component makefile.
|
||||
#
|
||||
# This Makefile can be left empty. By default, it will take the sources in the
|
||||
# src/ directory, compile them and link them into lib(subdirectory_name).a
|
||||
# in the build directory. This behaviour is entirely configurable,
|
||||
# please read the ESP-IDF documents if you need to do this.
|
||||
#
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
#include "asio.hpp"
|
||||
#include <string>
|
||||
#include <iostream>
|
||||
|
||||
using asio::ip::tcp;
|
||||
|
||||
class session
|
||||
: public std::enable_shared_from_this<session>
|
||||
{
|
||||
public:
|
||||
session(tcp::socket socket)
|
||||
: socket_(std::move(socket))
|
||||
{
|
||||
}
|
||||
|
||||
void start()
|
||||
{
|
||||
do_read();
|
||||
}
|
||||
|
||||
private:
|
||||
void do_read()
|
||||
{
|
||||
auto self(shared_from_this());
|
||||
socket_.async_read_some(asio::buffer(data_, max_length),
|
||||
[this, self](std::error_code ec, std::size_t length)
|
||||
{
|
||||
if (!ec)
|
||||
{
|
||||
std::cout << data_ << std::endl;
|
||||
do_write(length);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void do_write(std::size_t length)
|
||||
{
|
||||
auto self(shared_from_this());
|
||||
asio::async_write(socket_, asio::buffer(data_, length),
|
||||
[this, self](std::error_code ec, std::size_t length)
|
||||
{
|
||||
if (!ec)
|
||||
{
|
||||
do_read();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
tcp::socket socket_;
|
||||
enum { max_length = 1024 };
|
||||
char data_[max_length];
|
||||
};
|
||||
|
||||
class server
|
||||
{
|
||||
public:
|
||||
server(asio::io_context& io_context, short port)
|
||||
: acceptor_(io_context, tcp::endpoint(tcp::v4(), port))
|
||||
{
|
||||
do_accept();
|
||||
}
|
||||
|
||||
private:
|
||||
void do_accept()
|
||||
{
|
||||
acceptor_.async_accept(
|
||||
[this](std::error_code ec, tcp::socket socket)
|
||||
{
|
||||
if (!ec)
|
||||
{
|
||||
std::make_shared<session>(std::move(socket))->start();
|
||||
}
|
||||
|
||||
do_accept();
|
||||
});
|
||||
}
|
||||
|
||||
tcp::acceptor acceptor_;
|
||||
};
|
||||
|
||||
|
||||
void asio_main()
|
||||
{
|
||||
|
||||
asio::io_context io_context;
|
||||
|
||||
server s(io_context, std::atoi(CONFIG_EXAMPLE_PORT));
|
||||
|
||||
io_context.run();
|
||||
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
CONFIG_MAIN_TASK_STACK_SIZE=8192
|
||||
@@ -0,0 +1,7 @@
|
||||
#
|
||||
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
|
||||
# project subdirectory.
|
||||
#
|
||||
PROJECT_NAME := asio_udp_echoserver
|
||||
|
||||
include $(IDF_PATH)/make/project.mk
|
||||
@@ -0,0 +1,18 @@
|
||||
# ASIO udp echo server example
|
||||
|
||||
Simple asio echo server using WiFi STA
|
||||
|
||||
## Example workflow
|
||||
|
||||
- WiFi STA is started and trying to connect to the access point defined through `make menuconfig`
|
||||
- Once connected and acquired IP address, ASIO udp server is started on port number defined through `make menuconfig`
|
||||
- Server receives and echoes back messages transmitted from client
|
||||
|
||||
## Running the example
|
||||
|
||||
- Run `make menuconfig` to configure the access point's SSID and Password and port number
|
||||
- Run `make flash monitor` to build and upload the example to your board and connect to it's serial terminal
|
||||
- Wait for WiFi to connect to your access point (note the IP address)
|
||||
- You can now send a udp message and check it is repeated, for example using netcat `nc -u IP PORT`
|
||||
|
||||
See the README.md file in the upper level 'examples' directory for more information about examples.
|
||||
@@ -0,0 +1,59 @@
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
from socket import *
|
||||
|
||||
|
||||
# this is a test case write with tiny-test-fw.
|
||||
# to run test cases outside tiny-test-fw,
|
||||
# we need to set environment variable `TEST_FW_PATH`,
|
||||
# then get and insert `TEST_FW_PATH` to sys path before import FW module
|
||||
test_fw_path = os.getenv("TEST_FW_PATH")
|
||||
if test_fw_path and test_fw_path not in sys.path:
|
||||
sys.path.insert(0, test_fw_path)
|
||||
|
||||
import TinyFW
|
||||
import IDF
|
||||
|
||||
|
||||
|
||||
|
||||
@IDF.idf_example_test(env_tag="Example_WIFI")
|
||||
def test_examples_protocol_asio_udp_server(env, extra_data):
|
||||
"""
|
||||
steps: |
|
||||
1. join AP
|
||||
2. Start server
|
||||
3. Test connects to server and sends a test message
|
||||
4. Test evaluates received test message from server
|
||||
5. Test evaluates received test message on server stdout
|
||||
"""
|
||||
test_msg="echo message from client to server"
|
||||
dut1 = env.get_dut("udp_echo_server", "examples/protocols/asio/udp_echo_server")
|
||||
# check and log bin size
|
||||
binary_file = os.path.join(dut1.app.binary_path, "asio_udp_echoserver.bin")
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
IDF.log_performance("asio_udp_echoserver_bin_size", "{}KB".format(bin_size//1024))
|
||||
IDF.check_performance("asio_udp_echoserver_size", bin_size//1024)
|
||||
# 1. start test
|
||||
dut1.start_app()
|
||||
# 2. get the server IP address
|
||||
data = dut1.expect(re.compile(r" sta ip: ([^,]+),"), timeout=30)
|
||||
# 3. create tcp client and connect to server
|
||||
cli = socket(AF_INET, SOCK_DGRAM)
|
||||
cli.settimeout(30)
|
||||
cli.connect((data[0], 80))
|
||||
cli.send(test_msg)
|
||||
data = cli.recv(1024)
|
||||
# 4. check the message received back from the server
|
||||
if (data == test_msg):
|
||||
print("PASS: Received correct message")
|
||||
pass
|
||||
else:
|
||||
print("Failure!")
|
||||
raise ValueError('Wrong data received from asi udp server: {} (expoected:{})'.format(data, test_msg))
|
||||
# 5. check the client message appears also on server terminal
|
||||
dut1.expect(test_msg)
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_examples_protocol_asio_udp_server()
|
||||
@@ -0,0 +1,10 @@
|
||||
#
|
||||
# Component Makefile
|
||||
#
|
||||
# This Makefile should, at the very least, just include $(SDK_PATH)/Makefile. By default,
|
||||
# this will take the sources in the src/ directory, compile them and link them into
|
||||
# lib(subdirectory_name).a in the build directory. This behaviour is entirely configurable,
|
||||
# please read the SDK documents if you need to do this.
|
||||
#
|
||||
|
||||
COMPONENT_SRCDIRS = .
|
||||
@@ -0,0 +1,136 @@
|
||||
/* Common WiFi Init as STA for ASIO examples
|
||||
|
||||
This example code is in the Public Domain (or CC0 licensed, at your option.)
|
||||
|
||||
Unless required by applicable law or agreed to in writing, this
|
||||
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
CONDITIONS OF ANY KIND, either express or implied.
|
||||
*/
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/event_groups.h"
|
||||
#include "esp_system.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_event_loop.h"
|
||||
#include "esp_log.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "driver/uart.h"
|
||||
#include "esp_console.h"
|
||||
#include "esp_vfs_dev.h"
|
||||
|
||||
#include "lwip/err.h"
|
||||
#include "lwip/sys.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
/* The examples use simple WiFi configuration that you can set via
|
||||
'make menuconfig'.
|
||||
|
||||
If you'd rather not, just change the below entries to strings with
|
||||
the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid"
|
||||
*/
|
||||
#define EXAMPLE_ESP_WIFI_SSID CONFIG_ESP_WIFI_SSID
|
||||
#define EXAMPLE_ESP_WIFI_PASS CONFIG_ESP_WIFI_PASSWORD
|
||||
|
||||
/* FreeRTOS event group to signal when we are connected*/
|
||||
static EventGroupHandle_t wifi_event_group;
|
||||
|
||||
/* The event group allows multiple bits for each event,
|
||||
but we only care about one event - are we connected
|
||||
to the AP with an IP? */
|
||||
const int WIFI_CONNECTED_BIT = BIT0;
|
||||
|
||||
static const char *TAG = "asio example wifi init";
|
||||
|
||||
/**
|
||||
* Definition of ASIO main method, which is called after network initialized
|
||||
*/
|
||||
void asio_main();
|
||||
|
||||
static esp_err_t event_handler(void *ctx, system_event_t *event)
|
||||
{
|
||||
switch(event->event_id) {
|
||||
case SYSTEM_EVENT_STA_START:
|
||||
esp_wifi_connect();
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_GOT_IP:
|
||||
ESP_LOGI(TAG, "got ip:%s",
|
||||
ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
|
||||
xEventGroupSetBits(wifi_event_group, WIFI_CONNECTED_BIT);
|
||||
break;
|
||||
case SYSTEM_EVENT_AP_STACONNECTED:
|
||||
ESP_LOGI(TAG, "station:" MACSTR " join, AID=%d",
|
||||
MAC2STR(event->event_info.sta_connected.mac),
|
||||
event->event_info.sta_connected.aid);
|
||||
break;
|
||||
case SYSTEM_EVENT_AP_STADISCONNECTED:
|
||||
ESP_LOGI(TAG, "station:" MACSTR "leave, AID=%d",
|
||||
MAC2STR(event->event_info.sta_disconnected.mac),
|
||||
event->event_info.sta_disconnected.aid);
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_DISCONNECTED:
|
||||
esp_wifi_connect();
|
||||
xEventGroupClearBits(wifi_event_group, WIFI_CONNECTED_BIT);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void wifi_init_sta()
|
||||
{
|
||||
wifi_event_group = xEventGroupCreate();
|
||||
|
||||
tcpip_adapter_init();
|
||||
ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL) );
|
||||
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||
wifi_config_t wifi_config;
|
||||
// zero out the config struct to ensure defaults are setup
|
||||
memset(&wifi_config, 0, sizeof(wifi_sta_config_t));
|
||||
// only copy ssid&password from example config
|
||||
strcpy((char*)(wifi_config.sta.ssid), EXAMPLE_ESP_WIFI_SSID);
|
||||
strcpy((char*)(wifi_config.sta.password), EXAMPLE_ESP_WIFI_PASS);
|
||||
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) );
|
||||
ESP_ERROR_CHECK(esp_wifi_start() );
|
||||
|
||||
ESP_LOGI(TAG, "wifi_init_sta finished.");
|
||||
ESP_LOGI(TAG, "connect to ap SSID:%s password:%s",
|
||||
EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
|
||||
}
|
||||
|
||||
extern "C" void app_main()
|
||||
{
|
||||
//Initialize NVS
|
||||
esp_err_t ret = nvs_flash_init();
|
||||
if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
ret = nvs_flash_init();
|
||||
}
|
||||
ESP_ERROR_CHECK(ret);
|
||||
|
||||
ESP_LOGI(TAG, "ESP_WIFI_MODE_AP");
|
||||
wifi_init_sta();
|
||||
|
||||
// Initialize VFS & UART so we can use std::cout/cin
|
||||
setvbuf(stdin, NULL, _IONBF, 0);
|
||||
setvbuf(stdout, NULL, _IONBF, 0);
|
||||
/* Install UART driver for interrupt-driven reads and writes */
|
||||
ESP_ERROR_CHECK( uart_driver_install( (uart_port_t)CONFIG_CONSOLE_UART_NUM,
|
||||
256, 0, 0, NULL, 0) );
|
||||
/* Tell VFS to use UART driver */
|
||||
esp_vfs_dev_uart_use_driver(CONFIG_CONSOLE_UART_NUM);
|
||||
esp_vfs_dev_uart_set_rx_line_endings(ESP_LINE_ENDINGS_CR);
|
||||
/* Move the caret to the beginning of the next line on '\n' */
|
||||
esp_vfs_dev_uart_set_tx_line_endings(ESP_LINE_ENDINGS_CRLF);
|
||||
|
||||
// wait till we receive IP, so asio realated code can be started
|
||||
xEventGroupWaitBits(wifi_event_group, WIFI_CONNECTED_BIT, 1, 1, portMAX_DELAY);
|
||||
|
||||
// network is ready, let's proceed with ASIO example
|
||||
asio_main();
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
menu "Example Configuration"
|
||||
|
||||
config ESP_WIFI_SSID
|
||||
string "WiFi SSID"
|
||||
default "myssid"
|
||||
help
|
||||
SSID (network name) for the example to connect to.
|
||||
|
||||
config ESP_WIFI_PASSWORD
|
||||
string "WiFi Password"
|
||||
default "mypassword"
|
||||
help
|
||||
WiFi password (WPA or WPA2) for the example to use.
|
||||
|
||||
config EXAMPLE_PORT
|
||||
string "asio example port number"
|
||||
default "80"
|
||||
help
|
||||
Port number used by ASIO example
|
||||
|
||||
endmenu
|
||||
@@ -0,0 +1,8 @@
|
||||
#
|
||||
# Main component makefile.
|
||||
#
|
||||
# This Makefile can be left empty. By default, it will take the sources in the
|
||||
# src/ directory, compile them and link them into lib(subdirectory_name).a
|
||||
# in the build directory. This behaviour is entirely configurable,
|
||||
# please read the ESP-IDF documents if you need to do this.
|
||||
#
|
||||
@@ -0,0 +1,69 @@
|
||||
//
|
||||
// async_udp_echo_server.cpp
|
||||
// ~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
//
|
||||
// Copyright (c) 2003-2018 Christopher M. Kohlhoff (chris at kohlhoff dot com)
|
||||
//
|
||||
// Distributed under the Boost Software License, Version 1.0. (See accompanying
|
||||
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
|
||||
//
|
||||
|
||||
#include <cstdlib>
|
||||
#include <iostream>
|
||||
|
||||
#include "asio.hpp"
|
||||
|
||||
using asio::ip::udp;
|
||||
|
||||
class server
|
||||
{
|
||||
public:
|
||||
server(asio::io_context& io_context, short port)
|
||||
: socket_(io_context, udp::endpoint(udp::v4(), port))
|
||||
{
|
||||
do_receive();
|
||||
}
|
||||
|
||||
void do_receive()
|
||||
{
|
||||
socket_.async_receive_from(
|
||||
asio::buffer(data_, max_length), sender_endpoint_,
|
||||
[this](std::error_code ec, std::size_t bytes_recvd)
|
||||
{
|
||||
if (!ec && bytes_recvd > 0)
|
||||
{
|
||||
std::cout << data_ << std::endl;
|
||||
do_send(bytes_recvd);
|
||||
}
|
||||
else
|
||||
{
|
||||
do_receive();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void do_send(std::size_t length)
|
||||
{
|
||||
socket_.async_send_to(
|
||||
asio::buffer(data_, length), sender_endpoint_,
|
||||
[this](std::error_code /*ec*/, std::size_t bytes /*bytes_sent*/)
|
||||
{
|
||||
do_receive();
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
udp::socket socket_;
|
||||
udp::endpoint sender_endpoint_;
|
||||
enum { max_length = 1024 };
|
||||
char data_[max_length];
|
||||
};
|
||||
|
||||
void asio_main()
|
||||
{
|
||||
asio::io_context io_context;
|
||||
|
||||
server s(io_context, std::atoi(CONFIG_EXAMPLE_PORT));
|
||||
|
||||
io_context.run();
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
CONFIG_MAIN_TASK_STACK_SIZE=8192
|
||||
@@ -0,0 +1,136 @@
|
||||
/* Common WiFi Init as STA for ASIO examples
|
||||
|
||||
This example code is in the Public Domain (or CC0 licensed, at your option.)
|
||||
|
||||
Unless required by applicable law or agreed to in writing, this
|
||||
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
CONDITIONS OF ANY KIND, either express or implied.
|
||||
*/
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "freertos/event_groups.h"
|
||||
#include "esp_system.h"
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_event_loop.h"
|
||||
#include "esp_log.h"
|
||||
#include "nvs_flash.h"
|
||||
#include "driver/uart.h"
|
||||
#include "esp_console.h"
|
||||
#include "esp_vfs_dev.h"
|
||||
|
||||
#include "lwip/err.h"
|
||||
#include "lwip/sys.h"
|
||||
|
||||
#include <cstring>
|
||||
|
||||
/* The examples use simple WiFi configuration that you can set via
|
||||
'make menuconfig'.
|
||||
|
||||
If you'd rather not, just change the below entries to strings with
|
||||
the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid"
|
||||
*/
|
||||
#define EXAMPLE_ESP_WIFI_SSID CONFIG_ESP_WIFI_SSID
|
||||
#define EXAMPLE_ESP_WIFI_PASS CONFIG_ESP_WIFI_PASSWORD
|
||||
|
||||
/* FreeRTOS event group to signal when we are connected*/
|
||||
static EventGroupHandle_t wifi_event_group;
|
||||
|
||||
/* The event group allows multiple bits for each event,
|
||||
but we only care about one event - are we connected
|
||||
to the AP with an IP? */
|
||||
const int WIFI_CONNECTED_BIT = BIT0;
|
||||
|
||||
static const char *TAG = "asio example wifi init";
|
||||
|
||||
/**
|
||||
* Definition of ASIO main method, which is called after network initialized
|
||||
*/
|
||||
void asio_main();
|
||||
|
||||
static esp_err_t event_handler(void *ctx, system_event_t *event)
|
||||
{
|
||||
switch(event->event_id) {
|
||||
case SYSTEM_EVENT_STA_START:
|
||||
esp_wifi_connect();
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_GOT_IP:
|
||||
ESP_LOGI(TAG, "got ip:%s",
|
||||
ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
|
||||
xEventGroupSetBits(wifi_event_group, WIFI_CONNECTED_BIT);
|
||||
break;
|
||||
case SYSTEM_EVENT_AP_STACONNECTED:
|
||||
ESP_LOGI(TAG, "station:" MACSTR " join, AID=%d",
|
||||
MAC2STR(event->event_info.sta_connected.mac),
|
||||
event->event_info.sta_connected.aid);
|
||||
break;
|
||||
case SYSTEM_EVENT_AP_STADISCONNECTED:
|
||||
ESP_LOGI(TAG, "station:" MACSTR "leave, AID=%d",
|
||||
MAC2STR(event->event_info.sta_disconnected.mac),
|
||||
event->event_info.sta_disconnected.aid);
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_DISCONNECTED:
|
||||
esp_wifi_connect();
|
||||
xEventGroupClearBits(wifi_event_group, WIFI_CONNECTED_BIT);
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void wifi_init_sta()
|
||||
{
|
||||
wifi_event_group = xEventGroupCreate();
|
||||
|
||||
tcpip_adapter_init();
|
||||
ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL) );
|
||||
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||
wifi_config_t wifi_config;
|
||||
// zero out the config struct to ensure defaults are setup
|
||||
memset(&wifi_config, 0, sizeof(wifi_sta_config_t));
|
||||
// only copy ssid&password from example config
|
||||
strcpy((char*)(wifi_config.sta.ssid), EXAMPLE_ESP_WIFI_SSID);
|
||||
strcpy((char*)(wifi_config.sta.password), EXAMPLE_ESP_WIFI_PASS);
|
||||
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) );
|
||||
ESP_ERROR_CHECK(esp_wifi_start() );
|
||||
|
||||
ESP_LOGI(TAG, "wifi_init_sta finished.");
|
||||
ESP_LOGI(TAG, "connect to ap SSID:%s password:%s",
|
||||
EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
|
||||
}
|
||||
|
||||
extern "C" void app_main()
|
||||
{
|
||||
//Initialize NVS
|
||||
esp_err_t ret = nvs_flash_init();
|
||||
if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
ret = nvs_flash_init();
|
||||
}
|
||||
ESP_ERROR_CHECK(ret);
|
||||
|
||||
ESP_LOGI(TAG, "ESP_WIFI_MODE_AP");
|
||||
wifi_init_sta();
|
||||
|
||||
// Initialize VFS & UART so we can use std::cout/cin
|
||||
setvbuf(stdin, NULL, _IONBF, 0);
|
||||
setvbuf(stdout, NULL, _IONBF, 0);
|
||||
/* Install UART driver for interrupt-driven reads and writes */
|
||||
ESP_ERROR_CHECK( uart_driver_install( (uart_port_t)CONFIG_CONSOLE_UART_NUM,
|
||||
256, 0, 0, NULL, 0) );
|
||||
/* Tell VFS to use UART driver */
|
||||
esp_vfs_dev_uart_use_driver(CONFIG_CONSOLE_UART_NUM);
|
||||
esp_vfs_dev_uart_set_rx_line_endings(ESP_LINE_ENDINGS_CR);
|
||||
/* Move the caret to the beginning of the next line on '\n' */
|
||||
esp_vfs_dev_uart_set_tx_line_endings(ESP_LINE_ENDINGS_CRLF);
|
||||
|
||||
// wait till we receive IP, so asio realated code can be started
|
||||
xEventGroupWaitBits(wifi_event_group, WIFI_CONNECTED_BIT, 1, 1, portMAX_DELAY);
|
||||
|
||||
// network is ready, let's proceed with ASIO example
|
||||
asio_main();
|
||||
}
|
||||
@@ -1,28 +1,28 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB
|
||||
yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL
|
||||
ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp
|
||||
U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW
|
||||
ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0
|
||||
aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCByjEL
|
||||
MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW
|
||||
ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2ln
|
||||
biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp
|
||||
U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y
|
||||
aXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvJAgIKXo1
|
||||
nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKzj/i5Vbex
|
||||
t0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIz
|
||||
SdhDY2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQG
|
||||
BO+QueQA5N06tRn/Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+
|
||||
rCpSx4/VBEnkjWNHiDxpg8v+R70rfk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/
|
||||
NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E
|
||||
BAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEwHzAH
|
||||
BgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy
|
||||
aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKv
|
||||
MzEzMA0GCSqGSIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzE
|
||||
p6B4Eq1iDkVwZMXnl2YtmAl+X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y
|
||||
5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKEKQsTb47bDN0lAtukixlE0kF6BWlK
|
||||
WE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiCKm0oHw0LxOXnGiYZ
|
||||
4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vEZV8N
|
||||
hnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB
|
||||
yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL
|
||||
ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp
|
||||
U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW
|
||||
ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0
|
||||
aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCByjEL
|
||||
MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW
|
||||
ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2ln
|
||||
biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp
|
||||
U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y
|
||||
aXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvJAgIKXo1
|
||||
nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKzj/i5Vbex
|
||||
t0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIz
|
||||
SdhDY2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQG
|
||||
BO+QueQA5N06tRn/Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+
|
||||
rCpSx4/VBEnkjWNHiDxpg8v+R70rfk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/
|
||||
NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E
|
||||
BAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEwHzAH
|
||||
BgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy
|
||||
aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKv
|
||||
MzEzMA0GCSqGSIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzE
|
||||
p6B4Eq1iDkVwZMXnl2YtmAl+X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y
|
||||
5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKEKQsTb47bDN0lAtukixlE0kF6BWlK
|
||||
WE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiCKm0oHw0LxOXnGiYZ
|
||||
4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vEZV8N
|
||||
hnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq
|
||||
-----END CERTIFICATE-----
|
||||
@@ -321,7 +321,7 @@ void app_main()
|
||||
{
|
||||
// Initialize NVS.
|
||||
esp_err_t err = nvs_flash_init();
|
||||
if (err == ESP_ERR_NVS_NO_FREE_PAGES) {
|
||||
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
err = nvs_flash_init();
|
||||
}
|
||||
|
||||
@@ -1,28 +1,28 @@
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB
|
||||
yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL
|
||||
ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp
|
||||
U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW
|
||||
ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0
|
||||
aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCByjEL
|
||||
MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW
|
||||
ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2ln
|
||||
biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp
|
||||
U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y
|
||||
aXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvJAgIKXo1
|
||||
nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKzj/i5Vbex
|
||||
t0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIz
|
||||
SdhDY2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQG
|
||||
BO+QueQA5N06tRn/Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+
|
||||
rCpSx4/VBEnkjWNHiDxpg8v+R70rfk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/
|
||||
NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E
|
||||
BAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEwHzAH
|
||||
BgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy
|
||||
aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKv
|
||||
MzEzMA0GCSqGSIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzE
|
||||
p6B4Eq1iDkVwZMXnl2YtmAl+X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y
|
||||
5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKEKQsTb47bDN0lAtukixlE0kF6BWlK
|
||||
WE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiCKm0oHw0LxOXnGiYZ
|
||||
4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vEZV8N
|
||||
hnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq
|
||||
-----BEGIN CERTIFICATE-----
|
||||
MIIE0zCCA7ugAwIBAgIQGNrRniZ96LtKIVjNzGs7SjANBgkqhkiG9w0BAQUFADCB
|
||||
yjELMAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQL
|
||||
ExZWZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJp
|
||||
U2lnbiwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxW
|
||||
ZXJpU2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0
|
||||
aG9yaXR5IC0gRzUwHhcNMDYxMTA4MDAwMDAwWhcNMzYwNzE2MjM1OTU5WjCByjEL
|
||||
MAkGA1UEBhMCVVMxFzAVBgNVBAoTDlZlcmlTaWduLCBJbmMuMR8wHQYDVQQLExZW
|
||||
ZXJpU2lnbiBUcnVzdCBOZXR3b3JrMTowOAYDVQQLEzEoYykgMjAwNiBWZXJpU2ln
|
||||
biwgSW5jLiAtIEZvciBhdXRob3JpemVkIHVzZSBvbmx5MUUwQwYDVQQDEzxWZXJp
|
||||
U2lnbiBDbGFzcyAzIFB1YmxpYyBQcmltYXJ5IENlcnRpZmljYXRpb24gQXV0aG9y
|
||||
aXR5IC0gRzUwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCvJAgIKXo1
|
||||
nmAMqudLO07cfLw8RRy7K+D+KQL5VwijZIUVJ/XxrcgxiV0i6CqqpkKzj/i5Vbex
|
||||
t0uz/o9+B1fs70PbZmIVYc9gDaTY3vjgw2IIPVQT60nKWVSFJuUrjxuf6/WhkcIz
|
||||
SdhDY2pSS9KP6HBRTdGJaXvHcPaz3BJ023tdS1bTlr8Vd6Gw9KIl8q8ckmcY5fQG
|
||||
BO+QueQA5N06tRn/Arr0PO7gi+s3i+z016zy9vA9r911kTMZHRxAy3QkGSGT2RT+
|
||||
rCpSx4/VBEnkjWNHiDxpg8v+R70rfk/Fla4OndTRQ8Bnc+MUCH7lP59zuDMKz10/
|
||||
NIeWiu5T6CUVAgMBAAGjgbIwga8wDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8E
|
||||
BAMCAQYwbQYIKwYBBQUHAQwEYTBfoV2gWzBZMFcwVRYJaW1hZ2UvZ2lmMCEwHzAH
|
||||
BgUrDgMCGgQUj+XTGoasjY5rw8+AatRIGCx7GS4wJRYjaHR0cDovL2xvZ28udmVy
|
||||
aXNpZ24uY29tL3ZzbG9nby5naWYwHQYDVR0OBBYEFH/TZafC3ey78DAJ80M5+gKv
|
||||
MzEzMA0GCSqGSIb3DQEBBQUAA4IBAQCTJEowX2LP2BqYLz3q3JktvXf2pXkiOOzE
|
||||
p6B4Eq1iDkVwZMXnl2YtmAl+X6/WzChl8gGqCBpH3vn5fJJaCGkgDdk+bW48DW7Y
|
||||
5gaRQBi5+MHt39tBquCWIMnNZBU4gcmU7qKEKQsTb47bDN0lAtukixlE0kF6BWlK
|
||||
WE9gyn6CagsCqiUXObXbf+eEZSqVir2G3l6BFoMtEMze/aiCKm0oHw0LxOXnGiYZ
|
||||
4fQRbxC1lfznQgUy286dUV4otp6F01vvpX1FQHKOtw5rDgb7MzVIcbidJ4vEZV8N
|
||||
hnacRHr2lVz2XTIIM6RUthg/aFzyQkqFOFSDX9HoLPKsEdao7WNq
|
||||
-----END CERTIFICATE-----
|
||||
@@ -200,12 +200,14 @@ void aws_iot_task(void *param) {
|
||||
windowActuator.pData = &windowOpen;
|
||||
windowActuator.pKey = "windowOpen";
|
||||
windowActuator.type = SHADOW_JSON_BOOL;
|
||||
windowActuator.dataLength = sizeof(bool);
|
||||
|
||||
jsonStruct_t temperatureHandler;
|
||||
temperatureHandler.cb = NULL;
|
||||
temperatureHandler.pKey = "temperature";
|
||||
temperatureHandler.pData = &temperature;
|
||||
temperatureHandler.type = SHADOW_JSON_FLOAT;
|
||||
temperatureHandler.dataLength = sizeof(float);
|
||||
|
||||
ESP_LOGI(TAG, "AWS IoT SDK Version %d.%d.%d-%s", VERSION_MAJOR, VERSION_MINOR, VERSION_PATCH, VERSION_TAG);
|
||||
|
||||
@@ -356,7 +358,7 @@ static void initialise_wifi(void)
|
||||
void app_main()
|
||||
{
|
||||
esp_err_t err = nvs_flash_init();
|
||||
if (err == ESP_ERR_NVS_NO_FREE_PAGES) {
|
||||
if (err == ESP_ERR_NVS_NO_FREE_PAGES || err == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
err = nvs_flash_init();
|
||||
}
|
||||
|
||||
@@ -79,7 +79,7 @@ static void coap_example_task(void *p)
|
||||
coap_pdu_t* request = NULL;
|
||||
const char* server_uri = COAP_DEFAULT_DEMO_URI;
|
||||
uint8_t get_method = 1;
|
||||
|
||||
char* phostname = NULL;
|
||||
while (1) {
|
||||
/* Wait for the callback to set the CONNECTED_BIT in the
|
||||
event group.
|
||||
@@ -93,7 +93,16 @@ static void coap_example_task(void *p)
|
||||
break;
|
||||
}
|
||||
|
||||
hp = gethostbyname((const char *)uri.host.s);
|
||||
phostname = (char *)calloc(1, uri.host.length + 1);
|
||||
|
||||
if (phostname == NULL) {
|
||||
ESP_LOGE(TAG, "calloc failed");
|
||||
continue;
|
||||
}
|
||||
|
||||
memcpy(phostname, uri.host.s, uri.host.length);
|
||||
hp = gethostbyname(phostname);
|
||||
free(phostname);
|
||||
|
||||
if (hp == NULL) {
|
||||
ESP_LOGE(TAG, "DNS lookup failed");
|
||||
|
||||
@@ -14,7 +14,7 @@ import TinyFW
|
||||
import IDF
|
||||
|
||||
|
||||
@IDF.idf_example_test(env_tag="Example_WIFI")
|
||||
@IDF.idf_example_test(env_tag="Example_WIFI", ignore=True)
|
||||
def test_examples_protocol_esp_http_client(env, extra_data):
|
||||
"""
|
||||
steps: |
|
||||
@@ -35,13 +35,14 @@ def test_examples_protocol_esp_http_client(env, extra_data):
|
||||
dut1.expect(re.compile(r"HTTP PUT Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP PATCH Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP DELETE Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP HEAD Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP Basic Auth Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP Basic Auth redirect Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP Digest Auth Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP Relative path redirect Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP Absolute path redirect Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTPS Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP redirect to HTTPS Status = 200, content_length = (\d)"))
|
||||
dut1.expect(re.compile(r"HTTP redirect to HTTPS Status = 200, content_length = (\d)"), timeout=10)
|
||||
dut1.expect(re.compile(r"HTTP chunk encoding Status = 200, content_length = -1"))
|
||||
dut1.expect(re.compile(r"HTTP Stream reader Status = 200, content_length = (\d)"))
|
||||
dut1.expect("Finish http example")
|
||||
|
||||
@@ -136,6 +136,18 @@ static void http_rest()
|
||||
ESP_LOGE(TAG, "HTTP DELETE request failed: %s", esp_err_to_name(err));
|
||||
}
|
||||
|
||||
//HEAD
|
||||
esp_http_client_set_url(client, "http://httpbin.org/get");
|
||||
esp_http_client_set_method(client, HTTP_METHOD_HEAD);
|
||||
err = esp_http_client_perform(client);
|
||||
if (err == ESP_OK) {
|
||||
ESP_LOGI(TAG, "HTTP HEAD Status = %d, content_length = %d",
|
||||
esp_http_client_get_status_code(client),
|
||||
esp_http_client_get_content_length(client));
|
||||
} else {
|
||||
ESP_LOGE(TAG, "HTTP HEAD request failed: %s", esp_err_to_name(err));
|
||||
}
|
||||
|
||||
esp_http_client_cleanup(client);
|
||||
}
|
||||
|
||||
@@ -296,7 +308,7 @@ static void http_download_chunk()
|
||||
|
||||
static void http_perform_as_stream_reader()
|
||||
{
|
||||
char *buffer = malloc(MAX_HTTP_RECV_BUFFER);
|
||||
char *buffer = malloc(MAX_HTTP_RECV_BUFFER + 1);
|
||||
if (buffer == NULL) {
|
||||
ESP_LOGE(TAG, "Cannot malloc http receive buffer");
|
||||
return;
|
||||
@@ -351,7 +363,7 @@ static void http_test_task(void *pvParameters)
|
||||
void app_main()
|
||||
{
|
||||
esp_err_t ret = nvs_flash_init();
|
||||
if (ret == ESP_ERR_NVS_NO_FREE_PAGES) {
|
||||
if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
|
||||
ESP_ERROR_CHECK(nvs_flash_erase());
|
||||
ret = nvs_flash_init();
|
||||
}
|
||||
|
||||
@@ -58,22 +58,19 @@ static ssize_t callback_send(nghttp2_session *session, const uint8_t *data,
|
||||
int pending_data = length;
|
||||
|
||||
/* Send data in 1000 byte chunks */
|
||||
while (copy_offset != (length - 1)) {
|
||||
while (copy_offset != length) {
|
||||
int chunk_len = pending_data > 1000 ? 1000 : pending_data;
|
||||
int subrv = callback_send_inner(hd, data + copy_offset, chunk_len);
|
||||
if (subrv <= 0) {
|
||||
if (copy_offset) {
|
||||
/* If some data was xferred, send the number of bytes
|
||||
* xferred */
|
||||
rv = copy_offset;
|
||||
} else {
|
||||
/* If not, send the error code */
|
||||
if (copy_offset == 0) {
|
||||
/* If no data is transferred, send the error code */
|
||||
rv = subrv;
|
||||
}
|
||||
break;
|
||||
}
|
||||
copy_offset += chunk_len;
|
||||
pending_data -= chunk_len;
|
||||
copy_offset += subrv;
|
||||
pending_data -= subrv;
|
||||
rv += subrv;
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
@@ -145,6 +145,7 @@ static void http2_task(void *args)
|
||||
}
|
||||
|
||||
sh2lib_free(&hd);
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
static esp_err_t event_handler(void *ctx, system_event_t *event)
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
#
|
||||
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
|
||||
# project subdirectory.
|
||||
#
|
||||
|
||||
PROJECT_NAME := tests
|
||||
|
||||
include $(IDF_PATH)/make/project.mk
|
||||
|
||||
@@ -0,0 +1,183 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2018 Espressif Systems (Shanghai) PTE LTD
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import imp
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
import string
|
||||
import random
|
||||
import socket
|
||||
|
||||
# This environment variable is expected on the host machine
|
||||
test_fw_path = os.getenv("TEST_FW_PATH")
|
||||
if test_fw_path and test_fw_path not in sys.path:
|
||||
sys.path.insert(0, test_fw_path)
|
||||
|
||||
# When running on local machine execute the following before running this script
|
||||
# > export TEST_FW_PATH='~/esp/esp-idf/tools/tiny-test-fw'
|
||||
# > make print_flash_cmd | tail -n 1 > build/download.config
|
||||
# > make app bootloader
|
||||
|
||||
import TinyFW
|
||||
import IDF
|
||||
|
||||
# Import client module
|
||||
expath = os.path.dirname(os.path.realpath(__file__))
|
||||
client = imp.load_source("client", expath + "/scripts/test.py")
|
||||
|
||||
@IDF.idf_example_test(env_tag="Example_WIFI", ignore=True)
|
||||
def test_examples_protocol_http_server_advanced(env, extra_data):
|
||||
# Acquire DUT
|
||||
dut1 = env.get_dut("http_server", "examples/protocols/http_server/advanced_tests")
|
||||
|
||||
# Get binary file
|
||||
binary_file = os.path.join(dut1.app.binary_path, "tests.bin")
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
IDF.log_performance("http_server_bin_size", "{}KB".format(bin_size//1024))
|
||||
IDF.check_performance("http_server_bin_size", bin_size//1024)
|
||||
|
||||
# Upload binary and start testing
|
||||
dut1.start_app()
|
||||
|
||||
# Parse IP address of STA
|
||||
got_ip = dut1.expect(re.compile(r"(?:[\s\S]*)Got IP: (\d+.\d+.\d+.\d+)"), timeout=30)[0]
|
||||
|
||||
print "Leak Tests..."
|
||||
# Expected Leak test Logs
|
||||
dut1.expect("Leak Test Started...");
|
||||
dut1.expect("Leak Test Passed");
|
||||
|
||||
got_port = dut1.expect(re.compile(r"(?:[\s\S]*)Started HTTP server on port: (\d+)"))[0]
|
||||
result = dut1.expect(re.compile(r"(?:[\s\S]*)Max URI handlers: (\d+)(?:[\s\S]*)Max Open Sessions: (\d+)(?:[\s\S]*)Max Header Length: (\d+)(?:[\s\S]*)Max URI Length: (\d+)(?:[\s\S]*)Max Stack Size: (\d+)"))
|
||||
max_uri_handlers = int(result[0])
|
||||
max_sessions = int(result[1])
|
||||
max_hdr_len = int(result[2])
|
||||
max_uri_len = int(result[3])
|
||||
max_stack_size = int(result[4])
|
||||
|
||||
print "Got IP : " + got_ip
|
||||
print "Got Port : " + got_port
|
||||
|
||||
print "Handler Tests..."
|
||||
# Expected Handler Test Logs
|
||||
dut1.expect("Test: Register Max URI handlers")
|
||||
dut1.expect("Success")
|
||||
dut1.expect("Test: Register Max URI + 1 handlers")
|
||||
dut1.expect("no slots left for registering handler")
|
||||
dut1.expect("Success")
|
||||
dut1.expect("Test: Unregister 0th handler")
|
||||
dut1.expect("Success")
|
||||
dut1.expect("Test: Again unregister 0th handler not registered")
|
||||
dut1.expect("handler 0 with method 1 not found")
|
||||
dut1.expect("Success")
|
||||
dut1.expect("Test: Register back 0th handler")
|
||||
dut1.expect("Success")
|
||||
dut1.expect("Test: Register 0th handler again after registering")
|
||||
dut1.expect("handler 0 with method 1 already registered")
|
||||
dut1.expect("Success")
|
||||
dut1.expect("Test: Register 1 more handler")
|
||||
dut1.expect("no slots left for registering handler")
|
||||
dut1.expect("Success")
|
||||
dut1.expect("Test: Unregister all handlers")
|
||||
dut1.expect("Success")
|
||||
dut1.expect("Registering basic handlers")
|
||||
dut1.expect("Success")
|
||||
|
||||
# Run test script
|
||||
# If failed raise appropriate exception
|
||||
|
||||
print "Basic HTTP Client Tests..."
|
||||
if not client.get_hello(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
|
||||
inital_stack = int(dut1.expect(re.compile(r"(?:[\s\S]*)Free Stack for server task: (\d+)"))[0])
|
||||
|
||||
if inital_stack < 0.1*max_stack_size:
|
||||
print "More than 90% of stack being used on server start"
|
||||
raise RuntimeError
|
||||
|
||||
if not client.post_hello(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
if not client.put_hello(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
if not client.post_echo(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
if not client.get_echo(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
if not client.put_echo(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
if not client.get_hello_type(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
if not client.get_hello_status(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
if not client.get_false_uri(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
|
||||
print "Error code tests..."
|
||||
if not client.code_500_server_error_test(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
if not client.code_501_method_not_impl(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
if not client.code_505_version_not_supported(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
if not client.code_400_bad_request(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
if not client.code_404_not_found(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
if not client.code_405_method_not_allowed(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
if not client.code_408_req_timeout(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
if not client.code_414_uri_too_long(got_ip, got_port, max_uri_len):
|
||||
raise RuntimeError
|
||||
if not client.code_431_hdr_too_long(got_ip, got_port, max_hdr_len):
|
||||
raise RuntimeError
|
||||
if not client.test_upgrade_not_supported(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
|
||||
print "Sessions and Context Tests..."
|
||||
if not client.parallel_sessions_adder(got_ip, got_port, max_sessions):
|
||||
raise RuntimeError
|
||||
if not client.leftover_data_test(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
if not client.async_response_test(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
if not client.spillover_session(got_ip, got_port, max_sessions):
|
||||
raise RuntimeError
|
||||
if not client.recv_timeout_test(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
|
||||
# May timeout in case requests are sent slower than responses are read.
|
||||
# Instead use httperf stress test
|
||||
#if not client.pipeline_test(got_ip, got_port, max_sessions):
|
||||
# raise RuntimeError
|
||||
|
||||
test_size = 50*1024 # 50KB
|
||||
if not client.packet_size_limit_test(got_ip, got_port, test_size):
|
||||
raise RuntimeError
|
||||
|
||||
if not client.get_hello(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
|
||||
final_stack = int(dut1.expect(re.compile(r"(?:[\s\S]*)Free Stack for server task: (\d+)"))[0])
|
||||
|
||||
if final_stack < 0.05*max_stack_size:
|
||||
print "More than 95% of stack got used during tests"
|
||||
raise RuntimeError
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_examples_protocol_http_server_advanced()
|
||||
@@ -0,0 +1,16 @@
|
||||
menu "Example Configuration"
|
||||
|
||||
config WIFI_SSID
|
||||
string "WiFi SSID"
|
||||
default "myssid"
|
||||
help
|
||||
SSID (network name) for the example to connect to.
|
||||
|
||||
config WIFI_PASSWORD
|
||||
string "WiFi Password"
|
||||
default "mypassword"
|
||||
help
|
||||
WiFi password (WPA or WPA2) for the example to use.
|
||||
Can be left blank if the network has no security set.
|
||||
|
||||
endmenu
|
||||
@@ -0,0 +1,5 @@
|
||||
#
|
||||
# "main" pseudo-component makefile.
|
||||
#
|
||||
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
#ifndef __HTTPD_TESTS_H__
|
||||
#define __HTTPD_TESTS_H__
|
||||
|
||||
#include <http_server.h>
|
||||
|
||||
extern httpd_handle_t start_tests(void);
|
||||
extern void stop_tests(httpd_handle_t hd);
|
||||
|
||||
#endif // __HTTPD_TESTS_H__
|
||||
@@ -0,0 +1,81 @@
|
||||
#include "esp_wifi.h"
|
||||
#include "esp_event_loop.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_system.h"
|
||||
#include "nvs_flash.h"
|
||||
|
||||
#include "tests.h"
|
||||
|
||||
/* The examples use simple WiFi configuration that you can set via
|
||||
'make menuconfig'.
|
||||
|
||||
If you'd rather not, just change the below entries to strings with
|
||||
the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid"
|
||||
*/
|
||||
#define EXAMPLE_WIFI_SSID CONFIG_WIFI_SSID
|
||||
#define EXAMPLE_WIFI_PASS CONFIG_WIFI_PASSWORD
|
||||
|
||||
static const char *TAG="TEST_WIFI";
|
||||
|
||||
static esp_err_t event_handler(void *ctx, system_event_t *event)
|
||||
{
|
||||
httpd_handle_t *hd = (httpd_handle_t *) ctx;
|
||||
|
||||
switch(event->event_id) {
|
||||
case SYSTEM_EVENT_STA_START:
|
||||
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_START");
|
||||
ESP_ERROR_CHECK(esp_wifi_connect());
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_GOT_IP:
|
||||
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_GOT_IP");
|
||||
ESP_LOGI(TAG, "Got IP: %s",
|
||||
ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
|
||||
|
||||
// Start webserver tests
|
||||
if (*hd == NULL) {
|
||||
*hd = start_tests();
|
||||
}
|
||||
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_DISCONNECTED:
|
||||
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_DISCONNECTED");
|
||||
ESP_ERROR_CHECK(esp_wifi_connect());
|
||||
|
||||
// Stop webserver tests
|
||||
if (*hd) {
|
||||
stop_tests(*hd);
|
||||
*hd = NULL;
|
||||
}
|
||||
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void initialise_wifi(void)
|
||||
{
|
||||
tcpip_adapter_init();
|
||||
static httpd_handle_t hd = NULL;
|
||||
ESP_ERROR_CHECK(esp_event_loop_init(event_handler, &hd));
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
|
||||
wifi_config_t wifi_config = {
|
||||
.sta = {
|
||||
.ssid = EXAMPLE_WIFI_SSID,
|
||||
.password = EXAMPLE_WIFI_PASS,
|
||||
},
|
||||
};
|
||||
ESP_LOGI(TAG, "Setting WiFi configuration SSID %s...", wifi_config.sta.ssid);
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
|
||||
ESP_ERROR_CHECK(esp_wifi_start());
|
||||
}
|
||||
|
||||
void app_main()
|
||||
{
|
||||
ESP_ERROR_CHECK(nvs_flash_init());
|
||||
initialise_wifi();
|
||||
}
|
||||
@@ -0,0 +1,511 @@
|
||||
#include <stdlib.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#include <esp_log.h>
|
||||
#include <esp_system.h>
|
||||
#include <http_server.h>
|
||||
|
||||
#include "tests.h"
|
||||
|
||||
static const char *TAG="TESTS";
|
||||
|
||||
int pre_start_mem, post_stop_mem, post_stop_min_mem;
|
||||
bool basic_sanity = true;
|
||||
|
||||
/********************* Basic Handlers Start *******************/
|
||||
|
||||
esp_err_t hello_get_handler(httpd_req_t *req)
|
||||
{
|
||||
#define STR "Hello World!"
|
||||
ESP_LOGI(TAG, "Free Stack for server task: %d", uxTaskGetStackHighWaterMark(NULL));
|
||||
httpd_resp_send(req, STR, strlen(STR));
|
||||
return ESP_OK;
|
||||
#undef STR
|
||||
}
|
||||
|
||||
esp_err_t hello_type_get_handler(httpd_req_t *req)
|
||||
{
|
||||
#define STR "Hello World!"
|
||||
httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
|
||||
httpd_resp_send(req, STR, strlen(STR));
|
||||
return ESP_OK;
|
||||
#undef STR
|
||||
}
|
||||
|
||||
esp_err_t hello_status_get_handler(httpd_req_t *req)
|
||||
{
|
||||
#define STR "Hello World!"
|
||||
httpd_resp_set_status(req, HTTPD_500);
|
||||
httpd_resp_send(req, STR, strlen(STR));
|
||||
return ESP_OK;
|
||||
#undef STR
|
||||
}
|
||||
|
||||
esp_err_t echo_post_handler(httpd_req_t *req)
|
||||
{
|
||||
ESP_LOGI(TAG, "/echo handler read content length %d", req->content_len);
|
||||
|
||||
char* buf = malloc(req->content_len + 1);
|
||||
size_t off = 0;
|
||||
int ret;
|
||||
|
||||
if (!buf) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
while (off < req->content_len) {
|
||||
/* Read data received in the request */
|
||||
ret = httpd_req_recv(req, buf + off, req->content_len - off);
|
||||
if (ret < 0) {
|
||||
free (buf);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
off += ret;
|
||||
ESP_LOGI(TAG, "/echo handler recv length %d", ret);
|
||||
}
|
||||
buf[off] = '\0';
|
||||
|
||||
if (req->content_len < 128) {
|
||||
ESP_LOGI(TAG, "/echo handler read %s", buf);
|
||||
}
|
||||
|
||||
/* Search for Custom header field */
|
||||
char* req_hdr = 0;
|
||||
size_t hdr_len = httpd_req_get_hdr_value_len(req, "Custom");
|
||||
if (hdr_len) {
|
||||
/* Read Custom header value */
|
||||
req_hdr = malloc(hdr_len + 1);
|
||||
if (req_hdr) {
|
||||
httpd_req_get_hdr_value_str(req, "Custom", req_hdr, hdr_len + 1);
|
||||
|
||||
/* Set as additional header for response packet */
|
||||
httpd_resp_set_hdr(req, "Custom", req_hdr);
|
||||
}
|
||||
}
|
||||
httpd_resp_send(req, buf, req->content_len);
|
||||
free (req_hdr);
|
||||
free (buf);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void adder_free_func(void *ctx)
|
||||
{
|
||||
ESP_LOGI(TAG, "Custom Free Context function called");
|
||||
free(ctx);
|
||||
}
|
||||
|
||||
/* Create a context, keep incrementing value in the context, by whatever was
|
||||
* received. Return the result
|
||||
*/
|
||||
esp_err_t adder_post_handler(httpd_req_t *req)
|
||||
{
|
||||
char buf[10];
|
||||
char outbuf[50];
|
||||
int ret;
|
||||
|
||||
/* Read data received in the request */
|
||||
ret = httpd_req_recv(req, buf, sizeof(buf));
|
||||
if (ret < 0) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
buf[ret] = '\0';
|
||||
int val = atoi(buf);
|
||||
ESP_LOGI(TAG, "/adder handler read %d", val);
|
||||
|
||||
if (! req->sess_ctx) {
|
||||
ESP_LOGI(TAG, "/adder allocating new session");
|
||||
req->sess_ctx = malloc(sizeof(int));
|
||||
req->free_ctx = adder_free_func;
|
||||
*(int *)req->sess_ctx = 0;
|
||||
}
|
||||
int *adder = (int *)req->sess_ctx;
|
||||
*adder += val;
|
||||
|
||||
snprintf(outbuf, sizeof(outbuf),"%d", *adder);
|
||||
httpd_resp_send(req, outbuf, strlen(outbuf));
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t leftover_data_post_handler(httpd_req_t *req)
|
||||
{
|
||||
/* Only echo the first 10 bytes of the request, leaving the rest of the
|
||||
* request data as is.
|
||||
*/
|
||||
char buf[11];
|
||||
int ret;
|
||||
|
||||
/* Read data received in the request */
|
||||
ret = httpd_req_recv(req, buf, sizeof(buf) - 1);
|
||||
if (ret < 0) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
buf[ret] = '\0';
|
||||
ESP_LOGI(TAG, "leftover data handler read %s", buf);
|
||||
httpd_resp_send(req, buf, strlen(buf));
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
int httpd_default_send(int sockfd, const char *buf, unsigned buf_len, int flags);
|
||||
void generate_async_resp(void *arg)
|
||||
{
|
||||
char buf[250];
|
||||
int fd = (int )arg;
|
||||
#define HTTPD_HDR_STR "HTTP/1.1 200 OK\r\n" \
|
||||
"Content-Type: text/html\r\n" \
|
||||
"Content-Length: %d\r\n"
|
||||
#define STR "Hello Double World!"
|
||||
|
||||
ESP_LOGI(TAG, "Executing queued work fd : %d", fd);
|
||||
|
||||
snprintf(buf, sizeof(buf), HTTPD_HDR_STR,
|
||||
strlen(STR));
|
||||
httpd_default_send(fd, buf, strlen(buf), 0);
|
||||
/* Space for sending additional headers based on set_header */
|
||||
httpd_default_send(fd, "\r\n", strlen("\r\n"), 0);
|
||||
httpd_default_send(fd, STR, strlen(STR), 0);
|
||||
#undef STR
|
||||
}
|
||||
|
||||
esp_err_t async_get_handler(httpd_req_t *req)
|
||||
{
|
||||
#define STR "Hello World!"
|
||||
httpd_resp_send(req, STR, strlen(STR));
|
||||
/* Also register a HTTPD Work which sends the same data on the same
|
||||
* socket again
|
||||
*/
|
||||
int fd = httpd_req_to_sockfd(req);
|
||||
if (fd < 0) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
ESP_LOGI(TAG, "Queuing work fd : %d", fd);
|
||||
httpd_queue_work(req->handle, generate_async_resp, (void *)fd);
|
||||
return ESP_OK;
|
||||
#undef STR
|
||||
}
|
||||
|
||||
|
||||
httpd_uri_t basic_handlers[] = {
|
||||
{ .uri = "/hello/type_html",
|
||||
.method = HTTP_GET,
|
||||
.handler = hello_type_get_handler,
|
||||
.user_ctx = NULL,
|
||||
},
|
||||
{ .uri = "/hello",
|
||||
.method = HTTP_GET,
|
||||
.handler = hello_get_handler,
|
||||
.user_ctx = NULL,
|
||||
},
|
||||
{ .uri = "/hello/status_500",
|
||||
.method = HTTP_GET,
|
||||
.handler = hello_status_get_handler,
|
||||
.user_ctx = NULL,
|
||||
},
|
||||
{ .uri = "/echo",
|
||||
.method = HTTP_POST,
|
||||
.handler = echo_post_handler,
|
||||
.user_ctx = NULL,
|
||||
},
|
||||
{ .uri = "/echo",
|
||||
.method = HTTP_PUT,
|
||||
.handler = echo_post_handler,
|
||||
.user_ctx = NULL,
|
||||
},
|
||||
{ .uri = "/leftover_data",
|
||||
.method = HTTP_POST,
|
||||
.handler = leftover_data_post_handler,
|
||||
.user_ctx = NULL,
|
||||
},
|
||||
{ .uri = "/adder",
|
||||
.method = HTTP_POST,
|
||||
.handler = adder_post_handler,
|
||||
.user_ctx = NULL,
|
||||
},
|
||||
{ .uri = "/async_data",
|
||||
.method = HTTP_GET,
|
||||
.handler = async_get_handler,
|
||||
.user_ctx = NULL,
|
||||
}
|
||||
};
|
||||
|
||||
int basic_handlers_no = sizeof(basic_handlers)/sizeof(httpd_uri_t);
|
||||
void register_basic_handlers(httpd_handle_t hd)
|
||||
{
|
||||
int i;
|
||||
ESP_LOGI(TAG, "Registering basic handlers");
|
||||
ESP_LOGI(TAG, "No of handlers = %d", basic_handlers_no);
|
||||
for (i = 0; i < basic_handlers_no; i++) {
|
||||
if (httpd_register_uri_handler(hd, &basic_handlers[i]) != ESP_OK) {
|
||||
ESP_LOGW(TAG, "register uri failed for %d", i);
|
||||
return;
|
||||
}
|
||||
}
|
||||
ESP_LOGI(TAG, "Success");
|
||||
}
|
||||
|
||||
/********************* Basic Handlers End *******************/
|
||||
|
||||
esp_err_t my_hello_post_handler(httpd_req_t *req)
|
||||
{
|
||||
char buf[10];
|
||||
char outbuf[50];
|
||||
int ret;
|
||||
|
||||
ret = httpd_req_recv(req, buf, sizeof(buf));
|
||||
if (ret < 0) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
httpd_resp_set_status(req, HTTPD_404);
|
||||
httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
|
||||
ESP_LOGI(TAG, "Read %d bytes as:%s:", ret, buf);
|
||||
buf[ret] = '\0';
|
||||
#define STR "my_hello_handler"
|
||||
snprintf(outbuf, sizeof(outbuf), STR" %s", buf);
|
||||
httpd_resp_send(req, outbuf, strlen(outbuf));
|
||||
return ESP_OK;
|
||||
#undef STR
|
||||
}
|
||||
|
||||
|
||||
/********************* Test Handler Limit Start *******************/
|
||||
|
||||
esp_err_t null_func(httpd_req_t *req)
|
||||
{
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
httpd_uri_t handler_limit_uri (char* path)
|
||||
{
|
||||
httpd_uri_t uri = {
|
||||
.uri = path,
|
||||
.method = HTTP_GET,
|
||||
.handler = null_func,
|
||||
.user_ctx = NULL,
|
||||
};
|
||||
return uri;
|
||||
};
|
||||
|
||||
static inline unsigned num_digits(unsigned x)
|
||||
{
|
||||
unsigned digits = 1;
|
||||
while ((x = x/10) != 0) {
|
||||
digits++;
|
||||
}
|
||||
return digits;
|
||||
}
|
||||
|
||||
#define HTTPD_TEST_MAX_URI_HANDLERS 8
|
||||
|
||||
void test_handler_limit(httpd_handle_t hd)
|
||||
{
|
||||
int i, ret;
|
||||
char x[HTTPD_TEST_MAX_URI_HANDLERS+1][num_digits(HTTPD_TEST_MAX_URI_HANDLERS)+1];
|
||||
httpd_uri_t uris[HTTPD_TEST_MAX_URI_HANDLERS+1];
|
||||
|
||||
for (i = 0; i < HTTPD_TEST_MAX_URI_HANDLERS + 1; i++) {
|
||||
sprintf(x[i],"%d",i);
|
||||
uris[i] = handler_limit_uri(x[i]);
|
||||
}
|
||||
|
||||
/* Register multiple instances of the same handler for MAX URI Handlers */
|
||||
ESP_LOGI(TAG, "Test: Register Max URI handlers: %d...", HTTPD_TEST_MAX_URI_HANDLERS);
|
||||
for (i = 0; i < HTTPD_TEST_MAX_URI_HANDLERS; i++) {
|
||||
ret = httpd_register_uri_handler(hd, &uris[i]);
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGI(TAG, "Fail");
|
||||
goto error_ret;
|
||||
}
|
||||
}
|
||||
ESP_LOGI(TAG, "Success");
|
||||
|
||||
/* Register the MAX URI + 1 Handlers should fail */
|
||||
ESP_LOGI(TAG, "Test: Register Max URI + 1 handlers: %d th...", HTTPD_TEST_MAX_URI_HANDLERS +1 );
|
||||
ret = httpd_register_uri_handler(hd, &uris[HTTPD_TEST_MAX_URI_HANDLERS]);
|
||||
if (ret == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Fail");
|
||||
goto error_ret;
|
||||
}
|
||||
ESP_LOGI(TAG, "Success");
|
||||
|
||||
/* Unregister the one of the Handler should pass */
|
||||
ESP_LOGI(TAG, "Test: Unregister 0th handler...");
|
||||
ret = httpd_unregister_uri_handler(hd, uris[0].uri, uris[0].method);
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGI(TAG, "Fail");
|
||||
goto error_ret;
|
||||
}
|
||||
ESP_LOGI(TAG, "Success");
|
||||
|
||||
/* Unregister non added Handler should fail */
|
||||
ESP_LOGI(TAG, "Test: Again unregister 0th handler not registered...");
|
||||
ret = httpd_unregister_uri_handler(hd, uris[0].uri, uris[0].method);
|
||||
if (ret == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Fail");
|
||||
goto error_ret;
|
||||
}
|
||||
ESP_LOGI(TAG, "Success");
|
||||
|
||||
/* Register the MAX URI Handler should pass */
|
||||
ESP_LOGI(TAG, "Test: Register back 0th handler...");
|
||||
ret = httpd_register_uri_handler(hd, &uris[0]);
|
||||
if (ret != ESP_OK) {
|
||||
ESP_LOGI(TAG, "Fail");
|
||||
goto error_ret;
|
||||
}
|
||||
ESP_LOGI(TAG, "Success");
|
||||
|
||||
/* Reregister same instance of handler should fail */
|
||||
ESP_LOGI(TAG, "Test: Register 0th handler again after registering...");
|
||||
ret = httpd_register_uri_handler(hd, &uris[0]);
|
||||
if (ret == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Fail");
|
||||
goto error_ret;
|
||||
}
|
||||
ESP_LOGI(TAG, "Success");
|
||||
|
||||
/* Register the MAX URI + 1 Handlers should fail */
|
||||
ESP_LOGI(TAG, "Test: Register 1 more handler...");
|
||||
ret = httpd_register_uri_handler(hd, &uris[HTTPD_TEST_MAX_URI_HANDLERS]);
|
||||
if (ret == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Fail");
|
||||
goto error_ret;
|
||||
}
|
||||
ESP_LOGI(TAG, "Success");
|
||||
|
||||
/* Unregister the same handler for MAX URI Handlers */
|
||||
ESP_LOGI(TAG, "Test: Unregister all handlers:");
|
||||
for (i = 0; i < HTTPD_TEST_MAX_URI_HANDLERS; i++) {
|
||||
ret = httpd_unregister_uri_handler(hd, uris[i].uri, uris[i].method);
|
||||
if (ret != 0) {
|
||||
ESP_LOGI(TAG, "Fail");
|
||||
goto error_ret;
|
||||
}
|
||||
}
|
||||
ESP_LOGI(TAG, "Success");
|
||||
error_ret:
|
||||
for (; i < HTTPD_TEST_MAX_URI_HANDLERS; i++) {
|
||||
httpd_unregister_uri_handler(hd, uris[i].uri, uris[i].method);
|
||||
}
|
||||
basic_sanity = false;
|
||||
}
|
||||
|
||||
/********************* Test Handler Limit End *******************/
|
||||
|
||||
httpd_handle_t test_httpd_start()
|
||||
{
|
||||
pre_start_mem = esp_get_free_heap_size();
|
||||
httpd_handle_t hd;
|
||||
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
|
||||
if (httpd_start(&hd, &config) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Started HTTP server on port: %d", config.server_port);
|
||||
ESP_LOGI(TAG, "Max URI handlers: %d", config.max_uri_handlers);
|
||||
ESP_LOGI(TAG, "Max Open Sessions: %d", config.max_open_sockets);
|
||||
ESP_LOGI(TAG, "Max Header Length: %d", HTTPD_MAX_REQ_HDR_LEN);
|
||||
ESP_LOGI(TAG, "Max URI Length: %d", HTTPD_MAX_URI_LEN);
|
||||
ESP_LOGI(TAG, "Max Stack Size: %d", config.stack_size);
|
||||
return hd;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
httpd_handle_t test_httpd_start_dummy(uint16_t id)
|
||||
{
|
||||
pre_start_mem = esp_get_free_heap_size();
|
||||
ESP_LOGI(TAG, "HTTPD Start: Current free memory: %d", pre_start_mem);
|
||||
httpd_handle_t hd;
|
||||
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
|
||||
config.max_uri_handlers = HTTPD_TEST_MAX_URI_HANDLERS;
|
||||
config.server_port += id;
|
||||
config.ctrl_port += id;
|
||||
if (httpd_start(&hd, &config) == ESP_OK) {
|
||||
return hd;
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void test_httpd_stop(httpd_handle_t hd)
|
||||
{
|
||||
httpd_stop(hd);
|
||||
post_stop_mem = esp_get_free_heap_size();
|
||||
ESP_LOGI(TAG, "HTTPD Stop: Current free memory: %d", post_stop_mem);
|
||||
|
||||
// Below function is not available but would be desirable to have
|
||||
// post_stop_min_mem = os_get_minimum_free_mem();
|
||||
// ESP_LOGI(TAG, "HTTPD Stop: Minimum free memory: %d", post_stop_min_mem);
|
||||
}
|
||||
|
||||
#define SERVER_INSTANCES 10
|
||||
|
||||
/* Currently this only tests for the number of tasks.
|
||||
* Heap leakage is not tested as LWIP allocates memory
|
||||
* which may not be freed immedietly causing erroneous
|
||||
* evaluation. Another test to implement would be the
|
||||
* monitoring of open sockets, but LWIP presently provides
|
||||
* no such API for getting the number of open sockets.
|
||||
*/
|
||||
bool leak_test(void)
|
||||
{
|
||||
httpd_handle_t hd[SERVER_INSTANCES];
|
||||
bool success = true;
|
||||
|
||||
unsigned task_count = uxTaskGetNumberOfTasks();
|
||||
ESP_LOGI(TAG, "Leak Test Started...");
|
||||
ESP_LOGI(TAG, "Current free heap : %d", xPortGetFreeHeapSize());
|
||||
ESP_LOGI(TAG, "Total tasks running : %d", task_count);
|
||||
|
||||
for (int i = 0; i < SERVER_INSTANCES; i++) {
|
||||
ESP_LOGI(TAG, "Starting Server Instance [%d]", i);
|
||||
hd[i] = test_httpd_start_dummy(i);
|
||||
if (hd[i]) {
|
||||
register_basic_handlers(hd[i]);
|
||||
task_count++;
|
||||
}
|
||||
ESP_LOGI(TAG, "Current free heap : %d", xPortGetFreeHeapSize());
|
||||
ESP_LOGI(TAG, "Total tasks running : %d", uxTaskGetNumberOfTasks());
|
||||
if (uxTaskGetNumberOfTasks() != task_count) {
|
||||
ESP_LOGE(TAG, "Task count mismatch");
|
||||
success = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < SERVER_INSTANCES; i++) {
|
||||
ESP_LOGI(TAG, "Stopping Server Instance [%d]", i);
|
||||
if (hd[i]) {
|
||||
httpd_stop(hd[i]);
|
||||
task_count--;
|
||||
}
|
||||
ESP_LOGI(TAG, "Current free heap : %d", xPortGetFreeHeapSize());
|
||||
ESP_LOGI(TAG, "Total tasks running : %d", uxTaskGetNumberOfTasks());
|
||||
if (uxTaskGetNumberOfTasks() != task_count) {
|
||||
ESP_LOGE(TAG, "Task count mismatch");
|
||||
success = false;
|
||||
}
|
||||
}
|
||||
if (success) {
|
||||
ESP_LOGI(TAG, "Leak Test Passed");
|
||||
}
|
||||
else {
|
||||
ESP_LOGI(TAG, "Leak Test Failed");
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
httpd_handle_t start_tests()
|
||||
{
|
||||
leak_test();
|
||||
httpd_handle_t hd = test_httpd_start();
|
||||
if (hd) {
|
||||
test_handler_limit(hd);
|
||||
register_basic_handlers(hd);
|
||||
}
|
||||
return hd;
|
||||
}
|
||||
|
||||
void stop_tests(httpd_handle_t hd)
|
||||
{
|
||||
ESP_LOGI(TAG, "Stopping httpd");
|
||||
test_httpd_stop(hd);
|
||||
}
|
||||
@@ -0,0 +1,841 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2018 Espressif Systems (Shanghai) PTE LTD
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
# Utility for testing the web server. Test cases:
|
||||
# Assume the device supports 'n' simultaneous open sockets
|
||||
#
|
||||
# HTTP Server Tests
|
||||
#
|
||||
# 0. Firmware Settings:
|
||||
# - Create a dormant thread whose sole job is to call httpd_stop() when instructed
|
||||
# - Measure the following before httpd_start() is called:
|
||||
# - current free memory
|
||||
# - current free sockets
|
||||
# - Measure the same whenever httpd_stop is called
|
||||
# - Register maximum possible URI handlers: should be successful
|
||||
# - Register one more URI handler: should fail
|
||||
# - Deregister on URI handler: should be successful
|
||||
# - Register on more URI handler: should succeed
|
||||
# - Register separate handlers for /hello, /hello/type_html. Also
|
||||
# ensure that /hello/type_html is registered BEFORE /hello. (tests
|
||||
# that largest matching URI is picked properly)
|
||||
# - Create URI handler /adder. Make sure it uses a custom free_ctx
|
||||
# structure to free it up
|
||||
|
||||
# 1. Using Standard Python HTTP Client
|
||||
# - simple GET on /hello (returns Hello World. Ensures that basic
|
||||
# firmware tests are complete, or returns error)
|
||||
# - POST on /hello (should fail)
|
||||
# - PUT on /hello (should fail)
|
||||
# - simple POST on /echo (returns whatever the POST data)
|
||||
# - simple PUT on /echo (returns whatever the PUT data)
|
||||
# - GET on /echo (should fail)
|
||||
# - simple GET on /hello/type_html (returns Content type as text/html)
|
||||
# - simple GET on /hello/status_500 (returns HTTP status 500)
|
||||
# - simple GET on /false_uri (returns HTTP status 404)
|
||||
# - largest matching URI handler is picked is already verified because
|
||||
# of /hello and /hello/type_html tests
|
||||
#
|
||||
#
|
||||
# 2. Session Tests
|
||||
# - Sessions + Pipelining basics:
|
||||
# - Create max supported sessions
|
||||
# - On session i,
|
||||
# - send 3 back-to-back POST requests with data i on /adder
|
||||
# - read back 3 responses. They should be i, 2i and 3i
|
||||
# - Tests that
|
||||
# - pipelining works
|
||||
# - per-session context is maintained for all supported
|
||||
# sessions
|
||||
# - Close all sessions
|
||||
#
|
||||
# - Cleanup leftover data: Tests that the web server properly cleans
|
||||
# up leftover data
|
||||
# - Create a session
|
||||
# - POST on /leftover_data with 52 bytes of data (data includes
|
||||
# \r\n)(the handler only
|
||||
# reads first 10 bytes and returns them, leaving the rest of the
|
||||
# bytes unread)
|
||||
# - GET on /hello (should return 'Hello World')
|
||||
# - POST on /false_uri with 52 bytes of data (data includes \r\n)
|
||||
# (should return HTTP 404)
|
||||
# - GET on /hello (should return 'Hello World')
|
||||
#
|
||||
# - Test HTTPd Asynchronous response
|
||||
# - Create a session
|
||||
# - GET on /async_data
|
||||
# - returns 'Hello World!' as a response
|
||||
# - the handler schedules an async response, which generates a second
|
||||
# response 'Hello Double World!'
|
||||
#
|
||||
# - Spillover test
|
||||
# - Create max supported sessions with the web server
|
||||
# - GET /hello on all the sessions (should return Hello World)
|
||||
# - Create one more session, this should fail
|
||||
# - GET /hello on all the sessions (should return Hello World)
|
||||
#
|
||||
# - Timeout test
|
||||
# - Create a session and only Send 'GE' on the same (simulates a
|
||||
# client that left the network halfway through a request)
|
||||
# - Wait for recv-wait-timeout
|
||||
# - Server should automatically close the socket
|
||||
|
||||
|
||||
############# TODO TESTS #############
|
||||
|
||||
# 3. Stress Tests
|
||||
#
|
||||
# - httperf
|
||||
# - Run the following httperf command:
|
||||
# httperf --server=10.31.130.126 --wsess=8,50,0.5 --rate 8 --burst-length 2
|
||||
#
|
||||
# - The above implies that the test suite will open
|
||||
# - 8 simultaneous connections with the server
|
||||
# - the rate of opening the sessions will be 8 per sec. So in our
|
||||
# case, a new connection will be opened every 0.2 seconds for 1 second
|
||||
# - The burst length 2 indicates that 2 requests will be sent
|
||||
# simultaneously on the same connection in a single go
|
||||
# - 0.5 seconds is the time between sending out 2 bursts
|
||||
# - 50 is the total number of requests that will be sent out
|
||||
#
|
||||
# - So in the above example, the test suite will open 8
|
||||
# connections, each separated by 0.2 seconds. On each connection
|
||||
# it will send 2 requests in a single burst. The bursts on a
|
||||
# single connection will be separated by 0.5 seconds. A total of
|
||||
# 25 bursts (25 x 2 = 50) will be sent out
|
||||
|
||||
# 4. Leak Tests
|
||||
# - Simple Leak test
|
||||
# - Simple GET on /hello/restart (returns success, stop web server, measures leaks, restarts webserver)
|
||||
# - Simple GET on /hello/restart_results (returns the leak results)
|
||||
# - Leak test with open sockets
|
||||
# - Open 8 sessions
|
||||
# - Simple GET on /hello/restart (returns success, stop web server,
|
||||
# measures leaks, restarts webserver)
|
||||
# - All sockets should get closed
|
||||
# - Simple GET on /hello/restart_results (returns the leak results)
|
||||
|
||||
|
||||
import threading
|
||||
import socket
|
||||
import time
|
||||
import argparse
|
||||
import requests
|
||||
import signal
|
||||
import sys
|
||||
import string
|
||||
import random
|
||||
|
||||
_verbose_ = False
|
||||
|
||||
class Session:
|
||||
def __init__(self, addr, port):
|
||||
self.client = socket.create_connection((addr, int(port)))
|
||||
self.client.settimeout(30)
|
||||
self.target = addr
|
||||
|
||||
def send_get(self, path, headers=None):
|
||||
request = "GET " + path + " HTTP/1.1\r\nHost: " + self.target
|
||||
if headers:
|
||||
for field, value in headers.iteritems():
|
||||
request += "\r\n"+field+": "+value
|
||||
request += "\r\n\r\n"
|
||||
self.client.send(request);
|
||||
|
||||
def send_put(self, path, data, headers=None):
|
||||
request = "PUT " + path + " HTTP/1.1\r\nHost: " + self.target
|
||||
if headers:
|
||||
for field, value in headers.iteritems():
|
||||
request += "\r\n"+field+": "+value
|
||||
request += "\r\nContent-Length: " + str(len(data)) +"\r\n\r\n"
|
||||
self.client.send(request)
|
||||
self.client.send(data)
|
||||
|
||||
def send_post(self, path, data, headers=None):
|
||||
request = "POST " + path + " HTTP/1.1\r\nHost: " + self.target
|
||||
if headers:
|
||||
for field, value in headers.iteritems():
|
||||
request += "\r\n"+field+": "+value
|
||||
request += "\r\nContent-Length: " + str(len(data)) +"\r\n\r\n"
|
||||
self.client.send(request)
|
||||
self.client.send(data)
|
||||
|
||||
def read_resp_hdrs(self):
|
||||
state = 'nothing'
|
||||
resp_read = ''
|
||||
while True:
|
||||
char = self.client.recv(1)
|
||||
if char == '\r' and state == 'nothing':
|
||||
state = 'first_cr'
|
||||
elif char == '\n' and state == 'first_cr':
|
||||
state = 'first_lf'
|
||||
elif char == '\r' and state == 'first_lf':
|
||||
state = 'second_cr'
|
||||
elif char == '\n' and state == 'second_cr':
|
||||
state = 'second_lf'
|
||||
else:
|
||||
state = 'nothing'
|
||||
resp_read += char
|
||||
if state == 'second_lf':
|
||||
break;
|
||||
# Handle first line
|
||||
line_hdrs = resp_read.splitlines()
|
||||
line_comp = line_hdrs[0].split()
|
||||
self.status = line_comp[1]
|
||||
del line_hdrs[0]
|
||||
self.encoding = ''
|
||||
self.content_type = ''
|
||||
headers = dict()
|
||||
# Process other headers
|
||||
for h in range(len(line_hdrs)):
|
||||
line_comp = line_hdrs[h].split(':')
|
||||
if line_comp[0] == 'Content-Length':
|
||||
self.content_len = int(line_comp[1])
|
||||
if line_comp[0] == 'Content-Type':
|
||||
self.content_type = line_comp[1].lstrip()
|
||||
if line_comp[0] == 'Transfer-Encoding':
|
||||
self.encoding = line_comp[1].lstrip()
|
||||
if len(line_comp) == 2:
|
||||
headers[line_comp[0]] = line_comp[1].lstrip()
|
||||
return headers
|
||||
|
||||
def read_resp_data(self):
|
||||
read_data = ''
|
||||
if self.encoding != 'chunked':
|
||||
while len(read_data) != self.content_len:
|
||||
read_data += self.client.recv(self.content_len)
|
||||
self.content_len = 0
|
||||
else:
|
||||
chunk_data_buf = ''
|
||||
while (True):
|
||||
# Read one character into temp buffer
|
||||
read_ch = self.client.recv(1)
|
||||
# Check CRLF
|
||||
if (read_ch == '\r'):
|
||||
read_ch = self.client.recv(1)
|
||||
if (read_ch == '\n'):
|
||||
# If CRLF decode length of chunk
|
||||
chunk_len = int(chunk_data_buf, 16)
|
||||
# Keep adding to contents
|
||||
self.content_len += chunk_len
|
||||
read_data += self.client.recv(chunk_len)
|
||||
chunk_data_buf = ''
|
||||
# Fetch remaining CRLF
|
||||
if self.client.recv(2) != "\r\n":
|
||||
# Error in packet
|
||||
return None
|
||||
if not chunk_len:
|
||||
# If last chunk
|
||||
break
|
||||
continue
|
||||
chunk_data_buf += '\r'
|
||||
# If not CRLF continue appending
|
||||
# character to chunked data buffer
|
||||
chunk_data_buf += read_ch
|
||||
return read_data
|
||||
|
||||
def close(self):
|
||||
self.client.close()
|
||||
|
||||
def test_val(text, expected, received):
|
||||
if expected != received:
|
||||
print " Fail!"
|
||||
print " [reason] " + text + ":"
|
||||
print " expected: " + str(expected)
|
||||
print " received: " + str(received)
|
||||
return False
|
||||
return True
|
||||
|
||||
class myThread (threading.Thread):
|
||||
def __init__(self, id, dut, port):
|
||||
threading.Thread.__init__(self)
|
||||
self.id = id
|
||||
self.dut = dut
|
||||
self.session = Session(dut, port)
|
||||
|
||||
def run(self):
|
||||
self.response = []
|
||||
|
||||
# Pipeline 3 requests
|
||||
if (_verbose_):
|
||||
print " Thread: Using adder start " + str(self.id)
|
||||
self.session.send_post('/adder', str(self.id));
|
||||
time.sleep(1)
|
||||
self.session.send_post('/adder', str(self.id));
|
||||
time.sleep(1)
|
||||
self.session.send_post('/adder', str(self.id));
|
||||
time.sleep(1)
|
||||
|
||||
self.session.read_resp_hdrs()
|
||||
self.response.append(self.session.read_resp_data())
|
||||
self.session.read_resp_hdrs()
|
||||
self.response.append(self.session.read_resp_data())
|
||||
self.session.read_resp_hdrs()
|
||||
self.response.append(self.session.read_resp_data())
|
||||
|
||||
def adder_result(self):
|
||||
for i in range(len(self.response)):
|
||||
# print self.response[i]
|
||||
if not test_val("thread" + str(self.id) + ": response[" + str(i) + "]",
|
||||
str(self.id * (i + 1)), str(self.response[i])):
|
||||
return False
|
||||
return True
|
||||
|
||||
def close(self):
|
||||
self.session.close()
|
||||
|
||||
def get_hello(dut, port):
|
||||
# GET /hello should return 'Hello World!'
|
||||
print "[test] GET /hello returns 'Hello World!' =>",
|
||||
r = requests.get("http://" + dut + ":" + port + "/hello")
|
||||
if not test_val("status_code", 200, r.status_code):
|
||||
return False
|
||||
if not test_val("data", "Hello World!", r.text):
|
||||
return False
|
||||
if not test_val("data", "application/json", r.headers['Content-Type']):
|
||||
return False
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def post_hello(dut, port):
|
||||
# PUT /hello returns 405'
|
||||
print "[test] PUT /hello returns 405' =>",
|
||||
r = requests.put("http://" + dut + ":" + port + "/hello", data="Hello")
|
||||
if not test_val("status_code", 405, r.status_code):
|
||||
return False
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def put_hello(dut, port):
|
||||
# POST /hello returns 405'
|
||||
print "[test] POST /hello returns 404' =>",
|
||||
r = requests.post("http://" + dut + ":" + port + "/hello", data="Hello")
|
||||
if not test_val("status_code", 405, r.status_code):
|
||||
return False
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def post_echo(dut, port):
|
||||
# POST /echo echoes data'
|
||||
print "[test] POST /echo echoes data' =>",
|
||||
r = requests.post("http://" + dut + ":" + port + "/echo", data="Hello")
|
||||
if not test_val("status_code", 200, r.status_code):
|
||||
return False
|
||||
if not test_val("data", "Hello", r.text):
|
||||
return False
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def put_echo(dut, port):
|
||||
# POST /echo echoes data'
|
||||
print "[test] PUT /echo echoes data' =>",
|
||||
r = requests.put("http://" + dut + ":" + port + "/echo", data="Hello")
|
||||
if not test_val("status_code", 200, r.status_code):
|
||||
return False
|
||||
if not test_val("data", "Hello", r.text):
|
||||
return False
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def get_echo(dut, port):
|
||||
# GET /echo returns 404'
|
||||
print "[test] GET /echo returns 405' =>",
|
||||
r = requests.get("http://" + dut + ":" + port + "/echo")
|
||||
if not test_val("status_code", 405, r.status_code):
|
||||
return False
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def get_hello_type(dut, port):
|
||||
# GET /hello/type_html returns text/html as Content-Type'
|
||||
print "[test] GET /hello/type_html has Content-Type of text/html =>",
|
||||
r = requests.get("http://" + dut + ":" + port + "/hello/type_html")
|
||||
if not test_val("status_code", 200, r.status_code):
|
||||
return False
|
||||
if not test_val("data", "Hello World!", r.text):
|
||||
return False
|
||||
if not test_val("data", "text/html", r.headers['Content-Type']):
|
||||
return False
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def get_hello_status(dut, port):
|
||||
# GET /hello/status_500 returns status 500'
|
||||
print "[test] GET /hello/status_500 returns status 500 =>",
|
||||
r = requests.get("http://" + dut + ":" + port + "/hello/status_500")
|
||||
if not test_val("status_code", 500, r.status_code):
|
||||
return False
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def get_false_uri(dut, port):
|
||||
# GET /false_uri returns status 404'
|
||||
print "[test] GET /false_uri returns status 404 =>",
|
||||
r = requests.get("http://" + dut + ":" + port + "/false_uri")
|
||||
if not test_val("status_code", 404, r.status_code):
|
||||
return False
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def parallel_sessions_adder(dut, port, max_sessions):
|
||||
# POSTs on /adder in parallel sessions
|
||||
print "[test] POST {pipelined} on /adder in " + str(max_sessions) + " sessions =>",
|
||||
t = []
|
||||
# Create all sessions
|
||||
for i in xrange(max_sessions):
|
||||
t.append(myThread(i * 2, dut, port))
|
||||
|
||||
for i in xrange(len(t)):
|
||||
t[i].start()
|
||||
|
||||
for i in xrange(len(t)):
|
||||
t[i].join()
|
||||
|
||||
res = True
|
||||
for i in xrange(len(t)):
|
||||
if not t[i].adder_result():
|
||||
if not test_val("Thread" + str(i) + "Failed", "True", "False"):
|
||||
res = False
|
||||
t[i].close()
|
||||
if (res):
|
||||
print "Success"
|
||||
return res
|
||||
|
||||
def async_response_test(dut, port):
|
||||
# Test that an asynchronous work is executed in the HTTPD's context
|
||||
# This is tested by reading two responses over the same session
|
||||
print "[test] Test HTTPD Work Queue (Async response) =>",
|
||||
s = Session(dut, port)
|
||||
|
||||
s.send_get('/async_data')
|
||||
s.read_resp_hdrs()
|
||||
if not test_val("First Response", "Hello World!", s.read_resp_data()):
|
||||
s.close()
|
||||
return False
|
||||
s.read_resp_hdrs()
|
||||
if not test_val("Second Response", "Hello Double World!", s.read_resp_data()):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def leftover_data_test(dut, port):
|
||||
# Leftover data in POST is purged (valid and invalid URIs)
|
||||
print "[test] Leftover data in POST is purged (valid and invalid URIs) =>",
|
||||
s = Session(dut, port)
|
||||
|
||||
s.send_post('/leftover_data',
|
||||
"abcdefghijklmnopqrstuvwxyz\r\nabcdefghijklmnopqrstuvwxyz")
|
||||
s.read_resp_hdrs()
|
||||
if not test_val("Partial data", "abcdefghij", s.read_resp_data()):
|
||||
s.close()
|
||||
return False
|
||||
|
||||
s.send_get('/hello')
|
||||
s.read_resp_hdrs()
|
||||
if not test_val("Hello World Data", "Hello World!", s.read_resp_data()):
|
||||
s.close()
|
||||
return False
|
||||
|
||||
s.send_post('/false_uri',
|
||||
"abcdefghijklmnopqrstuvwxyz\r\nabcdefghijklmnopqrstuvwxyz")
|
||||
s.read_resp_hdrs()
|
||||
if not test_val("False URI Status", str(404), str(s.status)):
|
||||
s.close()
|
||||
return False
|
||||
s.read_resp_data()
|
||||
|
||||
s.send_get('/hello')
|
||||
s.read_resp_hdrs()
|
||||
if not test_val("Hello World Data", "Hello World!", s.read_resp_data()):
|
||||
s.close()
|
||||
return False
|
||||
|
||||
s.close()
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def timeout_handler(signum, frame):
|
||||
raise Exception("Timeout")
|
||||
|
||||
def spillover_session(dut, port, max):
|
||||
# Session max_sessions + 1 is rejected
|
||||
print "[test] Session max_sessions (" + str(max) + ") + 1 is rejected =>",
|
||||
s = []
|
||||
# Register a timeout callback
|
||||
signal.signal(signal.SIGALRM, timeout_handler)
|
||||
for i in xrange(max + 1):
|
||||
if (_verbose_):
|
||||
print "Executing " + str(i)
|
||||
a = Session(dut, port)
|
||||
a.send_get('/hello')
|
||||
|
||||
try:
|
||||
# Check for response timeout
|
||||
signal.alarm(5)
|
||||
a.read_resp_hdrs()
|
||||
a.read_resp_data()
|
||||
signal.alarm(0)
|
||||
|
||||
# Control reaches here only if connection was established
|
||||
s.append(a)
|
||||
except Exception, msg:
|
||||
if (_verbose_):
|
||||
print str(msg) + ": Connection " + str(i) + " rejected"
|
||||
break
|
||||
|
||||
# Close open connections
|
||||
for a in s:
|
||||
a.close()
|
||||
|
||||
# Check if number of connections is equal to max
|
||||
print ["Fail","Success"][len(s) == max]
|
||||
return (len(s) == max)
|
||||
|
||||
def recv_timeout_test(dut, port):
|
||||
print "[test] Timeout occurs if partial packet sent =>",
|
||||
signal.signal(signal.SIGALRM, timeout_handler)
|
||||
s = Session(dut, port)
|
||||
s.client.send("GE")
|
||||
try:
|
||||
signal.alarm(15)
|
||||
s.read_resp_hdrs()
|
||||
resp = s.read_resp_data()
|
||||
signal.alarm(0)
|
||||
if not test_val("Request Timeout", "Server closed this connection", resp):
|
||||
s.close()
|
||||
return False
|
||||
except:
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def pipeline_test(dut, port, max_sess):
|
||||
print "[test] Pipelining test =>",
|
||||
s = [Session(dut, port) for _ in range(max_sess)]
|
||||
path = "/echo"
|
||||
pipeline_depth = 10
|
||||
header = "POST " + path + " HTTP/1.1\r\nHost: " + dut + "\r\nContent-Length: "
|
||||
s[0].client.send(header)
|
||||
for i in range(1, max_sess):
|
||||
for j in range(pipeline_depth):
|
||||
data = str(i) + ":" + str(j)
|
||||
request = header + str(len(data)) + "\r\n\r\n" + data
|
||||
s[i].client.send(request)
|
||||
|
||||
s[0].client.send(str(len("0:0")) + "\r\n\r\n" + "0:0")
|
||||
for j in range(1, pipeline_depth):
|
||||
data = "0:" + str(j)
|
||||
request = header + str(len(data)) + "\r\n\r\n" + data
|
||||
s[0].client.send(request)
|
||||
|
||||
res = True
|
||||
for i in range(max_sess):
|
||||
#time.sleep(1)
|
||||
for j in range(pipeline_depth):
|
||||
s[i].read_resp_hdrs()
|
||||
echo_data = s[i].read_resp_data()
|
||||
if (_verbose_):
|
||||
print "[" + str(i) + "][" + str(j) + "] = " + echo_data
|
||||
if not test_val("Echo Data", str(i) + ":" + str(j), echo_data):
|
||||
res = False
|
||||
s[i].close()
|
||||
|
||||
#for i in range(max_sess):
|
||||
#s[i].close()
|
||||
|
||||
if (res):
|
||||
print "Success"
|
||||
return res
|
||||
|
||||
def packet_size_limit_test(dut, port, test_size):
|
||||
print "[test] LWIP send size limit test =>",
|
||||
s = Session(dut, port)
|
||||
random_data = ''.join(string.printable[random.randint(0,len(string.printable))-1] for _ in range(test_size))
|
||||
path = "/echo"
|
||||
s.send_post(path, random_data)
|
||||
s.read_resp_hdrs()
|
||||
resp = s.read_resp_data()
|
||||
result = (resp == random_data)
|
||||
if not result:
|
||||
test_val("Data size", str(len(random_data)), str(len(resp)))
|
||||
s.close()
|
||||
return False
|
||||
print "Success"
|
||||
s.close()
|
||||
return True
|
||||
|
||||
def code_500_server_error_test(dut, port):
|
||||
print "[test] 500 Server Error test =>",
|
||||
s = Session(dut, port)
|
||||
s.client.send("abcdefgh\0")
|
||||
s.read_resp_hdrs()
|
||||
resp = s.read_resp_data()
|
||||
# Presently server sends back 400 Bad Request
|
||||
#if not test_val("Server Error", "500", s.status):
|
||||
#s.close()
|
||||
#return False
|
||||
if not test_val("Server Error", "400", s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def code_501_method_not_impl(dut, port):
|
||||
print "[test] 501 Method Not Implemented =>",
|
||||
s = Session(dut, port)
|
||||
path = "/hello"
|
||||
s.client.send("ABC " + path + " HTTP/1.1\r\nHost: " + dut + "\r\n\r\n")
|
||||
s.read_resp_hdrs()
|
||||
resp = s.read_resp_data()
|
||||
# Presently server sends back 400 Bad Request
|
||||
#if not test_val("Server Error", "501", s.status):
|
||||
#s.close()
|
||||
#return False
|
||||
if not test_val("Server Error", "400", s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def code_505_version_not_supported(dut, port):
|
||||
print "[test] 505 Version Not Supported =>",
|
||||
s = Session(dut, port)
|
||||
path = "/hello"
|
||||
s.client.send("GET " + path + " HTTP/2.0\r\nHost: " + dut + "\r\n\r\n")
|
||||
s.read_resp_hdrs()
|
||||
resp = s.read_resp_data()
|
||||
if not test_val("Server Error", "505", s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def code_400_bad_request(dut, port):
|
||||
print "[test] 400 Bad Request =>",
|
||||
s = Session(dut, port)
|
||||
path = "/hello"
|
||||
s.client.send("XYZ " + path + " HTTP/1.1\r\nHost: " + dut + "\r\n\r\n")
|
||||
s.read_resp_hdrs()
|
||||
resp = s.read_resp_data()
|
||||
if not test_val("Client Error", "400", s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def code_404_not_found(dut, port):
|
||||
print "[test] 404 Not Found =>",
|
||||
s = Session(dut, port)
|
||||
path = "/dummy"
|
||||
s.client.send("GET " + path + " HTTP/1.1\r\nHost: " + dut + "\r\n\r\n")
|
||||
s.read_resp_hdrs()
|
||||
resp = s.read_resp_data()
|
||||
if not test_val("Client Error", "404", s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def code_405_method_not_allowed(dut, port):
|
||||
print "[test] 405 Method Not Allowed =>",
|
||||
s = Session(dut, port)
|
||||
path = "/hello"
|
||||
s.client.send("POST " + path + " HTTP/1.1\r\nHost: " + dut + "\r\n\r\n")
|
||||
s.read_resp_hdrs()
|
||||
resp = s.read_resp_data()
|
||||
if not test_val("Client Error", "405", s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def code_408_req_timeout(dut, port):
|
||||
print "[test] 408 Request Timeout =>",
|
||||
signal.signal(signal.SIGALRM, timeout_handler)
|
||||
s = Session(dut, port)
|
||||
s.client.send("POST /echo HTTP/1.1\r\nHost: " + dut + "\r\nContent-Length: 10\r\n\r\nABCD")
|
||||
try:
|
||||
signal.alarm(15)
|
||||
s.read_resp_hdrs()
|
||||
resp = s.read_resp_data()
|
||||
signal.alarm(0)
|
||||
if not test_val("Client Error", "408", s.status):
|
||||
s.close()
|
||||
return False
|
||||
except:
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def code_411_length_required(dut, port):
|
||||
print "[test] 411 Length Required =>",
|
||||
s = Session(dut, port)
|
||||
path = "/echo"
|
||||
s.client.send("POST " + path + " HTTP/1.1\r\nHost: " + dut + "\r\nContent-Type: text/plain\r\nTransfer-Encoding: chunked\r\n\r\n")
|
||||
s.read_resp_hdrs()
|
||||
resp = s.read_resp_data()
|
||||
# Presently server sends back 400 Bad Request
|
||||
#if not test_val("Client Error", "411", s.status):
|
||||
#s.close()
|
||||
#return False
|
||||
if not test_val("Client Error", "400", s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def send_getx_uri_len(dut, port, length):
|
||||
s = Session(dut, port)
|
||||
method = "GET "
|
||||
version = " HTTP/1.1\r\n"
|
||||
path = "/"+"x"*(length - len(method) - len(version) - len("/"))
|
||||
s.client.send(method)
|
||||
time.sleep(1)
|
||||
s.client.send(path)
|
||||
time.sleep(1)
|
||||
s.client.send(version + "Host: " + dut + "\r\n\r\n")
|
||||
s.read_resp_hdrs()
|
||||
resp = s.read_resp_data()
|
||||
s.close()
|
||||
return s.status
|
||||
|
||||
def code_414_uri_too_long(dut, port, max_uri_len):
|
||||
print "[test] 414 URI Too Long =>",
|
||||
status = send_getx_uri_len(dut, port, max_uri_len)
|
||||
if not test_val("Client Error", "404", status):
|
||||
return False
|
||||
status = send_getx_uri_len(dut, port, max_uri_len + 1)
|
||||
if not test_val("Client Error", "414", status):
|
||||
return False
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def send_postx_hdr_len(dut, port, length):
|
||||
s = Session(dut, port)
|
||||
path = "/echo"
|
||||
host = "Host: " + dut
|
||||
custom_hdr_field = "\r\nCustom: "
|
||||
custom_hdr_val = "x"*(length - len(host) - len(custom_hdr_field) - len("\r\n\r\n") + len("0"))
|
||||
request = "POST " + path + " HTTP/1.1\r\n" + host + custom_hdr_field + custom_hdr_val + "\r\n\r\n"
|
||||
s.client.send(request[:length/2])
|
||||
time.sleep(1)
|
||||
s.client.send(request[length/2:])
|
||||
hdr = s.read_resp_hdrs()
|
||||
resp = s.read_resp_data()
|
||||
s.close()
|
||||
if "Custom" in hdr:
|
||||
return (hdr["Custom"] == custom_hdr_val), resp
|
||||
return False, s.status
|
||||
|
||||
def code_431_hdr_too_long(dut, port, max_hdr_len):
|
||||
print "[test] 431 Header Too Long =>",
|
||||
res, status = send_postx_hdr_len(dut, port, max_hdr_len)
|
||||
if not res:
|
||||
return False
|
||||
res, status = send_postx_hdr_len(dut, port, max_hdr_len + 1)
|
||||
if not test_val("Client Error", "431", status):
|
||||
return False
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
def test_upgrade_not_supported(dut, port):
|
||||
print "[test] Upgrade Not Supported =>",
|
||||
s = Session(dut, port)
|
||||
path = "/hello"
|
||||
s.client.send("OPTIONS * HTTP/1.1\r\nHost:" + dut + "\r\nUpgrade: TLS/1.0\r\nConnection: Upgrade\r\n\r\n");
|
||||
s.read_resp_hdrs()
|
||||
resp = s.read_resp_data()
|
||||
if not test_val("Client Error", "200", s.status):
|
||||
s.close()
|
||||
return False
|
||||
s.close()
|
||||
print "Success"
|
||||
return True
|
||||
|
||||
if __name__ == '__main__':
|
||||
########### Execution begins here...
|
||||
# Configuration
|
||||
# Max number of threads/sessions
|
||||
max_sessions = 7
|
||||
max_uri_len = 512
|
||||
max_hdr_len = 512
|
||||
|
||||
parser = argparse.ArgumentParser(description='Run HTTPD Test')
|
||||
parser.add_argument('-4','--ipv4', help='IPv4 address')
|
||||
parser.add_argument('-6','--ipv6', help='IPv6 address')
|
||||
parser.add_argument('-p','--port', help='Port')
|
||||
args = vars(parser.parse_args())
|
||||
|
||||
dut4 = args['ipv4']
|
||||
dut6 = args['ipv6']
|
||||
port = args['port']
|
||||
dut = dut4
|
||||
|
||||
_verbose_ = True
|
||||
|
||||
print "### Basic HTTP Client Tests"
|
||||
get_hello(dut, port)
|
||||
post_hello(dut, port)
|
||||
put_hello(dut, port)
|
||||
post_echo(dut, port)
|
||||
get_echo(dut, port)
|
||||
put_echo(dut, port)
|
||||
get_hello_type(dut, port)
|
||||
get_hello_status(dut, port)
|
||||
get_false_uri(dut, port)
|
||||
|
||||
print "### Error code tests"
|
||||
code_500_server_error_test(dut, port)
|
||||
code_501_method_not_impl(dut, port)
|
||||
code_505_version_not_supported(dut, port)
|
||||
code_400_bad_request(dut, port)
|
||||
code_404_not_found(dut, port)
|
||||
code_405_method_not_allowed(dut, port)
|
||||
code_408_req_timeout(dut, port)
|
||||
code_414_uri_too_long(dut, port, max_uri_len)
|
||||
code_431_hdr_too_long(dut, port, max_hdr_len)
|
||||
test_upgrade_not_supported(dut, port)
|
||||
|
||||
# Not supported yet (Error on chunked request)
|
||||
###code_411_length_required(dut, port)
|
||||
|
||||
print "### Sessions and Context Tests"
|
||||
parallel_sessions_adder(dut, port, max_sessions)
|
||||
leftover_data_test(dut, port)
|
||||
async_response_test(dut, port)
|
||||
spillover_session(dut, port, max_sessions)
|
||||
recv_timeout_test(dut, port)
|
||||
|
||||
# May timeout in case requests are sent slower than responses are read.
|
||||
# Instead use httperf stress test
|
||||
pipeline_test(dut, port, max_sessions)
|
||||
packet_size_limit_test(dut, port, 50*1024)
|
||||
get_hello(dut, port)
|
||||
|
||||
sys.exit()
|
||||
@@ -0,0 +1,9 @@
|
||||
#
|
||||
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
|
||||
# project subdirectory.
|
||||
#
|
||||
|
||||
PROJECT_NAME := persistent_sockets
|
||||
|
||||
include $(IDF_PATH)/make/project.mk
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
# HTTPD Server Persistant Sockets Example
|
||||
|
||||
The Example consists of HTTPD server persistent sockets demo.
|
||||
This sort of persistancy enables the server to have independent sessions/contexts per client.
|
||||
|
||||
* Configure the project using "make menuconfig" and goto :
|
||||
* Example Configuration ->
|
||||
1. WIFI SSID: WIFI network to which your PC is also connected to.
|
||||
2. WIFI Password: WIFI password
|
||||
|
||||
* In order to test the HTTPD server persistent sockets demo :
|
||||
1. compile and burn the firmware "make flash"
|
||||
2. run "make monitor" and note down the IP assigned to your ESP module. The default port is 80
|
||||
3. run the test script "python2 scripts/adder.py \<IP\> \<port\> \<N\>"
|
||||
* the provided test script sends (POST) numbers from 1 to N to the server which has a URI POST handler for adding these numbers into an accumulator that is valid throughout the lifetime of the connection socket, hence persistent
|
||||
* the script does a GET before closing and displays the final value of the accumulator
|
||||
|
||||
See the README.md file in the upper level 'examples' directory for more information about examples.
|
||||
@@ -0,0 +1,132 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2018 Espressif Systems (Shanghai) PTE LTD
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import imp
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
import string
|
||||
import random
|
||||
import socket
|
||||
|
||||
# This environment variable is expected on the host machine
|
||||
test_fw_path = os.getenv("TEST_FW_PATH")
|
||||
if test_fw_path and test_fw_path not in sys.path:
|
||||
sys.path.insert(0, test_fw_path)
|
||||
|
||||
# When running on local machine execute the following before running this script
|
||||
# > export TEST_FW_PATH='~/esp/esp-idf/tools/tiny-test-fw'
|
||||
# > make print_flash_cmd | tail -n 1 > build/download.config
|
||||
# > make app bootloader
|
||||
|
||||
import TinyFW
|
||||
import IDF
|
||||
|
||||
# Import client module
|
||||
expath = os.path.dirname(os.path.realpath(__file__))
|
||||
client = imp.load_source("client", expath + "/scripts/adder.py")
|
||||
|
||||
@IDF.idf_example_test(env_tag="Example_WIFI")
|
||||
def test_examples_protocol_http_server_persistence(env, extra_data):
|
||||
# Acquire DUT
|
||||
dut1 = env.get_dut("http_server", "examples/protocols/http_server/persistent_sockets")
|
||||
|
||||
# Get binary file
|
||||
binary_file = os.path.join(dut1.app.binary_path, "persistent_sockets.bin")
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
IDF.log_performance("http_server_bin_size", "{}KB".format(bin_size//1024))
|
||||
IDF.check_performance("http_server_bin_size", bin_size//1024)
|
||||
|
||||
# Upload binary and start testing
|
||||
dut1.start_app()
|
||||
|
||||
# Parse IP address of STA
|
||||
got_ip = dut1.expect(re.compile(r"(?:[\s\S]*)Got IP: (\d+.\d+.\d+.\d+)"), timeout=30)[0]
|
||||
got_port = dut1.expect(re.compile(r"(?:[\s\S]*)Starting server on port: (\d+)"))[0]
|
||||
|
||||
print "Got IP : " + got_ip
|
||||
print "Got Port : " + got_port
|
||||
|
||||
# Expected Logs
|
||||
dut1.expect("Registering URI handlers")
|
||||
|
||||
# Run test script
|
||||
conn = client.start_session(got_ip, got_port)
|
||||
visitor = 0
|
||||
adder = 0
|
||||
|
||||
# Test PUT request and initialize session context
|
||||
num = random.randint(0,100)
|
||||
client.putreq(conn, "/adder", str(num))
|
||||
visitor += 1
|
||||
dut1.expect("/adder visitor count = " + str(visitor))
|
||||
dut1.expect("/adder PUT handler read " + str(num))
|
||||
dut1.expect("PUT allocating new session")
|
||||
|
||||
# Retest PUT request and change session context value
|
||||
num = random.randint(0,100)
|
||||
print "Adding :", num
|
||||
client.putreq(conn, "/adder", str(num))
|
||||
visitor += 1
|
||||
adder += num
|
||||
dut1.expect("/adder visitor count = " + str(visitor))
|
||||
dut1.expect("/adder PUT handler read " + str(num))
|
||||
try:
|
||||
# Re allocation shouldn't happen
|
||||
dut1.expect("PUT allocating new session")
|
||||
# Not expected
|
||||
raise RuntimeError
|
||||
except:
|
||||
# As expected
|
||||
pass
|
||||
|
||||
# Test POST request and session persistence
|
||||
random_nums = [random.randint(0,100) for _ in range(100)]
|
||||
for num in random_nums:
|
||||
print "Adding :", num
|
||||
client.postreq(conn, "/adder", str(num))
|
||||
visitor += 1
|
||||
adder += num
|
||||
dut1.expect("/adder visitor count = " + str(visitor))
|
||||
dut1.expect("/adder handler read " + str(num))
|
||||
|
||||
# Test GET request and session persistence
|
||||
print "Matching final sum :", adder
|
||||
if client.getreq(conn, "/adder") != str(adder):
|
||||
raise RuntimeError
|
||||
visitor += 1
|
||||
dut1.expect("/adder visitor count = " + str(visitor))
|
||||
dut1.expect("/adder GET handler send " + str(adder))
|
||||
|
||||
print "Ending session"
|
||||
# Close connection and check for invocation of context "Free" function
|
||||
client.end_session(conn)
|
||||
dut1.expect("/adder Free Context function called")
|
||||
|
||||
print "Validating user context data"
|
||||
# Start another session to check user context data
|
||||
conn2 = client.start_session(got_ip, got_port)
|
||||
num = random.randint(0,100)
|
||||
client.putreq(conn, "/adder", str(num))
|
||||
visitor += 1
|
||||
dut1.expect("/adder visitor count = " + str(visitor))
|
||||
dut1.expect("/adder PUT handler read " + str(num))
|
||||
dut1.expect("PUT allocating new session")
|
||||
client.end_session(conn)
|
||||
dut1.expect("/adder Free Context function called")
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_examples_protocol_http_server_persistence()
|
||||
@@ -0,0 +1,16 @@
|
||||
menu "Example Configuration"
|
||||
|
||||
config WIFI_SSID
|
||||
string "WiFi SSID"
|
||||
default "myssid"
|
||||
help
|
||||
SSID (network name) for the example to connect to.
|
||||
|
||||
config WIFI_PASSWORD
|
||||
string "WiFi Password"
|
||||
default "mypassword"
|
||||
help
|
||||
WiFi password (WPA or WPA2) for the example to use.
|
||||
Can be left blank if the network has no security set.
|
||||
|
||||
endmenu
|
||||
@@ -0,0 +1,5 @@
|
||||
#
|
||||
# "main" pseudo-component makefile.
|
||||
#
|
||||
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)
|
||||
|
||||
@@ -0,0 +1,246 @@
|
||||
/* Persistent Sockets Example
|
||||
|
||||
This example code is in the Public Domain (or CC0 licensed, at your option.)
|
||||
|
||||
Unless required by applicable law or agreed to in writing, this
|
||||
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
CONDITIONS OF ANY KIND, either express or implied.
|
||||
*/
|
||||
|
||||
#include <esp_wifi.h>
|
||||
#include <esp_event_loop.h>
|
||||
#include <esp_log.h>
|
||||
#include <esp_system.h>
|
||||
#include <nvs_flash.h>
|
||||
|
||||
#include <http_server.h>
|
||||
|
||||
/* An example to demonstrate persistent sockets, with context maintained across
|
||||
* multiple requests on that socket.
|
||||
* The examples use simple WiFi configuration that you can set via 'make menuconfig'.
|
||||
* If you'd rather not, just change the below entries to strings with
|
||||
* the config you want - ie #define EXAMPLE_WIFI_SSID "mywifissid"
|
||||
*/
|
||||
#define EXAMPLE_WIFI_SSID CONFIG_WIFI_SSID
|
||||
#define EXAMPLE_WIFI_PASS CONFIG_WIFI_PASSWORD
|
||||
|
||||
static const char *TAG="APP";
|
||||
|
||||
/* Function to free context */
|
||||
void adder_free_func(void *ctx)
|
||||
{
|
||||
ESP_LOGI(TAG, "/adder Free Context function called");
|
||||
free(ctx);
|
||||
}
|
||||
|
||||
/* This handler keeps accumulating data that is posted to it into a per
|
||||
* socket/session context. And returns the result.
|
||||
*/
|
||||
esp_err_t adder_post_handler(httpd_req_t *req)
|
||||
{
|
||||
/* Log total visitors */
|
||||
unsigned *visitors = (unsigned *)req->user_ctx;
|
||||
ESP_LOGI(TAG, "/adder visitor count = %d", ++(*visitors));
|
||||
|
||||
char buf[10];
|
||||
char outbuf[50];
|
||||
int ret;
|
||||
|
||||
/* Read data received in the request */
|
||||
ret = httpd_req_recv(req, buf, sizeof(buf));
|
||||
if (ret < 0) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
buf[ret] = '\0';
|
||||
int val = atoi(buf);
|
||||
ESP_LOGI(TAG, "/adder handler read %d", val);
|
||||
|
||||
/* Create session's context if not already available */
|
||||
if (! req->sess_ctx) {
|
||||
ESP_LOGI(TAG, "/adder allocating new session");
|
||||
req->sess_ctx = malloc(sizeof(int));
|
||||
req->free_ctx = adder_free_func;
|
||||
*(int *)req->sess_ctx = 0;
|
||||
}
|
||||
|
||||
/* Add the received data to the context */
|
||||
int *adder = (int *)req->sess_ctx;
|
||||
*adder += val;
|
||||
|
||||
/* Respond with the accumulated value */
|
||||
snprintf(outbuf, sizeof(outbuf),"%d", *adder);
|
||||
httpd_resp_send(req, outbuf, strlen(outbuf));
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
/* This handler gets the present value of the accumulator */
|
||||
esp_err_t adder_get_handler(httpd_req_t *req)
|
||||
{
|
||||
/* Log total visitors */
|
||||
unsigned *visitors = (unsigned *)req->user_ctx;
|
||||
ESP_LOGI(TAG, "/adder visitor count = %d", ++(*visitors));
|
||||
|
||||
char outbuf[50];
|
||||
|
||||
/* Create session's context if not already available */
|
||||
if (! req->sess_ctx) {
|
||||
ESP_LOGI(TAG, "/adder GET allocating new session");
|
||||
req->sess_ctx = malloc(sizeof(int));
|
||||
req->free_ctx = adder_free_func;
|
||||
*(int *)req->sess_ctx = 0;
|
||||
}
|
||||
ESP_LOGI(TAG, "/adder GET handler send %d", *(int *)req->sess_ctx);
|
||||
|
||||
/* Respond with the accumulated value */
|
||||
snprintf(outbuf, sizeof(outbuf),"%d", *((int *)req->sess_ctx));
|
||||
httpd_resp_send(req, outbuf, strlen(outbuf));
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
/* This handler resets the value of the accumulator */
|
||||
esp_err_t adder_put_handler(httpd_req_t *req)
|
||||
{
|
||||
/* Log total visitors */
|
||||
unsigned *visitors = (unsigned *)req->user_ctx;
|
||||
ESP_LOGI(TAG, "/adder visitor count = %d", ++(*visitors));
|
||||
|
||||
char buf[10];
|
||||
char outbuf[50];
|
||||
int ret;
|
||||
|
||||
/* Read data received in the request */
|
||||
ret = httpd_req_recv(req, buf, sizeof(buf));
|
||||
if (ret < 0) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
buf[ret] = '\0';
|
||||
int val = atoi(buf);
|
||||
ESP_LOGI(TAG, "/adder PUT handler read %d", val);
|
||||
|
||||
/* Create session's context if not already available */
|
||||
if (! req->sess_ctx) {
|
||||
ESP_LOGI(TAG, "/adder PUT allocating new session");
|
||||
req->sess_ctx = malloc(sizeof(int));
|
||||
req->free_ctx = adder_free_func;
|
||||
}
|
||||
*(int *)req->sess_ctx = val;
|
||||
|
||||
/* Respond with the reset value */
|
||||
snprintf(outbuf, sizeof(outbuf),"%d", *((int *)req->sess_ctx));
|
||||
httpd_resp_send(req, outbuf, strlen(outbuf));
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
/* Maintain a variable which stores the number of times
|
||||
* the "/adder" URI has been visited */
|
||||
static unsigned visitors = 0;
|
||||
|
||||
httpd_uri_t adder_post = {
|
||||
.uri = "/adder",
|
||||
.method = HTTP_POST,
|
||||
.handler = adder_post_handler,
|
||||
.user_ctx = &visitors
|
||||
};
|
||||
|
||||
httpd_uri_t adder_get = {
|
||||
.uri = "/adder",
|
||||
.method = HTTP_GET,
|
||||
.handler = adder_get_handler,
|
||||
.user_ctx = &visitors
|
||||
};
|
||||
|
||||
httpd_uri_t adder_put = {
|
||||
.uri = "/adder",
|
||||
.method = HTTP_PUT,
|
||||
.handler = adder_put_handler,
|
||||
.user_ctx = &visitors
|
||||
};
|
||||
|
||||
httpd_handle_t start_webserver(void)
|
||||
{
|
||||
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
|
||||
// Start the httpd server
|
||||
ESP_LOGI(TAG, "Starting server on port: %d", config.server_port);
|
||||
httpd_handle_t server;
|
||||
|
||||
if (httpd_start(&server, &config) == ESP_OK) {
|
||||
// Set URI handlers
|
||||
ESP_LOGI(TAG, "Registering URI handlers");
|
||||
httpd_register_uri_handler(server, &adder_get);
|
||||
httpd_register_uri_handler(server, &adder_put);
|
||||
httpd_register_uri_handler(server, &adder_post);
|
||||
return server;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Error starting server!");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void stop_webserver(httpd_handle_t server)
|
||||
{
|
||||
// Stop the httpd server
|
||||
httpd_stop(server);
|
||||
}
|
||||
|
||||
static esp_err_t event_handler(void *ctx, system_event_t *event)
|
||||
{
|
||||
httpd_handle_t *server = (httpd_handle_t *) ctx;
|
||||
|
||||
switch(event->event_id) {
|
||||
case SYSTEM_EVENT_STA_START:
|
||||
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_START");
|
||||
ESP_ERROR_CHECK(esp_wifi_connect());
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_GOT_IP:
|
||||
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_GOT_IP");
|
||||
ESP_LOGI(TAG, "Got IP: %s",
|
||||
ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
|
||||
|
||||
/* Start the web server */
|
||||
if (*server == NULL) {
|
||||
*server = start_webserver();
|
||||
}
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_DISCONNECTED:
|
||||
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_DISCONNECTED");
|
||||
ESP_ERROR_CHECK(esp_wifi_connect());
|
||||
|
||||
/* Stop the webserver */
|
||||
if (*server) {
|
||||
stop_webserver(*server);
|
||||
*server = NULL;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void initialise_wifi(void *arg)
|
||||
{
|
||||
tcpip_adapter_init();
|
||||
ESP_ERROR_CHECK(esp_event_loop_init(event_handler, arg));
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
|
||||
wifi_config_t wifi_config = {
|
||||
.sta = {
|
||||
.ssid = EXAMPLE_WIFI_SSID,
|
||||
.password = EXAMPLE_WIFI_PASS,
|
||||
},
|
||||
};
|
||||
ESP_LOGI(TAG, "Setting WiFi configuration SSID %s...", wifi_config.sta.ssid);
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
|
||||
ESP_ERROR_CHECK(esp_wifi_start());
|
||||
}
|
||||
|
||||
void app_main()
|
||||
{
|
||||
static httpd_handle_t server = NULL;
|
||||
ESP_ERROR_CHECK(nvs_flash_init());
|
||||
initialise_wifi(&server);
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2018 Espressif Systems (Shanghai) PTE LTD
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import httplib
|
||||
import argparse
|
||||
|
||||
def start_session (ip, port):
|
||||
return httplib.HTTPConnection(ip, int(port))
|
||||
|
||||
def end_session (conn):
|
||||
conn.close()
|
||||
|
||||
def getreq (conn, path, verbose = False):
|
||||
conn.request("GET", path)
|
||||
resp = conn.getresponse()
|
||||
data = resp.read()
|
||||
if verbose:
|
||||
print "GET : ", path
|
||||
print "Status : ", resp.status
|
||||
print "Reason : ", resp.reason
|
||||
print "Data length : ", len(data)
|
||||
print "Data content : ", data
|
||||
return data
|
||||
|
||||
def postreq (conn, path, data, verbose = False):
|
||||
conn.request("POST", path, data)
|
||||
resp = conn.getresponse()
|
||||
data = resp.read()
|
||||
if verbose:
|
||||
print "POST : ", data
|
||||
print "Status : ", resp.status
|
||||
print "Reason : ", resp.reason
|
||||
print "Data length : ", len(data)
|
||||
print "Data content : ", data
|
||||
return data
|
||||
|
||||
def putreq (conn, path, body, verbose = False):
|
||||
conn.request("PUT", path, body)
|
||||
resp = conn.getresponse()
|
||||
data = resp.read()
|
||||
if verbose:
|
||||
print "PUT : ", path, body
|
||||
print "Status : ", resp.status
|
||||
print "Reason : ", resp.reason
|
||||
print "Data length : ", len(data)
|
||||
print "Data content : ", data
|
||||
return data
|
||||
|
||||
if __name__ == '__main__':
|
||||
# Configure argument parser
|
||||
parser = argparse.ArgumentParser(description='Run HTTPd Test')
|
||||
parser.add_argument('IP' , metavar='IP' , type=str, help='Server IP')
|
||||
parser.add_argument('port', metavar='port', type=str, help='Server port')
|
||||
parser.add_argument('N' , metavar='integer', type=int, help='Integer to sum upto')
|
||||
args = vars(parser.parse_args())
|
||||
|
||||
# Get arguments
|
||||
ip = args['IP']
|
||||
port = args['port']
|
||||
N = args['N']
|
||||
|
||||
# Establish HTTP connection
|
||||
print "Connecting to => " + ip + ":" + port
|
||||
conn = start_session (ip, port)
|
||||
|
||||
# Reset adder context to specified value(0)
|
||||
# -- Not needed as new connection will always
|
||||
# -- have zero value of the accumulator
|
||||
print "Reset the accumulator to 0"
|
||||
putreq (conn, "/adder", str(0))
|
||||
|
||||
# Sum numbers from 1 to specified value(N)
|
||||
print "Summing numbers from 1 to " + str(N)
|
||||
for i in xrange(1, N+1):
|
||||
postreq (conn, "/adder", str(i))
|
||||
|
||||
# Fetch the result
|
||||
print "Result :", getreq (conn, "/adder")
|
||||
|
||||
# Close HTTP connection
|
||||
end_session (conn)
|
||||
@@ -0,0 +1,9 @@
|
||||
#
|
||||
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
|
||||
# project subdirectory.
|
||||
#
|
||||
|
||||
PROJECT_NAME := simple
|
||||
|
||||
include $(IDF_PATH)/make/project.mk
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# Simple HTTPD Server Example
|
||||
|
||||
The Example consists of HTTPD server demo with demostration of URI handling :
|
||||
1. URI \hello for GET command returns "Hello World!" message
|
||||
2. URI \echo for POST command echoes back the POSTed message
|
||||
|
||||
* Configure the project using "make menuconfig" and goto :
|
||||
* Example Configuration ->
|
||||
1. WIFI SSID: WIFI network to which your PC is also connected to.
|
||||
2. WIFI Password: WIFI password
|
||||
|
||||
* In order to test the HTTPD server persistent sockets demo :
|
||||
1. compile and burn the firmware "make flash"
|
||||
2. run "make monitor" and note down the IP assigned to your ESP module. The default port is 80
|
||||
3. test the example :
|
||||
* run the test script : "python2 scripts/client.py \<IP\> \<port\> \<MSG\>"
|
||||
* the provided test script first does a GET \hello and displays the response
|
||||
* the script does a POST to \echo with the user input \<MSG\> and displays the response
|
||||
* or use curl (asssuming IP is 192.168.43.130):
|
||||
1. "curl 192.168.43.130:80/hello" - tests the GET "\hello" handler
|
||||
2. "curl -X POST --data-binary @anyfile 192.168.43.130:80/echo > tmpfile"
|
||||
* "anyfile" is the file being sent as request body and "tmpfile" is where the body of the response is saved
|
||||
* since the server echoes back the request body, the two files should be same, as can be confirmed using : "cmp anyfile tmpfile"
|
||||
3. "curl -X PUT -d "0" 192.168.43.130:80/ctrl" - disable /hello and /echo handlers
|
||||
4. "curl -X PUT -d "1" 192.168.43.130:80/ctrl" - enable /hello and /echo handlers
|
||||
|
||||
See the README.md file in the upper level 'examples' directory for more information about examples.
|
||||
@@ -0,0 +1,114 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2018 Espressif Systems (Shanghai) PTE LTD
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import imp
|
||||
import re
|
||||
import os
|
||||
import sys
|
||||
import string
|
||||
import random
|
||||
import socket
|
||||
|
||||
# This environment variable is expected on the host machine
|
||||
test_fw_path = os.getenv("TEST_FW_PATH")
|
||||
if test_fw_path and test_fw_path not in sys.path:
|
||||
sys.path.insert(0, test_fw_path)
|
||||
|
||||
# When running on local machine execute the following before running this script
|
||||
# > export TEST_FW_PATH='~/esp/esp-idf/tools/tiny-test-fw'
|
||||
# > make print_flash_cmd | tail -n 1 > build/download.config
|
||||
# > make app bootloader
|
||||
|
||||
import TinyFW
|
||||
import IDF
|
||||
|
||||
# Import client module
|
||||
expath = os.path.dirname(os.path.realpath(__file__))
|
||||
client = imp.load_source("client", expath + "/scripts/client.py")
|
||||
|
||||
@IDF.idf_example_test(env_tag="Example_WIFI", ignore=True)
|
||||
def test_examples_protocol_http_server_simple(env, extra_data):
|
||||
# Acquire DUT
|
||||
dut1 = env.get_dut("http_server", "examples/protocols/http_server/simple")
|
||||
|
||||
# Get binary file
|
||||
binary_file = os.path.join(dut1.app.binary_path, "simple.bin")
|
||||
bin_size = os.path.getsize(binary_file)
|
||||
IDF.log_performance("http_server_bin_size", "{}KB".format(bin_size//1024))
|
||||
IDF.check_performance("http_server_bin_size", bin_size//1024)
|
||||
|
||||
# Upload binary and start testing
|
||||
dut1.start_app()
|
||||
|
||||
# Parse IP address of STA
|
||||
got_ip = dut1.expect(re.compile(r"(?:[\s\S]*)Got IP: (\d+.\d+.\d+.\d+)"), timeout=30)[0]
|
||||
got_port = dut1.expect(re.compile(r"(?:[\s\S]*)Starting server on port: (\d+)"))[0]
|
||||
|
||||
print "Got IP : " + got_ip
|
||||
print "Got Port : " + got_port
|
||||
|
||||
# Expected Logs
|
||||
dut1.expect("Registering URI handlers")
|
||||
|
||||
# Run test script
|
||||
# If failed raise appropriate exception
|
||||
print "Test /hello GET handler"
|
||||
if not client.test_get_handler(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
|
||||
# Acquire host IP. Need a way to check it
|
||||
host_ip = dut1.expect(re.compile(r"(?:[\s\S]*)Found header => Host: (\d+.\d+.\d+.\d+)"))[0]
|
||||
|
||||
# Match additional headers sent in the request
|
||||
dut1.expect("Found header => Test-Header-2: Test-Value-2")
|
||||
dut1.expect("Found header => Test-Header-1: Test-Value-1")
|
||||
dut1.expect("Found URL query parameter => query1=value1")
|
||||
dut1.expect("Found URL query parameter => query3=value3")
|
||||
dut1.expect("Found URL query parameter => query2=value2")
|
||||
dut1.expect("Request headers lost")
|
||||
|
||||
print "Test /ctrl PUT handler and realtime handler de/registration"
|
||||
if not client.test_put_handler(got_ip, got_port):
|
||||
raise RuntimeError
|
||||
dut1.expect("Unregistering /hello and /echo URIs")
|
||||
dut1.expect("Registering /hello and /echo URIs")
|
||||
|
||||
# Generate random data of 10KB
|
||||
random_data = ''.join(string.printable[random.randint(0,len(string.printable))-1] for _ in range(1024*10))
|
||||
print "Test /echo POST handler with random data"
|
||||
if not client.test_post_handler(got_ip, got_port, random_data):
|
||||
raise RuntimeError
|
||||
|
||||
query = "http://foobar"
|
||||
print "Test /hello with custom query : " + query
|
||||
if not client.test_custom_uri_query(got_ip, got_port, query):
|
||||
raise RuntimeError
|
||||
dut1.expect("Found URL query => " + query)
|
||||
|
||||
query = "abcd+1234%20xyz"
|
||||
print "Test /hello with custom query : " + query
|
||||
if not client.test_custom_uri_query(got_ip, got_port, query):
|
||||
raise RuntimeError
|
||||
dut1.expect("Found URL query => " + query)
|
||||
|
||||
query = "abcd\nyz"
|
||||
print "Test /hello with invalid query"
|
||||
if client.test_custom_uri_query(got_ip, got_port, query):
|
||||
raise RuntimeError
|
||||
dut1.expect("400 Bad Request - Server unable to understand request due to invalid syntax")
|
||||
|
||||
if __name__ == '__main__':
|
||||
test_examples_protocol_http_server_simple()
|
||||
@@ -0,0 +1,16 @@
|
||||
menu "Example Configuration"
|
||||
|
||||
config WIFI_SSID
|
||||
string "WiFi SSID"
|
||||
default "myssid"
|
||||
help
|
||||
SSID (network name) for the example to connect to.
|
||||
|
||||
config WIFI_PASSWORD
|
||||
string "WiFi Password"
|
||||
default "mypassword"
|
||||
help
|
||||
WiFi password (WPA or WPA2) for the example to use.
|
||||
Can be left blank if the network has no security set.
|
||||
|
||||
endmenu
|
||||
@@ -0,0 +1,5 @@
|
||||
#
|
||||
# "main" pseudo-component makefile.
|
||||
#
|
||||
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)
|
||||
|
||||
@@ -0,0 +1,272 @@
|
||||
/* Simple HTTP Server Example
|
||||
|
||||
This example code is in the Public Domain (or CC0 licensed, at your option.)
|
||||
|
||||
Unless required by applicable law or agreed to in writing, this
|
||||
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
|
||||
CONDITIONS OF ANY KIND, either express or implied.
|
||||
*/
|
||||
|
||||
#include <esp_wifi.h>
|
||||
#include <esp_event_loop.h>
|
||||
#include <esp_log.h>
|
||||
#include <esp_system.h>
|
||||
#include <nvs_flash.h>
|
||||
#include <sys/param.h>
|
||||
|
||||
#include <http_server.h>
|
||||
|
||||
/* A simple example that demonstrates how to create GET and POST
|
||||
* handlers for the web server.
|
||||
* The examples use simple WiFi configuration that you can set via
|
||||
* 'make menuconfig'.
|
||||
* If you'd rather not, just change the below entries to strings
|
||||
* with the config you want -
|
||||
* ie. #define EXAMPLE_WIFI_SSID "mywifissid"
|
||||
*/
|
||||
#define EXAMPLE_WIFI_SSID CONFIG_WIFI_SSID
|
||||
#define EXAMPLE_WIFI_PASS CONFIG_WIFI_PASSWORD
|
||||
|
||||
static const char *TAG="APP";
|
||||
|
||||
/* An HTTP GET handler */
|
||||
esp_err_t hello_get_handler(httpd_req_t *req)
|
||||
{
|
||||
char* buf;
|
||||
size_t buf_len;
|
||||
|
||||
/* Get header value string length and allocate memory for length + 1,
|
||||
* extra byte for null termination */
|
||||
buf_len = httpd_req_get_hdr_value_len(req, "Host") + 1;
|
||||
if (buf_len > 1) {
|
||||
buf = malloc(buf_len);
|
||||
/* Copy null terminated value string into buffer */
|
||||
if (httpd_req_get_hdr_value_str(req, "Host", buf, buf_len) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Found header => Host: %s", buf);
|
||||
}
|
||||
free(buf);
|
||||
}
|
||||
|
||||
buf_len = httpd_req_get_hdr_value_len(req, "Test-Header-2") + 1;
|
||||
if (buf_len > 1) {
|
||||
buf = malloc(buf_len);
|
||||
if (httpd_req_get_hdr_value_str(req, "Test-Header-2", buf, buf_len) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Found header => Test-Header-2: %s", buf);
|
||||
}
|
||||
free(buf);
|
||||
}
|
||||
|
||||
buf_len = httpd_req_get_hdr_value_len(req, "Test-Header-1") + 1;
|
||||
if (buf_len > 1) {
|
||||
buf = malloc(buf_len);
|
||||
if (httpd_req_get_hdr_value_str(req, "Test-Header-1", buf, buf_len) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Found header => Test-Header-1: %s", buf);
|
||||
}
|
||||
free(buf);
|
||||
}
|
||||
|
||||
/* Read URL query string length and allocate memory for length + 1,
|
||||
* extra byte for null termination */
|
||||
buf_len = httpd_req_get_url_query_len(req) + 1;
|
||||
if (buf_len > 1) {
|
||||
buf = malloc(buf_len);
|
||||
if (httpd_req_get_url_query_str(req, buf, buf_len) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Found URL query => %s", buf);
|
||||
char param[32];
|
||||
/* Get value of expected key from query string */
|
||||
if (httpd_query_key_value(buf, "query1", param, sizeof(param)) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Found URL query parameter => query1=%s", param);
|
||||
}
|
||||
if (httpd_query_key_value(buf, "query3", param, sizeof(param)) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Found URL query parameter => query3=%s", param);
|
||||
}
|
||||
if (httpd_query_key_value(buf, "query2", param, sizeof(param)) == ESP_OK) {
|
||||
ESP_LOGI(TAG, "Found URL query parameter => query2=%s", param);
|
||||
}
|
||||
}
|
||||
free(buf);
|
||||
}
|
||||
|
||||
/* Set some custom headers */
|
||||
httpd_resp_set_hdr(req, "Custom-Header-1", "Custom-Value-1");
|
||||
httpd_resp_set_hdr(req, "Custom-Header-2", "Custom-Value-2");
|
||||
|
||||
/* Send response with custom headers and body set as the
|
||||
* string passed in user context*/
|
||||
const char* resp_str = (const char*) req->user_ctx;
|
||||
httpd_resp_send(req, resp_str, strlen(resp_str));
|
||||
|
||||
/* After sending the HTTP response the old HTTP request
|
||||
* headers are lost. Check if HTTP request headers can be read now. */
|
||||
if (httpd_req_get_hdr_value_len(req, "Host") == 0) {
|
||||
ESP_LOGI(TAG, "Request headers lost");
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
httpd_uri_t hello = {
|
||||
.uri = "/hello",
|
||||
.method = HTTP_GET,
|
||||
.handler = hello_get_handler,
|
||||
/* Let's pass response string in user
|
||||
* context to demonstrate it's usage */
|
||||
.user_ctx = "Hello World!"
|
||||
};
|
||||
|
||||
/* An HTTP POST handler */
|
||||
esp_err_t echo_post_handler(httpd_req_t *req)
|
||||
{
|
||||
char buf[100];
|
||||
int ret, remaining = req->content_len;
|
||||
|
||||
while (remaining > 0) {
|
||||
/* Read the data for the request */
|
||||
if ((ret = httpd_req_recv(req, buf,
|
||||
MIN(remaining, sizeof(buf)))) < 0) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
/* Send back the same data */
|
||||
httpd_resp_send_chunk(req, buf, ret);
|
||||
remaining -= ret;
|
||||
|
||||
/* Log data received */
|
||||
ESP_LOGI(TAG, "=========== RECEIVED DATA ==========");
|
||||
ESP_LOGI(TAG, "%.*s", ret, buf);
|
||||
ESP_LOGI(TAG, "====================================");
|
||||
}
|
||||
|
||||
// End response
|
||||
httpd_resp_send_chunk(req, NULL, 0);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
httpd_uri_t echo = {
|
||||
.uri = "/echo",
|
||||
.method = HTTP_POST,
|
||||
.handler = echo_post_handler,
|
||||
.user_ctx = NULL
|
||||
};
|
||||
|
||||
/* An HTTP PUT handler. This demonstrates realtime
|
||||
* registration and deregistration of URI handlers
|
||||
*/
|
||||
esp_err_t ctrl_put_handler(httpd_req_t *req)
|
||||
{
|
||||
char buf;
|
||||
int ret;
|
||||
|
||||
if ((ret = httpd_req_recv(req, &buf, 1)) < 0) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
if (buf == '0') {
|
||||
/* Handler can be unregistered using the uri string */
|
||||
ESP_LOGI(TAG, "Unregistering /hello and /echo URIs");
|
||||
httpd_unregister_uri(req->handle, "/hello");
|
||||
httpd_unregister_uri(req->handle, "/echo");
|
||||
}
|
||||
else {
|
||||
ESP_LOGI(TAG, "Registering /hello and /echo URIs");
|
||||
httpd_register_uri_handler(req->handle, &hello);
|
||||
httpd_register_uri_handler(req->handle, &echo);
|
||||
}
|
||||
|
||||
/* Respond with empty body */
|
||||
httpd_resp_send(req, NULL, 0);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
httpd_uri_t ctrl = {
|
||||
.uri = "/ctrl",
|
||||
.method = HTTP_PUT,
|
||||
.handler = ctrl_put_handler,
|
||||
.user_ctx = NULL
|
||||
};
|
||||
|
||||
httpd_handle_t start_webserver(void)
|
||||
{
|
||||
httpd_handle_t server = NULL;
|
||||
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
|
||||
|
||||
// Start the httpd server
|
||||
ESP_LOGI(TAG, "Starting server on port: %d", config.server_port);
|
||||
if (httpd_start(&server, &config) == ESP_OK) {
|
||||
// Set URI handlers
|
||||
ESP_LOGI(TAG, "Registering URI handlers");
|
||||
httpd_register_uri_handler(server, &hello);
|
||||
httpd_register_uri_handler(server, &echo);
|
||||
httpd_register_uri_handler(server, &ctrl);
|
||||
return server;
|
||||
}
|
||||
|
||||
ESP_LOGI(TAG, "Error starting server!");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
void stop_webserver(httpd_handle_t server)
|
||||
{
|
||||
// Stop the httpd server
|
||||
httpd_stop(server);
|
||||
}
|
||||
|
||||
static esp_err_t event_handler(void *ctx, system_event_t *event)
|
||||
{
|
||||
httpd_handle_t *server = (httpd_handle_t *) ctx;
|
||||
|
||||
switch(event->event_id) {
|
||||
case SYSTEM_EVENT_STA_START:
|
||||
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_START");
|
||||
ESP_ERROR_CHECK(esp_wifi_connect());
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_GOT_IP:
|
||||
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_GOT_IP");
|
||||
ESP_LOGI(TAG, "Got IP: %s",
|
||||
ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
|
||||
|
||||
/* Start the web server */
|
||||
if (*server == NULL) {
|
||||
*server = start_webserver();
|
||||
}
|
||||
break;
|
||||
case SYSTEM_EVENT_STA_DISCONNECTED:
|
||||
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_DISCONNECTED");
|
||||
ESP_ERROR_CHECK(esp_wifi_connect());
|
||||
|
||||
/* Stop the web server */
|
||||
if (*server) {
|
||||
stop_webserver(*server);
|
||||
*server = NULL;
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static void initialise_wifi(void *arg)
|
||||
{
|
||||
tcpip_adapter_init();
|
||||
ESP_ERROR_CHECK(esp_event_loop_init(event_handler, arg));
|
||||
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
|
||||
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
|
||||
wifi_config_t wifi_config = {
|
||||
.sta = {
|
||||
.ssid = EXAMPLE_WIFI_SSID,
|
||||
.password = EXAMPLE_WIFI_PASS,
|
||||
},
|
||||
};
|
||||
ESP_LOGI(TAG, "Setting WiFi configuration SSID %s...", wifi_config.sta.ssid);
|
||||
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
|
||||
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
|
||||
ESP_ERROR_CHECK(esp_wifi_start());
|
||||
}
|
||||
|
||||
void app_main()
|
||||
{
|
||||
static httpd_handle_t server = NULL;
|
||||
ESP_ERROR_CHECK(nvs_flash_init());
|
||||
initialise_wifi(&server);
|
||||
}
|
||||
@@ -0,0 +1,258 @@
|
||||
#!/usr/bin/env python
|
||||
#
|
||||
# Copyright 2018 Espressif Systems (Shanghai) PTE LTD
|
||||
#
|
||||
# Licensed under the Apache License, Version 2.0 (the "License");
|
||||
# you may not use this file except in compliance with the License.
|
||||
# You may obtain a copy of the License at
|
||||
#
|
||||
# http://www.apache.org/licenses/LICENSE-2.0
|
||||
#
|
||||
# Unless required by applicable law or agreed to in writing, software
|
||||
# distributed under the License is distributed on an "AS IS" BASIS,
|
||||
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
# See the License for the specific language governing permissions and
|
||||
# limitations under the License.
|
||||
|
||||
import socket
|
||||
import argparse
|
||||
|
||||
class Session:
|
||||
def __init__(self, addr, port):
|
||||
self.client = socket.create_connection((addr, int(port)))
|
||||
self.target = addr
|
||||
|
||||
def send_get(self, path, headers=None):
|
||||
request = "GET " + path + " HTTP/1.1\r\nHost: " + self.target
|
||||
if headers:
|
||||
for field, value in headers.iteritems():
|
||||
request += "\r\n"+field+": "+value
|
||||
request += "\r\n\r\n"
|
||||
self.client.send(request);
|
||||
|
||||
def send_put(self, path, data, headers=None):
|
||||
request = "PUT " + path + " HTTP/1.1\r\nHost: " + self.target
|
||||
if headers:
|
||||
for field, value in headers.iteritems():
|
||||
request += "\r\n"+field+": "+value
|
||||
request += "\r\nContent-Length: " + str(len(data)) +"\r\n\r\n"
|
||||
self.client.send(request)
|
||||
self.client.send(data)
|
||||
|
||||
def send_post(self, path, data, headers=None):
|
||||
request = "POST " + path + " HTTP/1.1\r\nHost: " + self.target
|
||||
if headers:
|
||||
for field, value in headers.iteritems():
|
||||
request += "\r\n"+field+": "+value
|
||||
request += "\r\nContent-Length: " + str(len(data)) +"\r\n\r\n"
|
||||
self.client.send(request)
|
||||
self.client.send(data)
|
||||
|
||||
def read_resp_hdrs(self):
|
||||
state = 'nothing'
|
||||
resp_read = ''
|
||||
while True:
|
||||
char = self.client.recv(1)
|
||||
if char == '\r' and state == 'nothing':
|
||||
state = 'first_cr'
|
||||
elif char == '\n' and state == 'first_cr':
|
||||
state = 'first_lf'
|
||||
elif char == '\r' and state == 'first_lf':
|
||||
state = 'second_cr'
|
||||
elif char == '\n' and state == 'second_cr':
|
||||
state = 'second_lf'
|
||||
else:
|
||||
state = 'nothing'
|
||||
resp_read += char
|
||||
if state == 'second_lf':
|
||||
break;
|
||||
# Handle first line
|
||||
line_hdrs = resp_read.splitlines()
|
||||
line_comp = line_hdrs[0].split()
|
||||
self.status = line_comp[1]
|
||||
del line_hdrs[0]
|
||||
self.encoding = ''
|
||||
self.content_type = ''
|
||||
headers = dict()
|
||||
# Process other headers
|
||||
for h in range(len(line_hdrs)):
|
||||
line_comp = line_hdrs[h].split(':')
|
||||
if line_comp[0] == 'Content-Length':
|
||||
self.content_len = int(line_comp[1])
|
||||
if line_comp[0] == 'Content-Type':
|
||||
self.content_type = line_comp[1].lstrip()
|
||||
if line_comp[0] == 'Transfer-Encoding':
|
||||
self.encoding = line_comp[1].lstrip()
|
||||
if len(line_comp) == 2:
|
||||
headers[line_comp[0]] = line_comp[1].lstrip()
|
||||
return headers
|
||||
|
||||
def read_resp_data(self):
|
||||
read_data = ''
|
||||
if self.encoding != 'chunked':
|
||||
while len(read_data) != self.content_len:
|
||||
read_data += self.client.recv(self.content_len)
|
||||
self.content_len = 0
|
||||
else:
|
||||
chunk_data_buf = ''
|
||||
while (True):
|
||||
# Read one character into temp buffer
|
||||
read_ch = self.client.recv(1)
|
||||
# Check CRLF
|
||||
if (read_ch == '\r'):
|
||||
read_ch = self.client.recv(1)
|
||||
if (read_ch == '\n'):
|
||||
# If CRLF decode length of chunk
|
||||
chunk_len = int(chunk_data_buf, 16)
|
||||
# Keep adding to contents
|
||||
self.content_len += chunk_len
|
||||
read_data += self.client.recv(chunk_len)
|
||||
chunk_data_buf = ''
|
||||
# Fetch remaining CRLF
|
||||
if self.client.recv(2) != "\r\n":
|
||||
# Error in packet
|
||||
return None
|
||||
if not chunk_len:
|
||||
# If last chunk
|
||||
break
|
||||
continue
|
||||
chunk_data_buf += '\r'
|
||||
# If not CRLF continue appending
|
||||
# character to chunked data buffer
|
||||
chunk_data_buf += read_ch
|
||||
return read_data
|
||||
|
||||
def close(self):
|
||||
self.client.close()
|
||||
|
||||
def verbose_print(verbosity, *args):
|
||||
if (verbosity):
|
||||
print ''.join(str(elems) for elems in args)
|
||||
|
||||
def test_get_handler(ip, port, verbosity = False):
|
||||
verbose_print(verbosity, "======== GET HANDLER TEST =============")
|
||||
# Establish HTTP connection
|
||||
verbose_print(verbosity, "Connecting to => " + ip + ":" + port)
|
||||
sess = Session(ip, port)
|
||||
|
||||
uri = "/hello?query1=value1&query2=value2&query3=value3"
|
||||
# GET hello response
|
||||
test_headers = {"Test-Header-1":"Test-Value-1", "Test-Header-2":"Test-Value-2"}
|
||||
verbose_print(verbosity, "Sending GET to URI : ", uri)
|
||||
verbose_print(verbosity, "Sending additional headers : ")
|
||||
for k, v in test_headers.iteritems():
|
||||
verbose_print(verbosity, "\t", k, ": ", v)
|
||||
sess.send_get(uri, test_headers)
|
||||
resp_hdrs = sess.read_resp_hdrs()
|
||||
resp_data = sess.read_resp_data()
|
||||
try:
|
||||
if resp_hdrs["Custom-Header-1"] != "Custom-Value-1":
|
||||
return False
|
||||
if resp_hdrs["Custom-Header-2"] != "Custom-Value-2":
|
||||
return False
|
||||
except:
|
||||
return False
|
||||
|
||||
verbose_print(verbosity, "vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv")
|
||||
verbose_print(verbosity, "Server response to GET /hello")
|
||||
verbose_print(verbosity, "Response Headers : ")
|
||||
for k, v in resp_hdrs.iteritems():
|
||||
verbose_print(verbosity, "\t", k, ": ", v)
|
||||
verbose_print(verbosity, "Response Data : " + resp_data)
|
||||
verbose_print(verbosity, "========================================\n")
|
||||
|
||||
# Close HTTP connection
|
||||
sess.close()
|
||||
return (resp_data == "Hello World!")
|
||||
|
||||
def test_post_handler(ip, port, msg, verbosity = False):
|
||||
verbose_print(verbosity, "======== POST HANDLER TEST ============")
|
||||
# Establish HTTP connection
|
||||
verbose_print(verbosity, "Connecting to => " + ip + ":" + port)
|
||||
sess = Session(ip, port)
|
||||
|
||||
# POST message to /echo and get back response
|
||||
sess.send_post("/echo", msg)
|
||||
resp_hdrs = sess.read_resp_hdrs()
|
||||
resp_data = sess.read_resp_data()
|
||||
verbose_print(verbosity, "Server response to POST /echo (" + msg + ")")
|
||||
verbose_print(verbosity, "vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv")
|
||||
verbose_print(verbosity, resp_data)
|
||||
verbose_print(verbosity, "========================================\n")
|
||||
|
||||
# Close HTTP connection
|
||||
sess.close()
|
||||
return (resp_data == msg)
|
||||
|
||||
def test_put_handler(ip, port, verbosity = False):
|
||||
verbose_print(verbosity, "======== PUT HANDLER TEST =============")
|
||||
# Establish HTTP connection
|
||||
verbose_print(verbosity, "Connecting to => " + ip + ":" + port)
|
||||
sess = Session(ip, port)
|
||||
|
||||
# PUT message to /ctrl to disable /hello URI handler
|
||||
verbose_print(verbosity, "Disabling /hello handler")
|
||||
sess.send_put("/ctrl", "0")
|
||||
sess.read_resp_hdrs()
|
||||
if sess.content_len:
|
||||
sess.read_resp_data()
|
||||
|
||||
sess.send_get("/hello")
|
||||
sess.read_resp_hdrs()
|
||||
resp_data1 = sess.read_resp_data()
|
||||
verbose_print(verbosity, "Response on GET /hello : " + resp_data1)
|
||||
|
||||
# PUT message to /ctrl to enable /hello URI handler
|
||||
verbose_print(verbosity, "Enabling /hello handler")
|
||||
sess.send_put("/ctrl", "1")
|
||||
sess.read_resp_hdrs()
|
||||
if sess.content_len:
|
||||
sess.read_resp_data()
|
||||
|
||||
sess.send_get("/hello")
|
||||
sess.read_resp_hdrs()
|
||||
resp_data2 = sess.read_resp_data()
|
||||
verbose_print(verbosity, "Response on GET /hello : " + resp_data2)
|
||||
|
||||
# Close HTTP connection
|
||||
sess.close()
|
||||
return ((resp_data2 == "Hello World!") and (resp_data1 == "This URI doesn't exist"))
|
||||
|
||||
def test_custom_uri_query(ip, port, query, verbosity = False):
|
||||
verbose_print(verbosity, "======== GET HANDLER TEST =============")
|
||||
# Establish HTTP connection
|
||||
verbose_print(verbosity, "Connecting to => " + ip + ":" + port)
|
||||
sess = Session(ip, port)
|
||||
|
||||
uri = "/hello?" + query
|
||||
# GET hello response
|
||||
verbose_print(verbosity, "Sending GET to URI : ", uri)
|
||||
sess.send_get(uri, {})
|
||||
resp_hdrs = sess.read_resp_hdrs()
|
||||
resp_data = sess.read_resp_data()
|
||||
|
||||
verbose_print(verbosity, "vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv")
|
||||
verbose_print(verbosity, "Server response to GET /hello")
|
||||
verbose_print(verbosity, "Response Data : " + resp_data)
|
||||
verbose_print(verbosity, "========================================\n")
|
||||
|
||||
# Close HTTP connection
|
||||
sess.close()
|
||||
return (resp_data == "Hello World!")
|
||||
|
||||
if __name__ == '__main__':
|
||||
# Configure argument parser
|
||||
parser = argparse.ArgumentParser(description='Run HTTPd Test')
|
||||
parser.add_argument('IP' , metavar='IP' , type=str, help='Server IP')
|
||||
parser.add_argument('port', metavar='port', type=str, help='Server port')
|
||||
parser.add_argument('msg', metavar='message', type=str, help='Message to be sent to server')
|
||||
args = vars(parser.parse_args())
|
||||
|
||||
# Get arguments
|
||||
ip = args['IP']
|
||||
port = args['port']
|
||||
msg = args['msg']
|
||||
|
||||
test_get_handler (ip, port, True)
|
||||
test_post_handler(ip, port, msg, True)
|
||||
test_put_handler (ip, port, True)
|
||||
@@ -14,7 +14,7 @@ import TinyFW
|
||||
import IDF
|
||||
|
||||
|
||||
@IDF.idf_example_test(env_tag="Example_WIFI")
|
||||
@IDF.idf_example_test(env_tag="Example_WIFI", ignore=True)
|
||||
def test_examples_protocol_https_request(env, extra_data):
|
||||
"""
|
||||
steps: |
|
||||
|
||||
@@ -58,7 +58,7 @@ config EXAMPLE_MULTICAST_IPV6_ADDR
|
||||
config EXAMPLE_PORT
|
||||
int "Multicast port (send & receive)"
|
||||
range 0 65535
|
||||
default 333
|
||||
default 3333
|
||||
help
|
||||
Multicast port the example will both send & receive UDP packets on.
|
||||
|
||||
|
||||
@@ -499,13 +499,14 @@ static void mcast_example_task(void *pvParameters)
|
||||
#ifdef CONFIG_EXAMPLE_IPV4_ONLY
|
||||
((struct sockaddr_in *)res->ai_addr)->sin_port = htons(UDP_PORT);
|
||||
inet_ntoa_r(((struct sockaddr_in *)res->ai_addr)->sin_addr, addrbuf, sizeof(addrbuf)-1);
|
||||
ESP_LOGI(TAG, "Sending to IPV4 multicast address %s...", addrbuf);
|
||||
ESP_LOGI(TAG, "Sending to IPV4 multicast address %s:%d...", addrbuf, UDP_PORT);
|
||||
#else
|
||||
((struct sockaddr_in6 *)res->ai_addr)->sin6_port = htons(UDP_PORT);
|
||||
inet6_ntoa_r(((struct sockaddr_in6 *)res->ai_addr)->sin6_addr, addrbuf, sizeof(addrbuf)-1);
|
||||
ESP_LOGI(TAG, "Sending to IPV6 (V4 mapped) multicast address %s (%s)...", addrbuf, CONFIG_EXAMPLE_MULTICAST_IPV4_ADDR);
|
||||
ESP_LOGI(TAG, "Sending to IPV6 (V4 mapped) multicast address %s port %d (%s)...", addrbuf, UDP_PORT, CONFIG_EXAMPLE_MULTICAST_IPV4_ADDR);
|
||||
#endif
|
||||
err = sendto(sock, sendbuf, len, 0, res->ai_addr, res->ai_addrlen);
|
||||
freeaddrinfo(res);
|
||||
if (err < 0) {
|
||||
ESP_LOGE(TAG, "IPV4 sendto failed. errno: %d", errno);
|
||||
break;
|
||||
@@ -523,12 +524,12 @@ static void mcast_example_task(void *pvParameters)
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
struct sockaddr_in6 *s6addr = (struct sockaddr_in6 *)res->ai_addr;
|
||||
s6addr->sin6_port = htons(UDP_PORT);
|
||||
inet6_ntoa_r(s6addr->sin6_addr, addrbuf, sizeof(addrbuf)-1);
|
||||
ESP_LOGI(TAG, "Sending to IPV6 multicast address %s...", addrbuf);
|
||||
ESP_LOGI(TAG, "Sending to IPV6 multicast address %s port %d...", addrbuf, UDP_PORT);
|
||||
err = sendto(sock, sendbuf, len, 0, res->ai_addr, res->ai_addrlen);
|
||||
freeaddrinfo(res);
|
||||
if (err < 0) {
|
||||
ESP_LOGE(TAG, "IPV6 sendto failed. errno: %d", errno);
|
||||
break;
|
||||
|
||||
Reference in New Issue
Block a user