Page 14 of 16
Page 354 complete program from fragments
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "nvs_flash.h"
#include "esp_wifi.h"
int retry_num = 0;
static void wifi_event_handler(void *event_handler_arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
switch (event_id)
{
case WIFI_EVENT_STA_START:
printf("WIFI CONNECTING....\n");
break;
case WIFI_EVENT_STA_CONNECTED:
printf("WiFi CONNECTED\n");
break;
case WIFI_EVENT_STA_DISCONNECTED:
printf("WiFi lost connection\n");
if (retry_num < 5)
{
esp_wifi_connect();
retry_num++;
printf("Retrying to Connect...\n");
}
break;
case IP_EVENT_STA_GOT_IP:
printf("Wifi got IP...\n\n");
break;
}
}
void app_main(void)
{
nvs_flash_init();
esp_netif_init();
esp_event_loop_create_default();
esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID,
wifi_event_handler, NULL);
esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP,
wifi_event_handler, NULL);
wifi_init_config_t wificonfig = WIFI_INIT_CONFIG_DEFAULT();
esp_wifi_init(&wificonfig);
esp_netif_t *netif = esp_netif_create_default_wifi_sta();
wifi_config_t staconf = {
.sta = {
.ssid = "ssid",
.password = "password",
.threshold.authmode = WIFI_AUTH_WPA_PSK,
}};
esp_wifi_set_mode(WIFI_MODE_STA);
esp_wifi_set_config(WIFI_IF_STA, &staconf);
esp_wifi_set_country_code("CO", false);
esp_wifi_start();
esp_wifi_connect();
}
Page 355 wificonnect.h
int retry_num = 0;
int wifiStatus = 1000;
static void wifi_event_handler(void *event_handler_arg, esp_event_base_t event_base, int32_t event_id, void *event_data)
{
switch (event_id)
{
case WIFI_EVENT_STA_START:
wifiStatus = 1001;
break;
case WIFI_EVENT_STA_CONNECTED:
wifiStatus = 1002;
break;
case WIFI_EVENT_STA_DISCONNECTED:
if (retry_num < 5)
{
esp_wifi_connect();
retry_num++;
wifiStatus = 1001;
}
break;
case IP_EVENT_STA_GOT_IP:
wifiStatus = 1010;
break;
}
}
void wifiConnect(char *country, char *ssid, char *password)
{
nvs_flash_init();
esp_netif_init();
esp_event_loop_create_default();
esp_event_handler_register(WIFI_EVENT, ESP_EVENT_ANY_ID,
wifi_event_handler, NULL);
esp_event_handler_register(IP_EVENT, IP_EVENT_STA_GOT_IP,
wifi_event_handler, NULL);
wifi_init_config_t wificonfig = WIFI_INIT_CONFIG_DEFAULT();
esp_wifi_init(&wificonfig);
esp_netif_create_default_wifi_sta();
wifi_config_t staconf = {
.sta = {
.threshold.authmode = WIFI_AUTH_WPA_PSK}};
strcpy((char *)staconf.sta.ssid, ssid);
strcpy((char *)staconf.sta.password, password);
esp_wifi_set_mode(WIFI_MODE_STA);
esp_wifi_set_config(WIFI_IF_STA, &staconf);
esp_wifi_set_country_code(country, false);
esp_wifi_start();
esp_wifi_connect();
}
Page 356 main.c uses wificonnect.h
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_wifi.h"
#include "string.h"
#include "nvs_flash.h"
#include "wificonnect.h"
void app_main(void)
{
wifiConnect("co", "ssid", "password");
while (wifiStatus != 1010) {
vTaskDelay(10 / portTICK_PERIOD_MS);
};
//use WiFi connection
}
Page 361 uses wificonnect.h
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "string.h"
#include "socket.h"
#include "wificonnect.h"
void app_main(void)
{
wifiConnect("CO", "ssid", "password");
{
vTaskDelay(10 / portTICK_PERIOD_MS);
};
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in addr;
addr.sin_family = AF_INET;
addr.sin_port = htons(80);
addr.sin_addr.s_addr = 0x0Ed7b85d;
if (connect(sockfd, (struct sockaddr *)&addr, sizeof(addr)) < 0)
return;
char header[] = "GET /index.html HTTP/1.1\r\nHost:example.com\r\n\r\n";
int n = write(sockfd, header, strlen(header));
char buffer[2048];
n = read(sockfd, buffer, 2048);
buffer[n] = 0;
printf("%s\n", buffer);
}
Page 364 uses wificonnect.h
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "string.h"
#include "esp_http_client.h"
#include "wificonnect.h"
#include "esp_crt_bundle.h"
esp_err_t http_event_handler(esp_http_client_event_t *evt)
{
static int pos = 0;
switch (evt->event_id)
{
case HTTP_EVENT_ERROR:
printf("HTTP_EVENT_ERROR\n");
break;
case HTTP_EVENT_ON_CONNECTED:
printf("HTTP_EVENT_ON_CONNECTED\n");
break;
case HTTP_EVENT_HEADER_SENT:
printf("HTTP_EVENT_HEADER_SENT\n");
break;
case HTTP_EVENT_ON_HEADER:
printf("HTTP_EVENT_ON_HEADER\n");
printf("header = %s, %s\n", evt->header_key, evt->header_value);
break;
case HTTP_EVENT_ON_DATA:
printf("HTTP_EVENT_ON_DATA, len=%d\n", evt->data_len);
if (!esp_http_client_is_chunked_response(evt->client))
{
printf("%.*s", evt->data_len, (char *)evt->data);
char *buf = (char *)(evt->user_data);
memcpy(buf + pos, evt->data, evt->data_len);
pos += evt->data_len;
buf[pos] = 0;
}
break;
case HTTP_EVENT_ON_FINISH:
printf("HTTP_EVENT_ON_FINISH\n");
pos = 0;
break;
case HTTP_EVENT_DISCONNECTED:
printf("HTTP_EVENT_DISCONNECTED\n");
break;
default:
}
return ESP_OK;
}
char httpdata[2000];
void app_main(void)
{
wifiConnect("co", "ssid", "password");
while (wifiStatus != 1010)
{
vTaskDelay(10 / portTICK_PERIOD_MS);
};
esp_http_client_config_t httpconfig = {
.url = "https://example.com",
.method = HTTP_METHOD_GET,
.event_handler = http_event_handler,
.buffer_size = DEFAULT_HTTP_BUF_SIZE,
.buffer_size_tx = DEFAULT_HTTP_BUF_SIZE,
.user_data = httpdata,
.transport_type = HTTP_TRANSPORT_OVER_SSL,
.crt_bundle_attach = esp_crt_bundle_attach,
};
esp_http_client_handle_t httphandle = esp_http_client_init(&httpconfig);
esp_http_client_perform(httphandle);
printf("len data= %d\n", strlen(httpdata));
printf("html \n %s\n ", httpdata);
}
Page 367 full program uses wificonnect.h
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "string.h"
#include "esp_http_client.h"
#include "wificonnect.h"
#include "esp_crt_bundle.h"
esp_err_t http_event_handler(esp_http_client_event_t *evt)
{
static int pos = 0;
switch (evt->event_id)
{
case HTTP_EVENT_ERROR:
printf("HTTP_EVENT_ERROR\n");
break;
case HTTP_EVENT_ON_CONNECTED:
printf("HTTP_EVENT_ON_CONNECTED\n");
break;
case HTTP_EVENT_HEADER_SENT:
printf("HTTP_EVENT_HEADER_SENT\n");
break;
case HTTP_EVENT_ON_HEADER:
printf("HTTP_EVENT_ON_HEADER\n");
printf("header = %s, %s\n", evt->header_key, evt->header_value);
break;
case HTTP_EVENT_ON_DATA:
printf("HTTP_EVENT_ON_DATA, len=%d\n", evt->data_len);
if (!esp_http_client_is_chunked_response(evt->client))
{
printf("%.*s", evt->data_len, (char *)evt->data);
char *buf = (char *)(evt->user_data);
memcpy(buf + pos, evt->data, evt->data_len);
pos += evt->data_len;
buf[pos] = 0;
}
break;
case HTTP_EVENT_ON_FINISH:
printf("HTTP_EVENT_ON_FINISH\n");
pos = 0;
break;
case HTTP_EVENT_DISCONNECTED:
printf("HTTP_EVENT_DISCONNECTED\n");
break;
default:
}
return ESP_OK;
}
char httpdata[2000];
void app_main(void)
{
wifiConnect("CO", "ssid", "password");
while (wifiStatus != 1010) {
vTaskDelay(10 / portTICK_PERIOD_MS);
};
esp_http_client_config_t httpconfig = {
.host = "192.168.253.75",
.path = "/test",
.port = 8080,
.method = HTTP_METHOD_PUT,
.event_handler = http_event_handler,
.buffer_size = DEFAULT_HTTP_BUF_SIZE,
.buffer_size_tx = DEFAULT_HTTP_BUF_SIZE,
.user_data = httpdata,
.transport_type = HTTP_TRANSPORT_OVER_TCP
};
esp_http_client_handle_t httphandle =
esp_http_client_init(&httpconfig);
esp_http_client_set_post_field(httphandle, "20.5", 3);
esp_http_client_perform(httphandle);
printf("html \n %s\n ", httpdata);
}
Page 368 Python
from http.server import HTTPServer, BaseHTTPRequestHandler
from io import BytesIO
class SimpleHTTPRequestHandler(BaseHTTPRequestHandler):
def log_message(self,*args, **kwargs):
pass
def do_PUT(self):
content_length = int(self.headers['Content-Length'])
body = self.rfile.read(content_length)
bodyString= body.decode(encoding="utf-8")
temp=float(bodyString)
print(temp)
self.send_response(200)
self.end_headers()
httpd = HTTPServer(('', 8080), SimpleHTTPRequestHandler)
httpd.serve_forever()
Page 368 complete program http server
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "string.h"
#include "wificonnect.h"
#include "esp_http_server.h"
esp_err_t get_handlertemp(httpd_req_t *req)
{
const char resp[] = "Temperature is 20.3";
httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN);
return ESP_OK;
}
esp_err_t get_handlerhum(httpd_req_t *req)
{
/* Send a simple response */
const char resp[] = "Humidity is 80%";
httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN);
return ESP_OK;
}
void app_main(void)
{
wifiConnect("co", "ssid", "password");
while (wifiStatus != 1010)
{
vTaskDelay(10 / portTICK_PERIOD_MS);
};
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
httpd_handle_t server = NULL;
httpd_uri_t uri_get = {
.uri = "/temp",
.method = HTTP_GET,
.handler = get_handlertemp,
.user_ctx = NULL};
if (httpd_start(&server, &config) == ESP_OK)
{
httpd_register_uri_handler(server, &uri_get);
uri_get.uri = "/hum";
uri_get.handler = get_handlerhum;
httpd_register_uri_handler(server, &uri_get);
}
}
Page 371 Python
with open("iopress.key", 'rb') as f:
lines = f.readlines()
lines=b'"'.join(lines)
lines=lines.decode("ascii")
lines=lines.replace("\n",'\\n"\n')
print("static const unsigned char key[]="+'"', lines+";")
with open("iopress.crt", 'rb') as f:
lines = f.readlines()
lines=b'"'.join(lines)
lines=lines.decode("ascii")
lines=lines.replace("\n",'\\n"\n')
print("static const unsigned char cert[]="+'"', lines+";")
Page 372 HTTPS Server - the certificates listed will eventually timeout and they need to be replaced
#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "esp_wifi.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "string.h"
#include "wificonnect.h"
#include "esp_https_server.h"
esp_err_t get_handlertemp(httpd_req_t* req)
{
/* Send a simple response */
const char resp[] = "Temperature is 20.3";
httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN);
return ESP_OK;
}
esp_err_t get_handlerhum(httpd_req_t* req)
{
/* Send a simple response */
const char resp[] = "Humidity is 80%";
httpd_resp_send(req, resp, HTTPD_RESP_USE_STRLEN);
return ESP_OK;
}
void app_main(void)
{
wifiConnect("co", "ssid", "password");
while (wifiStatus != 1010) {
vTaskDelay(10 / portTICK_PERIOD_MS);
};
static const unsigned char cert[] = " -----BEGIN CERTIFICATE-----\n"
"MIIDazCCAlOgAwIBAgIUA+lvUf9wMrNvaz9DuKnfx4TCoeQwDQYJKoZIhvcNAQEL\n"
"BQAwRTELMAkGA1UEBhMCR0IxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoM\n"
"GEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDAeFw0yNDA4MTYxMzQwMTNaFw0yNTA4\n"
"MTYxMzQwMTNaMEUxCzAJBgNVBAYTAkdCMRMwEQYDVQQIDApTb21lLVN0YXRlMSEw\n"
"HwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQwggEiMA0GCSqGSIb3DQEB\n"
"AQUAA4IBDwAwggEKAoIBAQC5zxoZHid/tAtRY+V/Y1rRue4yMiHVLBTmh0kqGM/h\n"
"NvOuxJUnXKP2qn9cbM1OhZvF7NIIcqNTfHaNwDG+tF8p7YlQGcSBdk5+v3HTIAFI\n"
"gg3nwHEW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knjE4fvvN\n"
"rmiPcxzOi00rXlYnv2o1iNH8OY2PXjFcApxcapqllNo8QrDqm7tEmudBAoGAcNua\n"
"CCoQYH3JQhSJGH1//OcQDekPXYxQ5f0TsCnMYGXfYYnoBfuZ0Issrl4yZvL0fuWk\n"
"2N8u0ULUI4Yy9KRbwAPFb8d7K7uUzfzJn3TN+zAjynX5H+3mzhx5wVSLTS48lM9+\n"
"tNY2d4UJf/4FisTby/Gr/aM0mXrnvZh8LgtShuUCgYEAw+3K2PalVraWHGbg18pz\n"
"fL212YObHDdbHM+SaBoopuiJed9Yz5DRbhVSSfuJMNu9WMjk9aR3Tr7s41l5L/+M\n"
"YGJGNJCE7I4mIfvgXwezxgd5P39+2Ei/qwR9nwsX/y6Mp3EuLKuPJUUaZERjrkIl\n"
"EVzn7XZ781QWSSBer5/vcQM=\n"
"-----END PRIVATE KEY-----\n"
;
httpd_ssl_config_t config = HTTPD_SSL_CONFIG_DEFAULT();
printf("%s", key);
config.servercert = cert;
config.servercert_len = sizeof(cert);
config.prvtkey_pem = key;
config.prvtkey_len = sizeof(key);
httpd_handle_t server = NULL;
httpd_uri_t uri_get = {
.uri = "/temp",
.method = HTTP_GET,
.handler = get_handlertemp,
.user_ctx = NULL
};
if (httpd_ssl_start(&server, &config) == ESP_OK) {
httpd_register_uri_handler(server, &uri_get);
uri_get.uri = "/hum";
uri_get.handler = get_handlerhum;
httpd_register_uri_handler(server, &uri_get);
}
}